@sentry/junior 0.300.0 → 0.302.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 (81) hide show
  1. package/dist/adapter-context-Cx9fn9B3.js +43 -0
  2. package/dist/{admin-UrTniSPO.js → admin-_poE5NKL.js} +2 -2
  3. package/dist/{agent-runner-bY4_0UPm.js → agent-runner-CY9RvsTX.js} +1367 -10649
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +6 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +124 -67
  8. package/dist/{app-D-AcIcCV.d.ts → app-BpY3wtRP.d.ts} +3 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +71 -299
  11. package/dist/{automation-Dw82oQ-h.js → automation-Cva5ZOwW.js} +1 -1
  12. package/dist/{background-compaction-queue-B6U3060-.js → background-compaction-queue-CXFq1_Cz.js} +94 -203
  13. package/dist/{briefs-DqiwWu-n.js → briefs-B3NG-pid.js} +3 -3
  14. package/dist/{catalog-runtime-D1oYNv04.js → catalog-runtime-Dss0lSV6.js} +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-9nHoFiJP.js → config-CzeZiMKs.js} +2 -2
  23. package/dist/{connections-DZjTN3JC.js → connections-CDYhMfrs.js} +6 -6
  24. package/dist/{continue-in-slack-Dtv7_U42.js → continue-in-slack-7Uf05ndC.js} +5 -6
  25. package/dist/{conversation-Dyjq2CZ8.js → conversation-BNXfq6Lb.js} +11 -1
  26. package/dist/{conversation-feed-CcDxlrlQ.js → conversation-feed-Clf_cv0n.js} +2 -1
  27. package/dist/{conversation-privacy-D-5HTXjS.js → conversation-privacy-D9xnM5mK.js} +1 -1
  28. package/dist/{conversation-turn-Cxl8WZD7.js → conversation-turn-D7SEZgTG.js} +16 -17
  29. package/dist/{credential-sync-C49ClwDX.js → credential-sync-DoD0gW-j.js} +13 -15
  30. package/dist/{db-BJNo6fK5.js → db-B-gtnNjr.js} +314 -5
  31. package/dist/{db-2resqBh1.d.ts → db-BdsCzytP.d.ts} +1 -1
  32. package/dist/{executor-DBIaOeJ_.js → executor-DZg20EqU.js} +39 -4
  33. package/dist/install-t1KQyTUs.js +228 -0
  34. package/dist/instrumentation.js +2 -2
  35. package/dist/{state-zSilNpbi.js → legacy-web-actor-id-C-cEeWqL.js} +33 -4
  36. package/dist/{lineage-0dereG7H.js → lineage-C79GjoQr.js} +2 -2
  37. package/dist/{logging-BIclibct.js → logging-C9oDAg4M.js} +7 -3
  38. package/dist/{message-dkOl-Iii.js → message-BLUCzJXN.js} +8 -8
  39. package/dist/{model-input-CLo9TaUd.js → model-input-5jwNC45G.js} +3 -3
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +4 -3
  42. package/dist/{oauth-callback-server-WmpjfJgQ.js → oauth-callback-server-BBl66vCb.js} +2 -2
  43. package/dist/{projection-w_X-zi7v.js → projection-CIBwgD3s.js} +437 -97
  44. package/dist/{prompt-B1Xw46-S.js → prompt-CRQbzp5e.js} +15 -5
  45. package/dist/queue-DtCDaIct.js +115 -0
  46. package/dist/{registry-BmP5vnlj.js → registry-DdFQHZ_d.js} +1 -1
  47. package/dist/{resolve-goo34bJK.js → resolve-CdW4BdrK.js} +4 -229
  48. package/dist/{result-PVBeU0Wf.js → result-oOMv1t4O.js} +9 -9
  49. package/dist/{runner-DKrfvNV6.js → runner-DqitLtm-.js} +9 -9
  50. package/dist/{sandbox-egress-signals-DsUcqrI0.js → sandbox-egress-signals-Bw9I0yfJ.js} +1 -1
  51. package/dist/{schema-Dns-sTas.d.ts → schema-BIFM-U1a.d.ts} +470 -30
  52. package/dist/{schema-C9iNFz5n.js → schema-DnVQepWP.js} +76 -31
  53. package/dist/{service-account-CMAAloAL.js → service-account-B6mKAPVo.js} +3 -3
  54. package/dist/{service-account-CmowamcB.js → service-account-CrZftRTb.js} +257 -6
  55. package/dist/{session-stop-BcAXze8a.js → session-stop-DW63Z3kj.js} +1103 -1007
  56. package/dist/{skills-DfsazET6.js → skills-C16fz60Z.js} +2 -2
  57. package/dist/{slack-conversation-unfurl-CzQonuWz.js → slack-conversation-unfurl-BHhefEb7.js} +8 -7
  58. package/dist/{spawn-C7o0FDDp.js → spawn-D_RnFYfy.js} +6 -6
  59. package/dist/{stop-CFOujp8C.js → stop-7p1i08CY.js} +941 -2311
  60. package/dist/{store-E3x2Fg_F.js → store-C28I0CVW.js} +5 -5
  61. package/dist/{task-queue-D-hCqdZW.js → task-queue-BVUJbQ28.js} +3 -3
  62. package/dist/{task-runner-vohUPLHe.js → task-runner-CWi8j7Z6.js} +6 -8
  63. package/dist/{thread-context-BzvdkgI9.js → thread-context-D3-yYUd0.js} +8 -8
  64. package/dist/{store-Dkeis_8o.js → turn-session-routing-BFMS9ATF.js} +382 -11
  65. package/dist/{turn-user-message-D5RnVmxQ.js → turn-user-message-C3-O8Omt.js} +3 -3
  66. package/dist/{validation-BbWikeSa.js → validation-BSFKUIb4.js} +1 -1
  67. package/dist/{version-GVBMW2jA.js → version-BHHXNi-0.js} +1 -1
  68. package/dist/version.js +1 -1
  69. package/dist/{viewer-BpxRliyO.js → viewer-B1SO21Qa.js} +3 -3
  70. package/dist/warmup-Bz9bzkzN.js +13927 -0
  71. package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
  72. package/dist/{worker-Cbd-iuwZ.js → worker-BspReIIK.js} +7 -7
  73. package/migrations/0108_conversation_embeddings.sql +13 -0
  74. package/migrations/meta/0108_snapshot.json +4688 -0
  75. package/migrations/meta/_journal.json +7 -0
  76. package/package.json +10 -8
  77. package/dist/adapter-S5UkjNK3.js +0 -303
  78. package/dist/reporting-window-DopzcOHh.js +0 -137
  79. package/dist/turn-session-routing-Bo_LxFum.js +0 -380
  80. package/dist/users-2bggndVg.js +0 -424
  81. package/dist/warmup-BW2qwnal.js +0 -3693
