@sentry/junior 0.299.0 → 0.301.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-AgCNqqsG.js → adapter-CNjGEJO9.js} +5 -4
- package/dist/{admin-1VwEXztm.js → admin-CRJHvCGg.js} +2 -2
- package/dist/{agent-runner-Ciet8_nn.js → agent-runner-H4YhvNBj.js} +514 -270
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +6 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +327 -61
- package/dist/{app--ky-Eu33.d.ts → app-HDZglaIu.d.ts} +14 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +60 -220
- package/dist/{automation-M3RFJUBf.js → automation-Cva5ZOwW.js} +2 -2
- package/dist/{background-compaction-queue-CnimvRdk.js → background-compaction-queue-CNrZ3QcU.js} +8 -4
- package/dist/{briefs-CwzvgdCa.js → briefs-x6Mzwxmg.js} +3 -3
- package/dist/{catalog-runtime-DaBaHY7u.js → catalog-runtime-BEY6EGRi.js} +1 -1
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +5 -5
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +4 -4
- package/dist/{config-CAXIpWQb.js → config-CmjhyqgB.js} +39 -8
- package/dist/{connections-Dy0hPdUq.js → connections-CfIRm0xv.js} +6 -6
- package/dist/{continue-in-slack-DIOjFj76.js → continue-in-slack-DPoABVkB.js} +6 -6
- package/dist/{conversation-fCWD9Az3.js → conversation-BNXfq6Lb.js} +30 -9
- package/dist/{conversation-feed-BPK8vkkZ.js → conversation-feed-CfpyFMHP.js} +23 -2
- package/dist/{conversation-privacy-DUgtRkf8.js → conversation-privacy-0CM0V2qK.js} +1 -1
- package/dist/{conversation-turn-DkJB6yMF.js → conversation-turn-C0sxyvS-.js} +17 -17
- package/dist/{credential-sync-RX24Y8aY.js → credential-sync-tEMKZ_8M.js} +15 -15
- package/dist/{db-B07FtU9g.d.ts → db-BdUHQhrC.d.ts} +1 -1
- package/dist/{db-COYOGzYS.js → db-Czra10QW.js} +13 -8
- package/dist/{executor-BWmAgSyi.js → executor-D_023K0H.js} +9 -4
- package/dist/instrumentation.js +14 -5
- package/dist/{lineage-D-5jm_oj.js → lineage-DmMIE0VL.js} +2 -2
- package/dist/{logging-DPLEa8Bn.js → logging-DcjLDDqi.js} +1 -1
- package/dist/{message-BIHR1yRk.js → message-C0JY9RJP.js} +8 -8
- package/dist/{model-input-BPZYH8Nd.js → model-input-CBp-p24N.js} +4 -4
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +4 -4
- package/dist/{oauth-callback-server-R7qvSzFG.js → oauth-callback-server-BRq9QNhU.js} +2 -2
- package/dist/{plugins-CBW2Prb_.js → plugins-BBX07Jzt.js} +1 -1
- package/dist/{projection-DEdP1q6f.js → projection-CQNDOi82.js} +911 -671
- package/dist/{prompt-4M98h_tC.js → prompt-DLUB5m72.js} +4 -4
- package/dist/{registry-BTKmKM-r.js → registry-Dj377ADs.js} +2 -2
- package/dist/{resolve-B8hXNVZ3.js → resolve-DJkh9Fky.js} +3 -3
- package/dist/{result-g-XAaOj6.js → result-C8iIpDl1.js} +9 -9
- package/dist/{runner-BlPSA5A8.js → runner-DZqrOy8C.js} +9 -9
- package/dist/{sandbox-egress-signals-Pai-MzEY.js → sandbox-egress-signals-CGwH86S9.js} +1 -1
- package/dist/{schema-DbuWR-DN.d.ts → schema-CdZFn7Qd.d.ts} +248 -6
- package/dist/{schema-BNnY_trV.js → schema-DyHXiQKI.js} +28 -16
- package/dist/{service-account-BYGZ08DQ.js → service-account-D6jGR4a1.js} +3 -3
- package/dist/{service-account-9OLNQMyz.js → service-account-suY004dx.js} +4 -4
- package/dist/{session-stop-2XJrcNCy.js → session-stop-BLmfFI3d.js} +121 -46
- package/dist/{skills-DpBQoeHV.js → skills-CmNG0dHb.js} +2 -2
- package/dist/{slack-conversation-unfurl-BcDIWo67.js → slack-conversation-unfurl-Bty-DlHe.js} +7 -7
- package/dist/{spawn-09GssFod.js → spawn-CNjkpXpk.js} +6 -6
- package/dist/{state-Cufq0_rH.js → state-CEbZuZD6.js} +2 -2
- package/dist/{statuses-B8mUfghF.js → statuses-Hn-HsOph.js} +86 -2
- package/dist/{stop-U7iUrR1g.js → stop-Bjy2-K4H.js} +967 -93
- package/dist/{store-BHiaHCQu.js → store-DmV4CoNr.js} +5 -5
- package/dist/{store-CSgUTMdv.js → store-Epv6t4vV.js} +9 -9
- package/dist/{task-queue-bMNq0clp.js → task-queue-AhG1tSXR.js} +3 -3
- package/dist/{task-runner-B__rxwxU.js → task-runner-BMxZI3o7.js} +8 -8
- package/dist/{thread-context-d0ceWbVT.js → thread-context-CXLnbg7g.js} +8 -8
- package/dist/{turn-session-routing-BVZHBFCF.js → turn-session-routing-BD3-jJl7.js} +5 -5
- package/dist/{turn-user-message-BEw7acTP.js → turn-user-message-DsUZi9gn.js} +3 -3
- package/dist/{users-BK3dbxZL.js → users-BxvYclQg.js} +3 -3
- package/dist/{validation-BDVJjO2E.js → validation-DOz8X9BU.js} +1 -1
- package/dist/{version-DQgZoQ3D.js → version-CGMRmMPK.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-CAWfFo29.js → viewer-H3EsMWtJ.js} +16 -114
- package/dist/{warmup-9ySPacF9.js → warmup-CdU5hR49.js} +51 -27
- package/dist/{worker-D8jJO-WO.js → worker-ClphajjD.js} +24 -20
- package/migrations/0107_attachment_deferred_download.sql +2 -0
- package/migrations/meta/0107_snapshot.json +4617 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +10 -8
- package/dist/media-BAHvgkok.js +0 -85
|
@@ -1,36 +1,35 @@
|
|
|
1
1
|
import { g as withActiveSpan, h as startSpan, i as getActiveSpan, m as startInactiveSpan } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { $ as loadTurnCheckpoint, $a as
|
|
3
|
-
import { A as
|
|
4
|
-
import { C as summarizeMessageText, E as withSpan, G as isRecord$4, S as setTags, T as withLogContext, V as runWithLogAttributes, W as normalizeIdentityEmail, _ 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, o as getActiveTraceContext, p as logException, q as toOptionalString, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-
|
|
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-
|
|
2
|
+
import { $ as loadTurnCheckpoint, $a as workspaceRepoCheckoutPath, $i as setWorkspaceSnapshotBuild, $r as EVERYONE_ASSIGNEE, $t as TurnSliceLimitExceededError, Aa as updateSlackMessage, An as isStandaloneRuntimeContextMessage, B as getAgentContextInputLimitTokens, Ba as isWorkspaceSnapshotNotReadyError, Bn as SCRIPT_TOOLS_SECTION_TAG, Br as updateReviewItemContent, Ca as getSlackMessagePermalink, Cn as getTerminalAssistantMessages, Cs as piMessageFromHistoryItem, Da as postSlackMessage, En as hasTurnInput, Fa as isAlreadyExistsError, Fi as getDashboardTaskLink, Fn as retainRuntimeTurnContext, G as AuthPausePersistenceError, Ga as createSandboxEgressCredentialToken, Gi as getWorkspaceByName, Gn as readParentAgentTask, H as PluginCredentialFailureError, Ha as clearSandboxEgressSignals, Hi as createWorkspace, Hn as TURN_CONTEXT_TAG, Ia as throwSandboxOperationError, In as stripRuntimeTurnContext, J as abandonReplacedPendingAuth, Ja as buildSandboxEgressNetworkPolicy, Ji as updateWorkspace, Jo as getFilePermalink, Jr as requireReviewItemAssignees, K as AuthorizationFlowDisabledError, Ki as listWorkspaces, Ko as SlackActionError, L as calculateContextCompactionTargetTokens, La as wrapSandboxSetupError, Ln as trimTrailingAssistantMessages, Mn as isToolResultMessage, Mr as getOpenReviewItemByDedupeKey, Ni as getDashboardReviewItemLink, Nn as latestTurnContextSection, Nr as getReviewItem, On as isAssistantMessage, Pa as isAbortError, Pn as normalizeToolNameFromResult, Pr as insertReviewItem, Q as continuableMessages, Qa as tryWorkspaceRepoCheckoutPath, Qi as setWorkspaceSnapshot, Qn as findLegacyWebActorUserId, Qt as TurnBudgetExceededError, R as getAgentBackgroundCompactionMarkTokens, Ra as WorkspaceSnapshotNotReadyError, Rn as CAPABILITY_SECTION_TAG, Rr as searchReviewItems, Sa as deleteSlackMessage, Sn as getPiMessageRole, Ss as historyItemFromPiMessage, T as resolveTaskTitle, Ts as getConfigDefaults, U as createPluginAuthOrchestration, Ua as consumeSandboxEgressAuthRequiredSignal, Ui as deleteWorkspace, Uo as readSlackAttachmentSource, Ur as canAgentChangeReviewItem, V as createPluginEgress, Va as workspaceSnapshotNotReadyUserMessage, Vi as renderToolResultNudge, Vo as matchSlackAttachments, Vr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, W as authorizationId, Wa as consumeSandboxEgressPermissionDeniedSignal, Wi as getWorkspace, Wr as canReadReviewItem, Xi as invalidateReadySnapshot, Xo as getSlackClient, Xt as GATED_TURN_LIMIT_WRAP_UP_MESSAGE, Y as canReusePendingAuthLink, Ya as resolveSandboxCommandEnvironment, Yi as WorkspaceValidationError, Yr as requireReviewItemLinks, Za as SANDBOX_RUNTIME, Zi as loadSnapshotsForProfile, Zn as createUserTokenStore, Zo as isConversationScopedChannel, Zt as TURN_LIMIT_WRAP_UP_MESSAGE, _a as slackMention, _i as findMatchingWatches, _n as CODE_MODE_CALL_STATUS_TEXT, _s as credentialAuditAttributes, ai as resolveChannelCapabilities, an as isAnswerToolName, ao as SANDBOX_COMMAND_PATH, ar as createPluginHookRunner, c as recordAgentsInstructionsUpdated, ca as formatProviderLabel, ci as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, cn as replyTextSchema, co as SANDBOX_SKILLS_ROOT, dn as sanitizeAssistantText, do as sandboxSkillFile, ea as create, ei as activeParticipantUserIds, en as TurnToolCallLimitExceededError, eo as ToolInputError, er as getOAuthAccountProviders, es as normalizeSlackConversationId, f as recordAuthorizationRequested, fi as cancelWatch, fn as NO_REPLY_TOOL_NAME, fo as sandboxSkillPathResolution, fr as getPlugins, g as recordToolExecutionStarted, gi as deliverWatch, gn as CODEMODE_TOOL_NAME, ha as normalizeSlackReplyMarkdown, hi as createWatch, hn as readNoReply, ho as runNonInteractiveCommand, i as loadConversationProjection, ia as getSandboxProvider, in as REPLY_TOOL_NAME, is as sleep, ja as uploadFilesToConversation, jn as isToolResultError, jr as dismissOpenReviewItems, ki as getDashboardConversationLink, kn as isContinuablePiBoundary, kr as closeReviewItem, l as recordAttachmentsDelivered, li as RESOURCE_WATCH_TOOL_SOURCE, ln as decideReply, lo as SANDBOX_WORKSPACE_ROOT, ls as saveObjectAnnotations, m as recordMcpProviderConnected, mi as createTimerWatch, mn as isLegacyNoReplyMarker, mo as buildNonInteractiveShellScript, ms as resolveUserTimezone, na as isStale, ni as resolveAssignee, nn as createTurnLimitGate, no as PluginToolDeniedError, nt as saveTurnCheckpoint, oi as getSlackToolContext, on as readTurnAnswer, oo as SANDBOX_DATA_ROOT, p as recordGuardianActionReviewed, pa as escapeSlackMrkdwnText, pn as findLegacyNoReplyMarker, po as buildCommandScript, ps as defaultTimezone, q as AuthorizationPauseError, qo as downloadPrivateSlackFile, qr as readReviewItemAgentScope, r as loadConnectedMcpProviders, ra as ensureDockerDaemon, ri as resolveAssignees, rn as isTurnExecutionLimitExceededError, rs as withSlackRetries, sa as deliverOAuthAuthorization, si as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, sn as remindMissingAnswer, so as SANDBOX_REPOS_ROOT, ss as AttachmentSourceUnavailableError, ta as hash, ti as automationCreatorUserId, to as isToolInputError, ua as resolveBaseUrl, ui as STOP_WATCHING_TOOL_NAME, un as getAssistantReplyText, uo as sandboxSkillDir, ur as getPluginTools, us as createPluginAnnotations, vi as getWatch, vn as REPORT_BLOCKED_TOOL_NAME, vo as canAccessConversation, vs as credentialAuditSource, w as fallbackShortTitle, wa as openSlackDirectMessage, wn as getUserMessageInstructionText, ws as projectConversationEvents, xa as addReactionToMessage, xn as extractAssistantText, xo as readConversationAccessFromSql, yi as listWatches, yn as readBlockedReport, z as getAgentContextCompactionTriggerTokens, za as getWorkspaceSnapshotNotReadyError, zn as REQUEST_CONTEXT_SECTION_TAG } from "./projection-CQNDOi82.js";
|
|
3
|
+
import { A as estimateRequestOverheadTokens, B as ProviderError, D as resolveGatewayModel, F as isCompactionSummaryText, H as createProviderError, J as getGatewayApiKey, K as isProviderRefusal, L as unwrapCurrentInstruction, M as textCharsForTokens, N as COMPACTION_SUMMARY_PREFIX, O as requestPrefixAttributes, P as hasCompactedConversationContext, R as escapeXml, U as findProviderError, V as createAssistantProviderError, W as getProviderErrorAttributes, X as bufferBody, Y as resolveGatewayCredential, _ as TURN_REASONING_LEVELS, b as GEN_AI_PROVIDER_NAME, j as estimateTextTokens, k as estimateMessagesTokens, n as botConfig, q as isProviderRetryError, v as toPiReasoningLevel, x as GEN_AI_SERVER_ADDRESS, y as normalizeSlackEmojiName, z as escapeXmlText } from "./config-CmjhyqgB.js";
|
|
4
|
+
import { C as summarizeMessageText, E as withSpan, G as isRecord$4, S as setTags, T as withLogContext, V as runWithLogAttributes, W as normalizeIdentityEmail, _ 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, o as getActiveTraceContext, p as logException, q as toOptionalString, u as getTracePropagationHeaders, v as serializeGenAiAttribute, x as setSpanStatus } from "./logging-DcjLDDqi.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-0CM0V2qK.js";
|
|
6
6
|
import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, n as createSlackActor, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
|
|
7
|
-
import { $ as resolveRootConversationId, C as isPersonInput, E as turnBehavior, J as addAgentTurnUsage, N as resolveActorIdentityId, Q as hasAgentTurnUsage, Y as agentTurnCostUsd, a as getConversationStore, at as parseDestination, c as hasAnnotationKey, g as setArchivedAt, h as readConversationTrees, i as getConversationMessageSearchStore, j as SYSTEM_IDENTITY_ID, l as treeHasAnnotationKey, m as conversationDescendants, nt as nextDetailVersion, o as getDb, p as conversationAncestors, r as getConversationEventStore, rt as touchConversationDetail, s as getSqlExecutor, st as sameDestination, tt as conversationDetailTouch, w as isTopLevelKind } from "./db-
|
|
8
|
-
import { A as juniorAttachments, F as juniorArtifacts, M as juniorIdentities, N as juniorUsers, P as juniorDestinations, _ as juniorConversationReadPositions, b as juniorConversationBriefs, c as juniorReviewItemSlackCards, f as juniorAutomations, j as juniorConversations, k as juniorAttachmentUploads, p as juniorStats, u as juniorAutomationRuns, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-
|
|
7
|
+
import { $ as resolveRootConversationId, C as isPersonInput, E as turnBehavior, J as addAgentTurnUsage, N as resolveActorIdentityId, Q as hasAgentTurnUsage, Y as agentTurnCostUsd, a as getConversationStore, at as parseDestination, c as hasAnnotationKey, g as setArchivedAt, h as readConversationTrees, i as getConversationMessageSearchStore, j as SYSTEM_IDENTITY_ID, l as treeHasAnnotationKey, m as conversationDescendants, nt as nextDetailVersion, o as getDb, p as conversationAncestors, r as getConversationEventStore, rt as touchConversationDetail, s as getSqlExecutor, st as sameDestination, tt as conversationDetailTouch, w as isTopLevelKind } from "./db-Czra10QW.js";
|
|
8
|
+
import { A as juniorAttachments, F as juniorArtifacts, M as juniorIdentities, N as juniorUsers, P as juniorDestinations, _ as juniorConversationReadPositions, b as juniorConversationBriefs, c as juniorReviewItemSlackCards, f as juniorAutomations, j as juniorConversations, k as juniorAttachmentUploads, p as juniorStats, u as juniorAutomationRuns, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-D_023K0H.js";
|
|
9
9
|
import { d as contextProvenance, f as instructionActors, m as sameActorIdentity, p as instructionProvenanceFor, t as KNOWN_CONVERSATION_EVENT_TYPES } from "./history-IjdmO_r6.js";
|
|
10
|
-
import { c as fenceLock, l as withLock, r as getStateAdapter } from "./adapter-
|
|
10
|
+
import { c as fenceLock, l as withLock, r as getStateAdapter } from "./adapter-CNjGEJO9.js";
|
|
11
11
|
import { a as listReferenceFiles } from "./package-discovery-DJhGdS4c.js";
|
|
12
|
-
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-
|
|
13
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
14
|
-
import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-
|
|
15
|
-
import { l as completeObject, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-
|
|
12
|
+
import { c as fetchWithBoundedOAuthErrorBodies, d as actorLogContext, f as credentialContextForActor, g as credentialUserSubjectId, i as resolvePluginHeaderEnvRefs, l as getOAuthProviderErrorAttributes, s as OAuthProviderError } from "./registry-Dj377ADs.js";
|
|
13
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-BEY6EGRi.js";
|
|
14
|
+
import { a as parseSkillInvocation, n as findSkillByName, r as loadSkillsByName, t as discoverSkills } from "./skills-CmNG0dHb.js";
|
|
15
|
+
import { l as completeObject, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-DLUB5m72.js";
|
|
16
16
|
import { i as getFirstRunAtMs, o as getZonedDateTimeParts, s as isValidTimeZone } from "./schedule-cP0AACm1.js";
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import { a as
|
|
28
|
-
import { a as
|
|
29
|
-
import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-9OLNQMyz.js";
|
|
17
|
+
import { a as readActorIdentityFromSql, f as identityAvatarUrl, h as readUserAvatarUrls, i as readActorIdentity } from "./viewer-H3EsMWtJ.js";
|
|
18
|
+
import { G as MAX_ATTACHMENT_BYTES, M as formatAgentTypes, Q as briefOutcomeStatusSchema, U as removedCardSchema, Z as briefLinkSchema, k as AGENT_TYPES, nt as parseStoredBrief } from "./conversation-BNXfq6Lb.js";
|
|
19
|
+
import { n as readEncryptedState, t as createEncryptedState } from "./state-CEbZuZD6.js";
|
|
20
|
+
import { B as requireSlackChannelMessageScope, G as WORKSPACE_SNAPSHOT_FAILED_EVENT, J as workspaceSnapshotWatch, K as WORKSPACE_SNAPSHOT_READY_EVENT, M as EVENT_WAIT_MS, N as enqueueEventNotification, Q as resolveSlackReplyTarget, R as getEventCatalog, S as addConversationNote, W as slackChannelMessageTrigger, b as isExperimentalFeatureEnabled, d as buildPromptInput, dt as AGENTS_REPLACEMENT_NOTICE, et as resolveEventMentions, f as buildSteeringPiMessage, ft as buildAgentsInstructionsMessage, gt as showsAgentsInstructions, h as loadPromptTurnContext, ht as renderAgentsInstructions, lt as JUNIOR_PERSONALITY, mt as readRepositoryInstructions, pt as findVisibleAgentsInstructions, q as workspaceSnapshotFinishedEvent, u as assemblePrompt, ut as AGENTS_REMOVAL_NOTICE, v as saveUserCustomization } from "./session-stop-BLmfFI3d.js";
|
|
21
|
+
import { $ as AgentDepthLimitError, G as stopChildAgent, I as readLastParentMessageAtMs, N as isParentMessageMeta, S as listOpenAgentInvocations, ct as CHILD_AGENT_RESULTS, et as AgentInvocationLimitError, f as listDescendantAgents, i as createCacheWarmingRecorder, it as AgentNameInUseError, l as readLastUserMessageAtByConversation, lt as PARENT_AGENT_TARGET, nt as AgentMessageQueueFullError, rt as AgentMessageTargetError, st as CHILD_AGENT_KINDS, tt as AgentMessagePausedError, u as listAgentRelatives, ut as agentNameSchema, x as listAgentInvocationsForConversation, y as getLatestAgentInvocationForConversation } from "./warmup-CdU5hR49.js";
|
|
22
|
+
import { T as getTurnRequestDeadline, l as getVercelConversationWorkQueue, n as backgroundCompactionId, o as sendNextWorkspaceSnapshotJob, s as sendWorkspaceSnapshotJob, x as QUEUE_SIGNATURE_MAX_AGE_MS } from "./background-compaction-queue-CNrZ3QcU.js";
|
|
23
|
+
import { R as buildDeterministicTurnId, d as isTurnInputCommitLostError, o as CooperativeTurnYieldError, s as TurnInputCommitLostError } from "./turn-user-message-DsUZi9gn.js";
|
|
24
|
+
import { n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage } from "./store-DmV4CoNr.js";
|
|
25
|
+
import { S as requireValidEventTrigger, _ as registeredEventMatchSchema, b as registeredResourceTypeSchema, d as describeRegisteredEventTrigger, g as hasEventCatalogEntries, h as eventWatchUnavailable, m as eventNamespaceSchema, t as resolveConversationRouting, u as automationEventCatalog, v as registeredEventTriggerProblems, x as requireEventIdentifier, y as registeredEventTypeSchema } from "./turn-session-routing-BD3-jJl7.js";
|
|
26
|
+
import { _ as userCustomizationTextSchema, a as USER_INPUT_NOTE, h as USER_CUSTOMIZATION_MAX_CHARS, i as USER_INPUT_LIMITS, l as normalizeUserInputAnswer, m as isVisionImageMediaType, o as buttonUserInputField, p as detectImageMediaType, r as AGENT_INVOCATION_STATUSES, s as formatUserInputAnswer, u as userInputRequestSchema } from "./statuses-Hn-HsOph.js";
|
|
27
|
+
import { a as setSnapshotSpanAttributes, i as postinstall, n as resolve$1, r as dependencies, s as getSandboxResources } from "./resolve-DJkh9Fky.js";
|
|
28
|
+
import { _ as getMcpProviderErrorAttributes, a as serviceAccountOnly, c as createMcpServiceAccountClientProvider, d as PluginMcpClient, f as McpProviderError, g as getMcpAwareTelemetryMessage, h as getMcpAwareErrorType, i as serviceAccountAllows, l as getMcpServiceAccountCredentials, m as McpToolError, p as McpServiceAccountRequiredError, u as McpAuthorizationRequiredError, v as toMcpProviderError } from "./service-account-suY004dx.js";
|
|
30
29
|
import { m as apiErrorSchema, p as webMessageId, s as sumUtcHoursIntoSixHours } from "./reporting-window-DopzcOHh.js";
|
|
31
|
-
import { A as eventAutomationTriggerSchema, D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, H as automationTaskSchema, I as scheduleIntentFromTool, L as toolScheduleIntentSchema, O as taskOutcomeInputSchema, P as ScheduleIntentError, R as weekdaySchema, T as automationContextToolSchema, U as automationTaskText, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, l as automationListQuerySchema, z as automationSkillNameSchema } from "./automation-
|
|
32
|
-
import { C as readAutomationExecutionStatusHours, E as readAutomationRuns, G as deleteEventAutomation, I as parseScheduledAutomationRow, J as listDeletedEventAutomationsCreatedBy, L as readScheduledAutomation, N as createScheduledAutomation, P as deleteScheduledAutomation, R as saveScheduledAutomation, S as readAutomationExecutionStatusDays, T as readAutomationExecutions, W as createEventAutomation, X as saveEventAutomation, Y as parseEventAutomationRow, Z as setEventAutomationStatus, c as getDispatchRecord, et as automationDefinition, it as sameDefinitionValue, nt as listAutomationVersions, o as getDispatchIdForConversation, ot as automationRevision, q as getEventAutomation, rt as readAutomationVersion, s as getDispatchInputMessageId, st as requireAutomationRevision, w as readAutomationExecutionSummaries, x as readAutomationExecutionByConversationId, y as emptyAutomationRunWindows } from "./store-
|
|
33
|
-
import { a as runWithSlackInstallation, c as joinPublicChannelForRead, h as listThreadReplies, i as searchSlackUsers, m as listChannelMessages, n as lookupSlackUserByEmail, p as joinPublicChannel, r as lookupSlackUserProfile, s as checkSlackChannelReadAccess } from "./users-
|
|
30
|
+
import { A as eventAutomationTriggerSchema, D as automationTitleSchema, E as automationInstructionToolSchema, F as compileScheduleIntent, H as automationTaskSchema, I as scheduleIntentFromTool, L as toolScheduleIntentSchema, O as taskOutcomeInputSchema, P as ScheduleIntentError, R as weekdaySchema, T as automationContextToolSchema, U as automationTaskText, V as automationTaskDescription, j as SCHEDULED_AUTOMATION_SYSTEM_ACTOR, l as automationListQuerySchema, z as automationSkillNameSchema } from "./automation-Cva5ZOwW.js";
|
|
31
|
+
import { C as readAutomationExecutionStatusHours, E as readAutomationRuns, G as deleteEventAutomation, I as parseScheduledAutomationRow, J as listDeletedEventAutomationsCreatedBy, L as readScheduledAutomation, N as createScheduledAutomation, P as deleteScheduledAutomation, R as saveScheduledAutomation, S as readAutomationExecutionStatusDays, T as readAutomationExecutions, W as createEventAutomation, X as saveEventAutomation, Y as parseEventAutomationRow, Z as setEventAutomationStatus, c as getDispatchRecord, et as automationDefinition, it as sameDefinitionValue, nt as listAutomationVersions, o as getDispatchIdForConversation, ot as automationRevision, q as getEventAutomation, rt as readAutomationVersion, s as getDispatchInputMessageId, st as requireAutomationRevision, w as readAutomationExecutionSummaries, x as readAutomationExecutionByConversationId, y as emptyAutomationRunWindows } from "./store-Epv6t4vV.js";
|
|
32
|
+
import { a as runWithSlackInstallation, c as joinPublicChannelForRead, h as listThreadReplies, i as searchSlackUsers, m as listChannelMessages, n as lookupSlackUserByEmail, p as joinPublicChannel, r as lookupSlackUserProfile, s as checkSlackChannelReadAccess } from "./users-BxvYclQg.js";
|
|
34
33
|
import { n as privateTraceResultAttributes } from "./private-trace-result-CE7_lEdq.js";
|
|
35
34
|
import * as z from "zod";
|
|
36
35
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
@@ -207,6 +206,36 @@ var SkillSandbox = class {
|
|
|
207
206
|
throw new Error("No active skill is loaded. Call loadSkill first or pass skill_name explicitly.");
|
|
208
207
|
}
|
|
209
208
|
};
|
|
209
|
+
// src/chat/pi/agent-history.ts
|
|
210
|
+
function isSystemMessage(message) {
|
|
211
|
+
return message.role === "system";
|
|
212
|
+
}
|
|
213
|
+
/** Return Junior history: the messages without Pi's system messages. */
|
|
214
|
+
function readAgentHistory(messages) {
|
|
215
|
+
return messages.filter((message) => !isSystemMessage(message));
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Return the message list that replaces `current` with `history`. The leading
|
|
219
|
+
* system message of `current` stays first. System messages in `history` are
|
|
220
|
+
* dropped.
|
|
221
|
+
*/
|
|
222
|
+
function writeAgentHistory(current, history) {
|
|
223
|
+
const leading = current[0];
|
|
224
|
+
const messages = readAgentHistory(history);
|
|
225
|
+
return leading && isSystemMessage(leading) ? [leading, ...messages] : messages;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Give the stream path Junior's own system prompt and tools, with Junior
|
|
229
|
+
* history as the messages. The traced stream and cache warming then read the
|
|
230
|
+
* same request on every Pi version, without Pi's system messages.
|
|
231
|
+
*/
|
|
232
|
+
function withAgentRequest(base, request) {
|
|
233
|
+
return (model, context, options) => base(model, {
|
|
234
|
+
systemPrompt: request.systemPrompt,
|
|
235
|
+
messages: readAgentHistory(context.messages),
|
|
236
|
+
tools: request.tools
|
|
237
|
+
}, options);
|
|
238
|
+
}
|
|
210
239
|
// src/chat/agent/repository-context.ts
|
|
211
240
|
function findRestoredInstructions(messages, provenance) {
|
|
212
241
|
const restoredContext = messages?.map((message, index) => ({
|
|
@@ -222,15 +251,19 @@ function createRepositoryInstructionsContext(options) {
|
|
|
222
251
|
content: options.promptContextContentParts
|
|
223
252
|
}]) : findRestoredInstructions(options.restoredMessages, options.restoredProvenance);
|
|
224
253
|
return {
|
|
225
|
-
/**
|
|
226
|
-
|
|
227
|
-
|
|
254
|
+
/**
|
|
255
|
+
* Re-read AGENTS.md and append a context message to `messages` when it
|
|
256
|
+
* changed. Returns whether it set new messages.
|
|
257
|
+
*/
|
|
258
|
+
async applyUpdate(messages) {
|
|
259
|
+
if (!options.hasSandbox()) return false;
|
|
228
260
|
return await withSpan("agent.repository_instructions.refresh", "agent.repository_instructions.refresh", {}, async (setSpanAttributes) => {
|
|
229
261
|
const instructions = await options.capture();
|
|
230
262
|
const outcome = refreshOutcome(instructions);
|
|
231
263
|
setSpanAttributes({ "app.repository_instructions.outcome": outcome });
|
|
232
|
-
if (outcome === "unchanged" || outcome === "none") return;
|
|
233
|
-
|
|
264
|
+
if (outcome === "unchanged" || outcome === "none") return false;
|
|
265
|
+
await appendUpdate(instructions, messages);
|
|
266
|
+
return true;
|
|
234
267
|
});
|
|
235
268
|
} };
|
|
236
269
|
function refreshOutcome(instructions) {
|
|
@@ -239,12 +272,12 @@ async applyUpdate(currentContext) {
|
|
|
239
272
|
if (!instructionsVisible) return "added";
|
|
240
273
|
return showsAgentsInstructions(visibleInstructions, instructions) ? "unchanged" : "updated";
|
|
241
274
|
}
|
|
242
|
-
async function appendUpdate(instructions,
|
|
275
|
+
async function appendUpdate(instructions, currentMessages) {
|
|
243
276
|
const message = instructions ? buildAgentsInstructionsMessage({
|
|
244
277
|
directory: instructions.directory,
|
|
245
278
|
text: visibleInstructions?.active === true ? `${AGENTS_REPLACEMENT_NOTICE}\n\n${instructions.text}` : instructions.text
|
|
246
279
|
}) : buildAgentsInstructionsMessage({ text: AGENTS_REMOVAL_NOTICE });
|
|
247
|
-
const messages = [...
|
|
280
|
+
const messages = [...currentMessages, message];
|
|
248
281
|
options.setMessages(messages);
|
|
249
282
|
await options.commit(messages);
|
|
250
283
|
visibleInstructions = instructions ? {
|
|
@@ -253,10 +286,6 @@ async applyUpdate(currentContext) {
|
|
|
253
286
|
text: instructions.text
|
|
254
287
|
} : { active: false };
|
|
255
288
|
await options.onTransition?.(instructions);
|
|
256
|
-
return { context: {
|
|
257
|
-
...currentContext,
|
|
258
|
-
messages
|
|
259
|
-
} };
|
|
260
289
|
}
|
|
261
290
|
}
|
|
262
291
|
// src/chat/pi/traced-stream.ts
|
|
@@ -1388,63 +1417,6 @@ async function prepareWorkspaceSnapshot(params) {
|
|
|
1388
1417
|
});
|
|
1389
1418
|
if (result.exitCode !== 0) throw new Error(`Workspace setup failed: ${workspaceSetupFailureDetail(result)}`);
|
|
1390
1419
|
}
|
|
1391
|
-
// src/chat/events/people.ts
|
|
1392
|
-
const linkedSlackIdentity$1 = alias(juniorIdentities, "event_people_slack");
|
|
1393
|
-
function personKey(person) {
|
|
1394
|
-
return "email" in person ? `email:${normalizeIdentityEmail(person.email)}` : `${person.provider}:${person.handle.toLowerCase()}`;
|
|
1395
|
-
}
|
|
1396
|
-
function personCondition(person) {
|
|
1397
|
-
if ("email" in person) return and(eq(juniorIdentities.emailVerified, true), eq(juniorIdentities.emailNormalized, normalizeIdentityEmail(person.email)));
|
|
1398
|
-
return and(eq(juniorIdentities.provider, person.provider), sql`lower(${juniorIdentities.handle}) = lower(${person.handle})`);
|
|
1399
|
-
}
|
|
1400
|
-
/**
|
|
1401
|
-
* Resolve the Event people and the Event doer to Slack mentions through
|
|
1402
|
-
* linked user identities in one Slack workspace, with one query.
|
|
1403
|
-
*
|
|
1404
|
-
* A person resolves only when exactly one linked Slack user in that workspace
|
|
1405
|
-
* matches. Core drops unlinked and ambiguous people, so a provider value never
|
|
1406
|
-
* guesses a mention.
|
|
1407
|
-
*/
|
|
1408
|
-
async function resolveEventMentions(event, slackTeamId) {
|
|
1409
|
-
const people = event.people ?? [];
|
|
1410
|
-
const lookup = event.doneBy ? [...people, event.doneBy] : people;
|
|
1411
|
-
if (lookup.length === 0) return { people: [] };
|
|
1412
|
-
const rows = await getSqlExecutor().db().select({
|
|
1413
|
-
emailNormalized: juniorIdentities.emailNormalized,
|
|
1414
|
-
emailVerified: juniorIdentities.emailVerified,
|
|
1415
|
-
handle: juniorIdentities.handle,
|
|
1416
|
-
provider: juniorIdentities.provider,
|
|
1417
|
-
slackUserId: linkedSlackIdentity$1.providerSubjectId
|
|
1418
|
-
}).from(juniorIdentities).innerJoin(linkedSlackIdentity$1, and(eq(linkedSlackIdentity$1.userId, juniorIdentities.userId), eq(linkedSlackIdentity$1.kind, "user"), eq(linkedSlackIdentity$1.provider, "slack"), eq(linkedSlackIdentity$1.providerTenantId, slackTeamId))).where(and(eq(juniorIdentities.kind, "user"), or(...lookup.map(personCondition))));
|
|
1419
|
-
const slackUsersByKey = /* @__PURE__ */ new Map();
|
|
1420
|
-
const add = (key, slackUserId) => {
|
|
1421
|
-
const users = slackUsersByKey.get(key) ?? /* @__PURE__ */ new Set();
|
|
1422
|
-
users.add(slackUserId);
|
|
1423
|
-
slackUsersByKey.set(key, users);
|
|
1424
|
-
};
|
|
1425
|
-
for (const row of rows) {
|
|
1426
|
-
if (row.handle) add(`${row.provider}:${row.handle.toLowerCase()}`, row.slackUserId);
|
|
1427
|
-
if (row.emailVerified && row.emailNormalized) add(`email:${row.emailNormalized}`, row.slackUserId);
|
|
1428
|
-
}
|
|
1429
|
-
const mentionOf = (person) => {
|
|
1430
|
-
const users = slackUsersByKey.get(personKey(person));
|
|
1431
|
-
return users?.size === 1 ? slackMention([...users][0]) : void 0;
|
|
1432
|
-
};
|
|
1433
|
-
const mentions = [];
|
|
1434
|
-
for (const person of people) {
|
|
1435
|
-
const mention = mentionOf(person);
|
|
1436
|
-
if (mention && !mentions.includes(mention)) mentions.push(mention);
|
|
1437
|
-
}
|
|
1438
|
-
const doneByMention = event.doneBy ? mentionOf(event.doneBy) : void 0;
|
|
1439
|
-
if (!doneByMention || !event.doneBy) return { people: mentions };
|
|
1440
|
-
return {
|
|
1441
|
-
people: mentions,
|
|
1442
|
-
doneBy: {
|
|
1443
|
-
mention: doneByMention,
|
|
1444
|
-
..."handle" in event.doneBy ? { handle: event.doneBy.handle } : void 0
|
|
1445
|
-
}
|
|
1446
|
-
};
|
|
1447
|
-
}
|
|
1448
1420
|
// src/chat/events/ingest.ts
|
|
1449
1421
|
/** Match a normalized event and enqueue notifications into conversations. */
|
|
1450
1422
|
async function ingestEvent(input, options) {
|
|
@@ -3038,7 +3010,7 @@ function createEditFileTool() {
|
|
|
3038
3010
|
openWorldHint: false,
|
|
3039
3011
|
readOnlyHint: false
|
|
3040
3012
|
},
|
|
3041
|
-
description: "Edit one sandbox workspace file with exact text replacements. Use for precise changes to existing files; prefer this over writeFile for targeted changes.
|
|
3013
|
+
description: "Edit one sandbox workspace file with exact text replacements. Use for precise changes to existing files; prefer this over writeFile for targeted changes. Returns a diff. Multiple changes to the same file: use one edits[] call.",
|
|
3042
3014
|
prepareArguments: prepareEditFileArguments,
|
|
3043
3015
|
executionMode: "sequential",
|
|
3044
3016
|
inputSchema: z.object({
|
|
@@ -4793,10 +4765,10 @@ function createCallMcpToolTool(mcpToolManager) {
|
|
|
4793
4765
|
openWorldHint: true,
|
|
4794
4766
|
readOnlyHint: false
|
|
4795
4767
|
},
|
|
4796
|
-
description: "Call an active MCP tool by exact
|
|
4768
|
+
description: "Call an active MCP tool by its exact name. Use searchMcpTools to discover tool names and schemas; copy required provider fields into arguments. Authorization is handled by the runtime when required.",
|
|
4797
4769
|
inputSchema: z.object({
|
|
4798
4770
|
tool_name: z.string().min(1).describe("Exact MCP tool_name from searchMcpTools."),
|
|
4799
|
-
arguments: z.record(z.string(), z.unknown()).describe("Arguments matching the disclosed MCP tool schema, for example { \"query\": \"...\" } when searchMcpTools shows query is required.").optional(),
|
|
4771
|
+
arguments: z.record(z.string(), z.unknown()).describe("Arguments matching the disclosed MCP tool schema, for example { \"query\": \"...\" } when searchMcpTools shows query is required. Omit only when the discovered tool has no arguments.").optional(),
|
|
4800
4772
|
intent: z.string().min(1).describe("Optional short purpose to show the user if this call needs them to connect their account, for example \"search Notion for the Q3 offsite doc\".").optional()
|
|
4801
4773
|
}).passthrough(),
|
|
4802
4774
|
resolveApprovalMetadata: ({ tool_name }) => {
|
|
@@ -5273,7 +5245,7 @@ const messageAgentOutputSchema = juniorToolOutputSchema.extend({
|
|
|
5273
5245
|
*/
|
|
5274
5246
|
function createMessageAgentTool(messageAgent) {
|
|
5275
5247
|
return zodTool({
|
|
5276
|
-
description: `Send a message to your parent agent or to a child agent that this conversation started. Use it to give an existing child agent more work, an answer, or a correction, and to send your parent agent a finding or a question while you keep working. A message to a child continues its history. If the child is still working, it reads the message at its next step or after its current work. A child replies when it has something to report. Its reply arrives later as a new task in this conversation; do not wait or poll for it.
|
|
5248
|
+
description: `Send a message to your parent agent or to a child agent that this conversation started. Use it to give an existing child agent more work, an answer, or a correction, and to send your parent agent a finding or a question while you keep working. A message to a child continues its history. If the child is still working, it reads the message at its next step or after its current work. A child replies when it has something to report. Its reply arrives later as a new task in this conversation; do not wait or poll for it. Make sure people know what is going on, but post only updates that matter to them. A message to your parent does not end your task. A top-level agent (its conversation is not a child agent, such as a Slack thread) can also message another top-level agent. Both conversations must be public, or both must be private conversations in the same place, such as one private channel or DM. The target runs the message as its own task and sends no result. Use spawnAgent only to start a new child agent.`,
|
|
5277
5249
|
exposure: "modelOnly",
|
|
5278
5250
|
approvalMode: "auto",
|
|
5279
5251
|
annotations: {
|
|
@@ -5283,8 +5255,8 @@ function createMessageAgentTool(messageAgent) {
|
|
|
5283
5255
|
readOnlyHint: false
|
|
5284
5256
|
},
|
|
5285
5257
|
inputSchema: z.object({
|
|
5286
|
-
to: z.string().trim().min(1).describe(`"${PARENT_AGENT_TARGET}" for your parent agent, the name or conversation_id of a child agent from spawnAgent or listAgents, or the conversation_id of another top-level agent`),
|
|
5287
|
-
text: z.string().trim().min(1).max(MESSAGE_AGENT_TEXT_MAX_LENGTH).describe("Message text. Include all context the target needs.")
|
|
5258
|
+
to: z.string().trim().min(1).describe(`"${PARENT_AGENT_TARGET}" for your parent agent, the name or conversation_id of a child agent from spawnAgent or listAgents, or the conversation_id of another top-level agent, such as one from searchConversations or slackThreadRead`),
|
|
5259
|
+
text: z.string().trim().min(1).max(MESSAGE_AGENT_TEXT_MAX_LENGTH).describe("Message text. Include all context the target needs. Text to a child agent is its instruction. Its action review judges the child's actions against that text, so name only actions that your own conversation backs, with the exact target.")
|
|
5288
5260
|
}).strict(),
|
|
5289
5261
|
outputSchema: messageAgentOutputSchema,
|
|
5290
5262
|
execute: async (input, options) => {
|
|
@@ -5324,8 +5296,8 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
|
|
|
5324
5296
|
"Start a new asynchronous child agent. A child agent has its own sandbox and tool budget, runs at the same time as you, and replies when it has something to report. Its kind is a Thread for one discrete work item that people will own and talk to, or a Task for work that you delegate. Use Tasks to run independent work in parallel and to keep long investigations out of your context.",
|
|
5325
5297
|
"Delegate a Task when: the request splits into independent tracks that each need real investigation, such as several repos, services, sources, or items (start every track in the same message); an answer needs reading across many files, logs, or sources and you need the conclusion, not the raw output; a side task does not block your main answer; or you want a second opinion that is not anchored on your analysis (give it the evidence, not your conclusion).",
|
|
5326
5298
|
"Do it yourself instead of a Task when: the work fits in a handful of tool calls; you already know the file, symbol, or value to look up; or the job is one modest task that you would only split into pieces. Each child rebuilds its context and its result arrives in a later turn, so when in doubt, do not spawn a Task.",
|
|
5327
|
-
`
|
|
5328
|
-
|
|
5299
|
+
`Child agent types:\n${formatAgentTypes()}`,
|
|
5300
|
+
"After you delegate, do not do the same work yourself. Make sure people know what is going on, but post only updates that matter to them. Share a Thread's dashboard_url so people can find it.",
|
|
5329
5301
|
"You know nothing about a child's findings until its result arrives: do not predict them, do not wait or poll, and if the user asks before then, give status.",
|
|
5330
5302
|
"Give a child a name when you may send it more work later. To give more work to a child agent that already exists, use messageAgent instead.",
|
|
5331
5303
|
"A child keeps its type and kind when it receives more work through messageAgent.",
|
|
@@ -5340,12 +5312,12 @@ function createSpawnAgentTool(spawnAgent, titleCost) {
|
|
|
5340
5312
|
readOnlyHint: false
|
|
5341
5313
|
},
|
|
5342
5314
|
inputSchema: z.object({
|
|
5343
|
-
task: z.string().trim().min(1).describe("Self-contained brief. Unless fork is true, the child has not seen this thread, so this is its only context. Brief it like a capable peer who just joined: the goal and why it matters; target repos, refs, paths, and URLs; facts you already verified and what you ruled out; constraints, including which remote side effects are allowed (scratch work in its sandbox is always fine); what counts as done; and the shape and length of the result to return. Do the synthesis yourself: name the exact question, files, or change instead of writing 'based on your findings, fix it'. If you cannot write a clear brief, you do not understand the task well enough to delegate it. Summarize thread facts instead of pasting the thread."),
|
|
5315
|
+
task: z.string().trim().min(1).describe("Self-contained brief. Unless fork is true, the child has not seen this thread, so this is its only context. Brief it like a capable peer who just joined: the goal and why it matters; target repos, refs, paths, and URLs; facts you already verified and what you ruled out; constraints, including which remote side effects are allowed (scratch work in its sandbox is always fine); what counts as done; and the shape and length of the result to return. Do the synthesis yourself: name the exact question, files, or change instead of writing 'based on your findings, fix it'. If you cannot write a clear brief, you do not understand the task well enough to delegate it. Summarize thread facts instead of pasting the thread. When fork is true, the task is a directive: say what to do and what is in or out of scope; do not re-explain the background."),
|
|
5344
5316
|
title: z.string().trim().min(1).max(60).nullable().optional().describe("Optional short display title of the child and its Conversation. Pass one to skip title generation; omit it to generate one from the task."),
|
|
5345
5317
|
name: agentNameSchema.refine((name) => name !== PARENT_AGENT_TARGET, { message: `"${PARENT_AGENT_TARGET}" is reserved` }).nullable().optional().describe("New child-agent name that messageAgent can address, or omit for a one-off agent"),
|
|
5346
|
-
kind: z.enum(CHILD_AGENT_KINDS).nullable().optional().describe("thread: one
|
|
5347
|
-
agent_type: z.enum(AGENT_TYPES).nullable().optional().describe("Child agent type from the list in this tool's description. Omit or pass null for a general-purpose child."),
|
|
5348
|
-
fork: z.boolean().nullable().optional().describe("true: the child
|
|
5318
|
+
kind: z.enum(CHILD_AGENT_KINDS).nullable().optional().describe("thread: one work item about the size of one issue or code change, or long-lived work, that people open, message, follow, and steer. A request to create or start a thread means this kind, not a Slack thread. task (default): background work only you message."),
|
|
5319
|
+
agent_type: z.enum(AGENT_TYPES).nullable().optional().describe("Child agent type from the list in this tool's description. Pick one when it fits. Omit or pass null for a general-purpose child with your tools."),
|
|
5320
|
+
fork: z.boolean().nullable().optional().describe("true: the child gets a copy of this conversation's history, which adds cost and noise. Pass true only when the child needs most of this conversation, such as its discussion and decisions, so that a brief would repeat most of it. Works with any agent_type."),
|
|
5349
5321
|
reasoning_level: z.enum(TURN_REASONING_LEVELS).nullable().optional().describe("Optional reasoning level for this delegated task only")
|
|
5350
5322
|
}).strict(),
|
|
5351
5323
|
outputSchema: spawnAgentOutputSchema,
|
|
@@ -5759,19 +5731,26 @@ const DAY_MS = 864e5;
|
|
|
5759
5731
|
const ATTACHMENT_GC_BATCH_LIMIT = 200;
|
|
5760
5732
|
/** Time that Junior keeps attachment bytes after the file is stored. */
|
|
5761
5733
|
const ATTACHMENT_RETENTION_MS = 30 * DAY_MS;
|
|
5762
|
-
function
|
|
5763
|
-
return createHash("sha256").update(file.data).digest("hex");
|
|
5734
|
+
function attachmentIdentity(file) {
|
|
5735
|
+
if ("data" in file) return file.source ?? { sha256: createHash("sha256").update(file.data).digest("hex") };
|
|
5736
|
+
return file.source;
|
|
5764
5737
|
}
|
|
5765
|
-
/** Stable conversation-owned id for one file
|
|
5738
|
+
/** Stable conversation-owned id for one file and its presentation metadata. */
|
|
5766
5739
|
function attachmentId(args) {
|
|
5767
|
-
const identity = [
|
|
5740
|
+
const identity = "sha256" in args.identity ? [
|
|
5768
5741
|
args.conversationId,
|
|
5769
5742
|
args.storageProvider,
|
|
5770
|
-
args.sha256,
|
|
5743
|
+
args.identity.sha256,
|
|
5771
5744
|
args.filename,
|
|
5772
5745
|
args.contentType
|
|
5746
|
+
] : [
|
|
5747
|
+
args.conversationId,
|
|
5748
|
+
args.storageProvider,
|
|
5749
|
+
args.filename,
|
|
5750
|
+
args.contentType,
|
|
5751
|
+
args.identity.provider,
|
|
5752
|
+
args.identity.id
|
|
5773
5753
|
];
|
|
5774
|
-
if (args.source) identity.push(args.source.provider, args.source.id);
|
|
5775
5754
|
return createHash("sha256").update(identity.join("\0")).digest("hex");
|
|
5776
5755
|
}
|
|
5777
5756
|
/**
|
|
@@ -5784,11 +5763,66 @@ function attachmentId(args) {
|
|
|
5784
5763
|
function attachmentKey(args) {
|
|
5785
5764
|
return `conversations/${args.conversationId}/attachments/${args.attachmentId}/${args.writeId}/${args.filename}`;
|
|
5786
5765
|
}
|
|
5766
|
+
/** A source whose bytes do not match its declared size. A retry cannot fix it. */
|
|
5767
|
+
var AttachmentSizeError = class extends Error {
|
|
5768
|
+
constructor(bytes, expected, options) {
|
|
5769
|
+
super(`Attachment body does not match its declared ${expected} bytes (read ${bytes})`, options);
|
|
5770
|
+
this.name = "AttachmentSizeError";
|
|
5771
|
+
}
|
|
5772
|
+
};
|
|
5773
|
+
/** Tries for one object write, each with a freshly opened body. */
|
|
5774
|
+
const WRITE_ATTEMPTS = 3;
|
|
5787
5775
|
async function bestEffortDelete(storage, key) {
|
|
5776
|
+
if (key === null) return;
|
|
5788
5777
|
try {
|
|
5789
5778
|
await storage.delete([key]);
|
|
5790
5779
|
} catch {}
|
|
5791
5780
|
}
|
|
5781
|
+
/**
|
|
5782
|
+
* Stream one file to a fresh key, and return its size and digest.
|
|
5783
|
+
*
|
|
5784
|
+
* The digest is taken while the bytes stream, so the body is never held
|
|
5785
|
+
* whole. A body that does not match its declared size is not kept.
|
|
5786
|
+
*/
|
|
5787
|
+
async function writeAttachmentObject(args) {
|
|
5788
|
+
for (let attempt = 1;; attempt += 1) try {
|
|
5789
|
+
return await writeAttachmentObjectOnce(args);
|
|
5790
|
+
} catch (error) {
|
|
5791
|
+
if (error instanceof AttachmentSizeError || attempt >= WRITE_ATTEMPTS) {
|
|
5792
|
+
await bestEffortDelete(args.storage, args.key);
|
|
5793
|
+
throw error;
|
|
5794
|
+
}
|
|
5795
|
+
}
|
|
5796
|
+
}
|
|
5797
|
+
async function writeAttachmentObjectOnce(args) {
|
|
5798
|
+
const { file } = args;
|
|
5799
|
+
const expected = "data" in file ? file.data.byteLength : file.bytes;
|
|
5800
|
+
const source = "data" in file ? bufferBody(file.data) : await file.open();
|
|
5801
|
+
const hash = createHash("sha256");
|
|
5802
|
+
let bytes = 0;
|
|
5803
|
+
const body = source.pipeThrough(new TransformStream({ transform(chunk, controller) {
|
|
5804
|
+
bytes += chunk.byteLength;
|
|
5805
|
+
if (bytes > expected) throw new AttachmentSizeError(bytes, expected);
|
|
5806
|
+
hash.update(chunk);
|
|
5807
|
+
controller.enqueue(chunk);
|
|
5808
|
+
} }));
|
|
5809
|
+
try {
|
|
5810
|
+
await args.storage.put({
|
|
5811
|
+
body,
|
|
5812
|
+
bytes: expected,
|
|
5813
|
+
contentType: file.mimeType,
|
|
5814
|
+
key: args.key
|
|
5815
|
+
});
|
|
5816
|
+
} catch (error) {
|
|
5817
|
+
if (bytes > expected) throw new AttachmentSizeError(bytes, expected, { cause: error });
|
|
5818
|
+
throw error;
|
|
5819
|
+
}
|
|
5820
|
+
if (bytes !== expected) throw new AttachmentSizeError(bytes, expected);
|
|
5821
|
+
return {
|
|
5822
|
+
bytes,
|
|
5823
|
+
sha256: hash.digest("hex")
|
|
5824
|
+
};
|
|
5825
|
+
}
|
|
5792
5826
|
async function isConversationPurged(db, conversationId) {
|
|
5793
5827
|
const [row] = await db.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
|
|
5794
5828
|
return row?.transcriptPurgedAt != null;
|
|
@@ -5821,7 +5855,8 @@ async function reuseLiveAttachment(args) {
|
|
|
5821
5855
|
/**
|
|
5822
5856
|
* Persist one conversation-owned file.
|
|
5823
5857
|
*
|
|
5824
|
-
* Identity is
|
|
5858
|
+
* Identity is stable under the conversation: it comes from the file's source
|
|
5859
|
+
* when it has one, and from its digest otherwise. Object storage is written
|
|
5825
5860
|
* first under a unique key; the SQL row is created only after that write
|
|
5826
5861
|
* succeeds. A row means the attachment is durable. Retries reuse an existing
|
|
5827
5862
|
* live row. A purge-marked row is revived by writing a new object and pointing
|
|
@@ -5832,14 +5867,14 @@ async function reuseLiveAttachment(args) {
|
|
|
5832
5867
|
*/
|
|
5833
5868
|
async function storeAttachment(args) {
|
|
5834
5869
|
const now = new Date(args.nowMs ?? Date.now());
|
|
5835
|
-
const
|
|
5870
|
+
const identity = attachmentIdentity(args.file);
|
|
5871
|
+
const source = args.file.source;
|
|
5836
5872
|
const id = attachmentId({
|
|
5837
5873
|
conversationId: args.conversationId,
|
|
5838
5874
|
contentType: args.file.mimeType,
|
|
5839
5875
|
filename: args.file.filename,
|
|
5840
|
-
|
|
5841
|
-
storageProvider: args.storage.provider
|
|
5842
|
-
sha256
|
|
5876
|
+
identity,
|
|
5877
|
+
storageProvider: args.storage.provider
|
|
5843
5878
|
});
|
|
5844
5879
|
const [existing] = await args.db.db().select({
|
|
5845
5880
|
contentType: juniorAttachments.contentType,
|
|
@@ -5854,24 +5889,33 @@ async function storeAttachment(args) {
|
|
|
5854
5889
|
storageKey: juniorAttachments.storageKey
|
|
5855
5890
|
}).from(juniorAttachments).where(eq(juniorAttachments.id, id));
|
|
5856
5891
|
if (existing) {
|
|
5857
|
-
if (existing.contentType !== args.file.mimeType || existing.conversationId !== args.conversationId || existing.filename !== args.file.filename || existing.provider !== (
|
|
5892
|
+
if (existing.contentType !== args.file.mimeType || existing.conversationId !== args.conversationId || existing.filename !== args.file.filename || existing.provider !== (source?.provider ?? null) || existing.providerId !== (source?.id ?? null) || existing.storageProvider !== args.storage.provider || "sha256" in identity && existing.sha256 !== identity.sha256) throw new Error(`Attachment write conflicts with ${existing.id}`);
|
|
5858
5893
|
if (existing.deleteRequestedAt === null) {
|
|
5859
5894
|
await assertConversationNotPurged(args.db, args.conversationId);
|
|
5860
5895
|
return { id: existing.id };
|
|
5861
5896
|
}
|
|
5862
5897
|
}
|
|
5863
5898
|
await assertConversationNotPurged(args.db, args.conversationId);
|
|
5864
|
-
const
|
|
5865
|
-
|
|
5866
|
-
|
|
5867
|
-
|
|
5868
|
-
|
|
5869
|
-
|
|
5870
|
-
|
|
5871
|
-
|
|
5872
|
-
|
|
5873
|
-
|
|
5874
|
-
|
|
5899
|
+
const { file } = args;
|
|
5900
|
+
let storageKey = null;
|
|
5901
|
+
let written;
|
|
5902
|
+
if ("deferred" in file) written = {
|
|
5903
|
+
bytes: file.bytes,
|
|
5904
|
+
sha256: null
|
|
5905
|
+
};
|
|
5906
|
+
else {
|
|
5907
|
+
storageKey = attachmentKey({
|
|
5908
|
+
attachmentId: id,
|
|
5909
|
+
conversationId: args.conversationId,
|
|
5910
|
+
filename: file.filename,
|
|
5911
|
+
writeId: randomUUID()
|
|
5912
|
+
});
|
|
5913
|
+
written = await writeAttachmentObject({
|
|
5914
|
+
file,
|
|
5915
|
+
key: storageKey,
|
|
5916
|
+
storage: args.storage
|
|
5917
|
+
});
|
|
5918
|
+
}
|
|
5875
5919
|
if (existing?.deleteRequestedAt != null) {
|
|
5876
5920
|
if (await isConversationPurged(args.db, args.conversationId)) {
|
|
5877
5921
|
await bestEffortDelete(args.storage, storageKey);
|
|
@@ -5879,6 +5923,7 @@ async function storeAttachment(args) {
|
|
|
5879
5923
|
}
|
|
5880
5924
|
const oldStorageKey = existing.storageKey;
|
|
5881
5925
|
if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
|
|
5926
|
+
...written,
|
|
5882
5927
|
deleteRequestedAt: null,
|
|
5883
5928
|
storageKey
|
|
5884
5929
|
}).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
|
|
@@ -5913,12 +5958,11 @@ async function storeAttachment(args) {
|
|
|
5913
5958
|
conversationId: args.conversationId,
|
|
5914
5959
|
storageProvider: args.storage.provider,
|
|
5915
5960
|
storageKey,
|
|
5916
|
-
provider:
|
|
5917
|
-
providerId:
|
|
5961
|
+
provider: source?.provider,
|
|
5962
|
+
providerId: source?.id,
|
|
5918
5963
|
filename: args.file.filename,
|
|
5919
5964
|
contentType: args.file.mimeType,
|
|
5920
|
-
|
|
5921
|
-
sha256,
|
|
5965
|
+
...written,
|
|
5922
5966
|
createdAt: now
|
|
5923
5967
|
}).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id });
|
|
5924
5968
|
} catch (error) {
|
|
@@ -5957,6 +6001,7 @@ async function storeAttachment(args) {
|
|
|
5957
6001
|
throw purgedConversationError(args.conversationId);
|
|
5958
6002
|
}
|
|
5959
6003
|
if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
|
|
6004
|
+
...written,
|
|
5960
6005
|
deleteRequestedAt: null,
|
|
5961
6006
|
storageKey
|
|
5962
6007
|
}).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
|
|
@@ -6017,6 +6062,8 @@ async function readLiveAttachment(args) {
|
|
|
6017
6062
|
deleteRequestedAt: juniorAttachments.deleteRequestedAt,
|
|
6018
6063
|
filename: juniorAttachments.filename,
|
|
6019
6064
|
id: juniorAttachments.id,
|
|
6065
|
+
provider: juniorAttachments.provider,
|
|
6066
|
+
providerId: juniorAttachments.providerId,
|
|
6020
6067
|
storageProvider: juniorAttachments.storageProvider,
|
|
6021
6068
|
storageKey: juniorAttachments.storageKey
|
|
6022
6069
|
}).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
|
|
@@ -6028,6 +6075,10 @@ async function readLiveAttachment(args) {
|
|
|
6028
6075
|
conversationId: row.conversationId,
|
|
6029
6076
|
filename: row.filename,
|
|
6030
6077
|
id: row.id,
|
|
6078
|
+
source: row.provider && row.providerId ? {
|
|
6079
|
+
id: row.providerId,
|
|
6080
|
+
provider: row.provider
|
|
6081
|
+
} : null,
|
|
6031
6082
|
storageKey: row.storageKey,
|
|
6032
6083
|
storageProvider: row.storageProvider
|
|
6033
6084
|
};
|
|
@@ -6038,7 +6089,11 @@ async function storeAttachments(args) {
|
|
|
6038
6089
|
for (const file of args.files) stored.push(await storeAttachment({
|
|
6039
6090
|
conversationId: args.conversationId,
|
|
6040
6091
|
db: args.db,
|
|
6041
|
-
file
|
|
6092
|
+
file: {
|
|
6093
|
+
data: file.data,
|
|
6094
|
+
filename: file.filename,
|
|
6095
|
+
mimeType: file.mimeType
|
|
6096
|
+
},
|
|
6042
6097
|
...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
|
|
6043
6098
|
storage: args.storage
|
|
6044
6099
|
}));
|
|
@@ -6064,7 +6119,8 @@ async function collectAttachmentGarbage(args) {
|
|
|
6064
6119
|
storageKey: juniorAttachments.storageKey
|
|
6065
6120
|
}).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(and(eq(juniorAttachments.storageProvider, args.storage.provider), or(lte(juniorAttachments.createdAt, expiresBefore), isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt)))).orderBy(asc(juniorAttachments.createdAt), asc(juniorAttachments.id)).limit(args.limit ?? ATTACHMENT_GC_BATCH_LIMIT);
|
|
6066
6121
|
if (rows.length === 0) return { deleted: 0 };
|
|
6067
|
-
|
|
6122
|
+
const keys = rows.flatMap((row) => row.storageKey ? [row.storageKey] : []);
|
|
6123
|
+
if (keys.length > 0) await args.storage.delete(keys);
|
|
6068
6124
|
const stillEligible = await args.db.db().select({ id: juniorAttachments.id }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(and(inArray(juniorAttachments.id, rows.map((row) => row.id)), or(lte(juniorAttachments.createdAt, expiresBefore), isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt))));
|
|
6069
6125
|
if (stillEligible.length === 0) return { deleted: 0 };
|
|
6070
6126
|
const removed = await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({ conversationId: juniorAttachments.conversationId });
|
|
@@ -6138,7 +6194,8 @@ async function writeAttachmentUpload(args) {
|
|
|
6138
6194
|
})) throw new AttachmentUploadError("Upload was already sent.");
|
|
6139
6195
|
if (args.body.byteLength !== row.bytes) throw new AttachmentUploadError("Upload size does not match the file.");
|
|
6140
6196
|
await args.storage.put({
|
|
6141
|
-
body: args.body,
|
|
6197
|
+
body: bufferBody(args.body),
|
|
6198
|
+
bytes: row.bytes,
|
|
6142
6199
|
contentType: row.contentType,
|
|
6143
6200
|
key: row.storageKey
|
|
6144
6201
|
});
|
|
@@ -6774,7 +6831,7 @@ function subjectInput(subject) {
|
|
|
6774
6831
|
/** Create the tool that adds a Review item or updates the open one. */
|
|
6775
6832
|
function createAddReviewItemTool(context, services) {
|
|
6776
6833
|
return zodTool({
|
|
6777
|
-
description: `Ask a person for input, or tell them about work that needs them. This is how you ask a person anything: the item goes on the review desk
|
|
6834
|
+
description: `Ask a person for input, or tell them about work that needs them. This is how you ask a person anything: the item goes on the review desk and, in a Slack thread, shows as a card with buttons. The answer arrives later as a \`<review-item-answer>\` with the item id. A dismiss sends you nothing. An assignee's thread reply that answers the item also closes it. If your next step needs the answer, end the Turn now with \`${NO_REPLY_TOOL_NAME}\` and no text: the card is your reply. Continue other work that does not need the answer.`,
|
|
6778
6835
|
annotations: {
|
|
6779
6836
|
destructiveHint: false,
|
|
6780
6837
|
idempotentHint: true,
|
|
@@ -6782,14 +6839,14 @@ function createAddReviewItemTool(context, services) {
|
|
|
6782
6839
|
readOnlyHint: false
|
|
6783
6840
|
},
|
|
6784
6841
|
inputSchema: z.object({
|
|
6785
|
-
kind: z.enum(["notice", "action"]),
|
|
6842
|
+
kind: z.enum(["notice", "action"]).describe("Use `action` with a `request` to ask. Use `notice` only to tell a person something."),
|
|
6786
6843
|
title: titleSchema,
|
|
6787
6844
|
body: bodySchema,
|
|
6788
|
-
assignees: assigneesSchema.nullable().optional().describe("Who can act on the item. Omit
|
|
6789
|
-
dedupe_key: z.string().trim().min(1).max(200).nullable().optional().describe("Stable key for what the item is about, such as `fair-source:entry:acme`. Use the same key on each run. Omit for a one-time question."),
|
|
6790
|
-
request: userInputRequestSchema.nullable().optional().describe("Required for an action item. Not allowed for a notice."),
|
|
6845
|
+
assignees: assigneesSchema.nullable().optional().describe("Who can act on the item. Omit for the person in this Turn, else the Automation creator in an Automation run, else the people still subscribed to the Conversation."),
|
|
6846
|
+
dedupe_key: z.string().trim().min(1).max(200).nullable().optional().describe("Stable key for what the item is about, such as `fair-source:entry:acme`. If an open item has this key, the call updates that item instead of adding another. Use the same key on each run. Omit for a one-time question."),
|
|
6847
|
+
request: userInputRequestSchema.nullable().optional().describe("Required for an action item. Not allowed for a notice. Ask for related input in one item. Write the question so it stands alone: a person who sees only the card must understand it."),
|
|
6791
6848
|
subject: subjectSchema.nullable().optional(),
|
|
6792
|
-
conversation_ids: conversationIdsSchema.nullable().optional().describe("Other Conversations to link.")
|
|
6849
|
+
conversation_ids: conversationIdsSchema.nullable().optional().describe("Other Conversations to link. The current Conversation is always linked.")
|
|
6793
6850
|
}).strict(),
|
|
6794
6851
|
outputSchema: juniorToolOutputSchema,
|
|
6795
6852
|
execute: async (input, options) => {
|
|
@@ -6882,7 +6939,7 @@ function createAddReviewItemTool(context, services) {
|
|
|
6882
6939
|
*/
|
|
6883
6940
|
function createUpdateReviewItemTool(context, services) {
|
|
6884
6941
|
return zodTool({
|
|
6885
|
-
description: "Change an open review desk item, or close it.
|
|
6942
|
+
description: "Change an open review desk item, or close it. An item also closes when a person answers or dismisses it, when a person's reply in its thread answers it, when its Conversation is purged, when its Automation is deleted, or when the plugin that added it closes it. You cannot submit the answer to an action item: only an assignee can.",
|
|
6886
6943
|
exposure: "deferred",
|
|
6887
6944
|
source: REVIEW_DESK_TOOL_SOURCE,
|
|
6888
6945
|
annotations: {
|
|
@@ -6897,7 +6954,7 @@ function createUpdateReviewItemTool(context, services) {
|
|
|
6897
6954
|
body: bodySchema.nullable().optional(),
|
|
6898
6955
|
assignees: assigneesSchema.nullable().optional().describe("Replaces every assignee."),
|
|
6899
6956
|
conversation_ids: conversationIdsSchema.nullable().optional().describe("Replaces every other linked Conversation. The Conversation that added the item stays linked."),
|
|
6900
|
-
status: z.enum(["done", "dismissed"]).nullable().optional(),
|
|
6957
|
+
status: z.enum(["done", "dismissed"]).nullable().optional().describe("Close the item, for example when its pull request merged."),
|
|
6901
6958
|
reason: z.string().trim().min(1).max(500).nullable().optional().describe("Why the item closed. Required with `status`.")
|
|
6902
6959
|
}).strict(),
|
|
6903
6960
|
outputSchema: juniorToolOutputSchema,
|
|
@@ -9241,14 +9298,14 @@ function createAutomationTool(context, catalog, skills = []) {
|
|
|
9241
9298
|
readOnlyHint: false
|
|
9242
9299
|
},
|
|
9243
9300
|
executionMode: "sequential",
|
|
9244
|
-
description: "Create a durable automation. It belongs to the channel or DM of this conversation, never a thread.
|
|
9301
|
+
description: "Create a durable automation. It belongs to the channel or DM of this conversation, never a thread. When an installed skill does the work, have the automation run that skill; do not write an instruction that names the skill. Ordinary watch, notify, or tell-me-when requests use watchEvents instead. Store the requested future work; do not perform it or check its service access now unless the user also asks for that. When the trigger is known, create it without redundant confirmation.",
|
|
9245
9302
|
inputSchema: z.object({
|
|
9246
9303
|
instruction: automationInstructionToolSchema.nullable().optional(),
|
|
9247
9304
|
skill: automationSkillToolSchema(skills).nullable().optional(),
|
|
9248
9305
|
context: automationContextToolSchema.nullable().optional(),
|
|
9249
9306
|
title: z.string().trim().min(1).max(60).nullable().describe("Optional short display title. Omit or use null to generate one from the instruction or skill.").optional(),
|
|
9250
|
-
trigger,
|
|
9251
|
-
outcomes: z.array(taskOutcomeInputSchema).max(5).describe("Successful work is silent by default
|
|
9307
|
+
trigger: trigger.describe("Use type \"schedule\" for one-time or recurring work. Use type \"event\" only when the user explicitly asks for an event automation or durable whenever-this-happens-do-X work; it runs for every matching event."),
|
|
9308
|
+
outcomes: z.array(taskOutcomeInputSchema).max(5).describe("Successful work is silent by default: omit this or use an empty list when the Automation acts through tools without a status message. Add send_message only when the user asks for a reminder, notification, post, digest, summary, or other visible result.").optional(),
|
|
9252
9309
|
credential_mode: z.enum(["creator", "system"]).nullable().describe("Omit or use null for the system default: runs use your own credentials. Use creator only when the creator asks for their connected credentials to be available to the runs.").optional()
|
|
9253
9310
|
}).strict(),
|
|
9254
9311
|
prepareArguments(args) {
|
|
@@ -9396,7 +9453,7 @@ function createSearchAutomationsTool(context, catalog) {
|
|
|
9396
9453
|
openWorldHint: false,
|
|
9397
9454
|
readOnlyHint: true
|
|
9398
9455
|
},
|
|
9399
|
-
description: "Search scheduled and event automations. It finds the requester's automations, automations in public channels, and automations that deliver to this conversation. Each result
|
|
9456
|
+
description: "Search scheduled and event automations. It finds the requester's automations, automations in public channels, and automations that deliver to this conversation. Each result says whether the requester is the creator (is_creator); only the creator can change its credential use. For an event automation, warn when trigger.available is false and explain trigger.problems: the automation stays stored, but a plugin no longer supports its resource type, an event, or a filter. Update the trigger to fix it.",
|
|
9400
9457
|
inputSchema: automationSearchInputSchema,
|
|
9401
9458
|
outputSchema: automationSearchResultSchema,
|
|
9402
9459
|
async execute(input) {
|
|
@@ -9576,7 +9633,7 @@ function createUpdateAutomationTool(context, catalog, skills = []) {
|
|
|
9576
9633
|
context: automationContextToolSchema.nullable().describe(`${automationContextToolSchema.description} Only for a skill Automation, or with skill. Use null to remove the context. Omit to keep it.`).optional(),
|
|
9577
9634
|
trigger: trigger.nullable().describe("Replacement trigger of the same type. For an event trigger, match changes only the filters that it names. Omit or use null to keep the trigger.").optional(),
|
|
9578
9635
|
outcomes: z.array(taskOutcomeInputSchema).max(5).nullable().describe("Replacement messages to send after successful work. Use an empty list to send nothing. Omit or use null to leave unchanged.").optional(),
|
|
9579
|
-
credential_mode: z.enum(["system", "creator"]).nullable().describe("Set creator to make the automation creator's credentials available, or system to disable them. Creator always means the automation's createdBy actor, never the current requester. Only that creator may enable creator mode. Omit or
|
|
9636
|
+
credential_mode: z.enum(["system", "creator"]).nullable().describe("Set creator to make the automation creator's credentials available, or system to disable them. Creator always means the automation's createdBy actor, never the current requester. Only that creator may enable creator mode. Omit or null leaves it unchanged.").optional(),
|
|
9580
9637
|
status: z.enum(["active", "paused"]).nullable().describe("Set active to resume a paused or blocked automation, or paused to stop it. When it uses its creator's credentials, only the creator can resume it. Omit or use null to leave unchanged.").optional(),
|
|
9581
9638
|
destination: slackChannelRefParam.nullable().describe("Where to move a scheduled automation. Set \"current_conversation\" for the channel or DM of this conversation, or name a public Slack channel by id, mention, or known name. Omit to keep its destination.").optional()
|
|
9582
9639
|
}).strict();
|
|
@@ -9591,7 +9648,7 @@ function createUpdateAutomationTool(context, catalog, skills = []) {
|
|
|
9591
9648
|
readOnlyHint: false
|
|
9592
9649
|
},
|
|
9593
9650
|
executionMode: "sequential",
|
|
9594
|
-
description: "Update the title, instruction or skill and its context, trigger, outcomes, credential use, or status of a scheduled or event automation. Anyone in the workspace can update anything on an automation in a public channel, including its outcomes and destination. Automations in private channels and DMs can be updated from there or by their creator
|
|
9651
|
+
description: "Update the title, instruction or skill and its context, trigger, outcomes, credential use, or status of a scheduled or event automation. Anyone in the workspace can update anything on an automation in a public channel, including its outcomes and destination. Automations in private channels and DMs can be updated from there or by their creator; only their creator can move them. A non-creator who changes the instruction, skill, context, trigger, outcomes, or destination switches it to system credentials.",
|
|
9595
9652
|
inputSchema,
|
|
9596
9653
|
prepareArguments(args) {
|
|
9597
9654
|
return Object.fromEntries(Object.entries(args).filter(([key, value]) => value !== void 0 && (value !== null || key === "context")));
|
|
@@ -9839,7 +9896,7 @@ function normalizeRangeTimestamp(field, value, targetChannelId) {
|
|
|
9839
9896
|
/** Create the channel history tool with optional cross-channel targets. */
|
|
9840
9897
|
function createSlackChannelListMessagesTool(context) {
|
|
9841
9898
|
return zodTool({
|
|
9842
|
-
description: "List messages from Slack channel history.
|
|
9899
|
+
description: "List messages from Slack channel history.",
|
|
9843
9900
|
annotations: {
|
|
9844
9901
|
destructiveHint: false,
|
|
9845
9902
|
idempotentHint: true,
|
|
@@ -9847,7 +9904,7 @@ function createSlackChannelListMessagesTool(context) {
|
|
|
9847
9904
|
readOnlyHint: true
|
|
9848
9905
|
},
|
|
9849
9906
|
inputSchema: z.object({
|
|
9850
|
-
channel_id: slackChannelRefParam.nullable().optional(),
|
|
9907
|
+
channel_id: slackChannelRefParam.nullable().describe("Omit to read the active channel. Another channel must be public.").optional(),
|
|
9851
9908
|
limit: z.coerce.number().int().min(1).max(1e3).describe("Maximum number of messages to return across pages.").nullable().optional(),
|
|
9852
9909
|
cursor: z.string().min(1).describe("Cursor from `next_cursor` in a prior result. Use null or omit it for the first page; never invent a cursor.").nullable().optional(),
|
|
9853
9910
|
oldest: slackTimestampParam("Oldest message timestamp (Slack ts) for range filtering.").nullable().optional(),
|
|
@@ -10127,7 +10184,7 @@ function createSearchConversationsTool(context) {
|
|
|
10127
10184
|
return zodTool({
|
|
10128
10185
|
exposure: "deferred",
|
|
10129
10186
|
source: CONVERSATIONS_TOOL_SOURCE,
|
|
10130
|
-
description: "Search other conversations for past or current work, with the summary, outcome, and links of their latest Brief. Finds conversations in public channels and in the same private channel or DM.
|
|
10187
|
+
description: "Search other conversations for past or current work, with the summary, outcome, and links of their latest Brief. Finds conversations in public channels and in the same private channel or DM. A root Brief covers the work of its child agents. Briefs remain after transcripts are purged.",
|
|
10131
10188
|
annotations: {
|
|
10132
10189
|
destructiveHint: false,
|
|
10133
10190
|
idempotentHint: true,
|
|
@@ -12692,7 +12749,7 @@ async function resolveStoredProvider(teamId, provider, query) {
|
|
|
12692
12749
|
/** Create the tool that resolves people by identity provider and query. */
|
|
12693
12750
|
function createUserLookupTool(teamId, providers) {
|
|
12694
12751
|
return zodTool({
|
|
12695
|
-
description: "Look up people by identity provider and query.
|
|
12752
|
+
description: "Look up people by identity provider and query. Name search can miss people in large workspaces. Returns Slack `mention` values (`<@U…>`) for the current workspace. Slack results also list `linked_identities`: verified handles of other accounts the person linked to you, such as `github`. Use a mention or handle only when one person clearly matches; otherwise ask which person the user means.",
|
|
12696
12753
|
annotations: {
|
|
12697
12754
|
destructiveHint: false,
|
|
12698
12755
|
idempotentHint: true,
|
|
@@ -12701,7 +12758,7 @@ function createUserLookupTool(teamId, providers) {
|
|
|
12701
12758
|
},
|
|
12702
12759
|
inputSchema: z.object({
|
|
12703
12760
|
provider: z.enum(providers).describe("Enabled identity provider to query."),
|
|
12704
|
-
query: z.string().trim().min(1).describe("Provider subject ID, handle, Slack email, or Slack name.
|
|
12761
|
+
query: z.string().trim().min(1).describe("Provider subject ID, handle, Slack email, or Slack name. For Slack, pass the user ID (`U…`) whenever the conversation shows one, such as the requester's `author_id`, a participant's `actor_id`, or a `<@U…>` mention. Search by name only with no known ID.")
|
|
12705
12762
|
}).strict(),
|
|
12706
12763
|
outputSchema: juniorToolOutputSchema,
|
|
12707
12764
|
execute: async ({ provider, query }) => {
|
|
@@ -13090,7 +13147,8 @@ async function publishImage(args) {
|
|
|
13090
13147
|
const id = existing?.id ?? randomUUID();
|
|
13091
13148
|
const storageKey = artifactKey(`${id}.${extension}`);
|
|
13092
13149
|
await args.storage.put({
|
|
13093
|
-
body: args.body,
|
|
13150
|
+
body: bufferBody(args.body),
|
|
13151
|
+
bytes: args.body.byteLength,
|
|
13094
13152
|
contentType,
|
|
13095
13153
|
key: storageKey
|
|
13096
13154
|
});
|
|
@@ -13248,29 +13306,138 @@ function createUnpublishImageTool(args) {
|
|
|
13248
13306
|
}
|
|
13249
13307
|
});
|
|
13250
13308
|
}
|
|
13309
|
+
// src/chat/attachments/download.ts
|
|
13310
|
+
/** Refusal for a file over `MAX_ATTACHMENT_BYTES`. */
|
|
13311
|
+
const ATTACHMENT_TOO_LARGE_MESSAGE = `Attachment is larger than the ${MAX_ATTACHMENT_BYTES / 1024 / 1024} MB file limit.`;
|
|
13312
|
+
/** An attachment whose bytes cannot be read. The message is safe to show. */
|
|
13313
|
+
var AttachmentDownloadError = class extends Error {
|
|
13314
|
+
constructor(message, options) {
|
|
13315
|
+
super(message, options);
|
|
13316
|
+
this.name = "AttachmentDownloadError";
|
|
13317
|
+
}
|
|
13318
|
+
};
|
|
13319
|
+
/**
|
|
13320
|
+
* Find where the bytes of one attachment row are, without reading them.
|
|
13321
|
+
*
|
|
13322
|
+
* A stored file reads from storage. A large Slack file is never stored, so
|
|
13323
|
+
* each `open` downloads it from its source. The source reports the current
|
|
13324
|
+
* size, and the size check runs before any download. Errors that the person
|
|
13325
|
+
* should see are `AttachmentDownloadError`, from here or from `open`.
|
|
13326
|
+
*
|
|
13327
|
+
* The row must come from a lookup scoped to the caller's conversation. The
|
|
13328
|
+
* source id comes from that row only, never from a request.
|
|
13329
|
+
*/
|
|
13330
|
+
async function readAttachmentContent(args) {
|
|
13331
|
+
const { attachment, storage } = args;
|
|
13332
|
+
const { storageKey } = attachment;
|
|
13333
|
+
if (storageKey !== null) return {
|
|
13334
|
+
bytes: attachment.bytes,
|
|
13335
|
+
open: async () => {
|
|
13336
|
+
const body = await storage.get(storageKey);
|
|
13337
|
+
if (!body) throw new AttachmentDownloadError("Stored attachment contents are unavailable.");
|
|
13338
|
+
return body;
|
|
13339
|
+
}
|
|
13340
|
+
};
|
|
13341
|
+
const { source } = attachment;
|
|
13342
|
+
if (!source || !args.readAttachmentSource) throw new AttachmentDownloadError("Attachment cannot be downloaded from this conversation.");
|
|
13343
|
+
const unavailable = (error) => error instanceof AttachmentSourceUnavailableError ? new AttachmentDownloadError(`${attachment.filename} is no longer available: ${error.message}`, { cause: error }) : error;
|
|
13344
|
+
let file;
|
|
13345
|
+
try {
|
|
13346
|
+
file = await args.readAttachmentSource(source);
|
|
13347
|
+
} catch (error) {
|
|
13348
|
+
throw unavailable(error);
|
|
13349
|
+
}
|
|
13350
|
+
if (file.bytes > 262144e3) throw new AttachmentDownloadError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
13351
|
+
return {
|
|
13352
|
+
bytes: file.bytes,
|
|
13353
|
+
open: async () => {
|
|
13354
|
+
try {
|
|
13355
|
+
return await file.open();
|
|
13356
|
+
} catch (error) {
|
|
13357
|
+
throw unavailable(error);
|
|
13358
|
+
}
|
|
13359
|
+
}
|
|
13360
|
+
};
|
|
13361
|
+
}
|
|
13251
13362
|
// src/chat/tools/load-attachment.ts
|
|
13252
13363
|
const ATTACHMENT_DIR = ".junior/attachments";
|
|
13253
|
-
|
|
13254
|
-
|
|
13255
|
-
|
|
13256
|
-
|
|
13257
|
-
|
|
13258
|
-
|
|
13259
|
-
|
|
13364
|
+
/** Bytes held in memory and sent to the sandbox in one write. */
|
|
13365
|
+
const PART_BYTES = 8388608;
|
|
13366
|
+
const JOIN_PARTS_SCRIPT = "set -eu; out=$1; shift; cat -- \"$@\" > \"$out\"";
|
|
13367
|
+
/** Turn a read failure that the model can relay into a tool error. */
|
|
13368
|
+
function toolError(error) {
|
|
13369
|
+
return error instanceof AttachmentDownloadError ? new ToolInputError(error.message, { cause: error }) : error;
|
|
13370
|
+
}
|
|
13371
|
+
/** Run one sandbox command, and return its stdout. Throw when it fails. */
|
|
13372
|
+
async function runChecked(workspace, action, input) {
|
|
13373
|
+
const result = await workspace.runCommand(input);
|
|
13374
|
+
if (result.exitCode !== 0) throw new Error(`Failed to ${action}: ${result.stderr}`);
|
|
13375
|
+
return result.stdout;
|
|
13376
|
+
}
|
|
13377
|
+
/**
|
|
13378
|
+
* Write an attachment body to the sandbox in parts of at most `PART_BYTES`.
|
|
13379
|
+
*
|
|
13380
|
+
* The sandbox SDK writes only whole buffers, so this keeps one part in
|
|
13381
|
+
* memory, not the file. Returns the part paths in order.
|
|
13382
|
+
*/
|
|
13383
|
+
async function writeParts(args) {
|
|
13384
|
+
const parts = [];
|
|
13385
|
+
let pending = [];
|
|
13386
|
+
let pendingBytes = 0;
|
|
13387
|
+
let total = 0;
|
|
13388
|
+
const flush = async () => {
|
|
13389
|
+
const partPath = path.posix.join(args.partsDir, String(parts.length).padStart(4, "0"));
|
|
13390
|
+
await args.workspace.writeFiles([{
|
|
13391
|
+
content: Buffer.concat(pending),
|
|
13392
|
+
path: partPath
|
|
13393
|
+
}]);
|
|
13394
|
+
parts.push(partPath);
|
|
13395
|
+
pending = [];
|
|
13396
|
+
pendingBytes = 0;
|
|
13397
|
+
};
|
|
13398
|
+
const reader = args.body.getReader();
|
|
13399
|
+
try {
|
|
13400
|
+
for (;;) {
|
|
13401
|
+
const { done, value } = await reader.read();
|
|
13402
|
+
if (done) break;
|
|
13403
|
+
total += value.byteLength;
|
|
13404
|
+
if (total > args.expectedBytes) break;
|
|
13405
|
+
let chunk = value;
|
|
13406
|
+
while (pendingBytes + chunk.byteLength >= PART_BYTES) {
|
|
13407
|
+
const take = PART_BYTES - pendingBytes;
|
|
13408
|
+
pending.push(chunk.subarray(0, take));
|
|
13409
|
+
pendingBytes += take;
|
|
13410
|
+
await flush();
|
|
13411
|
+
chunk = chunk.subarray(take);
|
|
13412
|
+
}
|
|
13413
|
+
if (chunk.byteLength > 0) {
|
|
13414
|
+
pending.push(chunk);
|
|
13415
|
+
pendingBytes += chunk.byteLength;
|
|
13416
|
+
}
|
|
13417
|
+
}
|
|
13418
|
+
} finally {
|
|
13419
|
+
await reader.cancel().catch(() => void 0);
|
|
13260
13420
|
}
|
|
13261
|
-
|
|
13421
|
+
if (total !== args.expectedBytes) throw new Error(`Attachment ${args.attachmentId} read ${total} bytes, expected ${args.expectedBytes}.`);
|
|
13422
|
+
if (pendingBytes > 0 || parts.length === 0) await flush();
|
|
13423
|
+
return parts;
|
|
13262
13424
|
}
|
|
13263
|
-
/**
|
|
13425
|
+
/**
|
|
13426
|
+
* Create a tool that restores one conversation attachment to the sandbox.
|
|
13427
|
+
*
|
|
13428
|
+
* A large Slack file is never stored: each load streams it from Slack
|
|
13429
|
+
* through the host. The sandbox never gets a Slack URL or token.
|
|
13430
|
+
*/
|
|
13264
13431
|
function createLoadAttachmentTool(args) {
|
|
13265
13432
|
return zodTool({
|
|
13266
|
-
description: "Load a stored attachment for this conversation into the sandbox.
|
|
13433
|
+
description: "Load a stored attachment for this conversation into the sandbox.",
|
|
13267
13434
|
annotations: {
|
|
13268
13435
|
destructiveHint: false,
|
|
13269
13436
|
idempotentHint: true,
|
|
13270
|
-
openWorldHint:
|
|
13437
|
+
openWorldHint: true,
|
|
13271
13438
|
readOnlyHint: false
|
|
13272
13439
|
},
|
|
13273
|
-
inputSchema: z.object({ attachment_id: z.string().min(1).describe("Stored attachment ID.") }),
|
|
13440
|
+
inputSchema: z.object({ attachment_id: z.string().min(1).describe("Stored attachment ID, as shown in attachment context or Slack read results.") }),
|
|
13274
13441
|
outputSchema: juniorToolOutputSchema,
|
|
13275
13442
|
execute: async ({ attachment_id }) => {
|
|
13276
13443
|
const attachment = await readLiveAttachment({
|
|
@@ -13279,26 +13446,92 @@ function createLoadAttachmentTool(args) {
|
|
|
13279
13446
|
db: args.db
|
|
13280
13447
|
});
|
|
13281
13448
|
if (!attachment || attachment.storageProvider !== args.storage.provider) throw new ToolInputError("Attachment not found in this conversation.");
|
|
13282
|
-
|
|
13283
|
-
|
|
13284
|
-
|
|
13285
|
-
|
|
13449
|
+
if (attachment.bytes > 262144e3) throw new ToolInputError(ATTACHMENT_TOO_LARGE_MESSAGE);
|
|
13450
|
+
let content;
|
|
13451
|
+
try {
|
|
13452
|
+
content = await readAttachmentContent({
|
|
13453
|
+
attachment,
|
|
13454
|
+
readAttachmentSource: args.readAttachmentSource,
|
|
13455
|
+
storage: args.storage
|
|
13456
|
+
});
|
|
13457
|
+
} catch (error) {
|
|
13458
|
+
throw toolError(error);
|
|
13459
|
+
}
|
|
13286
13460
|
const attachmentDir = path.posix.join(ATTACHMENT_DIR, attachment.id);
|
|
13461
|
+
const partsDir = `${attachmentDir}.parts`;
|
|
13287
13462
|
const sandboxPath = path.posix.join(attachmentDir, path.posix.basename(attachment.filename));
|
|
13288
|
-
|
|
13463
|
+
await runChecked(args.workspace, "create attachment directory", {
|
|
13289
13464
|
cmd: "mkdir",
|
|
13290
|
-
args: [
|
|
13465
|
+
args: [
|
|
13466
|
+
"-p",
|
|
13467
|
+
"--",
|
|
13468
|
+
attachmentDir,
|
|
13469
|
+
partsDir
|
|
13470
|
+
]
|
|
13471
|
+
});
|
|
13472
|
+
const joinedPath = path.posix.join(partsDir, "joined");
|
|
13473
|
+
try {
|
|
13474
|
+
const parts = await writeParts({
|
|
13475
|
+
attachmentId: attachment.id,
|
|
13476
|
+
body: await content.open(),
|
|
13477
|
+
expectedBytes: content.bytes,
|
|
13478
|
+
partsDir,
|
|
13479
|
+
workspace: args.workspace
|
|
13480
|
+
});
|
|
13481
|
+
await runChecked(args.workspace, "join attachment parts", {
|
|
13482
|
+
cmd: "sh",
|
|
13483
|
+
args: [
|
|
13484
|
+
"-c",
|
|
13485
|
+
JOIN_PARTS_SCRIPT,
|
|
13486
|
+
"sh",
|
|
13487
|
+
joinedPath,
|
|
13488
|
+
...parts
|
|
13489
|
+
]
|
|
13490
|
+
});
|
|
13491
|
+
const size = await runChecked(args.workspace, "read attachment size", {
|
|
13492
|
+
cmd: "stat",
|
|
13493
|
+
args: [
|
|
13494
|
+
"-c",
|
|
13495
|
+
"%s",
|
|
13496
|
+
"--",
|
|
13497
|
+
joinedPath
|
|
13498
|
+
]
|
|
13499
|
+
});
|
|
13500
|
+
const written = Number(size.trim());
|
|
13501
|
+
if (written !== content.bytes) throw new Error(`Attachment ${attachment.id} wrote ${written} bytes to the sandbox, expected ${content.bytes}.`);
|
|
13502
|
+
await runChecked(args.workspace, "move attachment into place", {
|
|
13503
|
+
cmd: "mv",
|
|
13504
|
+
args: [
|
|
13505
|
+
"-f",
|
|
13506
|
+
"--",
|
|
13507
|
+
joinedPath,
|
|
13508
|
+
sandboxPath
|
|
13509
|
+
]
|
|
13510
|
+
});
|
|
13511
|
+
} catch (error) {
|
|
13512
|
+
await args.workspace.runCommand({
|
|
13513
|
+
cmd: "rm",
|
|
13514
|
+
args: [
|
|
13515
|
+
"-rf",
|
|
13516
|
+
"--",
|
|
13517
|
+
partsDir
|
|
13518
|
+
]
|
|
13519
|
+
}).catch(() => void 0);
|
|
13520
|
+
throw toolError(error);
|
|
13521
|
+
}
|
|
13522
|
+
await runChecked(args.workspace, "remove attachment parts", {
|
|
13523
|
+
cmd: "rm",
|
|
13524
|
+
args: [
|
|
13525
|
+
"-rf",
|
|
13526
|
+
"--",
|
|
13527
|
+
partsDir
|
|
13528
|
+
]
|
|
13291
13529
|
});
|
|
13292
|
-
if (mkdir.exitCode !== 0) throw new Error(`Failed to create attachment directory: ${mkdir.stderr}`);
|
|
13293
|
-
await args.workspace.writeFiles([{
|
|
13294
|
-
content: data,
|
|
13295
|
-
path: sandboxPath
|
|
13296
|
-
}]);
|
|
13297
13530
|
return {
|
|
13298
13531
|
path: sandboxPath,
|
|
13299
13532
|
filename: attachment.filename,
|
|
13300
13533
|
mime_type: attachment.contentType,
|
|
13301
|
-
bytes:
|
|
13534
|
+
bytes: content.bytes
|
|
13302
13535
|
};
|
|
13303
13536
|
}
|
|
13304
13537
|
});
|
|
@@ -14437,6 +14670,7 @@ function createTools(availableSkills, hooks = {}, context, options = {}) {
|
|
|
14437
14670
|
tools.loadAttachment = createLoadAttachmentTool({
|
|
14438
14671
|
conversationId: context.conversationId,
|
|
14439
14672
|
db: getSqlExecutor(),
|
|
14673
|
+
...slackContext ? { readAttachmentSource: readSlackAttachmentSource } : void 0,
|
|
14440
14674
|
storage: context.attachmentStorage,
|
|
14441
14675
|
workspace: context.workspace
|
|
14442
14676
|
});
|
|
@@ -14751,12 +14985,6 @@ function buildSandboxInput(toolName, params) {
|
|
|
14751
14985
|
return params;
|
|
14752
14986
|
}
|
|
14753
14987
|
// src/chat/guardian/gate.ts
|
|
14754
|
-
/**
|
|
14755
|
-
* Owns the execution gate for reviewable tool actions.
|
|
14756
|
-
*
|
|
14757
|
-
* Deterministic host checks establish authority before the model evaluates
|
|
14758
|
-
* untrusted action evidence.
|
|
14759
|
-
*/
|
|
14760
14988
|
const ACTION_CONFIRMATION_INSTRUCTIONS = [
|
|
14761
14989
|
"The action was not executed because explicit user confirmation is required.",
|
|
14762
14990
|
"Do not retry it, or get the same outcome another way, until the user explicitly confirms this exact action.",
|
|
@@ -14814,13 +15042,15 @@ var ToolActionReviewLimitError = class extends Error {
|
|
|
14814
15042
|
}
|
|
14815
15043
|
};
|
|
14816
15044
|
/**
|
|
14817
|
-
* True when an `auto` action must enter review.
|
|
14818
|
-
*
|
|
14819
|
-
*
|
|
15045
|
+
* True when an `auto` action must enter review. The tool's annotations alone
|
|
15046
|
+
* decide: an action marked read-only and not destructive skips review, like
|
|
15047
|
+
* MCP clients such as Codex do. MCP annotations come from the server, and
|
|
15048
|
+
* plugin annotations from the plugin. Anything else, including missing
|
|
15049
|
+
* annotations, is unknown risk.
|
|
14820
15050
|
*/
|
|
14821
15051
|
function autoActionNeedsReview(tool, resolved) {
|
|
14822
15052
|
const annotations = resolved?.annotations ?? tool.annotations;
|
|
14823
|
-
return
|
|
15053
|
+
return !(annotations?.readOnlyHint === true && annotations.destructiveHint !== true);
|
|
14824
15054
|
}
|
|
14825
15055
|
function actionActor(actor) {
|
|
14826
15056
|
if (actor.platform === "system") return {
|
|
@@ -15203,7 +15433,7 @@ function createExecuteToolTool() {
|
|
|
15203
15433
|
openWorldHint: true,
|
|
15204
15434
|
readOnlyHint: false
|
|
15205
15435
|
},
|
|
15206
|
-
description: "Execute a catalog tool by exact
|
|
15436
|
+
description: "Execute a catalog tool by its exact name. Use it for a tool that is not in your tool list: one that searchTools returned, or one that a skill, tool result, or error names. Put tool-specific parameters inside arguments.",
|
|
15207
15437
|
executionMode: "sequential",
|
|
15208
15438
|
exposure: "modelOnly",
|
|
15209
15439
|
inputSchema: z.object({
|
|
@@ -16277,9 +16507,8 @@ function renderScriptTools(tools) {
|
|
|
16277
16507
|
].join("\n");
|
|
16278
16508
|
}
|
|
16279
16509
|
const DESCRIPTION = [
|
|
16280
|
-
"Run a JavaScript script that calls other tools, and get back only what the script returns or prints.
|
|
16510
|
+
"Run a JavaScript script that calls other tools, and get back only what the script returns or prints.",
|
|
16281
16511
|
"",
|
|
16282
|
-
"The code is the body of an async function: top-level `await` and `return` work. It runs in a QuickJS VM with no Node, file system, network, or timers.",
|
|
16283
16512
|
"- `await tools.<name>(args)` runs one tool through the normal tool path, including action review. It resolves to the tool result, and rejects with an Error when the call fails or action review rejects it.",
|
|
16284
16513
|
"- Arguments and results must be JSON-serializable.",
|
|
16285
16514
|
"- Run calls at the same time (`Promise.all`) only when they do not depend on each other. Await a call before a call that needs its result. Run calls that change the same thing one after another.",
|
|
@@ -16321,7 +16550,7 @@ function createCodeModeTool(options) {
|
|
|
16321
16550
|
description: DESCRIPTION,
|
|
16322
16551
|
executionMode: "sequential",
|
|
16323
16552
|
exposure: "modelOnly",
|
|
16324
|
-
inputSchema: z.object({ code: z.string().min(1).describe("JavaScript source: the body of an async function. Raw code, not JSON and not in a code fence.") }).strict(),
|
|
16553
|
+
inputSchema: z.object({ code: z.string().min(1).describe("JavaScript source: the body of an async function, so top-level `await` and `return` work. Raw code, not JSON and not in a code fence. It runs in a QuickJS VM with no Node, file system, network, or timers.") }).strict(),
|
|
16325
16554
|
outputSchema: juniorToolOutputSchema,
|
|
16326
16555
|
execute: async ({ code }, { signal, toolCallId }) => {
|
|
16327
16556
|
if (!toolCallId) throw new Error("codemode requires a tool call id.");
|
|
@@ -18900,7 +19129,7 @@ function waitsForUse(event, nowMs) {
|
|
|
18900
19129
|
*/
|
|
18901
19130
|
async function requestBackgroundCompaction(args) {
|
|
18902
19131
|
if (!args.queue) return;
|
|
18903
|
-
const inputSize = lastRequestInputSize(args.agent.state.messages);
|
|
19132
|
+
const inputSize = lastRequestInputSize(readAgentHistory(args.agent.state.messages));
|
|
18904
19133
|
if (inputSize === void 0 || inputSize < getAgentBackgroundCompactionMarkTokens(args.modelId)) return;
|
|
18905
19134
|
try {
|
|
18906
19135
|
await requestAboveMark({
|
|
@@ -20284,7 +20513,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20284
20513
|
const terminatingToolCallIds = /* @__PURE__ */ new Set();
|
|
20285
20514
|
let discardedRetryUsage;
|
|
20286
20515
|
const turnLimitGate = createTurnLimitGate(runResume.turnLimitWrappedUp);
|
|
20287
|
-
const currentAgentMessages = () => agent ?
|
|
20516
|
+
const currentAgentMessages = () => agent ? readAgentHistory(agent.state.messages) : [];
|
|
20517
|
+
const setAgentHistory = (messages) => {
|
|
20518
|
+
agent.state.messages = writeAgentHistory(agent.state.messages, messages);
|
|
20519
|
+
};
|
|
20288
20520
|
const usageSinceCurrentBoundary = (messages) => {
|
|
20289
20521
|
const usage = extractGenAiUsageSummary(...messages.slice(runResume.beforeMessageCount).filter(isAssistantMessage));
|
|
20290
20522
|
return hasAgentTurnUsage(usage) ? usage : void 0;
|
|
@@ -20379,7 +20611,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20379
20611
|
restoredMessages: existingSessionRecord?.piMessages,
|
|
20380
20612
|
restoredProvenance: existingSessionRecord?.piMessageProvenance,
|
|
20381
20613
|
setMessages(messages) {
|
|
20382
|
-
|
|
20614
|
+
setAgentHistory(messages);
|
|
20383
20615
|
},
|
|
20384
20616
|
shouldPromptAgent
|
|
20385
20617
|
});
|
|
@@ -20390,7 +20622,10 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20390
20622
|
...streamFn ? { base: streamFn } : void 0
|
|
20391
20623
|
});
|
|
20392
20624
|
const nextInputAfterReplacement = createNextInputTracker();
|
|
20393
|
-
/**
|
|
20625
|
+
/**
|
|
20626
|
+
* Commit and adopt an active capacity replacement. True when it replaced
|
|
20627
|
+
* history.
|
|
20628
|
+
*/
|
|
20394
20629
|
const applyActiveContextCompaction = async (messages, hookSignal, pendingMessages, clearSteeringQueueOnCommit = false, pairPendingRuntimeContext = false, mode = "active") => {
|
|
20395
20630
|
const compaction = await compactWithPreparedSummary({
|
|
20396
20631
|
conversationId,
|
|
@@ -20404,7 +20639,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20404
20639
|
signal: hookSignal,
|
|
20405
20640
|
turnStartMessageIndex: runResume.turnStartMessageIndex
|
|
20406
20641
|
}, async (summaryMessages, summarySignal) => await requestContextSummary(await buildAgentModelRequest(agent, summaryMessages, summarySignal), summaryStreamFn));
|
|
20407
|
-
if (!compaction.compacted || !compaction.piMessages) return;
|
|
20642
|
+
if (!compaction.compacted || !compaction.piMessages) return false;
|
|
20408
20643
|
priorPhaseUsage = addAgentTurnUsage(priorPhaseUsage, usageSinceCurrentBoundary(messages));
|
|
20409
20644
|
const replacement = [...compaction.piMessages];
|
|
20410
20645
|
const previousTurnStartMessageIndex = runResume.turnStartMessageIndex;
|
|
@@ -20415,16 +20650,12 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20415
20650
|
runResume.setTurnStartMessageIndex(previousTurnStartMessageIndex);
|
|
20416
20651
|
throw error;
|
|
20417
20652
|
}
|
|
20418
|
-
|
|
20653
|
+
setAgentHistory(replacement);
|
|
20419
20654
|
nextInputAfterReplacement.replaced(mode, getAgentContextCompactionTriggerTokens(activeModelId));
|
|
20420
20655
|
runResume.setBeforeMessageCount(replacement.length);
|
|
20421
20656
|
runResume.adoptCommittedBoundary(replacement);
|
|
20422
20657
|
if (clearSteeringQueueOnCommit && pendingMessages?.length) agent.clearSteeringQueue();
|
|
20423
|
-
return
|
|
20424
|
-
systemPrompt: baseInstructions,
|
|
20425
|
-
messages: replacement,
|
|
20426
|
-
tools: agent.state.tools
|
|
20427
|
-
} };
|
|
20658
|
+
return true;
|
|
20428
20659
|
};
|
|
20429
20660
|
/**
|
|
20430
20661
|
* Request a background summary when the model call that just ended was at
|
|
@@ -20459,7 +20690,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20459
20690
|
await durability.drainSteeringMessages(async (messages) => {
|
|
20460
20691
|
const piMessages = messages.map(buildSteeringPiMessage);
|
|
20461
20692
|
if (piMessages.length === 0) return;
|
|
20462
|
-
await runResume.requireDurableInputCheckpoint([...
|
|
20693
|
+
await runResume.requireDurableInputCheckpoint([...currentAgentMessages(), ...piMessages], messages.map((message) => message.provenance));
|
|
20463
20694
|
committedInstructionProvenance.push(...messages.map((message) => message.provenance));
|
|
20464
20695
|
for (const message of messages) {
|
|
20465
20696
|
const text = message.text.trim();
|
|
@@ -20485,13 +20716,52 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20485
20716
|
});
|
|
20486
20717
|
const toolBatchStats = createToolBatchStats();
|
|
20487
20718
|
let setAgentSpanAttributes;
|
|
20719
|
+
let messagesChanged = false;
|
|
20720
|
+
/**
|
|
20721
|
+
* Do Junior's work after a model call and its tool batch, before Pi polls
|
|
20722
|
+
* steering. Pi awaits this listener after every model call. Pi turns its
|
|
20723
|
+
* errors into error turns, so the caller keeps them for the step.
|
|
20724
|
+
*/
|
|
20725
|
+
const finishModelStep = async (event, runSignal) => {
|
|
20726
|
+
if (event.toolResults.length > 0) {
|
|
20727
|
+
cacheWarming.toolsReturned();
|
|
20728
|
+
await requireConversationLease("save");
|
|
20729
|
+
await runResume.persistSafeBoundary(currentAgentMessages());
|
|
20730
|
+
}
|
|
20731
|
+
if (runSignal?.aborted || isAssistantMessage(event.message) && (event.message.stopReason === "error" || event.message.stopReason === "aborted")) return;
|
|
20732
|
+
await durability.checkStop?.();
|
|
20733
|
+
signal?.throwIfAborted();
|
|
20734
|
+
const boundary = await withSpan("agent.step.prepare", "agent.step.prepare", {}, async () => {
|
|
20735
|
+
const contextUpdated = await repositoryInstructionsContext.applyUpdate(currentAgentMessages());
|
|
20736
|
+
const pendingMessages = await drainSteeringMessages();
|
|
20737
|
+
const runEnded = pendingMessages.length === 0 && event.toolResults.every((result) => terminatingToolCallIds.has(result.toolCallId));
|
|
20738
|
+
if (runEnded) await requestBackgroundCompactionAfterModelCall();
|
|
20739
|
+
return {
|
|
20740
|
+
contextUpdated,
|
|
20741
|
+
pendingMessages,
|
|
20742
|
+
runEnded
|
|
20743
|
+
};
|
|
20744
|
+
});
|
|
20745
|
+
messagesChanged = boundary.contextUpdated;
|
|
20746
|
+
const yieldError = runResume.prepareYieldIfDue(currentAgentMessages());
|
|
20747
|
+
if (yieldError) throw yieldError;
|
|
20748
|
+
if (boundary.runEnded) return;
|
|
20749
|
+
if (await applyActiveContextCompaction(currentAgentMessages(), runSignal, boundary.pendingMessages, true)) {
|
|
20750
|
+
messagesChanged = true;
|
|
20751
|
+
return;
|
|
20752
|
+
}
|
|
20753
|
+
await requestBackgroundCompactionAfterModelCall();
|
|
20754
|
+
};
|
|
20488
20755
|
agent = new Agent({
|
|
20489
20756
|
getApiKey: getGatewayApiKey,
|
|
20490
20757
|
sessionId: conversationId,
|
|
20491
|
-
streamFn: createTracedStreamFn({
|
|
20758
|
+
streamFn: withAgentRequest(createTracedStreamFn({
|
|
20492
20759
|
conversationPrivacy,
|
|
20493
20760
|
base: cacheWarming.wrap(streamFn),
|
|
20494
20761
|
endAttributes: (message) => nextInputAfterReplacement.attributes(lastRequestInputSize([message]))
|
|
20762
|
+
}), {
|
|
20763
|
+
systemPrompt: baseInstructions,
|
|
20764
|
+
tools: wiring.agentTools
|
|
20495
20765
|
}),
|
|
20496
20766
|
steeringMode: "all",
|
|
20497
20767
|
beforeToolCall: async ({ assistantMessage, context, toolCall }) => {
|
|
@@ -20557,32 +20827,13 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20557
20827
|
}
|
|
20558
20828
|
return override;
|
|
20559
20829
|
},
|
|
20560
|
-
prepareNextTurnWithContext: async (nextTurn
|
|
20561
|
-
|
|
20562
|
-
|
|
20563
|
-
|
|
20564
|
-
|
|
20565
|
-
|
|
20566
|
-
|
|
20567
|
-
const pendingMessages = await drainSteeringMessages();
|
|
20568
|
-
if (nextTurn.toolResults.every((result) => terminatingToolCallIds.has(result.toolCallId)) && pendingMessages.length === 0) {
|
|
20569
|
-
await requestBackgroundCompactionAfterModelCall();
|
|
20570
|
-
return contextUpdate;
|
|
20571
|
-
}
|
|
20572
|
-
const capacityUpdate = await applyActiveContextCompaction(contextUpdate ? currentAgentMessages() : nextTurn.context.messages, hookSignal, pendingMessages, true);
|
|
20573
|
-
if (!capacityUpdate) await requestBackgroundCompactionAfterModelCall();
|
|
20574
|
-
return capacityUpdate ? {
|
|
20575
|
-
...contextUpdate,
|
|
20576
|
-
...capacityUpdate
|
|
20577
|
-
} : contextUpdate;
|
|
20578
|
-
});
|
|
20579
|
-
const yieldError = runResume.prepareYieldIfDue(currentAgentMessages());
|
|
20580
|
-
if (yieldError) throw yieldError;
|
|
20581
|
-
return stepUpdate;
|
|
20582
|
-
} catch (error) {
|
|
20583
|
-
pendingPiHookError ??= error instanceof Error ? error : new Error(String(error));
|
|
20584
|
-
throw error;
|
|
20585
|
-
}
|
|
20830
|
+
prepareNextTurnWithContext: async (nextTurn) => {
|
|
20831
|
+
if (!messagesChanged) return;
|
|
20832
|
+
messagesChanged = false;
|
|
20833
|
+
return { context: {
|
|
20834
|
+
...nextTurn.context,
|
|
20835
|
+
messages: writeAgentHistory(nextTurn.context.messages, currentAgentMessages())
|
|
20836
|
+
} };
|
|
20586
20837
|
},
|
|
20587
20838
|
initialState: {
|
|
20588
20839
|
systemPrompt: baseInstructions,
|
|
@@ -20591,15 +20842,12 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20591
20842
|
tools: wiring.agentTools
|
|
20592
20843
|
}
|
|
20593
20844
|
});
|
|
20594
|
-
const unsubscribe = agent.subscribe((event) => {
|
|
20845
|
+
const unsubscribe = agent.subscribe((event, runSignal) => {
|
|
20595
20846
|
if (event.type === "tool_execution_start") return recordParentToolExecutionStart(event);
|
|
20596
|
-
if (event.type === "turn_end"
|
|
20597
|
-
|
|
20598
|
-
|
|
20599
|
-
|
|
20600
|
-
throw error;
|
|
20601
|
-
});
|
|
20602
|
-
}
|
|
20847
|
+
if (event.type === "turn_end") return finishModelStep(event, runSignal).catch((error) => {
|
|
20848
|
+
pendingPiHookError ??= error instanceof Error ? error : new Error(String(error));
|
|
20849
|
+
throw error;
|
|
20850
|
+
});
|
|
20603
20851
|
if (event.type === "message_end" && isAssistantMessage(event.message)) {
|
|
20604
20852
|
const message = event.message;
|
|
20605
20853
|
const delivery = message.stopReason === "error" || message.stopReason === "aborted" ? void 0 : deliverAssistantMessage(message);
|
|
@@ -20611,15 +20859,15 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20611
20859
|
});
|
|
20612
20860
|
let newMessages = [];
|
|
20613
20861
|
const turnStartIndex = () => existingSessionRecord?.turnStartMessageIndex ?? runResume.turnStartMessageIndex ?? runResume.beforeMessageCount;
|
|
20614
|
-
const turnMessages = () =>
|
|
20862
|
+
const turnMessages = () => currentAgentMessages().slice(turnStartIndex());
|
|
20615
20863
|
try {
|
|
20616
20864
|
if (resumedFromSessionRecord) {
|
|
20617
|
-
|
|
20865
|
+
setAgentHistory(shouldPromptAgent ? promptHistoryMessages : existingSessionRecord.piMessages);
|
|
20618
20866
|
runResume.setTurnStartMessageIndex(existingSessionRecord.turnStartMessageIndex);
|
|
20619
|
-
runResume.adoptCommittedBoundary(
|
|
20620
|
-
} else if (promptHistoryMessages.length > 0)
|
|
20621
|
-
runResume.setBeforeMessageCount(
|
|
20622
|
-
if (shouldPromptAgent) runResume.setTurnStartMessageIndex(
|
|
20867
|
+
runResume.adoptCommittedBoundary(currentAgentMessages());
|
|
20868
|
+
} else if (promptHistoryMessages.length > 0) setAgentHistory(promptHistoryMessages);
|
|
20869
|
+
runResume.setBeforeMessageCount(currentAgentMessages().length);
|
|
20870
|
+
if (shouldPromptAgent) runResume.setTurnStartMessageIndex(currentAgentMessages().length);
|
|
20623
20871
|
const authPauseOutcome = await withSpan(`invoke_agent ${botConfig.userName}`, "gen_ai.invoke_agent", spanContext, async (setInvokeAgentSpanAttributes) => {
|
|
20624
20872
|
setAgentSpanAttributes = setInvokeAgentSpanAttributes;
|
|
20625
20873
|
if (behavior.gated && readTurnAnswer(turnMessages())) return;
|
|
@@ -20636,17 +20884,13 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20636
20884
|
};
|
|
20637
20885
|
if (shouldPromptAgent) {
|
|
20638
20886
|
if (await runResume.requireDurableInputCheckpoint([
|
|
20639
|
-
...
|
|
20887
|
+
...currentAgentMessages(),
|
|
20640
20888
|
...contextMessage ? [contextMessage] : [],
|
|
20641
20889
|
freshPromptMessage
|
|
20642
20890
|
], [turnStartProvenance])) await runResume.commitInput();
|
|
20643
20891
|
}
|
|
20644
|
-
if (contextMessage)
|
|
20645
|
-
if (!shouldPromptAgent) await repositoryInstructionsContext.applyUpdate(
|
|
20646
|
-
messages: agent.state.messages,
|
|
20647
|
-
systemPrompt: agent.state.systemPrompt,
|
|
20648
|
-
tools: agent.state.tools
|
|
20649
|
-
});
|
|
20892
|
+
if (contextMessage) setAgentHistory([...currentAgentMessages(), contextMessage]);
|
|
20893
|
+
if (!shouldPromptAgent) await repositoryInstructionsContext.applyUpdate(currentAgentMessages());
|
|
20650
20894
|
/** Race one provider operation against the turn deadline and abort its owner. */
|
|
20651
20895
|
const runAgentStep = async (run, abortRun = () => agent.abort()) => {
|
|
20652
20896
|
let timeoutId;
|
|
@@ -20720,11 +20964,11 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20720
20964
|
};
|
|
20721
20965
|
let run;
|
|
20722
20966
|
const compactionAbortController = new AbortController();
|
|
20723
|
-
const
|
|
20967
|
+
const compacted = await runAgentStep(applyActiveContextCompaction(currentAgentMessages(), compactionAbortController.signal, shouldPromptAgent ? [{
|
|
20724
20968
|
message: freshPromptMessage,
|
|
20725
20969
|
provenance: turnStartProvenance
|
|
20726
20970
|
}] : void 0, false, Boolean(contextMessage), "blocking"), () => compactionAbortController.abort());
|
|
20727
|
-
run = shouldPromptAgent && !
|
|
20971
|
+
run = shouldPromptAgent && !compacted ? agent.prompt(freshPromptMessage) : agent.continue();
|
|
20728
20972
|
discardedRetryUsage = void 0;
|
|
20729
20973
|
let actionConfirmationRetryUsed = false;
|
|
20730
20974
|
let answerReminderUsed = !behavior.gated;
|
|
@@ -20732,8 +20976,8 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20732
20976
|
let refusalFallbackUsed = false;
|
|
20733
20977
|
let emptyOutputAttempt = 0;
|
|
20734
20978
|
const prepareRetry = async (messages) => {
|
|
20735
|
-
discardedRetryUsage = addAgentTurnUsage(discardedRetryUsage, getDiscardedRetryUsage(
|
|
20736
|
-
|
|
20979
|
+
discardedRetryUsage = addAgentTurnUsage(discardedRetryUsage, getDiscardedRetryUsage(currentAgentMessages(), messages));
|
|
20980
|
+
setAgentHistory(messages);
|
|
20737
20981
|
await runResume.persistSafeBoundary(messages);
|
|
20738
20982
|
signal?.throwIfAborted();
|
|
20739
20983
|
};
|
|
@@ -20742,7 +20986,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20742
20986
|
await runAgentStep(run);
|
|
20743
20987
|
if (assistantMessageDeliveryError) throw assistantMessageDeliveryError;
|
|
20744
20988
|
signal?.throwIfAborted();
|
|
20745
|
-
newMessages =
|
|
20989
|
+
newMessages = currentAgentMessages().slice(runResume.beforeMessageCount);
|
|
20746
20990
|
const outputMessages = newMessages.filter(isAssistantMessage);
|
|
20747
20991
|
const outputMessagesAttribute = serializeGenAiAttribute(conversationPrivacy === "public" ? outputMessages.map(toCanonicalOutputMessage) : void 0);
|
|
20748
20992
|
const lastAssistant = outputMessages.at(-1);
|
|
@@ -20761,17 +21005,17 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20761
21005
|
runResume.captureResumeSnapshot(runResume.getResumeSnapshot(currentAgentMessages()));
|
|
20762
21006
|
throw pendingAuthPause;
|
|
20763
21007
|
}
|
|
20764
|
-
const confirmationRetry = actionConfirmationRetryUsed ? void 0 : actionConfirmationRetryMessages(
|
|
21008
|
+
const confirmationRetry = actionConfirmationRetryUsed ? void 0 : actionConfirmationRetryMessages(currentAgentMessages());
|
|
20765
21009
|
if (confirmationRetry) {
|
|
20766
21010
|
actionConfirmationRetryUsed = true;
|
|
20767
21011
|
await prepareRetry(confirmationRetry);
|
|
20768
21012
|
run = agent.continue();
|
|
20769
21013
|
continue;
|
|
20770
21014
|
}
|
|
20771
|
-
const answerReminder = answerReminderUsed || failedAnswerCallsPastLimit >= MAX_FAILED_ANSWER_CALLS_PAST_LIMIT ? void 0 : remindMissingAnswer(
|
|
21015
|
+
const answerReminder = answerReminderUsed || failedAnswerCallsPastLimit >= MAX_FAILED_ANSWER_CALLS_PAST_LIMIT ? void 0 : remindMissingAnswer(currentAgentMessages(), turnStartIndex());
|
|
20772
21016
|
if (answerReminder) {
|
|
20773
21017
|
answerReminderUsed = true;
|
|
20774
|
-
|
|
21018
|
+
setAgentHistory(answerReminder);
|
|
20775
21019
|
await runResume.persistSafeBoundary(answerReminder);
|
|
20776
21020
|
logWarn("agent.turn.answer.reminded", {});
|
|
20777
21021
|
run = agent.continue();
|
|
@@ -20780,7 +21024,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20780
21024
|
const emptyOutputContinuation = nextEmptyOutputContinuation({
|
|
20781
21025
|
attempt: emptyOutputAttempt,
|
|
20782
21026
|
lastAssistant,
|
|
20783
|
-
messages:
|
|
21027
|
+
messages: currentAgentMessages()
|
|
20784
21028
|
});
|
|
20785
21029
|
if (emptyOutputContinuation.kind === "retry") {
|
|
20786
21030
|
emptyOutputAttempt += 1;
|
|
@@ -20793,13 +21037,13 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20793
21037
|
const providerRetry = nextProviderRetry({
|
|
20794
21038
|
attempt: providerRetryAttempt,
|
|
20795
21039
|
failure: lastAssistant,
|
|
20796
|
-
messages:
|
|
21040
|
+
messages: currentAgentMessages()
|
|
20797
21041
|
});
|
|
20798
21042
|
if (!providerRetry) {
|
|
20799
21043
|
const refusalFallback = refusalFallbackUsed ? void 0 : nextRefusalFallback({
|
|
20800
21044
|
failure: lastAssistant,
|
|
20801
21045
|
fallbackModelId: botConfig.refusalFallbackModelId,
|
|
20802
|
-
messages:
|
|
21046
|
+
messages: currentAgentMessages()
|
|
20803
21047
|
});
|
|
20804
21048
|
if (!refusalFallback) break;
|
|
20805
21049
|
refusalFallbackUsed = true;
|
|
@@ -20852,7 +21096,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20852
21096
|
userInput,
|
|
20853
21097
|
toolCalls,
|
|
20854
21098
|
sandboxRef: wiring.getSandboxRef(),
|
|
20855
|
-
piMessages:
|
|
21099
|
+
piMessages: currentAgentMessages(),
|
|
20856
21100
|
durationMs: Date.now() - replyStartedAtMs,
|
|
20857
21101
|
generatedFileCount: generatedFiles.length,
|
|
20858
21102
|
shouldTrace,
|
|
@@ -20875,7 +21119,7 @@ async function executeAgentRunInPrivacyContext(run, conversationKind, conversati
|
|
|
20875
21119
|
if (resume?.timedOut && acceptedToolFreeAssistant && agent) {
|
|
20876
21120
|
await requireConversationLease("save");
|
|
20877
21121
|
await recordActiveMcpProviders();
|
|
20878
|
-
const piMessages =
|
|
21122
|
+
const piMessages = readAgentHistory(agent.state.messages);
|
|
20879
21123
|
return {
|
|
20880
21124
|
status: "completed",
|
|
20881
21125
|
result: buildTurnResult({
|
|
@@ -20960,7 +21204,7 @@ function createAgentRunner(execute, options) {
|
|
|
20960
21204
|
}
|
|
20961
21205
|
};
|
|
20962
21206
|
const loadStoredAttachments = async (attachments) => {
|
|
20963
|
-
const { loadInputAttachments } = await import("./model-input-
|
|
21207
|
+
const { loadInputAttachments } = await import("./model-input-CBp-p24N.js").then((n) => n.r);
|
|
20964
21208
|
const storage = nextRun.environment?.attachmentStorage;
|
|
20965
21209
|
if (!storage) throw new Error("Attachment storage is unavailable.");
|
|
20966
21210
|
return await loadInputAttachments({
|
|
@@ -20984,4 +21228,4 @@ function createAgentRunner(execute, options) {
|
|
|
20984
21228
|
return await execute(nextRun, streamFn);
|
|
20985
21229
|
} };
|
|
20986
21230
|
}
|
|
20987
|
-
export {
|
|
21231
|
+
export { effectiveTaskOutcomes as $, parseSlackReviewItemClick as A, ingestEvent as At, activateViewerAutomationVersion as B, renderBlockText as C, markConversationRead as Ct, syncReviewItemSlackCards as D, throwApiError as Dt, readSlackReviewItemCardConversationId as E, jsonResponse as Et, resolveSlackChannelIdFromMessage as F, toolInvocationDestination as Ft, ViewerTaskNotFoundError as G, deleteViewerTask as H, resolveSlackChannelIdFromThreadId as I, shouldEmitDevAgentTrace as It, readViewerAutomationRuns as J, readConversationSourceTask as K, resolveDestinationVisibility as L, parseSlackUserInputSubmission as M, missingAutomationSkillReason as Mt, parseSlackThreadId as N, RetryableDeliveryError as Nt, SLACK_REVIEW_ITEM_VIEW_ID as O, previewOriginBelongsTo as Ot, readSlackRawMessageContext as P, actorFromRun as Pt, AutomationEditError as Q, logScheduledAutomationRunSkipped as R, renderAttachmentText as S, conversationReadPositionQuery as St, createSlackReviewItemShow as T, emptyResponse as Tt, readViewerAutomationEdit as U, changeViewerAutomationLifecycle as V, updateViewerAutomation as W, readViewerAutomationVersions as X, readViewerAutomationSummary as Y, readViewerAutomations as Z, readAttachmentContent as _, collectAttachmentGarbage as _t, buildAuthPauseResponse as a, appendAndEnqueueWebMessage as at, unpublishedArtifactHeaders as b, storeAttachment as bt, deleteMcpAuthSessionsForUserProvider as c, createConversationId as ct, getMcpAuthSession as d, resolveConversationDestination as dt, listOwnedWatches as et, getMcpStoredOAuthCredentials as f, AttachmentUploadError as ft, AttachmentDownloadError as g, writeAttachmentUpload as gt, readStats as h, verifyAttachmentUploads as ht, measureTurnCompactionWait as i, acceptsWebMessages as it, parseSlackReviewItemFormTarget as j, findAutomationSkill as jt, buildSlackReviewItemModal as k, processWorkspaceSnapshotJob as kt, deleteMcpServerSessionId as l, recordWebConversationActivity as lt, latestProgressStatus as m, createAttachmentUpload as mt, executeAgentRun as n, renderReviewItemMessage as nt, finalizeMcpAuthorization as o, conversationTurnIdForMessage as ot, putMcpStoredOAuthCredentials as p, collectAttachmentUploadGarbage as pt, readViewerAutomationExecutions as q, processBackgroundCompaction as r, reviewItemChangeRecord as rt, deleteMcpAuthSession as s, createAndEnqueueConversation as st, createAgentRunner as t, deliverReviewItemChange as tt, deleteMcpStoredOAuthCredentials as u, webActorFromUser as ut, publicArtifactHeaders as v, readLiveAttachment as vt, parseSlackMessageReference as w, reportConversationRead as wt, setConversationSubscription as x, archiveConversation as xt, readPublicArtifact as y, requestAttachmentDeletion as yt, scheduledAutomationRunAttributes as z };
|