@sentry/junior 0.304.0 → 0.306.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.
Files changed (80) hide show
  1. package/dist/{adapter-context-B1IpoELr.js → adapter-context-CnY-i32r.js} +2 -2
  2. package/dist/{admin-BnVFGo_z.js → admin-BLLdLnXh.js} +2 -2
  3. package/dist/{agent-runner-CoEeZSRh.js → agent-runner-BaLjEjPR.js} +312 -204
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -8
  6. package/dist/api.d.ts +19 -4
  7. package/dist/api.js +137 -40
  8. package/dist/{app-Cs157Zc5.d.ts → app-DvYbM9UD.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +489 -445
  11. package/dist/{background-compaction-queue-WLPNSF_b.js → background-compaction-queue-D2wzxtGU.js} +7 -3
  12. package/dist/{briefs-CagVVefw.js → briefs-DvyzXfrF.js} +3 -3
  13. package/dist/{catalog-runtime-B8ZXvXWm.js → catalog-runtime-B1R-nHd3.js} +1 -1
  14. package/dist/cli/chat.js +15 -15
  15. package/dist/cli/check.js +3 -3
  16. package/dist/cli/main.js +3 -3
  17. package/dist/cli/plugins.js +4 -4
  18. package/dist/cli/snapshot-create.js +5 -5
  19. package/dist/cli/upgrade.d.ts +1 -1
  20. package/dist/cli/upgrade.js +3 -3
  21. package/dist/{config-DdO1BNcw.js → config-DUD-zMvp.js} +111 -13
  22. package/dist/{connections-D20kp0j5.js → connections-CDhsqPcC.js} +6 -6
  23. package/dist/{continue-in-slack-BKEVMBj1.js → continue-in-slack-BXQizz9o.js} +5 -5
  24. package/dist/{conversation-BOqdRtUx.js → conversation--f85g4zL.js} +132 -132
  25. package/dist/{conversation-feed-CgpgP7yi.js → conversation-feed-BNs9KiqC.js} +1 -1
  26. package/dist/{conversation-privacy-L1SK_v0V.js → conversation-privacy-YE54gMN8.js} +1 -1
  27. package/dist/{conversation-turn-BptVJylj.js → conversation-turn-BzdmrHb0.js} +22 -40
  28. package/dist/{credential-sync-D1J1CGzL.js → credential-sync-Cdm-e1vJ.js} +14 -13
  29. package/dist/{db-EKJnkrIb.js → db-DV2ZUb1Y.js} +90 -11
  30. package/dist/{db-zbN5ZV_o.d.ts → db-pH357Dkt.d.ts} +1 -1
  31. package/dist/{executor-CoIZmFK8.js → executor-CjNhwwnj.js} +47 -4
  32. package/dist/{history-m2-ceTTX.js → history-N7IVbUom.js} +5 -1
  33. package/dist/{install-BT2Pf6HP.js → install-DbD7C5td.js} +2 -2
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{lineage-C5DGQCS_.js → lineage-BFdIPb3o.js} +2 -2
  36. package/dist/{logging-QSZuMcvo.js → logging-oYpJYr-S.js} +1 -1
  37. package/dist/{message-TtxftRHj.js → message-BBPcMKJY.js} +8 -8
  38. package/dist/{model-input-BHXfA29g.js → model-input-DYYF3a8B.js} +3 -3
  39. package/dist/nitro.d.ts +1 -1
  40. package/dist/nitro.js +4 -4
  41. package/dist/{oauth-callback-server-B0enqHtZ.js → oauth-callback-server-C7Q987su.js} +2 -2
  42. package/dist/{projection-CNKK7doO.js → projection-CWXDE0f6.js} +7740 -6165
  43. package/dist/{prompt-DSjhoKu5.js → prompt-P3eRqO8C.js} +15 -7
  44. package/dist/{queue-CDxkit82.js → queue-7FSijgqG.js} +4 -4
  45. package/dist/{registry-DBDNUUmz.js → registry-1pzXmplY.js} +1 -1
  46. package/dist/{resolve-CQLhMWSu.js → resolve-n87oXY-d.js} +3 -3
  47. package/dist/{result-B-pauj42.js → result-BmF9v9bv.js} +9 -9
  48. package/dist/{runner-B3KxKks5.js → runner-4j7ZsxP5.js} +13 -15
  49. package/dist/{sandbox-egress-signals-DJJX9ClG.js → sandbox-egress-signals-BRQI8HvT.js} +1 -1
  50. package/dist/{automation-CuA3yEcD.js → schedule-CHPWQn-x.js} +347 -5
  51. package/dist/{schema-CKcu-IK6.d.ts → schema-CVbIjrF3.d.ts} +71 -1
  52. package/dist/{schema-Bx0Mlo32.js → schema-D7iIEh6t.js} +52 -6
  53. package/dist/{service-account-DQLqkSVv.js → service-account-BDQ9xzta.js} +3 -3
  54. package/dist/{service-account-2HmlNPvy.js → service-account-DzQiOmqa.js} +5 -5
  55. package/dist/{session-stop-DEeZKqbX.js → session-stop-BQxgHR4X.js} +919 -168
  56. package/dist/{skills-2UrD7JkN.js → skills-CPf4vNuC.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-Dd129Uov.js → slack-conversation-unfurl-B1KEptUg.js} +10 -9
  58. package/dist/{spawn-eMho9HDJ.js → spawn-CjGddiAU.js} +6 -6
  59. package/dist/{state-Bveuc4Zh.js → state-9wfj6aSD.js} +4 -4
  60. package/dist/{stop-D_ltJLDS.js → stop-CsQGuN5n.js} +62 -118
  61. package/dist/{store-COeYnPL_.js → store-Dz3YZ7gQ.js} +5 -5
  62. package/dist/{task-queue-CBIDXZpV.js → task-queue-CFlrJguF.js} +3 -3
  63. package/dist/{task-runner-CJF7zIJL.js → task-runner-frzlUvFD.js} +8 -9
  64. package/dist/{thread-context-Cg0jt0aE.js → thread-context-C4QuZlM8.js} +8 -91
  65. package/dist/turn-session-routing-BXaubz2w.js +244 -0
  66. package/dist/{turn-user-message-tcom1RYd.js → turn-user-message-DNC0eRZ7.js} +3 -3
  67. package/dist/users-XCCKn3xW.js +181 -0
  68. package/dist/{validation-EU91JwIT.js → validation-L5fdjmFX.js} +1 -1
  69. package/dist/{version-BYRPhY5G.js → version-BFmuwgxP.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-Cf8ISkAc.js → viewer-DKOeHpv3.js} +3 -3
  72. package/dist/{warmup-TgY4S1vx.js → warmup-mTMIatCV.js} +271 -279
  73. package/dist/{web-message-id-lNodcCOI.js → web-message-id-CUaSiGme.js} +16 -1
  74. package/dist/{worker-C6Uq4OKD.js → worker-Bz4KNxjI.js} +7 -7
  75. package/migrations/0114_plan_items.sql +22 -0
  76. package/migrations/meta/0114_snapshot.json +5203 -0
  77. package/migrations/meta/_journal.json +7 -0
  78. package/package.json +6 -6
  79. package/dist/schedule-cP0AACm1.js +0 -344
  80. package/dist/turn-session-routing-CaY3Tp8m.js +0 -1792
@@ -1,28 +1,28 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $ as loadTurnCheckpoint, $a as workspaceRepoCheckoutPath, $i as setWorkspaceSnapshotBuild, $r as EVERYONE_ASSIGNEE, Ar as dismissOpenReviewItems, Ba as isWorkspaceSnapshotNotReadyError, Br as PLUGIN_REVIEW_ITEM_KEY_PREFIX, Ca as getSlackMessagePermalink, Cn as getTerminalAssistantMessages, Cs as defaultTimezone, Dr as closeReviewItem, Fi as getDashboardTaskLink, Ga as createSandboxEgressCredentialToken, Gi as getWorkspaceByName, Gn as renderTag, H as PluginCredentialFailureError, Hi as createWorkspace, Hr as canAgentChangeReviewItem, Ja as buildSandboxEgressNetworkPolicy, Ji as updateWorkspace, Jo as readLiveAttachment, Jr as requireReviewItemAssignees, K as AuthorizationFlowDisabledError, Ki as listWorkspaces, Lo as FORK_INSTRUCTIONS, Lr as searchReviewItems, Mr as getReviewItem, Nr as insertReviewItem, Pa as isAbortError, Qi as setWorkspaceSnapshot, Ra as WorkspaceSnapshotNotReadyError, Ro as loadForkHistory, T as resolveTaskTitle, Ui as deleteWorkspace, Ur as canReadReviewItem, Vn as escapeClosingTags, Vo as matchSlackAttachments, Wi as getWorkspace, X as clearPendingAuth, Xi as invalidateReadySnapshot, Xn as getOAuthAccountProviders, Yi as WorkspaceValidationError, Yo as recordUploadedAttachment, Yr as requireReviewItemLinks, Za as SANDBOX_RUNTIME, Zi as loadSnapshotsForProfile, _a as slackMention, _i as findMatchingWatches, _o as createPluginLogger, _s as searchConversations, as as isConversationScopedChannel, at as failTurnRecord, bs as createPluginAnnotations, ci as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, cn as replyTextSchema, cr as getPlugins, cs as normalizeSlackConversationId, ds as withSlackRetries, ea as create, ei as activeParticipantUserIds, eo as ToolInputError, es as SlackActionError, et as lostWorkerBeforeFirstSave, fi as cancelWatch, fn as NO_REPLY_TOOL_NAME, fs as sleep, gi as deliverWatch, hi as createWatch, ia as getSandboxProvider, in as REPLY_TOOL_NAME, is as getSlackClient, j as markConversationMessage, jr as getOpenReviewItemByDedupeKey, ki as getDashboardConversationLink, ks as createPluginCache, li as RESOURCE_WATCH_TOOL_SOURCE, lo as SANDBOX_WORKSPACE_ROOT, lr as getStaticPluginToolDefinitions, mi as createTimerWatch, mn as isLegacyNoReplyMarker, na as isStale, ni as resolveAssignee, ns as getFilePermalink, nt as saveTurnCheckpoint, oi as getSlackToolContext, on as readTurnAnswer, pn as findLegacyNoReplyMarker, qr as readReviewItemAgentScope, ri as resolveAssignees, rn as isTurnExecutionLimitExceededError, rt as abandonTurnRecord, s as openConversationProjection, si as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, so as SANDBOX_REPOS_ROOT, st as getTurnRecord, ti as automationCreatorUserId, tr as createPluginHookRunner, ts as downloadPrivateSlackFile, tt as pauseLostWorkerTurn, ui as STOP_WATCHING_TOOL_NAME, un as getAssistantReplyText, v as hydrateConversationMessages, vi as getWatch, vn as REPORT_BLOCKED_TOOL_NAME, vo as canAccessConversation, w as fallbackShortTitle, wa as openSlackDirectMessage, xo as readConversationAccessFromSql, yi as listWatches, ys as saveObjectAnnotations, zr as updateReviewItemContent } from "./projection-CNKK7doO.js";
3
- import { $ as bufferBody, X as isProviderRetryError, _ as TURN_REASONING_LEVELS, i as getChatConfig, k as resolveGatewayModel, n as botConfig } from "./config-DdO1BNcw.js";
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-QSZuMcvo.js";
2
+ import { $ as pauseLostWorkerTurn, $n as getPlugins, $r as RESOURCE_SUBSCRIPTION_MAX_TTL_MS, $s as deleteEventAutomation, Ac as ToolInputError, Ai as WorkspaceValidationError, Ar as updateReviewItemContent, B as PluginCredentialFailureError, Br as requireReviewItemLinks, Ca as SANDBOX_WORKSPACE_ROOT, Ci as createWorkspace, Cr as getReviewItem, Di as listWorkspaces, Ec as sameDefinitionValue, Ei as getWorkspaceByName, Fa as readConversationAccessFromSql, Fc as readAutomationExecutionStatusDays, Fi as create, Fo as getDispatchRecord, Fs as saveScheduledAutomation, Gr as activeParticipantUserIds, Gs as getDashboardTaskLink, Hc as fallbackShortTitle, Ic as readAutomationExecutionStatusHours, J as clearPendingAuth, Jo as getSlackMessagePermalink, Jr as resolveAssignees, Kn as createPluginHookRunner, Kr as automationCreatorUserId, Lc as readAutomationExecutionSummaries, Li as isStale, Ma as canAccessConversation, Mc as emptyAutomationRunWindows, Mi as loadSnapshotsForProfile, Ni as setWorkspaceSnapshot, No as getDispatchIdForConversation, Nr as canAgentChangeReviewItem, Ns as parseScheduledAutomationRow, Oc as automationRevision, Or as searchReviewItems, Pc as readAutomationExecutionByConversationId, Pi as setWorkspaceSnapshotBuild, Po as getDispatchInputMessageId, Pr as canReadReviewItem, Q as lostWorkerBeforeFirstSave, Qa as loadForkHistory, Qr as RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS, Rc as readAutomationExecutions, Rr as readReviewItemAgentScope, Sc as automationDefinition, So as defaultTimezone, Sr as getOpenReviewItemByDedupeKey, Tc as readAutomationVersion, Ti as getWorkspace, Ts as slackMention, Uc as resolveTaskTitle, Vn as getOAuthAccountProviders, W as AuthorizationFlowDisabledError, Wr as EVERYONE_ASSIGNEE, Xc as createPluginCache, Xi as isAbortError, Yo as openSlackDirectMessage, Z as loadTurnCheckpoint, Za as FORK_INSTRUCTIONS, Zr as getSlackToolContext, _c as registeredEventTriggerProblems, _s as sleep, ac as setEventAutomationStatus, ai as createTimerWatch, as as SlackActionError, at as getTurnRecord, bc as requireEventIdentifier, ci as findMatchingWatches, cn as getAssistantReplyText, co as readLiveAttachment, di as listWatches, dn as findLegacyNoReplyMarker, ea as WorkspaceSnapshotNotReadyError, ei as RESOURCE_WATCH_TOOL_SOURCE, er as getStaticPluginToolDefinitions, et as saveTurnCheckpoint, fn as isLegacyNoReplyMarker, gc as registeredEventMatchSchema, gn as REPORT_BLOCKED_TOOL_NAME, go as searchConversations, gs as withSlackRetries, ha as workspaceRepoCheckoutPath, hc as hasEventCatalogEntries, ic as saveEventAutomation, in as readTurnAnswer, ja as createPluginLogger, ji as invalidateReadySnapshot, jr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, js as deleteScheduledAutomation, k as markConversationMessage, kc as requireAutomationRevision, ki as updateWorkspace, lc as automationEventCatalog, li as getWatch, lo as recordUploadedAttachment, ls as getSlackClient, mc as eventWatchUnavailable, na as isWorkspaceSnapshotNotReadyError, nc as listDeletedEventAutomationsCreatedBy, nn as REPLY_TOOL_NAME, oi as createWatch, on as replyTextSchema, os as downloadPrivateSlackFile, pa as SANDBOX_RUNTIME, pc as eventNamespaceSchema, pi as turnEvents, ps as normalizeSlackConversationId, qr as resolveAssignee, rc as parseEventAutomationRow, ri as cancelWatch, rt as failTurnRecord, s as openConversationProjection, sa as createSandboxEgressCredentialToken, si as deliverWatch, ss as getFilePermalink, ti as STOP_WATCHING_TOOL_NAME, tn as isTurnExecutionLimitExceededError, to as matchSlackAttachments, tt as abandonTurnRecord, ua as buildSandboxEgressNetworkPolicy, uc as describeRegisteredEventTrigger, ui as isQuietEvent, un as NO_REPLY_TOOL_NAME, us as isConversationScopedChannel, v as hydrateConversationMessages, vc as registeredEventTypeSchema, vo as saveObjectAnnotations, vr as closeReviewItem, wc as listAutomationVersions, wi as deleteWorkspace, wr as insertReviewItem, xa as SANDBOX_REPOS_ROOT, xc as requireValidEventTrigger, xn as getTerminalAssistantMessages, xr as dismissOpenReviewItems, yc as registeredResourceTypeSchema, yo as createPluginAnnotations, zc as readAutomationRuns, zi as getSandboxProvider, zr as requireReviewItemAssignees, zs as getDashboardConversationLink } from "./projection-CWXDE0f6.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-DUD-zMvp.js";
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-oYpJYr-S.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-B8ZXvXWm.js";
7
- import { A as enqueueEventNotification, B as resolveEventMentions, C as listActiveMailboxTurns, G as conversationSubtree, I as maybePostAutomatedTurnLimitNotice, J as isExperimentalFeatureEnabled, K as conversationSubtreeColumns, M as isEventMailboxMetadata, Q as requireSlackChannelMessageScope, S as listActiveMailboxTurnSources, U as recordFinishedTurnForAutomatedLimit, W as resetAutomatedTurnLimit, X as getEventCatalog, at as workspaceSnapshotFinishedEvent, b as getAuthPausedConversationTurnId, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, i as resumeStoppedConversationTree, it as WORKSPACE_SNAPSHOT_READY_EVENT, k as EVENT_WAIT_MS, m as instructionForInputs, n as isSkippedAfterConversationStop, nt as slackChannelMessageTrigger, ot as workspaceSnapshotWatch, r as markConversationsStopped, rt as WORKSPACE_SNAPSHOT_FAILED_EVENT, st as buildDeploymentSystemPrompt, t as getConversationStoppedAtMs, v as saveUserCustomization, y as addConversationNote } from "./session-stop-DEeZKqbX.js";
8
- import { A as agentTypeSchema, H as removedCardSchema, O as AGENT_TYPES, X as briefLinkSchema, Z as briefOutcomeStatusSchema, j as formatAgentTypes, k as agentTypeInstructions } from "./conversation-BOqdRtUx.js";
9
- import { A as eventAutomationTriggerSchema, F as compileScheduleIntent, H as automationTaskSchema, L as toolScheduleIntentSchema, P as ScheduleIntentError, R as weekdaySchema, U as automationTaskText, V as automationTaskDescription, l as automationListQuerySchema, z as automationSkillNameSchema } from "./automation-CuA3yEcD.js";
6
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-B1R-nHd3.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-BQxgHR4X.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 toolScheduleIntentSchema, G as isValidTimeZone, H as getFirstRunAtMs, J as automationTaskDescription, K as automationSkillNameSchema, L as ScheduleIntentError, N as eventAutomationTriggerSchema, R as compileScheduleIntent, V as weekdaySchema, W as getZonedDateTimeParts, X as automationTaskText, Y as automationTaskSchema, f as automationListQuerySchema } from "./schedule-CHPWQn-x.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, T as isPersonInput, X as getStateAdapter, _ as readConversationTrees, a as getConversationStore, dt as resolveRootConversationId, ft as rootConversationIsArchived, g as conversationDescendants, h as conversationAncestors, i as getConversationMessageSearchStore, k as turnBehavior, mt as nextDetailVersion, nt as withLock, o as getDb, r as getConversationEventStore, s as getSqlExecutor, tt as fenceLock, v as setArchivedAt, x as userMessageQueries, yt as sameDestination } from "./db-EKJnkrIb.js";
12
- import { $ as deleteEventAutomation, A as readAutomationExecutionStatusDays, Ct as hasEventCatalogEntries, D as emptyAutomationRunWindows, Dt as registeredResourceTypeSchema, Et as registeredEventTypeSchema, H as deleteScheduledAutomation, K as saveScheduledAutomation, M as readAutomationExecutionSummaries, N as readAutomationExecutions, Ot as requireEventIdentifier, P as readAutomationRuns, St as eventWatchUnavailable, Tt as registeredEventTriggerProblems, W as parseScheduledAutomationRow, _t as automationEventCatalog, a as getPersistedThreadState, at as setEventAutomationStatus, c as coerceThreadConversationState, ct as automationDefinition, dt as readAutomationVersion, ft as sameDefinitionValue, g as getDispatchRecord, h as getDispatchInputMessageId, ht as requireAutomationRevision, i as getPersistedSandboxState, it as saveEventAutomation, j as readAutomationExecutionStatusHours, k as readAutomationExecutionByConversationId, kt as requireValidEventTrigger, m as getDispatchIdForConversation, mt as automationRevision, n as resolveTurnSessionRouting, nt as listDeletedEventAutomationsCreatedBy, rt as parseEventAutomationRow, s as persistThreadStateById, ut as listAutomationVersions, vt as describeRegisteredEventTrigger, wt as registeredEventMatchSchema, xt as eventNamespaceSchema } from "./turn-session-routing-CaY3Tp8m.js";
13
- import { A as juniorAttachmentUploads, F as juniorUsers, I as juniorDestinations, N as juniorConversations, P as juniorIdentities, T as juniorConversationEvents, _ as juniorConversationReadPositions, f as juniorAutomations, g as juniorAgentInvocations, h as juniorAgentBindings, j as juniorAttachments, p as juniorStats, u as juniorAutomationRuns, v as juniorConversationParticipants } from "./executor-CoIZmFK8.js";
14
- import { i as getFirstRunAtMs, o as getZonedDateTimeParts, s as isValidTimeZone } from "./schedule-cP0AACm1.js";
15
- import { t as discoverSkills } from "./skills-2UrD7JkN.js";
16
- import { M as sumUtcHoursIntoSixHours, T as apiErrorSchema, 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 isAgentInvocationResultEventType, x as AGENT_PARENT_MESSAGE_EVENT_TYPE, y as AGENT_INVOCATION_EVENT_NAMESPACE } from "./web-message-id-lNodcCOI.js";
17
- import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-Cf8ISkAc.js";
18
- 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-tcom1RYd.js";
19
- 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-COeYnPL_.js";
20
- import { d as contextProvenance, m as sameActorIdentity, t as KNOWN_CONVERSATION_EVENT_TYPES, u as agentInstructionProvenance } from "./history-m2-ceTTX.js";
21
- import { f as credentialContextForActor, p as credentialContextSchema } from "./registry-DBDNUUmz.js";
22
- import { o as getVercelConversationWorkQueue, p as getTurnRequestDeadline } from "./background-compaction-queue-WLPNSF_b.js";
23
- import { p as searchWeb, r as EVENT_AUTHOR_ID, u as completeText } from "./prompt-DSjhoKu5.js";
24
- import { n as postinstall, o as getSandboxResources, t as dependencies } from "./install-BT2Pf6HP.js";
25
- import { a as sendCacheWarmup, c as sendWorkspaceSnapshotJob, s as sendNextWorkspaceSnapshotJob } from "./queue-CDxkit82.js";
11
+ import { $ as getStateAdapter, A as conversationKindFromRow, E as isTopLevelKind, I as resolveActorIdentityId, O as promptModeTurnTools, P as SYSTEM_IDENTITY_ID, St as sameDestination, T as isPersonInput, _ as readConversationTrees, _t as nextDetailVersion, a as getConversationStore, at as withLock, g as conversationDescendants, h as conversationAncestors, ht as rootConversationIsArchived, i as getConversationMessageSearchStore, it as fenceLock, k as turnBehavior, mt as resolveRootConversationId, o as getDb, r as getConversationEventStore, s as getSqlExecutor, v as setArchivedAt, x as userMessageQueries } from "./db-DV2ZUb1Y.js";
12
+ import { D as juniorConversationEvents, F as juniorConversations, I as juniorIdentities, L as juniorUsers, M as juniorAttachmentUploads, N as juniorAttachments, R as juniorDestinations, _ as juniorAgentBindings, b as juniorConversationParticipants, f as juniorAutomationRuns, h as juniorStats, m as juniorAutomations, v as juniorAgentInvocations, y as juniorConversationReadPositions } from "./executor-CjNhwwnj.js";
13
+ import { t as discoverSkills } from "./skills-CPf4vNuC.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-CUaSiGme.js";
15
+ import { f as identityAvatarUrl, h as readUserAvatarUrls } from "./viewer-DKOeHpv3.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-DNC0eRZ7.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-Dz3YZ7gQ.js";
18
+ import { d as contextProvenance, m as sameActorIdentity, t as KNOWN_CONVERSATION_EVENT_TYPES, u as agentInstructionProvenance } from "./history-N7IVbUom.js";
19
+ import { f as credentialContextForActor, p as credentialContextSchema } from "./registry-1pzXmplY.js";
20
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, n as resolveTurnSessionRouting, s as persistThreadStateById } from "./turn-session-routing-BXaubz2w.js";
21
+ import { o as getVercelConversationWorkQueue, p as getTurnRequestDeadline } from "./background-compaction-queue-D2wzxtGU.js";
22
+ import { d as completeText, m as searchWeb, r as EVENT_AUTHOR_ID } from "./prompt-P3eRqO8C.js";
23
+ import { a as searchSlackUsers, i as lookupSlackUserProfile, r as lookupSlackUserByEmail } from "./users-XCCKn3xW.js";
24
+ import { n as postinstall, o as getSandboxResources, t as dependencies } from "./install-DbD7C5td.js";
25
+ import { a as sendCacheWarmup, c as sendWorkspaceSnapshotJob, s as sendNextWorkspaceSnapshotJob } from "./queue-7FSijgqG.js";
26
26
  import * as z from "zod";
