@sentry/junior 0.302.0 → 0.304.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 (100) hide show
  1. package/dist/{adapter-context-Cx9fn9B3.js → adapter-context-B1IpoELr.js} +2 -2
  2. package/dist/{admin-_poE5NKL.js → admin-BnVFGo_z.js} +5 -5
  3. package/dist/{agent-runner-CY9RvsTX.js → agent-runner-CoEeZSRh.js} +1461 -1248
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +6 -6
  6. package/dist/api.d.ts +13 -12
  7. package/dist/api.js +230 -105
  8. package/dist/{app-BpY3wtRP.d.ts → app-Cs157Zc5.d.ts} +17 -15
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +108 -96
  11. package/dist/{automation-Cva5ZOwW.js → automation-CuA3yEcD.js} +3 -1
  12. package/dist/{background-compaction-queue-CXFq1_Cz.js → background-compaction-queue-WLPNSF_b.js} +6 -6
  13. package/dist/{briefs-B3NG-pid.js → briefs-CagVVefw.js} +12 -9
  14. package/dist/{catalog-runtime-Dss0lSV6.js → catalog-runtime-B8ZXvXWm.js} +2 -2
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +21 -21
  17. package/dist/cli/check.js +10 -10
  18. package/dist/cli/env.d.ts +1 -0
  19. package/dist/cli/env.js +8 -7
  20. package/dist/cli/init.js +13 -4
  21. package/dist/cli/main.js +4 -4
  22. package/dist/cli/plugins.js +6 -6
  23. package/dist/cli/snapshot-create.js +7 -5
  24. package/dist/cli/upgrade.d.ts +2 -2
  25. package/dist/cli/upgrade.js +6 -6
  26. package/dist/{config-CzeZiMKs.js → config-DdO1BNcw.js} +142 -67
  27. package/dist/{connections-CDYhMfrs.js → connections-D20kp0j5.js} +6 -6
  28. package/dist/{continue-in-slack-7Uf05ndC.js → continue-in-slack-BKEVMBj1.js} +8 -8
  29. package/dist/{conversation-BNXfq6Lb.js → conversation-BOqdRtUx.js} +4 -12
  30. package/dist/{conversation-feed-Clf_cv0n.js → conversation-feed-CgpgP7yi.js} +35 -2
  31. package/dist/{conversation-privacy-D9xnM5mK.js → conversation-privacy-L1SK_v0V.js} +16 -8
  32. package/dist/{conversation-turn-D7SEZgTG.js → conversation-turn-BptVJylj.js} +20 -23
  33. package/dist/{credential-sync-DoD0gW-j.js → credential-sync-D1J1CGzL.js} +19 -19
  34. package/dist/{db-B-gtnNjr.js → db-EKJnkrIb.js} +180 -17
  35. package/dist/{db-BdsCzytP.d.ts → db-zbN5ZV_o.d.ts} +26 -26
  36. package/dist/{executor-DZg20EqU.js → executor-CoIZmFK8.js} +55 -15
  37. package/dist/{history-IjdmO_r6.js → history-m2-ceTTX.js} +21 -12
  38. package/dist/{install-t1KQyTUs.js → install-BT2Pf6HP.js} +3 -3
  39. package/dist/instrumentation.d.ts +4 -4
  40. package/dist/instrumentation.js +15 -11
  41. package/dist/{lineage-C79GjoQr.js → lineage-C5DGQCS_.js} +2 -2
  42. package/dist/{logging-C9oDAg4M.js → logging-QSZuMcvo.js} +19 -19
  43. package/dist/{message-BLUCzJXN.js → message-TtxftRHj.js} +9 -9
  44. package/dist/{model-input-5jwNC45G.js → model-input-BHXfA29g.js} +4 -9
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +8 -8
  47. package/dist/{oauth-callback-server-BBl66vCb.js → oauth-callback-server-B0enqHtZ.js} +5 -4
  48. package/dist/{oauth-relay-DRzq73b6.js → oauth-relay-DAmfVmJu.js} +3 -6
  49. package/dist/{package-discovery-DJhGdS4c.js → package-discovery-x4AvVhMj.js} +1 -1
  50. package/dist/{plugin-module-Cf5gVPWP.js → plugin-module-Cv2ETe8Y.js} +1 -1
  51. package/dist/{plugins-BBX07Jzt.js → plugins-Bkk0XRo2.js} +3 -3
  52. package/dist/{projection-CIBwgD3s.js → projection-CNKK7doO.js} +755 -221
  53. package/dist/{prompt-CRQbzp5e.js → prompt-DSjhoKu5.js} +185 -12
  54. package/dist/{queue-DtCDaIct.js → queue-CDxkit82.js} +4 -4
  55. package/dist/{queue-CZyYgPF0.d.ts → queue-CbEHUO0l.d.ts} +1 -1
  56. package/dist/{registry-DdFQHZ_d.js → registry-DBDNUUmz.js} +37 -37
  57. package/dist/{resolve-CdW4BdrK.js → resolve-CQLhMWSu.js} +3 -3
  58. package/dist/{result-oOMv1t4O.js → result-B-pauj42.js} +10 -15
  59. package/dist/rolldown-runtime-BKpuH2hG.js +26 -0
  60. package/dist/{runner-DqitLtm-.js → runner-B3KxKks5.js} +10 -10
  61. package/dist/{sandbox-egress-signals-Bw9I0yfJ.js → sandbox-egress-signals-DJJX9ClG.js} +1 -1
  62. package/dist/{schema-DnVQepWP.js → schema-Bx0Mlo32.js} +77 -13
  63. package/dist/{schema-BIFM-U1a.d.ts → schema-CKcu-IK6.d.ts} +562 -23
  64. package/dist/{secrets-DebYU866.js → secrets-DHaJ5TTn.js} +4 -4
  65. package/dist/{sentry-BRTJqumy.js → sentry-CPbZjomA.js} +3 -28
  66. package/dist/{sentry-route-name-BhwWnfqj.js → sentry-route-name-C6EIzAGP.js} +1 -1
  67. package/dist/{service-account-CrZftRTb.js → service-account-2HmlNPvy.js} +49 -48
  68. package/dist/{service-account-B6mKAPVo.js → service-account-DQLqkSVv.js} +5 -5
  69. package/dist/{session-stop-DW63Z3kj.js → session-stop-DEeZKqbX.js} +132 -74
  70. package/dist/{skills-C16fz60Z.js → skills-2UrD7JkN.js} +6 -9
  71. package/dist/{slack-conversation-unfurl-BHhefEb7.js → slack-conversation-unfurl-Dd129Uov.js} +14 -18
  72. package/dist/{spawn-D_RnFYfy.js → spawn-eMho9HDJ.js} +7 -7
  73. package/dist/{legacy-web-actor-id-C-cEeWqL.js → state-Bveuc4Zh.js} +32 -32
  74. package/dist/{stop-7p1i08CY.js → stop-D_ltJLDS.js} +359 -171
  75. package/dist/{store-C28I0CVW.js → store-COeYnPL_.js} +5 -5
  76. package/dist/{task-queue-BVUJbQ28.js → task-queue-CBIDXZpV.js} +3 -3
  77. package/dist/{task-runner-CWi8j7Z6.js → task-runner-CJF7zIJL.js} +15 -18
  78. package/dist/{thread-context-D3-yYUd0.js → thread-context-Cg0jt0aE.js} +12 -12
  79. package/dist/{turn-session-routing-BFMS9ATF.js → turn-session-routing-CaY3Tp8m.js} +32 -32
  80. package/dist/{turn-user-message-C3-O8Omt.js → turn-user-message-tcom1RYd.js} +3 -3
  81. package/dist/{validation-BSFKUIb4.js → validation-EU91JwIT.js} +2 -2
  82. package/dist/vercel.js +1 -1
  83. package/dist/{version-BHHXNi-0.js → version-BYRPhY5G.js} +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/{viewer-B1SO21Qa.js → viewer-Cf8ISkAc.js} +3 -3
  86. package/dist/{warmup-Bz9bzkzN.js → warmup-TgY4S1vx.js} +202 -577
  87. package/dist/{worker-BspReIIK.js → worker-C6Uq4OKD.js} +9 -12
  88. package/migrations/0109_user_preferences.sql +1 -0
  89. package/migrations/0110_code_change_repository_state_index.sql +1 -0
  90. package/migrations/0111_attachment_kinds.sql +14 -0
  91. package/migrations/0112_attachment_url_fill.sql +51 -0
  92. package/migrations/0113_attachment_url_index.sql +1 -0
  93. package/migrations/meta/0099_snapshot.json +102 -326
  94. package/migrations/meta/0109_snapshot.json +4925 -0
  95. package/migrations/meta/0110_snapshot.json +4952 -0
  96. package/migrations/meta/0111_snapshot.json +5011 -0
  97. package/migrations/meta/0112_snapshot.json +5011 -0
  98. package/migrations/meta/0113_snapshot.json +5033 -0
  99. package/migrations/meta/_journal.json +36 -1
  100. package/package.json +16 -19
@@ -1,20 +1,21 @@
1
- import { a as getClient$1, h as startSpan, n as captureMessage, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { C as completeObject, D as resolveGatewayModel, E as rerankTexts, L as unwrapCurrentInstruction, Q as toOptionalTrimmed, R as escapeXml, S as completeDecision, T as embedTexts, b as GEN_AI_PROVIDER_NAME, i as getChatConfig, j as estimateTextTokens, n as botConfig, o as getSlackBotToken, y as normalizeSlackEmojiName } from "./config-CzeZiMKs.js";
3
- import { E as withSpan, J as toOptionalString, K as isRecord$2, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalNumber, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-C9oDAg4M.js";
4
- import { t as canExposeConversationPayload } from "./conversation-privacy-D9xnM5mK.js";
5
- 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 { $ as fenceLock, C as isPersonInput, G as createCache, J as getStateAdapter, P as resolveActorIdentityId, Q as acquireActiveLock, V as saveUserTimezone, X as setStateValues, Y as getStateValues, Z as MUTATION_LOCK_TTL_MS, _t as sameDestination, a as getConversationStore, b as createSqlStore, c as hasAnnotationKey, ct as hasAgentTurnUsage, d as eventFromRow, dt as conversationDetailTouch, et as withLock, f as withConversationEventLock, ht as parseDestination, it as addAgentTurnUsage, j as startLocationThread, l as treeHasAnnotationKey, o as getDb, q as getDefaultRedisStateAdapterFor, r as getConversationEventStore, s as getSqlExecutor, tt as claimProviderConversation, u as createSqlConversationEventStore, z as readUserTimezone } from "./db-B-gtnNjr.js";
7
- import { D as juniorConversationAnnotations, F as juniorDestinations, M as juniorConversations, N as juniorIdentities, O as juniorCodeChanges, P as juniorUsers, T as juniorConversationEvents, a as juniorPushSubscriptions, b as juniorConversationEmbeddings, f as juniorAutomations, i as juniorWorkspaces, j as juniorAttachments, k as juniorCodeRepositories, l as juniorReviewItems, m as juniorLocationConfigurations, n as juniorSnapshots, o as juniorReviewItemAssignees, r as juniorWorkspaceRepos, s as juniorReviewItemConversations, v as juniorConversationParticipants, x as juniorConversationBriefs } from "./executor-DZg20EqU.js";
8
- import { d as contextProvenance, f as instructionActors, n as agentHistoryItemSchema, p as instructionProvenanceFor } from "./history-IjdmO_r6.js";
9
- import { _ as CredentialUnavailableError, a as resolveAuthTokenPlaceholder, f as credentialContextForActor, g as credentialUserSubjectId, h as credentialSubjectSchema, m as credentialLogContext, o as resolvePluginCommandEnv, p as credentialContextSchema } from "./registry-DdFQHZ_d.js";
10
- import { n as pluginCatalogRuntime } from "./catalog-runtime-Dss0lSV6.js";
11
- import { _ as renderJuniorNativeConversationEvent, d as embedTexts$1, f as JUNIOR_NATIVE_EVENT_NAMESPACE, h as authenticationUnlinkedEvent, l as completeObject$1, m as authenticationLinkedEvent, n as briefEntriesFromReportEvents, o as isEventConversationMessage, p as agentsInstructionsUpdatedEvent, s as generateBrief, t as BRIEF_PROMPT, u as completeText } from "./prompt-CRQbzp5e.js";
1
+ import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
+ import { d as contextProvenance, f as instructionActors, n as agentHistoryItemSchema, p as instructionProvenanceFor } from "./history-m2-ceTTX.js";
3
+ import { _ as agentsInstructionsUpdatedEvent, d as embedTexts, g as JUNIOR_NATIVE_EVENT_NAMESPACE, l as completeObject, n as briefEntriesFromReportEvents, o as isEventConversationMessage, s as generateBrief, t as BRIEF_PROMPT, u as completeText, v as authenticationLinkedEvent, x as renderJuniorNativeConversationEvent, y as authenticationUnlinkedEvent } from "./prompt-DSjhoKu5.js";
4
+ import { $ as MUTATION_LOCK_TTL_MS, I as resolveActorIdentityId, N as startLocationThread, Q as setStateValues, S as createSqlStore, T as isPersonInput, U as saveUserTimezone, V as readUserTimezone, X as getStateAdapter, Y as getDefaultRedisStateAdapterFor, Z as getStateValues, _t as parseDestination, a as getConversationStore, c as hasAnnotationKey, d as eventFromRow, et as acquireActiveLock, ht as touchConversationDetail, l as treeHasAnnotationKey, m as withConversationEventLock, nt as withLock, o as getDb, ot as addAgentTurnUsage, pt as conversationDetailTouch, q as createCache, r as getConversationEventStore, rt as claimProviderConversation, s as getSqlExecutor, tt as fenceLock, u as createSqlConversationEventStore, ut as hasAgentTurnUsage, yt as sameDestination } from "./db-EKJnkrIb.js";
5
+ import { D as juniorConversationAnnotations, F as juniorUsers, I as juniorDestinations, M as juniorMessageAttachments, N as juniorConversations, O as juniorCodeChanges, P as juniorIdentities, T as juniorConversationEvents, a as juniorPushSubscriptions, b as juniorConversationEmbeddings, f as juniorAutomations, i as juniorWorkspaces, j as juniorAttachments, k as juniorCodeRepositories, l as juniorReviewItems, m as juniorLocationConfigurations, n as juniorSnapshots, o as juniorReviewItemAssignees, r as juniorWorkspaceRepos, s as juniorReviewItemConversations, v as juniorConversationParticipants, x as juniorConversationBriefs } from "./executor-CoIZmFK8.js";
6
+ import { E as withSpan, J as toOptionalString, K as isRecord$2, _ as runBestEffort, a as extractGenAiUsageSummary, b as setSpanAttributes, c as getLogContextAttributes, d as logAudit, h as logWarn, m as logInfo, o as getActiveTraceContext, p as logException, q as toOptionalNumber, t as buildTurnFailureResponse, x as setSpanStatus, y as setSentryUser } from "./logging-QSZuMcvo.js";
7
+ 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-DBDNUUmz.js";
12
8
  import { n as isWithinNotificationSchedule, r as notificationScheduleSchema, s as isValidTimeZone, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-cP0AACm1.js";
13
- import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-B1SO21Qa.js";
14
- import { $ as briefResourceLabel, B as messageCardRef, H as readMessageCardRefs, R as reviewItemChangeRecordSchema, Y as readMessageAttachments, _ as conversationReportEventSchema, et as conversationBriefSchema, nt as parseStoredBrief, tt as parseBriefInput, v as conversationReportMessageEventSchema } from "./conversation-BNXfq6Lb.js";
9
+ import { $ as bufferBody, B as unwrapCurrentInstruction, C as completeObject$1, O as rerankTexts, P as estimateTextTokens, S as completeDecision, T as embedTexts$1, V as escapeXml, b as GEN_AI_PROVIDER_NAME, i as getChatConfig, k as resolveGatewayModel, n as botConfig, o as getSlackBotToken, tt as toOptionalTrimmed, y as normalizeSlackEmojiName } from "./config-DdO1BNcw.js";
10
+ 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";
11
+ import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-Cf8ISkAc.js";
12
+ 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-BOqdRtUx.js";
13
+ import { a as getClient$1, h as startSpan, n as captureMessage, r as continueTrace } from "./sentry-CPbZjomA.js";
14
+ import { t as canExposeConversationPayload } from "./conversation-privacy-L1SK_v0V.js";
15
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-B8ZXvXWm.js";
15
16
  import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
16
- import { i as readEncryptedState, r as createEncryptedState, t as findLegacyWebActorUserId } from "./legacy-web-actor-id-C-cEeWqL.js";
17
- import { i as readWebPushPrivateKey, t as readJuniorSecret } from "./secrets-DebYU866.js";
17
+ import { n as readEncryptedState, r as findLegacyWebActorUserId, t as createEncryptedState } from "./state-Bveuc4Zh.js";
18
+ import { i as readWebPushPrivateKey, t as readJuniorSecret } from "./secrets-DHaJ5TTn.js";
18
19
  import * as z from "zod";
19
20
  import path from "node:path";
20
21
  import { isDeepStrictEqual } from "node:util";
@@ -92,7 +93,10 @@ function historyItemFromPiMessage(message, provenance) {
92
93
  ...fields,
93
94
  type: "tool_result"
94
95
  });
95
- throw new Error(`Unsupported durable agent message role "${role}"`);
96
+ return agentHistoryItemSchema.parse({
97
+ ...fields,
98
+ type: "system_message"
99
+ });
96
100
  }
97
101
  /** Translate one Junior-native history item into the Pi message it represents. */
98
102
  function piMessageFromHistoryItem(data) {
@@ -110,6 +114,13 @@ function piMessageFromHistoryItem(data) {
110
114
  role: "assistant"
111
115
  });
112
116
  }
