@sentry/junior 0.299.0 → 0.301.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 (78) hide show
  1. package/dist/{adapter-AgCNqqsG.js → adapter-CNjGEJO9.js} +5 -4
  2. package/dist/{admin-1VwEXztm.js → admin-CRJHvCGg.js} +2 -2
  3. package/dist/{agent-runner-Ciet8_nn.js → agent-runner-H4YhvNBj.js} +514 -270
  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 +327 -61
  8. package/dist/{app--ky-Eu33.d.ts → app-HDZglaIu.d.ts} +14 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +60 -220
  11. package/dist/{automation-M3RFJUBf.js → automation-Cva5ZOwW.js} +2 -2
  12. package/dist/{background-compaction-queue-CnimvRdk.js → background-compaction-queue-CNrZ3QcU.js} +8 -4
  13. package/dist/{briefs-CwzvgdCa.js → briefs-x6Mzwxmg.js} +3 -3
  14. package/dist/{catalog-runtime-DaBaHY7u.js → catalog-runtime-BEY6EGRi.js} +1 -1
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +5 -5
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +4 -4
  22. package/dist/{config-CAXIpWQb.js → config-CmjhyqgB.js} +39 -8
  23. package/dist/{connections-Dy0hPdUq.js → connections-CfIRm0xv.js} +6 -6
  24. package/dist/{continue-in-slack-DIOjFj76.js → continue-in-slack-DPoABVkB.js} +6 -6
  25. package/dist/{conversation-fCWD9Az3.js → conversation-BNXfq6Lb.js} +30 -9
  26. package/dist/{conversation-feed-BPK8vkkZ.js → conversation-feed-CfpyFMHP.js} +23 -2
  27. package/dist/{conversation-privacy-DUgtRkf8.js → conversation-privacy-0CM0V2qK.js} +1 -1
  28. package/dist/{conversation-turn-DkJB6yMF.js → conversation-turn-C0sxyvS-.js} +17 -17
  29. package/dist/{credential-sync-RX24Y8aY.js → credential-sync-tEMKZ_8M.js} +15 -15
  30. package/dist/{db-B07FtU9g.d.ts → db-BdUHQhrC.d.ts} +1 -1
  31. package/dist/{db-COYOGzYS.js → db-Czra10QW.js} +13 -8
  32. package/dist/{executor-BWmAgSyi.js → executor-D_023K0H.js} +9 -4
  33. package/dist/instrumentation.js +14 -5
  34. package/dist/{lineage-D-5jm_oj.js → lineage-DmMIE0VL.js} +2 -2
  35. package/dist/{logging-DPLEa8Bn.js → logging-DcjLDDqi.js} +1 -1
  36. package/dist/{message-BIHR1yRk.js → message-C0JY9RJP.js} +8 -8
  37. package/dist/{model-input-BPZYH8Nd.js → model-input-CBp-p24N.js} +4 -4
  38. package/dist/nitro.d.ts +1 -1
  39. package/dist/nitro.js +4 -4
  40. package/dist/{oauth-callback-server-R7qvSzFG.js → oauth-callback-server-BRq9QNhU.js} +2 -2
  41. package/dist/{plugins-CBW2Prb_.js → plugins-BBX07Jzt.js} +1 -1
  42. package/dist/{projection-DEdP1q6f.js → projection-CQNDOi82.js} +911 -671
  43. package/dist/{prompt-4M98h_tC.js → prompt-DLUB5m72.js} +4 -4
  44. package/dist/{registry-BTKmKM-r.js → registry-Dj377ADs.js} +2 -2
  45. package/dist/{resolve-B8hXNVZ3.js → resolve-DJkh9Fky.js} +3 -3
  46. package/dist/{result-g-XAaOj6.js → result-C8iIpDl1.js} +9 -9
  47. package/dist/{runner-BlPSA5A8.js → runner-DZqrOy8C.js} +9 -9
  48. package/dist/{sandbox-egress-signals-Pai-MzEY.js → sandbox-egress-signals-CGwH86S9.js} +1 -1
  49. package/dist/{schema-DbuWR-DN.d.ts → schema-CdZFn7Qd.d.ts} +248 -6
  50. package/dist/{schema-BNnY_trV.js → schema-DyHXiQKI.js} +28 -16
  51. package/dist/{service-account-BYGZ08DQ.js → service-account-D6jGR4a1.js} +3 -3
  52. package/dist/{service-account-9OLNQMyz.js → service-account-suY004dx.js} +4 -4
  53. package/dist/{session-stop-2XJrcNCy.js → session-stop-BLmfFI3d.js} +121 -46
  54. package/dist/{skills-DpBQoeHV.js → skills-CmNG0dHb.js} +2 -2
  55. package/dist/{slack-conversation-unfurl-BcDIWo67.js → slack-conversation-unfurl-Bty-DlHe.js} +7 -7
  56. package/dist/{spawn-09GssFod.js → spawn-CNjkpXpk.js} +6 -6
  57. package/dist/{state-Cufq0_rH.js → state-CEbZuZD6.js} +2 -2
  58. package/dist/{statuses-B8mUfghF.js → statuses-Hn-HsOph.js} +86 -2
  59. package/dist/{stop-U7iUrR1g.js → stop-Bjy2-K4H.js} +967 -93
  60. package/dist/{store-BHiaHCQu.js → store-DmV4CoNr.js} +5 -5
  61. package/dist/{store-CSgUTMdv.js → store-Epv6t4vV.js} +9 -9
  62. package/dist/{task-queue-bMNq0clp.js → task-queue-AhG1tSXR.js} +3 -3
  63. package/dist/{task-runner-B__rxwxU.js → task-runner-BMxZI3o7.js} +8 -8
  64. package/dist/{thread-context-d0ceWbVT.js → thread-context-CXLnbg7g.js} +8 -8
  65. package/dist/{turn-session-routing-BVZHBFCF.js → turn-session-routing-BD3-jJl7.js} +5 -5
  66. package/dist/{turn-user-message-BEw7acTP.js → turn-user-message-DsUZi9gn.js} +3 -3
  67. package/dist/{users-BK3dbxZL.js → users-BxvYclQg.js} +3 -3
  68. package/dist/{validation-BDVJjO2E.js → validation-DOz8X9BU.js} +1 -1
  69. package/dist/{version-DQgZoQ3D.js → version-CGMRmMPK.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-CAWfFo29.js → viewer-H3EsMWtJ.js} +16 -114
  72. package/dist/{warmup-9ySPacF9.js → warmup-CdU5hR49.js} +51 -27
  73. package/dist/{worker-D8jJO-WO.js → worker-ClphajjD.js} +24 -20
  74. package/migrations/0107_attachment_deferred_download.sql +2 -0
  75. package/migrations/meta/0107_snapshot.json +4617 -0
  76. package/migrations/meta/_journal.json +7 -0
  77. package/package.json +10 -8
  78. package/dist/media-BAHvgkok.js +0 -85
@@ -1,20 +1,20 @@
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 { A as estimateTextTokens, E as resolveGatewayModel, I as unwrapCurrentInstruction, L as escapeXml, S as completeObject, T as rerankTexts, X as toOptionalTrimmed, i as getChatConfig, n as botConfig, o as getSlackBotToken, v as normalizeSlackEmojiName, w as embedTexts, x as completeDecision, y as GEN_AI_PROVIDER_NAME } from "./config-CAXIpWQb.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-DPLEa8Bn.js";
4
- import { t as canExposeConversationPayload } from "./conversation-privacy-DUgtRkf8.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-CmjhyqgB.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-DcjLDDqi.js";
4
+ import { t as canExposeConversationPayload } from "./conversation-privacy-0CM0V2qK.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-COYOGzYS.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-BWmAgSyi.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-Czra10QW.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-D_023K0H.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-AgCNqqsG.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-BTKmKM-r.js";
11
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DaBaHY7u.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-4M98h_tC.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-CNjGEJO9.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-Dj377ADs.js";
11
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BEY6EGRi.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-DLUB5m72.js";
13
13
  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-CAWfFo29.js";
15
- import { $ as conversationBriefSchema, J as readMessageAttachments, L as reviewItemChangeRecordSchema, Q as briefResourceLabel, V as readMessageCardRefs, _ as conversationReportMessageEventSchema, et as parseBriefInput, g as conversationReportEventSchema, tt as parseStoredBrief, z as messageCardRef } from "./conversation-fCWD9Az3.js";
14
+ import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-H3EsMWtJ.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-BNXfq6Lb.js";
16
16
  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-Cufq0_rH.js";
17
+ import { n as readEncryptedState, t as createEncryptedState } from "./state-CEbZuZD6.js";
18
18
  import { i as readWebPushPrivateKey, t as readJuniorSecret } from "./secrets-DebYU866.js";
19
19
  import * as z from "zod";
20
20
  import path from "node:path";
@@ -25,7 +25,9 @@ import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt,
25
25
  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
26
  import { alias } from "drizzle-orm/pg-core";
27
27
  import fs from "node:fs/promises";
28
+ import { parseMarkdown, walkAst } from "chat";
28
29
  import pLimit from "p-limit";
30
+ import { WebClient } from "@slack/web-api";
29
31
  import http from "node:http";
30
32
  import os from "node:os";
31
33
  import dns from "node:dns/promises";
@@ -33,7 +35,6 @@ import net from "node:net";
33
35
  import { Duplex, Readable } from "node:stream";
34
36
  import tls from "node:tls";
35
37
  import { FileSystem, Sandbox } from "@vercel/sandbox";
36
- import { WebClient } from "@slack/web-api";
37
38
  import { createRemoteJWKSet, decodeJwt, jwtVerify } from "jose";
38
39
  import webPush, { WebPushError } from "web-push";
39
40
  // src/chat/configuration/defaults.ts
@@ -632,6 +633,100 @@ function fragmentSelectionSet(selection, fragments, seen) {
632
633
  seen.add(name);
633
634
  return fragments.get(name)?.selectionSet ?? false;
634
635
  }
636
+ // src/chat/identities/slack-mention-text.ts
637
+ const SLACK_TOKEN_PATTERN = new RegExp([
638
+ String.raw`<@(?<user>[UW][A-Z0-9]+)(?:\|(?<userLabel>[^<>]*))?>`,
639
+ String.raw`<#(?<channel>[CG][A-Z0-9]+)(?:\|(?<channelLabel>[^<>]*))?>`,
640
+ String.raw`<!(?<special>[a-z]+(?:\^[^<>|\s]*)?)(?:\|(?<specialLabel>[^<>]*))?>`,
641
+ String.raw`<(?<url>(?:https?|mailto):[^<>|\s]+)\|(?<urlLabel>[^<>]*)>`
642
+ ].join("|"), "g");
643
+ function plainLabel(label) {
644
+ return label?.trim().replace(/^[@#]/, "") || void 0;
645
+ }
646
+ const slackIdentity = alias(juniorIdentities, "slack_mention_identity");
647
+ /**
648
+ * Read a name and the `provider` account handle of the people behind Slack
649
+ * user IDs. A person with several accounts at `provider` gets the first
650
+ * handle in sort order, so the result is stable.
651
+ */
652
+ async function readSlackPeople(slackUserIds, provider) {
653
+ if (slackUserIds.length === 0) return /* @__PURE__ */ new Map();
654
+ const rows = await getSqlExecutor().db().select({
655
+ handle: juniorIdentities.handle,
656
+ slackHandle: slackIdentity.handle,
657
+ slackName: slackIdentity.displayName,
658
+ slackUserId: slackIdentity.providerSubjectId,
659
+ userName: juniorUsers.displayName
660
+ }).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)));
661
+ const people = /* @__PURE__ */ new Map();
662
+ for (const row of rows) {
663
+ const current = people.get(row.slackUserId) ?? {};
664
+ const handle = row.handle && (!current.handle || row.handle < current.handle) ? row.handle : current.handle;
665
+ const name = current.name ?? (row.userName?.trim() || row.slackName?.trim() || row.slackHandle?.trim());
666
+ people.set(row.slackUserId, {
667
+ ...handle ? { handle } : void 0,
668
+ ...name ? { name } : void 0
669
+ });
670
+ }
671
+ return people;
672
+ }
673
+ function mapStrings(value, replace) {
674
+ if (typeof value === "string") return replace(value);
675
+ if (Array.isArray(value)) return value.map((item) => mapStrings(item, replace));
676
+ if (value && typeof value === "object") return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, mapStrings(item, replace)]));
677
+ return value;
678
+ }
679
+ /** Return the Slack tokens in `text` outside Markdown code. */
680
+ function slackTokens(text) {
681
+ const code = [];
682
+ walkAst(parseMarkdown(text), (node) => {
683
+ const { start, end } = node.position ?? {};
684
+ if ((node.type === "code" || node.type === "inlineCode") && start?.offset !== void 0 && end?.offset !== void 0) code.push([start.offset, end.offset]);
685
+ return node;
686
+ });
687
+ return [...text.matchAll(SLACK_TOKEN_PATTERN)].filter(({ index }) => !code.some(([start, end]) => index >= start && index < end));
688
+ }
689
+ function replaceToken(token, people) {
690
+ if (token.url) return token.urlLabel ? `[${token.urlLabel}](${token.url})` : token.url;
691
+ if (token.user) {
692
+ const person = people.get(token.user);
693
+ if (person?.handle) return `@${person.handle}`;
694
+ return person?.name ?? plainLabel(token.userLabel) ?? "a Slack user";
695
+ }
696
+ if (token.channel) {
697
+ const name = plainLabel(token.channelLabel);
698
+ return name ? `#${name}` : "a Slack channel";
699
+ }
700
+ return plainLabel(token.specialLabel) ?? token.special.split("^")[0];
701
+ }
702
+ /**
703
+ * Rewrite Slack syntax in every string of `value`, such as a tool input that
704
+ * goes to another provider, because the provider shows it as literal text.
705
+ * Markdown code stays as written. A Slack user becomes `@handle` of their
706
+ * linked account at `provider`. Without one, they become their name, so the
707
+ * text never mentions a guessed account. Channel and special mentions become
708
+ * plain words, and `<url|label>` becomes a Markdown link.
709
+ */
710
+ async function replaceSlackMentions(value, provider) {
711
+ const tokens = /* @__PURE__ */ new Map();
712
+ mapStrings(value, (text) => {
713
+ if (text.includes("<")) tokens.set(text, slackTokens(text));
714
+ return text;
715
+ });
716
+ const matches = [...tokens.values()].flat();
717
+ if (matches.length === 0) return value;
718
+ const people = await readSlackPeople([...new Set(matches.flatMap((match) => match.groups?.user ?? []))], provider);
719
+ return mapStrings(value, (text) => {
720
+ let result = "";
721
+ let cursor = 0;
722
+ for (const match of tokens.get(text) ?? []) {
723
+ result += text.slice(cursor, match.index);
724
+ result += replaceToken(match.groups, people);
725
+ cursor = match.index + match[0].length;
726
+ }
727
+ return result + text.slice(cursor);
728
+ });
729
+ }
635
730
  // src/chat/slack/user.ts
636
731
  const slackUserInfoSchema = z.object({
637
732
  ok: z.literal(true),
@@ -1001,188 +1096,627 @@ const briefUpdatedEvent = defineConversationEvent({
1001
1096
  }).strict(),
1002
1097
  renderEvent: renderBriefUpdated
1003
1098
  });
