@sentry/junior 0.305.0 → 0.307.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-context-BpvbUki8.js → adapter-context-B69WPn6b.js} +2 -2
- package/dist/{admin-CoDt35ny.js → admin-nCJXMgkp.js} +2 -2
- package/dist/{agent-runner-C5d6rY5g.js → agent-runner-DdFcxAxG.js} +463 -303
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -8
- package/dist/api.d.ts +19 -4
- package/dist/api.js +437 -310
- package/dist/{app-Cs157Zc5.d.ts → app-EZur8cVC.d.ts} +12 -3
- package/dist/app.d.ts +2 -2
- package/dist/app.js +532 -439
- package/dist/background-compaction-queue-BhEe4UfU.js +231 -0
- package/dist/{briefs-BRdznF7c.js → briefs-Dl9lxi7J.js} +3 -3
- package/dist/{catalog-runtime-J52Tej47.js → catalog-runtime-OXrv2Ewn.js} +1 -1
- package/dist/cli/chat.d.ts +1 -1
- package/dist/cli/chat.js +17 -16
- package/dist/cli/check.js +58 -48
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.d.ts +1 -1
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +2 -2
- package/dist/cli/upgrade.js +3 -8
- package/dist/{config-CBZp0udd.js → config-362yMSIz.js} +183 -49
- package/dist/{connections-BYmuJ6Vm.js → connections-BJv3EjmB.js} +10 -8
- package/dist/{continue-in-slack-Cvot6S38.js → continue-in-slack-CFEevC7z.js} +5 -5
- package/dist/{conversation-BOqdRtUx.js → conversation--f85g4zL.js} +132 -132
- package/dist/{conversation-feed-CgpgP7yi.js → conversation-feed-BNs9KiqC.js} +1 -1
- package/dist/{conversation-privacy-D2pOzBNl.js → conversation-privacy-Tjj5P2W6.js} +1 -1
- package/dist/{conversation-turn-CI8WDpnK.js → conversation-turn-DU0_WDAr.js} +26 -72
- package/dist/{credential-sync-COqnZ1Dx.js → credential-sync-D6aFARKE.js} +28 -27
- package/dist/{db-DU84dCVu.js → db-Bcbd9zQc.js} +226 -18
- package/dist/{db-zbN5ZV_o.d.ts → db-C41UgdBj.d.ts} +1 -1
- package/dist/{executor-CFyrgOu1.js → executor-DBMBrpNV.js} +137 -33
- package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
- package/dist/{install-CQ76CfRw.js → install-CgoAbzfF.js} +2 -2
- package/dist/instrumentation.js +2 -2
- package/dist/{lineage-DLd2UxVP.js → lineage-CsZDmz3e.js} +2 -2
- package/dist/{logging-BPNTQVFu.js → logging-CHCuQ5iz.js} +1 -1
- package/dist/{message-BWJLeQ5e.js → message-B8vCbZZB.js} +8 -8
- package/dist/{model-input-DoM9Ht-d.js → model-input-Xluiy-1W.js} +3 -3
- package/dist/nitro.d.ts +2 -2
- package/dist/nitro.js +3 -4
- package/dist/{oauth-callback-server-DeHbnAQl.js → oauth-callback-server-BUuNvfvu.js} +2 -2
- package/dist/{oauth-relay-DAmfVmJu.js → oauth-relay-DGAZzg9m.js} +1 -1
- package/dist/{plugins-B_0Cr0MO.d.ts → plugins-fBrz8PCV.d.ts} +2 -0
- package/dist/{projection-CcFBVFUo.js → projection-xPpvqexa.js} +13423 -11432
- package/dist/{prompt-C5LREK2p.js → prompt-D8u4jFs_.js} +15 -7
- package/dist/{registry-BjZZqKqi.js → registry-D20hG3r6.js} +19 -9
- package/dist/{resolve-CeJgXuH1.js → resolve-BhCySRCW.js} +3 -3
- package/dist/{result-icDrueyB.js → result-DddO63S9.js} +13 -11
- package/dist/{runner-nVfMkMMB.js → runner-DQR9vYce.js} +13 -15
- package/dist/{sandbox-egress-signals-H9vQ5qRf.js → sandbox-egress-signals-DFlNUOnK.js} +1 -1
- package/dist/{automation-CuA3yEcD.js → schedule-BG1tEbRF.js} +380 -8
- package/dist/{schema-CKcu-IK6.d.ts → schema-CRXcj4fj.d.ts} +420 -143
- package/dist/{schema-Bx0Mlo32.js → schema-D4jdesIu.js} +62 -8
- package/dist/{service-account-DU5865XA.js → service-account-Bv5QwrEq.js} +8 -6
- package/dist/{service-account-Dw06p3zm.js → service-account-CNfycv0z.js} +3 -3
- package/dist/{session-stop-uotLtp4g.js → session-stop-BDdwyZaa.js} +878 -171
- package/dist/{skills-Bex1EaO5.js → skills-63i1Bcv1.js} +32 -28
- package/dist/{slack-conversation-unfurl-EPG3riWF.js → slack-conversation-unfurl-DtpBUlUu.js} +10 -9
- package/dist/{spawn-CoD3vDuS.js → spawn-mwimEY9_.js} +6 -6
- package/dist/{state-nCR4Muhn.js → state-BBn9L6gC.js} +4 -4
- package/dist/{stop-BFVd0P0m.js → stop-Da-Ug7tg.js} +172 -239
- package/dist/{store-Ca6G962n.js → store-CdWg2r2L.js} +5 -5
- package/dist/{background-compaction-queue-BTqMIfTA.js → task-queue-BcjAYWyB.js} +164 -180
- package/dist/{task-runner-xsOPIxCZ.js → task-runner-CoXmMlsW.js} +13 -11
- package/dist/{thread-context-BOvZhsKK.js → thread-context-ZPGqOjW7.js} +8 -91
- package/dist/turn-session-routing-DFYak28Q.js +263 -0
- package/dist/{turn-user-message-BrhuyYrH.js → turn-user-message-B1S8nOnG.js} +3 -3
- package/dist/users-DDbENg-I.js +181 -0
- package/dist/{validation-BnY9K5WB.js → validation-fl21ps-k.js} +1 -1
- package/dist/{version-qROlRQGF.js → version-DCdMMx_0.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-CxUiOraX.js → viewer-DN_xzVKj.js} +3 -3
- package/dist/{warmup--Gkz7iB-.js → warmup-CxhEhm71.js} +842 -532
- package/dist/{web-message-id-lNodcCOI.js → web-message-id-BT8Mg8LL.js} +16 -1
- package/dist/{worker-DJ8d9fmD.js → worker-Btb1SB5h.js} +8 -7
- package/migrations/0114_plan_items.sql +22 -0
- package/migrations/0115_automation_creator_slack_index.sql +1 -0
- package/migrations/0116_conversation_event_search.sql +25 -0
- package/migrations/0117_automation_last_run.sql +46 -0
- package/migrations/0118_automation_last_run_index.sql +1 -0
- package/migrations/0119_money_micro_usd.sql +29 -0
- package/migrations/0120_conversation_cost_micro_usd.sql +8 -0
- package/migrations/meta/0114_snapshot.json +5203 -0
- package/migrations/meta/0115_snapshot.json +5225 -0
- package/migrations/meta/0116_snapshot.json +5388 -0
- package/migrations/meta/0117_snapshot.json +5413 -0
- package/migrations/meta/0118_snapshot.json +5428 -0
- package/migrations/meta/0119_snapshot.json +5441 -0
- package/migrations/meta/0120_snapshot.json +5441 -0
- package/migrations/meta/_journal.json +49 -0
- package/package.json +10 -9
- package/dist/queue-B2AAL3ym.js +0 -115
- package/dist/schedule-cP0AACm1.js +0 -344
- package/dist/secrets-DHaJ5TTn.js +0 -18
- package/dist/task-queue-BLPZU6kC.js +0 -89
- package/dist/turn-session-routing-2bW2qfeb.js +0 -1792
|
@@ -1,37 +1,38 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
-
import { $ as
|
|
3
|
-
import {
|
|
4
|
-
import { E as withSpan, G as normalizeIdentityEmail, J as toOptionalString, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, x as setSpanStatus, z as getDeploymentId } from "./logging-
|
|
2
|
+
import { $ as pauseLostWorkerTurn, $c as readAutomationExecutions, $n as getTerminalAssistantMessages, Ac as hasEventCatalogEntries, B as PluginCredentialFailureError, Bc as readAutomationVersion, Bi as updateWorkspace, Bs as slackMention, Ea as workspaceRepoCheckoutPath, En as createPluginHookRunner, Fa as SANDBOX_WORKSPACE_ROOT, Fc as requireEventIdentifier, Fi as deleteWorkspace, Fr as insertReviewItem, Gc as ToolInputError, Gi as setWorkspaceSnapshotBuild, Gn as seqIn, Gr as canReadReviewItem, Hi as invalidateReadySnapshot, Hr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, Ic as requireValidEventTrigger, Ii as getWorkspace, Io as defaultTimezone, J as clearPendingAuth, Ji as isStale, Jn as eventExcerpt, Jo as getDispatchInputMessageId, Js as parseScheduledAutomationRow, Ki as create, Kn as SEARCHABLE_EVENT_TYPES, Ks as deleteScheduledAutomation, Lc as automationDefinition, Li as getWorkspaceByName, Ma as SANDBOX_REPOS_ROOT, Mc as registeredEventTriggerProblems, Mo as saveObjectAnnotations, Mr as dismissOpenReviewItems, Ms as sleep, Na as SANDBOX_SCRATCH_ROOT, Nc as registeredEventTypeSchema, Nn as getPlugins, No as createPluginAnnotations, Nr as getOpenReviewItemByDedupeKey, Oc as eventNamespaceSchema, Oo as searchConversations, Os as normalizeSlackConversationId, Pc as registeredResourceTypeSchema, Pi as createWorkspace, Pn as getStaticPluginToolDefinitions, Pr as getReviewItem, Q as lostWorkerBeforeFirstSave, Qc as readAutomationExecutionSummaries, Ri as listWorkspaces, Si as listWatches, Ss as getFilePermalink, Tc as describeRegisteredEventTrigger, Ts as isConversationScopedChannel, Ua as createPluginLogger, Uc as automationRevision, Ui as loadSnapshotsForProfile, Un as lexemesSql, Vc as sameDefinitionValue, Vi as WorkspaceValidationError, Vr as updateReviewItemContent, W as AuthorizationFlowDisabledError, Wa as canAccessConversation, Wc as requireAutomationRevision, Wi as setWorkspaceSnapshot, Wn as searchedEventTextSql, Wr as canAgentChangeReviewItem, Xc as readAutomationExecutionStatusDays, Xi as getSandboxProvider, Xr as requireReviewItemAssignees, Xs as saveScheduledAutomation, Yc as readAutomationExecutionByConversationId, Yn as excerptTerms, Yo as getDispatchRecord, Yr as readReviewItemAgentScope, Z as loadTurnCheckpoint, Zc as readAutomationExecutionStatusHours, Zr as requireReviewItemLinks, _c as listDeletedEventAutomationsCreatedBy, _i as createWatch, ai as resolveAssignees, al as fallbackShortTitle, at as getTurnRecord, bc as setEventAutomationStatus, bi as getWatch, bo as readLiveAttachment, bs as SlackActionError, ci as getSlackToolContext, cn as getAssistantReplyText, cs as getSlackMessagePermalink, da as WorkspaceSnapshotNotReadyError, di as RESOURCE_WATCH_TOOL_SOURCE, dn as findLegacyNoReplyMarker, ec as getDashboardConversationLink, el as readAutomationRowStats, et as saveTurnCheckpoint, fi as STOP_WATCHING_TOOL_NAME, fn as isLegacyNoReplyMarker, gi as createTimerWatch, gn as REPORT_BLOCKED_TOOL_NAME, ii as resolveAssignee, in as readTurnAnswer, jc as registeredEventMatchSchema, jo as embedConversationQuery, js as withSlackRetries, k as markConversationMessage, kc as eventWatchUnavailable, kr as closeReviewItem, li as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, lo as FORK_INSTRUCTIONS, ls as openSlackDirectMessage, mc as deleteEventAutomation, mi as cancelWatch, ni as activeParticipantUserIds, nn as REPLY_TOOL_NAME, oc as getDashboardTaskLink, ol as resolveTaskTitle, on as replyTextSchema, pa as isWorkspaceSnapshotNotReadyError, po as matchSlackAttachments, qa as readConversationAccessFromSql, qc as emptyAutomationRunWindows, qn as callsToolSql, qo as getDispatchIdForConversation, ri as automationCreatorUserId, rt as failTurnRecord, s as openConversationProjection, sa as isAbortError, st as recordTurnSummary, ti as EVERYONE_ASSIGNEE, tl as readAutomationRuns, tn as isTurnExecutionLimitExceededError, tt as abandonTurnRecord, ui as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, ul as createPluginCache, un as NO_REPLY_TOOL_NAME, uo as loadForkHistory, v as hydrateConversationMessages, va as createSandboxEgressCredentialToken, vc as parseEventAutomationRow, vi as deliverWatch, wa as SANDBOX_RUNTIME, wc as automationEventCatalog, wi as turnEvents, ws as getSlackClient, xa as buildSandboxEgressNetworkPolicy, xi as isQuietEvent, xn as getOAuthAccountProviders, xo as recordUploadedAttachment, xs as downloadPrivateSlackFile, yc as saveEventAutomation, yi as findMatchingWatches, zc as listAutomationVersions, zr as searchReviewItems } from "./projection-xPpvqexa.js";
|
|
3
|
+
import { W as escapeClosingTags, X as renderTag, _ as TURN_REASONING_LEVELS, i as getChatConfig, k as resolveGatewayModel, lt as bufferBody, n as botConfig, ot as isProviderRetryError } from "./config-362yMSIz.js";
|
|
4
|
+
import { E as withSpan, G as normalizeIdentityEmail, J as toOptionalString, b as setSpanAttributes, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, x as setSpanStatus, z as getDeploymentId } from "./logging-CHCuQ5iz.js";
|
|
5
5
|
import { h as startSpan, n as captureMessage, u as sentry_exports } from "./sentry-CPbZjomA.js";
|
|
6
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
7
|
-
import {
|
|
8
|
-
import { A as agentTypeSchema,
|
|
9
|
-
import {
|
|
6
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-OXrv2Ewn.js";
|
|
7
|
+
import { Ct as workspaceSnapshotFinishedEvent, E as getAuthPausedConversationTurnId, F as EVENT_WAIT_MS, H as addConversationNote, I as addQuietEventNote, J as resolveEventAuthor, L as enqueueEventNotification, O as listActiveMailboxTurnSources, Q as maybePostAutomatedTurnLimitNotice, St as WORKSPACE_SNAPSHOT_READY_EVENT, Tt as buildDeploymentSystemPrompt, bt as slackChannelMessageTrigger, ct as resetAutomatedTurnLimit, f as buildSteeringPiMessage, ft as isExperimentalFeatureEnabled, g as withoutSavedSteeringMessages, gt as requireSlackChannelMessageScope, i as resumeStoppedConversationTree, k as listActiveMailboxTurns, lt as conversationSubtree, m as instructionForInputs, mt as getEventCatalog, n as isSkippedAfterConversationStop, nt as resolveEventMentions, r as markConversationsStopped, st as recordFinishedTurnForAutomatedLimit, t as getConversationStoppedAtMs, ut as conversationSubtreeColumns, v as saveUserCustomization, w as renderPlanAssignee, wt as workspaceSnapshotWatch, x as listPlanItems, xt as WORKSPACE_SNAPSHOT_FAILED_EVENT, y as changePlan, z as isEventMailboxMetadata } from "./session-stop-BDdwyZaa.js";
|
|
8
|
+
import { A as agentTypeSchema, N as briefLinkSchema, O as AGENT_TYPES, P as briefOutcomeStatusSchema, Y as removedCardSchema, j as formatAgentTypes, k as agentTypeInstructions } from "./conversation--f85g4zL.js";
|
|
9
|
+
import { B as compileScheduleIntent, F as eventAutomationTriggerSchema, H as toolScheduleIntentSchema, J as automationSkillNameSchema, K as getZonedDateTimeParts, Q as automationTaskText, U as weekdaySchema, W as getFirstRunAtMs, X as automationTaskDescription, Z as automationTaskSchema, m as automationListQuerySchema, q as isValidTimeZone, z as ScheduleIntentError } from "./schedule-BG1tEbRF.js";
|
|
10
10
|
import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, o as isUserActor, p as parseSlackUserId, u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
|
|
11
|
-
import { A as conversationKindFromRow, E as isTopLevelKind, I as resolveActorIdentityId, O as promptModeTurnTools, P as SYSTEM_IDENTITY_ID,
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
11
|
+
import { $ as getStateAdapter, A as conversationKindFromRow, E as isTopLevelKind, I as resolveActorIdentityId, O as promptModeTurnTools, P as SYSTEM_IDENTITY_ID, St as rootConversationIsArchived, T as isPersonInput, _ as readConversationTrees, a as getConversationStore, at as withLock, d as eventFromRow, et as getStateValues, ft as usdToMicroUsd, g as conversationDescendants, h as conversationAncestors, i as getConversationMessageSearchStore, it as fenceLock, k as turnBehavior, kt as sameDestination, o as getDb, r as getConversationEventStore, s as getSqlExecutor, v as setArchivedAt, wt as nextDetailVersion, x as userMessageQueries, xt as resolveRootConversationId } from "./db-Bcbd9zQc.js";
|
|
12
|
+
import { A as juniorConversationEvents, B as juniorUsers, C as juniorConversationEventLexemes, F as juniorAttachmentUploads, I as juniorAttachments, R as juniorConversations, V as juniorDestinations, b as juniorConversationReadPositions, g as juniorStats, h as juniorAutomations, p as juniorAutomationRuns, v as juniorAgentBindings, w as juniorConversationEventEmbeddings, x as juniorConversationParticipants, y as juniorAgentInvocations, z as juniorIdentities } from "./executor-DBMBrpNV.js";
|
|
13
|
+
import { t as discoverSkills } from "./skills-63i1Bcv1.js";
|
|
14
|
+
import { D as isAgentInvocationResultEventType, F as sumUtcHoursIntoSixHours, O as apiErrorSchema, S as AGENT_INVOCATION_EVENT_NAMESPACE, b as SELF_PLAN_ASSIGNEE, c as formatUserInputAnswer, d as userInputRequestSchema, g as USER_CUSTOMIZATION_MAX_CHARS, h as isVisionImageMediaType, m as detectImageMediaType, n as AGENT_INVOCATION_MAILBOX_STATUSES, r as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, t as webMessageId, v as userCustomizationTextSchema, w as AGENT_PARENT_MESSAGE_EVENT_TYPE, x as isOpenPlanItemStatus, y as PLAN_ITEM_STATUSES } from "./web-message-id-BT8Mg8LL.js";
|
|
15
|
+
import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-DN_xzVKj.js";
|
|
16
|
+
import { A as getAgentInvocationResultMessageId, C as ownAgentInvocation, I as getUnnamedAgentConversationId, N as getChildAgentLockName, O as getAgentInvocationIdForResult, P as getNamedAgentConversationId, R as buildDeterministicTurnId, S as listChildMessages, T as getAgentInvocationId, _ as ConversationTurnLifecycleService, b as hasAgentInvocationReply, d as isTurnInputCommitLostError, j as getAgentInvocationTurnId, k as getAgentInvocationMessageId, l as getConversationTurnBoundaryError, p as markTurnClosed, s as TurnInputCommitLostError, t as getTurnUserMessage, w as readChildMessageSender } from "./turn-user-message-B1S8nOnG.js";
|
|
17
|
+
import { D as stopConversationWork, _ as getConversationWorkState, h as ensureConversationWake, m as dropPendingMessages, n as appendAndEnqueueExclusiveInboundMessage, r as appendAndEnqueueInboundMessage, v as getConversationWorkStates, w as requestConversationWork } from "./store-CdWg2r2L.js";
|
|
18
|
+
import { d as contextProvenance, m as sameActorIdentity, t as KNOWN_CONVERSATION_EVENT_TYPES, u as agentInstructionProvenance } from "./history-N7IVbUom.js";
|
|
19
|
+
import { m as credentialContextSchema, p as credentialContextForActor } from "./registry-D20hG3r6.js";
|
|
20
|
+
import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnResumeRouting, s as persistThreadStateById } from "./turn-session-routing-DFYak28Q.js";
|
|
21
|
+
import { g as getTurnRequestDeadline } from "./task-queue-BcjAYWyB.js";
|
|
22
|
+
import { d as sendNextWorkspaceSnapshotJob, f as sendWorkspaceSnapshotJob, l as sendCacheWarmup, m as getVercelConversationWorkQueue } from "./background-compaction-queue-BhEe4UfU.js";
|
|
23
|
+
import { d as completeText, m as searchWeb, r as EVENT_AUTHOR_ID } from "./prompt-D8u4jFs_.js";
|
|
24
|
+
import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-DDbENg-I.js";
|
|
25
|
+
import { n as postinstall, o as getSandboxResources, t as dependencies } from "./install-CgoAbzfF.js";
|
|
26
|
+
import pLimit from "p-limit";
|
|
26
27
|
import * as z from "zod";
|
|
27
28
|
import { streamSimple } from "@earendil-works/pi-ai/compat";
|
|
28
29
|
import path from "node:path";
|
|
29
30
|
import { isDeepStrictEqual, promisify } from "node:util";
|
|
30
31
|
import { createHash, randomUUID } from "node:crypto";
|
|
31
|
-
import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, notExists, notInArray, or, sql } from "drizzle-orm";
|
|
32
|
+
import { and, asc, count, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, max, min, ne, not, notExists, notInArray, or, sql } from "drizzle-orm";
|
|
32
33
|
import { actorSchema, agentEventKeys, agentEventMatchKey, agentEventMatchSchema, createWebSource, declaredEventKeys, destinationSchema, eventMatchFieldSchema, eventSchema, eventTriggerText, localDestinationSchema, ownedObjectAnnotationSchema, sourceSchema, stableEventMatchKey, watchResultSchema } from "@sentry/junior-plugin-api";
|
|
33
|
-
import { alias } from "drizzle-orm/pg-core";
|
|
34
|
-
import
|
|
34
|
+
import { alias, unionAll } from "drizzle-orm/pg-core";
|
|
35
|
+
import { guardedCosineDistance } from "@sentry/junior-plugin-api/embeddings";
|
|
35
36
|
import http from "node:http";
|
|
36
37
|
import dns from "node:dns/promises";
|
|
37
38
|
import net from "node:net";
|
|
@@ -39,6 +40,7 @@ import { Readable } from "node:stream";
|
|
|
39
40
|
import { NodeHtmlMarkdown } from "node-html-markdown";
|
|
40
41
|
import { structuredPatch } from "diff";
|
|
41
42
|
import { HTTPException } from "hono/http-exception";
|
|
43
|
+
import { bm25InverseDocumentFrequency, bm25NormalizedFrequency, bm25Saturation, fuseRankedLists } from "@sentry/junior-search";
|
|
42
44
|
import https from "node:https";
|
|
43
45
|
import { constants, zstdCompress as zstdCompress$1, zstdDecompress as zstdDecompress$1 } from "node:zlib";
|
|
44
46
|
// src/chat/cache-warming/model.ts
|
|
@@ -358,15 +360,16 @@ function viewerAutomationCollection(viewer) {
|
|
|
358
360
|
const owned = or(inArray(automation.creatorIdentityId, identityIds), ...slackAccounts.map((account) => and(eq(automation.teamId, account.providerTenantId), eq(automation.creatorSlackUserId, account.providerSubjectId))));
|
|
359
361
|
const publicDestination = sql`coalesce(${destination.visibility} = 'public', false)`;
|
|
360
362
|
const sharedToViewer = and(ne(automation.status, "completed"), or(and(inArray(automation.teamId, teamIds), publicDestination), viewer.location ? and(eq(automation.teamId, viewer.location.teamId), eq(automation.channelId, viewer.location.channelId)) : void 0));
|
|
361
|
-
const
|
|
362
|
-
const lastRunNeedsAttention = sql`coalesce(
|
|
363
|
-
|
|
364
|
-
order by ${runs.completedAtMs} desc, ${runs.id} desc limit 1), false)`;
|
|
363
|
+
const lastRun = juniorAutomationRuns;
|
|
364
|
+
const lastRunNeedsAttention = sql`coalesce(${lastRun.status} in ('failed', 'blocked'), false)`;
|
|
365
|
+
const activityAtMs = sql`coalesce(${lastRun.completedAtMs}, ${automation.createdAtMs})`;
|
|
365
366
|
return db.select({
|
|
366
367
|
kind: automation.kind,
|
|
367
368
|
id: automation.id,
|
|
368
369
|
title: automation.title,
|
|
369
370
|
createdAtMs: automation.createdAtMs,
|
|
371
|
+
lastRunId: automation.lastRunId,
|
|
372
|
+
activityAtMs: activityAtMs.mapWith(Number).as("activity_at_ms"),
|
|
370
373
|
state: sql`${automation.status}`.as("state"),
|
|
371
374
|
lastRunNeedsAttention: lastRunNeedsAttention.as("last_run_needs_attention"),
|
|
372
375
|
trigger: sql`${automation.record}->'trigger'`.as("trigger"),
|
|
@@ -380,7 +383,7 @@ function viewerAutomationCollection(viewer) {
|
|
|
380
383
|
instruction: automation.instruction,
|
|
381
384
|
skill: automation.skill,
|
|
382
385
|
task: sql`${automation.record}->'task'`.as("task")
|
|
383
|
-
}).from(automation).leftJoin(destination, and(eq(destination.provider, "slack"), eq(destination.providerTenantId, automation.teamId), eq(destination.providerDestinationId, automation.channelId))).where(and(ne(automation.status, "deleted"), or(owned, sharedToViewer))).as("accessible_automations");
|
|
386
|
+
}).from(automation).leftJoin(destination, and(eq(destination.provider, "slack"), eq(destination.providerTenantId, automation.teamId), eq(destination.providerDestinationId, automation.channelId))).leftJoin(lastRun, eq(lastRun.id, automation.lastRunId)).where(and(ne(automation.status, "deleted"), or(owned, sharedToViewer))).as("accessible_automations");
|
|
384
387
|
}
|
|
385
388
|
function eventTriggerAvailable(catalog, trigger) {
|
|
386
389
|
const parsed = eventAutomationTriggerSchema.safeParse(trigger);
|
|
@@ -426,12 +429,71 @@ async function countOwnedAutomationsNeedingAttention(viewer) {
|
|
|
426
429
|
const catalog = automationEventCatalog(getEventCatalog());
|
|
427
430
|
return rows.filter((row) => row.state === "blocked" || row.lastRunNeedsAttention || row.kind === "event" && !eventTriggerAvailable(catalog, row.trigger)).length;
|
|
428
431
|
}
|
|
429
|
-
/**
|
|
432
|
+
/** Build the access-scoped collection and the filters of one list query. */
|
|
433
|
+
async function selectViewerAutomations(viewer, input) {
|
|
434
|
+
const collection = viewerAutomationCollection(viewer);
|
|
435
|
+
const { attention, unavailable } = input.scope === "attention" || input.state === "unavailable" ? await attentionFilters(collection) : {
|
|
436
|
+
attention: void 0,
|
|
437
|
+
unavailable: void 0
|
|
438
|
+
};
|
|
439
|
+
return {
|
|
440
|
+
collection,
|
|
441
|
+
where: and(input.scope === "mine" ? eq(collection.owned, true) : input.scope === "public" ? eq(collection.isPublic, true) : input.scope === "attention" ? attention : void 0, input.type === "all" ? void 0 : eq(collection.kind, input.type), input.state === "all" ? void 0 : input.state === "unavailable" ? unavailable : eq(collection.state, input.state), input.creator ? eq(collection.creator, input.creator) : void 0, input.owner === "me" ? eq(collection.owned, true) : void 0, input.destination ? eq(collection.destination, input.destination) : void 0, input.skill ? eq(collection.skill, input.skill) : void 0, input.q ? sql`(strpos(lower(concat_ws(' ', ${collection.title}, ${collection.instruction}, ${collection.skill}, ${collection.resource})), ${input.q.toLowerCase()}) > 0 or strpos(${input.q.toLowerCase()}, lower(${collection.id})) > 0)` : void 0)
|
|
442
|
+
};
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Read one `sort=activity` page: the rows after `after`, newest activity
|
|
446
|
+
* first. `next` is set when more rows follow.
|
|
447
|
+
*/
|
|
448
|
+
async function readAutomationActivityPage({ collection, where }, pageSize, after) {
|
|
449
|
+
const db = getDb();
|
|
450
|
+
const limit = pageSize + 1;
|
|
451
|
+
const run = alias(juniorAutomationRuns, "page_run");
|
|
452
|
+
const withRun = db.select({
|
|
453
|
+
activityAtMs: sql`${run.completedAtMs}`.mapWith(Number).as("activity_at_ms"),
|
|
454
|
+
id: collection.id,
|
|
455
|
+
kind: collection.kind
|
|
456
|
+
}).from(run).innerJoin(collection, eq(collection.lastRunId, run.id)).where(and(where, after ? and(lte(run.completedAtMs, after.activityAtMs), sql`(${run.completedAtMs}, ${collection.id}) < (${after.activityAtMs}, ${after.id})`) : void 0)).orderBy(desc(run.completedAtMs), desc(collection.id)).limit(limit);
|
|
457
|
+
const withoutRun = db.select({
|
|
458
|
+
activityAtMs: sql`${collection.createdAtMs}`.mapWith(Number).as("activity_at_ms"),
|
|
459
|
+
id: collection.id,
|
|
460
|
+
kind: collection.kind
|
|
461
|
+
}).from(collection).where(and(where, isNull(collection.lastRunId), after ? sql`(${collection.createdAtMs}, ${collection.id}) < (${after.activityAtMs}, ${after.id})` : void 0)).orderBy(desc(collection.createdAtMs), desc(collection.id)).limit(limit);
|
|
462
|
+
const rows = await unionAll(withRun, withoutRun).orderBy(desc(sql.identifier("activity_at_ms")), desc(sql.identifier("id"))).limit(limit);
|
|
463
|
+
const pageRows = rows.slice(0, pageSize);
|
|
464
|
+
const last = pageRows.at(-1);
|
|
465
|
+
return {
|
|
466
|
+
rows: pageRows,
|
|
467
|
+
...rows.length > pageSize && last ? { next: {
|
|
468
|
+
activityAtMs: last.activityAtMs,
|
|
469
|
+
id: last.id
|
|
470
|
+
} } : void 0
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
/** Read an SQL page by offset and complete, access-scoped counts and filter options. */
|
|
430
474
|
async function readAutomationCollection(viewer, input) {
|
|
475
|
+
const selection = await selectViewerAutomations(viewer, input);
|
|
476
|
+
const { collection, where } = selection;
|
|
477
|
+
const facets = await readAutomationFacets(selection);
|
|
478
|
+
const page = Math.min(input.page, Math.max(1, Math.ceil(facets.total / input.pageSize)));
|
|
479
|
+
const order = input.sort === "oldest" ? asc(collection.createdAtMs) : input.sort === "title" ? asc(sql`lower(coalesce(nullif(trim(${collection.title}), ''), ${collection.instruction}, ${collection.skill}))`) : input.sort === "activity" ? desc(collection.activityAtMs) : desc(collection.createdAtMs);
|
|
480
|
+
return {
|
|
481
|
+
rows: await getDb().select({
|
|
482
|
+
id: collection.id,
|
|
483
|
+
kind: collection.kind
|
|
484
|
+
}).from(collection).where(where).orderBy(order, desc(collection.id)).limit(input.pageSize).offset((page - 1) * input.pageSize),
|
|
485
|
+
page,
|
|
486
|
+
pageSize: input.pageSize,
|
|
487
|
+
...facets
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
/**
|
|
491
|
+
* Read the match total, the scope counts, and the creator and Destination
|
|
492
|
+
* options. Separate statements run in parallel on their own connections,
|
|
493
|
+
* which measured faster than one grouped statement.
|
|
494
|
+
*/
|
|
495
|
+
async function readAutomationFacets({ collection, where }) {
|
|
431
496
|
const db = getDb();
|
|
432
|
-
const collection = viewerAutomationCollection(viewer);
|
|
433
|
-
const { attention, unavailable } = await attentionFilters(collection);
|
|
434
|
-
const where = and(input.scope === "mine" ? eq(collection.owned, true) : input.scope === "public" ? eq(collection.isPublic, true) : input.scope === "attention" ? attention : void 0, input.type === "all" ? void 0 : eq(collection.kind, input.type), input.state === "all" ? void 0 : input.state === "unavailable" ? unavailable : eq(collection.state, input.state), input.creator ? eq(collection.creator, input.creator) : void 0, input.owner === "me" ? eq(collection.owned, true) : void 0, input.destination ? eq(collection.destination, input.destination) : void 0, input.skill ? eq(collection.skill, input.skill) : void 0, input.q ? sql`(strpos(lower(concat_ws(' ', ${collection.title}, ${collection.instruction}, ${collection.skill}, ${collection.resource})), ${input.q.toLowerCase()}) > 0 or strpos(${input.q.toLowerCase()}, lower(${collection.id})) > 0)` : void 0);
|
|
435
497
|
const [totals, counts, creators, destinations] = await Promise.all([
|
|
436
498
|
db.select({ total: count() }).from(collection).where(where),
|
|
437
499
|
db.select({
|
|
@@ -449,17 +511,8 @@ async function readAutomationCollection(viewer, input) {
|
|
|
449
511
|
label: sql`min(${collection.destinationLabel})`
|
|
450
512
|
}).from(collection).groupBy(collection.destination).orderBy(sql`min(${collection.destinationLabel})`, collection.destination)
|
|
451
513
|
]);
|
|
452
|
-
const total = totals[0].total;
|
|
453
|
-
const page = Math.min(input.page, Math.max(1, Math.ceil(total / input.pageSize)));
|
|
454
|
-
const order = input.sort === "oldest" ? asc(collection.createdAtMs) : input.sort === "title" ? asc(sql`lower(coalesce(nullif(trim(${collection.title}), ''), ${collection.instruction}, ${collection.skill}))`) : desc(collection.createdAtMs);
|
|
455
514
|
return {
|
|
456
|
-
|
|
457
|
-
id: collection.id,
|
|
458
|
-
kind: collection.kind
|
|
459
|
-
}).from(collection).where(where).orderBy(order, desc(collection.id)).limit(input.pageSize).offset((page - 1) * input.pageSize),
|
|
460
|
-
total,
|
|
461
|
-
page,
|
|
462
|
-
pageSize: input.pageSize,
|
|
515
|
+
total: totals[0].total,
|
|
463
516
|
counts: counts[0],
|
|
464
517
|
creators,
|
|
465
518
|
destinations
|
|
@@ -593,6 +646,22 @@ function namesPerson(text, name) {
|
|
|
593
646
|
return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "iu").test(text);
|
|
594
647
|
}
|
|
595
648
|
const CONVERSATION_REFERENCE = /\bthis (?:channel|conversation|thread)\b/i;
|
|
649
|
+
const FIRST_PERSON_WORDS = [
|
|
650
|
+
"me",
|
|
651
|
+
"my",
|
|
652
|
+
"myself"
|
|
653
|
+
];
|
|
654
|
+
function wordCount(text, word) {
|
|
655
|
+
return text.match(new RegExp(`\\b${word}\\b`, "gi"))?.length ?? 0;
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Return a first-person word that the text uses more often than the previous
|
|
659
|
+
* text, or undefined. A creator's "my" that the edit keeps stays allowed, but
|
|
660
|
+
* a new "me" next to it does not.
|
|
661
|
+
*/
|
|
662
|
+
function addedFirstPerson(text, previousText) {
|
|
663
|
+
return FIRST_PERSON_WORDS.find((word) => wordCount(text, word) > wordCount(previousText, word));
|
|
664
|
+
}
|
|
596
665
|
function refersTo(text, person) {
|
|
597
666
|
return text.includes(slackMention(person.slackUserId)) || !!person.fullName && namesPerson(text, person.fullName);
|
|
598
667
|
}
|
|
@@ -604,7 +673,8 @@ function refersTo(text, person) {
|
|
|
604
673
|
* names the channel only where the run reads or acts on it. Each run reads
|
|
605
674
|
* "the Automation creator" as its creator, so the text calls the creator
|
|
606
675
|
* that. Every other requester needs their Slack mention, because a display
|
|
607
|
-
* name does not notify the person and it can match another person.
|
|
676
|
+
* name does not notify the person and it can match another person. Their
|
|
677
|
+
* "me" needs it too, because each run reads "me" as the creator. A run
|
|
608
678
|
* ends with `reply`, `noReply`, or `reportBlocked`, so a legacy no-reply
|
|
609
679
|
* marker does nothing. A problem that the previous text already had stays
|
|
610
680
|
* allowed, so an edit does not have to rewrite text that the requester did
|
|
@@ -617,9 +687,11 @@ function taskTextProblem(text, references) {
|
|
|
617
687
|
const marker = findLegacyNoReplyMarker(text);
|
|
618
688
|
if (marker && !previousText.includes(marker)) return `Remove "${marker}". Say when the run posts nothing; it then ends without a message.`;
|
|
619
689
|
if (refersTo(text, creator) && !refersTo(previousText, creator)) return `The ${label} names ${creator.fullName ?? slackMention(creator.slackUserId)}, the Automation creator. Write "the Automation creator" for this person; each run knows who that is.`;
|
|
620
|
-
if (!requester
|
|
690
|
+
if (!requester || requester.slackUserId === creator.slackUserId) return;
|
|
621
691
|
const mention = slackMention(requester.slackUserId);
|
|
622
|
-
|
|
692
|
+
const firstPerson = addedFirstPerson(text, previousText);
|
|
693
|
+
if (firstPerson) return `The ${label} says "${firstPerson}", and each run reads that as the Automation creator. Write ${mention} for the requester.`;
|
|
694
|
+
if (!requester.fullName || text.includes(mention) || !namesPerson(text, requester.fullName)) return;
|
|
623
695
|
return `The ${label} names ${requester.fullName} without a Slack mention. Write ${mention} for this person.`;
|
|
624
696
|
}
|
|
625
697
|
/**
|
|
@@ -640,6 +712,91 @@ function requireAutomationTaskText(task, references) {
|
|
|
640
712
|
});
|
|
641
713
|
if (problem) throw new AutomationEditError(problem, `task.${label}`);
|
|
642
714
|
}
|
|
715
|
+
// src/chat/automations/result.ts
|
|
716
|
+
/** Model-facing fields that every Automation result has. */
|
|
717
|
+
const automationResultFieldSchemas = {
|
|
718
|
+
destination: z.object({
|
|
719
|
+
id: z.string().min(1),
|
|
720
|
+
channel: z.string().min(1),
|
|
721
|
+
thread: z.string().min(1).nullable()
|
|
722
|
+
}).strict(),
|
|
723
|
+
credential_mode: z.enum(["system", "creator"]),
|
|
724
|
+
is_creator: z.boolean(),
|
|
725
|
+
outcomes: z.array(z.object({
|
|
726
|
+
action: z.literal("send_message"),
|
|
727
|
+
destination: z.object({
|
|
728
|
+
channel: z.string().min(1),
|
|
729
|
+
thread: z.string().min(1).nullable()
|
|
730
|
+
}).strict()
|
|
731
|
+
}).strict()).max(5),
|
|
732
|
+
created_by: z.object({
|
|
733
|
+
name: z.string().min(1).nullable(),
|
|
734
|
+
username: z.string().min(1).nullable()
|
|
735
|
+
}).strict()
|
|
736
|
+
};
|
|
737
|
+
/** Project the fields that every Automation has into its result shape. */
|
|
738
|
+
function automationResultFields(task, isCreator) {
|
|
739
|
+
return {
|
|
740
|
+
destination: {
|
|
741
|
+
id: destinationFilterValue(task.destination),
|
|
742
|
+
channel: task.destination.channelId,
|
|
743
|
+
thread: null
|
|
744
|
+
},
|
|
745
|
+
credential_mode: task.credentialMode,
|
|
746
|
+
is_creator: isCreator,
|
|
747
|
+
outcomes: effectiveTaskOutcomes(task.outcomes, task.destination).map((outcome) => ({
|
|
748
|
+
action: outcome.action,
|
|
749
|
+
destination: {
|
|
750
|
+
channel: outcome.destination.channelId,
|
|
751
|
+
thread: outcome.destination.threadTs ?? null
|
|
752
|
+
}
|
|
753
|
+
})),
|
|
754
|
+
created_by: {
|
|
755
|
+
name: task.createdBy.fullName ?? null,
|
|
756
|
+
username: task.createdBy.userName ?? null
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
/**
|
|
761
|
+
* Return the status and warning that the card and the Slack details of an
|
|
762
|
+
* Automation show. The status is the saved status, except that an active
|
|
763
|
+
* Automation whose trigger cannot work shows as unavailable. Only a block or
|
|
764
|
+
* a trigger problem gives a warning, like Needs attention in `collection.ts`.
|
|
765
|
+
*/
|
|
766
|
+
function automationCardStatus(automation) {
|
|
767
|
+
const problems = automation.triggerProblems ?? [];
|
|
768
|
+
const warning = [automation.status === "blocked" ? automation.statusReason ?? "This automation is blocked." : void 0, problems.length > 0 ? ["Trigger unavailable.", ...problems].join(" ") : void 0].filter(Boolean).join(" ");
|
|
769
|
+
return {
|
|
770
|
+
status: automation.status === "active" && problems.length > 0 ? "unavailable" : automation.status,
|
|
771
|
+
warning: warning || void 0
|
|
772
|
+
};
|
|
773
|
+
}
|
|
774
|
+
/** Save the card of an Automation that a tool changed, and return the tool result. */
|
|
775
|
+
async function saveAutomationCardResult(conversationId, automation, card) {
|
|
776
|
+
const description = automationTaskDescription(card.task);
|
|
777
|
+
const title = automation.title ?? fallbackShortTitle(description, card.fallbackTitle);
|
|
778
|
+
const { status, warning } = automationCardStatus({
|
|
779
|
+
status: automation.status,
|
|
780
|
+
statusReason: automation.status_reason,
|
|
781
|
+
triggerProblems: card.triggerProblems
|
|
782
|
+
});
|
|
783
|
+
const annotation = {
|
|
784
|
+
kind: "object",
|
|
785
|
+
objectType: "automation",
|
|
786
|
+
label: title,
|
|
787
|
+
key: automation.id,
|
|
788
|
+
title,
|
|
789
|
+
url: automation.dashboard_url,
|
|
790
|
+
description,
|
|
791
|
+
status,
|
|
792
|
+
trigger: card.trigger,
|
|
793
|
+
warning: warning ?? (status === "completed" ? "This automation has completed." : void 0)
|
|
794
|
+
};
|
|
795
|
+
return {
|
|
796
|
+
automation,
|
|
797
|
+
objectCards: await saveObjectAnnotations(conversationId, "junior", [annotation])
|
|
798
|
+
};
|
|
799
|
+
}
|
|
643
800
|
// src/chat/event-automations/tool-support.ts
|
|
644
801
|
/** Model-facing shape of one event automation. */
|
|
645
802
|
const compactEventAutomationResultSchema = z.object({
|
|
@@ -665,24 +822,7 @@ const compactEventAutomationResultSchema = z.object({
|
|
|
665
822
|
available: z.boolean(),
|
|
666
823
|
problems: z.array(z.string().min(1)).min(1).optional()
|
|
667
824
|
}).strict(),
|
|
668
|
-
|
|
669
|
-
id: z.string().min(1),
|
|
670
|
-
channel: z.string().min(1),
|
|
671
|
-
thread: z.string().min(1).nullable()
|
|
672
|
-
}).strict(),
|
|
673
|
-
credential_mode: z.enum(["system", "creator"]),
|
|
674
|
-
is_creator: z.boolean(),
|
|
675
|
-
outcomes: z.array(z.object({
|
|
676
|
-
action: z.literal("send_message"),
|
|
677
|
-
destination: z.object({
|
|
678
|
-
channel: z.string().min(1),
|
|
679
|
-
thread: z.string().min(1).nullable()
|
|
680
|
-
}).strict()
|
|
681
|
-
}).strict()).max(5),
|
|
682
|
-
created_by: z.object({
|
|
683
|
-
name: z.string().min(1).nullable(),
|
|
684
|
-
username: z.string().min(1).nullable()
|
|
685
|
-
}).strict()
|
|
825
|
+
...automationResultFieldSchemas
|
|
686
826
|
}).strict();
|
|
687
827
|
/** Build the validated event trigger accepted by event-automation tools. */
|
|
688
828
|
function registeredEventAutomationTriggerSchema(catalog) {
|
|
@@ -776,47 +916,18 @@ function compactEventAutomation(task, catalog, isCreator) {
|
|
|
776
916
|
available: problems.length === 0,
|
|
777
917
|
...problems.length > 0 ? { problems } : void 0
|
|
778
918
|
},
|
|
779
|
-
|
|
780
|
-
id: destinationFilterValue(task.destination),
|
|
781
|
-
channel: task.destination.channelId,
|
|
782
|
-
thread: null
|
|
783
|
-
},
|
|
784
|
-
credential_mode: task.credentialMode,
|
|
785
|
-
is_creator: isCreator,
|
|
786
|
-
outcomes: effectiveTaskOutcomes(task.outcomes, task.destination).map((outcome) => ({
|
|
787
|
-
action: outcome.action,
|
|
788
|
-
destination: {
|
|
789
|
-
channel: outcome.destination.channelId,
|
|
790
|
-
thread: outcome.destination.threadTs ?? null
|
|
791
|
-
}
|
|
792
|
-
})),
|
|
793
|
-
created_by: {
|
|
794
|
-
name: task.createdBy.fullName ?? null,
|
|
795
|
-
username: task.createdBy.userName ?? null
|
|
796
|
-
}
|
|
919
|
+
...automationResultFields(task, isCreator)
|
|
797
920
|
});
|
|
798
921
|
}
|
|
799
922
|
/** Return the standard successful event-automation tool result. */
|
|
800
923
|
async function eventAutomationToolResult(conversationId, task, catalog, isCreator) {
|
|
801
|
-
const automation = compactEventAutomation(task, catalog, isCreator);
|
|
802
924
|
const description = describeEventAutomationTrigger(task.trigger, catalog);
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
objectType: "automation",
|
|
810
|
-
label: title,
|
|
811
|
-
key: task.id,
|
|
812
|
-
title,
|
|
813
|
-
url: automation.dashboard_url,
|
|
814
|
-
description: taskDescription,
|
|
815
|
-
status: description.problems.length === 0 ? "ready" : "unavailable",
|
|
816
|
-
trigger: eventTriggerText(task.trigger.label, description),
|
|
817
|
-
warning: description.problems.length > 0 ? ["Trigger unavailable.", ...description.problems].join(" ") : void 0
|
|
818
|
-
}])
|
|
819
|
-
};
|
|
925
|
+
return saveAutomationCardResult(conversationId, compactEventAutomation(task, catalog, isCreator), {
|
|
926
|
+
task: task.task,
|
|
927
|
+
fallbackTitle: "Event automation",
|
|
928
|
+
trigger: eventTriggerText(task.trigger.label, description),
|
|
929
|
+
triggerProblems: description.problems
|
|
930
|
+
});
|
|
820
931
|
}
|
|
821
932
|
// src/chat/event-automations/edit.ts
|
|
822
933
|
function changesEventAutomationTrigger(current, next) {
|
|
@@ -942,19 +1053,23 @@ async function destinationDetails(destinations) {
|
|
|
942
1053
|
}];
|
|
943
1054
|
}));
|
|
944
1055
|
}
|
|
945
|
-
function
|
|
1056
|
+
function rowStatsFields(stats) {
|
|
946
1057
|
return {
|
|
947
1058
|
lastRunStatus: stats?.lastRunStatus,
|
|
948
1059
|
...stats?.lastConversationId ? { lastConversationId: stats.lastConversationId } : void 0,
|
|
949
1060
|
...stats?.lastExecutedAtMs ? { lastRunAt: new Date(stats.lastExecutedAtMs).toISOString() } : void 0,
|
|
1061
|
+
recentRuns: stats?.recentRuns ?? []
|
|
1062
|
+
};
|
|
1063
|
+
}
|
|
1064
|
+
function totalFields(stats) {
|
|
1065
|
+
return {
|
|
950
1066
|
costUsd: stats?.costUsd ?? emptyAutomationRunWindows(),
|
|
951
|
-
recentRuns: stats?.recentRuns ?? [],
|
|
952
1067
|
runs: stats?.runs ?? emptyAutomationRunWindows(),
|
|
953
1068
|
totalCostUsd: stats?.totalCostUsd ?? 0,
|
|
954
1069
|
totalRuns: stats?.totalRuns ?? 0
|
|
955
1070
|
};
|
|
956
1071
|
}
|
|
957
|
-
function
|
|
1072
|
+
function scheduledAutomationListItem(task, ownedByViewer, destination, stats, creator) {
|
|
958
1073
|
if (task.status === "deleted") throw new Error("Deleted scheduled automations cannot enter the Automations view");
|
|
959
1074
|
const nextRunAtMs = task.status === "active" ? task.runNowAtMs ?? task.nextRunAtMs : void 0;
|
|
960
1075
|
const description = displayText(automationTaskDescription(task.task), "Untitled scheduled automation");
|
|
@@ -972,7 +1087,7 @@ function scheduledAutomationSummary(task, ownedByViewer, destination, stats, cre
|
|
|
972
1087
|
id: task.id,
|
|
973
1088
|
task: task.task,
|
|
974
1089
|
kind: "scheduled",
|
|
975
|
-
...
|
|
1090
|
+
...rowStatsFields(stats),
|
|
976
1091
|
...nextRunAtMs !== void 0 ? { nextRunAt: new Date(nextRunAtMs).toISOString() } : void 0,
|
|
977
1092
|
ownedByViewer,
|
|
978
1093
|
schedule: displayText(task.schedule.description, "Schedule unavailable"),
|
|
@@ -984,7 +1099,8 @@ function scheduledAutomationSummary(task, ownedByViewer, destination, stats, cre
|
|
|
984
1099
|
title: taskDisplayTitle(task.title, description, "Untitled scheduled automation")
|
|
985
1100
|
};
|
|
986
1101
|
}
|
|
987
|
-
function
|
|
1102
|
+
function eventAutomationListItem(task, ownedByViewer, destination, stats, creator) {
|
|
1103
|
+
if (task.status === "deleted") throw new Error("Deleted event automations cannot enter the Automations view");
|
|
988
1104
|
const description = automationTaskDescription(task.task);
|
|
989
1105
|
const catalog = getEventCatalog();
|
|
990
1106
|
return {
|
|
@@ -1001,18 +1117,27 @@ function eventAutomationSummary(task, ownedByViewer, destination, stats, creator
|
|
|
1001
1117
|
id: task.id,
|
|
1002
1118
|
task: task.task,
|
|
1003
1119
|
kind: "event",
|
|
1004
|
-
...
|
|
1120
|
+
...rowStatsFields(stats),
|
|
1005
1121
|
ownedByViewer,
|
|
1006
1122
|
resource: task.trigger.identifier ? `${task.trigger.label} · ${task.trigger.identifier}` : task.trigger.label,
|
|
1007
1123
|
source: task.trigger.namespace,
|
|
1008
1124
|
credentialMode: task.credentialMode,
|
|
1009
1125
|
outcomes: effectiveTaskOutcomes(task.outcomes, task.destination),
|
|
1010
1126
|
title: taskDisplayTitle(task.title, description, "Untitled event automation"),
|
|
1011
|
-
status: task.status
|
|
1127
|
+
status: task.status,
|
|
1012
1128
|
statusReason: task.statusReason,
|
|
1013
1129
|
trigger: describeEventAutomationTrigger(task.trigger, catalog)
|
|
1014
1130
|
};
|
|
1015
1131
|
}
|
|
1132
|
+
/** Build one list row from loaded Destinations, creators, and run stats. */
|
|
1133
|
+
function automationListItem(candidate, destinations, creators, stats) {
|
|
1134
|
+
const destination = destinations.get(destinationKey(candidate.task.destination)) ?? {
|
|
1135
|
+
label: `Channel ${candidate.task.destination.channelId}`,
|
|
1136
|
+
visibility: "private"
|
|
1137
|
+
};
|
|
1138
|
+
const creator = creators.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
|
|
1139
|
+
return candidate.kind === "scheduled" ? scheduledAutomationListItem(candidate.task, candidate.ownedByViewer, destination, stats, creator) : eventAutomationListItem(candidate.task, candidate.ownedByViewer, destination, stats, creator);
|
|
1140
|
+
}
|
|
1016
1141
|
function viewerTeamIds(viewer) {
|
|
1017
1142
|
return [...new Set(viewer.identities.filter((identity) => identity.provider === "slack").map((identity) => identity.providerTenantId).filter((teamId) => Boolean(teamId)))];
|
|
1018
1143
|
}
|
|
@@ -1063,13 +1188,11 @@ async function automationSummaryForCandidate(candidate) {
|
|
|
1063
1188
|
creatorProfiles([candidate]),
|
|
1064
1189
|
readAutomationExecutionSummaries([candidate.task.id])
|
|
1065
1190
|
]);
|
|
1066
|
-
const
|
|
1067
|
-
|
|
1068
|
-
|
|
1191
|
+
const summary = stats.get(candidate.task.id);
|
|
1192
|
+
return {
|
|
1193
|
+
...automationListItem(candidate, destinations, creators, summary),
|
|
1194
|
+
...totalFields(summary)
|
|
1069
1195
|
};
|
|
1070
|
-
const creator = creators.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
|
|
1071
|
-
if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
|
|
1072
|
-
return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
|
|
1073
1196
|
}
|
|
1074
1197
|
function emptyAutomationExecutionStatusDay(date) {
|
|
1075
1198
|
return {
|
|
@@ -1116,27 +1239,42 @@ async function readTaskCandidates(viewer, ids) {
|
|
|
1116
1239
|
return candidate ? [candidate] : [];
|
|
1117
1240
|
});
|
|
1118
1241
|
}
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1242
|
+
async function readViewerAutomations(user, input = automationListQuerySchema.parse({}), after) {
|
|
1243
|
+
if (input.sort !== "activity") {
|
|
1244
|
+
const { rows, ...page } = await readAutomationCollection(user, input);
|
|
1245
|
+
return {
|
|
1246
|
+
automations: await readAutomationListItems(user, rows.map((row) => row.id)),
|
|
1247
|
+
...page
|
|
1248
|
+
};
|
|
1249
|
+
}
|
|
1250
|
+
const selection = await selectViewerAutomations(user, input);
|
|
1251
|
+
const [facets, { automations, next }] = await Promise.all([after ? void 0 : readAutomationFacets(selection), readAutomationActivityPage(selection, input.pageSize, after).then(async ({ rows, next }) => ({
|
|
1252
|
+
automations: await readAutomationListItems(user, rows.map((row) => row.id)),
|
|
1253
|
+
next
|
|
1254
|
+
}))]);
|
|
1127
1255
|
return {
|
|
1128
|
-
automations
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
const creator = creators.get(creatorKey(candidate.task.destination.teamId, candidate.task.createdBy.slackUserId));
|
|
1134
|
-
if (candidate.kind === "scheduled") return scheduledAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
|
|
1135
|
-
return eventAutomationSummary(candidate.task, candidate.ownedByViewer, destination, stats.get(candidate.task.id), creator);
|
|
1136
|
-
}),
|
|
1137
|
-
...page
|
|
1256
|
+
automations,
|
|
1257
|
+
page: 1,
|
|
1258
|
+
pageSize: input.pageSize,
|
|
1259
|
+
...facets,
|
|
1260
|
+
...next ? { next } : void 0
|
|
1138
1261
|
};
|
|
1139
1262
|
}
|
|
1263
|
+
/**
|
|
1264
|
+
* Build list items for collection rows, in their order. The run stats load
|
|
1265
|
+
* while the Destination and creator details do.
|
|
1266
|
+
*/
|
|
1267
|
+
async function readAutomationListItems(user, ids) {
|
|
1268
|
+
const [{ selected, destinations, creators }, stats] = await Promise.all([readTaskCandidates(user, ids).then(async (selected) => {
|
|
1269
|
+
const [destinations, creators] = await Promise.all([destinationDetails(selected.map(({ task }) => task.destination)), creatorProfiles(selected)]);
|
|
1270
|
+
return {
|
|
1271
|
+
selected,
|
|
1272
|
+
destinations,
|
|
1273
|
+
creators
|
|
1274
|
+
};
|
|
1275
|
+
}), readAutomationRowStats(ids)]);
|
|
1276
|
+
return selected.filter((candidate) => candidate.ownedByViewer || destinations.get(destinationKey(candidate.task.destination))?.visibility === "public").map((candidate) => automationListItem(candidate, destinations, creators, stats.get(candidate.task.id)));
|
|
1277
|
+
}
|
|
1140
1278
|
/** Load deleted scheduled automations the viewer still owns, newest first. */
|
|
1141
1279
|
async function readDeletedOwnedScheduledAutomations(user) {
|
|
1142
1280
|
const identityIds = user.identities.map((identity) => identity.id);
|
|
@@ -1215,10 +1353,8 @@ var ViewerTaskNotFoundError = class extends Error {
|
|
|
1215
1353
|
};
|
|
1216
1354
|
/** Read one viewer-visible task and its newest terminal executions. */
|
|
1217
1355
|
async function readViewerAutomationExecutions(user, id) {
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
const [automation, executions, executionDays, executionHours] = await Promise.all([
|
|
1221
|
-
automationSummaryForCandidate(candidate),
|
|
1356
|
+
if (!await resolveViewerTaskCandidate(user, id)) throw new ViewerTaskNotFoundError();
|
|
1357
|
+
const [executions, executionDays, executionHours] = await Promise.all([
|
|
1222
1358
|
readAutomationExecutions({
|
|
1223
1359
|
automationId: id,
|
|
1224
1360
|
limit: 101
|
|
@@ -1231,7 +1367,6 @@ async function readViewerAutomationExecutions(user, id) {
|
|
|
1231
1367
|
executionHours,
|
|
1232
1368
|
executionSixHours: automationExecutionStatusSixHours(executionHours),
|
|
1233
1369
|
executions: executions.slice(0, TASK_EXECUTION_LIST_LIMIT),
|
|
1234
|
-
automation,
|
|
1235
1370
|
truncated: executions.length > TASK_EXECUTION_LIST_LIMIT
|
|
1236
1371
|
};
|
|
1237
1372
|
}
|
|
@@ -1759,11 +1894,7 @@ const compactTaskResultSchema = z.object({
|
|
|
1759
1894
|
timezone: z.string(),
|
|
1760
1895
|
recurrence: z.unknown().nullable(),
|
|
1761
1896
|
next_run_at: z.string().nullable(),
|
|
1762
|
-
|
|
1763
|
-
id: z.string().min(1),
|
|
1764
|
-
channel: z.string().min(1),
|
|
1765
|
-
thread: z.string().min(1).nullable()
|
|
1766
|
-
}).strict(),
|
|
1897
|
+
...automationResultFieldSchemas,
|
|
1767
1898
|
conversation_access: z.object({
|
|
1768
1899
|
audience: z.enum([
|
|
1769
1900
|
"direct",
|
|
@@ -1772,19 +1903,6 @@ const compactTaskResultSchema = z.object({
|
|
|
1772
1903
|
]),
|
|
1773
1904
|
visibility: z.enum(["private", "public"])
|
|
1774
1905
|
}).strict(),
|
|
1775
|
-
credential_mode: z.enum(["system", "creator"]),
|
|
1776
|
-
is_creator: z.boolean(),
|
|
1777
|
-
created_by: z.object({
|
|
1778
|
-
name: z.string().min(1).nullable(),
|
|
1779
|
-
username: z.string().min(1).nullable()
|
|
1780
|
-
}).strict(),
|
|
1781
|
-
outcomes: z.array(z.object({
|
|
1782
|
-
action: z.literal("send_message"),
|
|
1783
|
-
destination: z.object({
|
|
1784
|
-
channel: z.string().min(1),
|
|
1785
|
-
thread: z.string().min(1).nullable()
|
|
1786
|
-
}).strict()
|
|
1787
|
-
}).strict()).max(5),
|
|
1788
1906
|
dashboard_url: z.string().url().nullable(),
|
|
1789
1907
|
last_run_at: z.string().nullable(),
|
|
1790
1908
|
run_now_at: z.string().nullable()
|
|
@@ -1831,25 +1949,8 @@ function compactTask(task, isCreator) {
|
|
|
1831
1949
|
day_of_month: task.schedule.recurrence.dayOfMonth
|
|
1832
1950
|
} : null,
|
|
1833
1951
|
next_run_at: task.nextRunAtMs ? new Date(task.nextRunAtMs).toISOString() : null,
|
|
1834
|
-
|
|
1835
|
-
id: destinationFilterValue(task.destination),
|
|
1836
|
-
channel: task.destination.channelId,
|
|
1837
|
-
thread: null
|
|
1838
|
-
},
|
|
1952
|
+
...automationResultFields(task, isCreator),
|
|
1839
1953
|
conversation_access: task.conversationAccess,
|
|
1840
|
-
credential_mode: task.credentialMode,
|
|
1841
|
-
is_creator: isCreator,
|
|
1842
|
-
created_by: {
|
|
1843
|
-
name: task.createdBy.fullName ?? null,
|
|
1844
|
-
username: task.createdBy.userName ?? null
|
|
1845
|
-
},
|
|
1846
|
-
outcomes: effectiveTaskOutcomes(task.outcomes, task.destination).map((outcome) => ({
|
|
1847
|
-
action: outcome.action,
|
|
1848
|
-
destination: {
|
|
1849
|
-
channel: outcome.destination.channelId,
|
|
1850
|
-
thread: outcome.destination.threadTs ?? null
|
|
1851
|
-
}
|
|
1852
|
-
})),
|
|
1853
1954
|
dashboard_url: getDashboardTaskLink(task.id) ?? null,
|
|
1854
1955
|
last_run_at: task.lastRunAtMs ? new Date(task.lastRunAtMs).toISOString() : null,
|
|
1855
1956
|
run_now_at: task.runNowAtMs ? new Date(task.runNowAtMs).toISOString() : null
|
|
@@ -1857,29 +1958,15 @@ function compactTask(task, isCreator) {
|
|
|
1857
1958
|
}
|
|
1858
1959
|
/** Build the result of a tool that changed one scheduled automation, with its card. */
|
|
1859
1960
|
async function scheduleAutomationToolResult(conversationId, task, isCreator) {
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
const annotation = {
|
|
1864
|
-
kind: "object",
|
|
1865
|
-
objectType: "automation",
|
|
1866
|
-
label: title,
|
|
1867
|
-
key: task.id,
|
|
1868
|
-
title,
|
|
1869
|
-
url: automation.dashboard_url,
|
|
1870
|
-
description,
|
|
1871
|
-
status: automation.status,
|
|
1961
|
+
return saveAutomationCardResult(conversationId, compactTask(task, isCreator), {
|
|
1962
|
+
task: task.task,
|
|
1963
|
+
fallbackTitle: "Scheduled automation",
|
|
1872
1964
|
trigger: task.schedule.kind === "one_off" && task.nextRunAtMs !== void 0 ? `${new Intl.DateTimeFormat("en-US", {
|
|
1873
1965
|
dateStyle: "medium",
|
|
1874
1966
|
timeStyle: "short",
|
|
1875
1967
|
timeZone: task.schedule.timezone
|
|
1876
|
-
}).format(task.nextRunAtMs)} · ${task.schedule.timezone}` :
|
|
1877
|
-
|
|
1878
|
-
};
|
|
1879
|
-
return {
|
|
1880
|
-
automation,
|
|
1881
|
-
objectCards: await saveObjectAnnotations(conversationId, "junior", [annotation])
|
|
1882
|
-
};
|
|
1968
|
+
}).format(task.nextRunAtMs)} · ${task.schedule.timezone}` : task.schedule.description
|
|
1969
|
+
});
|
|
1883
1970
|
}
|
|
1884
1971
|
// src/chat/tool-support/structured-result.ts
|
|
1885
1972
|
const juniorToolContinuationSchema = z.object({
|
|
@@ -2048,6 +2135,7 @@ function formatZodPath(path) {
|
|
|
2048
2135
|
function formatToolInputError(error) {
|
|
2049
2136
|
return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
|
|
2050
2137
|
}
|
|
2138
|
+
/** Parse tool input with its Zod schema, as a model-repairable error on failure. */
|
|
2051
2139
|
function parseToolInput(schema, args) {
|
|
2052
2140
|
const result = schema.safeParse(args);
|
|
2053
2141
|
if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
|
|
@@ -3483,7 +3571,7 @@ const CONVERSATIONS_TOOL_SOURCE = {
|
|
|
3483
3571
|
description: "Search other conversations for past or current work, and read messages and events in retained conversations."
|
|
3484
3572
|
};
|
|
3485
3573
|
// src/chat/slack/tools/conversation-message-search.ts
|
|
3486
|
-
const DEFAULT_LIMIT$
|
|
3574
|
+
const DEFAULT_LIMIT$3 = 20;
|
|
3487
3575
|
const MAX_LIMIT$3 = 50;
|
|
3488
3576
|
const conversationMessageSearchOutputSchema = juniorToolOutputSchema.extend({
|
|
3489
3577
|
after: z.string().datetime().optional(),
|
|
@@ -3547,7 +3635,7 @@ const searchConversationMessagesToolDefinition = zodToolDefinition({
|
|
|
3547
3635
|
before: z.string().datetime().nullable().describe("Include conversations active before this timestamp.").optional(),
|
|
3548
3636
|
channel_id: slackChannelRefParam.nullable().optional(),
|
|
3549
3637
|
query: z.string().trim().min(1).max(200).nullable().describe("Words or phrase to match in message text.").optional(),
|
|
3550
|
-
limit: z.number().int().min(1).max(MAX_LIMIT$3).describe(`Maximum conversations. Default ${DEFAULT_LIMIT$
|
|
3638
|
+
limit: z.number().int().min(1).max(MAX_LIMIT$3).describe(`Maximum conversations. Default ${DEFAULT_LIMIT$3}; max ${MAX_LIMIT$3}.`).nullable().optional()
|
|
3551
3639
|
}).strict(),
|
|
3552
3640
|
outputSchema: conversationMessageSearchOutputSchema
|
|
3553
3641
|
});
|
|
@@ -3566,7 +3654,7 @@ function createSlackConversationMessageSearchTool(teamId, currentConversationId)
|
|
|
3566
3654
|
const matches = await getConversationMessageSearchStore().search({
|
|
3567
3655
|
currentConversationId,
|
|
3568
3656
|
filters,
|
|
3569
|
-
limit: input.limit ?? DEFAULT_LIMIT$
|
|
3657
|
+
limit: input.limit ?? DEFAULT_LIMIT$3
|
|
3570
3658
|
});
|
|
3571
3659
|
const matchesOutput = await Promise.all(matches.map(async (match) => {
|
|
3572
3660
|
const reference = parseSlackThreadId(match.conversationId);
|
|
@@ -3961,7 +4049,7 @@ function createSlackListUpdateItemTool(state) {
|
|
|
3961
4049
|
});
|
|
3962
4050
|
}
|
|
3963
4051
|
// src/chat/slack/tools/public-search.ts
|
|
3964
|
-
const DEFAULT_LIMIT$
|
|
4052
|
+
const DEFAULT_LIMIT$2 = 10;
|
|
3965
4053
|
const DEFAULT_CONTENT_TYPES = ["messages"];
|
|
3966
4054
|
const CONTENT_TYPES = [
|
|
3967
4055
|
"messages",
|
|
@@ -4231,7 +4319,7 @@ function createSlackPublicSearchTool(actionToken) {
|
|
|
4231
4319
|
channel_types: ["public_channel"],
|
|
4232
4320
|
content_types: normalizedContentTypes,
|
|
4233
4321
|
include_bots: true,
|
|
4234
|
-
limit: limit ?? DEFAULT_LIMIT$
|
|
4322
|
+
limit: limit ?? DEFAULT_LIMIT$2,
|
|
4235
4323
|
...normalizedAfter !== void 0 ? { after: normalizedAfter } : void 0,
|
|
4236
4324
|
...normalizedBefore !== void 0 ? { before: normalizedBefore } : void 0,
|
|
4237
4325
|
...cursor ? { cursor } : void 0,
|
|
@@ -5099,17 +5187,19 @@ async function getPausedTurnRequest(args) {
|
|
|
5099
5187
|
if (!turn || turn.state !== "paused" || turn.resumeReason !== "timeout" && turn.resumeReason !== "yield" && turn.resumeReason !== "retry" && !(turn.resumeReason === "auth" && await getTurnAuthorization(turn)) || turn.resumeReason === "timeout" && turn.sliceId < 2) return;
|
|
5100
5188
|
let routing;
|
|
5101
5189
|
try {
|
|
5102
|
-
routing = await
|
|
5190
|
+
routing = await resolveTurnResumeRouting({
|
|
5103
5191
|
conversationId: args.conversationId,
|
|
5104
|
-
conversationStore: args.conversationStore
|
|
5192
|
+
conversationStore: args.conversationStore,
|
|
5193
|
+
dispatchId: turn.dispatchId
|
|
5105
5194
|
});
|
|
5106
5195
|
} catch (error) {
|
|
5107
|
-
await failTurnRecord({
|
|
5196
|
+
const failed = await failTurnRecord({
|
|
5108
5197
|
conversationId: args.conversationId,
|
|
5109
5198
|
expectedVersion: turn.version,
|
|
5110
5199
|
turnId: args.turnId,
|
|
5111
5200
|
errorMessage: error instanceof Error ? error.message : String(error)
|
|
5112
5201
|
});
|
|
5202
|
+
if (failed) await recordFailedDispatchTurn(failed);
|
|
5113
5203
|
return;
|
|
5114
5204
|
}
|
|
5115
5205
|
return {
|
|
@@ -5120,6 +5210,32 @@ async function getPausedTurnRequest(args) {
|
|
|
5120
5210
|
traceContext: turn.traceContext
|
|
5121
5211
|
};
|
|
5122
5212
|
}
|
|
5213
|
+
/**
|
|
5214
|
+
* Record that a resume failed a dispatch turn for good. Without this outcome,
|
|
5215
|
+
* the dispatch runs the turn again, so a failed write is only logged.
|
|
5216
|
+
*/
|
|
5217
|
+
async function recordFailedDispatchTurn(turn) {
|
|
5218
|
+
if (!turn.dispatchId) return;
|
|
5219
|
+
try {
|
|
5220
|
+
const dispatch = await getDispatchRecord(turn.dispatchId);
|
|
5221
|
+
await recordTurnSummary({
|
|
5222
|
+
conversationId: turn.conversationId,
|
|
5223
|
+
destination: dispatch?.destination,
|
|
5224
|
+
dispatchId: turn.dispatchId,
|
|
5225
|
+
dispatchOutcome: "failed",
|
|
5226
|
+
turnId: turn.turnId,
|
|
5227
|
+
sliceId: turn.sliceId,
|
|
5228
|
+
source: dispatch?.source,
|
|
5229
|
+
state: "failed",
|
|
5230
|
+
surface: turn.surface
|
|
5231
|
+
});
|
|
5232
|
+
} catch (error) {
|
|
5233
|
+
logException(error, "agent.continue.dispatch_failure_summary.failed", {
|
|
5234
|
+
"app.ai.conversation_id": turn.conversationId,
|
|
5235
|
+
"app.ai.session_id": turn.turnId
|
|
5236
|
+
});
|
|
5237
|
+
}
|
|
5238
|
+
}
|
|
5123
5239
|
/** Wake the conversation worker for a paused turn. */
|
|
5124
5240
|
async function wakePausedTurn(request, options = {}) {
|
|
5125
5241
|
const nowMs = options.nowMs ?? Date.now();
|
|
@@ -7027,7 +7143,6 @@ function isChildAgentResult(status) {
|
|
|
7027
7143
|
const childAgentKindSchema = z.enum(CHILD_AGENT_KINDS);
|
|
7028
7144
|
/** Bound the agent invocations that one child agent listing reads. */
|
|
7029
7145
|
const CHILD_AGENT_LIST_INVOCATION_LIMIT = 200;
|
|
7030
|
-
const CONVERSATION_LOOP_CHECK_CONCURRENCY = 8;
|
|
7031
7146
|
/** Return whether a child's session stopped after its latest agent invocation. */
|
|
7032
7147
|
function isChildAgentSessionStopped(latest, stoppedAtMs) {
|
|
7033
7148
|
return stoppedAtMs !== void 0 && stoppedAtMs >= latest.createdAtMs;
|
|
@@ -7088,7 +7203,7 @@ async function listChildAgentsFromInvocations(parentConversationId) {
|
|
|
7088
7203
|
const active = conversations.filter((row) => row.executionStatus === "pending" || row.executionStatus === "running" || row.executionStatus === "paused");
|
|
7089
7204
|
const activeIds = active.map((row) => row.conversationId);
|
|
7090
7205
|
const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(activeIds), listActiveMailboxTurnSources(activeIds)]);
|
|
7091
|
-
const limit = pLimit(
|
|
7206
|
+
const limit = pLimit(8);
|
|
7092
7207
|
const onConversationLoop = new Set((await Promise.all(active.map((row) => limit(async () => await runsOnConversationLoop(conversationKindFromRow(row), byChild.get(row.conversationId)[0], row.stoppedAt?.getTime(), workStates.get(row.conversationId)?.execution.pendingMessages ?? [], mailboxTurnSources.get(row.conversationId) ?? []) ? row.conversationId : void 0)))).filter((id) => id !== void 0));
|
|
7093
7208
|
const factsByChild = new Map(conversations.map((row) => [row.conversationId, {
|
|
7094
7209
|
...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
|
|
@@ -7131,7 +7246,7 @@ async function listChildAgentsWithoutAgentInvocations(parentConversationId) {
|
|
|
7131
7246
|
}).from(juniorConversations).leftJoin(juniorAgentBindings, eq(juniorAgentBindings.childConversationId, juniorConversations.conversationId)).where(and(eq(juniorConversations.parentConversationId, parentConversationId), isNotNull(juniorConversations.agentConfig), notExists(db.select({ invocationId: juniorAgentInvocations.invocationId }).from(juniorAgentInvocations).where(eq(juniorAgentInvocations.childConversationId, juniorConversations.conversationId))))).limit(CHILD_AGENT_LIST_INVOCATION_LIMIT);
|
|
7132
7247
|
const ids = rows.map((row) => row.conversationId);
|
|
7133
7248
|
const [workStates, mailboxTurnSources] = await Promise.all([getConversationWorkStates(ids), listActiveMailboxTurnSources(ids)]);
|
|
7134
|
-
const limit = pLimit(
|
|
7249
|
+
const limit = pLimit(8);
|
|
7135
7250
|
return await Promise.all(rows.map(async (row) => {
|
|
7136
7251
|
const kind = childAgentKindSchema.parse(row.kind);
|
|
7137
7252
|
const stoppedAtMs = row.stoppedAt?.getTime();
|
|
@@ -7177,10 +7292,11 @@ async function listOpenLoopTurnIds(conversationId) {
|
|
|
7177
7292
|
}
|
|
7178
7293
|
async function listAnsweredLoopChildren(children, parentMessages) {
|
|
7179
7294
|
if (children.length === 0 || parentMessages.length === 0) return [];
|
|
7180
|
-
|
|
7295
|
+
const limit = pLimit(8);
|
|
7296
|
+
return (await Promise.all(children.map(({ childConversationId }) => limit(async () => {
|
|
7181
7297
|
const turnIds = await listOpenLoopTurnIds(childConversationId);
|
|
7182
7298
|
return parentMessages.some(({ sender }) => sender.conversationId === childConversationId && turnIds.includes(sender.turnId)) ? childConversationId : void 0;
|
|
7183
|
-
}))).filter((id) => id !== void 0);
|
|
7299
|
+
})))).filter((id) => id !== void 0);
|
|
7184
7300
|
}
|
|
7185
7301
|
/**
|
|
7186
7302
|
* List the other child agents of one parent whose results have not reached
|
|
@@ -7259,10 +7375,11 @@ async function listAgentRelatives(input) {
|
|
|
7259
7375
|
/** List the active watches that one Conversation owns, oldest first. */
|
|
7260
7376
|
async function listOwnedWatches(conversationId) {
|
|
7261
7377
|
const [own, childAgents] = await Promise.all([listWatches({ conversationId }), listDescendantAgents(conversationId)]);
|
|
7262
|
-
const
|
|
7378
|
+
const limit = pLimit(8);
|
|
7379
|
+
const childWatches = await Promise.all(childAgents.map((childAgent) => limit(async () => (await listWatches({ conversationId: childAgent.conversationId })).map((watch) => ({
|
|
7263
7380
|
childAgent,
|
|
7264
7381
|
watch
|
|
7265
|
-
}))));
|
|
7382
|
+
})))));
|
|
7266
7383
|
return [...own.map((watch) => ({ watch })), ...childWatches.flat()].sort((left, right) => left.watch.createdAtMs - right.watch.createdAtMs);
|
|
7267
7384
|
}
|
|
7268
7385
|
/**
|
|
@@ -7302,6 +7419,7 @@ const listedResourceWatchSchema = z.object({
|
|
|
7302
7419
|
namespace: z.string().min(1),
|
|
7303
7420
|
resource_type: z.string().min(1),
|
|
7304
7421
|
events: z.array(z.string().min(1)).min(1),
|
|
7422
|
+
quiet_events: z.array(z.string().min(1)).min(1).optional().describe("Events that start no Turn. The next Turn gets each one as a Conversation note."),
|
|
7305
7423
|
match: z.record(z.string(), z.unknown()).optional(),
|
|
7306
7424
|
intent: z.string().min(1),
|
|
7307
7425
|
expires_at: z.string().datetime(),
|
|
@@ -7340,7 +7458,8 @@ function createListWatchesTool(context) {
|
|
|
7340
7458
|
identifier: subscription.identifier,
|
|
7341
7459
|
namespace: subscription.namespace,
|
|
7342
7460
|
resource_type: subscription.resourceType,
|
|
7343
|
-
events: subscription
|
|
7461
|
+
events: turnEvents(subscription),
|
|
7462
|
+
...subscription.quietEvents ? { quiet_events: subscription.quietEvents } : void 0,
|
|
7344
7463
|
...subscription.match ? { match: agentEventKeys(subscription.match) } : void 0,
|
|
7345
7464
|
intent: subscription.intent,
|
|
7346
7465
|
expires_at: new Date(subscription.expiresAtMs).toISOString(),
|
|
@@ -7738,20 +7857,18 @@ async function verifyAttachmentUploads(args) {
|
|
|
7738
7857
|
}
|
|
7739
7858
|
/** Record checked uploads as attachments of their Conversation. */
|
|
7740
7859
|
async function recordAttachmentUploads(args) {
|
|
7741
|
-
|
|
7742
|
-
|
|
7743
|
-
|
|
7744
|
-
attachment
|
|
7745
|
-
|
|
7746
|
-
|
|
7747
|
-
|
|
7748
|
-
|
|
7749
|
-
|
|
7750
|
-
|
|
7751
|
-
|
|
7752
|
-
|
|
7753
|
-
});
|
|
7754
|
-
}
|
|
7860
|
+
const limit = pLimit(8);
|
|
7861
|
+
await Promise.all(args.uploads.filter((upload) => !upload.recorded).map((upload) => limit(() => recordUploadedAttachment({
|
|
7862
|
+
attachment: {
|
|
7863
|
+
...upload.attachment,
|
|
7864
|
+
conversationId: args.conversationId,
|
|
7865
|
+
sha256: upload.sha256,
|
|
7866
|
+
storageKey: upload.storageKey
|
|
7867
|
+
},
|
|
7868
|
+
db: args.db,
|
|
7869
|
+
nowMs: args.nowMs ?? Date.now(),
|
|
7870
|
+
storage: args.storage
|
|
7871
|
+
}))));
|
|
7755
7872
|
return args.uploads.map((upload) => upload.attachment);
|
|
7756
7873
|
}
|
|
7757
7874
|
/**
|
|
@@ -8153,12 +8270,10 @@ async function sendReviewItemMessages(args) {
|
|
|
8153
8270
|
conversationId,
|
|
8154
8271
|
text
|
|
8155
8272
|
})));
|
|
8156
|
-
results.
|
|
8157
|
-
|
|
8158
|
-
|
|
8159
|
-
|
|
8160
|
-
"gen_ai.conversation.id": conversationIds[index]
|
|
8161
|
-
});
|
|
8273
|
+
for (const [index, result] of results.entries()) if (result.status === "rejected") logWarn("review_item.message.failed", {
|
|
8274
|
+
"app.review_item.id": args.item.id,
|
|
8275
|
+
"app.review_item.change": args.change.kind,
|
|
8276
|
+
"gen_ai.conversation.id": conversationIds[index]
|
|
8162
8277
|
});
|
|
8163
8278
|
const failed = results.find((result) => result.status === "rejected");
|
|
8164
8279
|
if (failed) throw failed.reason;
|
|
@@ -8199,7 +8314,7 @@ const REVIEW_DESK_TOOL_SOURCE = {
|
|
|
8199
8314
|
id: "review-desk",
|
|
8200
8315
|
description: "Update and search Review items: work on the review desk that needs a person."
|
|
8201
8316
|
};
|
|
8202
|
-
const DEFAULT_LIMIT$
|
|
8317
|
+
const DEFAULT_LIMIT$1 = 10;
|
|
8203
8318
|
const MAX_LIMIT$2 = 25;
|
|
8204
8319
|
const assigneesSchema = z.array(z.string().trim().min(1).max(320)).min(1).max(20).describe("Who can act on the item. Each entry is `everyone`, an email, or a mention such as `<@U123>`. Everyone means any person who can see the item.");
|
|
8205
8320
|
const subjectSchema = z.object({
|
|
@@ -8208,7 +8323,7 @@ const subjectSchema = z.object({
|
|
|
8208
8323
|
url: z.string().url().max(2e3).nullable().optional()
|
|
8209
8324
|
}).strict();
|
|
8210
8325
|
const conversationIdsSchema = z.array(z.string().trim().min(1).max(500)).max(10);
|
|
8211
|
-
const titleSchema = z.string().trim().min(1).max(200);
|
|
8326
|
+
const titleSchema$1 = z.string().trim().min(1).max(200);
|
|
8212
8327
|
const bodySchema = z.string().trim().min(1).max(4e3).describe("Markdown details for the person.");
|
|
8213
8328
|
/**
|
|
8214
8329
|
* Pick the assignees of a new item when the agent names none: the User of
|
|
@@ -8286,7 +8401,7 @@ const addReviewItemToolDefinition = zodToolDefinition({
|
|
|
8286
8401
|
},
|
|
8287
8402
|
inputSchema: z.object({
|
|
8288
8403
|
kind: z.enum(["notice", "action"]).describe("Use `action` with a `request` to ask. Use `notice` only to tell a person something."),
|
|
8289
|
-
title: titleSchema,
|
|
8404
|
+
title: titleSchema$1,
|
|
8290
8405
|
body: bodySchema,
|
|
8291
8406
|
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."),
|
|
8292
8407
|
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."),
|
|
@@ -8396,7 +8511,7 @@ const updateReviewItemToolDefinition = zodToolDefinition({
|
|
|
8396
8511
|
},
|
|
8397
8512
|
inputSchema: z.object({
|
|
8398
8513
|
id: z.string().trim().min(1),
|
|
8399
|
-
title: titleSchema.nullable().optional(),
|
|
8514
|
+
title: titleSchema$1.nullable().optional(),
|
|
8400
8515
|
body: bodySchema.nullable().optional(),
|
|
8401
8516
|
assignees: assigneesSchema.nullable().optional().describe("Replaces every assignee."),
|
|
8402
8517
|
conversation_ids: conversationIdsSchema.nullable().optional().describe("Replaces every other linked Conversation. The Conversation that added the item stays linked."),
|
|
@@ -8513,7 +8628,7 @@ const searchReviewItemsToolDefinition = zodToolDefinition({
|
|
|
8513
8628
|
assignee: z.string().trim().min(1).max(320).nullable().optional().describe("`everyone`, an email, or a mention such as `<@U123>`."),
|
|
8514
8629
|
automation_id: z.string().trim().min(1).nullable().optional(),
|
|
8515
8630
|
conversation_id: z.string().trim().min(1).nullable().optional(),
|
|
8516
|
-
limit: z.number().int().min(1).max(MAX_LIMIT$2).nullable().optional().describe(`Default ${DEFAULT_LIMIT$
|
|
8631
|
+
limit: z.number().int().min(1).max(MAX_LIMIT$2).nullable().optional().describe(`Default ${DEFAULT_LIMIT$1}; max ${MAX_LIMIT$2}.`)
|
|
8517
8632
|
}).strict(),
|
|
8518
8633
|
outputSchema: juniorToolOutputSchema
|
|
8519
8634
|
});
|
|
@@ -8531,7 +8646,7 @@ function createSearchReviewItemsTool(context, services) {
|
|
|
8531
8646
|
"dismissed"
|
|
8532
8647
|
] : [status];
|
|
8533
8648
|
const items = await searchReviewItems(db, scope.reader, {
|
|
8534
|
-
limit: input.limit ?? DEFAULT_LIMIT$
|
|
8649
|
+
limit: input.limit ?? DEFAULT_LIMIT$1,
|
|
8535
8650
|
statuses,
|
|
8536
8651
|
...input.assignee ? { assignee: await resolveAssignee(db, input.assignee, scope.tenant, services.findMentionedUserId) } : void 0,
|
|
8537
8652
|
...input.automation_id ? { automationId: input.automation_id } : void 0,
|
|
@@ -8954,6 +9069,25 @@ function createReportProgressTool() {
|
|
|
8954
9069
|
execute: async () => ({})
|
|
8955
9070
|
});
|
|
8956
9071
|
}
|
|
9072
|
+
// src/chat/plan/tool-output.ts
|
|
9073
|
+
/** Plan item shape in tool results. */
|
|
9074
|
+
const planItemOutputSchema = z.object({
|
|
9075
|
+
id: z.number().int(),
|
|
9076
|
+
title: z.string(),
|
|
9077
|
+
notes: z.string().optional(),
|
|
9078
|
+
status: z.enum(PLAN_ITEM_STATUSES),
|
|
9079
|
+
assignee: z.string()
|
|
9080
|
+
}).strict();
|
|
9081
|
+
/** Render one Plan item for a tool result, with assignee text for the reader. */
|
|
9082
|
+
function outputPlanItem(item, assignee) {
|
|
9083
|
+
return {
|
|
9084
|
+
id: item.id,
|
|
9085
|
+
title: item.title,
|
|
9086
|
+
...item.notes ? { notes: item.notes } : void 0,
|
|
9087
|
+
status: item.status,
|
|
9088
|
+
assignee
|
|
9089
|
+
};
|
|
9090
|
+
}
|
|
8957
9091
|
// src/chat/tools/runtime/list-agents.ts
|
|
8958
9092
|
const TASK_MAX_LENGTH = 1e3;
|
|
8959
9093
|
const ERROR_MAX_LENGTH = 500;
|
|
@@ -9004,8 +9138,23 @@ const listedAgentSchema = z.object({
|
|
|
9004
9138
|
dashboard_url: z.string().url().optional().describe("Dashboard link of the conversation"),
|
|
9005
9139
|
archived: z.literal(true).optional().describe("The conversation is archived."),
|
|
9006
9140
|
error: z.string().optional().describe("Why the agent is blocked, failed, or stopped"),
|
|
9007
|
-
updated_at: z.string().describe("Time of the latest change")
|
|
9141
|
+
updated_at: z.string().describe("Time of the latest change"),
|
|
9142
|
+
plan: z.array(planItemOutputSchema).optional().describe("Open items of the parent's plan, read-only. Only on the parent. Assignee self is this conversation; parent is the parent's own agent.")
|
|
9008
9143
|
}).strict();
|
|
9144
|
+
/**
|
|
9145
|
+
* Render a parent's Plan item for its child: "self" is the child, and
|
|
9146
|
+
* "parent" is the parent's own agent.
|
|
9147
|
+
*/
|
|
9148
|
+
function parentPlanItem(item, conversationId) {
|
|
9149
|
+
const { assignee } = item;
|
|
9150
|
+
if (assignee.kind === "self") return outputPlanItem(item, "parent");
|
|
9151
|
+
if (assignee.kind === "agent" && assignee.conversationId === conversationId) return outputPlanItem(item, SELF_PLAN_ASSIGNEE);
|
|
9152
|
+
return outputPlanItem(item, renderPlanAssignee(assignee));
|
|
9153
|
+
}
|
|
9154
|
+
/** Open items of the parent's Plan. A child never edits them. */
|
|
9155
|
+
async function parentPlan(parentConversationId, conversationId) {
|
|
9156
|
+
return (await listPlanItems(getSqlExecutor(), parentConversationId)).filter((item) => isOpenPlanItemStatus(item.status)).map((item) => parentPlanItem(item, conversationId));
|
|
9157
|
+
}
|
|
9009
9158
|
function listedChildAgent(relation, agent) {
|
|
9010
9159
|
const dashboardUrl = getDashboardConversationLink(agent.childConversationId);
|
|
9011
9160
|
return {
|
|
@@ -9028,7 +9177,7 @@ const listAgentsOutputSchema = juniorToolOutputSchema.extend({ agents: z.array(l
|
|
|
9028
9177
|
const listAgentsToolDefinition = zodToolDefinition({
|
|
9029
9178
|
exposure: "deferred",
|
|
9030
9179
|
source: AGENTS_TOOL_SOURCE,
|
|
9031
|
-
description: "List the agents that this conversation can see, with the state recorded by the runtime: the child agents it started and, for a child agent, itself, its parent, and its siblings. Results of child agents arrive as new tasks, not through this tool.",
|
|
9180
|
+
description: "List the agents that this conversation can see, with the state recorded by the runtime: the child agents it started and, for a child agent, itself, its parent with the open items of the parent's plan, and its siblings. Results of child agents arrive as new tasks, not through this tool.",
|
|
9032
9181
|
annotations: {
|
|
9033
9182
|
destructiveHint: false,
|
|
9034
9183
|
idempotentHint: true,
|
|
@@ -9048,13 +9197,15 @@ function createListAgentsTool(context) {
|
|
|
9048
9197
|
...listAgentsToolDefinition,
|
|
9049
9198
|
execute: async () => {
|
|
9050
9199
|
const { children, parent, self, siblings } = await listAgentRelatives(context);
|
|
9200
|
+
const plan = parent ? await parentPlan(parent.conversationId, context.conversationId) : [];
|
|
9051
9201
|
return { agents: [
|
|
9052
9202
|
...self ? [listedChildAgent("self", self)] : [],
|
|
9053
9203
|
...parent ? [{
|
|
9054
9204
|
relation: "parent",
|
|
9055
9205
|
conversation_id: parent.conversationId,
|
|
9056
9206
|
status: parentAgentStatus(parent),
|
|
9057
|
-
updated_at: new Date(parent.updatedAtMs).toISOString()
|
|
9207
|
+
updated_at: new Date(parent.updatedAtMs).toISOString(),
|
|
9208
|
+
...plan.length > 0 ? { plan } : void 0
|
|
9058
9209
|
}] : [],
|
|
9059
9210
|
...children.map((agent) => listedChildAgent("child", agent)),
|
|
9060
9211
|
...siblings.map((agent) => listedChildAgent("sibling", agent))
|
|
@@ -9175,40 +9326,112 @@ function createStopAgentTool(conversationId) {
|
|
|
9175
9326
|
});
|
|
9176
9327
|
}
|
|
9177
9328
|
// src/chat/tools/runtime/update-plan.ts
|
|
9178
|
-
const
|
|
9179
|
-
|
|
9180
|
-
|
|
9181
|
-
|
|
9182
|
-
|
|
9183
|
-
|
|
9184
|
-
|
|
9185
|
-
}).strict();
|
|
9186
|
-
const updatePlanInputSchema = z.object({
|
|
9187
|
-
explanation: z.string().optional().describe("Optional explanation for this plan update."),
|
|
9188
|
-
plan: z.array(planItemSchema).describe("The list of steps")
|
|
9189
|
-
}).strict();
|
|
9329
|
+
const MAX_ITEMS_PER_CALL = 50;
|
|
9330
|
+
const statusSchema = z.enum(PLAN_ITEM_STATUSES).describe("done and cancelled close the item.");
|
|
9331
|
+
const assigneeSchema = z.string().trim().min(1).max(320).describe("Who does the item: `self`, the name or conversation_id of a child agent, or a person's email or mention such as `<@U123>`. Null or omitted on a new item means `self`.");
|
|
9332
|
+
const titleSchema = z.string().trim().min(1).max(200).describe("Short outcome to reach.");
|
|
9333
|
+
const notesSchema = z.string().trim().min(1).max(2e3).describe("What you need to do the item later, such as the brief for a child agent.");
|
|
9334
|
+
const itemIdSchema = z.number().int().positive().describe("Plan item id from an earlier result or a plan block.");
|
|
9335
|
+
const changesSchema = (item) => z.array(item).min(1).max(MAX_ITEMS_PER_CALL).nullable().optional();
|
|
9190
9336
|
const updatePlanToolDefinition = zodToolDefinition({
|
|
9191
9337
|
annotations: {
|
|
9192
9338
|
destructiveHint: false,
|
|
9193
|
-
idempotentHint:
|
|
9339
|
+
idempotentHint: false,
|
|
9194
9340
|
openWorldHint: false,
|
|
9195
9341
|
readOnlyHint: false
|
|
9196
9342
|
},
|
|
9197
|
-
description:
|
|
9198
|
-
|
|
9199
|
-
|
|
9200
|
-
|
|
9201
|
-
|
|
9202
|
-
|
|
9343
|
+
description: "Change the plan: the durable list of work that outlives this Turn, such as work queued for a later Turn, work for a child agent, or work for a person. It survives context compaction and sandbox resets. Do not add steps that you finish in this Turn. Give work for a child agent that child as assignee, with the brief in notes if you send it later. Each assignee can have one item in progress. Returns the items that changed, or every open item when the call changes nothing.",
|
|
9344
|
+
inputSchema: z.object({
|
|
9345
|
+
add: changesSchema(z.object({
|
|
9346
|
+
title: titleSchema,
|
|
9347
|
+
notes: notesSchema.nullable().optional(),
|
|
9348
|
+
status: statusSchema.nullable().optional().describe("Null or omitted means pending."),
|
|
9349
|
+
assignee: assigneeSchema.nullable().optional()
|
|
9350
|
+
}).strict()).describe("New items."),
|
|
9351
|
+
update: changesSchema(z.object({
|
|
9352
|
+
id: itemIdSchema,
|
|
9353
|
+
title: titleSchema.nullable().optional(),
|
|
9354
|
+
notes: notesSchema.nullable().optional().describe("New notes. Null clears them; omit to keep them."),
|
|
9355
|
+
status: statusSchema.nullable().optional(),
|
|
9356
|
+
assignee: assigneeSchema.nullable().optional()
|
|
9357
|
+
}).strict()).describe("Changes to existing items. Null or omitted fields stay."),
|
|
9358
|
+
remove: changesSchema(itemIdSchema).describe("Ids of items added by mistake. Close finished or dropped work with a status instead.")
|
|
9359
|
+
}).strict(),
|
|
9360
|
+
outputSchema: juniorToolOutputSchema.extend({
|
|
9361
|
+
items: z.array(planItemOutputSchema).describe("Items that this call added or changed, or every open item when it changed none."),
|
|
9362
|
+
removed_ids: z.array(z.number().int()).optional(),
|
|
9363
|
+
replaced_person_changes: z.array(z.object({
|
|
9364
|
+
id: z.number().int(),
|
|
9365
|
+
status: z.enum(PLAN_ITEM_STATUSES),
|
|
9366
|
+
changed_by: z.string()
|
|
9367
|
+
}).strict()).optional().describe("Statuses that a person set and this call replaced. Check that the person agrees, or set the status back.")
|
|
9368
|
+
})
|
|
9203
9369
|
});
|
|
9204
|
-
|
|
9205
|
-
|
|
9370
|
+
function outputItem(item) {
|
|
9371
|
+
return outputPlanItem(item, renderPlanAssignee(item.assignee));
|
|
9372
|
+
}
|
|
9373
|
+
/**
|
|
9374
|
+
* Resolve the assignee text of the model: the plan's own agent, one of its
|
|
9375
|
+
* child agents, or a person. Only a child of this conversation can take an
|
|
9376
|
+
* item, as with `stopAgent`.
|
|
9377
|
+
*/
|
|
9378
|
+
async function resolvePlanAssignee(context, value, findMentionedUserId) {
|
|
9379
|
+
const text = value.trim();
|
|
9380
|
+
if (text.toLowerCase() === "self" || text === context.conversationId) return { conversationId: context.conversationId };
|
|
9381
|
+
const childConversationId = await findChildAgentConversationId({
|
|
9382
|
+
parentConversationId: context.conversationId,
|
|
9383
|
+
target: text
|
|
9384
|
+
});
|
|
9385
|
+
if (childConversationId) return { conversationId: childConversationId };
|
|
9386
|
+
if (text.includes("@")) {
|
|
9387
|
+
const db = getDb();
|
|
9388
|
+
const tenant = (await readConversationAccessFromSql(db, [context.conversationId])).get(context.conversationId)?.tenant;
|
|
9389
|
+
const person = await resolveAssignee(db, text, tenant, findMentionedUserId);
|
|
9390
|
+
if ("userId" in person) return { userId: person.userId };
|
|
9391
|
+
}
|
|
9392
|
+
throw new ToolInputError(`Unknown assignee ${JSON.stringify(text)}. Use ${SELF_PLAN_ASSIGNEE}, the name or conversation_id of a child agent from listAgents, or the email or mention of one person.`);
|
|
9393
|
+
}
|
|
9394
|
+
/** Create the tool that changes the durable plan of one conversation. */
|
|
9395
|
+
function createUpdatePlanTool(context, findMentionedUserId) {
|
|
9396
|
+
const assignee = (value) => resolvePlanAssignee(context, value, findMentionedUserId);
|
|
9206
9397
|
return zodTool({
|
|
9207
9398
|
...updatePlanToolDefinition,
|
|
9208
|
-
execute: async () =>
|
|
9209
|
-
|
|
9210
|
-
|
|
9211
|
-
|
|
9399
|
+
execute: async (input) => {
|
|
9400
|
+
const add = input.add ?? [];
|
|
9401
|
+
const update = input.update ?? [];
|
|
9402
|
+
const remove = input.remove ?? [];
|
|
9403
|
+
const executor = getSqlExecutor();
|
|
9404
|
+
if (add.length + update.length + remove.length === 0) return { items: (await listPlanItems(executor, context.conversationId)).filter((item) => isOpenPlanItemStatus(item.status)).map(outputItem) };
|
|
9405
|
+
const { items, replacedPersonChanges } = await changePlan(executor, {
|
|
9406
|
+
conversationId: context.conversationId,
|
|
9407
|
+
nowMs: Date.now(),
|
|
9408
|
+
change: {
|
|
9409
|
+
add: await Promise.all(add.map(async (item) => ({
|
|
9410
|
+
title: item.title,
|
|
9411
|
+
...item.notes ? { notes: item.notes } : void 0,
|
|
9412
|
+
status: item.status ?? "pending",
|
|
9413
|
+
assignee: await assignee(item.assignee ?? "self")
|
|
9414
|
+
}))),
|
|
9415
|
+
update: await Promise.all(update.map(async (item) => ({
|
|
9416
|
+
id: item.id,
|
|
9417
|
+
...item.title ? { title: item.title } : void 0,
|
|
9418
|
+
...item.notes !== void 0 ? { notes: item.notes } : void 0,
|
|
9419
|
+
...item.status ? { status: item.status } : void 0,
|
|
9420
|
+
...item.assignee ? { assignee: await assignee(item.assignee) } : void 0
|
|
9421
|
+
}))),
|
|
9422
|
+
remove
|
|
9423
|
+
}
|
|
9424
|
+
});
|
|
9425
|
+
return {
|
|
9426
|
+
items: items.map(outputItem),
|
|
9427
|
+
...remove.length > 0 ? { removed_ids: remove } : void 0,
|
|
9428
|
+
...replacedPersonChanges.length > 0 ? { replaced_person_changes: replacedPersonChanges.map((item) => ({
|
|
9429
|
+
id: item.id,
|
|
9430
|
+
status: item.status,
|
|
9431
|
+
changed_by: item.changedBy.email
|
|
9432
|
+
})) } : void 0
|
|
9433
|
+
};
|
|
9434
|
+
}
|
|
9212
9435
|
});
|
|
9213
9436
|
}
|
|
9214
9437
|
// src/chat/tools/sandbox/bash.ts
|
|
@@ -9219,6 +9442,7 @@ const bashToolDefinition = zodToolDefinition({
|
|
|
9219
9442
|
openWorldHint: false,
|
|
9220
9443
|
readOnlyHint: false
|
|
9221
9444
|
},
|
|
9445
|
+
approvalMode: "auto",
|
|
9222
9446
|
description: "Run a bash command inside the isolated sandbox workspace. Use this for repository inspection/execution tasks that need shell access. Do not use for network-sensitive or destructive actions unless explicitly required.",
|
|
9223
9447
|
inputSchema: z.object({
|
|
9224
9448
|
command: z.string().min(1).describe("Bash command to run inside the sandbox."),
|
|
@@ -9298,7 +9522,7 @@ function createEditFileTool() {
|
|
|
9298
9522
|
// src/chat/tool-support/result-cap.ts
|
|
9299
9523
|
/** Default limit for the text that the model sees from one tool result. */
|
|
9300
9524
|
const TOOL_RESULT_MAX_CHARS = 32e3;
|
|
9301
|
-
const FULL_RESULT_DIR =
|
|
9525
|
+
const FULL_RESULT_DIR = `${SANDBOX_SCRATCH_ROOT}/spills`;
|
|
9302
9526
|
function fullResultPath(toolCallId) {
|
|
9303
9527
|
const id = createHash("sha256").update(toolCallId).digest("hex").slice(0, 8);
|
|
9304
9528
|
return `${FULL_RESULT_DIR}/${id}`;
|
|
@@ -9515,7 +9739,7 @@ function createWriteFileTool() {
|
|
|
9515
9739
|
// src/chat/tools/search-conversations.ts
|
|
9516
9740
|
const SUMMARY_MAX_LENGTH = 1e3;
|
|
9517
9741
|
const CONVERSATION_IDS_MAX = 25;
|
|
9518
|
-
const DEFAULT_LIMIT
|
|
9742
|
+
const DEFAULT_LIMIT = 10;
|
|
9519
9743
|
const MAX_LIMIT$1 = 25;
|
|
9520
9744
|
/**
|
|
9521
9745
|
* What the agent of the Conversation does now. The words match the
|
|
@@ -9585,7 +9809,7 @@ function searchConversationsInputSchema(channels) {
|
|
|
9585
9809
|
...channels ? { channel_id: channels.channelFilterSchema.nullable().optional().describe("Channel of the conversation.") } : void 0,
|
|
9586
9810
|
roots_only: z.boolean().nullable().optional().describe("Return only root conversations. Set false to also find child agents (Threads and Tasks) by their own Brief, title, or linked resources. Default true."),
|
|
9587
9811
|
include_archived: z.boolean().nullable().optional().describe("Include archived conversations, such as finished past work. Default false."),
|
|
9588
|
-
limit: z.number().int().min(1).max(MAX_LIMIT$1).nullable().optional().describe(`Maximum results. Default ${DEFAULT_LIMIT
|
|
9812
|
+
limit: z.number().int().min(1).max(MAX_LIMIT$1).nullable().optional().describe(`Maximum results. Default ${DEFAULT_LIMIT}; max ${MAX_LIMIT$1}.`)
|
|
9589
9813
|
}).strict();
|
|
9590
9814
|
}
|
|
9591
9815
|
/** Static definition of `searchConversations`, with the provider channel filter when there is one. */
|
|
@@ -9632,7 +9856,7 @@ function createSearchConversationsTool(context) {
|
|
|
9632
9856
|
...channelId ? { channelId } : void 0,
|
|
9633
9857
|
...conversationIds ? { conversationIds } : void 0,
|
|
9634
9858
|
includeArchived: input.include_archived ?? false,
|
|
9635
|
-
limit: input.limit ?? DEFAULT_LIMIT
|
|
9859
|
+
limit: input.limit ?? DEFAULT_LIMIT,
|
|
9636
9860
|
...outcomeStatus ? { outcomeStatus } : void 0,
|
|
9637
9861
|
...query ? { query } : void 0,
|
|
9638
9862
|
rootsOnly: input.roots_only ?? true
|
|
@@ -9642,11 +9866,209 @@ function createSearchConversationsTool(context) {
|
|
|
9642
9866
|
}
|
|
9643
9867
|
});
|
|
9644
9868
|
}
|
|
9645
|
-
// src/chat/
|
|
9646
|
-
|
|
9869
|
+
// src/chat/conversations/event-search.ts
|
|
9870
|
+
/**
|
|
9871
|
+
* Hybrid text search over the event history of one Conversation, across
|
|
9872
|
+
* every history version, so a query finds what compaction removed from the
|
|
9873
|
+
* model context.
|
|
9874
|
+
*
|
|
9875
|
+
* Two legs rank the searchable events. Keyword: BM25 over Postgres full-text
|
|
9876
|
+
* lexemes, which `event-lexemes.ts` stores after each Turn. An event with no
|
|
9877
|
+
* stored lexemes yet gets them computed for the query. Meaning: cosine
|
|
9878
|
+
* distance to the event embeddings that `event-embedding.ts` stores after
|
|
9879
|
+
* each Turn. Reciprocal rank fusion combines the two ranks, so neither leg
|
|
9880
|
+
* needs a score threshold.
|
|
9881
|
+
*
|
|
9882
|
+
* The agent's tool calls count half in the fusion, so what a tool returned
|
|
9883
|
+
* ranks above the call that repeats the query's words. The input of the
|
|
9884
|
+
* running Turn is not a result: it is in the model context already.
|
|
9885
|
+
*
|
|
9886
|
+
* The caller checks access to the Conversation first.
|
|
9887
|
+
*
|
|
9888
|
+
* Attributes on the `searchConversationEvents` `gen_ai.execute_tool` span:
|
|
9889
|
+
* - `app.event_search.keyword.candidate.count`: events with a query lexeme.
|
|
9890
|
+
* - `app.event_search.keyword.computed.count`: events whose lexemes were
|
|
9891
|
+
* computed for this query because none were stored yet.
|
|
9892
|
+
* - `app.event_search.keyword_ms`, `app.event_search.meaning_ms`: time of
|
|
9893
|
+
* each leg, which run at the same time.
|
|
9894
|
+
* - `app.event_search.meaning.candidate.count`: events with a vector.
|
|
9895
|
+
* - `app.event_search.meaning.top_distance`: cosine distance of the nearest
|
|
9896
|
+
* event, to tune a similarity floor.
|
|
9897
|
+
* - `app.event_search.result.count`: events returned.
|
|
9898
|
+
* Without an embedder, the meaning attributes are not set.
|
|
9899
|
+
* Policy: policies/observability.md.
|
|
9900
|
+
*/
|
|
9901
|
+
const MAX_COMPUTED_EVENTS = 2e4;
|
|
9902
|
+
const CANDIDATES_PER_LEG = 100;
|
|
9903
|
+
const BM25_B = .75;
|
|
9904
|
+
const TOOL_CALL_WEIGHT = .5;
|
|
9905
|
+
/**
|
|
9906
|
+
* Rank keyword candidates with Okapi BM25. Document frequencies and the mean
|
|
9907
|
+
* length come from the candidates, which are every event that has a query
|
|
9908
|
+
* lexeme. Length is the count of distinct lexemes, the size that Postgres
|
|
9909
|
+
* stores for a tsvector.
|
|
9910
|
+
*/
|
|
9911
|
+
function rankKeywordCandidates(candidates, searchedEvents) {
|
|
9912
|
+
if (candidates.length === 0) return [];
|
|
9913
|
+
const documentFrequency = /* @__PURE__ */ new Map();
|
|
9914
|
+
for (const candidate of candidates) for (const term of Object.keys(candidate.termFrequencies)) documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1);
|
|
9915
|
+
const total = Math.max(searchedEvents, candidates.length);
|
|
9916
|
+
const meanLength = candidates.reduce((sum, candidate) => sum + candidate.length, 0) / candidates.length;
|
|
9917
|
+
const score = (candidate) => Object.entries(candidate.termFrequencies).reduce((sum, [term, tf]) => {
|
|
9918
|
+
const idf = bm25InverseDocumentFrequency(total, documentFrequency.get(term) ?? 0);
|
|
9919
|
+
const frequency = bm25NormalizedFrequency(tf, candidate.length, meanLength, BM25_B);
|
|
9920
|
+
return sum + idf * bm25Saturation(frequency);
|
|
9921
|
+
}, 0);
|
|
9922
|
+
return candidates.map((candidate) => ({
|
|
9923
|
+
seq: candidate.seq,
|
|
9924
|
+
score: score(candidate)
|
|
9925
|
+
})).sort((left, right) => right.score - left.score || right.seq - left.seq).map(({ seq }) => seq);
|
|
9926
|
+
}
|
|
9927
|
+
/**
|
|
9928
|
+
* Fuse ranked event lists with reciprocal rank fusion. An event in both
|
|
9929
|
+
* lists ranks above an event in one. Events in `toolCalls` count
|
|
9930
|
+
* `TOOL_CALL_WEIGHT` as much. Ties go to the newer event.
|
|
9931
|
+
*/
|
|
9932
|
+
function fuseEventRanks(lists, toolCalls = /* @__PURE__ */ new Set()) {
|
|
9933
|
+
const ranked = lists.flatMap((list) => {
|
|
9934
|
+
const entries = list.map((seq, index) => ({
|
|
9935
|
+
item: seq,
|
|
9936
|
+
rank: index + 1
|
|
9937
|
+
}));
|
|
9938
|
+
return [entries.filter((entry) => !toolCalls.has(entry.item)), entries.filter((entry) => toolCalls.has(entry.item))];
|
|
9939
|
+
});
|
|
9940
|
+
return fuseRankedLists(ranked, {
|
|
9941
|
+
key: (seq) => seq,
|
|
9942
|
+
tiebreak: (left, right) => right - left,
|
|
9943
|
+
weights: ranked.map((_, index) => index % 2 ? TOOL_CALL_WEIGHT : 1)
|
|
9944
|
+
});
|
|
9945
|
+
}
|
|
9946
|
+
async function searchBounds(db, search, types) {
|
|
9947
|
+
const events = juniorConversationEvents;
|
|
9948
|
+
return and(eq(events.conversationId, search.conversationId), inArray(events.type, [...types]), search.afterSeq === void 0 ? void 0 : gt(events.seq, search.afterSeq), search.beforeSeq === void 0 ? void 0 : lt(events.seq, search.beforeSeq), search.currentTurnId === void 0 ? void 0 : await notTurnInput(db, search.conversationId, search.currentTurnId));
|
|
9949
|
+
}
|
|
9950
|
+
async function notTurnInput(db, conversationId, turnId) {
|
|
9951
|
+
const events = juniorConversationEvents;
|
|
9952
|
+
const [started] = await db.select({
|
|
9953
|
+
seq: events.seq,
|
|
9954
|
+
inputMessageIds: sql`${events.payload}->'inputMessageIds'`
|
|
9955
|
+
}).from(events).where(and(eq(events.conversationId, conversationId), eq(events.type, "turn_started"), eq(sql`${events.payload}->>'turnId'`, turnId))).limit(1);
|
|
9956
|
+
if (!started) return void 0;
|
|
9957
|
+
return not(or(and(eq(events.type, "user_message"), gt(events.seq, started.seq)), and(inArray(events.type, ["message", "message_updated"]), inArray(sql`${events.payload}->>'messageId'`, started.inputMessageIds))));
|
|
9958
|
+
}
|
|
9959
|
+
async function toolCallSeqs(db, conversationId, seqs) {
|
|
9960
|
+
if (seqs.length === 0) return /* @__PURE__ */ new Set();
|
|
9961
|
+
const events = juniorConversationEvents;
|
|
9962
|
+
const rows = await db.select({ seq: events.seq }).from(events).where(and(eq(events.conversationId, conversationId), inArray(events.seq, [...seqs]), callsToolSql()));
|
|
9963
|
+
return new Set(rows.map((row) => row.seq));
|
|
9964
|
+
}
|
|
9965
|
+
async function keywordRanks(db, search, bounds) {
|
|
9966
|
+
const events = juniorConversationEvents;
|
|
9967
|
+
const stored = juniorConversationEventLexemes;
|
|
9968
|
+
const storedRow = and(eq(stored.conversationId, events.conversationId), eq(stored.seq, events.seq));
|
|
9969
|
+
const queryVector = lexemesSql(search.query);
|
|
9970
|
+
const tsquery = sql`regexp_replace(strip(${queryVector})::text, ''' ''', ''' | ''', 'g')::tsquery`;
|
|
9971
|
+
const storedDocuments = db.select({
|
|
9972
|
+
seq: events.seq,
|
|
9973
|
+
searchVector: sql`${stored.lexemes}`.as("search_vector")
|
|
9974
|
+
}).from(stored).innerJoin(events, storedRow).where(and(bounds, sql`${stored.lexemes} @@ ${tsquery}`)).as("stored_events");
|
|
9975
|
+
const unstored = await db.select({ seq: events.seq }).from(events).leftJoin(stored, storedRow).where(and(bounds, isNull(stored.seq))).orderBy(desc(events.seq)).limit(MAX_COMPUTED_EVENTS);
|
|
9976
|
+
const computedDocuments = db.select({
|
|
9977
|
+
seq: events.seq,
|
|
9978
|
+
searchVector: sql`${lexemesSql(searchedEventTextSql())}`.as("search_vector")
|
|
9979
|
+
}).from(events).where(and(eq(events.conversationId, search.conversationId), seqIn(unstored.map((row) => row.seq)))).limit(MAX_COMPUTED_EVENTS).as("computed_events");
|
|
9980
|
+
const [storedCandidates, computedCandidates, [searched]] = await Promise.all([
|
|
9981
|
+
keywordCandidates(db, storedDocuments, queryVector),
|
|
9982
|
+
unstored.length === 0 ? [] : keywordCandidates(db, computedDocuments, queryVector, tsquery),
|
|
9983
|
+
db.select({ total: count() }).from(events).where(bounds)
|
|
9984
|
+
]);
|
|
9985
|
+
const candidates = [...storedCandidates, ...computedCandidates];
|
|
9986
|
+
return {
|
|
9987
|
+
candidates: candidates.length,
|
|
9988
|
+
computed: unstored.length,
|
|
9989
|
+
seqs: rankKeywordCandidates(candidates, searched?.total ?? 0).slice(0, CANDIDATES_PER_LEG)
|
|
9990
|
+
};
|
|
9991
|
+
}
|
|
9992
|
+
async function keywordCandidates(db, documents, queryVector, tsquery) {
|
|
9993
|
+
return (await db.select({
|
|
9994
|
+
seq: documents.seq,
|
|
9995
|
+
length: sql`length(${documents.searchVector})`,
|
|
9996
|
+
termFrequencies: sql`(
|
|
9997
|
+
SELECT coalesce(jsonb_object_agg(lexeme, coalesce(cardinality(positions), 1)), '{}'::jsonb)
|
|
9998
|
+
FROM unnest(ts_filter(setweight(${documents.searchVector}, 'A', tsvector_to_array(${queryVector})), '{a}'))
|
|
9999
|
+
)`
|
|
10000
|
+
}).from(documents).where(tsquery ? sql`${documents.searchVector} @@ ${tsquery}` : void 0)).map((row) => ({
|
|
10001
|
+
...row,
|
|
10002
|
+
length: Number(row.length)
|
|
10003
|
+
}));
|
|
10004
|
+
}
|
|
10005
|
+
async function meaningRanks(db, search, bounds) {
|
|
10006
|
+
if (!search.embedder) return { seqs: [] };
|
|
10007
|
+
const query = await embedConversationQuery(search.embedder, search.query);
|
|
10008
|
+
const events = juniorConversationEvents;
|
|
10009
|
+
const embeddings = juniorConversationEventEmbeddings;
|
|
10010
|
+
const distance = guardedCosineDistance({
|
|
10011
|
+
column: embeddings.embedding,
|
|
10012
|
+
dimensions: embeddings.dimensions,
|
|
10013
|
+
query: query.vector,
|
|
10014
|
+
type: "halfvec"
|
|
10015
|
+
});
|
|
10016
|
+
const rows = await db.select({
|
|
10017
|
+
seq: embeddings.seq,
|
|
10018
|
+
distance
|
|
10019
|
+
}).from(embeddings).innerJoin(events, and(eq(events.conversationId, embeddings.conversationId), eq(events.seq, embeddings.seq))).where(and(bounds, eq(embeddings.provider, query.provider), eq(embeddings.model, query.model), eq(embeddings.dimensions, query.vector.length))).orderBy(distance).limit(CANDIDATES_PER_LEG);
|
|
10020
|
+
const top = rows[0];
|
|
10021
|
+
return {
|
|
10022
|
+
seqs: rows.map((row) => row.seq),
|
|
10023
|
+
...top ? { topDistance: Number(top.distance) } : void 0
|
|
10024
|
+
};
|
|
10025
|
+
}
|
|
10026
|
+
/** Search the event text of one Conversation. Best match first. */
|
|
10027
|
+
async function searchConversationEventText(db, search) {
|
|
10028
|
+
const types = SEARCHABLE_EVENT_TYPES.filter((type) => !search.types || search.types.includes(type));
|
|
10029
|
+
if (types.length === 0) return [];
|
|
10030
|
+
const bounds = await searchBounds(db, search, types);
|
|
10031
|
+
const timed = async (work) => {
|
|
10032
|
+
const startedAt = Date.now();
|
|
10033
|
+
return {
|
|
10034
|
+
...await work,
|
|
10035
|
+
ms: Date.now() - startedAt
|
|
10036
|
+
};
|
|
10037
|
+
};
|
|
10038
|
+
const [keyword, meaning] = await Promise.all([timed(keywordRanks(db, search, bounds)), timed(meaningRanks(db, search, bounds))]);
|
|
10039
|
+
const toolCalls = await toolCallSeqs(db, search.conversationId, [.../* @__PURE__ */ new Set([...keyword.seqs, ...meaning.seqs])]);
|
|
10040
|
+
const seqs = fuseEventRanks([keyword.seqs, meaning.seqs], toolCalls).slice(0, search.limit);
|
|
10041
|
+
setSpanAttributes({
|
|
10042
|
+
"app.event_search.keyword.candidate.count": keyword.candidates,
|
|
10043
|
+
"app.event_search.keyword.computed.count": keyword.computed,
|
|
10044
|
+
"app.event_search.keyword_ms": keyword.ms,
|
|
10045
|
+
"app.event_search.result.count": seqs.length,
|
|
10046
|
+
...search.embedder ? {
|
|
10047
|
+
"app.event_search.meaning.candidate.count": meaning.seqs.length,
|
|
10048
|
+
"app.event_search.meaning.top_distance": meaning.topDistance,
|
|
10049
|
+
"app.event_search.meaning_ms": meaning.ms
|
|
10050
|
+
} : void 0
|
|
10051
|
+
});
|
|
10052
|
+
if (seqs.length === 0) return [];
|
|
10053
|
+
const events = juniorConversationEvents;
|
|
10054
|
+
const rows = await db.select({
|
|
10055
|
+
row: events,
|
|
10056
|
+
text: searchedEventTextSql()
|
|
10057
|
+
}).from(events).where(and(eq(events.conversationId, search.conversationId), inArray(events.seq, seqs)));
|
|
10058
|
+
const bySeq = new Map(rows.map((row) => [row.row.seq, row]));
|
|
10059
|
+
const terms = excerptTerms(search.query);
|
|
10060
|
+
return seqs.flatMap((seq) => {
|
|
10061
|
+
const match = bySeq.get(seq);
|
|
10062
|
+
return match ? [{
|
|
10063
|
+
event: eventFromRow(match.row),
|
|
10064
|
+
excerpt: eventExcerpt(match.text ?? "", terms)
|
|
10065
|
+
}] : [];
|
|
10066
|
+
});
|
|
10067
|
+
}
|
|
9647
10068
|
const MAX_LIMIT = 100;
|
|
9648
10069
|
const MAX_EVENT_DATA_BYTES = 4e3;
|
|
9649
10070
|
const MAX_IDENTITY_CHARS = 256;
|
|
10071
|
+
const MAX_QUERY_CHARS = 200;
|
|
9650
10072
|
const textEncoder = new TextEncoder();
|
|
9651
10073
|
const knownEventTypeSchema = z.enum(KNOWN_CONVERSATION_EVENT_TYPES);
|
|
9652
10074
|
const projectedEventSchema = z.object({
|
|
@@ -9654,16 +10076,17 @@ const projectedEventSchema = z.object({
|
|
|
9654
10076
|
history_version: z.number().int().nonnegative().describe("Agent history generation after replacement."),
|
|
9655
10077
|
created_at: z.iso.datetime().describe("When the event was recorded."),
|
|
9656
10078
|
idempotency_key: z.string().min(1).optional().describe("Retry-stable event identity, when assigned."),
|
|
9657
|
-
data: z.record(z.string(), z.unknown()).describe("Bounded event data. Read an omitted payload with readConversationEvent.")
|
|
10079
|
+
data: z.record(z.string(), z.unknown()).describe("Bounded event data. With a query, only its identity fields. Read an omitted payload with readConversationEvent."),
|
|
10080
|
+
excerpt: z.string().optional().describe("Event text around the best query match.")
|
|
9658
10081
|
}).strict();
|
|
9659
10082
|
const searchConversationEventsOutputSchema = juniorToolOutputSchema.extend({
|
|
9660
10083
|
conversation_id: z.string().min(1),
|
|
9661
|
-
events: z.array(projectedEventSchema),
|
|
9662
|
-
has_older: z.boolean().describe("Whether matching older events exist."),
|
|
9663
|
-
has_newer: z.boolean().describe("Whether matching newer events exist.")
|
|
10084
|
+
events: z.array(projectedEventSchema).describe("Best match first for a query, else in seq order."),
|
|
10085
|
+
has_older: z.boolean().optional().describe("Whether matching older events exist. Omitted for a query."),
|
|
10086
|
+
has_newer: z.boolean().optional().describe("Whether matching newer events exist. Omitted for a query.")
|
|
9664
10087
|
});
|
|
9665
10088
|
const searchConversationEventsToolDefinition = zodToolDefinition({
|
|
9666
|
-
description: "Search the durable event log for one conversation, including messages, agent history, tool results, and compactions. Defaults to the current conversation. Outside the current conversation tree, only retained public conversations are accessible.",
|
|
10089
|
+
description: "Search the durable event log for one conversation, including messages, agent history, tool results, and compactions, across every history version. Finds events by words or meaning, or pages them in seq order. Defaults to the current conversation. Outside the current conversation tree, only retained public conversations are accessible.",
|
|
9667
10090
|
exposure: "deferred",
|
|
9668
10091
|
source: CONVERSATIONS_TOOL_SOURCE,
|
|
9669
10092
|
annotations: {
|
|
@@ -9674,15 +10097,16 @@ const searchConversationEventsToolDefinition = zodToolDefinition({
|
|
|
9674
10097
|
},
|
|
9675
10098
|
inputSchema: z.object({
|
|
9676
10099
|
conversation_id: z.string().trim().min(1).nullable().describe("Conversation ID to search. Omit or null for the current conversation.").optional(),
|
|
10100
|
+
query: z.string().trim().min(1).max(MAX_QUERY_CHARS).nullable().describe("Words or meaning to find in messages, agent history, and tool calls and results, such as a path, URL, id, or name. Any word may match. Omit or null to page in seq order.").optional(),
|
|
9677
10101
|
after_seq: z.number().int().nonnegative().nullable().describe("Exclusive event sequence lower bound; returns ascending.").optional(),
|
|
9678
10102
|
before_seq: z.number().int().nonnegative().nullable().describe("Exclusive event sequence upper bound.").optional(),
|
|
9679
|
-
limit: z.number().int().min(1).max(MAX_LIMIT).nullable().describe(`Maximum events. Default
|
|
10103
|
+
limit: z.number().int().min(1).max(MAX_LIMIT).nullable().describe(`Maximum events. Default 25; max ${MAX_LIMIT}.`).optional(),
|
|
9680
10104
|
types: z.array(knownEventTypeSchema).min(1).nullable().describe("Event types to include; omit for all types.").optional()
|
|
9681
10105
|
}).strict(),
|
|
9682
10106
|
outputSchema: searchConversationEventsOutputSchema
|
|
9683
10107
|
});
|
|
9684
10108
|
/** Create a deferred tool that searches one conversation's durable event log. */
|
|
9685
|
-
function createSearchConversationEventsTool(context) {
|
|
10109
|
+
function createSearchConversationEventsTool(context, options = {}) {
|
|
9686
10110
|
return zodTool({
|
|
9687
10111
|
...searchConversationEventsToolDefinition,
|
|
9688
10112
|
execute: async (input) => {
|
|
@@ -9690,10 +10114,27 @@ function createSearchConversationEventsTool(context) {
|
|
|
9690
10114
|
const conversationId = input.conversation_id?.trim() || currentConversationId;
|
|
9691
10115
|
const afterSeq = input.after_seq ?? void 0;
|
|
9692
10116
|
const beforeSeq = input.before_seq ?? void 0;
|
|
9693
|
-
const limit = input.limit ??
|
|
10117
|
+
const limit = input.limit ?? 25;
|
|
9694
10118
|
const types = input.types ?? void 0;
|
|
9695
10119
|
if (afterSeq !== void 0 && beforeSeq !== void 0 && afterSeq >= beforeSeq) throw new ToolInputError("after_seq must be less than before_seq when both are provided");
|
|
9696
10120
|
await assertCanReadConversationEvents(context, conversationId);
|
|
10121
|
+
const query = input.query ?? void 0;
|
|
10122
|
+
if (query) return {
|
|
10123
|
+
conversation_id: conversationId,
|
|
10124
|
+
events: (await searchConversationEventText(getDb(), {
|
|
10125
|
+
conversationId,
|
|
10126
|
+
limit,
|
|
10127
|
+
query,
|
|
10128
|
+
...conversationId === currentConversationId && context.turnId ? { currentTurnId: context.turnId } : void 0,
|
|
10129
|
+
...afterSeq === void 0 ? void 0 : { afterSeq },
|
|
10130
|
+
...beforeSeq === void 0 ? void 0 : { beforeSeq },
|
|
10131
|
+
...types === void 0 ? void 0 : { types },
|
|
10132
|
+
...options.embedder ? { embedder: options.embedder } : void 0
|
|
10133
|
+
})).map((match) => ({
|
|
10134
|
+
...projectEvent(match.event, { omitPayload: true }),
|
|
10135
|
+
excerpt: match.excerpt
|
|
10136
|
+
}))
|
|
10137
|
+
};
|
|
9697
10138
|
const page = await getConversationEventStore().query(conversationId, {
|
|
9698
10139
|
limit,
|
|
9699
10140
|
...afterSeq === void 0 ? void 0 : { afterSeq },
|
|
@@ -9702,15 +10143,15 @@ function createSearchConversationEventsTool(context) {
|
|
|
9702
10143
|
});
|
|
9703
10144
|
return {
|
|
9704
10145
|
conversation_id: conversationId,
|
|
9705
|
-
events: page.events.map(projectEvent),
|
|
10146
|
+
events: page.events.map((event) => projectEvent(event)),
|
|
9706
10147
|
has_older: page.hasOlder,
|
|
9707
10148
|
has_newer: page.hasNewer
|
|
9708
10149
|
};
|
|
9709
10150
|
}
|
|
9710
10151
|
});
|
|
9711
10152
|
}
|
|
9712
|
-
function projectEvent(event) {
|
|
9713
|
-
const data = boundEventData(stripReplacementHistory(event.data));
|
|
10153
|
+
function projectEvent(event, options = {}) {
|
|
10154
|
+
const data = boundEventData(stripReplacementHistory(event.data), options);
|
|
9714
10155
|
return {
|
|
9715
10156
|
seq: event.seq,
|
|
9716
10157
|
history_version: event.historyVersion,
|
|
@@ -9719,9 +10160,9 @@ function projectEvent(event) {
|
|
|
9719
10160
|
data
|
|
9720
10161
|
};
|
|
9721
10162
|
}
|
|
9722
|
-
function boundEventData(data) {
|
|
10163
|
+
function boundEventData(data, options) {
|
|
9723
10164
|
const payloadJsonBytes = jsonByteLength(data);
|
|
9724
|
-
if (payloadJsonBytes <= MAX_EVENT_DATA_BYTES) return data;
|
|
10165
|
+
if (!options.omitPayload && payloadJsonBytes <= MAX_EVENT_DATA_BYTES) return data;
|
|
9725
10166
|
return {
|
|
9726
10167
|
...eventIdentity(data),
|
|
9727
10168
|
payload_omitted: true,
|
|
@@ -10056,168 +10497,6 @@ function createUpdateUserCustomizationTool(context) {
|
|
|
10056
10497
|
}
|
|
10057
10498
|
});
|
|
10058
10499
|
}
|
|
10059
|
-
// src/chat/slack/users.ts
|
|
10060
|
-
const profileFieldsSchema = z.object({ fields: z.record(z.string(), z.object({
|
|
10061
|
-
value: z.string().optional(),
|
|
10062
|
-
alt: z.string().optional(),
|
|
10063
|
-
label: z.string().optional()
|
|
10064
|
-
}).nullable()).nullish() });
|
|
10065
|
-
function normalizeUser(raw) {
|
|
10066
|
-
const rawFields = profileFieldsSchema.parse(raw.profile ?? {}).fields;
|
|
10067
|
-
const profileFields = [];
|
|
10068
|
-
if (rawFields) for (const [id, field] of Object.entries(rawFields)) {
|
|
10069
|
-
if (!field) continue;
|
|
10070
|
-
profileFields.push({
|
|
10071
|
-
id,
|
|
10072
|
-
label: field.label || void 0,
|
|
10073
|
-
value: field.value || void 0,
|
|
10074
|
-
alt: field.alt || void 0
|
|
10075
|
-
});
|
|
10076
|
-
}
|
|
10077
|
-
return {
|
|
10078
|
-
id: raw.id ?? "",
|
|
10079
|
-
team_id: raw.team_id || void 0,
|
|
10080
|
-
name: raw.name || void 0,
|
|
10081
|
-
real_name: raw.real_name || raw.profile?.real_name || void 0,
|
|
10082
|
-
display_name: raw.profile?.display_name || void 0,
|
|
10083
|
-
title: raw.profile?.title || void 0,
|
|
10084
|
-
email: raw.profile?.email || void 0,
|
|
10085
|
-
status_text: raw.profile?.status_text ?? void 0,
|
|
10086
|
-
status_emoji: raw.profile?.status_emoji ?? void 0,
|
|
10087
|
-
avatar_url: raw.profile?.image_512 || void 0,
|
|
10088
|
-
is_bot: raw.is_bot ?? false,
|
|
10089
|
-
is_deleted: raw.deleted ?? false,
|
|
10090
|
-
timezone: raw.tz || void 0,
|
|
10091
|
-
...profileFields.length > 0 ? { profile_fields: profileFields } : void 0
|
|
10092
|
-
};
|
|
10093
|
-
}
|
|
10094
|
-
function normalizeNameTokens(value) {
|
|
10095
|
-
return value.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
|
|
10096
|
-
}
|
|
10097
|
-
function nameFields(user) {
|
|
10098
|
-
return [
|
|
10099
|
-
user.name ?? "",
|
|
10100
|
-
user.profile?.display_name ?? "",
|
|
10101
|
-
user.real_name ?? user.profile?.real_name ?? ""
|
|
10102
|
-
].map((value) => value.toLowerCase().trim()).filter(Boolean);
|
|
10103
|
-
}
|
|
10104
|
-
/** Look up a Slack user by ID, returning the full profile including custom fields. */
|
|
10105
|
-
async function lookupSlackUserProfile(userId) {
|
|
10106
|
-
const client = getSlackClient();
|
|
10107
|
-
const user = (await withSlackRetries(() => client.users.info({ user: userId }), 3, { action: "users.info" })).user;
|
|
10108
|
-
if (!user) throw new Error(`Slack users.info returned no user for ${userId}`);
|
|
10109
|
-
return normalizeUser(user);
|
|
10110
|
-
}
|
|
10111
|
-
/** Look up a Slack bot by ID. Returns undefined when Slack has no such bot. */
|
|
10112
|
-
async function lookupSlackBot(botId) {
|
|
10113
|
-
try {
|
|
10114
|
-
return (await withSlackRetries(() => getSlackClient().bots.info({ bot: botId }), 3, { action: "bots.info" })).bot;
|
|
10115
|
-
} catch (error) {
|
|
10116
|
-
if (error instanceof SlackActionError && error.apiError === "bot_not_found") return;
|
|
10117
|
-
throw error;
|
|
10118
|
-
}
|
|
10119
|
-
}
|
|
10120
|
-
/** Look up a Slack user by email. Returns null when no user matches. */
|
|
10121
|
-
async function lookupSlackUserByEmail(email) {
|
|
10122
|
-
const client = getSlackClient();
|
|
10123
|
-
let result;
|
|
10124
|
-
try {
|
|
10125
|
-
result = await withSlackRetries(() => client.users.lookupByEmail({ email }), 3, { action: "users.lookupByEmail" });
|
|
10126
|
-
} catch (error) {
|
|
10127
|
-
if (error instanceof SlackActionError && error.apiError === "users_not_found") return null;
|
|
10128
|
-
throw error;
|
|
10129
|
-
}
|
|
10130
|
-
const user = result.user;
|
|
10131
|
-
if (!user) return null;
|
|
10132
|
-
return normalizeUser(user);
|
|
10133
|
-
}
|
|
10134
|
-
/**
|
|
10135
|
-
* Rank Slack name-search quality for one candidate.
|
|
10136
|
-
* Exact field and token matches beat field prefixes so a display-name prefix
|
|
10137
|
-
* cannot outrank a real-name first-name hit.
|
|
10138
|
-
*/
|
|
10139
|
-
function scoreNameMatch(user, query) {
|
|
10140
|
-
const queryLower = query.toLowerCase().trim();
|
|
10141
|
-
if (!queryLower) return 0;
|
|
10142
|
-
const fields = nameFields(user);
|
|
10143
|
-
if (fields.length === 0) return 0;
|
|
10144
|
-
let best = 0;
|
|
10145
|
-
const queryTokens = normalizeNameTokens(queryLower);
|
|
10146
|
-
for (const field of fields) {
|
|
10147
|
-
if (field === queryLower) {
|
|
10148
|
-
best = Math.max(best, 100);
|
|
10149
|
-
continue;
|
|
10150
|
-
}
|
|
10151
|
-
if (field.startsWith(queryLower)) best = Math.max(best, 70);
|
|
10152
|
-
else if (field.includes(queryLower)) best = Math.max(best, 25);
|
|
10153
|
-
const tokens = normalizeNameTokens(field);
|
|
10154
|
-
for (const token of tokens) if (token === queryLower) best = Math.max(best, 85);
|
|
10155
|
-
else if (token.startsWith(queryLower)) best = Math.max(best, 60);
|
|
10156
|
-
if (queryTokens.length > 1 && queryTokens.every((queryToken) => tokens.some((token) => token === queryToken || token.startsWith(queryToken)))) best = Math.max(best, 95);
|
|
10157
|
-
}
|
|
10158
|
-
return best;
|
|
10159
|
-
}
|
|
10160
|
-
function compareNameMatches(left, right) {
|
|
10161
|
-
if (right.score !== left.score) return right.score - left.score;
|
|
10162
|
-
return (left.user.name ?? "").localeCompare(right.user.name ?? "");
|
|
10163
|
-
}
|
|
10164
|
-
async function listWorkspaceUsers(options) {
|
|
10165
|
-
const client = getSlackClient();
|
|
10166
|
-
const matches = [];
|
|
10167
|
-
let cursor;
|
|
10168
|
-
let pages = 0;
|
|
10169
|
-
let totalScanned = 0;
|
|
10170
|
-
while (pages < options.maxPages) {
|
|
10171
|
-
pages++;
|
|
10172
|
-
const result = await withSlackRetries(() => client.users.list({
|
|
10173
|
-
limit: 200,
|
|
10174
|
-
...cursor ? { cursor } : void 0
|
|
10175
|
-
}), 3, { action: "users.list" });
|
|
10176
|
-
const members = result.members ?? [];
|
|
10177
|
-
totalScanned += members.length;
|
|
10178
|
-
for (const member of members) {
|
|
10179
|
-
if (!options.includeDeleted && member.deleted) continue;
|
|
10180
|
-
if (!options.includeBots && member.is_bot) continue;
|
|
10181
|
-
if (member.id === "USLACKBOT") continue;
|
|
10182
|
-
const score = options.score(member);
|
|
10183
|
-
if (score <= 0) continue;
|
|
10184
|
-
matches.push({
|
|
10185
|
-
user: member,
|
|
10186
|
-
score
|
|
10187
|
-
});
|
|
10188
|
-
}
|
|
10189
|
-
const nextCursor = result.response_metadata?.next_cursor;
|
|
10190
|
-
if (!nextCursor) {
|
|
10191
|
-
cursor = void 0;
|
|
10192
|
-
break;
|
|
10193
|
-
}
|
|
10194
|
-
cursor = nextCursor;
|
|
10195
|
-
}
|
|
10196
|
-
return {
|
|
10197
|
-
matches,
|
|
10198
|
-
searched_pages: pages,
|
|
10199
|
-
searched_user_count: totalScanned,
|
|
10200
|
-
truncated: pages >= options.maxPages && Boolean(cursor)
|
|
10201
|
-
};
|
|
10202
|
-
}
|
|
10203
|
-
/** Search workspace users by name with bounded pagination through `users.list`. */
|
|
10204
|
-
async function searchSlackUsers(options) {
|
|
10205
|
-
const { query, limit = 10, maxPages = 3, includeDeleted = false, includeBots = false } = options;
|
|
10206
|
-
const queryLower = query.toLowerCase().trim();
|
|
10207
|
-
const listed = await listWorkspaceUsers({
|
|
10208
|
-
maxPages,
|
|
10209
|
-
includeDeleted,
|
|
10210
|
-
includeBots,
|
|
10211
|
-
score: (member) => scoreNameMatch(member, queryLower)
|
|
10212
|
-
});
|
|
10213
|
-
listed.matches.sort(compareNameMatches);
|
|
10214
|
-
return {
|
|
10215
|
-
users: listed.matches.slice(0, limit).map((m) => normalizeUser(m.user)),
|
|
10216
|
-
searched_pages: listed.searched_pages,
|
|
10217
|
-
searched_user_count: listed.searched_user_count,
|
|
10218
|
-
truncated: listed.truncated
|
|
10219
|
-
};
|
|
10220
|
-
}
|
|
10221
10500
|
// src/chat/tools/user-lookup.ts
|
|
10222
10501
|
const linkedSlackIdentity = alias(juniorIdentities, "user_lookup_slack_identity");
|
|
10223
10502
|
function explicitUserLookupError(error) {
|
|
@@ -10364,7 +10643,7 @@ function userLookupToolDefinition(providers) {
|
|
|
10364
10643
|
},
|
|
10365
10644
|
inputSchema: z.object({
|
|
10366
10645
|
provider: z.enum(providers).describe("Enabled identity provider to query."),
|
|
10367
|
-
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
|
|
10646
|
+
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 an `author_id` or a `<@U…>` mention. Search by name only with no known ID.")
|
|
10368
10647
|
}).strict(),
|
|
10369
10648
|
outputSchema: juniorToolOutputSchema
|
|
10370
10649
|
});
|
|
@@ -10899,13 +11178,13 @@ function createWebFetchTool(hooks, options = {}) {
|
|
|
10899
11178
|
filename: filenameForUrl(safeUrl, contentType.split(";")[0] ?? "image/png"),
|
|
10900
11179
|
mimeType: contentType.split(";")[0] ?? "application/octet-stream"
|
|
10901
11180
|
}];
|
|
10902
|
-
const
|
|
11181
|
+
const fileRefs = hooks.writeGeneratedFiles ? await hooks.writeGeneratedFiles(files) : [];
|
|
10903
11182
|
return {
|
|
10904
11183
|
url: safeUrl.toString(),
|
|
10905
11184
|
media_type: contentType,
|
|
10906
11185
|
bytes: bytes.byteLength,
|
|
10907
|
-
images:
|
|
10908
|
-
delivery:
|
|
11186
|
+
images: fileRefs,
|
|
11187
|
+
delivery: fileRefs.length > 0 ? options.canSendFilesToActiveConversation ? "Fetched images were written to sandbox paths. To share them, pass the returned image objects unchanged as sendFiles files." : "Fetched image was written to a sandbox path, but this runtime has no file-send tool for the active conversation." : "Fetched image bytes are available only in this tool result; this runtime has no file-send tool for the active conversation."
|
|
10909
11188
|
};
|
|
10910
11189
|
}
|
|
10911
11190
|
return await extractWebFetchResponse(safeUrl, response);
|
|
@@ -10991,42 +11270,70 @@ async function ingestEvent(input, options) {
|
|
|
10991
11270
|
identifier: event.identifier,
|
|
10992
11271
|
state: options.state
|
|
10993
11272
|
});
|
|
10994
|
-
|
|
10995
|
-
|
|
10996
|
-
|
|
11273
|
+
if (subscriptions.length === 0) return { enqueued: 0 };
|
|
11274
|
+
const author = await resolveEventAuthor(event);
|
|
11275
|
+
if (author.status === "untrusted") logInfo("event.author.untrusted", {
|
|
11276
|
+
"app.event.event_type": event.eventType,
|
|
11277
|
+
"app.event.namespace": event.namespace,
|
|
11278
|
+
"app.event.author.reason": author.reason
|
|
11279
|
+
});
|
|
11280
|
+
let people = [];
|
|
11281
|
+
if (options.slackTeamId && event.people?.length) try {
|
|
11282
|
+
people = await resolveEventMentions(event.people, options.slackTeamId);
|
|
10997
11283
|
} catch (error) {
|
|
10998
11284
|
logException(error, "event.people.resolve.failed", {
|
|
10999
11285
|
"app.event.event_type": event.eventType,
|
|
11000
11286
|
"app.event.namespace": event.namespace
|
|
11001
11287
|
});
|
|
11002
11288
|
}
|
|
11289
|
+
const doneBy = author.status === "trusted" && author.actor ? {
|
|
11290
|
+
mention: slackMention(author.actor.userId),
|
|
11291
|
+
handle: author.handle
|
|
11292
|
+
} : void 0;
|
|
11293
|
+
const turnConversations = /* @__PURE__ */ new Set();
|
|
11294
|
+
const ordered = [...subscriptions].sort((left, right) => Number(isQuietEvent(left, event.eventType)) - Number(isQuietEvent(right, event.eventType)));
|
|
11003
11295
|
let enqueued = 0;
|
|
11004
11296
|
const errors = [];
|
|
11005
11297
|
const waitDeadlineMs = Date.now() + 1e4;
|
|
11006
|
-
for (const subscription of
|
|
11007
|
-
|
|
11008
|
-
|
|
11009
|
-
|
|
11010
|
-
|
|
11011
|
-
|
|
11012
|
-
|
|
11013
|
-
|
|
11014
|
-
|
|
11015
|
-
|
|
11016
|
-
|
|
11017
|
-
|
|
11018
|
-
|
|
11019
|
-
|
|
11020
|
-
event
|
|
11021
|
-
|
|
11022
|
-
|
|
11023
|
-
|
|
11024
|
-
|
|
11025
|
-
|
|
11026
|
-
|
|
11027
|
-
|
|
11028
|
-
|
|
11029
|
-
|
|
11298
|
+
for (const subscription of ordered) {
|
|
11299
|
+
let quiet = false;
|
|
11300
|
+
try {
|
|
11301
|
+
if (await deliverWatch({
|
|
11302
|
+
data: event.data,
|
|
11303
|
+
eventType: event.eventType,
|
|
11304
|
+
namespace: event.namespace,
|
|
11305
|
+
identifier: event.identifier,
|
|
11306
|
+
terminal: event.terminal,
|
|
11307
|
+
nowMs,
|
|
11308
|
+
state: options.state,
|
|
11309
|
+
subscription,
|
|
11310
|
+
waitDeadlineMs,
|
|
11311
|
+
deliver: async (current) => {
|
|
11312
|
+
if (isQuietEvent(current, event.eventType)) {
|
|
11313
|
+
quiet = true;
|
|
11314
|
+
if (!turnConversations.has(current.conversationId)) await addQuietEventNote({
|
|
11315
|
+
event,
|
|
11316
|
+
subscription: current
|
|
11317
|
+
});
|
|
11318
|
+
return true;
|
|
11319
|
+
}
|
|
11320
|
+
const result = await enqueueEventNotification({
|
|
11321
|
+
author,
|
|
11322
|
+
doneBy,
|
|
11323
|
+
event,
|
|
11324
|
+
people,
|
|
11325
|
+
queue: options.queue,
|
|
11326
|
+
state: options.state,
|
|
11327
|
+
subscription: current
|
|
11328
|
+
});
|
|
11329
|
+
if (result.status === "paused") return false;
|
|
11330
|
+
turnConversations.add(current.conversationId);
|
|
11331
|
+
return result.status === "appended";
|
|
11332
|
+
}
|
|
11333
|
+
}) && !quiet) enqueued += 1;
|
|
11334
|
+
} catch (error) {
|
|
11335
|
+
errors.push(error);
|
|
11336
|
+
}
|
|
11030
11337
|
}
|
|
11031
11338
|
if (errors.length > 0) throw new AggregateError(errors, "Failed to deliver one or more watches");
|
|
11032
11339
|
return { enqueued };
|
|
@@ -11642,12 +11949,18 @@ async function addStats(amounts, options = {}) {
|
|
|
11642
11949
|
juniorStats.metric,
|
|
11643
11950
|
juniorStats.name
|
|
11644
11951
|
],
|
|
11645
|
-
set: { count: sql`${juniorStats.count} + excluded.count` }
|
|
11952
|
+
set: { count: sql`${juniorStats.count} + excluded.${sql.identifier(juniorStats.count.name)}` }
|
|
11646
11953
|
});
|
|
11647
11954
|
}
|
|
11648
11955
|
/** Read daily counters inside an inclusive UTC date range. */
|
|
11649
11956
|
async function readStats(start, end) {
|
|
11650
|
-
return await getDb().select(
|
|
11957
|
+
return await getDb().select({
|
|
11958
|
+
count: juniorStats.count,
|
|
11959
|
+
date: juniorStats.date,
|
|
11960
|
+
metric: juniorStats.metric,
|
|
11961
|
+
name: juniorStats.name,
|
|
11962
|
+
namespace: juniorStats.namespace
|
|
11963
|
+
}).from(juniorStats).where(and(gte(juniorStats.date, start), lte(juniorStats.date, end))).orderBy(asc(juniorStats.date), asc(juniorStats.namespace), asc(juniorStats.metric), asc(juniorStats.name));
|
|
11651
11964
|
}
|
|
11652
11965
|
/**
|
|
11653
11966
|
* Return the first day with a counter in the namespace, if any. Days that
|
|
@@ -12005,7 +12318,7 @@ function always(definition) {
|
|
|
12005
12318
|
}
|
|
12006
12319
|
const slackOnly = ({ platform }) => platform === "slack";
|
|
12007
12320
|
const hasEvents = () => hasEventCatalogEntries(getEventCatalog());
|
|
12008
|
-
const hasAgents = ({
|
|
12321
|
+
const hasAgents = ({ listedTools }) => listedTools.agents !== "none";
|
|
12009
12322
|
function workspaceTool(name) {
|
|
12010
12323
|
return {
|
|
12011
12324
|
when: () => workspaceProviderNames() !== void 0,
|
|
@@ -12050,11 +12363,11 @@ const CORE_TOOLS = {
|
|
|
12050
12363
|
definition: () => runOperatorSqlToolDefinition
|
|
12051
12364
|
},
|
|
12052
12365
|
updateUserCustomization: {
|
|
12053
|
-
when: ({
|
|
12366
|
+
when: ({ listedTools }) => isExperimentalFeatureEnabled("user-customization") && listedTools.userCustomization,
|
|
12054
12367
|
definition: () => updateUserCustomizationToolDefinition
|
|
12055
12368
|
},
|
|
12056
12369
|
setConversationSubscription: {
|
|
12057
|
-
when: ({
|
|
12370
|
+
when: ({ listedTools }) => listedTools.subscriptions,
|
|
12058
12371
|
definition: () => setConversationSubscriptionToolDefinition
|
|
12059
12372
|
},
|
|
12060
12373
|
searchConversationEvents: always(searchConversationEventsToolDefinition),
|
|
@@ -12092,15 +12405,15 @@ const CORE_TOOLS = {
|
|
|
12092
12405
|
definition: () => messageAgentToolDefinition
|
|
12093
12406
|
},
|
|
12094
12407
|
[REPLY_TOOL_NAME]: {
|
|
12095
|
-
when: ({
|
|
12096
|
-
definition: ({
|
|
12408
|
+
when: ({ listedTools }) => listedTools.reply !== "none",
|
|
12409
|
+
definition: ({ listedTools }) => replyToolDefinition(enabledMode(listedTools.reply))
|
|
12097
12410
|
},
|
|
12098
12411
|
[REPORT_BLOCKED_TOOL_NAME]: {
|
|
12099
|
-
when: ({
|
|
12100
|
-
definition: ({
|
|
12412
|
+
when: ({ listedTools }) => listedTools.reportBlocked !== "none",
|
|
12413
|
+
definition: ({ listedTools }) => reportBlockedToolDefinition(enabledMode(listedTools.reportBlocked))
|
|
12101
12414
|
},
|
|
12102
12415
|
[NO_REPLY_TOOL_NAME]: {
|
|
12103
|
-
when: ({
|
|
12416
|
+
when: ({ listedTools }) => listedTools.noReply,
|
|
12104
12417
|
definition: () => noReplyToolDefinition
|
|
12105
12418
|
},
|
|
12106
12419
|
searchMcpTools: RUN_BUILT,
|
|
@@ -12200,7 +12513,7 @@ function modelFacing(definition) {
|
|
|
12200
12513
|
function staticToolDefinitions(key) {
|
|
12201
12514
|
const scope = {
|
|
12202
12515
|
platform: key.platform,
|
|
12203
|
-
|
|
12516
|
+
listedTools: promptModeTurnTools(key.mode)
|
|
12204
12517
|
};
|
|
12205
12518
|
const core = {};
|
|
12206
12519
|
for (const [name, entry] of coreToolEntries()) {
|
|
@@ -12289,11 +12602,12 @@ async function breakerOpen(state, modelId) {
|
|
|
12289
12602
|
* models. Providers that no model uses are left out.
|
|
12290
12603
|
*/
|
|
12291
12604
|
async function breakerStates(state, modelIds) {
|
|
12292
|
-
const
|
|
12293
|
-
|
|
12605
|
+
const warmed = [...new Set(modelIds.map(providerOf).filter((provider) => Object.hasOwn(CACHE_TTL_MS, provider)))];
|
|
12606
|
+
const open = await getStateValues(state, warmed.map(breakerOpenKey));
|
|
12607
|
+
return warmed.map((provider, index) => ({
|
|
12294
12608
|
provider,
|
|
12295
|
-
open:
|
|
12296
|
-
}))
|
|
12609
|
+
open: open[index] === true
|
|
12610
|
+
}));
|
|
12297
12611
|
}
|
|
12298
12612
|
/**
|
|
12299
12613
|
* Close a provider's breaker so warming starts again, and forget its recent
|
|
@@ -12487,19 +12801,14 @@ async function definitionsChanged(state, definitions) {
|
|
|
12487
12801
|
*/
|
|
12488
12802
|
/** `junior_stats` namespace of the cache warming counters. */
|
|
12489
12803
|
const SAVINGS_NAMESPACE = "cache_warming";
|
|
12490
|
-
/**
|
|
12491
|
-
* Dollar counters store this many units per dollar. A day of one model then
|
|
12492
|
-
* fits the integer counter up to about $200,000.
|
|
12493
|
-
*/
|
|
12494
|
-
const UNITS_PER_USD = 1e4;
|
|
12495
12804
|
const METRICS = {
|
|
12496
12805
|
hits: "hits",
|
|
12497
12806
|
idlePeriods: "idle_periods",
|
|
12498
|
-
oracleSavings: "
|
|
12499
|
-
saved: "
|
|
12807
|
+
oracleSavings: "oracle_savings_micro_usd",
|
|
12808
|
+
saved: "saved_micro_usd",
|
|
12500
12809
|
unwarmedIdlePeriods: "unwarmed_idle_periods",
|
|
12501
|
-
unwarmedOracleSavings: "
|
|
12502
|
-
warmupCost: "
|
|
12810
|
+
unwarmedOracleSavings: "unwarmed_oracle_savings_micro_usd",
|
|
12811
|
+
warmupCost: "warmup_cost_micro_usd",
|
|
12503
12812
|
historyDays: "history_days"
|
|
12504
12813
|
};
|
|
12505
12814
|
const TTL_START_DELAY_MS = 1e4;
|
|
@@ -12530,7 +12839,6 @@ function idlePeriodSavings(input) {
|
|
|
12530
12839
|
savedUsd: hit ? writeSavedUsd : 0
|
|
12531
12840
|
};
|
|
12532
12841
|
}
|
|
12533
|
-
const units = (usd) => Math.round(usd * UNITS_PER_USD);
|
|
12534
12842
|
const savingsStats = (modelId, counts) => Object.entries(counts).map(([metric, count]) => ({
|
|
12535
12843
|
namespace: SAVINGS_NAMESPACE,
|
|
12536
12844
|
metric: METRICS[metric],
|
|
@@ -12538,12 +12846,12 @@ const savingsStats = (modelId, counts) => Object.entries(counts).map(([metric, c
|
|
|
12538
12846
|
count
|
|
12539
12847
|
}));
|
|
12540
12848
|
function periodCounts(savings, warmed) {
|
|
12541
|
-
const oracle =
|
|
12849
|
+
const oracle = usdToMicroUsd(savings.oracleUsd);
|
|
12542
12850
|
return {
|
|
12543
12851
|
idlePeriods: 1,
|
|
12544
12852
|
hits: savings.hit ? 1 : 0,
|
|
12545
12853
|
oracleSavings: oracle,
|
|
12546
|
-
saved:
|
|
12854
|
+
saved: usdToMicroUsd(savings.savedUsd),
|
|
12547
12855
|
...warmed === false ? {
|
|
12548
12856
|
unwarmedIdlePeriods: 1,
|
|
12549
12857
|
unwarmedOracleSavings: oracle
|
|
@@ -12570,7 +12878,7 @@ async function recordIdlePeriodSavings(modelId, savings, warmed) {
|
|
|
12570
12878
|
}
|
|
12571
12879
|
/** Add the cost of one warmup call. */
|
|
12572
12880
|
async function recordWarmupCost(modelId, costUsd) {
|
|
12573
|
-
await addSavingsStats(modelId, { warmupCost:
|
|
12881
|
+
await addSavingsStats(modelId, { warmupCost: usdToMicroUsd(costUsd) });
|
|
12574
12882
|
}
|
|
12575
12883
|
const utcDate = (ms) => new Date(ms).toISOString().slice(0, 10);
|
|
12576
12884
|
/**
|
|
@@ -12621,11 +12929,11 @@ function savingsTotals(stats) {
|
|
|
12621
12929
|
historyDays: sum(METRICS.historyDays),
|
|
12622
12930
|
hits: sum(METRICS.hits),
|
|
12623
12931
|
idlePeriods: sum(METRICS.idlePeriods),
|
|
12624
|
-
|
|
12625
|
-
|
|
12932
|
+
oracleSavingsMicroUsd: sum(METRICS.oracleSavings),
|
|
12933
|
+
savedMicroUsd: sum(METRICS.saved),
|
|
12626
12934
|
unwarmedIdlePeriods: sum(METRICS.unwarmedIdlePeriods),
|
|
12627
|
-
|
|
12628
|
-
|
|
12935
|
+
unwarmedOracleSavingsMicroUsd: sum(METRICS.unwarmedOracleSavings),
|
|
12936
|
+
warmupCostMicroUsd: sum(METRICS.warmupCost)
|
|
12629
12937
|
};
|
|
12630
12938
|
}
|
|
12631
12939
|
// src/chat/cache-warming/snapshot.ts
|
|
@@ -12718,11 +13026,12 @@ async function loadSnapshot(state, conversationId, key) {
|
|
|
12718
13026
|
const snapshot = await state.get(key);
|
|
12719
13027
|
if (!snapshot) return "stopped";
|
|
12720
13028
|
const context = JSON.parse((await zstdDecompress(Buffer.from(snapshot, "base64"))).toString("utf8"));
|
|
12721
|
-
|
|
12722
|
-
|
|
12723
|
-
|
|
12724
|
-
|
|
12725
|
-
|
|
13029
|
+
const parts = context.messages.flatMap(imageParts).filter((part) => part.data.startsWith(IMAGE_REF_PREFIX));
|
|
13030
|
+
const limit = pLimit(8);
|
|
13031
|
+
const images = await Promise.all(parts.map((part) => limit(() => state.get(imageKey(conversationId, part.data.slice(7))))));
|
|
13032
|
+
for (const [index, part] of parts.entries()) {
|
|
13033
|
+
const data = images[index];
|
|
13034
|
+
if (data === null || data === void 0) return "image_missing";
|
|
12726
13035
|
part.data = data;
|
|
12727
13036
|
}
|
|
12728
13037
|
return context;
|
|
@@ -12947,16 +13256,17 @@ function askedReviewItem(messages, final) {
|
|
|
12947
13256
|
* The active Watches of the Conversation, and what else its idle period
|
|
12948
13257
|
* waits on. Watches include timers and the event Watches that tools such as
|
|
12949
13258
|
* `createPullRequest` add. A child agent that still runs comes first: its
|
|
12950
|
-
* result starts a Turn without a person.
|
|
12951
|
-
* agent or a Watch can start a later Turn, so
|
|
13259
|
+
* result starts a Turn without a person. When `idleNeedsPendingWork`, as in
|
|
13260
|
+
* an Automation run, only a child agent or a Watch can start a later Turn, so
|
|
13261
|
+
* a Review item does not count.
|
|
12952
13262
|
*/
|
|
12953
|
-
async function readPendingWork(conversationId, messages, final,
|
|
13263
|
+
async function readPendingWork(conversationId, messages, final, idleNeedsPendingWork) {
|
|
12954
13264
|
const [watches, children] = await Promise.all([listWatches({ conversationId }), listChildAgents(conversationId)]);
|
|
12955
13265
|
if (children.some((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status))) return {
|
|
12956
13266
|
watches,
|
|
12957
13267
|
waitingOn: "child"
|
|
12958
13268
|
};
|
|
12959
|
-
if (
|
|
13269
|
+
if (idleNeedsPendingWork) return watches.length > 0 ? {
|
|
12960
13270
|
watches,
|
|
12961
13271
|
waitingOn: "watch"
|
|
12962
13272
|
} : { watches };
|
|
@@ -13013,9 +13323,10 @@ async function listConversationWork(conversationIds) {
|
|
|
13013
13323
|
const finishedAtById = /* @__PURE__ */ new Map();
|
|
13014
13324
|
const unfinished = /* @__PURE__ */ new Set();
|
|
13015
13325
|
let failed = false;
|
|
13016
|
-
|
|
13326
|
+
const limit = pLimit(8);
|
|
13327
|
+
await Promise.all(getPlugins().map((plugin) => limit(async () => {
|
|
13017
13328
|
const hook = plugin.hooks?.unfinishedWork;
|
|
13018
|
-
if (!hook)
|
|
13329
|
+
if (!hook) return;
|
|
13019
13330
|
try {
|
|
13020
13331
|
const result = await hook({
|
|
13021
13332
|
conversationIds: queriedIds,
|
|
@@ -13049,7 +13360,7 @@ async function listConversationWork(conversationIds) {
|
|
|
13049
13360
|
"exception.message": error instanceof Error ? error.message : String(error)
|
|
13050
13361
|
});
|
|
13051
13362
|
}
|
|
13052
|
-
}
|
|
13363
|
+
})));
|
|
13053
13364
|
return {
|
|
13054
13365
|
assignedIds: conversationIds.filter((conversationId) => assigned.has(conversationId)),
|
|
13055
13366
|
failed,
|
|
@@ -13167,19 +13478,19 @@ async function scheduleWarmup(message, requestStartedAtMs, warm) {
|
|
|
13167
13478
|
}
|
|
13168
13479
|
async function recordGap(state, conversationId, generation, warm, gapMs) {
|
|
13169
13480
|
if (!await state.setIfNotExists(gapClaimKey(conversationId, generation), true, CONVERSATION_STATE_TTL_MS)) return;
|
|
13170
|
-
|
|
13481
|
+
const limit = pLimit(8);
|
|
13482
|
+
await Promise.all(recordedSegments(warm).map((segment) => limit(() => state.appendToList(segmentGapsKey(segment), gapMs, {
|
|
13171
13483
|
maxLength: GLOBAL_GAPS_MAX,
|
|
13172
13484
|
ttlMs: GLOBAL_GAPS_TTL_MS
|
|
13173
|
-
});
|
|
13485
|
+
}))));
|
|
13174
13486
|
await state.appendToList(conversationGapsKey(conversationId, decisionSegment(warm)), gapMs, {
|
|
13175
13487
|
maxLength: CONVERSATION_GAPS_MAX,
|
|
13176
13488
|
ttlMs: CONVERSATION_STATE_TTL_MS
|
|
13177
13489
|
});
|
|
13178
13490
|
}
|
|
13179
13491
|
async function startIdlePeriod(state, conversationId, request, message, turn, definitionsKey, turnEnding) {
|
|
13180
|
-
const
|
|
13181
|
-
|
|
13182
|
-
if (automation && !waitingOn) return void 0;
|
|
13492
|
+
const { watches, waitingOn } = await readPendingWork(conversationId, request.context.messages, message, turn.idleNeedsPendingWork);
|
|
13493
|
+
if (turn.idleNeedsPendingWork && !waitingOn) return void 0;
|
|
13183
13494
|
const idle = {
|
|
13184
13495
|
generation: randomUUID(),
|
|
13185
13496
|
sinceMs: request.startedAtMs
|
|
@@ -13254,7 +13565,7 @@ async function recordSavings(idle, request, message) {
|
|
|
13254
13565
|
if (!savings) return;
|
|
13255
13566
|
await recordIdlePeriodSavings(idle.warm?.modelId ?? request.model.id, savings, idle.warm !== void 0);
|
|
13256
13567
|
}
|
|
13257
|
-
async function recordModelCall(conversationId,
|
|
13568
|
+
async function recordModelCall(conversationId, turn, definitionsKey, request, message, turnEnding) {
|
|
13258
13569
|
const state = await connectedState();
|
|
13259
13570
|
const previous = await state.get(conversationKey(conversationId));
|
|
13260
13571
|
const idle = previous?.idle;
|
|
@@ -13275,7 +13586,7 @@ async function recordModelCall(conversationId, userActor, definitionsKey, reques
|
|
|
13275
13586
|
if (idle) await recordSavings(idle, request, message);
|
|
13276
13587
|
const endedTurns = previous?.endedTurns ?? 0;
|
|
13277
13588
|
const nextIdle = turnEnding ? await startIdlePeriod(state, conversationId, request, message, {
|
|
13278
|
-
|
|
13589
|
+
...turn,
|
|
13279
13590
|
endedTurns
|
|
13280
13591
|
}, definitionsKey, turnEnding) : void 0;
|
|
13281
13592
|
const next = nextIdle ? {
|
|
@@ -13309,11 +13620,10 @@ async function stopIdleWarmups(conversationId) {
|
|
|
13309
13620
|
}
|
|
13310
13621
|
}
|
|
13311
13622
|
/**
|
|
13312
|
-
* Create a recorder for one agent run.
|
|
13313
|
-
*
|
|
13314
|
-
* logged and does not stop the run.
|
|
13623
|
+
* Create a recorder for one agent run. A failure to record only loses cache
|
|
13624
|
+
* warming, so it is logged and does not stop the run.
|
|
13315
13625
|
*/
|
|
13316
|
-
function createCacheWarmingRecorder(conversationId,
|
|
13626
|
+
function createCacheWarmingRecorder(conversationId, turn, definitionsKey) {
|
|
13317
13627
|
let lastRequest;
|
|
13318
13628
|
let lastCall;
|
|
13319
13629
|
let answerToolEnding;
|
|
@@ -13358,7 +13668,7 @@ function createCacheWarmingRecorder(conversationId, userActor, definitionsKey) {
|
|
|
13358
13668
|
if (idleEnded && message.stopReason !== "stop") return;
|
|
13359
13669
|
idleEnded = message.stopReason !== "stop";
|
|
13360
13670
|
try {
|
|
13361
|
-
await recordModelCall(conversationId,
|
|
13671
|
+
await recordModelCall(conversationId, turn, definitionsKey, request, message, message.stopReason === "stop" ? "reply" : void 0);
|
|
13362
13672
|
} catch (error) {
|
|
13363
13673
|
logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
|
|
13364
13674
|
}
|
|
@@ -13375,7 +13685,7 @@ function createCacheWarmingRecorder(conversationId, userActor, definitionsKey) {
|
|
|
13375
13685
|
}
|
|
13376
13686
|
if (!answerToolEnding || !lastCall) return;
|
|
13377
13687
|
try {
|
|
13378
|
-
await recordModelCall(conversationId,
|
|
13688
|
+
await recordModelCall(conversationId, turn, definitionsKey, lastCall.request, lastCall.message, answerToolEnding);
|
|
13379
13689
|
} catch (error) {
|
|
13380
13690
|
logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
|
|
13381
13691
|
}
|
|
@@ -13546,4 +13856,4 @@ async function runCacheWarmup(message) {
|
|
|
13546
13856
|
}, startedAtMs, warm);
|
|
13547
13857
|
}, attributes);
|
|
13548
13858
|
}
|
|
13549
|
-
export {
|
|
13859
|
+
export { createStopAgentTool as $, createSlackListUpdateItemTool as $n, requireToolCreator as $r, readChildConversationSender as $t, createWebSearchTool as A, MINUTE_MS$1 as Ai, recordFailedDispatchTurn as An, createRunAutomationNowTool as Ar, verifyAttachmentUploads as At, createSearchEventTypesTool as B, getWebAuthorization as Bn, automationTriggerChangesSchema as Br, getActiveAgentInvocationForConversation as Bt, incrementStat as C, findAutomationSkill as Ci, findChildAgentConversationId as Cn, SLACK_TOOL_SOURCE as Cr, createConversationId as Ct, requireReadyWorkspaceSnapshot as D, resolveTaskOutcomes as Di, supersedeTurnForInput as Dn, createOperationKey as Dr, AttachmentUploadError as Dt, processWorkspaceSnapshotJob as E, moveTaskOutcomes as Ei, supersedeOpenMailboxTurns as En, resolveWorkspacePath as Er, resolveConversationDestination as Et, userLookupIdentityProviders as F, canShareTurn as Fn, zodToolDefinition as Fr, listOwnedWatches as Ft, missingFileResult as G, emptyResponse as Gn, injectContinuationToolName as Gr, listAgentInvocationsForConversation as Gt, createSearchConversationsTool as H, executeTurn as Hn, editedAutomationTask as Hr, getChildAgentLabel as Ht, createUpdateUserCustomizationTool as I, isAttemptInterrupt as In, automationIdForToolCall as Ir, listChildAgents as It, capToolResult as J, createSlackThreadReadTool as Jn, getConversationAccess as Jr, markAgentInvocationParentMailboxAppended as Jt, sliceFileContent as K, jsonResponse as Kn, juniorToolOutputSchema as Kr, listPendingAgentInvocationMailboxAppends as Kt, createSubmitFeedbackTool as L, selectAttemptMessages as Ln, automationSkillToolSchema as Lr, listUnreportedSiblingAgents as Lt, createWatchTimerTool as M, NO_REPLY_GAP_MS as Mi, wakePausedTurn as Mn, AUTOMATIONS_TOOL_SOURCE as Mr, createReadConversationEventTool as Mt, createWatchEventsTool as N, gapSegment as Ni, getTurnAuthorization as Nn, parseToolInput as Nr, createRunOperatorSqlTool as Nt, prepareWorkspaceSnapshot as O, countOwnedAutomationsNeedingAttention as Oi, createPausedTurns as On, createCanvas as Or, collectAttachmentUploadGarbage as Ot, createUserLookupTool as P, canJoinTurn as Pn, zodTool as Pr, createListWatchesTool as Pt, createUpdatePlanTool as Q, createSlackPublicSearchTool as Qn, requireToolCaller as Qr, getChildAgentInputSender as Qt, createSystemTimeTool as R, createWebAuthorization as Rn, automationToolResult as Rr, NON_TERMINAL_AGENT_INVOCATION_STATUSES as Rt, createWorkspaceTools as S, requireAutomationSkill as Si, AgentMessageTargetError as Sn, createSlackCanvasEditTool as Sr, createAndEnqueueConversation as St, ensureWorkspaceSnapshotBuild as T, effectiveTaskOutcomes as Ti, PARENT_AGENT_TARGET as Tn, positiveInteger$1 as Tr, webActorFromUser as Tt, createWriteFileTool as U, createSetConversationSubscriptionTool as Un, newAutomationTask as Ur, getLatestAgentInvocationForConversation as Ut, createSearchConversationEventsTool as V, AgentRunError as Vn, automationTriggerSchema as Vr, getAgentInvocation as Vt, createReadFileTool as W, setConversationSubscription as Wn, triggerKind as Wr, isTerminalAgentInvocation as Wt, editFile as X, renderBlockText as Xn, automationToolsDisabledReason as Xr, sendsResultToParent as Xt, createEditFileTool as Y, renderAttachmentText as Yn, automationToolContext as Yr, reportReplacedWithoutOpenWork as Yt, createBashTool as Z, parseSlackMessageReference as Zn, requireToolAutomation as Zr, childAgentInput as Zt, closeBreaker as _, changedEventMatch as _i, recordSubagentEnded as _n, isPublicSlackChannel as _r, renderReviewItemMessage as _t, createCacheWarmingRecorder as a, deleteViewerTask as ai, readParentMessage as an, createSlackChannelListMessagesTool as ar, createNoReplyTool as at, coreToolSlots as b, requireAutomationTaskText as bi, AgentDepthLimitError as bn, createSlackCanvasWriteTool as br, appendAndEnqueueWebMessage as bt, isConversationWorkDone as c, ViewerTaskNotFoundError as ci, endActiveAgentInvocations as cn, resolveSlackChannelIdFromMessage as cr, readLastUserMessageAtByConversation as ct, addHistoryPeriod as d, readViewerAutomationRuns as di, resolveAgentInvocationId as dn, slackChannelRefParam as dr, markConversationRead as dt, requireToolDestination as ei, routeChildInput as en, createSlackListGetItemsTool as er, createSpawnAgentTool as et, firstLiveSavingsDate as f, readViewerAutomationSummary as fi, dropOwnUnreadLoopReplies as fn, checkSlackChannelReadAccess as fr, reportConversationRead as ft, breakerStates as g, editEventAutomation as gi, completeCancelledConversationTurn as gn, isConversationMember as gr, deliverReviewItemChange as gt, savingsTotals as h, editScheduledAutomation as hi, cancelSignInWait as hn, getConversationInfo as hr, createUpdateReviewItemTool as ht, GLOBAL_GAPS_TTL_MS as i, changeViewerAutomationLifecycle as ii, parentMessageText as in, createSlackConversationSearchChannelPort as ir, createReplyTool as it, createWebFetchTool as j, MIN_WARMUP_PREFIX_TOKENS as ji, wakeAuthorizedTurn as jn, createDeleteAutomationTool as jr, writeAttachmentUpload as jt, ingestEvent as k, IDLE_HORIZON_MS as ki, getPausedTurnRequest as kn, createSearchAutomationsTool as kr, createAttachmentUpload as kt, listConversationWork as l, readConversationSourceTask as li, endAgentInvocationsOfStoppedWork as ln, createSlackChannelJoinTool as lr, archiveConversation as lt, replaceHistorySavings as m, readViewerAutomations as mi, stopChildAgentsOf as mn, getChannelMessage as mr, createSearchReviewItemsTool as mt, CONVERSATION_STATE_TTL_MS as n, automationEditor as ni, isParentMessageMeta as nn, createSlackListAddItemsTool as nr, createReportProgressTool as nt, segmentGapsKey as o, readViewerAutomationEdit as oi, createAgentInvocationWorker as on, parseSlackThreadId as or, createMessageAgentTool as ot, idlePeriodSavings as p, readViewerAutomationVersions as pi, stopChildAgentsBelow as pn, joinPublicChannelForRead as pr, createAddReviewItemTool as pt, TOOL_RESULT_MAX_CHARS as q, throwApiError as qn, makeStructuredToolOutput as qr, listPendingAgentInvocationResults as qt, GLOBAL_GAPS_MAX as r, changeAutomationLifecycle as ri, logDroppedParentMessage as rn, createSlackConversationMessageSearchTool as rr, createReportBlockedTool as rt, warmup_exports as s, updateViewerAutomation as si, createAndEnqueueAgentInvocation as sn, readSlackRawMessageContext as sr, createArchiveAgentTool as st, ANSWER_TOOL_ENDINGS as t, activateViewerAutomationVersion as ti, childAgentTurnOptions as tn, createSlackListCreateTool as tr, createListAgentsTool as tt, SAVINGS_NAMESPACE as u, readViewerAutomationExecutions as ui, enqueueAgentInvocation as un, resolveSlackChannelRef as ur, conversationReadPositionQuery as ut, connectedState as v, requireEventAutomationTrigger as vi, createAgentInvocationForMessage as vn, joinPublicChannel as vr, reviewItemChangeRecord as vt, readStats as w, missingAutomationSkillReason as wi, getAgentBinding as wn, isMissingPathError as wr, recordWebConversationActivity as wt, enabledMode as x, AutomationEditError as xi, AgentMessagePausedError as xn, createSlackCanvasReadTool as xr, conversationTurnIdForMessage as xt, providerCacheTtlMs as y, automationCardStatus as yi, createAgentInvocationFromLatest as yn, listThreadReplies as yr, acceptsWebMessages as yt, createStopWatchingResourcesTool as z, deleteWebAuthorization as zn, automationToolResultSchema as zr, TERMINAL_AGENT_INVOCATION_STATUSES as zt };
|