@sentry/junior 0.313.0 → 0.314.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 (108) hide show
  1. package/dist/{adapter-CYAvJzZS.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-CVsHoVSf.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-Cyhb4TwZ.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-B5y9MsT-.js → agent-runner-qZU5TR8i.js} +797 -118
  5. package/dist/agent-update-cS7Z9mnG.js +26 -0
  6. package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
  7. package/dist/api/schema.d.ts +2 -2
  8. package/dist/api/schema.js +6 -6
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.js +334 -100
  11. package/dist/{app-DA8-hCMj.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -169
  14. package/dist/{background-compaction-queue-iZXadLV3.js → background-compaction-queue-C_uIBUvS.js} +6 -67
  15. package/dist/callback-C8SdXCwr.js +68 -0
  16. package/dist/{catalog-runtime-kkE3hvCX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-mt7K6dPh.js → channel-access-BOL29BG3.js} +6 -6
  18. package/dist/child-message--2G3Ft26.js +19 -0
  19. package/dist/cli/chat.js +18 -21
  20. package/dist/cli/check.js +4 -4
  21. package/dist/cli/main.js +2 -2
  22. package/dist/cli/plugins.js +5 -5
  23. package/dist/cli/snapshot-create.js +5 -5
  24. package/dist/cli/upgrade.d.ts +1 -1
  25. package/dist/cli/upgrade.js +23 -4
  26. package/dist/{config-CWbwKj0j.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-CxyFzdlF.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-BEXLD3Me.js → conversation-feed-DdFQuQDR.js} +1 -1
  29. package/dist/{logging-DNt-qOIO.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-B35eu0uz.js → conversation-turn-DScuDYmN.js} +418 -33
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-DWTOEQrm.js → credential-sync-CtqsGjj1.js} +14 -17
  33. package/dist/{credentialed-Dyv8b-lu.js → credentialed-dWRA3-oJ.js} +910 -426
  34. package/dist/{db-PwSRzWWn.js → db-BTmLKZrp.js} +2235 -38
  35. package/dist/{db-DYGcXYl3.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-DidUcRhI.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-2urLLXNt.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-BXplQAVH.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-DyIyReSV.js → list-C5400AlJ.js} +235 -77
  42. package/dist/{turn-membership-DTR3SaKD.js → mailbox-turn-DL3Lvsm0.js} +4698 -587
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-B0pZJ0bG.js → media-FYM-Bl3H.js} +33 -8
  45. package/dist/{message-Z5YKC-Af.js → message-DuDelZFr.js} +16 -29
  46. package/dist/{model-input-BhPJYdSV.js → model-input-0osF3pBS.js} +3 -3
  47. package/dist/nitro.d.ts +2 -4
  48. package/dist/nitro.js +340 -13
  49. package/dist/{oauth-callback-server-ByvDdcdY.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-D-kK0yoN.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-POH4bZC4.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{resolve-CWtBNSKP.js → resolve-D8CPJcNK.js} +3 -3
  54. package/dist/result-D090hxr5.js +402 -0
  55. package/dist/{runner-CsZ_VRxp.js → runner-BU7fgrm-.js} +7 -8
  56. package/dist/{sandbox-egress-signals-FbCk1FkN.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  57. package/dist/{schema-DojR2uCL.js → schema-7gW9vBpJ.js} +90 -9
  58. package/dist/{schema-DBf18QPS.d.ts → schema-BB6E0wyV.d.ts} +138 -5
  59. package/dist/{service-account-CDYb9hfX.js → service-account-plA-uzIB.js} +6 -5
  60. package/dist/{skills-B0jP4whm.js → skills-CIosT6bS.js} +3 -3
  61. package/dist/{slack-conversation-unfurl-D26t9kBC.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  62. package/dist/{spawn-BjljgExZ.js → spawn-DRjdzh3R.js} +9 -17
  63. package/dist/{start-conversation-DbVujrwO.js → start-conversation-a4NXH4X9.js} +12 -15
  64. package/dist/{store-CjXrp-Up.js → store-BuhF1QDm.js} +2 -4
  65. package/dist/{task-queue-Cwlatjz3.js → task-queue-CrRjFzOh.js} +5 -16
  66. package/dist/{task-runner--Ke8KSMf.js → task-runner-C-pXsgHM.js} +104 -50
  67. package/dist/{thread-context-B8exINEe.js → thread-context-CDX4dSZd.js} +8 -9
  68. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  69. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  70. package/dist/user-customization-B27StpVQ.js +9 -0
  71. package/dist/{validation-Ce0qbMlT.js → validation-bTq88sya.js} +1 -1
  72. package/dist/{vercel-queue-q4z8w5QO.js → vercel-queue-nL0Hq3hr.js} +32 -147
  73. package/dist/{version-DFh4n9nr.js → version-DGUa1dZK.js} +1 -1
  74. package/dist/version.js +1 -1
  75. package/dist/{warmup-D5hzqTcp.js → warmup-CCOuIwAS.js} +639 -137
  76. package/dist/{worker-CDg9Lbpg.js → worker-AkZg7Dg1.js} +5 -6
  77. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  78. package/migrations/0161_agent_config_backfill.sql +34 -0
  79. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  80. package/migrations/0163_pg_trgm.sql +2 -0
  81. package/migrations/0164_search_indexes.sql +4 -0
  82. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  83. package/migrations/0166_memory_prefix_index.sql +1 -0
  84. package/migrations/0167_todo_search_indexes.sql +2 -0
  85. package/migrations/0168_todo_inbox_items.sql +4 -0
  86. package/migrations/0169_drop_code_urls.sql +2 -0
  87. package/migrations/meta/0160_snapshot.json +6515 -0
  88. package/migrations/meta/0161_snapshot.json +6278 -0
  89. package/migrations/meta/0162_snapshot.json +6404 -0
  90. package/migrations/meta/0163_snapshot.json +6404 -0
  91. package/migrations/meta/0164_snapshot.json +6466 -0
  92. package/migrations/meta/0165_snapshot.json +6466 -0
  93. package/migrations/meta/0166_snapshot.json +6494 -0
  94. package/migrations/meta/0167_snapshot.json +6525 -0
  95. package/migrations/meta/0168_snapshot.json +6525 -0
  96. package/migrations/meta/0169_snapshot.json +6513 -0
  97. package/migrations/meta/_journal.json +70 -0
  98. package/package.json +9 -18
  99. package/skills/design-automation-skill/SKILL.md +2 -3
  100. package/dist/actor-BsBdxDXQ.js +0 -208
  101. package/dist/conversation-privacy-BrMiDN61.js +0 -189
  102. package/dist/executor-CgWyWfYz.js +0 -1858
  103. package/dist/fan-out-Cod-yEHG.js +0 -10
  104. package/dist/ingest-B0AggUEC.js +0 -7931
  105. package/dist/request-deadline-BUiRYQYj.js +0 -24
  106. package/dist/service-account-o15pZWcJ.js +0 -931
  107. package/dist/state-BTawTCme.js +0 -161
  108. package/dist/statuses-BKwqCPhj.js +0 -69
@@ -1,18 +1,14 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { _ as credentialUserSubjectId, a as HOST_MANAGED_CREDENTIAL_PLACEHOLDER, g as credentialSubjectSchema, h as credentialLogContext, m as credentialContextSchema, o as resolveAuthTokenPlaceholder, s as resolvePluginCommandEnv, v as CredentialUnavailableError } from "./registry-POH4bZC4.js";
3
- import { E as withSpan, J as normalizeIdentityEmail, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, i as extractGenAiUsageAttributes, m as logInfo, p as logException, x as setSpanStatus, y as setSentryUser } from "./logging-DNt-qOIO.js";
4
- import { C as completeText$1, D as rerankTexts, E as generateImages$1, I as MUTATION_LOCK_TTL_MS, L as acquireActiveLock, P as createCache, Q as THREAD_CONTEXT_TAGS, S as completeObject$1, T as gatewayCostUsd, Y as hasCurrentInstruction, Z as unwrapCurrentInstruction, _t as toOptionalTrimmed, a as getSlackBotToken, at as ProviderError, b as GEN_AI_SERVER_ADDRESS, et as isRuntimeInputText, ft as isProviderRetryError, ht as bufferBody, k as searchWeb$1, mt as resolveGatewayCredential, n as botConfig, r as getChatConfig, st as createProviderError, tt as readParentAgentTask, v as normalizeSlackEmojiName, w as embedTexts$1, x as completeDecision$1, y as GEN_AI_PROVIDER_NAME, z as withLock } from "./config-CWbwKj0j.js";
5
- import { a as getStateValues, i as getStateAdapter, o as setStateValues, r as getDefaultRedisStateAdapterFor } from "./adapter-CYAvJzZS.js";
6
- import { At as automationCreatorUserId, F as turnBehavior, Fn as nextDetailVersion, G as microUsdToUsd, In as touchConversationDetail, It as readActorIdentity, Kt as parseAvatarUrl, O as isPersonInput, On as agentTurnCostUsd, P as sourceLabel, Pn as conversationDetailTouch, Pt as findUserByEmailFromSql, Rt as readIdentityById, U as conversationCostOf, Vt as resolveViewerUser, Wt as hasUserPhoto, Yt as userAvatarUrlsFromIdentities, _t as inboxItemPlugin, a as getConversationStore, an as linkedSlackUser, at as AUTOMATION_INBOX_ITEM_KEY_PREFIX, bt as inboxItemVisibleTo, c as hasAnnotationKey, cn as saveUserTimezone, dn as ToolInputError, dt as inboxItemAssignedTo, fn as isToolInputError, ft as inboxItemForUser, gt as inboxItemOwnedByConversation, hn as canReadConversation, ht as inboxItemNeedsUser, j as personSourcePlatform, k as isPersonSource, kn as agentTurnTotalTokens, l as treeHasAnnotationKey, o as getDb, on as readUserTimezone, ot as PLUGIN_INBOX_ITEM_KEY_PREFIX, pt as inboxItemLinkedTo, r as getConversationEventStore, s as getSqlExecutor, vn as readConversationAccessFromSql, zt as readIdentityByIdFromSql } from "./db-PwSRzWWn.js";
7
- import { Ft as scheduledAutomationSchema, Gt as isValidTimeZone, Jt as inboxItemRequestSchema, Kt as eventAutomationSchema, N as automationVersionSchema, Yt as USER_INPUT_LIMITS, a as DEFAULT_NOTIFICATION_SCHEDULE, an as automationTaskDescription, c as CONTENT_VERSION_HEADER, in as automationTaskColumns, o as isWithinNotificationSchedule, on as automationTaskSchema, qt as eventAutomationTriggerSchema, r as detectImageMediaType, rn as automationSkillNameSchema, s as notificationScheduleSchema } from "./media-B0pZJ0bG.js";
8
- import { d as parseSlackChannelReferenceId, f as parseSlackTeamId, i as isActorUserId, p as parseSlackUserId, s as parseActorUserId, v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
9
- import { f as readJuniorSecret, h as readWebPushPrivateKey, t as getVercelConversationWorkQueue } from "./vercel-queue-q4z8w5QO.js";
10
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
11
- import { $ as MEMORY_SCOPES, C as juniorConversationParticipants, D as juniorConversationEventEmbeddings, E as juniorConversationEventLexemes, H as juniorConversations, J as juniorMemoryEmbeddings, K as juniorUsers, L as juniorCodeChanges, M as juniorConversationEvents, O as juniorConversationEmbeddings, P as juniorConversationAnnotations, Q as MEMORY_KINDS, R as juniorCodeRepositories, U as juniorIdentities, X as juniorMemorySignals, Y as juniorMemoryMemories, Z as MEMORY_EMBEDDING_DIMENSIONS, _ as juniorAutomationRuns, a as juniorWorkspaces, at as guardedCosineDistance, ct as juniorArtifacts, d as juniorInboxSnoozes, et as MEMORY_SOURCE_PLATFORMS, f as juniorInboxItemAssignees, g as juniorAutomations, h as juniorInboxItems, i as juniorWorkspaceRepos, it as embedText, n as isPostgresErrorCode, nt as memoryRuntimeContextSchema, o as juniorPushSubscriptions, ot as parseEmbeddingBatch$1, p as juniorInboxItemConversations, q as juniorDestinations, r as juniorSnapshots, rt as cosineDistance, st as refreshEmbeddings, tt as MEMORY_SUBJECT_TYPES, u as juniorInboxSnoozeTriggers, v as juniorAutomationVersions } from "./executor-CgWyWfYz.js";
2
+ import { A as readEncryptedState, J as credentialLogContext, P as resolvePluginCommandEnv, Q as ServiceAccountUnavailableError, X as credentialUserSubjectId, Y as credentialSubjectSchema, Z as CredentialUnavailableError, j as findLegacyWebActorUserId, k as createEncryptedState, n as HOST_MANAGED_CREDENTIAL_PLACEHOLDER, q as credentialContextSchema, r as resolveAuthTokenPlaceholder } from "./registry-D6kS6xYH.js";
3
+ import { A as setSpanStatus, C as logInfo, E as runBestEffort, F as withSpan, O as setSentryUser, S as logException, _ as getLogContextAttributes, b as logAudit, k as setSpanAttributes, m as extractGenAiUsageSummary, p as extractGenAiUsageAttributes, rt as normalizeIdentityEmail, w as logWarn } from "./conversation-privacy-DtZhI91r.js";
4
+ import { C as completeText$1, D as rerankTexts, E as generateImages$1, I as MUTATION_LOCK_TTL_MS, L as acquireActiveLock, P as createCache, Q as THREAD_CONTEXT_TAGS, S as completeObject$1, T as gatewayCostUsd, Y as hasCurrentInstruction, Z as unwrapCurrentInstruction, _t as bufferBody, a as getSlackBotToken, at as ProviderError, b as GEN_AI_SERVER_ADDRESS, et as isRuntimeInputText, ft as isProviderRetryError, gt as mapBounded, k as searchWeb$1, mt as resolveGatewayCredential, n as botConfig, r as getChatConfig, st as createProviderError, tt as readParentAgentTask, v as normalizeSlackEmojiName, w as embedTexts$1, x as completeDecision$1, y as GEN_AI_PROVIDER_NAME, yt as toOptionalTrimmed, z as withLock } from "./config-BIfHKNXN.js";
5
+ import { a as getStateValues, i as getStateAdapter, o as setStateValues, r as getDefaultRedisStateAdapterFor } from "./adapter-JARQvoLw.js";
6
+ import { $n as juniorWorkspaceRepos, $r as MEMORY_SOURCE_PLATFORMS, $t as readIdentityByIdFromSql, Ar as juniorConversationEvents, B as personSourcePlatform, Br as juniorConversations, Cr as juniorConversationReadPositions, D as parseActorUserId, Dr as juniorConversationEventEmbeddings, En as isToolInputError, Er as juniorConversationEventLexemes, Et as inboxItemLinkedTo, Fr as juniorCodeChanges, Gr as juniorDestinations, Ir as juniorCodeRepositories, Jr as juniorMemorySignals, Jt as findUserByEmailFromSql, Kr as juniorMemoryEmbeddings, L as isPersonInput, Mn as readConversationAccessFromSql, Mr as juniorConversationAnnotations, Or as juniorConversationEmbeddings, Ot as inboxItemNeedsUser, Pt as inboxItemVisibleTo, Q as conversationCostOf, Qn as juniorSnapshots, Qr as MEMORY_SCOPES, Qt as readIdentityById, R as isPersonSource, Sn as saveUserTimezone, T as isActorUserId, Tn as ToolInputError, Tt as inboxItemForUser, U as sourceLabel, Un as agentTurnCostUsd, Vr as juniorIdentities, W as turnBehavior, Wn as agentTurnTotalTokens, Wr as juniorUsers, Wt as automationCreatorUserId, Xn as nextDetailVersion, Xr as MEMORY_EMBEDDING_DIMENSIONS, Xt as readActorIdentity, Yn as conversationDetailTouch, Yr as memoryPrefixDocument, Zn as touchConversationDetail, Zr as MEMORY_KINDS, _t as REPLY_NOTICE_KEY_PREFIX, a as getDb, ai as parseEmbeddingBatch$1, bi as parseSlackMessageTs, bn as readUserTimezone, br as juniorAutomationVersions, c as isPostgresErrorCode, cr as juniorInboxSnoozes, dr as juniorInboxItemAssignees, ei as MEMORY_SUBJECT_TYPES, er as juniorWorkspaces, et as microUsdToUsd, fr as juniorInboxItemConversations, gt as PLUGIN_INBOX_ITEM_KEY_PREFIX, hi as parseSlackUserId, hr as juniorInboxItems, ht as AUTOMATION_INBOX_ITEM_KEY_PREFIX, i as getConversationStore, ii as guardedCosineDistance, in as hasUserPhoto, kt as inboxItemOwnedByConversation, l as hasAnnotationKey, ln as userAvatarUrlsFromIdentities, mi as parseSlackTeamId, n as getConversationEventStore, ni as cosineDistance, o as getSqlExecutor, oi as refreshEmbeddings, on as parseAvatarUrl, pi as parseSlackChannelReferenceId, pr as juniorInboxItemDeliveries, qr as juniorMemoryMemories, ri as embedText, si as juniorArtifacts, sr as juniorInboxSnoozeTriggers, ti as memoryRuntimeContextSchema, tn as resolveViewerUser, tr as juniorPushSubscriptions, u as treeHasAnnotationKey, vr as juniorAutomations, wr as juniorConversationParticipants, wt as inboxItemAssignedTo, yn as linkedSlackUser, yr as juniorAutomationRuns, yt as TODO_INBOX_ITEM_KEY_PREFIX } from "./db-BTmLKZrp.js";
7
+ import { Ft as scheduledAutomationSchema, Gt as isValidTimeZone, Jt as inboxItemRequestSchema, Kt as eventAutomationSchema, N as automationVersionSchema, Yt as USER_INPUT_LIMITS, a as DEFAULT_NOTIFICATION_SCHEDULE, an as AGENT_UPDATE_EVENT_TYPE, c as CONTENT_VERSION_HEADER, cn as automationSkillNameSchema, dn as automationTaskSchema, ln as automationTaskColumns, o as isWithinNotificationSchedule, qt as eventAutomationTriggerSchema, r as detectImageMediaType, s as notificationScheduleSchema, un as automationTaskDescription } from "./media-FYM-Bl3H.js";
8
+ import { f as readJuniorSecret, h as readWebPushPrivateKey, t as getVercelConversationWorkQueue } from "./vercel-queue-nL0Hq3hr.js";
12
9
  import { n as captureMessage, r as continueTrace } from "./sentry-CPbZjomA.js";
13
- import { n as pluginCatalogRuntime } from "./catalog-runtime-kkE3hvCX.js";
10
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BLKtnUL3.js";
14
11
  import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
15
- import { n as readEncryptedState, r as findLegacyWebActorUserId, t as createEncryptedState } from "./state-BTawTCme.js";
16
12
  import * as z from "zod";
17
13
  import pLimit from "p-limit";
18
14
  import { createGatewayProvider } from "@ai-sdk/gateway";
@@ -20,12 +16,12 @@ import { transcribe } from "ai";
20
16
  import path from "node:path";
21
17
  import { AsyncLocalStorage } from "node:async_hooks";
22
18
  import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
23
- import { EgressAuthRequired, EgressPolicyDenied, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, defineConversationEvent, defineJuniorPlugin, definePluginTool, definePromptContext, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagText, escapeTagTextAndQuotes, eventDataSchema, eventInputSchema, eventMatchFieldsSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, getSourceKey, isPluginModelCostEventName, isSlackDestination, missingToolAnnotationKeys, normalizeEventIdentifier, normalizeEventMatch, objectAnnotationSchema, objectIconPath, objectLinkFilterSchema, openingTag, pluginApiRouteRequestContextSchema, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolOutputSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, stripTags, taskOutcomeSchema, withToolContext } from "@sentry/junior-plugin-api";
24
- import { and, asc, count, desc, eq, exists, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, ne, not, notExists, notInArray, notLike, or, sql } from "drizzle-orm";
19
+ import { EgressAuthRequired, EgressPolicyDenied, MAX_CONVERSATION_CHANGES, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, defineConversationEvent, defineJuniorPlugin, definePluginTool, definePromptContext, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagText, escapeTagTextAndQuotes, eventDataSchema, eventInputSchema, eventMatchFieldsSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, getSourceKey, isPluginModelCostEventName, isSlackDestination, markdownPlainText, missingToolAnnotationKeys, normalizeEventIdentifier, normalizeEventMatch, objectAnnotationSchema, objectIconPath, objectLinkFilterSchema, openingTag, pluginApiRouteRequestContextSchema, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolOutputSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, stripTags, taskOutcomeSchema, withToolContext } from "@sentry/junior-plugin-api";
20
+ import { and, asc, count, desc, eq, exists, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, max, ne, not, notExists, notInArray, notLike, or, sql } from "drizzle-orm";
25
21
  import { PgDatabase, QueryBuilder, alias } from "drizzle-orm/pg-core";
26
22
  import fs from "node:fs/promises";
27
23
  import { WebClient } from "@slack/web-api";
28
- import { parseMarkdown, walkAst } from "chat";
24
+ import { parseMarkdown as parseMarkdown$1, walkAst } from "chat";
29
25
  import http from "node:http";
30
26
  import os from "node:os";
31
27
  import dns from "node:dns/promises";
@@ -1847,29 +1843,25 @@ async function deliverWatch(input) {
1847
1843
  }
1848
1844
  // src/chat/conversations/watch-events.ts
1849
1845
  const CONVERSATION_RESOURCE_TYPE = "conversation";
1850
- const CONVERSATION_COMPLETED_EVENT = "conversation.completed";
1851
- const CONVERSATION_FAILED_EVENT = "conversation.failed";
1852
- const CONVERSATION_WAITING_EVENT = "conversation.waiting";
1853
- const CONVERSATION_STOPPED_EVENT = "conversation.stopped";
1854
- const CONVERSATION_EVENTS = [
1855
- CONVERSATION_COMPLETED_EVENT,
1856
- CONVERSATION_FAILED_EVENT,
1857
- CONVERSATION_WAITING_EVENT,
1858
- CONVERSATION_STOPPED_EVENT
1859
- ];
1860
- /** Core catalog entry for the status Events of a Conversation. */
1846
+ const CONVERSATION_EVENTS = [AGENT_UPDATE_EVENT_TYPE];
1847
+ const LEGACY_EVENT_TYPES = {
1848
+ stopped: "conversation.stopped",
1849
+ turn: "conversation.completed",
1850
+ turn_failed: "conversation.failed",
1851
+ waiting: "conversation.waiting"
1852
+ };
1853
+ /** Core catalog entry for the agent updates of a Conversation. */
1861
1854
  function conversationEvents() {
1862
- const guidance = "Read the Conversation with readConversationEvent before you report it, and report only what the Watch intent asks for.";
1863
1855
  return {
1864
1856
  resourceTypes: [{
1865
1857
  type: CONVERSATION_RESOURCE_TYPE,
1866
1858
  supportedEvents: CONVERSATION_EVENTS,
1867
1859
  suggestedEvents: CONVERSATION_EVENTS
1868
1860
  }],
1869
- events: Object.fromEntries(CONVERSATION_EVENTS.map((eventType) => [eventType, {
1861
+ events: { [AGENT_UPDATE_EVENT_TYPE]: {
1870
1862
  reach: "resource",
1871
- guidance
1872
- }])),
1863
+ guidance: "Report only what the Watch intent asks for. Read the Conversation with readConversationEvent only when the update does not say enough."
1864
+ } },
1873
1865
  limits: { [CONVERSATION_RESOURCE_TYPE]: { automation: false } }
1874
1866
  };
1875
1867
  }
@@ -1884,84 +1876,58 @@ function conversationWatch(input) {
1884
1876
  type: CONVERSATION_RESOURCE_TYPE
1885
1877
  };
1886
1878
  }
1887
- function statusEvent(conversationId, status, occurredAtMs) {
1888
- const base = {
1879
+ function updateEventKey(conversationId, key) {
1880
+ const prefix = `${CORE_EVENT_NAMESPACE}:${CONVERSATION_RESOURCE_TYPE}:${conversationId}`;
1881
+ switch (key.type) {
1882
+ case "turn":
1883
+ case "turn_failed": return `${prefix}:turn:${key.turnId}`;
1884
+ case "waiting": return `${prefix}:inbox_item:${key.inboxItemId}`;
1885
+ case "stopped": return `${prefix}:stopped:${key.stoppedAtMs}`;
1886
+ }
1887
+ }
1888
+ async function findUpdateWatches(conversationId, key, nowMs, state) {
1889
+ const matched = /* @__PURE__ */ new Map();
1890
+ for (const eventType of [AGENT_UPDATE_EVENT_TYPE, LEGACY_EVENT_TYPES[key.type]]) for (const watch of await findMatchingWatches({
1891
+ eventType,
1889
1892
  identifier: conversationId,
1890
1893
  namespace: CORE_EVENT_NAMESPACE,
1891
- occurredAtMs,
1892
- terminal: false
1893
- };
1894
- const key = `${CORE_EVENT_NAMESPACE}:${CONVERSATION_RESOURCE_TYPE}:${conversationId}`;
1895
- switch (status.type) {
1896
- case "turn_completed": return {
1897
- ...base,
1898
- eventKey: `${key}:turn:${status.turnId}`,
1899
- eventType: CONVERSATION_COMPLETED_EVENT,
1900
- trustedSummary: `The Conversation ended a Turn: ${status.outcome}.`,
1901
- data: {
1902
- conversationId,
1903
- outcome: status.outcome
1904
- }
1905
- };
1906
- case "turn_failed": return {
1907
- ...base,
1908
- eventKey: `${key}:turn:${status.turnId}`,
1909
- eventType: CONVERSATION_FAILED_EVENT,
1910
- trustedSummary: `A Turn of the Conversation failed: ${status.failureCode}.`,
1911
- data: {
1912
- conversationId,
1913
- failureCode: status.failureCode
1914
- }
1915
- };
1916
- case "waiting": return {
1917
- ...base,
1918
- eventKey: `${key}:inbox_item:${status.inboxItemId}`,
1919
- eventType: CONVERSATION_WAITING_EVENT,
1920
- trustedSummary: "The Conversation waits on a person.",
1921
- data: {
1922
- conversationId,
1923
- inboxItemId: status.inboxItemId
1924
- }
1925
- };
1926
- case "stopped": return {
1927
- ...base,
1928
- eventKey: `${key}:stopped:${status.stoppedAtMs}`,
1929
- eventType: CONVERSATION_STOPPED_EVENT,
1930
- trustedSummary: "The Conversation stopped.",
1931
- data: { conversationId }
1932
- };
1933
- }
1894
+ nowMs,
1895
+ state
1896
+ })) if (!matched.has(watch.id)) matched.set(watch.id, {
1897
+ eventType,
1898
+ watch
1899
+ });
1900
+ return [...matched.values()];
1934
1901
  }
1935
1902
  /**
1936
- * Deliver one status Event of a Conversation to the Watches that may still
1937
- * read it. `skip` runs only when a Watch matches, so a Conversation that no
1938
- * one watches pays one Watch index read. The work that the Event reports
1939
- * already happened, so a failed delivery is logged and never fails that
1940
- * work. A retry delivers the same Event key once.
1903
+ * Deliver one agent update of a Conversation to the Watches that may still
1904
+ * read it. `skip` and `update` run only when a Watch matches, so a
1905
+ * Conversation that no one watches pays only the Watch index reads. An
1906
+ * undefined update reports nothing. The work that the update reports already
1907
+ * happened, so a failed delivery is logged and never fails that work. A
1908
+ * retry delivers the same Event key once.
1941
1909
  */
1942
- async function publishConversationStatus(conversationId, status, options) {
1910
+ async function publishAgentUpdate(conversationId, key, options) {
1943
1911
  const nowMs = options.nowMs ?? Date.now();
1944
- const event = statusEvent(conversationId, status, nowMs);
1945
1912
  try {
1946
- if ((await findMatchingWatches({
1947
- data: event.data,
1948
- eventType: event.eventType,
1949
- identifier: conversationId,
1950
- namespace: event.namespace,
1951
- nowMs,
1952
- state: options.state
1953
- })).length === 0 || await options.skip?.()) return;
1954
- const { ingestEvent } = await import("./ingest-B0AggUEC.js").then((n) => n.n);
1955
- await ingestEvent(event, {
1956
- admit: async (watch) => await canReadConversation(getDb(), watch.conversationId, conversationId),
1913
+ const watches = await findUpdateWatches(conversationId, key, nowMs, options.state);
1914
+ if (watches.length === 0 || await options.skip?.()) return;
1915
+ const update = await options.update();
1916
+ if (!update) return;
1917
+ const { deliverAgentUpdate } = await import("./agent-update-delivery-CZ5M8RDa.js");
1918
+ await deliverAgentUpdate({
1919
+ conversationId,
1920
+ eventKey: updateEventKey(conversationId, key),
1957
1921
  nowMs,
1958
1922
  queue: options.queue,
1959
- state: options.state
1923
+ state: options.state,
1924
+ update,
1925
+ watches
1960
1926
  });
1961
1927
  } catch (error) {
1962
1928
  logException(error, "conversation.watch.publish.failed", {
1963
1929
  "app.conversation.id": conversationId,
1964
- "app.event.event_type": event.eventType
1930
+ "app.event.event_type": AGENT_UPDATE_EVENT_TYPE
1965
1931
  });
1966
1932
  }
1967
1933
  }
@@ -2116,7 +2082,7 @@ function slackChannelMessageTrigger(trigger, channelId) {
2116
2082
  function requireSlackChannelMessageScope(automation) {
2117
2083
  if (automation.trigger.namespace !== "slack") return automation;
2118
2084
  const channelId = automation.destination.channelId;
2119
- if (!CHANNEL_ID_PATTERN.test(channelId)) throw new ToolInputError("A Slack channel-message automation works only in a channel, not in a DM.");
2085
+ if (!CHANNEL_ID_PATTERN.test(channelId)) throw new ToolInputError("A Slack channel-message automation works only in a channel, not in a DM. Create it from the Slack channel to watch.");
2120
2086
  const { identifier, match } = automation.trigger;
2121
2087
  if ((identifier === void 0 ? match?.["channelId"] : identifier === SLACK_CURRENT_CHANNEL_IDENTIFIER ? channelId : identifier) !== channelId) throw new ToolInputError("A Slack channel-message automation can watch only the channel where it posts. Leave out the channel_id filter, or create the automation in the channel to watch.");
2122
2088
  return {
@@ -2187,7 +2153,7 @@ function slackChannelMessageReplyThreadTs(event) {
2187
2153
  /**
2188
2154
  * Enabled event registrations for search, guidance, and tool schemas.
2189
2155
  *
2190
- * Includes core Workspace snapshot and Conversation status events under the
2156
+ * Includes core Workspace snapshot and agent update events under the
2191
2157
  * `junior` namespace, Slack channel-message events under the `slack`
2192
2158
  * namespace, plus every enabled plugin registration. Plugins may not use the `junior` or `slack` namespaces.
2193
2159
  */
@@ -2244,6 +2210,7 @@ const SNOOZE_RETENTION_LIMIT = 1e3;
2244
2210
  /** The Event of a snooze timer. Its identifier is the timer id. */
2245
2211
  const SNOOZE_TIMER_EVENT_TYPE = "timer.fired";
2246
2212
  const linkRoot = alias(juniorConversations, "snooze_link_root");
2213
+ const ownerRoot = alias(juniorConversations, "snooze_owner_root");
2247
2214
  const itemLink = alias(juniorInboxItemConversations, "snooze_item_link");
2248
2215
  const queries = new QueryBuilder();
2249
2216
  /** Subquery: the root Conversation of each Conversation that the item links. */
@@ -2252,10 +2219,11 @@ function rowRootsOfItem(itemId) {
2252
2219
  }
2253
2220
  /**
2254
2221
  * SQL: the Inbox item is in the Inbox row of this root Conversation: the
2255
- * item links that Conversation or one of its threads.
2222
+ * item links that Conversation or one of its threads, or one of them owns
2223
+ * it. A To-do's item links nothing, so its owner puts it in the row.
2256
2224
  */
2257
2225
  function inboxItemInRow(rootConversationId) {
2258
- return inArray(sql`${rootConversationId}`, rowRootsOfItem(sql`${juniorInboxItems.id}`));
2226
+ return or(inArray(sql`${rootConversationId}`, rowRootsOfItem(sql`${juniorInboxItems.id}`)), and(eq(juniorInboxItems.ownerKind, "conversation"), inArray(juniorInboxItems.ownerId, queries.select({ id: ownerRoot.conversationId }).from(ownerRoot).where(or(eq(ownerRoot.conversationId, rootConversationId), eq(ownerRoot.rootConversationId, rootConversationId))))));
2259
2227
  }
2260
2228
  /** SQL: this User snoozed the Inbox item, and it has not woken. */
2261
2229
  function inboxItemSnoozedBy(userId) {
@@ -2340,22 +2308,27 @@ async function listFiringInboxSnoozeTriggers(db, input) {
2340
2308
  return db.select({
2341
2309
  eventType: juniorInboxSnoozeTriggers.eventType,
2342
2310
  identifier: juniorInboxSnoozeTriggers.identifier,
2311
+ inboxItemId: juniorInboxSnoozes.inboxItemId,
2343
2312
  match: juniorInboxSnoozeTriggers.match,
2344
2313
  outcome: juniorInboxSnoozeTriggers.outcome,
2345
- snoozeId: juniorInboxSnoozeTriggers.snoozeId
2314
+ snoozeId: juniorInboxSnoozeTriggers.snoozeId,
2315
+ userId: juniorInboxSnoozes.userId
2346
2316
  }).from(juniorInboxSnoozeTriggers).innerJoin(juniorInboxSnoozes, eq(juniorInboxSnoozes.id, juniorInboxSnoozeTriggers.snoozeId)).where(and(eq(juniorInboxSnoozeTriggers.namespace, input.namespace), inArray(juniorInboxSnoozeTriggers.identifier, [...input.identifiers]), inArray(juniorInboxSnoozeTriggers.eventType, [...input.eventTypes]), eq(juniorInboxSnoozes.state, "snoozed")));
2347
2317
  }
2348
2318
  /**
2349
2319
  * End snoozes that a trigger fired. Only a `snoozed` row changes, so the
2350
- * first trigger to fire wins. A woken snooze records why it woke. Return
2351
- * the items of the snoozes that changed.
2320
+ * first trigger to fire wins, and only its caller gets the snooze back. A
2321
+ * woken snooze records why it woke. Return the snoozes that changed.
2352
2322
  */
2353
2323
  async function settleInboxSnoozes(db, input) {
2354
2324
  if (input.snoozeIds.length === 0) return [];
2355
- return (await db.update(juniorInboxSnoozes).set(input.state === "woken" ? {
2325
+ return await db.update(juniorInboxSnoozes).set(input.state === "woken" ? {
2356
2326
  state: input.state,
2357
2327
  wakeReason: input.reason
2358
- } : { state: input.state }).where(and(inArray(juniorInboxSnoozes.id, [...input.snoozeIds]), eq(juniorInboxSnoozes.state, "snoozed"))).returning({ inboxItemId: juniorInboxSnoozes.inboxItemId })).map((row) => row.inboxItemId);
2328
+ } : { state: input.state }).where(and(inArray(juniorInboxSnoozes.id, [...input.snoozeIds]), eq(juniorInboxSnoozes.state, "snoozed"))).returning({
2329
+ inboxItemId: juniorInboxSnoozes.inboxItemId,
2330
+ userId: juniorInboxSnoozes.userId
2331
+ });
2359
2332
  }
2360
2333
  /**
2361
2334
  * Forget why this User's snoozes of these items woke, once they open or
@@ -2398,6 +2371,107 @@ async function deleteExpiredInboxSnoozes(db, nowMs) {
2398
2371
  const expired = db.select({ id: juniorInboxSnoozes.id }).from(juniorInboxSnoozes).where(and(ne(juniorInboxSnoozes.state, "snoozed"), lt(juniorInboxSnoozes.createdAt, /* @__PURE__ */ new Date(nowMs - SNOOZE_RETENTION_MS)))).limit(SNOOZE_RETENTION_LIMIT);
2399
2372
  return (await db.delete(juniorInboxSnoozes).where(inArray(juniorInboxSnoozes.id, expired)).returning({ id: juniorInboxSnoozes.id })).length;
2400
2373
  }
2374
+ // src/chat/inbox-items/deliveries.ts
2375
+ /** Keep at most this many closed items in one push. */
2376
+ const MAX_CLEARED_ITEMS = 20;
2377
+ /** Return the Users that already have the `created` web push of an item. */
2378
+ async function listInboxItemPushUserIds(db, itemId) {
2379
+ const rows = await db.select({ userId: juniorInboxItemDeliveries.userId }).from(juniorInboxItemDeliveries).where(and(eq(juniorInboxItemDeliveries.itemId, itemId), eq(juniorInboxItemDeliveries.channel, "web_push"), eq(juniorInboxItemDeliveries.event, "created")));
2380
+ return new Set(rows.map((row) => row.userId));
2381
+ }
2382
+ /**
2383
+ * Record the `created` web push of one item to one User. Return false when
2384
+ * a row already exists, so only the first caller sends.
2385
+ */
2386
+ async function claimInboxItemPush(db, input) {
2387
+ const now = new Date(input.nowMs);
2388
+ return (await db.insert(juniorInboxItemDeliveries).values({
2389
+ channel: "web_push",
2390
+ createdAt: now,
2391
+ event: "created",
2392
+ itemId: input.itemId,
2393
+ skipReason: input.skipReason ?? null,
2394
+ status: input.skipReason ? "skipped" : "sent",
2395
+ updatedAt: now,
2396
+ userId: input.userId
2397
+ }).onConflictDoNothing().returning({ itemId: juniorInboxItemDeliveries.itemId })).length > 0;
2398
+ }
2399
+ /**
2400
+ * Record that a Slack card shows an item to these Users, once per User.
2401
+ * Return when each of them first got a card, so their wait for a push
2402
+ * starts then, also after a later show of the item.
2403
+ */
2404
+ async function recordInboxItemSlackCard(db, input) {
2405
+ if (input.userIds.length === 0) return /* @__PURE__ */ new Map();
2406
+ const now = new Date(input.nowMs);
2407
+ await db.insert(juniorInboxItemDeliveries).values(input.userIds.map((userId) => ({
2408
+ channel: "slack",
2409
+ createdAt: now,
2410
+ event: "created",
2411
+ itemId: input.itemId,
2412
+ status: "sent",
2413
+ updatedAt: now,
2414
+ userId
2415
+ }))).onConflictDoNothing();
2416
+ const rows = await db.select({
2417
+ createdAt: juniorInboxItemDeliveries.createdAt,
2418
+ userId: juniorInboxItemDeliveries.userId
2419
+ }).from(juniorInboxItemDeliveries).where(and(eq(juniorInboxItemDeliveries.itemId, input.itemId), eq(juniorInboxItemDeliveries.channel, "slack"), eq(juniorInboxItemDeliveries.event, "created"), inArray(juniorInboxItemDeliveries.userId, [...input.userIds])));
2420
+ return new Map(rows.map((row) => [row.userId, row.createdAt.getTime()]));
2421
+ }
2422
+ /**
2423
+ * Record a web push that can repeat for one item and User: a reply to its
2424
+ * starter, or the wake of their snooze. Each one pushes again, so the one
2425
+ * record of the event holds the latest push. A skipped push keeps an
2426
+ * earlier `sent` record: that notification still shows, and the close of
2427
+ * the item must clear it.
2428
+ */
2429
+ async function recordRepeatInboxItemPush(db, input) {
2430
+ const now = new Date(input.nowMs);
2431
+ const result = {
2432
+ skipReason: input.skipReason ?? null,
2433
+ status: input.skipReason ? "skipped" : "sent",
2434
+ updatedAt: now
2435
+ };
2436
+ const insert = db.insert(juniorInboxItemDeliveries).values({
2437
+ ...result,
2438
+ channel: "web_push",
2439
+ createdAt: now,
2440
+ event: input.event,
2441
+ itemId: input.itemId,
2442
+ userId: input.userId
2443
+ });
2444
+ if (input.skipReason) {
2445
+ await insert.onConflictDoNothing();
2446
+ return;
2447
+ }
2448
+ await insert.onConflictDoUpdate({
2449
+ target: [
2450
+ juniorInboxItemDeliveries.itemId,
2451
+ juniorInboxItemDeliveries.userId,
2452
+ juniorInboxItemDeliveries.channel,
2453
+ juniorInboxItemDeliveries.event
2454
+ ],
2455
+ set: result
2456
+ });
2457
+ }
2458
+ /** Mark the sent deliveries of closed items as cleared. */
2459
+ async function clearInboxItemDeliveries(db, itemIds, nowMs) {
2460
+ if (itemIds.length === 0) return;
2461
+ await db.update(juniorInboxItemDeliveries).set({
2462
+ status: "cleared",
2463
+ updatedAt: new Date(nowMs)
2464
+ }).where(and(inArray(juniorInboxItemDeliveries.itemId, [...itemIds]), eq(juniorInboxItemDeliveries.status, "sent")));
2465
+ }
2466
+ /**
2467
+ * Return the items whose web push to this User cleared after `sinceMs`,
2468
+ * newest first. A device can still show them, so the next push closes them.
2469
+ * An item can have more than one push, such as its creation and a wake, but
2470
+ * shows as one notification, so it is listed once.
2471
+ */
2472
+ async function listClearedInboxItemPushes(db, userId, sinceMs) {
2473
+ return (await db.select({ itemId: juniorInboxItemDeliveries.itemId }).from(juniorInboxItemDeliveries).where(and(eq(juniorInboxItemDeliveries.userId, userId), eq(juniorInboxItemDeliveries.channel, "web_push"), eq(juniorInboxItemDeliveries.status, "cleared"), gt(juniorInboxItemDeliveries.updatedAt, new Date(sinceMs)))).groupBy(juniorInboxItemDeliveries.itemId).orderBy(desc(max(juniorInboxItemDeliveries.updatedAt))).limit(MAX_CLEARED_ITEMS)).map((row) => row.itemId);
2474
+ }
2401
2475
  // src/chat/inbox-items/store.ts
2402
2476
  /**
2403
2477
  * Close reason of an action item that a person answered with a reply in
@@ -2524,14 +2598,19 @@ async function replaceLinks(db, itemId, content) {
2524
2598
  async function getInboxItem(db, id) {
2525
2599
  return (await hydrate(db, await db.select().from(juniorInboxItems).where(eq(juniorInboxItems.id, id))))[0];
2526
2600
  }
2601
+ /** Return whether one Inbox item is open. */
2602
+ async function isInboxItemOpen(db, id) {
2603
+ return (await db.select({ id: juniorInboxItems.id }).from(juniorInboxItems).where(and(eq(juniorInboxItems.id, id), eq(juniorInboxItems.status, "open"))).limit(1)).length > 0;
2604
+ }
2527
2605
  /**
2528
2606
  * Read the action items that the agent added in one Conversation and that a
2529
2607
  * reply can answer: the open items, and the items that a reply closed. A
2530
2608
  * plugin's items are left out: the plugin closes them when its provider
2531
- * state changes, such as when a pull request merges.
2609
+ * state changes, such as when a pull request merges. A To-do's items are
2610
+ * left out too: they close when the To-do does.
2532
2611
  */
2533
2612
  async function listReplyActionItems(db, conversationId) {
2534
- return await hydrate(db, await db.select().from(juniorInboxItems).where(and(inboxItemOwnedByConversation(conversationId), eq(juniorInboxItems.kind, "action"), notLike(juniorInboxItems.dedupeKey, `${PLUGIN_INBOX_ITEM_KEY_PREFIX}%`), or(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.closeReason, INBOX_ITEM_REPLIED_REASON)))));
2613
+ return await hydrate(db, await db.select().from(juniorInboxItems).where(and(inboxItemOwnedByConversation(conversationId), eq(juniorInboxItems.kind, "action"), notLike(juniorInboxItems.dedupeKey, `${PLUGIN_INBOX_ITEM_KEY_PREFIX}%`), notLike(juniorInboxItems.dedupeKey, `${TODO_INBOX_ITEM_KEY_PREFIX}%`), or(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.closeReason, INBOX_ITEM_REPLIED_REASON)))));
2535
2614
  }
2536
2615
  /**
2537
2616
  * Read the open Inbox item with one dedupe key in one provider tenant, if
@@ -2610,8 +2689,10 @@ async function closeInboxItem(db, input) {
2610
2689
  status: input.status,
2611
2690
  updatedAt: now
2612
2691
  }).where(and(eq(juniorInboxItems.id, input.id), eq(juniorInboxItems.status, "open"))).returning(ownerColumns);
2692
+ if (updated.length === 0) return false;
2693
+ await clearInboxItemDeliveries(db, [input.id], input.nowMs);
2613
2694
  await touchConversationDetail(db, ownerConversationIds(updated));
2614
- return updated.length > 0;
2695
+ return true;
2615
2696
  }
2616
2697
  /**
2617
2698
  * Dismiss open Inbox items by id, or the ones that an Automation or a set
@@ -2629,7 +2710,11 @@ async function dismissOpenInboxItems(db, input) {
2629
2710
  closedAt: now,
2630
2711
  status: "dismissed",
2631
2712
  updatedAt: now
2632
- }).where(and(eq(juniorInboxItems.status, "open"), "ids" in input ? inArray(juniorInboxItems.id, [...input.ids]) : "automationId" in input ? eq(juniorInboxItems.automationId, input.automationId) : and(eq(juniorInboxItems.ownerKind, "conversation"), inArray(juniorInboxItems.ownerId, [...input.ownerConversationIds]), isNull(juniorInboxItems.automationId)))).returning(ownerColumns);
2713
+ }).where(and(eq(juniorInboxItems.status, "open"), "ids" in input ? inArray(juniorInboxItems.id, [...input.ids]) : "automationId" in input ? eq(juniorInboxItems.automationId, input.automationId) : and(eq(juniorInboxItems.ownerKind, "conversation"), inArray(juniorInboxItems.ownerId, [...input.ownerConversationIds]), isNull(juniorInboxItems.automationId)))).returning({
2714
+ ...ownerColumns,
2715
+ id: juniorInboxItems.id
2716
+ });
2717
+ await clearInboxItemDeliveries(db, dismissed.map((item) => item.id), input.nowMs);
2633
2718
  await touchConversationDetail(db, ownerConversationIds(dismissed));
2634
2719
  }
2635
2720
  /**
@@ -2648,6 +2733,12 @@ async function takeInboxItem(db, input) {
2648
2733
  itemId: input.id,
2649
2734
  userId: input.userId
2650
2735
  });
2736
+ await claimInboxItemPush(tx, {
2737
+ itemId: input.id,
2738
+ nowMs: input.nowMs,
2739
+ skipReason: "taken",
2740
+ userId: input.userId
2741
+ });
2651
2742
  await touchConversationDetail(tx, ownerConversationIds(updated));
2652
2743
  return true;
2653
2744
  });
@@ -2686,8 +2777,8 @@ function inboxItemNeedsUserNow(userId) {
2686
2777
  }
2687
2778
  /**
2688
2779
  * Count the open Inbox items that need a User (`inboxItemNeedsUser`), one
2689
- * row per subject URL, with the ones that ask with a form as `decisions`
2690
- * and the Automation alerts as `automations`.
2780
+ * row per subject URL, with the ones that ask with a form as `decisions`,
2781
+ * the Automation alerts as `automations`, and the To-dos as `todos`.
2691
2782
  * The nav count and the Inbox bundle counts all read this one query. A
2692
2783
  * snoozed item does not count until it wakes.
2693
2784
  */
@@ -2696,6 +2787,7 @@ async function countInboxItemsNeedingUserBySubject(db, userId) {
2696
2787
  automations: sql`count(*) filter (where ${eq(juniorInboxItems.ownerKind, "automation")})`.mapWith(Number),
2697
2788
  decisions: count(juniorInboxItems.request),
2698
2789
  subjectUrl: juniorInboxItems.subjectUrl,
2790
+ todos: sql`count(*) filter (where ${like(juniorInboxItems.dedupeKey, `${TODO_INBOX_ITEM_KEY_PREFIX}%`)})`.mapWith(Number),
2699
2791
  total: count()
2700
2792
  }).from(juniorInboxItems).where(inboxItemNeedsUserNow(userId)).groupBy(juniorInboxItems.subjectUrl);
2701
2793
  }
@@ -2733,46 +2825,6 @@ async function searchInboxItems(db, reader, filters) {
2733
2825
  ownerRootConversationId: rows[index].ownerRootConversationId
2734
2826
  }));
2735
2827
  }
2736
- const waitingRootId = sql`coalesce(${juniorConversations.rootConversationId}, ${juniorInboxItemConversations.conversationId})`;
2737
- /**
2738
- * Return a query for the ids of the root Conversations that wait on a User,
2739
- * as `listWaitingConversations` lists them, to filter another query by.
2740
- */
2741
- function waitingConversationIdsQuery(db, userId) {
2742
- return db.select({ conversationId: waitingRootId }).from(juniorInboxItemConversations).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorInboxItemConversations.conversationId)).where(inboxItemNeedsUserNow(userId));
2743
- }
2744
- /**
2745
- * List the root Conversations that wait on a User: each root or one of its
2746
- * child conversations is linked to an open item that needs the User now
2747
- * (`inboxItemNeedsUserNow`), so a snoozed item leaves it out.
2748
- */
2749
- async function listWaitingConversations(db, userId) {
2750
- const rows = await db.selectDistinct({
2751
- conversationId: waitingRootId,
2752
- itemId: juniorInboxItems.id,
2753
- dedupeKey: juniorInboxItems.dedupeKey,
2754
- title: juniorInboxItems.title,
2755
- createdAt: juniorInboxItems.createdAt
2756
- }).from(juniorInboxItemConversations).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemConversations.itemId)).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorInboxItemConversations.conversationId)).where(inboxItemNeedsUserNow(userId)).orderBy(desc(juniorInboxItems.createdAt), desc(juniorInboxItems.id));
2757
- const waiting = /* @__PURE__ */ new Map();
2758
- for (const row of rows) {
2759
- const plugin = inboxItemPlugin(row.dedupeKey);
2760
- const item = {
2761
- title: row.title,
2762
- ...plugin ? { plugin } : void 0
2763
- };
2764
- const current = waiting.get(row.conversationId);
2765
- if (current) {
2766
- current.items.push(item);
2767
- current.waitingSince = row.createdAt.toISOString();
2768
- } else waiting.set(row.conversationId, {
2769
- conversationId: row.conversationId,
2770
- items: [item],
2771
- waitingSince: row.createdAt.toISOString()
2772
- });
2773
- }
2774
- return [...waiting.values()].sort((left, right) => left.conversationId.localeCompare(right.conversationId));
2775
- }
2776
2828
  const SOURCE_TEXT_MAX_LENGTH = {
2777
2829
  conversation: 500,
2778
2830
  run: 2e3,
@@ -4362,12 +4414,11 @@ function bulletListFollowUpParagraphs(text) {
4362
4414
  }
4363
4415
  /** Insert blank lines between content blocks so Slack renders them with visual separation. */
4364
4416
  function ensureBlockSpacing(text) {
4365
- const codeBlockPattern = /^```/;
4366
4417
  const lines = text.split("\n");
4367
4418
  const result = [];
4368
4419
  let inCodeBlock = false;
4369
4420
  for (const line of lines) {
4370
- if (codeBlockPattern.test(line.trimStart())) {
4421
+ if (line.trimStart().startsWith("```")) {
4371
4422
  if (!inCodeBlock) {
4372
4423
  const prev = result.length > 0 ? result[result.length - 1] : void 0;
4373
4424
  if (prev !== void 0 && prev.trim() !== "") result.push("");
@@ -5336,7 +5387,7 @@ function mapStrings(value, replace) {
5336
5387
  /** Return the Slack tokens in `text` outside Markdown code. */
5337
5388
  function slackTokens(text) {
5338
5389
  const code = [];
5339
- walkAst(parseMarkdown(text), (node) => {
5390
+ walkAst(parseMarkdown$1(text), (node) => {
5340
5391
  const { start, end } = node.position ?? {};
5341
5392
  if ((node.type === "code" || node.type === "inlineCode") && start?.offset !== void 0 && end?.offset !== void 0) code.push([start.offset, end.offset]);
5342
5393
  return node;
@@ -5402,8 +5453,8 @@ function createPluginLogger(plugin) {
5402
5453
  ...metadata
5403
5454
  });
5404
5455
  },
5405
- error(message, metadata) {
5406
- logException(new Error(message), "plugin.log.error", {
5456
+ error(message, metadata, cause) {
5457
+ logException(new Error(message, { cause }), "plugin.log.error", {
5407
5458
  "app.plugin.name": plugin,
5408
5459
  ...metadata
5409
5460
  });
@@ -6284,30 +6335,42 @@ function annotationFromRow(row) {
6284
6335
  updatedAt: row.updatedAt.toISOString()
6285
6336
  };
6286
6337
  }
6338
+ /**
6339
+ * Add or replace one annotation of a plugin, and mark the Conversation detail
6340
+ * changed in the same statement. Pass a transaction to save it with other
6341
+ * changes.
6342
+ */
6343
+ async function upsertPluginAnnotation(db, args) {
6344
+ const annotation = conversationAnnotationInputSchema.parse(args.annotation);
6345
+ const now = /* @__PURE__ */ new Date();
6346
+ await db.with(conversationDetailTouch(db, [args.conversationId])).insert(juniorConversationAnnotations).values({
6347
+ annotation,
6348
+ conversationId: args.conversationId,
6349
+ createdAt: now,
6350
+ key: annotation.key,
6351
+ kind: annotation.kind,
6352
+ plugin: args.plugin,
6353
+ updatedAt: now
6354
+ }).onConflictDoUpdate({
6355
+ target: [
6356
+ juniorConversationAnnotations.conversationId,
6357
+ juniorConversationAnnotations.plugin,
6358
+ juniorConversationAnnotations.kind,
6359
+ juniorConversationAnnotations.key
6360
+ ],
6361
+ set: {
6362
+ annotation,
6363
+ updatedAt: now
6364
+ }
6365
+ });
6366
+ }
6287
6367
  function createPluginAnnotations(args) {
6288
6368
  return {
6289
- async upsert(input) {
6290
- const annotation = conversationAnnotationInputSchema.parse(input);
6291
- const now = /* @__PURE__ */ new Date();
6292
- await args.db.with(conversationDetailTouch(args.db, [args.conversationId])).insert(juniorConversationAnnotations).values({
6369
+ async upsert(annotation) {
6370
+ await upsertPluginAnnotation(args.db, {
6293
6371
  annotation,
6294
6372
  conversationId: args.conversationId,
6295
- createdAt: now,
6296
- key: annotation.key,
6297
- kind: annotation.kind,
6298
- plugin: args.plugin,
6299
- updatedAt: now
6300
- }).onConflictDoUpdate({
6301
- target: [
6302
- juniorConversationAnnotations.conversationId,
6303
- juniorConversationAnnotations.plugin,
6304
- juniorConversationAnnotations.kind,
6305
- juniorConversationAnnotations.key
6306
- ],
6307
- set: {
6308
- annotation,
6309
- updatedAt: now
6310
- }
6373
+ plugin: args.plugin
6311
6374
  });
6312
6375
  },
6313
6376
  async remove(kind, key) {
@@ -6360,6 +6423,168 @@ async function listConversationAnnotationsById(db, conversationIds) {
6360
6423
  }
6361
6424
  return byConversation;
6362
6425
  }
6426
+ // src/chat/inbox-items/plugin.ts
6427
+ /**
6428
+ * Resolve the Users to assign. A plugin notice goes only to people in its
6429
+ * Conversation, public or private. Junior leaves out an Identity without a
6430
+ * User and a User who is not in the Conversation.
6431
+ */
6432
+ async function assigneeUserIds(db, identityIds, conversationId) {
6433
+ return (await mapBounded([...new Set(identityIds)], async (identityId) => {
6434
+ const user = (await readIdentityByIdFromSql(db, identityId))?.user;
6435
+ if (!user) return [];
6436
+ return (await readConversationAccessFromSql(db, [conversationId], user)).get(conversationId)?.isParticipant ? [user.id] : [];
6437
+ })).flat();
6438
+ }
6439
+ /** Field id of the one choice field of a plugin item with choices. */
6440
+ const PLUGIN_CHOICE_FIELD_ID = "choice";
6441
+ /** The request that shows a plugin item's choices as one row of buttons. */
6442
+ function choicesRequest(notice) {
6443
+ return inboxItemRequestSchema.parse({
6444
+ question: notice.body,
6445
+ fields: [{
6446
+ id: PLUGIN_CHOICE_FIELD_ID,
6447
+ kind: "choice",
6448
+ label: notice.title,
6449
+ options: notice.choices
6450
+ }]
6451
+ });
6452
+ }
6453
+ /** The stored dedupe key of a plugin item: `plugin:<name>:<key>`. */
6454
+ function pluginItemKey(plugin, dedupeKey) {
6455
+ return `${PLUGIN_INBOX_ITEM_KEY_PREFIX}${plugin}:${dedupeKey}`;
6456
+ }
6457
+ async function readAccess(db, conversationId) {
6458
+ const access = (await readConversationAccessFromSql(db, [conversationId])).get(conversationId);
6459
+ if (!access) throw new Error(`Conversation ${conversationId} is not found`);
6460
+ return access;
6461
+ }
6462
+ /**
6463
+ * Close the open item of a plugin with the key, in the tenant of the
6464
+ * Conversation. Return the id of the item that closed, or undefined when no
6465
+ * item was open. Pass a transaction to save it with other changes. The
6466
+ * caller shows the item after the write.
6467
+ */
6468
+ async function closePluginInboxItem(db, args) {
6469
+ const access = await readAccess(db, args.conversationId);
6470
+ const item = await getOpenInboxItemByDedupeKey(db, pluginItemKey(args.plugin, args.dedupeKey), access.tenant);
6471
+ if (!item) return void 0;
6472
+ return await closeInboxItem(db, {
6473
+ id: item.id,
6474
+ nowMs: Date.now(),
6475
+ reason: args.reason,
6476
+ status: args.status
6477
+ }) ? item.id : void 0;
6478
+ }
6479
+ /**
6480
+ * Connect a plugin to the Inbox for one Conversation. Dedupe keys are
6481
+ * `plugin:<name>:<key>`, so a plugin changes only its own items, and agents
6482
+ * cannot change them. A change sends no message to the Conversation. It
6483
+ * only shows the new state through `show`. An item is private when the
6484
+ * Conversation is not public.
6485
+ */
6486
+ function createPluginInboxItems(args) {
6487
+ const { conversationId, show } = args;
6488
+ return {
6489
+ async upsert(notice) {
6490
+ const db = getDb();
6491
+ const access = await readAccess(db, conversationId);
6492
+ const existing = await getOpenInboxItemByDedupeKey(db, pluginItemKey(args.plugin, notice.dedupeKey), access.tenant);
6493
+ const isPrivate = access.visibility !== "public" || existing?.visibility === "private";
6494
+ if (existing && isPrivate && ownerConversationId(existing) !== conversationId) throw new Error("A private inbox item links only to the Conversation that added it");
6495
+ const content = {
6496
+ assignedToEveryone: false,
6497
+ assigneeUserIds: await assigneeUserIds(db, notice.assigneeIdentityIds, conversationId),
6498
+ body: notice.body,
6499
+ conversationIds: [.../* @__PURE__ */ new Set([conversationId, ...existing?.conversationIds ?? []])],
6500
+ kind: notice.waitsOnAssignees || notice.choices ? "action" : "notice",
6501
+ title: notice.title,
6502
+ visibility: isPrivate ? "private" : "public",
6503
+ ...notice.choices ? { request: choicesRequest(notice) } : void 0,
6504
+ ...notice.subject ? { subject: notice.subject } : void 0
6505
+ };
6506
+ let itemId;
6507
+ let open = true;
6508
+ if (existing) {
6509
+ open = await updateInboxItemContent(db, {
6510
+ ...content,
6511
+ id: existing.id,
6512
+ nowMs: Date.now()
6513
+ });
6514
+ itemId = existing.id;
6515
+ } else {
6516
+ const item = await insertInboxItem(db, {
6517
+ ...content,
6518
+ dedupeKey: pluginItemKey(args.plugin, notice.dedupeKey),
6519
+ owner: {
6520
+ id: conversationId,
6521
+ kind: "conversation"
6522
+ },
6523
+ nowMs: Date.now(),
6524
+ ...access.tenant ? { tenant: access.tenant } : void 0
6525
+ });
6526
+ if (!item) return;
6527
+ itemId = item.id;
6528
+ }
6529
+ await show(itemId);
6530
+ if (open && content.kind === "action") await publishAgentUpdate(conversationId, {
6531
+ type: "waiting",
6532
+ inboxItemId: itemId
6533
+ }, {
6534
+ queue: getVercelConversationWorkQueue(),
6535
+ update: async () => ({
6536
+ status: "waiting",
6537
+ text: content.request?.question ?? content.body
6538
+ })
6539
+ });
6540
+ },
6541
+ async close(input) {
6542
+ const itemId = await closePluginInboxItem(getDb(), {
6543
+ ...input,
6544
+ conversationId,
6545
+ plugin: args.plugin
6546
+ });
6547
+ if (!itemId) return false;
6548
+ await show(itemId);
6549
+ return true;
6550
+ }
6551
+ };
6552
+ }
6553
+ // src/chat/plugins/conversation-changes.ts
6554
+ /**
6555
+ * Apply one plugin's batch of annotation and Inbox item changes in one
6556
+ * transaction, so readers and both version tokens see all of it or none of
6557
+ * it. Each entry uses the write of its `forConversation` call. The Slack
6558
+ * cards and pushes are outside calls, so they show the closed items after
6559
+ * the commit.
6560
+ */
6561
+ function createPluginConversationChanges(args) {
6562
+ return { async apply(batch) {
6563
+ const annotations = batch.annotations ?? [];
6564
+ const inboxItems = batch.inboxItems ?? [];
6565
+ const count = annotations.length + inboxItems.length;
6566
+ if (count > MAX_CONVERSATION_CHANGES) throw new Error(`A conversation change batch has ${count} entries, more than the limit of ${MAX_CONVERSATION_CHANGES}`);
6567
+ if (count === 0) return;
6568
+ const closedItemIds = await getDb().transaction(async (tx) => {
6569
+ for (const entry of annotations) await upsertPluginAnnotation(tx, {
6570
+ annotation: entry.upsert,
6571
+ conversationId: entry.conversationId,
6572
+ plugin: args.plugin
6573
+ });
6574
+ const closed = [];
6575
+ for (const entry of inboxItems) {
6576
+ const itemId = await closePluginInboxItem(tx, {
6577
+ ...entry.close,
6578
+ conversationId: entry.conversationId,
6579
+ plugin: args.plugin
6580
+ });
6581
+ if (itemId) closed.push(itemId);
6582
+ }
6583
+ return closed;
6584
+ });
6585
+ await mapBounded(closedItemIds, args.show);
6586
+ } };
6587
+ }
6363
6588
  // src/chat/conversations/annotation-results.ts
6364
6589
  /** Save object annotations and retain returned facts in the tool result. */
6365
6590
  async function saveObjectAnnotations(conversationId, plugin, value) {
@@ -11259,20 +11484,18 @@ async function recordCodeChange(db, provider, input) {
11259
11484
  "vcs.change.id": String(change.number),
11260
11485
  "vcs.change.state": change.state,
11261
11486
  "vcs.provider.name": provider,
11262
- "vcs.repository.url.full": change.repository.url
11487
+ "vcs.repository.name": change.repository.name
11263
11488
  });
11264
11489
  const repositories = await db.insert(juniorCodeRepositories).values({
11265
11490
  id: randomUUID(),
11266
11491
  name: change.repository.name,
11267
11492
  provider,
11268
11493
  providerId: change.repository.providerId,
11269
- url: change.repository.url,
11270
11494
  updatedAt: change.updatedAt
11271
11495
  }).onConflictDoUpdate({
11272
11496
  target: [juniorCodeRepositories.provider, juniorCodeRepositories.providerId],
11273
11497
  set: {
11274
11498
  name: change.repository.name,
11275
- ...change.repository.url ? { url: change.repository.url } : void 0,
11276
11499
  updatedAt: change.updatedAt
11277
11500
  },
11278
11501
  where: lte(juniorCodeRepositories.updatedAt, change.updatedAt)
@@ -11302,8 +11525,7 @@ async function recordCodeChange(db, provider, input) {
11302
11525
  repositoryId,
11303
11526
  state: change.state,
11304
11527
  ...change.title ? { title: change.title } : void 0,
11305
- updatedAt: change.updatedAt,
11306
- url: change.url ?? null
11528
+ updatedAt: change.updatedAt
11307
11529
  };
11308
11530
  await db.insert(juniorCodeChanges).values({
11309
11531
  ...values,
@@ -11350,126 +11572,22 @@ function createCodeChangePublisher(provider) {
11350
11572
  }
11351
11573
  };
11352
11574
  }
11353
- // src/chat/inbox-items/plugin.ts
11575
+ // src/chat/turn-context-tag.ts
11354
11576
  /**
11355
- * Resolve the Users to assign. A plugin notice goes only to people in its
11356
- * Conversation, public or private. Junior leaves out an Identity without a
11357
- * User and a User who is not in the Conversation.
11577
+ * Canonical tag name for the runtime turn context block injected into Pi
11578
+ * messages. Shared between prompt assembly and turn context stripping to keep
11579
+ * both in sync without requiring the full prompt module.
11358
11580
  */
11359
- async function assigneeUserIds(db, identityIds, conversationId) {
11360
- return (await mapBounded([...new Set(identityIds)], async (identityId) => {
11361
- const user = (await readIdentityByIdFromSql(db, identityId))?.user;
11362
- if (!user) return [];
11363
- return (await readConversationAccessFromSql(db, [conversationId], user)).get(conversationId)?.isParticipant ? [user.id] : [];
11364
- })).flat();
11365
- }
11366
- /** Field id of the one choice field of a plugin item with choices. */
11367
- const PLUGIN_CHOICE_FIELD_ID = "choice";
11368
- /** The request that shows a plugin item's choices as one row of buttons. */
11369
- function choicesRequest(notice) {
11370
- return inboxItemRequestSchema.parse({
11371
- question: notice.body,
11372
- fields: [{
11373
- id: PLUGIN_CHOICE_FIELD_ID,
11374
- kind: "choice",
11375
- label: notice.title,
11376
- options: notice.choices
11377
- }]
11378
- });
11379
- }
11581
+ const TURN_CONTEXT_TAG = "runtime-turn-context";
11582
+ /** Turn context section that only session context includes. */
11583
+ const SESSION_CONTEXT_SECTION_TAG = "runtime";
11380
11584
  /**
11381
- * Connect a plugin to the Inbox for one Conversation. Dedupe keys are
11382
- * `plugin:<name>:<key>`, so a plugin changes only its own items, and agents
11383
- * cannot change them. A change sends no message to the Conversation. It
11384
- * only shows the new state through `show`. An item is private when the
11385
- * Conversation is not public.
11386
- */
11387
- function createPluginInboxItems(args) {
11388
- const { conversationId, show } = args;
11389
- const scopedKey = (dedupeKey) => `${PLUGIN_INBOX_ITEM_KEY_PREFIX}${args.plugin}:${dedupeKey}`;
11390
- const readAccess = async (db) => {
11391
- const access = (await readConversationAccessFromSql(db, [conversationId])).get(conversationId);
11392
- if (!access) throw new Error(`Conversation ${conversationId} is not found`);
11393
- return access;
11394
- };
11395
- return {
11396
- async upsert(notice) {
11397
- const db = getDb();
11398
- const access = await readAccess(db);
11399
- const existing = await getOpenInboxItemByDedupeKey(db, scopedKey(notice.dedupeKey), access.tenant);
11400
- const isPrivate = access.visibility !== "public" || existing?.visibility === "private";
11401
- if (existing && isPrivate && ownerConversationId(existing) !== conversationId) throw new Error("A private inbox item links only to the Conversation that added it");
11402
- const content = {
11403
- assignedToEveryone: false,
11404
- assigneeUserIds: await assigneeUserIds(db, notice.assigneeIdentityIds, conversationId),
11405
- body: notice.body,
11406
- conversationIds: [.../* @__PURE__ */ new Set([conversationId, ...existing?.conversationIds ?? []])],
11407
- kind: notice.waitsOnAssignees || notice.choices ? "action" : "notice",
11408
- title: notice.title,
11409
- visibility: isPrivate ? "private" : "public",
11410
- ...notice.choices ? { request: choicesRequest(notice) } : void 0,
11411
- ...notice.subject ? { subject: notice.subject } : void 0
11412
- };
11413
- let itemId;
11414
- let open = true;
11415
- if (existing) {
11416
- open = await updateInboxItemContent(db, {
11417
- ...content,
11418
- id: existing.id,
11419
- nowMs: Date.now()
11420
- });
11421
- itemId = existing.id;
11422
- } else {
11423
- const item = await insertInboxItem(db, {
11424
- ...content,
11425
- dedupeKey: scopedKey(notice.dedupeKey),
11426
- owner: {
11427
- id: conversationId,
11428
- kind: "conversation"
11429
- },
11430
- nowMs: Date.now(),
11431
- ...access.tenant ? { tenant: access.tenant } : void 0
11432
- });
11433
- if (!item) return;
11434
- itemId = item.id;
11435
- }
11436
- await show(itemId);
11437
- if (open && content.kind === "action") await publishConversationStatus(conversationId, {
11438
- type: "waiting",
11439
- inboxItemId: itemId
11440
- }, { queue: getVercelConversationWorkQueue() });
11441
- },
11442
- async close(input) {
11443
- const db = getDb();
11444
- const access = await readAccess(db);
11445
- const item = await getOpenInboxItemByDedupeKey(db, scopedKey(input.dedupeKey), access.tenant);
11446
- if (!item) return false;
11447
- const closed = await closeInboxItem(db, {
11448
- id: item.id,
11449
- nowMs: Date.now(),
11450
- reason: input.reason,
11451
- status: input.status
11452
- });
11453
- if (closed) await show(item.id);
11454
- return closed;
11455
- }
11456
- };
11457
- }
11458
- // src/chat/turn-context-tag.ts
11459
- /**
11460
- * Canonical tag name for the runtime turn context block injected into Pi
11461
- * messages. Shared between prompt assembly and turn context stripping to keep
11462
- * both in sync without requiring the full prompt module.
11463
- */
11464
- const TURN_CONTEXT_TAG = "runtime-turn-context";
11465
- /** Turn context section that only session context includes. */
11466
- const SESSION_CONTEXT_SECTION_TAG = "runtime";
11467
- /**
11468
- * Named system prompt sections that list what the model can use now: the
11469
- * skills, MCP catalogs, tool guidance, Workspaces, and the tools that a Code
11470
- * Mode script can call. A Turn sends a changed section in a later system
11471
- * message (`systemSectionsUpdate`). The Turn context of older Turns held
11472
- * copies of them, which context compaction drops.
11585
+ * Named system prompt sections that list what the model can use now: the
11586
+ * skills, MCP catalogs, tool guidance, Workspaces, and the tools that a Code
11587
+ * Mode script can call. A Turn sends a changed section in a later system
11588
+ * message (`systemSectionsUpdate`). The Turn context of older Turns held
11589
+ * copies of them, which context compaction drops. Keep text from people and
11590
+ * providers out of them: it goes in the context message.
11473
11591
  */
11474
11592
  const CAPABILITY_SECTION_TAG = {
11475
11593
  availableSkills: "available-skills",
@@ -11480,7 +11598,8 @@ const CAPABILITY_SECTION_TAG = {
11480
11598
  };
11481
11599
  /**
11482
11600
  * Turn context sections that are true only for the Turn that received them.
11483
- * Context compaction removes them from the context of earlier Turns.
11601
+ * Context compaction removes them from the context of earlier Turns. A fact
11602
+ * for one request goes in one of these, never in the system prompt.
11484
11603
  */
11485
11604
  const REQUEST_CONTEXT_SECTION_TAG = {
11486
11605
  pluginContext: "plugin-context",
@@ -11799,16 +11918,26 @@ function eventIndexLockKey(conversationId) {
11799
11918
  async function embedConversationEvents(db, embedder, conversationId, limits = {}) {
11800
11919
  const events = juniorConversationEvents;
11801
11920
  const embeddings = juniorConversationEventEmbeddings;
11921
+ const lexemes = juniorConversationEventLexemes;
11802
11922
  const text = sql`left(${eventSearchTextSql()}, ${MAX_EMBEDDED_CHARS})`;
11803
11923
  return (await refreshEmbeddings({
11804
11924
  batchSize: EMBEDDING_BATCH_SIZE,
11805
11925
  deadlineMs: limits.deadlineMs,
11806
11926
  embedder,
11807
11927
  maxItems: limits.maxEvents ?? MAX_EVENTS_PER_RUN,
11808
- listMissing: async ({ after, limit }) => await db.select({
11809
- seq: events.seq,
11810
- text
11811
- }).from(events).leftJoin(embeddings, and(eq(embeddings.conversationId, events.conversationId), eq(embeddings.seq, events.seq), eq(embeddings.provider, embedder.provider), eq(embeddings.model, embedder.model))).where(and(eq(events.conversationId, conversationId), inArray(events.type, [...SEARCHABLE_EVENT_TYPES]), isNull(embeddings.seq), sql`${eventSearchTextSql()} ~ '[^[:space:]]'`, after ? lt(events.seq, after.seq) : void 0)).orderBy(desc(events.seq)).limit(limit),
11928
+ listMissing: async ({ after, limit }) => {
11929
+ const missing = await db.select({ seq: events.seq }).from(events).leftJoin(embeddings, and(eq(embeddings.conversationId, events.conversationId), eq(embeddings.seq, events.seq), eq(embeddings.provider, embedder.provider), eq(embeddings.model, embedder.model))).leftJoin(lexemes, and(eq(lexemes.conversationId, events.conversationId), eq(lexemes.seq, events.seq))).where(and(eq(events.conversationId, conversationId), inArray(events.type, [...SEARCHABLE_EVENT_TYPES]), isNull(embeddings.seq), or(isNull(lexemes.seq), sql`length(${lexemes.lexemes}) > 0`), after ? lt(events.seq, after.seq) : void 0)).orderBy(desc(events.seq)).limit(limit);
11930
+ if (missing.length === 0) return [];
11931
+ const texts = await db.select({
11932
+ seq: events.seq,
11933
+ text
11934
+ }).from(events).where(and(eq(events.conversationId, conversationId), seqIn(missing.map((row) => row.seq))));
11935
+ const textBySeq = new Map(texts.map((row) => [row.seq, row.text]));
11936
+ return missing.map(({ seq }) => ({
11937
+ seq,
11938
+ text: textBySeq.get(seq) ?? ""
11939
+ }));
11940
+ },
11812
11941
  write: async (rows, batch) => {
11813
11942
  await db.insert(embeddings).values(rows.map(({ item, vector }) => ({
11814
11943
  conversationId,
@@ -11973,6 +12102,127 @@ function fuseRankedLists(lists, options) {
11973
12102
  }
11974
12103
  return [...fused.values()].sort((left, right) => right.score - left.score || (options.tiebreak?.(left.item, right.item) ?? 0)).map(({ item }) => item);
11975
12104
  }
12105
+ // src/search/match-ranking.ts
12106
+ const SEARCH_LEGS = [
12107
+ "exact",
12108
+ "lexical",
12109
+ "prefix",
12110
+ "fuzzy",
12111
+ "vector"
12112
+ ];
12113
+ /**
12114
+ * Rank values that are already in order, best first. Equal keys share a
12115
+ * rank, and the next key takes its position: 1, 1, 3.
12116
+ */
12117
+ function withDenseRanks(values, key) {
12118
+ let previous;
12119
+ let rank = 0;
12120
+ return values.map((value, index) => {
12121
+ const current = key(value);
12122
+ if (index === 0 || current !== previous) {
12123
+ rank = index + 1;
12124
+ previous = current;
12125
+ }
12126
+ return {
12127
+ rank,
12128
+ value
12129
+ };
12130
+ });
12131
+ }
12132
+ /**
12133
+ * Rank each way's matches by its score, larger is better. A row is in a
12134
+ * way only when its score is defined.
12135
+ */
12136
+ function scoredSearchMatches(rows, scores) {
12137
+ const matches = rows.map((item) => ({
12138
+ item,
12139
+ ranks: {}
12140
+ }));
12141
+ for (const leg of SEARCH_LEGS) {
12142
+ const score = scores[leg];
12143
+ if (!score) continue;
12144
+ const scored = matches.flatMap((match) => {
12145
+ const value = score(match.item);
12146
+ return value === void 0 ? [] : [{
12147
+ match,
12148
+ value
12149
+ }];
12150
+ });
12151
+ scored.sort((left, right) => right.value - left.value);
12152
+ for (const { rank, value: entry } of withDenseRanks(scored, (row) => row.value)) entry.match.ranks[leg] = rank;
12153
+ }
12154
+ return matches;
12155
+ }
12156
+ /**
12157
+ * Fuse the ranks of every way that found each match into one order, best
12158
+ * first, with reciprocal rank fusion. Raw scores of two ways are never
12159
+ * compared, so any source can add a way. `weights` default to 1.
12160
+ */
12161
+ function rankSearchMatches(matches, options) {
12162
+ return fuseRankedLists(SEARCH_LEGS.map((leg) => matches.flatMap((match) => {
12163
+ const rank = match.ranks[leg];
12164
+ return rank === void 0 ? [] : [{
12165
+ item: match.item,
12166
+ rank
12167
+ }];
12168
+ })), {
12169
+ key: options.key,
12170
+ weights: SEARCH_LEGS.map((leg) => options.weights?.[leg] ?? 1),
12171
+ ...options.tiebreak ? { tiebreak: options.tiebreak } : void 0
12172
+ });
12173
+ }
12174
+ // src/search/text-match.ts
12175
+ /** SQL: the `simple` tsquery of typed text, each word as a prefix. */
12176
+ function prefixTsquery(query) {
12177
+ return sql`to_tsquery('simple', ${query.prefix})`;
12178
+ }
12179
+ /**
12180
+ * SQL: a `simple` search document has a word that each word of the query
12181
+ * starts. A GIN index on the document finds the rows.
12182
+ */
12183
+ function prefixMatch(document, query) {
12184
+ return sql`(${document} @@ ${prefixTsquery(query)})`;
12185
+ }
12186
+ /**
12187
+ * SQL: how well a document matches the query, larger is better. Words in
12188
+ * a heavier field and words close together rank higher. Rank only the rows
12189
+ * of a bounded window, because it reads each document.
12190
+ */
12191
+ function prefixRank(document, query) {
12192
+ return sql`ts_rank_cd(${document}, ${prefixTsquery(query)})`;
12193
+ }
12194
+ /**
12195
+ * SQL: some extent of the lowercase text has most of the query's trigrams,
12196
+ * so a title matches through a typo. A GIN `gin_trgm_ops` index on the text
12197
+ * finds the rows. False for a query too short to match by trigrams.
12198
+ */
12199
+ function fuzzyMatch(text, query) {
12200
+ return query.fuzzy ? sql`(${query.fuzzy} <% ${text})` : sql`false`;
12201
+ }
12202
+ /** SQL: how close the lowercase text is to the query, from 0 to 1. */
12203
+ function fuzzyRank(text, query) {
12204
+ return query.fuzzy ? sql`word_similarity(${query.fuzzy}, ${text})` : sql`0`;
12205
+ }
12206
+ // src/search/typed-query.ts
12207
+ const TYPED_QUERY_TERMS = 4;
12208
+ const TYPED_QUERY_TOKENS = 16;
12209
+ const FUZZY_QUERY_MIN_LENGTH = 3;
12210
+ /**
12211
+ * Parse text that a person types into a search. Each word must start a
12212
+ * word of the document, so a result shows while the last word is still
12213
+ * half typed. Returns undefined when the text has no letters or digits.
12214
+ */
12215
+ function parseTypedQuery(text) {
12216
+ const lower = text.toLowerCase();
12217
+ const terms = (lower.match(/[\p{L}\p{N}]+/gu) ?? []).slice(0, TYPED_QUERY_TERMS);
12218
+ if (terms.length === 0) return void 0;
12219
+ const fuzzy = terms.join(" ");
12220
+ return {
12221
+ ...fuzzy.length >= FUZZY_QUERY_MIN_LENGTH ? { fuzzy } : void 0,
12222
+ prefix: terms.map((term) => `${term}:*`).join(" & "),
12223
+ tokens: (lower.match(/[\p{L}\p{N}_-]+/gu) ?? []).slice(0, TYPED_QUERY_TOKENS)
12224
+ };
12225
+ }
11976
12226
  // src/chat/memory/ranking.ts
11977
12227
  const ONE_DAY_MS = 864e5;
11978
12228
  const DEFAULT_RRF_WEIGHT = 1;
@@ -11986,17 +12236,21 @@ function observedAgeRank(memory, nowMs) {
11986
12236
  function positiveWeight(value, fallback) {
11987
12237
  return value !== void 0 && Number.isFinite(value) && value > 0 ? value : fallback;
11988
12238
  }
11989
- /** Fuse lexical and vector ranks without comparing provider raw scores. */
12239
+ /** Fuse lexical, word prefix, and vector ranks without comparing raw scores. */
11990
12240
  function rankMemoryMatches(matches, options) {
11991
- return fuseRankedLists([matches.flatMap((match) => match.vector ? [{
11992
- item: match,
11993
- rank: match.vector.rank
11994
- }] : []), matches.flatMap((match) => match.lexical ? [{
12241
+ return rankSearchMatches(matches.map((match) => ({
11995
12242
  item: match,
11996
- rank: match.lexical.rank
11997
- }] : [])], {
12243
+ ranks: {
12244
+ lexical: match.lexical?.rank,
12245
+ prefix: match.prefix?.rank,
12246
+ vector: match.vector?.rank
12247
+ }
12248
+ })), {
11998
12249
  key: (match) => match.memory.id,
11999
- weights: [positiveWeight(options.vectorWeight, DEFAULT_RRF_WEIGHT), positiveWeight(options.lexicalWeight, DEFAULT_RRF_WEIGHT)],
12250
+ weights: {
12251
+ lexical: positiveWeight(options.lexicalWeight, DEFAULT_RRF_WEIGHT),
12252
+ vector: positiveWeight(options.vectorWeight, DEFAULT_RRF_WEIGHT)
12253
+ },
12000
12254
  tiebreak: (left, right) => observedAgeRank(right.memory, options.nowMs) - observedAgeRank(left.memory, options.nowMs) || right.memory.observedAtMs - left.memory.observedAtMs || left.memory.id.localeCompare(right.memory.id)
12001
12255
  });
12002
12256
  }
@@ -12373,21 +12627,6 @@ async function archiveExpiredRows(args) {
12373
12627
  return idsToClean;
12374
12628
  })).length };
12375
12629
  }
12376
- function withDenseRanks(values, key) {
12377
- let previous;
12378
- let rank = 0;
12379
- return values.map((value, index) => {
12380
- const current = key(value);
12381
- if (index === 0 || current !== previous) {
12382
- rank = index + 1;
12383
- previous = current;
12384
- }
12385
- return {
12386
- rank,
12387
- value
12388
- };
12389
- });
12390
- }
12391
12630
  async function embedOne(embedder, text, inputType) {
12392
12631
  const normalized = normalizeContent(text);
12393
12632
  if (!normalized) throw new Error("Embedding text is required.");
@@ -12587,22 +12826,17 @@ function retrievalLegLimit(limit, overfetch) {
12587
12826
  const withOverfetch = requested * Math.max(1, overfetch);
12588
12827
  return Math.min(MAX_RETRIEVAL_LEG_CANDIDATES, Math.max(requested, withOverfetch));
12589
12828
  }
12590
- /** Search a bounded active candidate set with PostgreSQL full-text ranking. */
12591
- async function searchVisibleLexicalMemories(args) {
12829
+ /**
12830
+ * Search a bounded active candidate set with PostgreSQL full-text ranking.
12831
+ * A GIN index on `document` finds the matches of `tsquery`, and only a
12832
+ * bounded window of the newest ones is ranked.
12833
+ */
12834
+ async function searchVisibleTextMemories(args) {
12835
+ const { document, tsquery } = args;
12592
12836
  const predicate = activeVisiblePredicate(args.nowMs);
12593
- const query = normalizeRetrievalQuery(args.query);
12594
- if (!query) return [];
12595
- const queryVector = sql`to_tsvector('english', ${query})`;
12596
- const tsquery = sql`(
12597
- SELECT COALESCE(
12598
- string_agg(quote_literal(term), ' | ')::tsquery,
12599
- ''::tsquery
12600
- )
12601
- FROM unnest(tsvector_to_array(${queryVector})) AS query_terms(term)
12602
- )`;
12603
12837
  const candidateLimit = Math.min(MAX_LEXICAL_RANK_CANDIDATES, args.limit * LEXICAL_RANK_WINDOW_MULTIPLIER);
12604
- const candidates = args.db.select().from(juniorMemoryMemories).where(and(predicate, sql`${juniorMemoryMemories.searchVector} @@ ${tsquery}`)).orderBy(desc(juniorMemoryMemories.observedAtMs), asc(juniorMemoryMemories.id)).limit(candidateLimit).as("lexical_candidates");
12605
- const textRank = sql`ts_rank_cd(${candidates.searchVector}, ${tsquery})`;
12838
+ const candidates = args.db.select().from(juniorMemoryMemories).where(and(predicate, sql`${document(juniorMemoryMemories)} @@ ${tsquery}`)).orderBy(desc(juniorMemoryMemories.observedAtMs), asc(juniorMemoryMemories.id)).limit(candidateLimit).as("lexical_candidates");
12839
+ const textRank = sql`ts_rank_cd(${document(candidates)}, ${tsquery})`;
12606
12840
  return withDenseRanks(await args.db.select({
12607
12841
  memory: {
12608
12842
  archiveReason: candidates.archiveReason,
@@ -12627,8 +12861,47 @@ async function searchVisibleLexicalMemories(args) {
12627
12861
  },
12628
12862
  textRank
12629
12863
  }).from(candidates).orderBy(desc(textRank), desc(candidates.observedAtMs), asc(candidates.id)).limit(args.limit), (row) => Number(row.textRank)).map(({ rank, value: row }) => ({
12864
+ memory: parseMemoryRow(row.memory),
12865
+ rank
12866
+ }));
12867
+ }
12868
+ /** Match the stemmed `english` words of the query, as recall does. */
12869
+ async function searchVisibleLexicalMemories(args) {
12870
+ const query = normalizeRetrievalQuery(args.query);
12871
+ if (!query) return [];
12872
+ const queryVector = sql`to_tsvector('english', ${query})`;
12873
+ const tsquery = sql`(
12874
+ SELECT COALESCE(
12875
+ string_agg(quote_literal(term), ' | ')::tsquery,
12876
+ ''::tsquery
12877
+ )
12878
+ FROM unnest(tsvector_to_array(${queryVector})) AS query_terms(term)
12879
+ )`;
12880
+ return (await searchVisibleTextMemories({
12881
+ db: args.db,
12882
+ document: (table) => sql`${table.searchVector}`,
12883
+ limit: args.limit,
12884
+ nowMs: args.nowMs,
12885
+ tsquery
12886
+ })).map(({ memory, rank }) => ({
12630
12887
  lexical: { rank },
12631
- memory: parseMemoryRow(row.memory)
12888
+ memory
12889
+ }));
12890
+ }
12891
+ /**
12892
+ * Match typed text: each word of the query starts a `simple` word of the
12893
+ * memory, so a half-typed inflected word still matches.
12894
+ */
12895
+ async function searchVisiblePrefixMemories(args) {
12896
+ return (await searchVisibleTextMemories({
12897
+ db: args.db,
12898
+ document: memoryPrefixDocument,
12899
+ limit: args.limit,
12900
+ nowMs: args.nowMs,
12901
+ tsquery: prefixTsquery(args.query)
12902
+ })).map(({ memory, rank }) => ({
12903
+ memory,
12904
+ prefix: { rank }
12632
12905
  }));
12633
12906
  }
12634
12907
  /** Search every visible vector of the query model. Exact, but reads each one. */
@@ -12682,6 +12955,71 @@ async function searchVisibleVectorMemories(args) {
12682
12955
  }];
12683
12956
  });
12684
12957
  }
12958
+ /**
12959
+ * Hybrid retrieval for automatic recall, explicit search, and typed search.
12960
+ *
12961
+ * Keep both legs parallel and fuse ranks with RRF. Never skip lexical when
12962
+ * vectors already hit: that drops exact/token memories and serializes the
12963
+ * miss path. Each leg is a hard-capped top-k probe so Postgres work stays
12964
+ * bounded even on broad queries.
12965
+ */
12966
+ async function retrieveVisibleMemories(args) {
12967
+ const { db, embedder, nowMs, vectorMaxDistance } = args;
12968
+ const input = searchMemoriesInputSchema$1.parse(args.input);
12969
+ const limit = boundedLimit$1(input.limit, DEFAULT_SEARCH_LIMIT$1);
12970
+ const candidateLimit = retrievalLegLimit(limit, vectorMaxDistance === void 0 ? SEARCH_RETRIEVAL_OVERFETCH : RECALL_RETRIEVAL_OVERFETCH);
12971
+ const query = normalizeRetrievalQuery(input.query);
12972
+ const vectorMatches = async () => {
12973
+ const embedding = embedder && query ? await embedOne(embedder, query, "query").catch(() => void 0) : void 0;
12974
+ if (!embedding) return [];
12975
+ return await searchVisibleVectorMemories({
12976
+ db,
12977
+ embedding,
12978
+ limit: candidateLimit,
12979
+ ...vectorMaxDistance !== void 0 ? { maxDistance: vectorMaxDistance } : void 0,
12980
+ nowMs
12981
+ });
12982
+ };
12983
+ return rankMemoryMatches((await Promise.all([
12984
+ vectorMatches(),
12985
+ searchVisibleLexicalMemories({
12986
+ db,
12987
+ limit: candidateLimit,
12988
+ nowMs,
12989
+ query: input.query
12990
+ }),
12991
+ args.typed ? searchVisiblePrefixMemories({
12992
+ db,
12993
+ limit: candidateLimit,
12994
+ nowMs,
12995
+ query: args.typed
12996
+ }) : []
12997
+ ])).flat(), {
12998
+ nowMs,
12999
+ ...vectorMaxDistance === void 0 ? void 0 : {
13000
+ lexicalWeight: 1,
13001
+ vectorWeight: .85
13002
+ }
13003
+ }).slice(0, limit).map(({ memory }) => memory);
13004
+ }
13005
+ /**
13006
+ * Search active public memory for text that a person is typing, with the
13007
+ * legs, ranking, and vector cutoff of automatic recall, plus a word prefix
13008
+ * leg, so a half-typed last word still matches.
13009
+ */
13010
+ async function searchTypedMemories(args) {
13011
+ return await retrieveVisibleMemories({
13012
+ db: args.db,
13013
+ embedder: args.embedder,
13014
+ input: {
13015
+ limit: args.limit,
13016
+ query: args.query
13017
+ },
13018
+ nowMs: args.nowMs,
13019
+ typed: parseTypedQuery(args.query),
13020
+ vectorMaxDistance: RECALL_MAX_VECTOR_DISTANCE
13021
+ });
13022
+ }
12685
13023
  /** Create a context-bound SQL-backed store for explicit memory operations. */
12686
13024
  function createMemoryStore(db, context, options = {}) {
12687
13025
  const runtimeContext = memoryRuntimeContextSchema.parse(context);
@@ -12925,44 +13263,6 @@ function createMemoryStore(db, context, options = {}) {
12925
13263
  memory: idempotent.memory
12926
13264
  };
12927
13265
  }
12928
- /**
12929
- * Hybrid retrieval for both automatic recall and explicit search.
12930
- *
12931
- * Keep both legs parallel and fuse ranks with RRF. Never skip lexical when
12932
- * vectors already hit: that drops exact/token memories and serializes the
12933
- * miss path. Each leg is a hard-capped top-k probe so Postgres work stays
12934
- * bounded even on broad queries.
12935
- */
12936
- async function retrieveVisibleMemories(rawInput, vectorMaxDistance) {
12937
- const input = searchMemoriesInputSchema$1.parse(rawInput);
12938
- const nowMs = getNowMs();
12939
- const limit = boundedLimit$1(input.limit, DEFAULT_SEARCH_LIMIT$1);
12940
- const candidateLimit = retrievalLegLimit(limit, vectorMaxDistance === void 0 ? SEARCH_RETRIEVAL_OVERFETCH : RECALL_RETRIEVAL_OVERFETCH);
12941
- const query = normalizeRetrievalQuery(input.query);
12942
- const vectorMatches = async () => {
12943
- const embedding = embedder && query ? await embedOne(embedder, query, "query").catch(() => void 0) : void 0;
12944
- if (!embedding) return [];
12945
- return await searchVisibleVectorMemories({
12946
- db,
12947
- embedding,
12948
- limit: candidateLimit,
12949
- ...vectorMaxDistance !== void 0 ? { maxDistance: vectorMaxDistance } : void 0,
12950
- nowMs
12951
- });
12952
- };
12953
- return rankMemoryMatches((await Promise.all([vectorMatches(), searchVisibleLexicalMemories({
12954
- db,
12955
- limit: candidateLimit,
12956
- nowMs,
12957
- query: input.query
12958
- })])).flat(), {
12959
- nowMs,
12960
- ...vectorMaxDistance === void 0 ? void 0 : {
12961
- lexicalWeight: 1,
12962
- vectorWeight: .85
12963
- }
12964
- }).slice(0, limit).map(({ memory }) => memory);
12965
- }
12966
13266
  return {
12967
13267
  async archiveExpiredMemories(input) {
12968
13268
  return await archiveExpiredVisibleMemories(input, getNowMs());
@@ -12982,10 +13282,21 @@ function createMemoryStore(db, context, options = {}) {
12982
13282
  });
12983
13283
  },
12984
13284
  async recallMemories(input) {
12985
- return await retrieveVisibleMemories(input, RECALL_MAX_VECTOR_DISTANCE);
13285
+ return await retrieveVisibleMemories({
13286
+ db,
13287
+ embedder,
13288
+ input,
13289
+ nowMs: getNowMs(),
13290
+ vectorMaxDistance: RECALL_MAX_VECTOR_DISTANCE
13291
+ });
12986
13292
  },
12987
13293
  async searchMemories(input) {
12988
- return await retrieveVisibleMemories(input, void 0);
13294
+ return await retrieveVisibleMemories({
13295
+ db,
13296
+ embedder,
13297
+ input,
13298
+ nowMs: getNowMs()
13299
+ });
12989
13300
  },
12990
13301
  async archiveMemory(input) {
12991
13302
  input = archiveMemoryInputSchema$1.parse(input);
@@ -14361,7 +14672,7 @@ const memoryManyOutputSchema = pluginToolOutputSchema.extend({
14361
14672
  /** Parse memory tool input, as a model-repairable error when invalid. */
14362
14673
  function parseMemoryToolInput(schema, input) {
14363
14674
  const result = schema.safeParse(input);
14364
- if (!result.success) throw new PluginToolInputError("Invalid memory tool input.", { cause: result.error });
14675
+ if (!result.success) throw new PluginToolInputError("Invalid memory tool input. Check the arguments against the tool schema and call it again.", { cause: result.error });
14365
14676
  return result.data;
14366
14677
  }
14367
14678
  /** Return the model-visible projection without hidden ownership/source fields. */
@@ -14520,10 +14831,10 @@ const memoryCreateTool = definePluginTool({
14520
14831
  } catch (error) {
14521
14832
  if (error instanceof PluginToolInputError) throw error;
14522
14833
  const detail = error instanceof Error && error.message.trim() ? `: ${error.message}` : "";
14523
- throw new PluginToolInputError(`Memory agent review failed${detail}`, { cause: error });
14834
+ throw new PluginToolInputError(`Memory agent review failed${detail}. Continue without storing this memory.`, { cause: error });
14524
14835
  }
14525
14836
  })();
14526
- if (review.decision === "reject") throw new PluginToolInputError(`Memory was not stored: ${review.reason}`);
14837
+ if (review.decision === "reject") throw new PluginToolInputError(`Memory was not stored. Change the memory to fix this problem, or do not store it: ${review.reason}`);
14527
14838
  const memoryInput = createInput(context, {
14528
14839
  content: review.content,
14529
14840
  kind: review.kind,
@@ -15495,6 +15806,90 @@ function projectConversationMessages(history) {
15495
15806
  };
15496
15807
  });
15497
15808
  }
15809
+ // src/chat/inbox-items/reply-notice.ts
15810
+ function replyNoticeKey(conversationId) {
15811
+ return `${REPLY_NOTICE_KEY_PREFIX}${conversationId}`;
15812
+ }
15813
+ /**
15814
+ * Add the reply notice of a Conversation for its starter, or replace the
15815
+ * content of the open one with the latest reply. Return the id of the
15816
+ * open item.
15817
+ */
15818
+ async function upsertReplyNotice(db, input) {
15819
+ const access = (await readConversationAccessFromSql(db, [input.conversationId])).get(input.conversationId);
15820
+ const tenant = access?.tenant;
15821
+ const key = replyNoticeKey(input.conversationId);
15822
+ const content = {
15823
+ assignedToEveryone: false,
15824
+ assigneeUserIds: [input.starterUserId],
15825
+ body: input.body,
15826
+ conversationIds: [input.conversationId],
15827
+ kind: "notice",
15828
+ title: input.title,
15829
+ visibility: access?.visibility === "public" ? "public" : "private"
15830
+ };
15831
+ const open = await getOpenInboxItemByDedupeKey(db, key, tenant);
15832
+ if (open) {
15833
+ if (await updateInboxItemContent(db, {
15834
+ ...content,
15835
+ visibility: open.visibility === "private" ? "private" : content.visibility,
15836
+ addedByTurnId: input.turnId,
15837
+ id: open.id,
15838
+ nowMs: input.nowMs
15839
+ })) return open.id;
15840
+ }
15841
+ const inserted = await insertInboxItem(db, {
15842
+ ...content,
15843
+ addedByTurnId: input.turnId,
15844
+ dedupeKey: key,
15845
+ nowMs: input.nowMs,
15846
+ owner: {
15847
+ id: input.conversationId,
15848
+ kind: "conversation"
15849
+ },
15850
+ ...tenant ? { tenant } : void 0
15851
+ });
15852
+ if (!inserted) throw new Error(`Reply notice of ${input.conversationId} changed`);
15853
+ return inserted.id;
15854
+ }
15855
+ /**
15856
+ * Return whether the User read the latest reply of a Conversation: their
15857
+ * read position reaches it, or they wrote a later Message. Conversation
15858
+ * status reads a starter's read the same way.
15859
+ */
15860
+ async function hasReadLatestReply(db, conversationId, userId) {
15861
+ const [latest] = await db.select({ seq: max(juniorConversationEvents.seq) }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'assistant'`));
15862
+ const replySeq = latest?.seq;
15863
+ if (replySeq == null) return false;
15864
+ const [position] = await db.select({ lastReadSeq: juniorConversationReadPositions.lastReadSeq }).from(juniorConversationReadPositions).where(and(eq(juniorConversationReadPositions.conversationId, conversationId), eq(juniorConversationReadPositions.userId, userId))).limit(1);
15865
+ if (position && position.lastReadSeq >= replySeq) return true;
15866
+ const [later] = await db.select({ seq: juniorConversationEvents.seq }).from(juniorConversationEvents).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId)).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), gt(juniorConversationEvents.seq, replySeq), eq(juniorIdentities.userId, userId))).limit(1);
15867
+ return later !== void 0;
15868
+ }
15869
+ /**
15870
+ * Close the User's open reply notice of a Conversation when they read the
15871
+ * latest reply. The notice holds that reply, so an earlier read leaves it
15872
+ * open.
15873
+ */
15874
+ async function closeReadReplyNotice(db, input) {
15875
+ const notice = await openReplyNoticeId(db, input);
15876
+ if (!notice) return;
15877
+ if (!await hasReadLatestReply(db, input.conversationId, input.userId)) return;
15878
+ await closeRead(db, notice, input);
15879
+ }
15880
+ async function openReplyNoticeId(db, input) {
15881
+ const [notice] = await db.select({ id: juniorInboxItems.id }).from(juniorInboxItems).where(and(eq(juniorInboxItems.dedupeKey, replyNoticeKey(input.conversationId)), eq(juniorInboxItems.status, "open"), inboxItemAssignedTo(input.userId))).limit(1);
15882
+ return notice?.id;
15883
+ }
15884
+ async function closeRead(db, id, input) {
15885
+ await closeInboxItem(db, {
15886
+ closedByUserId: input.userId,
15887
+ id,
15888
+ nowMs: input.nowMs,
15889
+ reason: "Read",
15890
+ status: "done"
15891
+ });
15892
+ }
15498
15893
  // src/chat/slack/dnd.ts
15499
15894
  const dndInfoSchema = z.object({
15500
15895
  dnd_enabled: z.boolean(),
@@ -15520,6 +15915,25 @@ async function isSlackDndActive(userId, nowMs) {
15520
15915
  const dnd = dndInfoSchema.parse(response);
15521
15916
  return dnd.dnd_enabled && nowMs >= dnd.next_dnd_start_ts * 1e3 && nowMs < dnd.next_dnd_end_ts * 1e3;
15522
15917
  }
15918
+ // src/chat/slack/presence.ts
15919
+ const presenceSchema = z.object({ presence: z.enum(["active", "away"]) });
15920
+ /**
15921
+ * Return whether a Slack user is active in Slack now, from
15922
+ * `users.getPresence`. Return undefined when Slack cannot answer.
15923
+ */
15924
+ async function isSlackUserActive(userId) {
15925
+ let response;
15926
+ try {
15927
+ response = await withSlackRetries(() => getSlackClient().users.getPresence({ user: userId }), 3, {
15928
+ action: "users.getPresence",
15929
+ idempotent: true
15930
+ });
15931
+ } catch (error) {
15932
+ if (error instanceof SlackActionError) return void 0;
15933
+ throw error;
15934
+ }
15935
+ return presenceSchema.parse(response).presence === "active";
15936
+ }
15523
15937
  // src/chat/notifications/slack.ts
15524
15938
  const SLACK_PAUSE_BUCKET_MS = 6e4;
15525
15939
  /**
@@ -15537,6 +15951,15 @@ async function isPausedBySlack(db, userId, nowMs) {
15537
15951
  };
15538
15952
  }) ?? void 0;
15539
15953
  }
15954
+ /**
15955
+ * Return whether the user's linked Slack user is active in Slack now.
15956
+ * Return false when the user has no linked Slack user or Slack cannot
15957
+ * answer.
15958
+ */
15959
+ async function isActiveInSlack(db, userId) {
15960
+ const slack = await linkedSlackUser(db, userId);
15961
+ return slack ? await isSlackUserActive(slack.userId) ?? false : false;
15962
+ }
15540
15963
  // src/chat/notifications/store.ts
15541
15964
  /**
15542
15965
  * Save a browser subscription for a user. The endpoint identifies one browser,
@@ -15616,8 +16039,35 @@ async function resolveNotificationTimezone(args) {
15616
16039
  timezone: defaultTimezone()
15617
16040
  };
15618
16041
  }
16042
+ // src/chat/notifications/pause.ts
16043
+ /**
16044
+ * Return why pushes to this User are paused now, or undefined when Junior
16045
+ * can push. By default the linked Slack user's notification schedule
16046
+ * decides. The saved hours apply when the User turns that off or Slack
16047
+ * cannot answer.
16048
+ */
16049
+ async function readNotificationPause(db, userId, nowMs) {
16050
+ const schedule = await readNotificationSchedule(db, userId);
16051
+ const pausedBySlack = schedule.followSlack !== false ? await isPausedBySlack(db, userId, nowMs) : void 0;
16052
+ if (pausedBySlack) return "slack_paused";
16053
+ if (pausedBySlack !== void 0) return void 0;
16054
+ const { timezone } = await resolveNotificationTimezone({
16055
+ db,
16056
+ nowMs,
16057
+ schedule,
16058
+ userId
16059
+ });
16060
+ return isWithinNotificationSchedule(schedule, timezone, nowMs) ? void 0 : "outside_hours";
16061
+ }
16062
+ // src/chat/notifications/preview.ts
16063
+ const PREVIEW_MAX_CHARS = 180;
16064
+ /** Turn Markdown text into one short plain line for a notification. */
16065
+ function notificationPreview(text) {
16066
+ const plain = markdownPlainText(text, { proseOnly: true });
16067
+ return plain.length > PREVIEW_MAX_CHARS ? `${plain.slice(0, 179).trimEnd()}…` : plain;
16068
+ }
15619
16069
  // src/chat/notifications/web-push.ts
15620
- /** Keep a reply notification for 12 hours while the device is offline. */
16070
+ /** Keep a notification for 12 hours while the device is offline. */
15621
16071
  const PUSH_TTL_SECONDS = 43200;
15622
16072
  const PUSH_TIMEOUT_MS = 1e4;
15623
16073
  function subjectFromBaseUrl() {
@@ -15693,7 +16143,11 @@ async function sendToDevice(subscription, body, config) {
15693
16143
  */
15694
16144
  async function sendPushNotificationToUser(args) {
15695
16145
  const subscriptions = await listPushSubscriptions(args.db, args.userId);
15696
- const body = JSON.stringify(args.payload);
16146
+ const close = await listClearedInboxItemPushes(args.db, args.userId, Date.now() - PUSH_TTL_SECONDS * 1e3);
16147
+ const body = JSON.stringify(close.length > 0 ? {
16148
+ ...args.payload,
16149
+ close
16150
+ } : args.payload);
15697
16151
  const outcomes = await mapBounded(subscriptions, (subscription) => sendToDevice(subscription, body, args.config));
15698
16152
  const gone = subscriptions.filter((_, index) => outcomes[index] === "gone").map((subscription) => subscription.id);
15699
16153
  await deletePushSubscriptionsById(args.db, gone);
@@ -15713,12 +16167,6 @@ async function sendPushNotificationToUser(args) {
15713
16167
  return result;
15714
16168
  }
15715
16169
  // src/chat/notifications/task.ts
15716
- const PREVIEW_MAX_CHARS = 180;
15717
- /** Turn Markdown reply text into one short plain line for a notification. */
15718
- function notificationPreview(text) {
15719
- const plain = text.replace(/```[\s\S]*?```/g, " ").replace(/!\[[^\]]*\]\([^)]*\)/g, " ").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/[`*_~>#|]/g, "").replace(/\s+/g, " ").trim();
15720
- return plain.length > PREVIEW_MAX_CHARS ? `${plain.slice(0, 179).trimEnd()}…` : plain;
15721
- }
15722
16170
  /**
15723
16171
  * Return the stored reply of the Turn: the text that the person sees. The
15724
16172
  * run transcript has the raw model text, which can be a no-reply marker.
@@ -15728,11 +16176,15 @@ async function readTurnReply(run) {
15728
16176
  return projectConversationMessages(await getConversationEventStore().loadMessageHistory(run.conversationId)).filter((message) => message.role === "assistant" && message.id.startsWith(prefix)).at(-1);
15729
16177
  }
15730
16178
  /**
15731
- * Return the user to notify. The run context links Slack Actors to users. A
15732
- * dashboard Actor carries the verified sign-in email, so read its user by
15733
- * that email.
16179
+ * Return the starter: the User of the root's actor. Only a root runs
16180
+ * session tasks, so the run's Conversation is the root. A root from before
16181
+ * Conversations stored their actor has none, so the Actor of the run, who
16182
+ * sent the message, stands in. A dashboard Actor carries the verified
16183
+ * sign-in email, so read its user by that email.
15734
16184
  */
15735
- async function recipientUserId(db, run) {
16185
+ async function starterUserId(db, run) {
16186
+ const [root] = await db.select({ userId: juniorIdentities.userId }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).where(eq(juniorConversations.conversationId, run.conversationId)).limit(1);
16187
+ if (root?.userId) return root.userId;
15736
16188
  if (run.actorUserId) return run.actorUserId;
15737
16189
  if (run.actor?.platform !== "web" || !run.actor.email) return void 0;
15738
16190
  return (await findUserByEmailFromSql(db, run.actor.email))?.id;
@@ -15748,44 +16200,64 @@ function skip(reason) {
15748
16200
  logInfo("notification.reply.skipped", { "app.notification.skip_reason": reason });
15749
16201
  }
15750
16202
  /**
15751
- * Send a push notification to the Actor's user when a Turn finishes.
16203
+ * Turn the reply of a finished Turn into the reply notice of its starter,
16204
+ * and push the notice to them.
15752
16205
  *
15753
16206
  * Only Conversations without a Location qualify. A Conversation with a
15754
16207
  * Location, such as a Slack thread, already notifies people there.
15755
16208
  */
15756
16209
  async function notifyReply(context) {
15757
- const config = readWebPushConfig();
15758
- if (!config) return skip("not_configured");
15759
16210
  const run = await context.run.load();
15760
16211
  if (run.locationId) return skip("has_location");
15761
- const url = getDashboardConversationLink(run.conversationId);
15762
- if (!url) return skip("no_dashboard");
15763
16212
  const reply = await readTurnReply(run);
15764
16213
  if (!reply) return skip("no_reply");
15765
16214
  const db = context.db;
15766
- const userId = await recipientUserId(db, run);
16215
+ const userId = await starterUserId(db, run);
15767
16216
  if (!userId) return skip("no_user");
15768
- const nowMs = Date.now();
15769
- const schedule = await readNotificationSchedule(db, userId);
15770
- const pausedBySlack = schedule.followSlack !== false ? await isPausedBySlack(db, userId, nowMs) : void 0;
15771
- if (pausedBySlack) return skip("slack_paused");
15772
- if (pausedBySlack === void 0) {
15773
- const { timezone } = await resolveNotificationTimezone({
15774
- db,
15775
- nowMs,
15776
- schedule,
16217
+ if (await hasReadLatestReply(db, run.conversationId, userId)) {
16218
+ await closeReadReplyNotice(db, {
16219
+ conversationId: run.conversationId,
16220
+ nowMs: Date.now(),
15777
16221
  userId
15778
16222
  });
15779
- if (!isWithinNotificationSchedule(schedule, timezone, nowMs)) return skip("outside_hours");
16223
+ return skip("read");
16224
+ }
16225
+ const title = await readConversationTitle(db, run.conversationId) ?? botConfig.userName;
16226
+ const body = notificationPreview(reply.text) || "New reply";
16227
+ const itemId = await upsertReplyNotice(db, {
16228
+ body,
16229
+ conversationId: run.conversationId,
16230
+ nowMs: Date.now(),
16231
+ starterUserId: userId,
16232
+ title,
16233
+ turnId: run.runId
16234
+ });
16235
+ const config = readWebPushConfig();
16236
+ if (!config) return skip("not_configured");
16237
+ const url = getDashboardConversationLink(run.conversationId);
16238
+ if (!url) return skip("no_dashboard");
16239
+ const nowMs = Date.now();
16240
+ const pause = await readNotificationPause(db, userId, nowMs);
16241
+ await recordRepeatInboxItemPush(db, {
16242
+ event: "reply",
16243
+ itemId,
16244
+ nowMs,
16245
+ skipReason: pause,
16246
+ userId
16247
+ });
16248
+ if (pause) return skip(pause);
16249
+ if (!await isInboxItemOpen(db, itemId)) {
16250
+ await clearInboxItemDeliveries(db, [itemId], Date.now());
16251
+ return skip("read");
15780
16252
  }
15781
16253
  const result = await sendPushNotificationToUser({
15782
16254
  config,
15783
16255
  db,
15784
16256
  kind: "reply",
15785
16257
  payload: {
15786
- body: notificationPreview(reply.text) || "New reply",
15787
- tag: run.conversationId,
15788
- title: await readConversationTitle(db, run.conversationId) ?? botConfig.userName,
16258
+ body,
16259
+ tag: itemId,
16260
+ title,
15789
16261
  url
15790
16262
  },
15791
16263
  userId
@@ -15820,7 +16292,7 @@ const MAX_SUMMARY_CHARS = 1500;
15820
16292
  const relatedConversationSchema = z.object({
15821
16293
  channelName: z.string().optional(),
15822
16294
  conversationId: z.string(),
15823
- dashboardUrl: z.string().optional(),
16295
+ url: z.string().optional(),
15824
16296
  status: z.string(),
15825
16297
  summary: z.string(),
15826
16298
  title: z.string().optional(),
@@ -15832,7 +16304,7 @@ function renderConversation(conversation) {
15832
16304
  ...conversation.title ? [` title: ${conversation.title}`] : [],
15833
16305
  ` status: ${conversation.status}`,
15834
16306
  ...conversation.channelName ? [` channel_name: ${conversation.channelName}`] : [],
15835
- ...conversation.dashboardUrl ? [` dashboard_url: ${conversation.dashboardUrl}`] : [],
16307
+ ...conversation.url ? [` url: ${conversation.url}`] : [],
15836
16308
  ` updated_at: ${new Date(conversation.updatedAtMs).toISOString()}`,
15837
16309
  ` summary: ${conversation.summary.slice(0, MAX_SUMMARY_CHARS)}`
15838
16310
  ].join("\n");
@@ -15867,11 +16339,11 @@ async function isFirstRequest(ctx, conversationId) {
15867
16339
  return events.length === 0;
15868
16340
  }
15869
16341
  function toRelatedConversation(result) {
15870
- const dashboardUrl = getDashboardConversationLink(result.conversationId);
16342
+ const url = getDashboardConversationLink(result.conversationId);
15871
16343
  return {
15872
16344
  ...result.channelName ? { channelName: result.channelName } : void 0,
15873
16345
  conversationId: result.conversationId,
15874
- ...dashboardUrl ? { dashboardUrl } : void 0,
16346
+ ...url ? { url } : void 0,
15875
16347
  status: result.status === "failed" ? "idle" : result.status,
15876
16348
  summary: result.summary,
15877
16349
  ...result.title ? { title: result.title } : void 0,
@@ -16061,8 +16533,8 @@ function resolvePublicBaseUrl(publicBaseUrl) {
16061
16533
  * With `expiresAt`, the URL stops serving at that time.
16062
16534
  */
16063
16535
  async function publishImage(args) {
16064
- if (args.body.byteLength === 0) throw new ToolInputError("image is empty");
16065
- if (args.body.byteLength > MAX_IMAGE_BYTES) throw new ToolInputError(`image exceeds ${MAX_IMAGE_BYTES} bytes (${args.body.byteLength} bytes)`);
16536
+ if (args.body.byteLength === 0) throw new ToolInputError("The image file is empty. Write the image first, then publish it.");
16537
+ if (args.body.byteLength > MAX_IMAGE_BYTES) throw new ToolInputError(`image exceeds ${MAX_IMAGE_BYTES} bytes (${args.body.byteLength} bytes). Make the image smaller first.`);
16066
16538
  const contentType = detectImageMediaType(args.body);
16067
16539
  if (!contentType) throw new ToolInputError("unsupported image format; use PNG, JPEG, GIF, or WebP");
16068
16540
  const extension = IMAGE_EXTENSIONS[contentType];
@@ -16123,7 +16595,7 @@ async function unpublishArtifact(args) {
16123
16595
  const parsed = parseArtifactFilename(filename);
16124
16596
  if (!parsed) throw new ToolInputError("artifact ref must be a public artifact URL or <id>.<ext> filename");
16125
16597
  const now = args.now ?? /* @__PURE__ */ new Date();
16126
- if ((await args.db.db().update(juniorArtifacts).set({ deleteRequestedAt: now }).where(and(eq(juniorArtifacts.id, parsed.id), eq(juniorArtifacts.conversationId, args.conversationId))).returning({ id: juniorArtifacts.id })).length === 0) throw new ToolInputError(`artifact not found for this conversation: ${filename}`);
16598
+ if ((await args.db.db().update(juniorArtifacts).set({ deleteRequestedAt: now }).where(and(eq(juniorArtifacts.id, parsed.id), eq(juniorArtifacts.conversationId, args.conversationId))).returning({ id: juniorArtifacts.id })).length === 0) throw new ToolInputError(`artifact not found for this conversation: ${filename}. Pass the URL or filename that publishImage returned in this conversation.`);
16127
16599
  return { filename };
16128
16600
  }
16129
16601
  /** Open one public artifact by id when the row allows it. */
@@ -16280,7 +16752,7 @@ function pluginInvocationContext(context) {
16280
16752
  case "scheduled_automation":
16281
16753
  case "event_automation":
16282
16754
  case "plugin_dispatch":
16283
- case "agent_invocation": return {
16755
+ case "parent_message": return {
16284
16756
  ...common,
16285
16757
  actor: context.actor,
16286
16758
  destination: context.destination,
@@ -16748,7 +17220,7 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
16748
17220
  case "scheduled_automation":
16749
17221
  case "event_automation":
16750
17222
  case "plugin_dispatch":
16751
- case "agent_invocation": pluginContext = {
17223
+ case "parent_message": pluginContext = {
16752
17224
  ...common,
16753
17225
  actor: context.actor,
16754
17226
  destination: context.destination,
@@ -16856,6 +17328,10 @@ function getPluginRoutes(options) {
16856
17328
  plugin: pluginName
16857
17329
  }) },
16858
17330
  codeChanges: createCodeChangePublisher(pluginName),
17331
+ conversationChanges: createPluginConversationChanges({
17332
+ plugin: pluginName,
17333
+ show: options.showInboxItem ?? (async () => {})
17334
+ }),
16859
17335
  state: createPluginState(pluginName),
16860
17336
  inboxItems: { forConversation: (conversationId) => createPluginInboxItems({
16861
17337
  conversationId,
@@ -17422,6 +17898,7 @@ var ProviderCredentialRouter = class {
17422
17898
  if (!broker) throw new Error(`No credential broker registered for provider: ${input.provider}`);
17423
17899
  return await broker.issue({
17424
17900
  context: input.context,
17901
+ ...input.operation ? { operation: input.operation } : void 0,
17425
17902
  reason: input.reason
17426
17903
  });
17427
17904
  }
@@ -17664,7 +18141,7 @@ function authorizationForSandboxEgressGrant(provider, selection) {
17664
18141
  * cannot leave stale auth headers in place. The sandbox context only authorizes
17665
18142
  * the request.
17666
18143
  */
17667
- async function sandboxEgressCredentialLease(provider, selection, context) {
18144
+ async function sandboxEgressCredentialLease(provider, selection, context, operation) {
17668
18145
  const { grant } = selection;
17669
18146
  const cached = await getSandboxEgressCredentialLease(provider, grant, context);
17670
18147
  if (cached) {
@@ -17701,10 +18178,17 @@ async function sandboxEgressCredentialLease(provider, selection, context) {
17701
18178
  } else try {
17702
18179
  lease = await issueProviderCredentialLease({
17703
18180
  context: context.credentials,
18181
+ ...operation ? { operation } : void 0,
17704
18182
  provider,
17705
18183
  reason: grant.reason ?? `sandbox-egress:${provider}:default`
17706
18184
  });
17707
18185
  } catch (error) {
18186
+ if (error instanceof ServiceAccountUnavailableError) throw new SandboxEgressCredentialError({
18187
+ provider,
18188
+ grant,
18189
+ kind: "unavailable",
18190
+ message: error.message
18191
+ });
17708
18192
  if (error instanceof CredentialUnavailableError) throw new SandboxEgressCredentialError({
17709
18193
  provider,
17710
18194
  grant,
@@ -18131,7 +18615,7 @@ async function executeCredentialedEgressRequest(input) {
18131
18615
  }) };
18132
18616
  async function resolveLease() {
18133
18617
  try {
18134
- return await sandboxEgressCredentialLease(provider, grantSelection, credentialContext);
18618
+ return await sandboxEgressCredentialLease(provider, grantSelection, credentialContext, operation);
18135
18619
  } catch (error) {
18136
18620
  if (!(error instanceof SandboxEgressCredentialError)) throw error;
18137
18621
  const isAuthRequired = error.kind === "auth_required";
@@ -18305,4 +18789,4 @@ async function executeCredentialedEgressRequest(input) {
18305
18789
  }) };
18306
18790
  }
18307
18791
  }
18308
- export { SEARCHABLE_EVENT_TYPES as $, WORKSPACE_SNAPSHOT_FAILED_EVENT as $a, AutomationConflictError as $i, resolveUserTimezone as $n, registeredResourceTypeSchema as $o, updateSlackMessage as $r, isRetryableSandboxFailure as $t, deletePushSubscription as A, ownerConversationId as Aa, getDashboardSettingsLink as Ai, workspaceRepoCheckoutPath as An, getSlackClient as Ao, getDispatchConversationId as Ar, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as At, contentVersionHeaders as B, listFiringInboxSnoozeTriggers as Ba, findMatchingEventAutomations as Bi, readConversationMetadata as Bn, getWorkspaceTeamId as Bo, markDispatchCompleted as Br, listWorkspaces as Bt, unpublishArtifact as C, dismissOpenInboxItems as Ca, withScheduledAutomationLock as Ci, sandboxEgressSignalsResponseSchema as Cn, verifyScheduledAutomationCredentialSubject as Co, runNonInteractiveCommand as Cr, TURN_CONTEXT_TAG as Ct, readWebPushConfig as D, insertInboxItem as Da, getDashboardLinkFilter as Di, normalizeSandboxEgressTracePropagationDomains as Dn, downloadPrivateSlackFile as Do, claimDispatchMailboxAppend as Dr, resolveChannelCapabilities as Dt, coreRegistrations as E, inboxItemsNeedingUserVersionQuery as Ea, getDashboardInboxItemSnoozeLink as Ei, resolveSandboxEgressProviderForHost as En, SlackActionError as Eo, buildDispatchId as Er, createCodeChangePublisher as Et, isPausedBySlack as F, SNOOZE_TIMER_EVENT_TYPE as Fa, setDashboardConversationLinkOptions as Fi, createPluginTurnEventReader as Fn, readPrivateSlackFile as Fo, getPluginDispatchProjection as Fr, renderToolResultNudge as Ft, setEventEmbeddingsConfig as G, unsnoozeInboxRow as Ga, setEventAutomationStatus as Gi, embedConversationQuery as Gn, describeRegisteredEventTrigger as Go, deleteSlackMessage as Gr, loadSnapshotsForProfile as Gt, fuseRankedLists as H, settleInboxSnoozes as Ha, listDeletedEventAutomationsCreatedBy as Hi, resolveRootVisibility as Hn, updateTimerIndex as Ho, markDispatchRunning as Hr, updateWorkspace as Ht, projectConversationMessages as I, clearInboxWakeReasons as Ia, blockEventAutomation as Ii, createPluginConversationEvents as In, runWithSlackInstallationToken as Io, isTerminalDispatchStatus as Ir, createWorkspace as It, eventIndexLockKey as J, requireSlackChannelMessageScope as Ja, automationDefinition as Ji, createPluginAnnotations as Jn, eventWatchUnavailable as Jo, openSlackModal as Jr, create as Jt, EVENT_INDEX_LOCK_TTL_MS as K, getEventCatalog as Ka, admitEventAutomationRun as Ki, storeConversationEmbedding as Kn, eventGuidance as Ko, getSlackMessagePermalink as Kr, setWorkspaceSnapshot as Kt, setMemoryConfig as L, deleteExpiredInboxSnoozes as La, collectEventAutomationMatchKeys as Li, renderPluginConversationEvent as Ln, streamPrivateSlackFile as Lo, listPendingDispatchMailboxAppends as Lr, deleteWorkspace as Lt, readNotificationSchedule as M, takeInboxItem as Ma, isDashboardLink as Mi, createPluginEmbedder as Mn, isDmChannel as Mo, getDispatchInputMessageId as Mr, RESOURCE_WATCH_TOOL_SOURCE as Mt, saveNotificationSchedule as N, updateInboxItemContent as Na, parseDashboardConversationLink as Ni, createPluginModel as Nn, isSlackRequestTimeout as No, getDispatchRecord as Nr, STOP_WATCHING_TOOL_NAME as Nt, sendPushNotificationToUser as O, listReplyActionItems as Oa, getDashboardObjectIconLink as Oi, SANDBOX_RUNTIME as On, getFilePermalink as Oo, confirmDispatchMailboxAppend as Or, getSlackToolContext as Ot, savePushSubscription as P, waitingConversationIdsQuery as Pa, parseDashboardPersonLink as Pi, createPluginModelCostRecorder as Pn, normalizeSlackConversationId as Po, getDispatchTurnId as Pr, createPluginState as Pt, storeConversationEventLexemes as Q, slackChannelMessageTrigger as Qa, sameDefinitionValue as Qi, findActorTimezone as Qn, registeredEventTypeSchema as Qo, unfurlSlackLinks as Qr, getSandboxProvider as Qt, REVALIDATED_READ_PATHS as R, inboxItemInRow as Ra, createEventAutomation as Ri, searchConversations as Rn, withSlackRetries as Ro, markDispatchAwaitingResume as Rr, getWorkspace as Rt, readPublicArtifact as S, countInboxItemsNeedingUserBySubject as Sa, scheduledRunId as Si, parseSandboxEgressAuthRequiredSignal as Sn, verifyEventAutomationCredentialSubject as So, buildNonInteractiveShellScript as Sr, SESSION_CONTEXT_SECTION_TAG as St, apiRoutePrefix as T, getOpenInboxItemByDedupeKey as Ta, getDashboardInboxItemLink as Ti, resolveSandboxCommandEnvironment as Tn, verifyTimerWatchCredentialSubject as To, readConversationAutomationRun as Tr, createPluginInboxItems as Tt, event_embedding_config_exports as U, snoozeInboxItems as Ua, parseEventAutomationRow as Ui, backfillConversationEmbeddings as Un, CORE_EVENT_NAMESPACE as Uo, notifyAutomationBlocked as Ur, WorkspaceValidationError as Ut, revalidateContent as V, readViewerInboxSnoozes as Va, getEventAutomation as Vi, writeConversationMetadata as Vn, runWithWorkspaceTeamId as Vo, markDispatchFailed as Vr, listWorkspacesByRepository as Vt, isEventEmbeddingsEnabled as W, snoozeTimerTrigger as Wa, saveEventAutomation as Wi, createConversationEmbedder as Wn, automationEventCatalog as Wo, addReactionToMessage as Wr, invalidateReadySnapshot as Wt, searchedEventTextSql as X, slackChannelMessageReplyThreadTs as Xa, listAutomationVersions as Xi, listConversationAnnotationsById as Xn, registeredEventMatchSchema as Xo, postSlackMessage as Xr, isStale as Xt, lexemesSql as Y, slackChannelMessageEvent as Ya, automationVersionOf as Yi, listConversationAnnotations as Yn, hasEventCatalogEntries as Yo, postSlackEphemeralMessage as Yr, hash as Yt, seqIn as Z, slackChannelMessageRunsAutomation as Za, readAutomationVersion as Zi, defaultTimezone as Zn, registeredEventTriggerProblems as Zo, removeReactionFromMessage as Zr, ensureDockerDaemon as Zt, getStaticPluginToolDefinitions as _, fallbackShortTitle as _a, listScheduledAutomationsForTeam as _i, clearSandboxEgressSignals as _n, takeDueTimerWatches as _o, SANDBOX_WORKSPACE_ROOT as _r, renderJuniorNativeConversationEvent as _s, retainRuntimeTurnContext as _t, agent_hooks_exports as a, readAutomationExecutionStatusDays as aa, escapeSlackMrkdwnText as ai, resolveBaseUrl as an, publishConversationStatus as ao, lookupActiveSlackWorkspaceMember as ar, createPluginCache as as, getPiMessageRole as at, publicArtifactHeaders as b, INBOX_ITEM_REPLIED_REASON as ba, saveScheduledAutomation as bi, createSandboxEgressCredentialToken as bn, bindScheduledAutomationCredentialSubject as bo, sandboxSkillPathResolution as br, CAPABILITY_SECTION_TAG as bt, createPluginHookRunner as c, readAutomationExecutions as ca, normalizeSlackReplyMarkdown as ci, findInErrorChain as cn, collectEventMatchKeys as co, userLookupIdentityProviders as cr, completeText as cs, hasRuntimeTurnContext as ct, getPluginSlackConversationLink as d, readAutomationTitlesByConversationId as da, slackMentionedUserIds as di, throwSandboxOperationError as dn, deliverWatch as do, ATTACHMENT_DIR as dr, transcribeFromUrl as ds, isAssistantMessage as dt, automationRevision as ea, uploadFilesToConversation as ei, isVercelSandboxEgressRequest as en, WORKSPACE_SNAPSHOT_READY_EVENT as eo, lookupSlackUser as er, requireEventIdentifier as es, callsToolSql as et, getPluginSystemPromptContributions as f, recordAutomationExecution as fa, wrapBareSlackUserIds as fi, wrapSandboxSetupError as fn, findMatchingWatches as fo, SANDBOX_COMMAND_PATH as fr, NoAudioError as fs, isContinuablePiBoundary as ft, getRegistrations as g, syncAutomationAlerts as ga, deleteScheduledAutomation as gi, workspaceSnapshotNotReadyUserMessage as gn, listWatches as go, SANDBOX_SKILLS_ROOT as gr, conversationNoteEvent as gs, normalizeToolNameFromResult as gt, getPlugins as h, AUTOMATION_ALERT_STEP_FIELD_ID as ha, createScheduledAutomation as hi, isWorkspaceSnapshotNotReadyError as hn, listConversationsWithWatches as ho, SANDBOX_SCRATCH_ROOT as hr, authenticationLinkedEvent as hs, isToolResultMessage as ht, resolvePluginOAuthAccount as i, readAutomationExecutionByConversationId as ia, SLACK_USER_MENTION_RE as ii, parseOAuthStatePayload as in, conversationWatch as io, lookupUsers as ir, credentialAuditSource as is, extractAssistantText as it, listPushSubscriptions as j, searchInboxItems as ja, getDashboardTaskLink as ji, PluginToolDeniedError as jn, isConversationScopedChannel as jo, getDispatchIdForConversation as jr, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as jt, resolveNotificationTimezone as k, listWaitingConversations as ka, getDashboardPersonLink as ki, tryWorkspaceRepoCheckoutPath as kn, getHeaderString as ko, createOrGetDispatch as kr, createPluginConversationWatches as kt, getPluginApiRoutes as l, readAutomationRowStats as la, normalizeSlackStatusText as li, isAbortError as ln, createTimerWatch as lo, basePluginContext$1 as lr, generateImages as ls, hasTurnInput as lt, getPluginUserPromptContributions as m, AUTOMATION_ALERT_STEPS as ma, blockScheduledAutomation as mi, getWorkspaceSnapshotNotReadyError as mn, isQuietEvent as mo, SANDBOX_REPOS_ROOT as mr, agentsInstructionsUpdatedEvent as ms, isToolResultError as mt, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as n, emptyAutomationRunWindows as na, slackEntitySchema as ni, deliverOAuthAuthorization as nn, workspaceSnapshotWatch as no, isSlackUserNotFound as nr, JUNIOR_THREAD_STATE_TTL_MS as ns, excerptTerms as nt, applyPluginFormatMarkdown as o, readAutomationExecutionStatusHours as oa, formatSlackLink as oi, startOAuthFlow as on, cancelSubscriptions as oo, lookupSlackBot as or, completeDecision as os, getTerminalAssistantMessages as ot, getPluginTools as p, refreshAutomationLastRun as pa, truncateStatusText as pi, WorkspaceSnapshotNotReadyError as pn, getWatch as po, SANDBOX_DATA_ROOT as pr, JUNIOR_NATIVE_EVENT_NAMESPACE as ps, isStandaloneRuntimeContextMessage as pt, embedConversationEvents as q, SLACK_EVENT_NAMESPACE as qa, eventAutomationRunLimitReason as qi, saveObjectAnnotations as qn, eventNamespaceSchema as qo, openSlackDirectMessage as qr, setWorkspaceSnapshotBuild as qt, createUserTokenStore as r, existingConversationId as ra, slackExternalRefIdSchema as ri, formatProviderLabel as rn, CONVERSATION_RESOURCE_TYPE as ro, looksLikeEmail as rr, credentialAuditAttributes as rs, storedMessageJson as rt, createPluginEventPublisher as s, readAutomationExecutionSummaries as sa, isTableRow as si, SandboxCallTimeoutError as sn, cancelWatch as so, lookupSlackUserProfile as sr, completeObject as ss, getUserMessageInstructionText as st, executeCredentialedEgressRequest as t, requireAutomationRevision as ta, fitsSlackMetadataLimit as ti, proxyVercelSandboxEgressRequest as tn, workspaceSnapshotFinishedEvent as to, lookupSlackUserNames as tr, requireValidEventTrigger as ts, eventExcerpt as tt, getPluginRoutes as u, readAutomationRuns as ua, slackMention as ui, isAlreadyExistsError as un, createWatch as uo, pluginConfigValues as ur, searchWeb as us, instructionTextForProjection as ut, setPlugins as v, generateShortTitle as va, parseScheduledAutomationRow as vi, consumeSandboxEgressAuthRequiredSignal as vn, turnEvents as vo, sandboxSkillDir as vr, getConfigDefaults as vs, stripRuntimeTurnContext as vt, unpublishedArtifactHeaders as w, getInboxItem as wa, getDashboardConversationLink as wi, buildSandboxEgressNetworkPolicy as wn, verifySlackDirectCredentialSubject as wo, createPluginLogger as wr, PLUGIN_CHOICE_FIELD_ID as wt, publishImage as x, closeInboxItem as xa, saveScheduledAutomationInLock as xi, parseSandboxEgressCredentialToken as xn, bindSlackDirectCredentialSubject as xo, buildCommandScript as xr, REQUEST_CONTEXT_SECTION_TAG as xt, validatePlugins as y, resolveTaskTitle as ya, readScheduledAutomation as yi, consumeSandboxEgressPermissionDeniedSignal as yn, bindEventAutomationCredentialSubject as yo, sandboxSkillFile as yr, setConfigDefaults as ys, trimTrailingAssistantMessages as yt, contentVersion as z, inboxItemSnoozedBy as za, deleteEventAutomation as zi, conversationSearchVector as zn, sleep$1 as zo, markDispatchBlocked as zr, getWorkspaceByName as zt };
18792
+ export { rankSearchMatches as $, recordRepeatInboxItemPush as $a, deleteEventAutomation as $i, resolveRootVisibility as $n, normalizeSlackConversationId as $o, markDispatchBlocked as $r, updateWorkspace as $t, readNotificationPause as A, syncAutomationAlerts as Aa, deleteScheduledAutomation as Ai, consumeSandboxEgressPermissionDeniedSignal as An, deliverWatch as Ao, SANDBOX_SKILLS_ROOT as Ar, transcribeFromUrl as As, retainRuntimeTurnContext as At, projectConversationMessages as B, inboxItemNeedsUserNow as Ba, getDashboardInboxItemSnoozeLink as Bi, tryWorkspaceRepoCheckoutPath as Bn, bindSlackDirectCredentialSubject as Bo, buildDispatchId as Br, createPluginConversationWatches as Bt, unpublishArtifact as C, readAutomationRowStats as Ca, normalizeSlackStatusText as Ci, wrapSandboxSetupError as Cn, conversationWatch as Co, basePluginContext$1 as Cr, credentialAuditSource as Cs, instructionTextForProjection as Ct, readWebPushConfig as D, refreshAutomationLastRun as Da, truncateStatusText as Di, workspaceSnapshotNotReadyUserMessage as Dn, collectEventMatchKeys as Do, SANDBOX_DATA_ROOT as Dr, completeText as Ds, isToolResultError as Dt, coreRegistrations as E, recordAutomationExecution as Ea, wrapBareSlackUserIds as Ei, isWorkspaceSnapshotNotReadyError as En, cancelWatch as Eo, SANDBOX_COMMAND_PATH as Er, completeObject as Es, isStandaloneRuntimeContextMessage as Et, saveNotificationSchedule as F, closeInboxItem as Fa, saveScheduledAutomationInLock as Fi, buildSandboxEgressNetworkPolicy as Fn, listWatches as Fo, buildCommandScript as Fr, conversationNoteEvent as Fs, SESSION_CONTEXT_SECTION_TAG as Ft, revalidateContent as G, ownerConversationId as Ga, getDashboardTaskLink as Gi, createPluginModelCostRecorder as Gn, SlackActionError as Go, getDispatchIdForConversation as Gr, createPluginState as Gt, REVALIDATED_READ_PATHS as H, insertInboxItem as Ha, getDashboardObjectIconLink as Hi, PluginToolDeniedError as Hn, verifyScheduledAutomationCredentialSubject as Ho, confirmDispatchMailboxAppend as Hr, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Ht, savePushSubscription as I, countInboxItemsNeedingUserBySubject as Ia, scheduledRunId as Ii, resolveSandboxCommandEnvironment as In, takeDueTimerWatches as Io, buildNonInteractiveShellScript as Ir, renderJuniorNativeConversationEvent as Is, TURN_CONTEXT_TAG as It, parseTypedQuery as J, updateInboxItemContent as Ja, parseDashboardPersonLink as Ji, renderPluginConversationEvent as Jn, getHeaderString as Jo, getDispatchTurnId as Jr, deleteWorkspace as Jt, memoryDb as K, searchInboxItems as Ka, isDashboardLink as Ki, createPluginTurnEventReader as Kn, downloadPrivateSlackFile as Ko, getDispatchInputMessageId as Kr, renderToolResultNudge as Kt, isActiveInSlack as L, dismissOpenInboxItems as La, withScheduledAutomationLock as Li, resolveSandboxEgressProviderForHost as Ln, turnEvents as Lo, runNonInteractiveCommand as Lr, getConfigDefaults as Ls, createCodeChangePublisher as Lt, deletePushSubscription as M, generateShortTitle as Ma, parseScheduledAutomationRow as Mi, parseSandboxEgressCredentialToken as Mn, getWatch as Mo, sandboxSkillDir as Mr, JUNIOR_NATIVE_EVENT_NAMESPACE as Ms, trimTrailingAssistantMessages as Mt, listPushSubscriptions as N, resolveTaskTitle as Na, readScheduledAutomation as Ni, parseSandboxEgressAuthRequiredSignal as Nn, isQuietEvent as No, sandboxSkillFile as Nr, agentsInstructionsUpdatedEvent as Ns, CAPABILITY_SECTION_TAG as Nt, sendPushNotificationToUser as O, AUTOMATION_ALERT_STEPS as Oa, blockScheduledAutomation as Oi, clearSandboxEgressSignals as On, createTimerWatch as Oo, SANDBOX_REPOS_ROOT as Or, generateImages as Os, isToolResultMessage as Ot, readNotificationSchedule as P, INBOX_ITEM_REPLIED_REASON as Pa, saveScheduledAutomation as Pi, sandboxEgressSignalsResponseSchema as Pn, listConversationsWithWatches as Po, sandboxSkillPathResolution as Pr, authenticationLinkedEvent as Ps, REQUEST_CONTEXT_SECTION_TAG as Pt, prefixRank as Q, recordInboxItemSlackCard as Qa, createEventAutomation as Qi, writeConversationMetadata as Qn, isSlackRequestTimeout as Qo, markDispatchAwaitingResume as Qr, listWorkspacesByRepository as Qt, isPausedBySlack as R, getInboxItem as Ra, getDashboardConversationLink as Ri, normalizeSandboxEgressTracePropagationDomains as Rn, bindEventAutomationCredentialSubject as Ro, createPluginLogger as Rr, setConfigDefaults as Rs, resolveChannelCapabilities as Rt, readPublicArtifact as S, readAutomationExecutions as Sa, normalizeSlackReplyMarkdown as Si, throwSandboxOperationError as Sn, CONVERSATION_RESOURCE_TYPE as So, userLookupIdentityProviders as Sr, credentialAuditAttributes as Ss, hasTurnInput as St, apiRoutePrefix as T, readAutomationTitlesByConversationId as Ta, slackMentionedUserIds as Ti, getWorkspaceSnapshotNotReadyError as Tn, cancelSubscriptions as To, ATTACHMENT_DIR as Tr, completeDecision as Ts, isContinuablePiBoundary as Tt, contentVersion as U, isInboxItemOpen as Ua, getDashboardPersonLink as Ui, createPluginEmbedder as Un, verifySlackDirectCredentialSubject as Uo, createOrGetDispatch as Ur, RESOURCE_WATCH_TOOL_SOURCE as Ut, setMemoryConfig as V, inboxItemsNeedingUserVersionQuery as Va, getDashboardLinkFilter as Vi, workspaceRepoCheckoutPath as Vn, verifyEventAutomationCredentialSubject as Vo, claimDispatchMailboxAppend as Vr, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Vt, contentVersionHeaders as W, listReplyActionItems as Wa, getDashboardSettingsLink as Wi, createPluginModel as Wn, verifyTimerWatchCredentialSubject as Wo, getDispatchConversationId as Wr, STOP_WATCHING_TOOL_NAME as Wt, fuzzyRank as X, clearInboxItemDeliveries as Xa, blockEventAutomation as Xi, conversationSearchVector as Xn, isConversationScopedChannel as Xo, isTerminalDispatchStatus as Xr, getWorkspaceByName as Xt, fuzzyMatch as Y, claimInboxItemPush as Ya, setDashboardConversationLinkOptions as Yi, searchConversations as Yn, getSlackClient as Yo, getPluginDispatchProjection as Yr, getWorkspace as Yt, prefixMatch as Z, listInboxItemPushUserIds as Za, collectEventAutomationMatchKeys as Zi, readConversationMetadata as Zn, isDmChannel as Zo, listPendingDispatchMailboxAppends as Zr, listWorkspaces as Zt, getStaticPluginToolDefinitions as _, existingConversationId as _a, slackExternalRefIdSchema as _i, startOAuthFlow as _n, slackChannelMessageTrigger as _o, looksLikeEmail as _r, registeredEventTypeSchema as _s, extractAssistantText as _t, agent_hooks_exports as a, setEventAutomationStatus as aa, deleteSlackMessage as ai, create as an, listFiringInboxSnoozeTriggers as ao, createPluginConversationChanges as ar, getWorkspaceTeamId as as, EVENT_INDEX_LOCK_TTL_MS as at, publicArtifactHeaders as b, readAutomationExecutionStatusHours as ba, formatSlackLink as bi, isAbortError as bn, workspaceSnapshotFinishedEvent as bo, lookupSlackBot as br, requireValidEventTrigger as bs, getUserMessageInstructionText as bt, createPluginHookRunner as c, automationDefinition as ca, openSlackModal as ci, ensureDockerDaemon as cn, snoozeInboxItems as co, createPluginAnnotations as cr, CORE_EVENT_NAMESPACE as cs, lexemesSql as ct, getPluginSlackConversationLink as d, readAutomationVersion as da, removeReactionFromMessage as di, isVercelSandboxEgressRequest as dn, getEventCatalog as do, defaultTimezone as dr, eventGuidance as ds, storeConversationEventLexemes as dt, findMatchingEventAutomations as ea, markDispatchCompleted as ei, WorkspaceValidationError as en, SNOOZE_TIMER_EVENT_TYPE as eo, backfillConversationEmbeddings as er, readPrivateSlackFile as es, scoredSearchMatches as et, getPluginSystemPromptContributions as f, sameDefinitionValue as fa, unfurlSlackLinks as fi, proxyVercelSandboxEgressRequest as fn, SLACK_EVENT_NAMESPACE as fo, findActorTimezone as fr, eventNamespaceSchema as fs, SEARCHABLE_EVENT_TYPES as ft, getRegistrations as g, emptyAutomationRunWindows as ga, slackEntitySchema as gi, resolveBaseUrl as gn, slackChannelMessageRunsAutomation as go, isSlackUserNotFound as gr, registeredEventTriggerProblems as gs, storedMessageJson as gt, getPlugins as h, requireAutomationRevision as ha, fitsSlackMetadataLimit as hi, parseOAuthStatePayload as hn, slackChannelMessageReplyThreadTs as ho, lookupSlackUserNames as hr, registeredEventMatchSchema as hs, excerptTerms as ht, resolvePluginOAuthAccount as i, saveEventAutomation as ia, addReactionToMessage as ii, setWorkspaceSnapshotBuild as in, inboxItemSnoozedBy as io, saveObjectAnnotations as ir, sleep$1 as is, setEventEmbeddingsConfig as it, resolveNotificationTimezone as j, fallbackShortTitle as ja, listScheduledAutomationsForTeam as ji, createSandboxEgressCredentialToken as jn, findMatchingWatches as jo, SANDBOX_WORKSPACE_ROOT as jr, NoAudioError as js, stripRuntimeTurnContext as jt, notificationPreview as k, AUTOMATION_ALERT_STEP_FIELD_ID as ka, createScheduledAutomation as ki, consumeSandboxEgressAuthRequiredSignal as kn, createWatch as ko, SANDBOX_SCRATCH_ROOT as kr, searchWeb as ks, normalizeToolNameFromResult as kt, getPluginApiRoutes as l, automationVersionOf as la, postSlackEphemeralMessage as li, getSandboxProvider as ln, snoozeTimerTrigger as lo, listConversationAnnotations as lr, automationEventCatalog as ls, searchedEventTextSql as lt, getPluginUserPromptContributions as m, automationRevision as ma, uploadFilesToConversation as mi, formatProviderLabel as mn, slackChannelMessageEvent as mo, lookupSlackUser as mr, hasEventCatalogEntries as ms, eventExcerpt as mt, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as n, listDeletedEventAutomationsCreatedBy as na, markDispatchRunning as ni, loadSnapshotsForProfile as nn, deleteExpiredInboxSnoozes as no, embedConversationQuery as nr, streamPrivateSlackFile as ns, event_embedding_config_exports as nt, applyPluginFormatMarkdown as o, admitEventAutomationRun as oa, getSlackMessagePermalink as oi, hash as on, readViewerInboxSnoozes as oo, PLUGIN_CHOICE_FIELD_ID as or, runWithWorkspaceTeamId as os, embedConversationEvents as ot, getPluginTools as p, AutomationConflictError as pa, updateSlackMessage as pi, deliverOAuthAuthorization as pn, requireSlackChannelMessageScope as po, resolveUserTimezone as pr, eventWatchUnavailable as ps, callsToolSql as pt, searchTypedMemories as q, takeInboxItem as qa, parseDashboardConversationLink as qi, createPluginConversationEvents as qn, getFilePermalink as qo, getDispatchRecord as qr, createWorkspace as qt, createUserTokenStore as r, parseEventAutomationRow as ra, notifyAutomationBlocked as ri, setWorkspaceSnapshot as rn, inboxItemInRow as ro, storeConversationEmbedding as rr, withSlackRetries as rs, isEventEmbeddingsEnabled as rt, createPluginEventPublisher as s, eventAutomationRunLimitReason as sa, openSlackDirectMessage as si, isStale as sn, settleInboxSnoozes as so, createPluginInboxItems as sr, updateTimerIndex as ss, eventIndexLockKey as st, executeCredentialedEgressRequest as t, getEventAutomation as ta, markDispatchFailed as ti, invalidateReadySnapshot as tn, clearInboxWakeReasons as to, createConversationEmbedder as tr, runWithSlackInstallationToken as ts, fuseRankedLists as tt, getPluginRoutes as u, listAutomationVersions as ua, postSlackMessage as ui, isRetryableSandboxFailure as un, unsnoozeInboxRow as uo, listConversationAnnotationsById as ur, describeRegisteredEventTrigger as us, seqIn as ut, setPlugins as v, readAutomationExecutionByConversationId as va, SLACK_USER_MENTION_RE as vi, SandboxCallTimeoutError as vn, WORKSPACE_SNAPSHOT_FAILED_EVENT as vo, lookupUsers as vr, registeredResourceTypeSchema as vs, getPiMessageRole as vt, unpublishedArtifactHeaders as w, readAutomationRuns as wa, slackMention as wi, WorkspaceSnapshotNotReadyError as wn, publishAgentUpdate as wo, pluginConfigValues as wr, createPluginCache as ws, isAssistantMessage as wt, publishImage as x, readAutomationExecutionSummaries as xa, isTableRow as xi, isAlreadyExistsError as xn, workspaceSnapshotWatch as xo, lookupSlackUserProfile as xr, JUNIOR_THREAD_STATE_TTL_MS as xs, hasRuntimeTurnContext as xt, validatePlugins as y, readAutomationExecutionStatusDays as ya, escapeSlackMrkdwnText as yi, findInErrorChain as yn, WORKSPACE_SNAPSHOT_READY_EVENT as yo, lookupActiveSlackWorkspaceMember as yr, requireEventIdentifier as ys, getTerminalAssistantMessages as yt, closeReadReplyNotice as z, getOpenInboxItemByDedupeKey as za, getDashboardInboxItemLink as zi, SANDBOX_RUNTIME as zn, bindScheduledAutomationCredentialSubject as zo, readConversationAutomationRun as zr, getSlackToolContext as zt };