27
27
  import { streamSimple } from "@earendil-works/pi-ai/compat";
28
28
  import path from "node:path";
@@ -593,6 +593,22 @@ function namesPerson(text, name) {
593
593
  return new RegExp(`(?<![\\p{L}\\p{N}])${escaped}(?![\\p{L}\\p{N}])`, "iu").test(text);
594
594
  }
595
595
  const CONVERSATION_REFERENCE = /\bthis (?:channel|conversation|thread)\b/i;
596
+ const FIRST_PERSON_WORDS = [
597
+ "me",
598
+ "my",
599
+ "myself"
600
+ ];
601
+ function wordCount(text, word) {
602
+ return text.match(new RegExp(`\\b${word}\\b`, "gi"))?.length ?? 0;
603
+ }
604
+ /**
605
+ * Return a first-person word that the text uses more often than the previous
606
+ * text, or undefined. A creator's "my" that the edit keeps stays allowed, but
607
+ * a new "me" next to it does not.
608
+ */
609
+ function addedFirstPerson(text, previousText) {
610
+ return FIRST_PERSON_WORDS.find((word) => wordCount(text, word) > wordCount(previousText, word));
611
+ }
596
612
  function refersTo(text, person) {
597
613
  return text.includes(slackMention(person.slackUserId)) || !!person.fullName && namesPerson(text, person.fullName);
598
614
  }
