@sentry/junior 0.285.0 → 0.286.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 (73) hide show
  1. package/dist/{adapter-DN5AB4VU.js → adapter-JQZaJ-B_.js} +1 -1
  2. package/dist/{admin-DOITMKnn.js → admin-Dm2bimJ-.js} +1 -1
  3. package/dist/{agent-runner-BsWhHe4N.js → agent-runner-DGCwOEyL.js} +1567 -1048
  4. package/dist/api/schema.d.ts +1 -1
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +70 -92
  8. package/dist/{app-DyMs9330.d.ts → app-BKq0JzWx.d.ts} +2 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +37 -40
  11. package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-CAPafcUY.js} +1 -1
  12. package/dist/{automation-Mk8aaHzy.js → automation-B-jJN_gM.js} +1 -1
  13. package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-Btu2oab_.js} +137 -3
  14. package/dist/{briefs-Cl8-nK9B.js → briefs-UMeYehUe.js} +4 -4
  15. package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-Bym8GVdh.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -6
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-DDbBucBw.js → client-B0aAs7wC.js} +2 -2
  24. package/dist/{config-DqFnykQT.js → config-B9f9Lqo5.js} +1 -1
  25. package/dist/{connections-DA4LT9LL.js → connections-CQ7p0aNJ.js} +16 -50
  26. package/dist/{conversation-D8kVoCrP.js → conversation-BusI2uzj.js} +15 -6
  27. package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
  28. package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-Cd_nZZBM.js} +1 -1
  29. package/dist/{credential-sync-hcsYatw-.js → credential-sync-DmiJi_At.js} +13 -13
  30. package/dist/{db-BhHZSuFw.d.ts → db-C5zi4ecs.d.ts} +4 -4
  31. package/dist/{executor-BLEMIgIZ.js → executor-Dipi2Ixl.js} +11 -17
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BfORLKoq.js → logging-CMFhLLj4.js} +1 -1
  34. package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
  35. package/dist/{message-DqjuKzUx.js → message-D1xLljUF.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -3
  38. package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-DCAFIUQr.js} +2 -2
  39. package/dist/{projection-DliWYrnT.js → projection-CoeMNxJ4.js} +286 -212
  40. package/dist/{prompt-BvIUzY4y.js → prompt-C9OQEfan.js} +1 -1
  41. package/dist/{registry-rC7MCxu8.js → registry-u-sFYtx_.js} +1 -1
  42. package/dist/{resolve-Biu8Qw3u.js → resolve-DYqgL3Eo.js} +3 -3
  43. package/dist/{result-DxJMCX47.js → result-CescSwAw.js} +8 -8
  44. package/dist/{runner-BQJSFLKg.js → runner-Cr67a8TB.js} +16 -12
  45. package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
  46. package/dist/{schema-BasXTvi2.js → schema-BUSi3sgv.js} +5 -5
  47. package/dist/{schema-BUviRAs8.d.ts → schema-Ih60j59-.d.ts} +44 -7
  48. package/dist/{service-account-BI5Wgx22.js → service-account-CGEqz9wG.js} +3 -3
  49. package/dist/{service-account-CAE-_1dR.js → service-account-CsKxktLk.js} +3 -3
  50. package/dist/{session-stop-CA-jOJ84.js → session-stop-CGz5DByb.js} +22 -20
  51. package/dist/{skills-B22duVJU.js → skills-COCqf61f.js} +2 -2
  52. package/dist/{spawn-BB2_4VYn.js → spawn-C8F_iXWO.js} +13 -2
  53. package/dist/{stop-DioIcEAu.js → stop-GyFZkHuQ.js} +242 -952
  54. package/dist/{store-Dn4W7qgH.js → store-D0-8plWp.js} +3 -3
  55. package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-xPuQmEot.js} +1439 -993
  56. package/dist/{store-B26LV6UP.js → turn-failure-response-BOviBdT-.js} +331 -5
  57. package/dist/{validation-TzhfQABF.js → validation-DZDKorGz.js} +1 -1
  58. package/dist/{version-DSk8CFvA.js → version-BTIz7fGi.js} +1 -1
  59. package/dist/version.js +1 -1
  60. package/dist/{viewer-1Ea81s0b.js → viewer-CH-ASQzh.js} +39 -36
  61. package/dist/{work-ybG4_q5C.js → work-C75_IM5e.js} +92 -87
  62. package/dist/{worker-ccSyZRNz.js → worker-Dl47I729.js} +6 -6
  63. package/migrations/0086_shared_archive.sql +31 -0
  64. package/migrations/0087_child_location.sql +64 -0
  65. package/migrations/meta/0086_snapshot.json +4366 -0
  66. package/migrations/meta/0087_snapshot.json +4366 -0
  67. package/migrations/meta/_journal.json +14 -0
  68. package/package.json +5 -4
  69. package/dist/task-queue-Bt0IoR2i.js +0 -139
  70. package/dist/task-runner-D8lddjzp.js +0 -290
  71. package/dist/thread-state-CrFk3K_7.js +0 -173
  72. package/dist/turn-failure-response-DaJ04qVj.js +0 -224
  73. package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