@@ -1,30 +1,30 @@
1
1
  import { a as getClient$1, h as startSpan, n as captureMessage, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { C as completeObject, D as resolveGatewayModel, E as rerankTexts, L as unwrapCurrentInstruction, Q as toOptionalTrimmed, R as escapeXml, S as completeDecision, T as embedTexts, b as GEN_AI_PROVIDER_NAME, i as getChatConfig, j as estimateTextTokens, n as botConfig, o as getSlackBotToken, y as normalizeSlackEmojiName } from "./config-9nHoFiJP.js";
3
- import { E as withSpan, G as isRecord$2, K as toOptionalNumber, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalString, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-BIclibct.js";
4
- import { t as canExposeConversationPayload } from "./conversation-privacy-D-5HTXjS.js";
2
+ import { C as completeObject, D as resolveGatewayModel, E as rerankTexts, L as unwrapCurrentInstruction, Q as toOptionalTrimmed, R as escapeXml, S as completeDecision, T as embedTexts, b as GEN_AI_PROVIDER_NAME, i as getChatConfig, j as estimateTextTokens, n as botConfig, o as getSlackBotToken, y as normalizeSlackEmojiName } from "./config-CzeZiMKs.js";
3
+ import { E as withSpan, J as toOptionalString, K as isRecord$2, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalNumber, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-C9oDAg4M.js";
4
+ import { t as canExposeConversationPayload } from "./conversation-privacy-D9xnM5mK.js";
5
5
  import { c as parseStoredSlackActor, d as parseSlackChannelReferenceId, f as parseSlackTeamId, i as isActorUserId, l as toStoredSlackActor, p as parseSlackUserId, s as parseActorUserId, v as parseSlackMessageTs } from "./actor-D2iXzvlN.js";
6
- import { A as startLocationThread, B as saveUserTimezone, C as isPersonInput, G as claimProviderConversation, J as addAgentTurnUsage, N as resolveActorIdentityId, Q as hasAgentTurnUsage, R as readUserTimezone, W as createCache, a as getConversationStore, at as parseDestination, b as createSqlStore, d as eventFromRow, f as withConversationEventLock, o as getDb, r as getConversationEventStore, s as getSqlExecutor, st as sameDestination, tt as conversationDetailTouch, u as createSqlConversationEventStore } from "./db-BJNo6fK5.js";
7
- import { A as juniorAttachments, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorIdentities, N as juniorUsers, O as juniorCodeRepositories, P as juniorDestinations, a as juniorPushSubscriptions, b as juniorConversationBriefs, f as juniorAutomations, i as juniorWorkspaces, j as juniorConversations, l as juniorReviewItems, m as juniorLocationConfigurations, n as juniorSnapshots, o as juniorReviewItemAssignees, r as juniorWorkspaceRepos, s as juniorReviewItemConversations, v as juniorConversationParticipants, w as juniorConversationEvents } from "./executor-DBIaOeJ_.js";
6
+ import { $ as fenceLock, C as isPersonInput, G as createCache, J as getStateAdapter, P as resolveActorIdentityId, Q as acquireActiveLock, V as saveUserTimezone, X as setStateValues, Y as getStateValues, Z as MUTATION_LOCK_TTL_MS, _t as sameDestination, a as getConversationStore, b as createSqlStore, c as hasAnnotationKey, ct as hasAgentTurnUsage, d as eventFromRow, dt as conversationDetailTouch, et as withLock, f as withConversationEventLock, ht as parseDestination, it as addAgentTurnUsage, j as startLocationThread, l as treeHasAnnotationKey, o as getDb, q as getDefaultRedisStateAdapterFor, r as getConversationEventStore, s as getSqlExecutor, tt as claimProviderConversation, u as createSqlConversationEventStore, z as readUserTimezone } from "./db-B-gtnNjr.js";
7
+ import { D as juniorConversationAnnotations, F as juniorDestinations, M as juniorConversations, N as juniorIdentities, O as juniorCodeChanges, P as juniorUsers, T as juniorConversationEvents, a as juniorPushSubscriptions, b as juniorConversationEmbeddings, f as juniorAutomations, i as juniorWorkspaces, j as juniorAttachments, k as juniorCodeRepositories, l as juniorReviewItems, m as juniorLocationConfigurations, n as juniorSnapshots, o as juniorReviewItemAssignees, r as juniorWorkspaceRepos, s as juniorReviewItemConversations, v as juniorConversationParticipants, x as juniorConversationBriefs } from "./executor-DZg20EqU.js";
8
8
  import { d as contextProvenance, f as instructionActors, n as agentHistoryItemSchema, p as instructionProvenanceFor } from "./history-IjdmO_r6.js";
9
- import { a as setStateValues, c as fenceLock, i as getStateValues, l as withLock, n as getDefaultRedisStateAdapterFor, o as MUTATION_LOCK_TTL_MS, r as getStateAdapter, s as acquireActiveLock } from "./adapter-S5UkjNK3.js";
10
- import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, g as credentialUserSubjectId, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-BmP5vnlj.js";
11
- import { n as pluginCatalogRuntime } from "./catalog-runtime-D1oYNv04.js";
12
- import { d as JUNIOR_NATIVE_EVENT_NAMESPACE, f as agentsInstructionsUpdatedEvent, g as renderJuniorNativeConversationEvent, l as completeObject$1, m as authenticationUnlinkedEvent, n as briefEntriesFromReportEvents, o as isEventConversationMessage, p as authenticationLinkedEvent, s as generateBrief, t as BRIEF_PROMPT, u as completeText } from "./prompt-B1Xw46-S.js";
9
+ import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, g as credentialUserSubjectId, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-DdFQHZ_d.js";
10
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Dss0lSV6.js";
11
+ import { _ as renderJuniorNativeConversationEvent, d as embedTexts$1, f as JUNIOR_NATIVE_EVENT_NAMESPACE, h as authenticationUnlinkedEvent, l as completeObject$1, m as authenticationLinkedEvent, n as briefEntriesFromReportEvents, o as isEventConversationMessage, p as agentsInstructionsUpdatedEvent, s as generateBrief, t as BRIEF_PROMPT, u as completeText } from "./prompt-CRQbzp5e.js";
13
12
  import { n as isWithinNotificationSchedule, r as notificationScheduleSchema, s as isValidTimeZone, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-cP0AACm1.js";
14
- import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-BpxRliyO.js";
15
- import { $ as briefResourceLabel, B as messageCardRef, H as readMessageCardRefs, R as reviewItemChangeRecordSchema, Y as readMessageAttachments, _ as conversationReportEventSchema, et as conversationBriefSchema, nt as parseStoredBrief, tt as parseBriefInput, v as conversationReportMessageEventSchema } from "./conversation-Dyjq2CZ8.js";
13
+ import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-B1SO21Qa.js";
14
+ import { $ as briefResourceLabel, B as messageCardRef, H as readMessageCardRefs, R as reviewItemChangeRecordSchema, Y as readMessageAttachments, _ as conversationReportEventSchema, et as conversationBriefSchema, nt as parseStoredBrief, tt as parseBriefInput, v as conversationReportMessageEventSchema } from "./conversation-BNXfq6Lb.js";
16
15
  import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
17
- import { n as readEncryptedState, t as createEncryptedState } from "./state-zSilNpbi.js";
16
+ import { i as readEncryptedState, r as createEncryptedState, t as findLegacyWebActorUserId } from "./legacy-web-actor-id-C-cEeWqL.js";
18
17
  import { i as readWebPushPrivateKey, t as readJuniorSecret } from "./secrets-DebYU866.js";
19
18
  import * as z from "zod";
20
19
  import path from "node:path";
21
20
  import { isDeepStrictEqual } from "node:util";
22
21
  import { AsyncLocalStorage } from "node:async_hooks";
23
22
  import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
24
- import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, not, notLike, or, sql } from "drizzle-orm";
23
+ import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, not, notExists, notLike, or, sql } from "drizzle-orm";
25
24
  import { EgressAuthRequired, EgressPolicyDenied, PluginToolInputError, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema, defineConversationEvent, destinationSchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTypeSchema, isPluginModelCostEventName, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectIconPath, objectLinkFilterSchema, objectTypeSchema, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, sourceSchema, stableEventMatchKey } from "@sentry/junior-plugin-api";
26
25
  import { alias } from "drizzle-orm/pg-core";
27
26
  import fs from "node:fs/promises";
27
+ import { parseMarkdown, walkAst } from "chat";
28
28
  import pLimit from "p-limit";
29
29
  import { WebClient } from "@slack/web-api";
30
30
  import http from "node:http";
@@ -632,6 +632,100 @@ function fragmentSelectionSet(selection, fragments, seen) {
632
632
  seen.add(name);
633
633
  return fragments.get(name)?.selectionSet ?? false;
634
634
  }
635
+ // src/chat/identities/slack-mention-text.ts
636
+ const SLACK_TOKEN_PATTERN = new RegExp([
637
+ String.raw`<@(?<user>[UW][A-Z0-9]+)(?:\|(?<userLabel>[^<>]*))?>`,
638
+ String.raw`<#(?<channel>[CG][A-Z0-9]+)(?:\|(?<channelLabel>[^<>]*))?>`,
639
+ String.raw`<!(?<special>[a-z]+(?:\^[^<>|\s]*)?)(?:\|(?<specialLabel>[^<>]*))?>`,
640
+ String.raw`<(?<url>(?:https?|mailto):[^<>|\s]+)\|(?<urlLabel>[^<>]*)>`
641
+ ].join("|"), "g");
642
+ function plainLabel(label) {
643
+ return label?.trim().replace(/^[@#]/, "") || void 0;
644
+ }
645
+ const slackIdentity = alias(juniorIdentities, "slack_mention_identity");
646
+ /**
647
+ * Read a name and the `provider` account handle of the people behind Slack
648
+ * user IDs. A person with several accounts at `provider` gets the first
649
+ * handle in sort order, so the result is stable.
650
+ */
651
+ async function readSlackPeople(slackUserIds, provider) {
652
+ if (slackUserIds.length === 0) return /* @__PURE__ */ new Map();
653
+ const rows = await getSqlExecutor().db().select({
654
+ handle: juniorIdentities.handle,
655
+ slackHandle: slackIdentity.handle,
656
+ slackName: slackIdentity.displayName,
657
+ slackUserId: slackIdentity.providerSubjectId,
658
+ userName: juniorUsers.displayName
659
+ }).from(slackIdentity).leftJoin(juniorUsers, eq(juniorUsers.id, slackIdentity.userId)).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, slackIdentity.userId), eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, provider))).where(and(eq(slackIdentity.kind, "user"), eq(slackIdentity.provider, "slack"), inArray(slackIdentity.providerSubjectId, slackUserIds)));
660
+ const people = /* @__PURE__ */ new Map();
661
+ for (const row of rows) {
662
+ const current = people.get(row.slackUserId) ?? {};
663
+ const handle = row.handle && (!current.handle || row.handle < current.handle) ? row.handle : current.handle;
664
+ const name = current.name ?? (row.userName?.trim() || row.slackName?.trim() || row.slackHandle?.trim());
665
+ people.set(row.slackUserId, {
666
+ ...handle ? { handle } : void 0,
667
+ ...name ? { name } : void 0
668
+ });
669
+ }
670
+ return people;
671
+ }
672
+ function mapStrings(value, replace) {
673
+ if (typeof value === "string") return replace(value);
674
+ if (Array.isArray(value)) return value.map((item) => mapStrings(item, replace));
675
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapStrings(item, replace)]));
676
+ return value;
677
+ }
678
+ /** Return the Slack tokens in `text` outside Markdown code. */
679
+ function slackTokens(text) {
680
+ const code = [];
681
+ walkAst(parseMarkdown(text), (node) => {
682
+ const { start, end } = node.position ?? {};
683
+ if ((node.type === "code" || node.type === "inlineCode") && start?.offset !== void 0 && end?.offset !== void 0) code.push([start.offset, end.offset]);
684
+ return node;
685
+ });
686
+ return [...text.matchAll(SLACK_TOKEN_PATTERN)].filter(({ index }) => !code.some(([start, end]) => index >= start && index < end));
687
+ }
688
+ function replaceToken(token, people) {
689
+ if (token.url) return token.urlLabel ? `[${token.urlLabel}](${token.url})` : token.url;
690
+ if (token.user) {
691
+ const person = people.get(token.user);
692
+ if (person?.handle) return `@${person.handle}`;
693
+ return person?.name ?? plainLabel(token.userLabel) ?? "a Slack user";
694
+ }
695
+ if (token.channel) {
696
+ const name = plainLabel(token.channelLabel);
697
+ return name ? `#${name}` : "a Slack channel";
698
+ }
699
+ return plainLabel(token.specialLabel) ?? token.special.split("^")[0];
700
+ }
701
+ /**
702
+ * Rewrite Slack syntax in every string of `value`, such as a tool input that
703
+ * goes to another provider, because the provider shows it as literal text.
704
+ * Markdown code stays as written. A Slack user becomes `@handle` of their
705
+ * linked account at `provider`. Without one, they become their name, so the
706
+ * text never mentions a guessed account. Channel and special mentions become
707
+ * plain words, and `<url|label>` becomes a Markdown link.
708
+ */
709
+ async function replaceSlackMentions(value, provider) {
710
+ const tokens = /* @__PURE__ */ new Map();
711
+ mapStrings(value, (text) => {
712
+ if (text.includes("<")) tokens.set(text, slackTokens(text));
713
+ return text;
714
+ });
715
+ const matches = [...tokens.values()].flat();
716
+ if (matches.length === 0) return value;
717
+ const people = await readSlackPeople([...new Set(matches.flatMap((match) => match.groups?.user ?? []))], provider);
718
+ return mapStrings(value, (text) => {
719
+ let result = "";
720
+ let cursor = 0;
721
+ for (const match of tokens.get(text) ?? []) {
722
+ result += text.slice(cursor, match.index);
723
+ result += replaceToken(match.groups, people);
724
+ cursor = match.index + match[0].length;
725
+ }
726
+ return result + text.slice(cursor);
727
+ });
728
+ }
635
729
  // src/chat/slack/user.ts