@@ -604,7 +620,8 @@ function refersTo(text, person) {
604
620
  * names the channel only where the run reads or acts on it. Each run reads
605
621
  * "the Automation creator" as its creator, so the text calls the creator
606
622
  * that. Every other requester needs their Slack mention, because a display
607
- * name does not notify the person and it can match another person. A run
623
+ * name does not notify the person and it can match another person. Their
624
+ * "me" needs it too, because each run reads "me" as the creator. A run
608
625
  * ends with `reply`, `noReply`, or `reportBlocked`, so a legacy no-reply
609
626
  * marker does nothing. A problem that the previous text already had stays
610
627
  * allowed, so an edit does not have to rewrite text that the requester did
@@ -617,9 +634,11 @@ function taskTextProblem(text, references) {
617
634
  const marker = findLegacyNoReplyMarker(text);
618
635
  if (marker && !previousText.includes(marker)) return `Remove "${marker}". Say when the run posts nothing; it then ends without a message.`;
619
636
  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?.fullName || requester.slackUserId === creator.slackUserId) return;
637
+ if (!requester || requester.slackUserId === creator.slackUserId) return;
621
638
  const mention = slackMention(requester.slackUserId);
622
- if (text.includes(mention) || !namesPerson(text, requester.fullName)) return;
639
+ const firstPerson = addedFirstPerson(text, previousText);
640
+ if (firstPerson) return `The ${label} says "${firstPerson}", and each run reads that as the Automation creator. Write ${mention} for the requester.`;
641
+ if (!requester.fullName || text.includes(mention) || !namesPerson(text, requester.fullName)) return;
623
642
  return `The ${label} names ${requester.fullName} without a Slack mention. Write ${mention} for this person.`;
624
643
  }