@@ -1,29 +1,30 @@
1
1
  import { a as getClient$1, h as startSpan, n as captureMessage, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { a as completeText, c as resolveGatewayModel, i as completeObject, m as escapeXml, o as embedTexts, p as unwrapCurrentInstruction, r as completeDecision, s as rerankTexts, t as GEN_AI_PROVIDER_NAME, w as toOptionalTrimmed, x as isProviderRetryError } from "./client-DDbBucBw.js";
3
- import { i as getChatConfig, n as botConfig, o as getSlackBotToken, v as normalizeSlackEmojiName } from "./config-DqFnykQT.js";
4
- import { E as withSpan, G as toOptionalNumber, K as toOptionalString, W as isRecord$2, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-BfORLKoq.js";
5
- import { t as canExposeConversationPayload } from "./conversation-privacy-D0j_h70R.js";
2
+ import { a as completeText, c as resolveGatewayModel, i as completeObject, m as escapeXml, o as embedTexts, p as unwrapCurrentInstruction, r as completeDecision, s as rerankTexts, t as GEN_AI_PROVIDER_NAME, w as toOptionalTrimmed, x as isProviderRetryError } from "./client-B0aAs7wC.js";
3
+ import { i as getChatConfig, n as botConfig, o as getSlackBotToken, v as normalizeSlackEmojiName } from "./config-B9f9Lqo5.js";
4
+ import { E as withSpan, G as toOptionalNumber, K as toOptionalString, W as isRecord$2, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-CMFhLLj4.js";
5
+ import { t as canExposeConversationPayload } from "./conversation-privacy-Cd_nZZBM.js";
6
6
  import { c as parseStoredSlackActor, d as parseSlackChannelReferenceId, f as parseSlackTeamId, h as parseSlackMessageTs, i as isActorUserId, l as toStoredSlackActor, p as parseSlackUserId, s as parseActorUserId } from "./actor-6jsm_v96.js";
7
- import { B as startLocationThread, C as getSqlExecutor, D as createSqlConversationEventStore, F as createSqlStore, J as readUserTimezone, O as eventFromRow, Q as bindProviderConversation, S as getDb, U as resolveActorIdentityId, X as saveUserTimezone, et as conversationDetailTouch, ft as sameDestination, g as createCache, i as readActorIdentity, k as withConversationEventLock, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, rt as addAgentTurnUsage, s as readIdentityByIdFromSql, st as hasAgentTurnUsage, ut as parseDestination, x as getConversationStore, y as getConversationEventStore } from "./viewer-1Ea81s0b.js";
8
- import { 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, k as juniorAttachments, 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-BLEMIgIZ.js";
9
- import { _ as instructionProvenanceFor, g as instructionActors, h as contextProvenance, o as agentHistoryItemSchema } from "./media-Bu9C6lz0.js";
10
- import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-rC7MCxu8.js";
11
- import { n as pluginCatalogRuntime } from "./catalog-runtime-Bte6jRB2.js";
7
+ import { $ as conversationDetailTouch, B as startLocationThread, C as getSqlExecutor, D as createSqlConversationEventStore, F as createSqlStore, H as resolveActorIdentityId, O as eventFromRow, S as getDb, Y as saveUserTimezone, Z as bindProviderConversation, dt as sameDestination, g as createCache, i as readActorIdentity, k as withConversationEventLock, l as resolveViewerUser, lt as parseDestination, n as findUserByEmailFromSql, nt as addAgentTurnUsage, o as readIdentityById, ot as hasAgentTurnUsage, p as parseAvatarUrl, q as readUserTimezone, s as readIdentityByIdFromSql, x as getConversationStore, y as getConversationEventStore } from "./viewer-CH-ASQzh.js";
8
+ import { A as juniorConversations, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, O as juniorCodeRepositories, a as juniorPushSubscriptions, b as juniorConversationBriefs, f as juniorAutomations, i as juniorWorkspaces, j as juniorIdentities, k as juniorAttachments, 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-Dipi2Ixl.js";
9
+ import { _ as instructionProvenanceFor, g as instructionActors, h as contextProvenance, o as agentHistoryItemSchema } from "./media-B-BpXo41.js";
10
+ import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-u-sFYtx_.js";
11
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Bym8GVdh.js";
12
12
  import { a as withLock, i as fenceLock, n as MUTATION_LOCK_TTL_MS, r as acquireActiveLock } from "./locks-D-0h111u.js";
13
- import { n as getDefaultRedisStateAdapterFor, r as getStateAdapter } from "./adapter-DN5AB4VU.js";
13
+ import { a as setStateValues, i as getStateValues, n as getDefaultRedisStateAdapterFor, r as getStateAdapter } from "./adapter-JQZaJ-B_.js";
14
14
  import { n as isWithinNotificationSchedule, r as notificationScheduleSchema, s as isValidTimeZone, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-BTp__wrw.js";
15
- import { A as reviewItemChangeRecordSchema, B as readMessageAttachments, G as conversationBriefSchema, K as parseBriefInput, M as messageCardRef, P as readMessageCardRefs, W as briefResourceLabel, _ as conversationReportEventSchema, q as parseStoredBrief, v as conversationReportMessageEventSchema } from "./conversation-D8kVoCrP.js";
16
- import { n as briefEntriesFromReportEvents, s as generateBrief, t as BRIEF_PROMPT } from "./prompt-BvIUzY4y.js";
15
+ import { A as reviewItemChangeRecordSchema, B as readMessageAttachments, G as conversationBriefSchema, K as parseBriefInput, M as messageCardRef, P as readMessageCardRefs, W as briefResourceLabel, _ as conversationReportEventSchema, q as parseStoredBrief, v as conversationReportMessageEventSchema } from "./conversation-BusI2uzj.js";
16
+ import { n as briefEntriesFromReportEvents, o as isEventConversationMessage, s as generateBrief, t as BRIEF_PROMPT } from "./prompt-C9OQEfan.js";
17
17
  import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
18
18
  import path from "node:path";
19
19
  import { isDeepStrictEqual } from "node:util";
20
20
  import { AsyncLocalStorage } from "node:async_hooks";
21
21
  import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
22
22
  import * as z from "zod";
23
- import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, notExists, or, sql } from "drizzle-orm";
24
- import { EgressAuthRequired, EgressPolicyDenied, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, defineConversationEvent, destinationSchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTypeSchema, isPluginModelCostEventName, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectIconPath, objectTypeSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, promptContextSchema, promptMessageSchema, sourceSchema, stableEventMatchKey } from "@sentry/junior-plugin-api";
23
+ import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, or, sql } from "drizzle-orm";
24
+ import { EgressAuthRequired, EgressPolicyDenied, actorSchema, codeChangeInputSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, defineConversationEvent, destinationSchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTypeSchema, isPluginModelCostEventName, missingToolAnnotationKeys, normalizeEventIdentifier, objectAnnotationSchema, objectIconPath, objectTypeSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, sourceSchema, stableEventMatchKey } from "@sentry/junior-plugin-api";
25
25
  import { alias, union } from "drizzle-orm/pg-core";
26
26
  import fs from "node:fs/promises";
27
+ import pLimit from "p-limit";
27
28
  import http from "node:http";
28
29
  import os from "node:os";
29
30
  import dns from "node:dns/promises";
@@ -625,6 +626,49 @@ async function lookupSlackUser(teamId, userId) {
625
626
  return null;
626
627
  }
627
628
  }
629
+ const USER_NAMES_SHARED_TTL_MS = 864e5;
630
+ const USER_NAMES_LOOKUP_CONCURRENCY = 5;
631
+ const sharedUserNamesSchema = z.object({
632
+ fullName: z.string().optional(),
633
+ userName: z.string().optional()
634
+ });
635
+ function sharedUserNamesKey(teamId, userId) {
636
+ return `slack-user-names:${teamId}:${userId}`;
637
+ }
638
+ /**
639
+ * Look up the names of Slack users in one workspace, shared across instances.
640
+ * A user is missing from the result when Slack has no answer for them.
641
+ */
642
+ async function lookupSlackUserNames(teamId, userIds) {
643
+ const names = /* @__PURE__ */ new Map();
644
+ if (userIds.length === 0) return names;
645
+ const state = getStateAdapter();
646
+ const shared = await getStateValues(state, userIds.map((userId) => sharedUserNamesKey(teamId, userId)));
647
+ const missing = [];
648
+ for (const [index, userId] of userIds.entries()) {
649
+ const parsed = sharedUserNamesSchema.safeParse(shared[index]);
650
+ if (parsed.success) names.set(userId, parsed.data);
651
+ else missing.push(userId);
652
+ }
653
+ const limit = pLimit(USER_NAMES_LOOKUP_CONCURRENCY);
654
+ const profiles = await Promise.all(missing.map((userId) => limit(() => lookupSlackUser(teamId, userId))));
655
+ const found = [];
656
+ for (const [index, userId] of missing.entries()) {
657
+ const profile = profiles[index];
658
+ if (!profile) continue;
659
+ const value = {
660
+ ...profile.fullName ? { fullName: profile.fullName } : void 0,
661
+ ...profile.userName ? { userName: profile.userName } : void 0
662
+ };
663
+ names.set(userId, value);
664
+ found.push({
665
+ key: sharedUserNamesKey(teamId, userId),
666
+ value
667
+ });
668
+ }
669
+ await setStateValues(state, found, USER_NAMES_SHARED_TTL_MS);
670
+ return names;
671
+ }
628
672
  // src/chat/identities/timezone.ts
629
673
  const DEFAULT_TIMEZONE = "America/Los_Angeles";
630
674
  /** The install timezone, used when Junior does not know a person's timezone. */
@@ -768,6 +812,36 @@ async function annotateToolResult(conversationId, plugin, result) {
768
812
  };
769
813
  return annotated;
770
814
  }
815
+ // src/chat/conversations/tool-replies.ts
816
+ /**
817
+ * Record the reply that a plugin tool posted for Junior, such as a pull
818
+ * request comment, and remove it from the model-facing result. The model
819
+ * wrote the text, so it reads only the provider facts.
820
+ */
821
+ async function recordToolReply(args) {
822
+ const { result } = args;
823
+ if (!isRecord$2(result) || result.isError === true) return result;
824
+ const details = isRecord$2(result.details) ? result.details : result;
825
+ if (details.reply === void 0) return result;
826
+ const reply = pluginToolReplySchema.parse(details.reply);
827
+ if (args.toolCallId) await getConversationEventStore().append(args.conversationId, [{
828
+ idempotencyKey: `reply_posted:tool:${args.toolCallId}`,
829
+ data: {
830
+ type: "reply_posted",
831
+ plugin: args.plugin,
832
+ text: reply.text,
833
+ ...reply.url ? { url: reply.url } : void 0,
834
+ toolCallId: args.toolCallId
835
+ },
836
+ createdAtMs: Date.now()
837
+ }]);
838
+ const { reply: _reply, ...rest } = details;
839
+ if (isRecord$2(result.details)) return {
840
+ ...result,
841
+ details: rest
842
+ };
843
+ return rest;
844
+ }
771
845
  // src/chat/conversations/sql/privacy.ts
772
846
  const privacyRoot = alias(juniorConversations, "privacy_root");
773
847
  /** Accept only a structurally valid persisted root as privacy authority. */
@@ -1032,6 +1106,7 @@ const conversationReportSourceEventTypes = [
1032
1106
  "turn_context",
1033
1107
  "structured_event",
1034
1108
  "attachments_delivered",
1109
+ "reply_posted",
1035
1110
  "turn_completed",
1036
1111
  "turn_failed",
1037
1112
  "compaction",
@@ -1252,6 +1327,7 @@ function reportEventData(args) {
1252
1327
  ...args.canExposePayload ? reportReviewItemChanges(data.meta) : void 0,
1253
1328
  eventObjectType: objectTypeSchema.safeParse(data.meta?.eventObjectType).data,
1254
1329
  ...typeof data.meta?.eventType === "string" ? { eventType: data.meta.eventType } : void 0,
1330
+ ...typeof data.meta?.eventNamespace === "string" ? { eventNamespace: data.meta.eventNamespace } : void 0,
1255
1331
  ...typeof data.meta?.explicitMention === "boolean" ? { explicitMention: data.meta.explicitMention } : void 0,
1256
1332
  ...data.meta?.quiet === true ? { quiet: true } : void 0,
1257
1333
  ...args.canExposePayload && typeof data.meta?.trustedSummary === "string" ? { trustedSummary: data.meta.trustedSummary } : void 0,
@@ -1289,6 +1365,14 @@ function reportEventData(args) {
1289
1365
  type: "attachments_delivered",
1290
1366
  attachments: data.attachments
1291
1367
  };
1368
+ case "reply_posted":
1369
+ if (!args.canExposePayload) return;
1370
+ return {
1371
+ type: "reply_posted",
1372
+ plugin: data.plugin,
1373
+ text: data.text,
1374
+ ...data.url ? { url: data.url } : void 0
1375
+ };
1292
1376
  case "guardian_action_reviewed": return {
1293
1377
  type: "guardian_action_reviewed",
1294
1378
  turnId: data.turnId,
@@ -2066,25 +2150,16 @@ function conversationIsMemberRoot(member) {
2066
2150
  const memberRoots = "userId" in member ? union(started.where(eq(juniorIdentities.userId, member.userId)), participating.where(eq(juniorConversationParticipants.userId, member.userId))) : union(started.innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(eq(juniorUsers.primaryEmailNormalized, member.email)), participating.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(eq(juniorUsers.primaryEmailNormalized, member.email)));
2067
2151
  return inArray(juniorConversations.conversationId, memberRoots);
2068
2152
  }
2069
- /** True when the person's personal feed has archived this root. */
2070
- function conversationArchivedFor(member) {
2071
- return exists(memberParticipantRow(member, isNotNull(juniorConversationParticipants.archivedAt)));
2072
- }
2073
- /** True when the person's personal feed has not archived this root. */
2074
- function conversationNotArchivedFor(member) {
2075
- return notExists(memberParticipantRow(member, isNotNull(juniorConversationParticipants.archivedAt)));
2076
- }
2077
2153
  /** Root-actor ownership or a materialized participant row for the same person. */
2078
2154
  function viewerConversationMembership(args) {
2079
2155
  if (args.actorMatch && args.participantMatch) return or(args.actorMatch, args.participantMatch);
2080
2156
  return args.actorMatch ?? args.participantMatch;
2081
2157
  }
2082
- /** Read personal archive and pin marks for a bounded set of conversation roots. */
2158
+ /** Read personal pin marks for a bounded set of conversation roots. */
2083
2159
  async function conversationViewerMarks(db, conversationIds, subject) {
2084
2160
  if (!subject || conversationIds.length === 0) return /* @__PURE__ */ new Map();
2085
- const marked = and(inArray(juniorConversationParticipants.rootConversationId, [...conversationIds]), or(isNotNull(juniorConversationParticipants.archivedAt), isNotNull(juniorConversationParticipants.pinnedAt)));
2161
+ const marked = and(inArray(juniorConversationParticipants.rootConversationId, [...conversationIds]), isNotNull(juniorConversationParticipants.pinnedAt));
2086
2162
  const query = db.select({
2087
- archivedAt: juniorConversationParticipants.archivedAt,
2088
2163
  pinnedAt: juniorConversationParticipants.pinnedAt,
2089
2164
  pinPosition: juniorConversationParticipants.pinPosition,
2090
2165
  rootConversationId: juniorConversationParticipants.rootConversationId
@@ -2097,11 +2172,10 @@ async function conversationViewerMarks(db, conversationIds, subject) {
2097
2172
  }
2098
2173
  /** Project one participant row into marks, or undefined when it has none. */
2099
2174
  function viewerMarksFromParticipant(row) {
2100
- if (!row.archivedAt && !row.pinnedAt) return void 0;
2175
+ if (!row.pinnedAt) return void 0;
2101
2176
  return {
2102
- ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
2103
- ...row.pinnedAt ? { pinnedAtMs: row.pinnedAt.getTime() } : void 0,
2104
- ...row.pinnedAt && row.pinPosition !== null ? { pinPosition: row.pinPosition } : void 0
2177
+ pinnedAtMs: row.pinnedAt.getTime(),
2178
+ ...row.pinPosition !== null ? { pinPosition: row.pinPosition } : void 0
2105
2179
  };
2106
2180
  }
2107
2181
  /** True when one user pinned this root. Feeds sort these rows first. */
@@ -3546,7 +3620,7 @@ const BASE_IMAGE = {
3546
3620
  };
3547
3621
  const RUNTIME_REPOSITORY = "junior-sandbox-runtime";
3548
3622
  /** System packages for each runtime, installed on top of the base image. */
3549
- const RUNTIME_PACKAGES = { node22: ["nodejs22", "nodejs22-npm"] };
3623
+ const RUNTIME_PACKAGES = { node24: ["nodejs24", "nodejs24-npm"] };
3550
3624
  const COMMON_PACKAGES = [
3551
3625
  "coreutils",
3552
3626
  "diffutils",
@@ -3672,7 +3746,7 @@ async function ensureRuntimeImage(runtime, signal) {
3672
3746
  }
3673
3747
  // src/chat/sandbox/snapshot/runtime.ts
3674
3748
  /** Runtime used to build and start reusable Sandbox snapshots. */
3675
- const SANDBOX_RUNTIME = "node22";
3749
+ const SANDBOX_RUNTIME = "node24";
3676
3750
  // src/chat/sandbox/docker/relay.ts
3677
3751
  /** Host name of the Docker host as seen from a container. */
3678
3752
  const RELAY_PROXY_HOST = "host.docker.internal";
@@ -5029,7 +5103,7 @@ function adaptSession$1(container, options) {
5029
5103
  // src/chat/sandbox/docker/provider.ts
5030
5104
  /** Create a sandbox container and return a session for it. */
5031
5105
  async function createSession(input) {
5032
- const image = input.snapshotId ?? await ensureRuntimeImage(input.runtime ?? "node22", input.signal);
5106
+ const image = input.snapshotId ?? await ensureRuntimeImage(input.runtime ?? "node24", input.signal);
5033
5107
  const container = await createContainer({
5034
5108
  name: input.name ?? newSandboxName(),
5035
5109
  image,
@@ -8247,7 +8321,7 @@ const RESOURCE_SUBSCRIPTION_MAX_TTL_MS = 2592e6;
8247
8321
  const STOP_WATCHING_TOOL_NAME = "stopWatchingResources";
8248
8322
  const RESOURCE_WATCH_TOOL_SOURCE = {
8249
8323
  id: "resource-watches",
8250
- description: "Inspect or stop watches for the current conversation and its child agents."
8324
+ description: "Find event types, and inspect or stop watches for the current conversation and its child agents."
8251
8325
  };
8252
8326
  // src/chat/slack/tool-support/context.ts
8253
8327
  /** Resolve Slack tool context from the Conversation Location. */
@@ -8436,6 +8510,13 @@ function reviewItemNeedsUser(userId) {
8436
8510
  return and(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.kind, "action"), reviewItemAssignedTo(userId));
8437
8511
  }
8438
8512
  /**
8513
+ * SQL: the Review item needs some person: an open `action` item with an
8514
+ * assigned User. It is `reviewItemNeedsUser` for any User.
8515
+ */
8516
+ function reviewItemNeedsSomeone() {
8517
+ return and(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.kind, "action"), sql`exists (select 1 from ${juniorReviewItemAssignees} where ${juniorReviewItemAssignees.itemId} = ${juniorReviewItems.id})`);
8518
+ }
8519
+ /**
8439
8520
  * SQL: the Review item is not assigned only to other people. It is assigned
8440
8521
  * to this User, to Everyone, or to no one. This is the assignee rule of
8441
8522
  * `canActOnReviewItem`; keep the two the same.
@@ -9701,7 +9782,12 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
9701
9782
  const execute = definition.execute;
9702
9783
  if (execute) {
9703
9784
  const wrapped = Object.create(definition);
9704
- wrapped.execute = async (input, options) => annotateToolResult(context.conversationId, pluginName, await execute.call(definition, input, options));
9785
+ wrapped.execute = async (input, options) => annotateToolResult(context.conversationId, pluginName, await recordToolReply({
9786
+ conversationId: context.conversationId,
9787
+ plugin: pluginName,
9788
+ result: await execute.call(definition, input, options),
9789
+ toolCallId: options.toolCallId
9790
+ }));
9705
9791
  tools[name] = wrapped;
9706
9792
  } else tools[name] = definition;
9707
9793
  }
@@ -12084,7 +12170,6 @@ const storedInboundMessageSchema = z.object({
12084
12170
  delivery: inboundMessageDeliverySchema,
12085
12171
  destination: destinationSchema.optional(),
12086
12172
  inboundMessageId: z.string().refine((value) => value.trim().length > 0),
12087
- injectedAtMs: z.number().finite().optional(),
12088
12173
  input: agentInputSchema,
12089
12174
  receivedAtMs: z.number().finite(),
12090
12175
  source: inboundMessageSourceSchema,
@@ -12202,7 +12287,6 @@ function normalizeExecution(conversationId, value) {
12202
12287
  for (const rawMessage of value.pendingMessages) {
12203
12288
  const message = normalizeMessage(rawMessage);
12204
12289
  if (!message || message.conversationId !== conversationId) return;
12205
- if (message.injectedAtMs !== void 0) continue;
12206
12290
  pendingMessages.push(message);
12207
12291
  }
12208
12292
  pendingMessages.sort(compareMessages);
@@ -13319,6 +13403,17 @@ async function executionMetricsForTurn(conversationStore, conversation, turnId)
13319
13403
  function definedProps$1(values) {
13320
13404
  return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== void 0));
13321
13405
  }
13406
+ /** A completed, failed, or abandoned Turn never runs again. */
13407
+ function isFinishedTurnState(state) {
13408
+ return state === "completed" || state === "failed" || state === "abandoned";
13409
+ }
13410
+ /** A running or paused write reached a Turn that already finished. */
13411
+ var TurnAlreadyFinishedError = class extends Error {
13412
+ constructor(turnId, state) {
13413
+ super(`Turn ${turnId} already finished as ${state}`);
13414
+ this.name = "TurnAlreadyFinishedError";
13415
+ }
13416
+ };
13322
13417
  const turnStatusSchema = z.enum([
13323
13418
  "running",
13324
13419
  "paused",
@@ -13660,12 +13755,17 @@ async function updateTurnState(args) {
13660
13755
  })
13661
13756
  });
13662
13757
  }
13663
- /** Commit stable Pi state and advance the turn cursor. */
13758
+ /**
13759
+ * Commit stable Pi state and advance the turn cursor. A running or paused
13760
+ * write to a completed, failed, or abandoned Turn throws
13761
+ * `TurnAlreadyFinishedError`.
13762
+ */
13664
13763
  async function upsertTurnRecord(args) {
13665
13764
  return await withTurnCursorMutation(args.conversationId, args.turnId, async (fence) => await upsertTurnRecordLocked(args, fence));
13666
13765
  }
13667
13766
  async function upsertTurnRecordLocked(args, fence) {
13668
13767
  const existingRecord = await getStoredTurnRecord(args.conversationId, args.turnId);
13768
+ if (existingRecord && isFinishedTurnState(existingRecord.state) && !isFinishedTurnState(args.state)) throw new TurnAlreadyFinishedError(args.turnId, existingRecord.state);
13669
13769
  const conversationStore = args.conversationStore ?? getConversationStore();
13670
13770
  const conversation = await conversationStore.get({ conversationId: args.conversationId });
13671
13771
  const executionMetrics = await executionMetricsForTurn(conversationStore, conversation, args.turnId);
@@ -13751,10 +13851,10 @@ async function recordTurnSummaryOwned(args, fence) {
13751
13851
  const conversation = await conversationStore.get({ conversationId: args.conversationId });
13752
13852
  const executionMetrics = await executionMetricsForTurn(conversationStore, conversation, args.turnId);
13753
13853
  const priorSummary = (await listTurnSummaries(args.conversationId)).find((summary) => summary.turnId === args.turnId);
13754
- const terminalSummary = priorSummary && (priorSummary.state === "completed" || priorSummary.state === "failed" || priorSummary.state === "abandoned") ? priorSummary : void 0;
13755
- const terminalRecord = stored && (stored.state === "completed" || stored.state === "failed" || stored.state === "abandoned") ? stored : void 0;
13756
- const existing = terminalSummary ?? terminalRecord ?? stored ?? priorSummary;
13757
- if ((terminalSummary || terminalRecord) && (args.state === "running" || args.state === "paused")) return;
13854
+ const finishedSummary = priorSummary && isFinishedTurnState(priorSummary.state) ? priorSummary : void 0;
13855
+ const finishedRecord = stored && isFinishedTurnState(stored.state) ? stored : void 0;
13856
+ const existing = finishedSummary ?? finishedRecord ?? stored ?? priorSummary;
13857
+ if ((finishedSummary || finishedRecord) && !isFinishedTurnState(args.state)) return;
13758
13858
  const existingDispatchId = existing?.dispatchId;
13759
13859
  const existingDispatchOutcome = priorSummary?.dispatchOutcome ?? stored?.dispatchOutcome;
13760
13860
  const existingResultMessageId = priorSummary?.resultMessageId ?? stored?.resultMessageId;
@@ -13817,11 +13917,17 @@ async function readTurnSummaries(key) {
13817
13917
  async function listTurnSummaries(conversationId) {
13818
13918
  return readTurnSummaries(turnCursorIndexKey(conversationId));
13819
13919
  }
13820
- /** Mark an unfinished turn cursor as abandoned when a newer turn wins. */
13920
+ /**
13921
+ * Mark an unfinished turn cursor as abandoned when a newer turn wins. With
13922
+ * `onlyIfAuthPaused`, abandon only a Turn that still waits for sign-in. This
13923
+ * leaves a resumed Turn alone only after the worker's first running
13924
+ * checkpoint. Before that the Turn still reads as paused, so the stop abandons
13925
+ * it and signals the worker.
13926
+ */
13821
13927
  async function abandonTurnRecord(args) {
13822
13928
  return await withTurnCursorMutation(args.conversationId, args.turnId, async (fence) => {
13823
13929
  const existing = await getTurnRecord(args.conversationId, args.turnId);
13824
- if (!existing || existing.state === "completed" || existing.state === "failed" || existing.state === "abandoned") return;
13930
+ if (!existing || existing.state === "completed" || existing.state === "failed" || existing.state === "abandoned" || args.onlyIfAuthPaused && (existing.state !== "paused" || existing.resumeReason !== "auth")) return;
13825
13931
  return await updateTurnState({
13826
13932
  existing,
13827
13933
  fence,
@@ -13932,7 +14038,7 @@ async function saveRunning(args, traceContext) {
13932
14038
  state: "running"
13933
14039
  });
13934
14040
  } catch (error) {
13935
- if (!(error instanceof AgentHistoryBranchError)) logException(error, "agent.turn.checkpoint.running.failed", {
14041
+ if (!(error instanceof AgentHistoryBranchError) && !(error instanceof TurnAlreadyFinishedError)) logException(error, "agent.turn.checkpoint.running.failed", {
13936
14042
  "app.ai.resume_conversation_id": args.conversationId,
13937
14043
  "app.ai.resume_session_id": args.turnId,
13938
14044
  "app.ai.resume_slice_id": args.sliceId
@@ -13978,6 +14084,7 @@ async function savePaused(args, traceContext) {
13978
14084
  });
13979
14085
  } catch (error) {
13980
14086
  if (error instanceof TurnSliceLimitExceededError) throw error;
14087
+ if (error instanceof TurnAlreadyFinishedError) return;
13981
14088
  logException(error, "agent.turn.checkpoint.paused.failed", {
13982
14089
  "app.ai.resume_conversation_id": args.conversationId,
13983
14090
  "app.ai.resume_session_id": args.turnId,
@@ -14011,6 +14118,42 @@ async function saveDone(args, traceContext) {
14011
14118
  });
14012
14119
  });
14013
14120
  }
14121
+ /** Recovery resumes a turn at most once after its worker stops checking in. */
14122
+ const MAX_LOST_WORKER_RESUMES = 1;
14123
+ /**
14124
+ * Saved on the paused turn when recovery resumes it. The resumed run replaces
14125
+ * it at its first save.
14126
+ */
14127
+ const LOST_WORKER_RESUME_MESSAGE = "Turn lost its worker; resuming from its last boundary";
14128
+ /** True when a resumed turn lost its worker again before it saved anything. */
14129
+ function lostWorkerBeforeFirstSave(turn) {
14130
+ return turn.errorMessage === "Turn lost its worker; resuming from its last boundary" && (turn.lostWorkerResumeCount ?? 0) >= MAX_LOST_WORKER_RESUMES;
14131
+ }
14132
+ /**
14133
+ * Pause a turn whose worker stopped checking in, so it resumes from its last
14134
+ * save. Returns false when the turn already used its resume or has no slice
14135
+ * left.
14136
+ */
14137
+ async function pauseLostWorkerTurn(turn) {
14138
+ if ((turn.lostWorkerResumeCount ?? 0) >= MAX_LOST_WORKER_RESUMES || turn.sliceId + 1 > botConfig.maxSlicesPerTurn) return false;
14139
+ const paused = await saveTurnCheckpoint({
14140
+ mode: "paused",
14141
+ reason: "retry",
14142
+ conversationId: turn.conversationId,
14143
+ turnId: turn.turnId,
14144
+ sliceId: turn.sliceId,
14145
+ messages: turn.piMessages,
14146
+ lostWorkerResumeCount: (turn.lostWorkerResumeCount ?? 0) + 1,
14147
+ errorMessage: LOST_WORKER_RESUME_MESSAGE
14148
+ });
14149
+ if (!paused) return false;
14150
+ logWarn("agent.turn.lost_worker.resumed", {
14151
+ "app.ai.conversation_id": turn.conversationId,
14152
+ "app.ai.session_id": turn.turnId,
14153
+ "app.ai.resume_slice_id": paused.sliceId
14154
+ });
14155
+ return true;
14156
+ }
14014
14157
  // src/chat/services/pending-auth.ts
14015
14158
  const AUTH_LINK_REUSE_WINDOW_MS = 6e5;
14016
14159
  /** Decide whether the same agent-run session can reuse its fresh auth link. */
@@ -14307,13 +14450,12 @@ async function getPluginConversationTitleContext(args) {
14307
14450
  }
14308
14451
  // src/chat/services/conversation-memory.ts
14309
14452
  const CONTEXT_MIN_LIVE_MESSAGES = 12;
14310
- const CONTEXT_COMPACTION_BATCH_SIZE = 24;
14311
- const CONTEXT_MAX_COMPACTIONS = 16;
14312
14453
  const CONTEXT_MAX_MESSAGE_CHARS = 3200;
14454
+ const THREAD_CONTEXT_MAX_CHARS = 6e4;
14455
+ const THREAD_CONTEXT_OPEN = "<thread-context authority=\"evidence-only\">";
14456
+ const THREAD_CONTEXT_CLOSE = "</thread-context>";
14457
+ const THREAD_CONTEXT_OMITTED_NOTE = "Older Messages of this thread are not shown. Find them with the searchConversationEvents and readConversationEvent tools.";
14313
14458
  const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
14314
- function generateConversationId(prefix) {
14315
- return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
14316
- }
14317
14459
  /** Normalize message boundaries without changing transcript formatting. */
14318
14460
  function normalizeConversationText(text) {
14319
14461
  return text.replace(/\r\n?/g, "\n").trim();
@@ -14346,9 +14488,9 @@ function authorDisplayField(value, userId) {
14346
14488
  if (!value || value === userId || SLACK_USER_ID_DISPLAY_PATTERN.test(value)) return;
14347
14489
  return value;
14348
14490
  }
14349
- /** Estimate the token cost of the current visible conversation context. */
14350
- function estimateConversationContextTokens(conversation) {
14351
- return estimateTextTokens(buildConversationContext(conversation) ?? "");
14491
+ /** Estimate the visible Message working set that trimming bounds. */
14492
+ function estimateConversationMessagesTokens(conversation) {
14493
+ return estimateTextTokens(conversation.messages.map((message) => renderConversationMessageLine(message, conversation)).join("\n"));
14352
14494
  }
14353
14495
  function upsertConversationMessage(conversation, message) {
14354
14496
  const existingIndex = conversation.messages.findIndex((entry) => entry.id === message.id);
@@ -14416,114 +14558,62 @@ function isTakeOnly(message) {
14416
14558
  const changes = message.meta?.reviewItemChanges;
14417
14559
  return Boolean(changes?.length && changes.every((change) => change.kind === "taken"));
14418
14560
  }
14419
- /**
14420
- * Render thread history as structured XML. Each compaction and message is
14421
- * wrapped with index/ts metadata so the model can reference prior items
14422
- * individually instead of treating the whole block as one flat narrative.
14423
- */
14424
- function buildConversationContext(conversation, options = {}) {
14425
- const messages = conversation.messages.filter((entry) => !options.excludeMessageIds?.includes(entry.id) && !isTakeOnly(entry));
14426
- if (messages.length === 0 && conversation.compactions.length === 0) return;
14427
- const lines = [];
14428
- if (conversation.compactions.length > 0) {
14429
- lines.push("<thread-compactions>");
14430
- for (const [index, compaction] of conversation.compactions.entries()) lines.push(` <compaction index="${index + 1}" covered_messages="${compaction.coveredMessageCount}" created_at="${new Date(compaction.createdAtMs).toISOString()}">`, compaction.summary, " </compaction>");
14431
- lines.push("</thread-compactions>");
14432
- }
14433
- if (messages.length > 0) {
14434
- if (lines.length > 0) lines.push("");
14435
- lines.push("<thread-context authority=\"evidence-only\">");
14436
- for (const [index, message] of messages.entries()) {
14437
- const author = escapeXml(conversationAuthorDisplayName(message));
14438
- const actorIdAttr = message.author?.userId ? ` actor_id="${escapeXml(message.author.userId)}"` : "";
14439
- const ts = new Date(message.createdAtMs).toISOString();
14440
- const slackTsAttr = message.meta?.slackTs ? ` slack_ts="${escapeXml(message.meta.slackTs)}"` : "";
14441
- lines.push(` <message index="${index + 1}" ts="${ts}" role="${message.role}" author="${author}"${actorIdAttr}${slackTsAttr}>`, renderConversationMessageLine(message, conversation), " </message>");
14442
- }
14443
- lines.push("</thread-context>");
14444
- }
14445
- return lines.join("\n");
14561
+ function renderThreadContextMessage(message, conversation, index) {
14562
+ const author = escapeXml(conversationAuthorDisplayName(message));
14563
+ const actorIdAttr = message.author?.userId ? ` actor_id="${escapeXml(message.author.userId)}"` : "";
14564
+ const ts = new Date(message.createdAtMs).toISOString();
14565
+ const slackTsAttr = message.meta?.slackTs ? ` slack_ts="${escapeXml(message.meta.slackTs)}"` : "";
14566
+ return [
14567
+ ` <message index="${index}" ts="${ts}" role="${message.role}" author="${author}"${actorIdAttr}${slackTsAttr}>`,
14568
+ renderConversationMessageLine(message, conversation),
14569
+ " </message>"
14570
+ ].join("\n");
14571
+ }
14572
+ function isUntaggedThreadMessage(message) {
14573
+ return message.role === "user" && !message.meta?.explicitMention && !isEventConversationMessage(message);
14574
+ }
14575
+ /** Return the highest saved Message seq, the thread context cursor of a Turn. */
14576
+ function latestConversationMessageSeq(conversation) {
14577
+ let latest;
14578
+ for (const message of conversation.messages) if (message.seq !== void 0 && (latest ?? -1) < message.seq) latest = message.seq;
14579
+ return latest;
14446
14580
  }
14447
- const THREAD_CONTEXT_OPEN = "<thread-context authority=\"evidence-only\">";
14448
- const THREAD_CONTEXT_CLOSE = "</thread-context>";
14449
14581
  /**
14450
- * Keep ambient history as one evidence-only block.
14582
+ * Render the thread Messages that this Turn needs as one evidence-only block.
14451
14583
  *
14452
- * When durable context already ends a thread-context envelope, append message
14453
- * lines inside that envelope. Otherwise wrap the new messages in one envelope.
14454
- */
14455
- function appendThreadContextMessages(baseContext, messageLines) {
14456
- const base = baseContext?.trim();
14457
- if (messageLines.length === 0) return base || void 0;
14458
- const entryBlock = messageLines.join("\n");
14459
- if (!base) return [
14460
- THREAD_CONTEXT_OPEN,
14461
- entryBlock,
14462
- THREAD_CONTEXT_CLOSE
14463
- ].join("\n");
14464
- const closeIdx = base.lastIndexOf(THREAD_CONTEXT_CLOSE);
14465
- if (closeIdx >= 0) return `${base.slice(0, closeIdx).replace(/\s*$/, "")}\n${entryBlock}\n${base.slice(closeIdx)}`;
14466
- return [
14467
- base,
14468
- "",
14584
+ * With agent history, earlier Turns already hold their thread context, Turn
14585
+ * input, and replies. So only untagged Messages saved after the cursor of the
14586
+ * previous Turn are new. Without history, show the latest Messages. Both keep
14587
+ * the newest Messages under one hard size cap, so the block cannot grow with
14588
+ * the thread.
14589
+ */
14590
+ function buildConversationContext(conversation, options = {}) {
14591
+ const { history } = options;
14592
+ const candidates = conversation.messages.filter((entry) => !options.excludeMessageIds?.includes(entry.id) && !isTakeOnly(entry) && (!history || isUntaggedThreadMessage(entry) && (history.afterSeq === void 0 || entry.seq === void 0 || entry.seq > history.afterSeq)));
14593
+ let first = candidates.length;
14594
+ let chars = 0;
14595
+ while (first > 0) {
14596
+ const size = renderThreadContextMessage(candidates[first - 1], conversation, first).length;
14597
+ if (chars + size > THREAD_CONTEXT_MAX_CHARS) break;
14598
+ chars += size;
14599
+ first -= 1;
14600
+ }
14601
+ const shown = candidates.slice(first).map((message, index) => renderThreadContextMessage(message, conversation, index + 1));
14602
+ const counts = {
14603
+ shownMessages: shown.length,
14604
+ omittedMessages: candidates.length - shown.length
14605
+ };
14606
+ if (shown.length === 0) return counts;
14607
+ const lines = [
14469
14608
  THREAD_CONTEXT_OPEN,
14470
- entryBlock,
14609
+ ...shown,
14471
14610
  THREAD_CONTEXT_CLOSE
14472
- ].join("\n");
14473
- }
14474
- function pruneCompactions(compactions) {
14475
- if (compactions.length <= CONTEXT_MAX_COMPACTIONS) return compactions;
14476
- const overflowCount = compactions.length - CONTEXT_MAX_COMPACTIONS + 1;
14477
- const merged = compactions.slice(0, overflowCount);
14478
- const mergedSummary = merged.map((entry) => entry.summary).join("\n").slice(0, 3500);
14479
- const coveredMessageCount = merged.reduce((count, entry) => count + entry.coveredMessageCount, 0);
14480
- return [{
14481
- id: generateConversationId("compaction"),
14482
- createdAtMs: Date.now(),
14483
- summary: mergedSummary,
14484
- coveredMessageCount
14485
- }, ...compactions.slice(overflowCount)];
14486
- }
14487
- async function summarizeConversationChunk(messages, conversation, context, deps) {
14488
- const transcript = messages.map((message) => renderConversationMessageLine(message, conversation)).join("\n");
14489
- try {
14490
- const summary = (await deps.completeText({
14491
- modelId: botConfig.fastModelId,
14492
- temperature: 0,
14493
- promptName: "junior.thread_compaction",
14494
- messages: [{
14495
- role: "user",
14496
- content: [
14497
- "Summarize the following older Slack thread transcript segment for future assistant turns.",
14498
- "Keep the summary factual and concise. Do not invent details.",
14499
- "",
14500
- "Output exactly three XML sections in this order:",
14501
- "<active-asks> one bullet per outstanding user ask that has not been narrowed, answered, or replaced by a later turn. Omit the section body if none. </active-asks>",
14502
- "<resolved-or-replaced-asks> one bullet per ask that has been replaced, narrowed, answered, or already acted on in this segment. Include the replacement/outcome inline. Omit the section body if none. </resolved-or-replaced-asks>",
14503
- "<facts> one bullet per durable fact useful regardless of scope: names, ids, URLs, decisions, locations, preferences, constraints that remain true. Omit the section body if none. </facts>",
14504
- "",
14505
- "Do not output any text outside the three sections.",
14506
- "",
14507
- transcript
14508
- ].join("\n"),
14509
- timestamp: Date.now()
14510
- }],
14511
- metadata: {
14512
- modelId: botConfig.fastModelId,
14513
- threadId: context.threadId ?? "",
14514
- channelId: context.channelId ?? "",
14515
- actorId: context.actorId ?? "",
14516
- runId: context.runId ?? ""
14517
- }
14518
- })).text.trim();
14519
- if (summary.length > 0) return summary.slice(0, 3500);
14520
- } catch (error) {
14521
- logWarn("conversation.compaction.summary.failed", {
14522
- "exception.message": error instanceof Error ? error.message : String(error),
14523
- "app.compaction_messages_covered": messages.length
14524
- });
14525
- }
14526
- return transcript.slice(0, 2800);
14611
+ ];
14612
+ if (shown.length < candidates.length || !history && conversation.historyFromSeq !== void 0) lines.push(THREAD_CONTEXT_OMITTED_NOTE);
14613
+ return {
14614
+ ...counts,
14615
+ text: lines.join("\n")
14616
+ };
14527
14617
  }
14528
14618
  /** Return the earliest human-authored message known for a thread. */
14529
14619
  function getThreadTitleSourceMessage(conversation) {
@@ -14542,37 +14632,35 @@ function getThreadTitleSourceMessage(conversation) {
14542
14632
  }
14543
14633
  return firstMessage;
14544
14634
  }
14545
- async function compactConversationIfNeededWithDeps(conversation, context, deps) {
14546
- let estimatedTokens = estimateConversationContextTokens(conversation);
14635
+ /**
14636
+ * Drop the oldest visible Messages until the working set fits the target, so
14637
+ * the Messages that each Turn loads stay bounded. This makes no model call.
14638
+ * Return whether a Message was dropped.
14639
+ */
14640
+ async function trimConversationMessages(conversation, loadKeepAfterSeq) {
14641
+ let estimatedTokens = estimateConversationMessagesTokens(conversation);
14547
14642
  setSpanAttributes({ "app.context_tokens_estimated": estimatedTokens });
14548
14643
  const triggerTokens = getConversationContextCompactionTriggerTokens();
14644
+ if (estimatedTokens <= triggerTokens) return false;
14549
14645
  const targetTokens = calculateContextCompactionTargetTokens(triggerTokens);
14550
- while (estimatedTokens > triggerTokens && conversation.messages.length > CONTEXT_MIN_LIVE_MESSAGES) {
14551
- const compactCount = Math.min(CONTEXT_COMPACTION_BATCH_SIZE, conversation.messages.length - CONTEXT_MIN_LIVE_MESSAGES);
14552
- if (compactCount <= 0) break;
14553
- const compactedChunk = conversation.messages.slice(0, compactCount);
14554
- const summary = await summarizeConversationChunk(compactedChunk, conversation, context, deps);
14555
- conversation.compactions.push({
14556
- id: generateConversationId("compaction"),
14557
- createdAtMs: Date.now(),
14558
- summary,
14559
- coveredMessageCount: compactedChunk.length
14560
- });
14561
- conversation.compactions = pruneCompactions(conversation.compactions);
14562
- conversation.messages = conversation.messages.slice(compactCount);
14563
- estimatedTokens = estimateConversationContextTokens(conversation);
14564
- setSpanAttributes({
14565
- "app.compaction_messages_covered": compactCount,
14566
- "app.compaction.trigger_tokens": triggerTokens,
14567
- "app.compaction.target_tokens": targetTokens,
14568
- "app.context_tokens_estimated": estimatedTokens
14569
- });
14570
- if (estimatedTokens <= targetTokens) break;
14571
- }
14572
- }
14573
- /** Build the service that owns durable conversation memory compaction. */
14574
- function createConversationMemoryService(deps) {
14575
- return { compactConversationIfNeeded: async (conversation, context) => await compactConversationIfNeededWithDeps(conversation, context, deps) };
14646
+ const keepAfterSeq = await loadKeepAfterSeq();
14647
+ const maxDropped = conversation.messages.length - CONTEXT_MIN_LIVE_MESSAGES;
14648
+ let dropped = 0;
14649
+ while (dropped < maxDropped && estimatedTokens > targetTokens) {
14650
+ const message = conversation.messages[dropped];
14651
+ if (keepAfterSeq !== void 0 && (message.seq === void 0 || message.seq > keepAfterSeq)) break;
14652
+ estimatedTokens -= estimateTextTokens(`${renderConversationMessageLine(message, conversation)}\n`);
14653
+ dropped += 1;
14654
+ }
14655
+ if (dropped === 0) return false;
14656
+ conversation.messages = conversation.messages.slice(dropped);
14657
+ const historyFromSeq = conversation.messages[0]?.seq;
14658
+ if (historyFromSeq !== void 0) conversation.historyFromSeq = historyFromSeq;
14659
+ setSpanAttributes({
14660
+ "app.thread_messages.trimmed": dropped,
14661
+ "app.context_tokens_estimated": estimateConversationMessagesTokens(conversation)
14662
+ });
14663
+ return true;
14576
14664
  }
14577
14665
  function isHumanConversationMessage(message) {
14578
14666
  return message.role === "user" && message.author?.isBot !== true;
@@ -14802,32 +14890,6 @@ async function resolveConversationTitle(args) {
14802
14890
  }
14803
14891
  return (await (args.conversationStore ?? getConversationStore()).get({ conversationId: args.conversationId }))?.title?.trim() || void 0;
14804
14892
  }
14805
- // src/chat/conversations/message-summaries.ts
14806
- /** Project the latest source-message summary snapshot from event history. */
14807
- function projectConversationMessageSummaries(events) {
14808
- for (let index = events.length - 1; index >= 0; index -= 1) {
14809
- const data = events[index]?.data;
14810
- if (data?.type === "messages_summarized") return data.compactions;
14811
- }
14812
- return [];
14813
- }
14814
- /** Persist a changed source-message summary snapshot in event history. */
14815
- async function persistConversationMessageSummaries(args) {
14816
- const eventStore = getConversationEventStore();
14817
- const history = await eventStore.loadMessageHistory(args.conversationId);
14818
- const existing = history.compaction ? projectConversationMessageSummaries([history.compaction]) : [];
14819
- if (isDeepStrictEqual(existing, args.conversation.compactions)) return;
14820
- const liveMessageIds = new Set(args.conversation.messages.map((message) => message.id));
14821
- const nextHistoryFromSeq = history.events.find((event) => event.data.type === "message" && liveMessageIds.has(event.data.messageId))?.seq ?? Math.max(history.historyFromSeq, (history.events.at(-1)?.seq ?? -1) + 1);
14822
- await eventStore.append(args.conversationId, [{
14823
- data: {
14824
- type: "messages_summarized",
14825
- historyFromSeq: nextHistoryFromSeq,
14826
- compactions: args.conversation.compactions
14827
- },
14828
- createdAtMs: args.conversation.compactions.at(-1)?.createdAtMs ?? Date.now()
14829
- }]);
14830
- }
14831
14893
  // src/chat/conversations/message-projection.ts
14832
14894
  function isMessageEvent(event) {
14833
14895
  return event.data.type === "message" || event.data.type === "message_updated" || event.data.type === "message_handled";
@@ -14868,7 +14930,8 @@ function projectConversationMessages(history) {
14868
14930
  byId.set(data.messageId, {
14869
14931
  message: {
14870
14932
  ...message,
14871
- createdAtMs: current?.message.createdAtMs ?? message.createdAtMs
14933
+ createdAtMs: current?.message.createdAtMs ?? message.createdAtMs,
14934
+ seq: current?.message.seq ?? event.seq
14872
14935
  },
14873
14936
  ...current?.repliedAtMs === void 0 ? void 0 : { repliedAtMs: current.repliedAtMs }
14874
14937
  });
@@ -14926,9 +14989,20 @@ async function hydrateConversationMessages(args) {
14926
14989
  return;
14927
14990
  }
14928
14991
  const history = await getConversationEventStore().loadMessageHistory(args.conversationId);
14929
- args.conversation.compactions = history.compaction ? projectConversationMessageSummaries([history.compaction]) : [];
14992
+ args.conversation.historyFromSeq = history.historyFromSeq > 0 ? history.historyFromSeq : void 0;
14930
14993
  args.conversation.messages = projectConversationMessages(history);
14931
14994
  }
14995
+ /** Save where the trimmed Message window starts, so later loads skip older Messages. */
14996
+ async function persistConversationMessageWindow(args) {
14997
+ await getConversationEventStore().append(args.conversationId, [{
14998
+ data: {
14999
+ type: "messages_summarized",
15000
+ historyFromSeq: args.historyFromSeq,
15001
+ compactions: []
15002
+ },
15003
+ createdAtMs: Date.now()
15004
+ }]);
15005
+ }
14932
15006
  /** Append new messages and handled markers idempotently. */
14933
15007
  async function persistConversationMessages(args) {
14934
15008
  if (!args.conversationId || args.conversation.messages.length === 0) return;
@@ -15412,4 +15486,4 @@ async function recordGuardianActionReviewed(args) {
15412
15486
  createdAtMs: Date.now()
15413
15487
  }]);
15414
15488
  }
15415
- export { abandonTurnRecord as $, conversationArchivedFor as $a, slackEntitySchema as $i, readWebPushConfig as $n, verifyEventAutomationCredentialSubject as $r, hasTurnInput as $t, estimateConversationContextTokens as A, SANDBOX_RUNTIME as Aa, isVercelSandboxEgressRequest as Ai, getAgentContextInputLimitTokens as An, lookupSlackUser as Ao, EVERYONE_ASSIGNEE as Ar, recordConversationRetry as At, createPluginAuthOrchestration as B, SANDBOX_SKILLS_ROOT as Ba, normalizeSlackStatusText as Bi, createPluginHookRunner as Bn, setConfigDefaults as Bo, cancelSubscriptions as Br, TurnBudgetExceededError as Bt, resolveConversationTitle as C, consumeSandboxEgressPermissionDeniedSignal as Ca, setWorkspaceSnapshot as Ci, getSubscribedReplyPreflightDecision as Cn, resolveRootVisibility as Co, canReadReviewItem as Cr, hasRunnableConversationWork as Ct, appendThreadContextMessages as D, buildSandboxEgressNetworkPolicy as Da, isStale as Di, estimateTextTokens as Dn, listConversationAnnotationsById as Do, requireReviewItemLinks as Dr, markConversationWorkEnqueued as Dt, resolveTaskTitle as E, sandboxEgressSignalsResponseSchema as Ea, hash as Ei, estimateRequestOverheadTokens as En, listConversationAnnotations as Eo, requireReviewItemAssignees as Er, listActiveConversationIds as Et, recordDeliveredAssistantMessage as F, createPluginEmbedder as Fa, resolveBaseUrl as Fi, findLegacyWebActorUserId as Fn, piMessageFromHistoryItem as Fo, getSlackToolContext as Fr, requestConversationWork as Ft, abandonReplacedPendingAuth as G, buildCommandScript as Ga, getSlackMessagePermalink as Gi, getPluginTools as Gn, deliverWatch as Gr, isTurnExecutionLimitExceededError as Gt, AuthPausePersistenceError as H, sandboxSkillDir as Ha, truncateStatusText as Hi, getPluginRoutes as Hn, collectEventMatchKeys as Hr, TurnToolCallLimitExceededError as Ht, turnHasReply as I, createPluginModel as Ia, startOAuthFlow as Ii, webActorUserIds as In, projectConversationEvents$1 as Io, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Ir, startConversationWork as It, getConversationPendingAuth as J, createPluginModelCostRecorder as Ja, postSlackEphemeralMessage as Ji, setPlugins as Jn, listWatches as Jr, extractAssistantText as Jt, canReusePendingAuthLink as K, buildNonInteractiveShellScript as Ka, openSlackDirectMessage as Ki, getPluginUserPromptContributions as Kn, findMatchingWatches as Kr, CODEMODE_TOOL_NAME as Kt, upsertConversationMessage as L, SANDBOX_COMMAND_PATH as La, escapeSlackMrkdwnText as Li, getOAuthAccountProviders as Ln, JUNIOR_NATIVE_EVENT_NAMESPACE as Lo, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as Lr, steerWebPendingMessages as Lt, isHumanConversationMessage as M, tryWorkspaceRepoCheckoutPath as Ma, deliverOAuthAuthorization as Mi, isExperimentalFeatureEnabled as Mn, createDurableLocationConfigurationService as Mo, resolveAssignee as Mr, releaseInboundMessage as Mt, markConversationMessage as N, workspaceRepoCheckoutPath as Na, formatProviderLabel as Ni, setExperimentalFeatures as Nn, configValueSchema as No, resolveAssignees as Nr, removeActiveConversation as Nt, buildConversationContext as O, resolveSandboxCommandEnvironment as Oa, ensureDockerDaemon as Oi, getAgentBackgroundCompactionMarkTokens as On, defaultTimezone as Oo, reviewItemNeedsUser as Or, moveIdleConversationDestination as Ot, normalizeConversationText as P, PluginToolDeniedError as Pa, parseOAuthStatePayload as Pi, createUserTokenStore as Pn, historyItemFromPiMessage as Po, resolveChannelCapabilities as Pr, requestAnotherSlice as Pt, saveTurnCheckpoint as Q, readConversationAccessFromSql as Qa, uploadFilesToConversation as Qi, setBriefsConfig as Qn, bindSlackDirectCredentialSubject as Qr, hasRuntimeTurnContext as Qt, createPluginEgress as R, SANDBOX_DATA_ROOT as Ra, formatSlackLink as Ri, resolvePluginOAuthAccount as Rn, conversationNoteEvent as Ro, RESOURCE_WATCH_TOOL_SOURCE as Rr, stopConversationWork as Rt, persistConversationMessageSummaries as S, consumeSandboxEgressAuthRequiredSignal as Sa, loadSnapshotsForProfile as Si, decideSubscribedThreadReply as Sn, slackAttachmentsVersionQuery as So, canAgentChangeReviewItem as Sr, hasConversationStop as St, fallbackShortTitle as T, parseSandboxEgressCredentialToken as Ta, create as Ti, calculateContextCompactionTargetTokens as Tn, createPluginAnnotations as To, readReviewItemAgentScope as Tr, isInvalidConversationRecordError as Tt, AuthorizationFlowDisabledError as U, sandboxSkillFile as Ua, addReactionToMessage as Ui, getPluginSlackConversationLink as Un, createTimerWatch as Ur, buildTurnErrorResponse as Ut, authorizationId as V, SANDBOX_WORKSPACE_ROOT as Va, slackMention as Vi, getPluginApiRoutes as Vn, cancelWatch as Vr, TurnSliceLimitExceededError as Vt, AuthorizationPauseError as W, sandboxSkillPathResolution as Wa, deleteSlackMessage as Wi, getPluginSystemPromptContributions as Wn, createWatch as Wr, createTurnLimitGate as Wt, continuableMessages as X, canAccessConversation as Xa, removeReactionFromMessage as Xi, coreTaskRegistrations as Xn, bindEventAutomationCredentialSubject as Xr, getTerminalAssistantMessages as Xt, wasPendingAuthStopped as Y, createPluginLogger as Ya, postSlackMessage as Yi, validatePlugins as Yn, takeDueTimerWatches as Yr, getPiMessageRole as Yt, loadTurnCheckpoint as Z, createConversationAccessReader as Za, updateSlackMessage as Zi, registration_exports as Zn, bindScheduledAutomationCredentialSubject as Zr, getUserMessageInstructionText as Zt, appendConversationMessages as _, WorkspaceSnapshotNotReadyError as _a, listWorkspaces as _i, renderUntrustedTag as _n, notInheritedByForkChild as _o, searchReviewItems as _r, completeConversationWork as _t, loadProjection as a, getSlackClient as aa, getDashboardObjectIconLink as ai, isToolResultMessage as an, viewerConversationMembership as ao, saveNotificationSchedule as ar, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as at, toStoredConversationMessage as b, workspaceSnapshotNotReadyUserMessage as ba, WorkspaceValidationError as bi, buildDeterministicTurnId as bn, readAttachmentVisionSummary as bo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as br, getConversation as bt, recordAgentsInstructionsUpdated as c, normalizeSlackConversationId as ca, getDashboardTaskLink as ci, stripRuntimeTurnContext as cn, readConversationBriefThrough as co, closeReviewItem as cr, appendExclusiveInboundMessage as ct, recordAuthorizationCompleted as d, getWorkspaceTeamId as da, createPluginState as di, SESSION_CONTEXT_SECTION_TAG as dn, readConversationEventPageAfter as do, getOpenReviewItemByDedupeKey as dr, cancelHumanFacingPendingMessages as dt, slackExternalRefIdSchema as ea, verifyScheduledAutomationCredentialSubject as ei, instructionTextForProjection as en, conversationHasParticipantUser as eo, sendPushNotificationToUser as er, completeTurnRecord as et, recordAuthorizationRequested as f, runWithWorkspaceTeamId as fa, renderToolResultNudge as fi, TURN_CONTEXT_TAG as fn, readConversationEventPageAround as fo, getReviewItem as fr, checkInConversationWork as ft, recordToolExecutionStarted as g, wrapSandboxSetupError as ga, getWorkspaceByName as gi, renderTag as gn, loadForkHistory as go, reviewItemsNeedingUserVersionQuery as gr, completeConversationStop as gt, recordSubscribedReplyRoute as h, throwSandboxOperationError as ha, getWorkspace as hi, renderChildTag as hn, buildSentryConversationUrl as ho, listWaitingConversations as hr, clearExpiredConversationLease as ht, loadConversationProjection as i, getHeaderString as ia, getDashboardConversationLink as ii, isToolResultError as in, conversationViewerMarks as io, readNotificationSchedule as ir, recordTurnSummary as it, getConversationMessageSlackTs as j, sleep$2 as ja, proxyVercelSandboxEgressRequest as ji, getExperimentalFeatures as jn, createPluginCache as jo, automationCreatorUserId as jr, releaseConversationWork as jt, createConversationMemoryService as k, normalizeSandboxEgressTracePropagationDomains as ka, getSandboxProvider as ki, getAgentContextCompactionTriggerTokens as kn, resolveUserTimezone as ko, reviewItemReaderForUser as kr, recordAttemptFailure as kt, recordAttachmentsDelivered as l, runWithSlackInstallationToken as la, setDashboardConversationLinkOptions as li, trimTrailingAssistantMessages as ln, readLatestConversationBrief as lo, countReviewItemsNeedingUser as lr, appendInboundMessage as lt, recordMcpProviderConnected as m, isAlreadyExistsError as ma, deleteWorkspace as mi, escapeTagText as mn, readConversationMessageEventSeq as mo, listReplyActionItems as mr, clearConsumedConversationWake as mt, commitMessages as n, downloadPrivateSlackFile as na, verifyTimerWatchCredentialSubject as ni, isContinuablePiBoundary as nn, conversationNotArchivedFor as no, deletePushSubscription as nr, getTurnRecord as nt, loadTurnProjection as o, isConversationScopedChannel as oa, getDashboardReviewItemLink as oi, normalizeToolNameFromResult as on, viewerMarksFromParticipant as oo, savePushSubscription as or, CONVERSATION_WORK_STALE_ENQUEUE_MS as ot, recordGuardianActionReviewed as p, isAbortError as pa, createWorkspace as pi, escapeClosingTags as pn, readConversationLastEventSeq as po, insertReviewItem as pr, claimInboundMessage as pt, clearPendingAuth as q, runNonInteractiveCommand as qa, openSlackModal as qi, getPlugins as qn, getWatch as qr, persistWithRetry as qt, loadConnectedMcpProviders as r, getFilePermalink as ra, JUNIOR_THREAD_STATE_TTL_MS as ri, isStandaloneRuntimeContextMessage as rn, conversationPinnedForUser as ro, listPushSubscriptions as rr, listTurnSummaries as rt, openConversationProjection as s, isDmChannel as sa, getDashboardSettingsLink as si, retainRuntimeTurnContext as sn, createPluginConversationEvents as so, REVIEW_ITEM_REPLIED_REASON as sr, ackMessages as st, commitAcceptedReply as t, SlackActionError as ta, verifySlackDirectCredentialSubject as ti, isAssistantMessage as tn, conversationIsMemberRoot as to, resolveNotificationTimezone as tr, failTurnRecord as tt, recordAuthenticationLinked as u, withSlackRetries as ua, ToolInputError as ui, REQUEST_CONTEXT_SECTION_TAG as un, readConversationEventPage as uo, dismissOpenReviewItems as ur, beginConversationResume as ut, hydrateConversationMessages as v, getWorkspaceSnapshotNotReadyError as va, listWorkspacesByRepository as vi, tagJson as vn, getSlackFileId as vo, takeReviewItem as vr, deadLetterAttempt as vt, settleConversationTitleWork as w, createSandboxEgressCredentialToken as wa, setWorkspaceSnapshotBuild as wi, getThreadStopDecision as wn, saveObjectAnnotations as wo, isOnlyAssignee as wr, isFinalAttempt as wt, projectConversationMessages as x, clearSandboxEgressSignals as xa, invalidateReadySnapshot as xi, SubscribedReplyReason as xn, recordSlackAttachment as xo, canActOnReviewItem as xr, getConversationWorkState as xt, persistConversationMessages as y, isWorkspaceSnapshotNotReadyError as ya, updateWorkspace as yi, buildDeterministicAssistantMessageId as yn, matchSlackAttachments as yo, updateReviewItemContent as yr, drainConversationMailbox as yt, PluginCredentialFailureError as z, SANDBOX_REPOS_ROOT as za, normalizeSlackReplyMarkdown as zi, agent_hooks_exports as zn, getConfigDefaults as zo, STOP_WATCHING_TOOL_NAME as zr, TURN_LIMIT_WRAP_UP_MESSAGE as zt };
15489
+ export { pauseLostWorkerTurn as $, createConversationAccessReader as $a, updateSlackMessage as $i, registration_exports as $n, bindScheduledAutomationCredentialSubject as $r, getUserMessageInstructionText as $t, isHumanConversationMessage as A, resolveSandboxCommandEnvironment as Aa, ensureDockerDaemon as Ai, getAgentBackgroundCompactionMarkTokens as An, lookupSlackUser as Ao, reviewItemNeedsSomeone as Ar, moveIdleConversationDestination as At, createPluginAuthOrchestration as B, SANDBOX_DATA_ROOT as Ba, formatSlackLink as Bi, resolvePluginOAuthAccount as Bn, getConfigDefaults as Bo, RESOURCE_WATCH_TOOL_SOURCE as Br, stopConversationWork as Bt, resolveConversationTitle as C, clearSandboxEgressSignals as Ca, invalidateReadySnapshot as Ci, SubscribedReplyReason as Cn, resolveRootVisibility as Co, canActOnReviewItem as Cr, getConversationWorkState as Ct, buildConversationContext as D, parseSandboxEgressCredentialToken as Da, create as Di, calculateContextCompactionTargetTokens as Dn, listConversationAnnotationsById as Do, readReviewItemAgentScope as Dr, isInvalidConversationRecordError as Dt, resolveTaskTitle as E, createSandboxEgressCredentialToken as Ea, setWorkspaceSnapshotBuild as Ei, getThreadStopDecision as En, listConversationAnnotations as Eo, isOnlyAssignee as Er, isFinalAttempt as Et, trimConversationMessages as F, workspaceRepoCheckoutPath as Fa, formatProviderLabel as Fi, setExperimentalFeatures as Fn, historyItemFromPiMessage as Fo, resolveAssignees as Fr, removeActiveConversation as Ft, abandonReplacedPendingAuth as G, sandboxSkillFile as Ga, addReactionToMessage as Gi, getPluginSlackConversationLink as Gn, createTimerWatch as Gr, buildTurnErrorResponse as Gt, AuthPausePersistenceError as H, SANDBOX_SKILLS_ROOT as Ha, normalizeSlackStatusText as Hi, createPluginHookRunner as Hn, cancelSubscriptions as Hr, TurnBudgetExceededError as Ht, turnHasReply as I, PluginToolDeniedError as Ia, parseOAuthStatePayload as Ii, createUserTokenStore as In, piMessageFromHistoryItem as Io, resolveChannelCapabilities as Ir, requestAnotherSlice as It, getConversationPendingAuth as J, buildNonInteractiveShellScript as Ja, openSlackDirectMessage as Ji, getPluginUserPromptContributions as Jn, findMatchingWatches as Jr, CODEMODE_TOOL_NAME as Jt, canReusePendingAuthLink as K, sandboxSkillPathResolution as Ka, deleteSlackMessage as Ki, getPluginSystemPromptContributions as Kn, createWatch as Kr, createTurnLimitGate as Kt, upsertConversationMessage as L, createPluginEmbedder as La, resolveBaseUrl as Li, findLegacyWebActorUserId as Ln, projectConversationEvents$1 as Lo, getSlackToolContext as Lr, requestConversationWork as Lt, markConversationMessage as M, SANDBOX_RUNTIME as Ma, isVercelSandboxEgressRequest as Mi, getAgentContextInputLimitTokens as Mn, createPluginCache as Mo, EVERYONE_ASSIGNEE as Mr, recordConversationRetry as Mt, normalizeConversationText as N, sleep$2 as Na, proxyVercelSandboxEgressRequest as Ni, getExperimentalFeatures as Nn, createDurableLocationConfigurationService as No, automationCreatorUserId as Nr, releaseConversationWork as Nt, estimateConversationMessagesTokens as O, sandboxEgressSignalsResponseSchema as Oa, hash as Oi, estimateRequestOverheadTokens as On, defaultTimezone as Oo, requireReviewItemAssignees as Or, listActiveConversationIds as Ot, recordDeliveredAssistantMessage as P, tryWorkspaceRepoCheckoutPath as Pa, deliverOAuthAuthorization as Pi, isExperimentalFeatureEnabled as Pn, configValueSchema as Po, resolveAssignee as Pr, releaseInboundMessage as Pt, lostWorkerBeforeFirstSave as Q, canAccessConversation as Qa, removeReactionFromMessage as Qi, coreTaskRegistrations as Qn, bindEventAutomationCredentialSubject as Qr, getTerminalAssistantMessages as Qt, createPluginEgress as R, createPluginModel as Ra, startOAuthFlow as Ri, webActorUserIds as Rn, JUNIOR_NATIVE_EVENT_NAMESPACE as Ro, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Rr, startConversationWork as Rt, projectConversationMessages as S, workspaceSnapshotNotReadyUserMessage as Sa, WorkspaceValidationError as Si, buildDeterministicTurnId as Sn, slackAttachmentsVersionQuery as So, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Sr, getConversation as St, fallbackShortTitle as T, consumeSandboxEgressPermissionDeniedSignal as Ta, setWorkspaceSnapshot as Ti, getSubscribedReplyPreflightDecision as Tn, createPluginAnnotations as To, canReadReviewItem as Tr, hasRunnableConversationWork as Tt, AuthorizationFlowDisabledError as U, SANDBOX_WORKSPACE_ROOT as Ua, slackMention as Ui, getPluginApiRoutes as Un, cancelWatch as Ur, TurnSliceLimitExceededError as Ut, authorizationId as V, SANDBOX_REPOS_ROOT as Va, normalizeSlackReplyMarkdown as Vi, agent_hooks_exports as Vn, setConfigDefaults as Vo, STOP_WATCHING_TOOL_NAME as Vr, TURN_LIMIT_WRAP_UP_MESSAGE as Vt, AuthorizationPauseError as W, sandboxSkillDir as Wa, truncateStatusText as Wi, getPluginRoutes as Wn, collectEventMatchKeys as Wr, TurnToolCallLimitExceededError as Wt, continuableMessages as X, createPluginModelCostRecorder as Xa, postSlackEphemeralMessage as Xi, setPlugins as Xn, listWatches as Xr, extractAssistantText as Xt, wasPendingAuthStopped as Y, runNonInteractiveCommand as Ya, openSlackModal as Yi, getPlugins as Yn, getWatch as Yr, persistWithRetry as Yt, loadTurnCheckpoint as Z, createPluginLogger as Za, postSlackMessage as Zi, validatePlugins as Zn, takeDueTimerWatches as Zr, getPiMessageRole as Zt, appendConversationMessages as _, throwSandboxOperationError as _a, getWorkspace as _i, renderChildTag as _n, notInheritedByForkChild as _o, listWaitingConversations as _r, clearExpiredConversationLease as _t, loadProjection as a, getFilePermalink as aa, JUNIOR_THREAD_STATE_TTL_MS as ai, isStandaloneRuntimeContextMessage as an, viewerConversationMembership as ao, listPushSubscriptions as ar, listTurnSummaries as at, persistConversationMessages as b, getWorkspaceSnapshotNotReadyError as ba, listWorkspacesByRepository as bi, tagJson as bn, readAttachmentVisionSummary as bo, takeReviewItem as br, deadLetterAttempt as bt, recordAgentsInstructionsUpdated as c, isConversationScopedChannel as ca, getDashboardReviewItemLink as ci, normalizeToolNameFromResult as cn, readConversationBriefThrough as co, savePushSubscription as cr, CONVERSATION_WORK_STALE_ENQUEUE_MS as ct, recordAuthorizationCompleted as d, runWithSlackInstallationToken as da, setDashboardConversationLinkOptions as di, trimTrailingAssistantMessages as dn, readConversationEventPageAfter as do, countReviewItemsNeedingUser as dr, appendInboundMessage as dt, uploadFilesToConversation as ea, bindSlackDirectCredentialSubject as ei, hasRuntimeTurnContext as en, readConversationAccessFromSql as eo, setBriefsConfig as er, saveTurnCheckpoint as et, recordAuthorizationRequested as f, withSlackRetries as fa, ToolInputError as fi, REQUEST_CONTEXT_SECTION_TAG as fn, readConversationEventPageAround as fo, dismissOpenReviewItems as fr, beginConversationResume as ft, recordToolExecutionStarted as g, isAlreadyExistsError as ga, deleteWorkspace as gi, escapeTagText as gn, loadForkHistory as go, listReplyActionItems as gr, clearConsumedConversationWake as gt, recordSubscribedReplyRoute as h, isAbortError as ha, createWorkspace as hi, escapeClosingTags as hn, buildSentryConversationUrl as ho, insertReviewItem as hr, claimInboundMessage as ht, loadConversationProjection as i, downloadPrivateSlackFile as ia, verifyTimerWatchCredentialSubject as ii, isContinuablePiBoundary as in, conversationViewerMarks as io, deletePushSubscription as ir, getTurnRecord as it, latestConversationMessageSeq as j, normalizeSandboxEgressTracePropagationDomains as ja, getSandboxProvider as ji, getAgentContextCompactionTriggerTokens as jn, lookupSlackUserNames as jo, reviewItemReaderForUser as jr, recordAttemptFailure as jt, getConversationMessageSlackTs as k, buildSandboxEgressNetworkPolicy as ka, isStale as ki, estimateTextTokens as kn, resolveUserTimezone as ko, requireReviewItemLinks as kr, markConversationWorkEnqueued as kt, recordAttachmentsDelivered as l, isDmChannel as la, getDashboardSettingsLink as li, retainRuntimeTurnContext as ln, readLatestConversationBrief as lo, REVIEW_ITEM_REPLIED_REASON as lr, ackMessages as lt, recordMcpProviderConnected as m, runWithWorkspaceTeamId as ma, renderToolResultNudge as mi, TURN_CONTEXT_TAG as mn, readConversationMessageEventSeq as mo, getReviewItem as mr, checkInConversationWork as mt, commitMessages as n, slackExternalRefIdSchema as na, verifyScheduledAutomationCredentialSubject as ni, instructionTextForProjection as nn, conversationIsMemberRoot as no, sendPushNotificationToUser as nr, completeTurnRecord as nt, loadTurnProjection as o, getHeaderString as oa, getDashboardConversationLink as oi, isToolResultError as on, viewerMarksFromParticipant as oo, readNotificationSchedule as or, recordTurnSummary as ot, recordGuardianActionReviewed as p, getWorkspaceTeamId as pa, createPluginState as pi, SESSION_CONTEXT_SECTION_TAG as pn, readConversationLastEventSeq as po, getOpenReviewItemByDedupeKey as pr, cancelHumanFacingPendingMessages as pt, clearPendingAuth as q, buildCommandScript as qa, getSlackMessagePermalink as qi, getPluginTools as qn, deliverWatch as qr, isTurnExecutionLimitExceededError as qt, loadConnectedMcpProviders as r, SlackActionError as ra, verifySlackDirectCredentialSubject as ri, isAssistantMessage as rn, conversationPinnedForUser as ro, resolveNotificationTimezone as rr, failTurnRecord as rt, openConversationProjection as s, getSlackClient as sa, getDashboardObjectIconLink as si, isToolResultMessage as sn, createPluginConversationEvents as so, saveNotificationSchedule as sr, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as st, commitAcceptedReply as t, slackEntitySchema as ta, verifyEventAutomationCredentialSubject as ti, hasTurnInput as tn, conversationHasParticipantUser as to, readWebPushConfig as tr, abandonTurnRecord as tt, recordAuthenticationLinked as u, normalizeSlackConversationId as ua, getDashboardTaskLink as ui, stripRuntimeTurnContext as un, readConversationEventPage as uo, closeReviewItem as ur, appendExclusiveInboundMessage as ut, hydrateConversationMessages as v, wrapSandboxSetupError as va, getWorkspaceByName as vi, renderTag as vn, getSlackFileId as vo, reviewItemsNeedingUserVersionQuery as vr, completeConversationStop as vt, settleConversationTitleWork as w, consumeSandboxEgressAuthRequiredSignal as wa, loadSnapshotsForProfile as wi, decideSubscribedThreadReply as wn, saveObjectAnnotations as wo, canAgentChangeReviewItem as wr, hasConversationStop as wt, toStoredConversationMessage as x, isWorkspaceSnapshotNotReadyError as xa, updateWorkspace as xi, buildDeterministicAssistantMessageId as xn, recordSlackAttachment as xo, updateReviewItemContent as xr, drainConversationMailbox as xt, persistConversationMessageWindow as y, WorkspaceSnapshotNotReadyError as ya, listWorkspaces as yi, renderUntrustedTag as yn, matchSlackAttachments as yo, searchReviewItems as yr, completeConversationWork as yt, PluginCredentialFailureError as z, SANDBOX_COMMAND_PATH as za, escapeSlackMrkdwnText as zi, getOAuthAccountProviders as zn, conversationNoteEvent as zo, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as zr, steerWebPendingMessages as zt };