636
730
  const slackUserInfoSchema = z.object({
637
731
  ok: z.literal(true),
@@ -897,6 +991,209 @@ async function annotateToolResult(conversationId, plugin, result) {
897
991
  };
898
992
  return annotated;
899
993
  }
994
+ // src/chat/conversations/embedding.ts
995
+ /**
996
+ * One embedding per Conversation: a derived index for semantic Conversation
997
+ * search. Its text is the latest Brief, which summarizes the Conversation.
998
+ * Vectors are stored per model. A search compares only vectors of the same
999
+ * provider, model, and size as its query.
1000
+ */
1001
+ const MAX_EMBEDDED_CHARS = 8e3;
1002
+ /** Create the embedder that charges its cost to one Conversation. */
1003
+ function createConversationEmbedder(args) {
1004
+ return async ({ inputType, text }) => {
1005
+ const result = await embedTexts$1({
1006
+ cost: args.cost,
1007
+ inputType,
1008
+ modelId: botConfig.embeddingModelId,
1009
+ operation: args.operation,
1010
+ texts: [text.slice(0, MAX_EMBEDDED_CHARS)]
1011
+ });
1012
+ const vector = result.vectors[0];
1013
+ if (!vector) throw new Error("Embedding provider returned no vector");
1014
+ return {
1015
+ model: result.model,
1016
+ provider: result.provider,
1017
+ vector
1018
+ };
1019
+ };
1020
+ }
1021
+ /**
1022
+ * Store the Conversation embedding of a stored Brief. Skip it when the
1023
+ * Conversation already has a vector for this or a newer Brief version, so a
1024
+ * task retry embeds once and an older Turn never replaces a newer vector.
1025
+ */
1026
+ async function storeConversationEmbedding(db, embed, brief) {
1027
+ if (!brief.searchText) return;
1028
+ const table = juniorConversationEmbeddings;
1029
+ const [current] = await db.select({ briefVersion: table.briefVersion }).from(table).where(eq(table.conversationId, brief.conversationId)).limit(1);
1030
+ if (current && current.briefVersion >= brief.version) return;
1031
+ const embedding = await embed({
1032
+ inputType: "document",
1033
+ text: brief.searchText
1034
+ });
1035
+ const row = {
1036
+ briefVersion: brief.version,
1037
+ dimensions: embedding.vector.length,
1038
+ embedding: embedding.vector,
1039
+ model: embedding.model,
1040
+ provider: embedding.provider
1041
+ };
1042
+ await db.insert(table).values({
1043
+ conversationId: brief.conversationId,
1044
+ ...row
1045
+ }).onConflictDoUpdate({
1046
+ target: table.conversationId,
1047
+ set: {
1048
+ ...row,
1049
+ createdAt: sql`now()`
1050
+ },
1051
+ setWhere: sql`${table.briefVersion} < excluded.brief_version`
1052
+ });
1053
+ }
1054
+ /**
1055
+ * Cosine similarity of the stored vector to a query vector. Null for a
1056
+ * vector of another model or size. CASE fixes the order, so Postgres never
1057
+ * compares vectors of different sizes, which fails.
1058
+ */
1059
+ function conversationSimilarity(query) {
1060
+ const table = juniorConversationEmbeddings;
1061
+ return sql`CASE WHEN ${table.provider} = ${query.provider} AND ${table.model} = ${query.model} AND ${table.dimensions} = ${query.vector.length} THEN 1 - (${table.embedding} <=> ${JSON.stringify(query.vector)}::vector) END`;
1062
+ }
1063
+ // src/chat/conversations/search.ts
1064
+ /**
1065
+ * Search the Conversations that one requester may find: Conversations whose
1066
+ * root is public, of any surface, and Conversations whose root is at the
1067
+ * Destination of the requester's root. No other private Conversation is
1068
+ * returned, so no result leaks private data into the requester. See
1069
+ * `policies/conversation-access.md`.
1070
+ */
1071
+ const MAX_LINKS = 5;
1072
+ const MIN_VECTOR_SIMILARITY = .4;
1073
+ /**
1074
+ * Search the Conversations, outside the requester's own tree, that the
1075
+ * requester may find. Newest activity first, or best match for a query.
1076
+ * With an embedder, a query also matches by the meaning of the latest
1077
+ * Brief, and a match by meaning alone needs `MIN_VECTOR_SIMILARITY`.
1078
+ */
1079
+ async function searchConversations(db, args) {
1080
+ const { embedder, requesterConversationId, search } = args;
1081
+ const conversations = juniorConversations;
1082
+ const briefs = juniorConversationBriefs;
1083
+ const newer = alias(juniorConversationBriefs, "newer_briefs");
1084
+ const roots = alias(juniorConversations, "target_roots");
1085
+ const requesterRoot = alias(juniorConversations, "requester_roots");
1086
+ const embeddings = juniorConversationEmbeddings;
1087
+ const query = search.query?.trim() || void 0;
1088
+ const queryVector = query && embedder ? await embedder({
1089
+ inputType: "query",
1090
+ text: query
1091
+ }) : void 0;
1092
+ const similarity = queryVector ? conversationSimilarity(queryVector) : void 0;
1093
+ const tsquery = sql`websearch_to_tsquery('english', ${query ?? ""})`;
1094
+ const searchVector = sql`to_tsvector('english', ${briefs.searchText})`;
1095
+ const outcomeStatus = sql`${briefs.content}->'outcome'->>'status'`;
1096
+ const [requester] = await db.select({ rootId: conversations.rootConversationId }).from(conversations).where(eq(conversations.conversationId, requesterConversationId)).limit(1);
1097
+ const requesterRootId = requester?.rootId ?? requesterConversationId;
1098
+ const conditions = [
1099
+ isNull(roots.quickQuestionAt),
1100
+ isNull(conversations.quickQuestionAt),
1101
+ search.rootsOnly ? eq(conversations.conversationId, conversations.rootConversationId) : void 0,
1102
+ ne(conversations.rootConversationId, requesterRootId),
1103
+ or(eq(juniorDestinations.visibility, "public"), eq(roots.destinationId, db.select({ destinationId: requesterRoot.destinationId }).from(requesterRoot).where(eq(requesterRoot.conversationId, requesterRootId)))),
1104
+ search.annotation ? or(search.annotationOnSelf ? void 0 : treeHasAnnotationKey(conversations.conversationId, search.annotation), hasAnnotationKey(conversations.conversationId, search.annotation)) : void 0,
1105
+ search.statuses ? inArray(conversations.executionStatus, [...search.statuses]) : void 0,
1106
+ search.conversationIds ? inArray(conversations.conversationId, [...search.conversationIds]) : void 0,
1107
+ search.includeArchived ? void 0 : and(isNull(conversations.archivedAt), isNull(roots.archivedAt)),
1108
+ search.channelId ? eq(juniorDestinations.providerDestinationId, search.channelId) : void 0,
1109
+ search.outcomeStatus ? sql`${outcomeStatus} = ${search.outcomeStatus}` : void 0,
1110
+ search.afterMs !== void 0 ? gte(conversations.lastActivityAt, new Date(search.afterMs)) : void 0,
1111
+ search.beforeMs !== void 0 ? lt(conversations.lastActivityAt, new Date(search.beforeMs)) : void 0,
1112
+ query ? or(sql`${searchVector} @@ ${tsquery}`, ilike(conversations.title, `%${escapeLike(query)}%`), similarity ? sql`${similarity} >= ${MIN_VECTOR_SIMILARITY}` : void 0) : void 0
1113
+ ];
1114
+ const newestFirst = desc(conversations.lastActivityAt);
1115
+ const wordRank = sql`coalesce(ts_rank_cd(${searchVector}, ${tsquery}, 32), 0)`;
1116
+ const order = query ? [desc(similarity ? sql`${wordRank} + coalesce(${similarity}, 0)` : wordRank), newestFirst] : [newestFirst];
1117
+ const excerpt = query ? sql`ts_headline('english', ${briefs.searchText}, ${tsquery}, 'MaxFragments=2, MinWords=8, MaxWords=40, FragmentDelimiter=" … ", StartSel=**, StopSel=**')` : sql`null`;
1118
+ return (await db.select({
1119
+ archivedAt: conversations.archivedAt,
1120
+ rootArchivedAt: roots.archivedAt,
1121
+ briefContent: briefs.content,
1122
+ channelName: juniorDestinations.displayName,
1123
+ conversationId: conversations.conversationId,
1124
+ excerpt: excerpt.as("excerpt"),
1125
+ kind: conversations.kind,
1126
+ lastActivityAt: conversations.lastActivityAt,
1127
+ providerDestinationId: juniorDestinations.providerDestinationId,
1128
+ rootConversationId: roots.conversationId,
1129
+ status: conversations.executionStatus,
1130
+ title: conversations.title,
1131
+ transcriptPurgedAt: conversations.transcriptPurgedAt
1132
+ }).from(conversations).innerJoin(roots, eq(roots.conversationId, conversations.rootConversationId)).innerJoin(juniorDestinations, eq(juniorDestinations.id, roots.destinationId)).leftJoin(briefs, and(eq(briefs.conversationId, conversations.conversationId), notExists(db.select({ one: sql`1` }).from(newer).where(and(eq(newer.conversationId, briefs.conversationId), gt(newer.version, briefs.version)))))).leftJoin(embeddings, and(eq(embeddings.conversationId, briefs.conversationId), eq(embeddings.briefVersion, briefs.version))).where(and(...conditions)).orderBy(...order).limit(search.limit)).map((row) => {
1133
+ const brief = row.briefContent ? parseStoredBrief(row.briefContent) : void 0;
1134
+ return {
1135
+ archived: row.archivedAt !== null || row.rootArchivedAt !== null,
1136
+ ...row.channelName ? { channelName: row.channelName } : void 0,
1137
+ conversationId: row.conversationId,
1138
+ ...row.excerpt ? { excerpt: row.excerpt } : void 0,
1139
+ ...row.kind ? { kind: row.kind } : void 0,
1140
+ links: brief?.links.slice(0, MAX_LINKS) ?? [],
1141
+ ...brief ? { outcomeStatus: brief.outcome.status } : void 0,
1142
+ ...row.providerDestinationId ? { providerDestinationId: row.providerDestinationId } : void 0,
1143
+ rootConversationId: row.rootConversationId,
1144
+ status: row.status,
1145
+ ...brief ? { summary: brief.summary } : void 0,
1146
+ ...row.title ? { title: row.title } : void 0,
1147
+ transcriptPurged: row.transcriptPurgedAt !== null,
1148
+ updatedAtMs: row.lastActivityAt.getTime()
1149
+ };
1150
+ });
1151
+ }
1152
+ function escapeLike(value) {
1153
+ return value.replace(/[\\%_]/g, (match) => `\\${match}`);
1154
+ }
1155
+ // src/chat/conversations/plugin-search.ts
1156
+ const DEFAULT_LIMIT = 10;
1157
+ const MAX_LIMIT = 25;
1158
+ const WORKING_STATUSES = [
1159
+ "pending",
1160
+ "running",
1161
+ "paused"
1162
+ ];
1163
+ /**
1164
+ * Let a plugin tool find other Conversations by Annotation key. The current
1165
+ * Conversation is the requester, so the access rules of `searchConversations`
1166
+ * apply and its own tree is never a result.
1167
+ */
1168
+ function createPluginConversations(conversationId) {
1169
+ return { async search(input) {
1170
+ const limit = Math.min(input.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
1171
+ const search = {
1172
+ annotation: input.annotation,
1173
+ annotationOnSelf: true,
1174
+ includeArchived: false,
1175
+ limit,
1176
+ rootsOnly: false
1177
+ };
1178
+ const find = async (filters) => await searchConversations(getDb(), {
1179
+ requesterConversationId: conversationId,
1180
+ search: {
1181
+ ...search,
1182
+ ...filters
1183
+ }
1184
+ });
1185
+ const [working, newest] = await Promise.all([find({ statuses: WORKING_STATUSES }), find({})]);
1186
+ const seen = new Set(working.map((match) => match.conversationId));
1187
+ return [...working, ...newest.filter((match) => !seen.has(match.conversationId))].slice(0, limit).map((match) => ({
1188
+ conversationId: match.conversationId,
1189
+ ...match.rootConversationId !== match.conversationId ? { rootConversationId: match.rootConversationId } : void 0,
1190
+ status: match.status === "failed" ? "idle" : match.status,
1191
+ ...match.summary ? { summary: match.summary } : void 0,
1192
+ ...match.title ? { title: match.title } : void 0,
1193
+ updatedAt: new Date(match.updatedAtMs).toISOString()
1194
+ }));
1195
+ } };
1196
+ }
900
1197
  // src/chat/conversations/tool-replies.ts
901
1198
  /**
902
1199
  * Record the reply that a plugin tool posted for Junior, such as a pull
@@ -2568,9 +2865,17 @@ async function updateConversationBrief(context) {
2568
2865
  }
2569
2866
  await context.state.withLock(`brief:${run.conversationId}`, BRIEF_LOCK_TTL_MS, async () => {
2570
2867
  const db = context.db;
2868
+ const embed = createConversationEmbedder({
2869
+ cost: {
2870
+ conversationId: run.conversationId,
2871
+ turnId: run.runId
2872
+ },
2873
+ operation: "conversation_embedding"
2874
+ });
2571
2875
  const existing = await readConversationBriefForTurn(db, run.conversationId, run.runId);
2572
2876
  if (existing) {
2573
2877
  await emitBriefUpdated(context, existing);
2878
+ await storeConversationEmbedding(db, embed, existing);
2574
2879
  logSkip(context, run.conversationId, "turn_already_stored");
2575
2880
  return;
2576
2881
  }
@@ -2604,6 +2909,7 @@ async function updateConversationBrief(context) {
2604
2909
  ...generation.costUsd !== void 0 ? { costUsd: generation.costUsd } : void 0
2605
2910
  });
2606
2911
  await emitBriefUpdated(context, stored.value);
2912
+ await storeConversationEmbedding(db, embed, stored.value);
2607
2913
  if (!stored.inserted) logSkip(context, run.conversationId, "turn_already_stored");
2608
2914
  });
2609
2915
  }
@@ -3132,6 +3438,11 @@ function basePluginContext$1(plugin) {
3132
3438
  db: getDb()
3133
3439
  };
3134
3440
  }
3441
+ /** Pick one plugin's string config values and drop the plugin name prefix. */
3442
+ function pluginConfigValues(pluginName, configuration) {
3443
+ const prefix = `${pluginName}.`;
3444
+ return Object.fromEntries(Object.entries(configuration).flatMap(([key, value]) => key.startsWith(prefix) && typeof value === "string" ? [[key.slice(prefix.length), value]] : []));
3445
+ }
3135
3446
  /** Time one plugin hook call so slow plugins show up in turn traces. */
3136
3447
  async function withPluginHookSpan(pluginName, hookName, callback) {
3137
3448
  return await withSpan(`plugin.hook ${hookName}`, "plugin.hook", {}, callback, {
@@ -6333,7 +6644,7 @@ function readBareSlackUserMention(line, start) {
6333
6644
  * Wrap bare http(s) URLs and bare `@U123` Slack user IDs on a single line as
6334
6645
  * Slack explicit `<url>` links and `<@U123>` mentions.
6335
6646
  */
6336
- function wrapBareReferencesOnLine(line) {
6647
+ function wrapBareReferencesOnLine(line, urls) {
6337
6648
  let result = "";
6338
6649
  let i = 0;
6339
6650
  while (i < line.length) {
@@ -6361,7 +6672,7 @@ function wrapBareReferencesOnLine(line) {
6361
6672
  i = userMention.end;
6362
6673
  continue;
6363
6674
  }
6364
- if (line.startsWith("https://", i) || line.startsWith("http://", i)) {
6675
+ if (urls && (line.startsWith("https://", i) || line.startsWith("http://", i))) {
6365
6676
  const parsed = readBareUrl(line, i);
6366
6677
  if (parsed) {
6367
6678
  result += `<${parsed.url}>${parsed.suffix}`;
@@ -6378,12 +6689,13 @@ function wrapBareReferencesOnLine(line) {
6378
6689
  * Pre-wrap bare http(s) URLs outside fenced code blocks as Slack explicit
6379
6690
  * links, preventing Slack's auto-linker from consuming adjacent formatting
6380
6691
  * markers into the URL. Bare `@U123` user IDs become `<@U123>` mentions,
6381
- * because Slack shows a bare ID as literal text.
6692
+ * because Slack shows a bare ID as literal text. Pass `urls: false` to wrap
6693
+ * only the user IDs.
6382
6694
  *
6383
6695
  * Uses the same fence-toggle rule as `ensureBlockSpacing` so both passes
6384
6696
  * agree on which lines are code.
6385
6697
  */
6386
- function wrapBareReferences(text) {
6698
+ function wrapBareReferences(text, urls = true) {
6387
6699
  const lines = text.split("\n");
6388
6700
  const out = [];
6389
6701
  let inCodeBlock = false;
@@ -6393,10 +6705,18 @@ function wrapBareReferences(text) {
6393
6705
  out.push(line);
6394
6706
  continue;
6395
6707
  }
6396
- out.push(inCodeBlock ? line : wrapBareReferencesOnLine(line));
6708
+ out.push(inCodeBlock ? line : wrapBareReferencesOnLine(line, urls));
6397
6709
  }
6398
6710
  return out.join("\n");
6399
6711
  }
6712
+ /**
6713
+ * Wrap bare `@U123` Slack user IDs as `<@U123>` mentions. Call it before
6714
+ * plugin Markdown rewrites of chat text, so a plugin does not read `@U123`
6715
+ * as an account name of its provider.
6716
+ */
6717
+ function wrapBareSlackUserIds(text) {
6718
+ return wrapBareReferences(text, false);
6719
+ }
6400
6720
  const LIST_ITEM_PATTERN = /^[-*•]\s|^\d+\.\s/;
6401
6721
  /**
6402
6722
  * Turn a follow-up paragraph inside a list item into a bullet at the same
@@ -6452,13 +6772,14 @@ function ensureBlockSpacing(text) {
6452
6772
  * Normalize model-authored Slack markdown for delivery via `markdown_text`
6453
6773
  * or `{ type: "markdown" }` blocks.
6454
6774
  *
6455
- * Plugins may first rewrite ordinary Markdown. Core then applies Slack-only
6775
+ * Plugins may first rewrite ordinary Markdown with the Conversation facts in
6776
+ * `format`. Core then applies Slack-only
6456
6777
  * delivery shaping: bare URL wrapping, block spacing, and list follow-up
6457
6778
  * paragraph bullets. Slack reply delivery owns chunking and continuation
6458
6779
  * markers separately.
6459
6780
  */
6460
- function normalizeSlackReplyMarkdown(text) {
6461
- let normalized = applyPluginFormatMarkdown(text).replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "");
6781
+ function normalizeSlackReplyMarkdown(text, format) {
6782
+ let normalized = applyPluginFormatMarkdown(wrapBareSlackUserIds(text), format).replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "");
6462
6783
  normalized = wrapBareReferences(normalized);
6463
6784
  normalized = ensureBlockSpacing(normalized);
6464
6785
  normalized = bulletListFollowUpParagraphs(normalized);
@@ -6988,19 +7309,25 @@ const vercelSandboxErrors = {
6988
7309
  isCommandStreamInterrupted
6989
7310
  };
6990
7311
  // src/chat/sandbox/vercel/provider.ts
6991
- function credentialOptions() {
6992
- return getVercelSandboxCredentials() ?? {};
6993
- }
6994
- /** Bind one abort signal to every API request made by a Sandbox client. */
6995
- function scopedFetchOptions(signal) {
6996
- if (!signal) return {};
6997
- return { fetch: (input, init) => {
7312
+ /**
7313
+ * Sandbox client options. Since 4.0, a client without `fetch` uses the SDK's
7314
+ * own undici `fetch` and skips process-level `fetch` replacements, such as the
7315
+ * eval proxy. So every request reads `globalThis.fetch` when it starts, and
7316
+ * the scope signal, when there is one, can abort it.
7317
+ */
7318
+ function clientOptions(signal) {
7319
+ const fetch = (input, init) => {
7320
+ if (!signal) return globalThis.fetch(input, init);
6998
7321
  const requestSignal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
6999
7322
  return globalThis.fetch(input, {
7000
7323
  ...init,
7001
7324
  signal: requestSignal ? AbortSignal.any([requestSignal, signal]) : signal
7002
7325
  });
7003
- } };
7326
+ };
7327
+ return {
7328
+ ...getVercelSandboxCredentials(),
7329
+ fetch
7330
+ };
7004
7331
  }
7005
7332
  /** Pin Junior's sandbox contract to one Vercel session without SDK replay. */
7006
7333
  function adaptSession(sandbox, options) {
@@ -7073,8 +7400,7 @@ async function createSandboxSession(input) {
7073
7400
  ...input.networkPolicy ? { networkPolicy: toVercelNetworkPolicy(input.networkPolicy) } : void 0,
7074
7401
  ...input.resources ? { resources: input.resources } : void 0,
7075
7402
  ...input.signal ? { signal: input.signal } : void 0,
7076
- ...credentialOptions(),
7077
- ...scopedFetchOptions(input.scopeSignal)
7403
+ ...clientOptions(input.scopeSignal)
7078
7404
  };
7079
7405
  return adaptSession(await Sandbox.create(input.snapshotId ? {
7080
7406
  ...shared,
@@ -7092,8 +7418,7 @@ async function getSandboxSession(input) {
7092
7418
  return adaptSession(await Sandbox.get({
7093
7419
  name: input.name,
7094
7420
  resume: true,
7095
- ...credentialOptions(),
7096
- ...scopedFetchOptions(input.scopeSignal)
7421
+ ...clientOptions(input.scopeSignal)
7097
7422
  }), input);
7098
7423
  }
7099
7424
  /** Create the named, persistent Sandbox that owns one Workspace snapshot build. */
@@ -7104,7 +7429,7 @@ async function createWorkspaceSnapshotBuilder(input) {
7104
7429
  timeout: input.timeoutMs,
7105
7430
  runtime: input.runtime,
7106
7431
  signal: input.signal,
7107
- ...credentialOptions(),
7432
+ ...clientOptions(),
7108
7433
  ...input.resources ? { resources: input.resources } : void 0
7109
7434
  });
7110
7435
  }
@@ -7114,7 +7439,7 @@ async function getWorkspaceSnapshotBuilder(name, signal) {
7114
7439
  name,
7115
7440
  resume: true,
7116
7441
  signal,
7117
- ...credentialOptions()
7442
+ ...clientOptions()
7118
7443
  });
7119
7444
  return {
7120
7445
  session: () => adaptSession(sandbox),
@@ -7142,7 +7467,7 @@ async function deleteWorkspaceSnapshotBuilders(names) {
7142
7467
  await (await Sandbox.get({
7143
7468
  name,
7144
7469
  resume: false,
7145
- ...credentialOptions()
7470
+ ...clientOptions()
7146
7471
  })).delete();
7147
7472
  } catch (error) {
7148
7473
  if (!vercelSandboxErrors.isMissing(error)) {
@@ -9807,6 +10132,7 @@ var agent_hooks_exports = /* @__PURE__ */ __exportAll({
9807
10132
  getPluginTools: () => getPluginTools,
9808
10133
  getPluginUserPromptContributions: () => getPluginUserPromptContributions,
9809
10134
  getPlugins: () => getPlugins,
10135
+ getStaticPluginToolDefinitions: () => getStaticPluginToolDefinitions,
9810
10136
  setPlugins: () => setPlugins,
9811
10137
  validatePlugins: () => validatePlugins
9812
10138
  });
@@ -10022,13 +10348,25 @@ function getPlugins() {
10022
10348
  return [...registeredPlugins];
10023
10349
  }
10024
10350
  /** Apply plugin Markdown rewrites before destination delivery formatting. */
10025
- function applyPluginFormatMarkdown(text) {
10351
+ function applyPluginFormatMarkdown(text, format = {}) {
10352
+ const resolved = {
10353
+ ...getConfigDefaults(),
10354
+ ...format.configuration
10355
+ };
10356
+ const platform = format.platform ?? "slack";
10357
+ const mention = ({ provider, handle }) => platform === "slack" ? format.mentions?.get(`${provider}:${handle}`.toLowerCase()) : void 0;
10026
10358
  let transformed = text;
10027
10359
  for (const plugin of getPlugins()) {
10028
10360
  const hook = plugin.hooks?.formatMarkdown;
10029
10361
  if (!hook) continue;
10030
10362
  try {
10031
- const next = hook({ text: transformed });
10363
+ const next = hook({
10364
+ config: pluginConfigValues(plugin.manifest.name, resolved),
10365
+ mention,
10366
+ platform,
10367
+ ...format.provider ? { provider: format.provider } : void 0,
10368
+ text: transformed
10369
+ });
10032
10370
  if (typeof next === "string") transformed = next;
10033
10371
  } catch (error) {
10034
10372
  logWarn("plugin.format_markdown.hook.failed", {
@@ -10132,13 +10470,46 @@ async function getPluginUserPromptContributions(args) {
10132
10470
  }
10133
10471
  return contributions;
10134
10472
  }
10473
+ /**
10474
+ * Model-facing definitions of one plugin's tools, by host tool name. They
10475
+ * come from the plugin's `tools()` with no Turn.
10476
+ */
10477
+ function pluginToolDefinitions(plugin) {
10478
+ const hook = plugin.hooks?.tools;
10479
+ if (!hook) return {};
10480
+ const pluginName = plugin.manifest.name;
10481
+ const namespace = pluginToolNamespace(pluginName);
10482
+ const definitions = {};
10483
+ for (const [localName, definition] of Object.entries(hook())) {
10484
+ const execute = definition.execute;
10485
+ definitions[`${namespace}_${localName}`] = {
10486
+ ...definition,
10487
+ ...execute ? { execute: execute.bind(definition) } : void 0,
10488
+ approvalMode: definition.approvalMode ?? "auto",
10489
+ identity: {
10490
+ id: `${pluginName}.${localName}`,
10491
+ name: localName,
10492
+ plugin: pluginName
10493
+ },
10494
+ source: {
10495
+ id: pluginName,
10496
+ description: plugin.manifest.description
10497
+ },
10498
+ exposure: definition.exposure ?? "deferred"
10499
+ };
10500
+ }
10501
+ return definitions;
10502
+ }
10503
+ /** Model-facing definitions of every plugin tool, with no Turn. */
10504
+ function getStaticPluginToolDefinitions() {
10505
+ return Object.assign({}, ...getPlugins().map(pluginToolDefinitions));
10506
+ }
10135
10507
  /** Collect turn-scoped tools exposed by plugins. */
10136
10508
  function getPluginTools(context, sandbox = createSandboxCapability(context.workspace)) {
10137
10509
  const tools = {};
10138
10510
  for (const plugin of getPlugins()) {
10139
10511
  const pluginName = plugin.manifest.name;
10140
- const hook = plugin.hooks?.tools;
10141
- if (!hook) continue;
10512
+ if (!plugin.hooks?.tools) continue;
10142
10513
  const slackToolContext = getSlackToolContext(context);
10143
10514
  const credentialSubject = slackToolContext ? createSlackDirectCredentialSubject({
10144
10515
  channelId: slackToolContext.locationChannelId,
@@ -10195,6 +10566,7 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
10195
10566
  ...automationUrl ? { automationLink: { url: automationUrl } } : void 0,
10196
10567
  ...dashboardConversationUrl ? { conversationLink: { url: dashboardConversationUrl } } : void 0,
10197
10568
  conversationId: context.conversationId,
10569
+ conversations: createPluginConversations(context.conversationId),
10198
10570
  locationId: context.locationId,
10199
10571
  ...slackContext ? { slack: slackContext } : void 0,
10200
10572
  userText: context.userText,
@@ -10220,7 +10592,8 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
10220
10592
  } } : void 0,
10221
10593
  ...resolved?.user ? { userId: resolved.user.id } : void 0
10222
10594
  });
10223
- }
10595
+ },
10596
+ replaceSlackMentions
10224
10597
  },
10225
10598
  workspaces: {
10226
10599
  async active() {
@@ -10273,40 +10646,31 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
10273
10646
  source: context.source
10274
10647
  };
10275
10648
  }
10276
- const pluginTools = hook(pluginContext);
10649
+ const definitions = pluginToolDefinitions(plugin);
10277
10650
  const namespace = pluginToolNamespace(pluginName);
10278
- for (const [localName, tool] of Object.entries(pluginTools)) {
10279
- const name = `${namespace}_${localName}`;
10651
+ const disabled = plugin.hooks?.disabledTools?.(pluginContext) ?? {};
10652
+ for (const localName of Object.keys(disabled)) if (!definitions[`${namespace}_${localName}`]) throw new Error(`Plugin "${pluginName}" disabled unknown tool "${localName}"`);
10653
+ for (const [name, definition] of Object.entries(definitions)) {
10654
+ const localName = definition.identity.name;
10280
10655
  if (tools[name]) throw new Error(`Duplicate plugin tool "${name}" from plugin "${pluginName}"`);
10281
- const definition = tool;
10282
10656
  const missingAnnotationKeys = missingToolAnnotationKeys(definition.annotations);
10283
10657
  if (missingAnnotationKeys.length > 0) logWarn("plugin.tool_annotations.missing", {
10284
10658
  "app.plugin.name": pluginName,
10285
10659
  "gen_ai.tool.name": localName,
10286
10660
  "app.tool.missing_annotations": missingAnnotationKeys.join(",")
10287
10661
  });
10288
- definition.approvalMode ??= "auto";
10289
- definition.identity = {
10290
- id: `${pluginName}.${localName}`,
10291
- name: localName,
10292
- plugin: pluginName
10293
- };
10294
- definition.source = {
10295
- id: pluginName,
10296
- description: plugin.manifest.description
10297
- };
10298
- definition.exposure ??= "deferred";
10299
10662
  const execute = definition.execute;
10300
- if (execute) {
10301
- const wrapped = Object.create(definition);
10302
- wrapped.execute = async (input, options) => annotateToolResult(context.conversationId, pluginName, await recordToolReply({
10663
+ const disabledReason = disabled[localName];
10664
+ tools[name] = {
10665
+ ...definition,
10666
+ ...disabledReason ? { disabledReason } : void 0,
10667
+ ...execute ? { execute: async (input, options) => annotateToolResult(context.conversationId, pluginName, await recordToolReply({
10303
10668
  conversationId: context.conversationId,
10304
10669
  plugin: pluginName,
10305
- result: await execute.call(definition, input, options),
10670
+ result: await execute(input, options, pluginContext),
10306
10671
  toolCallId: options.toolCallId
10307
- }));
10308
- tools[name] = wrapped;
10309
- } else tools[name] = definition;
10672
+ })) } : void 0
10673
+ };
10310
10674
  }
10311
10675
  }
10312
10676
  return tools;
@@ -10946,32 +11310,6 @@ var ProviderCredentialRouter = class {
10946
11310
  });
10947
11311
  }
10948
11312
  };
10949
- // src/chat/conversations/legacy-web-actor-id.ts
10950
- /**
10951
- * Web Actor ids that Junior stored before web Actors used the User id.
10952
- *
10953
- * Mailbox input, web authorizations, and OAuth credentials saved before that
10954
- * deploy still carry `dashboard:` and the first 24 hex characters of
10955
- * sha256(email).
10956
- *
10957
- * TODO(dcramer): Delete with its callers after that input and those
10958
- * authorizations expire and no `dashboard:` credential keys remain.
10959
- */
10960
- const USER_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
10961
- /** Return the legacy web Actor id for one email. */
10962
- function legacyWebActorUserId(email) {
10963
- return `dashboard:${createHash("sha256").update(email.trim().toLowerCase()).digest("hex").slice(0, 24)}`;
10964
- }
10965
- /** Return every web Actor id that names this User, the User id first. */
10966
- function webActorUserIds(user) {
10967
- return [user.id, legacyWebActorUserId(user.email)];
10968
- }
10969
- /** Return the legacy web Actor id of a User id, when the User exists. */
10970
- async function findLegacyWebActorUserId(userId) {
10971
- if (!USER_ID_PATTERN.test(userId)) return void 0;
10972
- const rows = await getDb().select({ email: juniorUsers.primaryEmailNormalized }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1);
10973
- return rows[0] ? legacyWebActorUserId(rows[0].email) : void 0;
10974
- }
10975
11313
  // src/chat/credentials/legacy-web-tokens.ts
10976
11314
  /**
10977
11315
  * Move OAuth tokens saved under a legacy web Actor id to the User id.
@@ -11167,6 +11505,11 @@ function assertLeaseTransformsOwnedByProvider(provider, lease) {
11167
11505
  * use that default for one request.
11168
11506
  */
11169
11507
  async function selectSandboxEgressGrant(input) {
11508
+ if (input.userOAuthOnly) {
11509
+ const manifest = pluginCatalogRuntime.getDefinition(input.provider)?.manifest;
11510
+ if (!manifest?.credentials || !manifest.oauth) throw new Error(`Plugin "${input.provider}" has no user OAuth for user-only egress`);
11511
+ return defaultGrantForProvider(input);
11512
+ }
11170
11513
  if (!hasEgressCredentialHooks(input.provider)) return defaultGrantForProvider(input);
11171
11514
  const pluginGrant = await selectPluginGrant({
11172
11515
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
@@ -11593,6 +11936,7 @@ async function executeCredentialedEgressRequest(input) {
11593
11936
  ...isGitReceivePack(request.method, upstreamUrl) ? { gitPush: readGitPush(body) } : void 0,
11594
11937
  ...isGraphqlPost(request.method, upstreamUrl) ? { graphql: await readGraphqlRequest(body) } : void 0,
11595
11938
  ...operation ? { operation } : void 0,
11939
+ ...input.userOAuthOnly ? { userOAuthOnly: true } : void 0,
11596
11940
  provider,
11597
11941
  method: request.method,
11598
11942
  upstreamUrl
@@ -14867,7 +15211,8 @@ function createPluginEgress(deps) {
14867
15211
  operation,
14868
15212
  provider: input.provider,
14869
15213
  request: input.request,
14870
- upstreamUrl
15214
+ upstreamUrl,
15215
+ ...deps.userOAuthOnly ? { userOAuthOnly: true } : void 0
14871
15216
  });
14872
15217
  } };
14873
15218
  }
@@ -14879,11 +15224,6 @@ const CONVERSATION_TITLE_SYSTEM_ACTOR = {
14879
15224
  platform: "system",
14880
15225
  name: "conversation-title"
14881
15226
  };
14882
- /** Pick one plugin's string config values and drop the plugin name prefix. */
14883
- function pluginConfig(pluginName, configuration) {
14884
- const prefix = `${pluginName}.`;
14885
- return Object.fromEntries(Object.entries(configuration).flatMap(([key, value]) => key.startsWith(prefix) && typeof value === "string" ? [[key.slice(prefix.length), value]] : []));
14886
- }
14887
15227
  /**
14888
15228
  * Collect plugin facts, such as linked issue titles, for one new
14889
15229
  * Conversation title. `configuration` holds config values by full key.
@@ -14904,7 +15244,7 @@ async function getPluginConversationTitleContext(args) {
14904
15244
  if (!hook) return [];
14905
15245
  try {
14906
15246
  const lines = await Promise.race([hook({
14907
- config: pluginConfig(plugin.manifest.name, args.configuration),
15247
+ config: pluginConfigValues(plugin.manifest.name, args.configuration),
14908
15248
  db: getDb(),
14909
15249
  egress,
14910
15250
  log: createPluginLogger(plugin.manifest.name),
@@ -15992,4 +16332,4 @@ async function recordGuardianActionReviewed(args) {
15992
16332
  createdAtMs: Date.now()
15993
16333
  }]);
15994
16334
  }
15995
- export { loadTurnCheckpoint as $, isToolInputError as $a, create as $i, webActorUserIds as $n, runWithSlackInstallationToken as $o, activeParticipantUserIds as $r, TurnSliceLimitExceededError as $t, latestConversationMessageSeq as A, slackEntitySchema as Aa, getDashboardObjectIconLink as Ai, isStandaloneRuntimeContextMessage as An, readConversationEventPageAfter as Ao, dismissOpenReviewItems as Ar, getConversationWorkStates as At, getAgentContextInputLimitTokens as B, clearSandboxEgressSignals as Ba, renderToolResultNudge as Bi, SCRIPT_TOOLS_SECTION_TAG as Bn, readAttachmentVisionSummary as Bo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Br, recordConversationRetry as Bt, settleConversationTitleWork as C, openSlackModal as Ca, verifyEventAutomationCredentialSubject as Ci, getTerminalAssistantMessages as Cn, conversationPinnedForUser as Co, saveNotificationSchedule as Cr, getConfigDefaults as Cs, countPendingConversationMessages as Ct, estimateConversationMessagesTokens as D, unfurlSlackLinks as Da, JUNIOR_THREAD_STATE_TTL_MS as Di, instructionTextForProjection as Dn, readConversationBriefThrough as Do, REVIEW_ITEM_REPLIED_REASON as Dr, dropPendingMessages as Dt, buildConversationContext as E, removeReactionFromMessage as Ea, verifyTimerWatchCredentialSubject as Ei, hasTurnInput as En, createPluginConversationEvents as Eo, projectConversationMessages as Er, drainConversationMailbox as Et, turnHasReply as F, wrapSandboxSetupError as Fa, isDashboardLink as Fi, retainRuntimeTurnContext as Fn, FORK_INSTRUCTIONS as Fo, listWaitingConversations as Fr, listActiveConversationIds as Ft, AuthPausePersistenceError as G, sandboxEgressSignalsResponseSchema as Ga, listWorkspaces as Gi, readParentAgentTask as Gn, downloadPrivateSlackFile as Go, isOnlyAssignee as Gr, startConversationWork as Gt, PluginCredentialFailureError as H, consumeSandboxEgressPermissionDeniedSignal as Ha, deleteWorkspace as Hi, TURN_CONTEXT_TAG as Hn, recordSlackAttachment as Ho, canAgentChangeReviewItem as Hr, releaseInboundMessage as Ht, upsertConversationMessage as I, WorkspaceSnapshotNotReadyError as Ia, parseDashboardConversationLink as Ii, stripRuntimeTurnContext as In, loadForkHistory as Io, reviewItemsNeedingUserVersionQuery as Ir, markConversationWorkEnqueued as It, abandonReplacedPendingAuth as J, normalizeSandboxEgressTracePropagationDomains as Ja, WorkspaceValidationError as Ji, renderUntrustedTag as Jn, getSlackClient as Jo, requireReviewItemLinks as Jr, takeDeferredConversationMove as Jt, AuthorizationFlowDisabledError as K, buildSandboxEgressNetworkPolicy as Ka, listWorkspacesByRepository as Ki, renderChildTag as Kn, getFilePermalink as Ko, readReviewItemAgentScope as Kr, steerWebPendingMessages as Kt, calculateContextCompactionTargetTokens as L, getWorkspaceSnapshotNotReadyError as La, parseDashboardPersonLink as Li, trimTrailingAssistantMessages as Ln, notInheritedByForkChild as Lo, searchReviewItems as Lr, moveIdleConversationDestination as Lt, normalizeConversationText as M, isAbortError as Ma, getDashboardReviewItemLink as Mi, isToolResultMessage as Mn, readConversationLastEventSeq as Mo, getReviewItem as Mr, hasRunnableConversationWork as Mt, recordDeliveredAssistantMessage as N, isAlreadyExistsError as Na, getDashboardSettingsLink as Ni, latestTurnContextSection as Nn, readConversationMessageEventSeq as No, insertReviewItem as Nr, isFinalAttempt as Nt, getConversationMessageSlackTs as O, updateSlackMessage as Oa, getDashboardConversationLink as Oi, isAssistantMessage as On, readLatestConversationBrief as Oo, closeReviewItem as Or, getConversation as Ot, trimConversationMessages as P, throwSandboxOperationError as Pa, getDashboardTaskLink as Pi, normalizeToolNameFromResult as Pn, buildSentryConversationUrl as Po, listReplyActionItems as Pr, isInvalidConversationRecordError as Pt, continuableMessages as Q, ToolInputError as Qa, setWorkspaceSnapshotBuild as Qi, findLegacyWebActorUserId as Qn, normalizeSlackConversationId as Qo, EVERYONE_ASSIGNEE as Qr, TurnBudgetExceededError as Qt, getAgentBackgroundCompactionMarkTokens as R, isWorkspaceSnapshotNotReadyError as Ra, setDashboardConversationLinkOptions as Ri, CAPABILITY_SECTION_TAG as Rn, getSlackFileId as Ro, takeReviewItem as Rr, pruneActiveConversation as Rt, resolveConversationTitle as S, openSlackDirectMessage as Sa, bindSlackDirectCredentialSubject as Si, getPiMessageRole as Sn, conversationIsNotUnsubscribedRoot as So, readNotificationSchedule as Sr, projectConversationEvents$1 as Ss, completeConversationWork as St, resolveTaskTitle as T, postSlackMessage as Ta, verifySlackDirectCredentialSubject as Ti, hasRuntimeTurnContext as Tn, viewerMarksFromParticipant as To, isPausedBySlack as Tr, deferConversationMove as Tt, createPluginAuthOrchestration as U, createSandboxEgressCredentialToken as Ua, getWorkspace as Ui, escapeClosingTags as Un, slackAttachmentsVersionQuery as Uo, canReadReviewItem as Ur, requestAnotherSlice as Ut, createPluginEgress as V, consumeSandboxEgressAuthRequiredSignal as Va, createWorkspace as Vi, SESSION_CONTEXT_SECTION_TAG as Vn, readSlackAttachmentSource as Vo, canActOnReviewItem as Vr, releaseConversationWork as Vt, authorizationId as W, parseSandboxEgressCredentialToken as Wa, getWorkspaceByName as Wi, escapeTagText as Wn, SlackActionError as Wo, canUserReadReviewItem as Wr, requestConversationWork as Wt, clearPendingAuth as X, tryWorkspaceRepoCheckoutPath as Xa, loadSnapshotsForProfile as Xi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Xn, isDmChannel as Xo, reviewItemReaderForUser as Xr, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Xt, canReusePendingAuthLink as Y, SANDBOX_RUNTIME as Ya, invalidateReadySnapshot as Yi, tagJson as Yn, isConversationScopedChannel as Yo, reviewItemNeedsSomeone as Yr, readInboundMessageSender as Yt, getConversationPendingAuth as Z, workspaceRepoCheckoutPath as Za, setWorkspaceSnapshot as Zi, createUserTokenStore as Zn, isSlackRequestTimeout as Zo, reviewItemReaderForUserInConversation as Zr, TURN_LIMIT_WRAP_UP_MESSAGE as Zt, appendConversationMessages as _, slackMentionedUserIds as _a, getWatch as _i, CODE_MODE_CALL_STATUS_TEXT as _n, canAddConversationMessages as _o, readWebPushConfig as _r, createPluginCache as _s, checkInConversationWork as _t, loadProjection as a, proxyVercelSandboxEgressRequest as aa, getSlackToolContext as ai, isAnswerToolName as an, SANDBOX_REPOS_ROOT as ao, getPluginApiRoutes as ar, AttachmentSourceUnavailableError as as, failTurnRecord as at, persistConversationMessages as b, deleteSlackMessage as ba, bindEventAutomationCredentialSubject as bi, persistWithRetry as bn, conversationHasParticipantUser as bo, deletePushSubscription as br, historyItemFromPiMessage as bs, clearExpiredConversationLease as bt, recordAgentsInstructionsUpdated as c, parseOAuthStatePayload as ca, RESOURCE_WATCH_TOOL_SOURCE as ci, replyTextSchema as cn, sandboxSkillDir as co, getPluginSystemPromptContributions as cr, createPluginAnnotations as cs, listTurnSummaries as ct, recordAuthorizationCompleted as d, SLACK_USER_MENTION_RE as da, cancelWatch as di, sanitizeAssistantText as dn, buildCommandScript as do, getPlugins as dr, defaultTimezone as ds, CONVERSATION_WORK_STALE_ENQUEUE_MS as dt, hash as ea, automationCreatorUserId as ei, TurnToolCallLimitExceededError as en, PluginToolDeniedError as eo, getOAuthAccountProviders as er, streamPrivateSlackFile as es, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, escapeSlackMrkdwnText as fa, collectEventMatchKeys as fi, NO_REPLY_TOOL_NAME as fn, buildNonInteractiveShellScript as fo, setPlugins as fr, resolveUserTimezone as fs, ackMessages as ft, recordToolExecutionStarted as g, slackMention as ga, findMatchingWatches as gi, CODEMODE_TOOL_NAME as gn, canAccessConversation as go, setBriefsConfig as gr, credentialAuditSource as gs, cancelHumanFacingPendingMessages as gt, recordSubscribedReplyRoute as h, normalizeSlackStatusText as ha, deliverWatch as hi, readNoReply as hn, createPluginLogger as ho, registration_exports as hr, credentialAuditAttributes as hs, beginConversationResume as ht, loadConversationProjection as i, isVercelSandboxEgressRequest as ia, resolveChannelCapabilities as ii, REPLY_TOOL_NAME as in, SANDBOX_DATA_ROOT as io, createPluginHookRunner as ir, runWithWorkspaceTeamId as is, completeTurnRecord as it, markConversationMessage as j, slackExternalRefIdSchema as ja, getDashboardPersonLink as ji, isToolResultError as jn, readConversationEventPageAround as jo, getOpenReviewItemByDedupeKey as jr, hasConversationStop as jt, isHumanConversationMessage as k, uploadFilesToConversation as ka, getDashboardLinkFilter as ki, isContinuablePiBoundary as kn, readConversationEventPage as ko, countReviewItemsNeedingUser as kr, getConversationWorkState as kt, recordAttachmentsDelivered as l, resolveBaseUrl as la, STOP_WATCHING_TOOL_NAME as li, decideReply as ln, sandboxSkillFile as lo, getPluginTools as lr, listConversationAnnotations as ls, recordTurnSummary as lt, recordMcpProviderConnected as m, normalizeSlackReplyMarkdown as ma, createWatch as mi, isLegacyNoReplyMarker as mn, createPluginModelCostRecorder as mo, coreTaskRegistrations as mr, lookupSlackUserNames as ms, appendInboundMessage as mt, commitMessages as n, ensureDockerDaemon as na, resolveAssignees as ni, createTurnLimitGate as nn, createPluginModel as no, agent_hooks_exports as nr, sleep$2 as ns, saveTurnCheckpoint as nt, loadTurnProjection as o, deliverOAuthAuthorization as oa, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as oi, readTurnAnswer as on, SANDBOX_SKILLS_ROOT as oo, getPluginRoutes as or, resolveRootVisibility as os, getStoredTurnFields as ot, recordGuardianActionReviewed as p, formatSlackLink as pa, createTimerWatch as pi, findLegacyNoReplyMarker as pn, runNonInteractiveCommand as po, validatePlugins as pr, lookupSlackUser as ps, appendExclusiveInboundMessage as pt, AuthorizationPauseError as q, resolveSandboxCommandEnvironment as qa, updateWorkspace as qi, renderTag as qn, getHeaderString as qo, requireReviewItemAssignees as qr, stopConversationWork as qt, loadConnectedMcpProviders as r, getSandboxProvider as ra, createCodeChangePublisher as ri, isTurnExecutionLimitExceededError as rn, SANDBOX_COMMAND_PATH as ro, createPluginEventPublisher as rr, getWorkspaceTeamId as rs, abandonTurnRecord as rt, openConversationProjection as s, formatProviderLabel as sa, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as si, remindMissingAnswer as sn, SANDBOX_WORKSPACE_ROOT as so, getPluginSlackConversationLink as sr, saveObjectAnnotations as ss, getTurnRecord as st, commitAcceptedReply as t, isStale as ta, resolveAssignee as ti, buildTurnErrorResponse as tn, createPluginEmbedder as to, resolvePluginOAuthAccount as tr, withSlackRetries as ts, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, startOAuthFlow as ua, cancelSubscriptions as ui, getAssistantReplyText as un, sandboxSkillPathResolution as uo, getPluginUserPromptContributions as ur, listConversationAnnotationsById as us, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as ut, hydrateConversationMessages as v, truncateStatusText as va, listWatches as vi, REPORT_BLOCKED_TOOL_NAME as vn, createConversationAccessReader as vo, sendPushNotificationToUser as vr, createDurableLocationConfigurationService as vs, claimInboundMessage as vt, fallbackShortTitle as w, postSlackEphemeralMessage as wa, verifyScheduledAutomationCredentialSubject as wi, getUserMessageInstructionText as wn, conversationViewerMarks as wo, savePushSubscription as wr, setConfigDefaults as ws, deadLetterAttempt as wt, toStoredConversationMessage as x, getSlackMessagePermalink as xa, bindScheduledAutomationCredentialSubject as xi, extractAssistantText as xn, conversationIsMemberRoot as xo, listPushSubscriptions as xr, piMessageFromHistoryItem as xs, completeConversationStop as xt, persistConversationMessageWindow as y, addReactionToMessage as ya, takeDueTimerWatches as yi, readBlockedReport as yn, readConversationAccessFromSql as yo, resolveNotificationTimezone as yr, configValueSchema as ys, clearConsumedConversationWake as yt, getAgentContextCompactionTriggerTokens as z, workspaceSnapshotNotReadyUserMessage as za, createPluginState as zi, REQUEST_CONTEXT_SECTION_TAG as zn, matchSlackAttachments as zo, updateReviewItemContent as zr, recordAttemptFailure as zt };
16335
+ export { loadTurnCheckpoint as $, workspaceRepoCheckoutPath as $a, setWorkspaceSnapshotBuild as $i, resolvePluginOAuthAccount as $n, isSlackRequestTimeout as $o, EVERYONE_ASSIGNEE as $r, TurnSliceLimitExceededError as $t, latestConversationMessageSeq as A, updateSlackMessage as Aa, getDashboardLinkFilter as Ai, isStandaloneRuntimeContextMessage as An, readLatestConversationBrief as Ao, countReviewItemsNeedingUser as Ar, getConversationWorkStates as At, getAgentContextInputLimitTokens as B, isWorkspaceSnapshotNotReadyError as Ba, createPluginState as Bi, SCRIPT_TOOLS_SECTION_TAG as Bn, getSlackFileId as Bo, updateReviewItemContent as Br, recordConversationRetry as Bt, settleConversationTitleWork as C, getSlackMessagePermalink as Ca, bindSlackDirectCredentialSubject as Ci, getTerminalAssistantMessages as Cn, conversationIsMemberRoot as Co, saveNotificationSchedule as Cr, configValueSchema as Cs, countPendingConversationMessages as Ct, estimateConversationMessagesTokens as D, postSlackMessage as Da, verifyTimerWatchCredentialSubject as Di, instructionTextForProjection as Dn, viewerMarksFromParticipant as Do, createPluginReviewItems as Dr, getConfigDefaults as Ds, dropPendingMessages as Dt, buildConversationContext as E, postSlackEphemeralMessage as Ea, verifySlackDirectCredentialSubject as Ei, hasTurnInput as En, conversationViewerMarks as Eo, projectConversationMessages as Er, projectConversationEvents$1 as Es, drainConversationMailbox as Et, turnHasReply as F, isAlreadyExistsError as Fa, getDashboardTaskLink as Fi, retainRuntimeTurnContext as Fn, readConversationMessageEventSeq as Fo, listReplyActionItems as Fr, listActiveConversationIds as Ft, AuthPausePersistenceError as G, createSandboxEgressCredentialToken as Ga, getWorkspaceByName as Gi, readParentAgentTask as Gn, slackAttachmentsVersionQuery as Go, canUserReadReviewItem as Gr, startConversationWork as Gt, PluginCredentialFailureError as H, clearSandboxEgressSignals as Ha, createWorkspace as Hi, TURN_CONTEXT_TAG as Hn, readAttachmentVisionSummary as Ho, canActOnReviewItem as Hr, releaseInboundMessage as Ht, upsertConversationMessage as I, throwSandboxOperationError as Ia, isDashboardLink as Ii, stripRuntimeTurnContext as In, buildSentryConversationUrl as Io, listWaitingConversations as Ir, markConversationWorkEnqueued as It, abandonReplacedPendingAuth as J, buildSandboxEgressNetworkPolicy as Ja, updateWorkspace as Ji, renderUntrustedTag as Jn, getFilePermalink as Jo, requireReviewItemAssignees as Jr, takeDeferredConversationMove as Jt, AuthorizationFlowDisabledError as K, parseSandboxEgressCredentialToken as Ka, listWorkspaces as Ki, renderChildTag as Kn, SlackActionError as Ko, isOnlyAssignee as Kr, steerWebPendingMessages as Kt, calculateContextCompactionTargetTokens as L, wrapSandboxSetupError as La, parseDashboardConversationLink as Li, trimTrailingAssistantMessages as Ln, FORK_INSTRUCTIONS as Lo, reviewItemsNeedingUserVersionQuery as Lr, moveIdleConversationDestination as Lt, normalizeConversationText as M, slackEntitySchema as Ma, getDashboardPersonLink as Mi, isToolResultMessage as Mn, readConversationEventPageAfter as Mo, getOpenReviewItemByDedupeKey as Mr, hasRunnableConversationWork as Mt, recordDeliveredAssistantMessage as N, slackExternalRefIdSchema as Na, getDashboardReviewItemLink as Ni, latestTurnContextSection as Nn, readConversationEventPageAround as No, getReviewItem as Nr, isFinalAttempt as Nt, getConversationMessageSlackTs as O, removeReactionFromMessage as Oa, JUNIOR_THREAD_STATE_TTL_MS as Oi, isAssistantMessage as On, createPluginConversationEvents as Oo, REVIEW_ITEM_REPLIED_REASON as Or, setConfigDefaults as Os, getConversation as Ot, trimConversationMessages as P, isAbortError as Pa, getDashboardSettingsLink as Pi, normalizeToolNameFromResult as Pn, readConversationLastEventSeq as Po, insertReviewItem as Pr, isInvalidConversationRecordError as Pt, continuableMessages as Q, tryWorkspaceRepoCheckoutPath as Qa, setWorkspaceSnapshot as Qi, getOAuthAccountProviders as Qn, isDmChannel as Qo, reviewItemReaderForUserInConversation as Qr, TurnBudgetExceededError as Qt, getAgentBackgroundCompactionMarkTokens as R, WorkspaceSnapshotNotReadyError as Ra, parseDashboardPersonLink as Ri, CAPABILITY_SECTION_TAG as Rn, loadForkHistory as Ro, searchReviewItems as Rr, pruneActiveConversation as Rt, resolveConversationTitle as S, deleteSlackMessage as Sa, bindScheduledAutomationCredentialSubject as Si, getPiMessageRole as Sn, conversationHasParticipantUser as So, readNotificationSchedule as Sr, createDurableLocationConfigurationService as Ss, completeConversationWork as St, resolveTaskTitle as T, openSlackModal as Ta, verifyScheduledAutomationCredentialSubject as Ti, hasRuntimeTurnContext as Tn, conversationPinnedForUser as To, isPausedBySlack as Tr, piMessageFromHistoryItem as Ts, deferConversationMove as Tt, createPluginAuthOrchestration as U, consumeSandboxEgressAuthRequiredSignal as Ua, deleteWorkspace as Ui, escapeClosingTags as Un, readSlackAttachmentSource as Uo, canAgentChangeReviewItem as Ur, requestAnotherSlice as Ut, createPluginEgress as V, workspaceSnapshotNotReadyUserMessage as Va, renderToolResultNudge as Vi, SESSION_CONTEXT_SECTION_TAG as Vn, matchSlackAttachments as Vo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Vr, releaseConversationWork as Vt, authorizationId as W, consumeSandboxEgressPermissionDeniedSignal as Wa, getWorkspace as Wi, escapeTagText as Wn, recordSlackAttachment as Wo, canReadReviewItem as Wr, requestConversationWork as Wt, clearPendingAuth as X, normalizeSandboxEgressTracePropagationDomains as Xa, invalidateReadySnapshot as Xi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Xn, getSlackClient as Xo, reviewItemNeedsSomeone as Xr, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Xt, canReusePendingAuthLink as Y, resolveSandboxCommandEnvironment as Ya, WorkspaceValidationError as Yi, tagJson as Yn, getHeaderString as Yo, requireReviewItemLinks as Yr, readInboundMessageSender as Yt, getConversationPendingAuth as Z, SANDBOX_RUNTIME as Za, loadSnapshotsForProfile as Zi, createUserTokenStore as Zn, isConversationScopedChannel as Zo, reviewItemReaderForUser as Zr, TURN_LIMIT_WRAP_UP_MESSAGE as Zt, appendConversationMessages as _, slackMention as _a, findMatchingWatches as _i, CODE_MODE_CALL_STATUS_TEXT as _n, createPluginLogger as _o, readWebPushConfig as _r, lookupSlackUser as _s, checkInConversationWork as _t, loadProjection as a, isVercelSandboxEgressRequest as aa, resolveChannelCapabilities as ai, isAnswerToolName as an, SANDBOX_COMMAND_PATH as ao, getPluginRoutes as ar, getWorkspaceTeamId as as, failTurnRecord as at, persistConversationMessages as b, truncateStatusText as ba, takeDueTimerWatches as bi, persistWithRetry as bn, createConversationAccessReader as bo, deletePushSubscription as br, credentialAuditSource as bs, clearExpiredConversationLease as bt, recordAgentsInstructionsUpdated as c, formatProviderLabel as ca, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as ci, replyTextSchema as cn, SANDBOX_SKILLS_ROOT as co, getPluginTools as cr, resolveRootVisibility as cs, listTurnSummaries as ct, recordAuthorizationCompleted as d, startOAuthFlow as da, cancelSubscriptions as di, sanitizeAssistantText as dn, sandboxSkillFile as do, getStaticPluginToolDefinitions as dr, saveObjectAnnotations as ds, CONVERSATION_WORK_STALE_ENQUEUE_MS as dt, create as ea, activeParticipantUserIds as ei, TurnToolCallLimitExceededError as en, ToolInputError as eo, agent_hooks_exports as er, normalizeSlackConversationId as es, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, SLACK_USER_MENTION_RE as fa, cancelWatch as fi, NO_REPLY_TOOL_NAME as fn, sandboxSkillPathResolution as fo, setPlugins as fr, createPluginAnnotations as fs, ackMessages as ft, recordToolExecutionStarted as g, normalizeSlackStatusText as ga, deliverWatch as gi, CODEMODE_TOOL_NAME as gn, createPluginModelCostRecorder as go, setBriefsConfig as gr, resolveUserTimezone as gs, cancelHumanFacingPendingMessages as gt, recordSubscribedReplyRoute as h, normalizeSlackReplyMarkdown as ha, createWatch as hi, readNoReply as hn, runNonInteractiveCommand as ho, registration_exports as hr, defaultTimezone as hs, beginConversationResume as ht, loadConversationProjection as i, getSandboxProvider as ia, createCodeChangePublisher as ii, REPLY_TOOL_NAME as in, createPluginModel as io, getPluginApiRoutes as ir, sleep$2 as is, completeTurnRecord as it, markConversationMessage as j, uploadFilesToConversation as ja, getDashboardObjectIconLink as ji, isToolResultError as jn, readConversationEventPage as jo, dismissOpenReviewItems as jr, hasConversationStop as jt, isHumanConversationMessage as k, unfurlSlackLinks as ka, getDashboardConversationLink as ki, isContinuablePiBoundary as kn, readConversationBriefThrough as ko, closeReviewItem as kr, getConversationWorkState as kt, recordAttachmentsDelivered as l, parseOAuthStatePayload as la, RESOURCE_WATCH_TOOL_SOURCE as li, decideReply as ln, SANDBOX_WORKSPACE_ROOT as lo, getPluginUserPromptContributions as lr, searchConversations as ls, recordTurnSummary as lt, recordMcpProviderConnected as m, formatSlackLink as ma, createTimerWatch as mi, isLegacyNoReplyMarker as mn, buildNonInteractiveShellScript as mo, coreTaskRegistrations as mr, listConversationAnnotationsById as ms, appendInboundMessage as mt, commitMessages as n, isStale as na, resolveAssignee as ni, createTurnLimitGate as nn, PluginToolDeniedError as no, createPluginEventPublisher as nr, streamPrivateSlackFile as ns, saveTurnCheckpoint as nt, loadTurnProjection as o, proxyVercelSandboxEgressRequest as oa, getSlackToolContext as oi, readTurnAnswer as on, SANDBOX_DATA_ROOT as oo, getPluginSlackConversationLink as or, runWithWorkspaceTeamId as os, getStoredTurnFields as ot, recordGuardianActionReviewed as p, escapeSlackMrkdwnText as pa, collectEventMatchKeys as pi, findLegacyNoReplyMarker as pn, buildCommandScript as po, validatePlugins as pr, listConversationAnnotations as ps, appendExclusiveInboundMessage as pt, AuthorizationPauseError as q, sandboxEgressSignalsResponseSchema as qa, listWorkspacesByRepository as qi, renderTag as qn, downloadPrivateSlackFile as qo, readReviewItemAgentScope as qr, stopConversationWork as qt, loadConnectedMcpProviders as r, ensureDockerDaemon as ra, resolveAssignees as ri, isTurnExecutionLimitExceededError as rn, createPluginEmbedder as ro, createPluginHookRunner as rr, withSlackRetries as rs, abandonTurnRecord as rt, openConversationProjection as s, deliverOAuthAuthorization as sa, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as si, remindMissingAnswer as sn, SANDBOX_REPOS_ROOT as so, getPluginSystemPromptContributions as sr, AttachmentSourceUnavailableError as ss, getTurnRecord as st, commitAcceptedReply as t, hash as ta, automationCreatorUserId as ti, buildTurnErrorResponse as tn, isToolInputError as to, applyPluginFormatMarkdown as tr, runWithSlackInstallationToken as ts, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, resolveBaseUrl as ua, STOP_WATCHING_TOOL_NAME as ui, getAssistantReplyText as un, sandboxSkillDir as uo, getPlugins as ur, createConversationEmbedder as us, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as ut, hydrateConversationMessages as v, slackMentionedUserIds as va, getWatch as vi, REPORT_BLOCKED_TOOL_NAME as vn, canAccessConversation as vo, sendPushNotificationToUser as vr, lookupSlackUserNames as vs, claimInboundMessage as vt, fallbackShortTitle as w, openSlackDirectMessage as wa, verifyEventAutomationCredentialSubject as wi, getUserMessageInstructionText as wn, conversationIsNotUnsubscribedRoot as wo, savePushSubscription as wr, historyItemFromPiMessage as ws, deadLetterAttempt as wt, toStoredConversationMessage as x, addReactionToMessage as xa, bindEventAutomationCredentialSubject as xi, extractAssistantText as xn, readConversationAccessFromSql as xo, listPushSubscriptions as xr, createPluginCache as xs, completeConversationStop as xt, persistConversationMessageWindow as y, wrapBareSlackUserIds as ya, listWatches as yi, readBlockedReport as yn, canAddConversationMessages as yo, resolveNotificationTimezone as yr, credentialAuditAttributes as ys, clearConsumedConversationWake as yt, getAgentContextCompactionTriggerTokens as z, getWorkspaceSnapshotNotReadyError as za, setDashboardConversationLinkOptions as zi, REQUEST_CONTEXT_SECTION_TAG as zn, notInheritedByForkChild as zo, takeReviewItem as zr, recordAttemptFailure as zt };