625
644
  /**
@@ -2048,6 +2067,7 @@ function formatZodPath(path) {
2048
2067
  function formatToolInputError(error) {
2049
2068
  return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
2050
2069
  }
2070
+ /** Parse tool input with its Zod schema, as a model-repairable error on failure. */
2051
2071
  function parseToolInput(schema, args) {
2052
2072
  const result = schema.safeParse(args);
2053
2073
  if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
@@ -6080,10 +6100,10 @@ const agentInvocationMailboxMetadataSchema = z.object({
6080
6100
  agentInvocationId: z.string().min(1),
6081
6101
  kind: z.literal("agent_invocation")
6082
6102
  }).strict();
6083
- /** Map a durable invocation's model settings and depth to the child Run policy. */
6084
- function agentInvocationRunPolicy(invocation, canSpawn) {
6103
+ /** Map a durable invocation's model settings to the child Run policy. */
6104
+ function agentInvocationRunPolicy(invocation) {
6085
6105
  return {
6086
- disabledFeatures: canSpawn ? ["interactive-auth"] : ["interactive-auth", "subagents"],
6106
+ disabledFeatures: ["interactive-auth"],
6087
6107
  ...invocation.reasoningLevel ? { reasoning: invocation.reasoningLevel } : void 0
6088
6108
  };
6089
6109
  }
@@ -6368,11 +6388,8 @@ async function saveAgentInvocationResult(args) {
6368
6388
  * Build the invocation consumer that advances work through the shared runner.
6369
6389
  * `enqueueResult` sends each terminal result to the parent mailbox. Omit it
6370
6390
  * only where the parent has no mailbox, such as the local CLI.
6371
- * `maxAgentDepth` is the number of child agent levels that can start their
6372
- * own child agents. The default, 0, lets only the root start child agents.
6373
6391
  */
6374
6392
  function createAgentInvocationWorker(agentRunner, options = {}) {
6375
- const canSpawn = (options.maxAgentDepth ?? 0) > 0;
6376
6393
  return async (context, invocationId) => {
6377
6394
  let invocation = await getAgentInvocation(invocationId);
6378
6395
  if (!invocation) throw new Error(`Agent invocation is missing for ${invocationId}`);
@@ -6487,7 +6504,7 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
6487
6504
  surface: "internal",
6488
6505
  deadlineAtMs: getTurnRequestDeadline()?.deadlineAtMs,
6489
6506
  ...stopSignal ? { signal: stopSignal } : void 0,
6490
- ...agentInvocationRunPolicy(invocation, canSpawn),
6507
+ ...agentInvocationRunPolicy(invocation),
6491
6508
  state: { sandboxRef },
6492
6509
  durability: {
6493
6510
  drainSteeringMessages: createAgentMessageSteeringDrain(context, invocation),
@@ -7305,6 +7322,7 @@ const listedResourceWatchSchema = z.object({
7305
7322
  namespace: z.string().min(1),
7306
7323
  resource_type: z.string().min(1),
7307
7324
  events: z.array(z.string().min(1)).min(1),
7325
+ 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."),
7308
7326
  match: z.record(z.string(), z.unknown()).optional(),
7309
7327
  intent: z.string().min(1),
7310
7328
  expires_at: z.string().datetime(),
@@ -7343,7 +7361,8 @@ function createListWatchesTool(context) {
7343
7361
  identifier: subscription.identifier,
7344
7362
  namespace: subscription.namespace,
7345
7363
  resource_type: subscription.resourceType,
7346
- events: subscription.events,
7364
+ events: turnEvents(subscription),
7365
+ ...subscription.quietEvents ? { quiet_events: subscription.quietEvents } : void 0,
7347
7366
  ...subscription.match ? { match: agentEventKeys(subscription.match) } : void 0,
7348
7367
  intent: subscription.intent,
7349
7368
  expires_at: new Date(subscription.expiresAtMs).toISOString(),
@@ -8211,7 +8230,7 @@ const subjectSchema = z.object({
8211
8230
  url: z.string().url().max(2e3).nullable().optional()
8212
8231
  }).strict();
8213
8232
  const conversationIdsSchema = z.array(z.string().trim().min(1).max(500)).max(10);
8214
- const titleSchema = z.string().trim().min(1).max(200);
8233
+ const titleSchema$1 = z.string().trim().min(1).max(200);
8215
8234
  const bodySchema = z.string().trim().min(1).max(4e3).describe("Markdown details for the person.");
8216
8235
  /**
8217
8236
  * Pick the assignees of a new item when the agent names none: the User of
@@ -8289,7 +8308,7 @@ const addReviewItemToolDefinition = zodToolDefinition({
8289
8308
  },
8290
8309
  inputSchema: z.object({
8291
8310
  kind: z.enum(["notice", "action"]).describe("Use `action` with a `request` to ask. Use `notice` only to tell a person something."),
8292
- title: titleSchema,
8311
+ title: titleSchema$1,
8293
8312
  body: bodySchema,
8294
8313
  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."),
8295
8314
  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."),
@@ -8399,7 +8418,7 @@ const updateReviewItemToolDefinition = zodToolDefinition({
8399
8418
  },
8400
8419
  inputSchema: z.object({
8401
8420
  id: z.string().trim().min(1),
8402
- title: titleSchema.nullable().optional(),
8421
+ title: titleSchema$1.nullable().optional(),
8403
8422
  body: bodySchema.nullable().optional(),
8404
8423
  assignees: assigneesSchema.nullable().optional().describe("Replaces every assignee."),
8405
8424
  conversation_ids: conversationIdsSchema.nullable().optional().describe("Replaces every other linked Conversation. The Conversation that added the item stays linked."),
@@ -8957,6 +8976,25 @@ function createReportProgressTool() {
8957
8976
  execute: async () => ({})
8958
8977
  });
8959
8978
  }
8979
+ // src/chat/plan/tool-output.ts
8980
+ /** Plan item shape in tool results. */
8981
+ const planItemOutputSchema = z.object({
8982
+ id: z.number().int(),
8983
+ title: z.string(),
8984
+ notes: z.string().optional(),
8985
+ status: z.enum(PLAN_ITEM_STATUSES),
8986
+ assignee: z.string()
8987
+ }).strict();
8988
+ /** Render one Plan item for a tool result, with assignee text for the reader. */
8989
+ function outputPlanItem(item, assignee) {
8990
+ return {
8991
+ id: item.id,
8992
+ title: item.title,
8993
+ ...item.notes ? { notes: item.notes } : void 0,
8994
+ status: item.status,
8995
+ assignee
8996
+ };
8997
+ }
8960
8998
  // src/chat/tools/runtime/list-agents.ts
8961
8999
  const TASK_MAX_LENGTH = 1e3;
8962
9000
  const ERROR_MAX_LENGTH = 500;
@@ -9007,8 +9045,23 @@ const listedAgentSchema = z.object({
9007
9045
  dashboard_url: z.string().url().optional().describe("Dashboard link of the conversation"),
9008
9046
  archived: z.literal(true).optional().describe("The conversation is archived."),
9009
9047
  error: z.string().optional().describe("Why the agent is blocked, failed, or stopped"),
9010
- updated_at: z.string().describe("Time of the latest change")
9048
+ updated_at: z.string().describe("Time of the latest change"),
9049
+ 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.")
9011
9050
  }).strict();
9051
+ /**
9052
+ * Render a parent's Plan item for its child: "self" is the child, and
9053
+ * "parent" is the parent's own agent.
9054
+ */
9055
+ function parentPlanItem(item, conversationId) {
9056
+ const { assignee } = item;
9057
+ if (assignee.kind === "self") return outputPlanItem(item, "parent");
9058
+ if (assignee.kind === "agent" && assignee.conversationId === conversationId) return outputPlanItem(item, SELF_PLAN_ASSIGNEE);
9059
+ return outputPlanItem(item, renderPlanAssignee(assignee));
9060
+ }
9061
+ /** Open items of the parent's Plan. A child never edits them. */
9062
+ async function parentPlan(parentConversationId, conversationId) {
9063
+ return (await listPlanItems(getSqlExecutor(), parentConversationId)).filter((item) => isOpenPlanItemStatus(item.status)).map((item) => parentPlanItem(item, conversationId));
9064
+ }
9012
9065
  function listedChildAgent(relation, agent) {
9013
9066
  const dashboardUrl = getDashboardConversationLink(agent.childConversationId);
9014
9067
  return {
@@ -9031,7 +9084,7 @@ const listAgentsOutputSchema = juniorToolOutputSchema.extend({ agents: z.array(l
9031
9084
  const listAgentsToolDefinition = zodToolDefinition({
9032
9085
  exposure: "deferred",
9033
9086
  source: AGENTS_TOOL_SOURCE,
9034
- 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.",
9087
+ 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.",
9035
9088
  annotations: {
9036
9089
  destructiveHint: false,
9037
9090
  idempotentHint: true,
@@ -9051,13 +9104,15 @@ function createListAgentsTool(context) {
9051
9104
  ...listAgentsToolDefinition,
9052
9105
  execute: async () => {
9053
9106
  const { children, parent, self, siblings } = await listAgentRelatives(context);
9107
+ const plan = parent ? await parentPlan(parent.conversationId, context.conversationId) : [];
9054
9108
  return { agents: [
9055
9109
  ...self ? [listedChildAgent("self", self)] : [],
9056
9110
  ...parent ? [{
9057
9111
  relation: "parent",
9058
9112
  conversation_id: parent.conversationId,
9059
9113
  status: parentAgentStatus(parent),
9060
- updated_at: new Date(parent.updatedAtMs).toISOString()
9114
+ updated_at: new Date(parent.updatedAtMs).toISOString(),
9115
+ ...plan.length > 0 ? { plan } : void 0
9061
9116
  }] : [],
9062
9117
  ...children.map((agent) => listedChildAgent("child", agent)),
9063
9118
  ...siblings.map((agent) => listedChildAgent("sibling", agent))
@@ -9178,40 +9233,112 @@ function createStopAgentTool(conversationId) {
9178
9233
  });
9179
9234
  }
9180
9235
  // src/chat/tools/runtime/update-plan.ts
9181
- const planItemSchema = z.object({
9182
- step: z.string().describe("Task step text."),
9183
- status: z.enum([
9184
- "pending",
9185
- "in_progress",
9186
- "completed"
9187
- ]).describe("Step status.")
9188
- }).strict();
9189
- const updatePlanInputSchema = z.object({
9190
- explanation: z.string().optional().describe("Optional explanation for this plan update."),
9191
- plan: z.array(planItemSchema).describe("The list of steps")
9192
- }).strict();
9236
+ const MAX_ITEMS_PER_CALL = 50;
9237
+ const statusSchema = z.enum(PLAN_ITEM_STATUSES).describe("done and cancelled close the item.");
9238
+ 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`.");
9239
+ const titleSchema = z.string().trim().min(1).max(200).describe("Short outcome to reach.");
9240
+ 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.");
9241
+ const itemIdSchema = z.number().int().positive().describe("Plan item id from an earlier result or a plan block.");
9242
+ const changesSchema = (item) => z.array(item).min(1).max(MAX_ITEMS_PER_CALL).nullable().optional();
9193
9243
  const updatePlanToolDefinition = zodToolDefinition({
9194
9244
  annotations: {
9195
9245
  destructiveHint: false,
9196
- idempotentHint: true,
9246
+ idempotentHint: false,
9197
9247
  openWorldHint: false,
9198
9248
  readOnlyHint: false
9199
9249
  },
9200
- description: [
9201
- "Updates the task plan.",
9202
- "Provide an optional explanation and a list of plan items, each with a step and status.",
9203
- "At most one step can be in_progress at a time. Mark finished steps completed and mark all steps completed when the work is done."
9204
- ].join("\n"),
9205
- inputSchema: updatePlanInputSchema
9250
+ 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.",
9251
+ inputSchema: z.object({
9252
+ add: changesSchema(z.object({
9253
+ title: titleSchema,
9254
+ notes: notesSchema.nullable().optional(),
9255
+ status: statusSchema.nullable().optional().describe("Null or omitted means pending."),
9256
+ assignee: assigneeSchema.nullable().optional()
9257
+ }).strict()).describe("New items."),
9258
+ update: changesSchema(z.object({
9259
+ id: itemIdSchema,
9260
+ title: titleSchema.nullable().optional(),
9261
+ notes: notesSchema.nullable().optional().describe("New notes. Null clears them; omit to keep them."),
9262
+ status: statusSchema.nullable().optional(),
9263
+ assignee: assigneeSchema.nullable().optional()
9264
+ }).strict()).describe("Changes to existing items. Null or omitted fields stay."),
9265
+ remove: changesSchema(itemIdSchema).describe("Ids of items added by mistake. Close finished or dropped work with a status instead.")
9266
+ }).strict(),
9267
+ outputSchema: juniorToolOutputSchema.extend({
9268
+ items: z.array(planItemOutputSchema).describe("Items that this call added or changed, or every open item when it changed none."),
9269
+ removed_ids: z.array(z.number().int()).optional(),
9270
+ replaced_person_changes: z.array(z.object({
9271
+ id: z.number().int(),
9272
+ status: z.enum(PLAN_ITEM_STATUSES),
9273
+ changed_by: z.string()
9274
+ }).strict()).optional().describe("Statuses that a person set and this call replaced. Check that the person agrees, or set the status back.")
9275
+ })
9206
9276
  });
9207
- /** Create the internal tool the model uses to replace its task plan. */
9208
- function createUpdatePlanTool() {
9277
+ function outputItem(item) {
9278
+ return outputPlanItem(item, renderPlanAssignee(item.assignee));
9279
+ }
9280
+ /**
9281
+ * Resolve the assignee text of the model: the plan's own agent, one of its
9282
+ * child agents, or a person. Only a child of this conversation can take an
9283
+ * item, as with `stopAgent`.
9284
+ */
9285
+ async function resolvePlanAssignee(context, value, findMentionedUserId) {
9286
+ const text = value.trim();
9287
+ if (text.toLowerCase() === "self" || text === context.conversationId) return { conversationId: context.conversationId };
9288
+ const childConversationId = await findChildAgentConversationId({
9289
+ parentConversationId: context.conversationId,
9290
+ target: text
9291
+ });
9292
+ if (childConversationId) return { conversationId: childConversationId };
9293
+ if (text.includes("@")) {
9294
+ const db = getDb();
9295
+ const tenant = (await readConversationAccessFromSql(db, [context.conversationId])).get(context.conversationId)?.tenant;
9296
+ const person = await resolveAssignee(db, text, tenant, findMentionedUserId);
9297
+ if ("userId" in person) return { userId: person.userId };
9298
+ }
9299
+ 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.`);
9300
+ }
9301
+ /** Create the tool that changes the durable plan of one conversation. */
9302
+ function createUpdatePlanTool(context, findMentionedUserId) {
9303
+ const assignee = (value) => resolvePlanAssignee(context, value, findMentionedUserId);
9209
9304
  return zodTool({
9210
9305
  ...updatePlanToolDefinition,
9211
- execute: async () => ({ content: [{
9212
- type: "text",
9213
- text: "Plan updated"
9214
- }] })
9306
+ execute: async (input) => {
9307
+ const add = input.add ?? [];
9308
+ const update = input.update ?? [];
9309
+ const remove = input.remove ?? [];
9310
+ const executor = getSqlExecutor();
9311
+ if (add.length + update.length + remove.length === 0) return { items: (await listPlanItems(executor, context.conversationId)).filter((item) => isOpenPlanItemStatus(item.status)).map(outputItem) };
9312
+ const { items, replacedPersonChanges } = await changePlan(executor, {
9313
+ conversationId: context.conversationId,
9314
+ nowMs: Date.now(),
9315
+ change: {
9316
+ add: await Promise.all(add.map(async (item) => ({
9317
+ title: item.title,
9318
+ ...item.notes ? { notes: item.notes } : void 0,
9319
+ status: item.status ?? "pending",
9320
+ assignee: await assignee(item.assignee ?? "self")
9321
+ }))),
9322
+ update: await Promise.all(update.map(async (item) => ({
9323
+ id: item.id,
9324
+ ...item.title ? { title: item.title } : void 0,
9325
+ ...item.notes !== void 0 ? { notes: item.notes } : void 0,
9326
+ ...item.status ? { status: item.status } : void 0,
9327
+ ...item.assignee ? { assignee: await assignee(item.assignee) } : void 0
9328
+ }))),
9329
+ remove
9330
+ }
9331
+ });
9332
+ return {
9333
+ items: items.map(outputItem),
9334
+ ...remove.length > 0 ? { removed_ids: remove } : void 0,
9335
+ ...replacedPersonChanges.length > 0 ? { replaced_person_changes: replacedPersonChanges.map((item) => ({
9336
+ id: item.id,
9337
+ status: item.status,
9338
+ changed_by: item.changedBy.email
9339
+ })) } : void 0
9340
+ };
9341
+ }
9215
9342
  });
9216
9343
  }
9217
9344
  // src/chat/tools/sandbox/bash.ts
@@ -10059,168 +10186,6 @@ function createUpdateUserCustomizationTool(context) {
10059
10186
  }
10060
10187
  });
10061
10188
  }
10062
- // src/chat/slack/users.ts
10063
- const profileFieldsSchema = z.object({ fields: z.record(z.string(), z.object({
10064
- value: z.string().optional(),
10065
- alt: z.string().optional(),
10066
- label: z.string().optional()
10067
- }).nullable()).nullish() });
10068
- function normalizeUser(raw) {
10069
- const rawFields = profileFieldsSchema.parse(raw.profile ?? {}).fields;
10070
- const profileFields = [];
10071
- if (rawFields) for (const [id, field] of Object.entries(rawFields)) {
10072
- if (!field) continue;
10073
- profileFields.push({
10074
- id,
10075
- label: field.label || void 0,
10076
- value: field.value || void 0,
10077
- alt: field.alt || void 0
10078
- });
10079
- }
10080
- return {
10081
- id: raw.id ?? "",
10082
- team_id: raw.team_id || void 0,
10083
- name: raw.name || void 0,
10084
- real_name: raw.real_name || raw.profile?.real_name || void 0,
10085
- display_name: raw.profile?.display_name || void 0,
10086
- title: raw.profile?.title || void 0,
10087
- email: raw.profile?.email || void 0,
10088
- status_text: raw.profile?.status_text ?? void 0,
10089
- status_emoji: raw.profile?.status_emoji ?? void 0,
10090
- avatar_url: raw.profile?.image_512 || void 0,
10091
- is_bot: raw.is_bot ?? false,
10092
- is_deleted: raw.deleted ?? false,
10093
- timezone: raw.tz || void 0,
10094
- ...profileFields.length > 0 ? { profile_fields: profileFields } : void 0
10095
- };
10096
- }
10097
- function normalizeNameTokens(value) {
10098
- return value.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean);
10099
- }
10100
- function nameFields(user) {
10101
- return [
10102
- user.name ?? "",
10103
- user.profile?.display_name ?? "",
10104
- user.real_name ?? user.profile?.real_name ?? ""
10105
- ].map((value) => value.toLowerCase().trim()).filter(Boolean);
10106
- }
10107
- /** Look up a Slack user by ID, returning the full profile including custom fields. */
10108
- async function lookupSlackUserProfile(userId) {
10109
- const client = getSlackClient();
10110
- const user = (await withSlackRetries(() => client.users.info({ user: userId }), 3, { action: "users.info" })).user;
10111
- if (!user) throw new Error(`Slack users.info returned no user for ${userId}`);
10112
- return normalizeUser(user);
10113
- }
10114
- /** Look up a Slack bot by ID. Returns undefined when Slack has no such bot. */
10115
- async function lookupSlackBot(botId) {
10116
- try {
10117
- return (await withSlackRetries(() => getSlackClient().bots.info({ bot: botId }), 3, { action: "bots.info" })).bot;
10118
- } catch (error) {
10119
- if (error instanceof SlackActionError && error.apiError === "bot_not_found") return;
10120
- throw error;
10121
- }
10122
- }
10123
- /** Look up a Slack user by email. Returns null when no user matches. */
10124
- async function lookupSlackUserByEmail(email) {
10125
- const client = getSlackClient();
10126
- let result;
10127
- try {
10128
- result = await withSlackRetries(() => client.users.lookupByEmail({ email }), 3, { action: "users.lookupByEmail" });
10129
- } catch (error) {
10130
- if (error instanceof SlackActionError && error.apiError === "users_not_found") return null;
10131
- throw error;
10132
- }
10133
- const user = result.user;
10134
- if (!user) return null;
10135
- return normalizeUser(user);
10136
- }
10137
- /**
10138
- * Rank Slack name-search quality for one candidate.
10139
- * Exact field and token matches beat field prefixes so a display-name prefix
10140
- * cannot outrank a real-name first-name hit.
10141
- */
10142
- function scoreNameMatch(user, query) {
10143
- const queryLower = query.toLowerCase().trim();
10144
- if (!queryLower) return 0;
10145
- const fields = nameFields(user);
10146
- if (fields.length === 0) return 0;
10147
- let best = 0;
10148
- const queryTokens = normalizeNameTokens(queryLower);
10149
- for (const field of fields) {
10150
- if (field === queryLower) {
10151
- best = Math.max(best, 100);
10152
- continue;
10153
- }
10154
- if (field.startsWith(queryLower)) best = Math.max(best, 70);
10155
- else if (field.includes(queryLower)) best = Math.max(best, 25);
10156
- const tokens = normalizeNameTokens(field);
10157
- for (const token of tokens) if (token === queryLower) best = Math.max(best, 85);
10158
- else if (token.startsWith(queryLower)) best = Math.max(best, 60);
10159
- if (queryTokens.length > 1 && queryTokens.every((queryToken) => tokens.some((token) => token === queryToken || token.startsWith(queryToken)))) best = Math.max(best, 95);
10160
- }
10161
- return best;
10162
- }
10163
- function compareNameMatches(left, right) {
10164
- if (right.score !== left.score) return right.score - left.score;
10165
- return (left.user.name ?? "").localeCompare(right.user.name ?? "");
10166
- }
10167
- async function listWorkspaceUsers(options) {
10168
- const client = getSlackClient();
10169
- const matches = [];
10170
- let cursor;
10171
- let pages = 0;
10172
- let totalScanned = 0;
10173
- while (pages < options.maxPages) {
10174
- pages++;
10175
- const result = await withSlackRetries(() => client.users.list({
10176
- limit: 200,
10177
- ...cursor ? { cursor } : void 0
10178
- }), 3, { action: "users.list" });
10179
- const members = result.members ?? [];
10180
- totalScanned += members.length;
10181
- for (const member of members) {
10182
- if (!options.includeDeleted && member.deleted) continue;
10183
- if (!options.includeBots && member.is_bot) continue;
10184
- if (member.id === "USLACKBOT") continue;
10185
- const score = options.score(member);
10186
- if (score <= 0) continue;
10187
- matches.push({
10188
- user: member,
10189
- score
10190
- });
10191
- }
10192
- const nextCursor = result.response_metadata?.next_cursor;
10193
- if (!nextCursor) {
10194
- cursor = void 0;
10195
- break;
10196
- }
10197
- cursor = nextCursor;
10198
- }
10199
- return {
10200
- matches,
10201
- searched_pages: pages,
10202
- searched_user_count: totalScanned,
10203
- truncated: pages >= options.maxPages && Boolean(cursor)
10204
- };
10205
- }
10206
- /** Search workspace users by name with bounded pagination through `users.list`. */
10207
- async function searchSlackUsers(options) {
10208
- const { query, limit = 10, maxPages = 3, includeDeleted = false, includeBots = false } = options;
10209
- const queryLower = query.toLowerCase().trim();
10210
- const listed = await listWorkspaceUsers({
10211
- maxPages,
10212
- includeDeleted,
10213
- includeBots,
10214
- score: (member) => scoreNameMatch(member, queryLower)
10215
- });
10216
- listed.matches.sort(compareNameMatches);
10217
- return {
10218
- users: listed.matches.slice(0, limit).map((m) => normalizeUser(m.user)),
10219
- searched_pages: listed.searched_pages,
10220
- searched_user_count: listed.searched_user_count,
10221
- truncated: listed.truncated
10222
- };
10223
- }
10224
10189
  // src/chat/tools/user-lookup.ts
10225
10190
  const linkedSlackIdentity = alias(juniorIdentities, "user_lookup_slack_identity");
10226
10191
  function explicitUserLookupError(error) {
@@ -10367,7 +10332,7 @@ function userLookupToolDefinition(providers) {
10367
10332
  },
10368
10333
  inputSchema: z.object({
10369
10334
  provider: z.enum(providers).describe("Enabled identity provider to query."),
10370
- query: z.string().trim().min(1).describe("Provider subject ID, handle, Slack email, or Slack name. For Slack, pass the user ID (`U…`) whenever the conversation shows one, such as the requester's `author_id`, a participant's `actor_id`, or a `<@U…>` mention. Search by name only with no known ID.")
10335
+ 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.")
10371
10336
  }).strict(),
10372
10337
  outputSchema: juniorToolOutputSchema
10373
10338
  });
@@ -10994,42 +10959,70 @@ async function ingestEvent(input, options) {
10994
10959
  identifier: event.identifier,
10995
10960
  state: options.state
10996
10961
  });
10997
- let mentions = { people: [] };
10998
- if (subscriptions.length > 0 && options.slackTeamId) try {
10999
- mentions = await resolveEventMentions(event, options.slackTeamId);
10962
+ if (subscriptions.length === 0) return { enqueued: 0 };
10963
+ const author = await resolveEventAuthor(event);
10964
+ if (author.status === "untrusted") logInfo("event.author.untrusted", {
10965
+ "app.event.event_type": event.eventType,
10966
+ "app.event.namespace": event.namespace,
10967
+ "app.event.author.reason": author.reason
10968
+ });
10969
+ let people = [];
10970
+ if (options.slackTeamId && event.people?.length) try {
10971
+ people = await resolveEventMentions(event.people, options.slackTeamId);
11000
10972
  } catch (error) {
11001
10973
  logException(error, "event.people.resolve.failed", {
11002
10974
  "app.event.event_type": event.eventType,
11003
10975
  "app.event.namespace": event.namespace
11004
10976
  });
11005
10977
  }
10978
+ const doneBy = author.status === "trusted" && author.actor ? {
10979
+ mention: slackMention(author.actor.userId),
10980
+ handle: author.handle
10981
+ } : void 0;
10982
+ const turnConversations = /* @__PURE__ */ new Set();
10983
+ const ordered = [...subscriptions].sort((left, right) => Number(isQuietEvent(left, event.eventType)) - Number(isQuietEvent(right, event.eventType)));
11006
10984
  let enqueued = 0;
11007
10985
  const errors = [];
11008
10986
  const waitDeadlineMs = Date.now() + 1e4;
11009
- for (const subscription of subscriptions) try {
11010
- if (await deliverWatch({
11011
- data: event.data,
11012
- eventType: event.eventType,
11013
- namespace: event.namespace,
11014
- identifier: event.identifier,
11015
- terminal: event.terminal,
11016
- nowMs,
11017
- state: options.state,
11018
- subscription,
11019
- waitDeadlineMs,
11020
- deliver: async (current) => {
11021
- return (await enqueueEventNotification({
11022
- doneBy: mentions.doneBy,
11023
- event,
11024
- people: mentions.people,
11025
- queue: options.queue,
11026
- state: options.state,
11027
- subscription: current
11028
- })).status === "appended";
11029
- }
11030
- })) enqueued += 1;
11031
- } catch (error) {
11032
- errors.push(error);
10987
+ for (const subscription of ordered) {
10988
+ let quiet = false;
10989
+ try {
10990
+ if (await deliverWatch({
10991
+ data: event.data,
10992
+ eventType: event.eventType,
10993
+ namespace: event.namespace,
10994
+ identifier: event.identifier,
10995
+ terminal: event.terminal,
10996
+ nowMs,
10997
+ state: options.state,
10998
+ subscription,
10999
+ waitDeadlineMs,
11000
+ deliver: async (current) => {
11001
+ if (isQuietEvent(current, event.eventType)) {
11002
+ quiet = true;
11003
+ if (!turnConversations.has(current.conversationId)) await addQuietEventNote({
11004
+ event,
11005
+ subscription: current
11006
+ });
11007
+ return true;
11008
+ }
11009
+ const result = await enqueueEventNotification({
11010
+ author,
11011
+ doneBy,
11012
+ event,
11013
+ people,
11014
+ queue: options.queue,
11015
+ state: options.state,
11016
+ subscription: current
11017
+ });
11018
+ if (result.status === "paused") return false;
11019
+ turnConversations.add(current.conversationId);
11020
+ return result.status === "appended";
11021
+ }
11022
+ }) && !quiet) enqueued += 1;
11023
+ } catch (error) {
11024
+ errors.push(error);
11025
+ }
11033
11026
  }
11034
11027
  if (errors.length > 0) throw new AggregateError(errors, "Failed to deliver one or more watches");
11035
11028
  return { enqueued };
@@ -12008,7 +12001,7 @@ function always(definition) {
12008
12001
  }
12009
12002
  const slackOnly = ({ platform }) => platform === "slack";
12010
12003
  const hasEvents = () => hasEventCatalogEntries(getEventCatalog());
12011
- const hasAgents = ({ turnTools }) => turnTools.agents !== "none";
12004
+ const hasAgents = ({ listedTools }) => listedTools.agents !== "none";
12012
12005
  function workspaceTool(name) {
12013
12006
  return {
12014
12007
  when: () => workspaceProviderNames() !== void 0,
@@ -12053,11 +12046,11 @@ const CORE_TOOLS = {
12053
12046
  definition: () => runOperatorSqlToolDefinition
12054
12047
  },
12055
12048
  updateUserCustomization: {
12056
- when: ({ turnTools }) => isExperimentalFeatureEnabled("user-customization") && turnTools.userCustomization,
12049
+ when: ({ listedTools }) => isExperimentalFeatureEnabled("user-customization") && listedTools.userCustomization,
12057
12050
  definition: () => updateUserCustomizationToolDefinition
12058
12051
  },
12059
12052
  setConversationSubscription: {
12060
- when: ({ turnTools }) => turnTools.subscriptions,
12053
+ when: ({ listedTools }) => listedTools.subscriptions,
12061
12054
  definition: () => setConversationSubscriptionToolDefinition
12062
12055
  },
12063
12056
  searchConversationEvents: always(searchConversationEventsToolDefinition),
@@ -12095,15 +12088,15 @@ const CORE_TOOLS = {
12095
12088
  definition: () => messageAgentToolDefinition
12096
12089
  },
12097
12090
  [REPLY_TOOL_NAME]: {
12098
- when: ({ turnTools }) => turnTools.reply !== "none",
12099
- definition: ({ turnTools }) => replyToolDefinition(enabledMode(turnTools.reply))
12091
+ when: ({ listedTools }) => listedTools.reply !== "none",
12092
+ definition: ({ listedTools }) => replyToolDefinition(enabledMode(listedTools.reply))
12100
12093
  },
12101
12094
  [REPORT_BLOCKED_TOOL_NAME]: {
12102
- when: ({ turnTools }) => turnTools.reportBlocked !== "none",
12103
- definition: ({ turnTools }) => reportBlockedToolDefinition(enabledMode(turnTools.reportBlocked))
12095
+ when: ({ listedTools }) => listedTools.reportBlocked !== "none",
12096
+ definition: ({ listedTools }) => reportBlockedToolDefinition(enabledMode(listedTools.reportBlocked))
12104
12097
  },
12105
12098
  [NO_REPLY_TOOL_NAME]: {
12106
- when: ({ turnTools }) => turnTools.noReply,
12099
+ when: ({ listedTools }) => listedTools.noReply,
12107
12100
  definition: () => noReplyToolDefinition
12108
12101
  },
12109
12102
  searchMcpTools: RUN_BUILT,
@@ -12203,7 +12196,7 @@ function modelFacing(definition) {
12203
12196
  function staticToolDefinitions(key) {
12204
12197
  const scope = {
12205
12198
  platform: key.platform,
12206
- turnTools: promptModeTurnTools(key.mode)
12199
+ listedTools: promptModeTurnTools(key.mode)
12207
12200
  };
12208
12201
  const core = {};
12209
12202
  for (const [name, entry] of coreToolEntries()) {
@@ -12950,16 +12943,17 @@ function askedReviewItem(messages, final) {
12950
12943
  * The active Watches of the Conversation, and what else its idle period
12951
12944
  * waits on. Watches include timers and the event Watches that tools such as
12952
12945
  * `createPullRequest` add. A child agent that still runs comes first: its
12953
- * result starts a Turn without a person. In an Automation run, only a child
12954
- * agent or a Watch can start a later Turn, so a Review item does not count.
12946
+ * result starts a Turn without a person. When `idleNeedsPendingWork`, as in
12947
+ * an Automation run, only a child agent or a Watch can start a later Turn, so
12948
+ * a Review item does not count.
12955
12949
  */
12956
- async function readPendingWork(conversationId, messages, final, automation) {
12950
+ async function readPendingWork(conversationId, messages, final, idleNeedsPendingWork) {
12957
12951
  const [watches, children] = await Promise.all([listWatches({ conversationId }), listChildAgents(conversationId)]);
12958
12952
  if (children.some((child) => NON_TERMINAL_AGENT_INVOCATION_STATUSES.includes(child.status))) return {
12959
12953
  watches,
12960
12954
  waitingOn: "child"
12961
12955
  };
12962
- if (automation) return watches.length > 0 ? {
12956
+ if (idleNeedsPendingWork) return watches.length > 0 ? {
12963
12957
  watches,
12964
12958
  waitingOn: "watch"
12965
12959
  } : { watches };
@@ -13180,9 +13174,8 @@ async function recordGap(state, conversationId, generation, warm, gapMs) {
13180
13174
  });
13181
13175
  }
13182
13176
  async function startIdlePeriod(state, conversationId, request, message, turn, definitionsKey, turnEnding) {
13183
- const automation = definitionsKey.mode === "automation";
13184
- const { watches, waitingOn } = await readPendingWork(conversationId, request.context.messages, message, automation);
13185
- if (automation && !waitingOn) return void 0;
13177
+ const { watches, waitingOn } = await readPendingWork(conversationId, request.context.messages, message, turn.idleNeedsPendingWork);
13178
+ if (turn.idleNeedsPendingWork && !waitingOn) return void 0;
13186
13179
  const idle = {
13187
13180
  generation: randomUUID(),
13188
13181
  sinceMs: request.startedAtMs
@@ -13257,7 +13250,7 @@ async function recordSavings(idle, request, message) {
13257
13250
  if (!savings) return;
13258
13251
  await recordIdlePeriodSavings(idle.warm?.modelId ?? request.model.id, savings, idle.warm !== void 0);
13259
13252
  }
13260
- async function recordModelCall(conversationId, userActor, definitionsKey, request, message, turnEnding) {
13253
+ async function recordModelCall(conversationId, turn, definitionsKey, request, message, turnEnding) {
13261
13254
  const state = await connectedState();
13262
13255
  const previous = await state.get(conversationKey(conversationId));
13263
13256
  const idle = previous?.idle;
@@ -13278,7 +13271,7 @@ async function recordModelCall(conversationId, userActor, definitionsKey, reques
13278
13271
  if (idle) await recordSavings(idle, request, message);
13279
13272
  const endedTurns = previous?.endedTurns ?? 0;
13280
13273
  const nextIdle = turnEnding ? await startIdlePeriod(state, conversationId, request, message, {
13281
- userActor,
13274
+ ...turn,
13282
13275
  endedTurns
13283
13276
  }, definitionsKey, turnEnding) : void 0;
13284
13277
  const next = nextIdle ? {
@@ -13312,11 +13305,10 @@ async function stopIdleWarmups(conversationId) {
13312
13305
  }
13313
13306
  }
13314
13307
  /**
13315
- * Create a recorder for one agent run. `userActor` is true when a person
13316
- * started the Turn. A failure to record only loses cache warming, so it is
13317
- * logged and does not stop the run.
13308
+ * Create a recorder for one agent run. A failure to record only loses cache
13309
+ * warming, so it is logged and does not stop the run.
13318
13310
  */
13319
- function createCacheWarmingRecorder(conversationId, userActor, definitionsKey) {
13311
+ function createCacheWarmingRecorder(conversationId, turn, definitionsKey) {
13320
13312
  let lastRequest;
13321
13313
  let lastCall;
13322
13314
  let answerToolEnding;
@@ -13361,7 +13353,7 @@ function createCacheWarmingRecorder(conversationId, userActor, definitionsKey) {
13361
13353
  if (idleEnded && message.stopReason !== "stop") return;
13362
13354
  idleEnded = message.stopReason !== "stop";
13363
13355
  try {
13364
- await recordModelCall(conversationId, userActor, definitionsKey, request, message, message.stopReason === "stop" ? "reply" : void 0);
13356
+ await recordModelCall(conversationId, turn, definitionsKey, request, message, message.stopReason === "stop" ? "reply" : void 0);
13365
13357
  } catch (error) {
13366
13358
  logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
13367
13359
  }
@@ -13378,7 +13370,7 @@ function createCacheWarmingRecorder(conversationId, userActor, definitionsKey) {
13378
13370
  }
13379
13371
  if (!answerToolEnding || !lastCall) return;
13380
13372
  try {
13381
- await recordModelCall(conversationId, userActor, definitionsKey, lastCall.request, lastCall.message, answerToolEnding);
13373
+ await recordModelCall(conversationId, turn, definitionsKey, lastCall.request, lastCall.message, answerToolEnding);
13382
13374
  } catch (error) {
13383
13375
  logWarn("cache_warming.model_call.record_failed", { "exception.message": error instanceof Error ? error.message : String(error) });
13384
13376
  }
@@ -13549,4 +13541,4 @@ async function runCacheWarmup(message) {
13549
13541
  }, startedAtMs, warm);
13550
13542
  }, attributes);
13551
13543
  }
13552
- export { createBashTool as $, createSlackPublicSearchTool as $n, requireToolCreator as $r, childAgentInput as $t, createWebSearchTool as A, MIN_WARMUP_PREFIX_TOKENS as Ai, createPausedTurns as An, createSearchAutomationsTool as Ar, collectAttachmentUploadGarbage as At, createSystemTimeTool as B, deleteWebAuthorization as Bn, automationTriggerChangesSchema as Br, NON_TERMINAL_AGENT_INVOCATION_STATUSES as Bt, incrementStat as C, missingAutomationSkillReason as Ci, AgentMessagePausedError as Cn, createSlackCanvasEditTool as Cr, conversationTurnIdForMessage as Ct, requireReadyWorkspaceSnapshot as D, countOwnedAutomationsNeedingAttention as Di, PARENT_AGENT_TARGET as Dn, resolveWorkspacePath as Dr, webActorFromUser as Dt, processWorkspaceSnapshotJob as E, resolveTaskOutcomes as Ei, getAgentBinding as En, positiveInteger$1 as Er, recordWebConversationActivity as Et, userLookupIdentityProviders as F, canJoinTurn as Fn, zodToolDefinition as Fr, createRunOperatorSqlTool as Ft, createWriteFileTool as G, setConversationSubscription as Gn, injectContinuationToolName as Gr, getLatestAgentInvocationForConversation as Gt, createSearchEventTypesTool as H, AgentRunError as Hn, editedAutomationTask as Hr, getActiveAgentInvocationForConversation as Ht, lookupSlackBot as I, canShareTurn as In, automationIdForToolCall as Ir, createListWatchesTool as It, sliceFileContent as J, throwApiError as Jn, getConversationAccess as Jr, listPendingAgentInvocationMailboxAppends as Jt, createReadFileTool as K, emptyResponse as Kn, juniorToolOutputSchema as Kr, isTerminalAgentInvocation as Kt, lookupSlackUserProfile as L, isAttemptInterrupt as Ln, automationSkillToolSchema as Lr, listOwnedWatches as Lt, createWatchTimerTool as M, gapSegment as Mi, wakeAuthorizedTurn as Mn, createDeleteAutomationTool as Mr, verifyAttachmentUploads as Mt, createWatchEventsTool as N, wakePausedTurn as Nn, AUTOMATIONS_TOOL_SOURCE as Nr, writeAttachmentUpload as Nt, prepareWorkspaceSnapshot as O, IDLE_HORIZON_MS as Oi, supersedeOpenMailboxTurns as On, createOperationKey as Or, resolveConversationDestination as Ot, createUserLookupTool as P, getTurnAuthorization as Pn, zodTool as Pr, createReadConversationEventTool as Pt, editFile as Q, parseSlackMessageReference as Qn, requireToolCaller as Qr, sendsResultToParent as Qt, createUpdateUserCustomizationTool as R, selectAttemptMessages as Rn, automationToolResult as Rr, listChildAgents as Rt, createWorkspaceTools as S, findAutomationSkill as Si, AgentDepthLimitError as Sn, createSlackCanvasReadTool as Sr, appendAndEnqueueWebMessage as St, ensureWorkspaceSnapshotBuild as T, moveTaskOutcomes as Ti, findChildAgentConversationId as Tn, isMissingPathError as Tr, createConversationId as Tt, createSearchConversationEventsTool as U, executeTurn as Un, newAutomationTask as Ur, getAgentInvocation as Ut, createStopWatchingResourcesTool as V, getWebAuthorization as Vn, automationTriggerSchema as Vr, TERMINAL_AGENT_INVOCATION_STATUSES as Vt, createSearchConversationsTool as W, createSetConversationSubscriptionTool as Wn, triggerKind as Wr, getChildAgentLabel as Wt, capToolResult as X, renderAttachmentText as Xn, automationToolsDisabledReason as Xr, markAgentInvocationParentMailboxAppended as Xt, TOOL_RESULT_MAX_CHARS as Y, createSlackThreadReadTool as Yn, automationToolContext as Yr, listPendingAgentInvocationResults as Yt, createEditFileTool as Z, renderBlockText as Zn, requireToolAutomation as Zr, reportReplacedWithoutOpenWork as Zt, closeBreaker as _, changedEventMatch as _i, cancelSignInWait as _n, isConversationMember as _r, createUpdateReviewItemTool as _t, createCacheWarmingRecorder as a, deleteViewerTask as ai, logDroppedParentMessage as an, createSlackConversationSearchChannelPort as ar, createReportBlockedTool as at, coreToolSlots as b, AutomationEditError as bi, createAgentInvocationForMessage as bn, listThreadReplies as br, reviewItemChangeRecord as bt, isConversationWorkDone as c, ViewerTaskNotFoundError as ci, createAgentInvocationWorker as cn, readSlackRawMessageContext as cr, createMessageAgentTool as ct, addHistoryPeriod as d, readViewerAutomationRuns as di, endAgentInvocationsOfStoppedWork as dn, resolveSlackChannelRef as dr, archiveConversation as dt, requireToolDestination as ei, getChildAgentInputSender as en, createSlackListUpdateItemTool as er, createUpdatePlanTool as et, firstLiveSavingsDate as f, readViewerAutomationSummary as fi, enqueueAgentInvocation as fn, slackChannelRefParam as fr, conversationReadPositionQuery as ft, breakerStates as g, editEventAutomation as gi, stopChildAgentsOf as gn, getConversationInfo as gr, createSearchReviewItemsTool as gt, savingsTotals as h, editScheduledAutomation as hi, stopChildAgentsBelow as hn, getChannelMessage as hr, createAddReviewItemTool as ht, GLOBAL_GAPS_TTL_MS as i, changeViewerAutomationLifecycle as ii, isParentMessageMeta as in, createSlackConversationMessageSearchTool as ir, createReportProgressTool as it, createWebFetchTool as j, NO_REPLY_GAP_MS as ji, getPausedTurnRequest as jn, createRunAutomationNowTool as jr, createAttachmentUpload as jt, ingestEvent as k, MINUTE_MS$1 as ki, supersedeTurnForInput as kn, createCanvas as kr, AttachmentUploadError as kt, listConversationWork as l, readConversationSourceTask as li, createAndEnqueueAgentInvocation as ln, resolveSlackChannelIdFromMessage as lr, createArchiveAgentTool as lt, replaceHistorySavings as m, readViewerAutomations as mi, dropOwnUnreadLoopReplies as mn, joinPublicChannelForRead as mr, reportConversationRead as mt, CONVERSATION_STATE_TTL_MS as n, automationEditor as ni, routeChildInput as nn, createSlackListCreateTool as nr, createSpawnAgentTool as nt, segmentGapsKey as o, readViewerAutomationEdit as oi, parentMessageText as on, createSlackChannelListMessagesTool as or, createReplyTool as ot, idlePeriodSavings as p, readViewerAutomationVersions as pi, resolveAgentInvocationId as pn, checkSlackChannelReadAccess as pr, markConversationRead as pt, missingFileResult as q, jsonResponse as qn, makeStructuredToolOutput as qr, listAgentInvocationsForConversation as qt, GLOBAL_GAPS_MAX as r, changeAutomationLifecycle as ri, childAgentTurnOptions as rn, createSlackListAddItemsTool as rr, createListAgentsTool as rt, warmup_exports as s, updateViewerAutomation as si, readParentMessage as sn, parseSlackThreadId as sr, createNoReplyTool as st, ANSWER_TOOL_ENDINGS as t, activateViewerAutomationVersion as ti, readChildConversationSender as tn, createSlackListGetItemsTool as tr, createStopAgentTool as tt, SAVINGS_NAMESPACE as u, readViewerAutomationExecutions as ui, endActiveAgentInvocations as un, createSlackChannelJoinTool as ur, readLastUserMessageAtByConversation as ut, connectedState as v, requireEventAutomationTrigger as vi, completeCancelledConversationTurn as vn, isPublicSlackChannel as vr, deliverReviewItemChange as vt, readStats as w, effectiveTaskOutcomes as wi, AgentMessageTargetError as wn, SLACK_TOOL_SOURCE as wr, createAndEnqueueConversation as wt, enabledMode as x, requireAutomationSkill as xi, createAgentInvocationFromLatest as xn, createSlackCanvasWriteTool as xr, acceptsWebMessages as xt, providerCacheTtlMs as y, requireAutomationTaskText as yi, recordSubagentEnded as yn, joinPublicChannel as yr, renderReviewItemMessage as yt, createSubmitFeedbackTool as z, createWebAuthorization as zn, automationToolResultSchema as zr, listUnreportedSiblingAgents as zt };
13544
+ export { createStopAgentTool as $, createSlackListGetItemsTool as $n, requireToolDestination as $r, readChildConversationSender as $t, createWebSearchTool as A, NO_REPLY_GAP_MS as Ai, wakeAuthorizedTurn as An, createDeleteAutomationTool as Ar, verifyAttachmentUploads as At, createSearchEventTypesTool as B, AgentRunError as Bn, automationTriggerSchema as Br, getActiveAgentInvocationForConversation as Bt, incrementStat as C, effectiveTaskOutcomes as Ci, findChildAgentConversationId as Cn, isMissingPathError as Cr, createConversationId as Ct, requireReadyWorkspaceSnapshot as D, IDLE_HORIZON_MS as Di, supersedeTurnForInput as Dn, createCanvas as Dr, AttachmentUploadError as Dt, processWorkspaceSnapshotJob as E, countOwnedAutomationsNeedingAttention as Ei, supersedeOpenMailboxTurns as En, createOperationKey as Er, resolveConversationDestination as Et, userLookupIdentityProviders as F, isAttemptInterrupt as Fn, automationIdForToolCall as Fr, listOwnedWatches as Ft, missingFileResult as G, jsonResponse as Gn, juniorToolOutputSchema as Gr, listAgentInvocationsForConversation as Gt, createSearchConversationsTool as H, createSetConversationSubscriptionTool as Hn, newAutomationTask as Hr, getChildAgentLabel as Ht, createUpdateUserCustomizationTool as I, selectAttemptMessages as In, automationSkillToolSchema as Ir, listChildAgents as It, capToolResult as J, renderAttachmentText as Jn, automationToolContext as Jr, markAgentInvocationParentMailboxAppended as Jt, sliceFileContent as K, throwApiError as Kn, makeStructuredToolOutput as Kr, listPendingAgentInvocationMailboxAppends as Kt, createSubmitFeedbackTool as L, createWebAuthorization as Ln, automationToolResult as Lr, listUnreportedSiblingAgents as Lt, createWatchTimerTool as M, getTurnAuthorization as Mn, parseToolInput as Mr, createReadConversationEventTool as Mt, createWatchEventsTool as N, canJoinTurn as Nn, zodTool as Nr, createRunOperatorSqlTool as Nt, prepareWorkspaceSnapshot as O, MINUTE_MS$1 as Oi, createPausedTurns as On, createSearchAutomationsTool as Or, collectAttachmentUploadGarbage as Ot, createUserLookupTool as P, canShareTurn as Pn, zodToolDefinition as Pr, createListWatchesTool as Pt, createUpdatePlanTool as Q, createSlackListUpdateItemTool as Qn, requireToolCreator as Qr, getChildAgentInputSender as Qt, createSystemTimeTool as R, deleteWebAuthorization as Rn, automationToolResultSchema as Rr, NON_TERMINAL_AGENT_INVOCATION_STATUSES as Rt, createWorkspaceTools as S, missingAutomationSkillReason as Si, AgentMessageTargetError as Sn, SLACK_TOOL_SOURCE as Sr, createAndEnqueueConversation as St, ensureWorkspaceSnapshotBuild as T, resolveTaskOutcomes as Ti, PARENT_AGENT_TARGET as Tn, resolveWorkspacePath as Tr, webActorFromUser as Tt, createWriteFileTool as U, setConversationSubscription as Un, triggerKind as Ur, getLatestAgentInvocationForConversation as Ut, createSearchConversationEventsTool as V, executeTurn as Vn, editedAutomationTask as Vr, getAgentInvocation as Vt, createReadFileTool as W, emptyResponse as Wn, injectContinuationToolName as Wr, isTerminalAgentInvocation as Wt, editFile as X, parseSlackMessageReference as Xn, requireToolAutomation as Xr, sendsResultToParent as Xt, createEditFileTool as Y, renderBlockText as Yn, automationToolsDisabledReason as Yr, reportReplacedWithoutOpenWork as Yt, createBashTool as Z, createSlackPublicSearchTool as Zn, requireToolCaller as Zr, childAgentInput as Zt, closeBreaker as _, requireEventAutomationTrigger as _i, recordSubagentEnded as _n, joinPublicChannel as _r, renderReviewItemMessage as _t, createCacheWarmingRecorder as a, readViewerAutomationEdit as ai, readParentMessage as an, parseSlackThreadId as ar, createNoReplyTool as at, coreToolSlots as b, requireAutomationSkill as bi, AgentDepthLimitError as bn, createSlackCanvasReadTool as br, appendAndEnqueueWebMessage as bt, isConversationWorkDone as c, readConversationSourceTask as ci, endActiveAgentInvocations as cn, createSlackChannelJoinTool as cr, readLastUserMessageAtByConversation as ct, addHistoryPeriod as d, readViewerAutomationSummary as di, resolveAgentInvocationId as dn, checkSlackChannelReadAccess as dr, markConversationRead as dt, activateViewerAutomationVersion as ei, routeChildInput as en, createSlackListCreateTool as er, createSpawnAgentTool as et, firstLiveSavingsDate as f, readViewerAutomationVersions as fi, dropOwnUnreadLoopReplies as fn, joinPublicChannelForRead as fr, reportConversationRead as ft, breakerStates as g, changedEventMatch as gi, completeCancelledConversationTurn as gn, isPublicSlackChannel as gr, deliverReviewItemChange as gt, savingsTotals as h, editEventAutomation as hi, cancelSignInWait as hn, isConversationMember as hr, createUpdateReviewItemTool as ht, GLOBAL_GAPS_TTL_MS as i, deleteViewerTask as ii, parentMessageText as in, createSlackChannelListMessagesTool as ir, createReplyTool as it, createWebFetchTool as j, gapSegment as ji, wakePausedTurn as jn, AUTOMATIONS_TOOL_SOURCE as jr, writeAttachmentUpload as jt, ingestEvent as k, MIN_WARMUP_PREFIX_TOKENS as ki, getPausedTurnRequest as kn, createRunAutomationNowTool as kr, createAttachmentUpload as kt, listConversationWork as l, readViewerAutomationExecutions as li, endAgentInvocationsOfStoppedWork as ln, resolveSlackChannelRef as lr, archiveConversation as lt, replaceHistorySavings as m, editScheduledAutomation as mi, stopChildAgentsOf as mn, getConversationInfo as mr, createSearchReviewItemsTool as mt, CONVERSATION_STATE_TTL_MS as n, changeAutomationLifecycle as ni, isParentMessageMeta as nn, createSlackConversationMessageSearchTool as nr, createReportProgressTool as nt, segmentGapsKey as o, updateViewerAutomation as oi, createAgentInvocationWorker as on, readSlackRawMessageContext as or, createMessageAgentTool as ot, idlePeriodSavings as p, readViewerAutomations as pi, stopChildAgentsBelow as pn, getChannelMessage as pr, createAddReviewItemTool as pt, TOOL_RESULT_MAX_CHARS as q, createSlackThreadReadTool as qn, getConversationAccess as qr, listPendingAgentInvocationResults as qt, GLOBAL_GAPS_MAX as r, changeViewerAutomationLifecycle as ri, logDroppedParentMessage as rn, createSlackConversationSearchChannelPort as rr, createReportBlockedTool as rt, warmup_exports as s, ViewerTaskNotFoundError as si, createAndEnqueueAgentInvocation as sn, resolveSlackChannelIdFromMessage as sr, createArchiveAgentTool as st, ANSWER_TOOL_ENDINGS as t, automationEditor as ti, childAgentTurnOptions as tn, createSlackListAddItemsTool as tr, createListAgentsTool as tt, SAVINGS_NAMESPACE as u, readViewerAutomationRuns as ui, enqueueAgentInvocation as un, slackChannelRefParam as ur, conversationReadPositionQuery as ut, connectedState as v, requireAutomationTaskText as vi, createAgentInvocationForMessage as vn, listThreadReplies as vr, reviewItemChangeRecord as vt, readStats as w, moveTaskOutcomes as wi, getAgentBinding as wn, positiveInteger$1 as wr, recordWebConversationActivity as wt, enabledMode as x, findAutomationSkill as xi, AgentMessagePausedError as xn, createSlackCanvasEditTool as xr, conversationTurnIdForMessage as xt, providerCacheTtlMs as y, AutomationEditError as yi, createAgentInvocationFromLatest as yn, createSlackCanvasWriteTool as yr, acceptsWebMessages as yt, createStopWatchingResourcesTool as z, getWebAuthorization as zn, automationTriggerChangesSchema as zr, TERMINAL_AGENT_INVOCATION_STATUSES as zt };