@sentry/junior 0.320.0 → 0.322.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 (65) hide show
  1. package/dist/{adapter-DlLLoJKj.js → adapter-CKtEUuWD.js} +23 -2
  2. package/dist/{admin-BzRXDVfh.js → admin-BGOiUGwR.js} +1 -1
  3. package/dist/{agent-DxZ7nHfD.js → agent-OUkEw6Bv.js} +276 -1648
  4. package/dist/{agent-status-Bq_AIpyp.js → agent-status-C_HHxO_d.js} +1 -10
  5. package/dist/{agent-update-delivery-CO4FU5Gg.js → agent-update-delivery-H6mnPI4q.js} +4 -4
  6. package/dist/api/schema.d.ts +98 -16
  7. package/dist/api/schema.js +6 -6
  8. package/dist/api.js +81 -36
  9. package/dist/{app-CHCFIIDu.d.ts → app-BK_vhZIq.d.ts} +1 -1
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +85 -48
  12. package/dist/{change-record-K-KsqNhT.d.ts → change-record-DdrJxahk.d.ts} +26 -15
  13. package/dist/{channel-access-BghWqlXx.js → channel-access-DRhVJIuQ.js} +1 -1
  14. package/dist/{chat-core-engine-BgfSLrDu.js → chat-core-engine-El308gYr.js} +5 -10
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +4 -4
  17. package/dist/cli/main.js +2 -2
  18. package/dist/cli/plugins.js +3 -3
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.js +2 -2
  21. package/dist/{continue-in-slack-DBlQP4PC.js → continue-in-slack-DYl631oM.js} +3 -3
  22. package/dist/{conversation-feed-DEUdD7mb.js → conversation-feed-BUaMmSLi.js} +2 -12
  23. package/dist/{conversation-privacy-qoh95v90.js → conversation-privacy-DR_j5Tqf.js} +1 -1
  24. package/dist/{create-jZSaDrCR.js → create-ZkI-_JAs.js} +2 -2
  25. package/dist/{credential-sync-Bj9-UlNE.js → credential-sync-Bo6_FtCI.js} +12 -12
  26. package/dist/{db-BacvswT0.js → db-RDpWIeRK.js} +1744 -216
  27. package/dist/{deployment-BoJkRPDt.js → deployment-CeKaP0ZJ.js} +1 -1
  28. package/dist/{html-DW0pw5Pr.js → html-BMv4fAPu.js} +5 -5
  29. package/dist/instrumentation.js +2 -2
  30. package/dist/{list-Dz3CdP3g.js → list-CuLf7Ob2.js} +39 -70
  31. package/dist/{logging-DsTnMqyi.js → logging-BQsfrLHl.js} +1 -1
  32. package/dist/{markers-C33gNYNE.js → markers-Bh0vqJ5k.js} +3186 -1754
  33. package/dist/nitro.d.ts +1 -1
  34. package/dist/nitro.js +3 -4
  35. package/dist/{oauth-callback-server-C-pEhAQK.js → oauth-callback-server-BxuN0Jqz.js} +2 -2
  36. package/dist/{oauth-relay-DIXdH-io.js → oauth-relay-vyG2gOwY.js} +1 -1
  37. package/dist/{profile-v9vA3RvH.js → profile-DiAB4QfT.js} +39 -8
  38. package/dist/{prompt-C5CW2wKO.js → prompt-5PDkRQ1K.js} +2 -1
  39. package/dist/{reports-eBgrhPXS.js → reports-CbqB7unq.js} +2 -2
  40. package/dist/{resolve-HVXmbeCr.js → resolve-C7e0pwuP.js} +5 -5
  41. package/dist/{result-BPNzgeTl.js → result-D_D-2Adp.js} +7 -7
  42. package/dist/{runner-aNSDTST6.js → runner-CCVTdp0x.js} +7 -7
  43. package/dist/{sandbox-egress-signals-nzp9Ykf7.js → sandbox-egress-signals-D4OKOFgy.js} +1 -1
  44. package/dist/{schema-BlTO5M1d.js → schema-CmPO8BfI.js} +50 -12
  45. package/dist/{service-account-DWIf1t6p.js → service-account-CeWsFrBi.js} +2 -2
  46. package/dist/{skills-50izzzdK.js → skills-DfbOjWxl.js} +5 -5
  47. package/dist/{slack-conversation-unfurl-C6jXhVYg.js → slack-conversation-unfurl-BxF0Yb3-.js} +10 -9
  48. package/dist/{system-prompt-table-CIR1B44Z.js → system-prompt-table-DySHMtu0.js} +17 -17
  49. package/dist/{topics-DxuKurCX.js → topic-ChZe9WPj.js} +6 -1
  50. package/dist/{engine-context-Bi3Ync5t.js → turn-ended-DQ10G3in.js} +11 -845
  51. package/dist/{types-BNHkJrOP.js → types-BWAgOJtR.js} +95 -78
  52. package/dist/{user-customization-CvfuY9Eo.js → user-customization-DNzu_r1x.js} +10 -1
  53. package/dist/{users-DOVo9sdU.js → users-BmZlg_ci.js} +13 -7
  54. package/dist/{validation-CK0vuEHB.js → validation-BU4tXvH3.js} +1 -1
  55. package/dist/{version-BuLVNlxB.js → version-D9yLYOBu.js} +1 -1
  56. package/dist/version.js +1 -1
  57. package/dist/{worker-C82kHU1R.js → worker-C7EDSL3d.js} +4 -4
  58. package/migrations/20261127184420_question_answerer/migration.sql +36 -0
  59. package/migrations/20261127184420_question_answerer/snapshot.json +108 -0
  60. package/migrations/20261127224730_inbox_item_close_action/migration.sql +1 -0
  61. package/migrations/20261127224730_inbox_item_close_action/snapshot.json +42 -0
  62. package/package.json +6 -6
  63. package/skills/design-automation-skill/SKILL.md +1 -1
  64. package/dist/storage-BtCxXiNt.js +0 -273
  65. package/dist/topic-B2EWKKBT.js +0 -6
@@ -1,19 +1,21 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $ as resolveGatewayModel, B as getSlackBotToken, C as parseActorUserId, D as parseSlackChannelReferenceId, J as normalizeSlackEmojiName, L as botConfig, O as parseSlackTeamId, P as parseSlackMessageTs, Q as findGatewayModel, R as getChatConfig, S as isUserActor, Y as TURN_REASONING_LEVELS, Z as GATEWAY_PROVIDER, a as getStateValues, at as streamSimpleAnthropic, b as isActorUserId, et as calculateCost, g as credentialUserSubjectId, h as credentialSubjectSchema, i as getStateAdapter, it as streamAnthropic, k as parseSlackUserId, l as fenceLock, nt as getEnvApiKey, o as setStateValues, p as credentialContextSchema, r as getDefaultRedisStateAdapterFor, rt as registerApiProvider, s as MUTATION_LOCK_TTL_MS, tt as completeSimple, u as withLock, v as createSlackActor, w as parseStoredSlackActor, x as isSlackUserId } from "./adapter-DlLLoJKj.js";
3
- import { A as automationVersionSchema, An as DEFAULT_NOTIFICATION_SCHEDULE, Bn as AGENT_UPDATE_EVENT_TYPE, Dn as automationTaskDescription, En as automationTaskColumns, Gn as gatewayOnlyProviders, In as isValidTimeZone, Kn as usageSchema, Ln as CONTENT_VERSION_HEADER, Mn as notificationScheduleSchema, On as automationTaskSchema, Tn as automationSkillNameSchema, Tt as sameActorIdentity, _t as historyReplacementSchema, a as UPDATE_TODOS_TOOL_NAME, dn as eventAutomationTriggerSchema, ft as encodeAgentHistoryPayload, gn as USER_INPUT_NOTE, hn as USER_INPUT_LIMITS, i as TODO_STATUSES, jn as isWithinNotificationSchedule, lt as decodeStoredConversationEvent, mn as inboxItemRequestSchema, n as SELF_TODO_ASSIGNEE, o as isOpenTodoStatus, ot as conversationEventDataSchema, pn as inboxItemQuestion, pt as isAgentHistoryData, r as TODOS_REGISTRATION_NAME, rn as scheduledAutomationSchema, rt as agentTypeSchema, t as OPEN_TODO_STATUSES, un as eventAutomationSchema, ut as newConversationEventSchema, vn as buttonUserInputField, xn as normalizeUserInputAnswer, zt as inboxItemChangeRecordSchema } from "./types-BNHkJrOP.js";
4
- import { _ as toOptionalTrimmed, d as pluginRoots, i as PLUGIN_TASK_QUEUE_TOPIC, o as discoverInstalledPluginPackageContent, s as normalizePluginPackageNames } from "./topics-DxuKurCX.js";
5
- import { A as toOptionalString, D as GOOGLE_IDENTITY_PROVIDER, T as withSpan, _ as serializeGenAiAttribute, b as setSpanStatus, f as logException, g as runBestEffort, i as extractGenAiUsageSummary, k as normalizeIdentityEmail, m as logWarn, p as logInfo, r as extractGenAiUsageAttributes, s as getLogContextAttributes, y as setSpanAttributes } from "./logging-DsTnMqyi.js";
6
- import { G as mapBounded, R as unwrapCurrentInstruction, d as SANDBOX_WORKSPACE_ROOT, g as RUNTIME_CONTEXT_TEXT_STARTS, h as createPluginLogger, n as toPromptContributionContext, r as runPluginHooksAtOnce, s as SANDBOX_JUNIOR_ROOT } from "./prompt-C5CW2wKO.js";
7
- import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-qoh95v90.js";
2
+ import { $ as resolveGatewayModel, B as getSlackBotToken, C as parseActorUserId, D as parseSlackChannelReferenceId, E as parseSlackChannelId, J as normalizeSlackEmojiName, L as botConfig, O as parseSlackTeamId, P as parseSlackMessageTs, Q as findGatewayModel, R as getChatConfig, S as isUserActor, Y as TURN_REASONING_LEVELS, Z as GATEWAY_PROVIDER, a as getStateValues, at as streamSimpleAnthropic, b as isActorUserId, et as calculateCost, g as credentialUserSubjectId, h as credentialSubjectSchema, i as getStateAdapter, it as streamAnthropic, k as parseSlackUserId, l as fenceLock, nt as getEnvApiKey, o as setStateValues, p as credentialContextSchema, r as getDefaultRedisStateAdapterFor, rt as registerApiProvider, s as MUTATION_LOCK_TTL_MS, tt as completeSimple, u as withLock, v as createSlackActor, w as parseStoredSlackActor, x as isSlackUserId } from "./adapter-CKtEUuWD.js";
3
+ import { A as automationVersionSchema, Bt as inboxItemChangeRecordSchema, Dn as automationTaskColumns, En as automationSkillNameSchema, Jn as usageTokensSchema, Kn as gatewayOnlyProviders, Ln as isValidTimeZone, Mn as isWithinNotificationSchedule, Nn as notificationScheduleSchema, On as automationTaskDescription, Rn as CONTENT_VERSION_HEADER, St as contextProvenance, Tt as sameActorIdentity, Vn as AGENT_UPDATE_EVENT_TYPE, _n as inboxItemQuestion, _t as historyReplacementSchema, a as UPDATE_TODOS_TOOL_NAME, bn as USER_INPUT_NOTE, dn as eventAutomationSchema, dt as agentHistoryFromRow, fn as eventAutomationTriggerSchema, ft as encodeAgentHistoryPayload, gt as historyItemFromPiMessage, i as TODO_STATUSES, in as scheduledAutomationSchema, jn as DEFAULT_NOTIFICATION_SCHEDULE, kn as automationTaskSchema, lt as decodeStoredConversationEvent, n as SELF_TODO_ASSIGNEE, o as isOpenTodoStatus, ot as conversationEventDataSchema, pt as isAgentHistoryData, qn as usageSchema, r as TODOS_REGISTRATION_NAME, rt as agentTypeSchema, t as OPEN_TODO_STATUSES, ut as newConversationEventSchema, vn as inboxItemRequestSchema, wn as normalizeUserInputAnswer, xn as buttonUserInputField, yn as USER_INPUT_LIMITS, yt as piMessageFromHistoryItem } from "./types-BWAgOJtR.js";
4
+ import { c as discoverInstalledPluginPackageContent, l as normalizePluginPackageNames, n as TURN_STEP_TOPIC, o as PLUGIN_TASK_QUEUE_TOPIC, p as pluginRoots, t as TURN_ENDED_TOPIC, y as toOptionalTrimmed } from "./topic-ChZe9WPj.js";
5
+ import { A as toOptionalString, D as GOOGLE_IDENTITY_PROVIDER, T as withSpan$1, _ as serializeGenAiAttribute, b as setSpanStatus, f as logException, g as runBestEffort, i as extractGenAiUsageSummary, k as normalizeIdentityEmail, m as logWarn, p as logInfo, r as extractGenAiUsageAttributes, s as getLogContextAttributes, y as setSpanAttributes } from "./logging-BQsfrLHl.js";
6
+ import { G as mapBounded, R as unwrapCurrentInstruction, d as SANDBOX_WORKSPACE_ROOT, g as RUNTIME_CONTEXT_TEXT_STARTS, h as createPluginLogger, n as toPromptContributionContext, r as runPluginHooksAtOnce, s as SANDBOX_JUNIOR_ROOT } from "./prompt-5PDkRQ1K.js";
7
+ import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes, t as canExposeConversationPayload } from "./conversation-privacy-DR_j5Tqf.js";
8
8
  import { _ as withScope, a as getClient$1, n as captureMessage } from "./sentry-CPbZjomA.js";
9
+ import { h as SERVICE_INSTANCE_ID } from "./deployment-CeKaP0ZJ.js";
9
10
  import * as z from "zod";
10
11
  import path from "node:path";
11
12
  import { SQL, and, arrayOverlaps, asc, count, desc, eq, exists, getTableName, gt, gte, ilike, inArray, is, isNotNull, isNull, like, lt, lte, max, ne, not, notExists, or, sql } from "drizzle-orm";
