@sentry/junior 0.302.0 → 0.304.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-context-Cx9fn9B3.js → adapter-context-B1IpoELr.js} +2 -2
- package/dist/{admin-_poE5NKL.js → admin-BnVFGo_z.js} +5 -5
- package/dist/{agent-runner-CY9RvsTX.js → agent-runner-CoEeZSRh.js} +1461 -1248
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +6 -6
- package/dist/api.d.ts +13 -12
- package/dist/api.js +230 -105
- package/dist/{app-BpY3wtRP.d.ts → app-Cs157Zc5.d.ts} +17 -15
- package/dist/app.d.ts +1 -1
- package/dist/app.js +108 -96
- package/dist/{automation-Cva5ZOwW.js → automation-CuA3yEcD.js} +3 -1
- package/dist/{background-compaction-queue-CXFq1_Cz.js → background-compaction-queue-WLPNSF_b.js} +6 -6
- package/dist/{briefs-B3NG-pid.js → briefs-CagVVefw.js} +12 -9
- package/dist/{catalog-runtime-Dss0lSV6.js → catalog-runtime-B8ZXvXWm.js} +2 -2
- package/dist/cli/chat.d.ts +1 -1
- package/dist/cli/chat.js +21 -21
- package/dist/cli/check.js +10 -10
- package/dist/cli/env.d.ts +1 -0
- package/dist/cli/env.js +8 -7
- package/dist/cli/init.js +13 -4
- package/dist/cli/main.js +4 -4
- package/dist/cli/plugins.js +6 -6
- package/dist/cli/snapshot-create.js +7 -5
- package/dist/cli/upgrade.d.ts +2 -2
- package/dist/cli/upgrade.js +6 -6
- package/dist/{config-CzeZiMKs.js → config-DdO1BNcw.js} +142 -67
- package/dist/{connections-CDYhMfrs.js → connections-D20kp0j5.js} +6 -6
- package/dist/{continue-in-slack-7Uf05ndC.js → continue-in-slack-BKEVMBj1.js} +8 -8
- package/dist/{conversation-BNXfq6Lb.js → conversation-BOqdRtUx.js} +4 -12
- package/dist/{conversation-feed-Clf_cv0n.js → conversation-feed-CgpgP7yi.js} +35 -2
- package/dist/{conversation-privacy-D9xnM5mK.js → conversation-privacy-L1SK_v0V.js} +16 -8
- package/dist/{conversation-turn-D7SEZgTG.js → conversation-turn-BptVJylj.js} +20 -23
- package/dist/{credential-sync-DoD0gW-j.js → credential-sync-D1J1CGzL.js} +19 -19
- package/dist/{db-B-gtnNjr.js → db-EKJnkrIb.js} +180 -17
- package/dist/{db-BdsCzytP.d.ts → db-zbN5ZV_o.d.ts} +26 -26
- package/dist/{executor-DZg20EqU.js → executor-CoIZmFK8.js} +55 -15
- package/dist/{history-IjdmO_r6.js → history-m2-ceTTX.js} +21 -12
- package/dist/{install-t1KQyTUs.js → install-BT2Pf6HP.js} +3 -3
- package/dist/instrumentation.d.ts +4 -4
- package/dist/instrumentation.js +15 -11
- package/dist/{lineage-C79GjoQr.js → lineage-C5DGQCS_.js} +2 -2
- package/dist/{logging-C9oDAg4M.js → logging-QSZuMcvo.js} +19 -19
- package/dist/{message-BLUCzJXN.js → message-TtxftRHj.js} +9 -9
- package/dist/{model-input-5jwNC45G.js → model-input-BHXfA29g.js} +4 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +8 -8
- package/dist/{oauth-callback-server-BBl66vCb.js → oauth-callback-server-B0enqHtZ.js} +5 -4
- package/dist/{oauth-relay-DRzq73b6.js → oauth-relay-DAmfVmJu.js} +3 -6
- package/dist/{package-discovery-DJhGdS4c.js → package-discovery-x4AvVhMj.js} +1 -1
- package/dist/{plugin-module-Cf5gVPWP.js → plugin-module-Cv2ETe8Y.js} +1 -1
- package/dist/{plugins-BBX07Jzt.js → plugins-Bkk0XRo2.js} +3 -3
- package/dist/{projection-CIBwgD3s.js → projection-CNKK7doO.js} +755 -221
- package/dist/{prompt-CRQbzp5e.js → prompt-DSjhoKu5.js} +185 -12
- package/dist/{queue-DtCDaIct.js → queue-CDxkit82.js} +4 -4
- package/dist/{queue-CZyYgPF0.d.ts → queue-CbEHUO0l.d.ts} +1 -1
- package/dist/{registry-DdFQHZ_d.js → registry-DBDNUUmz.js} +37 -37
- package/dist/{resolve-CdW4BdrK.js → resolve-CQLhMWSu.js} +3 -3
- package/dist/{result-oOMv1t4O.js → result-B-pauj42.js} +10 -15
- package/dist/rolldown-runtime-BKpuH2hG.js +26 -0
- package/dist/{runner-DqitLtm-.js → runner-B3KxKks5.js} +10 -10
- package/dist/{sandbox-egress-signals-Bw9I0yfJ.js → sandbox-egress-signals-DJJX9ClG.js} +1 -1
- package/dist/{schema-DnVQepWP.js → schema-Bx0Mlo32.js} +77 -13
- package/dist/{schema-BIFM-U1a.d.ts → schema-CKcu-IK6.d.ts} +562 -23
- package/dist/{secrets-DebYU866.js → secrets-DHaJ5TTn.js} +4 -4
- package/dist/{sentry-BRTJqumy.js → sentry-CPbZjomA.js} +3 -28
- package/dist/{sentry-route-name-BhwWnfqj.js → sentry-route-name-C6EIzAGP.js} +1 -1
- package/dist/{service-account-CrZftRTb.js → service-account-2HmlNPvy.js} +49 -48
- package/dist/{service-account-B6mKAPVo.js → service-account-DQLqkSVv.js} +5 -5
- package/dist/{session-stop-DW63Z3kj.js → session-stop-DEeZKqbX.js} +132 -74
- package/dist/{skills-C16fz60Z.js → skills-2UrD7JkN.js} +6 -9
- package/dist/{slack-conversation-unfurl-BHhefEb7.js → slack-conversation-unfurl-Dd129Uov.js} +14 -18
- package/dist/{spawn-D_RnFYfy.js → spawn-eMho9HDJ.js} +7 -7
- package/dist/{legacy-web-actor-id-C-cEeWqL.js → state-Bveuc4Zh.js} +32 -32
- package/dist/{stop-7p1i08CY.js → stop-D_ltJLDS.js} +359 -171
- package/dist/{store-C28I0CVW.js → store-COeYnPL_.js} +5 -5
- package/dist/{task-queue-BVUJbQ28.js → task-queue-CBIDXZpV.js} +3 -3
- package/dist/{task-runner-CWi8j7Z6.js → task-runner-CJF7zIJL.js} +15 -18
- package/dist/{thread-context-D3-yYUd0.js → thread-context-Cg0jt0aE.js} +12 -12
- package/dist/{turn-session-routing-BFMS9ATF.js → turn-session-routing-CaY3Tp8m.js} +32 -32
- package/dist/{turn-user-message-C3-O8Omt.js → turn-user-message-tcom1RYd.js} +3 -3
- package/dist/{validation-BSFKUIb4.js → validation-EU91JwIT.js} +2 -2
- package/dist/vercel.js +1 -1
- package/dist/{version-BHHXNi-0.js → version-BYRPhY5G.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-B1SO21Qa.js → viewer-Cf8ISkAc.js} +3 -3
- package/dist/{warmup-Bz9bzkzN.js → warmup-TgY4S1vx.js} +202 -577
- package/dist/{worker-BspReIIK.js → worker-C6Uq4OKD.js} +9 -12
- package/migrations/0109_user_preferences.sql +1 -0
- package/migrations/0110_code_change_repository_state_index.sql +1 -0
- package/migrations/0111_attachment_kinds.sql +14 -0
- package/migrations/0112_attachment_url_fill.sql +51 -0
- package/migrations/0113_attachment_url_index.sql +1 -0
- package/migrations/meta/0099_snapshot.json +102 -326
- package/migrations/meta/0109_snapshot.json +4925 -0
- package/migrations/meta/0110_snapshot.json +4952 -0
- package/migrations/meta/0111_snapshot.json +5011 -0
- package/migrations/meta/0112_snapshot.json +5011 -0
- package/migrations/meta/0113_snapshot.json +5033 -0
- package/migrations/meta/_journal.json +36 -1
- package/package.json +16 -19
|
@@ -1,52 +1,51 @@
|
|
|
1
|
-
import { g as
|
|
2
|
-
import { $ as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-
|
|
1
|
+
import { $ as loadTurnCheckpoint, $o as storeDeferredAttachment, $t as TurnSliceLimitExceededError, Aa as updateSlackMessage, An as isStandaloneRuntimeContextMessage, B as getAgentContextInputLimitTokens, Ba as isWorkspaceSnapshotNotReadyError, Bn as TURN_CONTEXT_TAG, Cn as getTerminalAssistantMessages, Da as postSlackMessage, Ds as credentialAuditAttributes, En as hasTurnInput, Fa as isAlreadyExistsError, Fn as stripRuntimeTurnContext, Fs as getConfigDefaults, G as AuthPausePersistenceError, Ga as createSandboxEgressCredentialToken, H as PluginCredentialFailureError, Ha as clearSandboxEgressSignals, Ia as throwSandboxOperationError, In as trimTrailingAssistantMessages, J as abandonReplacedPendingAuth, Ja as buildSandboxEgressNetworkPolicy, Jo as readLiveAttachment, K as AuthorizationFlowDisabledError, L as calculateContextCompactionTargetTokens, La as wrapSandboxSetupError, Ln as CAPABILITY_SECTION_TAG, Mn as isToolResultMessage, Mr as getReviewItem, Ms as historyItemFromPiMessage, Ni as getDashboardReviewItemLink, Nn as normalizeToolNameFromResult, Ns as piMessageFromHistoryItem, On as isAssistantMessage, Os as credentialAuditSource, Pn as retainRuntimeTurnContext, Ps as projectConversationEvents, Q as continuableMessages, Qa as tryWorkspaceRepoCheckoutPath, Qo as storeAttachments, Qt as TurnBudgetExceededError, R as getAgentBackgroundCompactionMarkTokens, Rn as REQUEST_CONTEXT_SECTION_TAG, Sa as deleteSlackMessage, Sn as getPiMessageRole, T as resolveTaskTitle, U as createPluginAuthOrchestration, Ua as consumeSandboxEgressAuthRequiredSignal, Un as readParentAgentTask, Uo as readSlackAttachmentSource, V as createPluginEgress, Va as workspaceSnapshotNotReadyUserMessage, Vi as renderToolResultNudge, W as authorizationId, Wa as consumeSandboxEgressPermissionDeniedSignal, Wi as getWorkspace, Xt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, Y as canReusePendingAuthLink, Ya as resolveSandboxCommandEnvironment, Yn as createUserTokenStore, Za as SANDBOX_RUNTIME, Zt as TURN_LIMIT_WRAP_UP_MESSAGE, _n as CODE_MODE_CALL_STATUS_TEXT, ai as resolveChannelCapabilities, an as isAnswerToolName, ao as SANDBOX_COMMAND_PATH, as as isConversationScopedChannel, c as recordAgentsInstructionsUpdated, ca as formatProviderLabel, co as SANDBOX_SKILLS_ROOT, dn as sanitizeAssistantText, do as sandboxSkillFile, en as TurnToolCallLimitExceededError, eo as ToolInputError, es as SlackActionError, f as recordAuthorizationRequested, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillPathResolution, fs as sleep, g as recordToolExecutionStarted, gn as CODEMODE_TOOL_NAME, ha as normalizeSlackReplyMarkdown, hn as readNoReply, ho as runNonInteractiveCommand, hs as AttachmentSourceUnavailableError, i as loadConversationProjection, ia as getSandboxProvider, in as REPLY_TOOL_NAME, ja as uploadFilesToConversation, jn as isToolResultError, kn as isContinuablePiBoundary, l as recordAttachmentsDelivered, ln as decideReply, lo as SANDBOX_WORKSPACE_ROOT, m as recordMcpProviderConnected, mn as isLegacyNoReplyMarker, mo as buildNonInteractiveShellScript, nn as createTurnLimitGate, no as PluginToolDeniedError, nt as saveTurnCheckpoint, oi as getSlackToolContext, on as readTurnAnswer, oo as SANDBOX_DATA_ROOT, or as getPluginTools, p as recordGuardianActionReviewed, pa as escapeSlackMrkdwnText, po as buildCommandScript, q as AuthorizationPauseError, r as loadConnectedMcpProviders, ra as ensureDockerDaemon, rn as isTurnExecutionLimitExceededError, sa as deliverOAuthAuthorization, sn as remindMissingAnswer, ta as hash, to as isToolInputError, tr as createPluginHookRunner, ua as resolveBaseUrl, un as getAssistantReplyText, uo as sandboxSkillDir, vn as REPORT_BLOCKED_TOOL_NAME, vs as createConversationEmbedder, wn as getUserMessageInstructionText, ws as resolveUserTimezone, xa as addReactionToMessage, xn as extractAssistantText, yn as readBlockedReport, z as getAgentContextCompactionTriggerTokens, za as getWorkspaceSnapshotNotReadyError } from "./projection-CNKK7doO.js";
|
|
2
|
+
import { $ as bufferBody, B as unwrapCurrentInstruction, F as textCharsForTokens, G as createProviderError, H as escapeXmlText, I as COMPACTION_SUMMARY_PREFIX, K as findProviderError, L as hasCompactedConversationContext, M as estimateMessagesTokens, N as estimateRequestOverheadTokens, P as estimateTextTokens, R as isCompactionSummaryText, U as ProviderError, V as escapeXml, W as createAssistantProviderError, X as isProviderRetryError, Y as isProviderRefusal, Z as getGatewayApiKey, b as GEN_AI_PROVIDER_NAME, j as requestPrefixAttributes, k as resolveGatewayModel, n as botConfig, q as getProviderErrorAttributes, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName } from "./config-DdO1BNcw.js";
|
|
3
|
+
import { C as summarizeMessageText, E as withSpan, H as runWithLogAttributes, S as setTags, T as withLogContext, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, d as logAudit, f as logError, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, l as getLogContextAttributesForSpan, m as logInfo, p as logException, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-QSZuMcvo.js";
|
|
4
|
+
import { g as withActiveSpan, i as getActiveSpan, m as startInactiveSpan } from "./sentry-CPbZjomA.js";
|
|
5
|
+
import { a as toCanonicalInputMessage, c as toGenAiPayloadMetadata, i as runWithConversationPrivacy, l as toGenAiPayloadTraceAttributes, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-L1SK_v0V.js";
|
|
6
6
|
import { f as parseSlackTeamId, n as createSlackActor, o as isUserActor, p as parseSlackUserId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-
|
|
10
|
-
import { a as listReferenceFiles } from "./package-discovery-
|
|
11
|
-
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-
|
|
12
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
13
|
-
import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
14
|
-
import { l as
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import { D as
|
|
20
|
-
import {
|
|
7
|
+
import { T as isPersonInput, X as getStateAdapter, a as getConversationStore, k as turnBehavior, nt as withLock, o as getDb, ot as addAgentTurnUsage, r as getConversationEventStore, s as getSqlExecutor, st as agentTurnCostUsd, ut as hasAgentTurnUsage, yt as sameDestination } from "./db-EKJnkrIb.js";
|
|
8
|
+
import { L as juniorArtifacts, c as juniorReviewItemSlackCards, u as juniorAutomationRuns } from "./executor-CoIZmFK8.js";
|
|
9
|
+
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor } from "./history-m2-ceTTX.js";
|
|
10
|
+
import { a as listReferenceFiles } from "./package-discovery-x4AvVhMj.js";
|
|
11
|
+
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-DBDNUUmz.js";
|
|
12
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-B8ZXvXWm.js";
|
|
13
|
+
import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-2UrD7JkN.js";
|
|
14
|
+
import { C as McpProviderError, D as getMcpAwareTelemetryMessage, E as getMcpAwareErrorType, O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, T as McpToolError, _ as getMcpServerSessionId, a as serviceAccountOnly, b as putMcpAuthSession, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as deleteMcpAuthSession, g as getMcpAuthSession, i as serviceAccountAllows, k as toMcpProviderError, l as getMcpServiceAccountCredentials, m as deleteMcpServerSessionId, u as McpAuthorizationRequiredError, v as getMcpStoredOAuthCredentials, w as McpServiceAccountRequiredError, x as putMcpServerSessionId, y as patchMcpAuthSession } from "./service-account-2HmlNPvy.js";
|
|
15
|
+
import { f as generateImages, h as NoAudioError, l as completeObject, m as transcribeFromUrl, u as completeText } from "./prompt-DSjhoKu5.js";
|
|
16
|
+
import { a as readActorIdentityFromSql, i as readActorIdentity } from "./viewer-Cf8ISkAc.js";
|
|
17
|
+
import { W as MAX_ATTACHMENT_BYTES } from "./conversation-BOqdRtUx.js";
|
|
18
|
+
import { Q as requireSlackChannelMessageScope, R as resolveSlackReplyTarget, X as getEventCatalog, _t as foldSystemMessages, bt as writeAgentHistory, ct as JUNIOR_PERSONALITY, d as buildPromptInput, dt as buildAgentsInstructionsMessage, f as buildSteeringPiMessage, ft as findVisibleAgentsInstructions, gt as foldLeadingSystemMessages, h as loadPromptTurnContext, ht as showsAgentsInstructions, lt as AGENTS_REMOVAL_NOTICE, mt as renderAgentsInstructions, nt as slackChannelMessageTrigger, pt as readRepositoryInstructions, u as assemblePrompt, ut as AGENTS_REPLACEMENT_NOTICE, vt as readAgentHistory, yt as withAgentRequest } from "./session-stop-DEeZKqbX.js";
|
|
19
|
+
import { $ as createBashTool, $n as createSlackPublicSearchTool, $r as requireToolCreator, A as createWebSearchTool, Ar as createSearchAutomationsTool, B as createSystemTimeTool, Br as automationTriggerChangesSchema, C as incrementStat, Ci as missingAutomationSkillReason, Cr as createSlackCanvasEditTool, D as requireReadyWorkspaceSnapshot, Dr as resolveWorkspacePath, Ei as resolveTaskOutcomes, Er as positiveInteger, F as userLookupIdentityProviders, Fr as zodToolDefinition, Ft as createRunOperatorSqlTool, G as createWriteFileTool, Gr as injectContinuationToolName, H as createSearchEventTypesTool, Hr as editedAutomationTask, Ir as automationIdForToolCall, It as createListWatchesTool, J as sliceFileContent, Jr as getConversationAccess, K as createReadFileTool, Kr as juniorToolOutputSchema, Lr as automationSkillToolSchema, M as createWatchTimerTool, Mr as createDeleteAutomationTool, N as createWatchEventsTool, Nr as AUTOMATIONS_TOOL_SOURCE, O as prepareWorkspaceSnapshot, Or as createOperationKey, P as createUserLookupTool, Pr as zodTool, Pt as createReadConversationEventTool, Q as editFile, Qr as requireToolCaller, R as createUpdateUserCustomizationTool, Rr as automationToolResult, S as createWorkspaceTools, Sr as createSlackCanvasReadTool, T as ensureWorkspaceSnapshotBuild, Ti as moveTaskOutcomes, Tr as isMissingPathError, U as createSearchConversationEventsTool, Ur as newAutomationTask, V as createStopWatchingResourcesTool, Vr as automationTriggerSchema, W as createSearchConversationsTool, Wn as createSetConversationSubscriptionTool, Wr as triggerKind, X as capToolResult, Xr as automationToolsDisabledReason, Y as TOOL_RESULT_MAX_CHARS, Yn as createSlackThreadReadTool, Yr as automationToolContext, Z as createEditFileTool, Zr as requireToolAutomation, _i as changedEventMatch, _t as createUpdateReviewItemTool, a as createCacheWarmingRecorder, ar as createSlackConversationSearchChannelPort, at as createReportBlockedTool, b as coreToolSlots, ct as createMessageAgentTool, dr as resolveSlackChannelRef, ei as requireToolDestination, er as createSlackListUpdateItemTool, et as createUpdatePlanTool, fr as slackChannelRefParam, gi as editEventAutomation, gt as createSearchReviewItemsTool, hi as editScheduledAutomation, ht as createAddReviewItemTool, in as isParentMessageMeta, ir as createSlackConversationMessageSearchTool, it as createReportProgressTool, j as createWebFetchTool, jr as createRunAutomationNowTool, kr as createCanvas, lt as createArchiveAgentTool, mr as joinPublicChannelForRead, ni as automationEditor, nr as createSlackListCreateTool, nt as createSpawnAgentTool, or as createSlackChannelListMessagesTool, ot as createReplyTool, pr as checkSlackChannelReadAccess, q as missingFileResult, qr as makeStructuredToolOutput, qt as listAgentInvocationsForConversation, ri as changeAutomationLifecycle, rr as createSlackListAddItemsTool, rt as createListAgentsTool, st as createNoReplyTool, tr as createSlackListGetItemsTool, tt as createStopAgentTool, ur as createSlackChannelJoinTool, vi as requireEventAutomationTrigger, wr as SLACK_TOOL_SOURCE, x as enabledMode, xi as requireAutomationSkill, xr as createSlackCanvasWriteTool, yi as requireAutomationTaskText, z as createSubmitFeedbackTool, zr as automationToolResultSchema } from "./warmup-TgY4S1vx.js";
|
|
20
|
+
import { D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, I as scheduleIntentFromTool, O as taskOutcomeInputSchema, P as ScheduleIntentError, T as automationContextToolSchema, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR } from "./automation-CuA3yEcD.js";
|
|
21
|
+
import { G as readScheduledAutomation, K as saveScheduledAutomation, Q as createEventAutomation, V as createScheduledAutomation, it as saveEventAutomation, mt as automationRevision, t as resolveConversationRouting, tt as getEventAutomation } from "./turn-session-routing-CaY3Tp8m.js";
|
|
21
22
|
import { a as USER_INPUT_LIMITS, i as AGENT_INVOCATION_STATUSES, m as detectImageMediaType, o as USER_INPUT_NOTE, s as buttonUserInputField, u as normalizeUserInputAnswer } from "./web-message-id-lNodcCOI.js";
|
|
22
|
-
import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-
|
|
23
|
-
import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-
|
|
24
|
-
import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-
|
|
25
|
-
import { n as resolve$1 } from "./resolve-
|
|
26
|
-
import {
|
|
27
|
-
import { t as runWithSlackInstallation } from "./adapter-context-Cx9fn9B3.js";
|
|
23
|
+
import { d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-tcom1RYd.js";
|
|
24
|
+
import { l as QUEUE_SIGNATURE_MAX_AGE_MS, n as backgroundCompactionId, o as getVercelConversationWorkQueue } from "./background-compaction-queue-WLPNSF_b.js";
|
|
25
|
+
import { o as getSandboxResources, r as setSnapshotSpanAttributes } from "./install-BT2Pf6HP.js";
|
|
26
|
+
import { n as resolve$1 } from "./resolve-CQLhMWSu.js";
|
|
27
|
+
import { t as runWithSlackInstallation } from "./adapter-context-B1IpoELr.js";
|
|
28
28
|
import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
|
|
29
29
|
import * as z from "zod";
|
|
30
30
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
31
|
-
import { createGatewayProvider } from "@ai-sdk/gateway";
|
|
32
|
-
import { NoImageGeneratedError, generateImage } from "ai";
|
|
33
31
|
import path from "node:path";
|
|
34
32
|
import { isDeepStrictEqual } from "node:util";
|
|
35
33
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
36
34
|
import { createHash, randomBytes, randomInt, randomUUID } from "node:crypto";
|
|
35
|
+
import { createAssistantMessageEventStream, getInitialSystemMessage, getSystemMessageText as getSystemMessageText$1, isRetryableAssistantError, mergeClientIdentity } from "@earendil-works/pi-ai";
|
|
37
36
|
import { and, eq, inArray, isNull } from "drizzle-orm";
|
|
38
37
|
import { declaredEventKeys, missingToolAnnotationKeys, ownedObjectAnnotationSchema } from "@sentry/junior-plugin-api";
|
|
39
38
|
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
40
|
-
import { Agent,
|
|
39
|
+
import { Agent, DEFAULT_AGENT_IDENTITY } from "@earendil-works/pi-agent-core";
|
|
41
40
|
import fs from "node:fs/promises";
|
|
41
|
+
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
42
42
|
import { SignJWT, importPKCS8 } from "jose";
|
|
43
43
|
import { performance as performance$1 } from "node:perf_hooks";
|
|
44
|
-
import { createAssistantMessageEventStream, isRetryableAssistantError } from "@earendil-works/pi-ai";
|
|
45
44
|
import { Bash, defineCommand } from "just-bash";
|
|
46
|
-
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
47
45
|
import { Kind } from "@sinclair/typebox";
|
|
48
46
|
import { Value } from "@sinclair/typebox/value";
|
|
49
47
|
import { CodemodeSandbox, renderToolSignature } from "@earendil-works/pi-codemode";
|
|
48
|
+
import { calculateContextTokens } from "@earendil-works/pi-ai/utils/estimate";
|
|
50
49
|
// src/chat/sandbox/skill-sandbox.ts
|
|
51
50
|
const MAX_SKILL_FILE_BYTES = 262144;
|
|
52
51
|
const DEFAULT_MAX_SKILL_FILE_CHARS = 2e4;
|
|
@@ -192,189 +191,609 @@ var SkillSandbox = class {
|
|
|
192
191
|
throw new Error("No active skill is loaded. Call loadSkill first or pass skill_name explicitly.");
|
|
193
192
|
}
|
|
194
193
|
};
|
|
195
|
-
// src/chat/
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
function readAgentHistory(messages) {
|
|
201
|
-
return messages.filter((message) => !isSystemMessage(message));
|
|
202
|
-
}
|
|
203
|
-
/**
|
|
204
|
-
* Return the message list that replaces `current` with `history`. The leading
|
|
205
|
-
* system message of `current` stays first. System messages in `history` are
|
|
206
|
-
* dropped.
|
|
207
|
-
*/
|
|
208
|
-
function writeAgentHistory(current, history) {
|
|
209
|
-
const leading = current[0];
|
|
210
|
-
const messages = readAgentHistory(history);
|
|
211
|
-
return leading && isSystemMessage(leading) ? [leading, ...messages] : messages;
|
|
194
|
+
// src/chat/mcp/tool-manager.ts
|
|
195
|
+
const MAX_TOOL_RESULT_TOKENS = 1e4;
|
|
196
|
+
const MAX_TOOL_RESULT_BYTES = 32768;
|
|
197
|
+
function normalizeMcpToolName(provider, toolName) {
|
|
198
|
+
return `mcp__${provider}__${toolName}`;
|
|
212
199
|
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
* same request on every Pi version, without Pi's system messages.
|
|
217
|
-
*/
|
|
218
|
-
function withAgentRequest(base, request) {
|
|
219
|
-
return (model, context, options) => base(model, {
|
|
220
|
-
systemPrompt: request.systemPrompt,
|
|
221
|
-
messages: readAgentHistory(context.messages),
|
|
222
|
-
tools: request.tools
|
|
223
|
-
}, options);
|
|
200
|
+
function summarizeStructuredContent(value) {
|
|
201
|
+
if (!value || typeof value !== "object") return;
|
|
202
|
+
return JSON.stringify(value, null, 2);
|
|
224
203
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
204
|
+
function summarizeResourcePart(part) {
|
|
205
|
+
if ("text" in part.resource) return part.resource.text;
|
|
206
|
+
return [
|
|
207
|
+
`Resource: ${part.resource.uri}`,
|
|
208
|
+
...part.resource.mimeType ? [`Mime Type: ${part.resource.mimeType}`] : [],
|
|
209
|
+
`Blob bytes (base64): ${part.resource.blob.length}`
|
|
210
|
+
].join("\n");
|
|
232
211
|
}
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
212
|
+
function toAgentToolContent(result) {
|
|
213
|
+
if ("toolResult" in result) return [{
|
|
214
|
+
type: "text",
|
|
215
|
+
text: JSON.stringify(result.toolResult, null, 2)
|
|
216
|
+
}];
|
|
217
|
+
const content = [];
|
|
218
|
+
for (const part of result.content) {
|
|
219
|
+
if (part.type === "text") {
|
|
220
|
+
content.push({
|
|
221
|
+
type: "text",
|
|
222
|
+
text: part.text
|
|
223
|
+
});
|
|
224
|
+
continue;
|
|
225
|
+
}
|
|
226
|
+
if (part.type === "image") {
|
|
227
|
+
content.push({
|
|
228
|
+
type: "image",
|
|
229
|
+
data: part.data,
|
|
230
|
+
mimeType: part.mimeType
|
|
231
|
+
});
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
if (part.type === "audio") {
|
|
235
|
+
content.push({
|
|
236
|
+
type: "text",
|
|
237
|
+
text: `Audio output (${part.mimeType}, ${part.data.length} base64 chars)`
|
|
238
|
+
});
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
if (part.type === "resource_link") {
|
|
242
|
+
content.push({
|
|
243
|
+
type: "text",
|
|
244
|
+
text: part.uri
|
|
245
|
+
});
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
content.push({
|
|
249
|
+
type: "text",
|
|
250
|
+
text: summarizeResourcePart(part)
|
|
253
251
|
});
|
|
254
|
-
} };
|
|
255
|
-
function refreshOutcome(instructions) {
|
|
256
|
-
const instructionsVisible = visibleInstructions?.active === true;
|
|
257
|
-
if (!instructions) return instructionsVisible ? "removed" : "none";
|
|
258
|
-
if (!instructionsVisible) return "added";
|
|
259
|
-
return showsAgentsInstructions(visibleInstructions, instructions) ? "unchanged" : "updated";
|
|
260
|
-
}
|
|
261
|
-
async function appendUpdate(instructions, currentMessages) {
|
|
262
|
-
const message = instructions ? buildAgentsInstructionsMessage({
|
|
263
|
-
directory: instructions.directory,
|
|
264
|
-
text: visibleInstructions?.active === true ? `${AGENTS_REPLACEMENT_NOTICE}\n\n${instructions.text}` : instructions.text
|
|
265
|
-
}) : buildAgentsInstructionsMessage({ text: AGENTS_REMOVAL_NOTICE });
|
|
266
|
-
const messages = [...currentMessages, message];
|
|
267
|
-
options.setMessages(messages);
|
|
268
|
-
await options.commit(messages);
|
|
269
|
-
visibleInstructions = instructions ? {
|
|
270
|
-
active: true,
|
|
271
|
-
directory: instructions.directory,
|
|
272
|
-
text: instructions.text
|
|
273
|
-
} : { active: false };
|
|
274
|
-
await options.onTransition?.(instructions);
|
|
275
252
|
}
|
|
253
|
+
if (content.length > 0) return content;
|
|
254
|
+
const structured = summarizeStructuredContent(result.structuredContent);
|
|
255
|
+
if (structured) return [{
|
|
256
|
+
type: "text",
|
|
257
|
+
text: structured
|
|
258
|
+
}];
|
|
259
|
+
return [{
|
|
260
|
+
type: "text",
|
|
261
|
+
text: "ok"
|
|
262
|
+
}];
|
|
276
263
|
}
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
return conversationPrivacy === "public" ? "content" : "metadata";
|
|
264
|
+
function utf8Bytes(value) {
|
|
265
|
+
return Buffer.byteLength(value, "utf8");
|
|
280
266
|
}
|
|
281
|
-
function
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
"gen_ai.output.type": "text",
|
|
289
|
-
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
290
|
-
"server.port": 443,
|
|
291
|
-
...options?.temperature !== void 0 ? { "gen_ai.request.temperature": options.temperature } : void 0,
|
|
292
|
-
...options?.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": options.maxTokens } : void 0,
|
|
293
|
-
...options?.reasoning ? { "gen_ai.request.reasoning.level": options.reasoning } : void 0,
|
|
294
|
-
...hasCompactedConversationContext(context.messages) ? { "gen_ai.conversation.compacted": true } : void 0,
|
|
295
|
-
...conversationPrivacy ? { "app.conversation.privacy": conversationPrivacy } : void 0,
|
|
296
|
-
...toGenAiMessagesTraceAttributes("gen_ai.input", context.messages)
|
|
297
|
-
};
|
|
298
|
-
if (mode === "content") {
|
|
299
|
-
const inputMessages = serializeGenAiAttribute(context.messages.map(toCanonicalInputMessage));
|
|
300
|
-
if (inputMessages) attributes["gen_ai.input.messages"] = inputMessages;
|
|
301
|
-
}
|
|
302
|
-
if (context.systemPrompt) {
|
|
303
|
-
if (mode === "content") {
|
|
304
|
-
const systemInstructions = serializeGenAiAttribute([{
|
|
305
|
-
type: "text",
|
|
306
|
-
content: context.systemPrompt
|
|
307
|
-
}]);
|
|
308
|
-
if (systemInstructions) attributes["gen_ai.system_instructions"] = systemInstructions;
|
|
309
|
-
}
|
|
310
|
-
attributes["gen_ai.system_instructions.content_chars"] = context.systemPrompt.length;
|
|
267
|
+
function prefixWithin(value, maxChars, maxBytes) {
|
|
268
|
+
let low = 0;
|
|
269
|
+
let high = Math.min(value.length, maxChars);
|
|
270
|
+
while (low < high) {
|
|
271
|
+
const middle = Math.ceil((low + high) / 2);
|
|
272
|
+
if (utf8Bytes(value.slice(0, middle)) <= maxBytes) low = middle;
|
|
273
|
+
else high = middle - 1;
|
|
311
274
|
}
|
|
312
|
-
|
|
275
|
+
if (low > 0 && /[\uD800-\uDBFF]/.test(value[low - 1])) low -= 1;
|
|
276
|
+
return value.slice(0, low);
|
|
313
277
|
}
|
|
314
|
-
function
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
if (message.usage.cacheWrite1h !== void 0) attributes["app.ai.usage.cache_write_1h"] = message.usage.cacheWrite1h;
|
|
322
|
-
if (message.stopReason) attributes["gen_ai.response.finish_reasons"] = [normalizeGenAiFinishReason(message.stopReason)];
|
|
323
|
-
if (message.model) attributes["gen_ai.response.model"] = message.model;
|
|
324
|
-
if (message.responseId) attributes["gen_ai.response.id"] = message.responseId;
|
|
325
|
-
if (message.stopReason === "error") {
|
|
326
|
-
const providerError = createAssistantProviderError(message);
|
|
327
|
-
Object.assign(attributes, getProviderErrorAttributes(providerError));
|
|
328
|
-
attributes["error.type"] = providerError.kind;
|
|
278
|
+
function suffixWithin(value, maxChars, maxBytes) {
|
|
279
|
+
let low = Math.max(0, value.length - maxChars);
|
|
280
|
+
let high = value.length;
|
|
281
|
+
while (low < high) {
|
|
282
|
+
const middle = Math.floor((low + high) / 2);
|
|
283
|
+
if (utf8Bytes(value.slice(middle)) <= maxBytes) high = middle;
|
|
284
|
+
else low = middle + 1;
|
|
329
285
|
}
|
|
330
|
-
|
|
286
|
+
if (low < value.length && /[\uDC00-\uDFFF]/.test(value[low])) low += 1;
|
|
287
|
+
return value.slice(low);
|
|
331
288
|
}
|
|
332
|
-
|
|
333
|
-
"
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
receivedAtMs: Date.now()
|
|
346
|
-
};
|
|
347
|
-
},
|
|
348
|
-
attributes: () => {
|
|
349
|
-
if (firstByteAtMs === void 0) return { "gen_ai.response.streaming": false };
|
|
350
|
-
return {
|
|
351
|
-
"gen_ai.response.streaming": true,
|
|
352
|
-
"app.ai.time_to_first_byte_ms": firstByteAtMs - requestStartedAtMs,
|
|
353
|
-
...firstToken ? {
|
|
354
|
-
"gen_ai.response.time_to_first_chunk": (firstToken.receivedAtMs - requestStartedAtMs) / 1e3,
|
|
355
|
-
"app.ai.first_token_type": firstToken.type
|
|
356
|
-
} : void 0
|
|
357
|
-
};
|
|
358
|
-
}
|
|
359
|
-
};
|
|
289
|
+
function boundMcpContent(content) {
|
|
290
|
+
const text = content.filter((part) => part.type === "text").map((part) => part.text).join("\n\n");
|
|
291
|
+
const originalBytes = utf8Bytes(text);
|
|
292
|
+
const originalTokens = estimateTextTokens(text);
|
|
293
|
+
if (originalTokens <= MAX_TOOL_RESULT_TOKENS && originalBytes <= MAX_TOOL_RESULT_BYTES) return content;
|
|
294
|
+
const warning = `\n\nWarning: truncated output (original token count: ${originalTokens}; original bytes: ${originalBytes})\n\n`;
|
|
295
|
+
const remainingChars = textCharsForTokens(MAX_TOOL_RESULT_TOKENS) - warning.length;
|
|
296
|
+
const remainingBytes = MAX_TOOL_RESULT_BYTES - utf8Bytes(warning);
|
|
297
|
+
const head = prefixWithin(text, Math.ceil(remainingChars / 2), Math.ceil(remainingBytes / 2));
|
|
298
|
+
return [{
|
|
299
|
+
type: "text",
|
|
300
|
+
text: `${head}${warning}${suffixWithin(text.slice(head.length), remainingChars - head.length, remainingBytes - utf8Bytes(head))}`
|
|
301
|
+
}, ...content.filter((part) => part.type === "image")];
|
|
360
302
|
}
|
|
361
|
-
function
|
|
362
|
-
const
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
const { utilization } = performance$1.eventLoopUtilization(eventLoopStart);
|
|
371
|
-
span.setAttribute("app.ai.event_loop.utilization", Math.round(utilization * 1e3) / 1e3);
|
|
372
|
-
} catch {}
|
|
373
|
-
await onResponse?.(response, model);
|
|
374
|
-
}
|
|
375
|
-
};
|
|
303
|
+
function toModelVisibleMcpContent(result) {
|
|
304
|
+
const content = toAgentToolContent(result);
|
|
305
|
+
if (content.some((part) => part.type === "image")) return content;
|
|
306
|
+
const structured = summarizeStructuredContent(result.structuredContent);
|
|
307
|
+
if (structured) return [{
|
|
308
|
+
type: "text",
|
|
309
|
+
text: structured
|
|
310
|
+
}];
|
|
311
|
+
return content;
|
|
376
312
|
}
|
|
377
|
-
function
|
|
313
|
+
function describeMcpTool(provider, tool) {
|
|
314
|
+
return `${`[${provider}]`} ${tool.description?.trim() || tool.title?.trim() || tool.name}`;
|
|
315
|
+
}
|
|
316
|
+
function extractMcpErrorMessage(result) {
|
|
317
|
+
if ("toolResult" in result) return JSON.stringify(result.toolResult, null, 2);
|
|
318
|
+
const textParts = result.content.filter((part) => part.type === "text").map((part) => part.text.trim()).filter((text) => text.length > 0);
|
|
319
|
+
if (textParts.length > 0) return textParts.join("\n\n");
|
|
320
|
+
const structured = summarizeStructuredContent(result.structuredContent);
|
|
321
|
+
if (structured) return structured;
|
|
322
|
+
return "MCP tool call failed";
|
|
323
|
+
}
|
|
324
|
+
var McpToolManager = class {
|
|
325
|
+
pluginsByProvider = /* @__PURE__ */ new Map();
|
|
326
|
+
activeProviders = /* @__PURE__ */ new Set();
|
|
327
|
+
authorizationPendingProviders = /* @__PURE__ */ new Set();
|
|
328
|
+
clientsByProvider = /* @__PURE__ */ new Map();
|
|
329
|
+
/** Actor clients for tools that a provider's service account may not call. */
|
|
330
|
+
actorClientsByProvider = /* @__PURE__ */ new Map();
|
|
331
|
+
serviceAccountProviders = /* @__PURE__ */ new Set();
|
|
332
|
+
clientPromisesByProvider = /* @__PURE__ */ new Map();
|
|
333
|
+
toolsByProvider = /* @__PURE__ */ new Map();
|
|
334
|
+
/** Clients of forgotten providers. `close()` still owns their transports. */
|
|
335
|
+
forgottenClients = [];
|
|
336
|
+
options;
|
|
337
|
+
constructor(plugins, options = {}) {
|
|
338
|
+
this.options = options;
|
|
339
|
+
for (const plugin of plugins) if (plugin.manifest.mcp) this.pluginsByProvider.set(plugin.manifest.name, plugin);
|
|
340
|
+
}
|
|
341
|
+
getActiveProviders() {
|
|
342
|
+
return [...this.activeProviders].sort((left, right) => left.localeCompare(right));
|
|
343
|
+
}
|
|
344
|
+
/** List configured MCP providers for discovery without connecting to them. */
|
|
345
|
+
getAvailableProviderCatalog() {
|
|
346
|
+
return [...this.pluginsByProvider.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([provider, plugin]) => ({
|
|
347
|
+
provider,
|
|
348
|
+
description: plugin.manifest.description,
|
|
349
|
+
active: this.activeProviders.has(provider)
|
|
350
|
+
}));
|
|
351
|
+
}
|
|
352
|
+
async activateProvider(provider, authorizationContext) {
|
|
353
|
+
if (this.activeProviders.has(provider)) return false;
|
|
354
|
+
if (this.authorizationPendingProviders.has(provider)) return false;
|
|
355
|
+
const plugin = this.pluginsByProvider.get(provider);
|
|
356
|
+
if (!plugin?.manifest.mcp) return false;
|
|
357
|
+
try {
|
|
358
|
+
const client = await this.getClient(plugin);
|
|
359
|
+
const listedTools = this.filterListedTools(plugin, await client.listTools());
|
|
360
|
+
this.assertWrappedToolsAvailable(plugin, listedTools);
|
|
361
|
+
const tools = this.filterServiceAccountOnlyTools(plugin, listedTools);
|
|
362
|
+
this.toolsByProvider.set(provider, tools.map((tool) => this.toManagedTool(plugin, client, tool)));
|
|
363
|
+
this.activeProviders.add(provider);
|
|
364
|
+
return true;
|
|
365
|
+
} catch (error) {
|
|
366
|
+
if (error instanceof McpAuthorizationRequiredError && await this.handleAuthorizationRequired(plugin.manifest.name, error, authorizationContext)) return false;
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
async close() {
|
|
371
|
+
let firstError;
|
|
372
|
+
for (const client of [
|
|
373
|
+
...this.clientsByProvider.values(),
|
|
374
|
+
...this.actorClientsByProvider.values(),
|
|
375
|
+
...this.forgottenClients
|
|
376
|
+
]) try {
|
|
377
|
+
await client.close();
|
|
378
|
+
} catch (error) {
|
|
379
|
+
firstError ??= error;
|
|
380
|
+
}
|
|
381
|
+
this.clientsByProvider.clear();
|
|
382
|
+
this.actorClientsByProvider.clear();
|
|
383
|
+
this.forgottenClients.length = 0;
|
|
384
|
+
this.serviceAccountProviders.clear();
|
|
385
|
+
this.toolsByProvider.clear();
|
|
386
|
+
this.activeProviders.clear();
|
|
387
|
+
this.authorizationPendingProviders.clear();
|
|
388
|
+
if (firstError) throw firstError;
|
|
389
|
+
}
|
|
390
|
+
/** Return descriptors for all active MCP provider tools, optionally filtered by provider. */
|
|
391
|
+
getActiveToolCatalog(options = {}) {
|
|
392
|
+
return this.getResolvedActiveTools(options).map((tool) => this.toToolDescriptor(tool));
|
|
393
|
+
}
|
|
394
|
+
filterListedTools(plugin, tools) {
|
|
395
|
+
const allowedTools = plugin.manifest.mcp?.allowedTools;
|
|
396
|
+
if (!allowedTools || allowedTools.length === 0) return tools;
|
|
397
|
+
const availableToolNames = new Set(tools.map((tool) => tool.name));
|
|
398
|
+
const missingTools = allowedTools.filter((toolName) => !availableToolNames.has(toolName));
|
|
399
|
+
if (missingTools.length > 0) throw new Error(`Plugin ${plugin.manifest.name} MCP discovery missing allowlisted tools: ${missingTools.join(", ")}`);
|
|
400
|
+
const loadedToolSet = /* @__PURE__ */ new Set([...allowedTools, ...plugin.manifest.mcp?.wrappedTools ?? []]);
|
|
401
|
+
return tools.filter((tool) => loadedToolSet.has(tool.name));
|
|
402
|
+
}
|
|
403
|
+
assertWrappedToolsAvailable(plugin, tools) {
|
|
404
|
+
const wrappedTools = plugin.manifest.mcp?.wrappedTools ?? [];
|
|
405
|
+
if (wrappedTools.length === 0) return;
|
|
406
|
+
const availableToolNames = new Set(tools.map((tool) => tool.name));
|
|
407
|
+
const missingTools = wrappedTools.filter((toolName) => !availableToolNames.has(toolName));
|
|
408
|
+
if (missingTools.length > 0) throw new Error(`Plugin ${plugin.manifest.name} MCP discovery missing wrapped tools: ${missingTools.join(", ")}`);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Hide tools that the service account does not list when no Actor
|
|
412
|
+
* connection exists to call them.
|
|
413
|
+
*/
|
|
414
|
+
filterServiceAccountOnlyTools(plugin, tools) {
|
|
415
|
+
if (!serviceAccountOnly(plugin.manifest)) return tools;
|
|
416
|
+
return tools.filter((tool) => serviceAccountAllows(plugin.manifest, { tool: tool.name }));
|
|
417
|
+
}
|
|
418
|
+
async getClient(plugin) {
|
|
419
|
+
const existing = this.clientsByProvider.get(plugin.manifest.name);
|
|
420
|
+
if (existing) return existing;
|
|
421
|
+
const pending = this.clientPromisesByProvider.get(plugin.manifest.name);
|
|
422
|
+
if (pending) return await pending;
|
|
423
|
+
const clientPromise = this.createClient(plugin);
|
|
424
|
+
this.clientPromisesByProvider.set(plugin.manifest.name, clientPromise);
|
|
425
|
+
try {
|
|
426
|
+
return await clientPromise;
|
|
427
|
+
} finally {
|
|
428
|
+
if (this.clientPromisesByProvider.get(plugin.manifest.name) === clientPromise) this.clientPromisesByProvider.delete(plugin.manifest.name);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
async createClient(plugin) {
|
|
432
|
+
const serviceAccount = await this.options.serviceAccountProviderFactory?.(plugin);
|
|
433
|
+
if (serviceAccount) this.serviceAccountProviders.add(plugin.manifest.name);
|
|
434
|
+
const client = await this.newClient(plugin, serviceAccount);
|
|
435
|
+
this.clientsByProvider.set(plugin.manifest.name, client);
|
|
436
|
+
return client;
|
|
437
|
+
}
|
|
438
|
+
async newClient(plugin, serviceAccount) {
|
|
439
|
+
if (!serviceAccount && serviceAccountOnly(plugin.manifest)) throw new McpServiceAccountRequiredError(plugin.manifest.name, plugin.manifest.displayName);
|
|
440
|
+
const authProvider = serviceAccount ?? await this.options.authProviderFactory?.(plugin);
|
|
441
|
+
return new PluginMcpClient(plugin, {
|
|
442
|
+
...authProvider ? { authProvider } : void 0,
|
|
443
|
+
...this.options.fetch ? { fetch: this.options.fetch } : void 0
|
|
444
|
+
});
|
|
445
|
+
}
|
|
446
|
+
/** Pick the client for one call: the service account for its tools, else the actor. */
|
|
447
|
+
async clientForTool(plugin, client, toolName) {
|
|
448
|
+
const provider = plugin.manifest.name;
|
|
449
|
+
if (!this.serviceAccountProviders.has(provider) || serviceAccountAllows(plugin.manifest, { tool: toolName })) return client;
|
|
450
|
+
if (serviceAccountOnly(plugin.manifest)) throw new McpToolError(`${plugin.manifest.displayName} tool ${toolName} is not available: the shared ${plugin.manifest.displayName} account cannot use it`);
|
|
451
|
+
const existing = this.actorClientsByProvider.get(provider);
|
|
452
|
+
if (existing) return existing;
|
|
453
|
+
const actorClient = await this.newClient(plugin);
|
|
454
|
+
this.actorClientsByProvider.set(provider, actorClient);
|
|
455
|
+
return actorClient;
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Record a completed tool call, with the account that made it.
|
|
459
|
+
* Arguments stay out: the conversation history keeps them.
|
|
460
|
+
*/
|
|
461
|
+
logToolCallAudit(plugin, toolName, attributes) {
|
|
462
|
+
const usedServiceAccount = this.serviceAccountProviders.has(plugin.manifest.name) && serviceAccountAllows(plugin.manifest, { tool: toolName });
|
|
463
|
+
logAudit("mcp.tool_call.completed", {
|
|
464
|
+
...this.options.auditAttributes,
|
|
465
|
+
...attributes,
|
|
466
|
+
"mcp.method.name": "tools/call",
|
|
467
|
+
"app.plugin.name": plugin.manifest.name,
|
|
468
|
+
"app.credential.account": usedServiceAccount ? "service_account" : "actor"
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
toManagedTool(plugin, client, tool) {
|
|
472
|
+
const outputSchema = toOptionalRecord(tool.outputSchema);
|
|
473
|
+
const annotations = tool.annotations;
|
|
474
|
+
const missingAnnotationKeys = missingToolAnnotationKeys(annotations);
|
|
475
|
+
if (missingAnnotationKeys.length > 0) logWarn("mcp.tool_annotations.missing", {
|
|
476
|
+
"app.plugin.name": plugin.manifest.name,
|
|
477
|
+
"gen_ai.tool.name": tool.name,
|
|
478
|
+
"app.tool.missing_annotations": missingAnnotationKeys.join(",")
|
|
479
|
+
});
|
|
480
|
+
return {
|
|
481
|
+
name: normalizeMcpToolName(plugin.manifest.name, tool.name),
|
|
482
|
+
description: describeMcpTool(plugin.manifest.name, tool),
|
|
483
|
+
parameters: tool.inputSchema,
|
|
484
|
+
provider: plugin.manifest.name,
|
|
485
|
+
rawName: tool.name,
|
|
486
|
+
...tool.title?.trim() ? { title: tool.title.trim() } : void 0,
|
|
487
|
+
...outputSchema ? { outputSchema } : void 0,
|
|
488
|
+
...annotations ? { annotations } : void 0,
|
|
489
|
+
execute: async (args, options) => {
|
|
490
|
+
const resolvedArgs = typeof args === "object" && args !== null ? args : {};
|
|
491
|
+
const conversationPrivacy = options?.conversationPrivacy ?? "private";
|
|
492
|
+
const managedToolName = normalizeMcpToolName(plugin.manifest.name, tool.name);
|
|
493
|
+
const baseAttributes = {
|
|
494
|
+
"mcp.method.name": "tools/call",
|
|
495
|
+
"gen_ai.operation.name": "execute_tool",
|
|
496
|
+
"gen_ai.tool.name": managedToolName,
|
|
497
|
+
"gen_ai.tool.description": describeMcpTool(plugin.manifest.name, tool),
|
|
498
|
+
"gen_ai.tool.type": "function",
|
|
499
|
+
"app.plugin.name": plugin.manifest.name,
|
|
500
|
+
...options?.toolCallId ? { "gen_ai.tool.call.id": options.toolCallId } : void 0
|
|
501
|
+
};
|
|
502
|
+
const argumentAttribute = serializeMcpPayload(resolvedArgs, conversationPrivacy, { privateMetadata: true });
|
|
503
|
+
return await withSpan(`execute_tool ${managedToolName}`, "gen_ai.execute_tool", {}, async () => {
|
|
504
|
+
try {
|
|
505
|
+
const result = await (await this.clientForTool(plugin, client, tool.name)).callTool(tool.name, resolvedArgs, options?.signal);
|
|
506
|
+
if ("isError" in result && result.isError) throw new McpToolError(extractMcpErrorMessage(result));
|
|
507
|
+
this.logToolCallAudit(plugin, tool.name, {
|
|
508
|
+
"gen_ai.tool.name": managedToolName,
|
|
509
|
+
...options?.toolCallId ? { "gen_ai.tool.call.id": options.toolCallId } : void 0
|
|
510
|
+
});
|
|
511
|
+
const resultAttribute = serializeMcpPayload(result, conversationPrivacy, { privateMetadata: true });
|
|
512
|
+
if (resultAttribute) setSpanAttributes({ "gen_ai.tool.call.result": resultAttribute });
|
|
513
|
+
const providerContent = boundMcpContent(toAgentToolContent(result));
|
|
514
|
+
const successResult = {
|
|
515
|
+
content: toModelVisibleMcpContent(result),
|
|
516
|
+
providerContent,
|
|
517
|
+
...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0
|
|
518
|
+
};
|
|
519
|
+
const cards = await this.options.onToolSuccess?.({
|
|
520
|
+
arguments: resolvedArgs,
|
|
521
|
+
content: toAgentToolContent(result),
|
|
522
|
+
provider: plugin.manifest.name,
|
|
523
|
+
...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0,
|
|
524
|
+
toolName: tool.name
|
|
525
|
+
});
|
|
526
|
+
return cards?.length ? {
|
|
527
|
+
...successResult,
|
|
528
|
+
cards
|
|
529
|
+
} : successResult;
|
|
530
|
+
} catch (error) {
|
|
531
|
+
if (error instanceof McpAuthorizationRequiredError && await this.handleAuthorizationRequired(plugin.manifest.name, error, {
|
|
532
|
+
toolName: tool.name,
|
|
533
|
+
...options?.authorizationIntent ? { intent: options.authorizationIntent } : void 0
|
|
534
|
+
})) {
|
|
535
|
+
const parkedContent = [{
|
|
536
|
+
type: "text",
|
|
537
|
+
text: "Authorization pending."
|
|
538
|
+
}];
|
|
539
|
+
return {
|
|
540
|
+
authorizationPending: true,
|
|
541
|
+
content: parkedContent,
|
|
542
|
+
providerContent: parkedContent
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
const errorAttributes = {
|
|
546
|
+
...baseAttributes,
|
|
547
|
+
...getMcpProviderErrorAttributes(error),
|
|
548
|
+
"error.type": getMcpAwareErrorType(error, "mcp_tool_error"),
|
|
549
|
+
"exception.message": getMcpAwareTelemetryMessage(error, conversationPrivacy)
|
|
550
|
+
};
|
|
551
|
+
setSpanAttributes(errorAttributes);
|
|
552
|
+
if (error instanceof McpToolError) logWarn("mcp.tool_call.failed", {
|
|
553
|
+
...this.options.auditAttributes,
|
|
554
|
+
...errorAttributes
|
|
555
|
+
});
|
|
556
|
+
throw error;
|
|
557
|
+
}
|
|
558
|
+
}, {
|
|
559
|
+
...baseAttributes,
|
|
560
|
+
...argumentAttribute ? { "gen_ai.tool.call.arguments": argumentAttribute } : void 0
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
async handleAuthorizationRequired(provider, error, context) {
|
|
566
|
+
const plugin = this.pluginsByProvider.get(provider);
|
|
567
|
+
if (plugin && serviceAccountOnly(plugin.manifest)) {
|
|
568
|
+
this.forgetProvider(provider);
|
|
569
|
+
throw new McpServiceAccountRequiredError(provider, plugin.manifest.displayName);
|
|
570
|
+
}
|
|
571
|
+
if (!this.options.onAuthorizationRequired) return false;
|
|
572
|
+
if (!(await this.options.onAuthorizationRequired(provider, error, context) === true)) return false;
|
|
573
|
+
this.authorizationPendingProviders.add(provider);
|
|
574
|
+
this.forgetProvider(provider);
|
|
575
|
+
return true;
|
|
576
|
+
}
|
|
577
|
+
forgetProvider(provider) {
|
|
578
|
+
for (const clients of [this.clientsByProvider, this.actorClientsByProvider]) {
|
|
579
|
+
const client = clients.get(provider);
|
|
580
|
+
if (client) this.forgottenClients.push(client);
|
|
581
|
+
}
|
|
582
|
+
this.clientsByProvider.delete(provider);
|
|
583
|
+
this.actorClientsByProvider.delete(provider);
|
|
584
|
+
this.serviceAccountProviders.delete(provider);
|
|
585
|
+
this.toolsByProvider.delete(provider);
|
|
586
|
+
this.activeProviders.delete(provider);
|
|
587
|
+
}
|
|
588
|
+
/** Return all active ManagedMcpTool objects, optionally filtered by provider. */
|
|
589
|
+
getResolvedActiveTools(options = {}) {
|
|
590
|
+
const resolved = [];
|
|
591
|
+
for (const provider of this.getActiveProviders()) {
|
|
592
|
+
if (options.provider && provider !== options.provider) continue;
|
|
593
|
+
const wrappedTools = new Set(this.pluginsByProvider.get(provider)?.manifest.mcp?.wrappedTools ?? []);
|
|
594
|
+
resolved.push(...(this.toolsByProvider.get(provider) ?? []).filter((tool) => !wrappedTools.has(tool.rawName)));
|
|
595
|
+
}
|
|
596
|
+
return resolved;
|
|
597
|
+
}
|
|
598
|
+
/** Call one active provider tool declared for plugin-owned wrapping. */
|
|
599
|
+
async callWrappedTool(provider, rawName, args, options) {
|
|
600
|
+
if (!this.activeProviders.has(provider)) throw new McpToolError(`MCP provider is not active: ${provider}`);
|
|
601
|
+
if (!new Set(this.pluginsByProvider.get(provider)?.manifest.mcp?.wrappedTools ?? []).has(rawName)) throw new McpToolError(`Plugin ${provider} cannot call unwrapped MCP tool ${rawName}`);
|
|
602
|
+
const tool = (this.toolsByProvider.get(provider) ?? []).find((candidate) => candidate.rawName === rawName);
|
|
603
|
+
if (!tool) throw new McpToolError(`MCP provider ${provider} does not expose tool ${rawName}`);
|
|
604
|
+
let result;
|
|
605
|
+
try {
|
|
606
|
+
result = await tool.execute(args, {
|
|
607
|
+
conversationPrivacy: "private",
|
|
608
|
+
...options?.toolCallId ? { toolCallId: options.toolCallId } : void 0
|
|
609
|
+
});
|
|
610
|
+
} catch (error) {
|
|
611
|
+
if (error instanceof McpToolError) return {
|
|
612
|
+
status: "error",
|
|
613
|
+
message: error.message
|
|
614
|
+
};
|
|
615
|
+
throw error;
|
|
616
|
+
}
|
|
617
|
+
if (result.authorizationPending) return { status: "authorization_pending" };
|
|
618
|
+
return {
|
|
619
|
+
status: "success",
|
|
620
|
+
content: result.providerContent ?? result.content,
|
|
621
|
+
...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
toToolDescriptor(tool) {
|
|
625
|
+
return {
|
|
626
|
+
name: tool.name,
|
|
627
|
+
rawName: tool.rawName,
|
|
628
|
+
...tool.title ? { title: tool.title } : void 0,
|
|
629
|
+
description: tool.description,
|
|
630
|
+
parameters: tool.parameters,
|
|
631
|
+
...tool.outputSchema ? { outputSchema: tool.outputSchema } : void 0,
|
|
632
|
+
...tool.annotations ? { annotations: tool.annotations } : void 0,
|
|
633
|
+
provider: tool.provider
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
};
|
|
637
|
+
function toOptionalRecord(value) {
|
|
638
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
639
|
+
}
|
|
640
|
+
function serializeMcpPayload(payload, privacy, options = {}) {
|
|
641
|
+
if (privacy !== "private") return serializeGenAiAttribute(payload);
|
|
642
|
+
return options.privateMetadata ? serializeGenAiAttribute(toGenAiPayloadMetadata(payload)) : void 0;
|
|
643
|
+
}
|
|
644
|
+
// src/chat/agent/repository-context.ts
|
|
645
|
+
function findRestoredInstructions(messages, provenance) {
|
|
646
|
+
const restoredContext = messages?.map((message, index) => ({
|
|
647
|
+
message,
|
|
648
|
+
provenance: provenance?.[index]
|
|
649
|
+
})).reverse().find(({ message, provenance: messageProvenance }) => messageProvenance?.authority === "context" ? Boolean(findVisibleAgentsInstructions([message])) : false);
|
|
650
|
+
return restoredContext ? findVisibleAgentsInstructions([restoredContext.message]) : void 0;
|
|
651
|
+
}
|
|
652
|
+
/** Track model-visible AGENTS.md state and append updates before later samples. */
|
|
653
|
+
function createRepositoryInstructionsContext(options) {
|
|
654
|
+
let visibleInstructions = options.shouldPromptAgent ? findVisibleAgentsInstructions([...options.promptHistoryMessages, {
|
|
655
|
+
role: "user",
|
|
656
|
+
content: options.promptContextContentParts
|
|
657
|
+
}]) : findRestoredInstructions(options.restoredMessages, options.restoredProvenance);
|
|
658
|
+
return {
|
|
659
|
+
/**
|
|
660
|
+
* Re-read AGENTS.md and append a context message to `messages` when it
|
|
661
|
+
* changed. Returns whether it set new messages.
|
|
662
|
+
*/
|
|
663
|
+
async applyUpdate(messages) {
|
|
664
|
+
if (!options.hasSandbox()) return false;
|
|
665
|
+
return await withSpan("agent.repository_instructions.refresh", "agent.repository_instructions.refresh", {}, async (setSpanAttributes) => {
|
|
666
|
+
const instructions = await options.capture();
|
|
667
|
+
const outcome = refreshOutcome(instructions);
|
|
668
|
+
setSpanAttributes({ "app.repository_instructions.outcome": outcome });
|
|
669
|
+
if (outcome === "unchanged" || outcome === "none") return false;
|
|
670
|
+
await appendUpdate(instructions, messages);
|
|
671
|
+
return true;
|
|
672
|
+
});
|
|
673
|
+
} };
|
|
674
|
+
function refreshOutcome(instructions) {
|
|
675
|
+
const instructionsVisible = visibleInstructions?.active === true;
|
|
676
|
+
if (!instructions) return instructionsVisible ? "removed" : "none";
|
|
677
|
+
if (!instructionsVisible) return "added";
|
|
678
|
+
return showsAgentsInstructions(visibleInstructions, instructions) ? "unchanged" : "updated";
|
|
679
|
+
}
|
|
680
|
+
async function appendUpdate(instructions, currentMessages) {
|
|
681
|
+
const message = instructions ? buildAgentsInstructionsMessage({
|
|
682
|
+
directory: instructions.directory,
|
|
683
|
+
text: visibleInstructions?.active === true ? `${AGENTS_REPLACEMENT_NOTICE}\n\n${instructions.text}` : instructions.text
|
|
684
|
+
}) : buildAgentsInstructionsMessage({ text: AGENTS_REMOVAL_NOTICE });
|
|
685
|
+
const messages = [...currentMessages, message];
|
|
686
|
+
options.setMessages(messages);
|
|
687
|
+
await options.commit(messages);
|
|
688
|
+
visibleInstructions = instructions ? {
|
|
689
|
+
active: true,
|
|
690
|
+
directory: instructions.directory,
|
|
691
|
+
text: instructions.text
|
|
692
|
+
} : { active: false };
|
|
693
|
+
await options.onTransition?.(instructions);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
// src/chat/pi/traced-stream.ts
|
|
697
|
+
function attributeModeForPrivacy(conversationPrivacy) {
|
|
698
|
+
return conversationPrivacy === "public" ? "content" : "metadata";
|
|
699
|
+
}
|
|
700
|
+
function buildChatStartAttributes(model, context, options, mode, conversationPrivacy, promptName) {
|
|
701
|
+
const attributes = {
|
|
702
|
+
"gen_ai.operation.name": "chat",
|
|
703
|
+
"gen_ai.provider.name": GEN_AI_PROVIDER_NAME,
|
|
704
|
+
"gen_ai.request.model": model.id,
|
|
705
|
+
...promptName ? { "gen_ai.prompt.name": promptName } : void 0,
|
|
706
|
+
"gen_ai.request.stream": true,
|
|
707
|
+
"gen_ai.output.type": "text",
|
|
708
|
+
"server.address": GEN_AI_SERVER_ADDRESS,
|
|
709
|
+
"server.port": 443,
|
|
710
|
+
...options?.temperature !== void 0 ? { "gen_ai.request.temperature": options.temperature } : void 0,
|
|
711
|
+
...options?.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": options.maxTokens } : void 0,
|
|
712
|
+
...options?.reasoning ? { "gen_ai.request.reasoning.level": options.reasoning } : void 0,
|
|
713
|
+
...hasCompactedConversationContext(context.messages) ? { "gen_ai.conversation.compacted": true } : void 0,
|
|
714
|
+
...conversationPrivacy ? { "app.conversation.privacy": conversationPrivacy } : void 0,
|
|
715
|
+
...toGenAiMessagesTraceAttributes("gen_ai.input", context.messages)
|
|
716
|
+
};
|
|
717
|
+
if (mode === "content") {
|
|
718
|
+
const inputMessages = serializeGenAiAttribute(context.messages.map(toCanonicalInputMessage));
|
|
719
|
+
if (inputMessages) attributes["gen_ai.input.messages"] = inputMessages;
|
|
720
|
+
}
|
|
721
|
+
if (context.systemPrompt) {
|
|
722
|
+
if (mode === "content") {
|
|
723
|
+
const systemInstructions = serializeGenAiAttribute([{
|
|
724
|
+
type: "text",
|
|
725
|
+
content: context.systemPrompt
|
|
726
|
+
}]);
|
|
727
|
+
if (systemInstructions) attributes["gen_ai.system_instructions"] = systemInstructions;
|
|
728
|
+
}
|
|
729
|
+
attributes["gen_ai.system_instructions.content_chars"] = context.systemPrompt.length;
|
|
730
|
+
}
|
|
731
|
+
return attributes;
|
|
732
|
+
}
|
|
733
|
+
function buildChatEndAttributes(message, mode) {
|
|
734
|
+
const attributes = { ...toGenAiMessagesTraceAttributes("gen_ai.output", [message]) };
|
|
735
|
+
if (mode === "content") {
|
|
736
|
+
const outputMessages = serializeGenAiAttribute([toCanonicalOutputMessage(message)]);
|
|
737
|
+
if (outputMessages) attributes["gen_ai.output.messages"] = outputMessages;
|
|
738
|
+
}
|
|
739
|
+
Object.assign(attributes, extractGenAiUsageAttributes(message));
|
|
740
|
+
if (message.usage.cacheWrite1h !== void 0) attributes["app.ai.usage.cache_write_1h"] = message.usage.cacheWrite1h;
|
|
741
|
+
if (message.stopReason) attributes["gen_ai.response.finish_reasons"] = [normalizeGenAiFinishReason(message.stopReason)];
|
|
742
|
+
if (message.model) attributes["gen_ai.response.model"] = message.model;
|
|
743
|
+
if (message.responseId) attributes["gen_ai.response.id"] = message.responseId;
|
|
744
|
+
if (message.stopReason === "error") {
|
|
745
|
+
const providerError = createAssistantProviderError(message);
|
|
746
|
+
Object.assign(attributes, getProviderErrorAttributes(providerError));
|
|
747
|
+
attributes["error.type"] = providerError.kind;
|
|
748
|
+
}
|
|
749
|
+
return attributes;
|
|
750
|
+
}
|
|
751
|
+
const NON_CONTENT_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
752
|
+
"start",
|
|
753
|
+
"done",
|
|
754
|
+
"error"
|
|
755
|
+
]);
|
|
756
|
+
function createResponseTiming(requestStartedAtMs) {
|
|
757
|
+
let firstByteAtMs;
|
|
758
|
+
let firstToken;
|
|
759
|
+
return {
|
|
760
|
+
observe: (event) => {
|
|
761
|
+
if (firstByteAtMs === void 0 && event.type !== "error") firstByteAtMs = Date.now();
|
|
762
|
+
if (!firstToken && !NON_CONTENT_EVENT_TYPES.has(event.type)) firstToken = {
|
|
763
|
+
type: event.type,
|
|
764
|
+
receivedAtMs: Date.now()
|
|
765
|
+
};
|
|
766
|
+
},
|
|
767
|
+
attributes: () => {
|
|
768
|
+
if (firstByteAtMs === void 0) return { "gen_ai.response.streaming": false };
|
|
769
|
+
return {
|
|
770
|
+
"gen_ai.response.streaming": true,
|
|
771
|
+
"app.ai.time_to_first_byte_ms": firstByteAtMs - requestStartedAtMs,
|
|
772
|
+
...firstToken ? {
|
|
773
|
+
"gen_ai.response.time_to_first_chunk": (firstToken.receivedAtMs - requestStartedAtMs) / 1e3,
|
|
774
|
+
"app.ai.first_token_type": firstToken.type
|
|
775
|
+
} : void 0
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
function traceResponseHeaders(span, options) {
|
|
781
|
+
const eventLoopStart = performance$1.eventLoopUtilization();
|
|
782
|
+
const onResponse = options?.onResponse;
|
|
783
|
+
return {
|
|
784
|
+
...options,
|
|
785
|
+
onResponse: async (response, model) => {
|
|
786
|
+
try {
|
|
787
|
+
const vercelId = response.headers["x-vercel-id"];
|
|
788
|
+
if (vercelId) span.setAttribute("app.ai.gateway.vercel_id", vercelId);
|
|
789
|
+
const { utilization } = performance$1.eventLoopUtilization(eventLoopStart);
|
|
790
|
+
span.setAttribute("app.ai.event_loop.utilization", Math.round(utilization * 1e3) / 1e3);
|
|
791
|
+
} catch {}
|
|
792
|
+
await onResponse?.(response, model);
|
|
793
|
+
}
|
|
794
|
+
};
|
|
795
|
+
}
|
|
796
|
+
function traceRequestPayload(span, options) {
|
|
378
797
|
const onPayload = options?.onPayload;
|
|
379
798
|
return {
|
|
380
799
|
...options,
|
|
@@ -474,7 +893,7 @@ function createTracedStreamFn(baseOrOptions = streamSimple) {
|
|
|
474
893
|
}
|
|
475
894
|
// src/chat/runtime/dev-agent-trace.ts
|
|
476
895
|
function shouldEmitDevAgentTrace() {
|
|
477
|
-
return process.env
|
|
896
|
+
return process.env["NODE_ENV"] === "development";
|
|
478
897
|
}
|
|
479
898
|
// src/chat/services/turn-result.ts
|
|
480
899
|
/** Process raw agent messages into a structured AgentRunResult. */
|
|
@@ -486,10 +905,11 @@ function buildTurnResult(input) {
|
|
|
486
905
|
const terminalAssistantMessages = getTerminalAssistantMessages(newMessages);
|
|
487
906
|
const blocked = readBlockedReport(newMessages);
|
|
488
907
|
const rawPrimaryText = sanitizeAssistantText(terminalAssistantMessages.map((message) => extractAssistantText(message)).join("\n\n")).trim();
|
|
489
|
-
const
|
|
908
|
+
const noReplyCall = readNoReply(newMessages);
|
|
909
|
+
const primaryText = noReplyCall ? "" : terminalAssistantMessages.map((message) => decideReply(message)).filter((output) => output.kind === "deliver").map((output) => output.text).join("\n\n");
|
|
490
910
|
const terminalTexts = terminalAssistantMessages.map((message) => sanitizeAssistantText(extractAssistantText(message)));
|
|
491
911
|
const legacyMarkerOnly = terminalTexts.some((text) => isLegacyNoReplyMarker(text)) && terminalTexts.every((text) => !text || isLegacyNoReplyMarker(text));
|
|
492
|
-
const noReply =
|
|
912
|
+
const noReply = noReplyCall ?? (!primaryText && legacyMarkerOnly ? {} : void 0);
|
|
493
913
|
const noReplyRequested = Boolean(noReply);
|
|
494
914
|
const toolErrorCount = toolResults.filter((result) => result.isError).length;
|
|
495
915
|
const reactionPerformed = toolResults.some((result) => !isToolResultError(result) && normalizeToolNameFromResult(result) === "addReaction");
|
|
@@ -688,7 +1108,7 @@ function projectTimedOutToolResult(result) {
|
|
|
688
1108
|
const details = result.details;
|
|
689
1109
|
if (!details || typeof details !== "object" || Array.isArray(details) || !("aborted" in details) || details.aborted !== true) return;
|
|
690
1110
|
const record = details;
|
|
691
|
-
const target = typeof record
|
|
1111
|
+
const target = typeof record["target"] === "string" && record["target"].length > 0 ? record["target"] : void 0;
|
|
692
1112
|
const envelope = makeStructuredToolOutput({
|
|
693
1113
|
...target ? { target } : void 0,
|
|
694
1114
|
timed_out: true
|
|
@@ -828,8 +1248,8 @@ function isRecord$2(value) {
|
|
|
828
1248
|
}
|
|
829
1249
|
/** Read a core-owned action rejection marker from one durable Pi message. */
|
|
830
1250
|
function getToolActionRejectionMarker(message) {
|
|
831
|
-
if (!isRecord$2(message) || !isRecord$2(message
|
|
832
|
-
const parsed = rejectionMarkerSchema.safeParse(message
|
|
1251
|
+
if (!isRecord$2(message) || !isRecord$2(message["details"])) return;
|
|
1252
|
+
const parsed = rejectionMarkerSchema.safeParse(message["details"]["guardianActionRejection"]);
|
|
833
1253
|
return parsed.success ? parsed.data : void 0;
|
|
834
1254
|
}
|
|
835
1255
|
/**
|
|
@@ -837,8 +1257,8 @@ function getToolActionRejectionMarker(message) {
|
|
|
837
1257
|
* call order. The bridge copies each marker from the gate.
|
|
838
1258
|
*/
|
|
839
1259
|
function getCodeModeRejectionMarkers(message) {
|
|
840
|
-
if (message
|
|
841
|
-
return message
|
|
1260
|
+
if (message["toolName"] !== "codemode" || !isRecord$2(message["details"]) || !Array.isArray(message["details"]["calls"])) return [];
|
|
1261
|
+
return message["details"]["calls"].flatMap((call) => {
|
|
842
1262
|
const marker = getToolActionRejectionMarker({ details: call });
|
|
843
1263
|
return marker ? [marker] : [];
|
|
844
1264
|
});
|
|
@@ -886,7 +1306,7 @@ function restoreToolActionRejections(messages) {
|
|
|
886
1306
|
const record = message;
|
|
887
1307
|
if (record.role !== "toolResult") continue;
|
|
888
1308
|
for (const rejection of getCodeModeRejectionMarkers(record)) addPriorRejection(priorRejections, rejection.priorRejection);
|
|
889
|
-
if (record.isError
|
|
1309
|
+
if (!record.isError) continue;
|
|
890
1310
|
const rejection = getToolActionRejectionMarker(record);
|
|
891
1311
|
if (!rejection) continue;
|
|
892
1312
|
addPriorRejection(priorRejections, rejection.priorRejection);
|
|
@@ -1458,7 +1878,7 @@ function captureOutput(output) {
|
|
|
1458
1878
|
};
|
|
1459
1879
|
}
|
|
1460
1880
|
function parseKeepAliveMs() {
|
|
1461
|
-
const parsed = Number.parseInt(process.env
|
|
1881
|
+
const parsed = Number.parseInt(process.env["VERCEL_SANDBOX_KEEPALIVE_MS"] ?? "0", 10);
|
|
1462
1882
|
return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
|
|
1463
1883
|
}
|
|
1464
1884
|
function getCommandAbortedResult() {
|
|
@@ -1790,7 +2210,7 @@ function createSandboxRuntime(options) {
|
|
|
1790
2210
|
"app.sandbox.runtime": SANDBOX_RUNTIME,
|
|
1791
2211
|
"app.sandbox.skills_count": availableSkills.length
|
|
1792
2212
|
}, async (setSpanAttributes) => {
|
|
1793
|
-
const cachedSandbox =
|
|
2213
|
+
const cachedSandbox = tryReuseCachedSandbox();
|
|
1794
2214
|
if (cachedSandbox) {
|
|
1795
2215
|
setSpanAttributes({ "app.sandbox.acquire.outcome": "memory" });
|
|
1796
2216
|
return {
|
|
@@ -1883,7 +2303,7 @@ function createSandboxRuntime(options) {
|
|
|
1883
2303
|
if (keepAliveMs === 0 || closed || keepAliveTimer) return;
|
|
1884
2304
|
const intervalMs = Math.max(MIN_KEEPALIVE_INTERVAL_MS, Math.min(MAX_KEEPALIVE_INTERVAL_MS, Math.floor(keepAliveMs / 2)));
|
|
1885
2305
|
const schedule = () => {
|
|
1886
|
-
|
|
2306
|
+
const tick = async () => {
|
|
1887
2307
|
keepAliveTimer = void 0;
|
|
1888
2308
|
if (closed || activeSandbox?.session !== session) return;
|
|
1889
2309
|
try {
|
|
@@ -1894,7 +2314,8 @@ function createSandboxRuntime(options) {
|
|
|
1894
2314
|
}
|
|
1895
2315
|
if (closed || activeSandbox?.session !== session) return;
|
|
1896
2316
|
schedule();
|
|
1897
|
-
}
|
|
2317
|
+
};
|
|
2318
|
+
keepAliveTimer = setTimeout(() => void tick(), intervalMs);
|
|
1898
2319
|
keepAliveTimer.unref?.();
|
|
1899
2320
|
};
|
|
1900
2321
|
schedule();
|
|
@@ -2167,9 +2588,9 @@ function createSandbox(options) {
|
|
|
2167
2588
|
});
|
|
2168
2589
|
};
|
|
2169
2590
|
const executeBashTool = async (rawInput, command, context) => {
|
|
2170
|
-
const env = parseEnv(rawInput
|
|
2171
|
-
const cwd = typeof rawInput
|
|
2172
|
-
const timeoutMs = positiveInteger(rawInput
|
|
2591
|
+
const env = parseEnv(rawInput["env"]);
|
|
2592
|
+
const cwd = typeof rawInput["cwd"] === "string" ? resolveWorkspacePath(rawInput["cwd"]) : SANDBOX_WORKSPACE_ROOT;
|
|
2593
|
+
const timeoutMs = positiveInteger(rawInput["timeoutMs"]);
|
|
2173
2594
|
logSandboxBootRequest("tool.bash", { "app.sandbox.command_length": command.length });
|
|
2174
2595
|
let tools = await runtime.tools(context.signal);
|
|
2175
2596
|
const waitStartedAtMs = Date.now();
|
|
@@ -2223,10 +2644,10 @@ function createSandbox(options) {
|
|
|
2223
2644
|
}
|
|
2224
2645
|
};
|
|
2225
2646
|
const executeReadFileTool = async (rawInput, context) => {
|
|
2226
|
-
const filePath = String(rawInput
|
|
2647
|
+
const filePath = String(rawInput["path"] ?? "").trim();
|
|
2227
2648
|
if (!filePath) throw new ToolInputError("path is required");
|
|
2228
|
-
const offset = positiveInteger(rawInput
|
|
2229
|
-
const limit = positiveInteger(rawInput
|
|
2649
|
+
const offset = positiveInteger(rawInput["offset"]);
|
|
2650
|
+
const limit = positiveInteger(rawInput["limit"]);
|
|
2230
2651
|
if (!runtime.sandboxRef()) {
|
|
2231
2652
|
const hostPath = resolveHostSkillPath(options.skills, filePath) ?? resolveHostDataPath(options.referenceFiles, filePath);
|
|
2232
2653
|
if (hostPath) try {
|
|
@@ -2279,10 +2700,10 @@ function createSandbox(options) {
|
|
|
2279
2700
|
});
|
|
2280
2701
|
};
|
|
2281
2702
|
const executeWriteFileTool = async (rawInput, context) => {
|
|
2282
|
-
const filePath = String(rawInput
|
|
2703
|
+
const filePath = String(rawInput["path"] ?? "").trim();
|
|
2283
2704
|
if (!filePath) throw new ToolInputError("path is required");
|
|
2284
2705
|
const workspacePath = resolveWorkspacePath(filePath);
|
|
2285
|
-
const content = String(rawInput
|
|
2706
|
+
const content = String(rawInput["content"] ?? "");
|
|
2286
2707
|
logSandboxBootRequest("tool.writeFile", { "file.path": filePath });
|
|
2287
2708
|
const fileSystem = await context.fileSystem();
|
|
2288
2709
|
await withSandboxToolSpan("sandbox.writeFile", "sandbox.fs.write", {
|
|
@@ -2304,19 +2725,19 @@ function createSandbox(options) {
|
|
|
2304
2725
|
});
|
|
2305
2726
|
};
|
|
2306
2727
|
const executeEditFileTool = async (rawInput, context) => {
|
|
2307
|
-
const filePath = String(rawInput
|
|
2728
|
+
const filePath = String(rawInput["path"] ?? "").trim();
|
|
2308
2729
|
if (!filePath) throw new ToolInputError("path is required");
|
|
2309
|
-
if (!Array.isArray(rawInput
|
|
2730
|
+
if (!Array.isArray(rawInput["edits"])) throw new ToolInputError("edits is required");
|
|
2310
2731
|
logSandboxBootRequest("tool.editFile", { "file.path": filePath });
|
|
2311
2732
|
const fileSystem = await context.fileSystem();
|
|
2312
2733
|
return await withSandboxToolSpan("sandbox.editFile", "sandbox.fs.edit", {
|
|
2313
2734
|
"app.sandbox.path.length": filePath.length,
|
|
2314
|
-
"app.sandbox.edit.count": rawInput
|
|
2735
|
+
"app.sandbox.edit.count": rawInput["edits"].length
|
|
2315
2736
|
}, async () => {
|
|
2316
2737
|
const response = await editFile({
|
|
2317
2738
|
fs: fileSystem,
|
|
2318
2739
|
path: filePath,
|
|
2319
|
-
edits: rawInput
|
|
2740
|
+
edits: rawInput["edits"]
|
|
2320
2741
|
});
|
|
2321
2742
|
setSpanStatus("ok");
|
|
2322
2743
|
return response;
|
|
@@ -2325,7 +2746,7 @@ function createSandbox(options) {
|
|
|
2325
2746
|
const execute = async (params) => {
|
|
2326
2747
|
const rawInput = params.input ?? {};
|
|
2327
2748
|
const context = createToolCallContext(params.signal);
|
|
2328
|
-
const bashCommand = params.toolName === "bash" ? String(rawInput
|
|
2749
|
+
const bashCommand = params.toolName === "bash" ? String(rawInput["command"] ?? "").trim() : void 0;
|
|
2329
2750
|
if (params.toolName === "bash") {
|
|
2330
2751
|
if (!bashCommand) throw new ToolInputError("command is required");
|
|
2331
2752
|
}
|
|
@@ -2538,8 +2959,8 @@ function isToolContent(value) {
|
|
|
2538
2959
|
return Array.isArray(value) && value.every((part) => {
|
|
2539
2960
|
if (!part || typeof part !== "object") return false;
|
|
2540
2961
|
const record = part;
|
|
2541
|
-
if (record
|
|
2542
|
-
if (record
|
|
2962
|
+
if (record["type"] === "text") return typeof record["text"] === "string";
|
|
2963
|
+
if (record["type"] === "image") return typeof record["data"] === "string" && typeof record["mimeType"] === "string";
|
|
2543
2964
|
return false;
|
|
2544
2965
|
});
|
|
2545
2966
|
}
|
|
@@ -2574,7 +2995,7 @@ function isRecord$1(value) {
|
|
|
2574
2995
|
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
2575
2996
|
}
|
|
2576
2997
|
function hasContinuation(value) {
|
|
2577
|
-
return isRecord$1(value) && isRecord$1(value
|
|
2998
|
+
return isRecord$1(value) && isRecord$1(value["continuation"]);
|
|
2578
2999
|
}
|
|
2579
3000
|
function stringField(record, key) {
|
|
2580
3001
|
const value = record[key];
|
|
@@ -2615,22 +3036,22 @@ function policyDeniedText(value, signal) {
|
|
|
2615
3036
|
].join("\n");
|
|
2616
3037
|
}
|
|
2617
3038
|
function permissionDeniedText(value) {
|
|
2618
|
-
if (!isRecord$1(value) || !isRecord$1(value
|
|
2619
|
-
const signal = value
|
|
2620
|
-
if (signal
|
|
2621
|
-
if (signal
|
|
3039
|
+
if (!isRecord$1(value) || !isRecord$1(value["permission_denied"])) return;
|
|
3040
|
+
const signal = value["permission_denied"];
|
|
3041
|
+
if (signal["source"] === "policy") return policyDeniedText(value, signal);
|
|
3042
|
+
if (signal["source"] !== "upstream") return;
|
|
2622
3043
|
const provider = stringField(signal, "provider");
|
|
2623
3044
|
const message = stringField(signal, "message");
|
|
2624
3045
|
const upstreamHost = stringField(signal, "upstreamHost");
|
|
2625
3046
|
const upstreamPath = stringField(signal, "upstreamPath");
|
|
2626
3047
|
const status = numberField(signal, "status");
|
|
2627
3048
|
if (!provider || !message || !upstreamHost || !upstreamPath || !status) return;
|
|
2628
|
-
const grant = isRecord$1(signal
|
|
3049
|
+
const grant = isRecord$1(signal["grant"]) ? signal["grant"] : {};
|
|
2629
3050
|
const grantName = stringField(grant, "name");
|
|
2630
3051
|
const grantAccess = stringField(grant, "access");
|
|
2631
3052
|
const grantReason = stringField(grant, "reason");
|
|
2632
3053
|
const grantRequirements = stringListField(grant, "requirements");
|
|
2633
|
-
const account = accountText(signal
|
|
3054
|
+
const account = accountText(signal["account"]);
|
|
2634
3055
|
const command = stringField(value, "command");
|
|
2635
3056
|
const stderr = stringField(value, "stderr").trim();
|
|
2636
3057
|
const stdout = stringField(value, "stdout").trim();
|
|
@@ -2698,7 +3119,7 @@ function record(value) {
|
|
|
2698
3119
|
function textContent(value) {
|
|
2699
3120
|
return Array.isArray(value) ? value.flatMap((part) => {
|
|
2700
3121
|
const item = record(part);
|
|
2701
|
-
return item
|
|
3122
|
+
return item["type"] === "text" && typeof item["text"] === "string" ? [item["text"]] : [];
|
|
2702
3123
|
}).join("\n") : "";
|
|
2703
3124
|
}
|
|
2704
3125
|
/** Adapt agent sandbox execution for plugin-owned workspace tools. */
|
|
@@ -2723,15 +3144,15 @@ function createPluginToolSandbox(sandbox, options) {
|
|
|
2723
3144
|
await options.handleAuthSignal(normalized.details);
|
|
2724
3145
|
input.signal?.throwIfAborted();
|
|
2725
3146
|
const details = record(normalized.details);
|
|
2726
|
-
if (details
|
|
3147
|
+
if (details["status"] === "building") return {
|
|
2727
3148
|
exitCode: 1,
|
|
2728
3149
|
stdout: "",
|
|
2729
|
-
stderr: (typeof details
|
|
3150
|
+
stderr: (typeof details["message"] === "string" && details["message"].trim() ? details["message"].trim() : textContent(normalized.content).trim()) || "The workspace is still preparing its sandbox. Wait for that preparation to finish, then try again."
|
|
2730
3151
|
};
|
|
2731
3152
|
return {
|
|
2732
|
-
exitCode: typeof details
|
|
2733
|
-
stdout: typeof details
|
|
2734
|
-
stderr: details
|
|
3153
|
+
exitCode: typeof details["exit_code"] === "number" ? details["exit_code"] : 1,
|
|
3154
|
+
stdout: typeof details["stdout"] === "string" ? details["stdout"] : "",
|
|
3155
|
+
stderr: details["permission_denied"] !== void 0 ? textContent(normalized.content) : typeof details["stderr"] === "string" ? details["stderr"] : ""
|
|
2735
3156
|
};
|
|
2736
3157
|
},
|
|
2737
3158
|
async writeFile(input) {
|
|
@@ -2801,738 +3222,716 @@ function createAgentSandbox(options) {
|
|
|
2801
3222
|
}
|
|
2802
3223
|
};
|
|
2803
3224
|
}
|
|
2804
|
-
// src/chat/
|
|
2805
|
-
|
|
2806
|
-
const
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
}
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
|
|
2825
|
-
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
}
|
|
2834
|
-
continue;
|
|
2835
|
-
}
|
|
2836
|
-
if (part.type === "image") {
|
|
2837
|
-
content.push({
|
|
2838
|
-
type: "image",
|
|
2839
|
-
data: part.data,
|
|
2840
|
-
mimeType: part.mimeType
|
|
2841
|
-
});
|
|
2842
|
-
continue;
|
|
2843
|
-
}
|
|
2844
|
-
if (part.type === "audio") {
|
|
2845
|
-
content.push({
|
|
2846
|
-
type: "text",
|
|
2847
|
-
text: `Audio output (${part.mimeType}, ${part.data.length} base64 chars)`
|
|
2848
|
-
});
|
|
2849
|
-
continue;
|
|
2850
|
-
}
|
|
2851
|
-
if (part.type === "resource_link") {
|
|
2852
|
-
content.push({
|
|
2853
|
-
type: "text",
|
|
2854
|
-
text: part.uri
|
|
2855
|
-
});
|
|
2856
|
-
continue;
|
|
3225
|
+
// src/chat/sandbox/tool-source.ts
|
|
3226
|
+
/** Deferred tool catalog source for sandbox preview URLs. */
|
|
3227
|
+
const SANDBOX_TOOL_SOURCE = {
|
|
3228
|
+
id: "sandbox",
|
|
3229
|
+
description: "Create public preview URLs for servers in the sandbox."
|
|
3230
|
+
};
|
|
3231
|
+
// src/chat/tools/sandbox/create-preview.ts
|
|
3232
|
+
const outputSchema$2 = juniorToolOutputSchema.extend({ url: z.string().url() });
|
|
3233
|
+
/**
|
|
3234
|
+
* Create a tool that gives a running sandbox server a public preview URL.
|
|
3235
|
+
*
|
|
3236
|
+
* @runBuilt createPreview
|
|
3237
|
+
*/
|
|
3238
|
+
function createCreatePreviewTool(createPreview) {
|
|
3239
|
+
return zodTool({
|
|
3240
|
+
exposure: "deferred",
|
|
3241
|
+
source: SANDBOX_TOOL_SOURCE,
|
|
3242
|
+
annotations: {
|
|
3243
|
+
destructiveHint: false,
|
|
3244
|
+
idempotentHint: true,
|
|
3245
|
+
openWorldHint: true,
|
|
3246
|
+
readOnlyHint: false
|
|
3247
|
+
},
|
|
3248
|
+
approvalMode: "approve",
|
|
3249
|
+
description: "Create a public HTTPS preview URL for a server running in the sandbox. Anyone with the URL can open it until the sandbox stops. The URL for a port stays the same while the sandbox runs. Use it after you build or change something that a person can open in a browser, such as a web page or app, so they can try it.",
|
|
3250
|
+
executionMode: "sequential",
|
|
3251
|
+
inputSchema: z.object({ port: z.number().int().min(1).max(65535).describe("Port that the server listens on. The server must listen on 0.0.0.0.") }).strict(),
|
|
3252
|
+
outputSchema: outputSchema$2,
|
|
3253
|
+
async execute({ port }) {
|
|
3254
|
+
return { url: await createPreview(port) };
|
|
2857
3255
|
}
|
|
2858
|
-
|
|
2859
|
-
type: "text",
|
|
2860
|
-
text: summarizeResourcePart(part)
|
|
2861
|
-
});
|
|
2862
|
-
}
|
|
2863
|
-
if (content.length > 0) return content;
|
|
2864
|
-
const structured = summarizeStructuredContent(result.structuredContent);
|
|
2865
|
-
if (structured) return [{
|
|
2866
|
-
type: "text",
|
|
2867
|
-
text: structured
|
|
2868
|
-
}];
|
|
2869
|
-
return [{
|
|
2870
|
-
type: "text",
|
|
2871
|
-
text: "ok"
|
|
2872
|
-
}];
|
|
2873
|
-
}
|
|
2874
|
-
function utf8Bytes(value) {
|
|
2875
|
-
return Buffer.byteLength(value, "utf8");
|
|
2876
|
-
}
|
|
2877
|
-
function prefixWithin(value, maxChars, maxBytes) {
|
|
2878
|
-
let low = 0;
|
|
2879
|
-
let high = Math.min(value.length, maxChars);
|
|
2880
|
-
while (low < high) {
|
|
2881
|
-
const middle = Math.ceil((low + high) / 2);
|
|
2882
|
-
if (utf8Bytes(value.slice(0, middle)) <= maxBytes) low = middle;
|
|
2883
|
-
else high = middle - 1;
|
|
2884
|
-
}
|
|
2885
|
-
if (low > 0 && /[\uD800-\uDBFF]/.test(value[low - 1])) low -= 1;
|
|
2886
|
-
return value.slice(0, low);
|
|
3256
|
+
});
|
|
2887
3257
|
}
|
|
2888
|
-
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
|
|
2892
|
-
|
|
2893
|
-
|
|
2894
|
-
|
|
2895
|
-
|
|
2896
|
-
|
|
2897
|
-
|
|
3258
|
+
// src/personal-tokens/preview-origins.ts
|
|
3259
|
+
/**
|
|
3260
|
+
* Previews that may receive a personal token from the dashboard.
|
|
3261
|
+
*
|
|
3262
|
+
* A Preview host such as `sb-*.vercel.run` can belong to anyone, so a host
|
|
3263
|
+
* pattern cannot say which Previews are safe. Junior records each Preview
|
|
3264
|
+
* that it creates, with the email of each person who asked for it. Only those
|
|
3265
|
+
* people can send a token to it, and only until their record expires.
|
|
3266
|
+
*/
|
|
3267
|
+
const PREVIEW_ORIGIN_TTL_MS = 864e5;
|
|
3268
|
+
function previewOriginKey(origin, email) {
|
|
3269
|
+
return `junior:preview-origin:v2:${origin}:${email.trim().toLowerCase()}`;
|
|
2898
3270
|
}
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
const originalTokens = estimateTextTokens(text);
|
|
2903
|
-
if (originalTokens <= MAX_TOOL_RESULT_TOKENS && originalBytes <= MAX_TOOL_RESULT_BYTES) return content;
|
|
2904
|
-
const warning = `\n\nWarning: truncated output (original token count: ${originalTokens}; original bytes: ${originalBytes})\n\n`;
|
|
2905
|
-
const remainingChars = textCharsForTokens(MAX_TOOL_RESULT_TOKENS) - warning.length;
|
|
2906
|
-
const remainingBytes = MAX_TOOL_RESULT_BYTES - utf8Bytes(warning);
|
|
2907
|
-
const head = prefixWithin(text, Math.ceil(remainingChars / 2), Math.ceil(remainingBytes / 2));
|
|
2908
|
-
return [{
|
|
2909
|
-
type: "text",
|
|
2910
|
-
text: `${head}${warning}${suffixWithin(text.slice(head.length), remainingChars - head.length, remainingBytes - utf8Bytes(head))}`
|
|
2911
|
-
}, ...content.filter((part) => part.type === "image")];
|
|
3271
|
+
/** Record that one person asked Junior for the Preview at `url`. */
|
|
3272
|
+
async function recordPreviewOrigin(args) {
|
|
3273
|
+
await getStateAdapter().set(previewOriginKey(new URL(args.url).origin, args.ownerEmail), true, PREVIEW_ORIGIN_TTL_MS);
|
|
2912
3274
|
}
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
|
|
2920
|
-
|
|
2921
|
-
|
|
3275
|
+
/**
|
|
3276
|
+
* Renew the records of the Previews that a resumed Sandbox serves again, for
|
|
3277
|
+
* the person whose turn resumed it.
|
|
3278
|
+
*/
|
|
3279
|
+
async function renewPreviewOrigins(sandbox, resolveOwner) {
|
|
3280
|
+
const urls = sandbox.previewUrls?.() ?? [];
|
|
3281
|
+
if (urls.length === 0) return;
|
|
3282
|
+
await runBestEffort(async () => {
|
|
3283
|
+
const owner = await resolveOwner();
|
|
3284
|
+
if (!owner) return;
|
|
3285
|
+
await Promise.all(urls.map(async (url) => await recordPreviewOrigin({
|
|
3286
|
+
ownerEmail: owner.email,
|
|
3287
|
+
url
|
|
3288
|
+
})));
|
|
3289
|
+
}, "sandbox.preview_origin.renew.failed");
|
|
2922
3290
|
}
|
|
2923
|
-
|
|
2924
|
-
|
|
3291
|
+
/** Return true when Junior made the Preview at `origin` for this person. */
|
|
3292
|
+
async function previewOriginBelongsTo(args) {
|
|
3293
|
+
return await getStateAdapter().get(previewOriginKey(args.origin, args.email)) !== null;
|
|
2925
3294
|
}
|
|
2926
|
-
|
|
2927
|
-
|
|
2928
|
-
|
|
2929
|
-
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
3295
|
+
// src/chat/tools/sandbox/image-files.ts
|
|
3296
|
+
/**
|
|
3297
|
+
* Read a sandbox image for a model request. The file signature, not the file
|
|
3298
|
+
* name, sets the MIME type.
|
|
3299
|
+
*/
|
|
3300
|
+
async function readSandboxImage(path, readFile, maxBytes) {
|
|
3301
|
+
const targetPath = normalizeSandboxPath(path);
|
|
3302
|
+
const data = await readFile(targetPath);
|
|
3303
|
+
if (!data) throw new SandboxFileNotFoundError(targetPath);
|
|
3304
|
+
if (data.byteLength === 0) throw new ToolInputError(`image file is empty: ${targetPath}`);
|
|
3305
|
+
if (data.byteLength > maxBytes) throw new ToolInputError(`image exceeds ${maxBytes} bytes: ${targetPath} (${data.byteLength} bytes). Make the image smaller first.`);
|
|
3306
|
+
const mimeType = detectImageMediaType(data);
|
|
3307
|
+
if (!mimeType) throw new ToolInputError(`not a readable image: ${targetPath} exists, but its content is not PNG, JPEG, GIF, or WebP data`);
|
|
3308
|
+
return {
|
|
3309
|
+
data,
|
|
3310
|
+
mimeType
|
|
3311
|
+
};
|
|
2933
3312
|
}
|
|
2934
|
-
|
|
2935
|
-
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2940
|
-
|
|
2941
|
-
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
|
|
2964
|
-
|
|
2965
|
-
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
2974
|
-
|
|
2975
|
-
}
|
|
2976
|
-
|
|
2977
|
-
|
|
2978
|
-
|
|
2979
|
-
|
|
2980
|
-
|
|
2981
|
-
|
|
2982
|
-
|
|
2983
|
-
|
|
2984
|
-
|
|
2985
|
-
|
|
2986
|
-
]) try {
|
|
2987
|
-
await client.close();
|
|
2988
|
-
} catch (error) {
|
|
2989
|
-
firstError ??= error;
|
|
2990
|
-
}
|
|
2991
|
-
this.clientsByProvider.clear();
|
|
2992
|
-
this.actorClientsByProvider.clear();
|
|
2993
|
-
this.forgottenClients.length = 0;
|
|
2994
|
-
this.serviceAccountProviders.clear();
|
|
2995
|
-
this.toolsByProvider.clear();
|
|
2996
|
-
this.activeProviders.clear();
|
|
2997
|
-
this.authorizationPendingProviders.clear();
|
|
2998
|
-
if (firstError) throw firstError;
|
|
2999
|
-
}
|
|
3000
|
-
/** Return descriptors for all active MCP provider tools, optionally filtered by provider. */
|
|
3001
|
-
getActiveToolCatalog(options = {}) {
|
|
3002
|
-
return this.getResolvedActiveTools(options).map((tool) => this.toToolDescriptor(tool));
|
|
3003
|
-
}
|
|
3004
|
-
filterListedTools(plugin, tools) {
|
|
3005
|
-
const allowedTools = plugin.manifest.mcp?.allowedTools;
|
|
3006
|
-
if (!allowedTools || allowedTools.length === 0) return tools;
|
|
3007
|
-
const availableToolNames = new Set(tools.map((tool) => tool.name));
|
|
3008
|
-
const missingTools = allowedTools.filter((toolName) => !availableToolNames.has(toolName));
|
|
3009
|
-
if (missingTools.length > 0) throw new Error(`Plugin ${plugin.manifest.name} MCP discovery missing allowlisted tools: ${missingTools.join(", ")}`);
|
|
3010
|
-
const loadedToolSet = /* @__PURE__ */ new Set([...allowedTools, ...plugin.manifest.mcp?.wrappedTools ?? []]);
|
|
3011
|
-
return tools.filter((tool) => loadedToolSet.has(tool.name));
|
|
3012
|
-
}
|
|
3013
|
-
assertWrappedToolsAvailable(plugin, tools) {
|
|
3014
|
-
const wrappedTools = plugin.manifest.mcp?.wrappedTools ?? [];
|
|
3015
|
-
if (wrappedTools.length === 0) return;
|
|
3016
|
-
const availableToolNames = new Set(tools.map((tool) => tool.name));
|
|
3017
|
-
const missingTools = wrappedTools.filter((toolName) => !availableToolNames.has(toolName));
|
|
3018
|
-
if (missingTools.length > 0) throw new Error(`Plugin ${plugin.manifest.name} MCP discovery missing wrapped tools: ${missingTools.join(", ")}`);
|
|
3019
|
-
}
|
|
3020
|
-
/**
|
|
3021
|
-
* Hide tools that the service account does not list when no Actor
|
|
3022
|
-
* connection exists to call them.
|
|
3023
|
-
*/
|
|
3024
|
-
filterServiceAccountOnlyTools(plugin, tools) {
|
|
3025
|
-
if (!serviceAccountOnly(plugin.manifest)) return tools;
|
|
3026
|
-
return tools.filter((tool) => serviceAccountAllows(plugin.manifest, { tool: tool.name }));
|
|
3027
|
-
}
|
|
3028
|
-
async getClient(plugin) {
|
|
3029
|
-
const existing = this.clientsByProvider.get(plugin.manifest.name);
|
|
3030
|
-
if (existing) return existing;
|
|
3031
|
-
const pending = this.clientPromisesByProvider.get(plugin.manifest.name);
|
|
3032
|
-
if (pending) return await pending;
|
|
3033
|
-
const clientPromise = this.createClient(plugin);
|
|
3034
|
-
this.clientPromisesByProvider.set(plugin.manifest.name, clientPromise);
|
|
3035
|
-
try {
|
|
3036
|
-
return await clientPromise;
|
|
3037
|
-
} finally {
|
|
3038
|
-
if (this.clientPromisesByProvider.get(plugin.manifest.name) === clientPromise) this.clientPromisesByProvider.delete(plugin.manifest.name);
|
|
3039
|
-
}
|
|
3040
|
-
}
|
|
3041
|
-
async createClient(plugin) {
|
|
3042
|
-
const serviceAccount = await this.options.serviceAccountProviderFactory?.(plugin);
|
|
3043
|
-
if (serviceAccount) this.serviceAccountProviders.add(plugin.manifest.name);
|
|
3044
|
-
const client = await this.newClient(plugin, serviceAccount);
|
|
3045
|
-
this.clientsByProvider.set(plugin.manifest.name, client);
|
|
3046
|
-
return client;
|
|
3047
|
-
}
|
|
3048
|
-
async newClient(plugin, serviceAccount) {
|
|
3049
|
-
if (!serviceAccount && serviceAccountOnly(plugin.manifest)) throw new McpServiceAccountRequiredError(plugin.manifest.name, plugin.manifest.displayName);
|
|
3050
|
-
const authProvider = serviceAccount ?? await this.options.authProviderFactory?.(plugin);
|
|
3051
|
-
return new PluginMcpClient(plugin, {
|
|
3052
|
-
...authProvider ? { authProvider } : void 0,
|
|
3053
|
-
...this.options.fetch ? { fetch: this.options.fetch } : void 0
|
|
3313
|
+
// src/chat/artifacts/tool-source.ts
|
|
3314
|
+
/** Deferred tool catalog source for generated, edited, and published images. */
|
|
3315
|
+
const IMAGES_TOOL_SOURCE = {
|
|
3316
|
+
id: "images",
|
|
3317
|
+
description: "Generate or edit images, and publish or unpublish public image URLs."
|
|
3318
|
+
};
|
|
3319
|
+
// src/chat/tools/web/image-generate.ts
|
|
3320
|
+
const MAX_REQUEST_IMAGE_BYTES = 3145728;
|
|
3321
|
+
const MAX_SOURCE_IMAGE_BYTES = 26214400;
|
|
3322
|
+
const RESIZE_LONGEST_EDGES = [
|
|
3323
|
+
2048,
|
|
3324
|
+
1536,
|
|
3325
|
+
1024,
|
|
3326
|
+
768
|
|
3327
|
+
];
|
|
3328
|
+
const resizedImageSchema = z.object({
|
|
3329
|
+
path: z.string(),
|
|
3330
|
+
original_bytes: z.number().int().positive(),
|
|
3331
|
+
bytes: z.number().int().positive(),
|
|
3332
|
+
width: z.number().int().positive(),
|
|
3333
|
+
height: z.number().int().positive()
|
|
3334
|
+
}).strict();
|
|
3335
|
+
const imageGenerateOutputSchema = juniorToolOutputSchema.extend({
|
|
3336
|
+
model: z.string(),
|
|
3337
|
+
prompt: z.string(),
|
|
3338
|
+
enriched_prompt: z.string(),
|
|
3339
|
+
image_count: z.number().int().nonnegative(),
|
|
3340
|
+
images: z.array(generatedArtifactFileRefSchema),
|
|
3341
|
+
delivery: z.string(),
|
|
3342
|
+
resized_images: z.array(resizedImageSchema).optional(),
|
|
3343
|
+
resize_notice: z.string().optional()
|
|
3344
|
+
}).strict();
|
|
3345
|
+
const ENRICHMENT_SYSTEM_PROMPT = `You are an image prompt enrichment agent. Your job is to rewrite image generation requests to reflect a specific visual identity and mood.
|
|
3346
|
+
|
|
3347
|
+
<personality>
|
|
3348
|
+
${JUNIOR_PERSONALITY}
|
|
3349
|
+
</personality>
|
|
3350
|
+
|
|
3351
|
+
Rewrite the user's image request into a detailed image generation prompt that encodes this personality's visual aesthetic. Output ONLY the rewritten prompt text — no explanation, no wrapper.`;
|
|
3352
|
+
async function enrichImagePrompt(rawPrompt, cost) {
|
|
3353
|
+
try {
|
|
3354
|
+
const { text } = await completeText({
|
|
3355
|
+
operation: "image_prompt_enrichment",
|
|
3356
|
+
cost,
|
|
3357
|
+
modelId: botConfig.fastModelId,
|
|
3358
|
+
system: ENRICHMENT_SYSTEM_PROMPT,
|
|
3359
|
+
messages: [{
|
|
3360
|
+
role: "user",
|
|
3361
|
+
content: rawPrompt,
|
|
3362
|
+
timestamp: Date.now()
|
|
3363
|
+
}],
|
|
3364
|
+
maxTokens: 1024
|
|
3054
3365
|
});
|
|
3366
|
+
if (text && text.trim().length > 0) {
|
|
3367
|
+
logInfo("image.prompt.enriched", { "app.image.enriched_prompt_length": text.trim().length });
|
|
3368
|
+
return text.trim();
|
|
3369
|
+
}
|
|
3370
|
+
return rawPrompt;
|
|
3371
|
+
} catch (error) {
|
|
3372
|
+
logWarn("image.prompt.enrichment.failed", { "exception.message": String(error) });
|
|
3373
|
+
return rawPrompt;
|
|
3055
3374
|
}
|
|
3056
|
-
|
|
3057
|
-
|
|
3058
|
-
|
|
3059
|
-
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
/**
|
|
3068
|
-
* Record a completed tool call, with the account that made it.
|
|
3069
|
-
* Arguments stay out: the conversation history keeps them.
|
|
3070
|
-
*/
|
|
3071
|
-
logToolCallAudit(plugin, toolName, attributes) {
|
|
3072
|
-
const usedServiceAccount = this.serviceAccountProviders.has(plugin.manifest.name) && serviceAccountAllows(plugin.manifest, { tool: toolName });
|
|
3073
|
-
logAudit("mcp.tool_call.completed", {
|
|
3074
|
-
...this.options.auditAttributes,
|
|
3075
|
-
...attributes,
|
|
3076
|
-
"mcp.method.name": "tools/call",
|
|
3077
|
-
"app.plugin.name": plugin.manifest.name,
|
|
3078
|
-
"app.credential.account": usedServiceAccount ? "service_account" : "actor"
|
|
3375
|
+
}
|
|
3376
|
+
/** Resize and re-encode one image until it fits in `maxBytes`. */
|
|
3377
|
+
async function shrinkImage(image, maxBytes) {
|
|
3378
|
+
const { default: sharp } = await import("sharp");
|
|
3379
|
+
const { hasAlpha } = await sharp(image.data).metadata();
|
|
3380
|
+
for (const edge of RESIZE_LONGEST_EDGES) {
|
|
3381
|
+
const resized = sharp(image.data).rotate().resize({
|
|
3382
|
+
width: edge,
|
|
3383
|
+
height: edge,
|
|
3384
|
+
fit: "inside",
|
|
3385
|
+
withoutEnlargement: true
|
|
3079
3386
|
});
|
|
3387
|
+
const { data, info } = await (hasAlpha ? resized.webp({ quality: 90 }) : resized.jpeg({ quality: 90 })).toBuffer({ resolveWithObject: true });
|
|
3388
|
+
if (data.byteLength <= maxBytes) return {
|
|
3389
|
+
image: {
|
|
3390
|
+
path: image.path,
|
|
3391
|
+
data
|
|
3392
|
+
},
|
|
3393
|
+
width: info.width,
|
|
3394
|
+
height: info.height
|
|
3395
|
+
};
|
|
3080
3396
|
}
|
|
3081
|
-
|
|
3082
|
-
|
|
3083
|
-
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3397
|
+
throw new ToolInputError(`could not resize ${image.path} below ${maxBytes} bytes. Use a smaller image.`);
|
|
3398
|
+
}
|
|
3399
|
+
/** Resize input images that would push the request over the gateway limit. */
|
|
3400
|
+
async function fitImagesToRequest(images) {
|
|
3401
|
+
if (images.reduce((sum, image) => sum + image.data.byteLength, 0) <= MAX_REQUEST_IMAGE_BYTES) return {
|
|
3402
|
+
images,
|
|
3403
|
+
resized: []
|
|
3404
|
+
};
|
|
3405
|
+
const fitted = [...images];
|
|
3406
|
+
const resized = [];
|
|
3407
|
+
let remainingBytes = MAX_REQUEST_IMAGE_BYTES;
|
|
3408
|
+
const bySize = images.map((image, index) => ({
|
|
3409
|
+
image,
|
|
3410
|
+
index
|
|
3411
|
+
})).sort((a, b) => a.image.data.byteLength - b.image.data.byteLength);
|
|
3412
|
+
for (const [position, { image, index }] of bySize.entries()) {
|
|
3413
|
+
const share = Math.floor(remainingBytes / (bySize.length - position));
|
|
3414
|
+
if (image.data.byteLength <= share) {
|
|
3415
|
+
remainingBytes -= image.data.byteLength;
|
|
3416
|
+
continue;
|
|
3417
|
+
}
|
|
3418
|
+
const smaller = await shrinkImage(image, share);
|
|
3419
|
+
fitted[index] = smaller.image;
|
|
3420
|
+
remainingBytes -= smaller.image.data.byteLength;
|
|
3421
|
+
resized.push({
|
|
3422
|
+
path: image.path,
|
|
3423
|
+
original_bytes: image.data.byteLength,
|
|
3424
|
+
bytes: smaller.image.data.byteLength,
|
|
3425
|
+
width: smaller.width,
|
|
3426
|
+
height: smaller.height
|
|
3089
3427
|
});
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
3428
|
+
}
|
|
3429
|
+
return {
|
|
3430
|
+
images: fitted,
|
|
3431
|
+
resized
|
|
3432
|
+
};
|
|
3433
|
+
}
|
|
3434
|
+
function extensionForMediaType(mediaType) {
|
|
3435
|
+
if (mediaType === "image/png") return "png";
|
|
3436
|
+
if (mediaType === "image/jpeg") return "jpg";
|
|
3437
|
+
if (mediaType === "image/webp") return "webp";
|
|
3438
|
+
if (mediaType === "image/gif") return "gif";
|
|
3439
|
+
return "bin";
|
|
3440
|
+
}
|
|
3441
|
+
/**
|
|
3442
|
+
* Create the image tool with sandbox artifact guidance matched to file-send capability.
|
|
3443
|
+
*
|
|
3444
|
+
* @runBuilt imageGenerate
|
|
3445
|
+
*/
|
|
3446
|
+
function createImageGenerateTool(hooks, options, deps = {}) {
|
|
3447
|
+
return zodTool({
|
|
3448
|
+
exposure: "deferred",
|
|
3449
|
+
source: IMAGES_TOOL_SOURCE,
|
|
3450
|
+
annotations: {
|
|
3451
|
+
destructiveHint: false,
|
|
3452
|
+
idempotentHint: false,
|
|
3453
|
+
openWorldHint: true,
|
|
3454
|
+
readOnlyHint: false
|
|
3455
|
+
},
|
|
3456
|
+
description: "Generate images from a prompt, or edit existing images. Use when the user wants to visually show or represent something — feelings, concepts, art, humor, or any visual idea. Also use for explicit image creation or image edit requests.",
|
|
3457
|
+
inputSchema: z.object({
|
|
3458
|
+
prompt: z.string().min(1).max(4e3).describe("Image generation prompt. When images are given, describe the change to make and what to keep."),
|
|
3459
|
+
images: z.array(z.string().min(1)).max(4).optional().describe("Sandbox paths of PNG, JPEG, GIF, or WebP images to edit or use as references. Use paths from loadAttachment or from an earlier imageGenerate result. Images over 3 MB in total are resized.")
|
|
3460
|
+
}),
|
|
3461
|
+
outputSchema: imageGenerateOutputSchema,
|
|
3462
|
+
execute: async ({ prompt, images = [] }) => {
|
|
3463
|
+
const model = options.modelId;
|
|
3464
|
+
const { images: inputImages, resized } = await fitImagesToRequest(await Promise.all(images.map(async (path) => ({
|
|
3465
|
+
path,
|
|
3466
|
+
...await readSandboxImage(path, (targetPath) => options.sandbox.readFileToBuffer({ path: targetPath }), MAX_SOURCE_IMAGE_BYTES)
|
|
3467
|
+
}))));
|
|
3468
|
+
const resizeResult = resized.length > 0 ? {
|
|
3469
|
+
resized_images: resized,
|
|
3470
|
+
resize_notice: "Some input images were too large for the image model, so they were resized first. Tell the user which images were resized."
|
|
3471
|
+
} : {};
|
|
3472
|
+
const enrichedPrompt = inputImages.length > 0 ? prompt : await enrichImagePrompt(prompt, options.modelCost);
|
|
3473
|
+
const { images: generatedImages } = await generateImages({
|
|
3474
|
+
operation: "image_generation",
|
|
3475
|
+
cost: options.modelCost,
|
|
3476
|
+
modelId: model,
|
|
3477
|
+
prompt: inputImages.length > 0 ? {
|
|
3478
|
+
text: enrichedPrompt,
|
|
3479
|
+
images: inputImages.map((image) => image.data)
|
|
3480
|
+
} : enrichedPrompt,
|
|
3481
|
+
fetch: deps.fetch
|
|
3482
|
+
}).catch((error) => {
|
|
3483
|
+
if (error instanceof Error && error.message.includes("not an image model")) throw new Error(`image generation failed: configured model "${model}" is not an image generation model. Set AI_IMAGE_MODEL to an AI Gateway image model.`, { cause: error });
|
|
3484
|
+
throw error;
|
|
3485
|
+
});
|
|
3486
|
+
const uploads = generatedImages.map((image, index) => ({
|
|
3487
|
+
data: Buffer.from(image.uint8Array),
|
|
3488
|
+
filename: `generated-image-${Date.now()}-${index + 1}.${extensionForMediaType(image.mediaType)}`,
|
|
3489
|
+
mimeType: image.mediaType
|
|
3490
|
+
}));
|
|
3491
|
+
if (uploads.length > 0) {
|
|
3492
|
+
const artifactRefs = await hooks.writeGeneratedArtifacts(uploads);
|
|
3493
|
+
return {
|
|
3494
|
+
model,
|
|
3495
|
+
prompt,
|
|
3496
|
+
enriched_prompt: enrichedPrompt,
|
|
3497
|
+
image_count: artifactRefs.length,
|
|
3498
|
+
images: artifactRefs,
|
|
3499
|
+
...resizeResult,
|
|
3500
|
+
delivery: options.canSendFilesToActiveConversation ? "Generated images were written to sandbox paths. To share them, pass the returned image objects unchanged as sendFiles files." : "Generated images were written to sandbox paths, but this runtime has no file-send tool for the active conversation."
|
|
3111
3501
|
};
|
|
3112
|
-
const argumentAttribute = serializeMcpPayload(resolvedArgs, conversationPrivacy, { privateMetadata: true });
|
|
3113
|
-
return await withSpan(`execute_tool ${managedToolName}`, "gen_ai.execute_tool", {}, async () => {
|
|
3114
|
-
try {
|
|
3115
|
-
const result = await (await this.clientForTool(plugin, client, tool.name)).callTool(tool.name, resolvedArgs, options?.signal);
|
|
3116
|
-
if ("isError" in result && result.isError) throw new McpToolError(extractMcpErrorMessage(result));
|
|
3117
|
-
this.logToolCallAudit(plugin, tool.name, {
|
|
3118
|
-
"gen_ai.tool.name": managedToolName,
|
|
3119
|
-
...options?.toolCallId ? { "gen_ai.tool.call.id": options.toolCallId } : void 0
|
|
3120
|
-
});
|
|
3121
|
-
const resultAttribute = serializeMcpPayload(result, conversationPrivacy, { privateMetadata: true });
|
|
3122
|
-
if (resultAttribute) setSpanAttributes({ "gen_ai.tool.call.result": resultAttribute });
|
|
3123
|
-
const providerContent = boundMcpContent(toAgentToolContent(result));
|
|
3124
|
-
const successResult = {
|
|
3125
|
-
content: toModelVisibleMcpContent(result),
|
|
3126
|
-
providerContent,
|
|
3127
|
-
...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0
|
|
3128
|
-
};
|
|
3129
|
-
const cards = await this.options.onToolSuccess?.({
|
|
3130
|
-
arguments: resolvedArgs,
|
|
3131
|
-
content: toAgentToolContent(result),
|
|
3132
|
-
provider: plugin.manifest.name,
|
|
3133
|
-
...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0,
|
|
3134
|
-
toolName: tool.name
|
|
3135
|
-
});
|
|
3136
|
-
return cards?.length ? {
|
|
3137
|
-
...successResult,
|
|
3138
|
-
cards
|
|
3139
|
-
} : successResult;
|
|
3140
|
-
} catch (error) {
|
|
3141
|
-
if (error instanceof McpAuthorizationRequiredError && await this.handleAuthorizationRequired(plugin.manifest.name, error, {
|
|
3142
|
-
toolName: tool.name,
|
|
3143
|
-
...options?.authorizationIntent ? { intent: options.authorizationIntent } : void 0
|
|
3144
|
-
})) {
|
|
3145
|
-
const parkedContent = [{
|
|
3146
|
-
type: "text",
|
|
3147
|
-
text: "Authorization pending."
|
|
3148
|
-
}];
|
|
3149
|
-
return {
|
|
3150
|
-
authorizationPending: true,
|
|
3151
|
-
content: parkedContent,
|
|
3152
|
-
providerContent: parkedContent
|
|
3153
|
-
};
|
|
3154
|
-
}
|
|
3155
|
-
const errorAttributes = {
|
|
3156
|
-
...baseAttributes,
|
|
3157
|
-
...getMcpProviderErrorAttributes(error),
|
|
3158
|
-
"error.type": getMcpAwareErrorType(error, "mcp_tool_error"),
|
|
3159
|
-
"exception.message": getMcpAwareTelemetryMessage(error, conversationPrivacy)
|
|
3160
|
-
};
|
|
3161
|
-
setSpanAttributes(errorAttributes);
|
|
3162
|
-
if (error instanceof McpToolError) logWarn("mcp.tool_call.failed", {
|
|
3163
|
-
...this.options.auditAttributes,
|
|
3164
|
-
...errorAttributes
|
|
3165
|
-
});
|
|
3166
|
-
throw error;
|
|
3167
|
-
}
|
|
3168
|
-
}, {
|
|
3169
|
-
...baseAttributes,
|
|
3170
|
-
...argumentAttribute ? { "gen_ai.tool.call.arguments": argumentAttribute } : void 0
|
|
3171
|
-
});
|
|
3172
3502
|
}
|
|
3173
|
-
|
|
3174
|
-
|
|
3175
|
-
|
|
3176
|
-
|
|
3177
|
-
|
|
3178
|
-
|
|
3179
|
-
|
|
3503
|
+
return {
|
|
3504
|
+
model,
|
|
3505
|
+
prompt,
|
|
3506
|
+
enriched_prompt: enrichedPrompt,
|
|
3507
|
+
image_count: 0,
|
|
3508
|
+
images: [],
|
|
3509
|
+
...resizeResult,
|
|
3510
|
+
delivery: "No images were generated."
|
|
3511
|
+
};
|
|
3180
3512
|
}
|
|
3181
|
-
|
|
3182
|
-
|
|
3183
|
-
|
|
3184
|
-
|
|
3185
|
-
|
|
3513
|
+
});
|
|
3514
|
+
}
|
|
3515
|
+
// src/chat/attachments/download.ts
|
|
3516
|
+
/** Refusal for a file over `MAX_ATTACHMENT_BYTES`. */
|
|
3517
|
+
const ATTACHMENT_TOO_LARGE_MESSAGE = `Attachment is larger than the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB file limit.`;
|
|
3518
|
+
/** An attachment whose bytes cannot be read. The message is safe to show. */
|
|
3519
|
+
var AttachmentDownloadError = class extends Error {
|
|
3520
|
+
constructor(message, options) {
|
|
3521
|
+
super(message, options);
|
|
3522
|
+
this.name = "AttachmentDownloadError";
|
|
3523
|
+
}
|
|
3524
|
+
};
|
|
3525
|
+
/**
|
|
3526
|
+
* Look up the source file of an unstored row, with the size check done.
|
|
3527
|
+
* Errors that the person should see are `AttachmentDownloadError`.
|
|
3528
|
+
*/
|
|
3529
|
+
async function readSourceFile(attachment, readAttachmentSource) {
|
|
3530
|
+
const { source } = attachment;
|
|
3531
|
+
if (!source || !readAttachmentSource) throw new AttachmentDownloadError("Attachment cannot be downloaded from this conversation.");
|
|
3532
|
+
let file;
|
|
3533
|
+
try {
|
|
3534
|
+
file = await readAttachmentSource(source);
|
|
3535
|
+
} catch (error) {
|
|
3536
|
+
throw unavailableError(attachment, error);
|
|
3186
3537
|
}
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3190
|
-
|
|
3538
|
+
if (file.bytes > 262144e3) throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
3539
|
+
return {
|
|
3540
|
+
file,
|
|
3541
|
+
source
|
|
3542
|
+
};
|
|
3543
|
+
}
|
|
3544
|
+
function unavailableError(attachment, error) {
|
|
3545
|
+
return error instanceof AttachmentSourceUnavailableError ? new AttachmentDownloadError(`${attachment.filename} is no longer available: ${error.message}`, { cause: error }) : error;
|
|
3546
|
+
}
|
|
3547
|
+
/**
|
|
3548
|
+
* Find where the bytes of one attachment row are, without reading them.
|
|
3549
|
+
*
|
|
3550
|
+
* A stored file reads from storage. A large Slack file that no read has
|
|
3551
|
+
* stored yet downloads from its source on each `open`. The source reports
|
|
3552
|
+
* the current size, and the size check runs before any download. Errors that
|
|
3553
|
+
* the person should see are `AttachmentDownloadError`, from here or from
|
|
3554
|
+
* `open`. Callers that need the bytes more than once use
|
|
3555
|
+
* `storeAttachmentOnFirstUse` first.
|
|
3556
|
+
*
|
|
3557
|
+
* The row must come from a lookup scoped to the caller's conversation. The
|
|
3558
|
+
* source id comes from that row only, never from a request.
|
|
3559
|
+
*/
|
|
3560
|
+
async function readAttachmentContent(args) {
|
|
3561
|
+
const { attachment, storage } = args;
|
|
3562
|
+
const { storageKey } = attachment;
|
|
3563
|
+
if (storageKey !== null) return {
|
|
3564
|
+
bytes: attachment.bytes,
|
|
3565
|
+
open: async () => {
|
|
3566
|
+
const body = await storage.get(storageKey);
|
|
3567
|
+
if (!body) throw new AttachmentDownloadError("Stored attachment contents are unavailable.");
|
|
3568
|
+
return body;
|
|
3191
3569
|
}
|
|
3192
|
-
|
|
3193
|
-
|
|
3194
|
-
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
|
|
3202
|
-
if (options.provider && provider !== options.provider) continue;
|
|
3203
|
-
const wrappedTools = new Set(this.pluginsByProvider.get(provider)?.manifest.mcp?.wrappedTools ?? []);
|
|
3204
|
-
resolved.push(...(this.toolsByProvider.get(provider) ?? []).filter((tool) => !wrappedTools.has(tool.rawName)));
|
|
3570
|
+
};
|
|
3571
|
+
const { file } = await readSourceFile(attachment, args.readAttachmentSource);
|
|
3572
|
+
return {
|
|
3573
|
+
bytes: file.bytes,
|
|
3574
|
+
open: async () => {
|
|
3575
|
+
try {
|
|
3576
|
+
return await file.open();
|
|
3577
|
+
} catch (error) {
|
|
3578
|
+
throw unavailableError(attachment, error);
|
|
3579
|
+
}
|
|
3205
3580
|
}
|
|
3206
|
-
|
|
3581
|
+
};
|
|
3582
|
+
}
|
|
3583
|
+
/**
|
|
3584
|
+
* Return the row of one attachment with its bytes in storage.
|
|
3585
|
+
*
|
|
3586
|
+
* A large Slack file is recorded without its bytes. The first read that
|
|
3587
|
+
* needs them streams the file from its source into storage once, and later
|
|
3588
|
+
* reads use storage. The same rules as `readAttachmentContent` apply to the
|
|
3589
|
+
* row and to errors.
|
|
3590
|
+
*/
|
|
3591
|
+
async function storeAttachmentOnFirstUse(args) {
|
|
3592
|
+
const { attachment } = args;
|
|
3593
|
+
const { storageKey } = attachment;
|
|
3594
|
+
if (storageKey !== null) return {
|
|
3595
|
+
...attachment,
|
|
3596
|
+
storageKey
|
|
3597
|
+
};
|
|
3598
|
+
const { file, source } = await readSourceFile(attachment, args.readAttachmentSource);
|
|
3599
|
+
let stored;
|
|
3600
|
+
try {
|
|
3601
|
+
stored = await withSpan("attachment.store", "attachment.store", {}, async () => await storeDeferredAttachment({
|
|
3602
|
+
attachment: {
|
|
3603
|
+
...attachment,
|
|
3604
|
+
source
|
|
3605
|
+
},
|
|
3606
|
+
db: args.db,
|
|
3607
|
+
file,
|
|
3608
|
+
storage: args.storage
|
|
3609
|
+
}), {
|
|
3610
|
+
"app.attachment.source.provider": source.provider,
|
|
3611
|
+
"file.size": file.bytes
|
|
3612
|
+
});
|
|
3613
|
+
} catch (error) {
|
|
3614
|
+
throw unavailableError(attachment, error);
|
|
3207
3615
|
}
|
|
3208
|
-
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3218
|
-
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3224
|
-
|
|
3225
|
-
|
|
3616
|
+
if (!stored) throw new AttachmentDownloadError(`${attachment.filename} is no longer available.`);
|
|
3617
|
+
return stored;
|
|
3618
|
+
}
|
|
3619
|
+
// src/chat/attachments/tool-params.ts
|
|
3620
|
+
/** Model-facing id of one attachment in the current Conversation. */
|
|
3621
|
+
const attachmentIdParam = z.string().min(1).describe("Stored attachment ID, as shown in attachment context or Slack read results.");
|
|
3622
|
+
// src/chat/tools/load-attachment.ts
|
|
3623
|
+
/** Sandbox directory for attachment files that tools write. */
|
|
3624
|
+
const ATTACHMENT_DIR = ".junior/attachments";
|
|
3625
|
+
/** Bytes held in memory and sent to the sandbox in one write. */
|
|
3626
|
+
const PART_BYTES = 8388608;
|
|
3627
|
+
const JOIN_PARTS_SCRIPT = "set -eu; out=$1; shift; cat -- \"$@\" > \"$out\"";
|
|
3628
|
+
/** Turn a read failure that the model can relay into a tool error. */
|
|
3629
|
+
function toolError(error) {
|
|
3630
|
+
return error instanceof AttachmentDownloadError ? new ToolInputError(error.message, { cause: error }) : error;
|
|
3631
|
+
}
|
|
3632
|
+
/** Run one sandbox command, and return its stdout. Throw when it fails. */
|
|
3633
|
+
async function runChecked(workspace, action, input) {
|
|
3634
|
+
const result = await workspace.runCommand(input);
|
|
3635
|
+
if (result.exitCode !== 0) throw new Error(`Failed to ${action}: ${result.stderr}`);
|
|
3636
|
+
return result.stdout;
|
|
3637
|
+
}
|
|
3638
|
+
/**
|
|
3639
|
+
* Write an attachment body to the sandbox in parts of at most `PART_BYTES`.
|
|
3640
|
+
*
|
|
3641
|
+
* The sandbox SDK writes only whole buffers, so this keeps one part in
|
|
3642
|
+
* memory, not the file. Returns the part paths in order.
|
|
3643
|
+
*/
|
|
3644
|
+
async function writeParts(args) {
|
|
3645
|
+
const parts = [];
|
|
3646
|
+
let pending = [];
|
|
3647
|
+
let pendingBytes = 0;
|
|
3648
|
+
let total = 0;
|
|
3649
|
+
const flush = async () => {
|
|
3650
|
+
const partPath = path.posix.join(args.partsDir, String(parts.length).padStart(4, "0"));
|
|
3651
|
+
await args.workspace.writeFiles([{
|
|
3652
|
+
content: Buffer.concat(pending),
|
|
3653
|
+
path: partPath
|
|
3654
|
+
}]);
|
|
3655
|
+
parts.push(partPath);
|
|
3656
|
+
pending = [];
|
|
3657
|
+
pendingBytes = 0;
|
|
3658
|
+
};
|
|
3659
|
+
const reader = args.body.getReader();
|
|
3660
|
+
try {
|
|
3661
|
+
for (;;) {
|
|
3662
|
+
const { done, value } = await reader.read();
|
|
3663
|
+
if (done) break;
|
|
3664
|
+
total += value.byteLength;
|
|
3665
|
+
if (total > args.expectedBytes) break;
|
|
3666
|
+
let chunk = value;
|
|
3667
|
+
while (pendingBytes + chunk.byteLength >= PART_BYTES) {
|
|
3668
|
+
const take = PART_BYTES - pendingBytes;
|
|
3669
|
+
pending.push(chunk.subarray(0, take));
|
|
3670
|
+
pendingBytes += take;
|
|
3671
|
+
await flush();
|
|
3672
|
+
chunk = chunk.subarray(take);
|
|
3673
|
+
}
|
|
3674
|
+
if (chunk.byteLength > 0) {
|
|
3675
|
+
pending.push(chunk);
|
|
3676
|
+
pendingBytes += chunk.byteLength;
|
|
3677
|
+
}
|
|
3226
3678
|
}
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
status: "success",
|
|
3230
|
-
content: result.providerContent ?? result.content,
|
|
3231
|
-
...result.structuredContent !== void 0 ? { structuredContent: result.structuredContent } : void 0
|
|
3232
|
-
};
|
|
3233
|
-
}
|
|
3234
|
-
toToolDescriptor(tool) {
|
|
3235
|
-
return {
|
|
3236
|
-
name: tool.name,
|
|
3237
|
-
rawName: tool.rawName,
|
|
3238
|
-
...tool.title ? { title: tool.title } : void 0,
|
|
3239
|
-
description: tool.description,
|
|
3240
|
-
parameters: tool.parameters,
|
|
3241
|
-
...tool.outputSchema ? { outputSchema: tool.outputSchema } : void 0,
|
|
3242
|
-
...tool.annotations ? { annotations: tool.annotations } : void 0,
|
|
3243
|
-
provider: tool.provider
|
|
3244
|
-
};
|
|
3679
|
+
} finally {
|
|
3680
|
+
await reader.cancel().catch(() => void 0);
|
|
3245
3681
|
}
|
|
3246
|
-
};
|
|
3247
|
-
|
|
3248
|
-
return
|
|
3249
|
-
}
|
|
3250
|
-
function serializeMcpPayload(payload, privacy, options = {}) {
|
|
3251
|
-
if (privacy !== "private") return serializeGenAiAttribute(payload);
|
|
3252
|
-
return options.privateMetadata ? serializeGenAiAttribute(toGenAiPayloadMetadata(payload)) : void 0;
|
|
3682
|
+
if (total !== args.expectedBytes) throw new Error(`Attachment ${args.attachmentId} read ${total} bytes, expected ${args.expectedBytes}.`);
|
|
3683
|
+
if (pendingBytes > 0 || parts.length === 0) await flush();
|
|
3684
|
+
return parts;
|
|
3253
3685
|
}
|
|
3254
|
-
// src/chat/sandbox/tool-source.ts
|
|
3255
|
-
/** Deferred tool catalog source for sandbox preview URLs. */
|
|
3256
|
-
const SANDBOX_TOOL_SOURCE = {
|
|
3257
|
-
id: "sandbox",
|
|
3258
|
-
description: "Create public preview URLs for servers in the sandbox."
|
|
3259
|
-
};
|
|
3260
|
-
// src/chat/tools/sandbox/create-preview.ts
|
|
3261
|
-
const outputSchema$2 = juniorToolOutputSchema.extend({ url: z.string().url() });
|
|
3262
3686
|
/**
|
|
3263
|
-
* Create a tool that
|
|
3687
|
+
* Create a tool that restores one conversation attachment to the sandbox.
|
|
3264
3688
|
*
|
|
3265
|
-
*
|
|
3689
|
+
* The first load of a large Slack file streams it from Slack into storage
|
|
3690
|
+
* through the host. The sandbox never gets a Slack URL or token.
|
|
3691
|
+
*
|
|
3692
|
+
* @runBuilt loadAttachment
|
|
3266
3693
|
*/
|
|
3267
|
-
function
|
|
3694
|
+
function createLoadAttachmentTool(args) {
|
|
3268
3695
|
return zodTool({
|
|
3269
|
-
|
|
3270
|
-
source: SANDBOX_TOOL_SOURCE,
|
|
3696
|
+
description: "Load a stored attachment for this conversation into the sandbox.",
|
|
3271
3697
|
annotations: {
|
|
3272
3698
|
destructiveHint: false,
|
|
3273
3699
|
idempotentHint: true,
|
|
3274
3700
|
openWorldHint: true,
|
|
3275
3701
|
readOnlyHint: false
|
|
3276
3702
|
},
|
|
3277
|
-
|
|
3278
|
-
|
|
3279
|
-
|
|
3280
|
-
|
|
3281
|
-
|
|
3282
|
-
|
|
3283
|
-
|
|
3703
|
+
inputSchema: z.object({ attachment_id: attachmentIdParam }),
|
|
3704
|
+
outputSchema: juniorToolOutputSchema,
|
|
3705
|
+
execute: async ({ attachment_id }) => {
|
|
3706
|
+
const attachment = await readLiveAttachment({
|
|
3707
|
+
attachmentId: attachment_id,
|
|
3708
|
+
conversationId: args.conversationId,
|
|
3709
|
+
db: args.db
|
|
3710
|
+
});
|
|
3711
|
+
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
3712
|
+
if (attachment.bytes > 262144e3) throw new ToolInputError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
3713
|
+
let content;
|
|
3714
|
+
try {
|
|
3715
|
+
content = await readAttachmentContent({
|
|
3716
|
+
attachment: await storeAttachmentOnFirstUse({
|
|
3717
|
+
attachment,
|
|
3718
|
+
db: args.db,
|
|
3719
|
+
readAttachmentSource: args.readAttachmentSource,
|
|
3720
|
+
storage: args.storage
|
|
3721
|
+
}),
|
|
3722
|
+
storage: args.storage
|
|
3723
|
+
});
|
|
3724
|
+
} catch (error) {
|
|
3725
|
+
throw toolError(error);
|
|
3726
|
+
}
|
|
3727
|
+
const attachmentDir = path.posix.join(ATTACHMENT_DIR, attachment.id);
|
|
3728
|
+
const partsDir = `${attachmentDir}.parts`;
|
|
3729
|
+
const sandboxPath = path.posix.join(attachmentDir, path.posix.basename(attachment.filename));
|
|
3730
|
+
await runChecked(args.workspace, "create attachment directory", {
|
|
3731
|
+
cmd: "mkdir",
|
|
3732
|
+
args: [
|
|
3733
|
+
"-p",
|
|
3734
|
+
"--",
|
|
3735
|
+
attachmentDir,
|
|
3736
|
+
partsDir
|
|
3737
|
+
]
|
|
3738
|
+
});
|
|
3739
|
+
const joinedPath = path.posix.join(partsDir, "joined");
|
|
3740
|
+
try {
|
|
3741
|
+
const parts = await writeParts({
|
|
3742
|
+
attachmentId: attachment.id,
|
|
3743
|
+
body: await content.open(),
|
|
3744
|
+
expectedBytes: content.bytes,
|
|
3745
|
+
partsDir,
|
|
3746
|
+
workspace: args.workspace
|
|
3747
|
+
});
|
|
3748
|
+
await runChecked(args.workspace, "join attachment parts", {
|
|
3749
|
+
cmd: "sh",
|
|
3750
|
+
args: [
|
|
3751
|
+
"-c",
|
|
3752
|
+
JOIN_PARTS_SCRIPT,
|
|
3753
|
+
"sh",
|
|
3754
|
+
joinedPath,
|
|
3755
|
+
...parts
|
|
3756
|
+
]
|
|
3757
|
+
});
|
|
3758
|
+
const size = await runChecked(args.workspace, "read attachment size", {
|
|
3759
|
+
cmd: "stat",
|
|
3760
|
+
args: [
|
|
3761
|
+
"-c",
|
|
3762
|
+
"%s",
|
|
3763
|
+
"--",
|
|
3764
|
+
joinedPath
|
|
3765
|
+
]
|
|
3766
|
+
});
|
|
3767
|
+
const written = Number(size.trim());
|
|
3768
|
+
if (written !== content.bytes) throw new Error(`Attachment ${attachment.id} wrote ${written} bytes to the sandbox, expected ${content.bytes}.`);
|
|
3769
|
+
await runChecked(args.workspace, "move attachment into place", {
|
|
3770
|
+
cmd: "mv",
|
|
3771
|
+
args: [
|
|
3772
|
+
"-f",
|
|
3773
|
+
"--",
|
|
3774
|
+
joinedPath,
|
|
3775
|
+
sandboxPath
|
|
3776
|
+
]
|
|
3777
|
+
});
|
|
3778
|
+
} catch (error) {
|
|
3779
|
+
await args.workspace.runCommand({
|
|
3780
|
+
cmd: "rm",
|
|
3781
|
+
args: [
|
|
3782
|
+
"-rf",
|
|
3783
|
+
"--",
|
|
3784
|
+
partsDir
|
|
3785
|
+
]
|
|
3786
|
+
}).catch(() => void 0);
|
|
3787
|
+
throw toolError(error);
|
|
3788
|
+
}
|
|
3789
|
+
await runChecked(args.workspace, "remove attachment parts", {
|
|
3790
|
+
cmd: "rm",
|
|
3791
|
+
args: [
|
|
3792
|
+
"-rf",
|
|
3793
|
+
"--",
|
|
3794
|
+
partsDir
|
|
3795
|
+
]
|
|
3796
|
+
});
|
|
3797
|
+
return {
|
|
3798
|
+
path: sandboxPath,
|
|
3799
|
+
filename: attachment.filename,
|
|
3800
|
+
mime_type: attachment.contentType,
|
|
3801
|
+
bytes: content.bytes
|
|
3802
|
+
};
|
|
3284
3803
|
}
|
|
3285
3804
|
});
|
|
3286
3805
|
}
|
|
3287
|
-
// src/
|
|
3288
|
-
/**
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
|
|
3292
|
-
* pattern cannot say which Previews are safe. Junior records each Preview
|
|
3293
|
-
* that it creates, with the email of the person who asked for it. Only that
|
|
3294
|
-
* person can send a token to it, and only until the record expires.
|
|
3295
|
-
*/
|
|
3296
|
-
const PREVIEW_ORIGIN_TTL_MS = 864e5;
|
|
3297
|
-
const previewOriginRecordSchema = z.object({ ownerEmailNormalized: z.string() }).strict();
|
|
3298
|
-
function previewOriginKey(origin) {
|
|
3299
|
-
return `junior:preview-origin:v1:${origin}`;
|
|
3300
|
-
}
|
|
3301
|
-
function normalizeEmail(email) {
|
|
3302
|
-
return email.trim().toLowerCase();
|
|
3303
|
-
}
|
|
3304
|
-
/** Record that one person asked Junior for the Preview at `url`. */
|
|
3305
|
-
async function recordPreviewOrigin(args) {
|
|
3306
|
-
await getStateAdapter().set(previewOriginKey(new URL(args.url).origin), previewOriginRecordSchema.parse({ ownerEmailNormalized: normalizeEmail(args.ownerEmail) }), PREVIEW_ORIGIN_TTL_MS);
|
|
3307
|
-
}
|
|
3308
|
-
/** Return true when Junior made the Preview at `origin` for this person. */
|
|
3309
|
-
async function previewOriginBelongsTo(args) {
|
|
3310
|
-
const value = await getStateAdapter().get(previewOriginKey(args.origin));
|
|
3311
|
-
if (value === null) return false;
|
|
3312
|
-
return previewOriginRecordSchema.parse(value).ownerEmailNormalized === normalizeEmail(args.email);
|
|
3313
|
-
}
|
|
3314
|
-
// src/chat/tools/sandbox/image-files.ts
|
|
3315
|
-
/**
|
|
3316
|
-
* Read a sandbox image for a model request. The file signature, not the file
|
|
3317
|
-
* name, sets the MIME type.
|
|
3318
|
-
*/
|
|
3319
|
-
async function readSandboxImage(path, readFile, maxBytes) {
|
|
3320
|
-
const targetPath = normalizeSandboxPath(path);
|
|
3321
|
-
const data = await readFile(targetPath);
|
|
3322
|
-
if (!data) throw new SandboxFileNotFoundError(targetPath);
|
|
3323
|
-
if (data.byteLength === 0) throw new ToolInputError(`image file is empty: ${targetPath}`);
|
|
3324
|
-
if (data.byteLength > maxBytes) throw new ToolInputError(`image exceeds ${maxBytes} bytes: ${targetPath} (${data.byteLength} bytes). Make the image smaller first.`);
|
|
3325
|
-
const mimeType = detectImageMediaType(data);
|
|
3326
|
-
if (!mimeType) throw new ToolInputError(`not a readable image: ${targetPath} exists, but its content is not PNG, JPEG, GIF, or WebP data`);
|
|
3327
|
-
return {
|
|
3328
|
-
data,
|
|
3329
|
-
mimeType
|
|
3330
|
-
};
|
|
3331
|
-
}
|
|
3332
|
-
// src/chat/artifacts/tool-source.ts
|
|
3333
|
-
/** Deferred tool catalog source for generated, edited, and published images. */
|
|
3334
|
-
const IMAGES_TOOL_SOURCE = {
|
|
3335
|
-
id: "images",
|
|
3336
|
-
description: "Generate or edit images, and publish or unpublish public image URLs."
|
|
3806
|
+
// src/chat/tools/transcribe-audio.ts
|
|
3807
|
+
/** Deferred tool catalog source for speech transcription. */
|
|
3808
|
+
const AUDIO_TOOL_SOURCE = {
|
|
3809
|
+
id: "audio",
|
|
3810
|
+
description: "Transcribe speech in audio and video attachments."
|
|
3337
3811
|
};
|
|
3338
|
-
|
|
3339
|
-
const
|
|
3340
|
-
const
|
|
3341
|
-
const
|
|
3342
|
-
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
const resizedImageSchema = z.object({
|
|
3348
|
-
path: z.string(),
|
|
3349
|
-
original_bytes: z.number().int().positive(),
|
|
3350
|
-
bytes: z.number().int().positive(),
|
|
3351
|
-
width: z.number().int().positive(),
|
|
3352
|
-
height: z.number().int().positive()
|
|
3353
|
-
}).strict();
|
|
3354
|
-
const imageGenerateOutputSchema = juniorToolOutputSchema.extend({
|
|
3355
|
-
model: z.string(),
|
|
3356
|
-
prompt: z.string(),
|
|
3357
|
-
enriched_prompt: z.string(),
|
|
3358
|
-
image_count: z.number().int().nonnegative(),
|
|
3359
|
-
images: z.array(generatedArtifactFileRefSchema),
|
|
3360
|
-
delivery: z.string(),
|
|
3361
|
-
resized_images: z.array(resizedImageSchema).optional(),
|
|
3362
|
-
resize_notice: z.string().optional()
|
|
3812
|
+
const DOWNLOAD_URL_TTL_MS = 3e5;
|
|
3813
|
+
const UNTYPED_CONTENT_TYPE = "application/octet-stream";
|
|
3814
|
+
const INLINE_RESERVE_CHARS = 1e3;
|
|
3815
|
+
const transcribeAudioOutputSchema = juniorToolOutputSchema.extend({
|
|
3816
|
+
transcript: z.string(),
|
|
3817
|
+
transcript_path: z.string().optional(),
|
|
3818
|
+
note: z.string().optional(),
|
|
3819
|
+
language: z.string().optional(),
|
|
3820
|
+
duration_seconds: z.number().nonnegative().optional()
|
|
3363
3821
|
}).strict();
|
|
3364
|
-
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
|
|
3373
|
-
|
|
3374
|
-
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
3379
|
-
|
|
3380
|
-
|
|
3381
|
-
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3387
|
-
|
|
3388
|
-
|
|
3389
|
-
|
|
3390
|
-
|
|
3391
|
-
|
|
3392
|
-
return rawPrompt;
|
|
3393
|
-
}
|
|
3394
|
-
}
|
|
3395
|
-
/** Resize and re-encode one image until it fits in `maxBytes`. */
|
|
3396
|
-
async function shrinkImage(image, maxBytes) {
|
|
3397
|
-
const { default: sharp } = await import("sharp");
|
|
3398
|
-
const { hasAlpha } = await sharp(image.data).metadata();
|
|
3399
|
-
for (const edge of RESIZE_LONGEST_EDGES) {
|
|
3400
|
-
const resized = sharp(image.data).rotate().resize({
|
|
3401
|
-
width: edge,
|
|
3402
|
-
height: edge,
|
|
3403
|
-
fit: "inside",
|
|
3404
|
-
withoutEnlargement: true
|
|
3405
|
-
});
|
|
3406
|
-
const { data, info } = await (hasAlpha ? resized.webp({ quality: 90 }) : resized.jpeg({ quality: 90 })).toBuffer({ resolveWithObject: true });
|
|
3407
|
-
if (data.byteLength <= maxBytes) return {
|
|
3408
|
-
image: {
|
|
3409
|
-
path: image.path,
|
|
3410
|
-
data
|
|
3411
|
-
},
|
|
3412
|
-
width: info.width,
|
|
3413
|
-
height: info.height
|
|
3414
|
-
};
|
|
3415
|
-
}
|
|
3416
|
-
throw new ToolInputError(`could not resize ${image.path} below ${maxBytes} bytes. Use a smaller image.`);
|
|
3417
|
-
}
|
|
3418
|
-
/** Resize input images that would push the request over the gateway limit. */
|
|
3419
|
-
async function fitImagesToRequest(images) {
|
|
3420
|
-
if (images.reduce((sum, image) => sum + image.data.byteLength, 0) <= MAX_REQUEST_IMAGE_BYTES) return {
|
|
3421
|
-
images,
|
|
3422
|
-
resized: []
|
|
3423
|
-
};
|
|
3424
|
-
const fitted = [...images];
|
|
3425
|
-
const resized = [];
|
|
3426
|
-
let remainingBytes = MAX_REQUEST_IMAGE_BYTES;
|
|
3427
|
-
const bySize = images.map((image, index) => ({
|
|
3428
|
-
image,
|
|
3429
|
-
index
|
|
3430
|
-
})).sort((a, b) => a.image.data.byteLength - b.image.data.byteLength);
|
|
3431
|
-
for (const [position, { image, index }] of bySize.entries()) {
|
|
3432
|
-
const share = Math.floor(remainingBytes / (bySize.length - position));
|
|
3433
|
-
if (image.data.byteLength <= share) {
|
|
3434
|
-
remainingBytes -= image.data.byteLength;
|
|
3435
|
-
continue;
|
|
3436
|
-
}
|
|
3437
|
-
const smaller = await shrinkImage(image, share);
|
|
3438
|
-
fitted[index] = smaller.image;
|
|
3439
|
-
remainingBytes -= smaller.image.data.byteLength;
|
|
3440
|
-
resized.push({
|
|
3441
|
-
path: image.path,
|
|
3442
|
-
original_bytes: image.data.byteLength,
|
|
3443
|
-
bytes: smaller.image.data.byteLength,
|
|
3444
|
-
width: smaller.width,
|
|
3445
|
-
height: smaller.height
|
|
3446
|
-
});
|
|
3822
|
+
function mayHaveAudio(contentType) {
|
|
3823
|
+
const mediaType = contentType.split(";", 1)[0]?.trim().toLowerCase() ?? "";
|
|
3824
|
+
return mediaType.startsWith("audio/") || mediaType.startsWith("video/") || mediaType === UNTYPED_CONTENT_TYPE;
|
|
3825
|
+
}
|
|
3826
|
+
/** Format seconds as `MM:SS.s`, or `H:MM:SS.s` from one hour. */
|
|
3827
|
+
function timestamp(seconds) {
|
|
3828
|
+
const tenths = Math.floor(seconds * 10);
|
|
3829
|
+
const hours = Math.floor(tenths / 36e3);
|
|
3830
|
+
const time = `${String(Math.floor(tenths / 600) % 60).padStart(2, "0")}:${String(Math.floor(tenths / 10) % 60).padStart(2, "0")}.${tenths % 10}`;
|
|
3831
|
+
return hours > 0 ? `${hours}:${time}` : time;
|
|
3832
|
+
}
|
|
3833
|
+
/** One log-style line per entry: start time, then speaker and text. */
|
|
3834
|
+
function transcriptLine(entry) {
|
|
3835
|
+
const text = entry.text.replace(/\s+/g, " ");
|
|
3836
|
+
const body = entry.kind === "sound" ? `(${text})` : entry.speaker ? `${entry.speaker}: ${text}` : text;
|
|
3837
|
+
return `[${timestamp(entry.startSeconds)}] ${body}`;
|
|
3838
|
+
}
|
|
3839
|
+
/**
|
|
3840
|
+
* Keep the leading lines whose JSON-escaped size fits in `budget` chars.
|
|
3841
|
+
* The cut is always on a line boundary.
|
|
3842
|
+
*/
|
|
3843
|
+
function leadingLines(lines, budget) {
|
|
3844
|
+
let used = 0;
|
|
3845
|
+
let count = 0;
|
|
3846
|
+
for (const line of lines) {
|
|
3847
|
+
used += JSON.stringify(line).length - 2 + (count > 0 ? 2 : 0);
|
|
3848
|
+
if (used > budget) break;
|
|
3849
|
+
count += 1;
|
|
3447
3850
|
}
|
|
3448
3851
|
return {
|
|
3449
|
-
|
|
3450
|
-
|
|
3852
|
+
text: lines.slice(0, count).join("\n"),
|
|
3853
|
+
truncated: count < lines.length
|
|
3451
3854
|
};
|
|
3452
3855
|
}
|
|
3453
|
-
function extensionForMediaType(mediaType) {
|
|
3454
|
-
if (mediaType === "image/png") return "png";
|
|
3455
|
-
if (mediaType === "image/jpeg") return "jpg";
|
|
3456
|
-
if (mediaType === "image/webp") return "webp";
|
|
3457
|
-
if (mediaType === "image/gif") return "gif";
|
|
3458
|
-
return "bin";
|
|
3459
|
-
}
|
|
3460
3856
|
/**
|
|
3461
|
-
* Create
|
|
3857
|
+
* Create a tool that transcribes speech in one Conversation attachment.
|
|
3462
3858
|
*
|
|
3463
|
-
*
|
|
3859
|
+
* The model provider downloads the file from a short-lived signed URL. The
|
|
3860
|
+
* URL never leaves this call. A large Slack file is stored first, so its
|
|
3861
|
+
* first transcription streams it through the host once.
|
|
3862
|
+
*
|
|
3863
|
+
* @runBuilt transcribeAudio
|
|
3464
3864
|
*/
|
|
3465
|
-
function
|
|
3865
|
+
function createTranscribeAudioTool(args) {
|
|
3466
3866
|
return zodTool({
|
|
3467
3867
|
exposure: "deferred",
|
|
3468
|
-
source:
|
|
3868
|
+
source: AUDIO_TOOL_SOURCE,
|
|
3869
|
+
description: "Transcribe speech in an audio or video attachment. Returns a transcript with one line per entry: `[MM:SS.s] speaker: text` for speech and `[MM:SS.s] (sound)` for sounds. The full transcript is saved at `transcript_path`. When `truncated` is true, the inline transcript has only the first lines: read the rest of the file with readFile, or search it with grep. When the save fails, `transcript_path` is absent and `note` says so.",
|
|
3469
3870
|
annotations: {
|
|
3470
3871
|
destructiveHint: false,
|
|
3471
|
-
idempotentHint:
|
|
3872
|
+
idempotentHint: true,
|
|
3472
3873
|
openWorldHint: true,
|
|
3473
|
-
readOnlyHint:
|
|
3874
|
+
readOnlyHint: true
|
|
3474
3875
|
},
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
3478
|
-
|
|
3479
|
-
|
|
3480
|
-
|
|
3481
|
-
|
|
3482
|
-
const gateway = createGatewayProvider({
|
|
3483
|
-
apiKey: await getGatewayApiKey(),
|
|
3484
|
-
...deps.fetch ? { fetch: deps.fetch } : void 0
|
|
3876
|
+
inputSchema: z.object({ attachment_id: attachmentIdParam }),
|
|
3877
|
+
outputSchema: transcribeAudioOutputSchema,
|
|
3878
|
+
execute: async ({ attachment_id }, { signal }) => {
|
|
3879
|
+
const attachment = await readLiveAttachment({
|
|
3880
|
+
attachmentId: attachment_id,
|
|
3881
|
+
conversationId: args.conversationId,
|
|
3882
|
+
db: args.db
|
|
3485
3883
|
});
|
|
3486
|
-
|
|
3487
|
-
|
|
3488
|
-
|
|
3489
|
-
|
|
3490
|
-
|
|
3491
|
-
|
|
3492
|
-
|
|
3493
|
-
|
|
3494
|
-
|
|
3495
|
-
|
|
3496
|
-
|
|
3884
|
+
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
3885
|
+
if (!mayHaveAudio(attachment.contentType)) throw new ToolInputError(`This attachment is ${attachment.contentType}, not audio or video.`);
|
|
3886
|
+
const { storageKey } = await storeAttachmentOnFirstUse({
|
|
3887
|
+
attachment,
|
|
3888
|
+
db: args.db,
|
|
3889
|
+
readAttachmentSource: args.readAttachmentSource,
|
|
3890
|
+
storage: args.storage
|
|
3891
|
+
}).catch((error) => {
|
|
3892
|
+
if (error instanceof AttachmentDownloadError) throw new ToolInputError(error.message, { cause: error });
|
|
3893
|
+
throw error;
|
|
3894
|
+
});
|
|
3895
|
+
const sourceUrl = await args.storage.createDownloadUrl({
|
|
3896
|
+
expiresAtMs: Date.now() + DOWNLOAD_URL_TTL_MS,
|
|
3897
|
+
key: storageKey
|
|
3898
|
+
});
|
|
3899
|
+
const transcript = await transcribeFromUrl({
|
|
3900
|
+
cost: args.modelCost,
|
|
3901
|
+
modelId: args.modelId,
|
|
3902
|
+
operation: "transcription",
|
|
3903
|
+
signal,
|
|
3904
|
+
sourceUrl
|
|
3905
|
+
}).catch((error) => {
|
|
3906
|
+
if (error instanceof NoAudioError) throw new ToolInputError(error.message, { cause: error });
|
|
3907
|
+
throw error;
|
|
3908
|
+
});
|
|
3909
|
+
const lines = transcript.entries.map(transcriptLine);
|
|
3910
|
+
const transcriptPath = path.posix.join(ATTACHMENT_DIR, `${attachment.id}.transcript.txt`);
|
|
3911
|
+
let saved = true;
|
|
3497
3912
|
try {
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
|
|
3501
|
-
|
|
3502
|
-
images: inputImages.map((image) => image.data)
|
|
3503
|
-
} : enrichedPrompt,
|
|
3504
|
-
n: 1
|
|
3505
|
-
}));
|
|
3913
|
+
await args.workspace.writeFiles([{
|
|
3914
|
+
content: `${lines.join("\n")}\n`,
|
|
3915
|
+
path: transcriptPath
|
|
3916
|
+
}]);
|
|
3506
3917
|
} catch (error) {
|
|
3507
|
-
|
|
3508
|
-
|
|
3509
|
-
else throw error;
|
|
3510
|
-
}
|
|
3511
|
-
const uploads = generatedImages.map((image, index) => ({
|
|
3512
|
-
data: Buffer.from(image.uint8Array),
|
|
3513
|
-
filename: `generated-image-${Date.now()}-${index + 1}.${extensionForMediaType(image.mediaType)}`,
|
|
3514
|
-
mimeType: image.mediaType
|
|
3515
|
-
}));
|
|
3516
|
-
if (uploads.length > 0) {
|
|
3517
|
-
const artifactRefs = await hooks.writeGeneratedArtifacts(uploads);
|
|
3518
|
-
return {
|
|
3519
|
-
model,
|
|
3520
|
-
prompt,
|
|
3521
|
-
enriched_prompt: enrichedPrompt,
|
|
3522
|
-
image_count: artifactRefs.length,
|
|
3523
|
-
images: artifactRefs,
|
|
3524
|
-
...resizeResult,
|
|
3525
|
-
delivery: options.canSendFilesToActiveConversation ? "Generated images were written to sandbox paths. To share them, pass the returned image objects unchanged as sendFiles files." : "Generated images were written to sandbox paths, but this runtime has no file-send tool for the active conversation."
|
|
3526
|
-
};
|
|
3918
|
+
saved = false;
|
|
3919
|
+
logWarn("tool.transcript.write.failed", { "exception.message": String(error) });
|
|
3527
3920
|
}
|
|
3921
|
+
const result = {
|
|
3922
|
+
...saved ? { transcript_path: transcriptPath } : { note: "The full transcript was not saved." },
|
|
3923
|
+
...transcript.language ? { language: transcript.language } : void 0,
|
|
3924
|
+
...transcript.durationSeconds !== void 0 ? { duration_seconds: transcript.durationSeconds } : void 0
|
|
3925
|
+
};
|
|
3926
|
+
const inline = leadingLines(lines, TOOL_RESULT_MAX_CHARS - INLINE_RESERVE_CHARS - JSON.stringify({
|
|
3927
|
+
...result,
|
|
3928
|
+
transcript: "",
|
|
3929
|
+
truncated: true
|
|
3930
|
+
}).length);
|
|
3528
3931
|
return {
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
image_count: 0,
|
|
3533
|
-
images: [],
|
|
3534
|
-
...resizeResult,
|
|
3535
|
-
delivery: "No images were generated."
|
|
3932
|
+
...result,
|
|
3933
|
+
transcript: inline.text,
|
|
3934
|
+
...inline.truncated ? { truncated: true } : void 0
|
|
3536
3935
|
};
|
|
3537
3936
|
}
|
|
3538
3937
|
});
|
|
@@ -3550,7 +3949,7 @@ function resolveMcpArguments(input) {
|
|
|
3550
3949
|
const extraKeys = Object.keys(input).filter((key) => key !== "tool_name" && key !== "arguments" && key !== "intent");
|
|
3551
3950
|
if (extraKeys.length > 0) throw new ToolInputError(`callMcpTool MCP arguments must be nested under arguments, not top-level fields: ${extraKeys.join(", ")}`);
|
|
3552
3951
|
if ("arguments" in input) {
|
|
3553
|
-
const args = input
|
|
3952
|
+
const args = input["arguments"];
|
|
3554
3953
|
if (args === void 0) return {};
|
|
3555
3954
|
if (!args || typeof args !== "object" || Array.isArray(args)) throw new ToolInputError("callMcpTool arguments must be an object when provided");
|
|
3556
3955
|
return args;
|
|
@@ -4070,6 +4469,17 @@ function slackUserInputAnswerNote(args) {
|
|
|
4070
4469
|
if (answer.other) lines.push(`*Other*: ${escapeSlackMrkdwnText(answer.other)}`);
|
|
4071
4470
|
return truncate$2([`${who} answered`, ...lines].join("\n"), MAX_NOTE_CHARS);
|
|
4072
4471
|
}
|
|
4472
|
+
// src/net/link-url.ts
|
|
4473
|
+
/**
|
|
4474
|
+
* Return the normalized href of an HTTP or HTTPS link, or undefined. Agents,
|
|
4475
|
+
* plugins and messages supply these links, and URL parsing also accepts
|
|
4476
|
+
* `javascript:` and `data:` URLs.
|
|
4477
|
+
*/
|
|
4478
|
+
function safeLinkUrl(url) {
|
|
4479
|
+
if (!url || !URL.canParse(url)) return void 0;
|
|
4480
|
+
const href = new URL(url);
|
|
4481
|
+
return href.protocol === "https:" || href.protocol === "http:" ? href.href : void 0;
|
|
4482
|
+
}
|
|
4073
4483
|
// src/chat/slack/review-item-card.ts
|
|
4074
4484
|
/** Callback id of the modal form that answers a Review item. */
|
|
4075
4485
|
const SLACK_REVIEW_ITEM_VIEW_ID = "junior_review_item";
|
|
@@ -4106,11 +4516,6 @@ function titleText(item) {
|
|
|
4106
4516
|
if (!href) return `**${item.title}**`;
|
|
4107
4517
|
return `**[${item.title.replace(/[[\]\\]/g, "\\$&")}](${href.replaceAll("(", "%28").replaceAll(")", "%29")})**`;
|
|
4108
4518
|
}
|
|
4109
|
-
function safeLinkUrl(url) {
|
|
4110
|
-
if (!url || !URL.canParse(url)) return void 0;
|
|
4111
|
-
const href = new URL(url);
|
|
4112
|
-
return href.protocol === "https:" || href.protocol === "http:" ? href.href : void 0;
|
|
4113
|
-
}
|
|
4114
4519
|
/** The title, body, and question of an item, in Slack markdown. */
|
|
4115
4520
|
function itemText(item) {
|
|
4116
4521
|
return normalizeSlackReplyMarkdown([
|
|
@@ -4407,7 +4812,7 @@ async function findSlackMentionedUserId(text, tenant) {
|
|
|
4407
4812
|
const slackUserId = parseSlackUserId(SLACK_MENTION.exec(text)?.[1] ?? text);
|
|
4408
4813
|
if (!slackUserId) return void 0;
|
|
4409
4814
|
const user = tenant?.provider === "slack" ? (await readActorIdentityFromSql(getDb(), createSlackActor(tenant.providerTenantId, slackUserId, void 0)))?.user : void 0;
|
|
4410
|
-
if (!user) throw new ToolInputError(`<@${slackUserId}> has no
|
|
4815
|
+
if (!user) throw new ToolInputError(`<@${slackUserId}> has no User yet. Assign them by email.`);
|
|
4411
4816
|
return user.id;
|
|
4412
4817
|
}
|
|
4413
4818
|
/**
|
|
@@ -5216,238 +5621,6 @@ function createUnpublishImageTool(args) {
|
|
|
5216
5621
|
}
|
|
5217
5622
|
});
|
|
5218
5623
|
}
|
|
5219
|
-
// src/chat/attachments/download.ts
|
|
5220
|
-
/** Refusal for a file over `MAX_ATTACHMENT_BYTES`. */
|
|
5221
|
-
const ATTACHMENT_TOO_LARGE_MESSAGE = `Attachment is larger than the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB file limit.`;
|
|
5222
|
-
/** An attachment whose bytes cannot be read. The message is safe to show. */
|
|
5223
|
-
var AttachmentDownloadError = class extends Error {
|
|
5224
|
-
constructor(message, options) {
|
|
5225
|
-
super(message, options);
|
|
5226
|
-
this.name = "AttachmentDownloadError";
|
|
5227
|
-
}
|
|
5228
|
-
};
|
|
5229
|
-
/**
|
|
5230
|
-
* Find where the bytes of one attachment row are, without reading them.
|
|
5231
|
-
*
|
|
5232
|
-
* A stored file reads from storage. A large Slack file is never stored, so
|
|
5233
|
-
* each `open` downloads it from its source. The source reports the current
|
|
5234
|
-
* size, and the size check runs before any download. Errors that the person
|
|
5235
|
-
* should see are `AttachmentDownloadError`, from here or from `open`.
|
|
5236
|
-
*
|
|
5237
|
-
* The row must come from a lookup scoped to the caller's conversation. The
|
|
5238
|
-
* source id comes from that row only, never from a request.
|
|
5239
|
-
*/
|
|
5240
|
-
async function readAttachmentContent(args) {
|
|
5241
|
-
const { attachment, storage } = args;
|
|
5242
|
-
const { storageKey } = attachment;
|
|
5243
|
-
if (storageKey !== null) return {
|
|
5244
|
-
bytes: attachment.bytes,
|
|
5245
|
-
open: async () => {
|
|
5246
|
-
const body = await storage.get(storageKey);
|
|
5247
|
-
if (!body) throw new AttachmentDownloadError("Stored attachment contents are unavailable.");
|
|
5248
|
-
return body;
|
|
5249
|
-
}
|
|
5250
|
-
};
|
|
5251
|
-
const { source } = attachment;
|
|
5252
|
-
if (!source || !args.readAttachmentSource) throw new AttachmentDownloadError("Attachment cannot be downloaded from this conversation.");
|
|
5253
|
-
const unavailable = (error) => error instanceof AttachmentSourceUnavailableError ? new AttachmentDownloadError(`${attachment.filename} is no longer available: ${error.message}`, { cause: error }) : error;
|
|
5254
|
-
let file;
|
|
5255
|
-
try {
|
|
5256
|
-
file = await args.readAttachmentSource(source);
|
|
5257
|
-
} catch (error) {
|
|
5258
|
-
throw unavailable(error);
|
|
5259
|
-
}
|
|
5260
|
-
if (file.bytes > 262144e3) throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
5261
|
-
return {
|
|
5262
|
-
bytes: file.bytes,
|
|
5263
|
-
open: async () => {
|
|
5264
|
-
try {
|
|
5265
|
-
return await file.open();
|
|
5266
|
-
} catch (error) {
|
|
5267
|
-
throw unavailable(error);
|
|
5268
|
-
}
|
|
5269
|
-
}
|
|
5270
|
-
};
|
|
5271
|
-
}
|
|
5272
|
-
// src/chat/tools/load-attachment.ts
|
|
5273
|
-
const ATTACHMENT_DIR = ".junior/attachments";
|
|
5274
|
-
/** Bytes held in memory and sent to the sandbox in one write. */
|
|
5275
|
-
const PART_BYTES = 8388608;
|
|
5276
|
-
const JOIN_PARTS_SCRIPT = "set -eu; out=$1; shift; cat -- \"$@\" > \"$out\"";
|
|
5277
|
-
/** Turn a read failure that the model can relay into a tool error. */
|
|
5278
|
-
function toolError(error) {
|
|
5279
|
-
return error instanceof AttachmentDownloadError ? new ToolInputError(error.message, { cause: error }) : error;
|
|
5280
|
-
}
|
|
5281
|
-
/** Run one sandbox command, and return its stdout. Throw when it fails. */
|
|
5282
|
-
async function runChecked(workspace, action, input) {
|
|
5283
|
-
const result = await workspace.runCommand(input);
|
|
5284
|
-
if (result.exitCode !== 0) throw new Error(`Failed to ${action}: ${result.stderr}`);
|
|
5285
|
-
return result.stdout;
|
|
5286
|
-
}
|
|
5287
|
-
/**
|
|
5288
|
-
* Write an attachment body to the sandbox in parts of at most `PART_BYTES`.
|
|
5289
|
-
*
|
|
5290
|
-
* The sandbox SDK writes only whole buffers, so this keeps one part in
|
|
5291
|
-
* memory, not the file. Returns the part paths in order.
|
|
5292
|
-
*/
|
|
5293
|
-
async function writeParts(args) {
|
|
5294
|
-
const parts = [];
|
|
5295
|
-
let pending = [];
|
|
5296
|
-
let pendingBytes = 0;
|
|
5297
|
-
let total = 0;
|
|
5298
|
-
const flush = async () => {
|
|
5299
|
-
const partPath = path.posix.join(args.partsDir, String(parts.length).padStart(4, "0"));
|
|
5300
|
-
await args.workspace.writeFiles([{
|
|
5301
|
-
content: Buffer.concat(pending),
|
|
5302
|
-
path: partPath
|
|
5303
|
-
}]);
|
|
5304
|
-
parts.push(partPath);
|
|
5305
|
-
pending = [];
|
|
5306
|
-
pendingBytes = 0;
|
|
5307
|
-
};
|
|
5308
|
-
const reader = args.body.getReader();
|
|
5309
|
-
try {
|
|
5310
|
-
for (;;) {
|
|
5311
|
-
const { done, value } = await reader.read();
|
|
5312
|
-
if (done) break;
|
|
5313
|
-
total += value.byteLength;
|
|
5314
|
-
if (total > args.expectedBytes) break;
|
|
5315
|
-
let chunk = value;
|
|
5316
|
-
while (pendingBytes + chunk.byteLength >= PART_BYTES) {
|
|
5317
|
-
const take = PART_BYTES - pendingBytes;
|
|
5318
|
-
pending.push(chunk.subarray(0, take));
|
|
5319
|
-
pendingBytes += take;
|
|
5320
|
-
await flush();
|
|
5321
|
-
chunk = chunk.subarray(take);
|
|
5322
|
-
}
|
|
5323
|
-
if (chunk.byteLength > 0) {
|
|
5324
|
-
pending.push(chunk);
|
|
5325
|
-
pendingBytes += chunk.byteLength;
|
|
5326
|
-
}
|
|
5327
|
-
}
|
|
5328
|
-
} finally {
|
|
5329
|
-
await reader.cancel().catch(() => void 0);
|
|
5330
|
-
}
|
|
5331
|
-
if (total !== args.expectedBytes) throw new Error(`Attachment ${args.attachmentId} read ${total} bytes, expected ${args.expectedBytes}.`);
|
|
5332
|
-
if (pendingBytes > 0 || parts.length === 0) await flush();
|
|
5333
|
-
return parts;
|
|
5334
|
-
}
|
|
5335
|
-
/**
|
|
5336
|
-
* Create a tool that restores one conversation attachment to the sandbox.
|
|
5337
|
-
*
|
|
5338
|
-
* A large Slack file is never stored: each load streams it from Slack
|
|
5339
|
-
* through the host. The sandbox never gets a Slack URL or token.
|
|
5340
|
-
*
|
|
5341
|
-
* @runBuilt loadAttachment
|
|
5342
|
-
*/
|
|
5343
|
-
function createLoadAttachmentTool(args) {
|
|
5344
|
-
return zodTool({
|
|
5345
|
-
description: "Load a stored attachment for this conversation into the sandbox.",
|
|
5346
|
-
annotations: {
|
|
5347
|
-
destructiveHint: false,
|
|
5348
|
-
idempotentHint: true,
|
|
5349
|
-
openWorldHint: true,
|
|
5350
|
-
readOnlyHint: false
|
|
5351
|
-
},
|
|
5352
|
-
inputSchema: z.object({ attachment_id: z.string().min(1).describe("Stored attachment ID, as shown in attachment context or Slack read results.") }),
|
|
5353
|
-
outputSchema: juniorToolOutputSchema,
|
|
5354
|
-
execute: async ({ attachment_id }) => {
|
|
5355
|
-
const attachment = await readLiveAttachment({
|
|
5356
|
-
attachmentId: attachment_id,
|
|
5357
|
-
conversationId: args.conversationId,
|
|
5358
|
-
db: args.db
|
|
5359
|
-
});
|
|
5360
|
-
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
5361
|
-
if (attachment.bytes > 262144e3) throw new ToolInputError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
5362
|
-
let content;
|
|
5363
|
-
try {
|
|
5364
|
-
content = await readAttachmentContent({
|
|
5365
|
-
attachment,
|
|
5366
|
-
readAttachmentSource: args.readAttachmentSource,
|
|
5367
|
-
storage: args.storage
|
|
5368
|
-
});
|
|
5369
|
-
} catch (error) {
|
|
5370
|
-
throw toolError(error);
|
|
5371
|
-
}
|
|
5372
|
-
const attachmentDir = path.posix.join(ATTACHMENT_DIR, attachment.id);
|
|
5373
|
-
const partsDir = `${attachmentDir}.parts`;
|
|
5374
|
-
const sandboxPath = path.posix.join(attachmentDir, path.posix.basename(attachment.filename));
|
|
5375
|
-
await runChecked(args.workspace, "create attachment directory", {
|
|
5376
|
-
cmd: "mkdir",
|
|
5377
|
-
args: [
|
|
5378
|
-
"-p",
|
|
5379
|
-
"--",
|
|
5380
|
-
attachmentDir,
|
|
5381
|
-
partsDir
|
|
5382
|
-
]
|
|
5383
|
-
});
|
|
5384
|
-
const joinedPath = path.posix.join(partsDir, "joined");
|
|
5385
|
-
try {
|
|
5386
|
-
const parts = await writeParts({
|
|
5387
|
-
attachmentId: attachment.id,
|
|
5388
|
-
body: await content.open(),
|
|
5389
|
-
expectedBytes: content.bytes,
|
|
5390
|
-
partsDir,
|
|
5391
|
-
workspace: args.workspace
|
|
5392
|
-
});
|
|
5393
|
-
await runChecked(args.workspace, "join attachment parts", {
|
|
5394
|
-
cmd: "sh",
|
|
5395
|
-
args: [
|
|
5396
|
-
"-c",
|
|
5397
|
-
JOIN_PARTS_SCRIPT,
|
|
5398
|
-
"sh",
|
|
5399
|
-
joinedPath,
|
|
5400
|
-
...parts
|
|
5401
|
-
]
|
|
5402
|
-
});
|
|
5403
|
-
const size = await runChecked(args.workspace, "read attachment size", {
|
|
5404
|
-
cmd: "stat",
|
|
5405
|
-
args: [
|
|
5406
|
-
"-c",
|
|
5407
|
-
"%s",
|
|
5408
|
-
"--",
|
|
5409
|
-
joinedPath
|
|
5410
|
-
]
|
|
5411
|
-
});
|
|
5412
|
-
const written = Number(size.trim());
|
|
5413
|
-
if (written !== content.bytes) throw new Error(`Attachment ${attachment.id} wrote ${written} bytes to the sandbox, expected ${content.bytes}.`);
|
|
5414
|
-
await runChecked(args.workspace, "move attachment into place", {
|
|
5415
|
-
cmd: "mv",
|
|
5416
|
-
args: [
|
|
5417
|
-
"-f",
|
|
5418
|
-
"--",
|
|
5419
|
-
joinedPath,
|
|
5420
|
-
sandboxPath
|
|
5421
|
-
]
|
|
5422
|
-
});
|
|
5423
|
-
} catch (error) {
|
|
5424
|
-
await args.workspace.runCommand({
|
|
5425
|
-
cmd: "rm",
|
|
5426
|
-
args: [
|
|
5427
|
-
"-rf",
|
|
5428
|
-
"--",
|
|
5429
|
-
partsDir
|
|
5430
|
-
]
|
|
5431
|
-
}).catch(() => void 0);
|
|
5432
|
-
throw toolError(error);
|
|
5433
|
-
}
|
|
5434
|
-
await runChecked(args.workspace, "remove attachment parts", {
|
|
5435
|
-
cmd: "rm",
|
|
5436
|
-
args: [
|
|
5437
|
-
"-rf",
|
|
5438
|
-
"--",
|
|
5439
|
-
partsDir
|
|
5440
|
-
]
|
|
5441
|
-
});
|
|
5442
|
-
return {
|
|
5443
|
-
path: sandboxPath,
|
|
5444
|
-
filename: attachment.filename,
|
|
5445
|
-
mime_type: attachment.contentType,
|
|
5446
|
-
bytes: content.bytes
|
|
5447
|
-
};
|
|
5448
|
-
}
|
|
5449
|
-
});
|
|
5450
|
-
}
|
|
5451
5624
|
// src/chat/tools/index.ts
|
|
5452
5625
|
function createToolState() {
|
|
5453
5626
|
const operationResultCache = /* @__PURE__ */ new Map();
|
|
@@ -5475,11 +5648,12 @@ const STATIC_TOOL_BINDERS = {
|
|
|
5475
5648
|
updatePlan: () => createUpdatePlanTool(),
|
|
5476
5649
|
reportProgress: () => createReportProgressTool(),
|
|
5477
5650
|
systemTime: () => createSystemTimeTool(),
|
|
5651
|
+
submitFeedback: (run) => createSubmitFeedbackTool(run.context),
|
|
5478
5652
|
bash: () => createBashTool(),
|
|
5479
5653
|
readFile: () => createReadFileTool(),
|
|
5480
5654
|
editFile: () => createEditFileTool(),
|
|
5481
5655
|
writeFile: () => createWriteFileTool(),
|
|
5482
|
-
webSearch: (run) => createWebSearchTool(botConfig.webSearchModelId, run.hooks.toolOverrides?.webSearch),
|
|
5656
|
+
webSearch: (run) => createWebSearchTool(botConfig.webSearchModelId, run.modelCost, run.hooks.toolOverrides?.webSearch),
|
|
5483
5657
|
webFetch: (run) => createWebFetchTool(run.hooks, { canSendFilesToActiveConversation: run.canSendFilesToActiveConversation }),
|
|
5484
5658
|
watchTimer: (run) => createWatchTimerTool(run.context),
|
|
5485
5659
|
searchEventTypes: (run) => createSearchEventTypesTool(run.catalog),
|
|
@@ -5489,11 +5663,11 @@ const STATIC_TOOL_BINDERS = {
|
|
|
5489
5663
|
searchAutomations: (run) => withDisabledReason(createSearchAutomationsTool(run.automation, run.catalog), run.automationDisabledReason),
|
|
5490
5664
|
deleteAutomation: (run) => withDisabledReason(createDeleteAutomationTool(run.automation, run.catalog), run.automationDisabledReason),
|
|
5491
5665
|
runAutomationNow: (run) => withDisabledReason(createRunAutomationNowTool(run.automation, run.catalog), run.automationDisabledReason),
|
|
5492
|
-
createWorkspace: (run) => run.workspaceTools()
|
|
5493
|
-
updateWorkspace: (run) => run.workspaceTools()
|
|
5494
|
-
deleteWorkspace: (run) => run.workspaceTools()
|
|
5495
|
-
listWorkspaces: (run) => run.workspaceTools()
|
|
5496
|
-
switchWorkspace: (run) => run.workspaceTools()
|
|
5666
|
+
createWorkspace: (run) => run.workspaceTools()["createWorkspace"],
|
|
5667
|
+
updateWorkspace: (run) => run.workspaceTools()["updateWorkspace"],
|
|
5668
|
+
deleteWorkspace: (run) => run.workspaceTools()["deleteWorkspace"],
|
|
5669
|
+
listWorkspaces: (run) => run.workspaceTools()["listWorkspaces"],
|
|
5670
|
+
switchWorkspace: (run) => run.workspaceTools()["switchWorkspace"],
|
|
5497
5671
|
runOperatorSql: (run) => isPublic(run) ? void 0 : createRunOperatorSqlTool(),
|
|
5498
5672
|
updateUserCustomization: (run) => createUpdateUserCustomizationTool(run.context),
|
|
5499
5673
|
setConversationSubscription: (run) => createSetConversationSubscriptionTool(run.context),
|
|
@@ -5576,7 +5750,7 @@ const RUN_BUILT_TOOL_BUILDERS = {
|
|
|
5576
5750
|
imageGenerate: (run) => run.hooks.writeGeneratedArtifacts ? createImageGenerateTool({ writeGeneratedArtifacts: run.hooks.writeGeneratedArtifacts }, {
|
|
5577
5751
|
modelId: botConfig.imageGenerationModelId,
|
|
5578
5752
|
canSendFilesToActiveConversation: run.canSendFilesToActiveConversation,
|
|
5579
|
-
|
|
5753
|
+
modelCost: run.modelCost,
|
|
5580
5754
|
sandbox: run.context.workspace
|
|
5581
5755
|
}, run.hooks.toolOverrides?.imageGenerate) : void 0,
|
|
5582
5756
|
localSendFiles: (run) => {
|
|
@@ -5603,6 +5777,22 @@ const RUN_BUILT_TOOL_BUILDERS = {
|
|
|
5603
5777
|
conversationId: run.context.conversationId,
|
|
5604
5778
|
db: getSqlExecutor()
|
|
5605
5779
|
}) : void 0,
|
|
5780
|
+
transcribeAudio: (run) => {
|
|
5781
|
+
const storage = run.context.attachmentStorage;
|
|
5782
|
+
const createDownloadUrl = storage?.createDownloadUrl?.bind(storage);
|
|
5783
|
+
return storage && createDownloadUrl ? createTranscribeAudioTool({
|
|
5784
|
+
conversationId: run.context.conversationId,
|
|
5785
|
+
db: getSqlExecutor(),
|
|
5786
|
+
modelCost: run.modelCost,
|
|
5787
|
+
modelId: botConfig.transcriptionModelId,
|
|
5788
|
+
...run.slack ? { readAttachmentSource: readSlackAttachmentSource } : void 0,
|
|
5789
|
+
storage: {
|
|
5790
|
+
...storage,
|
|
5791
|
+
createDownloadUrl
|
|
5792
|
+
},
|
|
5793
|
+
workspace: run.context.workspace
|
|
5794
|
+
}) : void 0;
|
|
5795
|
+
},
|
|
5606
5796
|
searchMcpTools: (run) => run.context.mcpToolManager ? createSearchMcpToolsTool(run.context.mcpToolManager) : void 0,
|
|
5607
5797
|
callMcpTool: (run) => run.context.mcpToolManager ? createCallMcpToolTool(run.context.mcpToolManager) : void 0,
|
|
5608
5798
|
slackCanvasCreate: (run) => {
|
|
@@ -5860,11 +6050,11 @@ function schemaErrorText(schema, value) {
|
|
|
5860
6050
|
function resolveCatalogToolCall(input, catalogTools) {
|
|
5861
6051
|
const extraKeys = Object.keys(input).filter((key) => key !== "tool_name" && key !== "arguments");
|
|
5862
6052
|
if (extraKeys.length > 0) throw new ToolInputError(`executeTool arguments must be nested under arguments, not top-level fields: ${extraKeys.join(", ")}`);
|
|
5863
|
-
const toolName = input
|
|
6053
|
+
const toolName = input["tool_name"];
|
|
5864
6054
|
if (typeof toolName !== "string" || toolName.length === 0) throw new ToolInputError("executeTool requires a catalog tool_name.");
|
|
5865
6055
|
const definition = catalogTools[toolName];
|
|
5866
6056
|
if (!definition) throw new ToolNameMissError(`executeTool can only call catalog tools returned by searchTools: ${toolName}.`, findToolNameHint(toolName, catalogTools));
|
|
5867
|
-
const args = input
|
|
6057
|
+
const args = input["arguments"];
|
|
5868
6058
|
if (args === void 0) return {
|
|
5869
6059
|
arguments: {},
|
|
5870
6060
|
definition,
|
|
@@ -5896,23 +6086,23 @@ function prepareCatalogToolCall(call, dispatcherName = "executeTool") {
|
|
|
5896
6086
|
function buildSandboxInput(toolName, params) {
|
|
5897
6087
|
const optionalNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
5898
6088
|
if (toolName === "bash") return {
|
|
5899
|
-
command: String(params
|
|
5900
|
-
...typeof params
|
|
5901
|
-
...params
|
|
5902
|
-
...optionalNumber(params
|
|
6089
|
+
command: String(params["command"] ?? ""),
|
|
6090
|
+
...typeof params["cwd"] === "string" ? { cwd: params["cwd"] } : void 0,
|
|
6091
|
+
...params["env"] && typeof params["env"] === "object" && !Array.isArray(params["env"]) ? { env: params["env"] } : void 0,
|
|
6092
|
+
...optionalNumber(params["timeout_ms"]) ? { timeoutMs: optionalNumber(params["timeout_ms"]) } : void 0
|
|
5903
6093
|
};
|
|
5904
6094
|
if (toolName === "readFile") return {
|
|
5905
|
-
path: String(params
|
|
5906
|
-
...optionalNumber(params
|
|
5907
|
-
...optionalNumber(params
|
|
6095
|
+
path: String(params["path"] ?? ""),
|
|
6096
|
+
...optionalNumber(params["offset"]) ? { offset: optionalNumber(params["offset"]) } : void 0,
|
|
6097
|
+
...optionalNumber(params["limit"]) ? { limit: optionalNumber(params["limit"]) } : void 0
|
|
5908
6098
|
};
|
|
5909
6099
|
if (toolName === "editFile") return {
|
|
5910
|
-
path: String(params
|
|
5911
|
-
edits: Array.isArray(params
|
|
6100
|
+
path: String(params["path"] ?? ""),
|
|
6101
|
+
edits: Array.isArray(params["edits"]) ? params["edits"] : []
|
|
5912
6102
|
};
|
|
5913
6103
|
if (toolName === "writeFile") return {
|
|
5914
|
-
path: String(params
|
|
5915
|
-
content: String(params
|
|
6104
|
+
path: String(params["path"] ?? ""),
|
|
6105
|
+
content: String(params["content"] ?? "")
|
|
5916
6106
|
};
|
|
5917
6107
|
return params;
|
|
5918
6108
|
}
|
|
@@ -6708,8 +6898,8 @@ function parameterText(schema) {
|
|
|
6708
6898
|
if (!schema || typeof schema !== "object") return [];
|
|
6709
6899
|
const record = schema;
|
|
6710
6900
|
const text = [];
|
|
6711
|
-
if (typeof record
|
|
6712
|
-
const properties = record
|
|
6901
|
+
if (typeof record["description"] === "string") text.push(record["description"]);
|
|
6902
|
+
const properties = record["properties"];
|
|
6713
6903
|
if (properties && typeof properties === "object") for (const [name, property] of Object.entries(properties)) text.push(name, ...parameterText(property));
|
|
6714
6904
|
for (const key of [
|
|
6715
6905
|
"items",
|
|
@@ -7404,8 +7594,8 @@ function renderDeclaration(name, tool) {
|
|
|
7404
7594
|
}).trim().replace(/\n/g, "\n ")}`;
|
|
7405
7595
|
}
|
|
7406
7596
|
/**
|
|
7407
|
-
* Tell the script which tools it may call, for the `<script-tools>`
|
|
7408
|
-
*
|
|
7597
|
+
* Tell the script which tools it may call, for the `<script-tools>` system
|
|
7598
|
+
* prompt section. Direct tools are only named: the model already has their
|
|
7409
7599
|
* input schemas. The other tools are declared within the token budget,
|
|
7410
7600
|
* cheapest first, so that the most tools fit. The others stay callable. The
|
|
7411
7601
|
* model finds their input with `searchTools`. Script-only tools come first,
|
|
@@ -7453,7 +7643,7 @@ const DESCRIPTION = [
|
|
|
7453
7643
|
`- The script has ${CODE_MODE_SCRIPT_TIMEOUT_MS / 1e3} seconds, including its tool calls.`,
|
|
7454
7644
|
`- Start at most 10 calls before the script awaits. A larger batch fails, and none of its calls run.`,
|
|
7455
7645
|
"- The result lists each tool call and its status. When action review rejects a call, do what its instructions say, such as ask the user, before you try it again.",
|
|
7456
|
-
"- `<script-tools>` in the
|
|
7646
|
+
"- `<script-tools>` in the system prompt lists the tools that a script can call."
|
|
7457
7647
|
].join("\n");
|
|
7458
7648
|
function renderCall(call, index) {
|
|
7459
7649
|
return [`${index + 1}. ${call.toolName}: ${CODE_MODE_CALL_STATUS_TEXT[call.status]}`, ...[...call.error ? [call.error] : [], ...(call.nudges ?? []).map(renderToolResultNudge)].map((note) => ` ${note.replace(/\n/g, "\n ")}`)].join("\n");
|
|
@@ -7599,7 +7789,7 @@ function createToolPipeline(options) {
|
|
|
7599
7789
|
const executionInput = {
|
|
7600
7790
|
...toolInput,
|
|
7601
7791
|
...Object.keys(beforeTool.env).length > 0 ? { env: {
|
|
7602
|
-
...toolInput
|
|
7792
|
+
...toolInput["env"] && typeof toolInput["env"] === "object" && !Array.isArray(toolInput["env"]) ? toolInput["env"] : void 0,
|
|
7603
7793
|
...beforeTool.env
|
|
7604
7794
|
} } : void 0
|
|
7605
7795
|
};
|
|
@@ -8013,7 +8203,7 @@ function createJwtBearerMcpClientProvider(subject, mcpUrl, auth) {
|
|
|
8013
8203
|
/** The client metadata that Junior registers for one MCP OAuth callback. */
|
|
8014
8204
|
function createClientMetadata(callbackUrl) {
|
|
8015
8205
|
return {
|
|
8016
|
-
client_name:
|
|
8206
|
+
client_name: `${botConfig.userName} MCP Client`,
|
|
8017
8207
|
redirect_uris: [callbackUrl],
|
|
8018
8208
|
grant_types: ["authorization_code", "refresh_token"],
|
|
8019
8209
|
response_types: ["code"],
|
|
@@ -8824,9 +9014,9 @@ function isRecord(value) {
|
|
|
8824
9014
|
* author and the root's provider. Returns nothing when it is not known.
|
|
8825
9015
|
*/
|
|
8826
9016
|
function messageAuthor(root, data) {
|
|
8827
|
-
const author = isRecord(data.meta?.author) ? data.meta
|
|
8828
|
-
const userId = typeof author?.userId === "string" ? author
|
|
8829
|
-
if (!userId || author?.isBot === true) return;
|
|
9017
|
+
const author = isRecord(data.meta?.["author"]) ? data.meta["author"] : void 0;
|
|
9018
|
+
const userId = typeof author?.["userId"] === "string" ? author["userId"].trim() : void 0;
|
|
9019
|
+
if (!userId || author?.["isBot"] === true) return;
|
|
8830
9020
|
const session = root.sessionSource;
|
|
8831
9021
|
const platform = session?.kind ?? root.destination?.platform;
|
|
8832
9022
|
if (platform === "slack") {
|
|
@@ -8867,8 +9057,8 @@ function messageLabel(root, data, actor, personIdentityIds, parentTaskIds) {
|
|
|
8867
9057
|
if (data.role === "assistant") return "assistant";
|
|
8868
9058
|
if (data.role !== "user") return "system";
|
|
8869
9059
|
if (parentTaskIds && isParentMessageMeta(data.meta)) return "user";
|
|
8870
|
-
if (data.meta?.eventType !== void 0) return "event";
|
|
8871
|
-
const invocationId = data.meta?.agentInvocationId;
|
|
9060
|
+
if (data.meta?.["eventType"] !== void 0) return "event";
|
|
9061
|
+
const invocationId = data.meta?.["agentInvocationId"];
|
|
8872
9062
|
if (typeof invocationId === "string" && parentTaskIds?.has(invocationId)) return "user";
|
|
8873
9063
|
if (data.authorIdentityId && personIdentityIds.has(data.authorIdentityId)) return "user";
|
|
8874
9064
|
const author = messageAuthor(root, data);
|
|
@@ -9050,7 +9240,11 @@ async function createRunSandbox(args) {
|
|
|
9050
9240
|
locationConfiguration: args.run.environment?.locationConfiguration,
|
|
9051
9241
|
configurationValues: args.configurationValues,
|
|
9052
9242
|
getActiveSkill: () => args.skillSandbox.getActiveSkill(),
|
|
9053
|
-
prepareSandbox:
|
|
9243
|
+
prepareSandbox: async (sandbox) => {
|
|
9244
|
+
const actor = args.currentActor;
|
|
9245
|
+
if (actor) await renewPreviewOrigins(sandbox, async () => (await readActorIdentity(actor))?.user);
|
|
9246
|
+
await pluginHooks.prepareSandbox(sandbox);
|
|
9247
|
+
},
|
|
9054
9248
|
prepareWorkspace: async (sandbox, recipe, signal) => await pluginHooks.prepareWorkspace(sandbox, recipe.repos, signal),
|
|
9055
9249
|
onSandboxRefChanged: args.onSandboxRefChanged,
|
|
9056
9250
|
persistSandboxRef: args.durability.onSandboxRefChanged
|
|
@@ -9076,7 +9270,7 @@ function createPromptHookContext(args) {
|
|
|
9076
9270
|
}
|
|
9077
9271
|
/** Record optional reporting without changing the loadSkill outcome. */
|
|
9078
9272
|
async function tryRecordSkillLoadStat(skill) {
|
|
9079
|
-
if (!process.env
|
|
9273
|
+
if (!process.env["DATABASE_URL"]) return;
|
|
9080
9274
|
try {
|
|
9081
9275
|
await incrementStat({
|
|
9082
9276
|
namespace: skill.pluginProvider ?? "junior",
|
|
@@ -9569,7 +9763,7 @@ function createResumeState(args) {
|
|
|
9569
9763
|
const parkMessages = reason === "yield" ? [...resumeMessages] : continuableMessages(resumeMessages, latestSafeBoundaryMessages);
|
|
9570
9764
|
const parkKey = boundaryKey(parkMessages);
|
|
9571
9765
|
if (reason !== "timeout" && !advancedPastResume && resumedBoundaryKey.length > 0 && parkKey === resumedBoundaryKey) {
|
|
9572
|
-
logWarn("agent.turn.
|
|
9766
|
+
logWarn("agent.turn.no_progress.failed", {
|
|
9573
9767
|
"app.ai.resume_conversation_id": args.conversationId,
|
|
9574
9768
|
"app.ai.resume_session_id": args.turnId,
|
|
9575
9769
|
"app.ai.resume_slice_id": currentSliceId,
|
|
@@ -9609,6 +9803,16 @@ function createResumeState(args) {
|
|
|
9609
9803
|
};
|
|
9610
9804
|
}
|
|
9611
9805
|
// src/chat/agent/context-summary.ts
|
|
9806
|
+
/**
|
|
9807
|
+
* Context summary for capacity compaction.
|
|
9808
|
+
*
|
|
9809
|
+
* The summary request is the agent model request for the same messages, with
|
|
9810
|
+
* one more user message that asks for the summary. The model, system prompt,
|
|
9811
|
+
* tools, and reasoning stay the same, so the provider can read the cached
|
|
9812
|
+
* prompt prefix of the last agent call. Anthropic drops cached messages when
|
|
9813
|
+
* `tool_choice`, thinking, or effort change, so the request keeps the tools
|
|
9814
|
+
* and the instruction forbids tool calls instead.
|
|
9815
|
+
*/
|
|
9612
9816
|
/** Prompt name of the summary request on its `gen_ai.chat` span. */
|
|
9613
9817
|
const CONTEXT_COMPACTION_PROMPT_NAME = "junior.context_compaction";
|
|
9614
9818
|
const SUMMARY_MAX_TOKENS = 8e3;
|
|
@@ -9658,13 +9862,13 @@ var ContextSummaryError = class extends Error {
|
|
|
9658
9862
|
* so it fails when Pi changes these steps.
|
|
9659
9863
|
*/
|
|
9660
9864
|
async function buildAgentModelRequest(agent, messages, signal) {
|
|
9661
|
-
const { model,
|
|
9865
|
+
const { model, thinkingLevel, tools } = agent.state;
|
|
9866
|
+
const leading = getInitialSystemMessage(agent.state.messages);
|
|
9662
9867
|
const transformed = agent.transformContext ? await agent.transformContext(messages, signal) : messages;
|
|
9663
9868
|
return {
|
|
9664
9869
|
model,
|
|
9665
9870
|
context: {
|
|
9666
|
-
|
|
9667
|
-
messages: await agent.convertToLlm(transformed),
|
|
9871
|
+
...foldLeadingSystemMessages(leading ? getSystemMessageText$1(leading) : "", await agent.convertToLlm(transformed)),
|
|
9668
9872
|
tools
|
|
9669
9873
|
},
|
|
9670
9874
|
options: {
|
|
@@ -9676,6 +9880,7 @@ async function buildAgentModelRequest(agent, messages, signal) {
|
|
|
9676
9880
|
thinkingBudgets: agent.thinkingBudgets,
|
|
9677
9881
|
maxRetryDelayMs: agent.maxRetryDelayMs,
|
|
9678
9882
|
apiKey: await agent.getApiKey?.(model.provider) || void 0,
|
|
9883
|
+
identity: mergeClientIdentity(DEFAULT_AGENT_IDENTITY, agent.identity),
|
|
9679
9884
|
signal
|
|
9680
9885
|
}
|
|
9681
9886
|
};
|
|
@@ -10222,39 +10427,18 @@ function withoutRequestContext(text) {
|
|
|
10222
10427
|
return withoutSections(text, Object.values(REQUEST_CONTEXT_SECTION_TAG));
|
|
10223
10428
|
}
|
|
10224
10429
|
/**
|
|
10225
|
-
*
|
|
10226
|
-
*
|
|
10430
|
+
* Remove the copies of capability sections that the Turn context of older
|
|
10431
|
+
* Turns held. Later system messages hold them now, and compaction folds
|
|
10432
|
+
* those.
|
|
10227
10433
|
*/
|
|
10228
|
-
|
|
10229
|
-
|
|
10230
|
-
return tags.flatMap((tag) => latestTurnContextSection(messages, tag) ?? []);
|
|
10231
|
-
}
|
|
10232
|
-
/**
|
|
10233
|
-
* Remove every copy of the latest-copy sections, then put the given copies in
|
|
10234
|
-
* the first Turn context part. Callers leave out a section that kept history
|
|
10235
|
-
* already has.
|
|
10236
|
-
*/
|
|
10237
|
-
function withLatestSections(content, sections) {
|
|
10238
|
-
const closingTag = `\n</${TURN_CONTEXT_TAG}>`;
|
|
10239
|
-
const added = sections.map((section) => `\n\n${section}`).join("");
|
|
10240
|
-
let pending = sections.length > 0;
|
|
10241
|
-
const result = content.map((part) => {
|
|
10434
|
+
function withoutCapabilitySections(content) {
|
|
10435
|
+
return content.map((part) => {
|
|
10242
10436
|
const text = textPart(part);
|
|
10243
|
-
|
|
10244
|
-
let stripped = withoutSections(text, LATEST_COPY_SECTION_TAGS);
|
|
10245
|
-
if (pending && stripped.endsWith(closingTag)) {
|
|
10246
|
-
stripped = `${stripped.slice(0, -closingTag.length)}${added}${closingTag}`;
|
|
10247
|
-
pending = false;
|
|
10248
|
-
}
|
|
10249
|
-
return {
|
|
10437
|
+
return text?.startsWith(`<runtime-turn-context>`) ? {
|
|
10250
10438
|
...part,
|
|
10251
|
-
text:
|
|
10252
|
-
};
|
|
10439
|
+
text: withoutSections(text, Object.values(CAPABILITY_SECTION_TAG))
|
|
10440
|
+
} : part;
|
|
10253
10441
|
});
|
|
10254
|
-
return pending ? [{
|
|
10255
|
-
type: "text",
|
|
10256
|
-
text: `<${TURN_CONTEXT_TAG}>${added}${closingTag}`
|
|
10257
|
-
}, ...result] : result;
|
|
10258
10442
|
}
|
|
10259
10443
|
/** Find the latest session context and keep only its session sections. */
|
|
10260
10444
|
function latestSessionContext(messages) {
|
|
@@ -10277,12 +10461,12 @@ function effectiveRuntimeContext(messages) {
|
|
|
10277
10461
|
break;
|
|
10278
10462
|
}
|
|
10279
10463
|
const effectiveMessages = latestBootstrapIndex < 0 ? messages : messages.slice(latestBootstrapIndex);
|
|
10280
|
-
return runtimeContextContent(effectiveMessages, effectiveMessages
|
|
10464
|
+
return runtimeContextContent(effectiveMessages, effectiveMessages);
|
|
10281
10465
|
}
|
|
10282
|
-
function runtimeContextContent(messages, agentsMessages
|
|
10466
|
+
function runtimeContextContent(messages, agentsMessages) {
|
|
10283
10467
|
const allContent = messages.flatMap(userMessageContent);
|
|
10284
10468
|
const firstAgentsIndex = allContent.findIndex((part) => textPart(part)?.startsWith("# AGENTS.md instructions") === true);
|
|
10285
|
-
const content =
|
|
10469
|
+
const content = withoutCapabilitySections(allContent.filter((part) => textPart(part)?.startsWith("# AGENTS.md instructions") !== true));
|
|
10286
10470
|
const visibleAgents = findVisibleAgentsInstructions(agentsMessages);
|
|
10287
10471
|
if (visibleAgents?.active === true) {
|
|
10288
10472
|
const insertionIndex = firstAgentsIndex < 0 ? content.length : Math.min(firstAgentsIndex, content.length);
|
|
@@ -10317,27 +10501,24 @@ function runtimeContextMessage(messages, timestamp) {
|
|
|
10317
10501
|
*
|
|
10318
10502
|
* Request context, such as plugin context and disabled tools, is true only for
|
|
10319
10503
|
* the Turn that received it. From earlier Turns, keep only the latest session
|
|
10320
|
-
* context
|
|
10321
|
-
* and AGENTS.md instructions.
|
|
10504
|
+
* context and AGENTS.md instructions.
|
|
10322
10505
|
*/
|
|
10323
10506
|
function turnRuntimeContextMessage(messages, turnStartMessageIndex, timestamp) {
|
|
10324
10507
|
if (turnStartMessageIndex === void 0) return runtimeContextMessage(retainRuntimeTurnContext(messages), timestamp);
|
|
10325
10508
|
const earlierContext = retainRuntimeTurnContext(messages.slice(0, turnStartMessageIndex));
|
|
10326
10509
|
const turnContext = retainRuntimeTurnContext(messages.slice(turnStartMessageIndex));
|
|
10327
10510
|
const sessionContext = turnContext.some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
10328
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]
|
|
10511
|
+
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext, ...turnContext] : turnContext, [...earlierContext, ...turnContext]), timestamp);
|
|
10329
10512
|
}
|
|
10330
10513
|
/**
|
|
10331
10514
|
* Build the runtime context of summarized history that the kept history
|
|
10332
|
-
* does not carry: the latest session context
|
|
10333
|
-
* capability section and `<script-tools>`, and the AGENTS.md instructions.
|
|
10515
|
+
* does not carry: the latest session context and the AGENTS.md instructions.
|
|
10334
10516
|
* Request context of earlier Turns is left out.
|
|
10335
10517
|
*/
|
|
10336
10518
|
function summarizedRuntimeContextMessage(summarized, kept) {
|
|
10337
10519
|
const earlierContext = retainRuntimeTurnContext(summarized);
|
|
10338
|
-
const
|
|
10339
|
-
|
|
10340
|
-
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext, latestSections(earlierContext, LATEST_COPY_SECTION_TAGS.filter((tag) => !latestTurnContextSection(keptContext, tag)))));
|
|
10520
|
+
const sessionContext = retainRuntimeTurnContext(kept).some((message) => userMessageContent(message).map(textPart).some(isSessionTurnContext)) ? void 0 : latestSessionContext(earlierContext);
|
|
10521
|
+
return toRuntimeContextMessage(runtimeContextContent(sessionContext ? [sessionContext] : [], findVisibleAgentsInstructions(kept) ? [] : earlierContext));
|
|
10341
10522
|
}
|
|
10342
10523
|
/**
|
|
10343
10524
|
* Build retained user messages for a compacted Pi replacement history. Each
|
|
@@ -10395,13 +10576,19 @@ async function loadRetainedUserMessages(conversationId, pendingMessages) {
|
|
|
10395
10576
|
};
|
|
10396
10577
|
});
|
|
10397
10578
|
}
|
|
10398
|
-
|
|
10579
|
+
const COMPACTION_READ_BACK_NOTE = "The summary replaced earlier messages and tool results. When you need an exact detail that the summary lacks, read the full text with the searchConversationEvents and readConversationEvent tools.";
|
|
10580
|
+
/**
|
|
10581
|
+
* Keep generated text inside the existing evidence-only prompt boundary. The
|
|
10582
|
+
* last line says where replaced detail stays readable: without it, the model
|
|
10583
|
+
* often decides an exact value from a compacted tool result is gone.
|
|
10584
|
+
*/
|
|
10399
10585
|
function renderCompactionSummary(summary) {
|
|
10400
10586
|
return [
|
|
10401
10587
|
COMPACTION_SUMMARY_PREFIX,
|
|
10402
10588
|
"<thread-context authority=\"evidence-only\">",
|
|
10403
10589
|
escapeXml(summary),
|
|
10404
|
-
"</thread-context>"
|
|
10590
|
+
"</thread-context>",
|
|
10591
|
+
COMPACTION_READ_BACK_NOTE
|
|
10405
10592
|
].join("\n");
|
|
10406
10593
|
}
|
|
10407
10594
|
function timestampOf(message) {
|
|
@@ -10431,6 +10618,17 @@ function measuredInputTokens(message) {
|
|
|
10431
10618
|
const tokens = (usage.input ?? 0) + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
|
|
10432
10619
|
return tokens > 0 ? tokens : void 0;
|
|
10433
10620
|
}
|
|
10621
|
+
function lastAssistantUsage(messages) {
|
|
10622
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
10623
|
+
const message = messages[index];
|
|
10624
|
+
if (message.role !== "assistant" || message.stopReason === "aborted" || message.stopReason === "error" || !message.usage) continue;
|
|
10625
|
+
const tokens = calculateContextTokens(message.usage);
|
|
10626
|
+
if (tokens > 0) return {
|
|
10627
|
+
tokens,
|
|
10628
|
+
index
|
|
10629
|
+
};
|
|
10630
|
+
}
|
|
10631
|
+
}
|
|
10434
10632
|
/**
|
|
10435
10633
|
* Measure provider-visible history without counting host-only message fields.
|
|
10436
10634
|
*
|
|
@@ -10440,10 +10638,10 @@ function measuredInputTokens(message) {
|
|
|
10440
10638
|
* the latest summary, estimate each message by size.
|
|
10441
10639
|
*/
|
|
10442
10640
|
function estimateHistoryTokens(messages, modelId, requestOverheadTokens = 0) {
|
|
10443
|
-
const
|
|
10641
|
+
const usage = lastAssistantUsage(messages);
|
|
10444
10642
|
const summaryAt = latestSummaryTimestamp(messages);
|
|
10445
|
-
const usageAt =
|
|
10446
|
-
if (
|
|
10643
|
+
const usageAt = usage ? timestampOf(messages[usage.index]) : void 0;
|
|
10644
|
+
if (usage && usageAt !== void 0 && (summaryAt === void 0 || usageAt > summaryAt)) return usage.tokens + estimateMessagesTokens(messages.slice(usage.index + 1), modelId);
|
|
10447
10645
|
return estimateReplacementTokens(messages, modelId, requestOverheadTokens);
|
|
10448
10646
|
}
|
|
10449
10647
|
/**
|
|
@@ -10461,7 +10659,8 @@ function measuredReplacementTokens(messages) {
|
|
|
10461
10659
|
for (const message of messages.slice(summaryIndex + 1)) {
|
|
10462
10660
|
const timestamp = timestampOf(message);
|
|
10463
10661
|
if (timestamp === void 0 || timestamp <= summaryAt) {
|
|
10464
|
-
|
|
10662
|
+
const role = message.role;
|
|
10663
|
+
if (role !== "user" && role !== "system") return void 0;
|
|
10465
10664
|
continue;
|
|
10466
10665
|
}
|
|
10467
10666
|
const tokens = measuredInputTokens(message);
|
|
@@ -10550,10 +10749,16 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
|
|
|
10550
10749
|
...index === 0 && retainedInstruction ? { sourceEventSeq: retainedInstruction.sourceEventSeq } : void 0
|
|
10551
10750
|
}));
|
|
10552
10751
|
const retainedUserMessages = retainUserMessages ? await loadRetainedUserMessages(args.conversationId, instructionMessages) : [];
|
|
10752
|
+
const systemMessage = foldSystemMessages(args.piMessages);
|
|
10753
|
+
const systemEntries = systemMessage ? [{
|
|
10754
|
+
message: systemMessage,
|
|
10755
|
+
provenance: contextProvenance
|
|
10756
|
+
}] : [];
|
|
10553
10757
|
const keptTokens = estimateReplacementTokens([
|
|
10554
10758
|
...retainedUserMessages,
|
|
10555
10759
|
...contextEntries,
|
|
10556
|
-
...instructionEntries
|
|
10760
|
+
...instructionEntries,
|
|
10761
|
+
...systemEntries
|
|
10557
10762
|
].map((entry) => entry.message), args.modelId, args.requestOverheadTokens);
|
|
10558
10763
|
if (belowInputLimit && keptTokens > calculateContextCompactionTargetTokens(triggerTokens)) return skip("over_target");
|
|
10559
10764
|
if (keptTokens >= inputLimitTokens) return skip("over_input_limit");
|
|
@@ -10582,12 +10787,14 @@ async function compactActiveAboveThreshold(args, summarize, source, triggerToken
|
|
|
10582
10787
|
const replacement = retainUserMessages ? [
|
|
10583
10788
|
...retainedUserMessages,
|
|
10584
10789
|
summaryEntry,
|
|
10790
|
+
...systemEntries,
|
|
10585
10791
|
...contextEntries,
|
|
10586
10792
|
...instructionEntries
|
|
10587
10793
|
] : [
|
|
10588
10794
|
...contextEntries,
|
|
10589
10795
|
...instructionEntries,
|
|
10590
|
-
summaryEntry
|
|
10796
|
+
summaryEntry,
|
|
10797
|
+
...systemEntries
|
|
10591
10798
|
];
|
|
10592
10799
|
const retainedMessageCount = retainedUserMessages.length + instructionMessages.length;
|
|
10593
10800
|
const messages = replacement.map((entry) => entry.message);
|
|
@@ -10863,6 +11070,7 @@ async function applyPreparedSummary(args, prepared, budget) {
|
|
|
10863
11070
|
provenance: contextProvenance
|
|
10864
11071
|
};
|
|
10865
11072
|
}));
|
|
11073
|
+
const systemMessage = foldSystemMessages(summarized);
|
|
10866
11074
|
const replacement = [
|
|
10867
11075
|
...contextMessage ? [{
|
|
10868
11076
|
message: contextMessage,
|
|
@@ -10873,6 +11081,10 @@ async function applyPreparedSummary(args, prepared, budget) {
|
|
|
10873
11081
|
message: userMessage(appendOpenPlan(renderCompactionSummary(prepared.summary), summarized)),
|
|
10874
11082
|
provenance: contextProvenance
|
|
10875
11083
|
},
|
|
11084
|
+
...systemMessage ? [{
|
|
11085
|
+
message: systemMessage,
|
|
11086
|
+
provenance: contextProvenance
|
|
11087
|
+
}] : [],
|
|
10876
11088
|
...trimmedEntries,
|
|
10877
11089
|
...pendingMessages
|
|
10878
11090
|
];
|
|
@@ -11355,7 +11567,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11355
11567
|
};
|
|
11356
11568
|
if (initialRepositoryInstructions) await recordAgentsTransition(initialRepositoryInstructions);
|
|
11357
11569
|
const getPendingAuthPause = wiring.getPendingAuthPause;
|
|
11358
|
-
const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
|
|
11570
|
+
const { baseInstructions: assembledBaseInstructions, contextContentParts: promptContextContentParts, inputMessages, inputMessagesAttribute, platform: promptPlatform, promptTimestamp: restoredPromptTimestamp, promptHistoryMessages, sectionsMessage, shouldPromptAgent, turnContexts, userContentParts: promptUserContentParts } = await assemblePrompt({
|
|
11359
11571
|
activeMcpCatalogs: wiring.activeMcpCatalogs,
|
|
11360
11572
|
promptMode: behavior.promptMode,
|
|
11361
11573
|
currentActor: actor,
|
|
@@ -11413,7 +11625,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11413
11625
|
pendingMessages,
|
|
11414
11626
|
mode,
|
|
11415
11627
|
piMessages: messages,
|
|
11416
|
-
requestOverheadTokens: estimateRequestOverheadTokens(
|
|
11628
|
+
requestOverheadTokens: estimateRequestOverheadTokens(baseInstructions, agent.state.tools, activeModelId),
|
|
11417
11629
|
...pairPendingRuntimeContext && pendingMessages ? { runtimeContextMessages: [...messages, ...pendingMessages.map((entry) => entry.message)] } : void 0,
|
|
11418
11630
|
signal: hookSignal,
|
|
11419
11631
|
turnStartMessageIndex: runResume.turnStartMessageIndex
|
|
@@ -11569,7 +11781,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11569
11781
|
if (decision === "allow") return;
|
|
11570
11782
|
if (decision === "wrap_up") {
|
|
11571
11783
|
runResume.markTurnLimitWrappedUp();
|
|
11572
|
-
logWarn("agent.turn.limit.
|
|
11784
|
+
logWarn("agent.turn.limit.wrapped_up", {
|
|
11573
11785
|
"app.ai.cost.total_usd": turnCostUsd,
|
|
11574
11786
|
"app.ai.tool_call_count": toolCallCount
|
|
11575
11787
|
});
|
|
@@ -11645,6 +11857,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
11645
11857
|
runResume.setTurnStartMessageIndex(existingSessionRecord.turnStartMessageIndex);
|
|
11646
11858
|
runResume.adoptCommittedBoundary(currentAgentMessages());
|
|
11647
11859
|
} else if (promptHistoryMessages.length > 0) setAgentHistory(promptHistoryMessages);
|
|
11860
|
+
if (sectionsMessage) setAgentHistory([...currentAgentMessages(), sectionsMessage]);
|
|
11648
11861
|
runResume.setBeforeMessageCount(currentAgentMessages().length);
|
|
11649
11862
|
if (shouldPromptAgent) runResume.setTurnStartMessageIndex(currentAgentMessages().length);
|
|
11650
11863
|
const authPauseOutcome = await withSpan(`invoke_agent ${botConfig.userName}`, "gen_ai.invoke_agent", spanContext, async (setInvokeAgentSpanAttributes) => {
|
|
@@ -11983,7 +12196,7 @@ function createAgentRunner(execute, options) {
|
|
|
11983
12196
|
}
|
|
11984
12197
|
};
|
|
11985
12198
|
const loadStoredAttachments = async (attachments) => {
|
|
11986
|
-
const { loadInputAttachments } = await import("./model-input-
|
|
12199
|
+
const { loadInputAttachments } = await import("./model-input-BHXfA29g.js").then((n) => n.r);
|
|
11987
12200
|
const storage = nextRun.environment?.attachmentStorage;
|
|
11988
12201
|
if (!storage) throw new Error("Attachment storage is unavailable.");
|
|
11989
12202
|
return await loadInputAttachments({
|
|
@@ -12007,4 +12220,4 @@ function createAgentRunner(execute, options) {
|
|
|
12007
12220
|
return await execute(nextRun, streamFn);
|
|
12008
12221
|
} };
|
|
12009
12222
|
}
|
|
12010
|
-
export {
|
|
12223
|
+
export { RetryableDeliveryError as A, parseSlackReviewItemClick as C, AttachmentDownloadError as D, parseSlackUserInputSubmission as E, toolInvocationDestination as M, shouldEmitDevAgentTrace as N, readAttachmentContent as O, buildSlackReviewItemModal as S, safeLinkUrl as T, createSlackReviewItemShow as _, buildAuthPauseResponse as a, findSlackThreadOwnerId as b, createClientMetadata as c, publicArtifactHeaders as d, readPublicArtifact as f, scheduledAutomationRunAttributes as g, logScheduledAutomationRunSkipped as h, measureTurnCompactionWait as i, actorFromRun as j, previewOriginBelongsTo as k, readMcpClientInformation as l, resolveDestinationVisibility as m, executeAgentRun as n, finalizeMcpAuthorization as o, unpublishedArtifactHeaders as p, processBackgroundCompaction as r, getMcpOAuthCallbackPath as s, createAgentRunner as t, latestProgressStatus as u, resolveSlackReviewItemCardConversationId as v, parseSlackReviewItemFormTarget as w, SLACK_REVIEW_ITEM_VIEW_ID as x, syncReviewItemSlackCards as y };
|