1004
- // src/chat/slack/attachments.ts
1005
- /** Save the vision summary for a stored Slack attachment. */
1006
- async function recordSlackAttachment(args) {
1007
- const db = args.db.db();
1008
- await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ visionSummary: args.visionSummary }).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
1009
- }
1010
- /** Read a saved vision summary for one live attachment. */
1011
- async function readAttachmentVisionSummary(args) {
1012
- const [row] = await args.db.db().select({ visionSummary: juniorAttachments.visionSummary }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
1013
- return row?.visionSummary;
1099
+ // src/chat/attachments/source.ts
1100
+ /** The source deleted the file, or Junior can no longer read it. */
1101
+ var AttachmentSourceUnavailableError = class extends Error {
1102
+ constructor(message, options) {
1103
+ super(message, options);
1104
+ this.name = "AttachmentSourceUnavailableError";
1105
+ }
1106
+ };
1107
+ // src/chat/slack/workspace-context.ts
1108
+ const workspaceTeamIdStorage = new AsyncLocalStorage();
1109
+ /** Run a callback with the Slack workspace team ID for the inbound webhook. */
1110
+ function runWithWorkspaceTeamId(teamId, fn) {
1111
+ if (!teamId) return fn();
1112
+ return workspaceTeamIdStorage.run(teamId, fn);
1014
1113
  }
1015
- /** Match live conversation attachments to Slack file ids. */
1016
- async function matchSlackAttachments(args) {
1017
- if (args.providerIds.length === 0) return [];
1018
- return await args.db.db().select({
1019
- id: juniorAttachments.id,
1020
- providerId: juniorAttachments.providerId,
1021
- bytes: juniorAttachments.bytes,
1022
- contentType: juniorAttachments.contentType,
1023
- filename: juniorAttachments.filename
1024
- }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, args.conversationId), eq(juniorAttachments.provider, "slack"), inArray(juniorAttachments.providerId, args.providerIds), isNull(juniorAttachments.deleteRequestedAt)));
1114
+ /** Return the Slack workspace team ID for the current inbound webhook. */
1115
+ function getWorkspaceTeamId() {
1116
+ return workspaceTeamIdStorage.getStore();
1025
1117
  }
1026
- /**
1027
- * Fingerprint the live Slack attachments that `matchSlackAttachments` can
1028
- * return for a Conversation. It changes when one is stored or deleted, so a
1029
- * reader can tell that stored messages may now show other files.
1030
- */
1031
- function slackAttachmentsVersionQuery(db, conversationId) {
1032
- return db.select({ version: sql`coalesce(md5(string_agg(${juniorAttachments.id}, ',' order by ${juniorAttachments.id})), '')` }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, conversationId), eq(juniorAttachments.provider, "slack"), isNull(juniorAttachments.deleteRequestedAt)));
1118
+ // src/chat/sleep.ts
1119
+ /** Wait for a duration, rejecting with the owning signal reason when cancelled. */
1120
+ function sleep$2(ms, signal) {
1121
+ if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
1122
+ return new Promise((resolve, reject) => {
1123
+ if (signal.aborted) {
1124
+ reject(signal.reason);
1125
+ return;
1126
+ }
1127
+ const timeoutId = setTimeout(() => {
1128
+ signal.removeEventListener("abort", onAbort);
1129
+ resolve();
1130
+ }, ms);
1131
+ const onAbort = () => {
1132
+ clearTimeout(timeoutId);
1133
+ reject(signal.reason);
1134
+ };
1135
+ signal.addEventListener("abort", onAbort, { once: true });
1136
+ });
1033
1137
  }