12
13
  import { PgAsyncDatabase, QueryBuilder, alias, bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgSequence, pgTable, primaryKey, text as text$1, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
13
- import { MAX_CONVERSATION_CHANGES, PluginInboxItemOwnerError, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeFilterSchema, codeChangeInputSchema, codeRepositoryInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, defineConversationEvent, defineJuniorPlugin, definePluginTool, definePromptContext, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagText, eventDataSchema, eventInputSchema, eventMatchFieldsSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, getSourceKey, identitySchema, isPluginModelCostEventName, isSlackDestination, locationSchema, markdownPlainText, normalizeEventIdentifier, normalizeEventMatch, objectFactFields, objectIconPath, objectLinkFilterMatches, objectLinkFilterSchema, objectLinkFilterSpecificity, objectPresentation, objectSubjectSchema, objectTypeSchema, pluginApiRouteRequestContextSchema, pluginEventsSchema, pluginModelCostEventNames, pluginTaskStartInputSchema, pluginToolOutputSchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, taskOutcomeSchema, userSchema, withToolContext } from "@sentry/junior-plugin-api";
14
+ import { CACHE_LOAD_TIMEOUT_MS, MAX_CONVERSATION_CHANGES, PluginInboxItemOwnerError, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeFilterSchema, codeChangeInputSchema, codeRepositoryInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, createEventSource, createSlackSource, createWebSource, defineConversationEvent, defineJuniorPlugin, definePluginTool, definePromptContext, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagText, eventDataSchema, eventInputSchema, eventMatchFieldsSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, getSourceKey, identitySchema, isPluginModelCostEventName, isSlackDestination, locationSchema, markdownNodes, markdownPlainText, normalizeEventIdentifier, normalizeEventMatch, objectFactFields, objectIconPath, objectLinkFilterMatches, objectLinkFilterSchema, objectLinkFilterSpecificity, objectPresentation, objectSubjectSchema, objectTypeSchema, parseMarkdown, pluginApiRouteRequestContextSchema, pluginEventsSchema, pluginModelCostEventNames, pluginTaskStartInputSchema, pluginToolOutputSchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, taskOutcomeSchema, untilAborted, userSchema, withToolContext } from "@sentry/junior-plugin-api";
14
15
  import { readFileSync, readdirSync, statSync } from "node:fs";
15
16
  import { isDeepStrictEqual } from "node:util";
16
17
  import { AsyncLocalStorage } from "node:async_hooks";
18
+ import * as Sentry from "@sentry/node";
17
19
  import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
18
20
  import { parse } from "yaml";
19
21
  import { UnauthorizedError, auth } from "@modelcontextprotocol/sdk/client/auth.js";
@@ -1031,8 +1033,9 @@ const juniorInboxItems = pgTable("junior_inbox_items", {
1031
1033
  status: text$1("status").$type().notNull(),
1032
1034
  /**
1033
1035
  * A `question` item's question holds its title, body, request, and
1034
- * answer (`junior_questions`). The item keeps a copy for the release
1035
- * before this one, and new code never reads it.
1036
+ * answer (`junior_questions`). The item keeps a copy of the title,
1037
+ * body, and request for the release before this one, and new code
1038
+ * never reads it.
1036
1039
  */
1037
1040
  title: text$1("title"),
1038
1041
  body: text$1("body"),
@@ -1049,6 +1052,11 @@ const juniorInboxItems = pgTable("junior_inbox_items", {
1049
1052
  closedAt: timestamptz("closed_at"),
1050
1053
  closedByUserId: text$1("closed_by_user_id").references(() => juniorUsers.id, { onDelete: "set null" }),
1051
1054
  closeReason: text$1("close_reason"),
1055
+ /**
1056
+ * The id of the subject kind's action that a person ran to close it,
1057
+ * such as `resume` (`PluginInboxSubjectKind.actions`).
1058
+ */
1059
+ closeAction: text$1("close_action"),
1052
1060
  createdAt: timestamptz("created_at").notNull(),
1053
1061
  updatedAt: timestamptz("updated_at").notNull()
1054
1062
  }, (table) => [
@@ -1309,9 +1317,10 @@ function questionFuzzyTitle(table) {
1309
1317
  }
1310
1318
  /**
1311
1319
  * One question or notice that an agent gave a person in a Conversation. It
1312
- * belongs to that Conversation, and it holds its own title, body, request
1313
- * (the form and the related links), and the answer. Its Inbox item has
1314
- * the subject `{ kind: "question", id }` and stores none of these.
1320
+ * belongs to that Conversation and holds its title, body, request (the form
1321
+ * and the related links), and its answer, who gave it, and when. Its Inbox
1322
+ * item has the subject `{ kind: "question", id }` and keeps only its own
1323
+ * open, done, or dismissed state.
1315
1324
  */
1316
1325
  const juniorQuestions = pgTable("junior_questions", {
1317
1326
  id: text$1("id").primaryKey(),
@@ -1322,6 +1331,8 @@ const juniorQuestions = pgTable("junior_questions", {
1322
1331
  body: text$1("body").notNull(),
1323
1332
  request: jsonb("request").$type(),
1324
1333
  answer: jsonb("answer").$type(),
1334
+ answeredByUserId: text$1("answered_by_user_id").references(() => juniorUsers.id, { onDelete: "set null" }),
1335
+ answeredAt: timestamptz("answered_at"),
1325
1336
  createdAt: timestamptz("created_at").notNull(),
1326
1337
  updatedAt: timestamptz("updated_at").notNull()
1327
1338
  }, (table) => [
@@ -1862,6 +1873,7 @@ function inlineMcpSource(mcp) {
1862
1873
  setDefined$1(result, "allowed-tools", mcp.allowedTools);
1863
1874
  setDefined$1(result, "wrapped-tools", mcp.wrappedTools);
1864
1875
  setDefined$1(result, "viewer-tools", mcp.viewerTools);
1876
+ setDefined$1(result, "guardian", mcp.guardian && { skipReview: mcp.guardian.skipReview });
1865
1877
  return result;
1866
1878
  }
1867
1879
  function inlineOauthSource(oauth) {
@@ -2208,7 +2220,8 @@ const mcpSourceSchema = z.object({
2208
2220
  "oauth-client": mcpOauthClientSourceSchema.optional(),
2209
2221
  "allowed-tools": nonEmptyStringArraySchema("allowed-tools").optional(),
2210
2222
  "wrapped-tools": nonEmptyStringArraySchema("wrapped-tools").optional(),
2211
- "viewer-tools": nonEmptyStringArraySchema("viewer-tools").optional()
2223
+ "viewer-tools": nonEmptyStringArraySchema("viewer-tools").optional(),
2224
+ guardian: z.object({ skipReview: nonEmptyStringArraySchema("skipReview").optional() }).strict().optional()
2212
2225
  }).passthrough();
2213
2226
  const targetSourceSchema = z.object({
2214
2227
  type: nonEmptyTrimmedString.refine((value) => PLUGIN_NAME_RE$1.test(value), { error: "type must be a lowercase target identifier" }),
@@ -2579,6 +2592,12 @@ function normalizeMcp(data, envVars, name) {
2579
2592
  wrappedTools: result.data["wrapped-tools"]
2580
2593
  }, result.data["viewer-tools"] ?? []);
2581
2594
  if (unloadedViewerTools.length > 0) throw new Error(`Plugin ${name} mcp.viewer-tools must be listed in mcp.allowed-tools or mcp.wrapped-tools: ${unloadedViewerTools.join(", ")}`);
2595
+ const skipReview = result.data.guardian?.["skipReview"];
2596
+ const unloadedSkipReview = skipReview ? unloadedMcpTools({
2597
+ allowedTools: result.data["allowed-tools"],
2598
+ wrappedTools: result.data["wrapped-tools"]
2599
+ }, skipReview) : [];
2600
+ if (unloadedSkipReview.length > 0) throw new Error(`Plugin ${name} mcp.guardian.skipReview must be listed in mcp.allowed-tools or mcp.wrapped-tools: ${unloadedSkipReview.join(", ")}`);
2582
2601
  return {
2583
2602
  transport: "http",
2584
2603
  url: result.data.url,
@@ -2596,7 +2615,8 @@ function normalizeMcp(data, envVars, name) {
2596
2615
  } } : void 0,
2597
2616
  ...result.data["allowed-tools"] ? { allowedTools: result.data["allowed-tools"] } : void 0,
2598
2617
  ...result.data["wrapped-tools"] ? { wrappedTools: result.data["wrapped-tools"] } : void 0,
2599
- ...result.data["viewer-tools"] ? { viewerTools: result.data["viewer-tools"] } : void 0
2618
+ ...result.data["viewer-tools"] ? { viewerTools: result.data["viewer-tools"] } : void 0,
2619
+ ...skipReview ? { guardian: { skipReview } } : void 0
2600
2620
  };
2601
2621
  }
2602
2622
  /**
@@ -4646,7 +4666,7 @@ async function mintAzure(azure) {
4646
4666
  * the failing step and HTTP status. Each mint records one span.
4647
4667
  */
4648
4668
  async function mintWorkloadIdentityToken(provider, credentials) {
4649
- return await withSpan("credential.workload_identity.mint", "credential.workload_identity.mint", {}, async (setSpanAttributes) => {
4669
+ return await withSpan$1("credential.workload_identity.mint", "credential.workload_identity.mint", {}, async (setSpanAttributes) => {
4650
4670
  try {
4651
4671
  const minted = credentials.gcp ? await mintGcp(credentials.gcp) : await mintAzure(credentials.azure);
4652
4672
  setSpanAttributes({ "app.workload_identity.outcome": "completed" });
@@ -5941,7 +5961,8 @@ function cacheKeyPrefix(namespace) {
5941
5961
  * Create a cache in the state adapter under `junior:cache:{namespace}:`.
5942
5962
  * Entries are wrapped, so `null` and `false` values are cache hits. A stale
5943
5963
  * `staleIfError` entry is returned when its reload throws, unless the caller
5944
- * asked for `refresh`. `onStale` then gets the time that it was stored.
5964
+ * asked for `refresh`, or to a `stale` get. `onStale` then gets the time
5965
+ * that it was stored.
5945
5966
  */
5946
5967
  function createCache(state, namespace, hooks = {}) {
5947
5968
  const stateKey = (key) => {
@@ -5950,15 +5971,23 @@ function createCache(state, namespace, hooks = {}) {
5950
5971
  return `${cacheKeyPrefix(namespace)}${key}`;
5951
5972
  };
5952
5973
  return {
5953
- async get(key) {
5974
+ async get(key, options) {
5954
5975
  const cacheKey = stateKey(key);
5955
5976
  await state.connect();
5956
5977
  const hit = await state.get(cacheKey);
5957
- return hit && isFresh(hit) ? hit.value : void 0;
5978
+ if (!hit) return void 0;
5979
+ if (isFresh(hit)) return hit.value;
5980
+ if (!options?.stale) return void 0;
5981
+ if (hit.storedAtMs !== void 0) hooks.onStale?.(hit.storedAtMs);
5982
+ return hit.value;
5958
5983
  },
5959
5984
  async getOrLoad(key, load, options) {
5960
5985
  const cacheKey = stateKey(key);
5961
5986
  const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
5987
+ const stale = (entry) => {
5988
+ if (entry.storedAtMs !== void 0) hooks.onStale?.(entry.storedAtMs);
5989
+ return entry.value;
5990
+ };
5962
5991
  await state.connect();
5963
5992
  const hit = await cached();
5964
5993
  if (hit && isFresh(hit)) return hit.value;
@@ -5982,11 +6011,10 @@ function createCache(state, namespace, hooks = {}) {
5982
6011
  waitMs: LOAD_WAIT_MS
5983
6012
  });
5984
6013
  if (attempt.acquired) return attempt.value;
5985
- return (await load()).value;
6014
+ return hit ? stale(hit) : (await load()).value;
5986
6015
  } catch (error) {
5987
6016
  if (!hit) throw error;
5988
- if (hit.storedAtMs !== void 0) hooks.onStale?.(hit.storedAtMs);
5989
- return hit.value;
6017
+ return stale(hit);
5990
6018
  }
5991
6019
  },
5992
6020
  async update(key, next) {
@@ -6064,7 +6092,7 @@ async function readServedProviders(state, modelId) {
6064
6092
  }));
6065
6093
  }
6066
6094
  async function gatewayOnlyForModel(modelId) {
6067
- const { getStateAdapter } = await import("./adapter-DlLLoJKj.js").then((n) => n.t);
6095
+ const { getStateAdapter } = await import("./adapter-CKtEUuWD.js").then((n) => n.t);
6068
6096
  const state = getStateAdapter();
6069
6097
  const enabled = await readLocal(localEnabledProviders, "enabled", () => readEnabledProviders(state));
6070
6098
  if (enabled === null) return void 0;
@@ -6176,7 +6204,7 @@ async function completeText$1(params) {
6176
6204
  "gen_ai.input.messages": recordContent ? serializeGenAiAttribute(params.messages.map(toCanonicalInputMessage)) : void 0,
6177
6205
  "gen_ai.provider.auth_mode": authMode
6178
6206
  };
6179
- return withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6207
+ return withSpan$1(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6180
6208
  let message;
6181
6209
  try {
6182
6210
  message = await completeSimple(model, {
@@ -6286,7 +6314,7 @@ async function completeObject$1(params) {
6286
6314
  const provider = createGatewayProvider({ apiKey: credential.token });
6287
6315
  let result;
6288
6316
  try {
6289
- result = await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6317
+ result = await withSpan$1(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6290
6318
  const result = await generateObject({
6291
6319
  model: provider.chat(params.modelId),
6292
6320
  schema: params.schema,
@@ -6328,7 +6356,7 @@ async function completeDecision$1(params) {
6328
6356
  const credential = await resolveGatewayCredential();
6329
6357
  const provider = createGatewayProvider({ apiKey: credential.token });
6330
6358
  try {
6331
- const result = await withSpan(`${GEN_AI_OPERATION_DECIDE} ${params.modelId}`, "gen_ai.decide", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6359
+ const result = await withSpan$1(`${GEN_AI_OPERATION_DECIDE} ${params.modelId}`, "gen_ai.decide", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6332
6360
  const result = await experimental_decide({
6333
6361
  model: provider.decisionModel(params.modelId),
6334
6362
  state: params.state,
@@ -6376,7 +6404,7 @@ async function embedTexts$1(params) {
6376
6404
  const provider = createGatewayProvider({ apiKey: credential.token });
6377
6405
  const providerOptions = embeddingProviderOptions(params.modelId, params.inputType);
6378
6406
  try {
6379
- const result = await withSpan(`${GEN_AI_OPERATION_EMBEDDINGS} ${params.modelId}`, "gen_ai.embeddings", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6407
+ const result = await withSpan$1(`${GEN_AI_OPERATION_EMBEDDINGS} ${params.modelId}`, "gen_ai.embeddings", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6380
6408
  const result = await embedMany({
6381
6409
  model: provider.embeddingModel(params.modelId),
6382
6410
  values: texts,
@@ -6442,7 +6470,7 @@ async function rerankTexts(params) {
6442
6470
  const credential = await resolveGatewayCredential();
6443
6471
  const provider = createGatewayProvider({ apiKey: credential.token });
6444
6472
  try {
6445
- return await withSpan(`${GEN_AI_OPERATION_RERANK} ${params.modelId}`, "gen_ai.rerank", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6473
+ return await withSpan$1(`${GEN_AI_OPERATION_RERANK} ${params.modelId}`, "gen_ai.rerank", logContextFromMetadata(params.modelId, params.metadata), async (setSpanAttributes) => {
6446
6474
  const result = await rerank({
6447
6475
  model: provider.rerankingModel(params.modelId),
6448
6476
  query,
@@ -6484,7 +6512,7 @@ const WEB_SEARCH_TOOL_NAME = "parallelSearch";
6484
6512
  async function searchWeb$1(params) {
6485
6513
  const credential = await resolveGatewayCredential();
6486
6514
  const provider = createGatewayProvider({ apiKey: credential.token });
6487
- return await withSpan(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", {}, async (setSpanAttributes) => {
6515
+ return await withSpan$1(`${GEN_AI_OPERATION_CHAT} ${params.modelId}`, "gen_ai.chat", {}, async (setSpanAttributes) => {
6488
6516
  const response = await generateText({
6489
6517
  model: provider.chat(params.modelId),
6490
6518
  prompt: params.query,
@@ -6623,7 +6651,7 @@ async function transcribeFromUrl$1(params) {
6623
6651
  const credential = await resolveGatewayCredential();
6624
6652
  const provider = createGatewayProvider({ apiKey: credential.token });
6625
6653
  try {
6626
- return await withSpan(`${GEN_AI_OPERATION_TRANSCRIPTION} ${params.modelId}`, "gen_ai.transcription", {
6654
+ return await withSpan$1(`${GEN_AI_OPERATION_TRANSCRIPTION} ${params.modelId}`, "gen_ai.transcription", {
6627
6655
  modelId: params.modelId,
6628
6656
  ...params.conversationId ? { conversationId: params.conversationId } : void 0
6629
6657
  }, async (setSpanAttributes) => {
@@ -7130,7 +7158,7 @@ async function embedConversationEvents(db, embedder, conversationId, limits = {}
7130
7158
  */
7131
7159
  async function indexConversationEvents(args) {
7132
7160
  const { conversationId, turnId } = args;
7133
- await withSpan("event_search.index", "event_search.index", { conversationId }, async (setSpanAttributes) => {
7161
+ await withSpan$1("event_search.index", "event_search.index", { conversationId }, async (setSpanAttributes) => {
7134
7162
  const waitStartedAtMs = Date.now();
7135
7163
  const attempt = await withLock(getStateAdapter(), eventIndexLockKey(conversationId), async () => {
7136
7164
  setSpanAttributes({ "app.event_search.index.lock.wait_ms": Date.now() - waitStartedAtMs });
@@ -7496,7 +7524,7 @@ const LEAD_TOOLS = [
7496
7524
  "searchConversationEvents",
7497
7525
  "readConversationEvent",
7498
7526
  "searchInboxItems",
7499
- "addInboxItem",
7527
+ "askUserQuestion",
7500
7528
  "updateInboxItem",
7501
7529
  "searchEventTypes",
7502
7530
  "watchEvents",
@@ -7600,6 +7628,13 @@ function copiesRootVisibility(conversation) {
7600
7628
  function remindsNoReplyForChildStatus(kind) {
7601
7629
  return kind === "lead";
7602
7630
  }
7631
+ /**
7632
+ * Return whether a feed row of this kind shows its child Threads. A Lead
7633
+ * shows as its Space, whose page lists them.
7634
+ */
7635
+ function feedRowShowsThreads(kind) {
7636
+ return kind !== "lead";
7637
+ }
7603
7638
  /** Return whether a Conversation of this kind stores its Space: a Lead. */
7604
7639
  function storesSpace(kind) {
7605
7640
  return kind === "lead";
@@ -11820,6 +11855,18 @@ async function lockUserSnoozes(tx, userId) {
11820
11855
  const lockKey = `junior:inbox-snooze:${userId}`;
11821
11856
  await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtext(${lockKey}))`);
11822
11857
  }
11858
+ /**
11859
+ * A new snooze timer id. It ends with the wake time, so a snooze can say
11860
+ * when it wakes without a read of the timer index.
11861
+ */
11862
+ function snoozeTimerId(wakeAtMs) {
11863
+ return `inbox-snooze:${randomUUID()}:${wakeAtMs}`;
11864
+ }
11865
+ /** The wake time in a snooze timer id. Older ids have none. */
11866
+ function snoozeTimerWakeAtMs(timerId) {
11867
+ const time = /^inbox-snooze:[^:]+:(\d+)$/.exec(timerId)?.[1];
11868
+ return time === void 0 ? void 0 : Number(time);
11869
+ }
11823
11870
  /** The trigger of a snooze timer: its `timer.fired` Event wakes the item. */
11824
11871
  function snoozeTimerTrigger(timerId) {
11825
11872
  return {
@@ -11912,25 +11959,38 @@ async function clearInboxWakeReasons(db, input) {
11912
11959
  await db.update(juniorInboxSnoozes).set({ wakeReason: null }).where(and(eq(juniorInboxSnoozes.userId, input.userId), inArray(juniorInboxSnoozes.inboxItemId, [...input.inboxItemIds]), isNotNull(juniorInboxSnoozes.wakeReason)));
11913
11960
  }
11914
11961
  /**
11915
- * Read this User's snoozes of these items: the items that they snoozed and
11916
- * that have not woken, and why each woken snooze woke. An item whose
11917
- * snooze the User woke, or whose reason they cleared, has no reason. A new
11918
- * snooze clears the last reason, so an item has at most one of either.
11962
+ * Read this User's snoozes of these items: each snooze that has not woken,
11963
+ * with its triggers, and why each woken snooze woke. An item whose snooze
11964
+ * the User woke, or whose reason they cleared, has no reason. A new snooze
11965
+ * clears the last reason, so an item has at most one of either.
11919
11966
  */
11920
11967
  async function readViewerInboxSnoozes(db, input) {
11921
- const snoozed = /* @__PURE__ */ new Set();
11968
+ const snoozed = /* @__PURE__ */ new Map();
11922
11969
  const wakeReasons = /* @__PURE__ */ new Map();
11923
11970
  if (input.inboxItemIds.length === 0) return {
11924
11971
  snoozed,
11925
11972
  wakeReasons
11926
11973
  };
11927
11974
  const rows = await db.select({
11975
+ createdAt: juniorInboxSnoozes.createdAt,
11928
11976
  inboxItemId: juniorInboxSnoozes.inboxItemId,
11929
11977
  state: juniorInboxSnoozes.state,
11978
+ trigger: {
11979
+ eventType: juniorInboxSnoozeTriggers.eventType,
11980
+ identifier: juniorInboxSnoozeTriggers.identifier,
11981
+ namespace: juniorInboxSnoozeTriggers.namespace,
11982
+ outcome: juniorInboxSnoozeTriggers.outcome
11983
+ },
11930
11984
  wakeReason: juniorInboxSnoozes.wakeReason
11931
- }).from(juniorInboxSnoozes).where(and(eq(juniorInboxSnoozes.userId, input.userId), inArray(juniorInboxSnoozes.inboxItemId, [...input.inboxItemIds]), or(eq(juniorInboxSnoozes.state, "snoozed"), and(eq(juniorInboxSnoozes.state, "woken"), isNotNull(juniorInboxSnoozes.wakeReason)))));
11932
- for (const row of rows) if (row.state === "snoozed") snoozed.add(row.inboxItemId);
11933
- else if (row.wakeReason) wakeReasons.set(row.inboxItemId, row.wakeReason);
11985
+ }).from(juniorInboxSnoozes).leftJoin(juniorInboxSnoozeTriggers, and(eq(juniorInboxSnoozeTriggers.snoozeId, juniorInboxSnoozes.id), eq(juniorInboxSnoozes.state, "snoozed"))).where(and(eq(juniorInboxSnoozes.userId, input.userId), inArray(juniorInboxSnoozes.inboxItemId, [...input.inboxItemIds]), or(eq(juniorInboxSnoozes.state, "snoozed"), and(eq(juniorInboxSnoozes.state, "woken"), isNotNull(juniorInboxSnoozes.wakeReason)))));
11986
+ for (const row of rows) if (row.state === "snoozed") {
11987
+ const snooze = snoozed.get(row.inboxItemId) ?? {
11988
+ createdAt: row.createdAt,
11989
+ triggers: []
11990
+ };
11991
+ if (row.trigger) snooze.triggers.push(row.trigger);
11992
+ snoozed.set(row.inboxItemId, snooze);
11993
+ } else if (row.wakeReason) wakeReasons.set(row.inboxItemId, row.wakeReason);
11934
11994
  return {
11935
11995
  snoozed,
11936
11996
  wakeReasons
@@ -12123,6 +12183,17 @@ function subjectKindDismissNote(kind, plugins, object, viewer) {
12123
12183
  return registered?.dismissNote?.(object, reader);
12124
12184
  }
12125
12185
  /**
12186
+ * Return the actions that a plugin kind puts on its open items, such as
12187
+ * Resume. Core kinds have none here: a To-do closes with Mark done.
12188
+ */
12189
+ function subjectKindActions(kind, plugins) {
12190
+ return registeredSubjectKind(kind, plugins, void 0).registered?.actions ?? [];
12191
+ }
12192
+ /** Return the label of a kind action by its id, such as Resume. */
12193
+ function subjectKindActionLabel(kind, plugins, id) {
12194
+ return subjectKindActions(kind, plugins).find((action) => action.id === id)?.label;
12195
+ }
12196
+ /**
12126
12197
  * Return the To-do of an item's subject, or undefined for another kind. A
12127
12198
  * Conversation id can hold colons, so the To-do id is after the last one.
12128
12199
  */
@@ -12152,8 +12223,6 @@ const inboxItemTitle = sql`coalesce(${juniorQuestions.title}, ${juniorInboxItems
12152
12223
  const inboxItemBody = sql`coalesce(${juniorQuestions.body}, ${juniorInboxItems.body}, '')`;
12153
12224
  /** SQL: the request of an item, from its question when it has one. */
12154
12225
  const inboxItemRequest = sql`coalesce(${juniorQuestions.request}, ${juniorInboxItems.request})`;
12155
- /** SQL: the answer of an item, from its question when it has one. */
12156
- const inboxItemAnswer = sql`coalesce(${juniorQuestions.answer}, ${juniorInboxItems.answer})`;
12157
12226
  // src/chat/inbox-items/store.ts
12158
12227
  /**
12159
12228
  * Close reason of an action item that a person answered with a reply in
@@ -12234,11 +12303,17 @@ async function hydrate(db, itemRows) {
12234
12303
  const rows = owned.map((row) => row.item);
12235
12304
  const ids = rows.map((row) => row.id);
12236
12305
  const [assigneeRows, conversationRows] = await Promise.all([db.select().from(juniorInboxItemAssignees).where(inArray(juniorInboxItemAssignees.itemId, ids)), db.select().from(juniorInboxItemConversations).where(inArray(juniorInboxItemConversations.itemId, ids))]);
12237
- const users = await readUsers(db, [...assigneeRows.map((row) => row.userId), ...rows.flatMap((row) => row.closedByUserId ? [row.closedByUserId] : [])]);
12306
+ const users = await readUsers(db, [
12307
+ ...assigneeRows.map((row) => row.userId),
12308
+ ...rows.flatMap((row) => row.closedByUserId ? [row.closedByUserId] : []),
12309
+ ...owned.flatMap(({ question }) => question?.answeredByUserId ? [question.answeredByUserId] : [])
12310
+ ]);
12238
12311
  return rows.map((row, index) => {
12239
12312
  const { addedByAutomationId, owner, question } = owned[index];
12240
12313
  const content = question ?? row;
12241
12314
  const closedBy = row.closedByUserId ? users.get(row.closedByUserId) : void 0;
12315
+ const answeredByUserId = question ? question.answeredByUserId : content.answer && row.closedByUserId;
12316
+ const answeredBy = answeredByUserId ? users.get(answeredByUserId) : void 0;
12242
12317
  return {
12243
12318
  assignedToEveryone: row.assignedToEveryone,
12244
12319
  assignees: assigneeRows.filter((assignee) => assignee.itemId === row.id).flatMap((assignee) => users.get(assignee.userId) ?? []).sort((a, b) => a.email.localeCompare(b.email)),
@@ -12260,8 +12335,10 @@ async function hydrate(db, itemRows) {
12260
12335
  updatedAt: row.updatedAt,
12261
12336
  visibility: owner.visibility,
12262
12337
  ...content.answer ? { answer: content.answer } : void 0,
12338
+ ...answeredBy ? { answeredBy } : void 0,
12263
12339
  ...row.addedByTurnId ? { addedByTurnId: row.addedByTurnId } : void 0,
12264
12340
  ...addedByAutomationId ? { addedByAutomationId } : void 0,
12341
+ ...row.closeAction ? { closeAction: row.closeAction } : void 0,
12265
12342
  ...row.closeReason ? { closeReason: row.closeReason } : void 0,
12266
12343
  ...row.closedAt ? { closedAt: row.closedAt } : void 0,
12267
12344
  ...closedBy ? { closedBy } : void 0,
@@ -12332,7 +12409,14 @@ async function listReplyActionItems(db, conversationId) {
12332
12409
  * names at most one open item.
12333
12410
  */
12334
12411
  async function getOpenInboxItemBySubject(db, subject) {
12335
- return (await hydrate(db, await selectItemRows(db).where(and(eq(juniorInboxItems.subjectKind, subject.kind), eq(juniorInboxItems.subjectId, subject.id), eq(juniorInboxItems.status, "open")))))[0];
12412
+ return (await hydrate(db, await selectItemRows(db).where(and(subjectIs(subject), eq(juniorInboxItems.status, "open")))))[0];
12413
+ }
12414
+ /** Read every Inbox item of one subject, open and closed, newest first. */
12415
+ async function listInboxItemsBySubject(db, subject) {
12416
+ return await hydrate(db, await selectItemRows(db).where(subjectIs(subject)).orderBy(desc(juniorInboxItems.createdAt), desc(juniorInboxItems.id)));
12417
+ }
12418
+ function subjectIs(subject) {
12419
+ return and(eq(juniorInboxItems.subjectKind, subject.kind), eq(juniorInboxItems.subjectId, subject.id));
12336
12420
  }
12337
12421
  /**
12338
12422
  * Add one open Inbox item. Return undefined when another open item already
@@ -12410,7 +12494,8 @@ async function closeInboxItem(db, input) {
12410
12494
  const now = new Date(input.nowMs);
12411
12495
  if ((await db.transaction(async (tx) => {
12412
12496
  const closed = await tx.update(juniorInboxItems).set({
12413
- answer: input.answer ?? null,
12497
+ answer: input.answer ? sql`case when ${juniorInboxItems.subjectKind} = ${INBOX_SUBJECT_KINDS.question} then null else ${JSON.stringify(input.answer)}::jsonb end` : null,
12498
+ closeAction: input.action ?? null,
12414
12499
  closeReason: input.reason ?? null,
12415
12500
  closedAt: now,
12416
12501
  closedByUserId: input.closedByUserId ?? null,
@@ -12424,6 +12509,8 @@ async function closeInboxItem(db, input) {
12424
12509
  const item = closed[0];
12425
12510
  if (input.answer && item?.subjectKind === INBOX_SUBJECT_KINDS.question) await tx.update(juniorQuestions).set({
12426
12511
  answer: input.answer,
12512
+ answeredAt: now,
12513
+ answeredByUserId: input.closedByUserId ?? null,
12427
12514
  updatedAt: now
12428
12515
  }).where(eq(juniorQuestions.id, item.subjectId));
12429
12516
  await touchConversationDetail(tx, ownerConversationIds(closed));
@@ -12482,7 +12569,7 @@ async function takeInboxItem(db, input) {
12482
12569
  });
12483
12570
  }
12484
12571
  function searchConditions(reader, filters) {
12485
- const conditions = [inboxItemVisibleTo(reader), inArray(juniorInboxItems.status, [...filters.statuses])];
12572
+ const conditions = [inboxItemVisibleTo(reader, filters.statuses), inArray(juniorInboxItems.status, [...filters.statuses])];
12486
12573
  if (filters.after) conditions.push(or(gt(juniorInboxItems.createdAt, filters.after.createdAt), and(eq(juniorInboxItems.createdAt, filters.after.createdAt), gt(juniorInboxItems.id, filters.after.id))));
12487
12574
  if (filters.afterWaiting) {
12488
12575
  if (typeof filters.order !== "object") throw new Error("afterWaiting needs the waiting-first order");
@@ -12495,9 +12582,9 @@ function searchConditions(reader, filters) {
12495
12582
  if (filters.subjectId) conditions.push(eq(juniorInboxItems.subjectId, filters.subjectId));
12496
12583
  if (filters.automationId) conditions.push(inboxItemAddedByAutomation(filters.automationId));
12497
12584
  if (filters.conversationId) conditions.push(inboxItemLinkedTo(filters.conversationId));
12498
- if (filters.assignee) conditions.push("everyone" in filters.assignee ? eq(juniorInboxItems.assignedToEveryone, true) : inboxItemAssignedTo(filters.assignee.userId));
12585
+ if (filters.assignee) conditions.push("everyone" in filters.assignee ? eq(juniorInboxItems.assignedToEveryone, true) : inboxItemAssignedTo(filters.assignee.userId, filters.statuses));
12499
12586
  if (filters.ownerKind) conditions.push(eq(inboxItemOwnerKind(), filters.ownerKind));
12500
- if (filters.forUserId) conditions.push(inboxItemForUser(filters.forUserId));
12587
+ if (filters.forUserId) conditions.push(inboxItemForUser(filters.forUserId, filters.statuses));
12501
12588
  if (filters.awakeForUserId) conditions.push(not(inboxItemSnoozedBy(filters.awakeForUserId)));
12502
12589
  if (filters.snoozedForUserId) conditions.push(inboxItemSnoozedBy(filters.snoozedForUserId));
12503
12590
  if (filters.query) {
@@ -12639,7 +12726,7 @@ async function closeHandledReplyNotices(db, input) {
12639
12726
  }
12640
12727
  }
12641
12728
  async function openReplyNoticeId(db, input) {
12642
- const [notice] = await db.select({ id: juniorInboxItems.id }).from(juniorInboxItems).where(and(eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.reply), eq(juniorInboxItems.subjectId, input.conversationId), eq(juniorInboxItems.status, "open"), inboxItemAssignedTo(input.userId))).limit(1);
12729
+ const [notice] = await db.select({ id: juniorInboxItems.id }).from(juniorInboxItems).where(and(eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.reply), eq(juniorInboxItems.subjectId, input.conversationId), eq(juniorInboxItems.status, "open"), inboxItemAssignedTo(input.userId, ["open"]))).limit(1);
12643
12730
  return notice?.id;
12644
12731
  }
12645
12732
  async function closeRead(db, id, input) {
@@ -12669,7 +12756,7 @@ function inboxItemNeedsUserNow(userId) {
12669
12756
  async function countInboxItemsNeedingUserBySubject(db, userId) {
12670
12757
  return await db.select({
12671
12758
  automations: sql`count(*) filter (where ${eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.automation)})`.mapWith(Number),
12672
- decisions: sql`count(*) filter (where ${inboxItemRequest} -> 'question' is not null)`.mapWith(Number),
12759
+ decisions: sql`count(*) filter (where ${inboxItemRequest} -> 'fields' is not null)`.mapWith(Number),
12673
12760
  subjectId: juniorInboxItems.subjectId,
12674
12761
  subjectKind: juniorInboxItems.subjectKind,
12675
12762
  todos: sql`count(*) filter (where ${eq(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.todo)})`.mapWith(Number),
@@ -12920,7 +13007,7 @@ async function readCachedLinkedHandle(lookup, load) {
12920
13007
  lookup.query
12921
13008
  ])).digest("hex");
12922
13009
  return await cache().getOrLoad(`linked-handle:${lookup.provider}:${version.token}:${lookupHash}`, async () => {
12923
- const value = await load();
13010
+ const value = await untilAborted(load(), AbortSignal.timeout(CACHE_LOAD_TIMEOUT_MS));
12924
13011
  return value.status === "found" && settled ? {
12925
13012
  value,
12926
13013
  ttlMs: LINKED_HANDLE_TTL_MS,
@@ -13647,9 +13734,9 @@ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
13647
13734
  attempt += 1;
13648
13735
  const attemptNumber = attempt;
13649
13736
  try {
13650
- return await withSpan(`POST slack.com/api/${action}`, "http.client", {}, async () => {
13737
+ return await withSpan$1(`POST slack.com/api/${action}`, "http.client", {}, async () => {
13651
13738
  try {
13652
- return await task();
13739
+ return await untilAborted(task(), context.signal);
13653
13740
  } catch (error) {
13654
13741
  const mapped = mapSlackError(error);
13655
13742
  const errorAttrs = { "error.type": mapped.code };
@@ -13688,7 +13775,7 @@ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
13688
13775
  ...mapped.statusCode !== void 0 ? { "http.response.status_code": mapped.statusCode } : void 0,
13689
13776
  ...context.attributes ?? {}
13690
13777
  };
13691
- if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0) {
13778
+ if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0 || context.signal?.aborted) {
13692
13779
  if (context.expectedErrorCodes?.includes(mapped.code)) throw mapped;
13693
13780
  logWarn("slack.action.failed", {
13694
13781
  ...baseLogAttributes,
@@ -13705,7 +13792,9 @@ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
13705
13792
  const backoffMs = Math.min(2e3, 250 * 2 ** (attempt - 1));
13706
13793
  const delayMs = Math.min(retryAfterMs ?? backoffMs, MAX_RETRY_DELAY_MS, remainingDelayBudgetMs);
13707
13794
  totalDelayMs += delayMs;
13708
- await sleep$2(delayMs);
13795
+ await sleep$2(delayMs, context.signal).catch(() => {
13796
+ throw mapped;
13797
+ });
13709
13798
  }
13710
13799
  }
13711
13800
  throw new SlackActionError("Slack action exhausted retries", "internal_error");
@@ -13813,12 +13902,13 @@ const dndInfoSchema = z.object({
13813
13902
  * at `nowMs`, from `dnd.info`. Return undefined when Slack cannot answer,
13814
13903
  * such as before the install grants `dnd:read`.
13815
13904
  */
13816
- async function isSlackDndActive(userId, nowMs) {
13905
+ async function isSlackDndActive(userId, nowMs, signal) {
13817
13906
  let response;
13818
13907
  try {
13819
13908
  response = await withSlackRetries(() => getSlackClient().dnd.info({ user: userId }), 3, {
13820
13909
  action: "dnd.info",
13821
- idempotent: true
13910
+ idempotent: true,
13911
+ signal
13822
13912
  });
13823
13913
  } catch (error) {
13824
13914
  if (error instanceof SlackActionError) return void 0;
@@ -13858,7 +13948,7 @@ async function isPausedBySlack(db, userId, nowMs) {
13858
13948
  return await createCache(getStateAdapter(), "core").getOrLoad(`notifications:slack-paused:${userId}:${bucket}`, async () => {
13859
13949
  const slack = await linkedSlackUser(db, userId);
13860
13950
  return {
13861
- value: (slack ? await isSlackDndActive(slack.userId, nowMs) : null) ?? null,
13951
+ value: (slack ? await isSlackDndActive(slack.userId, nowMs, AbortSignal.timeout(CACHE_LOAD_TIMEOUT_MS)) : null) ?? null,
13862
13952
  ttlMs: SLACK_PAUSE_BUCKET_MS
13863
13953
  };
13864
13954
  }) ?? void 0;
@@ -14195,7 +14285,7 @@ function pushErrorType(error) {
14195
14285
  */
14196
14286
  async function sendToDevice(subscription, body, config) {
14197
14287
  const serverAddress = new URL(subscription.endpoint).hostname;
14198
- return await withSpan("notification.push.send", "notification.push.send", {}, async (setSpanAttributes) => {
14288
+ return await withSpan$1("notification.push.send", "notification.push.send", {}, async (setSpanAttributes) => {
14199
14289
  let outcome;
14200
14290
  let statusCode;
14201
14291
  try {
@@ -14500,7 +14590,7 @@ async function writeConversationMetadata(db, input) {
14500
14590
  * imports search and the tools that save Annotations, so they load lazily.
14501
14591
  */
14502
14592
  async function loadAnnotationLabeler() {
14503
- const [{ annotationLabel }, { readObjectLinkTypes }] = await Promise.all([import("./agent-DxZ7nHfD.js").then((n) => n.Ct), import("./agent-DxZ7nHfD.js").then((n) => n.Mt)]);
14593
+ const [{ annotationLabel }, { readObjectLinkTypes }] = await Promise.all([import("./agent-OUkEw6Bv.js").then((n) => n.xt), import("./agent-OUkEw6Bv.js").then((n) => n.At)]);
14504
14594
  const linkTypes = readObjectLinkTypes();
14505
14595
  return (annotation) => annotationLabel(annotation, linkTypes);
14506
14596
  }
@@ -16188,7 +16278,7 @@ async function publishAgentUpdate(conversationId, key, options) {
16188
16278
  const eventKey = updateEventKey(conversationId, key);
16189
16279
  let update;
16190
16280
  const readUpdate = () => update ??= options.update();
16191
- const delivery = () => import("./agent-update-delivery-CO4FU5Gg.js");
16281
+ const delivery = () => import("./agent-update-delivery-H6mnPI4q.js");
16192
16282
  if (options.starter !== false) {
16193
16283
  const { deliverToStarter } = await delivery();
16194
16284
  await deliverToStarter({
@@ -17857,8 +17947,8 @@ function getConfigDefaults() {
17857
17947
  function createPluginCache(plugin, onStale) {
17858
17948
  const cache = () => createCache(getStateAdapter(), `plugin:${plugin}`, onStale ? { onStale } : void 0);
17859
17949
  return {
17860
- async get(key) {
17861
- return await cache().get(key);
17950
+ async get(key, options) {
17951
+ return await cache().get(key, options);
17862
17952
  },
17863
17953
  async getOrLoad(key, load, options) {
17864
17954
  return await cache().getOrLoad(key, load, options);
@@ -17977,7 +18067,7 @@ function pluginConfigValues(pluginName, configuration) {
17977
18067
  }
17978
18068
  /** Time one plugin hook call so slow plugins show up in turn traces. */
17979
18069
  async function withPluginHookSpan(pluginName, hookName, callback) {
17980
- return await withSpan(`plugin.hook ${hookName}`, "plugin.hook", {}, callback, {
18070
+ return await withSpan$1(`plugin.hook ${hookName}`, "plugin.hook", {}, callback, {
17981
18071
  "app.plugin.name": pluginName,
17982
18072
  "app.plugin.hook": hookName
17983
18073
  });
@@ -18250,7 +18340,7 @@ function createPluginState(plugin, adapter) {
18250
18340
  * returned to this plugin.
18251
18341
  */
18252
18342
  async function loadPluginPromptHistory(args) {
18253
- return await withSpan("plugin.prompt_history.load", "plugin.prompt_history.load", { conversationId: args.conversationId }, async (setSpanAttributes) => {
18343
+ return await withSpan$1("plugin.prompt_history.load", "plugin.prompt_history.load", { conversationId: args.conversationId }, async (setSpanAttributes) => {
18254
18344
  const eventStore = getConversationEventStore();
18255
18345
  const [replacement, contextEvents] = await Promise.all([eventStore.loadLatestEventOfTypes(args.conversationId, ["compaction", "handoff"]), eventStore.loadCurrentEventsOfType(args.conversationId, "turn_context")]);
18256
18346
  const contexts = contextEvents.flatMap((event) => event.data.type === "turn_context" && event.data.pluginName === args.pluginName ? [{
@@ -20003,11 +20093,22 @@ function getVercelQueueClients() {
20003
20093
  function visibility(consumer) {
20004
20094
  return consumer.visibilityTimeoutSeconds === void 0 ? {} : { visibilityTimeoutSeconds: consumer.visibilityTimeoutSeconds };
20005
20095
  }
20096
+ const MAX_IDEMPOTENCY_KEY_LENGTH = 256;
20097
+ function withBoundedIdempotencyKey(options) {
20098
+ const key = options?.idempotencyKey;
20099
+ if (!key || key.length <= MAX_IDEMPOTENCY_KEY_LENGTH) return options;
20100
+ const digest = createHash("sha256").update(key).digest("hex");
20101
+ const prefix = key.slice(0, MAX_IDEMPOTENCY_KEY_LENGTH - digest.length - 1);
20102
+ return {
20103
+ ...options,
20104
+ idempotencyKey: `${prefix}:${digest}`
20105
+ };
20106
+ }
20006
20107
  /** Queue provider backed by Vercel Queues. */
20007
20108
  const vercelQueueProvider = {
20008
20109
  messagingSystem: "vercel_queue",
20009
20110
  send: async (topic, payload, options) => {
20010
- const { messageId } = await getVercelQueueClients().send(topic, payload, options);
20111
+ const { messageId } = await getVercelQueueClients().send(topic, payload, withBoundedIdempotencyKey(options));
20011
20112
  return messageId ? { messageId } : {};
20012
20113
  },
20013
20114
  createCallback: (consumer) => getVercelQueueClients().callbacks.handleCallback(consumer.handler, {
@@ -20160,7 +20261,7 @@ function createVercelConversationWorkQueue(options = {}) {
20160
20261
  const client = options.client ?? getQueueProvider();
20161
20262
  return { async send(message, sendOptions) {
20162
20263
  const payload = signConversationQueueMessage(message);
20163
- return await withSpan("conversation.work.publish", "queue.publish", { conversationId: message.conversationId }, async (setSpanAttributes) => {
20264
+ return await withSpan$1("conversation.work.publish", "queue.publish", { conversationId: message.conversationId }, async (setSpanAttributes) => {
20164
20265
  const result = await client.send(topic, payload, {
20165
20266
  idempotencyKey: sendOptions?.idempotencyKey,
20166
20267
  delaySeconds: toDelaySeconds(sendOptions),
@@ -20660,19 +20761,16 @@ function sameContent(item, content) {
20660
20761
  }
20661
20762
  /** Why a plugin item closes when nobody on it has an ask now. */
20662
20763
  const NOBODY_LEFT_REASON = "Nobody on the item has an ask now.";
20663
- /** Field id of the one choice field of a plugin item with choices. */
20664
- const PLUGIN_CHOICE_FIELD_ID = "choice";
20665
- /** The request that shows a plugin item's choices as one row of buttons. */
20666
- function choicesRequest(notice) {
20667
- return inboxItemRequestSchema.parse({
20668
- question: notice.body,
20669
- fields: [{
20670
- id: PLUGIN_CHOICE_FIELD_ID,
20671
- kind: "choice",
20672
- label: notice.title,
20673
- options: notice.choices
20674
- }]
20675
- });
20764
+ /**
20765
+ * Return the kind action of a plugin item that closed with a pick of a
20766
+ * choice field named `choice`, as items did before kinds defined actions.
20767
+ * The picked label names the action by its label or, after the label
20768
+ * changed, by its id, as "Resume" names `resume`.
20769
+ */
20770
+ function legacyChoiceAction(item) {
20771
+ const label = item.answer?.values["choice"]?.[0];
20772
+ if (!label) return void 0;
20773
+ return subjectKindActions(item.subject.kind, getPlugins()).find((action) => action.label === label || action.id === label.toLowerCase())?.id;
20676
20774
  }
20677
20775
  /**
20678
20776
  * The stored subject of a plugin item: the plugin's own kind as
@@ -20743,10 +20841,9 @@ function createPluginInboxItems(args) {
20743
20841
  assigneeUserIds: userIds,
20744
20842
  body: notice.body,
20745
20843
  conversationIds: [.../* @__PURE__ */ new Set([conversationId, ...existing?.conversationIds ?? []])],
20746
- kind: notice.waitsOnAssignees || notice.choices ? "action" : "notice",
20844
+ kind: notice.waitsOnAssignees || subjectKindActions(subject.kind, getPlugins()).length > 0 ? "action" : "notice",
20747
20845
  title: notice.title,
20748
- subject,
20749
- ...notice.choices ? { request: choicesRequest(notice) } : void 0
20846
+ subject
20750
20847
  };
20751
20848
  if (existing && askedNow.size === 0 && sameContent(existing, content)) return;
20752
20849
  let itemId;
@@ -20787,10 +20884,24 @@ function createPluginInboxItems(args) {
20787
20884
  }
20788
20885
  return open && content.kind === "action" ? {
20789
20886
  itemId,
20790
- waitText: inboxItemQuestion(content.request)?.question ?? content.body
20887
+ waitText: content.body
20791
20888
  } : { itemId };
20792
20889
  };
20793
20890
  return {
20891
+ async history(subject) {
20892
+ const items = await listInboxItemsBySubject(getDb(), pluginItemSubject(args.plugin, subject));
20893
+ if (items[0]) requireOwner(items[0], conversationId);
20894
+ return items.map((item) => {
20895
+ const record = {
20896
+ id: item.id,
20897
+ status: item.status
20898
+ };
20899
+ const action = item.closeAction ?? legacyChoiceAction(item);
20900
+ if (action) record.action = action;
20901
+ if (item.closedAt) record.closedAtMs = item.closedAt.getTime();
20902
+ return record;
20903
+ });
20904
+ },
20794
20905
  async upsert(notice) {
20795
20906
  const subject = pluginItemSubject(args.plugin, notice.subject);
20796
20907
  if (!subjectKindLabel(subject.kind, getPlugins())) throw new Error(`Plugin "${args.plugin}" has no inbox subject kind "${notice.subject.kind}"`);
@@ -21263,7 +21374,7 @@ function pluginTaskCallback(options) {
21263
21374
  onRejected: logPluginTaskQueueMessageRejected,
21264
21375
  retryDelaySeconds: pluginTaskRetryDelaySeconds,
21265
21376
  run: async (message, metadata) => {
21266
- const { processPluginTask } = await import("./agent-DxZ7nHfD.js").then((n) => n.lt);
21377
+ const { processPluginTask } = await import("./agent-OUkEw6Bv.js").then((n) => n.st);
21267
21378
  await processPluginTask(message, {
21268
21379
  ...options,
21269
21380
  deliveryCount: metadata.deliveryCount
@@ -21860,14 +21971,18 @@ const SUGGESTED_SUFFIX = " (suggested)";
21860
21971
  function optionLabel(option, maxChars = Number.POSITIVE_INFINITY) {
21861
21972
  return option.recommended ? `${truncate$1(option.label, maxChars - 12)}${SUGGESTED_SUFFIX}` : option.label;
21862
21973
  }
21863
- /** The question and a short list of what to answer, in Slack markdown. */
21974
+ function fieldDetail(field) {
21975
+ return field.kind === "text" ? "short answer" : `${field.kind === "multi_choice" ? "pick any" : "pick one"}: ${field.options.map((option) => optionLabel(option)).join(", ")}`;
21976
+ }
21977
+ /**
21978
+ * The question and a short list of what to answer, in Slack markdown. A
21979
+ * request without a shared question shows each field's own question, so
21980
+ * each answer sits under its question.
21981
+ */
21864
21982
  function slackUserInputText(request) {
21865
21983
  const buttonField = buttonUserInputField(request);
21866
- const notes = buttonField ? buttonField.options.filter((option) => option.description).map((option) => `- **${optionLabel(option)}**: ${option.description}`) : request.fields.map((field) => {
21867
- const detail = field.kind === "text" ? "short answer" : `${field.kind === "multi_choice" ? "pick any" : "pick one"}: ${field.options.map((option) => optionLabel(option)).join(", ")}`;
21868
- return `- **${field.label}** (${detail})${field.description ? `: ${field.description}` : ""}`;
21869
- });
21870
- return normalizeSlackReplyMarkdown([request.question, ...notes.length ? [notes.join("\n")] : []].join("\n\n"));
21984
+ const optionNotes = buttonField ? buttonField.options.filter((option) => option.description).map((option) => `- **${optionLabel(option)}**: ${option.description}`) : [];
21985
+ return normalizeSlackReplyMarkdown((request.question ? [request.question, (buttonField ? optionNotes : request.fields.map((field) => `- **${field.label}** (${fieldDetail(field)})${field.description ? `: ${field.description}` : ""}`)).join("\n")] : request.fields.map((field) => [`**${field.label}**${field.description ? `: ${field.description}` : ""}`, ...buttonField ? optionNotes : [fieldDetail(field)]].join("\n"))).filter(Boolean).join("\n\n"));
21871
21986
  }
21872
21987
  function toOption(option) {
21873
21988
  return {
@@ -21878,17 +21993,16 @@ function toOption(option) {
21878
21993
  }
21879
21994
  /**
21880
21995
  * Render a request as a Slack modal form: one input for each field and one
21881
- * optional note input that goes with the answers. Every input is optional,
21882
- * so a person can answer with free text only. `callbackId` and `privateMetadata` tell the submit
21883
- * handler what the form answers.
21996
+ * optional notes input that goes with the answers. Every input is optional,
21997
+ * so a person can answer with free text only. `callbackId` and
21998
+ * `privateMetadata` tell the submit handler what the form answers.
21884
21999
  */
21885
22000
  function buildSlackUserInputForm(request, form) {
21886
22001
  const inputs = request.fields.map((field) => ({
21887
22002
  type: "input",
21888
22003
  block_id: `${FIELD_BLOCK_ID_PREFIX}${field.id}`,
21889
- label: plainText$1(field.label),
22004
+ label: plainText$1(field.description ? `${field.label}: ${field.description}` : field.label),
21890
22005
  optional: true,
21891
- ...field.description ? { hint: plainText$1(field.description) } : void 0,
21892
22006
  element: field.kind === "text" ? {
21893
22007
  type: "plain_text_input",
21894
22008
  action_id: VALUE_ACTION_ID,
@@ -21960,7 +22074,7 @@ function slackUserInputAnswerNote(args) {
21960
22074
  const values = answer.values[field.id];
21961
22075
  return values?.length ? [`*${escapeSlackMrkdwnText(field.label)}*: ${escapeSlackMrkdwnText(values.join(", "))}`] : [];
21962
22076
  });
21963
- if (answer.other) lines.push(`*Other*: ${escapeSlackMrkdwnText(answer.other)}`);
22077
+ if (answer.other) lines.push(`*${USER_INPUT_NOTE.label}*: ${escapeSlackMrkdwnText(answer.other)}`);
21964
22078
  return truncate$1([`${who} answered`, ...lines].join("\n"), MAX_NOTE_CHARS);
21965
22079
  }
21966
22080
  // src/net/link-url.ts
@@ -21980,6 +22094,7 @@ const SLACK_INBOX_ITEM_VIEW_ID = "junior_review_item";
21980
22094
  const ACTION_ID_PREFIX = "junior_review_item:";
21981
22095
  const CHOICE_ACTION_ID_PREFIX = `${ACTION_ID_PREFIX}choice:`;
21982
22096
  const ANSWER_ACTION_ID = `${ACTION_ID_PREFIX}answer`;
22097
+ const KIND_ACTION_ID_PREFIX = `${ACTION_ID_PREFIX}action:`;
21983
22098
  const DISMISS_ACTION_ID = `${ACTION_ID_PREFIX}dismiss`;
21984
22099
  const SNOOZE_ACTION_ID = `${ACTION_ID_PREFIX}snooze`;
21985
22100
  const MAX_BODY_CHARS = 3e3;
@@ -22042,9 +22157,10 @@ function relatedText(item) {
22042
22157
  function itemText(item, subjectUrl) {
22043
22158
  const question = inboxItemQuestion(item.request);
22044
22159
  const related = relatedText(item);
22160
+ const fromFields = question !== void 0 && !question.question;
22045
22161
  const render = (bodyChars) => normalizeSlackReplyMarkdown([
22046
- titleText(item, subjectUrl),
22047
- ...question?.question === item.body ? [] : [truncate(item.body, bodyChars)],
22162
+ ...fromFields ? [] : [titleText(item, subjectUrl)],
22163
+ ...fromFields || question?.question === item.body ? [] : [truncate(item.body, bodyChars)],
22048
22164
  ...related ? [related] : [],
22049
22165
  ...question ? [slackUserInputText(question)] : []
22050
22166
  ].join("\n\n"));
@@ -22072,8 +22188,15 @@ function controls(item) {
22072
22188
  text: plainText("Snooze"),
22073
22189
  url: snoozeUrl
22074
22190
  }] : []];
22191
+ if (item.kind === "notice") return quiet;
22075
22192
  const question = inboxItemQuestion(item.request);
22076
- if (item.kind === "notice" || !question) return quiet;
22193
+ if (!question) return [...quiet, ...subjectKindActions(item.subject.kind, getPlugins()).map((action) => ({
22194
+ type: "button",
22195
+ action_id: `${KIND_ACTION_ID_PREFIX}${action.id}`,
22196
+ style: "primary",
22197
+ text: plainText(action.label),
22198
+ value: item.id
22199
+ }))];
22077
22200
  const buttonField = buttonUserInputField(question);
22078
22201
  if (!buttonField) return [...quiet, {
22079
22202
  type: "button",
@@ -22106,11 +22229,13 @@ function controls(item) {
22106
22229
  function closedNote(item) {
22107
22230
  const who = item.closedBy ? personName(item.closedBy) : void 0;
22108
22231
  if (item.closeReason === "Replied in thread") return `${who ?? "A person"} replied in the thread`;
22232
+ const action = subjectKindActionLabel(item.subject.kind, getPlugins(), item.closeAction);
22233
+ if (item.status === "done" && action && who) return `${who} chose *${escapeSlackMrkdwnText(action)}*`;
22109
22234
  const question = inboxItemQuestion(item.request);
22110
- if (item.status === "done" && question && item.answer && who) return slackUserInputAnswerNote({
22235
+ if (item.status === "done" && question && item.answer && item.answeredBy) return slackUserInputAnswerNote({
22111
22236
  answer: item.answer,
22112
22237
  request: question,
22113
- who
22238
+ who: personName(item.answeredBy)
22114
22239
  });
22115
22240
  if (who) return item.status === "done" ? `${who} marked this done` : `${who} dismissed this`;
22116
22241
  const status = item.status === "done" ? "Closed as done" : "Dismissed";
@@ -22119,8 +22244,8 @@ function closedNote(item) {
22119
22244
  /**
22120
22245
  * Render an Inbox item as one Slack message. An open item shows its
22121
22246
  * controls: one button per choice when one click can answer it, an Answer
22122
- * button that opens a form otherwise, and only Dismiss and Snooze for a
22123
- * notice. A
22247
+ * button that opens a form otherwise, the buttons of its kind for an action
22248
+ * item without a question, and only Dismiss and Snooze for a notice. A
22124
22249
  * closed item shows a note instead, so nobody can act on it again.
22125
22250
  */
22126
22251
  function buildSlackInboxItemCard(item, subjectUrl) {
@@ -22178,6 +22303,14 @@ function parseChoiceValue(value) {
22178
22303
  function parseSlackInboxItemClick(action) {
22179
22304
  const value = action.value?.trim();
22180
22305
  if (!value || !action.action_id?.startsWith(ACTION_ID_PREFIX)) return;
22306
+ if (action.action_id.startsWith(KIND_ACTION_ID_PREFIX)) {
22307
+ const id = action.action_id.slice(KIND_ACTION_ID_PREFIX.length);
22308
+ return id ? {
22309
+ kind: "action",
22310
+ itemId: value,
22311
+ action: id
22312
+ } : void 0;
22313
+ }
22181
22314
  if (action.action_id.startsWith(CHOICE_ACTION_ID_PREFIX)) {
22182
22315
  const choice = parseChoiceValue(value);
22183
22316
  return choice ? {
@@ -22342,6 +22475,179 @@ async function syncInboxItemSlackCards(args) {
22342
22475
  }, { waitMs: SYNC_LOCK_WAIT_MS })).acquired) throw new Error("Another Inbox item card sync held the lock");
22343
22476
  }, "inbox_item.slack_card.sync.failed", { "app.inbox_item.id": itemId });
22344
22477
  }
22478
+ // src/chat/tool-support/zod-tool.ts
22479
+ function isContentOnlyToolResult(value) {
22480
+ return value !== null && typeof value === "object" && Array.isArray(value.content) && !("details" in value);
22481
+ }
22482
+ function isStructuredToolResultEnvelope(value) {
22483
+ return value !== null && typeof value === "object" && Array.isArray(value.content) && "details" in value;
22484
+ }
22485
+ function parseToolContent(content) {
22486
+ for (const item of content) if (!item || typeof item !== "object" || (item.type === "text" ? typeof item.text !== "string" : item.type === "image" ? typeof item.data !== "string" || typeof item.mimeType !== "string" : true)) throw new TypeError("zodTool() content must contain valid text or image items.");
22487
+ return content;
22488
+ }
22489
+ function formatZodPath(path) {
22490
+ return path.length > 0 ? path.map(String).join(".") : "root";
22491
+ }
22492
+ function formatToolInputError(error) {
22493
+ return `Invalid tool arguments: ${error.issues.slice(0, 5).map((issue) => `${formatZodPath(issue.path)}: ${issue.message}`).join("; ") || "input did not match schema"}`;
22494
+ }
22495
+ /** Parse tool input with its Zod schema, as a model-repairable error on failure. */
22496
+ function parseToolInput(schema, args) {
22497
+ const result = schema.safeParse(args);
22498
+ if (!result.success) throw new ToolInputError(formatToolInputError(result.error), { cause: result.error });
22499
+ return result.data;
22500
+ }
22501
+ /** Declare the static definition of a Zod tool once, for the registry and its factory. */
22502
+ function zodToolDefinition(definition) {
22503
+ return definition;
22504
+ }
22505
+ function zodTool(definition) {
22506
+ const { inputSchema, outputSchema, prepareArguments, execute, ...toolDef } = definition;
22507
+ let modelInputSchema;
22508
+ try {
22509
+ modelInputSchema = z.toJSONSchema(inputSchema);
22510
+ } catch (error) {
22511
+ throw new TypeError("zodTool() inputSchema must be representable as JSON Schema.", { cause: error });
22512
+ }
22513
+ let modelOutputSchema;
22514
+ if (outputSchema) try {
22515
+ modelOutputSchema = z.toJSONSchema(outputSchema);
22516
+ } catch (error) {
22517
+ throw new TypeError("zodTool() outputSchema must be representable as JSON Schema.", { cause: error });
22518
+ }
22519
+ return {
22520
+ ...toolDef,
22521
+ inputSchema: modelInputSchema,
22522
+ ...modelOutputSchema ? { outputSchema: modelOutputSchema } : void 0,
22523
+ prepareArguments(args) {
22524
+ return parseToolInput(inputSchema, prepareArguments ? prepareArguments(args) : args);
22525
+ },
22526
+ ...execute ? { async execute(input, options) {
22527
+ const result = await execute(input, options);
22528
+ if (!outputSchema) {
22529
+ if (isContentOnlyToolResult(result)) return result;
22530
+ throw new TypeError("zodTool() content-only tools must return { content } without details.");
22531
+ }
22532
+ if (isStructuredToolResultEnvelope(result)) return {
22533
+ content: parseToolContent(result.content),
22534
+ details: outputSchema.parse(result.details)
22535
+ };
22536
+ return outputSchema.parse(result);
22537
+ } } : void 0
22538
+ };
22539
+ }
22540
+ // src/chat/inbox-items/tool-support.ts
22541
+ /** Shared input and result shapes of the Inbox item tools. */
22542
+ /** Deferred tool catalog source for the Inbox item tools. */
22543
+ const INBOX_TOOL_SOURCE = {
22544
+ id: "inbox",
22545
+ description: "Update and search Inbox items: work that needs a person."
22546
+ };
22547
+ /** Who can act on an Inbox item. */
22548
+ const assigneesSchema = z.array(z.string().trim().min(1).max(320)).min(1).max(20).describe("Who can act on the item. Each entry is `everyone`, an email, or a mention such as `<@U123>`. Everyone means any person who can see the item.");
22549
+ /** Conversations that an Inbox item links to. */
22550
+ const conversationIdsSchema = z.array(z.string().trim().min(1).max(500)).max(10);
22551
+ /** Deliver an Inbox item change through the services of the tools. */
22552
+ function inboxItemDelivery(services) {
22553
+ return {
22554
+ queue: services.queue(),
22555
+ show: services.show
22556
+ };
22557
+ }
22558
+ /** The owner Conversation of an item, as a list of Conversations to check. */
22559
+ function ownerLinks(item) {
22560
+ const conversationId = item ? ownerConversationId(item) : void 0;
22561
+ return conversationId ? [conversationId] : [];
22562
+ }
22563
+ /** Read an Inbox item that the agent may read, or fail with a tool input error. */
22564
+ async function readableItem(id, scope) {
22565
+ const item = await getInboxItem(getDb(), id);
22566
+ if (!item || !canReadInboxItem(item, scope.reader)) throw new ToolInputError(`Inbox item ${id} is not found. Use searchInboxItems to find its id.`);
22567
+ return item;
22568
+ }
22569
+ /** Render one Inbox item for a tool result. */
22570
+ function itemResult(item) {
22571
+ return {
22572
+ id: item.id,
22573
+ kind: item.kind,
22574
+ status: item.status,
22575
+ title: item.title,
22576
+ body: item.body,
22577
+ assignees: [...item.assignedToEveryone ? [EVERYONE_ASSIGNEE] : [], ...item.assignees.map((assignee) => assignee.email)],
22578
+ conversation_ids: item.conversationIds,
22579
+ visibility: item.visibility,
22580
+ updated_at: item.updatedAt.toISOString(),
22581
+ subject: item.subject,
22582
+ ...item.addedByAutomationId ? { automation_id: item.addedByAutomationId } : void 0,
22583
+ ...item.request ? { request: requestResult(item.request) } : void 0,
22584
+ ...item.answer ? { answer: item.answer } : void 0,
22585
+ ...item.closedAt ? {
22586
+ closed_at: item.closedAt.toISOString(),
22587
+ closed_by: (item.answer ? item.answeredBy : item.closedBy)?.email ?? "agent"
22588
+ } : void 0,
22589
+ ...item.closeReason ? { close_reason: item.closeReason } : void 0
22590
+ };
22591
+ }
22592
+ /** Show the stored question with the tool's snake_case related link keys. */
22593
+ function requestResult({ related, ...question }) {
22594
+ return {
22595
+ ...question,
22596
+ ...related ? { related: related.map(({ conversationId, ...entry }) => ({
22597
+ ...entry,
22598
+ ...conversationId ? { conversation_id: conversationId } : void 0
22599
+ })) } : void 0
22600
+ };
22601
+ }
22602
+ const RECOMMENDED_SUFFIX = /\s*\(recommended\)$/i;
22603
+ const MAX_TITLE_CHARS = 200;
22604
+ const questionOptionSchema = z.object({
22605
+ label: z.string().trim().min(1).max(USER_INPUT_LIMITS.maxLabelChars).describe("The choice the person picks, 1-5 words. The answer uses this text."),
22606
+ description: z.string().trim().min(1).max(USER_INPUT_LIMITS.maxDescriptionChars).describe("What this choice means or what happens if it is picked.")
22607
+ }).strict();
22608
+ /**
22609
+ * The questions of `askUserQuestion` and `updateInboxItem`. The keys are
22610
+ * the ones of Claude Code's `AskUserQuestion`, which models know, so they
22611
+ * are camelCase where it is (`multiSelect`).
22612
+ */
22613
+ const questionsSchema = z.array(z.object({
22614
+ question: z.string().trim().min(1).max(USER_INPUT_LIMITS.maxFieldDescriptionChars).describe("The complete question, clear and specific, ending with a question mark."),
22615
+ header: z.string().trim().min(1).max(12).describe("A very short label for the question, max 12 characters, such as `Approach`."),
22616
+ options: z.array(questionOptionSchema).min(USER_INPUT_LIMITS.minOptions).max(4).describe("The 2-4 choices. Put the recommended one first and end its label with \"(Recommended)\". Do not add an \"Other\" choice: the person can always write their own answer."),
22617
+ multiSelect: z.boolean().nullable().optional().describe("True lets the person pick more than one choice. Default false.")
22618
+ }).strict()).min(1).max(USER_INPUT_LIMITS.maxFields).describe("The questions to ask, 1-4. Ask each decision as its own question, with its own choices, not several decisions in one question.");
22619
+ /** Cut text to the length of an item title, as a question's title is cut. */
22620
+ function cutInboxItemTitle(text) {
22621
+ return text.length <= MAX_TITLE_CHARS ? text : `${text.slice(0, 199)}…`;
22622
+ }
22623
+ /**
22624
+ * Store each question as one field with its own question, header, and
22625
+ * choices, and no question that the fields share, so every surface shows
22626
+ * each question with its own answer. A label that ends with
22627
+ * "(Recommended)" becomes a recommended choice.
22628
+ */
22629
+ function questionContent(questions) {
22630
+ const fields = questions.map((entry, index) => ({
22631
+ id: `q${index + 1}`,
22632
+ label: entry.header,
22633
+ description: entry.question,
22634
+ kind: entry.multiSelect ? "multi_choice" : "choice",
22635
+ options: entry.options.map((option) => {
22636
+ const label = option.label.replace(RECOMMENDED_SUFFIX, "").trim();
22637
+ return {
22638
+ label: label || option.label,
22639
+ description: option.description,
22640
+ ...label && label !== option.label ? { recommended: true } : void 0
22641
+ };
22642
+ })
22643
+ }));
22644
+ const request = parseToolInput(inboxItemRequestSchema, { fields });
22645
+ return {
22646
+ body: questions.map((entry) => entry.question).join("\n\n"),
22647
+ request,
22648
+ title: cutInboxItemTitle(questions.length === 1 ? questions[0].question : questions.map((entry) => entry.header).join(" · "))
22649
+ };
22650
+ }
22345
22651
  // src/chat/notifications/inbox-item-push.ts
22346
22652
  /**
22347
22653
  * How long a Slack card waits before its item pushes. A User who saw the
@@ -22419,12 +22725,13 @@ async function deliverPush(args) {
22419
22725
  logInfo("notification.inbox_item.skipped", { "app.notification.skip_reason": reason });
22420
22726
  return;
22421
22727
  }
22728
+ const repeatsTitle = item.title === cutInboxItemTitle(item.body);
22422
22729
  await sendPushNotificationToUser({
22423
22730
  config: args.config,
22424
22731
  db,
22425
22732
  kind: args.kind,
22426
22733
  payload: {
22427
- body: notificationPreview(item.body),
22734
+ body: repeatsTitle ? "" : notificationPreview(item.body),
22428
22735
  tag: item.id,
22429
22736
  title: item.title,
22430
22737
  url: args.url
@@ -22469,7 +22776,7 @@ async function syncInboxItemPush(itemId, options = {}) {
22469
22776
  await scheduleSlackCardPushes(db, item);
22470
22777
  return;
22471
22778
  }
22472
- await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, async () => {
22779
+ await withSpan$1("notification.inbox_item.push", "notification.inbox_item.push", {}, async () => {
22473
22780
  const pushed = await listInboxItemPushUserIds(db, item.id);
22474
22781
  await mapBounded(userIds.filter((userId) => !pushed.has(userId)), (userId) => deliverPush({
22475
22782
  config,
@@ -22510,7 +22817,7 @@ async function pushInboxSnoozeWakes(wakes) {
22510
22817
  const item = await getInboxItem(db, wake.inboxItemId);
22511
22818
  const url = item && wakePushUrl(item, wake.userId);
22512
22819
  if (!item || !url) return;
22513
- await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
22820
+ await withSpan$1("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
22514
22821
  config,
22515
22822
  db,
22516
22823
  item,
@@ -22557,7 +22864,7 @@ async function pushAfterSlackCard(db, config, timerId, unassigned) {
22557
22864
  }
22558
22865
  const url = getDashboardInboxItemLink(item.id);
22559
22866
  if (!url) return;
22560
- await withSpan("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
22867
+ await withSpan$1("notification.inbox_item.push", "notification.inbox_item.push", {}, () => deliverPush({
22561
22868
  afterSlackCard: true,
22562
22869
  config,
22563
22870
  db,
@@ -22813,6 +23120,1299 @@ function normalizeMessageSenders(value) {
22813
23120
  }
22814
23121
  return Object.keys(senders).length ? senders : void 0;
22815
23122
  }
23123
+ // src/conversation-events/lock.ts
23124
+ /** Serialize event sequence allocation with other conversation writes. */
23125
+ async function withConversationEventLock(executor, conversationId, callback) {
23126
+ return executor.withLock(`junior_conversation:${conversationId}`, callback);
23127
+ }
23128
+ // src/chat/conversations/stop-state.ts
23129
+ /** Return when a Conversation stopped, or undefined when it is not stopped. */
23130
+ async function getConversationStoppedAtMs(conversationId) {
23131
+ const [row] = await getSqlExecutor().db().select({ stoppedAt: juniorConversations.stoppedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
23132
+ return row?.stoppedAt?.getTime();
23133
+ }
23134
+ /**
23135
+ * End the stop of a Conversation and of the child agents below it, for new
23136
+ * work sent at `sentAtMs`: a person's input, or new work from its parent.
23137
+ * Nothing changes for work sent at or before the stop, so the input that a
23138
+ * stop drops does not undo it. Only Conversations that stopped no later than
23139
+ * this Conversation change, so a later stop of one child agent stays.
23140
+ */
23141
+ async function resumeConversationTree(conversationId, sentAtMs) {
23142
+ const subtree = sql`(select ${conversationSubtreeColumns.conversationId} from ${conversationSubtree([conversationId])})`;
23143
+ const executor = getSqlExecutor();
23144
+ await withConversationEventLock(executor, conversationId, () => executor.transaction(async () => {
23145
+ const tx = executor.db();
23146
+ const stoppedAt = (await tx.select({
23147
+ conversationId: juniorConversations.conversationId,
23148
+ stoppedAt: juniorConversations.stoppedAt
23149
+ }).from(juniorConversations).where(inArray(juniorConversations.conversationId, subtree)).orderBy(asc(juniorConversations.conversationId)).for("update")).find((row) => row.conversationId === conversationId)?.stoppedAt;
23150
+ if (!stoppedAt || sentAtMs <= stoppedAt.getTime()) return;
23151
+ await tx.update(juniorConversations).set({
23152
+ stoppedAt: null,
23153
+ detailVersion: nextDetailVersion
23154
+ }).where(and(inArray(juniorConversations.conversationId, subtree), lte(juniorConversations.stoppedAt, stoppedAt)));
23155
+ }));
23156
+ }
23157
+ // src/chat/conversations/web-mailbox.ts
23158
+ /** Parse web mailbox metadata written before Source and Actor were complete. */
23159
+ const legacyWebMailboxMetadataSchema = z.object({
23160
+ authorEmail: z.string().email(),
23161
+ authorFullName: z.string().min(1).optional(),
23162
+ authorUserId: z.string().min(1),
23163
+ authorUserName: z.string().min(1).optional(),
23164
+ kind: z.literal("api_turn"),
23165
+ messageId: z.string().min(1)
23166
+ }).strict();
23167
+ // src/chat/slack/context.ts
23168
+ function toTrimmedSlackString(value) {
23169
+ return toOptionalString(value)?.trim() || void 0;
23170
+ }
23171
+ const slackMessageEnvelopeSchema = z.object({ raw: z.unknown().optional() });
23172
+ const rawSlackMessageSchema = z.object({
23173
+ channel: z.unknown().optional(),
23174
+ message: z.unknown().optional(),
23175
+ team: z.unknown().optional(),
23176
+ team_id: z.unknown().optional(),
23177
+ thread_ts: z.unknown().optional(),
23178
+ ts: z.unknown().optional(),
23179
+ user_team: z.unknown().optional()
23180
+ });
23181
+ const nestedRawSlackMessageSchema = z.object({ ts: z.unknown().optional() });
23182
+ /** Project only the Slack raw fields consumed by runtime thread context. */
23183
+ function readSlackRawMessageContext(message) {
23184
+ const envelope = slackMessageEnvelopeSchema.safeParse(message);
23185
+ if (!envelope.success) return;
23186
+ const raw = rawSlackMessageSchema.safeParse(envelope.data.raw);
23187
+ if (!raw.success) return;
23188
+ const nestedMessage = nestedRawSlackMessageSchema.safeParse(raw.data.message);
23189
+ const channelId = parseSlackChannelId(raw.data.channel);
23190
+ const threadTs = parseSlackMessageTs(raw.data.thread_ts);
23191
+ const messageTs = parseSlackMessageTs(raw.data.ts);
23192
+ const nestedMessageTs = nestedMessage.success && parseSlackMessageTs(nestedMessage.data.ts);
23193
+ const teamId = parseSlackTeamId(raw.data.team_id) ?? parseSlackTeamId(raw.data.team);
23194
+ const authorTeamId = parseSlackTeamId(raw.data.user_team);
23195
+ return {
23196
+ ...channelId ? { channelId } : void 0,
23197
+ ...threadTs ? { threadTs } : void 0,
23198
+ ...messageTs ? { messageTs } : void 0,
23199
+ ...nestedMessageTs ? { nestedMessageTs } : void 0,
23200
+ ...teamId ? { teamId } : void 0,
23201
+ ...authorTeamId ? { authorTeamId } : void 0
23202
+ };
23203
+ }
23204
+ /** Extract a channel ID and validated Slack timestamp from `slack:<channel>:<ts>`. */
23205
+ function parseSlackThreadId(threadId) {
23206
+ const normalizedThreadId = toTrimmedSlackString(threadId);
23207
+ if (!normalizedThreadId) return;
23208
+ const parts = normalizedThreadId.split(":");
23209
+ if (parts.length !== 3 || parts[0] !== "slack") return;
23210
+ const channelId = parseSlackChannelId(parts[1]);
23211
+ const threadTs = parseSlackMessageTs(parts[2]);
23212
+ if (!channelId || !threadTs) return;
23213
+ return {
23214
+ channelId,
23215
+ threadTs
23216
+ };
23217
+ }
23218
+ /** Best-effort channel ID extraction from a raw Slack message payload. */
23219
+ function resolveSlackChannelIdFromMessage(message) {
23220
+ const messageChannelId = parseSlackChannelId(message.channelId);
23221
+ if (messageChannelId) return messageChannelId;
23222
+ const raw = message.raw;
23223
+ if (raw && typeof raw === "object") {
23224
+ const rawChannel = parseSlackChannelId(raw.channel);
23225
+ if (rawChannel) return rawChannel;
23226
+ }
23227
+ }
23228
+ // src/chat/slack/conversation-context.ts
23229
+ function normalizeConversationName(type, channelName) {
23230
+ const trimmed = channelName?.trim();
23231
+ if (!trimmed) return void 0;
23232
+ if (type === "public_channel" || type === "private_channel" || type === "private_channel_or_group_dm") return trimmed.startsWith("#") ? trimmed : `#${trimmed}`;
23233
+ return trimmed;
23234
+ }
23235
+ function typeFromSlackChannelType(channelType) {
23236
+ if (channelType === "channel") return "public_channel";
23237
+ if (channelType === "group") return "private_channel";
23238
+ if (channelType === "mpim") return "group_dm";
23239
+ if (channelType === "im") return "direct_message";
23240
+ }
23241
+ function typeFromChannelId(channelId, channelName) {
23242
+ const normalized = normalizeSlackConversationId(channelId);
23243
+ if (!normalized) return void 0;
23244
+ if (normalized.startsWith("C")) return "public_channel";
23245
+ if (normalized.startsWith("D")) return "direct_message";
23246
+ if (normalized.startsWith("G")) return channelName?.trim().startsWith("mpdm-") ? "group_dm" : "private_channel_or_group_dm";
23247
+ }
23248
+ function toSlackEventChannelType(channelType) {
23249
+ if (channelType === "channel" || channelType === "group" || channelType === "mpim" || channelType === "im") return channelType;
23250
+ }
23251
+ /**
23252
+ * Map Slack's Events API channel_type to a source-confirmed visibility.
23253
+ *
23254
+ * Slack's event metadata and live conversation metadata are the only
23255
+ * visibility authorities; channel IDs never classify visibility.
23256
+ */
23257
+ function conversationVisibilityFromSlackChannelType(channelType) {
23258
+ if (!channelType) return void 0;
23259
+ return channelType === "channel" ? "public" : "private";
23260
+ }
23261
+ /**
23262
+ * Map live `conversations.info` metadata to Slack's Events API channel type,
23263
+ * for events that carry no `channel_type`.
23264
+ */
23265
+ function slackChannelTypeFromConversationInfo(info) {
23266
+ if (info.isIm) return "im";
23267
+ if (info.isMpim) return "mpim";
23268
+ if (info.isPrivate) return "group";
23269
+ return info.isChannel ? "channel" : void 0;
23270
+ }
23271
+ /** Resolve Slack's raw event channel type from a Chat SDK message-like object. */
23272
+ function resolveSlackChannelTypeFromMessage(message) {
23273
+ const raw = message.raw;
23274
+ if (!raw || typeof raw !== "object") return;
23275
+ const channelType = raw["channel_type"];
23276
+ return typeof channelType === "string" ? toSlackEventChannelType(channelType.trim()) : void 0;
23277
+ }
23278
+ /** Build Slack conversation facts available to runtime consumers. */
23279
+ function resolveSlackConversationContext(input) {
23280
+ const type = typeFromSlackChannelType(input.channelType) ?? typeFromChannelId(input.channelId, input.channelName);
23281
+ if (!type) return void 0;
23282
+ const name = normalizeConversationName(type, input.channelName);
23283
+ const topic = input.channelTopic?.trim();
23284
+ const description = input.channelDescription?.trim();
23285
+ const visibility = conversationVisibilityFromSlackChannelType(input.channelType);
23286
+ return {
23287
+ type,
23288
+ ...name ? { name } : void 0,
23289
+ ...topic ? { topic } : void 0,
23290
+ ...description ? { description } : void 0,
23291
+ ...visibility ? { visibility } : void 0,
23292
+ ...input.botUserId ? { botUserId: input.botUserId } : void 0
23293
+ };
23294
+ }
23295
+ /** Build Slack conversation facts from Junior's persisted Slack thread id. */
23296
+ function resolveSlackConversationContextFromThreadId(input) {
23297
+ const context = resolveSlackConversationContext({
23298
+ channelId: parseSlackThreadId(input.threadId)?.channelId,
23299
+ channelName: input.channelName
23300
+ });
23301
+ if (!context || !input.visibility) return context;
23302
+ return {
23303
+ ...context,
23304
+ type: input.visibility === "private" && context.type === "public_channel" ? "private_channel" : context.type,
23305
+ visibility: input.visibility
23306
+ };
23307
+ }
23308
+ /** Render a human label for a privacy-preserving Slack conversation type. */
23309
+ function formatSlackConversationTypeLabel(type) {
23310
+ if (type === "public_channel") return "Public Channel";
23311
+ if (type === "private_channel") return "Private Channel";
23312
+ if (type === "group_dm") return "Group DM";
23313
+ if (type === "direct_message") return "Direct Message";
23314
+ return "Private Channel or Group DM";
23315
+ }
23316
+ /** Render a Slack conversation label without exposing conversation names. */
23317
+ function formatSlackConversationRedactedLabel(context) {
23318
+ if (!context) return void 0;
23319
+ return formatSlackConversationTypeLabel(context.type);
23320
+ }
23321
+ // src/core/telemetry.ts
23322
+ const SENTRY_TRACE_PATTERN = /^([0-9a-f]{32})-([0-9a-f]{16})(?:-([01]))?$/;
23323
+ function spanLink({ sentryTrace }) {
23324
+ const [, traceId, spanId, sampled] = SENTRY_TRACE_PATTERN.exec(sentryTrace) ?? [];
23325
+ return traceId && spanId ? [{ context: {
23326
+ traceId,
23327
+ spanId,
23328
+ traceFlags: sampled === "1" ? 1 : 0
23329
+ } }] : [];
23330
+ }
23331
+ /** Returns the trace context of the active span, so other work can link to it. */
23332
+ function activeTraceContext() {
23333
+ const sentryTrace = Sentry.getTraceData()["sentry-trace"];
23334
+ return sentryTrace ? { sentryTrace } : void 0;
23335
+ }
23336
+ /** Sets attributes on the active span, such as ids that a step learns late. */
23337
+ function setActiveSpanAttributes(attributes) {
23338
+ Sentry.getActiveSpan()?.setAttributes(attributes);
23339
+ }
23340
+ /** Adds one to a counter metric. Metrics are not sampled, unlike spans. */
23341
+ function countMetric(name, attributes) {
23342
+ Sentry.metrics.count(name, 1, { attributes });
23343
+ }
23344
+ const SPAN_STATUS_ERROR = 2;
23345
+ /** Runs `run` in a span whose op is `name`, and whose name is too by default. */
23346
+ function withSpan(name, attributes, run, options = {}) {
23347
+ const start = () => Sentry.startSpanManual({
23348
+ name: options.spanName ?? name,
23349
+ op: name,
23350
+ attributes,
23351
+ links: options.links?.flatMap(spanLink)
23352
+ }, async (span) => {
23353
+ try {
23354
+ return await run({
23355
+ setAttribute: (key, value) => span.setAttribute(key, value),
23356
+ setAttributes: (values) => span.setAttributes(values),
23357
+ fail: (message) => span.setStatus({
23358
+ code: SPAN_STATUS_ERROR,
23359
+ message
23360
+ })
23361
+ });
23362
+ } catch (error) {
23363
+ if (!options.isExpectedError?.(error)) {
23364
+ span.setStatus({
23365
+ code: SPAN_STATUS_ERROR,
23366
+ message: "internal_error"
23367
+ });
23368
+ span.setAttribute("error.type", error instanceof Error ? error.name : typeof error);
23369
+ }
23370
+ throw error;
23371
+ } finally {
23372
+ span.end();
23373
+ }
23374
+ });
23375
+ return options.newTrace ? Sentry.startNewTrace(start) : start();
23376
+ }
23377
+ // src/core/queue.ts
23378
+ const VISIBILITY_TIMEOUT_BUFFER_SECONDS = 30;
23379
+ /** Defines one signed topic. Returns its publish function and its consumer. */
23380
+ function signedTopic(def) {
23381
+ const publish = async ({ queue }, message, options = {}) => {
23382
+ await withSpan("queue.publish", {
23383
+ ...def.attributes(message),
23384
+ "messaging.destination.name": def.topic,
23385
+ "messaging.system": queue.messagingSystem
23386
+ }, async (span) => {
23387
+ const traceContext = activeTraceContext();
23388
+ const payload = signQueueMessage(def.sign, traceContext ? {
23389
+ ...message,
23390
+ traceContext
23391
+ } : message);
23392
+ span.setAttribute("messaging.message.body.size", Buffer.byteLength(JSON.stringify(payload)));
23393
+ const result = await queue.send(def.topic, payload, {
23394
+ delaySeconds: options.delayMs && options.delayMs > 0 ? Math.ceil(options.delayMs / 1e3) : void 0,
23395
+ idempotencyKey: options.idempotencyKey,
23396
+ retentionSeconds: QUEUE_SIGNATURE_MAX_AGE_MS / 1e3
23397
+ });
23398
+ if (result.messageId) span.setAttribute("messaging.message.id", result.messageId);
23399
+ });
23400
+ };
23401
+ const consumer = ({ queue, leaseMs }, run) => ({
23402
+ handler: async (value, metadata) => {
23403
+ const checked = verifyQueueMessage(def.sign, value);
23404
+ if (checked.status === "rejected") {
23405
+ def.onRejected({
23406
+ "app.queue.consumer_group": metadata.consumerGroup,
23407
+ "app.queue.delivery_count": metadata.deliveryCount,
23408
+ "app.queue.message_id": metadata.messageId,
23409
+ "app.queue.reject_reason": checked.reason,
23410
+ "app.queue.topic_name": metadata.topicName
23411
+ });
23412
+ return;
23413
+ }
23414
+ if (checked.status === "unavailable") throw new Error(`Queue message verification unavailable: ${checked.reason}`);
23415
+ const message = checked.message;
23416
+ await withSpan("queue.process", {
23417
+ ...def.attributes(message),
23418
+ "messaging.destination.name": metadata.topicName,
23419
+ "messaging.system": queue.messagingSystem,
23420
+ "messaging.message.id": metadata.messageId,
23421
+ "messaging.message.receive.latency": Date.now() - metadata.createdAt.getTime(),
23422
+ "messaging.message.retry.count": metadata.deliveryCount - 1
23423
+ }, () => run(message, metadata), {
23424
+ links: message.traceContext ? [message.traceContext] : [],
23425
+ newTrace: true
23426
+ });
23427
+ },
23428
+ retry: () => void 0,
23429
+ visibilityTimeoutSeconds: leaseMs / 1e3 + VISIBILITY_TIMEOUT_BUFFER_SECONDS
23430
+ });
23431
+ return {
23432
+ publish,
23433
+ consumer
23434
+ };
23435
+ }
23436
+ // src/core/turn/ended.ts
23437
+ const turnEndedMessageSchema = z.object({
23438
+ conversationId: z.string().min(1),
23439
+ turnId: z.string().min(1),
23440
+ traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
23441
+ }).strict();
23442
+ const turnEndedTopic = signedTopic({
23443
+ topic: TURN_ENDED_TOPIC,
23444
+ sign: {
23445
+ context: "junior.turn_ended.v1",
23446
+ schema: turnEndedMessageSchema,
23447
+ signatureVersion: "v1",
23448
+ parts: (message) => [
23449
+ message.conversationId,
23450
+ message.turnId,
23451
+ message.traceContext?.sentryTrace ?? ""
23452
+ ]
23453
+ },
23454
+ onRejected: (attributes) => logWarn("turn.ended.queue_message.rejected", attributes),
23455
+ attributes: (message) => ({
23456
+ "app.turn.id": message.turnId,
23457
+ "gen_ai.conversation.id": message.conversationId
23458
+ })
23459
+ });
23460
+ /**
23461
+ * Sends the message that the Turn ended, after `delayMs` if set. A handler
23462
+ * that must try its work again later sends it again with a delay.
23463
+ */
23464
+ async function publishTurnEnded(ctx, message, options = {}) {
23465
+ await turnEndedTopic.publish(ctx, message, options);
23466
+ }
23467
+ /**
23468
+ * Reads the messages that a Turn ended: it checks that core sent each one,
23469
+ * then calls `handle`. It acknowledges a message with a bad or expired
23470
+ * signature and retries one that cannot be checked yet. The host mounts the
23471
+ * consumer on its queue provider.
23472
+ */
23473
+ function readTurnEndedMessages(ctx, handle) {
23474
+ return turnEndedTopic.consumer(ctx, (message, metadata) => handle({
23475
+ conversationId: message.conversationId,
23476
+ turnId: message.turnId
23477
+ }, metadata));
23478
+ }
23479
+ // src/core/turn/inbox.ts
23480
+ /**
23481
+ * Finds the Turn of the input that has this idempotency key in the
23482
+ * Conversation. Undefined when no such input exists.
23483
+ */
23484
+ async function findInputTurn({ executor }, args) {
23485
+ const [turn] = await executor.db().select({
23486
+ turnId: juniorTurns.id,
23487
+ state: juniorTurns.state
23488
+ }).from(juniorTurnInbox).innerJoin(juniorTurns, eq(juniorTurns.id, juniorTurnInbox.turnId)).where(and(eq(juniorTurnInbox.conversationId, args.conversationId), eq(juniorTurnInbox.idempotencyKey, args.idempotencyKey)));
23489
+ return turn;
23490
+ }
23491
+ /**
23492
+ * Finds where a Turn's answer goes: the Destination of its first input. Null
23493
+ * when the Turn answers only in the Conversation history.
23494
+ */
23495
+ async function findTurnDestination({ executor }, turnId) {
23496
+ const [input] = await executor.db().select({ destination: juniorTurnInbox.destination }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
23497
+ return input?.destination ?? null;
23498
+ }
23499
+ /**
23500
+ * Finds who a Turn acts for: the sender of its first input. Undefined when
23501
+ * the Turn has no input.
23502
+ */
23503
+ async function findTurnActor({ executor }, turnId) {
23504
+ const [input] = await executor.db().select({ actorIdentityId: juniorTurnInbox.actorIdentityId }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
23505
+ return input?.actorIdentityId;
23506
+ }
23507
+ /** Finds every input of a Turn, oldest first. */
23508
+ async function findTurnInputs({ executor }, turnId) {
23509
+ return executor.db().select({
23510
+ inputId: juniorTurnInbox.id,
23511
+ payload: juniorTurnInbox.payload
23512
+ }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
23513
+ }
23514
+ const INPUT_EVENT_KEY_PREFIX = "inbox:";
23515
+ /** The idempotency key of the history event that reads an input. */
23516
+ function inputEventKey(inputId) {
23517
+ return `${INPUT_EVENT_KEY_PREFIX}${inputId}`;
23518
+ }
23519
+ function unreadOf({ executor }, turnId) {
23520
+ const readEvent = executor.db().select({ one: sql`1` }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorTurnInbox.conversationId), eq(juniorConversationEvents.idempotencyKey, sql`${INPUT_EVENT_KEY_PREFIX}::text || ${juniorTurnInbox.id}::text`)));
23521
+ return and(eq(juniorTurnInbox.turnId, turnId), notExists(readEvent));
23522
+ }
23523
+ const unreadColumns = {
23524
+ inputId: juniorTurnInbox.id,
23525
+ actorIdentityId: juniorTurnInbox.actorIdentityId,
23526
+ groupKey: juniorTurnInbox.groupKey,
23527
+ payload: juniorTurnInbox.payload,
23528
+ sentAt: juniorTurnInbox.sentAt,
23529
+ traceContext: juniorTurnInbox.traceContext,
23530
+ attemptedAt: juniorTurnInbox.attemptedAt
23531
+ };
23532
+ /** Finds the inputs of a Turn that the history has not read, oldest first. */
23533
+ async function findUnreadInputs({ executor }, turnId) {
23534
+ return executor.db().select(unreadColumns).from(juniorTurnInbox).where(unreadOf({ executor }, turnId)).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
23535
+ }
23536
+ /** Finds the unread inputs of a Turn, oldest first, with their Source. */
23537
+ async function findSourcedUnreadInputs({ executor }, turnId) {
23538
+ return executor.db().select({
23539
+ ...unreadColumns,
23540
+ idempotencyKey: juniorTurnInbox.idempotencyKey,
23541
+ source: juniorTurnInbox.source,
23542
+ receivedAt: juniorTurnInbox.createdAt
23543
+ }).from(juniorTurnInbox).where(unreadOf({ executor }, turnId)).orderBy(asc(juniorTurnInbox.sentAt), asc(juniorTurnInbox.createdAt));
23544
+ }
23545
+ /**
23546
+ * Records that an attempt of the Turn claimed it with these inputs unread.
23547
+ * The first attempt keeps its time. It does not mark the inputs read.
23548
+ */
23549
+ async function markInputsAttempted({ executor }, inputIds) {
23550
+ if (inputIds.length === 0) return;
23551
+ await executor.db().update(juniorTurnInbox).set({ attemptedAt: sql`coalesce(${juniorTurnInbox.attemptedAt}, now())` }).where(inArray(juniorTurnInbox.id, inputIds));
23552
+ }
23553
+ // src/core/turn/queue.ts
23554
+ const turnStepMessageSchema = z.object({
23555
+ turnId: z.string().min(1),
23556
+ traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
23557
+ }).strict();
23558
+ const turnStepTopic = signedTopic({
23559
+ topic: TURN_STEP_TOPIC,
23560
+ sign: {
23561
+ context: "junior.turn_step.v1",
23562
+ schema: turnStepMessageSchema,
23563
+ signatureVersion: "v1",
23564
+ parts: (message) => [message.turnId, message.traceContext?.sentryTrace ?? ""]
23565
+ },
23566
+ onRejected: (attributes) => logWarn("turn.step.queue_message.rejected", attributes),
23567
+ attributes: (message) => ({ "app.turn.id": message.turnId })
23568
+ });
23569
+ /**
23570
+ * Sends a message that runs the next step of a Turn. `idempotencyKey` drops a
23571
+ * second send with the same key.
23572
+ */
23573
+ async function publishTurnStep(ctx, turnId, options = {}) {
23574
+ await turnStepTopic.publish(ctx, { turnId }, options);
23575
+ }
23576
+ /**
23577
+ * Builds the queue consumer of Turn step messages. It acknowledges a message
23578
+ * with a bad or expired signature and retries one that cannot be checked yet.
23579
+ * advanceTurn fails a Turn after `maxAttempts` tries of one step. The host
23580
+ * mounts the consumer on its queue provider.
23581
+ */
23582
+ function createTurnStepConsumer(ctx, run) {
23583
+ return turnStepTopic.consumer(ctx, (message, metadata) => run({ turnId: message.turnId }, metadata));
23584
+ }
23585
+ // src/db/postgres-json.ts
23586
+ /**
23587
+ * Replace actual NUL characters that PostgreSQL cannot store in JSONB.
23588
+ * Literal `\\u0000` text is preserved because it contains no NUL character.
23589
+ */
23590
+ function sanitizePostgresJson(value) {
23591
+ if (typeof value === "string") return value.replaceAll("\0", " ");
23592
+ if (Array.isArray(value)) return value.map((item) => sanitizePostgresJson(item));
23593
+ if (value === null || typeof value !== "object") return value;
23594
+ const prototype = Object.getPrototypeOf(value);
23595
+ if (prototype !== Object.prototype && prototype !== null) return value;
23596
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizePostgresJson(item)]));
23597
+ }
23598
+ // src/conversation-events/store.ts
23599
+ /** Read the next seq and the current History version of a Conversation. */
23600
+ async function readEventCursor(executor, conversationId) {
23601
+ const [row] = await executor.db().select({
23602
+ maxSeq: sql`max(${juniorConversationEvents.seq})`,
23603
+ maxHistoryVersion: sql`max(${juniorConversationEvents.historyVersion})`
23604
+ }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
23605
+ return {
23606
+ nextSeq: row?.maxSeq == null ? 0 : Number(row.maxSeq) + 1,
23607
+ historyVersion: row?.maxHistoryVersion == null ? 0 : Number(row.maxHistoryVersion)
23608
+ };
23609
+ }
23610
+ /**
23611
+ * Drop the events whose idempotency key is already stored, or repeats an
23612
+ * earlier event of the same call. Events without a key are always kept.
23613
+ */
23614
+ async function unseenEvents(executor, conversationId, events) {
23615
+ const keys = events.flatMap((event) => event.idempotencyKey === void 0 ? [] : [event.idempotencyKey]);
23616
+ const seen = /* @__PURE__ */ new Set();
23617
+ if (keys.length > 0) {
23618
+ const rows = await executor.db().select({ key: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.idempotencyKey, keys)));
23619
+ for (const row of rows) if (row.key) seen.add(row.key);
23620
+ }
23621
+ return events.filter((event) => {
23622
+ if (event.idempotencyKey === void 0) return true;
23623
+ if (seen.has(event.idempotencyKey)) return false;
23624
+ seen.add(event.idempotencyKey);
23625
+ return true;
23626
+ });
23627
+ }
23628
+ /** Store rows in order from the cursor, at its History version. */
23629
+ async function insertEventRows(executor, conversationId, cursor, rows) {
23630
+ return await insertAt(executor, conversationId, cursor.historyVersion, rows.map((row, index) => ({
23631
+ row,
23632
+ seq: cursor.nextSeq + index
23633
+ })));
23634
+ }
23635
+ /**
23636
+ * Store a History replacement row. It starts the next History version, so
23637
+ * every later row belongs to the history that it sets.
23638
+ */
23639
+ async function insertHistoryReplacementRow(executor, conversationId, cursor, row) {
23640
+ const [inserted] = await insertAt(executor, conversationId, cursor.historyVersion + 1, [{
23641
+ row,
23642
+ seq: cursor.nextSeq
23643
+ }]);
23644
+ return inserted;
23645
+ }
23646
+ async function insertAt(executor, conversationId, historyVersion, rows) {
23647
+ const values = rows.map(({ row, seq }) => ({
23648
+ conversationId,
23649
+ seq,
23650
+ historyVersion,
23651
+ schemaVersion: row.schemaVersion,
23652
+ idempotencyKey: row.idempotencyKey ?? null,
23653
+ type: row.type,
23654
+ payload: sanitizePostgresJson(row.payload),
23655
+ actorIdentityId: row.actorIdentityId ?? null,
23656
+ turnId: row.turnId ?? null,
23657
+ createdAt: new Date(row.createdAtMs)
23658
+ }));
23659
+ if (values.length === 0) return [];
23660
+ const db = executor.db();
23661
+ await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(values);
23662
+ return values;
23663
+ }
23664
+ // src/core/history/write.ts
23665
+ /**
23666
+ * Appends the agent history items that one Turn writes, in order, at the
23667
+ * current History version. Skips an item whose idempotency key is already
23668
+ * stored. Call it under `withConversationEventLock`.
23669
+ */
23670
+ async function appendAgentHistory(executor, conversationId, turnId, items) {
23671
+ const pending = await unseenEvents(executor, conversationId, items);
23672
+ if (pending.length === 0) return;
23673
+ await insertEventRows(executor, conversationId, await readEventCursor(executor, conversationId), pending.map(({ item, idempotencyKey, createdAtMs }) => ({
23674
+ type: item.type,
23675
+ ...encodeAgentHistoryPayload(item),
23676
+ idempotencyKey,
23677
+ turnId,
23678
+ createdAtMs
23679
+ })));
23680
+ }
23681
+ // src/core/turn/replies.ts
23682
+ const LEGACY_NO_REPLY_MARKERS = ["[[NO_REPLY]]", "[[QUIET]]"];
23683
+ const THINKING_BLOCK_PATTERN = /[ \t]*<thinking\b[^>]*>[\s\S]*?<\/thinking>[ \t]*(?:\r?\n)?/gi;
23684
+ function isClosedFence(source) {
23685
+ const opener = source.trimStart();
23686
+ const marker = opener.startsWith("```") ? "`" : opener.startsWith("~~~") ? "~" : void 0;
23687
+ const lastLine = source.lastIndexOf("\n");
23688
+ let closer = lastLine < 0 ? "" : source.slice(lastLine + 1).trim();
23689
+ while (closer.startsWith(">")) closer = closer.slice(1).trimStart();
23690
+ return marker !== void 0 && closer.length >= 3 && closer === marker.repeat(closer.length);
23691
+ }
23692
+ function stripThinking(text) {
23693
+ let result = "";
23694
+ let cursor = 0;
23695
+ for (const { position } of markdownNodes(parseMarkdown(text), ["code"])) {
23696
+ const start = position?.start.offset ?? 0;
23697
+ const end = position?.end.offset ?? 0;
23698
+ if (!isClosedFence(text.slice(start, end))) continue;
23699
+ result += text.slice(cursor, start).replace(THINKING_BLOCK_PATTERN, "");
23700
+ result += text.slice(start, end);
23701
+ cursor = end;
23702
+ }
23703
+ return result + text.slice(cursor).replace(THINKING_BLOCK_PATTERN, "");
23704
+ }
23705
+ /**
23706
+ * The text that an assistant message delivers to a person, or undefined when
23707
+ * it is no reply. Text next to a tool call is the model working, not a reply.
23708
+ */
23709
+ function assistantReplyText(message) {
23710
+ if (message.content.some((part) => part.type === "toolCall")) return;
23711
+ const text = stripThinking(message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("\n")).trim();
23712
+ return text && !LEGACY_NO_REPLY_MARKERS.includes(text) ? text : void 0;
23713
+ }
23714
+ /** The key prefix of the message events that a Turn's steps wrote. */
23715
+ function turnEventKeyPrefix(turnId) {
23716
+ return `step:${turnId}:`;
23717
+ }
23718
+ /** The text that a message event delivers, or undefined when it is no reply. */
23719
+ function replyText(row) {
23720
+ if (row.type !== "assistant_message") return;
23721
+ const data = agentHistoryFromRow(row);
23722
+ if (data.type !== "assistant_message") return;
23723
+ const message = piMessageFromHistoryItem(data);
23724
+ return message.role === "assistant" ? assistantReplyText(message) : void 0;
23725
+ }
23726
+ /** Finds the reply events of a Turn, in history order. */
23727
+ async function findTurnReplies({ executor }, conversationId, turnId) {
23728
+ return (await executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "assistant_message"), like(juniorConversationEvents.idempotencyKey, `${turnEventKeyPrefix(turnId)}%`))).orderBy(asc(juniorConversationEvents.seq))).filter((row) => replyText(row) !== void 0);
23729
+ }
23730
+ // src/core/turn/outbox.ts
23731
+ /**
23732
+ * Adds an outbox row for each reply of the Turn that has none, but only while
23733
+ * the Turn has a Destination. Call it in the transaction that commits the
23734
+ * replies.
23735
+ */
23736
+ async function recordReplies({ executor }, turn) {
23737
+ const destination = await findTurnDestination({ executor }, turn.turnId);
23738
+ if (!destination) return;
23739
+ const replies = await findTurnReplies({ executor }, turn.conversationId, turn.turnId);
23740
+ if (replies.length === 0) return;
23741
+ await executor.db().insert(juniorTurnOutbox).values(replies.map((row) => ({
23742
+ id: randomUUID(),
23743
+ conversationId: turn.conversationId,
23744
+ turnId: turn.turnId,
23745
+ eventSeq: row.seq,
23746
+ destination,
23747
+ state: "pending"
23748
+ }))).onConflictDoNothing({ target: [juniorTurnOutbox.conversationId, juniorTurnOutbox.eventSeq] });
23749
+ }
23750
+ // src/core/turn/state.ts
23751
+ /**
23752
+ * Turn priorities: a lower number runs first. A Turn that supersedes the
23753
+ * running Turn runs before every other queued Turn.
23754
+ */
23755
+ const TURN_PRIORITY = {
23756
+ supersede: 0,
23757
+ normal: 1
23758
+ };
23759
+ const SUPERSEDED_END = {
23760
+ state: "cancelled",
23761
+ endReason: "superseded",
23762
+ endedAt: sql`now()`
23763
+ };
23764
+ function leaseExpiry(leaseMs) {
23765
+ return sql`now() + ${leaseMs}::integer * interval '1 millisecond'`;
23766
+ }
23767
+ function leaseFence(lease) {
23768
+ return and(eq(juniorTurns.id, lease.turnId), eq(juniorTurns.state, "running"), eq(juniorTurns.leaseEpoch, lease.leaseEpoch));
23769
+ }
23770
+ /**
23771
+ * Inserts a queued Turn. It sends no step message: the caller publishes the
23772
+ * Turn after its transaction commits, so a worker can claim it.
23773
+ */
23774
+ async function createTurn({ executor }, args) {
23775
+ const turnId = randomUUID();
23776
+ await executor.db().insert(juniorTurns).values({
23777
+ ...args,
23778
+ id: turnId,
23779
+ state: "queued"
23780
+ });
23781
+ return {
23782
+ turnId,
23783
+ state: "queued"
23784
+ };
23785
+ }
23786
+ /** Finds a Turn by id. Undefined when it does not exist. */
23787
+ async function findTurn({ executor }, turnId) {
23788
+ const [turn] = await executor.db().select({
23789
+ turnId: juniorTurns.id,
23790
+ state: juniorTurns.state,
23791
+ conversationId: juniorTurns.conversationId,
23792
+ failureCode: juniorTurns.failureCode,
23793
+ failureReason: juniorTurns.failureReason,
23794
+ failureEventId: juniorTurns.failureEventId,
23795
+ startedAt: juniorTurns.startedAt,
23796
+ endedAt: juniorTurns.endedAt
23797
+ }).from(juniorTurns).where(eq(juniorTurns.id, turnId));
23798
+ return turn;
23799
+ }
23800
+ /** Reads a Turn's discarded usage. Undefined when the Turn does not exist. */
23801
+ async function findDiscardedUsage({ executor }, turnId) {
23802
+ return selectDiscardedUsage({ executor }, eq(juniorTurns.id, turnId));
23803
+ }
23804
+ async function selectDiscardedUsage({ executor }, where) {
23805
+ const [turn] = await executor.db().select({
23806
+ costMicroUsd: juniorTurns.discardedCostMicroUsd,
23807
+ tokens: juniorTurns.discardedTokens
23808
+ }).from(juniorTurns).where(where);
23809
+ if (!turn) return;
23810
+ return turn.tokens === null ? { costMicroUsd: turn.costMicroUsd } : {
23811
+ costMicroUsd: turn.costMicroUsd,
23812
+ tokens: usageTokensSchema.parse(turn.tokens)
23813
+ };
23814
+ }
23815
+ async function discardedUsageUpdate({ executor }, lease, usage) {
23816
+ const current = usage ? await selectDiscardedUsage({ executor }, leaseFence(lease)) : void 0;
23817
+ if (!current) return {};
23818
+ const { cost: _, ...tokens } = addAgentTurnUsage(current.tokens, usage) ?? {};
23819
+ return {
23820
+ discardedCostMicroUsd: current.costMicroUsd + usdToMicroUsd(agentTurnCostUsd(usage) ?? 0),
23821
+ discardedTokens: tokens
23822
+ };
23823
+ }
23824
+ const runOrder = [
23825
+ sql`${juniorTurns.state} = 'running' desc`,
23826
+ asc(juniorTurns.priority),
23827
+ asc(juniorTurns.createdAt),
23828
+ asc(juniorTurns.id)
23829
+ ];
23830
+ /**
23831
+ * Finds the Turn of a Conversation that has not ended: the running Turn, else
23832
+ * the next queued Turn by priority and age.
23833
+ */
23834
+ async function findOpenTurn({ executor }, conversationId) {
23835
+ const [turn] = await executor.db().select({
23836
+ turnId: juniorTurns.id,
23837
+ state: juniorTurns.state
23838
+ }).from(juniorTurns).where(and(eq(juniorTurns.conversationId, conversationId), inArray(juniorTurns.state, ["queued", "running"]))).orderBy(...runOrder).limit(1);
23839
+ return turn;
23840
+ }
23841
+ /**
23842
+ * Finds the Turns of a Conversation that can still take inputs, in run order:
23843
+ * those that have not ended, less a running Turn that another Turn
23844
+ * supersedes.
23845
+ */
23846
+ async function findOpenTurns({ executor }, conversationId) {
23847
+ return (await executor.db().select({
23848
+ turnId: juniorTurns.id,
23849
+ state: juniorTurns.state,
23850
+ groupKey: juniorTurnInbox.groupKey,
23851
+ stepSeq: juniorTurns.stepSeq,
23852
+ attempts: juniorTurns.attempts
23853
+ }).from(juniorTurns).innerJoin(juniorTurnInbox, eq(juniorTurnInbox.turnId, juniorTurns.id)).where(and(eq(juniorTurns.conversationId, conversationId), or(eq(juniorTurns.state, "queued"), and(eq(juniorTurns.state, "running"), notExists(turnAhead({ executor })))))).groupBy(juniorTurns.id, juniorTurnInbox.groupKey).orderBy(...runOrder)).map(({ stepSeq, attempts, ...turn }) => ({
23854
+ ...turn,
23855
+ started: stepSeq > 0 || attempts > 0
23856
+ }));
23857
+ }
23858
+ function turnAhead({ executor }) {
23859
+ const ahead = alias(juniorTurns, "ahead");
23860
+ return executor.db().select({ one: sql`1` }).from(ahead).where(and(eq(ahead.conversationId, juniorTurns.conversationId), ne(ahead.id, juniorTurns.id), or(eq(ahead.state, "running"), and(eq(ahead.state, "queued"), sql`(${ahead.priority}, ${ahead.createdAt}, ${ahead.id}) < (${juniorTurns.priority}, ${juniorTurns.createdAt}, ${juniorTurns.id})`))));
23861
+ }
23862
+ async function isSuperseded({ executor }, turnId) {
23863
+ return (await executor.db().select({ id: juniorTurns.id }).from(juniorTurns).where(and(eq(juniorTurns.id, turnId), exists(turnAhead({ executor }))))).length > 0;
23864
+ }
23865
+ /**
23866
+ * Makes way for a Turn that supersedes this one. Call it under the
23867
+ * Conversation lock. A queued Turn has no step in flight, so it ends now and
23868
+ * moves `lease_epoch`. A running Turn moves behind the new Turn, and
23869
+ * `commitStep` or `releaseTurn` ends it, so the step's work is kept. True
23870
+ * when the Turn ended now.
23871
+ */
23872
+ async function supersedeTurn({ executor }, turnId) {
23873
+ const db = executor.db();
23874
+ const ended = await db.update(juniorTurns).set({
23875
+ ...SUPERSEDED_END,
23876
+ leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
23877
+ updatedAt: sql`now()`
23878
+ }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued"))).returning({ id: juniorTurns.id });
23879
+ await db.update(juniorTurns).set({
23880
+ priority: TURN_PRIORITY.normal,
23881
+ updatedAt: sql`now()`
23882
+ }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "running")));
23883
+ return ended.length > 0;
23884
+ }
23885
+ /**
23886
+ * Claims a Turn to run its next step: the Conversation's next queued Turn, or
23887
+ * a running Turn whose lease expired, so the queue's redelivery after a crash
23888
+ * resumes it. Any other Turn gets undefined, so one of two racing claims wins,
23889
+ * and a Conversation runs one Turn at a time, in order. Each claim moves
23890
+ * `lease_epoch` and `attempts` and holds the Conversation lock.
23891
+ */
23892
+ async function claimTurn({ executor, owner, leaseMs }, turnId) {
23893
+ const turn = await findTurn({ executor }, turnId);
23894
+ if (!turn) return;
23895
+ const claim = () => executor.db().update(juniorTurns).set({
23896
+ state: "running",
23897
+ leaseOwner: owner,
23898
+ leaseExpiresAt: leaseExpiry(leaseMs),
23899
+ leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
23900
+ attempts: sql`${juniorTurns.attempts} + 1`,
23901
+ startedAt: sql`coalesce(${juniorTurns.startedAt}, now())`,
23902
+ updatedAt: sql`now()`
23903
+ }).where(and(eq(juniorTurns.id, turnId), or(and(eq(juniorTurns.state, "queued"), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lte(juniorTurns.leaseExpiresAt, sql`now()`))))).returning({
23904
+ turnId: juniorTurns.id,
23905
+ leaseEpoch: juniorTurns.leaseEpoch,
23906
+ conversationId: juniorTurns.conversationId,
23907
+ stepSeq: juniorTurns.stepSeq,
23908
+ attempts: juniorTurns.attempts
23909
+ });
23910
+ const [claimed] = await executor.transaction(() => withConversationEventLock(executor, turn.conversationId, claim));
23911
+ return claimed;
23912
+ }
23913
+ /**
23914
+ * Checks without a write that the lease still holds: the Turn runs under the
23915
+ * caller's `lease_epoch`. False after a cancel or a takeover.
23916
+ */
23917
+ async function holdsLease({ executor }, lease) {
23918
+ return (await executor.db().select({ id: juniorTurns.id }).from(juniorTurns).where(leaseFence(lease))).length > 0;
23919
+ }
23920
+ /**
23921
+ * Finds Turns that a claim could take now but that no message is likely to
23922
+ * reach: the next queued Turn of its Conversation, unchanged for `staleMs`,
23923
+ * and running Turns whose lease expired `staleMs` ago. The queue redelivers
23924
+ * a dead step's message soon after its lease expires, so only a Turn that
23925
+ * missed that redelivery is stalled.
23926
+ */
23927
+ async function findStalledTurns({ executor }, { staleMs, limit }) {
23928
+ const staleBefore = sql`now() - make_interval(secs => ${staleMs / 1e3})`;
23929
+ const rows = await executor.db().select({
23930
+ turnId: juniorTurns.id,
23931
+ conversationId: juniorTurns.conversationId,
23932
+ state: juniorTurns.state,
23933
+ updatedAt: juniorTurns.updatedAt,
23934
+ leaseExpiresAt: juniorTurns.leaseExpiresAt
23935
+ }).from(juniorTurns).where(or(and(eq(juniorTurns.state, "queued"), lt(juniorTurns.updatedAt, staleBefore), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lt(juniorTurns.leaseExpiresAt, staleBefore)))).limit(limit);
23936
+ const nowMs = Date.now();
23937
+ return rows.map((row) => {
23938
+ const since = row.state === "running" && row.leaseExpiresAt ? row.leaseExpiresAt : row.updatedAt;
23939
+ return {
23940
+ turnId: row.turnId,
23941
+ conversationId: row.conversationId,
23942
+ reason: row.state === "running" ? "lease_expired" : "queued_lost",
23943
+ stalledMs: Math.max(0, nowMs - since.getTime())
23944
+ };
23945
+ });
23946
+ }
23947
+ /**
23948
+ * The idempotency key of one message event of a step. It names the Turn and
23949
+ * the step that wrote it, so Delivery finds a Turn's replies without reading
23950
+ * the rest of the history.
23951
+ */
23952
+ function stepEventKey(turnId, stepSeq, index) {
23953
+ return `${turnEventKeyPrefix(turnId)}${stepSeq}:${index}`;
23954
+ }
23955
+ /**
23956
+ * The idempotency key of one new message that a step's prompt added from a
23957
+ * message fragment. It is not a step event key, so Delivery does not read it.
23958
+ */
23959
+ function promptEventKey(turnId, stepSeq, index) {
23960
+ return `prompt:${turnId}:${stepSeq}:${index}`;
23961
+ }
23962
+ /**
23963
+ * Commits a step in one transaction: appends the prompt's new messages, with
23964
+ * the inputs the step read, then the step's messages to history, adds an
23965
+ * outbox row per new reply, and releases the lease. A Turn that continues
23966
+ * queues for a new claim. A `stale` final reply is not committed. Undefined,
23967
+ * with no write, when the lease is lost or the step is already committed.
23968
+ */
23969
+ async function commitStep({ executor }, turn, step, prompt) {
23970
+ const nextStep = {
23971
+ stepSeq: sql`${juniorTurns.stepSeq} + 1`,
23972
+ attempts: 0,
23973
+ leaseOwner: null,
23974
+ leaseExpiresAt: null,
23975
+ updatedAt: sql`now()`
23976
+ };
23977
+ return executor.transaction(() => withConversationEventLock(executor, turn.conversationId, async () => {
23978
+ const outcome = await commitOutcome({ executor }, turn.turnId, step, prompt);
23979
+ if (outcome === "stale") return await requeueStep({ executor }, turn, step) ? outcome : void 0;
23980
+ if ((await executor.db().update(juniorTurns).set(outcome === "completed" ? {
23981
+ ...nextStep,
23982
+ state: "completed",
23983
+ endedAt: sql`now()`
23984
+ } : outcome === "superseded" ? {
23985
+ ...nextStep,
23986
+ ...SUPERSEDED_END
23987
+ } : {
23988
+ ...nextStep,
23989
+ state: "queued"
23990
+ }).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length === 0) return;
23991
+ await appendAgentHistory(executor, turn.conversationId, turn.turnId, [...prompt.map((entry, index) => entry.source === "input" ? {
23992
+ item: historyItemFromPiMessage(entry.message, entry.provenance),
23993
+ idempotencyKey: inputEventKey(entry.inputId),
23994
+ createdAtMs: entry.message.timestamp
23995
+ } : {
23996
+ item: historyItemFromPiMessage(entry.message, contextProvenance),
23997
+ idempotencyKey: promptEventKey(turn.turnId, turn.stepSeq, index),
23998
+ createdAtMs: entry.message.timestamp
23999
+ }), ...step.messages.map((message, index) => ({
24000
+ item: historyItemFromPiMessage(message, contextProvenance),
24001
+ idempotencyKey: stepEventKey(turn.turnId, turn.stepSeq, index),
24002
+ createdAtMs: message.timestamp
24003
+ }))]);
24004
+ await recordReplies({ executor }, turn);
24005
+ return outcome;
24006
+ }));
24007
+ }
24008
+ /**
24009
+ * A completed step ends the Turn only when the commit reads every unread
24010
+ * input. The scheduler can add an input after the step read them, and the
24011
+ * Conversation lock keeps more out until the commit ends. A final reply that
24012
+ * missed an input is `stale`, so the Turn ends with one reply to every input.
24013
+ */
24014
+ async function commitOutcome({ executor }, turnId, step, prompt) {
24015
+ if (step.outcome === "completed") {
24016
+ const read = new Set(prompt.flatMap((entry) => entry.source === "input" ? [entry.inputId] : []));
24017
+ if ((await findUnreadInputs({ executor }, turnId)).every((input) => read.has(input.inputId))) return "completed";
24018
+ }
24019
+ if (await isSuperseded({ executor }, turnId)) return "superseded";
24020
+ return step.outcome === "completed" && finalReplyOf(step) ? "stale" : "continue";
24021
+ }
24022
+ function finalReplyOf(step) {
24023
+ const [message] = step.messages;
24024
+ return message?.role === "assistant" ? message : void 0;
24025
+ }
24026
+ /**
24027
+ * Queues the Turn for the same step again, with nothing committed, after a
24028
+ * stale final reply. The attempt does not count: the step did not fail. The
24029
+ * dropped reply's usage adds to the Turn's discarded usage.
24030
+ */
24031
+ async function requeueStep({ executor }, turn, step) {
24032
+ return (await executor.db().update(juniorTurns).set({
24033
+ ...await discardedUsageUpdate({ executor }, turn, extractGenAiUsageSummary(finalReplyOf(step))),
24034
+ state: "queued",
24035
+ attempts: 0,
24036
+ leaseOwner: null,
24037
+ leaseExpiresAt: null,
24038
+ updatedAt: sql`now()`
24039
+ }).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length > 0;
24040
+ }
24041
+ /**
24042
+ * Ends a running Turn as failed, with the reason and the failure details.
24043
+ * `discarded` is the usage of the model reply that the step drops. False when
24044
+ * the lease is lost. The engine calls it through `endFailedTurn`, which also
24045
+ * moves the Turn's late inputs.
24046
+ */
24047
+ async function failTurn({ executor }, lease, endReason, failure, discarded) {
24048
+ return (await executor.db().update(juniorTurns).set({
24049
+ ...await discardedUsageUpdate({ executor }, lease, discarded),
24050
+ state: "failed",
24051
+ endReason,
24052
+ failureCode: failure.failureCode,
24053
+ failureReason: failure.failureReason ?? null,
24054
+ failureEventId: failure.eventId ?? null,
24055
+ leaseOwner: null,
24056
+ leaseExpiresAt: null,
24057
+ updatedAt: sql`now()`,
24058
+ endedAt: sql`now()`
24059
+ }).where(leaseFence(lease)).returning({ id: juniorTurns.id })).length > 0;
24060
+ }
24061
+ /**
24062
+ * Queues a running Turn again after its invocation failed, so the queue's
24063
+ * retry can claim the step at once. The failed attempt still counts. A Turn
24064
+ * that another Turn supersedes ends instead, like at a commit. `discarded` is
24065
+ * the usage of the failed model reply that the retry drops. Returns the
24066
+ * Turn's new state, or undefined when the lease is lost.
24067
+ */
24068
+ async function releaseTurn({ executor }, lease, discarded) {
24069
+ return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
24070
+ const released = {
24071
+ ...await discardedUsageUpdate({ executor }, lease, discarded),
24072
+ leaseOwner: null,
24073
+ leaseExpiresAt: null,
24074
+ updatedAt: sql`now()`
24075
+ };
24076
+ return (await executor.db().update(juniorTurns).set(await isSuperseded({ executor }, lease.turnId) ? {
24077
+ ...released,
24078
+ ...SUPERSEDED_END
24079
+ } : {
24080
+ ...released,
24081
+ state: "queued"
24082
+ }).where(leaseFence(lease)).returning({ state: juniorTurns.state }))[0]?.state;
24083
+ }));
24084
+ }
24085
+ /**
24086
+ * Cancels every queued and running Turn of a Conversation, with no lease, and
24087
+ * returns their ids in run order. Call it under the Conversation lock, as
24088
+ * `stopTurns` does. Moving each `lease_epoch` keeps a running step from
24089
+ * committing.
24090
+ */
24091
+ async function cancelTurns({ executor }, conversationId) {
24092
+ const db = executor.db();
24093
+ const turnIds = (await db.select({ id: juniorTurns.id }).from(juniorTurns).where(and(eq(juniorTurns.conversationId, conversationId), inArray(juniorTurns.state, ["queued", "running"]))).orderBy(...runOrder)).map(({ id }) => id);
24094
+ if (turnIds.length === 0) return [];
24095
+ await db.update(juniorTurns).set({
24096
+ state: "cancelled",
24097
+ leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
24098
+ leaseOwner: null,
24099
+ leaseExpiresAt: null,
24100
+ updatedAt: sql`now()`,
24101
+ endedAt: sql`now()`
24102
+ }).where(inArray(juniorTurns.id, turnIds));
24103
+ return turnIds;
24104
+ }
24105
+ // src/core/turn/schedule.ts
24106
+ async function addInput({ executor }, input) {
24107
+ await executor.db().insert(juniorTurnInbox).values({
24108
+ ...input,
24109
+ id: randomUUID()
24110
+ });
24111
+ }
24112
+ /**
24113
+ * The rule for which Turn takes an input that is not a duplicate. Core owns
24114
+ * it, so every Source schedules the same way, and the host decides who may
24115
+ * share a Turn through the group key. An input joins a Turn only when its
24116
+ * group key matches. An interrupt joins the Turn that has started, and an
24117
+ * interrupt with another group key supersedes that Turn. Any input
24118
+ * joins the last Turn in line while no step of it has started. Otherwise the
24119
+ * input waits in a new Turn at the end of the line, so A1 B1 A2 makes A2 wait
24120
+ * for B1. It runs under the Conversation lock, so `openTurns` cannot change
24121
+ * before the write.
24122
+ */
24123
+ function assignTurn(input, openTurns) {
24124
+ const sameGroup = (turn) => turn.groupKey === input.groupKey;
24125
+ const started = openTurns.find((turn) => turn.started);
24126
+ if (input.delivery === "interrupt" && started) return sameGroup(started) ? { join: started } : {
24127
+ create: { priority: TURN_PRIORITY.supersede },
24128
+ supersede: started
24129
+ };
24130
+ const last = openTurns.at(-1);
24131
+ if (last && !last.started && sameGroup(last)) return { join: last };
24132
+ return { create: { priority: TURN_PRIORITY.normal } };
24133
+ }
24134
+ async function placeInput({ executor }, { delivery, ...input }) {
24135
+ const existing = await findInputTurn({ executor }, input);
24136
+ if (existing) return {
24137
+ turnId: existing.turnId,
24138
+ created: false,
24139
+ duplicate: true,
24140
+ publish: existing.state === "queued"
24141
+ };
24142
+ const openTurns = await findOpenTurns({ executor }, input.conversationId);
24143
+ const choice = assignTurn({
24144
+ ...input,
24145
+ delivery
24146
+ }, openTurns);
24147
+ if ("join" in choice) {
24148
+ const { turnId } = choice.join;
24149
+ await addInput({ executor }, {
24150
+ ...input,
24151
+ turnId
24152
+ });
24153
+ return {
24154
+ turnId,
24155
+ created: false,
24156
+ duplicate: false,
24157
+ publish: false
24158
+ };
24159
+ }
24160
+ const ended = choice.supersede && await supersedeTurn({ executor }, choice.supersede.turnId) ? choice.supersede.turnId : void 0;
24161
+ const turn = await createTurn({ executor }, {
24162
+ conversationId: input.conversationId,
24163
+ priority: choice.create.priority
24164
+ });
24165
+ await addInput({ executor }, {
24166
+ ...input,
24167
+ turnId: turn.turnId
24168
+ });
24169
+ return {
24170
+ turnId: turn.turnId,
24171
+ created: true,
24172
+ duplicate: false,
24173
+ publish: openTurns.length === 0 || choice.supersede !== void 0,
24174
+ ended
24175
+ };
24176
+ }
24177
+ async function scheduleInput({ executor, queue }, { startDelayMs, ...input }, options = {}) {
24178
+ const placement = await withConversationEventLock(executor, input.conversationId, async () => options.admit && !await options.admit() ? void 0 : placeInput({ executor }, input));
24179
+ if (!placement) return { refused: true };
24180
+ if (placement.ended) await publishTurnEnded({ queue }, {
24181
+ conversationId: input.conversationId,
24182
+ turnId: placement.ended
24183
+ });
24184
+ if (placement.publish) await publishTurnStep({ queue }, placement.turnId, startDelayMs ? { delayMs: startDelayMs } : {});
24185
+ return {
24186
+ turnId: placement.turnId,
24187
+ created: placement.created,
24188
+ duplicate: placement.duplicate
24189
+ };
24190
+ }
24191
+ async function moveInputs({ executor }, inputIds, turnId) {
24192
+ await executor.db().update(juniorTurnInbox).set({ turnId }).where(inArray(juniorTurnInbox.id, inputIds));
24193
+ }
24194
+ /**
24195
+ * Moves inputs of one Turn that ended to the Turn that `assignTurn` picks for
24196
+ * a deferred input. They share the ended Turn's group key, so they move
24197
+ * together. Call it under the Conversation lock.
24198
+ */
24199
+ async function moveToNextTurn({ executor }, conversationId, inputs) {
24200
+ const [first] = inputs;
24201
+ if (!first) return;
24202
+ const choice = assignTurn({
24203
+ ...first,
24204
+ delivery: "defer"
24205
+ }, await findOpenTurns({ executor }, conversationId));
24206
+ const target = "join" in choice ? choice.join : await createTurn({ executor }, {
24207
+ conversationId,
24208
+ priority: choice.create.priority
24209
+ });
24210
+ await moveInputs({ executor }, inputs.map((input) => input.inputId), target.turnId);
24211
+ }
24212
+ /**
24213
+ * Ends a running Turn as failed and, in the same commit, moves its inputs
24214
+ * that arrived after its last claim to the next Turn; it drops the rest. A
24215
+ * crash after the commit loses no input: the sweep finds the queued Turn.
24216
+ * `discarded` is the usage of a failed model reply that the Turn drops.
24217
+ * False when the lease is lost, and then nothing changes.
24218
+ */
24219
+ async function endFailedTurn({ executor }, lease, endReason, failure, discarded) {
24220
+ return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
24221
+ if (!await failTurn({ executor }, lease, endReason, failure, discarded)) return false;
24222
+ const leftovers = (await findUnreadInputs({ executor }, lease.turnId)).filter((input) => input.attemptedAt === null);
24223
+ await moveToNextTurn({ executor }, lease.conversationId, leftovers);
24224
+ return true;
24225
+ }));
24226
+ }
24227
+ /**
24228
+ * Stops a Conversation's work by sent time. In one commit under the lock it
24229
+ * cancels every queued and running Turn. Their unread inputs sent after
24230
+ * `sentAtOrBeforeMs` that `canMove` accepts move to a queued Turn; the rest,
24231
+ * or all of them with no cutoff, stay and drop. Then it reconciles each
24232
+ * stopped Turn.
24233
+ */
24234
+ async function stopTurns({ executor, queue }, conversationId, { sentAtOrBeforeMs, canMove = () => true } = {}) {
24235
+ const afterCutoff = (input) => sentAtOrBeforeMs !== void 0 && input.sentAt.getTime() > sentAtOrBeforeMs && canMove(input);
24236
+ const stopped = await executor.transaction(() => withConversationEventLock(executor, conversationId, async () => {
24237
+ const turnIds = await cancelTurns({ executor }, conversationId);
24238
+ const dropped = [];
24239
+ const moved = [];
24240
+ for (const turnId of turnIds) {
24241
+ const unread = await findSourcedUnreadInputs({ executor }, turnId);
24242
+ const later = unread.filter(afterCutoff);
24243
+ dropped.push(...unread.filter((input) => !afterCutoff(input)));
24244
+ moved.push(...later);
24245
+ await moveToNextTurn({ executor }, conversationId, later);
24246
+ }
24247
+ return {
24248
+ turnIds,
24249
+ dropped,
24250
+ moved
24251
+ };
24252
+ }));
24253
+ for (const turnId of stopped.turnIds) try {
24254
+ await reconcileTurn({
24255
+ executor,
24256
+ queue
24257
+ }, turnId);
24258
+ } catch (error) {
24259
+ logException(error, "turn.stop.reconcile.failed", {
24260
+ "app.turn.id": turnId,
24261
+ "gen_ai.conversation.id": conversationId
24262
+ });
24263
+ }
24264
+ return stopped;
24265
+ }
24266
+ /**
24267
+ * Brings the queue in line with this Turn's stored state, so it is safe to
24268
+ * repeat: it says the Turn ended if it has, then publishes the Conversation's
24269
+ * open Turn if it is queued. Call it after the commit that it follows,
24270
+ * outside a transaction, so a worker that takes a message sees that commit.
24271
+ */
24272
+ async function reconcileTurn({ executor, queue }, turnId) {
24273
+ const turn = await findTurn({ executor }, turnId);
24274
+ if (!turn) return;
24275
+ if (turn.state !== "queued" && turn.state !== "running") await publishTurnEnded({ queue }, {
24276
+ conversationId: turn.conversationId,
24277
+ turnId
24278
+ });
24279
+ const openTurn = await findOpenTurn({ executor }, turn.conversationId);
24280
+ if (openTurn?.state === "queued") await publishTurnStep({ queue }, openTurn.turnId);
24281
+ }
24282
+ // src/turn-steps/engine-context.ts
24283
+ /** Builds the context that core's Turn engine runs with. */
24284
+ function createEngineContext(config) {
24285
+ return {
24286
+ executor: getSqlExecutor(),
24287
+ queue: getQueueProvider(),
24288
+ owner: SERVICE_INSTANCE_ID,
24289
+ leaseMs: config.functionMaxDurationSeconds * 1e3
24290
+ };
24291
+ }
24292
+ // src/turn-steps/group-key.ts
24293
+ /** The group key of an input that this Actor Identity sent from this Source. */
24294
+ function turnGroupKey(actorIdentityId, source) {
24295
+ return `${actorIdentityId}:${source.kind}`;
24296
+ }
24297
+ // src/turn-steps/input-payload.ts
24298
+ /** Parses the payload of an inbox row that the host wrote. */
24299
+ const turnInputPayloadSchema = z.object({
24300
+ text: z.string().min(1),
24301
+ actor: actorSchema
24302
+ }).strict();
24303
+ // src/turn-steps/ingress.ts
24304
+ function slackFacts(message) {
24305
+ const { destination } = message;
24306
+ const { authorId, metadata } = message.input;
24307
+ if (destination?.platform !== "slack" || !authorId) throw new Error("Slack input requires a Slack Destination and an author");
24308
+ const slackMessage = metadata?.["message"];
24309
+ const raw = readSlackRawMessageContext(slackMessage);
24310
+ const threadTs = raw?.threadTs ?? raw?.messageTs;
24311
+ return {
24312
+ actor: createSlackActor(destination.teamId, authorId, null),
24313
+ actorIdentityId: message.input.authorIdentityId,
24314
+ destination: {
24315
+ ...destination,
24316
+ ...threadTs ? { threadTs } : void 0
24317
+ },
24318
+ source: createSlackSource({
24319
+ channelId: destination.channelId,
24320
+ messageTs: raw?.messageTs,
24321
+ teamId: destination.teamId,
24322
+ threadTs,
24323
+ visibility: conversationVisibilityFromSlackChannelType(resolveSlackChannelTypeFromMessage(slackMessage)) ?? "private"
24324
+ }),
24325
+ text: message.input.text
24326
+ };
24327
+ }
24328
+ async function webVisibility(conversationId) {
24329
+ const conversation = await getConversationStore().get({ conversationId });
24330
+ return (!conversation || isTopLevel(conversation) ? conversation?.visibility : conversation.visibility ?? "private") === "private" ? "private" : "public";
24331
+ }
24332
+ async function webFacts(message) {
24333
+ const metadata = legacyWebMailboxMetadataSchema.parse(message.input.metadata);
24334
+ return {
24335
+ actor: {
24336
+ platform: "web",
24337
+ userId: metadata.authorUserId,
24338
+ email: metadata.authorEmail,
24339
+ ...metadata.authorFullName ? { fullName: metadata.authorFullName } : void 0,
24340
+ ...metadata.authorUserName ? { userName: metadata.authorUserName } : void 0
24341
+ },
24342
+ actorIdentityId: message.input.authorIdentityId,
24343
+ destination: null,
24344
+ source: createWebSource(message.conversationId, await webVisibility(message.conversationId)),
24345
+ text: message.input.text
24346
+ };
24347
+ }
24348
+ function eventFacts(message) {
24349
+ const { metadata } = message.input;
24350
+ if (!isEventMailboxMetadata(metadata)) throw new Error("Event input has invalid metadata");
24351
+ return {
24352
+ actor: EVENT_SYSTEM_ACTOR,
24353
+ actorIdentityId: message.input.authorIdentityId ?? "system",
24354
+ destination: null,
24355
+ source: createEventSource(metadata.event),
24356
+ text: message.input.text
24357
+ };
24358
+ }
24359
+ async function dispatchFacts(message) {
24360
+ const dispatchId = getDispatchIdForConversation(message.conversationId);
24361
+ const dispatch = dispatchId && await getDispatchRecord(dispatchId);
24362
+ if (!dispatch) throw new Error(`No dispatch for ${message.conversationId}`);
24363
+ return {
24364
+ actor: dispatch.actor,
24365
+ actorIdentityId: message.input.authorIdentityId ?? "system",
24366
+ destination: dispatch.destination,
24367
+ source: dispatch.source,
24368
+ text: dispatch.input
24369
+ };
24370
+ }
24371
+ async function inputFacts(message) {
24372
+ switch (message.source) {
24373
+ case "slack": return slackFacts(message);
24374
+ case "web": return await webFacts(message);
24375
+ case "event": return eventFacts(message);
24376
+ case "plugin": return await dispatchFacts(message);
24377
+ default: throw new Error(`Core has no input for ${message.source} messages`);
24378
+ }
24379
+ }
24380
+ /**
24381
+ * Schedules a mailbox message as a core input. The message id is the
24382
+ * idempotency key, so a redelivery writes nothing and is a `duplicate`.
24383
+ * `startDelayMs` holds a new Turn so that inputs sent soon after join it, as
24384
+ * main's delayed wake does. Call it outside a transaction, as
24385
+ * `scheduleInput` requires.
24386
+ */
24387
+ async function scheduleInboundMessage(message, options = {}) {
24388
+ const facts = await inputFacts(message);
24389
+ if (!facts.actorIdentityId) throw new Error(`${message.source} input has no author Identity`);
24390
+ const scheduled = await scheduleInput(createEngineContext(getChatConfig()), {
24391
+ conversationId: message.conversationId,
24392
+ actorIdentityId: facts.actorIdentityId,
24393
+ groupKey: turnGroupKey(facts.actorIdentityId, facts.source),
24394
+ payload: turnInputPayloadSchema.parse({
24395
+ text: facts.text,
24396
+ actor: facts.actor
24397
+ }),
24398
+ idempotencyKey: message.inboundMessageId,
24399
+ sentAt: new Date(message.createdAtMs),
24400
+ source: facts.source,
24401
+ destination: facts.destination,
24402
+ delivery: message.delivery,
24403
+ ...message.traceContext ? { traceContext: message.traceContext } : void 0,
24404
+ startDelayMs: options.startDelayMs
24405
+ }, { admit: async () => {
24406
+ if (!isPersonInput(message.source)) return true;
24407
+ const stoppedAtMs = await getConversationStoppedAtMs(message.conversationId);
24408
+ if (stoppedAtMs === void 0) return true;
24409
+ if (message.createdAtMs <= stoppedAtMs) return false;
24410
+ await resumeConversationTree(message.conversationId, message.createdAtMs);
24411
+ return true;
24412
+ } });
24413
+ if ("refused" in scheduled) return { status: "appended" };
24414
+ return { status: scheduled.duplicate ? "duplicate" : "appended" };
24415
+ }
22816
24416
  // src/chat/child-agents/parent-message-input.ts
22817
24417
  /**
22818
24418
  * A parent agent task or message to a child: who sent it and the
@@ -24549,8 +26149,12 @@ async function enqueueAfterAppend(args) {
24549
26149
  ...wake.status === "enqueued" ? { queueMessageId: wake.queueMessageId } : void 0
24550
26150
  };
24551
26151
  }
24552
- /** Persist inbound work and ensure a worker wake-up. */
26152
+ /**
26153
+ * Persist inbound work and ensure a worker wake-up. On the core Turn engine,
26154
+ * schedule it as a core input instead.
26155
+ */
24553
26156
  async function appendAndEnqueueInboundMessage(args) {
26157
+ if (getChatConfig().turnEngine === "core") return await scheduleInboundMessage(args.message, { startDelayMs: args.queueDelayMs });
24554
26158
  const nowMs = args.nowMs ?? now$1();
24555
26159
  const result = await enqueueAfterAppend({
24556
26160
  ...args,
@@ -24565,8 +26169,12 @@ async function appendAndEnqueueInboundMessage(args) {
24565
26169
  if (result.status === "active") throw new Error("Non-exclusive mailbox enqueue returned active");
24566
26170
  return result;
24567
26171
  }
24568
- /** Persist exclusive inbound work and wake its worker when admitted. */
26172
+ /**
26173
+ * Persist exclusive inbound work and wake its worker when admitted. On the
26174
+ * core Turn engine, schedule it as a core input instead.
26175
+ */
24569
26176
  async function appendAndEnqueueExclusiveInboundMessage(args) {
26177
+ if (getChatConfig().turnEngine === "core") return await scheduleInboundMessage(args.message);
24570
26178
  const nowMs = args.nowMs ?? now$1();
24571
26179
  return await enqueueAfterAppend({
24572
26180
  ...args,
@@ -24697,7 +26305,7 @@ async function runDeferredMove(args) {
24697
26305
  const move = await takeDeferredConversationMove(args);
24698
26306
  if (move === void 0) return;
24699
26307
  try {
24700
- const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-C6jXhVYg.js").then((n) => n.r);
26308
+ const { continueDeferredSlackClick } = await import("./slack-conversation-unfurl-BxF0Yb3-.js").then((n) => n.r);
24701
26309
  await continueDeferredSlackClick(move, args.getSlackAdapter);
24702
26310
  } catch (error) {
24703
26311
  logException(error, "slack.continue_here.deferred.failed", { "gen_ai.conversation.id": args.conversationId });
@@ -25714,14 +27322,14 @@ function ownerConversationOpenTo(userId, ownerConversationId) {
25714
27322
  return exists(query.where(and(eq(todoOwner.conversationId, ownerConversationId), open)));
25715
27323
  }
25716
27324
  /**
25717
- * SQL: the Inbox item has this assigned User. A To-do's item counts only
25718
- * while the User can see its Conversation's private content, so a person
25719
- * who loses access to the Conversation no longer sees or acts on it. The
25720
- * set has no outer reference, so Postgres reads it once and checks the
25721
- * owner of only the User's To-dos.
27325
+ * SQL: the Inbox item has this assigned User and one of `statuses`, the
27326
+ * statuses that the outer query reads. A To-do's item counts only while
27327
+ * the User can see its Conversation's private content. The set has no
27328
+ * outer reference, so Postgres reads it once and checks the owner of only
27329
+ * the User's To-dos.
25722
27330
  */
25723
- function inboxItemAssignedTo(userId) {
25724
- const assigned = getDb().select({ id: juniorInboxItems.id }).from(juniorInboxItemAssignees).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemAssignees.itemId)).where(and(eq(juniorInboxItemAssignees.userId, userId), or(ne(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.todo), ownerConversationOpenTo(userId, todoItemOwnerConversationId()))));
27331
+ function inboxItemAssignedTo(userId, statuses) {
27332
+ const assigned = getDb().select({ id: juniorInboxItems.id }).from(juniorInboxItemAssignees).innerJoin(juniorInboxItems, eq(juniorInboxItems.id, juniorInboxItemAssignees.itemId)).where(and(eq(juniorInboxItemAssignees.userId, userId), inArray(juniorInboxItems.status, [...statuses]), or(ne(juniorInboxItems.subjectKind, INBOX_SUBJECT_KINDS.todo), ownerConversationOpenTo(userId, todoItemOwnerConversationId()))));
25725
27333
  return sql`${juniorInboxItems.id} = any(array(${assigned}))`;
25726
27334
  }
25727
27335
  /**
@@ -25732,7 +27340,7 @@ function inboxItemAssignedTo(userId) {
25732
27340
  * "Waiting on you" marker use this rule.
25733
27341
  */
25734
27342
  function inboxItemNeedsUser(userId) {
25735
- return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), inboxItemAssignedTo(userId));
27343
+ return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), inboxItemAssignedTo(userId, ["open"]));
25736
27344
  }
25737
27345
  /**
25738
27346
  * SQL: the Inbox item waits for a person's input: an open `action` item,
@@ -25757,8 +27365,8 @@ function inboxItemSetsConversationStatus() {
25757
27365
  * to this User, to Everyone, or to no one. This is the assignee rule of
25758
27366
  * `canActOnInboxItem`; keep the two the same.
25759
27367
  */
25760
- function inboxItemForUser(userId) {
25761
- return or(eq(juniorInboxItems.assignedToEveryone, true), sql`not exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id})`, inboxItemAssignedTo(userId));
27368
+ function inboxItemForUser(userId, statuses) {
27369
+ return or(eq(juniorInboxItems.assignedToEveryone, true), sql`not exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id})`, inboxItemAssignedTo(userId, statuses));
25762
27370
  }
25763
27371
  /**
25764
27372
  * SQL: the private Inbox item is for Everyone, and the User can see its
@@ -25795,8 +27403,8 @@ function inboxItemAddedByAnyAutomation() {
25795
27403
  * Inbox item access test checks that they agree. Only the SQL form reads
25796
27404
  * `ownerAudienceUserId`.
25797
27405
  */
25798
- function inboxItemVisibleTo(reader) {
25799
- return or(...publicIn(reader.tenants ?? []), ...reader.userId ? [inboxItemAssignedTo(reader.userId)] : [], ...reader.ownerAudienceUserId ? [inboxItemForEveryoneOfOwner(reader.ownerAudienceUserId)] : [], ...reader.conversationId ? [inboxItemLinkedTo(reader.conversationId)] : [], ...reader.publicConversationId ? [and(eq(inboxItemVisibility(), "public"), eq(juniorInboxItems.kind, "action"), inboxItemLinkedTo(reader.publicConversationId))] : [], ...reader.automationId ? [inboxItemAddedByAutomation(reader.automationId)] : []) ?? sql`false`;
27406
+ function inboxItemVisibleTo(reader, statuses) {
27407
+ return or(...publicIn(reader.tenants ?? []), ...reader.userId ? [inboxItemAssignedTo(reader.userId, statuses)] : [], ...reader.ownerAudienceUserId ? [inboxItemForEveryoneOfOwner(reader.ownerAudienceUserId)] : [], ...reader.conversationId ? [inboxItemLinkedTo(reader.conversationId)] : [], ...reader.publicConversationId ? [and(eq(inboxItemVisibility(), "public"), eq(juniorInboxItems.kind, "action"), inboxItemLinkedTo(reader.publicConversationId))] : [], ...reader.automationId ? [inboxItemAddedByAutomation(reader.automationId)] : []) ?? sql`false`;
25800
27408
  }
25801
27409
  /** Return whether an Inbox item is a public question (`action` item). */
25802
27410
  function isPublicQuestion(item) {
@@ -25964,12 +27572,11 @@ function canActOnInboxItem(item, userId) {
25964
27572
  return item.assignees.some((assignee) => assignee.userId === userId);
25965
27573
  }
25966
27574
  /**
25967
- * Return whether a User can answer an open question. Anyone who can act on
25968
- * it can (`canActOnInboxItem`). A public question that an agent asked in a
25969
- * Conversation is open to anyone who can see it, such as a member of its
25970
- * public Slack channel. A private item, a To-do, a plugin's item, and an
25971
- * Automation alert keep the assignee rule, and so do Take and Dismiss. The
25972
- * caller checks that the User can see the item.
27575
+ * Return whether a User can answer or dismiss an open item. Anyone who can
27576
+ * act on it can (`canActOnInboxItem`). A public question that an agent
27577
+ * asked in a Conversation is open to anyone who can see it, such as a
27578
+ * member of its public Slack channel. Other items, and Take, keep the
27579
+ * assignee rule. The caller checks that the User can see the item.
25973
27580
  */
25974
27581
  function canAnswerInboxItem(item, userId) {
25975
27582
  if (canActOnInboxItem(item, userId)) return true;
@@ -26195,15 +27802,20 @@ function isLeadSql(conversationId) {
26195
27802
  * the Lead's actor the starter of all Space work.
26196
27803
  */
26197
27804
  function conversationTopLevelIdSql(conversation) {
27805
+ const { conversationId, parentConversationId, rootConversationId } = conversation;
26198
27806
  const ancestorParent = sql`status_ancestor.parent_conversation_id`;
26199
- return sql`(case when ${conversation.parentConversationId} is null then ${conversation.conversationId} else (
27807
+ const belowRoot = sql`${ancestorParent} is not distinct from ${rootConversationId}`;
27808
+ return sql`(case
27809
+ when ${parentConversationId} is null then ${conversationId}
27810
+ when ${rootConversationId} <> ${conversationId} and not ${isLeadSql(rootConversationId)} then ${rootConversationId}
27811
+ else (
26200
27812
  with recursive status_ancestor(conversation_id, parent_conversation_id) as (
26201
- select ${conversation.conversationId}::text, ${conversation.parentConversationId}::text
27813
+ select ${conversationId}::text, ${parentConversationId}::text
26202
27814
  union
26203
27815
  select parent.conversation_id, parent.parent_conversation_id
26204
27816
  from status_ancestor
26205
27817
  join junior_conversations parent on parent.conversation_id = ${ancestorParent}
26206
- where not ${isLeadSql(ancestorParent)}
27818
+ where not ${belowRoot}
26207
27819
  )
26208
27820
  select conversation_id from status_ancestor
26209
27821
  where ${ancestorParent} is null or ${isLeadSql(ancestorParent)}
@@ -27496,90 +29108,6 @@ async function restoreArchivedPath(db, conversationId) {
27496
29108
  if (!node) return;
27497
29109
  await setArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.archivedAt).map((entry) => entry.conversationId), null);
27498
29110
  }
27499
- // src/conversation-events/lock.ts
27500
- /** Serialize event sequence allocation with other conversation writes. */
27501
- async function withConversationEventLock(executor, conversationId, callback) {
27502
- return executor.withLock(`junior_conversation:${conversationId}`, callback);
27503
- }
27504
- // src/db/postgres-json.ts
27505
- /**
27506
- * Replace actual NUL characters that PostgreSQL cannot store in JSONB.
27507
- * Literal `\\u0000` text is preserved because it contains no NUL character.
27508
- */
27509
- function sanitizePostgresJson(value) {
27510
- if (typeof value === "string") return value.replaceAll("\0", " ");
27511
- if (Array.isArray(value)) return value.map((item) => sanitizePostgresJson(item));
27512
- if (value === null || typeof value !== "object") return value;
27513
- const prototype = Object.getPrototypeOf(value);
27514
- if (prototype !== Object.prototype && prototype !== null) return value;
27515
- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, sanitizePostgresJson(item)]));
27516
- }
27517
- // src/conversation-events/store.ts
27518
- /** Read the next seq and the current History version of a Conversation. */
27519
- async function readEventCursor(executor, conversationId) {
27520
- const [row] = await executor.db().select({
27521
- maxSeq: sql`max(${juniorConversationEvents.seq})`,
27522
- maxHistoryVersion: sql`max(${juniorConversationEvents.historyVersion})`
27523
- }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
27524
- return {
27525
- nextSeq: row?.maxSeq == null ? 0 : Number(row.maxSeq) + 1,
27526
- historyVersion: row?.maxHistoryVersion == null ? 0 : Number(row.maxHistoryVersion)
27527
- };
27528
- }
27529
- /**
27530
- * Drop the events whose idempotency key is already stored, or repeats an
27531
- * earlier event of the same call. Events without a key are always kept.
27532
- */
27533
- async function unseenEvents(executor, conversationId, events) {
27534
- const keys = events.flatMap((event) => event.idempotencyKey === void 0 ? [] : [event.idempotencyKey]);
27535
- const seen = /* @__PURE__ */ new Set();
27536
- if (keys.length > 0) {
27537
- const rows = await executor.db().select({ key: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.idempotencyKey, keys)));
27538
- for (const row of rows) if (row.key) seen.add(row.key);
27539
- }
27540
- return events.filter((event) => {
27541
- if (event.idempotencyKey === void 0) return true;
27542
- if (seen.has(event.idempotencyKey)) return false;
27543
- seen.add(event.idempotencyKey);
27544
- return true;
27545
- });
27546
- }
27547
- /** Store rows in order from the cursor, at its History version. */
27548
- async function insertEventRows(executor, conversationId, cursor, rows) {
27549
- return await insertAt(executor, conversationId, cursor.historyVersion, rows.map((row, index) => ({
27550
- row,
27551
- seq: cursor.nextSeq + index
27552
- })));
27553
- }
27554
- /**
27555
- * Store a History replacement row. It starts the next History version, so
27556
- * every later row belongs to the history that it sets.
27557
- */
27558
- async function insertHistoryReplacementRow(executor, conversationId, cursor, row) {
27559
- const [inserted] = await insertAt(executor, conversationId, cursor.historyVersion + 1, [{
27560
- row,
27561
- seq: cursor.nextSeq
27562
- }]);
27563
- return inserted;
27564
- }
27565
- async function insertAt(executor, conversationId, historyVersion, rows) {
27566
- const values = rows.map(({ row, seq }) => ({
27567
- conversationId,
27568
- seq,
27569
- historyVersion,
27570
- schemaVersion: row.schemaVersion,
27571
- idempotencyKey: row.idempotencyKey ?? null,
27572
- type: row.type,
27573
- payload: sanitizePostgresJson(row.payload),
27574
- actorIdentityId: row.actorIdentityId ?? null,
27575
- turnId: row.turnId ?? null,
27576
- createdAt: new Date(row.createdAtMs)
27577
- }));
27578
- if (values.length === 0) return [];
27579
- const db = executor.db();
27580
- await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(values);
27581
- return values;
27582
- }
27583
29111
  // src/chat/conversations/message-links.ts
27584
29112
  /**
27585
29113
  * Web link matches in message text. Slack wraps links as <url|label>, and
@@ -28698,4 +30226,4 @@ async function closeDb() {
28698
30226
  current = void 0;
28699
30227
  await previous?.db.close();
28700
30228
  }
28701
- export { canActOnInboxItem as $, usdToMicroUsd as $a, questionLinks as $c, PluginMcpClient as $d, topLevelConversation as $f, createSandboxCapability as $i, isPersonInput as $l, resolveEventMentions as $n, pauseConversationDelivery as $o, annotationKeyDigest as $r, isDmChannel as $s, completeConversationWork as $t, NoAudioError as $u, setFirstConversationLocation as A, automationDefinition as Aa, countInboxItemsNeedingUserBySubject as Ac, conversationNoteEvent as Ad, ServiceAccountUnavailableError as Af, removeReactionFromMessage as Ai, parseDashboardConversationLink as Al, canJoinTurn as An, collectEventMatchKeys as Ao, juniorApiTokens as Ap, readConversationAccessRows as Ar, isPublicConversation as As, injectContinuationToolName as At, embedConversationEvents as Au, conversationAggregateColumns as B, linkAutomationRunConversation as Ba, getOpenInboxItemBySubject as Bc, disconnectServiceAccount as Bd, resolveRootConversationId as Bf, slackMentionedUserIds as Bi, parseTypedQuery as Bl, pushInboxSnoozeWakes as Bn, turnEvents as Bo, juniorSpaceConfigurations as Bp, verifyConversationQueueMessage as Br, deletePushSubscription as Bs, setTodoStatusByUser as Bt, excerptTerms as Bu, conversationSlackTenantId as C, getEventAutomation as Ca, findLinkedSlackUser as Cc, getProviderErrorUserMessage as Cd, getMcpProviderErrorAttributes as Cf, addReactionToMessage as Ci, getDashboardInboxItemLink as Cl, isFinalAttempt as Cn, AGENT_RESOURCE_TYPE as Co, juniorConversationParticipants as Cp, canAddConversationMessages as Cr, conversationAncestorsOrSelf as Cs, inboxItemOwnerConversationId as Ct, registeredEventTypeSchema as Cu, createSqlStore as D, setEventAutomationStatus as Da, upsertLinkedIdentity as Dc, JUNIOR_NATIVE_EVENT_NAMESPACE as Dd, getOAuthProviderErrorAttributes as Df, openSlackModal as Di, getDashboardSpaceLink as Dl, releaseInboundMessage as Dn, starterWatchId as Do, juniorConversationMetrics as Dp, createConversationAccessReader as Dr, conversationSearchVector as Ds, validatePlugins as Dt, ToolInputError as Du, latestUserMessageQuery as E, saveEventAutomation as Ea, recordGoogleSignIn as Ec, getGatewayApiKey as Ed, fetchWithBoundedOAuthErrorBodies as Ef, openSlackDirectMessage as Ei, getDashboardSettingsLink as El, pruneActiveConversation as En, publishAgentUpdate as Eo, juniorConversationEmbeddings as Ep, conversationAccessFromRows as Er, loadAnnotationLabeler as Es, getRegistrations as Et, requireValidEventTrigger as Eu, destinationUpsertFromDestination as F, AutomationConflictError as Fa, closeReadReplyNotice as Fc, installAppContext as Fd, agentTurnCostUsd as Ff, SLACK_USER_MENTION_RE as Fi, contentVersion as Fl, readInboundMessageSender as Fn, getWatch as Fo, juniorCodeRepositories as Fp, readMemberParticipants as Fr, defaultTimezone as Fs, CHILD_AGENT_KINDS as Ft, seqIn as Fu, conversationStatusSql as G, readAutomationExecutions as Ga, takeInboxItem as Gc, serviceAccountPlugins as Gd, createSlackDestination as Gf, createPluginState as Gi, rankSearchMatches as Gl, SLACK_INBOX_ITEM_VIEW_ID as Gn, verifyEventAutomationCredentialSubject as Go, juniorUsers as Gp, QUEUE_SIGNATURE_MAX_AGE_MS as Gr, isPausedBySlack as Gs, beginConversationResume as Gt, embedConversationQuery as Gu, conversationUsageCostExpr as H, readAutomationExecutionStatusDays as Ha, listReplyActionItems as Hc, getServiceAccountStatus as Hd, conversationDetailTouch as Hf, applyPluginFormatMarkdown as Hi, fuzzyRank as Hl, resolveSlackInboxItemCardConversationId as Hn, bindScheduledAutomationCredentialSubject as Ho, juniorIdentities as Hp, conversationQueueMessageSchema as Hr, readNotificationSchedule as Hs, appendAndEnqueueExclusiveInboundMessage as Ht, isEventEmbeddingsEnabled as Hu, upsertDestination as I, automationRevision as Ia, INBOX_ITEM_REPLIED_REASON as Ic, createPluginCatalogRuntime as Id, agentTurnTotalTokens as If, escapeSlackMrkdwnText as Ii, contentVersionHeaders as Il, isEventMailboxMetadata as In, isQuietEvent as Io, juniorAttachmentUploads as Ip, rootVisibleToViewer as Ir, findActorTimezone as Is, PARENT_AGENT_TARGET as It, storeConversationEventLexemes as Iu, executionIsActive as J, readAutomationTitlesByConversationId as Ja, inboxItemRequest as Jc, parseOAuthTokenResponse as Jd, isLeadSql$1 as Jf, createPluginModel as Ji, canMoveToSpace as Jl, parseSlackInboxItemFormTarget as Jn, verifyTimerWatchCredentialSubject as Jo, juniorArtifacts as Jp, getQueueProvider as Jr, getFilePermalink as Js, claimConversationAttempt as Jt, completeObject as Ju, conversationTurnFailedSql as K, readAutomationRowStats as Ka, updateInboxItemContent as Kc, startServiceAccountSignIn as Kd, requireSlackDestination as Kf, createPluginDecider as Ki, scoredSearchMatches as Kl, buildSlackInboxItemModal as Kn, verifyScheduledAutomationCredentialSubject as Ko, juniorDestinations as Kp, signQueueMessage as Kr, SlackActionError as Ks, cancelHumanFacingPendingMessages as Kt, storeConversationEmbedding as Ku, parseSessionSource as L, requireAutomationRevision as La, closeInboxItem as Lc, HOST_MANAGED_CREDENTIAL_PLACEHOLDER as Ld, agentTurnUsageSchema as Lf, formatSlackLink as Li, revalidateContent as Ll, createSlackInboxItemToolServices as Ln, listConversationsWithWatches as Lo, juniorAttachments as Lp, viewerMarksFromParticipant as Lr, resolveUserTimezone as Ls, agentNameSchema as Lt, SEARCHABLE_EVENT_TYPES as Lu, locationSchema as M, listAutomationVersions as Ma, listWaitingConversations as Mc, context_exports as Md, parsePluginManifest as Mf, uploadFilesToConversation as Mi, parseDashboardTaskLink as Ml, isAttemptInterrupt as Mn, createWatch as Mo, codeChangeSearchDocument as Mp, conversationIsMemberRoot as Mr, readWebPushConfig as Ms, makeStructuredToolOutput as Mt, indexEndedTurnEvents as Mu, claimProviderConversation as N, readAutomationVersion as Na, waitingConversationIdsQuery as Nc, createAppContext as Nd, workloadIdentityHeader as Nf, slackEntitySchema as Ni, projectConversationMessages as Nl, selectAttemptMessages as Nn, deliverWatch as No, codeRepositorySearchDocument as Np, conversationIsNotUnsubscribedRoot as Nr, sendPushNotificationToUser as Ns, findChildAgentConversationId as Nt, lexemesSql as Nu, withConversationMutationLock as O, admitEventAutomationRun as Oa, readCachedLinkedHandle as Oc, agentsInstructionsUpdatedEvent as Od, CredentialMintError as Of, postSlackEphemeralMessage as Oi, getDashboardTaskLink as Ol, traceContextSchema as On, cancelSubscriptions as Oo, juniorConversationEvents as Op, leaveEndsAccess as Or, readConversationMetadata as Os, apiRoutePrefix as Ot, isToolInputError as Ou, getConversationIdByProviderConversation as P, sameDefinitionValue as Pa, closeHandledReplyNotices as Pc, getAppContext as Pd, addAgentTurnUsage as Pf, slackExternalRefIdSchema as Pi, REVALIDATED_READ_PATHS as Pl, readParentMessage as Pn, findMatchingWatches as Po, juniorCodeChanges as Pp, conversationPinnedForUser as Pr, resolveNotificationTimezone as Ps, getAgentBinding as Pt, searchedEventTextSql as Pu, treeAwaitsAuthorization as Q, microUsdToUsd as Qa, pluginSubjectKind as Qc, McpAuthorizationRequiredError as Qd, notLeadConversation as Qf, basePluginContext as Qi, instructionAuthor as Ql, sendSlackReply as Qn, isConversationDeliveryPaused as Qo, renderSlackObjectCard as Qr, isConversationScopedChannel as Qs, completeConversationStop as Qt, transcribeFromUrl as Qu, replaceConversationMetrics as R, emptyAutomationRunWindows as Ra, dismissOpenInboxItems as Rc, resolveAuthTokenPlaceholder as Rd, hasAgentTurnUsage as Rf, normalizeSlackStatusText as Ri, memoryDb as Rl, createInboxItemShow as Rn, listWatches as Ro, juniorMessageAttachments as Rp, getVercelConversationWorkQueue as Rr, lookupSlackUser as Rs, spawnChildAgentInputSchema as Rt, callsToolSql as Ru, setArchivedAt as S, findMatchingEventAutomations as Sa, deleteProviderIdentityForUser as Sc, getProviderErrorAttributes as Sd, getMcpAwareTelemetryMessage as Sf, notifyAutomationBlocked as Si, getDashboardConversationLink as Sl, hasRunnableConversationWork as Sn, workspaceSnapshotWatch as So, juniorConversationReadPositions as Sp, canAccessConversation as Sr, upsertPluginAnnotation as Ss, inboxItemOwnedByThroughSubject as St, registeredEventTriggerProblems as Su, lastMessageAtSql as T, parseEventAutomationRow as Ta, findUserByVerifiedEmails as Tc, isProviderRetryError as Td, OAuthProviderError as Tf, getSlackMessagePermalink as Ti, getDashboardPersonLink as Tl, moveIdleConversationDestination as Tn, isAgentResourceType as To, juniorConversationEventEmbeddings as Tp, canReadConversation as Tr, conversationSubtreeColumns as Ts, getPlugins as Tt, requireEventIdentifier as Tu, conversationIsActiveSql as U, readAutomationExecutionStatusHours as Ua, ownerConversationId as Uc, serviceAccountAllows as Ud, nextDetailVersion as Uf, getPluginUserPromptContributions as Ui, prefixMatch as Ul, syncInboxItemSlackCards as Un, bindSlackDirectCredentialSubject as Uo, slackPersonPredicate as Up, isConversationQueueMessageRejectedError as Ur, saveNotificationSchedule as Us, appendAndEnqueueInboundMessage as Ut, backfillConversationEmbeddings as Uu, conversationRangeColumns as V, readAutomationExecutionByConversationId as Va, insertInboxItem as Vc, finishServiceAccountSignIn as Vd, rootConversationIsArchived as Vf, wrapBareSlackUserIds as Vi, fuzzyMatch as Vl, runInboxItemPushTimers as Vn, bindEventAutomationCredentialSubject as Vo, juniorSpaces as Vp, ConversationQueueMessageRejectedError as Vr, listPushSubscriptions as Vs, ackMessages as Vt, storedMessageJson as Vu, conversationLastTurnOutcomeSql as W, readAutomationExecutionSummaries as Wa, searchInboxItems as Wc, serviceAccountOnly as Wd, touchConversationDetail as Wf, pluginMcpContext as Wi, prefixRank as Wl, findSlackThreadOwnerId as Wn, createSlackDirectCredentialSubject as Wo, slackPersonSearchDocument as Wp, nudgeIdempotencyKey as Wr, savePushSubscription as Ws, appendInboundMessage as Wt, createConversationEmbedder as Wu, awaitsAuthorizationFrom as X, refreshAutomationLastRun as Xa, itemQuestion as Xc, createMcpServiceAccountClientProvider as Xd, spaceLeadIds as Xf, createPluginConversationEvents as Xi, dispatchInstructionsInvokeSkills as Xl, parseSlackUserInputSubmission as Xn, JUNIOR_THREAD_STATE_TTL_MS as Xo, buildSentryEventUrl as Xr, getSlackClient as Xs, clearConsumedConversationWake as Xt, generateImages as Xu, conversationKindFromRow as Y, recordAutomationExecution as Ya, inboxItemTitle as Yc, hasRequiredOAuthScope as Yd, rootSpaceIdSql as Yf, createPluginModelCostRecorder as Yi, deliversFinalText as Yl, safeLinkUrl as Yn, updateTimerIndex as Yo, buildSentryConversationUrl as Yr, getHeaderString as Ys, claimInboundMessage as Yt, completeText as Yu, hasUnexpiredAuthorizationRequest as Z, microUsdSql as Za, INBOX_SUBJECT_KINDS as Zc, getMcpServiceAccountCredentials as Zd, listedConversation as Zf, renderPluginConversationEvent as Zi, hasConversationMetadata as Zl, resolveSlackReplyTarget as Zn, canPauseConversationDelivery as Zo, formatSentryEventReference as Zr, isConversationChannel as Zs, clearExpiredConversationLease as Zt, searchWeb as Zu, unseenEvents as _, withScheduledAutomationLock as _a, updateViewerDisplayName as _c, isCompactionSummaryText as _d, resolvePluginCommandEnv as _f, markDispatchAwaitingResume as _i, readViewerInboxSnoozes as _l, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as _n, slackChannelMessageRunsAutomation as _o, inboxItemSearchDocument as _p, dismissPluginInboxItem as _r, createPluginAnnotations as _s, itemNeedsUser as _t, eventGuidance as _u, getDb as a, createPluginCache as aa, sleep$2 as ac, cacheKeyPrefix as ad, getMcpServerSessionId as af, buildDispatchId as ai, identityAvatarUrl as al, getConversationWorkState as an, generateShortTitle as ao, juniorTodos as ap, createVercelPluginTaskCallback as ar, codeChangeSubjectProvider as as, inboxItemAddedByAnyAutomation as at, remindsNoReplyForChildStatus as au, conversationDescendants as b, createEventAutomation as ba, saveActorAvatar as bc, createProviderError as bd, McpToolError as bf, markDispatchFailed as bi, snoozeTimerTrigger as bl, deferConversationMove as bn, WORKSPACE_SNAPSHOT_READY_EVENT as bo, juniorLocationConfigurations as bp, takeOverPluginClose as br, listConversationAnnotationsById as bs, requireInboxItemAssignees as bt, hasEventCatalogEntries as bu, pendingMigrations as c, blockScheduledAutomation as ca, createPluginUsers as cc, claudeMaxImageSize as cd, putMcpAuthSession as cf, createOrGetDispatch as ci, readUserAvatarUrls as cl, recordAttemptFailure as cn, activeParticipantUserIds as co, juniorQuestions as cp, sendVercelPluginTask as cr, codeChangeUrl as cs, inboxItemNeedsInput as ct, EVENT_AUTHOR_ID as cu, createSqlConversationEventStore as d, listScheduledAutomationsForTeam as da, readActorIdentity as dc, estimateTextTokens as dd, createEncryptedState as df, getDispatchInputMessageId as di, SNOOZE_TIMER_EVENT_TYPE as dl, requestAnotherSlice as dn, resolveAssignees as do, juniorAutomationRuns as dp, readThroughHttpCache as dr, assertNoObjectLinkConflicts as ds, inboxItemReaderForUserInConversation as dt, eventBotAuthorId as du, pluginConfigValues as ea, isSlackRequestTimeout as ec, GEN_AI_PROVIDER_NAME as ed, deleteMcpAuthSession as ef, decodeAnnotationRef as ei, subjectKindDismissNote as el, deadLetterAttempt as en, usdToMicroUsdUnbiased as eo, juniorTurnOutbox as ep, createPluginEventPublisher as er, resumeConversationDelivery as es, canAgentChangeInboxItem as et, isThread as eu, eventFromRow as f, parseScheduledAutomationRow as fa, readIdentityById as fc, textCharsForTokens as fd, readEncryptedState as ff, getDispatchRecord as fi, clearInboxWakeReasons as fl, requestConversationWork as fn, getEventCatalog as fo, automationFuzzyTitle as fp, createPluginConversationEventStats as fr, findObjectLinkType as fs, inboxItemVisibleTo as ft, isEventAuthorId as fu, readEventCursor as g, scheduledRunId as ga, setUserAdminFromSql as gc, hasCompactedConversationContext as gd, resolvePluginHeaderEnvRefs as gf, listPendingDispatchMailboxAppends as gi, listFiringInboxSnoozeTriggers as gl, takePendingEventMessages as gn, slackChannelMessageReplyThreadTs as go, inboxItemFuzzyTitle as gp, createPluginInboxItems as gr, annotationSubject as gs, isPluginInboxItem as gt, describeRegisteredEventTrigger as gu, insertEventRows as h, saveScheduledAutomationInLock as ha, resolveViewerUser as hc, COMPACTION_SUMMARY_PREFIX as hd, resolveApiHeaderTransforms as hf, isTerminalDispatchStatus as hi, inboxItemSnoozedBy as hl, stopConversationWork as hn, slackChannelMessageEvent as ho, juniorStats as hp, PLUGIN_CHOICE_FIELD_ID as hr, CORE_ANNOTATION_PLUGIN as hs, isOnlyAssignee as ht, automationEventCatalog as hu, getConversationStore as i, runNonInteractiveCommand as ia, withSlackRetries as ic, saveEnabledProviders as id, getMcpAuthSession as if, resolveTurnResumeRouting as ii, hasUserPhoto as il, getConversation as in, fallbackShortTitle as io, juniorWorkspaces as ip, startedTaskDefinition as ir, codeChangeSubjectKinds as is, conversationOwnsInboxItem as it, promptModeTurnTools as iu, startLocationThread as j, automationVersionOf as ja, inboxItemsNeedingUserVersionQuery as jc, renderJuniorNativeConversationEvent as jd, parseInlinePluginManifest as jf, unfurlSlackLinks as ji, parseDashboardPersonLink as jl, canShareTurn as jn, createTimerWatch as jo, juniorConversationAnnotations as jp, readableSlackTeamId as jr, resolveRootVisibility as js, juniorToolOutputSchema as jt, eventIndexLockKey as ju, locationFromRow as k, eventAutomationRunLimitReason as ka, readCachedUserByEmail as kc, authenticationLinkedEvent as kd, CredentialUnavailableError as kf, postSlackMessage as ki, isDashboardLink as kl, withIdleConversation as kn, cancelWatch as ko, juniorTurns as kp, readConversationAccessFromSql as kr, writeConversationMetadata as ks, coreRegistrations as kt, EVENT_INDEX_LOCK_TTL_MS as ku, readMigrationRecords as l, createScheduledAutomation as la, findUserByEmail as lc, estimateMessagesTokens as ld, putMcpServerSessionId as lf, getDispatchConversationId as li, userAvatarUrlsFromIdentities as ll, recordConversationRetry as ln, automationCreatorUserId as lo, questionFuzzyTitle as lp, queueCallback as lr, codeRepositoryUrl as ls, inboxItemPlugin as lt, EVENT_MESSAGE_AUTHOR as lu, deleteMessageLinks as m, saveScheduledAutomation as ma, readViewerAvatarUrl as mc, gatewayRoutingAttributes as md, webActorUserIds as mf, getPluginDispatchProjection as mi, inboxItemInRow as ml, steerWebPendingMessages as mn, requireSlackChannelMessageScope as mo, juniorAutomations as mp, createPluginConversationChanges as mr, ANNOTATION_SUBJECT_KINDS as ms, isInboxItemForEveryone as mt, CORE_EVENT_NAMESPACE as mu, getConversationEventStore as n, buildCommandScript as na, readPrivateSlackFile as nc, readEnabledProviders as nd, deleteMcpServerSessionId as nf, verifySlackSignature as ni, subjectKindPlugin as nl, dropPendingMessages as nn, AUTOMATION_ALERT_STEP_FIELD_ID as no, juniorSnapshots as np, getPluginRoutes as nr, annotationMatches as ns, canReadInboxItem as nt, parentResultActor as nu, getSqlExecutor as o, getConfigDefaults as oa, getWorkspaceTeamId as oc, createCache as od, getMcpStoredOAuthCredentials as of, claimDispatchMailboxAppend as oi, parseAvatarUrl as ol, getConversationWorkStates as on, resolveTaskTitle as oo, todoFuzzyTitle as op, pluginTaskId as or, readSubjectLinks as os, inboxItemAddedByAutomation as ot, turnBehavior as ou, copyMessageLinks as p, readScheduledAutomation as pa, readIdentityByIdFromSql as pc, readImageDimensions as pd, findLegacyWebActorUserId as pf, getDispatchTurnId as pi, deleteExpiredInboxSnoozes as pl, startConversationWork as pn, SLACK_EVENT_NAMESPACE as po, automationSearchDocument as pp, createPluginTurnEventReader as pr, linkTypeName as ps, isAutomationAlertItem as pt, isEventConversationMessage as pu, conversationWaitsOnUserSql as q, readAutomationRuns as qa, inboxItemAnswer as qc, buildOAuthTokenRequest as qd, sameDestination as qf, createPluginEmbedder as qi, fuseRankedLists as ql, parseSlackInboxItemClick as qn, verifySlackDirectCredentialSubject as qo, guardedCosineDistance as qp, verifyQueueMessage as qr, downloadPrivateSlackFile as qs, checkInConversationWork as qt, completeDecision as qu, getConversationMessageSearchStore as r, buildNonInteractiveShellScript as ra, streamPrivateSlackFile as rc, readServedProviders as rd, deleteMcpStoredOAuthCredentials as rf, resolveConversationRouting as ri, subjectTodo as rl, ensureConversationWake as rn, syncAutomationAlerts as ro, juniorWorkspaceRepos as rp, createPluginTaskStarter as rr, resolveAnnotationFilter as rs, canUserReadInboxItem as rt, postsRunNotices as ru, createJuniorSqlExecutor as s, truncateStatusText as sa, runWithWorkspaceTeamId as sc, requestPrefixAttributes as sd, patchMcpAuthSession as sf, confirmDispatchMailboxAppend as si, readAvatarFetch as sl, listActiveConversationIds as sn, EVERYONE_ASSIGNEE as so, todoSearchDocument as sp, pluginTaskParamsSchema as sr, subjectKey as ss, inboxItemForUser as st, watcherStartedConversation as su, db_exports as t, withPluginHookSpan as ta, normalizeSlackConversationId as tc, GEN_AI_SERVER_ADDRESS as td, deleteMcpAuthSessionsForUserProvider as tf, runWithSlackInstallation as ti, subjectKindLabel as tl, drainConversationMailbox as tn, AUTOMATION_ALERT_STEPS as to, juniorTurnInbox as tp, getPluginApiRoutes as tr, searchConversations as ts, canAnswerInboxItem as tt, isTopLevel as tu, isPostgresErrorCode as u, deleteScheduledAutomation as ua, listAdminUsersFromSql as uc, estimateRequestOverheadTokens as ud, putMcpStoredOAuthCredentials as uf, getDispatchIdForConversation as ui, userAvatarUrlsFromJoinedPhotos as ul, releaseConversationWork as un, resolveAssignee as uo, questionSearchDocument as up, getTurnRequestDeadline as ur, linkedCodeProviders as us, inboxItemReaderForUser as ut, EVENT_SYSTEM_ACTOR as uu, withConversationEventLock as v, blockEventAutomation as va, SYSTEM_IDENTITY_ID as vc, ProviderError as vd, McpProviderError as vf, markDispatchBlocked as vi, settleInboxSnoozes as vl, CONVERSATION_WORK_STALE_ENQUEUE_MS as vn, slackChannelMessageTrigger as vo, juniorInboxItemConversations as vp, hasAssigneeRoles as vr, createPluginConversationAnnotations as vs, questionSubject as vt, eventNamespaceSchema as vu, loadConversationSlackTenantIds as w, listDeletedEventAutomationsCreatedBy as wa, findSlackUserByPrimaryEmail as wc, isProviderRefusal as wd, toMcpProviderError as wf, deleteSlackMessage as wi, getDashboardLinkFilter as wl, isInvalidConversationRecordError as wn, agentWatch as wo, juniorConversationEventLexemes as wp, canInviteToConversation as wr, conversationSubtree as ws, inboxItemVisibility as wt, registeredResourceTypeSchema as wu, readConversationTrees as x, deleteEventAutomation as xa, deleteProviderIdentityForSlackUser as xc, findProviderError as xd, getMcpAwareErrorType as xf, markDispatchRunning as xi, unsnoozeInboxRow as xl, hasConversationStop as xn, workspaceSnapshotFinishedEvent as xo, juniorAgentBindings as xp, createPluginCodeChanges as xr, replaceAnnotationSubjectId as xs, requireInboxItemLinks as xt, registeredEventMatchSchema as xu, conversationAncestors as y, collectEventAutomationMatchKeys as ya, resolveActorIdentityId as yc, createAssistantProviderError as yd, McpServiceAccountRequiredError as yf, markDispatchCompleted as yi, snoozeInboxItems as yl, countPendingConversationMessages as yn, WORKSPACE_SNAPSHOT_FAILED_EVENT as yo, juniorInboxItems as yp, leavePluginInboxItem as yr, listConversationAnnotations as ys, readInboxItemAgentScope as yt, eventWatchUnavailable as yu, conversationCostOf as z, existingConversationId as za, getInboxItem as zc, mergeHeaderTransforms as zd, isLeadConversation as zf, slackMention as zi, searchTypedMemories as zl, pushConversationInboxItemsNow as zn, takeDueTimerWatches as zo, juniorConversations as zp, resolveConversationWorkTopic as zr, lookupSlackUserNames as zs, listTodos as zt, eventExcerpt as zu };
30229
+ export { conversationOwnsInboxItem as $, createPluginCache as $a, getWorkspaceTeamId as $c, readEnabledProviders as $d, deleteMcpServerSessionId as $f, buildDispatchId as $i, identityAvatarUrl as $l, publishTurnEnded as $n, generateShortTitle as $o, juniorSnapshots as $p, createVercelPluginTaskCallback as $r, readSubjectLinks as $s, getConversation as $t, parentResultActor as $u, getConversationIdByProviderConversation as A, escapeSlackMrkdwnText as Aa, resolveUserTimezone as Ac, lexemesSql as Ad, createAppContext as Af, rootVisibleToViewer as Ai, closeInboxItem as Al, codeRepositorySearchDocument as Am, turnInputPayloadSchema as An, automationRevision as Ao, workloadIdentityHeader as Ap, questionContent as Ar, listConversationsWithWatches as As, CHILD_AGENT_KINDS as At, REVALIDATED_READ_PATHS as Au, conversationLastTurnOutcomeSql as B, createPluginDecider as Ba, downloadPrivateSlackFile as Bc, backfillConversationEmbeddings as Bd, serviceAccountAllows as Bf, signQueueMessage as Bi, inboxItemRequest as Bl, slackPersonPredicate as Bm, findStalledTurns as Bn, readAutomationRowStats as Bo, nextDetailVersion as Bp, buildSlackInboxItemModal as Br, verifySlackDirectCredentialSubject as Bs, beginConversationResume as Bt, prefixRank as Bu, createSqlStore as C, postSlackMessage as Ca, isPublicConversation as Cc, requireValidEventTrigger as Cd, getGatewayApiKey as Cf, readConversationAccessFromSql as Ci, countInboxItemsNeedingUserBySubject as Cl, juniorConversationEmbeddings as Cm, traceContextSchema as Cn, eventAutomationRunLimitReason as Co, fetchWithBoundedOAuthErrorBodies as Cp, runInboxItemPushTimers as Cr, collectEventMatchKeys as Cs, apiRoutePrefix as Ct, getDashboardSpaceLink as Cu, startLocationThread as D, slackEntitySchema as Da, resolveNotificationTimezone as Dc, embedConversationEvents as Dd, conversationNoteEvent as Df, conversationIsNotUnsubscribedRoot as Di, closeHandledReplyNotices as Dl, juniorApiTokens as Dm, isAttemptInterrupt as Dn, readAutomationVersion as Do, ServiceAccountUnavailableError as Dp, inboxItemDelivery as Dr, findMatchingWatches as Ds, makeStructuredToolOutput as Dt, parseDashboardPersonLink as Du, setFirstConversationLocation as E, uploadFilesToConversation as Ea, sendPushNotificationToUser as Ec, EVENT_INDEX_LOCK_TTL_MS as Ed, authenticationLinkedEvent as Ef, conversationIsMemberRoot as Ei, waitingConversationIdsQuery as El, juniorTurns as Em, canShareTurn as En, listAutomationVersions as Eo, CredentialUnavailableError as Ep, conversationIdsSchema as Er, deliverWatch as Es, juniorToolOutputSchema as Et, parseDashboardConversationLink as Eu, conversationCostOf as F, wrapBareSlackUserIds as Fa, readNotificationSchedule as Fc, callsToolSql as Fd, resolveAuthTokenPlaceholder as Ff, ConversationQueueMessageRejectedError as Fi, listReplyActionItems as Fl, juniorMessageAttachments as Fm, scheduleInput as Fn, readAutomationExecutionByConversationId as Fo, hasAgentTurnUsage as Fp, zodToolDefinition as Fr, bindScheduledAutomationCredentialSubject as Fs, setTodoStatusByUser as Ft, searchTypedMemories as Fu, conversationKindFromRow as G, renderPluginConversationEvent as Ga, isConversationScopedChannel as Gc, completeObject as Gd, parseOAuthTokenResponse as Gf, formatSentryEventReference as Gi, questionLinks as Gl, juniorArtifacts as Gm, replyText as Gn, microUsdSql as Go, isLeadSql$1 as Gp, resolveSlackReplyTarget as Gr, isConversationDeliveryPaused as Gs, clearConsumedConversationWake as Gt, deliversFinalText as Gu, conversationTurnFailedSql as H, createPluginModel as Ha, getHeaderString as Hc, embedConversationQuery as Hd, serviceAccountPlugins as Hf, getQueueProvider as Hi, itemQuestion as Hl, juniorUsers as Hm, holdsLease as Hn, readAutomationTitlesByConversationId as Ho, createSlackDestination as Hp, parseSlackInboxItemFormTarget as Hr, updateTimerIndex as Hs, checkInConversationWork as Ht, scoredSearchMatches as Hu, conversationAggregateColumns as I, applyPluginFormatMarkdown as Ia, saveNotificationSchedule as Ic, eventExcerpt as Id, mergeHeaderTransforms as If, conversationQueueMessageSchema as Ii, ownerConversationId as Il, juniorConversations as Im, stopTurns as In, readAutomationExecutionStatusDays as Io, isLeadConversation as Ip, resolveSlackInboxItemCardConversationId as Ir, bindSlackDirectCredentialSubject as Is, ackMessages as It, parseTypedQuery as Iu, treeAwaitsAuthorization as J, pluginConfigValues as Ja, normalizeSlackConversationId as Jc, searchWeb as Jd, getMcpServiceAccountCredentials as Jf, decodeAnnotationRef as Ji, subjectKindDismissNote as Jl, findTurnActor as Jn, usdToMicroUsdUnbiased as Jo, listedConversation as Jp, createPluginEventPublisher as Jr, searchConversations as Js, completeConversationWork as Jt, hasConversationMetadata as Ju, awaitsAuthorizationFrom as K, basePluginContext as Ka, isDmChannel as Kc, completeText as Kd, hasRequiredOAuthScope as Kf, renderSlackObjectCard as Ki, subjectKindActionLabel as Kl, createTurnStepConsumer as Kn, microUsdToUsd as Ko, rootSpaceIdSql as Kp, sendSlackReply as Kr, pauseConversationDelivery as Ks, clearExpiredConversationLease as Kt, dispatchInstructionsInvokeSkills as Ku, conversationRangeColumns as L, getPluginUserPromptContributions as La, savePushSubscription as Lc, excerptTerms as Ld, disconnectServiceAccount as Lf, isConversationQueueMessageRejectedError as Li, searchInboxItems as Ll, juniorSpaceConfigurations as Lm, claimTurn as Ln, readAutomationExecutionStatusHours as Lo, resolveRootConversationId as Lp, syncInboxItemSlackCards as Lr, createSlackDirectCredentialSubject as Ls, appendAndEnqueueExclusiveInboundMessage as Lt, fuzzyMatch as Lu, upsertDestination as M, normalizeSlackStatusText as Ma, lookupSlackUserNames as Mc, seqIn as Md, installAppContext as Mf, getVercelConversationWorkQueue as Mi, getInboxItem as Ml, juniorCodeRepositories as Mm, createEngineContext as Mn, emptyAutomationRunWindows as Mo, agentTurnCostUsd as Mp, readableItem as Mr, takeDueTimerWatches as Ms, agentNameSchema as Mt, contentVersionHeaders as Mu, parseSessionSource as N, slackMention as Na, deletePushSubscription as Nc, storeConversationEventLexemes as Nd, createPluginCatalogRuntime as Nf, resolveConversationWorkTopic as Ni, getOpenInboxItemBySubject as Nl, juniorAttachmentUploads as Nm, endFailedTurn as Nn, existingConversationId as No, agentTurnTotalTokens as Np, parseToolInput as Nr, turnEvents as Ns, spawnChildAgentInputSchema as Nt, revalidateContent as Nu, locationSchema as O, slackExternalRefIdSchema as Oa, defaultTimezone as Oc, eventIndexLockKey as Od, renderJuniorNativeConversationEvent as Of, conversationPinnedForUser as Oi, closeReadReplyNotice as Ol, juniorConversationAnnotations as Om, selectAttemptMessages as On, sameDefinitionValue as Oo, parseInlinePluginManifest as Op, itemResult as Or, getWatch as Os, findChildAgentConversationId as Ot, parseDashboardTaskLink as Ou, replaceConversationMetrics as P, slackMentionedUserIds as Pa, listPushSubscriptions as Pc, SEARCHABLE_EVENT_TYPES as Pd, HOST_MANAGED_CREDENTIAL_PLACEHOLDER as Pf, verifyConversationQueueMessage as Pi, insertInboxItem as Pl, juniorAttachments as Pm, reconcileTurn as Pn, linkAutomationRunConversation as Po, agentTurnUsageSchema as Pp, zodTool as Pr, bindEventAutomationCredentialSubject as Ps, listTodos as Pt, memoryDb as Pu, canUserReadInboxItem as Q, runNonInteractiveCommand as Qa, sleep$2 as Qc, GEN_AI_SERVER_ADDRESS as Qd, deleteMcpAuthSessionsForUserProvider as Qf, resolveTurnResumeRouting as Qi, hasUserPhoto as Ql, markInputsAttempted as Qn, fallbackShortTitle as Qo, juniorTurnInbox as Qp, startedTaskDefinition as Qr, codeChangeSubjectProvider as Qs, ensureConversationWake as Qt, isTopLevel as Qu, conversationUsageCostExpr as R, pluginMcpContext as Ra, isPausedBySlack as Rc, storedMessageJson as Rd, finishServiceAccountSignIn as Rf, nudgeIdempotencyKey as Ri, takeInboxItem as Rl, juniorSpaces as Rm, commitStep as Rn, readAutomationExecutionSummaries as Ro, rootConversationIsArchived as Rp, findSlackThreadOwnerId as Rr, verifyEventAutomationCredentialSubject as Rs, appendAndEnqueueInboundMessage as Rt, fuzzyRank as Ru, latestUserMessageQuery as S, postSlackEphemeralMessage as Sa, writeConversationMetadata as Sc, requireEventIdentifier as Sd, isProviderRetryError as Sf, leaveEndsAccess as Si, readCachedUserByEmail as Sl, juniorConversationEventEmbeddings as Sm, releaseInboundMessage as Sn, admitEventAutomationRun as So, OAuthProviderError as Sp, pushInboxSnoozeWakes as Sr, cancelWatch as Ss, validatePlugins as St, getDashboardSettingsLink as Su, locationFromRow as T, unfurlSlackLinks as Ta, readWebPushConfig as Tc, isToolInputError as Td, agentsInstructionsUpdatedEvent as Tf, readableSlackTeamId as Ti, listWaitingConversations as Tl, juniorConversationEvents as Tm, canJoinTurn as Tn, automationVersionOf as To, CredentialMintError as Tp, assigneesSchema as Tr, createWatch as Ts, injectContinuationToolName as Tt, isDashboardLink as Tu, conversationWaitsOnUserSql as U, createPluginModelCostRecorder as Ua, getSlackClient as Uc, storeConversationEmbedding as Ud, startServiceAccountSignIn as Uf, buildSentryConversationUrl as Ui, INBOX_SUBJECT_KINDS as Ul, juniorDestinations as Um, releaseTurn as Un, recordAutomationExecution as Uo, requireSlackDestination as Up, safeLinkUrl as Ur, JUNIOR_THREAD_STATE_TTL_MS as Us, claimConversationAttempt as Ut, fuseRankedLists as Uu, conversationStatusSql as V, createPluginEmbedder as Va, getFilePermalink as Vc, createConversationEmbedder as Vd, serviceAccountOnly as Vf, verifyQueueMessage as Vi, inboxItemTitle as Vl, slackPersonSearchDocument as Vm, findTurn as Vn, readAutomationRuns as Vo, touchConversationDetail as Vp, parseSlackInboxItemClick as Vr, verifyTimerWatchCredentialSubject as Vs, cancelHumanFacingPendingMessages as Vt, rankSearchMatches as Vu, executionIsActive as W, createPluginConversationEvents as Wa, isConversationChannel as Wc, completeDecision as Wd, buildOAuthTokenRequest as Wf, buildSentryEventUrl as Wi, pluginSubjectKind as Wl, guardedCosineDistance as Wm, findTurnReplies as Wn, refreshAutomationLastRun as Wo, sameDestination as Wp, parseSlackUserInputSubmission as Wr, canPauseConversationDelivery as Ws, claimInboundMessage as Wt, canMoveToSpace as Wu, canAgentChangeInboxItem as X, buildCommandScript as Xa, streamPrivateSlackFile as Xc, NoAudioError as Xd, PluginMcpClient as Xf, verifySlackSignature as Xi, subjectKindPlugin as Xl, findTurnInputs as Xn, AUTOMATION_ALERT_STEP_FIELD_ID as Xo, topLevelConversation as Xp, getPluginRoutes as Xr, resolveAnnotationFilter as Xs, drainConversationMailbox as Xt, isPersonInput as Xu, canActOnInboxItem as Y, withPluginHookSpan as Ya, readPrivateSlackFile as Yc, transcribeFromUrl as Yd, McpAuthorizationRequiredError as Yf, runWithSlackInstallation as Yi, subjectKindLabel as Yl, findTurnDestination as Yn, AUTOMATION_ALERT_STEPS as Yo, notLeadConversation as Yp, getPluginApiRoutes as Yr, annotationMatches as Ys, deadLetterAttempt as Yt, instructionAuthor as Yu, canAnswerInboxItem as Z, buildNonInteractiveShellScript as Za, withSlackRetries as Zc, GEN_AI_PROVIDER_NAME as Zd, deleteMcpAuthSession as Zf, resolveConversationRouting as Zi, subjectTodo as Zl, findUnreadInputs as Zn, syncAutomationAlerts as Zo, juniorTurnOutbox as Zp, createPluginTaskStarter as Zr, codeChangeSubjectKinds as Zs, dropPendingMessages as Zt, isThread as Zu, readConversationTrees as _, addReactionToMessage as _a, conversationSubtree as _c, hasEventCatalogEntries as _d, createProviderError as _f, canAddConversationMessages as _i, findSlackUserByPrimaryEmail as _l, juniorLocationConfigurations as _m, hasRunnableConversationWork as _n, getEventAutomation as _o, McpToolError as _p, readInboundMessageSender as _r, agentWatch as _s, inboxItemOwnedByThroughSubject as _t, unsnoozeInboxRow as _u, getDb as a, getDispatchInputMessageId as aa, findObjectLinkType as ac, EVENT_AUTHOR_ID as ad, claudeMaxImageSize as af, readThroughHttpCache as ai, readIdentityById as al, juniorQuestions as am, releaseConversationWork as an, listScheduledAutomationsForTeam as ao, putMcpAuthSession as ap, formatSlackConversationRedactedLabel as ar, getEventCatalog as as, inboxItemReaderForUser as at, SNOOZE_TIMER_EVENT_TYPE as au, loadConversationSlackTenantIds as b, openSlackDirectMessage as ba, conversationSearchVector as bc, registeredEventTypeSchema as bd, getProviderErrorUserMessage as bf, conversationAccessFromRows as bi, upsertLinkedIdentity as bl, juniorConversationParticipants as bm, moveIdleConversationDestination as bn, saveEventAutomation as bo, getMcpProviderErrorAttributes as bp, createInboxItemShow as br, starterWatchId as bs, getPlugins as bt, getDashboardLinkFilter as bu, pendingMigrations as c, getPluginDispatchProjection as ca, CORE_ANNOTATION_PLUGIN as cc, eventBotAuthorId as cd, estimateTextTokens as cf, createPluginConversationChanges as ci, resolveViewerUser as cl, juniorAutomationRuns as cm, startConversationWork as cn, saveScheduledAutomation as co, createEncryptedState as cp, resolveSlackConversationContextFromThreadId as cr, slackChannelMessageEvent as cs, isAutomationAlertItem as ct, inboxItemInRow as cu, createSqlConversationEventStore as d, markDispatchAwaitingResume as da, createPluginConversationAnnotations as dc, CORE_EVENT_NAMESPACE as dd, gatewayRoutingAttributes as df, dismissPluginInboxItem as di, SYSTEM_IDENTITY_ID as dl, juniorAutomations as dm, takePendingEventMessages as dn, withScheduledAutomationLock as do, webActorUserIds as dp, readSlackRawMessageContext as dr, slackChannelMessageTrigger as ds, isPluginInboxItem as dt, readViewerInboxSnoozes as du, claimDispatchMailboxAppend as ea, subjectKey as ec, postsRunNotices as ed, readServedProviders as ef, pluginTaskId as ei, runWithWorkspaceTeamId as el, juniorWorkspaceRepos as em, getConversationWorkState as en, getConfigDefaults as eo, deleteMcpStoredOAuthCredentials as ep, readTurnEndedMessages as er, resolveTaskTitle as es, inboxItemAddedByAnyAutomation as et, parseAvatarUrl as eu, eventFromRow as f, markDispatchBlocked as fa, listConversationAnnotations as fc, automationEventCatalog as fd, COMPACTION_SUMMARY_PREFIX as ff, hasAssigneeRoles as fi, resolveActorIdentityId as fl, juniorStats as fm, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as fn, blockEventAutomation as fo, resolveApiHeaderTransforms as fp, resolveSlackChannelIdFromMessage as fr, WORKSPACE_SNAPSHOT_FAILED_EVENT as fs, itemNeedsUser as ft, settleInboxSnoozes as fu, conversationDescendants as g, notifyAutomationBlocked as ga, conversationAncestorsOrSelf as gc, eventWatchUnavailable as gd, createAssistantProviderError as gf, canAccessConversation as gi, findLinkedSlackUser as gl, juniorInboxItems as gm, hasConversationStop as gn, findMatchingEventAutomations as go, McpServiceAccountRequiredError as gp, withConversationEventLock as gr, AGENT_RESOURCE_TYPE as gs, requireInboxItemLinks as gt, snoozeTimerWakeAtMs as gu, conversationAncestors as h, markDispatchRunning as ha, upsertPluginAnnotation as hc, eventNamespaceSchema as hd, ProviderError as hf, createPluginCodeChanges as hi, deleteProviderIdentityForUser as hl, juniorInboxItemConversations as hm, deferConversationMove as hn, deleteEventAutomation as ho, McpProviderError as hp, resumeConversationTree as hr, workspaceSnapshotWatch as hs, requireInboxItemAssignees as ht, snoozeTimerTrigger as hu, getConversationStore as i, getDispatchIdForConversation as ia, assertNoObjectLinkConflicts as ic, watcherStartedConversation as id, requestPrefixAttributes as if, getTurnRequestDeadline as ii, readActorIdentity as il, todoSearchDocument as im, recordConversationRetry as in, deleteScheduledAutomation as io, patchMcpAuthSession as ip, conversationVisibilityFromSlackChannelType as ir, resolveAssignees as is, inboxItemPlugin as it, userAvatarUrlsFromJoinedPhotos as iu, destinationUpsertFromDestination as j, formatSlackLink as ja, lookupSlackUser as jc, searchedEventTextSql as jd, getAppContext as jf, viewerMarksFromParticipant as ji, dismissOpenInboxItems as jl, juniorCodeChanges as jm, turnGroupKey as jn, requireAutomationRevision as jo, addAgentTurnUsage as jp, questionsSchema as jr, listWatches as js, PARENT_AGENT_TARGET as jt, contentVersion as ju, claimProviderConversation as k, SLACK_USER_MENTION_RE as ka, findActorTimezone as kc, indexEndedTurnEvents as kd, context_exports as kf, readMemberParticipants as ki, INBOX_ITEM_REPLIED_REASON as kl, codeChangeSearchDocument as km, readParentMessage as kn, AutomationConflictError as ko, parsePluginManifest as kp, ownerLinks as kr, isQuietEvent as ks, getAgentBinding as kt, projectConversationMessages as ku, readMigrationRecords as l, isTerminalDispatchStatus as la, annotationSubject as lc, isEventAuthorId as ld, textCharsForTokens as lf, createPluginInboxItems as li, setUserAdminFromSql as ll, automationFuzzyTitle as lm, steerWebPendingMessages as ln, saveScheduledAutomationInLock as lo, readEncryptedState as lp, slackChannelTypeFromConversationInfo as lr, slackChannelMessageReplyThreadTs as ls, isInboxItemForEveryone as lt, inboxItemSnoozedBy as lu, deleteMessageLinks as m, markDispatchFailed as ma, replaceAnnotationSubjectId as mc, eventGuidance as md, isCompactionSummaryText as mf, takeOverPluginClose as mi, deleteProviderIdentityForSlackUser as ml, inboxItemSearchDocument as mm, countPendingConversationMessages as mn, createEventAutomation as mo, resolvePluginCommandEnv as mp, getConversationStoppedAtMs as mr, workspaceSnapshotFinishedEvent as ms, readInboxItemAgentScope as mt, snoozeTimerId as mu, getConversationEventStore as n, createOrGetDispatch as na, codeRepositoryUrl as nc, remindsNoReplyForChildStatus as nd, cacheKeyPrefix as nf, sendVercelPluginTask as ni, findUserByEmail as nl, juniorTodos as nm, listActiveConversationIds as nn, blockScheduledAutomation as no, getMcpServerSessionId as np, setActiveSpanAttributes as nr, automationCreatorUserId as ns, inboxItemForUser as nt, readUserAvatarUrls as nu, getSqlExecutor as o, getDispatchRecord as oa, linkTypeName as oc, EVENT_MESSAGE_AUTHOR as od, estimateMessagesTokens as of, createPluginConversationEventStats as oi, readIdentityByIdFromSql as ol, questionFuzzyTitle as om, requestAnotherSlice as on, parseScheduledAutomationRow as oo, putMcpServerSessionId as op, resolveSlackChannelTypeFromMessage as or, SLACK_EVENT_NAMESPACE as os, inboxItemReaderForUserInConversation as ot, clearInboxWakeReasons as ou, copyMessageLinks as p, markDispatchCompleted as pa, listConversationAnnotationsById as pc, describeRegisteredEventTrigger as pd, hasCompactedConversationContext as pf, leavePluginInboxItem as pi, saveActorAvatar as pl, inboxItemFuzzyTitle as pm, CONVERSATION_WORK_STALE_ENQUEUE_MS as pn, collectEventAutomationMatchKeys as po, resolvePluginHeaderEnvRefs as pp, legacyWebMailboxMetadataSchema as pr, WORKSPACE_SNAPSHOT_READY_EVENT as ps, questionSubject as pt, snoozeInboxItems as pu, hasUnexpiredAuthorizationRequest as q, createSandboxCapability as qa, isSlackRequestTimeout as qc, generateImages as qd, createMcpServiceAccountClientProvider as qf, annotationKeyDigest as qi, subjectKindActions as ql, publishTurnStep as qn, usdToMicroUsd as qo, spaceLeadIds as qp, resolveEventMentions as qr, resumeConversationDelivery as qs, completeConversationStop as qt, feedRowShowsThreads as qu, getConversationMessageSearchStore as r, getDispatchConversationId as ra, linkedCodeProviders as rc, turnBehavior as rd, createCache as rf, queueCallback as ri, listAdminUsersFromSql as rl, todoFuzzyTitle as rm, recordAttemptFailure as rn, createScheduledAutomation as ro, getMcpStoredOAuthCredentials as rp, withSpan as rr, resolveAssignee as rs, inboxItemNeedsInput as rt, userAvatarUrlsFromIdentities as ru, createJuniorSqlExecutor as s, getDispatchTurnId as sa, ANNOTATION_SUBJECT_KINDS as sc, EVENT_SYSTEM_ACTOR as sd, estimateRequestOverheadTokens as sf, createPluginTurnEventReader as si, readViewerAvatarUrl as sl, questionSearchDocument as sm, requestConversationWork as sn, readScheduledAutomation as so, putMcpStoredOAuthCredentials as sp, resolveSlackConversationContext as sr, requireSlackChannelMessageScope as ss, inboxItemVisibleTo as st, deleteExpiredInboxSnoozes as su, db_exports as t, confirmDispatchMailboxAppend as ta, codeChangeUrl as tc, promptModeTurnTools as td, saveEnabledProviders as tf, pluginTaskParamsSchema as ti, createPluginUsers as tl, juniorWorkspaces as tm, getConversationWorkStates as tn, truncateStatusText as to, getMcpAuthSession as tp, countMetric as tr, activeParticipantUserIds as ts, inboxItemAddedByAutomation as tt, readAvatarFetch as tu, isPostgresErrorCode as u, listPendingDispatchMailboxAppends as ua, createPluginAnnotations as uc, isEventConversationMessage as ud, readImageDimensions as uf, legacyChoiceAction as ui, updateViewerDisplayName as ul, automationSearchDocument as um, stopConversationWork as un, scheduledRunId as uo, findLegacyWebActorUserId as up, parseSlackThreadId as ur, slackChannelMessageRunsAutomation as us, isOnlyAssignee as ut, listFiringInboxSnoozeTriggers as uu, setArchivedAt as v, deleteSlackMessage as va, conversationSubtreeColumns as vc, registeredEventMatchSchema as vd, findProviderError as vf, canInviteToConversation as vi, findUserByVerifiedEmails as vl, juniorAgentBindings as vm, isFinalAttempt as vn, listDeletedEventAutomationsCreatedBy as vo, getMcpAwareErrorType as vp, isEventMailboxMetadata as vr, isAgentResourceType as vs, inboxItemOwnerConversationId as vt, getDashboardConversationLink as vu, withConversationMutationLock as w, removeReactionFromMessage as wa, resolveRootVisibility as wc, ToolInputError as wd, JUNIOR_NATIVE_EVENT_NAMESPACE as wf, readConversationAccessRows as wi, inboxItemsNeedingUserVersionQuery as wl, juniorConversationMetrics as wm, withIdleConversation as wn, automationDefinition as wo, getOAuthProviderErrorAttributes as wp, INBOX_TOOL_SOURCE as wr, createTimerWatch as ws, coreRegistrations as wt, getDashboardTaskLink as wu, lastMessageAtSql as x, openSlackModal as xa, readConversationMetadata as xc, registeredResourceTypeSchema as xd, isProviderRefusal as xf, createConversationAccessReader as xi, readCachedLinkedHandle as xl, juniorConversationEventLexemes as xm, pruneActiveConversation as xn, setEventAutomationStatus as xo, toMcpProviderError as xp, pushConversationInboxItemsNow as xr, cancelSubscriptions as xs, getRegistrations as xt, getDashboardPersonLink as xu, conversationSlackTenantId as y, getSlackMessagePermalink as ya, loadAnnotationLabeler as yc, registeredEventTriggerProblems as yd, getProviderErrorAttributes as yf, canReadConversation as yi, recordGoogleSignIn as yl, juniorConversationReadPositions as ym, isInvalidConversationRecordError as yn, parseEventAutomationRow as yo, getMcpAwareTelemetryMessage as yp, createSlackInboxItemToolServices as yr, publishAgentUpdate as ys, inboxItemVisibility as yt, getDashboardInboxItemLink as yu, conversationIsActiveSql as z, createPluginState as za, SlackActionError as zc, isEventEmbeddingsEnabled as zd, getServiceAccountStatus as zf, QUEUE_SIGNATURE_MAX_AGE_MS as zi, updateInboxItemContent as zl, juniorIdentities as zm, findDiscardedUsage as zn, readAutomationExecutions as zo, conversationDetailTouch as zp, SLACK_INBOX_ITEM_VIEW_ID as zr, verifyScheduledAutomationCredentialSubject as zs, appendInboundMessage as zt, prefixMatch as zu };