117
+ if (data.type === "system_message") {
118
+ const { type: _, ...fields } = data;
119
+ return piMessageSchema.parse({
120
+ ...fields,
121
+ role: "system"
122
+ });
123
+ }
113
124
  const { type: _, ...fields } = data;
114
125
  return piMessageSchema.parse({
115
126
  ...fields,
@@ -147,7 +158,7 @@ function projectConversationEvents$1(events, options = {}) {
147
158
  }
148
159
  continue;
149
160
  }
150
- if (event.data.type === "user_message" || event.data.type === "assistant_message" || event.data.type === "tool_result") {
161
+ if (event.data.type === "user_message" || event.data.type === "assistant_message" || event.data.type === "tool_result" || event.data.type === "system_message") {
151
162
  const message = piMessageFromHistoryItem(event.data);
152
163
  messages.push(message);
153
164
  provenance.push(historyItemProvenance(event.data));
@@ -212,27 +223,27 @@ function validateConfigValue(value) {
212
223
  // src/chat/configuration/service.ts
213
224
  function sanitizeEntry(value) {
214
225
  if (!isRecord$2(value)) return;
215
- const key = toOptionalString(value.key);
226
+ const key = toOptionalString(value["key"]);
216
227
  if (!key || validateConfigKey(key)) return;
217
- const updatedAt = toOptionalString(value.updatedAt);
228
+ const updatedAt = toOptionalString(value["updatedAt"]);
218
229
  if (!updatedAt) return;
219
- if (value.scope !== "channel" && value.scope !== "conversation" && value.scope !== "location") return;
220
- const parsedValue = configValueSchema.safeParse(value.value);
230
+ if (value["scope"] !== "channel" && value["scope"] !== "conversation" && value["scope"] !== "location") return;
231
+ const parsedValue = configValueSchema.safeParse(value["value"]);
221
232
  if (!parsedValue.success) return;
222
233
  return {
223
234
  key,
224
235
  value: parsedValue.data,
225
236
  scope: "location",
226
237
  updatedAt,
227
- updatedBy: toOptionalString(value.updatedBy),
228
- source: toOptionalString(value.source),
229
- expiresAt: toOptionalString(value.expiresAt)
238
+ updatedBy: toOptionalString(value["updatedBy"]),
239
+ source: toOptionalString(value["source"]),
240
+ expiresAt: toOptionalString(value["expiresAt"])
230
241
  };
231
242
  }
232
243
  /** Coerce legacy persisted configuration into current Location entries. */
233
244
  function coerceLegacyLocationConfig(raw) {
234
- const rawConfig = isRecord$2(raw) && isRecord$2(raw.configuration) ? raw.configuration : {};
235
- const rawEntries = isRecord$2(rawConfig.entries) ? rawConfig.entries : {};
245
+ const rawConfig = isRecord$2(raw) && isRecord$2(raw["configuration"]) ? raw["configuration"] : {};
246
+ const rawEntries = isRecord$2(rawConfig["entries"]) ? rawConfig["entries"] : {};
236
247
  return Object.values(rawEntries).flatMap((value) => {
237
248
  const entry = sanitizeEntry(value);
238
249
  return entry ? [entry] : [];
@@ -714,7 +725,7 @@ async function replaceSlackMentions(value, provider) {
714
725
  });
715
726
  const matches = [...tokens.values()].flat();
716
727
  if (matches.length === 0) return value;
717
- const people = await readSlackPeople([...new Set(matches.flatMap((match) => match.groups?.user ?? []))], provider);
728
+ const people = await readSlackPeople([...new Set(matches.flatMap((match) => match.groups?.["user"] ?? []))], provider);
718
729
  return mapStrings(value, (text) => {
719
730
  let result = "";
720
731
  let cursor = 0;
@@ -852,7 +863,7 @@ async function lookupSlackUserNames(teamId, userIds) {
852
863
  const DEFAULT_TIMEZONE = "America/Los_Angeles";
853
864
  /** The install timezone, used when Junior does not know a person's timezone. */
854
865
  function defaultTimezone() {
855
- return process.env.JUNIOR_TIMEZONE?.trim() || DEFAULT_TIMEZONE;
866
+ return process.env["JUNIOR_TIMEZONE"]?.trim() || DEFAULT_TIMEZONE;
856
867
  }
857
868
  /**
858
869
  * Pick a person's timezone: their Slack profile, then the saved user
@@ -974,18 +985,23 @@ async function saveObjectAnnotations(conversationId, plugin, value) {
974
985
  plugin
975
986
  }));
976
987
  }
977
- /** Save annotations from a successful plugin tool result and attach their cards. */
978
- async function annotateToolResult(conversationId, plugin, result) {
979
- if (!isRecord$2(result) || result.isError === true) return result;
980
- const details = isRecord$2(result.details) ? result.details : result;
981
- if (details.timed_out === true || details.isError === true || !Array.isArray(details.objectAnnotations)) return result;
982
- const cards = await saveObjectAnnotations(conversationId, plugin, details.objectAnnotations);
988
+ /**
989
+ * Save annotations from a successful plugin tool result and attach their cards.
990
+ * An Annotation marks work that the Conversation did, so a read-only tool must
991
+ * not return one: looking up an object does not link it.
992
+ */
993
+ async function annotateToolResult(conversationId, plugin, result, options) {
994
+ if (!isRecord$2(result) || result["isError"] === true) return result;
995
+ const details = isRecord$2(result["details"]) ? result["details"] : result;
996
+ if (details["timed_out"] === true || details["isError"] === true || !Array.isArray(details["objectAnnotations"])) return result;
997
+ if (options.readOnly) throw new Error(`Read-only ${plugin} tool returned objectAnnotations. Return them only from tools that change the object.`);
998
+ const cards = await saveObjectAnnotations(conversationId, plugin, details["objectAnnotations"]);
983
999
  const { objectAnnotations: _annotations, ...rest } = details;
984
1000
  const annotated = {
985
1001
  ...rest,
986
1002
  objectCards: cards
987
1003
  };
988
- if (isRecord$2(result.details)) return {
1004
+ if (isRecord$2(result["details"])) return {
989
1005
  ...result,
990
1006
  details: annotated
991
1007
  };
@@ -1002,7 +1018,7 @@ const MAX_EMBEDDED_CHARS = 8e3;
1002
1018
  /** Create the embedder that charges its cost to one Conversation. */
1003
1019
  function createConversationEmbedder(args) {
1004
1020
  return async ({ inputType, text }) => {
1005
- const result = await embedTexts$1({
1021
+ const result = await embedTexts({
1006
1022
  cost: args.cost,
1007
1023
  inputType,
1008
1024
  modelId: botConfig.embeddingModelId,
@@ -1202,10 +1218,10 @@ function createPluginConversations(conversationId) {
1202
1218
  */
1203
1219
  async function recordToolReply(args) {
1204
1220
  const { result } = args;
1205
- if (!isRecord$2(result) || result.isError === true) return result;
1206
- const details = isRecord$2(result.details) ? result.details : result;
1207
- if (details.reply === void 0) return result;
1208
- const reply = pluginToolReplySchema.parse(details.reply);
1221
+ if (!isRecord$2(result) || result["isError"] === true) return result;
1222
+ const details = isRecord$2(result["details"]) ? result["details"] : result;
1223
+ if (details["reply"] === void 0) return result;
1224
+ const reply = pluginToolReplySchema.parse(details["reply"]);
1209
1225
  if (args.toolCallId) await getConversationEventStore().append(args.conversationId, [{
1210
1226
  idempotencyKey: `reply_posted:tool:${args.toolCallId}`,
1211
1227
  data: {
@@ -1218,7 +1234,7 @@ async function recordToolReply(args) {
1218
1234
  createdAtMs: Date.now()
1219
1235
  }]);
1220
1236
  const { reply: _reply, ...rest } = details;
1221
- if (isRecord$2(result.details)) return {
1237
+ if (isRecord$2(result["details"])) return {
1222
1238
  ...result,
1223
1239
  details: rest
1224
1240
  };
@@ -1472,7 +1488,7 @@ function mapSlackError(error) {
1472
1488
  statusCode: candidate.statusCode,
1473
1489
  requestId: getHeaderString(candidate.headers, "x-slack-req-id"),
1474
1490
  errorData: serializeSlackErrorData(candidate.data),
1475
- ...parseSlackCanvasDetail(candidate.data?.detail)
1491
+ ...parseSlackCanvasDetail(candidate.data?.["detail"])
1476
1492
  };
1477
1493
  if (apiError === "missing_scope") return new SlackActionError(message, "missing_scope", {
1478
1494
  ...baseOptions,
@@ -1710,6 +1726,485 @@ async function streamPrivateSlackFile(url) {
1710
1726
  if (!response.body) throw new Error("Slack file download returned no body");
1711
1727
  return response.body;
1712
1728
  }
1729
+ // src/chat/attachments/store.ts
1730
+ const DAY_MS$3 = 864e5;
1731
+ const ATTACHMENT_GC_BATCH_LIMIT = 200;
1732
+ /** Time that Junior keeps attachment bytes after the file is stored. */
1733
+ const ATTACHMENT_RETENTION_MS = 30 * DAY_MS$3;
1734
+ /** Only `file` rows: a `url` row has no storage or file fields. */
1735
+ const isFileAttachment = eq(juniorAttachments.kind, "file");
1736
+ /**
1737
+ * The storage and file fields of a `file` row. Every `file` row has them, so
1738
+ * a missing one is a broken row.
1739
+ */
1740
+ function fileFields(row) {
1741
+ const { bytes, contentType, storageProvider, title } = row;
1742
+ if (bytes === null || contentType === null || storageProvider === null || title === null) throw new Error(`Attachment ${row.id} has no file fields`);
1743
+ return {
1744
+ bytes,
1745
+ contentType,
1746
+ filename: title,
1747
+ storageProvider
1748
+ };
1749
+ }
1750
+ function attachmentIdentity(file) {
1751
+ if ("data" in file) return file.source ?? { sha256: createHash("sha256").update(file.data).digest("hex") };
1752
+ return file.source;
1753
+ }
1754
+ /** Stable conversation-owned id for one file and its presentation metadata. */
1755
+ function attachmentId(args) {
1756
+ const identity = "sha256" in args.identity ? [
1757
+ args.conversationId,
1758
+ args.storageProvider,
1759
+ args.identity.sha256,
1760
+ args.filename,
1761
+ args.contentType
1762
+ ] : [
1763
+ args.conversationId,
1764
+ args.storageProvider,
1765
+ args.filename,
1766
+ args.contentType,
1767
+ args.identity.provider,
1768
+ args.identity.id
1769
+ ];
1770
+ return createHash("sha256").update(identity.join("\0")).digest("hex");
1771
+ }
1772
+ /**
1773
+ * Object key for one write attempt.
1774
+ *
1775
+ * Attachment ids are content-stable. Object keys are not: each put gets a fresh
1776
+ * key so a failed-write cleanup or GC delete cannot remove another writer's
1777
+ * durable blob.
1778
+ */
1779
+ function attachmentKey(args) {
1780
+ return `conversations/${args.conversationId}/attachments/${args.attachmentId}/${args.writeId}/${args.filename}`;
1781
+ }
1782
+ /** A source whose bytes do not match its declared size. A retry cannot fix it. */
1783
+ var AttachmentSizeError = class extends Error {
1784
+ constructor(bytes, expected, options) {
1785
+ super(`Attachment body does not match its declared ${expected} bytes (read ${bytes})`, options);
1786
+ this.name = "AttachmentSizeError";
1787
+ }
1788
+ };
1789
+ /** Tries for one object write, each with a freshly opened body. */
1790
+ const WRITE_ATTEMPTS = 3;
1791
+ async function bestEffortDelete(storage, key) {
1792
+ if (key === null) return;
1793
+ try {
1794
+ await storage.delete([key]);
1795
+ } catch {}
1796
+ }
1797
+ /**
1798
+ * Stream one file to a fresh key, and return its size and digest.
1799
+ *
1800
+ * The digest is taken while the bytes stream, so the body is never held
1801
+ * whole. A body that does not match its declared size is not kept.
1802
+ */
1803
+ async function writeAttachmentObject(args) {
1804
+ for (let attempt = 1;; attempt += 1) try {
1805
+ return await writeAttachmentObjectOnce(args);
1806
+ } catch (error) {
1807
+ if (error instanceof AttachmentSizeError || error instanceof AttachmentSourceUnavailableError || attempt >= WRITE_ATTEMPTS) {
1808
+ await bestEffortDelete(args.storage, args.key);
1809
+ throw error;
1810
+ }
1811
+ }
1812
+ }
1813
+ async function writeAttachmentObjectOnce(args) {
1814
+ const { file } = args;
1815
+ const expected = "data" in file ? file.data.byteLength : file.bytes;
1816
+ const source = "data" in file ? bufferBody(file.data) : await file.open();
1817
+ const hash = createHash("sha256");
1818
+ let bytes = 0;
1819
+ const body = source.pipeThrough(new TransformStream({ transform(chunk, controller) {
1820
+ bytes += chunk.byteLength;
1821
+ if (bytes > expected) throw new AttachmentSizeError(bytes, expected);
1822
+ hash.update(chunk);
1823
+ controller.enqueue(chunk);
1824
+ } }));
1825
+ try {
1826
+ await args.storage.put({
1827
+ body,
1828
+ bytes: expected,
1829
+ contentType: file.mimeType,
1830
+ key: args.key
1831
+ });
1832
+ } catch (error) {
1833
+ if (bytes > expected) throw new AttachmentSizeError(bytes, expected, { cause: error });
1834
+ throw error;
1835
+ }
1836
+ if (bytes !== expected) throw new AttachmentSizeError(bytes, expected);
1837
+ return {
1838
+ bytes,
1839
+ sha256: hash.digest("hex")
1840
+ };
1841
+ }
1842
+ async function isConversationPurged(db, conversationId) {
1843
+ const [row] = await db.db().select({ transcriptPurgedAt: juniorConversations.transcriptPurgedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
1844
+ return row?.transcriptPurgedAt != null;
1845
+ }
1846
+ function purgedConversationError(conversationId) {
1847
+ return /* @__PURE__ */ new Error(`Cannot store attachment for purged conversation ${conversationId}`);
1848
+ }
1849
+ async function assertConversationNotPurged(db, conversationId) {
1850
+ if (await isConversationPurged(db, conversationId)) throw purgedConversationError(conversationId);
1851
+ }
1852
+ /** Mark a just-written row for deletion and drop its unused object. */
1853
+ async function rejectPurgedAttachmentWrite(args) {
1854
+ const db = args.db.db();
1855
+ await db.with(conversationDetailTouch(db, [args.conversationId])).update(juniorAttachments).set({ deleteRequestedAt: args.now }).where(eq(juniorAttachments.id, args.id));
1856
+ await bestEffortDelete(args.storage, args.storageKey);
1857
+ throw purgedConversationError(args.conversationId);
1858
+ }
1859
+ /**
1860
+ * Return another writer's live row only when the conversation is still active.
1861
+ *
1862
+ * The caller already wrote a unique object for this attempt. Delete that unused
1863
+ * object either way. If the conversation is purged, do not report success for a
1864
+ * row that purge/GC is about to remove.
1865
+ */
1866
+ async function reuseLiveAttachment(args) {
1867
+ await bestEffortDelete(args.storage, args.storageKey);
1868
+ await assertConversationNotPurged(args.db, args.conversationId);
1869
+ return { id: args.id };
1870
+ }
1871
+ /**
1872
+ * Persist one conversation-owned file.
1873
+ *
1874
+ * Identity is stable under the conversation: it comes from the file's source
1875
+ * when it has one, and from its digest otherwise. Object storage is written
1876
+ * first under a unique key; the SQL row is created only after that write
1877
+ * succeeds. A row means the attachment is durable. Retries reuse an existing
1878
+ * live row. A purge-marked row is revived by writing a new object and pointing
1879
+ * the row at it, unless the conversation is still purged. If the SQL write
1880
+ * fails after object storage accepts the bytes, this path deletes that unique
1881
+ * object. A process crash between those steps can leave an unreferenced unique
1882
+ * object with no SQL row.
1883
+ */
1884
+ async function storeAttachment(args) {
1885
+ const now = new Date(args.nowMs ?? Date.now());
1886
+ const identity = attachmentIdentity(args.file);
1887
+ const source = args.file.source;
1888
+ const id = attachmentId({
1889
+ conversationId: args.conversationId,
1890
+ contentType: args.file.mimeType,
1891
+ filename: args.file.filename,
1892
+ identity,
1893
+ storageProvider: args.storage.provider
1894
+ });
1895
+ const [existing] = await args.db.db().select({
1896
+ contentType: juniorAttachments.contentType,
1897
+ conversationId: juniorAttachments.conversationId,
1898
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
1899
+ filename: juniorAttachments.title,
1900
+ id: juniorAttachments.id,
1901
+ provider: juniorAttachments.provider,
1902
+ providerId: juniorAttachments.providerId,
1903
+ storageProvider: juniorAttachments.storageProvider,
1904
+ sha256: juniorAttachments.sha256,
1905
+ storageKey: juniorAttachments.storageKey
1906
+ }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
1907
+ if (existing) {
1908
+ if (existing.contentType !== args.file.mimeType || existing.conversationId !== args.conversationId || existing.filename !== args.file.filename || existing.provider !== (source?.provider ?? null) || existing.providerId !== (source?.id ?? null) || existing.storageProvider !== args.storage.provider || "sha256" in identity && existing.sha256 !== identity.sha256) throw new Error(`Attachment write conflicts with ${existing.id}`);
1909
+ if (existing.deleteRequestedAt === null) {
1910
+ await assertConversationNotPurged(args.db, args.conversationId);
1911
+ return { id: existing.id };
1912
+ }
1913
+ }
1914
+ await assertConversationNotPurged(args.db, args.conversationId);
1915
+ const { file } = args;
1916
+ let storageKey = null;
1917
+ let written;
1918
+ if ("deferred" in file) written = {
1919
+ bytes: file.bytes,
1920
+ sha256: null
1921
+ };
1922
+ else {
1923
+ storageKey = attachmentKey({
1924
+ attachmentId: id,
1925
+ conversationId: args.conversationId,
1926
+ filename: file.filename,
1927
+ writeId: randomUUID()
1928
+ });
1929
+ written = await writeAttachmentObject({
1930
+ file,
1931
+ key: storageKey,
1932
+ storage: args.storage
1933
+ });
1934
+ }
1935
+ if (existing?.deleteRequestedAt != null) {
1936
+ if (await isConversationPurged(args.db, args.conversationId)) {
1937
+ await bestEffortDelete(args.storage, storageKey);
1938
+ throw purgedConversationError(args.conversationId);
1939
+ }
1940
+ const oldStorageKey = existing.storageKey;
1941
+ if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
1942
+ ...written,
1943
+ deleteRequestedAt: null,
1944
+ storageKey
1945
+ }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
1946
+ if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
1947
+ conversationId: args.conversationId,
1948
+ db: args.db,
1949
+ id,
1950
+ now,
1951
+ storage: args.storage,
1952
+ storageKey
1953
+ });
1954
+ if (oldStorageKey !== storageKey) await bestEffortDelete(args.storage, oldStorageKey);
1955
+ return { id };
1956
+ }
1957
+ const [afterRace] = await args.db.db().select({
1958
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
1959
+ id: juniorAttachments.id,
1960
+ storageKey: juniorAttachments.storageKey
1961
+ }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
1962
+ if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
1963
+ conversationId: args.conversationId,
1964
+ db: args.db,
1965
+ id: afterRace.id,
1966
+ storage: args.storage,
1967
+ storageKey
1968
+ });
1969
+ }
1970
+ let inserted = [];
1971
+ try {
1972
+ inserted = await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).insert(juniorAttachments).values({
1973
+ id,
1974
+ conversationId: args.conversationId,
1975
+ storageProvider: args.storage.provider,
1976
+ storageKey,
1977
+ provider: source?.provider,
1978
+ providerId: source?.id,
1979
+ title: args.file.filename,
1980
+ contentType: args.file.mimeType,
1981
+ ...written,
1982
+ createdAt: now
1983
+ }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id });
1984
+ } catch (error) {
1985
+ await bestEffortDelete(args.storage, storageKey);
1986
+ throw error;
1987
+ }
1988
+ if (inserted.length > 0) {
1989
+ if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
1990
+ conversationId: args.conversationId,
1991
+ db: args.db,
1992
+ id,
1993
+ now,
1994
+ storage: args.storage,
1995
+ storageKey
1996
+ });
1997
+ return { id };
1998
+ }
1999
+ const [row] = await args.db.db().select({
2000
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
2001
+ id: juniorAttachments.id,
2002
+ storageKey: juniorAttachments.storageKey
2003
+ }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
2004
+ if (!row) {
2005
+ await bestEffortDelete(args.storage, storageKey);
2006
+ throw new Error(`Attachment row missing after write for ${id}`);
2007
+ }
2008
+ if (row.deleteRequestedAt === null) return reuseLiveAttachment({
2009
+ conversationId: args.conversationId,
2010
+ db: args.db,
2011
+ id: row.id,
2012
+ storage: args.storage,
2013
+ storageKey
2014
+ });
2015
+ if (await isConversationPurged(args.db, args.conversationId)) {
2016
+ await bestEffortDelete(args.storage, storageKey);
2017
+ throw purgedConversationError(args.conversationId);
2018
+ }
2019
+ if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [args.conversationId])).update(juniorAttachments).set({
2020
+ ...written,
2021
+ deleteRequestedAt: null,
2022
+ storageKey
2023
+ }).where(and(eq(juniorAttachments.id, id), isNotNull(juniorAttachments.deleteRequestedAt))).returning({ id: juniorAttachments.id })).length > 0) {
2024
+ if (await isConversationPurged(args.db, args.conversationId)) await rejectPurgedAttachmentWrite({
2025
+ conversationId: args.conversationId,
2026
+ db: args.db,
2027
+ id,
2028
+ now,
2029
+ storage: args.storage,
2030
+ storageKey
2031
+ });
2032
+ if (row.storageKey !== storageKey) await bestEffortDelete(args.storage, row.storageKey);
2033
+ return { id };
2034
+ }
2035
+ const [afterRace] = await args.db.db().select({
2036
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
2037
+ id: juniorAttachments.id
2038
+ }).from(juniorAttachments).where(eq(juniorAttachments.id, id));
2039
+ if (afterRace?.deleteRequestedAt === null) return reuseLiveAttachment({
2040
+ conversationId: args.conversationId,
2041
+ db: args.db,
2042
+ id: afterRace.id,
2043
+ storage: args.storage,
2044
+ storageKey
2045
+ });
2046
+ await bestEffortDelete(args.storage, storageKey);
2047
+ throw new Error(`Attachment ${id} disappeared while reviving`);
2048
+ }
2049
+ /**
2050
+ * Record an object that a browser already wrote, under the upload's id.
2051
+ *
2052
+ * The row takes over the object key. A retry with the same id keeps the
2053
+ * first row. The caller checked the object's size, type, and digest.
2054
+ */
2055
+ async function recordUploadedAttachment(args) {
2056
+ const { attachment } = args;
2057
+ const now = new Date(args.nowMs);
2058
+ await assertConversationNotPurged(args.db, attachment.conversationId);
2059
+ if ((await args.db.db().with(conversationDetailTouch(args.db.db(), [attachment.conversationId])).insert(juniorAttachments).values({
2060
+ bytes: attachment.bytes,
2061
+ contentType: attachment.contentType,
2062
+ conversationId: attachment.conversationId,
2063
+ createdAt: now,
2064
+ id: attachment.id,
2065
+ sha256: attachment.sha256,
2066
+ storageKey: attachment.storageKey,
2067
+ storageProvider: args.storage.provider,
2068
+ title: attachment.filename
2069
+ }).onConflictDoNothing({ target: juniorAttachments.id }).returning({ id: juniorAttachments.id })).length > 0 && await isConversationPurged(args.db, attachment.conversationId)) await rejectPurgedAttachmentWrite({
2070
+ conversationId: attachment.conversationId,
2071
+ db: args.db,
2072
+ id: attachment.id,
2073
+ now,
2074
+ storage: args.storage,
2075
+ storageKey: attachment.storageKey
2076
+ });
2077
+ }
2078
+ /**
2079
+ * Store a file that Junior recorded without its bytes, on its first read.
2080
+ *
2081
+ * The bytes stream from the source to a fresh key. The row then takes that
2082
+ * key only while it is still unstored, live, and in a conversation that is
2083
+ * not purged. Purge marks rows in the transaction that purges the
2084
+ * conversation, so this update cannot revive a purged row. When the update
2085
+ * misses, the new object is deleted: return the row that another writer
2086
+ * stored, or null when the row is no longer live.
2087
+ */
2088
+ async function storeDeferredAttachment(args) {
2089
+ const { attachment, storage } = args;
2090
+ const storageKey = attachmentKey({
2091
+ attachmentId: attachment.id,
2092
+ conversationId: attachment.conversationId,
2093
+ filename: attachment.filename,
2094
+ writeId: randomUUID()
2095
+ });
2096
+ const written = await writeAttachmentObject({
2097
+ file: {
2098
+ bytes: args.file.bytes,
2099
+ filename: attachment.filename,
2100
+ mimeType: attachment.contentType,
2101
+ open: args.file.open,
2102
+ source: attachment.source
2103
+ },
2104
+ key: storageKey,
2105
+ storage
2106
+ });
2107
+ const db = args.db.db();
2108
+ if ((await db.with(conversationDetailTouch(db, [attachment.conversationId])).update(juniorAttachments).set({
2109
+ ...written,
2110
+ storageKey
2111
+ }).where(and(eq(juniorAttachments.id, attachment.id), eq(juniorAttachments.conversationId, attachment.conversationId), eq(juniorAttachments.storageProvider, storage.provider), isNull(juniorAttachments.storageKey), isNull(juniorAttachments.deleteRequestedAt), notExists(db.select({ id: juniorConversations.conversationId }).from(juniorConversations).where(and(eq(juniorConversations.conversationId, attachment.conversationId), isNotNull(juniorConversations.transcriptPurgedAt)))))).returning({ id: juniorAttachments.id })).length > 0) return {
2112
+ ...attachment,
2113
+ bytes: written.bytes,
2114
+ storageKey
2115
+ };
2116
+ await bestEffortDelete(storage, storageKey);
2117
+ const current = await readLiveAttachment({
2118
+ attachmentId: attachment.id,
2119
+ conversationId: attachment.conversationId,
2120
+ db: args.db
2121
+ });
2122
+ return current?.storageKey ? {
2123
+ ...current,
2124
+ storageKey: current.storageKey
2125
+ } : null;
2126
+ }
2127
+ /** Load one live attachment owned by a conversation. */
2128
+ async function readLiveAttachment(args) {
2129
+ const [row] = await args.db.db().select({
2130
+ bytes: juniorAttachments.bytes,
2131
+ contentType: juniorAttachments.contentType,
2132
+ conversationId: juniorAttachments.conversationId,
2133
+ deleteRequestedAt: juniorAttachments.deleteRequestedAt,
2134
+ id: juniorAttachments.id,
2135
+ provider: juniorAttachments.provider,
2136
+ providerId: juniorAttachments.providerId,
2137
+ storageProvider: juniorAttachments.storageProvider,
2138
+ storageKey: juniorAttachments.storageKey,
2139
+ title: juniorAttachments.title
2140
+ }).from(juniorAttachments).where(and(eq(juniorAttachments.id, args.attachmentId), isFileAttachment, eq(juniorAttachments.conversationId, args.conversationId), isNull(juniorAttachments.deleteRequestedAt)));
2141
+ if (!row) return null;
2142
+ if (await isConversationPurged(args.db, args.conversationId)) return null;
2143
+ return {
2144
+ ...fileFields(row),
2145
+ conversationId: row.conversationId,
2146
+ id: row.id,
2147
+ source: row.provider && row.providerId ? {
2148
+ id: row.providerId,
2149
+ provider: row.provider
2150
+ } : null,
2151
+ storageKey: row.storageKey
2152
+ };
2153
+ }
2154
+ /** Persist many conversation-owned files. */
2155
+ async function storeAttachments(args) {
2156
+ const stored = [];
2157
+ for (const file of args.files) stored.push(await storeAttachment({
2158
+ conversationId: args.conversationId,
2159
+ db: args.db,
2160
+ file: {
2161
+ data: file.data,
2162
+ filename: file.filename,
2163
+ mimeType: file.mimeType
2164
+ },
2165
+ ...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
2166
+ storage: args.storage
2167
+ }));
2168
+ return stored;
2169
+ }
2170
+ /** Mark attachments unavailable when their conversation content is purged. */
2171
+ async function requestAttachmentDeletion(db, conversationIds, nowMs) {
2172
+ if (conversationIds.length === 0) return;
2173
+ await db.db().with(conversationDetailTouch(db.db(), conversationIds)).update(juniorAttachments).set({ deleteRequestedAt: new Date(nowMs) }).where(and(inArray(juniorAttachments.conversationId, conversationIds), isNull(juniorAttachments.deleteRequestedAt)));
2174
+ }
2175
+ /**
2176
+ * Delete purged attachments in one bounded batch.
2177
+ *
2178
+ * Eligible files are 30 days old, explicitly purge-marked, or owned by a
2179
+ * conversation whose transcript is already purged. A `url` row has no bytes,
2180
+ * so it lives as long as its message: it is eligible only when purge-marked
2181
+ * or purged. Delete object keys first, then remove rows that are still
2182
+ * eligible so a failed blob delete remains retryable.
2183
+ */
2184
+ async function collectAttachmentGarbage(args) {
2185
+ const expiresBefore = /* @__PURE__ */ new Date(args.nowMs - ATTACHMENT_RETENTION_MS);
2186
+ const purged = or(isNotNull(juniorAttachments.deleteRequestedAt), isNotNull(juniorConversations.transcriptPurgedAt));
2187
+ const eligible = or(lte(juniorAttachments.createdAt, expiresBefore), purged);
2188
+ const isUrl = eq(juniorAttachments.kind, "url");
2189
+ const rows = await args.db.db().select({
2190
+ id: juniorAttachments.id,
2191
+ storageKey: juniorAttachments.storageKey
2192
+ }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(or(and(eq(juniorAttachments.storageProvider, args.storage.provider), eligible), and(isUrl, purged))).orderBy(asc(juniorAttachments.createdAt), asc(juniorAttachments.id)).limit(args.limit ?? ATTACHMENT_GC_BATCH_LIMIT);
2193
+ if (rows.length === 0) return { deleted: 0 };
2194
+ const keys = rows.flatMap((row) => row.storageKey ? [row.storageKey] : []);
2195
+ if (keys.length > 0) await args.storage.delete(keys);
2196
+ const stillEligible = await args.db.db().select({ id: juniorAttachments.id }).from(juniorAttachments).innerJoin(juniorConversations, eq(juniorAttachments.conversationId, juniorConversations.conversationId)).where(and(inArray(juniorAttachments.id, rows.map((row) => row.id)), or(and(isFileAttachment, eligible), and(isUrl, purged))));
2197
+ if (stillEligible.length === 0) return { deleted: 0 };
2198
+ const removed = await args.db.db().delete(juniorAttachments).where(inArray(juniorAttachments.id, stillEligible.map((row) => row.id))).returning({
2199
+ conversationId: juniorAttachments.conversationId,
2200
+ id: juniorAttachments.id,
2201
+ kind: juniorAttachments.kind
2202
+ });
2203
+ const urls = removed.filter((row) => row.kind === "url");
2204
+ if (urls.length > 0) await args.db.db().delete(juniorMessageAttachments).where(and(inArray(juniorMessageAttachments.conversationId, urls.map((row) => row.conversationId)), inArray(juniorMessageAttachments.attachmentId, urls.map((row) => row.id))));
2205
+ await touchConversationDetail(args.db.db(), removed.map((row) => row.conversationId));
2206
+ return { deleted: removed.length };
2207
+ }
1713
2208
  // src/chat/slack/attachments.ts
1714
2209
  /** Save the vision summary for a stored Slack attachment. */
1715
2210
  async function recordSlackAttachment(args) {
@@ -1729,35 +2224,47 @@ async function matchSlackAttachments(args) {
1729
2224
  providerId: juniorAttachments.providerId,
1730
2225
  bytes: juniorAttachments.bytes,
1731
2226
  contentType: juniorAttachments.contentType,
1732
- filename: juniorAttachments.filename,
1733
- storageKey: juniorAttachments.storageKey
1734
- }).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 ? {
1735
- ...row,
1736
- pending: true
1737
- } : row);
2227
+ storageKey: juniorAttachments.storageKey,
2228
+ storageProvider: juniorAttachments.storageProvider,
2229
+ title: juniorAttachments.title
2230
+ }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, args.conversationId), eq(juniorAttachments.provider, "slack"), inArray(juniorAttachments.providerId, args.providerIds), isNull(juniorAttachments.deleteRequestedAt)))).map((row) => {
2231
+ const { bytes, contentType, filename } = fileFields(row);
2232
+ const attachment = {
2233
+ bytes,
2234
+ contentType,
2235
+ filename,
2236
+ id: row.id,
2237
+ providerId: row.providerId
2238
+ };
2239
+ return row.storageKey === null ? {
2240
+ ...attachment,
2241
+ pending: true
2242
+ } : attachment;
2243
+ });
1738
2244
  }
1739
2245
  /**
1740
2246
  * Fingerprint the live Slack attachments that `matchSlackAttachments` can
1741
- * return for a Conversation. It changes when one is stored or deleted, so a
1742
- * reader can tell that stored messages may now show other files.
2247
+ * return for a Conversation. It changes when one is recorded, stored, or
2248
+ * deleted, so a reader can tell that stored messages may now show other
2249
+ * files, or a file that is no longer pending.
1743
2250
  */
1744
2251
  function slackAttachmentsVersionQuery(db, conversationId) {
1745
- 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)));
2252
+ return db.select({ version: sql`coalesce(md5(string_agg(concat(${juniorAttachments.id}, ':', ${juniorAttachments.storageKey} is null), ',' order by ${juniorAttachments.id})), '')` }).from(juniorAttachments).where(and(eq(juniorAttachments.conversationId, conversationId), eq(juniorAttachments.provider, "slack"), isNull(juniorAttachments.deleteRequestedAt)));
1746
2253
  }
1747
2254
  /** Read the Slack file identity retained by the Chat SDK. */
1748
2255
  function getSlackFileId(attachment) {
1749
- const metadataId = attachment.fetchMetadata?.fileId;
2256
+ const metadataId = attachment.fetchMetadata?.["fileId"];
1750
2257
  if (metadataId) return metadataId;
1751
- return (attachment.url ?? attachment.fetchMetadata?.url ?? "").match(/(?:^|[-/])(F[A-Z0-9]+)(?:[-/]|$)/)?.[1];
2258
+ return (attachment.url ?? attachment.fetchMetadata?.["url"] ?? "").match(/(?:^|[-/])(F[A-Z0-9]+)(?:[-/]|$)/)?.[1];
1752
2259
  }
1753
2260
  /**
1754
- * Look up a Slack file that Junior recorded without storing it.
2261
+ * Look up a Slack file that Junior recorded without storing it yet.
1755
2262
  *
1756
2263
  * Uses the installation token that the caller binds: the Slack turn, or the
1757
2264
  * dashboard route for the conversation's Slack team.
1758
2265
  */
1759
2266
  const readSlackAttachmentSource = async (source) => {
1760
- const unavailable = (cause) => new AttachmentSourceUnavailableError("The Slack file was deleted, or Junior can no longer access it.", { cause });
2267
+ const unavailable = (cause) => new AttachmentSourceUnavailableError("The Slack file was deleted, or this app can no longer access it.", { cause });
1761
2268
  if (source.provider !== "slack") throw unavailable();
1762
2269
  const file = await readPrivateSlackFile(source.id);
1763
2270
  if (!file) throw unavailable();
@@ -1786,7 +2293,7 @@ async function hydrateMessageAttachments(db, conversationId, events) {
1786
2293
  });
1787
2294
  const byFileId = new Map(attachments.map(({ providerId, ...attachment }) => [providerId, attachment]));
1788
2295
  for (const message of messages) {
1789
- const stored = readMessageAttachments(message.meta?.attachments);
2296
+ const stored = readMessageAttachments(message.meta?.["attachments"]);
1790
2297
  const matched = slackFileIds(message.meta).flatMap((id) => {
1791
2298
  const attachment = byFileId.get(id);
1792
2299
  return attachment ? [attachment] : [];
@@ -1798,7 +2305,7 @@ async function hydrateMessageAttachments(db, conversationId, events) {
1798
2305
  }
1799
2306
  }
1800
2307
  function slackFileIds(meta) {
1801
- const ids = meta?.slackFileIds ?? meta?.imageFileIds;
2308
+ const ids = meta?.["slackFileIds"] ?? meta?.["imageFileIds"];
1802
2309
  return Array.isArray(ids) ? ids.filter((id) => typeof id === "string") : [];
1803
2310
  }
1804
2311
  // src/chat/agent-invocations/fork-history.ts
@@ -1854,7 +2361,7 @@ function notInheritedByForkChild() {
1854
2361
  }
1855
2362
  // src/chat/sentry-links.ts
1856
2363
  function getSentryOrgSlug() {
1857
- return process.env.SENTRY_ORG_SLUG?.trim() || void 0;
2364
+ return process.env["SENTRY_ORG_SLUG"]?.trim() || void 0;
1858
2365
  }
1859
2366
  function isSentrySaasDsnHost(host) {
1860
2367
  return host === "sentry.io" || host.endsWith(".sentry.io");
@@ -1893,22 +2400,22 @@ function buildSentryEventUrl(eventId) {
1893
2400
  function conversationEventModel(data, current) {
1894
2401
  if (data.type === "turn_started") return void 0;
1895
2402
  if (data.type === "assistant_message") {
1896
- const model = text$1(data.model);
1897
- const provider = text$1(data.provider);
2403
+ const model = text(data["model"]);
2404
+ const provider = text(data["provider"]);
1898
2405
  if (model) return { modelId: model.includes("/") || !provider ? model : `${provider}/${model}` };
1899
2406
  }
1900
2407
  return current;
1901
2408
  }
1902
- function text$1(value) {
2409
+ function text(value) {
1903
2410
  return typeof value === "string" && value.length > 0 ? value : void 0;
1904
2411
  }
1905
2412
  /** Allowlist model-call diagnostics; never expose opaque provider metadata. */
1906
2413
  function conversationEventModelCall(data) {
1907
2414
  if (data.type !== "assistant_message") return void 0;
1908
2415
  const usage = extractGenAiUsageSummary(data);
1909
- const provider = text$1(data.provider);
1910
- const api = text$1(data.api);
1911
- const stopReason = text$1(data.stopReason);
2416
+ const provider = text(data["provider"]);
2417
+ const api = text(data["api"]);
2418
+ const stopReason = text(data["stopReason"]);
1912
2419
  return {
1913
2420
  ...provider ? { provider } : void 0,
1914
2421
  ...api ? { api } : void 0,
@@ -2001,7 +2508,7 @@ function modelVisibleToolOutput(content) {
2001
2508
  }
2002
2509
  function reportMessageActorIdentity(data) {
2003
2510
  if (data.role !== "user") return void 0;
2004
- const author = reportingMessageAuthorSchema.safeParse(data.meta?.author);
2511
+ const author = reportingMessageAuthorSchema.safeParse(data.meta?.["author"]);
2005
2512
  if (!author.success) return void 0;
2006
2513
  const actorIdentity = {
2007
2514
  ...author.data.fullName ? { fullName: author.data.fullName } : void 0,
@@ -2106,13 +2613,13 @@ function conversationReportToolResultIds(events) {
2106
2613
  const storedMessageEventsSchema = z.array(conversationReportMessageEventSchema);
2107
2614
  /** Read the Events listed on a message that holds several Events. */
2108
2615
  function reportMessageEvents(meta) {
2109
- const parsed = storedMessageEventsSchema.safeParse(meta?.events);
2616
+ const parsed = storedMessageEventsSchema.safeParse(meta?.["events"]);
2110
2617
  return parsed.success ? { events: parsed.data } : void 0;
2111
2618
  }
2112
2619
  const storedReviewItemChangesSchema = z.array(reviewItemChangeRecordSchema).min(1);
2113
2620
  /** Read the Review item changes that a message records. */
2114
2621
  function reportReviewItemChanges(meta) {
2115
- const parsed = storedReviewItemChangesSchema.safeParse(meta?.reviewItemChanges);
2622
+ const parsed = storedReviewItemChangesSchema.safeParse(meta?.["reviewItemChanges"]);
2116
2623
  return parsed.success ? { reviewItemChanges: parsed.data } : void 0;
2117
2624
  }
2118
2625
  const TURN_COMPLETED_STATES = {
@@ -2143,22 +2650,22 @@ function reportEventData(args) {
2143
2650
  type: "message",
2144
2651
  messageId: data.messageId,
2145
2652
  role: data.role,
2146
- ...data.meta?.source === "web" || data.meta?.source === "slack" ? { source: data.meta.source } : void 0,
2653
+ ...data.meta?.["source"] === "web" || data.meta?.["source"] === "slack" ? { source: data.meta["source"] } : void 0,
2147
2654
  ...actorIdentity ? { actorIdentity } : void 0,
2148
2655
  ...args.canExposePayload && data.role === "user" && data.authorIdentityId && data.authorIdentityId !== "system" ? { actorIdentityId: data.authorIdentityId } : void 0,
2149
- ...typeof data.meta?.agentInvocationId === "string" ? { agentInvocationId: data.meta.agentInvocationId } : void 0,
2656
+ ...typeof data.meta?.["agentInvocationId"] === "string" ? { agentInvocationId: data.meta["agentInvocationId"] } : void 0,
2150
2657
  ...args.canExposePayload ? reportReviewItemChanges(data.meta) : void 0,
2151
- eventObjectType: objectTypeSchema.safeParse(data.meta?.eventObjectType).data,
2152
- ...typeof data.meta?.eventType === "string" ? { eventType: data.meta.eventType } : void 0,
2153
- ...typeof data.meta?.eventNamespace === "string" ? { eventNamespace: data.meta.eventNamespace } : void 0,
2154
- ...typeof data.meta?.explicitMention === "boolean" ? { explicitMention: data.meta.explicitMention } : void 0,
2155
- ...data.meta?.quiet === true ? { quiet: true } : void 0,
2156
- ...args.canExposePayload && typeof data.meta?.trustedSummary === "string" ? { trustedSummary: data.meta.trustedSummary } : void 0,
2658
+ eventObjectType: objectTypeSchema.safeParse(data.meta?.["eventObjectType"]).data,
2659
+ ...typeof data.meta?.["eventType"] === "string" ? { eventType: data.meta["eventType"] } : void 0,
2660
+ ...typeof data.meta?.["eventNamespace"] === "string" ? { eventNamespace: data.meta["eventNamespace"] } : void 0,
2661
+ ...typeof data.meta?.["explicitMention"] === "boolean" ? { explicitMention: data.meta["explicitMention"] } : void 0,
2662
+ ...data.meta?.["quiet"] === true ? { quiet: true } : void 0,
2663
+ ...args.canExposePayload && typeof data.meta?.["trustedSummary"] === "string" ? { trustedSummary: data.meta["trustedSummary"] } : void 0,
2157
2664
  ...args.canExposePayload ? reportMessageEvents(data.meta) : void 0,
2158
- ...args.canExposePayload && (data.meta?.cards || data.meta?.objectCards) ? { cards: readMessageCardRefs(data.meta) } : void 0,
2665
+ ...args.canExposePayload && (data.meta?.["cards"] || data.meta?.["objectCards"]) ? { cards: readMessageCardRefs(data.meta) } : void 0,
2159
2666
  ...args.canExposePayload ? {
2160
2667
  text: data.text,
2161
- ...data.meta?.attachments ? { attachments: readMessageAttachments(data.meta.attachments) } : void 0
2668
+ ...data.meta?.["attachments"] ? { attachments: readMessageAttachments(data.meta["attachments"]) } : void 0
2162
2669
  } : { redacted: true }
2163
2670
  };
2164
2671
  }
@@ -2888,7 +3395,8 @@ async function updateConversationBrief(context) {
2888
3395
  const input = await briefInputFromSql(executor, run.conversationId, terminalSeq);
2889
3396
  const modelId = botConfig.fastModelId;
2890
3397
  const generation = await generateBrief({
2891
- completeObject: (request) => completeObject$1({
3398
+ assistantName: botConfig.userName,
3399
+ completeObject: (request) => completeObject({
2892
3400
  ...request,
2893
3401
  modelId,
2894
3402
  operation: "brief_update",
@@ -3263,7 +3771,7 @@ function createPluginLogger(plugin) {
3263
3771
  });
3264
3772
  },
3265
3773
  warn(message, metadata) {
3266
- logWarn("plugin.log.warn", {
3774
+ logWarn("plugin.log.warning", {
3267
3775
  "app.log.message": message,
3268
3776
  "app.plugin.name": plugin,
3269
3777
  ...metadata
@@ -3335,7 +3843,7 @@ const RUNTIME_GIT_CONFIG = [["credential.helper", ""], ["http.emptyAuth", "true"
3335
3843
  * always wins.
3336
3844
  */
3337
3845
  function gitConfigEnv(env) {
3338
- const count = Number.parseInt(env.GIT_CONFIG_COUNT ?? "0", 10) || 0;
3846
+ const count = Number.parseInt(env["GIT_CONFIG_COUNT"] ?? "0", 10) || 0;
3339
3847
  const entries = [];
3340
3848
  for (let index = 0; index < count; index++) {
3341
3849
  const key = env[`GIT_CONFIG_KEY_${index}`];
@@ -3403,7 +3911,7 @@ function normalizeWorkspaceRoot(input) {
3403
3911
  const normalized = candidate.replace(/\/+$/, "");
3404
3912
  return normalized.startsWith("/") ? normalized : `/${normalized}`;
3405
3913
  }
3406
- const SANDBOX_WORKSPACE_ROOT = normalizeWorkspaceRoot(process.env.VERCEL_SANDBOX_WORKSPACE_DIR);
3914
+ const SANDBOX_WORKSPACE_ROOT = normalizeWorkspaceRoot(process.env["VERCEL_SANDBOX_WORKSPACE_DIR"]);
3407
3915
  const SANDBOX_REPOS_ROOT = `${SANDBOX_WORKSPACE_ROOT}/repos`;
3408
3916
  const SANDBOX_SKILLS_ROOT = `${SANDBOX_WORKSPACE_ROOT}/skills`;
3409
3917
  const SANDBOX_DATA_ROOT = `${SANDBOX_WORKSPACE_ROOT}/data`;
@@ -3489,7 +3997,7 @@ function createSandboxCapability(workspace, ownerSignal) {
3489
3997
  function createPluginModel(pluginName, options = {}, runtime = {}) {
3490
3998
  return { async completeObject(input) {
3491
3999
  const modelId = options.structuredModelId ?? (options.structuredModel === "default" ? botConfig.modelId : botConfig.fastModelId);
3492
- const result = await completeObject({
4000
+ const result = await completeObject$1({
3493
4001
  modelId,
3494
4002
  schema: input.schema,
3495
4003
  prompt: input.prompt,
@@ -3518,7 +4026,7 @@ function createPluginEmbedder(pluginName, runtime = {}) {
3518
4026
  model: botConfig.embeddingModelId,
3519
4027
  provider: GEN_AI_PROVIDER_NAME,
3520
4028
  async embedTexts(input) {
3521
- const result = await embedTexts({
4029
+ const result = await embedTexts$1({
3522
4030
  modelId: botConfig.embeddingModelId,
3523
4031
  texts: input.texts,
3524
4032
  ...input.inputType !== void 0 ? { inputType: input.inputType } : void 0,
@@ -3636,7 +4144,7 @@ var DockerApiError = class extends Error {
3636
4144
  };
3637
4145
  /** Return the unix socket path of the Docker daemon from `DOCKER_HOST`. */
3638
4146
  function dockerSocketPath() {
3639
- const host = process.env.DOCKER_HOST?.trim();
4147
+ const host = process.env["DOCKER_HOST"]?.trim();
3640
4148
  if (!host) return DEFAULT_SOCKET_PATH;
3641
4149
  if (!host.startsWith("unix://")) throw new Error(`The Docker sandbox provider supports only unix sockets. DOCKER_HOST is ${host}`);
3642
4150
  return host.slice(7);
@@ -3919,7 +4427,7 @@ const DOCKER_SANDBOX_LABEL = "dev.junior.sandbox";
3919
4427
  * `JUNIOR_DOCKER_SANDBOX_DIR` overrides the default.
3920
4428
  */
3921
4429
  function dockerSandboxDir() {
3922
- const configured = process.env.JUNIOR_DOCKER_SANDBOX_DIR?.trim();
4430
+ const configured = process.env["JUNIOR_DOCKER_SANDBOX_DIR"]?.trim();
3923
4431
  if (configured) return configured;
3924
4432
  return path.join(os.homedir(), ".cache", "junior", "docker-sandbox");
3925
4433
  }
@@ -3931,7 +4439,7 @@ function dockerSandboxDir() {
3931
4439
  * verify the certificates that this proxy shows.
3932
4440
  */
3933
4441
  function dockerSandboxExtraCaFile() {
3934
- return process.env.JUNIOR_DOCKER_SANDBOX_EXTRA_CA_CERTS?.trim() || void 0;
4442
+ return process.env["JUNIOR_DOCKER_SANDBOX_EXTRA_CA_CERTS"]?.trim() || void 0;
3935
4443
  }
3936
4444
  // src/chat/sandbox/docker/tar.ts
3937
4445
  const BLOCK = 512;
@@ -4320,7 +4828,7 @@ const SANDBOX_FILE_OWNER = {
4320
4828
  user: SANDBOX_USER
4321
4829
  };
4322
4830
  // src/chat/sandbox/docker/certificates.ts
4323
- const CA_COMMON_NAME = "Junior Docker Sandbox Egress CA";
4831
+ const CA_COMMON_NAME = "Docker Sandbox Egress CA";
4324
4832
  const CA_VALID_DAYS = 3650;
4325
4833
  /** Clients reject long-lived leaf certificates, so keep them short. */
4326
4834
  const LEAF_VALID_DAYS = 365;
@@ -4354,7 +4862,7 @@ const octetString = (value) => tlv(4, value);
4354
4862
  const bitString = (value) => tlv(3, Buffer.concat([Buffer.from([0]), value]));
4355
4863
  const explicit = (index, value) => tlv(160 + index, value);
4356
4864
  const booleanTrue = () => tlv(1, Buffer.from([255]));
4357
- function integer$1(value) {
4865
+ function integer(value) {
4358
4866
  return tlv(2, (value[0] ?? 0) & 128 ? Buffer.concat([Buffer.from([0]), value]) : value);
4359
4867
  }
4360
4868
  function oid(value) {
@@ -4391,7 +4899,7 @@ function certificate(input) {
4391
4899
  serial[0] = (serial[0] ?? 0) & 127;
4392
4900
  const algorithm = sequence(oid(OID.ecdsaWithSha256));
4393
4901
  const now = Date.now();
4394
- const tbs = sequence(explicit(0, integer$1(Buffer.from([2]))), integer$1(serial), algorithm, input.issuer, sequence(time(/* @__PURE__ */ new Date(now - DAY_MS)), time(new Date(now + input.validDays * DAY_MS))), input.subject, publicKeyInfo(input.publicKey), explicit(3, sequence(...input.extensions)));
4902
+ const tbs = sequence(explicit(0, integer(Buffer.from([2]))), integer(serial), algorithm, input.issuer, sequence(time(/* @__PURE__ */ new Date(now - DAY_MS)), time(new Date(now + input.validDays * DAY_MS))), input.subject, publicKeyInfo(input.publicKey), explicit(3, sequence(...input.extensions)));
4395
4903
  const signature = sign("sha256", tbs, {
4396
4904
  key: input.signingKey,
4397
4905
  dsaEncoding: "der"
@@ -5854,7 +6362,7 @@ function absolute(filePath, cwd) {
5854
6362
  function notFound(filePath) {
5855
6363
  return Object.assign(/* @__PURE__ */ new Error(`ENOENT: no such file or directory, '${filePath}'`), { code: "ENOENT" });
5856
6364
  }
5857
- async function readFile$1(id, filePath, signal) {
6365
+ async function readFile(id, filePath, signal) {
5858
6366
  try {
5859
6367
  return unpackFirstFile(await dockerRequest({
5860
6368
  path: `/containers/${id}/archive`,
@@ -5907,7 +6415,7 @@ function fileSystem(id) {
5907
6415
  return {
5908
6416
  async readFile(filePath, options) {
5909
6417
  const target = absolute(filePath);
5910
- const content = await readFile$1(id, target, options.signal);
6418
+ const content = await readFile(id, target, options.signal);
5911
6419
  if (!content) throw notFound(target);
5912
6420
  return content.toString(options.encoding);
5913
6421
  },
@@ -5982,7 +6490,7 @@ function adaptSession$1(container, options) {
5982
6490
  const result = await runRawExec(id, { cmd: ["mkdir", target] });
5983
6491
  if (result.exitCode !== 0) throw new Error(`mkdir ${target} failed: ${result.stderr.trim()}`);
5984
6492
  }),
5985
- readFileToBuffer: (input) => run(() => readFile$1(id, absolute(input.path, input.cwd))),
6493
+ readFileToBuffer: (input) => run(() => readFile(id, absolute(input.path, input.cwd))),
5986
6494
  runCommand: (input) => run(() => runSandboxCommand(id, {
5987
6495
  ...input,
5988
6496
  cwd: input.cwd ?? SANDBOX_WORKSPACE_ROOT,
@@ -6113,9 +6621,9 @@ const dockerSandboxProvider = {
6113
6621
  * the SDK read ambient Vercel auth from its own environment detection.
6114
6622
  */
6115
6623
  function getVercelSandboxCredentials() {
6116
- const token = toOptionalTrimmed(process.env.VERCEL_TOKEN);
6117
- const teamId = toOptionalTrimmed(process.env.VERCEL_TEAM_ID);
6118
- const projectId = toOptionalTrimmed(process.env.VERCEL_PROJECT_ID);
6624
+ const token = toOptionalTrimmed(process.env["VERCEL_TOKEN"]);
6625
+ const teamId = toOptionalTrimmed(process.env["VERCEL_TEAM_ID"]);
6626
+ const projectId = toOptionalTrimmed(process.env["VERCEL_PROJECT_ID"]);
6119
6627
  if (token && teamId && projectId) return {
6120
6628
  token,
6121
6629
  teamId,
@@ -6834,24 +7342,24 @@ function optionalString(value) {
6834
7342
  /** Parse OAuth callback state that was persisted before a provider redirect. */
6835
7343
  function parseOAuthStatePayload(value) {
6836
7344
  if (!isRecord$2(value)) return;
6837
- if (typeof value.userId !== "string" || typeof value.provider !== "string") return;
6838
- const actor = value.actor === void 0 ? void 0 : actorSchema.safeParse(value.actor);
6839
- if (value.actor !== void 0 && (!actor || !actor.success)) return;
6840
- const destination = parseDestination(value.destination);
6841
- if (value.destination !== void 0 && !destination) return;
6842
- const source = value.source === void 0 ? void 0 : sourceSchema.safeParse(value.source);
6843
- if (value.source !== void 0 && (!source || !source.success)) return;
7345
+ if (typeof value["userId"] !== "string" || typeof value["provider"] !== "string") return;
7346
+ const actor = value["actor"] === void 0 ? void 0 : actorSchema.safeParse(value["actor"]);
7347
+ if (value["actor"] !== void 0 && (!actor || !actor.success)) return;
7348
+ const destination = parseDestination(value["destination"]);
7349
+ if (value["destination"] !== void 0 && !destination) return;
7350
+ const source = value["source"] === void 0 ? void 0 : sourceSchema.safeParse(value["source"]);
7351
+ if (value["source"] !== void 0 && (!source || !source.success)) return;
6844
7352
  return {
6845
- userId: value.userId,
6846
- provider: value.provider,
7353
+ userId: value["userId"],
7354
+ provider: value["provider"],
6847
7355
  ...actor?.success ? { actor: actor.data } : void 0,
6848
- ...optionalString(value.channelId) ? { channelId: optionalString(value.channelId) } : void 0,
7356
+ ...optionalString(value["channelId"]) ? { channelId: optionalString(value["channelId"]) } : void 0,
6849
7357
  ...destination ? { destination } : void 0,
6850
7358
  ...source?.success ? { source: source.data } : void 0,
6851
- ...optionalString(value.threadTs) ? { threadTs: optionalString(value.threadTs) } : void 0,
6852
- ...optionalString(value.resumeConversationId) ? { resumeConversationId: optionalString(value.resumeConversationId) } : void 0,
6853
- ...optionalString(value.resumeSessionId) ? { resumeSessionId: optionalString(value.resumeSessionId) } : void 0,
6854
- ...optionalString(value.scope) ? { scope: optionalString(value.scope) } : void 0
7359
+ ...optionalString(value["threadTs"]) ? { threadTs: optionalString(value["threadTs"]) } : void 0,
7360
+ ...optionalString(value["resumeConversationId"]) ? { resumeConversationId: optionalString(value["resumeConversationId"]) } : void 0,
7361
+ ...optionalString(value["resumeSessionId"]) ? { resumeSessionId: optionalString(value["resumeSessionId"]) } : void 0,
7362
+ ...optionalString(value["scope"]) ? { scope: optionalString(value["scope"]) } : void 0
6855
7363
  };
6856
7364
  }
6857
7365
  /** Return the manifest-owned display label for a provider. */
@@ -6862,11 +7370,11 @@ function formatProviderLabel(provider) {
6862
7370
  }
6863
7371
  /** Resolve the public base URL from environment variables (JUNIOR_BASE_URL or Vercel). */
6864
7372
  function resolveBaseUrl() {
6865
- const explicit = process.env.JUNIOR_BASE_URL?.trim();
7373
+ const explicit = process.env["JUNIOR_BASE_URL"]?.trim();
6866
7374
  if (explicit) return explicit;
6867
- const vercelProd = process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim();
7375
+ const vercelProd = process.env["VERCEL_PROJECT_PRODUCTION_URL"]?.trim();
6868
7376
  if (vercelProd) return `https://${vercelProd}`;
6869
- const vercelUrl = process.env.VERCEL_URL?.trim();
7377
+ const vercelUrl = process.env["VERCEL_URL"]?.trim();
6870
7378
  if (vercelUrl) return `https://${vercelUrl}`;
6871
7379
  }
6872
7380
  /**
@@ -7108,7 +7616,7 @@ function normalizePort(value) {
7108
7616
  return port >= 1 && port <= 65535 ? trimmed : void 0;
7109
7617
  }
7110
7618
  function sandboxIdFromPayload(payload) {
7111
- return typeof payload.sandbox_id === "string" ? payload.sandbox_id : void 0;
7619
+ return typeof payload["sandbox_id"] === "string" ? payload["sandbox_id"] : void 0;
7112
7620
  }
7113
7621
  function normalizedForwardedPath(path) {
7114
7622
  if (!path.startsWith("/") || path.startsWith("//") || path.includes("#") || /[\r\n]/.test(path)) return {
@@ -7253,9 +7761,9 @@ function searchableText(error) {
7253
7761
  }
7254
7762
  function isInvalidSandboxSessionError(error) {
7255
7763
  if (!isRecord$1(error)) return false;
7256
- if (isRecord$1(error.json) && error.json.invalidToken === true) return true;
7257
- const response = error.response;
7258
- return isRecord$1(response) && response.status === 403 && typeof response.url === "string" && response.url.includes("/sandboxes/sessions");
7764
+ if (isRecord$1(error["json"]) && error["json"]["invalidToken"] === true) return true;
7765
+ const response = error["response"];
7766
+ return isRecord$1(response) && response["status"] === 403 && typeof response["url"] === "string" && response["url"].includes("/sandboxes/sessions");
7259
7767
  }
7260
7768
  function isUnavailable(error) {
7261
7769
  return findInErrorChain(error, (candidate) => {
@@ -7285,13 +7793,13 @@ function isTransient(error) {
7285
7793
  const searchable = searchableText(candidate);
7286
7794
  if (searchable.includes("internal_server_error") || searchable.includes("status=500") || searchable.includes("status code 500") || searchable.includes("status=502") || searchable.includes("status code 502") || searchable.includes("status=503") || searchable.includes("status code 503") || searchable.includes("status=504") || searchable.includes("status code 504")) return true;
7287
7795
  if (!isRecord$1(candidate)) return false;
7288
- const response = candidate.response;
7289
- return isRecord$1(response) && typeof response.status === "number" && response.status >= 500 && response.status < 600;
7796
+ const response = candidate["response"];
7797
+ return isRecord$1(response) && typeof response["status"] === "number" && response["status"] >= 500 && response["status"] < 600;
7290
7798
  });
7291
7799
  }
7292
7800
  const SOCKET_FAILURE_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "UND_ERR_SOCKET"]);
7293
7801
  function isFetchSocketFailure(error) {
7294
- return error.name === "TypeError" && (error.message === "terminated" || error.message === "fetch failed") && isRecord$1(error.cause) && typeof error.cause.code === "string" && SOCKET_FAILURE_CODES.has(error.cause.code);
7802
+ return error.name === "TypeError" && (error.message === "terminated" || error.message === "fetch failed") && isRecord$1(error.cause) && typeof error.cause["code"] === "string" && SOCKET_FAILURE_CODES.has(error.cause["code"]);
7295
7803
  }
7296
7804
  function isCommandStreamInterrupted(error) {
7297
7805
  return findInErrorChain(error, (candidate) => {
@@ -7357,6 +7865,9 @@ function adaptSession(sandbox, options) {
7357
7865
  return session.domain(port);
7358
7866
  });
7359
7867
  },
7868
+ previewUrls() {
7869
+ return session.routes.map((route) => session.domain(route.port));
7870
+ },
7360
7871
  extendTimeout(duration) {
7361
7872
  return run(async () => await session.extendTimeout(duration));
7362
7873
  },
@@ -7664,7 +8175,7 @@ function mergeDependencies(dependencies) {
7664
8175
  return merged;
7665
8176
  }
7666
8177
  function floatingMaxAgeMs() {
7667
- const raw = process.env.SANDBOX_SNAPSHOT_FLOATING_MAX_AGE_MS;
8178
+ const raw = process.env["SANDBOX_SNAPSHOT_FLOATING_MAX_AGE_MS"];
7668
8179
  if (!raw?.trim()) return DEFAULT_FLOATING_MAX_AGE_MS;
7669
8180
  const parsed = Number.parseInt(raw, 10);
7670
8181
  return Number.isFinite(parsed) && parsed >= 0 ? parsed : DEFAULT_FLOATING_MAX_AGE_MS;
@@ -7699,7 +8210,7 @@ function create(runtime, workspace) {
7699
8210
  const { dependencies, postinstall } = getSandboxProvider().selectSnapshotRuntime?.(declared) ?? declared;
7700
8211
  const pluginPostinstall = postinstall.filter((command) => !GLOBAL_RUNTIME_POSTINSTALL.includes(command));
7701
8212
  if (dependencies.length === 0 && postinstall.length === 0 && !workspace) return null;
7702
- const rebuildEpoch = process.env.SANDBOX_SNAPSHOT_REBUILD_EPOCH?.trim() ?? "";
8213
+ const rebuildEpoch = process.env["SANDBOX_SNAPSHOT_REBUILD_EPOCH"]?.trim() ?? "";
7703
8214
  const floating = dependencies.some((dependency) => isFloating(dependency)) || pluginPostinstall.length > 0 || Boolean(workspace);
7704
8215
  return {
7705
8216
  hash: createHash("sha256").update(JSON.stringify({
@@ -8240,11 +8751,11 @@ function normalizeDashboardPath(path, fallback) {
8240
8751
  return stripTrailingSlashes(value.startsWith("/") ? value : `/${value}`);
8241
8752
  }
8242
8753
  function resolveDashboardBaseURL(config) {
8243
- const explicit = config.baseURL ?? process.env.JUNIOR_BASE_URL;
8754
+ const explicit = config.baseURL ?? process.env["JUNIOR_BASE_URL"];
8244
8755
  if (explicit?.trim()) return stripTrailingSlashes(withHttps(explicit.trim()));
8245
- const vercelProd = process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim();
8756
+ const vercelProd = process.env["VERCEL_PROJECT_PRODUCTION_URL"]?.trim();
8246
8757
  if (vercelProd) return stripTrailingSlashes(withHttps(vercelProd));
8247
- const vercelUrl = process.env.VERCEL_URL?.trim();
8758
+ const vercelUrl = process.env["VERCEL_URL"]?.trim();
8248
8759
  if (vercelUrl) return stripTrailingSlashes(withHttps(vercelUrl));
8249
8760
  return "http://localhost:3000";
8250
8761
  }
@@ -9127,7 +9638,7 @@ async function resolveAssignee(db, value, tenant, findMentionedUserId) {
9127
9638
  if (mentionedUserId) return { userId: mentionedUserId };
9128
9639
  if (text.includes("@")) {
9129
9640
  const user = await findUserByEmailFromSql(db, text);
9130
- if (!user) throw new ToolInputError(`No Junior user has the email ${text}.`);
9641
+ if (!user) throw new ToolInputError(`No User has the email ${text}.`);
9131
9642
  return { userId: user.id };
9132
9643
  }
9133
9644
  throw new ToolInputError(`Unknown assignee ${JSON.stringify(text)}. Use ${EVERYONE_ASSIGNEE}, an email, or a mention such as <@U123>.`);
@@ -9220,7 +9731,7 @@ function publicIn(tenants) {
9220
9731
  * Review item access test checks that they agree.
9221
9732
  */
9222
9733
  function reviewItemVisibleTo(reader) {
9223
- return or(sql`false`, ...publicIn(reader.tenants ?? []), ...reader.userId ? [reviewItemAssignedTo(reader.userId)] : [], ...reader.conversationId ? [reviewItemLinkedTo(reader.conversationId)] : [], ...reader.automationId ? [eq(juniorReviewItems.automationId, reader.automationId)] : []);
9734
+ return or(...publicIn(reader.tenants ?? []), ...reader.userId ? [reviewItemAssignedTo(reader.userId)] : [], ...reader.conversationId ? [reviewItemLinkedTo(reader.conversationId)] : [], ...reader.automationId ? [eq(juniorReviewItems.automationId, reader.automationId)] : []) ?? sql`false`;
9224
9735
  }
9225
9736
  /** Return whether a reader can see one Review item. */
9226
9737
  function canReadReviewItem(item, reader) {
@@ -9341,6 +9852,14 @@ function canActOnReviewItem(item, userId) {
9341
9852
  if (item.assignees.length === 0) return true;
9342
9853
  return item.assignees.some((assignee) => assignee.userId === userId);
9343
9854
  }
9855
+ /**
9856
+ * Return whether a Review item needs a User: an open `action` item that is
9857
+ * assigned to them. `reviewItemNeedsUser` is the SQL form; keep the two the
9858
+ * same.
9859
+ */
9860
+ function itemNeedsUser(item, userId) {
9861
+ return item.status === "open" && item.kind === "action" && item.assignees.some((assignee) => assignee.userId === userId);
9862
+ }
9344
9863
  /** Return whether a User is already the only assignee, so take does nothing. */
9345
9864
  function isOnlyAssignee(item, userId) {
9346
9865
  return !item.assignedToEveryone && item.assignees.length === 1 && item.assignees[0]?.userId === userId;
@@ -9550,6 +10069,14 @@ async function takeReviewItem(db, input) {
9550
10069
  function searchConditions(reader, filters) {
9551
10070
  const conditions = [reviewItemVisibleTo(reader), inArray(juniorReviewItems.status, [...filters.statuses])];
9552
10071
  if (filters.after) conditions.push(or(gt(juniorReviewItems.createdAt, filters.after.createdAt), and(eq(juniorReviewItems.createdAt, filters.after.createdAt), gt(juniorReviewItems.id, filters.after.id))));
10072
+ if (filters.afterWaiting) {
10073
+ if (typeof filters.order !== "object") throw new Error("afterWaiting needs the waiting-first order");
10074
+ const needs = reviewItemNeedsUser(filters.order.needsUserId);
10075
+ const { createdAt, id, needsUser } = filters.afterWaiting;
10076
+ const older = or(lt(juniorReviewItems.createdAt, createdAt), and(eq(juniorReviewItems.createdAt, createdAt), lt(juniorReviewItems.id, id)));
10077
+ conditions.push(needsUser ? or(not(needs), and(needs, older)) : and(not(needs), older));
10078
+ }
10079
+ if (filters.closedBefore) conditions.push(or(lt(juniorReviewItems.closedAt, filters.closedBefore.closedAt), and(eq(juniorReviewItems.closedAt, filters.closedBefore.closedAt), lt(juniorReviewItems.id, filters.closedBefore.id))));
9553
10080
  if (filters.subjectId) conditions.push(eq(juniorReviewItems.subjectId, filters.subjectId));
9554
10081
  if (filters.automationId) conditions.push(eq(juniorReviewItems.automationId, filters.automationId));
9555
10082
  if (filters.conversationId) conditions.push(reviewItemLinkedTo(filters.conversationId));
@@ -9561,9 +10088,26 @@ function searchConditions(reader, filters) {
9561
10088
  }
9562
10089
  return conditions;
9563
10090
  }
9564
- /** Count the open Review items that need a User (`reviewItemNeedsUser`). */
9565
- async function countReviewItemsNeedingUser(db, userId) {
9566
- return (await db.select({ count: count() }).from(juniorReviewItems).where(reviewItemNeedsUser(userId)))[0]?.count ?? 0;
10091
+ /**
10092
+ * Count the open Review items that need a User (`reviewItemNeedsUser`), one
10093
+ * row per subject URL, with the ones that ask with a form as `decisions`.
10094
+ * The nav count and the Inbox bundle counts all read this one query.
10095
+ */
10096
+ async function countReviewItemsNeedingUserBySubject(db, userId) {
10097
+ return await db.select({
10098
+ decisions: count(juniorReviewItems.request),
10099
+ subjectUrl: juniorReviewItems.subjectUrl,
10100
+ total: count()
10101
+ }).from(juniorReviewItems).where(reviewItemNeedsUser(userId)).groupBy(juniorReviewItems.subjectUrl);
10102
+ }
10103
+ /**
10104
+ * Count the items in `ids` that are still open and that the reader's Inbox
10105
+ * lists (`reviewItemForUser`). Snoozes live in the browser, so the
10106
+ * dashboard names the newest item of each snoozed row.
10107
+ */
10108
+ async function countOpenReviewItemsForUser(db, reader, ids) {
10109
+ if (ids.length === 0) return 0;
10110
+ return (await db.select({ count: count() }).from(juniorReviewItems).where(and(inArray(juniorReviewItems.id, [...ids]), eq(juniorReviewItems.status, "open"), reviewItemVisibleTo(reader), reviewItemForUser(reader.userId))))[0]?.count ?? 0;
9567
10111
  }
9568
10112
  /**
9569
10113
  * Return a query for a token that changes when the open Review items that
@@ -9578,10 +10122,18 @@ function reviewItemsNeedingUserVersionQuery(db, userId) {
9578
10122
  * the limit never drops an open item for a closed one. Then the newest
9579
10123
  * change comes first: `updated_at`, then `id`, both descending. With
9580
10124
  * `order: "oldest"`, the oldest item comes first: `created_at`, then `id`,
9581
- * both ascending. `after` pages through that order.
10125
+ * both ascending. `after` pages through that order. With `order: "closed"`,
10126
+ * the item closed last comes first: `closed_at`, then `id`, both
10127
+ * descending. `closedBefore` pages through that order. With
10128
+ * `order: { needsUserId }`, the items that need the User come first, then
10129
+ * `created_at` and `id`, both descending. `afterWaiting` pages through it.
9582
10130
  */
9583
10131
  async function searchReviewItems(db, reader, filters) {
9584
- return await hydrate(db, await db.select().from(juniorReviewItems).where(and(...searchConditions(reader, filters))).orderBy(desc(eq(juniorReviewItems.status, "open")), ...filters.order === "oldest" ? [asc(juniorReviewItems.createdAt), asc(juniorReviewItems.id)] : [desc(juniorReviewItems.updatedAt), desc(juniorReviewItems.id)]).limit(filters.limit));
10132
+ return await hydrate(db, await db.select().from(juniorReviewItems).where(and(...searchConditions(reader, filters))).orderBy(desc(eq(juniorReviewItems.status, "open")), ...typeof filters.order === "object" ? [
10133
+ desc(reviewItemNeedsUser(filters.order.needsUserId)),
10134
+ desc(juniorReviewItems.createdAt),
10135
+ desc(juniorReviewItems.id)
10136
+ ] : filters.order === "oldest" ? [asc(juniorReviewItems.createdAt), asc(juniorReviewItems.id)] : filters.order === "closed" ? [desc(juniorReviewItems.closedAt), desc(juniorReviewItems.id)] : [desc(juniorReviewItems.updatedAt), desc(juniorReviewItems.id)]).limit(filters.limit));
9585
10137
  }
9586
10138
  /**
9587
10139
  * List the root Conversations that wait on a User: each root or one of its
@@ -9701,8 +10253,8 @@ function isMessageEvent(event) {
9701
10253
  }
9702
10254
  function splitMeta(meta) {
9703
10255
  const rest = { ...meta ?? {} };
9704
- const author = rest.author;
9705
- delete rest.author;
10256
+ const author = rest["author"];
10257
+ delete rest["author"];
9706
10258
  return {
9707
10259
  ...author ? { author } : void 0,
9708
10260
  ...Object.keys(rest).length > 0 ? { meta: rest } : void 0
@@ -9905,7 +10457,7 @@ async function resolveNotificationTimezone(args) {
9905
10457
  const PUSH_TTL_SECONDS = 43200;
9906
10458
  const PUSH_TIMEOUT_MS = 1e4;
9907
10459
  function subjectFromBaseUrl() {
9908
- const baseUrl = process.env.JUNIOR_BASE_URL?.trim();
10460
+ const baseUrl = process.env["JUNIOR_BASE_URL"]?.trim();
9909
10461
  if (!baseUrl) return void 0;
9910
10462
  return baseUrl.startsWith("https://") || baseUrl.startsWith("http://") ? baseUrl : `https://${baseUrl}`;
9911
10463
  }
@@ -9919,10 +10471,10 @@ function isVapidSubject(subject) {
9919
10471
  * an `http://` base URL.
9920
10472
  */
9921
10473
  function readWebPushConfig() {
9922
- const publicKey = process.env.JUNIOR_WEB_PUSH_PUBLIC_KEY?.trim();
10474
+ const publicKey = process.env["JUNIOR_WEB_PUSH_PUBLIC_KEY"]?.trim();
9923
10475
  const privateKey = readWebPushPrivateKey();
9924
10476
  if (!publicKey || !privateKey) return void 0;
9925
- const subject = process.env.JUNIOR_WEB_PUSH_SUBJECT?.trim() || subjectFromBaseUrl();
10477
+ const subject = process.env["JUNIOR_WEB_PUSH_SUBJECT"]?.trim() || subjectFromBaseUrl();
9926
10478
  if (!subject || !isVapidSubject(subject)) return void 0;
9927
10479
  return {
9928
10480
  privateKey,
@@ -10005,8 +10557,7 @@ function notificationPreview(text) {
10005
10557
  }
10006
10558
  /**
10007
10559
  * Return the stored reply of the Turn: the text that the person sees. The
10008
- * run transcript has the raw model text, which can be a no-reply marker, and
10009
- * does not say whether the reply was quiet.
10560
+ * run transcript has the raw model text, which can be a no-reply marker.
10010
10561
  */
10011
10562
  async function readTurnReply(run) {
10012
10563
  const prefix = `${run.runId}:assistant:`;
@@ -10047,7 +10598,6 @@ async function notifyReply(context) {
10047
10598
  if (!url) return skip("no_dashboard");
10048
10599
  const reply = await readTurnReply(run);
10049
10600
  if (!reply) return skip("no_reply");
10050
- if (reply.meta?.quiet) return skip("quiet");
10051
10601
  const db = context.db;
10052
10602
  const userId = await recipientUserId(db, run);
10053
10603
  if (!userId) return skip("no_user");
@@ -10071,7 +10621,7 @@ async function notifyReply(context) {
10071
10621
  payload: {
10072
10622
  body: notificationPreview(reply.text) || "New reply",
10073
10623
  tag: run.conversationId,
10074
- title: await readConversationTitle(db, run.conversationId) ?? "Junior",
10624
+ title: await readConversationTitle(db, run.conversationId) ?? botConfig.userName,
10075
10625
  url
10076
10626
  },
10077
10627
  userId
@@ -10098,11 +10648,7 @@ const notificationsTaskRegistration = {
10098
10648
  } } }
10099
10649
  };
10100
10650
  // src/chat/briefs/registration.ts
10101
- var registration_exports = /* @__PURE__ */ __exportAll({
10102
- coreTaskRegistrations: () => coreTaskRegistrations,
10103
- isBriefsEnabled: () => isBriefsEnabled,
10104
- setBriefsConfig: () => setBriefsConfig
10105
- });
10651
+ var registration_exports = /* @__PURE__ */ __exportAll({ setBriefsConfig: () => setBriefsConfig });
10106
10652
  let configuredBriefs = {};
10107
10653
  /** Replace app-level Brief settings and return the previous setting. */
10108
10654
  function setBriefsConfig(config) {
@@ -10296,10 +10842,11 @@ function toUserPromptContributionContext(args) {
10296
10842
  message: message.data,
10297
10843
  pluginName: args.pluginName
10298
10844
  });
10299
- if (!isRecord(args.value) || typeof args.value.renderPrompt !== "function") return;
10300
- const context = promptContextSchema.safeParse(args.value.context);
10845
+ if (!isRecord(args.value) || typeof args.value["renderPrompt"] !== "function") return;
10846
+ const context = promptContextSchema.safeParse(args.value["context"]);
10301
10847
  if (!context.success) return;
10302
- const text = promptMessageSchema.safeParse({ text: args.value.renderPrompt() });
10848
+ const renderPrompt = args.value["renderPrompt"];
10849
+ const text = promptMessageSchema.safeParse({ text: renderPrompt.call(args.value) });
10303
10850
  if (!text.success) return;
10304
10851
  return {
10305
10852
  id: `userPrompt:${args.index}`,
@@ -10502,7 +11049,9 @@ function pluginToolDefinitions(plugin) {
10502
11049
  }
10503
11050
  /** Model-facing definitions of every plugin tool, with no Turn. */
10504
11051
  function getStaticPluginToolDefinitions() {
10505
- return Object.assign({}, ...getPlugins().map(pluginToolDefinitions));
11052
+ const definitions = {};
11053
+ for (const plugin of getPlugins()) Object.assign(definitions, pluginToolDefinitions(plugin));
11054
+ return definitions;
10506
11055
  }
10507
11056
  /** Collect turn-scoped tools exposed by plugins. */
10508
11057
  function getPluginTools(context, sandbox = createSandboxCapability(context.workspace)) {
@@ -10669,7 +11218,7 @@ function getPluginTools(context, sandbox = createSandboxCapability(context.works
10669
11218
  plugin: pluginName,
10670
11219
  result: await execute(input, options, pluginContext),
10671
11220
  toolCallId: options.toolCallId
10672
- })) } : void 0
11221
+ }), { readOnly: definition.annotations?.readOnlyHint === true }) } : void 0
10673
11222
  };
10674
11223
  }
10675
11224
  }
@@ -11133,7 +11682,7 @@ function createPluginHookRunner(input = {}) {
11133
11682
  juniorRoot: SANDBOX_JUNIOR_ROOT,
11134
11683
  env: {
11135
11684
  get(key) {
11136
- return env[key] ?? normalizeEnv(nextInput.env)[key];
11685
+ return env[key] ?? normalizeEnv(nextInput["env"])[key];
11137
11686
  },
11138
11687
  set(key, value) {
11139
11688
  env[key] = value;
@@ -12261,21 +12810,18 @@ const TURN_CONTEXT_TAG = "runtime-turn-context";
12261
12810
  /** Turn context section that only session context includes. */
12262
12811
  const SESSION_CONTEXT_SECTION_TAG = "runtime";
12263
12812
  /**
12264
- * Turn context section with the tools a Code Mode script can call. A Turn
12265
- * adds it only when it differs from the latest copy in history, and context
12266
- * compaction keeps only that latest copy.
12267
- */
12268
- const SCRIPT_TOOLS_SECTION_TAG = "script-tools";
12269
- /**
12270
- * Turn context sections that list what the model can use now. A Turn adds
12271
- * one only when it differs from the latest copy in history, and context
12272
- * compaction keeps only that latest copy.
12813
+ * Named system prompt sections that list what the model can use now: the
12814
+ * skills, MCP catalogs, tool guidance, Workspaces, and the tools that a Code
12815
+ * Mode script can call. A Turn sends a changed section in a later system
12816
+ * message (`systemSectionsUpdate`). The Turn context of older Turns held
12817
+ * copies of them, which context compaction drops.
12273
12818
  */
12274
12819
  const CAPABILITY_SECTION_TAG = {
12275
12820
  availableSkills: "available-skills",
12276
12821
  activeMcpCatalogs: "active-mcp-catalogs",
12277
12822
  toolGuidance: "tool-guidance",
12278
- workspaces: "workspaces"
12823
+ workspaces: "workspaces",
12824
+ scriptTools: "script-tools"
12279
12825
  };
12280
12826
  /**
12281
12827
  * Turn context sections that are true only for the Turn that received them.
@@ -12354,7 +12900,9 @@ function getPiMessageRole(value) {
12354
12900
  }
12355
12901
  /** Return whether Pi can continue directly from the current history tail. */
12356
12902
  function isContinuablePiBoundary(messages) {
12357
- const lastRole = getPiMessageRole(messages.at(-1));
12903
+ let end = messages.length;
12904
+ while (end > 0 && getPiMessageRole(messages[end - 1]) === "system") end -= 1;
12905
+ const lastRole = getPiMessageRole(messages[end - 1]);
12358
12906
  return lastRole === "user" || lastRole === "toolResult";
12359
12907
  }
12360
12908
  /** Concatenate text content parts from an assistant message. */
@@ -12392,23 +12940,6 @@ function retainRuntimeTurnContext(messages) {
12392
12940
  });
12393
12941
  }
12394
12942
  /**
12395
- * Find the latest copy of one `<runtime-turn-context>` section in history,
12396
- * such as `<script-tools>`, with its tags.
12397
- */
12398
- function latestTurnContextSection(messages, tag) {
12399
- const section = new RegExp(`\\n<${tag}>\\n[\\s\\S]*?\\n</${tag}>`, "g");
12400
- for (let index = messages.length - 1; index >= 0; index -= 1) {
12401
- const texts = (userMessageContent(messages[index]) ?? []).flatMap((part) => {
12402
- const text = textPartValue(part);
12403
- return text?.startsWith(RUNTIME_TURN_CONTEXT_START) ? [text] : [];
12404
- });
12405
- for (const text of texts.reverse()) {
12406
- const match = [...text.matchAll(section)].at(-1);
12407
- if (match) return match[0].slice(1);
12408
- }
12409
- }
12410
- }
12411
- /**
12412
12943
  * Reduce a runtime user-turn prompt to only the current turn's instruction.
12413
12944
  *
12414
12945
  * Live user prompts embed prior-thread context as `<thread-context
@@ -12640,6 +13171,7 @@ function parseAnswer(toolName, details, toolCallId) {
12640
13171
  case "misconfigured": return { blocked: { missing: parsed.data.reason } };
12641
13172
  }
12642
13173
  }
13174
+ default: return;
12643
13175
  }
12644
13176
  }
12645
13177
  /**
@@ -12755,7 +13287,7 @@ const inboundMessageSenderSchema = z.object({
12755
13287
  }).strict();
12756
13288
  /** Read the sender fields that one inbound message stores, if any. */
12757
13289
  function readInboundMessageSender(message) {
12758
- const parsed = inboundMessageSenderSchema.safeParse(message.input.metadata?.sender);
13290
+ const parsed = inboundMessageSenderSchema.safeParse(message.input.metadata?.["sender"]);
12759
13291
  return parsed.success ? parsed.data : void 0;
12760
13292
  }
12761
13293
  /**
@@ -12947,10 +13479,10 @@ function normalizeActor(value) {
12947
13479
  }
12948
13480
  function normalizeLease(value) {
12949
13481
  if (!isRecord$2(value)) return;
12950
- const token = toOptionalString(value.token);
12951
- const acquiredAtMs = toOptionalNumber(value.acquiredAtMs);
12952
- const lastCheckInAtMs = toOptionalNumber(value.lastCheckInAtMs);
12953
- const expiresAtMs = toOptionalNumber(value.expiresAtMs);
13482
+ const token = toOptionalString(value["token"]);
13483
+ const acquiredAtMs = toOptionalNumber(value["acquiredAtMs"]);
13484
+ const lastCheckInAtMs = toOptionalNumber(value["lastCheckInAtMs"]);
13485
+ const expiresAtMs = toOptionalNumber(value["expiresAtMs"]);
12954
13486
  if (!token || typeof acquiredAtMs !== "number" || typeof lastCheckInAtMs !== "number" || typeof expiresAtMs !== "number") return;
12955
13487
  return {
12956
13488
  token,
@@ -12961,8 +13493,8 @@ function normalizeLease(value) {
12961
13493
  }
12962
13494
  function normalizeStop(value) {
12963
13495
  if (!isRecord$2(value)) return;
12964
- const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(value.inboundMessageIds.filter((id) => typeof id === "string")) : [];
12965
- const runId = toOptionalString(value.runId);
13496
+ const inboundMessageIds = Array.isArray(value["inboundMessageIds"]) ? uniqueStrings(value["inboundMessageIds"].filter((id) => typeof id === "string")) : [];
13497
+ const runId = toOptionalString(value["runId"]);
12966
13498
  return runId ? {
12967
13499
  inboundMessageIds,
12968
13500
  runId
@@ -12971,44 +13503,44 @@ function normalizeStop(value) {
12971
13503
  /** Decode stored execution state. */
12972
13504
  function normalizeExecution(conversationId, value) {
12973
13505
  if (!isRecord$2(value)) return;
12974
- const status = normalizeExecutionStatus(value.status);
13506
+ const status = normalizeExecutionStatus(value["status"]);
12975
13507
  if (!status) return;
12976
13508
  const pendingMessages = [];
12977
- if (Array.isArray(value.pendingMessages)) {
12978
- for (const rawMessage of value.pendingMessages) {
13509
+ if (Array.isArray(value["pendingMessages"])) {
13510
+ for (const rawMessage of value["pendingMessages"]) {
12979
13511
  const message = normalizeMessage(rawMessage);
12980
13512
  if (!message || message.conversationId !== conversationId) return;
12981
13513
  pendingMessages.push(message);
12982
13514
  }
12983
13515
  pendingMessages.sort(compareMessages);
12984
13516
  }
12985
- const inboundMessageIds = Array.isArray(value.inboundMessageIds) ? uniqueStrings(value.inboundMessageIds.map((id) => typeof id === "string" ? id : void 0).filter((id) => Boolean(id))) : [];
12986
- const messageSenders = withMessageSenders(normalizeMessageSenders(value.messageSenders), pendingMessages);
13517
+ const inboundMessageIds = Array.isArray(value["inboundMessageIds"]) ? uniqueStrings(value["inboundMessageIds"].map((id) => typeof id === "string" ? id : void 0).filter((id) => Boolean(id))) : [];
13518
+ const messageSenders = withMessageSenders(normalizeMessageSenders(value["messageSenders"]), pendingMessages);
12987
13519
  return {
12988
13520
  status,
12989
13521
  inboundMessageIds: uniqueStrings([...inboundMessageIds, ...pendingMessages.map((message) => message.inboundMessageId)]),
12990
13522
  ...messageSenders ? { messageSenders } : void 0,
12991
13523
  pendingCount: pendingMessages.length,
12992
13524
  pendingMessages,
12993
- lease: normalizeLease(value.lease),
12994
- lastCheckpointAtMs: toOptionalNumber(value.lastCheckpointAtMs),
12995
- lastEnqueuedAtMs: toOptionalNumber(value.lastEnqueuedAtMs),
12996
- lastProgressAtMs: toOptionalNumber(value.lastProgressAtMs),
12997
- retryCount: toOptionalNumber(value.retryCount),
12998
- runId: toOptionalString(value.runId),
12999
- updatedAtMs: toOptionalNumber(value.updatedAtMs)
13525
+ lease: normalizeLease(value["lease"]),
13526
+ lastCheckpointAtMs: toOptionalNumber(value["lastCheckpointAtMs"]),
13527
+ lastEnqueuedAtMs: toOptionalNumber(value["lastEnqueuedAtMs"]),
13528
+ lastProgressAtMs: toOptionalNumber(value["lastProgressAtMs"]),
13529
+ retryCount: toOptionalNumber(value["retryCount"]),
13530
+ runId: toOptionalString(value["runId"]),
13531
+ updatedAtMs: toOptionalNumber(value["updatedAtMs"])
13000
13532
  };
13001
13533
  }
13002
13534
  /** Decode current conversation records. */
13003
13535
  function normalizeConversation(conversationId, value) {
13004
- if (!isRecord$2(value) || value.schemaVersion !== CONVERSATION_SCHEMA_VERSION) return;
13005
- const storedConversationId = toOptionalString(value.conversationId);
13006
- const createdAtMs = toOptionalNumber(value.createdAtMs);
13007
- const lastActivityAtMs = toOptionalNumber(value.lastActivityAtMs);
13008
- const updatedAtMs = toOptionalNumber(value.updatedAtMs);
13009
- const execution = normalizeExecution(conversationId, value.execution);
13010
- const destination = value.destination === void 0 ? void 0 : parseDestination(value.destination);
13011
- if (storedConversationId !== conversationId || typeof createdAtMs !== "number" || typeof lastActivityAtMs !== "number" || typeof updatedAtMs !== "number" || !execution || value.destination !== void 0 && !destination) return;
13536
+ if (!isRecord$2(value) || value["schemaVersion"] !== CONVERSATION_SCHEMA_VERSION) return;
13537
+ const storedConversationId = toOptionalString(value["conversationId"]);
13538
+ const createdAtMs = toOptionalNumber(value["createdAtMs"]);
13539
+ const lastActivityAtMs = toOptionalNumber(value["lastActivityAtMs"]);
13540
+ const updatedAtMs = toOptionalNumber(value["updatedAtMs"]);
13541
+ const execution = normalizeExecution(conversationId, value["execution"]);
13542
+ const destination = value["destination"] === void 0 ? void 0 : parseDestination(value["destination"]);
13543
+ if (storedConversationId !== conversationId || typeof createdAtMs !== "number" || typeof lastActivityAtMs !== "number" || typeof updatedAtMs !== "number" || !execution || value["destination"] !== void 0 && !destination) return;
13012
13544
  if (execution.pendingMessages.length > 0 && execution.pendingMessages.some((message) => {
13013
13545
  if (!message.destination) return false;
13014
13546
  return !destination || !sameDestination(message.destination, destination);
@@ -13021,10 +13553,10 @@ function normalizeConversation(conversationId, value) {
13021
13553
  updatedAtMs,
13022
13554
  execution,
13023
13555
  ...destination ? { destination } : void 0,
13024
- ...toOptionalString(value.title) ? { title: toOptionalString(value.title) } : void 0,
13025
- ...toOptionalString(value.channelName) ? { channelName: toOptionalString(value.channelName) } : void 0,
13026
- ...normalizeActor(value.actor) ? { actor: normalizeActor(value.actor) } : void 0,
13027
- ...normalizeSource(value.source) ? { source: normalizeSource(value.source) } : void 0
13556
+ ...toOptionalString(value["title"]) ? { title: toOptionalString(value["title"]) } : void 0,
13557
+ ...toOptionalString(value["channelName"]) ? { channelName: toOptionalString(value["channelName"]) } : void 0,
13558
+ ...normalizeActor(value["actor"]) ? { actor: normalizeActor(value["actor"]) } : void 0,
13559
+ ...normalizeSource(value["source"]) ? { source: normalizeSource(value["source"]) } : void 0
13028
13560
  };
13029
13561
  }
13030
13562
  function emptyConversation(args) {
@@ -13116,8 +13648,8 @@ async function withIndexLock(state, indexKey, callback) {
13116
13648
  }
13117
13649
  function normalizeIndexEntry(value) {
13118
13650
  if (!isRecord$2(value)) return;
13119
- const conversationId = toOptionalString(value.conversationId);
13120
- const score = toOptionalNumber(value.score);
13651
+ const conversationId = toOptionalString(value["conversationId"]);
13652
+ const score = toOptionalNumber(value["score"]);
13121
13653
  if (!conversationId || typeof score !== "number") return;
13122
13654
  return {
13123
13655
  conversationId,
@@ -13149,7 +13681,8 @@ function parseRedisIndexEntries(values) {
13149
13681
  const entries = [];
13150
13682
  for (let index = 0; index < values.length; index += 2) {
13151
13683
  const conversationId = toOptionalString(values[index]);
13152
- const score = typeof values[index + 1] === "number" ? values[index + 1] : Number(values[index + 1]);
13684
+ const rawScore = values[index + 1];
13685
+ const score = typeof rawScore === "number" ? rawScore : Number(rawScore);
13153
13686
  if (!conversationId || !Number.isFinite(score)) continue;
13154
13687
  entries.push({
13155
13688
  conversationId,
@@ -15390,7 +15923,6 @@ function recordDeliveredAssistantMessage(args) {
15390
15923
  },
15391
15924
  meta: {
15392
15925
  ...objectCards?.length ? { objectCards } : void 0,
15393
- ...args.quiet ? { quiet: args.quiet } : void 0,
15394
15926
  replied: true,
15395
15927
  ...args.source ? { source: args.source } : void 0
15396
15928
  }
@@ -15761,10 +16293,10 @@ async function resolveConversationTitle(args) {
15761
16293
  /** Serialize one in-memory message into its event-backed write shape. */
15762
16294
  function toStoredConversationMessage(message) {
15763
16295
  const meta = {};
15764
- if (message.author) meta.author = message.author;
16296
+ if (message.author) meta["author"] = message.author;
15765
16297
  const { replied, ...restMeta } = message.meta ?? {};
15766
16298
  Object.assign(meta, restMeta);
15767
- if (replied === false) meta.replied = false;
16299
+ if (replied === false) meta["replied"] = false;
15768
16300
  return {
15769
16301
  messageId: message.id,
15770
16302
  role: message.role,
@@ -15895,6 +16427,7 @@ function normalizeDurableMessage(message) {
15895
16427
  */
15896
16428
  function durableMessageIdentity(message) {
15897
16429
  const record = message;
16430
+ if (record.role === "system") return message;
15898
16431
  if (record.role === "toolResult") return {
15899
16432
  role: "toolResult",
15900
16433
  timestamp: record.timestamp,
@@ -16007,10 +16540,11 @@ function messageTimestamp(message) {
16007
16540
  * Append newly stable native history items.
16008
16541
  *
16009
16542
  * Checkpoints are append-only against the durable identity of the committed
16010
- * prefix (role, timestamp, content; tool results also match call id). A shorter
16011
- * history or a true content branch is rejected — only compaction may
16012
- * intentionally replace active model history. In-place Pi mutations of already
16013
- * committed assistant envelopes (usage/stopReason) do not block the suffix.
16543
+ * prefix (role, timestamp, content; tool results also match call id; system
16544
+ * messages match in full). A shorter history or a true content branch is
16545
+ * rejected — only compaction may intentionally replace active model history.
16546
+ * In-place Pi mutations of already committed assistant envelopes
16547
+ * (usage/stopReason) do not block the suffix.
16014
16548
  */
16015
16549
  async function commitMessages(args) {
16016
16550
  const executor = args.executor ?? getSqlExecutor();
@@ -16332,4 +16866,4 @@ async function recordGuardianActionReviewed(args) {
16332
16866
  createdAtMs: Date.now()
16333
16867
  }]);
16334
16868
  }
16335
- export { loadTurnCheckpoint as $, workspaceRepoCheckoutPath as $a, setWorkspaceSnapshotBuild as $i, resolvePluginOAuthAccount as $n, isSlackRequestTimeout as $o, EVERYONE_ASSIGNEE as $r, TurnSliceLimitExceededError as $t, latestConversationMessageSeq as A, updateSlackMessage as Aa, getDashboardLinkFilter as Ai, isStandaloneRuntimeContextMessage as An, readLatestConversationBrief as Ao, countReviewItemsNeedingUser as Ar, getConversationWorkStates as At, getAgentContextInputLimitTokens as B, isWorkspaceSnapshotNotReadyError as Ba, createPluginState as Bi, SCRIPT_TOOLS_SECTION_TAG as Bn, getSlackFileId as Bo, updateReviewItemContent as Br, recordConversationRetry as Bt, settleConversationTitleWork as C, getSlackMessagePermalink as Ca, bindSlackDirectCredentialSubject as Ci, getTerminalAssistantMessages as Cn, conversationIsMemberRoot as Co, saveNotificationSchedule as Cr, configValueSchema as Cs, countPendingConversationMessages as Ct, estimateConversationMessagesTokens as D, postSlackMessage as Da, verifyTimerWatchCredentialSubject as Di, instructionTextForProjection as Dn, viewerMarksFromParticipant as Do, createPluginReviewItems as Dr, getConfigDefaults as Ds, dropPendingMessages as Dt, buildConversationContext as E, postSlackEphemeralMessage as Ea, verifySlackDirectCredentialSubject as Ei, hasTurnInput as En, conversationViewerMarks as Eo, projectConversationMessages as Er, projectConversationEvents$1 as Es, drainConversationMailbox as Et, turnHasReply as F, isAlreadyExistsError as Fa, getDashboardTaskLink as Fi, retainRuntimeTurnContext as Fn, readConversationMessageEventSeq as Fo, listReplyActionItems as Fr, listActiveConversationIds as Ft, AuthPausePersistenceError as G, createSandboxEgressCredentialToken as Ga, getWorkspaceByName as Gi, readParentAgentTask as Gn, slackAttachmentsVersionQuery as Go, canUserReadReviewItem as Gr, startConversationWork as Gt, PluginCredentialFailureError as H, clearSandboxEgressSignals as Ha, createWorkspace as Hi, TURN_CONTEXT_TAG as Hn, readAttachmentVisionSummary as Ho, canActOnReviewItem as Hr, releaseInboundMessage as Ht, upsertConversationMessage as I, throwSandboxOperationError as Ia, isDashboardLink as Ii, stripRuntimeTurnContext as In, buildSentryConversationUrl as Io, listWaitingConversations as Ir, markConversationWorkEnqueued as It, abandonReplacedPendingAuth as J, buildSandboxEgressNetworkPolicy as Ja, updateWorkspace as Ji, renderUntrustedTag as Jn, getFilePermalink as Jo, requireReviewItemAssignees as Jr, takeDeferredConversationMove as Jt, AuthorizationFlowDisabledError as K, parseSandboxEgressCredentialToken as Ka, listWorkspaces as Ki, renderChildTag as Kn, SlackActionError as Ko, isOnlyAssignee as Kr, steerWebPendingMessages as Kt, calculateContextCompactionTargetTokens as L, wrapSandboxSetupError as La, parseDashboardConversationLink as Li, trimTrailingAssistantMessages as Ln, FORK_INSTRUCTIONS as Lo, reviewItemsNeedingUserVersionQuery as Lr, moveIdleConversationDestination as Lt, normalizeConversationText as M, slackEntitySchema as Ma, getDashboardPersonLink as Mi, isToolResultMessage as Mn, readConversationEventPageAfter as Mo, getOpenReviewItemByDedupeKey as Mr, hasRunnableConversationWork as Mt, recordDeliveredAssistantMessage as N, slackExternalRefIdSchema as Na, getDashboardReviewItemLink as Ni, latestTurnContextSection as Nn, readConversationEventPageAround as No, getReviewItem as Nr, isFinalAttempt as Nt, getConversationMessageSlackTs as O, removeReactionFromMessage as Oa, JUNIOR_THREAD_STATE_TTL_MS as Oi, isAssistantMessage as On, createPluginConversationEvents as Oo, REVIEW_ITEM_REPLIED_REASON as Or, setConfigDefaults as Os, getConversation as Ot, trimConversationMessages as P, isAbortError as Pa, getDashboardSettingsLink as Pi, normalizeToolNameFromResult as Pn, readConversationLastEventSeq as Po, insertReviewItem as Pr, isInvalidConversationRecordError as Pt, continuableMessages as Q, tryWorkspaceRepoCheckoutPath as Qa, setWorkspaceSnapshot as Qi, getOAuthAccountProviders as Qn, isDmChannel as Qo, reviewItemReaderForUserInConversation as Qr, TurnBudgetExceededError as Qt, getAgentBackgroundCompactionMarkTokens as R, WorkspaceSnapshotNotReadyError as Ra, parseDashboardPersonLink as Ri, CAPABILITY_SECTION_TAG as Rn, loadForkHistory as Ro, searchReviewItems as Rr, pruneActiveConversation as Rt, resolveConversationTitle as S, deleteSlackMessage as Sa, bindScheduledAutomationCredentialSubject as Si, getPiMessageRole as Sn, conversationHasParticipantUser as So, readNotificationSchedule as Sr, createDurableLocationConfigurationService as Ss, completeConversationWork as St, resolveTaskTitle as T, openSlackModal as Ta, verifyScheduledAutomationCredentialSubject as Ti, hasRuntimeTurnContext as Tn, conversationPinnedForUser as To, isPausedBySlack as Tr, piMessageFromHistoryItem as Ts, deferConversationMove as Tt, createPluginAuthOrchestration as U, consumeSandboxEgressAuthRequiredSignal as Ua, deleteWorkspace as Ui, escapeClosingTags as Un, readSlackAttachmentSource as Uo, canAgentChangeReviewItem as Ur, requestAnotherSlice as Ut, createPluginEgress as V, workspaceSnapshotNotReadyUserMessage as Va, renderToolResultNudge as Vi, SESSION_CONTEXT_SECTION_TAG as Vn, matchSlackAttachments as Vo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Vr, releaseConversationWork as Vt, authorizationId as W, consumeSandboxEgressPermissionDeniedSignal as Wa, getWorkspace as Wi, escapeTagText as Wn, recordSlackAttachment as Wo, canReadReviewItem as Wr, requestConversationWork as Wt, clearPendingAuth as X, normalizeSandboxEgressTracePropagationDomains as Xa, invalidateReadySnapshot as Xi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Xn, getSlackClient as Xo, reviewItemNeedsSomeone as Xr, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Xt, canReusePendingAuthLink as Y, resolveSandboxCommandEnvironment as Ya, WorkspaceValidationError as Yi, tagJson as Yn, getHeaderString as Yo, requireReviewItemLinks as Yr, readInboundMessageSender as Yt, getConversationPendingAuth as Z, SANDBOX_RUNTIME as Za, loadSnapshotsForProfile as Zi, createUserTokenStore as Zn, isConversationScopedChannel as Zo, reviewItemReaderForUser as Zr, TURN_LIMIT_WRAP_UP_MESSAGE as Zt, appendConversationMessages as _, slackMention as _a, findMatchingWatches as _i, CODE_MODE_CALL_STATUS_TEXT as _n, createPluginLogger as _o, readWebPushConfig as _r, lookupSlackUser as _s, checkInConversationWork as _t, loadProjection as a, isVercelSandboxEgressRequest as aa, resolveChannelCapabilities as ai, isAnswerToolName as an, SANDBOX_COMMAND_PATH as ao, getPluginRoutes as ar, getWorkspaceTeamId as as, failTurnRecord as at, persistConversationMessages as b, truncateStatusText as ba, takeDueTimerWatches as bi, persistWithRetry as bn, createConversationAccessReader as bo, deletePushSubscription as br, credentialAuditSource as bs, clearExpiredConversationLease as bt, recordAgentsInstructionsUpdated as c, formatProviderLabel as ca, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as ci, replyTextSchema as cn, SANDBOX_SKILLS_ROOT as co, getPluginTools as cr, resolveRootVisibility as cs, listTurnSummaries as ct, recordAuthorizationCompleted as d, startOAuthFlow as da, cancelSubscriptions as di, sanitizeAssistantText as dn, sandboxSkillFile as do, getStaticPluginToolDefinitions as dr, saveObjectAnnotations as ds, CONVERSATION_WORK_STALE_ENQUEUE_MS as dt, create as ea, activeParticipantUserIds as ei, TurnToolCallLimitExceededError as en, ToolInputError as eo, agent_hooks_exports as er, normalizeSlackConversationId as es, lostWorkerBeforeFirstSave as et, recordAuthorizationRequested as f, SLACK_USER_MENTION_RE as fa, cancelWatch as fi, NO_REPLY_TOOL_NAME as fn, sandboxSkillPathResolution as fo, setPlugins as fr, createPluginAnnotations as fs, ackMessages as ft, recordToolExecutionStarted as g, normalizeSlackStatusText as ga, deliverWatch as gi, CODEMODE_TOOL_NAME as gn, createPluginModelCostRecorder as go, setBriefsConfig as gr, resolveUserTimezone as gs, cancelHumanFacingPendingMessages as gt, recordSubscribedReplyRoute as h, normalizeSlackReplyMarkdown as ha, createWatch as hi, readNoReply as hn, runNonInteractiveCommand as ho, registration_exports as hr, defaultTimezone as hs, beginConversationResume as ht, loadConversationProjection as i, getSandboxProvider as ia, createCodeChangePublisher as ii, REPLY_TOOL_NAME as in, createPluginModel as io, getPluginApiRoutes as ir, sleep$2 as is, completeTurnRecord as it, markConversationMessage as j, uploadFilesToConversation as ja, getDashboardObjectIconLink as ji, isToolResultError as jn, readConversationEventPage as jo, dismissOpenReviewItems as jr, hasConversationStop as jt, isHumanConversationMessage as k, unfurlSlackLinks as ka, getDashboardConversationLink as ki, isContinuablePiBoundary as kn, readConversationBriefThrough as ko, closeReviewItem as kr, getConversationWorkState as kt, recordAttachmentsDelivered as l, parseOAuthStatePayload as la, RESOURCE_WATCH_TOOL_SOURCE as li, decideReply as ln, SANDBOX_WORKSPACE_ROOT as lo, getPluginUserPromptContributions as lr, searchConversations as ls, recordTurnSummary as lt, recordMcpProviderConnected as m, formatSlackLink as ma, createTimerWatch as mi, isLegacyNoReplyMarker as mn, buildNonInteractiveShellScript as mo, coreTaskRegistrations as mr, listConversationAnnotationsById as ms, appendInboundMessage as mt, commitMessages as n, isStale as na, resolveAssignee as ni, createTurnLimitGate as nn, PluginToolDeniedError as no, createPluginEventPublisher as nr, streamPrivateSlackFile as ns, saveTurnCheckpoint as nt, loadTurnProjection as o, proxyVercelSandboxEgressRequest as oa, getSlackToolContext as oi, readTurnAnswer as on, SANDBOX_DATA_ROOT as oo, getPluginSlackConversationLink as or, runWithWorkspaceTeamId as os, getStoredTurnFields as ot, recordGuardianActionReviewed as p, escapeSlackMrkdwnText as pa, collectEventMatchKeys as pi, findLegacyNoReplyMarker as pn, buildCommandScript as po, validatePlugins as pr, listConversationAnnotations as ps, appendExclusiveInboundMessage as pt, AuthorizationPauseError as q, sandboxEgressSignalsResponseSchema as qa, listWorkspacesByRepository as qi, renderTag as qn, downloadPrivateSlackFile as qo, readReviewItemAgentScope as qr, stopConversationWork as qt, loadConnectedMcpProviders as r, ensureDockerDaemon as ra, resolveAssignees as ri, isTurnExecutionLimitExceededError as rn, createPluginEmbedder as ro, createPluginHookRunner as rr, withSlackRetries as rs, abandonTurnRecord as rt, openConversationProjection as s, deliverOAuthAuthorization as sa, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as si, remindMissingAnswer as sn, SANDBOX_REPOS_ROOT as so, getPluginSystemPromptContributions as sr, AttachmentSourceUnavailableError as ss, getTurnRecord as st, commitAcceptedReply as t, hash as ta, automationCreatorUserId as ti, buildTurnErrorResponse as tn, isToolInputError as to, applyPluginFormatMarkdown as tr, runWithSlackInstallationToken as ts, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, resolveBaseUrl as ua, STOP_WATCHING_TOOL_NAME as ui, getAssistantReplyText as un, sandboxSkillDir as uo, getPlugins as ur, createConversationEmbedder as us, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as ut, hydrateConversationMessages as v, slackMentionedUserIds as va, getWatch as vi, REPORT_BLOCKED_TOOL_NAME as vn, canAccessConversation as vo, sendPushNotificationToUser as vr, lookupSlackUserNames as vs, claimInboundMessage as vt, fallbackShortTitle as w, openSlackDirectMessage as wa, verifyEventAutomationCredentialSubject as wi, getUserMessageInstructionText as wn, conversationIsNotUnsubscribedRoot as wo, savePushSubscription as wr, historyItemFromPiMessage as ws, deadLetterAttempt as wt, toStoredConversationMessage as x, addReactionToMessage as xa, bindEventAutomationCredentialSubject as xi, extractAssistantText as xn, readConversationAccessFromSql as xo, listPushSubscriptions as xr, createPluginCache as xs, completeConversationStop as xt, persistConversationMessageWindow as y, wrapBareSlackUserIds as ya, listWatches as yi, readBlockedReport as yn, canAddConversationMessages as yo, resolveNotificationTimezone as yr, credentialAuditAttributes as ys, clearConsumedConversationWake as yt, getAgentContextCompactionTriggerTokens as z, getWorkspaceSnapshotNotReadyError as za, setDashboardConversationLinkOptions as zi, REQUEST_CONTEXT_SECTION_TAG as zn, notInheritedByForkChild as zo, takeReviewItem as zr, recordAttemptFailure as zt };
16869
+ export { loadTurnCheckpoint as $, workspaceRepoCheckoutPath as $a, setWorkspaceSnapshotBuild as $i, applyPluginFormatMarkdown as $n, storeDeferredAttachment as $o, EVERYONE_ASSIGNEE as $r, TurnSliceLimitExceededError as $t, latestConversationMessageSeq as A, updateSlackMessage as Aa, getDashboardLinkFilter as Ai, isStandaloneRuntimeContextMessage as An, readLatestConversationBrief as Ao, dismissOpenReviewItems as Ar, createDurableLocationConfigurationService as As, getConversationWorkStates as At, getAgentContextInputLimitTokens as B, isWorkspaceSnapshotNotReadyError as Ba, createPluginState as Bi, TURN_CONTEXT_TAG as Bn, getSlackFileId as Bo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Br, recordConversationRetry as Bt, settleConversationTitleWork as C, getSlackMessagePermalink as Ca, bindSlackDirectCredentialSubject as Ci, getTerminalAssistantMessages as Cn, conversationIsMemberRoot as Co, isPausedBySlack as Cr, defaultTimezone as Cs, countPendingConversationMessages as Ct, estimateConversationMessagesTokens as D, postSlackMessage as Da, verifyTimerWatchCredentialSubject as Di, instructionTextForProjection as Dn, viewerMarksFromParticipant as Do, closeReviewItem as Dr, credentialAuditAttributes as Ds, dropPendingMessages as Dt, buildConversationContext as E, postSlackEphemeralMessage as Ea, verifySlackDirectCredentialSubject as Ei, hasTurnInput as En, conversationViewerMarks as Eo, REVIEW_ITEM_REPLIED_REASON as Er, lookupSlackUserNames as Es, drainConversationMailbox as Et, turnHasReply as F, isAlreadyExistsError as Fa, getDashboardTaskLink as Fi, stripRuntimeTurnContext as Fn, readConversationMessageEventSeq as Fo, listWaitingConversations as Fr, getConfigDefaults as Fs, listActiveConversationIds as Ft, AuthPausePersistenceError as G, createSandboxEgressCredentialToken as Ga, getWorkspaceByName as Gi, renderTag as Gn, slackAttachmentsVersionQuery as Go, isOnlyAssignee as Gr, startConversationWork as Gt, PluginCredentialFailureError as H, clearSandboxEgressSignals as Ha, createWorkspace as Hi, escapeTagText as Hn, readAttachmentVisionSummary as Ho, canAgentChangeReviewItem as Hr, releaseInboundMessage as Ht, upsertConversationMessage as I, throwSandboxOperationError as Ia, isDashboardLink as Ii, trimTrailingAssistantMessages as In, buildSentryConversationUrl as Io, reviewItemsNeedingUserVersionQuery as Ir, setConfigDefaults as Is, markConversationWorkEnqueued as It, abandonReplacedPendingAuth as J, buildSandboxEgressNetworkPolicy as Ja, updateWorkspace as Ji, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as Jn, readLiveAttachment as Jo, requireReviewItemAssignees as Jr, takeDeferredConversationMove as Jt, AuthorizationFlowDisabledError as K, parseSandboxEgressCredentialToken as Ka, listWorkspaces as Ki, renderUntrustedTag as Kn, collectAttachmentGarbage as Ko, itemNeedsUser as Kr, steerWebPendingMessages as Kt, calculateContextCompactionTargetTokens as L, wrapSandboxSetupError as La, parseDashboardConversationLink as Li, CAPABILITY_SECTION_TAG as Ln, FORK_INSTRUCTIONS as Lo, searchReviewItems as Lr, moveIdleConversationDestination as Lt, normalizeConversationText as M, slackEntitySchema as Ma, getDashboardPersonLink as Mi, isToolResultMessage as Mn, readConversationEventPageAfter as Mo, getReviewItem as Mr, historyItemFromPiMessage as Ms, hasRunnableConversationWork as Mt, recordDeliveredAssistantMessage as N, slackExternalRefIdSchema as Na, getDashboardReviewItemLink as Ni, normalizeToolNameFromResult as Nn, readConversationEventPageAround as No, insertReviewItem as Nr, piMessageFromHistoryItem as Ns, isFinalAttempt as Nt, getConversationMessageSlackTs as O, removeReactionFromMessage as Oa, JUNIOR_THREAD_STATE_TTL_MS as Oi, isAssistantMessage as On, createPluginConversationEvents as Oo, countOpenReviewItemsForUser as Or, credentialAuditSource as Os, getConversation as Ot, trimConversationMessages as P, isAbortError as Pa, getDashboardSettingsLink as Pi, retainRuntimeTurnContext as Pn, readConversationLastEventSeq as Po, listReplyActionItems as Pr, projectConversationEvents$1 as Ps, isInvalidConversationRecordError as Pt, continuableMessages as Q, tryWorkspaceRepoCheckoutPath as Qa, setWorkspaceSnapshot as Qi, agent_hooks_exports as Qn, storeAttachments as Qo, reviewItemReaderForUserInConversation as Qr, TurnBudgetExceededError as Qt, getAgentBackgroundCompactionMarkTokens as R, WorkspaceSnapshotNotReadyError as Ra, parseDashboardPersonLink as Ri, REQUEST_CONTEXT_SECTION_TAG as Rn, loadForkHistory as Ro, takeReviewItem as Rr, pruneActiveConversation as Rt, resolveConversationTitle as S, deleteSlackMessage as Sa, bindScheduledAutomationCredentialSubject as Si, getPiMessageRole as Sn, conversationHasParticipantUser as So, savePushSubscription as Sr, listConversationAnnotationsById as Ss, completeConversationWork as St, resolveTaskTitle as T, openSlackModal as Ta, verifyScheduledAutomationCredentialSubject as Ti, hasRuntimeTurnContext as Tn, conversationPinnedForUser as To, createPluginReviewItems as Tr, lookupSlackUser as Ts, deferConversationMove as Tt, createPluginAuthOrchestration as U, consumeSandboxEgressAuthRequiredSignal as Ua, deleteWorkspace as Ui, readParentAgentTask as Un, readSlackAttachmentSource as Uo, canReadReviewItem as Ur, requestAnotherSlice as Ut, createPluginEgress as V, workspaceSnapshotNotReadyUserMessage as Va, renderToolResultNudge as Vi, escapeClosingTags as Vn, matchSlackAttachments as Vo, canActOnReviewItem as Vr, releaseConversationWork as Vt, authorizationId as W, consumeSandboxEgressPermissionDeniedSignal as Wa, getWorkspace as Wi, renderChildTag as Wn, recordSlackAttachment as Wo, canUserReadReviewItem as Wr, requestConversationWork as Wt, clearPendingAuth as X, normalizeSandboxEgressTracePropagationDomains as Xa, invalidateReadySnapshot as Xi, getOAuthAccountProviders as Xn, requestAttachmentDeletion as Xo, reviewItemNeedsSomeone as Xr, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Xt, canReusePendingAuthLink as Y, resolveSandboxCommandEnvironment as Ya, WorkspaceValidationError as Yi, createUserTokenStore as Yn, recordUploadedAttachment as Yo, requireReviewItemLinks as Yr, readInboundMessageSender as Yt, getConversationPendingAuth as Z, SANDBOX_RUNTIME as Za, loadSnapshotsForProfile as Zi, resolvePluginOAuthAccount as Zn, storeAttachment 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, resolveNotificationTimezone as _r, searchConversations as _s, checkInConversationWork as _t, loadProjection as a, isVercelSandboxEgressRequest as aa, resolveChannelCapabilities as ai, isAnswerToolName as an, SANDBOX_COMMAND_PATH as ao, getPluginSystemPromptContributions as ar, isConversationScopedChannel as as, failTurnRecord as at, persistConversationMessages as b, truncateStatusText as ba, takeDueTimerWatches as bi, persistWithRetry as bn, createConversationAccessReader as bo, readNotificationSchedule as br, createPluginAnnotations 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, getPlugins as cr, normalizeSlackConversationId as cs, listTurnSummaries as ct, recordAuthorizationCompleted as d, startOAuthFlow as da, cancelSubscriptions as di, sanitizeAssistantText as dn, sandboxSkillFile as do, validatePlugins as dr, withSlackRetries as ds, CONVERSATION_WORK_STALE_ENQUEUE_MS as dt, create as ea, activeParticipantUserIds as ei, TurnToolCallLimitExceededError as en, ToolInputError as eo, createPluginEventPublisher as er, SlackActionError 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, coreTaskRegistrations as fr, sleep$2 as fs, ackMessages as ft, recordToolExecutionStarted as g, normalizeSlackStatusText as ga, deliverWatch as gi, CODEMODE_TOOL_NAME as gn, createPluginModelCostRecorder as go, sendPushNotificationToUser as gr, resolveRootVisibility as gs, cancelHumanFacingPendingMessages as gt, recordSubscribedReplyRoute as h, normalizeSlackReplyMarkdown as ha, createWatch as hi, readNoReply as hn, runNonInteractiveCommand as ho, readWebPushConfig as hr, AttachmentSourceUnavailableError as hs, beginConversationResume as ht, loadConversationProjection as i, getSandboxProvider as ia, createCodeChangePublisher as ii, REPLY_TOOL_NAME as in, createPluginModel as io, getPluginSlackConversationLink as ir, getSlackClient as is, completeTurnRecord as it, markConversationMessage as j, uploadFilesToConversation as ja, getDashboardObjectIconLink as ji, isToolResultError as jn, readConversationEventPage as jo, getOpenReviewItemByDedupeKey as jr, configValueSchema as js, hasConversationStop as jt, isHumanConversationMessage as k, unfurlSlackLinks as ka, getDashboardConversationLink as ki, isContinuablePiBoundary as kn, readConversationBriefThrough as ko, countReviewItemsNeedingUserBySubject as kr, createPluginCache as ks, getConversationWorkState as kt, recordAttachmentsDelivered as l, parseOAuthStatePayload as la, RESOURCE_WATCH_TOOL_SOURCE as li, decideReply as ln, SANDBOX_WORKSPACE_ROOT as lo, getStaticPluginToolDefinitions as lr, runWithSlackInstallationToken as ls, recordTurnSummary as lt, recordMcpProviderConnected as m, formatSlackLink as ma, createTimerWatch as mi, isLegacyNoReplyMarker as mn, buildNonInteractiveShellScript as mo, setBriefsConfig as mr, runWithWorkspaceTeamId as ms, appendInboundMessage as mt, commitMessages as n, isStale as na, resolveAssignee as ni, createTurnLimitGate as nn, PluginToolDeniedError as no, getPluginApiRoutes as nr, getFilePermalink as ns, saveTurnCheckpoint as nt, loadTurnProjection as o, proxyVercelSandboxEgressRequest as oa, getSlackToolContext as oi, readTurnAnswer as on, SANDBOX_DATA_ROOT as oo, getPluginTools as or, isDmChannel as os, getStoredTurnFields as ot, recordGuardianActionReviewed as p, escapeSlackMrkdwnText as pa, collectEventMatchKeys as pi, findLegacyNoReplyMarker as pn, buildCommandScript as po, registration_exports as pr, getWorkspaceTeamId as ps, appendExclusiveInboundMessage as pt, AuthorizationPauseError as q, sandboxEgressSignalsResponseSchema as qa, listWorkspacesByRepository as qi, tagJson as qn, isFileAttachment as qo, readReviewItemAgentScope as qr, stopConversationWork as qt, loadConnectedMcpProviders as r, ensureDockerDaemon as ra, resolveAssignees as ri, isTurnExecutionLimitExceededError as rn, createPluginEmbedder as ro, getPluginRoutes as rr, getHeaderString 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, getPluginUserPromptContributions as sr, isSlackRequestTimeout as ss, getTurnRecord as st, commitAcceptedReply as t, hash as ta, automationCreatorUserId as ti, buildTurnErrorResponse as tn, isToolInputError as to, createPluginHookRunner as tr, downloadPrivateSlackFile as ts, pauseLostWorkerTurn as tt, recordAuthenticationLinked as u, resolveBaseUrl as ua, STOP_WATCHING_TOOL_NAME as ui, getAssistantReplyText as un, sandboxSkillDir as uo, setPlugins as ur, streamPrivateSlackFile 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, deletePushSubscription as vr, createConversationEmbedder as vs, claimInboundMessage as vt, fallbackShortTitle as w, openSlackDirectMessage as wa, verifyEventAutomationCredentialSubject as wi, getUserMessageInstructionText as wn, conversationIsNotUnsubscribedRoot as wo, projectConversationMessages as wr, resolveUserTimezone as ws, deadLetterAttempt as wt, toStoredConversationMessage as x, addReactionToMessage as xa, bindEventAutomationCredentialSubject as xi, extractAssistantText as xn, readConversationAccessFromSql as xo, saveNotificationSchedule as xr, listConversationAnnotations as xs, completeConversationStop as xt, persistConversationMessageWindow as y, wrapBareSlackUserIds as ya, listWatches as yi, readBlockedReport as yn, canAddConversationMessages as yo, listPushSubscriptions as yr, saveObjectAnnotations as ys, clearConsumedConversationWake as yt, getAgentContextCompactionTriggerTokens as z, getWorkspaceSnapshotNotReadyError as za, setDashboardConversationLinkOptions as zi, SESSION_CONTEXT_SECTION_TAG as zn, notInheritedByForkChild as zo, updateReviewItemContent as zr, recordAttemptFailure as zt };