1034
- /** Read the Slack file identity retained by the Chat SDK. */
1035
- function getSlackFileId(attachment) {
1036
- const metadataId = attachment.fetchMetadata?.fileId;
1037
- if (metadataId) return metadataId;
1038
- return (attachment.url ?? attachment.fetchMetadata?.url ?? "").match(/(?:^|[-/])(F[A-Z0-9]+)(?:[-/]|$)/i)?.[1];
1138
+ // src/chat/slack/client.ts
1139
+ var SlackActionError = class extends Error {
1140
+ code;
1141
+ apiError;
1142
+ needed;
1143
+ provided;
1144
+ statusCode;
1145
+ requestId;
1146
+ errorData;
1147
+ retryAfterSeconds;
1148
+ detail;
1149
+ detailLine;
1150
+ detailRule;
1151
+ /** Network error code, such as `ECONNABORTED`, when no Slack response arrived. */
1152
+ networkCode;
1153
+ constructor(message, code, options = {}) {
1154
+ super(message);
1155
+ this.name = "SlackActionError";
1156
+ this.code = code;
1157
+ this.apiError = options.apiError;
1158
+ this.needed = options.needed;
1159
+ this.provided = options.provided;
1160
+ this.statusCode = options.statusCode;
1161
+ this.requestId = options.requestId;
1162
+ this.errorData = options.errorData;
1163
+ this.retryAfterSeconds = options.retryAfterSeconds;
1164
+ this.detail = options.detail;
1165
+ this.detailLine = options.detailLine;
1166
+ this.detailRule = options.detailRule;
1167
+ this.networkCode = options.networkCode;
1168
+ }
1169
+ };
1170
+ function serializeSlackErrorData(data) {
1171
+ if (!data || typeof data !== "object") return;
1172
+ const filtered = Object.fromEntries(Object.entries(data).filter(([key]) => key !== "error"));
1173
+ if (Object.keys(filtered).length === 0) return;
1174
+ try {
1175
+ const serialized = JSON.stringify(filtered);
1176
+ return serialized.length <= 600 ? serialized : `${serialized.slice(0, 597)}...`;
1177
+ } catch {
1178
+ return;
1179
+ }
1039
1180
  }
1040
- // src/api/conversations/message-attachments.ts
1041
- /** Resolve saved Slack file references without exposing private storage details. */
1042
- async function hydrateMessageAttachments(db, conversationId, events) {
1043
- const messages = events.flatMap((event) => event.data.type === "message" ? [event.data] : []);
1044
- const ids = [...new Set(messages.flatMap((message) => slackFileIds(message.meta)))];
1045
- if (!ids.length) return;
1046
- const attachments = await matchSlackAttachments({
1047
- db,
1048
- conversationId,
1049
- providerIds: ids
1050
- });
1051
- const byFileId = new Map(attachments.map(({ providerId, ...attachment }) => [providerId, attachment]));
1052
- for (const message of messages) {
1053
- const stored = readMessageAttachments(message.meta?.attachments);
1054
- const matched = slackFileIds(message.meta).flatMap((id) => {
1055
- const attachment = byFileId.get(id);
1056
- return attachment ? [attachment] : [];
1057
- });
1058
- if (matched.length) message.meta = {
1059
- ...message.meta,
1060
- attachments: [...stored, ...matched]
1061
- };
1181
+ /** Extract a header value by case-insensitive name from a raw headers object. */
1182
+ function getHeaderString(headers, name) {
1183
+ if (!headers || typeof headers !== "object") return;
1184
+ const key = name.toLowerCase();
1185
+ const entries = headers;
1186
+ for (const [entryKey, value] of Object.entries(entries)) {
1187
+ if (entryKey.toLowerCase() !== key) continue;
1188
+ if (typeof value === "string") return value;
1189
+ if (Array.isArray(value)) {
1190
+ const first = value.find((entry) => typeof entry === "string");
1191
+ return typeof first === "string" ? first : void 0;
1192
+ }
1062
1193
  }
1063
1194
  }
1064
- function slackFileIds(meta) {
1065
- const ids = meta?.slackFileIds ?? meta?.imageFileIds;
1066
- return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
1195
+ function parseSlackCanvasDetail(detail) {
1196
+ if (typeof detail !== "string") return {};
1197
+ const trimmed = detail.trim();
1198
+ if (!trimmed) return {};
1199
+ const parsed = { detail: trimmed };
1200
+ const lineMatch = trimmed.match(/line\s+(\d+):/i);
1201
+ if (lineMatch) {
1202
+ const line = Number.parseInt(lineMatch[1] ?? "", 10);
1203
+ if (Number.isFinite(line)) parsed.detailLine = line;
1204
+ }
1205
+ if (/unsupported heading depth/i.test(trimmed)) parsed.detailRule = "unsupported_heading_depth";
1206
+ return parsed;
1067
1207
  }
1068
- // src/chat/agent-invocations/fork-history.ts
1069
- /** Instructions that a fork child reads with its first task. */
1070
- const FORK_INSTRUCTIONS = "You are a fork of your parent agent. The messages before your first parent task are copied from the parent's conversation so you have its context. They are not your job: your job is the parent task below. Sandbox files, approvals, and credentials of the parent were not copied, and your sandbox is separate. Verify files in your own sandbox before you use them.";
1071
1208
  /**
1072
- * Cut parent history for a fork: everything before the parent's message that
1073
- * started the fork, through the last point where every tool call has its
1074
- * result. A model request with an unanswered tool call fails, and the parent
1075
- * can commit its history in the middle of a tool round.
1209
+ * Ambient destination-installation token for Slack outbound calls, bound by
1210
+ * installation-scoped entry points so writes carry the destination
1211
+ * workspace's credentials instead of the process-global env token.
1076
1212
  */
1077
- function forkHistoryFrom(messages, parentToolCallId) {
1078
- const spawnIndex = parentToolCallId ? messages.findIndex((message) => message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && part.id === parentToolCallId)) : -1;
1079
- const before = spawnIndex >= 0 ? messages.slice(0, spawnIndex) : messages;
1080
- const pending = /* @__PURE__ */ new Set();
1081
- let end = 0;
1082
- for (const [index, message] of before.entries()) {
1083
- if (message.role === "assistant") {
1084
- for (const part of message.content) if (part.type === "toolCall") pending.add(part.id);
1085
- } else if (message.role === "toolResult") pending.delete(message.toolCallId);
1086
- if (pending.size === 0) end = index + 1;
1087
- }
1088
- return before.slice(0, end);
1089
- }
1213
+ const installationTokenStorage = new AsyncLocalStorage();
1214
+ const clientsByToken = /* @__PURE__ */ new Map();
1090
1215
  /**
1091
- * Load the start history of a fork child from its parent Conversation. The
1092
- * child commits it as its own history in its first checkpoint, so later
1093
- * agent invocations of the child read it from the child Conversation.
1216
+ * Bind a workspace installation token for all Slack Web API calls inside
1217
+ * `fn`, so multi-workspace outbound writes use the destination workspace's
1218
+ * credentials rather than the env fallback token.
1094
1219
  */
1095
- async function loadForkHistory(invocation) {
1096
- return forkHistoryFrom((await openConversationProjection({ conversationId: invocation.parentConversationId })).messages, invocation.parentToolCallId);
1097
- }
1098
- /** True for agent history that a fork child inherited from its parent. */
1099
- function isInheritedForkHistory(event, firstTurnStart) {
1100
- return firstTurnStart !== void 0 && event.seq > firstTurnStart.seq && event.createdAtMs < firstTurnStart.createdAtMs && (event.data.type === "assistant_message" || event.data.type === "tool_result");
1220
+ function runWithSlackInstallationToken(token, fn) {
1221
+ const trimmed = token.trim();
1222
+ if (!trimmed) throw new SlackActionError("Slack installation token binding requires a non-empty token", "missing_token");
1223
+ return installationTokenStorage.run({ token: trimmed }, fn);
1101
1224
  }
1102
- const firstTurn = alias(juniorConversationEvents, "first_turn");
1103
1225
  /**
1104
- * SQL filter for event rows that a fork child did not inherit from its
1105
- * parent. Usage reports use it, so inherited model calls count only in the
1106
- * parent.
1226
+ * Token precedence: ambient installation token, then env token, then a hard
1227
+ * failure for team-scoped calls — a call scoped to one workspace must never
1228
+ * silently fall through to another workspace's credentials.
1107
1229
  */
1108
- function notInheritedByForkChild() {
1109
- return sql`not coalesce(${juniorConversationEvents.createdAt} < (
1110
- select ${firstTurn.createdAt}
1111
- from ${juniorConversationEvents} as ${sql.identifier("first_turn")}
1112
- where ${firstTurn.conversationId} = ${juniorConversationEvents.conversationId}
1113
- and ${firstTurn.type} = 'turn_started'
1114
- and ${firstTurn.seq} < ${juniorConversationEvents.seq}
1115
- order by ${firstTurn.seq}
1116
- limit 1
1117
- ), false)`;
1230
+ function resolveSlackToken() {
1231
+ const ambientToken = installationTokenStorage.getStore()?.token;
1232
+ if (ambientToken) return ambientToken;
1233
+ const envToken = getSlackBotToken();
1234
+ if (envToken) return envToken;
1235
+ const teamId = getWorkspaceTeamId();
1236
+ if (teamId) throw new SlackActionError(`Slack call is scoped to workspace ${teamId} but no installation token is bound and no default bot token is configured`, "missing_token");
1237
+ throw new SlackActionError("SLACK_BOT_TOKEN (or SLACK_BOT_USER_TOKEN) is required for Slack Web API actions in this service", "missing_token");
1118
1238
  }
1119
- // src/chat/sentry-links.ts
1120
- function getSentryOrgSlug() {
1121
- return process.env.SENTRY_ORG_SLUG?.trim() || void 0;
1239
+ /** Normalize Junior Slack references to native Slack conversation IDs. */
1240
+ function normalizeSlackConversationId(channelId) {
1241
+ return parseSlackChannelReferenceId(channelId);
1122
1242
  }
1123
- function isSentrySaasDsnHost(host) {
1124
- return host === "sentry.io" || host.endsWith(".sentry.io");
1243
+ /**
1244
+ * Return the per-token cached WebClient. `withSlackRetries` owns retry
1245
+ * classification for this boundary: the WebClient's built-in policy would
1246
+ * re-post timed-out writes (a duplicate-message hazard) and sleep for the
1247
+ * full unbounded Retry-After inside the request, so both internal behaviors
1248
+ * are disabled here.
1249
+ */
1250
+ function getClient() {
1251
+ const token = resolveSlackToken();
1252
+ let cached = clientsByToken.get(token);
1253
+ if (!cached) {
1254
+ cached = new WebClient(token, {
1255
+ retryConfig: { retries: 0 },
1256
+ rejectRateLimitedCalls: true
1257
+ });
1258
+ clientsByToken.set(token, cached);
1259
+ }
1260
+ return cached;
1125
1261
  }
1126
- function buildSentryWebBaseUrl(dsn) {
1127
- if (isSentrySaasDsnHost(dsn.host)) return "https://sentry.io";
1128
- const port = dsn.port ? `:${dsn.port}` : "";
1129
- const path = dsn.path ? `/${dsn.path}` : "";
1130
- return `${dsn.protocol}://${dsn.host}${port}${path}`;
1262
+ function mapSlackError(error) {
1263
+ if (error instanceof SlackActionError) return error;
1264
+ const candidate = error;
1265
+ const apiError = candidate.data?.error;
1266
+ const message = candidate.message ?? "Slack action failed";
1267
+ const baseOptions = {
1268
+ apiError,
1269
+ networkCode: findNetworkErrorCode(error),
1270
+ statusCode: candidate.statusCode,
1271
+ requestId: getHeaderString(candidate.headers, "x-slack-req-id"),
1272
+ errorData: serializeSlackErrorData(candidate.data),
1273
+ ...parseSlackCanvasDetail(candidate.data?.detail)
1274
+ };
1275
+ if (apiError === "missing_scope") return new SlackActionError(message, "missing_scope", {
1276
+ ...baseOptions,
1277
+ needed: candidate.data?.needed,
1278
+ provided: candidate.data?.provided
1279
+ });
1280
+ if (apiError === "not_in_channel") return new SlackActionError(message, "not_in_channel", baseOptions);
1281
+ if (apiError === "restricted_action_read_only_channel") return new SlackActionError(message, "read_only_channel", baseOptions);
1282
+ if (apiError === "already_reacted") return new SlackActionError(message, "already_reacted", baseOptions);
1283
+ if (apiError === "no_reaction") return new SlackActionError(message, "no_reaction", baseOptions);
1284
+ if (apiError === "invalid_arguments") return new SlackActionError(message, "invalid_arguments", baseOptions);
1285
+ if (apiError === "invalid_cursor") return new SlackActionError(message, "invalid_arguments", baseOptions);
1286
+ if (apiError === "invalid_name") return new SlackActionError(message, "invalid_arguments", baseOptions);
1287
+ if (apiError === "not_found" || apiError === "channel_not_found" || apiError === "message_not_found") return new SlackActionError(message, "not_found", baseOptions);
1288
+ if (apiError === "feature_not_enabled" || apiError === "not_allowed_token_type") return new SlackActionError(message, "feature_unavailable", baseOptions);
1289
+ if (apiError === "canvas_creation_failed") return new SlackActionError(message, "canvas_creation_failed", baseOptions);
1290
+ if (apiError === "canvas_editing_failed") return new SlackActionError(message, "canvas_editing_failed", baseOptions);
1291
+ if (candidate.code === "slack_webapi_rate_limited_error" || candidate.statusCode === 429) return new SlackActionError(message, "rate_limited", {
1292
+ ...baseOptions,
1293
+ retryAfterSeconds: candidate.retryAfter
1294
+ });
1295
+ return new SlackActionError(message, "internal_error", baseOptions);
1131
1296
  }
1132
- function buildSentryOrgPath(args) {
1133
- const dsn = getClient$1()?.getDsn();
1134
- if (!dsn?.host || !dsn.projectId) return;
1135
- const orgSlug = getSentryOrgSlug();
1136
- if (!orgSlug) return;
1137
- const params = new URLSearchParams();
1138
- params.set("project", dsn.projectId);
1139
- if (args.query) for (const [key, value] of Object.entries(args.query)) params.set(key, value);
1140
- const path = `${args.path}?${params.toString()}`;
1141
- if (isSentrySaasDsnHost(dsn.host)) return `https://${orgSlug}.sentry.io/${path}`;
1142
- return `${buildSentryWebBaseUrl(dsn)}/organizations/${orgSlug}/${path}`;
1297
+ const MAX_RETRY_DELAY_MS = 1e4;
1298
+ const MAX_TOTAL_RETRY_DELAY_MS = 2e4;
1299
+ const CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
1300
+ "ECONNREFUSED",
1301
+ "ECONNRESET",
1302
+ "ENOTFOUND",
1303
+ "EAI_AGAIN"
1304
+ ]);
1305
+ const TIMEOUT_ERROR_CODES = /* @__PURE__ */ new Set([
1306
+ "ETIMEDOUT",
1307
+ "ECONNABORTED",
1308
+ "ESOCKETTIMEDOUT"
1309
+ ]);
1310
+ function findNetworkErrorCode(error, depth = 0) {
1311
+ if (!error || typeof error !== "object" || depth > 4) return;
1312
+ const candidate = error;
1313
+ if (typeof candidate.code === "string" && (CONNECTION_ERROR_CODES.has(candidate.code) || TIMEOUT_ERROR_CODES.has(candidate.code))) return candidate.code;
1314
+ return findNetworkErrorCode(candidate.original, depth + 1) ?? findNetworkErrorCode(candidate.cause, depth + 1);
1143
1315
  }
1144
- /** Build a Sentry conversation URL only when the runtime has enough Sentry config. */
1145
- function buildSentryConversationUrl(conversationId) {
1146
- return buildSentryOrgPath({ path: `explore/conversations/${encodeURIComponent(conversationId)}/` });
1316
+ /** Report whether a Slack call failed because its request deadline elapsed. */
1317
+ function isSlackRequestTimeout(error) {
1318
+ const networkCode = error instanceof SlackActionError ? error.networkCode : findNetworkErrorCode(error);
1319
+ return networkCode !== void 0 && TIMEOUT_ERROR_CODES.has(networkCode);
1147
1320
  }
1148
- /** Build a Sentry event URL only when the runtime has enough Sentry config. */
1149
- function buildSentryEventUrl(eventId) {
1150
- return buildSentryOrgPath({
1151
- path: "issues/",
1152
- query: { query: eventId }
1153
- });
1321
+ function hasSocketHangUpMessage(error) {
1322
+ return error instanceof Error && error.message.toLowerCase().includes("socket hang up");
1154
1323
  }
1155
- // src/api/conversations/event-model.ts
1156
- /** Apply recorded model choices without carrying a previous turn's settings forward. */
1157
- function conversationEventModel(data, current) {
1158
- if (data.type === "turn_started") return void 0;
1159
- if (data.type === "assistant_message") {
1160
- const model = text$1(data.model);
1161
- const provider = text$1(data.provider);
1162
- if (model) return { modelId: model.includes("/") || !provider ? model : `${provider}/${model}` };
1324
+ /**
1325
+ * Classify a failed Slack call for retry: rate limits, Slack 5xx, and
1326
+ * connection-phase failures are always retryable; timeouts are retried only
1327
+ * for idempotent operations because Slack may already have accepted the
1328
+ * request.
1329
+ */
1330
+ function classifySlackRetry(raw, mapped) {
1331
+ if (mapped.code === "rate_limited") return "rate_limited";
1332
+ if (mapped.statusCode !== void 0 && mapped.statusCode >= 500) return "server_error";
1333
+ const networkCode = findNetworkErrorCode(raw);
1334
+ if (networkCode && CONNECTION_ERROR_CODES.has(networkCode)) return "connection";
1335
+ if (networkCode && TIMEOUT_ERROR_CODES.has(networkCode)) return "timeout";
1336
+ if (hasSocketHangUpMessage(raw)) return "connection";
1337
+ return "none";
1338
+ }
1339
+ /**
1340
+ * Run a Slack Web API call with bounded retries so transient platform
1341
+ * failures do not surface as turn failures, while non-idempotent posts are
1342
+ * never re-sent when Slack may already have accepted them.
1343
+ *
1344
+ * Retry classes: rate limits (bounded Retry-After), connection-phase network
1345
+ * failures, and Slack 5xx responses always retry; request timeouts retry only
1346
+ * when the caller marks the operation `idempotent`.
1347
+ */
1348
+ async function withSlackRetries(task, maxAttempts = 3, context = {}) {
1349
+ let attempt = 0;
1350
+ let totalDelayMs = 0;
1351
+ const action = context.action ?? "unknown";
1352
+ while (attempt < maxAttempts) {
1353
+ attempt += 1;
1354
+ const attemptNumber = attempt;
1355
+ try {
1356
+ return await withSpan(`POST slack.com/api/${action}`, "http.client", {}, async () => {
1357
+ try {
1358
+ return await task();
1359
+ } catch (error) {
1360
+ const mapped = mapSlackError(error);
1361
+ const errorAttrs = { "error.type": mapped.code };
1362
+ if (mapped.apiError) errorAttrs["app.slack.api_error_code"] = mapped.apiError;
1363
+ if (mapped.code === "rate_limited") {
1364
+ errorAttrs["http.response.status_code"] = 429;
1365
+ if (mapped.retryAfterSeconds) errorAttrs["app.slack.retry_after_ms"] = mapped.retryAfterSeconds * 1e3;
1366
+ } else if (mapped.statusCode != null) errorAttrs["http.response.status_code"] = mapped.statusCode;
1367
+ setSpanAttributes(errorAttrs);
1368
+ throw error;
1369
+ }
1370
+ }, {
1371
+ "http.request.method": "POST",
1372
+ "server.address": "slack.com",
1373
+ "url.scheme": "https",
1374
+ "url.path": `/api/${action}`,
1375
+ "app.slack.method": action,
1376
+ "app.retry.max_attempts": maxAttempts,
1377
+ ...attemptNumber > 1 ? { "http.request.resend_count": attemptNumber - 1 } : void 0,
1378
+ ...context.attributes ?? {},
1379
+ ...context.spanAttributes ?? {}
1380
+ });
1381
+ } catch (error) {
1382
+ const mapped = mapSlackError(error);
1383
+ const retryClass = classifySlackRetry(error, mapped);
1384
+ const isRetryable = retryClass === "rate_limited" || retryClass === "connection" || retryClass === "server_error" || retryClass === "timeout" && context.idempotent === true;
1385
+ const remainingDelayBudgetMs = MAX_TOTAL_RETRY_DELAY_MS - totalDelayMs;
1386
+ const baseLogAttributes = {
1387
+ "app.slack.action": action,
1388
+ "app.slack.error_code": mapped.code,
1389
+ ...mapped.apiError ? { "app.slack.api_error": mapped.apiError } : void 0,
1390
+ ...mapped.detail ? { "app.slack.detail": mapped.detail } : void 0,
1391
+ ...mapped.detailLine !== void 0 ? { "app.slack.detail_line": mapped.detailLine } : void 0,
1392
+ ...mapped.detailRule ? { "app.slack.detail_rule": mapped.detailRule } : void 0,
1393
+ ...mapped.requestId ? { "app.slack.request_id": mapped.requestId } : void 0,
1394
+ ...mapped.statusCode !== void 0 ? { "http.response.status_code": mapped.statusCode } : void 0,
1395
+ ...context.attributes ?? {}
1396
+ };
1397
+ if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0) {
1398
+ if (context.expectedErrorCodes?.includes(mapped.code)) throw mapped;
1399
+ logWarn("slack.action.failed", {
1400
+ ...baseLogAttributes,
1401
+ ...mapped.errorData ? { "app.slack.error_data": mapped.errorData } : void 0
1402
+ });
1403
+ throw mapped;
1404
+ }
1405
+ logWarn("slack.action.retrying", {
1406
+ ...baseLogAttributes,
1407
+ "app.slack.retry_attempt": attempt,
1408
+ "app.slack.retry_class": retryClass
1409
+ });
1410
+ const retryAfterMs = retryClass === "rate_limited" && mapped.retryAfterSeconds && mapped.retryAfterSeconds > 0 ? mapped.retryAfterSeconds * 1e3 : void 0;
1411
+ const backoffMs = Math.min(2e3, 250 * 2 ** (attempt - 1));
1412
+ const delayMs = Math.min(retryAfterMs ?? backoffMs, MAX_RETRY_DELAY_MS, remainingDelayBudgetMs);
1413
+ totalDelayMs += delayMs;
1414
+ await sleep$2(delayMs);
1415
+ }
1163
1416
  }
1164
- return current;
1417
+ throw new SlackActionError("Slack action exhausted retries", "internal_error");
1165
1418
  }
1166
- function text$1(value) {
1167
- return typeof value === "string" && value.length > 0 ? value : void 0;
1419
+ /**
1420
+ * Slack Web API client for the current destination workspace: the ambient
1421
+ * installation token when one is bound, otherwise the env bot token for
1422
+ * single-workspace deployments. Fails instead of falling back when the call
1423
+ * is workspace-scoped and no installation token can be resolved, so a write
1424
+ * never goes out with another workspace's credentials.
1425
+ */
1426
+ function getSlackClient(options) {
1427
+ if (options) return new WebClient(resolveSlackToken(), {
1428
+ retryConfig: { retries: 0 },
1429
+ rejectRateLimitedCalls: true,
1430
+ timeout: options.timeoutMs
1431
+ });
1432
+ return getClient();
1168
1433
  }
1169
- /** Allowlist model-call diagnostics; never expose opaque provider metadata. */
1170
- function conversationEventModelCall(data) {
1171
- if (data.type !== "assistant_message") return void 0;
1172
- const usage = extractGenAiUsageSummary(data);
1173
- const provider = text$1(data.provider);
1174
- const api = text$1(data.api);
1175
- const stopReason = text$1(data.stopReason);
1434
+ /**
1435
+ * Slack channel ID prefixes:
1436
+ * - C: channel — modern private channels also use C, so the prefix never
1437
+ * proves a channel is public
1438
+ * - G: legacy private channel / group DM
1439
+ * - D: direct message (1:1)
1440
+ */
1441
+ function isDmChannel(channelId) {
1442
+ const normalized = normalizeSlackConversationId(channelId);
1443
+ return Boolean(normalized && normalized.startsWith("D"));
1444
+ }
1445
+ /**
1446
+ * Conversation-scoped Slack contexts backed by a concrete conversation ID.
1447
+ * Includes channels/groups/DMs (C/G/D).
1448
+ */
1449
+ function isConversationScopedChannel(channelId) {
1450
+ const normalized = normalizeSlackConversationId(channelId);
1451
+ if (!normalized) return false;
1452
+ return normalized.startsWith("C") || normalized.startsWith("G") || normalized.startsWith("D");
1453
+ }
1454
+ function isConversationChannel(channelId) {
1455
+ const normalized = normalizeSlackConversationId(channelId);
1456
+ if (!normalized) return false;
1457
+ return normalized.startsWith("C") || normalized.startsWith("G");
1458
+ }
1459
+ async function getFilePermalink(fileId) {
1460
+ const client = getClient();
1461
+ return (await withSlackRetries(() => client.files.info({ file: fileId }), 3, {
1462
+ action: "files.info",
1463
+ idempotent: true,
1464
+ spanAttributes: { "app.slack.file_id": fileId }
1465
+ })).file?.permalink;
1466
+ }
1467
+ /**
1468
+ * Read the private download URL and size of one Slack file.
1469
+ *
1470
+ * Return undefined when Slack no longer has the file, or keeps only a
1471
+ * tombstone without a download URL.
1472
+ */
1473
+ async function readPrivateSlackFile(fileId) {
1474
+ const client = getClient();
1475
+ let response;
1476
+ try {
1477
+ response = await withSlackRetries(() => client.files.info({ file: fileId }), 3, {
1478
+ action: "files.info",
1479
+ idempotent: true,
1480
+ spanAttributes: { "app.slack.file_id": fileId }
1481
+ });
1482
+ } catch (error) {
1483
+ if (error instanceof SlackActionError && (error.code === "not_found" || error.apiError === "file_not_found" || error.apiError === "file_deleted")) return;
1484
+ throw error;
1485
+ }
1486
+ const url = response.file?.url_private_download ?? response.file?.url_private;
1487
+ const bytes = response.file?.size;
1488
+ if (!url || typeof bytes !== "number") return void 0;
1176
1489
  return {
1177
- ...provider ? { provider } : void 0,
1178
- ...api ? { api } : void 0,
1179
- ...stopReason ? { stopReason } : void 0,
1180
- ...hasAgentTurnUsage(usage) ? { usage } : void 0
1490
+ bytes,
1491
+ url
1181
1492
  };
1182
1493
  }
1183
- // src/api/conversations/events.ts
1184
- /** Canonical event types that can contribute to the reporting projection. */
1185
- const conversationReportSourceEventTypes = [
1494
+ async function fetchPrivateSlackFile(url) {
1495
+ const token = resolveSlackToken();
1496
+ const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
1497
+ if (!response.ok) throw new SlackActionError(`Slack file download failed: ${response.status}`, response.status === 404 || response.status === 410 ? "not_found" : "internal_error", { statusCode: response.status });
1498
+ return response;
1499
+ }
1500
+ /** Download a small private Slack file into memory. */
1501
+ async function downloadPrivateSlackFile(url) {
1502
+ const response = await fetchPrivateSlackFile(url);
1503
+ return Buffer.from(await response.arrayBuffer());
1504
+ }
1505
+ /** Open a private Slack file as a stream, so a large file is never held whole. */
1506
+ async function streamPrivateSlackFile(url) {
1507
+ const response = await fetchPrivateSlackFile(url);
1508
+ if (!response.body) throw new Error("Slack file download returned no body");
1509
+ return response.body;
1510
+ }
1511
+ // src/chat/slack/attachments.ts
1512
+ /** Save the vision summary for a stored Slack attachment. */
1513
+ async function recordSlackAttachment(args) {
1514
+ const db = args.db.db();
1515
+ await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ visionSummary: args.visionSummary }).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
1516
+ }
1517
+ /** Read a saved vision summary for one live attachment. */
1518
+ async function readAttachmentVisionSummary(args) {
1519
+ const [row] = await args.db.db().select({ visionSummary: juniorAttachments.visionSummary }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
1520
+ return row?.visionSummary;
1521
+ }
1522
+ /** Match live conversation attachments to Slack file ids. */
1523
+ async function matchSlackAttachments(args) {
1524
+ if (args.providerIds.length === 0) return [];
1525
+ return (await args.db.db().select({
1526
+ id: juniorAttachments.id,
1527
+ providerId: juniorAttachments.providerId,
1528
+ bytes: juniorAttachments.bytes,
1529
+ contentType: juniorAttachments.contentType,
1530
+ filename: juniorAttachments.filename,
1531
+ storageKey: juniorAttachments.storageKey
1532
+ }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, args.conversationId), eq(juniorAttachments.provider, "slack"), inArray(juniorAttachments.providerId, args.providerIds), isNull(juniorAttachments.deleteRequestedAt)))).map(({ storageKey, ...row }) => storageKey === null ? {
1533
+ ...row,
1534
+ pending: true
1535
+ } : row);
1536
+ }
1537
+ /**
1538
+ * Fingerprint the live Slack attachments that `matchSlackAttachments` can
1539
+ * return for a Conversation. It changes when one is stored or deleted, so a
1540
+ * reader can tell that stored messages may now show other files.
1541
+ */
1542
+ function slackAttachmentsVersionQuery(db, conversationId) {
1543
+ return db.select({ version: sql`coalesce(md5(string_agg(${juniorAttachments.id}, ',' order by ${juniorAttachments.id})), '')` }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, conversationId), eq(juniorAttachments.provider, "slack"), isNull(juniorAttachments.deleteRequestedAt)));
1544
+ }
1545
+ /** Read the Slack file identity retained by the Chat SDK. */
1546
+ function getSlackFileId(attachment) {
1547
+ const metadataId = attachment.fetchMetadata?.fileId;
1548
+ if (metadataId) return metadataId;
1549
+ return (attachment.url ?? attachment.fetchMetadata?.url ?? "").match(/(?:^|[-/])(F[A-Z0-9]+)(?:[-/]|$)/)?.[1];
1550
+ }
1551
+ /**
1552
+ * Look up a Slack file that Junior recorded without storing it.
1553
+ *
1554
+ * Uses the installation token that the caller binds: the Slack turn, or the
1555
+ * dashboard route for the conversation's Slack team.
1556
+ */
1557
+ const readSlackAttachmentSource = async (source) => {
1558
+ const unavailable = (cause) => new AttachmentSourceUnavailableError("The Slack file was deleted, or Junior can no longer access it.", { cause });
1559
+ if (source.provider !== "slack") throw unavailable();
1560
+ const file = await readPrivateSlackFile(source.id);
1561
+ if (!file) throw unavailable();
1562
+ return {
1563
+ bytes: file.bytes,
1564
+ open: async () => {
1565
+ try {
1566
+ return await streamPrivateSlackFile(file.url);
1567
+ } catch (error) {
1568
+ if (error instanceof SlackActionError && (error.code === "not_found" || error.statusCode === 403)) throw unavailable(error);
1569
+ throw error;
1570
+ }
1571
+ }
1572
+ };
1573
+ };
1574
+ // src/api/conversations/message-attachments.ts
1575
+ /** Resolve saved Slack file references without exposing private storage details. */
1576
+ async function hydrateMessageAttachments(db, conversationId, events) {
1577
+ const messages = events.flatMap((event) => event.data.type === "message" ? [event.data] : []);
1578
+ const ids = [...new Set(messages.flatMap((message) => slackFileIds(message.meta)))];
1579
+ if (!ids.length) return;
1580
+ const attachments = await matchSlackAttachments({
1581
+ db,
1582
+ conversationId,
1583
+ providerIds: ids
1584
+ });
1585
+ const byFileId = new Map(attachments.map(({ providerId, ...attachment }) => [providerId, attachment]));
1586
+ for (const message of messages) {
1587
+ const stored = readMessageAttachments(message.meta?.attachments);
1588
+ const matched = slackFileIds(message.meta).flatMap((id) => {
1589
+ const attachment = byFileId.get(id);
1590
+ return attachment ? [attachment] : [];
1591
+ });
1592
+ if (matched.length) message.meta = {
1593
+ ...message.meta,
1594
+ attachments: [...stored, ...matched]
1595
+ };
1596
+ }
1597
+ }
1598
+ function slackFileIds(meta) {
1599
+ const ids = meta?.slackFileIds ?? meta?.imageFileIds;
1600
+ return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
1601
+ }
1602
+ // src/chat/agent-invocations/fork-history.ts
1603
+ /** Instructions that a fork child reads with its first task. */
1604
+ const FORK_INSTRUCTIONS = "You are a fork of your parent agent. The messages before your first parent task are copied from the parent's conversation so you have its context. They are not your job: your job is the parent task below. Sandbox files, approvals, and credentials of the parent were not copied, and your sandbox is separate. Verify files in your own sandbox before you use them.";
1605
+ /**
1606
+ * Cut parent history for a fork: everything before the parent's message that
1607
+ * started the fork, through the last point where every tool call has its
1608
+ * result. A model request with an unanswered tool call fails, and the parent
1609
+ * can commit its history in the middle of a tool round.
1610
+ */
1611
+ function forkHistoryFrom(messages, parentToolCallId) {
1612
+ const spawnIndex = parentToolCallId ? messages.findIndex((message) => message.role === "assistant" && message.content.some((part) => part.type === "toolCall" && part.id === parentToolCallId)) : -1;
1613
+ const before = spawnIndex >= 0 ? messages.slice(0, spawnIndex) : messages;
1614
+ const pending = /* @__PURE__ */ new Set();
1615
+ let end = 0;
1616
+ for (const [index, message] of before.entries()) {
1617
+ if (message.role === "assistant") {
1618
+ for (const part of message.content) if (part.type === "toolCall") pending.add(part.id);
1619
+ } else if (message.role === "toolResult") pending.delete(message.toolCallId);
1620
+ if (pending.size === 0) end = index + 1;
1621
+ }
1622
+ return before.slice(0, end);
1623
+ }
1624
+ /**
1625
+ * Load the start history of a fork child from its parent Conversation. The
1626
+ * child commits it as its own history in its first checkpoint, so later
1627
+ * agent invocations of the child read it from the child Conversation.
1628
+ */
1629
+ async function loadForkHistory(invocation) {
1630
+ return forkHistoryFrom((await openConversationProjection({ conversationId: invocation.parentConversationId })).messages, invocation.parentToolCallId);
1631
+ }
1632
+ /** True for agent history that a fork child inherited from its parent. */
1633
+ function isInheritedForkHistory(event, firstTurnStart) {
1634
+ return firstTurnStart !== void 0 && event.seq > firstTurnStart.seq && event.createdAtMs < firstTurnStart.createdAtMs && (event.data.type === "assistant_message" || event.data.type === "tool_result");
1635
+ }
1636
+ const firstTurn = alias(juniorConversationEvents, "first_turn");
1637
+ /**
1638
+ * SQL filter for event rows that a fork child did not inherit from its
1639
+ * parent. Usage reports use it, so inherited model calls count only in the
1640
+ * parent.
1641
+ */
1642
+ function notInheritedByForkChild() {
1643
+ return sql`not coalesce(${juniorConversationEvents.createdAt} < (
1644
+ select ${firstTurn.createdAt}
1645
+ from ${juniorConversationEvents} as ${sql.identifier("first_turn")}
1646
+ where ${firstTurn.conversationId} = ${juniorConversationEvents.conversationId}
1647
+ and ${firstTurn.type} = 'turn_started'
1648
+ and ${firstTurn.seq} < ${juniorConversationEvents.seq}
1649
+ order by ${firstTurn.seq}
1650
+ limit 1
1651
+ ), false)`;
1652
+ }
1653
+ // src/chat/sentry-links.ts
1654
+ function getSentryOrgSlug() {
1655
+ return process.env.SENTRY_ORG_SLUG?.trim() || void 0;
1656
+ }
1657
+ function isSentrySaasDsnHost(host) {
1658
+ return host === "sentry.io" || host.endsWith(".sentry.io");
1659
+ }
1660
+ function buildSentryWebBaseUrl(dsn) {
1661
+ if (isSentrySaasDsnHost(dsn.host)) return "https://sentry.io";
1662
+ const port = dsn.port ? `:${dsn.port}` : "";
1663
+ const path = dsn.path ? `/${dsn.path}` : "";
1664
+ return `${dsn.protocol}://${dsn.host}${port}${path}`;
1665
+ }
1666
+ function buildSentryOrgPath(args) {
1667
+ const dsn = getClient$1()?.getDsn();
1668
+ if (!dsn?.host || !dsn.projectId) return;
1669
+ const orgSlug = getSentryOrgSlug();
1670
+ if (!orgSlug) return;
1671
+ const params = new URLSearchParams();
1672
+ params.set("project", dsn.projectId);
1673
+ if (args.query) for (const [key, value] of Object.entries(args.query)) params.set(key, value);
1674
+ const path = `${args.path}?${params.toString()}`;
1675
+ if (isSentrySaasDsnHost(dsn.host)) return `https://${orgSlug}.sentry.io/${path}`;
1676
+ return `${buildSentryWebBaseUrl(dsn)}/organizations/${orgSlug}/${path}`;
1677
+ }
1678
+ /** Build a Sentry conversation URL only when the runtime has enough Sentry config. */
1679
+ function buildSentryConversationUrl(conversationId) {
1680
+ return buildSentryOrgPath({ path: `explore/conversations/${encodeURIComponent(conversationId)}/` });
1681
+ }
1682
+ /** Build a Sentry event URL only when the runtime has enough Sentry config. */
1683
+ function buildSentryEventUrl(eventId) {
1684
+ return buildSentryOrgPath({
1685
+ path: "issues/",
1686
+ query: { query: eventId }
1687
+ });
1688
+ }
1689
+ // src/api/conversations/event-model.ts
1690
+ /** Apply recorded model choices without carrying a previous turn's settings forward. */
1691
+ function conversationEventModel(data, current) {
1692
+ if (data.type === "turn_started") return void 0;
1693
+ if (data.type === "assistant_message") {
1694
+ const model = text$1(data.model);
1695
+ const provider = text$1(data.provider);
1696
+ if (model) return { modelId: model.includes("/") || !provider ? model : `${provider}/${model}` };
1697
+ }
1698
+ return current;
1699
+ }
1700
+ function text$1(value) {
1701
+ return typeof value === "string" && value.length > 0 ? value : void 0;
1702
+ }
1703
+ /** Allowlist model-call diagnostics; never expose opaque provider metadata. */
1704
+ function conversationEventModelCall(data) {
1705
+ if (data.type !== "assistant_message") return void 0;
1706
+ const usage = extractGenAiUsageSummary(data);
1707
+ const provider = text$1(data.provider);
1708
+ const api = text$1(data.api);
1709
+ const stopReason = text$1(data.stopReason);
1710
+ return {
1711
+ ...provider ? { provider } : void 0,
1712
+ ...api ? { api } : void 0,
1713
+ ...stopReason ? { stopReason } : void 0,
1714
+ ...hasAgentTurnUsage(usage) ? { usage } : void 0
1715
+ };
1716
+ }
1717
+ // src/api/conversations/events.ts
1718
+ /** Canonical event types that can contribute to the reporting projection. */
1719
+ const conversationReportSourceEventTypes = [
1186
1720
  "message",
1187
1721
  "message_handled",
1188
1722
  "assistant_message",
@@ -2693,6 +3227,11 @@ function basePluginContext$1(plugin) {
2693
3227
  db: getDb()
2694
3228
  };
2695
3229
  }
3230
+ /** Pick one plugin's string config values and drop the plugin name prefix. */
3231
+ function pluginConfigValues(pluginName, configuration) {
3232
+ const prefix = `${pluginName}.`;
3233
+ return Object.fromEntries(Object.entries(configuration).flatMap(([key, value]) => key.startsWith(prefix) && typeof value === "string" ? [[key.slice(prefix.length), value]] : []));
3234
+ }
2696
3235
  /** Time one plugin hook call so slow plugins show up in turn traces. */
2697
3236
  async function withPluginHookSpan(pluginName, hookName, callback) {
2698
3237
  return await withSpan(`plugin.hook ${hookName}`, "plugin.hook", {}, callback, {
@@ -2951,26 +3490,6 @@ async function dockerOkStream(input) {
2951
3490
  if ((response.statusCode ?? 0) >= 400) return await errorFrom(response);
2952
3491
  return response;
2953
3492
  }
2954
- // src/chat/sleep.ts
2955
- /** Wait for a duration, rejecting with the owning signal reason when cancelled. */
2956
- function sleep$2(ms, signal) {
2957
- if (!signal) return new Promise((resolve) => setTimeout(resolve, ms));
2958
- return new Promise((resolve, reject) => {
2959
- if (signal.aborted) {
2960
- reject(signal.reason);
2961
- return;
2962
- }
2963
- const timeoutId = setTimeout(() => {
2964
- signal.removeEventListener("abort", onAbort);
2965
- resolve();
2966
- }, ms);
2967
- const onAbort = () => {
2968
- clearTimeout(timeoutId);
2969
- reject(signal.reason);
2970
- };
2971
- signal.addEventListener("abort", onAbort, { once: true });
2972
- });
2973
- }
2974
3493
  // src/chat/sandbox/docker/exec.ts
2975
3494
  /** Directory for command state in each sandbox. The runtime image creates it. */
2976
3495
  const COMMAND_STATE_DIR = "/var/tmp/junior-commands";
@@ -5282,461 +5801,115 @@ async function createSession(input) {
5282
5801
  if (input.networkPolicy) await applyEgressPolicy(container, input.networkPolicy);
5283
5802
  } catch (error) {
5284
5803
  await removeContainer(container.name).catch(() => void 0);
5285
- throw error;
5286
- }
5287
- return adaptSession$1(container, input);
5288
- }
5289
- /** Return a session for a named sandbox container. Start it if it stopped. */
5290
- async function getSession(input) {
5291
- return adaptSession$1(await getContainer(input.name, await egressCaPem(), input.scopeSignal), input);
5292
- }
5293
- /** Create the persistent container that runs one Workspace snapshot build. */
5294
- async function createWorkspaceSnapshotBuilder$1(input) {
5295
- await createContainer({
5296
- name: input.name,
5297
- image: await ensureRuntimeImage(input.runtime, input.signal),
5298
- timeoutMs: input.timeoutMs,
5299
- persistent: true,
5300
- vcpus: input.resources?.vcpus,
5301
- signal: input.signal
5302
- }, await egressCaPem());
5303
- }
5304
- /**
5305
- * Return the container that runs one Workspace snapshot build.
5306
- *
5307
- * A Docker snapshot is an image that does not depend on its builder. So
5308
- * `snapshot()` removes the builder right after the commit, and the image tag
5309
- * keeps the builder's name. Deleting the builder later removes that tag.
5310
- */
5311
- async function getWorkspaceSnapshotBuilder$1(name, signal) {
5312
- const container = await getContainer(name, await egressCaPem(), signal);
5313
- return {
5314
- session: () => adaptSession$1(container),
5315
- startDetachedCommand: (input) => startDetachedCommand(container.id, input),
5316
- async getCommand(commandId) {
5317
- return { wait: ({ signal: waitSignal }) => waitForDetachedCommand(container.id, commandId, waitSignal) };
5318
- },
5319
- async snapshot(options) {
5320
- const snapshotId = await commitSnapshot(container.id, name, options?.signal);
5321
- await removeContainer(name);
5322
- return { snapshotId };
5323
- }
5324
- };
5325
- }
5326
- async function deleteSnapshotTag(name) {
5327
- try {
5328
- await dockerRequest({
5329
- method: "DELETE",
5330
- path: `/images/${encodeURIComponent(`${SNAPSHOT_REPOSITORY}:${name}`)}`,
5331
- query: { force: true }
5332
- });
5333
- } catch (error) {
5334
- if (!(error instanceof DockerApiError && error.statusCode === 404)) throw error;
5335
- }
5336
- }
5337
- /**
5338
- * Remove Workspace builders and the snapshot images tagged with their names.
5339
- *
5340
- * Shared snapshot code calls this when a Workspace snapshot is no longer
5341
- * used. Each name is tried, and the first failure is thrown at the end.
5342
- */
5343
- async function deleteWorkspaceSnapshotBuilders$1(names) {
5344
- const failures = [];
5345
- for (const name of new Set(names)) for (const remove of [removeContainer, deleteSnapshotTag]) try {
5346
- await remove(name);
5347
- } catch (error) {
5348
- failures.push(error);
5349
- }
5350
- if (failures.length > 0) throw failures[0];
5351
- }
5352
- const DOCKER_SNAPSHOT_PACKAGES = /* @__PURE__ */ new Set([
5353
- "spal-release",
5354
- "ripgrep",
5355
- "gh",
5356
- "jq"
5357
- ]);
5358
- /**
5359
- * Keep only the small Docker base from the declared runtime dependencies.
5360
- *
5361
- * Postinstall commands are skipped, because they often download large tools.
5362
- * A base package that no plugin declares is not installed.
5363
- */
5364
- function selectSnapshotRuntime(runtime) {
5365
- return {
5366
- dependencies: runtime.dependencies.filter((dependency) => "package" in dependency && DOCKER_SNAPSHOT_PACKAGES.has(dependency.package)),
5367
- postinstall: []
5368
- };
5369
- }
5370
- /** Local Docker implementation of the sandbox provider contract. */
5371
- const dockerSandboxProvider = {
5372
- errors: dockerSandboxErrors,
5373
- createSession,
5374
- getSession,
5375
- createWorkspaceSnapshotBuilder: createWorkspaceSnapshotBuilder$1,
5376
- getWorkspaceSnapshotBuilder: getWorkspaceSnapshotBuilder$1,
5377
- deleteWorkspaceSnapshotBuilders: deleteWorkspaceSnapshotBuilders$1,
5378
- selectSnapshotRuntime
5379
- };
5380
- // src/chat/sandbox/vercel/credentials.ts
5381
- /**
5382
- * Resolve explicit Vercel Sandbox credentials, or return undefined to let
5383
- * the SDK read ambient Vercel auth from its own environment detection.
5384
- */
5385
- function getVercelSandboxCredentials() {
5386
- const token = toOptionalTrimmed(process.env.VERCEL_TOKEN);
5387
- const teamId = toOptionalTrimmed(process.env.VERCEL_TEAM_ID);
5388
- const projectId = toOptionalTrimmed(process.env.VERCEL_PROJECT_ID);
5389
- if (token && teamId && projectId) return {
5390
- token,
5391
- teamId,
5392
- projectId
5393
- };
5394
- }
5395
- // src/chat/slack/workspace-context.ts
5396
- const workspaceTeamIdStorage = new AsyncLocalStorage();
5397
- /** Run a callback with the Slack workspace team ID for the inbound webhook. */
5398
- function runWithWorkspaceTeamId(teamId, fn) {
5399
- if (!teamId) return fn();
5400
- return workspaceTeamIdStorage.run(teamId, fn);
5401
- }
5402
- /** Return the Slack workspace team ID for the current inbound webhook. */
5403
- function getWorkspaceTeamId() {
5404
- return workspaceTeamIdStorage.getStore();
5405
- }
5406
- // src/chat/slack/client.ts
5407
- var SlackActionError = class extends Error {
5408
- code;
5409
- apiError;
5410
- needed;
5411
- provided;
5412
- statusCode;
5413
- requestId;
5414
- errorData;
5415
- retryAfterSeconds;
5416
- detail;
5417
- detailLine;
5418
- detailRule;
5419
- /** Network error code, such as `ECONNABORTED`, when no Slack response arrived. */
5420
- networkCode;
5421
- constructor(message, code, options = {}) {
5422
- super(message);
5423
- this.name = "SlackActionError";
5424
- this.code = code;
5425
- this.apiError = options.apiError;
5426
- this.needed = options.needed;
5427
- this.provided = options.provided;
5428
- this.statusCode = options.statusCode;
5429
- this.requestId = options.requestId;
5430
- this.errorData = options.errorData;
5431
- this.retryAfterSeconds = options.retryAfterSeconds;
5432
- this.detail = options.detail;
5433
- this.detailLine = options.detailLine;
5434
- this.detailRule = options.detailRule;
5435
- this.networkCode = options.networkCode;
5436
- }
5437
- };
5438
- function serializeSlackErrorData(data) {
5439
- if (!data || typeof data !== "object") return;
5440
- const filtered = Object.fromEntries(Object.entries(data).filter(([key]) => key !== "error"));
5441
- if (Object.keys(filtered).length === 0) return;
5442
- try {
5443
- const serialized = JSON.stringify(filtered);
5444
- return serialized.length <= 600 ? serialized : `${serialized.slice(0, 597)}...`;
5445
- } catch {
5446
- return;
5447
- }
5448
- }
5449
- /** Extract a header value by case-insensitive name from a raw headers object. */
5450
- function getHeaderString(headers, name) {
5451
- if (!headers || typeof headers !== "object") return;
5452
- const key = name.toLowerCase();
5453
- const entries = headers;
5454
- for (const [entryKey, value] of Object.entries(entries)) {
5455
- if (entryKey.toLowerCase() !== key) continue;
5456
- if (typeof value === "string") return value;
5457
- if (Array.isArray(value)) {
5458
- const first = value.find((entry) => typeof entry === "string");
5459
- return typeof first === "string" ? first : void 0;
5460
- }
5461
- }
5462
- }
5463
- function parseSlackCanvasDetail(detail) {
5464
- if (typeof detail !== "string") return {};
5465
- const trimmed = detail.trim();
5466
- if (!trimmed) return {};
5467
- const parsed = { detail: trimmed };
5468
- const lineMatch = trimmed.match(/line\s+(\d+):/i);
5469
- if (lineMatch) {
5470
- const line = Number.parseInt(lineMatch[1] ?? "", 10);
5471
- if (Number.isFinite(line)) parsed.detailLine = line;
5472
- }
5473
- if (/unsupported heading depth/i.test(trimmed)) parsed.detailRule = "unsupported_heading_depth";
5474
- return parsed;
5475
- }
5476
- /**
5477
- * Ambient destination-installation token for Slack outbound calls, bound by
5478
- * installation-scoped entry points so writes carry the destination
5479
- * workspace's credentials instead of the process-global env token.
5480
- */
5481
- const installationTokenStorage = new AsyncLocalStorage();
5482
- const clientsByToken = /* @__PURE__ */ new Map();
5483
- /**
5484
- * Bind a workspace installation token for all Slack Web API calls inside
5485
- * `fn`, so multi-workspace outbound writes use the destination workspace's
5486
- * credentials rather than the env fallback token.
5487
- */
5488
- function runWithSlackInstallationToken(token, fn) {
5489
- const trimmed = token.trim();
5490
- if (!trimmed) throw new SlackActionError("Slack installation token binding requires a non-empty token", "missing_token");
5491
- return installationTokenStorage.run({ token: trimmed }, fn);
5492
- }
5493
- /**
5494
- * Token precedence: ambient installation token, then env token, then a hard
5495
- * failure for team-scoped calls — a call scoped to one workspace must never
5496
- * silently fall through to another workspace's credentials.
5497
- */
5498
- function resolveSlackToken() {
5499
- const ambientToken = installationTokenStorage.getStore()?.token;
5500
- if (ambientToken) return ambientToken;
5501
- const envToken = getSlackBotToken();
5502
- if (envToken) return envToken;
5503
- const teamId = getWorkspaceTeamId();
5504
- if (teamId) throw new SlackActionError(`Slack call is scoped to workspace ${teamId} but no installation token is bound and no default bot token is configured`, "missing_token");
5505
- throw new SlackActionError("SLACK_BOT_TOKEN (or SLACK_BOT_USER_TOKEN) is required for Slack Web API actions in this service", "missing_token");
5506
- }
5507
- /** Normalize Junior Slack references to native Slack conversation IDs. */
5508
- function normalizeSlackConversationId(channelId) {
5509
- return parseSlackChannelReferenceId(channelId);
5510
- }
5511
- /**
5512
- * Return the per-token cached WebClient. `withSlackRetries` owns retry
5513
- * classification for this boundary: the WebClient's built-in policy would
5514
- * re-post timed-out writes (a duplicate-message hazard) and sleep for the
5515
- * full unbounded Retry-After inside the request, so both internal behaviors
5516
- * are disabled here.
5517
- */
5518
- function getClient() {
5519
- const token = resolveSlackToken();
5520
- let cached = clientsByToken.get(token);
5521
- if (!cached) {
5522
- cached = new WebClient(token, {
5523
- retryConfig: { retries: 0 },
5524
- rejectRateLimitedCalls: true
5525
- });
5526
- clientsByToken.set(token, cached);
5527
- }
5528
- return cached;
5529
- }
5530
- function mapSlackError(error) {
5531
- if (error instanceof SlackActionError) return error;
5532
- const candidate = error;
5533
- const apiError = candidate.data?.error;
5534
- const message = candidate.message ?? "Slack action failed";
5535
- const baseOptions = {
5536
- apiError,
5537
- networkCode: findNetworkErrorCode(error),
5538
- statusCode: candidate.statusCode,
5539
- requestId: getHeaderString(candidate.headers, "x-slack-req-id"),
5540
- errorData: serializeSlackErrorData(candidate.data),
5541
- ...parseSlackCanvasDetail(candidate.data?.detail)
5542
- };
5543
- if (apiError === "missing_scope") return new SlackActionError(message, "missing_scope", {
5544
- ...baseOptions,
5545
- needed: candidate.data?.needed,
5546
- provided: candidate.data?.provided
5547
- });
5548
- if (apiError === "not_in_channel") return new SlackActionError(message, "not_in_channel", baseOptions);
5549
- if (apiError === "restricted_action_read_only_channel") return new SlackActionError(message, "read_only_channel", baseOptions);
5550
- if (apiError === "already_reacted") return new SlackActionError(message, "already_reacted", baseOptions);
5551
- if (apiError === "no_reaction") return new SlackActionError(message, "no_reaction", baseOptions);
5552
- if (apiError === "invalid_arguments") return new SlackActionError(message, "invalid_arguments", baseOptions);
5553
- if (apiError === "invalid_cursor") return new SlackActionError(message, "invalid_arguments", baseOptions);
5554
- if (apiError === "invalid_name") return new SlackActionError(message, "invalid_arguments", baseOptions);
5555
- if (apiError === "not_found" || apiError === "channel_not_found" || apiError === "message_not_found") return new SlackActionError(message, "not_found", baseOptions);
5556
- if (apiError === "feature_not_enabled" || apiError === "not_allowed_token_type") return new SlackActionError(message, "feature_unavailable", baseOptions);
5557
- if (apiError === "canvas_creation_failed") return new SlackActionError(message, "canvas_creation_failed", baseOptions);
5558
- if (apiError === "canvas_editing_failed") return new SlackActionError(message, "canvas_editing_failed", baseOptions);
5559
- if (candidate.code === "slack_webapi_rate_limited_error" || candidate.statusCode === 429) return new SlackActionError(message, "rate_limited", {
5560
- ...baseOptions,
5561
- retryAfterSeconds: candidate.retryAfter
5562
- });
5563
- return new SlackActionError(message, "internal_error", baseOptions);
5564
- }
5565
- const MAX_RETRY_DELAY_MS = 1e4;
5566
- const MAX_TOTAL_RETRY_DELAY_MS = 2e4;
5567
- const CONNECTION_ERROR_CODES = /* @__PURE__ */ new Set([
5568
- "ECONNREFUSED",
5569
- "ECONNRESET",
5570
- "ENOTFOUND",
5571
- "EAI_AGAIN"
5572
- ]);
5573
- const TIMEOUT_ERROR_CODES = /* @__PURE__ */ new Set([
5574
- "ETIMEDOUT",
5575
- "ECONNABORTED",
5576
- "ESOCKETTIMEDOUT"
5577
- ]);
5578
- function findNetworkErrorCode(error, depth = 0) {
5579
- if (!error || typeof error !== "object" || depth > 4) return;
5580
- const candidate = error;
5581
- if (typeof candidate.code === "string" && (CONNECTION_ERROR_CODES.has(candidate.code) || TIMEOUT_ERROR_CODES.has(candidate.code))) return candidate.code;
5582
- return findNetworkErrorCode(candidate.original, depth + 1) ?? findNetworkErrorCode(candidate.cause, depth + 1);
5583
- }
5584
- /** Report whether a Slack call failed because its request deadline elapsed. */
5585
- function isSlackRequestTimeout(error) {
5586
- const networkCode = error instanceof SlackActionError ? error.networkCode : findNetworkErrorCode(error);
5587
- return networkCode !== void 0 && TIMEOUT_ERROR_CODES.has(networkCode);
5804
+ throw error;
5805
+ }
5806
+ return adaptSession$1(container, input);
5588
5807
  }
5589
- function hasSocketHangUpMessage(error) {
5590
- return error instanceof Error && error.message.toLowerCase().includes("socket hang up");
5808
+ /** Return a session for a named sandbox container. Start it if it stopped. */
5809
+ async function getSession(input) {
5810
+ return adaptSession$1(await getContainer(input.name, await egressCaPem(), input.scopeSignal), input);
5591
5811
  }
5592
- /**
5593
- * Classify a failed Slack call for retry: rate limits, Slack 5xx, and
5594
- * connection-phase failures are always retryable; timeouts are retried only
5595
- * for idempotent operations because Slack may already have accepted the
5596
- * request.
5597
- */
5598
- function classifySlackRetry(raw, mapped) {
5599
- if (mapped.code === "rate_limited") return "rate_limited";
5600
- if (mapped.statusCode !== void 0 && mapped.statusCode >= 500) return "server_error";
5601
- const networkCode = findNetworkErrorCode(raw);
5602
- if (networkCode && CONNECTION_ERROR_CODES.has(networkCode)) return "connection";
5603
- if (networkCode && TIMEOUT_ERROR_CODES.has(networkCode)) return "timeout";
5604
- if (hasSocketHangUpMessage(raw)) return "connection";
5605
- return "none";
5812
+ /** Create the persistent container that runs one Workspace snapshot build. */
5813
+ async function createWorkspaceSnapshotBuilder$1(input) {
5814
+ await createContainer({
5815
+ name: input.name,
5816
+ image: await ensureRuntimeImage(input.runtime, input.signal),
5817
+ timeoutMs: input.timeoutMs,
5818
+ persistent: true,
5819
+ vcpus: input.resources?.vcpus,
5820
+ signal: input.signal
5821
+ }, await egressCaPem());
5606
5822
  }
5607
5823
  /**
5608
- * Run a Slack Web API call with bounded retries so transient platform
5609
- * failures do not surface as turn failures, while non-idempotent posts are
5610
- * never re-sent when Slack may already have accepted them.
5824
+ * Return the container that runs one Workspace snapshot build.
5611
5825
  *
5612
- * Retry classes: rate limits (bounded Retry-After), connection-phase network
5613
- * failures, and Slack 5xx responses always retry; request timeouts retry only
5614
- * when the caller marks the operation `idempotent`.
5826
+ * A Docker snapshot is an image that does not depend on its builder. So
5827
+ * `snapshot()` removes the builder right after the commit, and the image tag
5828
+ * keeps the builder's name. Deleting the builder later removes that tag.
5615
5829
  */
5616
- async function withSlackRetries(task, maxAttempts = 3, context = {}) {
5617
- let attempt = 0;
5618
- let totalDelayMs = 0;
5619
- const action = context.action ?? "unknown";
5620
- while (attempt < maxAttempts) {
5621
- attempt += 1;
5622
- const attemptNumber = attempt;
5623
- try {
5624
- return await withSpan(`POST slack.com/api/${action}`, "http.client", {}, async () => {
5625
- try {
5626
- return await task();
5627
- } catch (error) {
5628
- const mapped = mapSlackError(error);
5629
- const errorAttrs = { "error.type": mapped.code };
5630
- if (mapped.apiError) errorAttrs["app.slack.api_error_code"] = mapped.apiError;
5631
- if (mapped.code === "rate_limited") {
5632
- errorAttrs["http.response.status_code"] = 429;
5633
- if (mapped.retryAfterSeconds) errorAttrs["app.slack.retry_after_ms"] = mapped.retryAfterSeconds * 1e3;
5634
- } else if (mapped.statusCode != null) errorAttrs["http.response.status_code"] = mapped.statusCode;
5635
- setSpanAttributes(errorAttrs);
5636
- throw error;
5637
- }
5638
- }, {
5639
- "http.request.method": "POST",
5640
- "server.address": "slack.com",
5641
- "url.scheme": "https",
5642
- "url.path": `/api/${action}`,
5643
- "app.slack.method": action,
5644
- "app.retry.max_attempts": maxAttempts,
5645
- ...attemptNumber > 1 ? { "http.request.resend_count": attemptNumber - 1 } : void 0,
5646
- ...context.attributes ?? {},
5647
- ...context.spanAttributes ?? {}
5648
- });
5649
- } catch (error) {
5650
- const mapped = mapSlackError(error);
5651
- const retryClass = classifySlackRetry(error, mapped);
5652
- const isRetryable = retryClass === "rate_limited" || retryClass === "connection" || retryClass === "server_error" || retryClass === "timeout" && context.idempotent === true;
5653
- const remainingDelayBudgetMs = MAX_TOTAL_RETRY_DELAY_MS - totalDelayMs;
5654
- const baseLogAttributes = {
5655
- "app.slack.action": action,
5656
- "app.slack.error_code": mapped.code,
5657
- ...mapped.apiError ? { "app.slack.api_error": mapped.apiError } : void 0,
5658
- ...mapped.detail ? { "app.slack.detail": mapped.detail } : void 0,
5659
- ...mapped.detailLine !== void 0 ? { "app.slack.detail_line": mapped.detailLine } : void 0,
5660
- ...mapped.detailRule ? { "app.slack.detail_rule": mapped.detailRule } : void 0,
5661
- ...mapped.requestId ? { "app.slack.request_id": mapped.requestId } : void 0,
5662
- ...mapped.statusCode !== void 0 ? { "http.response.status_code": mapped.statusCode } : void 0,
5663
- ...context.attributes ?? {}
5664
- };
5665
- if (!isRetryable || attempt >= maxAttempts || remainingDelayBudgetMs <= 0) {
5666
- if (context.expectedErrorCodes?.includes(mapped.code)) throw mapped;
5667
- logWarn("slack.action.failed", {
5668
- ...baseLogAttributes,
5669
- ...mapped.errorData ? { "app.slack.error_data": mapped.errorData } : void 0
5670
- });
5671
- throw mapped;
5672
- }
5673
- logWarn("slack.action.retrying", {
5674
- ...baseLogAttributes,
5675
- "app.slack.retry_attempt": attempt,
5676
- "app.slack.retry_class": retryClass
5677
- });
5678
- const retryAfterMs = retryClass === "rate_limited" && mapped.retryAfterSeconds && mapped.retryAfterSeconds > 0 ? mapped.retryAfterSeconds * 1e3 : void 0;
5679
- const backoffMs = Math.min(2e3, 250 * 2 ** (attempt - 1));
5680
- const delayMs = Math.min(retryAfterMs ?? backoffMs, MAX_RETRY_DELAY_MS, remainingDelayBudgetMs);
5681
- totalDelayMs += delayMs;
5682
- await sleep$2(delayMs);
5830
+ async function getWorkspaceSnapshotBuilder$1(name, signal) {
5831
+ const container = await getContainer(name, await egressCaPem(), signal);
5832
+ return {
5833
+ session: () => adaptSession$1(container),
5834
+ startDetachedCommand: (input) => startDetachedCommand(container.id, input),
5835
+ async getCommand(commandId) {
5836
+ return { wait: ({ signal: waitSignal }) => waitForDetachedCommand(container.id, commandId, waitSignal) };
5837
+ },
5838
+ async snapshot(options) {
5839
+ const snapshotId = await commitSnapshot(container.id, name, options?.signal);
5840
+ await removeContainer(name);
5841
+ return { snapshotId };
5683
5842
  }
5843
+ };
5844
+ }
5845
+ async function deleteSnapshotTag(name) {
5846
+ try {
5847
+ await dockerRequest({
5848
+ method: "DELETE",
5849
+ path: `/images/${encodeURIComponent(`${SNAPSHOT_REPOSITORY}:${name}`)}`,
5850
+ query: { force: true }
5851
+ });
5852
+ } catch (error) {
5853
+ if (!(error instanceof DockerApiError && error.statusCode === 404)) throw error;
5684
5854
  }
5685
- throw new SlackActionError("Slack action exhausted retries", "internal_error");
5686
5855
  }
5687
5856
  /**
5688
- * Slack Web API client for the current destination workspace: the ambient
5689
- * installation token when one is bound, otherwise the env bot token for
5690
- * single-workspace deployments. Fails instead of falling back when the call
5691
- * is workspace-scoped and no installation token can be resolved, so a write
5692
- * never goes out with another workspace's credentials.
5857
+ * Remove Workspace builders and the snapshot images tagged with their names.
5858
+ *
5859
+ * Shared snapshot code calls this when a Workspace snapshot is no longer
5860
+ * used. Each name is tried, and the first failure is thrown at the end.
5693
5861
  */
5694
- function getSlackClient(options) {
5695
- if (options) return new WebClient(resolveSlackToken(), {
5696
- retryConfig: { retries: 0 },
5697
- rejectRateLimitedCalls: true,
5698
- timeout: options.timeoutMs
5699
- });
5700
- return getClient();
5862
+ async function deleteWorkspaceSnapshotBuilders$1(names) {
5863
+ const failures = [];
5864
+ for (const name of new Set(names)) for (const remove of [removeContainer, deleteSnapshotTag]) try {
5865
+ await remove(name);
5866
+ } catch (error) {
5867
+ failures.push(error);
5868
+ }
5869
+ if (failures.length > 0) throw failures[0];
5701
5870
  }
5871
+ const DOCKER_SNAPSHOT_PACKAGES = /* @__PURE__ */ new Set([
5872
+ "spal-release",
5873
+ "ripgrep",
5874
+ "gh",
5875
+ "jq"
5876
+ ]);
5702
5877
  /**
5703
- * Slack channel ID prefixes:
5704
- * - C: channel — modern private channels also use C, so the prefix never
5705
- * proves a channel is public
5706
- * - G: legacy private channel / group DM
5707
- * - D: direct message (1:1)
5878
+ * Keep only the small Docker base from the declared runtime dependencies.
5879
+ *
5880
+ * Postinstall commands are skipped, because they often download large tools.
5881
+ * A base package that no plugin declares is not installed.
5708
5882
  */
5709
- function isDmChannel(channelId) {
5710
- const normalized = normalizeSlackConversationId(channelId);
5711
- return Boolean(normalized && normalized.startsWith("D"));
5883
+ function selectSnapshotRuntime(runtime) {
5884
+ return {
5885
+ dependencies: runtime.dependencies.filter((dependency) => "package" in dependency && DOCKER_SNAPSHOT_PACKAGES.has(dependency.package)),
5886
+ postinstall: []
5887
+ };
5712
5888
  }
5889
+ /** Local Docker implementation of the sandbox provider contract. */
5890
+ const dockerSandboxProvider = {
5891
+ errors: dockerSandboxErrors,
5892
+ createSession,
5893
+ getSession,
5894
+ createWorkspaceSnapshotBuilder: createWorkspaceSnapshotBuilder$1,
5895
+ getWorkspaceSnapshotBuilder: getWorkspaceSnapshotBuilder$1,
5896
+ deleteWorkspaceSnapshotBuilders: deleteWorkspaceSnapshotBuilders$1,
5897
+ selectSnapshotRuntime
5898
+ };
5899
+ // src/chat/sandbox/vercel/credentials.ts
5713
5900
  /**
5714
- * Conversation-scoped Slack contexts backed by a concrete conversation ID.
5715
- * Includes channels/groups/DMs (C/G/D).
5901
+ * Resolve explicit Vercel Sandbox credentials, or return undefined to let
5902
+ * the SDK read ambient Vercel auth from its own environment detection.
5716
5903
  */
5717
- function isConversationScopedChannel(channelId) {
5718
- const normalized = normalizeSlackConversationId(channelId);
5719
- if (!normalized) return false;
5720
- return normalized.startsWith("C") || normalized.startsWith("G") || normalized.startsWith("D");
5721
- }
5722
- function isConversationChannel(channelId) {
5723
- const normalized = normalizeSlackConversationId(channelId);
5724
- if (!normalized) return false;
5725
- return normalized.startsWith("C") || normalized.startsWith("G");
5726
- }
5727
- async function getFilePermalink(fileId) {
5728
- const client = getClient();
5729
- return (await withSlackRetries(() => client.files.info({ file: fileId }), 3, {
5730
- action: "files.info",
5731
- idempotent: true,
5732
- spanAttributes: { "app.slack.file_id": fileId }
5733
- })).file?.permalink;
5734
- }
5735
- async function downloadPrivateSlackFile(url) {
5736
- const token = resolveSlackToken();
5737
- const response = await fetch(url, { headers: { Authorization: `Bearer ${token}` } });
5738
- if (!response.ok) throw new Error(`Slack file download failed: ${response.status}`);
5739
- return Buffer.from(await response.arrayBuffer());
5904
+ function getVercelSandboxCredentials() {
5905
+ const token = toOptionalTrimmed(process.env.VERCEL_TOKEN);
5906
+ const teamId = toOptionalTrimmed(process.env.VERCEL_TEAM_ID);
5907
+ const projectId = toOptionalTrimmed(process.env.VERCEL_PROJECT_ID);
5908
+ if (token && teamId && projectId) return {
5909
+ token,
5910
+ teamId,
5911
+ projectId
5912
+ };
5740
5913
  }
5741
5914
  // src/chat/slack/post-warning.ts
5742
5915
  const codes = /* @__PURE__ */ new Set([
@@ -6192,7 +6365,13 @@ function readExistingSlackAngleToken(line, start) {
6192
6365
  const close = line.indexOf(">", start + 1);
6193
6366
  if (close === -1) return;
6194
6367
  const body = line.slice(start + 1, close);
6195
- if (/^(?:https?:\/\/|@|#|!)/.test(body)) return {
6368
+ if ([
6369
+ "https://",
6370
+ "http://",
6371
+ "@",
6372
+ "#",
6373
+ "!"
6374
+ ].some((prefix) => body.startsWith(prefix))) return {
6196
6375
  text: line.slice(start, close + 1),
6197
6376
  end: close + 1
6198
6377
  };
@@ -6232,7 +6411,8 @@ function readBareUrl(line, start) {
6232
6411
  };
6233
6412
  const shouldPeel = () => raw.endsWith("_") || /[.,!?;:]$/.test(raw) || raw.endsWith(")") && hasUnmatchedClosingParen(raw);
6234
6413
  while (raw.length > 0 && shouldPeel()) peel();
6235
- if (!/^https?:\/\/.+/.test(raw)) return;
6414
+ const scheme = ["https://", "http://"].find((prefix) => raw.startsWith(prefix));
6415
+ if (!scheme || raw.length === scheme.length) return;
6236
6416
  return {
6237
6417
  url: raw,
6238
6418
  suffix,
@@ -6253,7 +6433,7 @@ function readBareSlackUserMention(line, start) {
6253
6433
  * Wrap bare http(s) URLs and bare `@U123` Slack user IDs on a single line as
6254
6434
  * Slack explicit `<url>` links and `<@U123>` mentions.
6255
6435
  */
6256
- function wrapBareReferencesOnLine(line) {
6436
+ function wrapBareReferencesOnLine(line, urls) {
6257
6437
  let result = "";
6258
6438
  let i = 0;
6259
6439
  while (i < line.length) {
@@ -6281,7 +6461,7 @@ function wrapBareReferencesOnLine(line) {
6281
6461
  i = userMention.end;
6282
6462
  continue;
6283
6463
  }
6284
- if (line.startsWith("https://", i) || line.startsWith("http://", i)) {
6464
+ if (urls && (line.startsWith("https://", i) || line.startsWith("http://", i))) {
6285
6465
  const parsed = readBareUrl(line, i);
6286
6466
  if (parsed) {
6287
6467
  result += `<${parsed.url}>${parsed.suffix}`;
@@ -6298,12 +6478,13 @@ function wrapBareReferencesOnLine(line) {
6298
6478
  * Pre-wrap bare http(s) URLs outside fenced code blocks as Slack explicit
6299
6479
  * links, preventing Slack's auto-linker from consuming adjacent formatting
6300
6480
  * markers into the URL. Bare `@U123` user IDs become `<@U123>` mentions,
6301
- * because Slack shows a bare ID as literal text.
6481
+ * because Slack shows a bare ID as literal text. Pass `urls: false` to wrap
6482
+ * only the user IDs.
6302
6483
  *
6303
6484
  * Uses the same fence-toggle rule as `ensureBlockSpacing` so both passes
6304
6485
  * agree on which lines are code.
6305
6486
  */
6306
- function wrapBareReferences(text) {
6487
+ function wrapBareReferences(text, urls = true) {
6307
6488
  const lines = text.split("\n");
6308
6489
  const out = [];
6309
6490
  let inCodeBlock = false;
@@ -6313,10 +6494,18 @@ function wrapBareReferences(text) {
6313
6494
  out.push(line);
6314
6495
  continue;
6315
6496
  }
6316
- out.push(inCodeBlock ? line : wrapBareReferencesOnLine(line));
6497
+ out.push(inCodeBlock ? line : wrapBareReferencesOnLine(line, urls));
6317
6498
  }
6318
6499
  return out.join("\n");
6319
6500
  }
6501
+ /**
6502
+ * Wrap bare `@U123` Slack user IDs as `<@U123>` mentions. Call it before
6503
+ * plugin Markdown rewrites of chat text, so a plugin does not read `@U123`
6504
+ * as an account name of its provider.
6505
+ */
6506
+ function wrapBareSlackUserIds(text) {
6507
+ return wrapBareReferences(text, false);
6508
+ }
6320
6509
  const LIST_ITEM_PATTERN = /^[-*•]\s|^\d+\.\s/;
6321
6510
  /**
6322
6511
  * Turn a follow-up paragraph inside a list item into a bullet at the same
@@ -6372,13 +6561,14 @@ function ensureBlockSpacing(text) {
6372
6561
  * Normalize model-authored Slack markdown for delivery via `markdown_text`
6373
6562
  * or `{ type: "markdown" }` blocks.
6374
6563
  *
6375
- * Plugins may first rewrite ordinary Markdown. Core then applies Slack-only
6564
+ * Plugins may first rewrite ordinary Markdown with the Conversation facts in
6565
+ * `format`. Core then applies Slack-only
6376
6566
  * delivery shaping: bare URL wrapping, block spacing, and list follow-up
6377
6567
  * paragraph bullets. Slack reply delivery owns chunking and continuation
6378
6568
  * markers separately.
6379
6569
  */
6380
- function normalizeSlackReplyMarkdown(text) {
6381
- let normalized = applyPluginFormatMarkdown(text).replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "");
6570
+ function normalizeSlackReplyMarkdown(text, format) {
6571
+ let normalized = applyPluginFormatMarkdown(wrapBareSlackUserIds(text), format).replace(/\r\n?/g, "\n").replace(/[ \t]+$/gm, "");
6382
6572
  normalized = wrapBareReferences(normalized);
6383
6573
  normalized = ensureBlockSpacing(normalized);
6384
6574
  normalized = bulletListFollowUpParagraphs(normalized);
@@ -6908,19 +7098,25 @@ const vercelSandboxErrors = {
6908
7098
  isCommandStreamInterrupted
6909
7099
  };
6910
7100
  // src/chat/sandbox/vercel/provider.ts
6911
- function credentialOptions() {
6912
- return getVercelSandboxCredentials() ?? {};
6913
- }
6914
- /** Bind one abort signal to every API request made by a Sandbox client. */
6915
- function scopedFetchOptions(signal) {
6916
- if (!signal) return {};
6917
- return { fetch: (input, init) => {
7101
+ /**
7102
+ * Sandbox client options. Since 4.0, a client without `fetch` uses the SDK's
7103
+ * own undici `fetch` and skips process-level `fetch` replacements, such as the
7104
+ * eval proxy. So every request reads `globalThis.fetch` when it starts, and
7105
+ * the scope signal, when there is one, can abort it.
7106
+ */
7107
+ function clientOptions(signal) {
7108
+ const fetch = (input, init) => {
7109
+ if (!signal) return globalThis.fetch(input, init);
6918
7110
  const requestSignal = init?.signal ?? (input instanceof Request ? input.signal : void 0);
6919
7111
  return globalThis.fetch(input, {
6920
7112
  ...init,
6921
7113
  signal: requestSignal ? AbortSignal.any([requestSignal, signal]) : signal
6922
7114
  });
6923
- } };
7115
+ };
7116
+ return {
7117
+ ...getVercelSandboxCredentials(),
7118
+ fetch
7119
+ };
6924
7120
  }
6925
7121
  /** Pin Junior's sandbox contract to one Vercel session without SDK replay. */
6926
7122
  function adaptSession(sandbox, options) {
@@ -6993,8 +7189,7 @@ async function createSandboxSession(input) {
6993
7189
  ...input.networkPolicy ? { networkPolicy: toVercelNetworkPolicy(input.networkPolicy) } : void 0,
6994
7190
  ...input.resources ? { resources: input.resources } : void 0,
6995
7191
  ...input.signal ? { signal: input.signal } : void 0,
6996
- ...credentialOptions(),
6997
- ...scopedFetchOptions(input.scopeSignal)
7192
+ ...clientOptions(input.scopeSignal)
6998
7193
  };
6999
7194
  return adaptSession(await Sandbox.create(input.snapshotId ? {
7000
7195
  ...shared,
@@ -7012,8 +7207,7 @@ async function getSandboxSession(input) {
7012
7207
  return adaptSession(await Sandbox.get({
7013
7208
  name: input.name,
7014
7209
  resume: true,
7015
- ...credentialOptions(),
7016
- ...scopedFetchOptions(input.scopeSignal)
7210
+ ...clientOptions(input.scopeSignal)
7017
7211
  }), input);
7018
7212
  }
7019
7213
  /** Create the named, persistent Sandbox that owns one Workspace snapshot build. */
@@ -7024,7 +7218,7 @@ async function createWorkspaceSnapshotBuilder(input) {
7024
7218
  timeout: input.timeoutMs,
7025
7219
  runtime: input.runtime,
7026
7220
  signal: input.signal,
7027
- ...credentialOptions(),
7221
+ ...clientOptions(),
7028
7222
  ...input.resources ? { resources: input.resources } : void 0
7029
7223
  });
7030
7224
  }
@@ -7034,7 +7228,7 @@ async function getWorkspaceSnapshotBuilder(name, signal) {
7034
7228
  name,
7035
7229
  resume: true,
7036
7230
  signal,
7037
- ...credentialOptions()
7231
+ ...clientOptions()
7038
7232
  });
7039
7233
  return {
7040
7234
  session: () => adaptSession(sandbox),
@@ -7062,7 +7256,7 @@ async function deleteWorkspaceSnapshotBuilders(names) {
7062
7256
  await (await Sandbox.get({
7063
7257
  name,
7064
7258
  resume: false,
7065
- ...credentialOptions()
7259
+ ...clientOptions()
7066
7260
  })).delete();
7067
7261
  } catch (error) {
7068
7262
  if (!vercelSandboxErrors.isMissing(error)) {
@@ -7823,7 +8017,7 @@ function createPluginState(plugin, adapter) {
7823
8017
  // src/chat/dashboard-link.ts
7824
8018
  let dashboardConversationLinkOptions;
7825
8019
  function withHttps(host) {
7826
- return /^https?:\/\//.test(host) ? host : `https://${host}`;
8020
+ return host.startsWith("https://") || host.startsWith("http://") ? host : `https://${host}`;
7827
8021
  }
7828
8022
  function stripTrailingSlashes(value) {
7829
8023
  let end = value.length;
@@ -7859,6 +8053,17 @@ function resolveDashboardPath(segmentPath) {
7859
8053
  function getDashboardConversationLink(conversationId) {
7860
8054
  return resolveDashboardPath(`/conversations/${encodeURIComponent(conversationId)}`);
7861
8055
  }
8056
+ /**
8057
+ * Return whether a URL is under the core dashboard base path. Other pages on
8058
+ * the same host are not Junior's.
8059
+ */
8060
+ function isDashboardLink(url) {
8061
+ const root = resolveDashboardPath("/");
8062
+ if (!root) return false;
8063
+ const base = new URL(root);
8064
+ const prefix = base.pathname.endsWith("/") ? base.pathname : `${base.pathname}/`;
8065
+ return url.origin === base.origin && (url.pathname.startsWith(prefix) || `${url.pathname}/` === prefix);
8066
+ }
7862
8067
  /** Build the dashboard settings URL when the core dashboard is enabled. */
7863
8068
  function getDashboardSettingsLink() {
7864
8069
  return resolveDashboardPath("/settings");
@@ -9491,11 +9696,11 @@ const PUSH_TIMEOUT_MS = 1e4;
9491
9696
  function subjectFromBaseUrl() {
9492
9697
  const baseUrl = process.env.JUNIOR_BASE_URL?.trim();
9493
9698
  if (!baseUrl) return void 0;
9494
- return /^https?:\/\//.test(baseUrl) ? baseUrl : `https://${baseUrl}`;
9699
+ return baseUrl.startsWith("https://") || baseUrl.startsWith("http://") ? baseUrl : `https://${baseUrl}`;
9495
9700
  }
9496
9701
  /** Web Push accepts only an `https:` or `mailto:` VAPID subject. */
9497
9702
  function isVapidSubject(subject) {
9498
- return /^(https:\/\/|mailto:)/.test(subject);
9703
+ return subject.startsWith("https://") || subject.startsWith("mailto:");
9499
9704
  }
9500
9705
  /**
9501
9706
  * Read VAPID settings from the environment. Push notifications are off when
@@ -9931,13 +10136,25 @@ function getPlugins() {
9931
10136
  return [...registeredPlugins];
9932
10137
  }
9933
10138
  /** Apply plugin Markdown rewrites before destination delivery formatting. */
9934
- function applyPluginFormatMarkdown(text) {
10139
+ function applyPluginFormatMarkdown(text, format = {}) {
10140
+ const resolved = {
10141
+ ...getConfigDefaults(),
10142
+ ...format.configuration
10143
+ };
10144
+ const platform = format.platform ?? "slack";
10145
+ const mention = ({ provider, handle }) => platform === "slack" ? format.mentions?.get(`${provider}:${handle}`.toLowerCase()) : void 0;
9935
10146
  let transformed = text;
9936
10147
  for (const plugin of getPlugins()) {
9937
10148
  const hook = plugin.hooks?.formatMarkdown;
9938
10149
  if (!hook) continue;
9939
10150
  try {
9940
- const next = hook({ text: transformed });
10151
+ const next = hook({
10152
+ config: pluginConfigValues(plugin.manifest.name, resolved),
10153
+ mention,
10154
+ platform,
10155
+ ...format.provider ? { provider: format.provider } : void 0,
10156
+ text: transformed
10157
+ });
9941
10158
  if (typeof next === "string") transformed = next;
9942
10159
  } catch (error) {
9943
10160
  logWarn("plugin.format_markdown.hook.failed", {
@@ -10129,7 +10346,8 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
10129
10346
  } } : void 0,
10130
10347
  ...resolved?.user ? { userId: resolved.user.id } : void 0
10131
10348
  });
10132
- }
10349
+ },
10350
+ replaceSlackMentions
10133
10351
  },
10134
10352
  workspaces: {
10135
10353
  async active() {
@@ -13539,6 +13757,7 @@ async function recordConversationRetry(args) {
13539
13757
  if (!current || current.execution.lease?.token !== args.leaseToken) return "lost_lease";
13540
13758
  const count = (current.execution.retryCount ?? 0) + 1;
13541
13759
  const stopped = count >= 5;
13760
+ if (stopped) await args.beforeWorkStops?.(args.conversationId, current.execution.inboundMessageIds);
13542
13761
  await writeConversation(state, lock, withExecutionUpdate(current, {
13543
13762
  ...current.execution,
13544
13763
  lastEnqueuedAtMs: void 0,
@@ -13762,9 +13981,11 @@ function isFinishedTurnState(state) {
13762
13981
  }
13763
13982
  /** A running or paused write reached a Turn that already finished. */
13764
13983
  var TurnAlreadyFinishedError = class extends Error {
13984
+ state;
13765
13985
  constructor(turnId, state) {
13766
13986
  super(`Turn ${turnId} already finished as ${state}`);
13767
13987
  this.name = "TurnAlreadyFinishedError";
13988
+ this.state = state;
13768
13989
  }
13769
13990
  };
13770
13991
  const turnStatusSchema = z.enum([
@@ -14075,6 +14296,19 @@ async function setStoredRecord(args) {
14075
14296
  * version it loaded, preventing stale resume callbacks from winning.
14076
14297
  */
14077
14298
  async function updateTurnState(args) {
14299
+ return await withSpan("turn.state.finish", "turn.state.finish", {}, async (setSpanAttributes) => {
14300
+ const updated = await writeTurnState(args);
14301
+ setSpanAttributes({ "app.turn.state.written": updated !== void 0 });
14302
+ return updated;
14303
+ }, {
14304
+ "app.turn.state": args.state,
14305
+ "app.turn.previous_state": args.existing.state,
14306
+ "app.turn.resume_reason": args.existing.resumeReason,
14307
+ "app.turn.slice_id": args.existing.sliceId,
14308
+ "app.turn.error_message": args.errorMessage
14309
+ });
14310
+ }
14311
+ async function writeTurnState(args) {
14078
14312
  const parsed = await getStoredTurnRecord(args.existing.conversationId, args.existing.turnId);
14079
14313
  if (!parsed || parsed.version !== args.existing.version) return;
14080
14314
  return await setStoredRecord({
@@ -14365,9 +14599,9 @@ async function loadTurnCheckpoint(args) {
14365
14599
  }
14366
14600
  async function saveTurnCheckpoint(args) {
14367
14601
  const traceContext = getActiveTraceContext();
14368
- return await withSpan("turn.checkpoint.save", "turn.checkpoint.save", {}, async () => {
14369
- if (args.mode === "running") return await saveRunning(args, traceContext);
14370
- if (args.mode === "paused") return await savePaused(args, traceContext);
14602
+ return await withSpan("turn.checkpoint.save", "turn.checkpoint.save", {}, async (setSpanAttributes) => {
14603
+ if (args.mode === "running") return await saveRunning(args, traceContext, setSpanAttributes);
14604
+ if (args.mode === "paused") return await savePaused(args, traceContext, setSpanAttributes);
14371
14605
  await saveDone(args, traceContext);
14372
14606
  }, { "app.turn.checkpoint.mode": args.mode });
14373
14607
  }
@@ -14392,7 +14626,7 @@ function sharedWrite(args, traceContext, latest) {
14392
14626
  })
14393
14627
  };
14394
14628
  }
14395
- async function saveRunning(args, traceContext) {
14629
+ async function saveRunning(args, traceContext, setSpanAttributes) {
14396
14630
  if (args.messages.length === 0 || !isContinuablePiBoundary(args.messages)) return;
14397
14631
  try {
14398
14632
  const latest = await getTurnRecord(args.conversationId, args.turnId);
@@ -14410,7 +14644,12 @@ async function saveRunning(args, traceContext) {
14410
14644
  state: "running"
14411
14645
  });
14412
14646
  } catch (error) {
14413
- if (!(error instanceof AgentHistoryBranchError) && !(error instanceof TurnAlreadyFinishedError)) logException(error, "agent.turn.checkpoint.running.failed", {
14647
+ if (error instanceof TurnAlreadyFinishedError) setSpanAttributes({
14648
+ "app.turn.checkpoint.rejected": error.name,
14649
+ "app.turn.previous_state": error.state
14650
+ });
14651
+ else if (error instanceof AgentHistoryBranchError) setSpanAttributes({ "app.turn.checkpoint.rejected": error.name });
14652
+ else logException(error, "agent.turn.checkpoint.running.failed", {
14414
14653
  "app.ai.resume_conversation_id": args.conversationId,
14415
14654
  "app.ai.resume_session_id": args.turnId,
14416
14655
  "app.ai.resume_slice_id": args.sliceId
@@ -14418,7 +14657,7 @@ async function saveRunning(args, traceContext) {
14418
14657
  return;
14419
14658
  }
14420
14659
  }
14421
- async function savePaused(args, traceContext) {
14660
+ async function savePaused(args, traceContext, setSpanAttributes) {
14422
14661
  const keepSlice = args.reason === "yield";
14423
14662
  const nextSliceId = keepSlice ? args.sliceId : args.sliceId + 1;
14424
14663
  try {
@@ -14456,7 +14695,13 @@ async function savePaused(args, traceContext) {
14456
14695
  });
14457
14696
  } catch (error) {
14458
14697
  if (error instanceof TurnSliceLimitExceededError) throw error;
14459
- if (error instanceof TurnAlreadyFinishedError) return;
14698
+ if (error instanceof TurnAlreadyFinishedError) {
14699
+ setSpanAttributes({
14700
+ "app.turn.checkpoint.rejected": error.name,
14701
+ "app.turn.previous_state": error.state
14702
+ });
14703
+ return;
14704
+ }
14460
14705
  logException(error, "agent.turn.checkpoint.paused.failed", {
14461
14706
  "app.ai.resume_conversation_id": args.conversationId,
14462
14707
  "app.ai.resume_session_id": args.turnId,
@@ -14761,11 +15006,6 @@ const CONVERSATION_TITLE_SYSTEM_ACTOR = {
14761
15006
  platform: "system",
14762
15007
  name: "conversation-title"
14763
15008
  };
14764
- /** Pick one plugin's string config values and drop the plugin name prefix. */
14765
- function pluginConfig(pluginName, configuration) {
14766
- const prefix = `${pluginName}.`;
14767
- return Object.fromEntries(Object.entries(configuration).flatMap(([key, value]) => key.startsWith(prefix) && typeof value === "string" ? [[key.slice(prefix.length), value]] : []));
14768
- }
14769
15009
  /**
14770
15010
  * Collect plugin facts, such as linked issue titles, for one new
14771
15011
  * Conversation title. `configuration` holds config values by full key.
@@ -14786,7 +15026,7 @@ async function getPluginConversationTitleContext(args) {
14786
15026
  if (!hook) return [];
14787
15027
  try {
14788
15028
  const lines = await Promise.race([hook({
14789
- config: pluginConfig(plugin.manifest.name, args.configuration),
15029
+ config: pluginConfigValues(plugin.manifest.name, args.configuration),
14790
15030
  db: getDb(),
14791
15031
  egress,
14792
15032
  log: createPluginLogger(plugin.manifest.name),
@@ -15874,4 +16114,4 @@ async function recordGuardianActionReviewed(args) {
15874
16114
  createdAtMs: Date.now()
15875
16115
  }]);
15876
16116
  }
15877
- export { loadTurnCheckpoint as $, consumeSandboxEgressAuthRequiredSignal as $a, hash as $i, webActorUserIds as $n, readAttachmentVisionSummary as $o, activeParticipantUserIds as $r, TurnSliceLimitExceededError as $t, latestConversationMessageSeq as A, slackExternalRefIdSchema as Aa, getDashboardObjectIconLink as Ai, isStandaloneRuntimeContextMessage as An, canAddConversationMessages as Ao, dismissOpenReviewItems as Ar, getConversationWorkStates as At, getAgentContextInputLimitTokens as B, runWithSlackInstallationToken as Ba, createWorkspace as Bi, SCRIPT_TOOLS_SECTION_TAG as Bn, readConversationBriefThrough as Bo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Br, recordConversationRetry as Bt, settleConversationTitleWork as C, postSlackEphemeralMessage as Ca, verifyEventAutomationCredentialSubject as Ci, getTerminalAssistantMessages as Cn, sandboxSkillPathResolution as Co, saveNotificationSchedule as Cr, countPendingConversationMessages as Ct, estimateConversationMessagesTokens as D, updateSlackMessage as Da, JUNIOR_THREAD_STATE_TTL_MS as Di, instructionTextForProjection as Dn, createPluginModelCostRecorder as Do, REVIEW_ITEM_REPLIED_REASON as Dr, dropPendingMessages as Dt, buildConversationContext as E, unfurlSlackLinks as Ea, verifyTimerWatchCredentialSubject as Ei, hasTurnInput as En, runNonInteractiveCommand as Eo, projectConversationMessages as Er, drainConversationMailbox as Et, turnHasReply as F, getSlackClient as Fa, parseDashboardConversationLink as Fi, retainRuntimeTurnContext as Fn, conversationIsNotUnsubscribedRoot as Fo, listWaitingConversations as Fr, listActiveConversationIds as Ft, AuthPausePersistenceError as G, isAlreadyExistsError as Ga, listWorkspacesByRepository as Gi, readParentAgentTask as Gn, readConversationLastEventSeq as Go, isOnlyAssignee as Gr, startConversationWork as Gt, PluginCredentialFailureError as H, getWorkspaceTeamId as Ha, getWorkspace as Hi, TURN_CONTEXT_TAG as Hn, readConversationEventPage as Ho, canAgentChangeReviewItem as Hr, releaseInboundMessage as Ht, upsertConversationMessage as I, isConversationScopedChannel as Ia, parseDashboardPersonLink as Ii, stripRuntimeTurnContext as In, conversationPinnedForUser as Io, reviewItemsNeedingUserVersionQuery as Ir, markConversationWorkEnqueued as It, abandonReplacedPendingAuth as J, WorkspaceSnapshotNotReadyError as Ja, invalidateReadySnapshot as Ji, renderUntrustedTag as Jn, FORK_INSTRUCTIONS as Jo, requireReviewItemLinks as Jr, takeDeferredConversationMove as Jt, AuthorizationFlowDisabledError as K, throwSandboxOperationError as Ka, updateWorkspace as Ki, renderChildTag as Kn, readConversationMessageEventSeq as Ko, readReviewItemAgentScope as Kr, steerWebPendingMessages as Kt, calculateContextCompactionTargetTokens as L, isDmChannel as La, setDashboardConversationLinkOptions as Li, trimTrailingAssistantMessages as Ln, conversationViewerMarks as Lo, searchReviewItems as Lr, moveIdleConversationDestination as Lt, normalizeConversationText as M, downloadPrivateSlackFile as Ma, getDashboardReviewItemLink as Mi, isToolResultMessage as Mn, readConversationAccessFromSql as Mo, getReviewItem as Mr, hasRunnableConversationWork as Mt, recordDeliveredAssistantMessage as N, getFilePermalink as Na, getDashboardSettingsLink as Ni, latestTurnContextSection as Nn, conversationHasParticipantUser as No, insertReviewItem as Nr, isFinalAttempt as Nt, getConversationMessageSlackTs as O, uploadFilesToConversation as Oa, getDashboardConversationLink as Oi, isAssistantMessage as On, createPluginLogger as Oo, closeReviewItem as Or, getConversation as Ot, trimConversationMessages as P, getHeaderString as Pa, getDashboardTaskLink as Pi, normalizeToolNameFromResult as Pn, conversationIsMemberRoot as Po, listReplyActionItems as Pr, isInvalidConversationRecordError as Pt, continuableMessages as Q, clearSandboxEgressSignals as Qa, create as Qi, findLegacyWebActorUserId as Qn, matchSlackAttachments as Qo, EVERYONE_ASSIGNEE as Qr, TurnBudgetExceededError as Qt, getAgentBackgroundCompactionMarkTokens as R, isSlackRequestTimeout as Ra, createPluginState as Ri, CAPABILITY_SECTION_TAG as Rn, viewerMarksFromParticipant as Ro, takeReviewItem as Rr, pruneActiveConversation as Rt, resolveConversationTitle as S, openSlackModal as Sa, bindSlackDirectCredentialSubject as Si, getPiMessageRole as Sn, sandboxSkillFile as So, readNotificationSchedule as Sr, completeConversationWork as St, resolveTaskTitle as T, removeReactionFromMessage as Ta, verifySlackDirectCredentialSubject as Ti, hasRuntimeTurnContext as Tn, buildNonInteractiveShellScript as To, isPausedBySlack as Tr, deferConversationMove as Tt, createPluginAuthOrchestration as U, runWithWorkspaceTeamId as Ua, getWorkspaceByName as Ui, escapeClosingTags as Un, readConversationEventPageAfter as Uo, canReadReviewItem as Ur, requestAnotherSlice as Ut, createPluginEgress as V, withSlackRetries as Va, deleteWorkspace as Vi, SESSION_CONTEXT_SECTION_TAG as Vn, readLatestConversationBrief as Vo, canActOnReviewItem as Vr, releaseConversationWork as Vt, authorizationId as W, isAbortError as Wa, listWorkspaces as Wi, escapeTagText as Wn, readConversationEventPageAround as Wo, canUserReadReviewItem as Wr, requestConversationWork as Wt, clearPendingAuth as X, isWorkspaceSnapshotNotReadyError as Xa, setWorkspaceSnapshot as Xi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Xn, notInheritedByForkChild as Xo, reviewItemReaderForUser as Xr, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Xt, canReusePendingAuthLink as Y, getWorkspaceSnapshotNotReadyError as Ya, loadSnapshotsForProfile as Yi, tagJson as Yn, loadForkHistory as Yo, reviewItemNeedsSomeone as Yr, readInboundMessageSender as Yt, getConversationPendingAuth as Z, workspaceSnapshotNotReadyUserMessage as Za, setWorkspaceSnapshotBuild as Zi, createUserTokenStore as Zn, getSlackFileId as Zo, reviewItemReaderForUserInConversation as Zr, TURN_LIMIT_WRAP_UP_MESSAGE as Zt, appendConversationMessages as _, truncateStatusText as _a, getWatch as _i, CODE_MODE_CALL_STATUS_TEXT as _n, SANDBOX_DATA_ROOT as _o, readWebPushConfig as _r, piMessageFromHistoryItem as _s, checkInConversationWork as _t, loadProjection as a, deliverOAuthAuthorization as aa, getSlackToolContext as ai, isAnswerToolName as an, resolveSandboxCommandEnvironment as ao, getPluginApiRoutes as ar, listConversationAnnotations as as, failTurnRecord as at, persistConversationMessages as b, getSlackMessagePermalink as ba, bindEventAutomationCredentialSubject as bi, persistWithRetry as bn, SANDBOX_WORKSPACE_ROOT as bo, deletePushSubscription as br, setConfigDefaults as bs, clearExpiredConversationLease as bt, recordAgentsInstructionsUpdated as c, resolveBaseUrl as ca, RESOURCE_WATCH_TOOL_SOURCE as ci, replyTextSchema as cn, sleep$2 as co, getPluginSystemPromptContributions as cr, resolveUserTimezone as cs, listTurnSummaries as ct, recordAuthorizationCompleted as d, escapeSlackMrkdwnText as da, cancelWatch as di, sanitizeAssistantText as dn, ToolInputError as do, getPlugins as dr, credentialAuditAttributes as ds, CONVERSATION_WORK_STALE_ENQUEUE_MS as dt, isStale as ea, automationCreatorUserId as ei, TurnToolCallLimitExceededError as en, consumeSandboxEgressPermissionDeniedSignal as eo, getOAuthAccountProviders as er, recordSlackAttachment as es, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, formatSlackLink as fa, collectEventMatchKeys as fi, NO_REPLY_TOOL_NAME as fn, isToolInputError as fo, setPlugins as fr, credentialAuditSource as fs, ackMessages as ft, recordToolExecutionStarted as g, slackMentionedUserIds as ga, findMatchingWatches as gi, CODEMODE_TOOL_NAME as gn, SANDBOX_COMMAND_PATH as go, setBriefsConfig as gr, historyItemFromPiMessage as gs, cancelHumanFacingPendingMessages as gt, recordSubscribedReplyRoute as h, slackMention as ha, deliverWatch as hi, readNoReply as hn, createPluginModel as ho, registration_exports as hr, configValueSchema as hs, beginConversationResume as ht, loadConversationProjection as i, proxyVercelSandboxEgressRequest as ia, resolveChannelCapabilities as ii, REPLY_TOOL_NAME as in, buildSandboxEgressNetworkPolicy as io, createPluginHookRunner as ir, createPluginAnnotations as is, completeTurnRecord as it, markConversationMessage as j, SlackActionError as ja, getDashboardPersonLink as ji, isToolResultError as jn, createConversationAccessReader as jo, getOpenReviewItemByDedupeKey as jr, hasConversationStop as jt, isHumanConversationMessage as k, slackEntitySchema as ka, getDashboardLinkFilter as ki, isContinuablePiBoundary as kn, canAccessConversation as ko, countReviewItemsNeedingUser as kr, getConversationWorkState as kt, recordAttachmentsDelivered as l, startOAuthFlow as la, STOP_WATCHING_TOOL_NAME as li, decideReply as ln, tryWorkspaceRepoCheckoutPath as lo, getPluginTools as lr, lookupSlackUser as ls, recordTurnSummary as lt, recordMcpProviderConnected as m, normalizeSlackStatusText as ma, createWatch as mi, isLegacyNoReplyMarker as mn, createPluginEmbedder as mo, coreTaskRegistrations as mr, createDurableLocationConfigurationService as ms, appendInboundMessage as mt, commitMessages as n, getSandboxProvider as na, resolveAssignees as ni, createTurnLimitGate as nn, parseSandboxEgressCredentialToken as no, agent_hooks_exports as nr, resolveRootVisibility as ns, saveTurnCheckpoint as nt, loadTurnProjection as o, formatProviderLabel as oa, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as oi, readTurnAnswer as on, normalizeSandboxEgressTracePropagationDomains as oo, getPluginRoutes as or, listConversationAnnotationsById as os, getStoredTurnFields as ot, recordGuardianActionReviewed as p, normalizeSlackReplyMarkdown as pa, createTimerWatch as pi, findLegacyNoReplyMarker as pn, PluginToolDeniedError as po, validatePlugins as pr, createPluginCache as ps, appendExclusiveInboundMessage as pt, AuthorizationPauseError as q, wrapSandboxSetupError as qa, WorkspaceValidationError as qi, renderTag as qn, buildSentryConversationUrl as qo, requireReviewItemAssignees as qr, stopConversationWork as qt, loadConnectedMcpProviders as r, isVercelSandboxEgressRequest as ra, createCodeChangePublisher as ri, isTurnExecutionLimitExceededError as rn, sandboxEgressSignalsResponseSchema as ro, createPluginEventPublisher as rr, saveObjectAnnotations as rs, abandonTurnRecord as rt, openConversationProjection as s, parseOAuthStatePayload as sa, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as si, remindMissingAnswer as sn, SANDBOX_RUNTIME as so, getPluginSlackConversationLink as sr, defaultTimezone as ss, getTurnRecord as st, commitAcceptedReply as t, ensureDockerDaemon as ta, resolveAssignee as ti, buildTurnErrorResponse as tn, createSandboxEgressCredentialToken as to, resolvePluginOAuthAccount as tr, slackAttachmentsVersionQuery as ts, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, SLACK_USER_MENTION_RE as ua, cancelSubscriptions as ui, getAssistantReplyText as un, workspaceRepoCheckoutPath as uo, getPluginUserPromptContributions as ur, lookupSlackUserNames as us, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as ut, hydrateConversationMessages as v, addReactionToMessage as va, listWatches as vi, REPORT_BLOCKED_TOOL_NAME as vn, SANDBOX_REPOS_ROOT as vo, sendPushNotificationToUser as vr, projectConversationEvents$1 as vs, claimInboundMessage as vt, fallbackShortTitle as w, postSlackMessage as wa, verifyScheduledAutomationCredentialSubject as wi, getUserMessageInstructionText as wn, buildCommandScript as wo, savePushSubscription as wr, deadLetterAttempt as wt, toStoredConversationMessage as x, openSlackDirectMessage as xa, bindScheduledAutomationCredentialSubject as xi, extractAssistantText as xn, sandboxSkillDir as xo, listPushSubscriptions as xr, completeConversationStop as xt, persistConversationMessageWindow as y, deleteSlackMessage as ya, takeDueTimerWatches as yi, readBlockedReport as yn, SANDBOX_SKILLS_ROOT as yo, resolveNotificationTimezone as yr, getConfigDefaults as ys, clearConsumedConversationWake as yt, getAgentContextCompactionTriggerTokens as z, normalizeSlackConversationId as za, renderToolResultNudge as zi, REQUEST_CONTEXT_SECTION_TAG as zn, createPluginConversationEvents as zo, updateReviewItemContent as zr, recordAttemptFailure as zt };
16117
+ export { loadTurnCheckpoint as $, workspaceRepoCheckoutPath as $a, setWorkspaceSnapshotBuild as $i, webActorUserIds 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, readNotificationSchedule as Cr, piMessageFromHistoryItem as Cs, countPendingConversationMessages as Ct, estimateConversationMessagesTokens as D, postSlackMessage as Da, verifyTimerWatchCredentialSubject as Di, instructionTextForProjection as Dn, viewerMarksFromParticipant as Do, projectConversationMessages as Dr, dropPendingMessages as Dt, buildConversationContext as E, postSlackEphemeralMessage as Ea, verifySlackDirectCredentialSubject as Ei, hasTurnInput as En, conversationViewerMarks as Eo, isPausedBySlack as Er, setConfigDefaults 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, 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, findLegacyWebActorUserId 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, listPushSubscriptions as Sr, historyItemFromPiMessage as Ss, completeConversationWork as St, resolveTaskTitle as T, openSlackModal as Ta, verifyScheduledAutomationCredentialSubject as Ti, hasRuntimeTurnContext as Tn, conversationPinnedForUser as To, savePushSubscription as Tr, getConfigDefaults 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, setBriefsConfig as _r, credentialAuditAttributes as _s, checkInConversationWork as _t, loadProjection as a, isVercelSandboxEgressRequest as aa, resolveChannelCapabilities as ai, isAnswerToolName as an, SANDBOX_COMMAND_PATH as ao, createPluginHookRunner as ar, getWorkspaceTeamId as as, failTurnRecord as at, persistConversationMessages as b, truncateStatusText as ba, takeDueTimerWatches as bi, persistWithRetry as bn, createConversationAccessReader as bo, resolveNotificationTimezone as br, createDurableLocationConfigurationService 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, getPluginSlackConversationLink as cr, resolveRootVisibility as cs, listTurnSummaries as ct, recordAuthorizationCompleted as d, startOAuthFlow as da, cancelSubscriptions as di, sanitizeAssistantText as dn, sandboxSkillFile as do, getPluginUserPromptContributions as dr, listConversationAnnotations as ds, CONVERSATION_WORK_STALE_ENQUEUE_MS as dt, create as ea, activeParticipantUserIds as ei, TurnToolCallLimitExceededError as en, ToolInputError as eo, getOAuthAccountProviders 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, getPlugins as fr, listConversationAnnotationsById as fs, ackMessages as ft, recordToolExecutionStarted as g, normalizeSlackStatusText as ga, deliverWatch as gi, CODEMODE_TOOL_NAME as gn, createPluginModelCostRecorder as go, registration_exports as gr, lookupSlackUserNames as gs, cancelHumanFacingPendingMessages as gt, recordSubscribedReplyRoute as h, normalizeSlackReplyMarkdown as ha, createWatch as hi, readNoReply as hn, runNonInteractiveCommand as ho, coreTaskRegistrations as hr, lookupSlackUser as hs, beginConversationResume as ht, loadConversationProjection as i, getSandboxProvider as ia, createCodeChangePublisher as ii, REPLY_TOOL_NAME as in, createPluginModel as io, createPluginEventPublisher 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, getPluginSystemPromptContributions as lr, saveObjectAnnotations as ls, recordTurnSummary as lt, recordMcpProviderConnected as m, formatSlackLink as ma, createTimerWatch as mi, isLegacyNoReplyMarker as mn, buildNonInteractiveShellScript as mo, validatePlugins as mr, resolveUserTimezone as ms, appendInboundMessage as mt, commitMessages as n, isStale as na, resolveAssignee as ni, createTurnLimitGate as nn, PluginToolDeniedError as no, agent_hooks_exports 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, getPluginApiRoutes as or, runWithWorkspaceTeamId as os, getStoredTurnFields as ot, recordGuardianActionReviewed as p, escapeSlackMrkdwnText as pa, collectEventMatchKeys as pi, findLegacyNoReplyMarker as pn, buildCommandScript as po, setPlugins as pr, defaultTimezone 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, applyPluginFormatMarkdown 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, getPluginRoutes as sr, AttachmentSourceUnavailableError as ss, getTurnRecord as st, commitAcceptedReply as t, hash as ta, automationCreatorUserId as ti, buildTurnErrorResponse as tn, isToolInputError as to, resolvePluginOAuthAccount 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, getPluginTools as ur, createPluginAnnotations 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, readWebPushConfig as vr, credentialAuditSource as vs, claimInboundMessage as vt, fallbackShortTitle as w, openSlackDirectMessage as wa, verifyEventAutomationCredentialSubject as wi, getUserMessageInstructionText as wn, conversationIsNotUnsubscribedRoot as wo, saveNotificationSchedule as wr, projectConversationEvents$1 as ws, deadLetterAttempt as wt, toStoredConversationMessage as x, addReactionToMessage as xa, bindEventAutomationCredentialSubject as xi, extractAssistantText as xn, readConversationAccessFromSql as xo, deletePushSubscription as xr, configValueSchema as xs, completeConversationStop as xt, persistConversationMessageWindow as y, wrapBareSlackUserIds as ya, listWatches as yi, readBlockedReport as yn, canAddConversationMessages as yo, sendPushNotificationToUser as yr, createPluginCache 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 };