@sentry/junior 0.307.1 → 0.309.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 (84) hide show
  1. package/dist/{actor-D2iXzvlN.js → actor-BsBdxDXQ.js} +0 -1
  2. package/dist/{adapter-context-HrBTD8rJ.js → adapter-context-1YUbMpD3.js} +2 -2
  3. package/dist/{admin-B78_KmfR.js → admin-u30A8TcD.js} +2 -2
  4. package/dist/{agent-runner-DxivxUYd.js → agent-runner-sJLhgPQV.js} +93 -90
  5. package/dist/api/schema.d.ts +1 -1
  6. package/dist/api/schema.js +4 -4
  7. package/dist/api.d.ts +4 -2
  8. package/dist/api.js +416 -272
  9. package/dist/{app-EZur8cVC.d.ts → app-B_7Wn0en.d.ts} +6 -7
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +73 -193
  12. package/dist/{background-compaction-queue-HlljT9ql.js → background-compaction-queue-CUJXVKG3.js} +4 -4
  13. package/dist/{briefs-DR8mp-TK.js → briefs-BHi70IR5.js} +3 -3
  14. package/dist/{catalog-runtime-Se9idiDR.js → catalog-runtime-Chc_IP2o.js} +1 -1
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +10 -10
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +5 -5
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-DY5c1E0l.js → config-BIyIdTtA.js} +52 -93
  23. package/dist/{continue-in-slack-DNkrrWuQ.js → continue-in-slack-BQJBfiQh.js} +6 -6
  24. package/dist/{conversation--f85g4zL.js → conversation-CzrLhdHG.js} +6 -1
  25. package/dist/{conversation-feed-BNs9KiqC.js → conversation-feed-B9e3_gxz.js} +1 -1
  26. package/dist/{conversation-privacy-CVj9vSrP.js → conversation-privacy-CkTW29hd.js} +1 -1
  27. package/dist/{conversation-turn-CkzrIfJ2.js → conversation-turn-CZaYQUum.js} +19 -20
  28. package/dist/{credential-sync-B9CIkgOT.js → credential-sync-58m_CyIJ.js} +31 -23
  29. package/dist/{db-C41UgdBj.d.ts → db-B4Hjxr-u.d.ts} +2 -2
  30. package/dist/{db-C21CyyTE.js → db-CFUpEZi9.js} +11 -9
  31. package/dist/{executor-DfNoVVGd.js → executor-DXL0O0MV.js} +4 -3
  32. package/dist/fan-out-Cod-yEHG.js +10 -0
  33. package/dist/{connections-C-SqzubG.js → html-CaBu2VbT.js} +146 -11
  34. package/dist/{install-lYZs8UCL.js → install-DhTBUUov.js} +2 -2
  35. package/dist/instrumentation.js +2 -2
  36. package/dist/{lineage-BJTSY53A.js → lineage-CxtOI2_p.js} +2 -2
  37. package/dist/{logging-DjW7LjgJ.js → logging-BNUovdcX.js} +1 -1
  38. package/dist/{message-BPPZpdoZ.js → message-DcUsS2vg.js} +8 -8
  39. package/dist/{model-input-DKqiLFGa.js → model-input-o3rEqgwM.js} +15 -10
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +4 -4
  42. package/dist/{oauth-callback-server-OJP8Y4Ca.js → oauth-callback-server-1Fizd1EM.js} +2 -2
  43. package/dist/{oauth-relay-KwDz41Z3.js → oauth-relay-DOwngqdM.js} +1 -1
  44. package/dist/{package-discovery-x4AvVhMj.js → package-discovery-DD9vencX.js} +0 -1
  45. package/dist/{projection-D47mlszd.js → projection-Ce4pmhKP.js} +108 -125
  46. package/dist/{prompt-DuWH_YIb.js → prompt-DEqjDVMs.js} +25 -14
  47. package/dist/{registry-yht0oxq6.js → registry-CNE4ZBnG.js} +3 -3
  48. package/dist/{resolve-gZ-hVMYl.js → resolve-qbPg-aC-.js} +3 -3
  49. package/dist/{result-CP99Ok0_.js → result-ZGnDzcsb.js} +12 -13
  50. package/dist/{runner-eVlnUkY7.js → runner-eGIxpAMf.js} +10 -10
  51. package/dist/{sandbox-egress-signals-DZL_0lnG.js → sandbox-egress-signals-DMFB1kCp.js} +1 -1
  52. package/dist/{schedule-BG1tEbRF.js → schedule-Cire6NU7.js} +1 -1
  53. package/dist/{schema-D4jdesIu.js → schema-CfIey9Ao.js} +65 -28
  54. package/dist/{schema-CRXcj4fj.d.ts → schema-DriSvB40.d.ts} +43 -43
  55. package/dist/{service-account-tI3LBg2_.js → service-account-B1VXCTqg.js} +3 -3
  56. package/dist/{service-account-CZneZHh7.js → service-account-Cw_LWZ4-.js} +7 -8
  57. package/dist/{session-stop-D3S7mSkX.js → session-stop-P2XdTiwr.js} +191 -187
  58. package/dist/{skills-Bm6uSO9V.js → skills-Zg8-vrje.js} +25 -29
  59. package/dist/{slack-conversation-unfurl-BeBvg3xU.js → slack-conversation-unfurl-DA51qH0c.js} +18 -15
  60. package/dist/{spawn-vhMAmLuh.js → spawn-DBi4-zD8.js} +6 -6
  61. package/dist/{state-3Yiy2FvP.js → state-C-Ftk23K.js} +4 -4
  62. package/dist/{stop-Bh53GUoX.js → stop-D9xideLM.js} +175 -134
  63. package/dist/{store-BZJdHYR7.js → store-BjIXA0Al.js} +5 -5
  64. package/dist/{task-queue-BEl5G38v.js → task-queue-D0_qbnpo.js} +7 -4
  65. package/dist/{task-runner-C6Bujc6h.js → task-runner-DQMq4XY0.js} +10 -11
  66. package/dist/{thread-context-DxMQGGd_.js → thread-context-D0i1e-5O.js} +13 -11
  67. package/dist/{turn-session-routing-CmQY0T60.js → turn-session-routing-C0l68I_O.js} +4 -4
  68. package/dist/{turn-user-message-Dfbr3Ud9.js → turn-user-message-nBVvOXjs.js} +14 -5
  69. package/dist/{queue-CbEHUO0l.d.ts → types-fnU7Xs__.d.ts} +3 -1
  70. package/dist/{users-6rSdqXXk.js → users-DdjMjbmM.js} +1 -1
  71. package/dist/{validation--hsjOLRL.js → validation-CRbvRPvu.js} +1 -1
  72. package/dist/{version-9iMT25Hq.js → version-BYdVs12p.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{viewer-De1vmuEA.js → viewer-DudYrQGj.js} +7 -5
  75. package/dist/{warmup-C0IblNtf.js → warmup-DN9OHN1-.js} +136 -78
  76. package/dist/{worker-CiyRr2q7.js → worker-C9ZfJXmV.js} +8 -8
  77. package/migrations/0121_people_list_metric_index.sql +1 -0
  78. package/migrations/0122_automation_rollout_repair.sql +56 -0
  79. package/migrations/0123_cache_warming_history_reset.sql +10 -0
  80. package/migrations/meta/0121_snapshot.json +5481 -0
  81. package/migrations/meta/0122_snapshot.json +5481 -0
  82. package/migrations/meta/0123_snapshot.json +5481 -0
  83. package/migrations/meta/_journal.json +21 -0
  84. package/package.json +7 -7
@@ -1,29 +1,30 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
2
  import { d as contextProvenance, f as instructionActors, n as agentHistoryItemSchema, p as instructionProvenanceFor } from "./history-N7IVbUom.js";
3
- import { S as renderJuniorNativeConversationEvent, _ as JUNIOR_NATIVE_EVENT_NAMESPACE, b as authenticationUnlinkedEvent, c as generateBrief, d as completeText, f as embedTexts, n as briefEntriesFromReportEvents, s as isEventConversationMessage, t as BRIEF_PROMPT, u as completeObject, v as agentsInstructionsUpdatedEvent, y as authenticationLinkedEvent } from "./prompt-DuWH_YIb.js";
4
- import { $ as getStateAdapter, Ct as conversationDetailTouch, Dt as parseDestination, I as resolveActorIdentityId, K as saveUserTimezone, N as startLocationThread, Q as getDefaultRedisStateAdapterFor, S as createSqlStore, T as isPersonInput, Tt as touchConversationDetail, U as linkedSlackUser, W as readUserTimezone, X as createCache, _t as agentTurnCostUsd, a as getConversationStore, at as withLock, bt as hasAgentTurnUsage, c as hasAnnotationKey, d as eventFromRow, dt as microUsdToUsd, et as getStateValues, ft as usdToMicroUsd, gt as addAgentTurnUsage, it as fenceLock, kt as sameDestination, l as treeHasAnnotationKey, lt as conversationCostOf, m as withConversationEventLock, nt as MUTATION_LOCK_TTL_MS, o as getDb, ot as claimProviderConversation, r as getConversationEventStore, rt as acquireActiveLock, s as getSqlExecutor, tt as setStateValues, u as createSqlConversationEventStore, vt as agentTurnTotalTokens } from "./db-C21CyyTE.js";
5
- import { A as juniorConversationEvents, B as juniorUsers, C as juniorConversationEventLexemes, E as juniorConversationBriefs, I as juniorAttachments, L as juniorMessageAttachments, M as juniorConversationAnnotations, N as juniorCodeChanges, P as juniorCodeRepositories, R as juniorConversations, T as juniorConversationEmbeddings, V as juniorDestinations, _ as juniorLocationConfigurations, a as juniorWorkspaces, f as juniorReviewItems, h as juniorAutomations, i as juniorWorkspaceRepos, l as juniorReviewItemAssignees, m as juniorAutomationVersions, n as isPostgresErrorCode, o as juniorPushSubscriptions, p as juniorAutomationRuns, r as juniorSnapshots, u as juniorReviewItemConversations, w as juniorConversationEventEmbeddings, x as juniorConversationParticipants, z as juniorIdentities } from "./executor-DfNoVVGd.js";
6
- import { E as withSpan, J as toOptionalString, K as isRecord$3, _ 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-DjW7LjgJ.js";
7
- import { _ as credentialUserSubjectId, a as HOST_MANAGED_CREDENTIAL_PLACEHOLDER, g as credentialSubjectSchema, h as credentialLogContext, m as credentialContextSchema, o as resolveAuthTokenPlaceholder, p as credentialContextForActor, s as resolvePluginCommandEnv, v as CredentialUnavailableError } from "./registry-yht0oxq6.js";
8
- import { D as automationVersionSchema, J as automationSkillNameSchema, L as scheduledAutomationSchema, P as eventAutomationSchema, X as automationTaskDescription, Y as automationTaskColumns, Z as automationTaskSchema, n as isWithinNotificationSchedule, q as isValidTimeZone, r as notificationScheduleSchema, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-BG1tEbRF.js";
9
- import { B as unwrapCurrentInstruction, C as completeObject$1, J as readParentAgentTask, K as isRuntimeInputText, O as rerankTexts, P as estimateTextTokens, S as completeDecision, T as embedTexts$1, U as authorAttrs, V as escapeXml, b as GEN_AI_PROVIDER_NAME, dt as toOptionalTrimmed, i as getChatConfig, k as resolveGatewayModel, lt as bufferBody, n as botConfig, o as getSlackBotToken, q as openingTag, y as normalizeSlackEmojiName } from "./config-DY5c1E0l.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";
3
+ import { _ as JUNIOR_NATIVE_EVENT_NAMESPACE, c as generateBrief, d as completeText, f as embedTexts, n as briefEntriesFromReportEvents, s as isEventConversationMessage, t as BRIEF_PROMPT, u as completeObject, v as agentsInstructionsUpdatedEvent, x as renderJuniorNativeConversationEvent, y as authenticationLinkedEvent } from "./prompt-DEqjDVMs.js";
4
+ import { $ as getDefaultRedisStateAdapterFor, At as sameDestination, Et as touchConversationDetail, I as resolveActorIdentityId, K as saveUserTimezone, N as startLocationThread, Ot as parseDestination, S as createSqlStore, T as isPersonInput, U as linkedSlackUser, W as readUserTimezone, Z as createCache, _t as addAgentTurnUsage, a as getConversationStore, at as fenceLock, c as hasAnnotationKey, d as eventFromRow, et as getStateAdapter, ft as microUsdToUsd, it as acquireActiveLock, l as treeHasAnnotationKey, m as withConversationEventLock, nt as setStateValues, o as getDb, ot as withLock, pt as usdToMicroUsd, r as getConversationEventStore, rt as MUTATION_LOCK_TTL_MS, s as getSqlExecutor, st as claimProviderConversation, tt as getStateValues, u as createSqlConversationEventStore, ut as conversationCostOf, vt as agentTurnCostUsd, wt as conversationDetailTouch, xt as hasAgentTurnUsage, yt as agentTurnTotalTokens } from "./db-CFUpEZi9.js";
5
+ import { A as juniorConversationEvents, B as juniorUsers, C as juniorConversationEventLexemes, E as juniorConversationBriefs, I as juniorAttachments, L as juniorMessageAttachments, M as juniorConversationAnnotations, N as juniorCodeChanges, P as juniorCodeRepositories, R as juniorConversations, T as juniorConversationEmbeddings, V as juniorDestinations, _ as juniorLocationConfigurations, a as juniorWorkspaces, f as juniorReviewItems, h as juniorAutomations, i as juniorWorkspaceRepos, l as juniorReviewItemAssignees, m as juniorAutomationVersions, n as isPostgresErrorCode, o as juniorPushSubscriptions, p as juniorAutomationRuns, r as juniorSnapshots, u as juniorReviewItemConversations, w as juniorConversationEventEmbeddings, x as juniorConversationParticipants, z as juniorIdentities } from "./executor-DXL0O0MV.js";
6
+ import { E as withSpan, J as toOptionalString, K as isRecord$3, _ 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-BNUovdcX.js";
7
+ import { _ as credentialUserSubjectId, a as HOST_MANAGED_CREDENTIAL_PLACEHOLDER, g as credentialSubjectSchema, h as credentialLogContext, m as credentialContextSchema, o as resolveAuthTokenPlaceholder, p as credentialContextForActor, s as resolvePluginCommandEnv, v as CredentialUnavailableError } from "./registry-CNE4ZBnG.js";
8
+ import { D as automationVersionSchema, J as automationSkillNameSchema, L as scheduledAutomationSchema, P as eventAutomationSchema, X as automationTaskDescription, Y as automationTaskColumns, Z as automationTaskSchema, n as isWithinNotificationSchedule, q as isValidTimeZone, r as notificationScheduleSchema, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-Cire6NU7.js";
9
+ import { C as completeObject$1, G as readParentAgentTask, H as THREAD_CONTEXT_TAGS, O as rerankTexts, P as estimateTextTokens, S as completeDecision, T as embedTexts$1, U as authorAttrs, V as unwrapCurrentInstruction, W as isRuntimeInputText, at as bufferBody, b as GEN_AI_PROVIDER_NAME, i as getChatConfig, k as resolveGatewayModel, n as botConfig, o as getSlackBotToken, q as renderThreadContext, st as toOptionalTrimmed, y as normalizeSlackEmojiName, z as hasCurrentInstruction } from "./config-BIyIdTtA.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-BsBdxDXQ.js";
11
11
  import { a as getClient$1, h as startSpan, n as captureMessage, r as continueTrace } from "./sentry-CPbZjomA.js";
12
- import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-De1vmuEA.js";
13
- import { F as briefResourceLabel, I as conversationBriefSchema, J as readMessageCardRefs, K as messageCardRef, L as parseBriefInput, R as parseStoredBrief, W as reviewItemChangeRecordSchema, _ as conversationReportMessageEventSchema, g as conversationReportEventSchema, tt as readMessageAttachments } from "./conversation--f85g4zL.js";
14
- import { d as readJuniorSecret, m as readWebPushPrivateKey, r as pluginTaskId } from "./task-queue-BEl5G38v.js";
15
- import { t as canExposeConversationPayload } from "./conversation-privacy-CVj9vSrP.js";
16
- import { n as pluginCatalogRuntime } from "./catalog-runtime-Se9idiDR.js";
12
+ import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-DudYrQGj.js";
13
+ import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
14
+ import { F as briefResourceLabel, I as conversationBriefSchema, J as readMessageCardRefs, K as messageCardRef, L as parseBriefInput, R as parseStoredBrief, W as reviewItemChangeRecordSchema, _ as conversationReportMessageEventSchema, g as conversationReportEventSchema, tt as readMessageAttachments } from "./conversation-CzrLhdHG.js";
15
+ import { d as readJuniorSecret, m as readWebPushPrivateKey, r as pluginTaskId } from "./task-queue-D0_qbnpo.js";
16
+ import { t as canExposeConversationPayload } from "./conversation-privacy-CkTW29hd.js";
17
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Chc_IP2o.js";
17
18
  import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
18
- import { n as readEncryptedState, r as findLegacyWebActorUserId, t as createEncryptedState } from "./state-3Yiy2FvP.js";
19
- import pLimit from "p-limit";
19
+ import { n as readEncryptedState, r as findLegacyWebActorUserId, t as createEncryptedState } from "./state-C-Ftk23K.js";
20
20
  import * as z from "zod";
21
+ import pLimit from "p-limit";
21
22
  import path from "node:path";
22
23
  import { isDeepStrictEqual } from "node:util";
23
24
  import { AsyncLocalStorage } from "node:async_hooks";
24
25
  import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, randomUUID, sign, timingSafeEqual } from "node:crypto";
26
+ import { EgressAuthRequired, EgressPolicyDenied, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeInputSchema, conversationAnnotationInputSchema, defineConversationEvent, describeEventTrigger, destinationSchema, destinationVisibilitySchema, escapeTagTextAndQuotes, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, indentTagLines, isPluginModelCostEventName, isSlackDestination, missingToolAnnotationKeys, normalizeEventIdentifier, normalizeEventMatch, objectAnnotationSchema, objectIconPath, objectLinkFilterSchema, objectTypeSchema, openingTag, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, renderInlineTag, renderTag, replyAttributionSchema, sourceSchema, stableEventMatchKey, stripTags, taskOutcomeSchema } from "@sentry/junior-plugin-api";
25
27
  import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, not, notExists, notLike, or, sql } from "drizzle-orm";
26
- import { EgressAuthRequired, EgressPolicyDenied, PluginToolInputError, actorSchema, agentEventMatchSchema, anyResourceMatchFields, codeChangeInputSchema, conversationAnnotationInputSchema, defineConversationEvent, describeEventTrigger, destinationSchema, destinationVisibilitySchema, eventDataSchema, eventInputSchema, eventMatchSchema, eventMatches, eventTriggerChoices, eventTriggerProblems, eventTypeSchema, isPluginModelCostEventName, isSlackDestination, missingToolAnnotationKeys, normalizeEventIdentifier, normalizeEventMatch, objectAnnotationSchema, objectIconPath, objectLinkFilterSchema, objectTypeSchema, pluginAuditAttributesSchema, pluginAuthorizationSchema, pluginCredentialHeaderTransformSchema, pluginCredentialResultSchema, pluginEventsSchema, pluginGrantSchema, pluginModelCostEventNames, pluginProviderAccountSchema, pluginStoredTokensSchema, pluginToolReplySchema, promptContextSchema, promptMessageSchema, replyAttributionSchema, sourceSchema, stableEventMatchKey, taskOutcomeSchema } from "@sentry/junior-plugin-api";
27
28
  import { alias } from "drizzle-orm/pg-core";
28
29
  import { embedText, guardedCosineDistance, refreshEmbeddings } from "@sentry/junior-plugin-api/embeddings";
29
30
  import fs from "node:fs/promises";
@@ -62,10 +63,6 @@ function getConfigDefaults() {
62
63
  // src/chat/pi/messages.ts
63
64
  /** Permissive schema for durable Pi SDK messages whose content shape may evolve. */
64
65
  const piMessageSchema = z.object({ role: z.string() }).passthrough().transform((value) => value);
65
- z.object({
66
- content: z.array(z.unknown()),
67
- role: z.string().min(1)
68
- }).passthrough().transform((value) => value);
69
66
  // src/chat/pi/conversation-events.ts
70
67
  function authorizationObservationMessage(data, createdAtMs) {
71
68
  const label = data.kind === "mcp" ? "MCP authorization" : "Authorization";
@@ -2166,6 +2163,13 @@ function wrapBareSlackUserIds(text) {
2166
2163
  }
2167
2164
  const LIST_ITEM_PATTERN = /^[-*•]\s|^\d+\.\s/;
2168
2165
  /**
2166
+ * Report whether a line is a Markdown pipe-table row. Slack's `markdown`
2167
+ * block renders a table only when its rows are on consecutive lines.
2168
+ */
2169
+ function isTableRow(line) {
2170
+ return line.trimStart().startsWith("|");
2171
+ }
2172
+ /**
2169
2173
  * Turn a follow-up paragraph inside a list item into a bullet at the same
2170
2174
  * indent.
2171
2175
  *
@@ -2182,7 +2186,7 @@ function bulletListFollowUpParagraphs(text) {
2182
2186
  const trimmed = line.trimStart();
2183
2187
  const isFence = trimmed.startsWith("```");
2184
2188
  if (!inCodeBlock && trimmed && trimmed.length === line.length) inList = LIST_ITEM_PATTERN.test(line);
2185
- else if (!inCodeBlock && inList && trimmed && !isFence && lines[i - 1]?.trim() === "" && !LIST_ITEM_PATTERN.test(trimmed)) lines[i] = `${line.slice(0, line.length - trimmed.length)}- ${trimmed}`;
2189
+ else if (!inCodeBlock && inList && trimmed && !isFence && lines[i - 1]?.trim() === "" && !LIST_ITEM_PATTERN.test(trimmed) && !isTableRow(trimmed)) lines[i] = `${line.slice(0, line.length - trimmed.length)}- ${trimmed}`;
2186
2190
  if (isFence) inCodeBlock = !inCodeBlock;
2187
2191
  }
2188
2192
  return lines.join("\n");
@@ -2210,7 +2214,7 @@ function ensureBlockSpacing(text) {
2210
2214
  const prev = result.length > 0 ? result[result.length - 1] : void 0;
2211
2215
  const isListItem = LIST_ITEM_PATTERN.test(line.trimStart());
2212
2216
  const isListContinuation = prev !== void 0 && !isListItem && /^\s/.test(line) && (/^\s/.test(prev) || LIST_ITEM_PATTERN.test(prev));
2213
- if (prev !== void 0 && prev.trim() !== "" && line.trim() !== "" && !isListContinuation && !(LIST_ITEM_PATTERN.test(prev.trimStart()) && isListItem)) result.push("");
2217
+ if (prev !== void 0 && prev.trim() !== "" && line.trim() !== "" && !isListContinuation && !(LIST_ITEM_PATTERN.test(prev.trimStart()) && isListItem) && !(isTableRow(prev) && isTableRow(line))) result.push("");
2214
2218
  result.push(line);
2215
2219
  }
2216
2220
  return result.join("\n");
@@ -3718,8 +3722,7 @@ async function lookupSlackUserNames(teamId, userIds) {
3718
3722
  if (parsed.success) names.set(userId, parsed.data);
3719
3723
  else missing.push(userId);
3720
3724
  }
3721
- const limit = pLimit(USER_NAMES_LOOKUP_CONCURRENCY);
3722
- const profiles = await Promise.all(missing.map((userId) => limit(() => lookupSlackUser(teamId, userId))));
3725
+ const profiles = await mapBounded(missing, (userId) => lookupSlackUser(teamId, userId), USER_NAMES_LOOKUP_CONCURRENCY);
3723
3726
  const found = [];
3724
3727
  for (const [index, userId] of missing.entries()) {
3725
3728
  const profile = profiles[index];
@@ -4715,8 +4718,7 @@ async function readLiveAttachment(args) {
4715
4718
  }
4716
4719
  /** Persist many conversation-owned files. */
4717
4720
  async function storeAttachments(args) {
4718
- const limit = pLimit(8);
4719
- return await Promise.all(args.files.map((file) => limit(() => storeAttachment({
4721
+ return await mapBounded(args.files, (file) => storeAttachment({
4720
4722
  conversationId: args.conversationId,
4721
4723
  db: args.db,
4722
4724
  file: {
@@ -4726,7 +4728,7 @@ async function storeAttachments(args) {
4726
4728
  },
4727
4729
  ...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
4728
4730
  storage: args.storage
4729
- }))));
4731
+ }));
4730
4732
  }
4731
4733
  /** Mark attachments unavailable when their conversation content is purged. */
4732
4734
  async function requestAttachmentDeletion(db, conversationIds, nowMs) {
@@ -5756,11 +5758,13 @@ async function buildBriefsOperationalReport(args) {
5756
5758
  const newestDay = startOfUtcDay(args.nowMs);
5757
5759
  const windowStart = /* @__PURE__ */ new Date(newestDay.getTime() - 29 * DAY_MS$2);
5758
5760
  const windowEnd = new Date(newestDay.getTime() + DAY_MS$2);
5759
- const [[counts], recentCounts] = await Promise.all([args.db.select({
5761
+ const inWindow = and(gte(juniorConversationBriefs.createdAt, windowStart), lt(juniorConversationBriefs.createdAt, windowEnd));
5762
+ const [[counts], briefDays] = await Promise.all([args.db.select({
5760
5763
  conversations: sql`count(distinct ${juniorConversationBriefs.conversationId})`.mapWith(Number),
5764
+ recent: sql`count(*) filter (where ${inWindow})`.mapWith(Number),
5761
5765
  stored: sql`count(*)`.mapWith(Number)
5762
- }).from(juniorConversationBriefs), args.db.select({ stored: sql`count(*)`.mapWith(Number) }).from(juniorConversationBriefs).where(and(gte(juniorConversationBriefs.createdAt, windowStart), lt(juniorConversationBriefs.createdAt, windowEnd)))]);
5763
- const recentDays = args.briefDays.filter((day) => {
5766
+ }).from(juniorConversationBriefs), args.briefDays]);
5767
+ const recentDays = briefDays.filter((day) => {
5764
5768
  const dayStart = Date.parse(`${day.date}T00:00:00.000Z`);
5765
5769
  return dayStart >= windowStart.getTime() && dayStart < windowEnd.getTime();
5766
5770
  });
@@ -5781,7 +5785,7 @@ async function buildBriefsOperationalReport(args) {
5781
5785
  },
5782
5786
  {
5783
5787
  label: "briefs · 30d",
5784
- value: formatCount(recentCounts[0]?.stored ?? 0)
5788
+ value: formatCount(counts?.recent ?? 0)
5785
5789
  },
5786
5790
  {
5787
5791
  label: "cost · 30d · retained",
@@ -5793,7 +5797,7 @@ async function buildBriefsOperationalReport(args) {
5793
5797
  }
5794
5798
  ],
5795
5799
  widgets: [{
5796
- categories: args.briefDays.map((day) => ({
5800
+ categories: briefDays.map((day) => ({
5797
5801
  id: day.date,
5798
5802
  label: day.date,
5799
5803
  values: {
@@ -6048,7 +6052,7 @@ const briefsTaskRegistration = {
6048
6052
  conversationEvents: [briefUpdatedEventV1, briefUpdatedEvent],
6049
6053
  hooks: { async operationalReport(context) {
6050
6054
  return await buildBriefsOperationalReport({
6051
- briefDays: await context.eventStats.costsByDay({
6055
+ briefDays: context.eventStats.costsByDay({
6052
6056
  days: 90,
6053
6057
  eventName: "brief_updated"
6054
6058
  }),
@@ -7194,11 +7198,10 @@ async function pruneNetworks() {
7194
7198
  const containers = await listSandboxResources("containers");
7195
7199
  const used = new Set(containers.map((container) => container.Labels[DOCKER_SANDBOX_LABEL]));
7196
7200
  const networks = await listSandboxResources("networks");
7197
- const limit = pLimit(8);
7198
- await Promise.all(networks.filter((network) => !used.has(network.Labels[DOCKER_SANDBOX_LABEL])).map((network) => limit(async () => {
7201
+ await mapBounded(networks.filter((network) => !used.has(network.Labels[DOCKER_SANDBOX_LABEL])), async (network) => {
7199
7202
  await forceRemove(egressRelayName(network.Name));
7200
7203
  await removeNetwork(network.Name);
7201
- })));
7204
+ });
7202
7205
  }
7203
7206
  async function createNetwork(name, signal) {
7204
7207
  await pruneNetworks();
@@ -7938,7 +7941,7 @@ async function resolveSandboxCommandEnvironment() {
7938
7941
  }
7939
7942
  // src/chat/sandbox/egress/credential-request.ts
7940
7943
  const CREDENTIAL_HEADERS = ["authorization", "cookie"];
7941
- const BROWSER_HEADER = "sec-fetch-mode";
7944
+ const BROWSER_HEADER = "sec-fetch-site";
7942
7945
  function placeholders(manifest) {
7943
7946
  return [HOST_MANAGED_CREDENTIAL_PLACEHOLDER, ...manifest.credentials ? [resolveAuthTokenPlaceholder(manifest.credentials)] : []];
7944
7947
  }
@@ -9261,7 +9264,6 @@ async function deleteSnapshotTag(name) {
9261
9264
  */
9262
9265
  async function deleteWorkspaceSnapshotBuilders$1(names) {
9263
9266
  const failures = [];
9264
- const limit = pLimit(8);
9265
9267
  const removeAll = async (name) => {
9266
9268
  for (const remove of [removeContainer, deleteSnapshotTag]) try {
9267
9269
  await remove(name);
@@ -9269,7 +9271,7 @@ async function deleteWorkspaceSnapshotBuilders$1(names) {
9269
9271
  failures.push(error);
9270
9272
  }
9271
9273
  };
9272
- await Promise.all([...new Set(names)].map((name) => limit(() => removeAll(name))));
9274
+ await mapBounded([...new Set(names)], (name) => removeAll(name));
9273
9275
  if (failures.length > 0) throw failures[0];
9274
9276
  }
9275
9277
  const DOCKER_SNAPSHOT_PACKAGES = /* @__PURE__ */ new Set([
@@ -9980,8 +9982,7 @@ async function getWorkspaceSnapshotBuilder(name, signal) {
9980
9982
  async function deleteWorkspaceSnapshotBuilders(names) {
9981
9983
  let hasError = false;
9982
9984
  let firstError;
9983
- const limit = pLimit(8);
9984
- await Promise.all([...new Set(names)].map((name) => limit(async () => {
9985
+ await mapBounded([...new Set(names)], async (name) => {
9985
9986
  try {
9986
9987
  await (await Sandbox.get({
9987
9988
  name,
@@ -9994,7 +9995,7 @@ async function deleteWorkspaceSnapshotBuilders(names) {
9994
9995
  hasError = true;
9995
9996
  }
9996
9997
  }
9997
- })));
9998
+ });
9998
9999
  if (hasError) throw firstError;
9999
10000
  }
10000
10001
  /** Vercel Sandbox implementation of the sandbox provider contract. */
@@ -10599,7 +10600,7 @@ async function deleteWorkspace(id) {
10599
10600
  // src/chat/plugins/after-tool-hooks.ts
10600
10601
  /** Render a nudge as the marked text the agent reads. */
10601
10602
  function renderToolResultNudge(nudge) {
10602
- return `<plugin-note plugin="${nudge.pluginName}">${escapeXml(nudge.message)}</plugin-note>`;
10603
+ return renderInlineTag("plugin-note", escapeTagTextAndQuotes(nudge.message), { plugin: nudge.pluginName });
10603
10604
  }
10604
10605
  async function activeWorkspace(sandbox) {
10605
10606
  const id = sandbox.workspaceId();
@@ -11336,16 +11337,20 @@ async function collectEventMatchKeys(input) {
11336
11337
  if (eventTypes.size === 0) return [];
11337
11338
  const keys = /* @__PURE__ */ new Set();
11338
11339
  const identifiers = new Set(input.identifiers.map((value) => value.trim()).filter(Boolean));
11339
- for (const identifier of identifiers) {
11340
- const records = await readSubscriptions(state, await readSubscriptionIdIndex(state, resourceIndexKey(input.namespace, identifier)));
11341
- for (const record of records) {
11342
- if (!record) continue;
11343
- if (record.namespace !== input.namespace) continue;
11344
- if (record.identifier !== identifier) continue;
11345
- if (!activeAt(record, nowMs)) continue;
11346
- if (!record.events.some((eventType) => eventTypes.has(eventType))) continue;
11347
- for (const key of Object.keys(record.match ?? {})) keys.add(key);
11348
- }
11340
+ const recordsByIdentifier = await mapBounded(identifiers, async (identifier) => {
11341
+ const ids = await readSubscriptionIdIndex(state, resourceIndexKey(input.namespace, identifier));
11342
+ return {
11343
+ identifier,
11344
+ records: await readSubscriptions(state, ids)
11345
+ };
11346
+ });
11347
+ for (const { identifier, records } of recordsByIdentifier) for (const record of records) {
11348
+ if (!record) continue;
11349
+ if (record.namespace !== input.namespace) continue;
11350
+ if (record.identifier !== identifier) continue;
11351
+ if (!activeAt(record, nowMs)) continue;
11352
+ if (!record.events.some((eventType) => eventTypes.has(eventType))) continue;
11353
+ for (const key of Object.keys(record.match ?? {})) keys.add(key);
11349
11354
  }
11350
11355
  return [...keys].sort();
11351
11356
  }
@@ -11552,26 +11557,26 @@ async function resolveAssignee(db, value, tenant, findMentionedUserId) {
11552
11557
  /** Resolve the assignees of a Review item. One is required. */
11553
11558
  async function resolveAssignees(db, values, tenant, findMentionedUserId) {
11554
11559
  if (values.length === 0) throw new ToolInputError("A review item needs at least one assignee.");
11555
- const resolved = await Promise.all(values.map((value) => resolveAssignee(db, value, tenant, findMentionedUserId)));
11560
+ const resolved = await mapBounded(values, (value) => resolveAssignee(db, value, tenant, findMentionedUserId));
11556
11561
  return {
11557
11562
  everyone: resolved.some((assignee) => "everyone" in assignee),
11558
11563
  userIds: [...new Set(resolved.flatMap((assignee) => "userId" in assignee ? [assignee.userId] : []))]
11559
11564
  };
11560
11565
  }
11561
- async function participantUserIds(db, conversationId, condition) {
11562
- return (await db.select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorConversations, eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(and(eq(juniorConversations.conversationId, conversationId), condition))).map((row) => row.userId);
11566
+ async function participantUserIds(db, conversationIds, condition) {
11567
+ return (await db.select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorConversations, eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), condition))).map((row) => row.userId);
11563
11568
  }
11564
- /** Return which of the Users are Participants of a Conversation. */
11565
- async function conversationParticipantUserIds(db, conversationId, userIds) {
11566
- if (userIds.length === 0) return /* @__PURE__ */ new Set();
11567
- return new Set(await participantUserIds(db, conversationId, inArray(juniorConversationParticipants.userId, [...userIds])));
11569
+ /** Return which of the Users are Participants of any of the Conversations. */
11570
+ async function conversationParticipantUserIds(db, conversationIds, userIds) {
11571
+ if (conversationIds.length === 0 || userIds.length === 0) return /* @__PURE__ */ new Set();
11572
+ return new Set(await participantUserIds(db, conversationIds, inArray(juniorConversationParticipants.userId, [...userIds])));
11568
11573
  }
11569
11574
  /**
11570
11575
  * Return the active Participants of a Conversation: the people who have not
11571
11576
  * unsubscribed from it.
11572
11577
  */
11573
11578
  async function activeParticipantUserIds(db, conversationId) {
11574
- return await participantUserIds(db, conversationId, isNull(juniorConversationParticipants.unsubscribedAt));
11579
+ return await participantUserIds(db, [conversationId], isNull(juniorConversationParticipants.unsubscribedAt));
11575
11580
  }
11576
11581
  /** Return the User who created an Automation, if Junior knows them. */
11577
11582
  async function automationCreatorUserId(db, automationId) {
@@ -11742,9 +11747,7 @@ async function requireReviewItemAssignees(args) {
11742
11747
  if (args.assignees.everyone) throw new ToolInputError("A private item cannot be assigned to Everyone. Assign Users instead.");
11743
11748
  const creatorId = args.automationId ? await automationCreatorUserId(getDb(), args.automationId) : void 0;
11744
11749
  const others = args.assignees.userIds.filter((id) => id !== args.scope.user?.id && id !== creatorId);
11745
- const limit = pLimit(8);
11746
- const participants = await Promise.all([...new Set(args.conversationIds)].map((conversationId) => limit(() => conversationParticipantUserIds(getDb(), conversationId, others))));
11747
- const inConversation = new Set(participants.flatMap((ids) => [...ids]));
11750
+ const inConversation = await conversationParticipantUserIds(getDb(), args.conversationIds, others);
11748
11751
  if (others.some((id) => !inConversation.has(id))) throw new ToolInputError("A private item can be assigned only to people in its Conversation.");
11749
11752
  }
11750
11753
  /**
@@ -12036,11 +12039,18 @@ function reviewItemsNeedingUserVersionQuery(db, userId) {
12036
12039
  * `created_at` and `id`, both descending. `afterWaiting` pages through it.
12037
12040
  */
12038
12041
  async function searchReviewItems(db, reader, filters) {
12039
- return await hydrate(db, await db.select().from(juniorReviewItems).where(and(...searchConditions(reader, filters))).orderBy(desc(eq(juniorReviewItems.status, "open")), ...typeof filters.order === "object" ? [
12042
+ const rows = await db.select({
12043
+ item: juniorReviewItems,
12044
+ addedByRootConversationId: juniorConversations.rootConversationId
12045
+ }).from(juniorReviewItems).leftJoin(juniorConversations, eq(juniorConversations.conversationId, juniorReviewItems.addedByConversationId)).where(and(...searchConditions(reader, filters))).orderBy(desc(eq(juniorReviewItems.status, "open")), ...typeof filters.order === "object" ? [
12040
12046
  desc(reviewItemNeedsUser(filters.order.needsUserId)),
12041
12047
  desc(juniorReviewItems.createdAt),
12042
12048
  desc(juniorReviewItems.id)
12043
- ] : 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));
12049
+ ] : 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);
12050
+ return (await hydrate(db, rows.map((row) => row.item))).map((item, index) => ({
12051
+ ...item,
12052
+ addedByRootConversationId: rows[index].addedByRootConversationId
12053
+ }));
12044
12054
  }
12045
12055
  /**
12046
12056
  * List the root Conversations that wait on a User: each root or one of its
@@ -12082,12 +12092,11 @@ async function listWaitingConversations(db, userId) {
12082
12092
  * User and a User who is not in the Conversation.
12083
12093
  */
12084
12094
  async function assigneeUserIds(db, identityIds, conversationId) {
12085
- const limit = pLimit(8);
12086
- return (await Promise.all([...new Set(identityIds)].map((identityId) => limit(async () => {
12095
+ return (await mapBounded([...new Set(identityIds)], async (identityId) => {
12087
12096
  const user = (await readIdentityByIdFromSql(db, identityId))?.user;
12088
12097
  if (!user) return [];
12089
12098
  return (await readConversationAccessFromSql(db, [conversationId], user)).get(conversationId)?.isParticipant ? [user.id] : [];
12090
- })))).flat();
12099
+ })).flat();
12091
12100
  }
12092
12101
  /**
12093
12102
  * Connect a plugin to the review desk for one Conversation. Dedupe keys are
@@ -12416,7 +12425,7 @@ async function sendToDevice(subscription, body, config) {
12416
12425
  async function sendPushNotificationToUser(args) {
12417
12426
  const subscriptions = await listPushSubscriptions(args.db, args.userId);
12418
12427
  const body = JSON.stringify(args.payload);
12419
- const outcomes = await Promise.all(subscriptions.map((subscription) => sendToDevice(subscription, body, args.config)));
12428
+ const outcomes = await mapBounded(subscriptions, (subscription) => sendToDevice(subscription, body, args.config));
12420
12429
  const gone = subscriptions.filter((_, index) => outcomes[index] === "gone").map((subscription) => subscription.id);
12421
12430
  await deletePushSubscriptionsById(args.db, gone);
12422
12431
  const result = {
@@ -12569,7 +12578,7 @@ const REQUEST_CONTEXT_SECTION_TAG = {
12569
12578
  turnInput: "turn-input"
12570
12579
  };
12571
12580
  /** Starts of user text parts that hold runtime context, not a person's words. */
12572
- const RUNTIME_CONTEXT_TEXT_STARTS = [`<${TURN_CONTEXT_TAG}>`, "# AGENTS.md instructions"];
12581
+ const RUNTIME_CONTEXT_TEXT_STARTS = [openingTag(TURN_CONTEXT_TAG), "# AGENTS.md instructions"];
12573
12582
  function isRecord$1(value) {
12574
12583
  return typeof value === "object" && value !== null;
12575
12584
  }
@@ -12597,7 +12606,7 @@ function isRuntimeTurnContextPart(part) {
12597
12606
  function hasTurnInput(message) {
12598
12607
  return userMessageContent(message)?.some((part) => {
12599
12608
  const text = textPartValue(part);
12600
- return text !== void 0 && (text.includes("<current-instruction") || isRuntimeInputText(text));
12609
+ return text !== void 0 && (hasCurrentInstruction(text) || isRuntimeInputText(text));
12601
12610
  }) ?? false;
12602
12611
  }
12603
12612
  /** Return whether the message is a Turn's context, paired with the instruction after it. */
@@ -12606,13 +12615,6 @@ function isStandaloneRuntimeContextMessage(messages, index) {
12606
12615
  const next = messages[index + 1];
12607
12616
  return Boolean(message && next && userMessageContent(message) && userMessageContent(next) && message.timestamp === next.timestamp && !hasTurnInput(message) && hasTurnInput(next));
12608
12617
  }
12609
- const EMBEDDED_THREAD_CONTEXT_PATTERN = new RegExp(`<(${[
12610
- "thread-context",
12611
- "recent-thread-messages",
12612
- "thread-compactions",
12613
- "thread-transcript",
12614
- "thread-background"
12615
- ].join("|")})(?:\\s[^>]*)?>[\\s\\S]*</\\1>`, "g");
12616
12618
  /** Type guard for Pi SDK assistant messages. */
12617
12619
  function isAssistantMessage(value) {
12618
12620
  return isRecord$1(value) && value["role"] === "assistant";
@@ -12689,7 +12691,7 @@ function retainRuntimeTurnContext(messages) {
12689
12691
  * a live run.
12690
12692
  */
12691
12693
  function instructionTextForProjection(text) {
12692
- const withoutContext = text.replace(EMBEDDED_THREAD_CONTEXT_PATTERN, "").trim();
12694
+ const withoutContext = stripTags(text, THREAD_CONTEXT_TAGS).trim();
12693
12695
  return unwrapCurrentInstruction(withoutContext) ?? withoutContext;
12694
12696
  }
12695
12697
  /**
@@ -12703,7 +12705,7 @@ function getUserMessageInstructionText(message) {
12703
12705
  if (message.role !== "user") return "";
12704
12706
  const texts = typeof message.content === "string" ? [message.content] : message.content.flatMap((part) => textPartValue(part) ?? []);
12705
12707
  const inputs = texts.flatMap((text) => {
12706
- const withoutContext = text.replace(EMBEDDED_THREAD_CONTEXT_PATTERN, "").trim();
12708
+ const withoutContext = stripTags(text, THREAD_CONTEXT_TAGS).trim();
12707
12709
  if (isRuntimeInputText(withoutContext)) return [readParentAgentTask(withoutContext) ?? withoutContext];
12708
12710
  const instruction = unwrapCurrentInstruction(withoutContext);
12709
12711
  return instruction === void 0 ? [] : [instruction.trim()];
@@ -17932,8 +17934,6 @@ function getConversationContextCompactionTriggerTokens() {
17932
17934
  const CONTEXT_MIN_LIVE_MESSAGES = 12;
17933
17935
  const CONTEXT_MAX_MESSAGE_CHARS = 3200;
17934
17936
  const THREAD_CONTEXT_MAX_CHARS = 6e4;
17935
- const THREAD_CONTEXT_OPEN = "<thread-context authority=\"evidence-only\">";
17936
- const THREAD_CONTEXT_CLOSE = "</thread-context>";
17937
17937
  const THREAD_CONTEXT_OMITTED_NOTE = "Older Messages of this thread are not shown. Find them with a searchConversationEvents query, then read them with readConversationEvent.";
17938
17938
  const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
17939
17939
  /** Normalize message boundaries without changing transcript formatting. */
@@ -17946,13 +17946,13 @@ function buildImageContextSuffix(message, conversation) {
17946
17946
  if (!byFileId || imageFileIds.length === 0) return "";
17947
17947
  const summaries = imageFileIds.map((fileId) => byFileId[fileId]?.summary?.trim()).filter((summary) => Boolean(summary));
17948
17948
  if (summaries.length === 0) return "";
17949
- return ` [image context: ${escapeXml(summaries.join(" | "))}]`;
17949
+ return ` [image context: ${escapeTagTextAndQuotes(summaries.join(" | "))}]`;
17950
17950
  }
17951
17951
  function renderConversationMessageLine(message, conversation) {
17952
- const displayName = escapeXml(conversationAuthorDisplayName(message));
17953
- const text = escapeXml(message.text.replace(/\s+/g, " ").slice(0, CONTEXT_MAX_MESSAGE_CHARS));
17952
+ const displayName = escapeTagTextAndQuotes(conversationAuthorDisplayName(message));
17953
+ const text = escapeTagTextAndQuotes(message.text.replace(/\s+/g, " ").slice(0, CONTEXT_MAX_MESSAGE_CHARS));
17954
17954
  const markers = [];
17955
- if (message.meta?.replied === false) markers.push(escapeXml(`assistant skipped: ${message.meta?.skippedReason ?? "no-reply route"}`));
17955
+ if (message.meta?.replied === false) markers.push(escapeTagTextAndQuotes(`assistant skipped: ${message.meta?.skippedReason ?? "no-reply route"}`));
17956
17956
  if (message.meta?.explicitMention) markers.push("explicit mention");
17957
17957
  const markerSuffix = markers.length > 0 ? ` (${markers.join("; ")})` : "";
17958
17958
  const imageContext = buildImageContextSuffix(message, conversation);
@@ -18038,20 +18038,16 @@ function isTakeOrDismissOnly(message) {
18038
18038
  return Boolean(changes?.length && changes.every((change) => change.kind === "taken" || change.kind === "dismissed"));
18039
18039
  }
18040
18040
  function renderThreadContextMessage(message, conversation, index) {
18041
- return [
18042
- ` ${openingTag("message", {
18043
- index,
18044
- ts: new Date(message.createdAtMs).toISOString(),
18045
- role: message.role,
18046
- ...authorAttrs({
18047
- authorId: message.author?.userId,
18048
- authorName: conversationAuthorDisplayName(message)
18049
- }),
18050
- slack_ts: message.meta?.slackTs
18051
- })}`,
18052
- renderConversationMessageLine(message, conversation),
18053
- " </message>"
18054
- ].join("\n");
18041
+ return indentTagLines(renderTag("message", {
18042
+ index,
18043
+ ts: new Date(message.createdAtMs).toISOString(),
18044
+ role: message.role,
18045
+ ...authorAttrs({
18046
+ authorId: message.author?.userId,
18047
+ authorName: conversationAuthorDisplayName(message)
18048
+ }),
18049
+ slack_ts: message.meta?.slackTs
18050
+ }, [renderConversationMessageLine(message, conversation)]), " ");
18055
18051
  }
18056
18052
  function isUntaggedThreadMessage(message) {
18057
18053
  return message.role === "user" && !message.meta?.explicitMention && !isEventConversationMessage(message);
@@ -18088,11 +18084,7 @@ function buildConversationContext(conversation, options = {}) {
18088
18084
  omittedMessages: candidates.length - shown.length
18089
18085
  };
18090
18086
  if (shown.length === 0) return counts;
18091
- const lines = [
18092
- THREAD_CONTEXT_OPEN,
18093
- ...shown,
18094
- THREAD_CONTEXT_CLOSE
18095
- ];
18087
+ const lines = [renderThreadContext(shown)];
18096
18088
  if (shown.length < candidates.length || !history && conversation.historyFromSeq !== void 0) lines.push(THREAD_CONTEXT_OMITTED_NOTE);
18097
18089
  return {
18098
18090
  ...counts,
@@ -18705,13 +18697,13 @@ async function recordAuthorizationCompleted(args) {
18705
18697
  isSameFact: (data) => data.type === "authorization_completed" && data.authorizationId === args.authorizationId
18706
18698
  });
18707
18699
  }
18708
- function authenticationEventIdempotencyKey(args) {
18709
- if (args.authorizationId) return `native:${JUNIOR_NATIVE_EVENT_NAMESPACE}:authentication_${args.action}:authorization:${args.authorizationId}`;
18710
- return `native:${JUNIOR_NATIVE_EVENT_NAMESPACE}:authentication_${args.action}:${args.provider}:actor:${args.actorId}`;
18700
+ function authenticationLinkedIdempotencyKey(args) {
18701
+ if (args.authorizationId) return `native:${JUNIOR_NATIVE_EVENT_NAMESPACE}:authentication_linked:authorization:${args.authorizationId}`;
18702
+ return `native:${JUNIOR_NATIVE_EVENT_NAMESPACE}:authentication_linked:${args.provider}:actor:${args.actorId}`;
18711
18703
  }
18712
- async function recordAuthenticationAccountChange(action, args) {
18713
- const definition = action === "linked" ? authenticationLinkedEvent : authenticationUnlinkedEvent;
18714
- const content = definition.parse({
18704
+ /** Record a successful conversation-bound account link as host transcript metadata. */
18705
+ async function recordAuthenticationLinked(args) {
18706
+ const content = authenticationLinkedEvent.parse({
18715
18707
  actorId: args.actorId,
18716
18708
  provider: args.provider,
18717
18709
  ...args.accountLabel ? { accountLabel: args.accountLabel } : void 0,
@@ -18720,26 +18712,17 @@ async function recordAuthenticationAccountChange(action, args) {
18720
18712
  });
18721
18713
  await getConversationEventStore().append(args.conversationId, [{
18722
18714
  createdAtMs: Date.now(),
18723
- idempotencyKey: authenticationEventIdempotencyKey({
18724
- action,
18725
- actorId: args.actorId,
18726
- authorizationId: args.authorizationId,
18727
- provider: args.provider
18728
- }),
18715
+ idempotencyKey: authenticationLinkedIdempotencyKey(args),
18729
18716
  data: {
18730
18717
  type: "structured_event",
18731
18718
  namespace: JUNIOR_NATIVE_EVENT_NAMESPACE,
18732
- name: definition.eventName,
18733
- version: definition.version,
18719
+ name: authenticationLinkedEvent.eventName,
18720
+ version: authenticationLinkedEvent.version,
18734
18721
  ...args.turnId ? { turnId: args.turnId } : void 0,
18735
18722
  content
18736
18723
  }
18737
18724
  }]);
18738
18725
  }
18739
- /** Record a successful conversation-bound account link as host transcript metadata. */
18740
- async function recordAuthenticationLinked(args) {
18741
- await recordAuthenticationAccountChange("linked", args);
18742
- }
18743
18726
  async function loadAgentsEvent(conversationId) {
18744
18727
  const event = await getConversationEventStore().loadLatestStructuredEvent(conversationId, JUNIOR_NATIVE_EVENT_NAMESPACE, agentsInstructionsUpdatedEvent.eventName);
18745
18728
  if (!event || event.data.type !== "structured_event") return void 0;
@@ -18860,4 +18843,4 @@ async function recordGuardianActionReviewed(args) {
18860
18843
  createdAtMs: Date.now()
18861
18844
  }]);
18862
18845
  }
18863
- export { pauseLostWorkerTurn as $, viewerMarksFromParticipant as $a, readAutomationExecutions as $c, proxyVercelSandboxEgressRequest as $i, getTerminalAssistantMessages as $n, listPendingDispatchMailboxAppends as $o, reviewItemReaderForUser as $r, withScheduledAutomationLock as $s, buildTurnErrorResponse as $t, normalizeConversationText as A, SANDBOX_COMMAND_PATH as Aa, hasEventCatalogEntries as Ac, verifySlackDirectCredentialSubject as Ai, getPluginSystemPromptContributions as An, createConversationEmbedder as Ao, countOpenReviewItemsForUser as Ar, streamPrivateSlackFile as As, hasRunnableConversationWork as At, PluginCredentialFailureError as B, buildNonInteractiveShellScript as Ba, readAutomationVersion as Bc, updateWorkspace as Bi, registration_exports as Bn, lookupSlackUserNames as Bo, takeReviewItem as Br, slackMention as Bs, releaseInboundMessage as Bt, settleConversationTitleWork as C, normalizeSandboxEgressTracePropagationDomains as Ca, CORE_EVENT_NAMESPACE as Cc, takeDueTimerWatches as Ci, agent_hooks_exports as Cn, storeAttachment as Co, saveNotificationSchedule as Cr, getHeaderString as Cs, deferConversationMove as Ct, isHumanConversationMessage as D, PluginToolDeniedError as Da, eventGuidance as Dc, bindSlackDirectCredentialSubject as Di, getPluginApiRoutes as Dn, resolveRootVisibility as Do, createPluginReviewItems as Dr, isSlackRequestTimeout as Ds, getConversationWorkState as Dt, getConversationMessageSlackTs as E, workspaceRepoCheckoutPath as Ea, eventCatalogEntry as Ec, bindScheduledAutomationCredentialSubject as Ei, createPluginHookRunner as En, AttachmentSourceUnavailableError as Eo, projectConversationMessages as Er, isDmChannel as Es, getConversation as Et, calculateContextCompactionTargetTokens as F, SANDBOX_WORKSPACE_ROOT as Fa, requireEventIdentifier as Fc, deleteWorkspace as Fi, setPlugins as Fn, listConversationAnnotationsById as Fo, insertReviewItem as Fr, SLACK_USER_MENTION_RE as Fs, moveIdleConversationDestination as Ft, AuthorizationPauseError as G, canAddConversationMessages as Ga, ToolInputError as Gc, setWorkspaceSnapshotBuild as Gi, seqIn as Gn, createOrGetDispatch as Go, canReadReviewItem as Gr, createScheduledAutomation as Gs, stopConversationWork as Gt, authorizationId as H, createPluginModelCostRecorder as Ha, AutomationConflictError as Hc, invalidateReadySnapshot as Hi, setEventEmbeddingsConfig as Hn, buildDispatchId as Ho, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Hr, wrapBareSlackUserIds as Hs, requestConversationWork as Ht, getAgentBackgroundCompactionMarkTokens as I, sandboxSkillDir as Ia, requireValidEventTrigger as Ic, getWorkspace as Ii, validatePlugins as In, defaultTimezone as Io, listReplyActionItems as Ir, escapeSlackMrkdwnText as Is, pruneActiveConversation as It, clearPendingAuth as J, conversationHasParticipantUser as Ja, existingConversationId as Jc, isStale as Ji, eventExcerpt as Jn, getDispatchInputMessageId as Jo, itemNeedsUser as Jr, parseScheduledAutomationRow as Js, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Jt, abandonReplacedPendingAuth as K, createConversationAccessReader as Ka, isToolInputError as Kc, create as Ki, SEARCHABLE_EVENT_TYPES as Kn, getDispatchConversationId as Ko, canUserReadReviewItem as Kr, deleteScheduledAutomation as Ks, takeDeferredConversationMove as Kt, getAgentContextCompactionTriggerTokens as L, sandboxSkillFile as La, automationDefinition as Lc, getWorkspaceByName as Li, coreTaskRegistrations as Ln, findActorTimezone as Lo, listWaitingConversations as Lr, formatSlackLink as Ls, recordAttemptFailure as Lt, trimConversationMessages as M, SANDBOX_REPOS_ROOT as Ma, registeredEventTriggerProblems as Mc, createPluginState as Mi, getPluginUserPromptContributions as Mn, saveObjectAnnotations as Mo, dismissOpenReviewItems as Mr, sleep$2 as Ms, isInvalidConversationRecordError as Mt, turnHasReply as N, SANDBOX_SCRATCH_ROOT as Na, registeredEventTypeSchema as Nc, renderToolResultNudge as Ni, getPlugins as Nn, createPluginAnnotations as No, getOpenReviewItemByDedupeKey as Nr, getWorkspaceTeamId as Ns, listActiveConversationIds as Nt, latestConversationMessageSeq as O, createPluginEmbedder as Oa, eventNamespaceSchema as Oc, verifyEventAutomationCredentialSubject as Oi, getPluginRoutes as On, searchConversations as Oo, REVIEW_ITEM_REPLIED_REASON as Or, normalizeSlackConversationId as Os, getConversationWorkStates as Ot, upsertConversationMessage as P, SANDBOX_SKILLS_ROOT as Pa, registeredResourceTypeSchema as Pc, createWorkspace as Pi, getStaticPluginToolDefinitions as Pn, listConversationAnnotations as Po, getReviewItem as Pr, runWithWorkspaceTeamId as Ps, markConversationWorkEnqueued as Pt, lostWorkerBeforeFirstSave as Q, conversationViewerMarks as Qa, readAutomationExecutionSummaries as Qc, isVercelSandboxEgressRequest as Qi, getPiMessageRole as Qn, isTerminalDispatchStatus as Qo, reviewItemNeedsSomeone as Qr, scheduledRunId as Qs, TurnToolCallLimitExceededError as Qt, getAgentContextInputLimitTokens as R, sandboxSkillPathResolution as Ra, automationVersionOf as Rc, listWorkspaces as Ri, isBriefsEnabled as Rn, resolveUserTimezone as Ro, reviewItemsNeedingUserVersionQuery as Rr, normalizeSlackReplyMarkdown as Rs, recordConversationRetry as Rt, resolveConversationTitle as S, resolveSandboxCommandEnvironment as Sa, eventAutomationRunLimitReason as Sc, listWatches as Si, resolvePluginOAuthAccount as Sn, requestAttachmentDeletion as So, readNotificationSchedule as Sr, getFilePermalink as Ss, deadLetterAttempt as St, estimateConversationMessagesTokens as T, tryWorkspaceRepoCheckoutPath as Ta, describeRegisteredEventTrigger as Tc, bindEventAutomationCredentialSubject as Ti, createPluginEventPublisher as Tn, storeDeferredAttachment as To, isPausedBySlack as Tr, isConversationScopedChannel as Ts, dropPendingMessages as Tt, AuthPausePersistenceError as U, createPluginLogger as Ua, automationRevision as Uc, loadSnapshotsForProfile as Ui, lexemesSql as Un, claimDispatchMailboxAppend as Uo, canActOnReviewItem as Ur, truncateStatusText as Us, startConversationWork as Ut, createPluginAuthOrchestration as V, runNonInteractiveCommand as Va, sameDefinitionValue as Vc, WorkspaceValidationError as Vi, setBriefsConfig as Vn, readConversationAutomationRun as Vo, updateReviewItemContent as Vr, slackMentionedUserIds as Vs, requestAnotherSlice as Vt, AuthorizationFlowDisabledError as W, canAccessConversation as Wa, requireAutomationRevision as Wc, setWorkspaceSnapshot as Wi, searchedEventTextSql as Wn, confirmDispatchMailboxAppend as Wo, canAgentChangeReviewItem as Wr, blockScheduledAutomation as Ws, steerWebPendingMessages as Wt, continuableMessages as X, conversationIsNotUnsubscribedRoot as Xa, readAutomationExecutionStatusDays as Xc, getSandboxProvider as Xi, storedMessageJson as Xn, getDispatchTurnId as Xo, requireReviewItemAssignees as Xr, saveScheduledAutomation as Xs, TurnBudgetExceededError as Xt, getConversationPendingAuth as Y, conversationIsMemberRoot as Ya, readAutomationExecutionByConversationId as Yc, ensureDockerDaemon as Yi, excerptTerms as Yn, getDispatchRecord as Yo, readReviewItemAgentScope as Yr, readScheduledAutomation as Ys, TURN_LIMIT_WRAP_UP_MESSAGE as Yt, loadTurnCheckpoint as Z, conversationPinnedForUser as Za, readAutomationExecutionStatusHours as Zc, isRetryableSandboxFailure as Zi, extractAssistantText as Zn, getPluginDispatchProjection as Zo, requireReviewItemLinks as Zr, saveScheduledAutomationInLock as Zs, TurnSliceLimitExceededError as Zt, appendConversationMessages as _, consumeSandboxEgressPermissionDeniedSignal as _a, listDeletedEventAutomationsCreatedBy as _c, createWatch as _i, setConfigDefaults as _l, readBlockedReport as _n, slackAttachmentsVersionQuery as _o, readWebPushConfig as _r, fitsSlackMetadataLimit as _s, clearConsumedConversationWake as _t, loadProjection as a, SandboxCallTimeoutError as aa, getDashboardSettingsLink as ac, resolveAssignees as ai, fallbackShortTitle as al, remindMissingAnswer as an, readConversationEventPageAround as ao, isContinuablePiBoundary as ar, notifyAutomationBlocked as as, getTurnRecord as at, persistConversationMessages as b, sandboxEgressSignalsResponseSchema as ba, setEventAutomationStatus as bc, getWatch as bi, createUserTokenStore as bn, readLiveAttachment as bo, deletePushSubscription as br, SlackActionError as bs, completeConversationWork as bt, recordAgentsInstructionsUpdated as c, isAlreadyExistsError as ca, parseDashboardConversationLink as cc, getSlackToolContext as ci, credentialAuditAttributes as cl, getAssistantReplyText as cn, buildSentryConversationUrl as co, isToolResultMessage as cr, getSlackMessagePermalink as cs, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as ct, recordAuthorizationCompleted as d, WorkspaceSnapshotNotReadyError as da, blockEventAutomation as dc, RESOURCE_WATCH_TOOL_SOURCE as di, createDurableLocationConfigurationService as dl, findLegacyNoReplyMarker as dn, notInheritedByForkChild as do, stripRuntimeTurnContext as dr, postSlackEphemeralMessage as ds, appendExclusiveInboundMessage as dt, deliverOAuthAuthorization as ea, getDashboardConversationLink as ec, reviewItemReaderForUserInConversation as ei, readAutomationRowStats as el, createTurnLimitGate as en, createPluginConversationEvents as eo, getUserMessageInstructionText as er, markDispatchAwaitingResume as es, saveTurnCheckpoint as et, recordAuthorizationRequested as f, getWorkspaceSnapshotNotReadyError as fa, collectEventAutomationMatchKeys as fc, STOP_WATCHING_TOOL_NAME as fi, configValueSchema as fl, isLegacyNoReplyMarker as fn, getSlackFileId as fo, trimTrailingAssistantMessages as fr, postSlackMessage as fs, appendInboundMessage as ft, recordToolExecutionStarted as g, consumeSandboxEgressAuthRequiredSignal as ga, getEventAutomation as gc, createTimerWatch as gi, getConfigDefaults as gl, REPORT_BLOCKED_TOOL_NAME as gn, recordSlackAttachment as go, TURN_CONTEXT_TAG as gr, uploadFilesToConversation as gs, claimInboundMessage as gt, recordSubscribedReplyRoute as h, clearSandboxEgressSignals as ha, findMatchingEventAutomations as hc, collectEventMatchKeys as hi, projectConversationEvents$1 as hl, CODE_MODE_CALL_STATUS_TEXT as hn, readSlackAttachmentSource as ho, SESSION_CONTEXT_SECTION_TAG as hr, updateSlackMessage as hs, checkInConversationWork as ht, loadConversationProjection as i, startOAuthFlow as ia, getDashboardReviewItemLink as ic, resolveAssignee as ii, refreshAutomationLastRun as il, readTurnAnswer as in, readConversationEventPageAfter as io, isAssistantMessage as ir, markDispatchRunning as is, getStoredTurnFields as it, recordDeliveredAssistantMessage as j, SANDBOX_DATA_ROOT as ja, registeredEventMatchSchema as jc, verifyTimerWatchCredentialSubject as ji, getPluginTools as jn, embedConversationQuery as jo, countReviewItemsNeedingUserBySubject as jr, withSlackRetries as js, isFinalAttempt as jt, markConversationMessage as k, createPluginModel as ka, eventWatchUnavailable as kc, verifyScheduledAutomationCredentialSubject as ki, getPluginSlackConversationLink as kn, backfillConversationEmbeddings as ko, closeReviewItem as kr, runWithSlackInstallationToken as ks, hasConversationStop as kt, recordAttachmentsDelivered as l, throwSandboxOperationError as la, parseDashboardPersonLink as lc, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as li, credentialAuditSource as ll, sanitizeAssistantText as ln, FORK_INSTRUCTIONS as lo, normalizeToolNameFromResult as lr, openSlackDirectMessage as ls, CONVERSATION_WORK_STALE_ENQUEUE_MS as lt, recordMcpProviderConnected as m, workspaceSnapshotNotReadyUserMessage as ma, deleteEventAutomation as mc, cancelWatch as mi, piMessageFromHistoryItem as ml, CODEMODE_TOOL_NAME as mn, readAttachmentVisionSummary as mo, REQUEST_CONTEXT_SECTION_TAG as mr, unfurlSlackLinks as ms, cancelHumanFacingPendingMessages as mt, commitMessages as n, parseOAuthStatePayload as na, getDashboardObjectIconLink as nc, activeParticipantUserIds as ni, readAutomationTitlesByConversationId as nl, REPLY_TOOL_NAME as nn, readLatestConversationBrief as no, hasTurnInput as nr, markDispatchCompleted as ns, completeTurnRecord as nt, loadTurnProjection as o, findInErrorChain as oa, getDashboardTaskLink as oc, createCodeChangePublisher as oi, resolveTaskTitle as ol, replyTextSchema as on, readConversationLastEventSeq as oo, isStandaloneRuntimeContextMessage as or, addReactionToMessage as os, listTurnSummaries as ot, recordGuardianActionReviewed as p, isWorkspaceSnapshotNotReadyError as pa, createEventAutomation as pc, cancelSubscriptions as pi, historyItemFromPiMessage as pl, readNoReply as pn, matchSlackAttachments as po, CAPABILITY_SECTION_TAG as pr, removeReactionFromMessage as ps, beginConversationResume as pt, canReusePendingAuthLink as q, readConversationAccessFromSql as qa, emptyAutomationRunWindows as qc, hash as qi, callsToolSql as qn, getDispatchIdForConversation as qo, isOnlyAssignee as qr, listScheduledAutomationsForTeam as qs, readInboundMessageSender as qt, loadConnectedMcpProviders as r, resolveBaseUrl as ra, getDashboardPersonLink as rc, automationCreatorUserId as ri, recordAutomationExecution as rl, isAnswerToolName as rn, readConversationEventPage as ro, instructionTextForProjection as rr, markDispatchFailed as rs, failTurnRecord as rt, openConversationProjection as s, isAbortError as sa, isDashboardLink as sc, resolveChannelCapabilities as si, JUNIOR_THREAD_STATE_TTL_MS as sl, decideReply as sn, readConversationMessageEventSeq as so, isToolResultError as sr, deleteSlackMessage as ss, recordTurnSummary as st, commitAcceptedReply as t, formatProviderLabel as ta, getDashboardLinkFilter as tc, EVERYONE_ASSIGNEE as ti, readAutomationRuns as tl, isTurnExecutionLimitExceededError as tn, readConversationBriefThrough as to, hasRuntimeTurnContext as tr, markDispatchBlocked as ts, abandonTurnRecord as tt, recordAuthenticationLinked as u, wrapSandboxSetupError as ua, setDashboardConversationLinkOptions as uc, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as ui, createPluginCache as ul, NO_REPLY_TOOL_NAME as un, loadForkHistory as uo, retainRuntimeTurnContext as ur, openSlackModal as us, ackMessages as ut, hydrateConversationMessages as v, createSandboxEgressCredentialToken as va, parseEventAutomationRow as vc, deliverWatch as vi, persistWithRetry as vn, collectAttachmentGarbage as vo, sendPushNotificationToUser as vr, slackEntitySchema as vs, clearExpiredConversationLease as vt, buildConversationContext as w, SANDBOX_RUNTIME as wa, automationEventCatalog as wc, turnEvents as wi, applyPluginFormatMarkdown as wn, storeAttachments as wo, savePushSubscription as wr, getSlackClient as ws, drainConversationMailbox as wt, toStoredConversationMessage as x, buildSandboxEgressNetworkPolicy as xa, admitEventAutomationRun as xc, isQuietEvent as xi, getOAuthAccountProviders as xn, recordUploadedAttachment as xo, listPushSubscriptions as xr, downloadPrivateSlackFile as xs, countPendingConversationMessages as xt, persistConversationMessageWindow as y, parseSandboxEgressCredentialToken as ya, saveEventAutomation as yc, findMatchingWatches as yi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as yn, isFileAttachment as yo, resolveNotificationTimezone as yr, slackExternalRefIdSchema as ys, completeConversationStop as yt, createPluginEgress as z, buildCommandScript as za, listAutomationVersions as zc, listWorkspacesByRepository as zi, isEventEmbeddingsEnabled as zn, lookupSlackUser as zo, searchReviewItems as zr, normalizeSlackStatusText as zs, releaseConversationWork as zt };
18846
+ export { pauseLostWorkerTurn as $, conversationViewerMarks as $a, readAutomationExecutionStatusHours as $c, isVercelSandboxEgressRequest as $i, getTerminalAssistantMessages as $n, isTerminalDispatchStatus as $o, reviewItemReaderForUser as $r, saveScheduledAutomationInLock as $s, buildTurnErrorResponse as $t, normalizeConversationText as A, createPluginModel as Aa, eventNamespaceSchema as Ac, verifyScheduledAutomationCredentialSubject as Ai, getPluginSystemPromptContributions as An, backfillConversationEmbeddings as Ao, countOpenReviewItemsForUser as Ar, runWithSlackInstallationToken as As, hasRunnableConversationWork as At, PluginCredentialFailureError as B, buildCommandScript as Ba, automationVersionOf as Bc, listWorkspacesByRepository as Bi, registration_exports as Bn, lookupSlackUser as Bo, takeReviewItem as Br, normalizeSlackReplyMarkdown as Bs, releaseInboundMessage as Bt, settleConversationTitleWork as C, resolveSandboxCommandEnvironment as Ca, admitEventAutomationRun as Cc, listWatches as Ci, agent_hooks_exports as Cn, requestAttachmentDeletion as Co, saveNotificationSchedule as Cr, getFilePermalink as Cs, deferConversationMove as Ct, isHumanConversationMessage as D, workspaceRepoCheckoutPath as Da, describeRegisteredEventTrigger as Dc, bindScheduledAutomationCredentialSubject as Di, getPluginApiRoutes as Dn, AttachmentSourceUnavailableError as Do, createPluginReviewItems as Dr, isDmChannel as Ds, getConversationWorkState as Dt, getConversationMessageSlackTs as E, tryWorkspaceRepoCheckoutPath as Ea, automationEventCatalog as Ec, bindEventAutomationCredentialSubject as Ei, createPluginHookRunner as En, storeDeferredAttachment as Eo, projectConversationMessages as Er, isConversationScopedChannel as Es, getConversation as Et, calculateContextCompactionTargetTokens as F, SANDBOX_SKILLS_ROOT as Fa, registeredEventTypeSchema as Fc, createWorkspace as Fi, setPlugins as Fn, listConversationAnnotations as Fo, insertReviewItem as Fr, runWithWorkspaceTeamId as Fs, moveIdleConversationDestination as Ft, AuthorizationPauseError as G, canAccessConversation as Ga, automationRevision as Gc, setWorkspaceSnapshot as Gi, seqIn as Gn, confirmDispatchMailboxAppend as Go, canReadReviewItem as Gr, truncateStatusText as Gs, stopConversationWork as Gt, authorizationId as H, runNonInteractiveCommand as Ha, readAutomationVersion as Hc, WorkspaceValidationError as Hi, setEventEmbeddingsConfig as Hn, readConversationAutomationRun as Ho, PLUGIN_REVIEW_ITEM_KEY_PREFIX as Hr, slackMention as Hs, requestConversationWork as Ht, getAgentBackgroundCompactionMarkTokens as I, SANDBOX_WORKSPACE_ROOT as Ia, registeredResourceTypeSchema as Ic, deleteWorkspace as Ii, validatePlugins as In, listConversationAnnotationsById as Io, listReplyActionItems as Ir, SLACK_USER_MENTION_RE as Is, pruneActiveConversation as It, clearPendingAuth as J, readConversationAccessFromSql as Ja, isToolInputError as Jc, hash as Ji, eventExcerpt as Jn, getDispatchIdForConversation as Jo, itemNeedsUser as Jr, deleteScheduledAutomation as Js, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Jt, abandonReplacedPendingAuth as K, canAddConversationMessages as Ka, requireAutomationRevision as Kc, setWorkspaceSnapshotBuild as Ki, SEARCHABLE_EVENT_TYPES as Kn, createOrGetDispatch as Ko, canUserReadReviewItem as Kr, blockScheduledAutomation as Ks, takeDeferredConversationMove as Kt, getAgentContextCompactionTriggerTokens as L, sandboxSkillDir as La, requireEventIdentifier as Lc, getWorkspace as Li, coreTaskRegistrations as Ln, defaultTimezone as Lo, listWaitingConversations as Lr, escapeSlackMrkdwnText as Ls, recordAttemptFailure as Lt, trimConversationMessages as M, SANDBOX_DATA_ROOT as Ma, hasEventCatalogEntries as Mc, verifyTimerWatchCredentialSubject as Mi, getPluginUserPromptContributions as Mn, embedConversationQuery as Mo, dismissOpenReviewItems as Mr, withSlackRetries as Ms, isInvalidConversationRecordError as Mt, turnHasReply as N, SANDBOX_REPOS_ROOT as Na, registeredEventMatchSchema as Nc, createPluginState as Ni, getPlugins as Nn, saveObjectAnnotations as No, getOpenReviewItemByDedupeKey as Nr, sleep$2 as Ns, listActiveConversationIds as Nt, latestConversationMessageSeq as O, PluginToolDeniedError as Oa, eventCatalogEntry as Oc, bindSlackDirectCredentialSubject as Oi, getPluginRoutes as On, resolveRootVisibility as Oo, REVIEW_ITEM_REPLIED_REASON as Or, isSlackRequestTimeout as Os, getConversationWorkStates as Ot, upsertConversationMessage as P, SANDBOX_SCRATCH_ROOT as Pa, registeredEventTriggerProblems as Pc, renderToolResultNudge as Pi, getStaticPluginToolDefinitions as Pn, createPluginAnnotations as Po, getReviewItem as Pr, getWorkspaceTeamId as Ps, markConversationWorkEnqueued as Pt, lostWorkerBeforeFirstSave as Q, conversationPinnedForUser as Qa, readAutomationExecutionStatusDays as Qc, isRetryableSandboxFailure as Qi, getPiMessageRole as Qn, getPluginDispatchProjection as Qo, reviewItemNeedsSomeone as Qr, saveScheduledAutomation as Qs, TurnToolCallLimitExceededError as Qt, getAgentContextInputLimitTokens as R, sandboxSkillFile as Ra, requireValidEventTrigger as Rc, getWorkspaceByName as Ri, isBriefsEnabled as Rn, findActorTimezone as Ro, reviewItemsNeedingUserVersionQuery as Rr, formatSlackLink as Rs, recordConversationRetry as Rt, resolveConversationTitle as S, buildSandboxEgressNetworkPolicy as Sa, setEventAutomationStatus as Sc, isQuietEvent as Si, resolvePluginOAuthAccount as Sn, recordUploadedAttachment as So, readNotificationSchedule as Sr, downloadPrivateSlackFile as Ss, deadLetterAttempt as St, estimateConversationMessagesTokens as T, SANDBOX_RUNTIME as Ta, CORE_EVENT_NAMESPACE as Tc, turnEvents as Ti, createPluginEventPublisher as Tn, storeAttachments as To, isPausedBySlack as Tr, getSlackClient as Ts, dropPendingMessages as Tt, AuthPausePersistenceError as U, createPluginModelCostRecorder as Ua, sameDefinitionValue as Uc, invalidateReadySnapshot as Ui, lexemesSql as Un, buildDispatchId as Uo, canActOnReviewItem as Ur, slackMentionedUserIds as Us, startConversationWork as Ut, createPluginAuthOrchestration as V, buildNonInteractiveShellScript as Va, listAutomationVersions as Vc, updateWorkspace as Vi, setBriefsConfig as Vn, lookupSlackUserNames as Vo, updateReviewItemContent as Vr, normalizeSlackStatusText as Vs, requestAnotherSlice as Vt, AuthorizationFlowDisabledError as W, createPluginLogger as Wa, AutomationConflictError as Wc, loadSnapshotsForProfile as Wi, searchedEventTextSql as Wn, claimDispatchMailboxAppend as Wo, canAgentChangeReviewItem as Wr, wrapBareSlackUserIds as Ws, steerWebPendingMessages as Wt, continuableMessages as X, conversationIsMemberRoot as Xa, existingConversationId as Xc, ensureDockerDaemon as Xi, storedMessageJson as Xn, getDispatchRecord as Xo, requireReviewItemAssignees as Xr, parseScheduledAutomationRow as Xs, TurnBudgetExceededError as Xt, getConversationPendingAuth as Y, conversationHasParticipantUser as Ya, emptyAutomationRunWindows as Yc, isStale as Yi, excerptTerms as Yn, getDispatchInputMessageId as Yo, readReviewItemAgentScope as Yr, listScheduledAutomationsForTeam as Ys, TURN_LIMIT_WRAP_UP_MESSAGE as Yt, loadTurnCheckpoint as Z, conversationIsNotUnsubscribedRoot as Za, readAutomationExecutionByConversationId as Zc, getSandboxProvider as Zi, extractAssistantText as Zn, getDispatchTurnId as Zo, requireReviewItemLinks as Zr, readScheduledAutomation as Zs, TurnSliceLimitExceededError as Zt, appendConversationMessages as _, consumeSandboxEgressAuthRequiredSignal as _a, findMatchingEventAutomations as _c, createTimerWatch as _i, projectConversationEvents$1 as _l, readBlockedReport as _n, recordSlackAttachment as _o, readWebPushConfig as _r, uploadFilesToConversation as _s, clearConsumedConversationWake as _t, loadProjection as a, startOAuthFlow as aa, getDashboardPersonLink as ac, resolveAssignee as ai, recordAutomationExecution as al, remindMissingAnswer as an, readConversationEventPageAfter as ao, isContinuablePiBoundary as ar, markDispatchRunning as as, getTurnRecord as at, persistConversationMessages as b, parseSandboxEgressCredentialToken as ba, parseEventAutomationRow as bc, findMatchingWatches as bi, createUserTokenStore as bn, isFileAttachment as bo, deletePushSubscription as br, slackExternalRefIdSchema as bs, completeConversationWork as bt, recordAgentsInstructionsUpdated as c, isAbortError as ca, getDashboardTaskLink as cc, resolveChannelCapabilities as ci, resolveTaskTitle as cl, getAssistantReplyText as cn, readConversationMessageEventSeq as co, isToolResultMessage as cr, deleteSlackMessage as cs, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as ct, recordAuthorizationCompleted as d, wrapSandboxSetupError as da, parseDashboardPersonLink as dc, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as di, credentialAuditSource as dl, findLegacyNoReplyMarker as dn, loadForkHistory as do, stripRuntimeTurnContext as dr, openSlackModal as ds, appendExclusiveInboundMessage as dt, proxyVercelSandboxEgressRequest as ea, scheduledRunId as ec, reviewItemReaderForUserInConversation as ei, readAutomationExecutionSummaries as el, createTurnLimitGate as en, viewerMarksFromParticipant as eo, getUserMessageInstructionText as er, listPendingDispatchMailboxAppends as es, saveTurnCheckpoint as et, recordAuthorizationRequested as f, WorkspaceSnapshotNotReadyError as fa, setDashboardConversationLinkOptions as fc, RESOURCE_WATCH_TOOL_SOURCE as fi, createPluginCache as fl, isLegacyNoReplyMarker as fn, notInheritedByForkChild as fo, trimTrailingAssistantMessages as fr, postSlackEphemeralMessage as fs, appendInboundMessage as ft, recordToolExecutionStarted as g, clearSandboxEgressSignals as ga, deleteEventAutomation as gc, collectEventMatchKeys as gi, piMessageFromHistoryItem as gl, REPORT_BLOCKED_TOOL_NAME as gn, readSlackAttachmentSource as go, TURN_CONTEXT_TAG as gr, updateSlackMessage as gs, claimInboundMessage as gt, recordSubscribedReplyRoute as h, workspaceSnapshotNotReadyUserMessage as ha, createEventAutomation as hc, cancelWatch as hi, historyItemFromPiMessage as hl, CODE_MODE_CALL_STATUS_TEXT as hn, readAttachmentVisionSummary as ho, SESSION_CONTEXT_SECTION_TAG as hr, unfurlSlackLinks as hs, checkInConversationWork as ht, loadConversationProjection as i, resolveBaseUrl as ia, getDashboardObjectIconLink as ic, automationCreatorUserId as ii, readAutomationTitlesByConversationId as il, readTurnAnswer as in, readConversationEventPage as io, isAssistantMessage as ir, markDispatchFailed as is, getStoredTurnFields as it, recordDeliveredAssistantMessage as j, SANDBOX_COMMAND_PATH as ja, eventWatchUnavailable as jc, verifySlackDirectCredentialSubject as ji, getPluginTools as jn, createConversationEmbedder as jo, countReviewItemsNeedingUserBySubject as jr, streamPrivateSlackFile as js, isFinalAttempt as jt, markConversationMessage as k, createPluginEmbedder as ka, eventGuidance as kc, verifyEventAutomationCredentialSubject as ki, getPluginSlackConversationLink as kn, searchConversations as ko, closeReviewItem as kr, normalizeSlackConversationId as ks, hasConversationStop as kt, recordAttachmentsDelivered as l, isAlreadyExistsError as la, isDashboardLink as lc, getSlackToolContext as li, JUNIOR_THREAD_STATE_TTL_MS as ll, sanitizeAssistantText as ln, buildSentryConversationUrl as lo, normalizeToolNameFromResult as lr, getSlackMessagePermalink as ls, CONVERSATION_WORK_STALE_ENQUEUE_MS as lt, recordMcpProviderConnected as m, isWorkspaceSnapshotNotReadyError as ma, collectEventAutomationMatchKeys as mc, cancelSubscriptions as mi, configValueSchema as ml, CODEMODE_TOOL_NAME as mn, matchSlackAttachments as mo, REQUEST_CONTEXT_SECTION_TAG as mr, removeReactionFromMessage as ms, cancelHumanFacingPendingMessages as mt, commitMessages as n, formatProviderLabel as na, getDashboardConversationLink as nc, EVERYONE_ASSIGNEE as ni, readAutomationRowStats as nl, REPLY_TOOL_NAME as nn, readConversationBriefThrough as no, hasTurnInput as nr, markDispatchBlocked as ns, completeTurnRecord as nt, loadTurnProjection as o, SandboxCallTimeoutError as oa, getDashboardReviewItemLink as oc, resolveAssignees as oi, refreshAutomationLastRun as ol, replyTextSchema as on, readConversationEventPageAround as oo, isStandaloneRuntimeContextMessage as or, notifyAutomationBlocked as os, listTurnSummaries as ot, recordGuardianActionReviewed as p, getWorkspaceSnapshotNotReadyError as pa, blockEventAutomation as pc, STOP_WATCHING_TOOL_NAME as pi, createDurableLocationConfigurationService as pl, readNoReply as pn, getSlackFileId as po, CAPABILITY_SECTION_TAG as pr, postSlackMessage as ps, beginConversationResume as pt, canReusePendingAuthLink as q, createConversationAccessReader as qa, ToolInputError as qc, create as qi, callsToolSql as qn, getDispatchConversationId as qo, isOnlyAssignee as qr, createScheduledAutomation as qs, readInboundMessageSender as qt, loadConnectedMcpProviders as r, parseOAuthStatePayload as ra, getDashboardLinkFilter as rc, activeParticipantUserIds as ri, readAutomationRuns as rl, isAnswerToolName as rn, readLatestConversationBrief as ro, instructionTextForProjection as rr, markDispatchCompleted as rs, failTurnRecord as rt, openConversationProjection as s, findInErrorChain as sa, getDashboardSettingsLink as sc, createCodeChangePublisher as si, fallbackShortTitle as sl, decideReply as sn, readConversationLastEventSeq as so, isToolResultError as sr, addReactionToMessage as ss, recordTurnSummary as st, commitAcceptedReply as t, deliverOAuthAuthorization as ta, withScheduledAutomationLock as tc, reviewItemVisibleTo as ti, readAutomationExecutions as tl, isTurnExecutionLimitExceededError as tn, createPluginConversationEvents as to, hasRuntimeTurnContext as tr, markDispatchAwaitingResume as ts, abandonTurnRecord as tt, recordAuthenticationLinked as u, throwSandboxOperationError as ua, parseDashboardConversationLink as uc, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as ui, credentialAuditAttributes as ul, NO_REPLY_TOOL_NAME as un, FORK_INSTRUCTIONS as uo, retainRuntimeTurnContext as ur, openSlackDirectMessage as us, ackMessages as ut, hydrateConversationMessages as v, consumeSandboxEgressPermissionDeniedSignal as va, getEventAutomation as vc, createWatch as vi, getConfigDefaults as vl, persistWithRetry as vn, slackAttachmentsVersionQuery as vo, sendPushNotificationToUser as vr, fitsSlackMetadataLimit as vs, clearExpiredConversationLease as vt, buildConversationContext as w, normalizeSandboxEgressTracePropagationDomains as wa, eventAutomationRunLimitReason as wc, takeDueTimerWatches as wi, applyPluginFormatMarkdown as wn, storeAttachment as wo, savePushSubscription as wr, getHeaderString as ws, drainConversationMailbox as wt, toStoredConversationMessage as x, sandboxEgressSignalsResponseSchema as xa, saveEventAutomation as xc, getWatch as xi, getOAuthAccountProviders as xn, readLiveAttachment as xo, listPushSubscriptions as xr, SlackActionError as xs, countPendingConversationMessages as xt, persistConversationMessageWindow as y, createSandboxEgressCredentialToken as ya, listDeletedEventAutomationsCreatedBy as yc, deliverWatch as yi, setConfigDefaults as yl, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as yn, collectAttachmentGarbage as yo, resolveNotificationTimezone as yr, slackEntitySchema as ys, completeConversationStop as yt, createPluginEgress as z, sandboxSkillPathResolution as za, automationDefinition as zc, listWorkspaces as zi, isEventEmbeddingsEnabled as zn, resolveUserTimezone as zo, searchReviewItems as zr, isTableRow as zs, releaseConversationWork as zt };