@sentry/junior 0.306.0 → 0.307.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 (91) hide show
  1. package/dist/{adapter-context-CnY-i32r.js → adapter-context-B69WPn6b.js} +2 -2
  2. package/dist/{admin-BLLdLnXh.js → admin-nCJXMgkp.js} +2 -2
  3. package/dist/{agent-runner-BaLjEjPR.js → agent-runner-DdFcxAxG.js} +226 -137
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +4 -4
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +328 -298
  8. package/dist/{app-DvYbM9UD.d.ts → app-EZur8cVC.d.ts} +12 -3
  9. package/dist/app.d.ts +2 -2
  10. package/dist/app.js +84 -44
  11. package/dist/background-compaction-queue-BhEe4UfU.js +231 -0
  12. package/dist/{briefs-DvyzXfrF.js → briefs-Dl9lxi7J.js} +2 -2
  13. package/dist/{catalog-runtime-B1R-nHd3.js → catalog-runtime-OXrv2Ewn.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +17 -16
  16. package/dist/cli/check.js +58 -48
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.d.ts +1 -1
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +2 -2
  22. package/dist/cli/upgrade.js +3 -8
  23. package/dist/{config-DUD-zMvp.js → config-362yMSIz.js} +74 -38
  24. package/dist/{connections-CDhsqPcC.js → connections-BJv3EjmB.js} +10 -8
  25. package/dist/{continue-in-slack-BXQizz9o.js → continue-in-slack-CFEevC7z.js} +5 -5
  26. package/dist/{conversation-privacy-YE54gMN8.js → conversation-privacy-Tjj5P2W6.js} +1 -1
  27. package/dist/{conversation-turn-BzdmrHb0.js → conversation-turn-DU0_WDAr.js} +19 -47
  28. package/dist/{credential-sync-Cdm-e1vJ.js → credential-sync-D6aFARKE.js} +28 -28
  29. package/dist/{db-DV2ZUb1Y.js → db-Bcbd9zQc.js} +140 -11
  30. package/dist/{db-pH357Dkt.d.ts → db-C41UgdBj.d.ts} +1 -1
  31. package/dist/{executor-CjNhwwnj.js → executor-DBMBrpNV.js} +93 -32
  32. package/dist/{install-DbD7C5td.js → install-CgoAbzfF.js} +2 -2
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{lineage-BFdIPb3o.js → lineage-CsZDmz3e.js} +2 -2
  35. package/dist/{logging-oYpJYr-S.js → logging-CHCuQ5iz.js} +1 -1
  36. package/dist/{message-BBPcMKJY.js → message-B8vCbZZB.js} +8 -8
  37. package/dist/{model-input-DYYF3a8B.js → model-input-Xluiy-1W.js} +3 -3
  38. package/dist/nitro.d.ts +2 -2
  39. package/dist/nitro.js +3 -4
  40. package/dist/{oauth-callback-server-C7Q987su.js → oauth-callback-server-BUuNvfvu.js} +2 -2
  41. package/dist/{oauth-relay-DAmfVmJu.js → oauth-relay-DGAZzg9m.js} +1 -1
  42. package/dist/{plugins-B_0Cr0MO.d.ts → plugins-fBrz8PCV.d.ts} +2 -0
  43. package/dist/{projection-CWXDE0f6.js → projection-xPpvqexa.js} +1112 -693
  44. package/dist/{prompt-P3eRqO8C.js → prompt-D8u4jFs_.js} +3 -3
  45. package/dist/{registry-1pzXmplY.js → registry-D20hG3r6.js} +19 -9
  46. package/dist/{resolve-n87oXY-d.js → resolve-BhCySRCW.js} +3 -3
  47. package/dist/{result-BmF9v9bv.js → result-DddO63S9.js} +13 -11
  48. package/dist/{runner-4j7ZsxP5.js → runner-DQR9vYce.js} +9 -9
  49. package/dist/{sandbox-egress-signals-BRQI8HvT.js → sandbox-egress-signals-DFlNUOnK.js} +1 -1
  50. package/dist/{schedule-CHPWQn-x.js → schedule-BG1tEbRF.js} +34 -4
  51. package/dist/{schema-CVbIjrF3.d.ts → schema-CRXcj4fj.d.ts} +350 -143
  52. package/dist/{schema-D7iIEh6t.js → schema-D4jdesIu.js} +12 -4
  53. package/dist/{service-account-DzQiOmqa.js → service-account-Bv5QwrEq.js} +8 -6
  54. package/dist/{service-account-BDQ9xzta.js → service-account-CNfycv0z.js} +3 -3
  55. package/dist/{session-stop-BQxgHR4X.js → session-stop-BDdwyZaa.js} +36 -23
  56. package/dist/{skills-CPf4vNuC.js → skills-63i1Bcv1.js} +32 -28
  57. package/dist/{slack-conversation-unfurl-B1KEptUg.js → slack-conversation-unfurl-DtpBUlUu.js} +10 -10
  58. package/dist/{spawn-CjGddiAU.js → spawn-mwimEY9_.js} +6 -6
  59. package/dist/{state-9wfj6aSD.js → state-BBn9L6gC.js} +4 -4
  60. package/dist/{stop-CsQGuN5n.js → stop-Da-Ug7tg.js} +146 -158
  61. package/dist/{store-Dz3YZ7gQ.js → store-CdWg2r2L.js} +5 -5
  62. package/dist/{background-compaction-queue-D2wzxtGU.js → task-queue-BcjAYWyB.js} +164 -180
  63. package/dist/{task-runner-frzlUvFD.js → task-runner-CoXmMlsW.js} +11 -8
  64. package/dist/{thread-context-C4QuZlM8.js → thread-context-ZPGqOjW7.js} +6 -6
  65. package/dist/{turn-session-routing-BXaubz2w.js → turn-session-routing-DFYak28Q.js} +24 -5
  66. package/dist/{turn-user-message-DNC0eRZ7.js → turn-user-message-B1S8nOnG.js} +3 -3
  67. package/dist/{users-XCCKn3xW.js → users-DDbENg-I.js} +1 -1
  68. package/dist/{validation-L5fdjmFX.js → validation-fl21ps-k.js} +1 -1
  69. package/dist/{version-BFmuwgxP.js → version-DCdMMx_0.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-DKOeHpv3.js → viewer-DN_xzVKj.js} +3 -3
  72. package/dist/{warmup-mTMIatCV.js → warmup-CxhEhm71.js} +596 -281
  73. package/dist/{web-message-id-CUaSiGme.js → web-message-id-BT8Mg8LL.js} +1 -1
  74. package/dist/{worker-Bz4KNxjI.js → worker-Btb1SB5h.js} +8 -7
  75. package/migrations/0115_automation_creator_slack_index.sql +1 -0
  76. package/migrations/0116_conversation_event_search.sql +25 -0
  77. package/migrations/0117_automation_last_run.sql +46 -0
  78. package/migrations/0118_automation_last_run_index.sql +1 -0
  79. package/migrations/0119_money_micro_usd.sql +29 -0
  80. package/migrations/0120_conversation_cost_micro_usd.sql +8 -0
  81. package/migrations/meta/0115_snapshot.json +5225 -0
  82. package/migrations/meta/0116_snapshot.json +5388 -0
  83. package/migrations/meta/0117_snapshot.json +5413 -0
  84. package/migrations/meta/0118_snapshot.json +5428 -0
  85. package/migrations/meta/0119_snapshot.json +5441 -0
  86. package/migrations/meta/0120_snapshot.json +5441 -0
  87. package/migrations/meta/_journal.json +42 -0
  88. package/package.json +10 -9
  89. package/dist/queue-7FSijgqG.js +0 -115
  90. package/dist/secrets-DHaJ5TTn.js +0 -18
  91. package/dist/task-queue-CFlrJguF.js +0 -89
@@ -1,21 +1,22 @@
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-P3eRqO8C.js";
4
- import { $ as getStateAdapter, I as resolveActorIdentityId, K as saveUserTimezone, N as startLocationThread, Q as getDefaultRedisStateAdapterFor, S as createSqlStore, St as sameDestination, T as isPersonInput, U as linkedSlackUser, W as readUserTimezone, X as createCache, a as getConversationStore, at as withLock, bt as parseDestination, c as hasAnnotationKey, d as eventFromRow, dt as agentTurnTotalTokens, et as getStateValues, gt as conversationDetailTouch, it as fenceLock, l as treeHasAnnotationKey, lt as addAgentTurnUsage, m as withConversationEventLock, nt as MUTATION_LOCK_TTL_MS, o as getDb, ot as claimProviderConversation, pt as hasAgentTurnUsage, r as getConversationEventStore, rt as acquireActiveLock, s as getSqlExecutor, tt as setStateValues, u as createSqlConversationEventStore, ut as agentTurnCostUsd, vt as touchConversationDetail } from "./db-DV2ZUb1Y.js";
5
- import { A as juniorCodeChanges, C as juniorConversationBriefs, D as juniorConversationEvents, F as juniorConversations, I as juniorIdentities, L as juniorUsers, N as juniorAttachments, P as juniorMessageAttachments, R as juniorDestinations, S as juniorConversationEmbeddings, a as juniorPushSubscriptions, b as juniorConversationParticipants, c as juniorReviewItemAssignees, d as juniorReviewItems, f as juniorAutomationRuns, g as juniorLocationConfigurations, i as juniorWorkspaces, j as juniorCodeRepositories, k as juniorConversationAnnotations, l as juniorReviewItemConversations, m as juniorAutomations, n as juniorSnapshots, p as juniorAutomationVersions, r as juniorWorkspaceRepos } from "./executor-CjNhwwnj.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-oYpJYr-S.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-1pzXmplY.js";
8
- import { F as scheduledAutomationSchema, G as isValidTimeZone, J as automationTaskDescription, K as automationSkillNameSchema, M as eventAutomationSchema, T as automationVersionSchema, Y as automationTaskSchema, n as isWithinNotificationSchedule, q as automationTaskColumns, r as notificationScheduleSchema, t as DEFAULT_NOTIFICATION_SCHEDULE } from "./schedule-CHPWQn-x.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-DUD-zMvp.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-D8u4jFs_.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-Bcbd9zQc.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-DBMBrpNV.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-CHCuQ5iz.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-D20hG3r6.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-362yMSIz.js";
10
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
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-DKOeHpv3.js";
12
+ import { i as readActorIdentity, l as resolveViewerUser, n as findUserByEmailFromSql, o as readIdentityById, p as parseAvatarUrl, s as readIdentityByIdFromSql } from "./viewer-DN_xzVKj.js";
13
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 { t as canExposeConversationPayload } from "./conversation-privacy-YE54gMN8.js";
15
- import { n as pluginCatalogRuntime } from "./catalog-runtime-B1R-nHd3.js";
14
+ import { d as readJuniorSecret, m as readWebPushPrivateKey, r as pluginTaskId } from "./task-queue-BcjAYWyB.js";
15
+ import { t as canExposeConversationPayload } from "./conversation-privacy-Tjj5P2W6.js";
16
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-OXrv2Ewn.js";
16
17
  import { n as redactSandboxEgressProxyPath, t as SANDBOX_EGRESS_PROXY_PATH } from "./proxy-path-BHYoKZdq.js";
17
- import { n as readEncryptedState, r as findLegacyWebActorUserId, t as createEncryptedState } from "./state-9wfj6aSD.js";
18
- import { i as readWebPushPrivateKey, t as readJuniorSecret } from "./secrets-DHaJ5TTn.js";
18
+ import { n as readEncryptedState, r as findLegacyWebActorUserId, t as createEncryptedState } from "./state-BBn9L6gC.js";
19
+ import pLimit from "p-limit";
19
20
  import * as z from "zod";
20
21
  import path from "node:path";
21
22
  import { isDeepStrictEqual } from "node:util";
@@ -24,10 +25,10 @@ import { createHash, createHmac, createPrivateKey, createPublicKey, generateKeyP
24
25
  import { and, arrayContains, asc, count, desc, eq, exists, getTableColumns, gt, gte, ilike, inArray, isNotNull, isNull, lt, lte, max, ne, not, notExists, notLike, or, sql } from "drizzle-orm";
25
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";
26
27
  import { alias } from "drizzle-orm/pg-core";
28
+ import { embedText, guardedCosineDistance, refreshEmbeddings } from "@sentry/junior-plugin-api/embeddings";
27
29
  import fs from "node:fs/promises";
28
30
  import { WebClient } from "@slack/web-api";
29
31
  import { parseMarkdown, walkAst } from "chat";
30
- import pLimit from "p-limit";
31
32
  import http from "node:http";
32
33
  import os from "node:os";
33
34
  import dns from "node:dns/promises";
@@ -222,7 +223,7 @@ function validateConfigValue(value) {
222
223
  }
223
224
  // src/chat/configuration/service.ts
224
225
  function sanitizeEntry(value) {
225
- if (!isRecord$2(value)) return;
226
+ if (!isRecord$3(value)) return;
226
227
  const key = toOptionalString(value["key"]);
227
228
  if (!key || validateConfigKey(key)) return;
228
229
  const updatedAt = toOptionalString(value["updatedAt"]);
@@ -242,8 +243,8 @@ function sanitizeEntry(value) {
242
243
  }
243
244
  /** Coerce legacy persisted configuration into current Location entries. */
244
245
  function coerceLegacyLocationConfig(raw) {
245
- const rawConfig = isRecord$2(raw) && isRecord$2(raw["configuration"]) ? raw["configuration"] : {};
246
- const rawEntries = isRecord$2(rawConfig["entries"]) ? rawConfig["entries"] : {};
246
+ const rawConfig = isRecord$3(raw) && isRecord$3(raw["configuration"]) ? raw["configuration"] : {};
247
+ const rawEntries = isRecord$3(rawConfig["entries"]) ? rawConfig["entries"] : {};
247
248
  return Object.values(rawEntries).flatMap((value) => {
248
249
  const entry = sanitizeEntry(value);
249
250
  return entry ? [entry] : [];
@@ -646,84 +647,6 @@ function fragmentSelectionSet(selection, fragments, seen) {
646
647
  // src/chat/state/ttl.ts
647
648
  /** Retain expiring conversation/runtime state long enough for resume and dashboard history. */
648
649
  const JUNIOR_THREAD_STATE_TTL_MS = 6048e5;
649
- // src/api/conversations/aggregate.ts
650
- function usageTokenValue(source, field) {
651
- return sql`CASE
652
- WHEN ${source.usage}->>${field} IS NOT NULL
653
- THEN (${source.usage}->>${field})::double precision
654
- ELSE NULL
655
- END`;
656
- }
657
- function tokenValue(source) {
658
- return sql`
659
- CASE
660
- WHEN COALESCE(
661
- ${source.usage}->>'inputTokens',
662
- ${source.usage}->>'outputTokens',
663
- ${source.usage}->>'cachedInputTokens',
664
- ${source.usage}->>'cacheCreationTokens'
665
- ) IS NOT NULL
666
- THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
667
- + COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
668
- + COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
669
- + COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
670
- WHEN ${source.usage}->>'totalTokens' IS NOT NULL
671
- THEN (${source.usage}->>'totalTokens')::double precision
672
- ELSE NULL
673
- END
674
- `;
675
- }
676
- function costValue(source) {
677
- return conversationUsageCostExpr(source.usage);
678
- }
679
- /** Read one conversation row's usage cost as a SQL expression. */
680
- function conversationUsageCostExpr(usage) {
681
- return sql`
682
- CASE
683
- WHEN ${usage}->'cost'->>'total' IS NOT NULL
684
- THEN (${usage}->'cost'->>'total')::double precision
685
- WHEN COALESCE(
686
- ${usage}->'cost'->>'input',
687
- ${usage}->'cost'->>'output',
688
- ${usage}->'cost'->>'cacheRead',
689
- ${usage}->'cost'->>'cacheWrite'
690
- ) IS NOT NULL
691
- THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
692
- + COALESCE((${usage}->'cost'->>'output')::double precision, 0)
693
- + COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
694
- + COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
695
- ELSE NULL
696
- END
697
- `;
698
- }
699
- /** Select complete conversation metrics inside the database instead of materializing source rows. */
700
- function conversationAggregateColumns(sources) {
701
- const metrics = sources?.metrics ?? juniorConversations;
702
- const roots = sources?.roots ?? juniorConversations;
703
- const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
704
- return {
705
- active: sql`${conversationCount} FILTER (
706
- WHERE ${roots.executionStatus} NOT IN ('idle', 'failed')
707
- )::integer`,
708
- conversations: sql`${conversationCount}::integer`,
709
- cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
710
- cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
711
- costUsd: sql`SUM(${costValue(metrics)})::double precision`,
712
- durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
713
- failed: sql`${conversationCount} FILTER (
714
- WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
715
- )::integer`,
716
- inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
717
- tokens: sql`SUM(${tokenValue(metrics)})::double precision`
718
- };
719
- }
720
- /** Select the complete first/last activity range for a grouped conversation aggregate. */
721
- function conversationRangeColumns() {
722
- return {
723
- firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
724
- lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
725
- };
726
- }
727
650
  const SOURCE_TEXT_MAX_LENGTH = {
728
651
  conversation: 500,
729
652
  run: 2e3,
@@ -828,9 +751,6 @@ const AUTOMATION_EXECUTION_STATUSES = [
828
751
  function isExecution() {
829
752
  return and(inArray(juniorAutomationRuns.status, [...AUTOMATION_EXECUTION_STATUSES]), isNotNull(juniorAutomationRuns.completedAtMs));
830
753
  }
831
- function addUsd(current, next) {
832
- return Math.round((current + next) * 0xe8d4a51000) / 0xe8d4a51000;
833
- }
834
754
  const EMPTY_RUN_WINDOWS = {
835
755
  1: 0,
836
756
  7: 0,
@@ -862,9 +782,20 @@ function existingConversationId(conversationId) {
862
782
  return sql`(select ${juniorConversations.conversationId} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
863
783
  }
864
784
  /**
785
+ * Copy when an Automation's latest execution ended, and its outcome, to the
786
+ * Automation row. Call it after each write that adds, settles, or removes an
787
+ * execution. It reads the runs again, so a late or out-of-order write cannot
788
+ * leave an older run.
789
+ */
790
+ async function refreshAutomationLastRun(db, automationId) {
791
+ const latest = (column) => sql`(select ${column} from ${juniorAutomationRuns} where ${juniorAutomationRuns.automationId} = ${automationId} and ${isExecution()} order by ${juniorAutomationRuns.completedAtMs} desc, ${juniorAutomationRuns.id} desc limit 1)`;
792
+ await db.update(juniorAutomations).set({ lastRunId: latest(sql`${juniorAutomationRuns.id}`) }).where(eq(juniorAutomations.id, automationId));
793
+ }
794
+ /**
865
795
  * Record the outcome of one Automation run. A run that already has an outcome
866
- * keeps it. A failed write is logged, and the heartbeat settles a started
867
- * event run later.
796
+ * keeps it. The run and the Automation's last run commit together, so the
797
+ * list never misses a stored outcome. A failed write is logged, and the
798
+ * heartbeat settles a started event run later.
868
799
  */
869
800
  async function recordAutomationExecution(automationId, options) {
870
801
  const nowMs = options.nowMs ?? Date.now();
@@ -875,18 +806,23 @@ async function recordAutomationExecution(automationId, options) {
875
806
  status
876
807
  };
877
808
  try {
878
- await getDb().insert(juniorAutomationRuns).values({
879
- id: options.executionId,
880
- automationId,
881
- conversationId: options.conversationId ? existingConversationId(options.conversationId) : null,
882
- ...outcome
883
- }).onConflictDoUpdate({
884
- target: juniorAutomationRuns.id,
885
- set: {
886
- ...outcome,
887
- conversationId: sql`coalesce(${juniorAutomationRuns.conversationId}, excluded.conversation_id)`
888
- },
889
- setWhere: inArray(juniorAutomationRuns.status, ["pending", "running"])
809
+ await getDb().transaction(async (tx) => {
810
+ await tx.insert(juniorAutomationRuns).values({
811
+ id: options.executionId,
812
+ automationId,
813
+ conversationId: options.conversationId ? existingConversationId(options.conversationId) : null,
814
+ costMicroUsd: options.conversationId ? conversationCostOf(options.conversationId) : null,
815
+ ...outcome
816
+ }).onConflictDoUpdate({
817
+ target: juniorAutomationRuns.id,
818
+ set: {
819
+ ...outcome,
820
+ conversationId: sql`coalesce(${juniorAutomationRuns.conversationId}, excluded.conversation_id)`,
821
+ costMicroUsd: conversationCostOf(sql`coalesce(${juniorAutomationRuns.conversationId}, excluded.conversation_id)`)
822
+ },
823
+ setWhere: inArray(juniorAutomationRuns.status, ["pending", "running"])
824
+ });
825
+ await refreshAutomationLastRun(tx, automationId);
890
826
  });
891
827
  } catch (error) {
892
828
  logWarn("task.execution.stat_failed", {
@@ -906,60 +842,50 @@ async function readAutomationExecutionSummaries(automationIds, options = {}) {
906
842
  const thirtyDaysAgoMs = nowMs - 2592e6;
907
843
  const ninetyDaysAgoMs = nowMs - 7776e6;
908
844
  const db = getDb();
909
- const selected = and(isExecution(), inArray(juniorAutomationRuns.automationId, automationIds));
910
- const latest = db.selectDistinctOn([juniorAutomationRuns.automationId], {
911
- status: juniorAutomationRuns.status,
912
- conversationId: juniorAutomationRuns.conversationId,
913
- automationId: juniorAutomationRuns.automationId
914
- }).from(juniorAutomationRuns).where(selected).orderBy(juniorAutomationRuns.automationId, desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).as("latest_task_execution");
915
- const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
916
- const costSince = (sinceMs) => sql`coalesce(sum(${conversationCost}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::double precision`;
845
+ const costSince = (sinceMs) => sql`coalesce(sum(${juniorAutomationRuns.costMicroUsd}) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sinceMs}), 0)::bigint`.mapWith(Number);
917
846
  const summaryRows = db.select({
918
847
  costLast1Day: costSince(oneDayAgoMs),
919
848
  costLast7Days: costSince(sevenDaysAgoMs),
920
849
  costLast30Days: costSince(thirtyDaysAgoMs),
921
850
  costLast90Days: costSince(ninetyDaysAgoMs),
922
- lastRunStatus: latest.status,
923
- lastConversationId: latest.conversationId,
924
- lastExecutedAtMs: max(juniorAutomationRuns.completedAtMs),
925
851
  runsLast1Day: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${oneDayAgoMs})::int`,
926
852
  runsLast7Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${sevenDaysAgoMs})::int`,
927
853
  runsLast30Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${thirtyDaysAgoMs})::int`,
928
854
  runsLast90Days: sql`count(*) filter (where ${juniorAutomationRuns.completedAtMs} >= ${ninetyDaysAgoMs})::int`,
929
855
  automationId: juniorAutomationRuns.automationId,
930
- totalCostUsd: sql`coalesce(sum(${conversationCost}), 0)::double precision`,
856
+ totalCostMicroUsd: sql`coalesce(sum(${juniorAutomationRuns.costMicroUsd}), 0)::bigint`.mapWith(Number),
931
857
  totalRuns: sql`count(*)::int`
932
- }).from(juniorAutomationRuns).innerJoin(latest, eq(latest.automationId, juniorAutomationRuns.automationId)).leftJoin(juniorConversations, executionConversation()).where(selected).groupBy(juniorAutomationRuns.automationId, latest.conversationId, latest.status);
933
- const [rows, recentRuns] = await Promise.all([summaryRows, readAutomationRecentRuns(automationIds)]);
858
+ }).from(juniorAutomationRuns).where(and(isExecution(), inArray(juniorAutomationRuns.automationId, automationIds))).groupBy(juniorAutomationRuns.automationId);
859
+ const [rows, rowStats] = await Promise.all([summaryRows, readAutomationRowStats(automationIds)]);
934
860
  return new Map(rows.map((row) => [row.automationId, {
861
+ ...rowStats.get(row.automationId),
935
862
  costUsd: {
936
- 1: addUsd(0, row.costLast1Day),
937
- 7: addUsd(0, row.costLast7Days),
938
- 30: addUsd(0, row.costLast30Days),
939
- 90: addUsd(0, row.costLast90Days)
863
+ 1: microUsdToUsd(row.costLast1Day),
864
+ 7: microUsdToUsd(row.costLast7Days),
865
+ 30: microUsdToUsd(row.costLast30Days),
866
+ 90: microUsdToUsd(row.costLast90Days)
940
867
  },
941
- lastRunStatus: row.lastRunStatus,
942
- ...row.lastConversationId ? { lastConversationId: row.lastConversationId } : void 0,
943
- ...row.lastExecutedAtMs !== null ? { lastExecutedAtMs: row.lastExecutedAtMs } : void 0,
944
- recentRuns: recentRuns.get(row.automationId) ?? [],
945
868
  runs: {
946
869
  1: row.runsLast1Day,
947
870
  7: row.runsLast7Days,
948
871
  30: row.runsLast30Days,
949
872
  90: row.runsLast90Days
950
873
  },
951
- totalCostUsd: addUsd(0, row.totalCostUsd),
874
+ totalCostUsd: microUsdToUsd(row.totalCostMicroUsd),
952
875
  totalRuns: row.totalRuns
953
876
  }]));
954
877
  }
955
878
  /**
956
- * Load the newest runs of each Automation, oldest first. A lateral limit
957
- * reads at most `AUTOMATION_RECENT_RUN_LIMIT` rows per Automation from the
958
- * (automation, completed) index, so long histories do not slow the list.
879
+ * Load the newest runs of each Automation, oldest first, and its last run.
880
+ * A lateral limit reads at most `AUTOMATION_RECENT_RUN_LIMIT` rows per
881
+ * Automation from the (automation, completed) index, so long histories do
882
+ * not slow the list. An Automation with no run is absent.
959
883
  */
960
- async function readAutomationRecentRuns(automationIds) {
884
+ async function readAutomationRowStats(automationIds) {
885
+ if (automationIds.length === 0) return /* @__PURE__ */ new Map();
961
886
  const db = getDb();
962
887
  const recent = db.select({
888
+ conversationId: juniorAutomationRuns.conversationId,
963
889
  durationMs: juniorConversations.durationMs,
964
890
  executedAtMs: juniorAutomationRuns.completedAtMs,
965
891
  executionId: juniorAutomationRuns.id,
@@ -967,6 +893,7 @@ async function readAutomationRecentRuns(automationIds) {
967
893
  }).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, juniorAutomations.id))).orderBy(desc(juniorAutomationRuns.completedAtMs), desc(juniorAutomationRuns.id)).limit(20).as("recent_run");
968
894
  const rows = await db.select({
969
895
  automationId: juniorAutomations.id,
896
+ conversationId: recent.conversationId,
970
897
  durationMs: recent.durationMs,
971
898
  executedAtMs: recent.executedAtMs,
972
899
  status: recent.status
@@ -974,13 +901,20 @@ async function readAutomationRecentRuns(automationIds) {
974
901
  const byAutomation = /* @__PURE__ */ new Map();
975
902
  for (const row of rows) {
976
903
  const durationMs = positiveDuration(row.durationMs);
977
- const runs = byAutomation.get(row.automationId) ?? [];
978
- runs.push({
904
+ const status = row.status;
905
+ const executedAtMs = row.executedAtMs;
906
+ const stats = byAutomation.get(row.automationId) ?? { recentRuns: [] };
907
+ stats.recentRuns.push({
979
908
  ...durationMs !== void 0 ? { durationMs } : void 0,
980
- executedAt: new Date(row.executedAtMs).toISOString(),
981
- status: row.status
909
+ executedAt: new Date(executedAtMs).toISOString(),
910
+ status
911
+ });
912
+ byAutomation.set(row.automationId, {
913
+ recentRuns: stats.recentRuns,
914
+ lastRunStatus: status,
915
+ lastExecutedAtMs: executedAtMs,
916
+ ...row.conversationId ? { lastConversationId: row.conversationId } : void 0
982
917
  });
983
- byAutomation.set(row.automationId, runs);
984
918
  }
985
919
  return byAutomation;
986
920
  }
@@ -1101,14 +1035,7 @@ async function readAutomationExecutionStatusDays(args) {
1101
1035
  const date = utcDate(startMs + offset * 864e5);
1102
1036
  byDate.set(date, emptyStatusDay(date));
1103
1037
  }
1104
- for (const row of rows) {
1105
- const day = byDate.get(row.date);
1106
- if (!day) continue;
1107
- if (row.status === "completed") day.completed = row.count;
1108
- else if (row.status === "failed") day.failed = row.count;
1109
- else if (row.status === "blocked") day.blocked = row.count;
1110
- if (row.costUsd !== null && row.costUsd > 0) day.costUsd = addUsd(day.costUsd, row.costUsd);
1111
- }
1038
+ applyExecutionStatusBuckets(byDate, rows);
1112
1039
  return [...byDate.values()];
1113
1040
  }
1114
1041
  /** Load a fixed trailing window of terminal executions for one automation by hour. */
@@ -1131,25 +1058,33 @@ async function readAutomationExecutionStatusHours(args) {
1131
1058
  const date = new Date(startMs + offset * 36e5).toISOString().slice(0, 13);
1132
1059
  byHour.set(date, emptyStatusDay(date));
1133
1060
  }
1061
+ applyExecutionStatusBuckets(byHour, rows);
1062
+ return [...byHour.values()];
1063
+ }
1064
+ /**
1065
+ * Add status counts and cost to their buckets. Cost sums in micro-USD, so a
1066
+ * bucket's USD comes from one exact integer.
1067
+ */
1068
+ function applyExecutionStatusBuckets(buckets, rows) {
1069
+ const costMicroUsd = /* @__PURE__ */ new Map();
1134
1070
  for (const row of rows) {
1135
- const hour = byHour.get(row.date);
1136
- if (!hour) continue;
1137
- if (row.status === "completed") hour.completed = row.count;
1138
- else if (row.status === "failed") hour.failed = row.count;
1139
- else if (row.status === "blocked") hour.blocked = row.count;
1140
- if (row.costUsd !== null && row.costUsd > 0) hour.costUsd = addUsd(hour.costUsd, row.costUsd);
1071
+ const bucket = buckets.get(row.date);
1072
+ if (!bucket) continue;
1073
+ if (row.status === "completed") bucket.completed = row.count;
1074
+ else if (row.status === "failed") bucket.failed = row.count;
1075
+ else if (row.status === "blocked") bucket.blocked = row.count;
1076
+ costMicroUsd.set(bucket, (costMicroUsd.get(bucket) ?? 0) + (row.costMicroUsd ?? 0));
1141
1077
  }
1142
- return [...byHour.values()];
1078
+ for (const [bucket, microUsd] of costMicroUsd) bucket.costUsd = microUsdToUsd(microUsd);
1143
1079
  }
1144
1080
  /** Count one automation's executions and their cost per time bucket and status. */
1145
1081
  async function readExecutionStatusBuckets(args) {
1146
- const conversationCost = conversationUsageCostExpr(juniorConversations.usage);
1147
1082
  return await getDb().select({
1148
1083
  count: count(),
1149
- costUsd: sql`SUM(${conversationCost})::double precision`,
1084
+ costMicroUsd: sql`SUM(${juniorAutomationRuns.costMicroUsd})::bigint`.mapWith(Number),
1150
1085
  date: args.bucket,
1151
1086
  status: juniorAutomationRuns.status
1152
- }).from(juniorAutomationRuns).leftJoin(juniorConversations, executionConversation()).where(and(isExecution(), eq(juniorAutomationRuns.automationId, args.automationId), gte(juniorAutomationRuns.completedAtMs, args.startMs), lte(juniorAutomationRuns.completedAtMs, args.endMs))).groupBy(args.bucket, juniorAutomationRuns.status).orderBy(asc(args.bucket), asc(juniorAutomationRuns.status));
1087
+ }).from(juniorAutomationRuns).where(and(isExecution(), eq(juniorAutomationRuns.automationId, args.automationId), gte(juniorAutomationRuns.completedAtMs, args.startMs), lte(juniorAutomationRuns.completedAtMs, args.endMs))).groupBy(args.bucket, juniorAutomationRuns.status).orderBy(asc(args.bucket), asc(juniorAutomationRuns.status));
1153
1088
  }
1154
1089
  // src/chat/tools/execution/tool-input-error.ts
1155
1090
  /** Thrown when a tool fails due to invalid model/user input, not a system error. */
@@ -1472,9 +1407,7 @@ async function admitEventAutomationRun(args) {
1472
1407
  const windowStartMs = args.nowMs - botConfig.eventAutomationRunWindowMs;
1473
1408
  const { entries, length } = await readEntries();
1474
1409
  let lastReset = -1;
1475
- entries.forEach((entry, index) => {
1476
- if ("reset" in entry) lastReset = index;
1477
- });
1410
+ for (const [index, entry] of entries.entries()) if ("reset" in entry) lastReset = index;
1478
1411
  const oldest = entries[0];
1479
1412
  const full = lastReset === -1 && length >= runListMaxLength() && oldest !== void 0 && "atMs" in oldest && oldest.atMs > windowStartMs;
1480
1413
  const runKeys = /* @__PURE__ */ new Set();
@@ -1964,7 +1897,10 @@ async function listScheduledAutomationsForTeam(db, teamId) {
1964
1897
  return await readListedScheduledAutomations(db, teamId);
1965
1898
  }
1966
1899
  async function writeScheduledAutomation(db, task, current, editedBy) {
1967
- if (current?.status === "blocked" && task.status === "active" && typeof task.nextRunAtMs === "number" && Number.isFinite(task.nextRunAtMs)) await db.delete(juniorAutomationRuns).where(and(eq(juniorAutomationRuns.id, scheduledRunId(task.id, task.nextRunAtMs)), eq(juniorAutomationRuns.status, "blocked")));
1900
+ if (current?.status === "blocked" && task.status === "active" && typeof task.nextRunAtMs === "number" && Number.isFinite(task.nextRunAtMs)) {
1901
+ await db.delete(juniorAutomationRuns).where(and(eq(juniorAutomationRuns.id, scheduledRunId(task.id, task.nextRunAtMs)), eq(juniorAutomationRuns.status, "blocked")));
1902
+ await refreshAutomationLastRun(db, task.id);
1903
+ }
1968
1904
  if (task.status === "deleted" && current?.status !== "deleted") await skipPendingRunsForDeletedTask(db, task);
1969
1905
  await upsertScheduledAutomation(db, task);
1970
1906
  await recordAutomationVersion(db, task, current, editedBy);
@@ -2864,6 +2800,13 @@ const slackEntitySchema = z.discriminatedUnion("entity_type", [entity.extend({
2864
2800
  entity_type: z.literal("slack#/entities/task"),
2865
2801
  entity_payload: payload.extend({ fields: z.strictObject({ status: z.strictObject({ value: z.string() }).optional() }).optional() })
2866
2802
  })]);
2803
+ const SLACK_METADATA_MAX_BYTES = 4e3;
2804
+ /** Return whether Slack keeps message metadata with these entities. */
2805
+ function fitsSlackMetadataLimit(entities) {
2806
+ const json = JSON.stringify({ entities });
2807
+ const escapes = 5 * (json.match(/[\u0080-\uffff]/g)?.length ?? 0) + (json.match(/\//g)?.length ?? 0);
2808
+ return json.length + escapes <= SLACK_METADATA_MAX_BYTES;
2809
+ }
2867
2810
  // src/chat/slack/outbound.ts
2868
2811
  const MAX_SLACK_MESSAGE_TEXT_CHARS = 4e4;
2869
2812
  function requireSlackConversationId(channelId, action) {
@@ -3161,6 +3104,7 @@ async function notifyAutomationBlocked(ref) {
3161
3104
  // src/chat/agent-dispatch/store.ts
3162
3105
  const DISPATCH_PREFIX = "junior:agent_dispatch";
3163
3106
  const DISPATCH_LOCK_TTL_MS = 6e5;
3107
+ const DISPATCH_LOCK_WAIT_MS = 5e3;
3164
3108
  const DISPATCH_MAILBOX_APPEND_INDEX_LOCK_TTL_MS = 1e4;
3165
3109
  const nonEmptyExactStringSchema = z.string().min(1).refine((value) => value === value.trim() && value.toLowerCase() !== "unknown");
3166
3110
  const pendingDispatchMailboxAppendIndexSchema = z.array(nonEmptyExactStringSchema);
@@ -3301,13 +3245,12 @@ function isTerminalDispatchStatus(status) {
3301
3245
  async function withDispatchLock(dispatchId, task) {
3302
3246
  const state = getStateAdapter();
3303
3247
  await state.connect();
3304
- const lock = await state.acquireLock(dispatchLockKey(dispatchId), DISPATCH_LOCK_TTL_MS);
3305
- if (!lock) throw new Error(`Could not acquire dispatch lock for ${dispatchId}`);
3306
- try {
3307
- return await task(state);
3308
- } finally {
3309
- await state.releaseLock(lock);
3310
- }
3248
+ const attempt = await withLock(state, dispatchLockKey(dispatchId), () => task(state), {
3249
+ ttlMs: DISPATCH_LOCK_TTL_MS,
3250
+ waitMs: DISPATCH_LOCK_WAIT_MS
3251
+ });
3252
+ if (!attempt.acquired) throw new Error(`Could not acquire dispatch lock for ${dispatchId}`);
3253
+ return attempt.value;
3311
3254
  }
3312
3255
  async function putRecord(state, record) {
3313
3256
  const parsed = dispatchRecordSchema.safeParse(record);
@@ -3964,8 +3907,8 @@ async function saveObjectAnnotations(conversationId, plugin, value) {
3964
3907
  * not return one: looking up an object does not link it.
3965
3908
  */
3966
3909
  async function annotateToolResult(conversationId, plugin, result, options) {
3967
- if (!isRecord$2(result) || result["isError"] === true) return result;
3968
- const details = isRecord$2(result["details"]) ? result["details"] : result;
3910
+ if (!isRecord$3(result) || result["isError"] === true) return result;
3911
+ const details = isRecord$3(result["details"]) ? result["details"] : result;
3969
3912
  if (details["timed_out"] === true || details["isError"] === true || !Array.isArray(details["objectAnnotations"])) return result;
3970
3913
  if (options.readOnly) throw new Error(`Read-only ${plugin} tool returned objectAnnotations. Return them only from tools that change the object.`);
3971
3914
  const cards = await saveObjectAnnotations(conversationId, plugin, details["objectAnnotations"]);
@@ -3974,80 +3917,133 @@ async function annotateToolResult(conversationId, plugin, result, options) {
3974
3917
  ...rest,
3975
3918
  objectCards: cards
3976
3919
  };
3977
- if (isRecord$2(result["details"])) return {
3920
+ if (isRecord$3(result["details"])) return {
3978
3921
  ...result,
3979
3922
  details: annotated
3980
3923
  };
3981
3924
  return annotated;
3982
3925
  }
3983
3926
  // src/chat/conversations/embedding.ts
3984
- /**
3985
- * One embedding per Conversation: a derived index for semantic Conversation
3986
- * search. Its text is the latest Brief, which summarizes the Conversation.
3987
- * Vectors are stored per model. A search compares only vectors of the same
3988
- * provider, model, and size as its query.
3989
- */
3990
- const MAX_EMBEDDED_CHARS = 8e3;
3991
- /** Create the embedder that charges its cost to one Conversation. */
3927
+ const MAX_EMBEDDED_CHARS$1 = 8e3;
3928
+ const BACKFILL_BATCH_SIZE = 32;
3929
+ /** Create the embedder of the configured model that charges its cost to `cost`. */
3992
3930
  function createConversationEmbedder(args) {
3993
- return async ({ inputType, text }) => {
3994
- const result = await embedTexts({
3995
- cost: args.cost,
3996
- inputType,
3997
- modelId: botConfig.embeddingModelId,
3998
- operation: args.operation,
3999
- texts: [text.slice(0, MAX_EMBEDDED_CHARS)]
4000
- });
4001
- const vector = result.vectors[0];
4002
- if (!vector) throw new Error("Embedding provider returned no vector");
4003
- return {
4004
- model: result.model,
4005
- provider: result.provider,
4006
- vector
4007
- };
3931
+ const model = botConfig.embeddingModelId;
3932
+ return {
3933
+ model,
3934
+ provider: GEN_AI_PROVIDER_NAME,
3935
+ async embedTexts(input) {
3936
+ return await embedTexts({
3937
+ cost: args.cost,
3938
+ inputType: input.inputType ?? "document",
3939
+ modelId: model,
3940
+ operation: args.operation,
3941
+ texts: input.texts.map((text) => text.slice(0, MAX_EMBEDDED_CHARS$1))
3942
+ });
3943
+ }
4008
3944
  };
4009
3945
  }
3946
+ /** Embed a search query for `conversationSimilarity`. */
3947
+ async function embedConversationQuery(embedder, text) {
3948
+ return await embedText(embedder, {
3949
+ inputType: "query",
3950
+ text
3951
+ });
3952
+ }
3953
+ /**
3954
+ * Store one batch of Brief vectors. A row is replaced only by a vector of
3955
+ * the same or a newer Brief version, so an older Turn never replaces a newer
3956
+ * vector, and a backfill can replace a vector of another model.
3957
+ */
3958
+ async function writeConversationEmbeddings(db, rows, batch) {
3959
+ const table = juniorConversationEmbeddings;
3960
+ await db.insert(table).values(rows.map(({ item, vector }) => ({
3961
+ briefVersion: item.version,
3962
+ conversationId: item.conversationId,
3963
+ dimensions: batch.dimensions,
3964
+ embedding: vector,
3965
+ model: batch.model,
3966
+ provider: batch.provider
3967
+ }))).onConflictDoUpdate({
3968
+ target: table.conversationId,
3969
+ set: {
3970
+ briefVersion: sql`excluded.brief_version`,
3971
+ dimensions: sql`excluded.dimensions`,
3972
+ embedding: sql`excluded.embedding`,
3973
+ model: sql`excluded.model`,
3974
+ provider: sql`excluded.provider`,
3975
+ createdAt: sql`now()`
3976
+ },
3977
+ setWhere: sql`${table.briefVersion} <= excluded.brief_version`
3978
+ });
3979
+ }
3980
+ /** Whether a stored row is the embedder's vector of this or a newer Brief. */
3981
+ function hasCurrentVector(embedder, version) {
3982
+ const table = juniorConversationEmbeddings;
3983
+ return and(eq(table.provider, embedder.provider), eq(table.model, embedder.model), sql`${table.briefVersion} >= ${version}`);
3984
+ }
4010
3985
  /**
4011
3986
  * Store the Conversation embedding of a stored Brief. Skip it when the
4012
- * Conversation already has a vector for this or a newer Brief version, so a
4013
- * task retry embeds once and an older Turn never replaces a newer vector.
3987
+ * Conversation already has a vector of the embedder's model for this or a
3988
+ * newer Brief version, so a task retry embeds once.
4014
3989
  */
4015
- async function storeConversationEmbedding(db, embed, brief) {
4016
- if (!brief.searchText) return;
3990
+ async function storeConversationEmbedding(db, embedder, brief) {
3991
+ if (!brief.searchText.trim()) return;
4017
3992
  const table = juniorConversationEmbeddings;
4018
- const [current] = await db.select({ briefVersion: table.briefVersion }).from(table).where(eq(table.conversationId, brief.conversationId)).limit(1);
4019
- if (current && current.briefVersion >= brief.version) return;
4020
- const embedding = await embed({
3993
+ const [current] = await db.select({ conversationId: table.conversationId }).from(table).where(and(eq(table.conversationId, brief.conversationId), hasCurrentVector(embedder, brief.version))).limit(1);
3994
+ if (current) return;
3995
+ const embedding = await embedText(embedder, {
4021
3996
  inputType: "document",
4022
3997
  text: brief.searchText
4023
3998
  });
4024
- const row = {
4025
- briefVersion: brief.version,
3999
+ await writeConversationEmbeddings(db, [{
4000
+ item: {
4001
+ conversationId: brief.conversationId,
4002
+ text: brief.searchText,
4003
+ version: brief.version
4004
+ },
4005
+ vector: embedding.vector
4006
+ }], {
4026
4007
  dimensions: embedding.vector.length,
4027
- embedding: embedding.vector,
4028
4008
  model: embedding.model,
4029
- provider: embedding.provider
4030
- };
4031
- await db.insert(table).values({
4032
- conversationId: brief.conversationId,
4033
- ...row
4034
- }).onConflictDoUpdate({
4035
- target: table.conversationId,
4036
- set: {
4037
- ...row,
4038
- createdAt: sql`now()`
4039
- },
4040
- setWhere: sql`${table.briefVersion} < excluded.brief_version`
4009
+ provider: embedding.provider,
4010
+ vectors: [embedding.vector]
4011
+ });
4012
+ }
4013
+ /**
4014
+ * Embed the latest Brief of each Conversation that has no vector of the
4015
+ * embedder's model for it, in Conversation id order. Return whether no such
4016
+ * Brief was left, and how many it embedded.
4017
+ */
4018
+ async function backfillConversationEmbeddings(args) {
4019
+ const briefs = juniorConversationBriefs;
4020
+ const embeddings = juniorConversationEmbeddings;
4021
+ const newer = alias(briefs, "newer_briefs");
4022
+ return await refreshEmbeddings({
4023
+ batchSize: BACKFILL_BATCH_SIZE,
4024
+ deadlineMs: args.deadlineMs,
4025
+ embedder: args.embedder,
4026
+ listMissing: async ({ after, limit }) => await args.db.select({
4027
+ conversationId: briefs.conversationId,
4028
+ text: briefs.searchText,
4029
+ version: briefs.version
4030
+ }).from(briefs).leftJoin(embeddings, and(eq(embeddings.conversationId, briefs.conversationId), hasCurrentVector(args.embedder, briefs.version))).where(and(notExists(args.db.select({ one: sql`1` }).from(newer).where(and(eq(newer.conversationId, briefs.conversationId), gt(newer.version, briefs.version)))), isNull(embeddings.conversationId), after ? gt(briefs.conversationId, after.conversationId) : void 0)).orderBy(asc(briefs.conversationId)).limit(limit),
4031
+ write: async (rows, batch) => await writeConversationEmbeddings(args.db, rows, batch)
4041
4032
  });
4042
4033
  }
4043
4034
  /**
4044
4035
  * Cosine similarity of the stored vector to a query vector. Null for a
4045
- * vector of another model or size. CASE fixes the order, so Postgres never
4046
- * compares vectors of different sizes, which fails.
4036
+ * vector of another model or size.
4047
4037
  */
4048
4038
  function conversationSimilarity(query) {
4049
4039
  const table = juniorConversationEmbeddings;
4050
- return sql`CASE WHEN ${table.provider} = ${query.provider} AND ${table.model} = ${query.model} AND ${table.dimensions} = ${query.vector.length} THEN 1 - (${table.embedding} <=> ${JSON.stringify(query.vector)}::vector) END`;
4040
+ const distance = guardedCosineDistance({
4041
+ column: table.embedding,
4042
+ dimensions: table.dimensions,
4043
+ query: query.vector,
4044
+ type: "vector"
4045
+ });
4046
+ return sql`CASE WHEN ${table.provider} = ${query.provider} AND ${table.model} = ${query.model} THEN 1 - ${distance} END`;
4051
4047
  }
4052
4048
  // src/chat/conversations/search.ts
4053
4049
  /**
@@ -4074,10 +4070,7 @@ async function searchConversations(db, args) {
4074
4070
  const requesterRoot = alias(juniorConversations, "requester_roots");
4075
4071
  const embeddings = juniorConversationEmbeddings;
4076
4072
  const query = search.query?.trim() || void 0;
4077
- const queryVector = query && embedder ? await embedder({
4078
- inputType: "query",
4079
- text: query
4080
- }) : void 0;
4073
+ const queryVector = query && embedder ? await embedConversationQuery(embedder, query) : void 0;
4081
4074
  const similarity = queryVector ? conversationSimilarity(queryVector) : void 0;
4082
4075
  const tsquery = sql`websearch_to_tsquery('english', ${query ?? ""})`;
4083
4076
  const searchVector = sql`to_tsvector('english', ${briefs.searchText})`;
@@ -4191,8 +4184,8 @@ function createPluginConversations(conversationId) {
4191
4184
  */
4192
4185
  async function recordToolReply(args) {
4193
4186
  const { result } = args;
4194
- if (!isRecord$2(result) || result["isError"] === true) return result;
4195
- const details = isRecord$2(result["details"]) ? result["details"] : result;
4187
+ if (!isRecord$3(result) || result["isError"] === true) return result;
4188
+ const details = isRecord$3(result["details"]) ? result["details"] : result;
4196
4189
  if (details["reply"] === void 0) return result;
4197
4190
  const reply = pluginToolReplySchema.parse(details["reply"]);
4198
4191
  if (args.toolCallId) await getConversationEventStore().append(args.conversationId, [{
@@ -4207,7 +4200,7 @@ async function recordToolReply(args) {
4207
4200
  createdAtMs: Date.now()
4208
4201
  }]);
4209
4202
  const { reply: _reply, ...rest } = details;
4210
- if (isRecord$2(result["details"])) return {
4203
+ if (isRecord$3(result["details"])) return {
4211
4204
  ...result,
4212
4205
  details: rest
4213
4206
  };
@@ -4722,8 +4715,8 @@ async function readLiveAttachment(args) {
4722
4715
  }
4723
4716
  /** Persist many conversation-owned files. */
4724
4717
  async function storeAttachments(args) {
4725
- const stored = [];
4726
- for (const file of args.files) stored.push(await storeAttachment({
4718
+ const limit = pLimit(8);
4719
+ return await Promise.all(args.files.map((file) => limit(() => storeAttachment({
4727
4720
  conversationId: args.conversationId,
4728
4721
  db: args.db,
4729
4722
  file: {
@@ -4733,8 +4726,7 @@ async function storeAttachments(args) {
4733
4726
  },
4734
4727
  ...args.nowMs !== void 0 ? { nowMs: args.nowMs } : void 0,
4735
4728
  storage: args.storage
4736
- }));
4737
- return stored;
4729
+ }))));
4738
4730
  }
4739
4731
  /** Mark attachments unavailable when their conversation content is purged. */
4740
4732
  async function requestAttachmentDeletion(db, conversationIds, nowMs) {
@@ -5835,7 +5827,7 @@ function briefVersionFromRow(row) {
5835
5827
  content: parseStoredBrief(row.content),
5836
5828
  searchText: row.searchText,
5837
5829
  modelId: row.modelId,
5838
- ...row.costUsd !== null ? { costUsd: row.costUsd } : void 0,
5830
+ ...row.costMicroUsd !== null ? { costUsd: microUsdToUsd(row.costMicroUsd) } : void 0,
5839
5831
  createdAt: row.createdAt
5840
5832
  };
5841
5833
  }
@@ -5864,7 +5856,7 @@ async function appendConversationBrief(db, input) {
5864
5856
  content: conversationBriefSchema.parse(input.content),
5865
5857
  searchText: input.searchText,
5866
5858
  modelId: input.modelId,
5867
- costUsd: input.costUsd ?? null
5859
+ costMicroUsd: input.costUsd === void 0 ? null : usdToMicroUsd(input.costUsd)
5868
5860
  }).onConflictDoNothing({ target: [juniorConversationBriefs.conversationId, juniorConversationBriefs.turnId] }).returning())[0];
5869
5861
  if (!row) throw new Error("Brief insert conflicted after the Turn check");
5870
5862
  return {
@@ -5893,6 +5885,8 @@ async function readConversationBriefThrough(db, conversationId, seq) {
5893
5885
  }
5894
5886
  // src/chat/briefs/task.ts
5895
5887
  const BRIEF_LOCK_TTL_MS = 6e5;
5888
+ const BRIEF_LOCK_WAIT_MS = 5e3;
5889
+ const BRIEF_MAX_PASSES = 3;
5896
5890
  function hasUserInstruction(run) {
5897
5891
  return run.transcript.some((entry) => entry.type === "message" && entry.role === "user" && entry.provenance?.authority === "instruction");
5898
5892
  }
@@ -5907,8 +5901,14 @@ async function readTurnCompletedSeq(db, conversationId, turnId) {
5907
5901
  if (seq === void 0) throw new Error(`Completed Turn ${turnId} has no terminal event in Conversation ${conversationId}`);
5908
5902
  return seq;
5909
5903
  }
5910
- async function emitBriefUpdated(context, stored) {
5911
- await context.events.emit(briefUpdatedEvent({
5904
+ async function readLatestCompletedTurn(db, conversationId) {
5905
+ return (await db.select({
5906
+ seq: juniorConversationEvents.seq,
5907
+ turnId: sql`${juniorConversationEvents.payload}->>'turnId'`
5908
+ }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "turn_completed"))).orderBy(desc(juniorConversationEvents.seq)).limit(1))[0];
5909
+ }
5910
+ async function emitBriefUpdated(events, stored) {
5911
+ await events.emit(briefUpdatedEvent({
5912
5912
  version: stored.version,
5913
5913
  modelId: stored.modelId,
5914
5914
  ...stored.costUsd !== void 0 ? { costUsd: stored.costUsd } : void 0,
@@ -5939,56 +5939,104 @@ async function updateConversationBrief(context) {
5939
5939
  logSkip(context, run.conversationId, "no_user_instruction");
5940
5940
  return;
5941
5941
  }
5942
- await context.state.withLock(`brief:${run.conversationId}`, BRIEF_LOCK_TTL_MS, async () => {
5943
- const db = context.db;
5944
- const embed = createConversationEmbedder({
5945
- cost: {
5942
+ const db = context.db;
5943
+ if (!(await context.state.withLock(`brief:${run.conversationId}`, BRIEF_LOCK_TTL_MS, async () => {
5944
+ let turn = {
5945
+ events: context.events,
5946
+ turnId: run.runId
5947
+ };
5948
+ for (let pass = 1;; pass++) {
5949
+ const throughSeq = await storeBriefForTurn(context, {
5946
5950
  conversationId: run.conversationId,
5947
- turnId: run.runId
5948
- },
5949
- operation: "conversation_embedding"
5950
- });
5951
- const existing = await readConversationBriefForTurn(db, run.conversationId, run.runId);
5952
- if (existing) {
5953
- await emitBriefUpdated(context, existing);
5954
- await storeConversationEmbedding(db, embed, existing);
5955
- logSkip(context, run.conversationId, "turn_already_stored");
5956
- return;
5957
- }
5958
- const terminalSeq = await readTurnCompletedSeq(db, run.conversationId, run.runId);
5959
- const previous = await readLatestConversationBrief(db, run.conversationId);
5960
- if (previous && previous.throughSeq >= terminalSeq) {
5961
- logSkip(context, run.conversationId, "turn_already_covered");
5962
- return;
5951
+ db,
5952
+ events: turn.events,
5953
+ executor,
5954
+ turnId: turn.turnId
5955
+ });
5956
+ const latest = await readLatestCompletedTurn(db, run.conversationId);
5957
+ if (!latest || latest.seq <= throughSeq) return;
5958
+ if (pass >= BRIEF_MAX_PASSES) throw new Error(`Brief catch-up stopped after ${BRIEF_MAX_PASSES} passes with Turn ${latest.turnId} uncovered in Conversation ${run.conversationId}`);
5959
+ turn = {
5960
+ events: await briefTaskEvents(run.conversationId, latest.turnId),
5961
+ turnId: latest.turnId
5962
+ };
5963
5963
  }
5964
- const input = await briefInputFromSql(executor, run.conversationId, terminalSeq);
5965
- const modelId = botConfig.fastModelId;
5966
- const generation = await generateBrief({
5967
- assistantName: botConfig.userName,
5968
- completeObject: (request) => completeObject({
5969
- ...request,
5970
- modelId,
5971
- operation: "brief_update",
5972
- cost: { owner: "caller" }
5973
- }),
5974
- input,
5975
- previous: previous?.content,
5976
- prompt: BRIEF_PROMPT,
5977
- throughIndex: terminalSeq
5978
- });
5979
- const stored = await appendConversationBrief(db, {
5980
- conversationId: run.conversationId,
5981
- turnId: run.runId,
5982
- throughSeq: terminalSeq,
5983
- content: generation.brief,
5984
- searchText: generation.searchText,
5964
+ }, { waitMs: BRIEF_LOCK_WAIT_MS })).acquired) logSkip(context, run.conversationId, "brief_in_progress");
5965
+ }
5966
+ /**
5967
+ * Write events as the Brief task of another Turn would, so its own task run
5968
+ * later finds the same event instead of adding a second one.
5969
+ */
5970
+ async function briefTaskEvents(conversationId, turnId) {
5971
+ const { createPluginConversationEvents } = await Promise.resolve().then(() => conversation_events_exports);
5972
+ return createPluginConversationEvents({
5973
+ conversationId,
5974
+ operationId: pluginTaskId({
5975
+ name: "updateBrief",
5976
+ params: {
5977
+ conversationId,
5978
+ sessionId: turnId
5979
+ },
5980
+ plugin: briefsTaskRegistration.manifest.name
5981
+ }),
5982
+ plugin: briefsTaskRegistration,
5983
+ turnId
5984
+ });
5985
+ }
5986
+ /**
5987
+ * Store the Brief for one completed Turn unless a Brief already covers it.
5988
+ * Returns the last event seq that the newest Brief covers.
5989
+ */
5990
+ async function storeBriefForTurn(context, args) {
5991
+ const { conversationId, db, events, executor, turnId } = args;
5992
+ const embed = createConversationEmbedder({
5993
+ cost: {
5994
+ conversationId,
5995
+ turnId
5996
+ },
5997
+ operation: "conversation_embedding"
5998
+ });
5999
+ const existing = await readConversationBriefForTurn(db, conversationId, turnId);
6000
+ if (existing) {
6001
+ await emitBriefUpdated(events, existing);
6002
+ await storeConversationEmbedding(db, embed, existing);
6003
+ logSkip(context, conversationId, "turn_already_stored");
6004
+ return existing.throughSeq;
6005
+ }
6006
+ const terminalSeq = await readTurnCompletedSeq(db, conversationId, turnId);
6007
+ const previous = await readLatestConversationBrief(db, conversationId);
6008
+ if (previous && previous.throughSeq >= terminalSeq) {
6009
+ logSkip(context, conversationId, "turn_already_covered");
6010
+ return previous.throughSeq;
6011
+ }
6012
+ const input = await briefInputFromSql(executor, conversationId, terminalSeq);
6013
+ const modelId = botConfig.fastModelId;
6014
+ const generation = await generateBrief({
6015
+ assistantName: botConfig.userName,
6016
+ completeObject: (request) => completeObject({
6017
+ ...request,
5985
6018
  modelId,
5986
- ...generation.costUsd !== void 0 ? { costUsd: generation.costUsd } : void 0
5987
- });
5988
- await emitBriefUpdated(context, stored.value);
5989
- await storeConversationEmbedding(db, embed, stored.value);
5990
- if (!stored.inserted) logSkip(context, run.conversationId, "turn_already_stored");
6019
+ operation: "brief_update",
6020
+ cost: { owner: "caller" }
6021
+ }),
6022
+ input,
6023
+ previous: previous?.content,
6024
+ prompt: BRIEF_PROMPT,
6025
+ throughIndex: terminalSeq
6026
+ });
6027
+ const stored = await appendConversationBrief(db, {
6028
+ conversationId,
6029
+ turnId,
6030
+ throughSeq: terminalSeq,
6031
+ content: generation.brief,
6032
+ searchText: generation.searchText,
6033
+ modelId,
6034
+ ...generation.costUsd !== void 0 ? { costUsd: generation.costUsd } : void 0
5991
6035
  });
6036
+ await emitBriefUpdated(events, stored.value);
6037
+ await storeConversationEmbedding(db, embed, stored.value);
6038
+ if (!stored.inserted) logSkip(context, conversationId, "turn_already_stored");
6039
+ return stored.value.throughSeq;
5992
6040
  }
5993
6041
  /** Core task registration kept outside the installed plugin catalog. */
5994
6042
  const briefsTaskRegistration = {
@@ -6013,6 +6061,7 @@ const briefsTaskRegistration = {
6013
6061
  } } }
6014
6062
  };
6015
6063
  // src/chat/plugins/conversation-events.ts
6064
+ var conversation_events_exports = /* @__PURE__ */ __exportAll({ createPluginConversationEvents: () => createPluginConversationEvents });
6016
6065
  function registeredDefinition(plugin, value) {
6017
6066
  return plugin.conversationEvents?.find((definition) => definition === value.definition);
6018
6067
  }
@@ -6420,10 +6469,10 @@ function gitConfigEnv(env) {
6420
6469
  }
6421
6470
  entries.push(...RUNTIME_GIT_CONFIG);
6422
6471
  const result = { GIT_CONFIG_COUNT: String(entries.length) };
6423
- entries.forEach(([key, value], index) => {
6472
+ for (const [index, [key, value]] of entries.entries()) {
6424
6473
  result[`GIT_CONFIG_KEY_${index}`] = key;
6425
6474
  result[`GIT_CONFIG_VALUE_${index}`] = value;
6426
- });
6475
+ }
6427
6476
  return result;
6428
6477
  }
6429
6478
  function shellQuote(value) {
@@ -6487,6 +6536,12 @@ const SANDBOX_DATA_ROOT = `${SANDBOX_WORKSPACE_ROOT}/data`;
6487
6536
  /** Runtime-owned files inside the sandbox, outside every repository. */
6488
6537
  const SANDBOX_JUNIOR_ROOT = `${SANDBOX_WORKSPACE_ROOT}/.junior`;
6489
6538
  /**
6539
+ * Runtime-written files that live only as long as the Sandbox. Nothing here
6540
+ * is ever copied out of the Sandbox. Tool notes name these paths, so keep the
6541
+ * root short.
6542
+ */
6543
+ const SANDBOX_SCRATCH_ROOT = "/tmp/jr";
6544
+ /**
6490
6545
  * PATH for sandbox commands. Plugin runtime binaries come last so they never
6491
6546
  * shadow repo or Workspace tools with the same name. Repo tools often start
6492
6547
  * child processes through PATH, so only PATH order can protect them. Plugin
@@ -7139,11 +7194,11 @@ async function pruneNetworks() {
7139
7194
  const containers = await listSandboxResources("containers");
7140
7195
  const used = new Set(containers.map((container) => container.Labels[DOCKER_SANDBOX_LABEL]));
7141
7196
  const networks = await listSandboxResources("networks");
7142
- for (const network of networks) {
7143
- if (used.has(network.Labels["dev.junior.sandbox"])) continue;
7197
+ const limit = pLimit(8);
7198
+ await Promise.all(networks.filter((network) => !used.has(network.Labels[DOCKER_SANDBOX_LABEL])).map((network) => limit(async () => {
7144
7199
  await forceRemove(egressRelayName(network.Name));
7145
7200
  await removeNetwork(network.Name);
7146
- }
7201
+ })));
7147
7202
  }
7148
7203
  async function createNetwork(name, signal) {
7149
7204
  await pruneNetworks();
@@ -7881,6 +7936,53 @@ async function resolveSandboxCommandEnvironment() {
7881
7936
  }
7882
7937
  return env;
7883
7938
  }
7939
+ // src/chat/sandbox/egress/credential-request.ts
7940
+ const CREDENTIAL_HEADERS = ["authorization", "cookie"];
7941
+ const BROWSER_HEADER = "sec-fetch-mode";
7942
+ function placeholders(manifest) {
7943
+ return [HOST_MANAGED_CREDENTIAL_PLACEHOLDER, ...manifest.credentials ? [resolveAuthTokenPlaceholder(manifest.credentials)] : []];
7944
+ }
7945
+ function credentialHeaders(manifest) {
7946
+ return new Set([
7947
+ ...CREDENTIAL_HEADERS,
7948
+ ...Object.keys(manifest.apiHeaders ?? {}),
7949
+ ...Object.keys(manifest.credentials?.apiHeaders ?? {})
7950
+ ].map((name) => name.toLowerCase()));
7951
+ }
7952
+ function decodedBasicAuth(value) {
7953
+ const match = /^basic\s+(\S+)$/i.exec(value.trim());
7954
+ if (!match?.[1]) return;
7955
+ return Buffer.from(match[1], "base64").toString("utf8");
7956
+ }
7957
+ function hasPlaceholder(value, markers) {
7958
+ const decoded = decodedBasicAuth(value);
7959
+ return markers.some((marker) => value.includes(marker) || decoded !== void 0 && decoded.includes(marker));
7960
+ }
7961
+ /**
7962
+ * Classify one Sandbox request by the credential it sends.
7963
+ *
7964
+ * A browser request is `browser`, whatever it sends. Otherwise a credential
7965
+ * header with any value other than a placeholder makes the request `carried`, even when another header has a placeholder, so the host
7966
+ * never replaces a credential that the request brought.
7967
+ */
7968
+ function classifySandboxCredentialRequest(manifest, headers) {
7969
+ if (headers.has(BROWSER_HEADER)) return "browser";
7970
+ const markers = placeholders(manifest);
7971
+ const names = credentialHeaders(manifest);
7972
+ let sawPlaceholder = false;
7973
+ for (const [key, value] of headers) if (hasPlaceholder(value, markers)) sawPlaceholder = true;
7974
+ else if (names.has(key) && value.trim()) return "carried";
7975
+ return sawPlaceholder ? "placeholder" : "none";
7976
+ }
7977
+ /**
7978
+ * Return whether the host adds the plugin's credential to a Sandbox request.
7979
+ *
7980
+ * A request gets a credential when it sends the plugin's placeholder, or when
7981
+ * it sends no credential and the plugin says that its tools send none.
7982
+ */
7983
+ function sandboxRequestGetsCredential(manifest, request) {
7984
+ return request === "placeholder" || request === "none" && manifest.toolsSendNoCredential === true;
7985
+ }
7884
7986
  // src/chat/sandbox/egress/schemas.ts
7885
7987
  const finiteNumberSchema = z.number().refine(Number.isFinite);
7886
7988
  const httpStatusSchema = z.number().int().min(100).max(599);
@@ -8221,6 +8323,18 @@ function continueSandboxEgressTrace(request, upstreamHost, tracePropagation, cre
8221
8323
  }, run);
8222
8324
  }
8223
8325
  /**
8326
+ * Choose whether this request gets the plugin's credential. Only a request
8327
+ * that asks for one gets it, so Sandbox code does not act as the Actor only
8328
+ * because it calls a provider domain.
8329
+ */
8330
+ function credentialRequestInput(provider, request) {
8331
+ const manifest = pluginCatalogRuntime.getDefinition(provider)?.manifest;
8332
+ if (!manifest) throw new Error(`Plugin "${provider}" has no manifest for sandbox egress`);
8333
+ const credentialRequest = classifySandboxCredentialRequest(manifest, request.headers);
8334
+ if (credentialRequest === "placeholder" || sandboxRequestGetsCredential(manifest, credentialRequest)) return {};
8335
+ return { withoutCredential: credentialRequest };
8336
+ }
8337
+ /**
8224
8338
  * Run one sandbox egress request that its sandbox provider authenticated.
8225
8339
  *
8226
8340
  * This is the shared authorization boundary. It rejects upstream hosts that no
@@ -8269,7 +8383,8 @@ async function executeSandboxEgressRequest(input, deps = {}) {
8269
8383
  deps,
8270
8384
  provider,
8271
8385
  request,
8272
- upstreamUrl
8386
+ upstreamUrl,
8387
+ ...credentialRequestInput(provider, request)
8273
8388
  });
8274
8389
  if (result.authRequired) await setSandboxEgressAuthRequiredSignal(credentialContext, result.authRequired);
8275
8390
  return result.response;
@@ -8432,9 +8547,7 @@ function requestHeaders$1(rawHeaders) {
8432
8547
  }
8433
8548
  async function writeResponse(response, res) {
8434
8549
  const headers = {};
8435
- response.headers.forEach((value, name) => {
8436
- if (name !== "set-cookie" && !HOP_BY_HOP.has(name)) headers[name] = value;
8437
- });
8550
+ for (const [name, value] of response.headers) if (name !== "set-cookie" && !HOP_BY_HOP.has(name)) headers[name] = value;
8438
8551
  const cookies = response.headers.getSetCookie();
8439
8552
  if (cookies.length > 0) headers["set-cookie"] = cookies;
8440
8553
  res.writeHead(response.status, headers);
@@ -9148,11 +9261,15 @@ async function deleteSnapshotTag(name) {
9148
9261
  */
9149
9262
  async function deleteWorkspaceSnapshotBuilders$1(names) {
9150
9263
  const failures = [];
9151
- for (const name of new Set(names)) for (const remove of [removeContainer, deleteSnapshotTag]) try {
9152
- await remove(name);
9153
- } catch (error) {
9154
- failures.push(error);
9155
- }
9264
+ const limit = pLimit(8);
9265
+ const removeAll = async (name) => {
9266
+ for (const remove of [removeContainer, deleteSnapshotTag]) try {
9267
+ await remove(name);
9268
+ } catch (error) {
9269
+ failures.push(error);
9270
+ }
9271
+ };
9272
+ await Promise.all([...new Set(names)].map((name) => limit(() => removeAll(name))));
9156
9273
  if (failures.length > 0) throw failures[0];
9157
9274
  }
9158
9275
  const DOCKER_SNAPSHOT_PACKAGES = /* @__PURE__ */ new Set([
@@ -9230,7 +9347,7 @@ function optionalString(value) {
9230
9347
  }
9231
9348
  /** Parse OAuth callback state that was persisted before a provider redirect. */
9232
9349
  function parseOAuthStatePayload(value) {
9233
- if (!isRecord$2(value)) return;
9350
+ if (!isRecord$3(value)) return;
9234
9351
  if (typeof value["userId"] !== "string" || typeof value["provider"] !== "string") return;
9235
9352
  const actor = value["actor"] === void 0 ? void 0 : actorSchema.safeParse(value["actor"]);
9236
9353
  if (value["actor"] !== void 0 && (!actor || !actor.success)) return;
@@ -9641,7 +9758,7 @@ async function proxyVercelSandboxEgressRequest(request, deps = {}) {
9641
9758
  }, deps);
9642
9759
  }
9643
9760
  // src/chat/sandbox/vercel/errors.ts
9644
- function isRecord$1(value) {
9761
+ function isRecord$2(value) {
9645
9762
  return typeof value === "object" && value !== null;
9646
9763
  }
9647
9764
  function searchableText(error) {
@@ -9649,10 +9766,10 @@ function searchableText(error) {
9649
9766
  return `${details.searchableText} ${details.summary}`.toLowerCase();
9650
9767
  }
9651
9768
  function isInvalidSandboxSessionError(error) {
9652
- if (!isRecord$1(error)) return false;
9653
- if (isRecord$1(error["json"]) && error["json"]["invalidToken"] === true) return true;
9769
+ if (!isRecord$2(error)) return false;
9770
+ if (isRecord$2(error["json"]) && error["json"]["invalidToken"] === true) return true;
9654
9771
  const response = error["response"];
9655
- return isRecord$1(response) && response["status"] === 403 && typeof response["url"] === "string" && response["url"].includes("/sandboxes/sessions");
9772
+ return isRecord$2(response) && response["status"] === 403 && typeof response["url"] === "string" && response["url"].includes("/sandboxes/sessions");
9656
9773
  }
9657
9774
  function isUnavailable(error) {
9658
9775
  return findInErrorChain(error, (candidate) => {
@@ -9681,14 +9798,14 @@ function isTransient(error) {
9681
9798
  return findInErrorChain(error, (candidate) => {
9682
9799
  const searchable = searchableText(candidate);
9683
9800
  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;
9684
- if (!isRecord$1(candidate)) return false;
9801
+ if (!isRecord$2(candidate)) return false;
9685
9802
  const response = candidate["response"];
9686
- return isRecord$1(response) && typeof response["status"] === "number" && response["status"] >= 500 && response["status"] < 600;
9803
+ return isRecord$2(response) && typeof response["status"] === "number" && response["status"] >= 500 && response["status"] < 600;
9687
9804
  });
9688
9805
  }
9689
9806
  const SOCKET_FAILURE_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "UND_ERR_SOCKET"]);
9690
9807
  function isFetchSocketFailure(error) {
9691
- 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"]);
9808
+ return error.name === "TypeError" && (error.message === "terminated" || error.message === "fetch failed") && isRecord$2(error.cause) && typeof error.cause["code"] === "string" && SOCKET_FAILURE_CODES.has(error.cause["code"]);
9692
9809
  }
9693
9810
  function isCommandStreamInterrupted(error) {
9694
9811
  return findInErrorChain(error, (candidate) => {
@@ -9863,18 +9980,21 @@ async function getWorkspaceSnapshotBuilder(name, signal) {
9863
9980
  async function deleteWorkspaceSnapshotBuilders(names) {
9864
9981
  let hasError = false;
9865
9982
  let firstError;
9866
- for (const name of new Set(names)) try {
9867
- await (await Sandbox.get({
9868
- name,
9869
- resume: false,
9870
- ...clientOptions()
9871
- })).delete();
9872
- } catch (error) {
9873
- if (!vercelSandboxErrors.isMissing(error)) {
9874
- if (!hasError) firstError = error;
9875
- hasError = true;
9983
+ const limit = pLimit(8);
9984
+ await Promise.all([...new Set(names)].map((name) => limit(async () => {
9985
+ try {
9986
+ await (await Sandbox.get({
9987
+ name,
9988
+ resume: false,
9989
+ ...clientOptions()
9990
+ })).delete();
9991
+ } catch (error) {
9992
+ if (!vercelSandboxErrors.isMissing(error)) {
9993
+ if (!hasError) firstError = error;
9994
+ hasError = true;
9995
+ }
9876
9996
  }
9877
- }
9997
+ })));
9878
9998
  if (hasError) throw firstError;
9879
9999
  }
9880
10000
  /** Vercel Sandbox implementation of the sandbox provider contract. */
@@ -10322,6 +10442,7 @@ function normalizeWorkspaceRecipe(input) {
10322
10442
  };
10323
10443
  }
10324
10444
  // src/chat/workspaces/store.ts
10445
+ const UNIQUE_VIOLATION = "23505";
10325
10446
  function workspaceFromRows(row, repos, snapshot) {
10326
10447
  return {
10327
10448
  id: row.id,
@@ -10364,14 +10485,6 @@ function sameWorkspaceRepos(current, next) {
10364
10485
  const nextIds = next.map(identity).sort();
10365
10486
  return currentIds.every((value, index) => value === nextIds[index]);
10366
10487
  }
10367
- function isUniqueViolation(error) {
10368
- let current = error;
10369
- for (let depth = 0; current && depth < 6; depth += 1) {
10370
- if (typeof current === "object" && current !== null && "code" in current && current.code === "23505") return true;
10371
- current = typeof current === "object" && current !== null && "cause" in current ? current.cause : void 0;
10372
- }
10373
- return false;
10374
- }
10375
10488
  async function cleanupSnapshotBuilders(workspaceId, names) {
10376
10489
  if (names.length === 0) return;
10377
10490
  try {
@@ -10433,7 +10546,7 @@ async function createWorkspace(input) {
10433
10546
  await replaceWorkspaceRepos(db, id, recipe.repos);
10434
10547
  });
10435
10548
  } catch (error) {
10436
- if (isUniqueViolation(error)) throw new WorkspaceValidationError(`Workspace name already exists: ${recipe.name}`);
10549
+ if (isPostgresErrorCode(error, UNIQUE_VIOLATION)) throw new WorkspaceValidationError(`Workspace name already exists: ${recipe.name}`);
10437
10550
  throw error;
10438
10551
  }
10439
10552
  return await getWorkspace(executor.db(), id);
@@ -10465,7 +10578,7 @@ async function updateWorkspace(id, input) {
10465
10578
  if (!result) return void 0;
10466
10579
  await cleanupSnapshotBuilders(id, result.builderNames);
10467
10580
  } catch (error) {
10468
- if (isUniqueViolation(error)) throw new WorkspaceValidationError(`Workspace name already exists: ${recipe.name}`);
10581
+ if (isPostgresErrorCode(error, UNIQUE_VIOLATION)) throw new WorkspaceValidationError(`Workspace name already exists: ${recipe.name}`);
10469
10582
  throw error;
10470
10583
  }
10471
10584
  return await getWorkspace(executor.db(), id);
@@ -10618,18 +10731,14 @@ function createPluginState(plugin, adapter) {
10618
10731
  await state.connect();
10619
10732
  return await state.setIfNotExists(pluginStateKey(plugin, key), value, ttlMs);
10620
10733
  },
10621
- async withLock(key, ttlMs, callback) {
10734
+ async withLock(key, ttlMs, callback, options) {
10622
10735
  validatePluginStateKey(key);
10623
10736
  const state = getAdapter();
10624
10737
  await state.connect();
10625
- const lockKey = pluginStateKey(plugin, key);
10626
- const lock = await state.acquireLock(lockKey, ttlMs);
10627
- if (!lock) throw new Error(`Could not acquire plugin state lock for ${key}`);
10628
- try {
10629
- return await callback();
10630
- } finally {
10631
- await state.releaseLock(lock);
10632
- }
10738
+ return await withLock(state, pluginStateKey(plugin, key), callback, {
10739
+ ttlMs,
10740
+ waitMs: options?.waitMs
10741
+ });
10633
10742
  }
10634
10743
  };
10635
10744
  }
@@ -10997,13 +11106,12 @@ function buildSubscriptionId(input) {
10997
11106
  return `resub_${digest(matchKey ? `${input.namespace}\0${input.identifier}\0${input.conversationId}\0${eventKey}\0${matchKey}` : `${input.namespace}\0${input.identifier}\0${input.conversationId}\0${eventKey}`)}`;
10998
11107
  }
10999
11108
  async function withIndexLock$1(state, key, callback) {
11000
- const lock = await state.acquireLock(indexLockKey$1(key), INDEX_LOCK_TTL_MS);
11001
- if (!lock) throw new Error(`Could not acquire event index lock for ${key}`);
11002
- try {
11003
- return await callback();
11004
- } finally {
11005
- await state.releaseLock(lock);
11006
- }
11109
+ const attempt = await withLock(state, indexLockKey$1(key), callback, {
11110
+ ttlMs: INDEX_LOCK_TTL_MS,
11111
+ waitMs: INDEX_LOCK_TTL_MS
11112
+ });
11113
+ if (!attempt.acquired) throw new Error(`Could not acquire event index lock for ${key}`);
11114
+ return attempt.value;
11007
11115
  }
11008
11116
  async function addToIndex(state, key, subscriptionId, nowMs) {
11009
11117
  await withIndexLock$1(state, key, async () => {
@@ -11019,9 +11127,13 @@ async function removeFromIndex(state, key, subscriptionId, nowMs) {
11019
11127
  });
11020
11128
  }
11021
11129
  async function indexTtlMs(state, subscriptionIds, nowMs) {
11022
- const records = await Promise.all(subscriptionIds.map(async (id) => parseSubscription(await state.get(subscriptionKey(id)))));
11130
+ const records = await readSubscriptions(state, subscriptionIds);
11023
11131
  return ttlUntil(Math.max(nowMs, ...records.filter((record) => record !== void 0 && activeAt(record, nowMs)).map((record) => record.expiresAtMs)), nowMs);
11024
11132
  }
11133
+ /** Read many Watch records in one state round trip. */
11134
+ async function readSubscriptions(state, ids) {
11135
+ return (await getStateValues(state, ids.map(subscriptionKey))).map(parseSubscription);
11136
+ }
11025
11137
  function parseSubscription(value) {
11026
11138
  if (value === void 0 || value === null) return;
11027
11139
  return subscriptionSchema.parse(value);
@@ -11167,8 +11279,7 @@ async function listWatches(input) {
11167
11279
  const state = input.state ?? getStateAdapter();
11168
11280
  await state.connect();
11169
11281
  const nowMs = input.nowMs ?? Date.now();
11170
- const ids = await readSubscriptionIdIndex(state, conversationIndexKey(input.conversationId));
11171
- return (await Promise.all(ids.map(async (id) => parseSubscription(await state.get(subscriptionKey(id)))))).filter((record) => record !== void 0 && record.conversationId === input.conversationId && activeAt(record, nowMs)).sort((left, right) => left.createdAtMs - right.createdAtMs);
11282
+ return (await readSubscriptions(state, await readSubscriptionIdIndex(state, conversationIndexKey(input.conversationId)))).filter((record) => record !== void 0 && record.conversationId === input.conversationId && activeAt(record, nowMs)).sort((left, right) => left.createdAtMs - right.createdAtMs);
11172
11283
  }
11173
11284
  /**
11174
11285
  * Read one watch by id in any status. The caller checks that its Conversation
@@ -11226,8 +11337,7 @@ async function collectEventMatchKeys(input) {
11226
11337
  const keys = /* @__PURE__ */ new Set();
11227
11338
  const identifiers = new Set(input.identifiers.map((value) => value.trim()).filter(Boolean));
11228
11339
  for (const identifier of identifiers) {
11229
- const ids = await readSubscriptionIdIndex(state, resourceIndexKey(input.namespace, identifier));
11230
- const records = await Promise.all(ids.map(async (id) => parseSubscription(await state.get(subscriptionKey(id)))));
11340
+ const records = await readSubscriptions(state, await readSubscriptionIdIndex(state, resourceIndexKey(input.namespace, identifier)));
11231
11341
  for (const record of records) {
11232
11342
  if (!record) continue;
11233
11343
  if (record.namespace !== input.namespace) continue;
@@ -11244,8 +11354,7 @@ async function findMatchingWatches(input) {
11244
11354
  const state = input.state ?? getStateAdapter();
11245
11355
  await state.connect();
11246
11356
  const nowMs = input.nowMs ?? Date.now();
11247
- const ids = await readSubscriptionIdIndex(state, resourceIndexKey(input.namespace, input.identifier));
11248
- return (await Promise.all(ids.map(async (id) => parseSubscription(await state.get(subscriptionKey(id)))))).filter((record) => record !== void 0 && matchesEvent(record, {
11357
+ return (await readSubscriptions(state, await readSubscriptionIdIndex(state, resourceIndexKey(input.namespace, input.identifier)))).filter((record) => record !== void 0 && matchesEvent(record, {
11249
11358
  data: input.data,
11250
11359
  eventType: input.eventType,
11251
11360
  nowMs,
@@ -11633,8 +11742,9 @@ async function requireReviewItemAssignees(args) {
11633
11742
  if (args.assignees.everyone) throw new ToolInputError("A private item cannot be assigned to Everyone. Assign Users instead.");
11634
11743
  const creatorId = args.automationId ? await automationCreatorUserId(getDb(), args.automationId) : void 0;
11635
11744
  const others = args.assignees.userIds.filter((id) => id !== args.scope.user?.id && id !== creatorId);
11636
- const inConversation = /* @__PURE__ */ new Set();
11637
- for (const conversationId of new Set(args.conversationIds)) for (const id of await conversationParticipantUserIds(getDb(), conversationId, others)) inConversation.add(id);
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]));
11638
11748
  if (others.some((id) => !inConversation.has(id))) throw new ToolInputError("A private item can be assigned only to people in its Conversation.");
11639
11749
  }
11640
11750
  /**
@@ -11972,13 +12082,12 @@ async function listWaitingConversations(db, userId) {
11972
12082
  * User and a User who is not in the Conversation.
11973
12083
  */
11974
12084
  async function assigneeUserIds(db, identityIds, conversationId) {
11975
- const userIds = [];
11976
- for (const identityId of new Set(identityIds)) {
12085
+ const limit = pLimit(8);
12086
+ return (await Promise.all([...new Set(identityIds)].map((identityId) => limit(async () => {
11977
12087
  const user = (await readIdentityByIdFromSql(db, identityId))?.user;
11978
- if (!user) continue;
11979
- if ((await readConversationAccessFromSql(db, [conversationId], user)).get(conversationId)?.isParticipant) userIds.push(user.id);
11980
- }
11981
- return userIds;
12088
+ if (!user) return [];
12089
+ return (await readConversationAccessFromSql(db, [conversationId], user)).get(conversationId)?.isParticipant ? [user.id] : [];
12090
+ })))).flat();
11982
12091
  }
11983
12092
  /**
11984
12093
  * Connect a plugin to the review desk for one Conversation. Dedupe keys are
@@ -12424,49 +12533,475 @@ const notificationsTaskRegistration = {
12424
12533
  await notifyReply(context);
12425
12534
  } } }
12426
12535
  };
12427
- // src/chat/briefs/registration.ts
12428
- var registration_exports = /* @__PURE__ */ __exportAll({ setBriefsConfig: () => setBriefsConfig });
12429
- let configuredBriefs = {};
12430
- /** Replace app-level Brief settings and return the previous setting. */
12431
- function setBriefsConfig(config) {
12432
- const previous = { ...configuredBriefs };
12433
- configuredBriefs = config ? { ...config } : {};
12434
- return previous;
12536
+ // src/chat/turn-context-tag.ts
12537
+ /**
12538
+ * Canonical tag name for the runtime turn context block injected into Pi
12539
+ * messages. Shared between prompt assembly and turn context stripping to keep
12540
+ * both in sync without requiring the full prompt module.
12541
+ */
12542
+ const TURN_CONTEXT_TAG = "runtime-turn-context";
12543
+ /** Turn context section that only session context includes. */
12544
+ const SESSION_CONTEXT_SECTION_TAG = "runtime";
12545
+ /**
12546
+ * Named system prompt sections that list what the model can use now: the
12547
+ * skills, MCP catalogs, tool guidance, Workspaces, and the tools that a Code
12548
+ * Mode script can call. A Turn sends a changed section in a later system
12549
+ * message (`systemSectionsUpdate`). The Turn context of older Turns held
12550
+ * copies of them, which context compaction drops.
12551
+ */
12552
+ const CAPABILITY_SECTION_TAG = {
12553
+ availableSkills: "available-skills",
12554
+ activeMcpCatalogs: "active-mcp-catalogs",
12555
+ toolGuidance: "tool-guidance",
12556
+ workspaces: "workspaces",
12557
+ scriptTools: "script-tools"
12558
+ };
12559
+ /**
12560
+ * Turn context sections that are true only for the Turn that received them.
12561
+ * Context compaction removes them from the context of earlier Turns.
12562
+ */
12563
+ const REQUEST_CONTEXT_SECTION_TAG = {
12564
+ pluginContext: "plugin-context",
12565
+ conversationNotes: "conversation-notes",
12566
+ disabledTools: "disabled-tools",
12567
+ userCustomization: "user-customization",
12568
+ askerTimezone: "asker-timezone",
12569
+ turnInput: "turn-input"
12570
+ };
12571
+ /** 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"];
12573
+ function isRecord$1(value) {
12574
+ return typeof value === "object" && value !== null;
12435
12575
  }
12436
- /** Return whether automatic Brief generation is enabled. */
12437
- function isBriefsEnabled() {
12438
- return configuredBriefs.enabled === true;
12576
+ function userMessageContent(message) {
12577
+ return message.role === "user" && Array.isArray(message.content) ? message.content : void 0;
12439
12578
  }
12440
- /** Return enabled core task registrations: Briefs and reply notifications. */
12441
- function coreTaskRegistrations() {
12442
- return [...isBriefsEnabled() ? [briefsTaskRegistration] : [], ...readWebPushConfig() ? [notificationsTaskRegistration] : []];
12579
+ /** The message with other content parts, if it is a user message. */
12580
+ function withUserContent(message, content) {
12581
+ return message.role === "user" ? {
12582
+ ...message,
12583
+ content
12584
+ } : message;
12443
12585
  }
12444
- // src/chat/plugins/agent-hooks.ts
12445
- var agent_hooks_exports = /* @__PURE__ */ __exportAll({
12446
- applyPluginFormatMarkdown: () => applyPluginFormatMarkdown,
12447
- createPluginEventPublisher: () => createPluginEventPublisher,
12448
- createPluginHookRunner: () => createPluginHookRunner,
12449
- getPluginApiRoutes: () => getPluginApiRoutes,
12450
- getPluginOperationalReports: () => getPluginOperationalReports,
12451
- getPluginProfileReports: () => getPluginProfileReports,
12452
- getPluginRoutes: () => getPluginRoutes,
12453
- getPluginSlackConversationLink: () => getPluginSlackConversationLink,
12454
- getPluginSystemPromptContributions: () => getPluginSystemPromptContributions,
12455
- getPluginTools: () => getPluginTools,
12456
- getPluginUserPromptContributions: () => getPluginUserPromptContributions,
12457
- getPlugins: () => getPlugins,
12458
- getStaticPluginToolDefinitions: () => getStaticPluginToolDefinitions,
12459
- setPlugins: () => setPlugins,
12460
- validatePlugins: () => validatePlugins
12461
- });
12462
- let registeredPlugins = [];
12463
- const PLUGIN_NAME_RE = /^[a-z][a-z0-9-]*$/;
12464
- const PLUGIN_TASK_NAME_RE = /^[a-z][A-Za-z0-9]*$/;
12465
- const OPERATIONAL_REPORT_MAX_METRICS = 8;
12466
- const OPERATIONAL_REPORT_MAX_WIDGETS = 12;
12467
- const OPERATIONAL_REPORT_MAX_CHART_SERIES = 8;
12468
- const OPERATIONAL_REPORT_MAX_RECORD_SETS = 8;
12469
- const OPERATIONAL_REPORT_MAX_FIELDS = 8;
12586
+ function textPartValue(part) {
12587
+ return part.type === "text" && typeof part.text === "string" ? part.text : void 0;
12588
+ }
12589
+ function isRuntimeTurnContextPart(part) {
12590
+ const text = textPartValue(part);
12591
+ return text !== void 0 && RUNTIME_CONTEXT_TEXT_STARTS.some((start) => text.startsWith(start));
12592
+ }
12593
+ /**
12594
+ * Whether a user message carries a Turn input, not only context: a
12595
+ * `<current-instruction>` or a runtime input tag such as `<task>`.
12596
+ */
12597
+ function hasTurnInput(message) {
12598
+ return userMessageContent(message)?.some((part) => {
12599
+ const text = textPartValue(part);
12600
+ return text !== void 0 && (text.includes("<current-instruction") || isRuntimeInputText(text));
12601
+ }) ?? false;
12602
+ }
12603
+ /** Return whether the message is a Turn's context, paired with the instruction after it. */
12604
+ function isStandaloneRuntimeContextMessage(messages, index) {
12605
+ const message = messages[index];
12606
+ const next = messages[index + 1];
12607
+ return Boolean(message && next && userMessageContent(message) && userMessageContent(next) && message.timestamp === next.timestamp && !hasTurnInput(message) && hasTurnInput(next));
12608
+ }
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
+ /** Type guard for Pi SDK assistant messages. */
12617
+ function isAssistantMessage(value) {
12618
+ return isRecord$1(value) && value["role"] === "assistant";
12619
+ }
12620
+ /** Type guard for Pi SDK tool result messages. */
12621
+ function isToolResultMessage(value) {
12622
+ return isRecord$1(value) && value["role"] === "toolResult";
12623
+ }
12624
+ /** Check whether a tool result carries an error flag. */
12625
+ function isToolResultError(result) {
12626
+ return isRecord$1(result) && Boolean(result["isError"]);
12627
+ }
12628
+ /** Extract the tool name from a raw tool result message. */
12629
+ function normalizeToolNameFromResult(result) {
12630
+ if (!isRecord$1(result)) return void 0;
12631
+ const { name, toolName } = result;
12632
+ if (typeof toolName === "string" && toolName.length > 0) return toolName;
12633
+ if (typeof name === "string" && name.length > 0) return name;
12634
+ }
12635
+ /** Extract role string from a raw Pi message. */
12636
+ function getPiMessageRole(value) {
12637
+ return isRecord$1(value) && typeof value["role"] === "string" ? value["role"] : void 0;
12638
+ }
12639
+ /** Return whether Pi can continue directly from the current history tail. */
12640
+ function isContinuablePiBoundary(messages) {
12641
+ let end = messages.length;
12642
+ while (end > 0 && getPiMessageRole(messages[end - 1]) === "system") end -= 1;
12643
+ const lastRole = getPiMessageRole(messages[end - 1]);
12644
+ return lastRole === "user" || lastRole === "toolResult";
12645
+ }
12646
+ /** Concatenate text content parts from an assistant message. */
12647
+ function extractAssistantText(message) {
12648
+ return (message.content ?? []).flatMap((part) => part.type === "text" && typeof part.text === "string" ? [part.text] : []).join("\n");
12649
+ }
12650
+ /** Return assistant messages that belong to the terminal post-tool reply phase. */
12651
+ function getTerminalAssistantMessages(messages) {
12652
+ let lastNonAssistantIndex = -1;
12653
+ for (let index = messages.length - 1; index >= 0; index -= 1) if (!isAssistantMessage(messages[index])) {
12654
+ lastNonAssistantIndex = index;
12655
+ break;
12656
+ }
12657
+ return messages.slice(lastNonAssistantIndex + 1).filter(isAssistantMessage);
12658
+ }
12659
+ /** Remove trailing assistant messages before committing a resumable boundary. */
12660
+ function trimTrailingAssistantMessages(messages) {
12661
+ let end = messages.length;
12662
+ while (end > 0 && getPiMessageRole(messages[end - 1]) === "assistant") end -= 1;
12663
+ return end === messages.length ? [...messages] : messages.slice(0, end);
12664
+ }
12665
+ /** Return whether Pi history already carries session bootstrap context. */
12666
+ function hasRuntimeTurnContext(messages) {
12667
+ return messages.some((message, index) => isStandaloneRuntimeContextMessage(messages, index) || userMessageContent(message)?.some(isRuntimeTurnContextPart));
12668
+ }
12669
+ /** Keep only volatile bootstrap messages needed by an in-turn context replacement. */
12670
+ function retainRuntimeTurnContext(messages) {
12671
+ return messages.flatMap((message, index) => {
12672
+ if (isStandaloneRuntimeContextMessage(messages, index)) return [message];
12673
+ const runtimeContent = userMessageContent(message)?.filter(isRuntimeTurnContextPart) ?? [];
12674
+ return runtimeContent.length > 0 ? [withUserContent(message, runtimeContent)] : [];
12675
+ });
12676
+ }
12677
+ /**
12678
+ * Reduce a runtime user-turn prompt to only the current turn's instruction.
12679
+ *
12680
+ * Live user prompts embed prior-thread context as `<thread-context
12681
+ * authority="evidence-only">` (or legacy transcript/background blocks) beside
12682
+ * the `<current-instruction>` block. Those blocks hold other participants'
12683
+ * verbatim messages, so completed-run projections consumed by plugins must
12684
+ * expose only the instruction authored by this turn's actor — otherwise
12685
+ * per-entry provenance can be defeated by reading another user's text out of an
12686
+ * instruction-authority entry. Prior thread context is projected separately as
12687
+ * per-author context-authority entries, so dropping it here is non-lossy for
12688
+ * plugins. This is projection-only; it never touches what the model sees during
12689
+ * a live run.
12690
+ */
12691
+ function instructionTextForProjection(text) {
12692
+ const withoutContext = text.replace(EMBEDDED_THREAD_CONTEXT_PATTERN, "").trim();
12693
+ return unwrapCurrentInstruction(withoutContext) ?? withoutContext;
12694
+ }
12695
+ /**
12696
+ * Return the projected input text carried by one user message. Each Turn
12697
+ * input is its own content part: a `<current-instruction>` gives its body,
12698
+ * and a runtime input tag stays as it is. Other parts, such as attachments,
12699
+ * are dropped. A message with no input part keeps the projection of all its
12700
+ * text.
12701
+ */
12702
+ function getUserMessageInstructionText(message) {
12703
+ if (message.role !== "user") return "";
12704
+ const texts = typeof message.content === "string" ? [message.content] : message.content.flatMap((part) => textPartValue(part) ?? []);
12705
+ const inputs = texts.flatMap((text) => {
12706
+ const withoutContext = text.replace(EMBEDDED_THREAD_CONTEXT_PATTERN, "").trim();
12707
+ if (isRuntimeInputText(withoutContext)) return [readParentAgentTask(withoutContext) ?? withoutContext];
12708
+ const instruction = unwrapCurrentInstruction(withoutContext);
12709
+ return instruction === void 0 ? [] : [instruction.trim()];
12710
+ });
12711
+ if (inputs.length > 0) return inputs.filter(Boolean).join("\n\n");
12712
+ return instructionTextForProjection(texts.join("\n")).trim();
12713
+ }
12714
+ /** Remove runtime context from a non-model projection or explicit replacement. */
12715
+ function stripRuntimeTurnContext(messages) {
12716
+ return messages.flatMap((message, index) => {
12717
+ if (isStandaloneRuntimeContextMessage(messages, index)) return [];
12718
+ const content = userMessageContent(message);
12719
+ if (!content) return [message];
12720
+ const nextContent = content.filter((part) => !isRuntimeTurnContextPart(part));
12721
+ if (nextContent.length === content.length) return [message];
12722
+ if (nextContent.length === 0) return [];
12723
+ return [withUserContent(message, nextContent)];
12724
+ });
12725
+ }
12726
+ // src/chat/conversations/sql/message-json.ts
12727
+ const UNICODE_ESCAPE = String.raw`\u`;
12728
+ const UNICODE_ESCAPE_PATTERN = String.raw`(?<!\\)((?:\\\\)*)\\u[0-9a-fA-F]{4}`;
12729
+ const UNICODE_ESCAPE_REPLACEMENT = String.raw`\1`;
12730
+ /**
12731
+ * Cast the stored JSON string of an agent history message to jsonb. One
12732
+ * message that jsonb rejects would fail its whole query, so the cast drops
12733
+ * every Unicode escape. JSON.stringify writes them only for control
12734
+ * characters and lone surrogates.
12735
+ */
12736
+ function storedMessageJson(messageText) {
12737
+ return sql`CASE
12738
+ WHEN strpos(${messageText}, ${UNICODE_ESCAPE}) = 0 THEN (${messageText})::jsonb
12739
+ ELSE regexp_replace(${messageText}, ${UNICODE_ESCAPE_PATTERN}, ${UNICODE_ESCAPE_REPLACEMENT}, 'g')::jsonb
12740
+ END`;
12741
+ }
12742
+ // src/chat/conversations/event-search-text.ts
12743
+ /**
12744
+ * The searchable text of one Conversation event: the words that a person or
12745
+ * the agent wrote, and the tool calls and results. Runtime context parts,
12746
+ * model reasoning, images, usage, and ids are not searchable text.
12747
+ *
12748
+ * One SQL expression reads the text for keyword search, embeddings, and
12749
+ * excerpts, so the three always see the same words.
12750
+ */
12751
+ /** Event types that have searchable text. Other events never match a query. */
12752
+ const SEARCHABLE_EVENT_TYPES = [
12753
+ "message",
12754
+ "message_updated",
12755
+ "user_message",
12756
+ "assistant_message",
12757
+ "tool_result"
12758
+ ];
12759
+ const EXCERPT_CHARS = 400;
12760
+ const EXCERPT_LEAD_CHARS = 120;
12761
+ const MAX_EXCERPT_TERMS = 16;
12762
+ const AGENT_HISTORY_TEXT_PATHS = [
12763
+ "lax $.content ? (@.type() == \"string\")",
12764
+ "lax $.toolName ? (@.type() == \"string\")",
12765
+ `lax $.content[*] ? (@.type == "text" && ${RUNTIME_CONTEXT_TEXT_STARTS.map((start) => `!(@.text starts with ${JSON.stringify(start)})`).join(" && ")}).text`,
12766
+ "lax $.content[*] ? (@.type == \"toolCall\").name",
12767
+ "lax $.content[*] ? (@.type == \"toolCall\").arguments.** ? (@.type() == \"string\" || @.type() == \"number\")"
12768
+ ];
12769
+ /** SQL condition: the row is an agent message that calls a tool. */
12770
+ function callsToolSql() {
12771
+ const { payload, type } = juniorConversationEvents;
12772
+ return sql`(${type} = 'assistant_message' AND jsonb_path_exists(
12773
+ coalesce(${storedMessageJson(sql`${payload}->>'message'`)}, ${payload}),
12774
+ 'lax $.content[*] ? (@.type == "toolCall")'
12775
+ ))`;
12776
+ }
12777
+ /**
12778
+ * SQL expression for the searchable text of a `junior_conversation_events`
12779
+ * row. Null for an event without searchable text.
12780
+ */
12781
+ function eventSearchTextSql() {
12782
+ const { payload, type } = juniorConversationEvents;
12783
+ const message = sql.raw("searchable_message.value");
12784
+ const parts = sql.join(AGENT_HISTORY_TEXT_PATHS.map((path) => sql`select jsonb_path_query(${message}, ${path}::jsonpath)`), sql` union all `);
12785
+ return sql`CASE
12786
+ WHEN ${type} IN ('message', 'message_updated') THEN ${payload}->>'text'
12787
+ WHEN ${type} IN ('user_message', 'assistant_message', 'tool_result') THEN (
12788
+ SELECT string_agg(part #>> '{}', E'\\n')
12789
+ FROM (SELECT coalesce(${storedMessageJson(sql`${payload}->>'message'`)}, ${payload}) AS value) searchable_message
12790
+ CROSS JOIN LATERAL (${parts}) searchable_parts(part)
12791
+ )
12792
+ END`;
12793
+ }
12794
+ /** Split a query into lowercase words for excerpts, with path parts too. */
12795
+ function excerptTerms(query) {
12796
+ const words = query.toLowerCase().split(/\s+/).map((word) => word.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, ""));
12797
+ const parts = words.flatMap((word) => word.split(/[/#\\:@?&=]+/));
12798
+ return [.../* @__PURE__ */ new Set([...words, ...parts])].filter((term) => term.length >= 2).slice(0, MAX_EXCERPT_TERMS);
12799
+ }
12800
+ function countOccurrences(haystack, needle) {
12801
+ let count = 0;
12802
+ for (let index = haystack.indexOf(needle); index !== -1; index = haystack.indexOf(needle, index + needle.length)) count += 1;
12803
+ return count;
12804
+ }
12805
+ /**
12806
+ * Return a short window of the text around the most specific query word:
12807
+ * the word that occurs least often, and the longest on a tie. Text without a
12808
+ * query word, such as a match by meaning, gives its start.
12809
+ */
12810
+ function eventExcerpt(text, terms) {
12811
+ const lower = text.toLowerCase();
12812
+ const best = terms.map((term) => ({
12813
+ term,
12814
+ count: countOccurrences(lower, term)
12815
+ })).filter(({ count }) => count > 0).sort((left, right) => left.count - right.count || right.term.length - left.term.length)[0];
12816
+ const position = best ? lower.indexOf(best.term) : 0;
12817
+ const start = Math.max(0, position - EXCERPT_LEAD_CHARS);
12818
+ const end = Math.min(text.length, start + EXCERPT_CHARS);
12819
+ return `${start > 0 ? "…" : ""}${text.slice(start, end).trim()}${end < text.length ? "…" : ""}`;
12820
+ }
12821
+ // src/chat/conversations/event-lexemes.ts
12822
+ /**
12823
+ * Stored full-text lexemes of searchable events, so keyword search reads
12824
+ * them instead of parsing every event on each query. The event search task
12825
+ * stores them after each completed Turn, newest events first. Keyword search
12826
+ * computes the lexemes of an event with no stored row, so old history and
12827
+ * apps without the task stay searchable.
12828
+ */
12829
+ const MAX_SEARCHED_EVENT_CHARS = 2e5;
12830
+ const MAX_EVENTS_PER_RUN$1 = 2e3;
12831
+ const LEXEME_SEPARATORS = "/#\\:@?&=";
12832
+ const NUMBER_PUNCTUATION = "(?<=[0-9])[.-]|[.-](?=[0-9])";
12833
+ const LEXEME_SEPARATOR_SPACES = " ".repeat(8);
12834
+ /**
12835
+ * Lexemes of query or event text, split the same way for both. Text that is
12836
+ * null gives no lexemes, so an event without text is still stored once.
12837
+ */
12838
+ function lexemesSql(text) {
12839
+ return sql`to_tsvector('english', translate(regexp_replace(coalesce(${text}, ''), ${NUMBER_PUNCTUATION}, ' ', 'g'), ${LEXEME_SEPARATORS}, ${LEXEME_SEPARATOR_SPACES}))`;
12840
+ }
12841
+ /** Match event seqs against one array parameter, however many there are. */
12842
+ function seqIn(seqs) {
12843
+ return sql`${juniorConversationEvents.seq} = ANY(${`{${seqs.join(",")}}`}::integer[])`;
12844
+ }
12845
+ /** Searchable text of the current event row, as far as search reads it. */
12846
+ function searchedEventTextSql() {
12847
+ return sql`left(${eventSearchTextSql()}, ${MAX_SEARCHED_EVENT_CHARS})`;
12848
+ }
12849
+ /**
12850
+ * Store the lexemes of the newest searchable events of one Conversation that
12851
+ * have none. Return how many it stored. Retries are safe: a stored row is
12852
+ * kept.
12853
+ */
12854
+ async function storeConversationEventLexemes(db, conversationId) {
12855
+ const events = juniorConversationEvents;
12856
+ const stored = juniorConversationEventLexemes;
12857
+ const unstored = await db.select({ seq: events.seq }).from(events).leftJoin(stored, and(eq(stored.conversationId, events.conversationId), eq(stored.seq, events.seq))).where(and(eq(events.conversationId, conversationId), inArray(events.type, [...SEARCHABLE_EVENT_TYPES]), isNull(stored.seq))).orderBy(desc(events.seq)).limit(MAX_EVENTS_PER_RUN$1);
12858
+ if (unstored.length === 0) return 0;
12859
+ return (await db.insert(stored).select(db.select({
12860
+ conversationId: events.conversationId,
12861
+ seq: events.seq,
12862
+ lexemes: sql`${lexemesSql(searchedEventTextSql())}`.as("lexemes"),
12863
+ createdAt: sql`now()`.as("created_at")
12864
+ }).from(events).where(and(eq(events.conversationId, conversationId), seqIn(unstored.map((row) => row.seq))))).onConflictDoNothing().returning({ seq: stored.seq })).length;
12865
+ }
12866
+ // src/chat/conversations/event-embedding.ts
12867
+ const MAX_EMBEDDED_CHARS = 8e3;
12868
+ const MAX_EVENTS_PER_RUN = 256;
12869
+ const EMBEDDING_BATCH_SIZE = 32;
12870
+ const EMBEDDING_LOCK_TTL_MS = 6e5;
12871
+ /**
12872
+ * Embed the newest searchable events of one Conversation that have no
12873
+ * vector of the embedder's model. Return how many it stored.
12874
+ */
12875
+ async function embedConversationEvents(db, embedder, conversationId) {
12876
+ const events = juniorConversationEvents;
12877
+ const embeddings = juniorConversationEventEmbeddings;
12878
+ const text = sql`left(${eventSearchTextSql()}, ${MAX_EMBEDDED_CHARS})`;
12879
+ return (await refreshEmbeddings({
12880
+ batchSize: EMBEDDING_BATCH_SIZE,
12881
+ embedder,
12882
+ maxItems: MAX_EVENTS_PER_RUN,
12883
+ listMissing: async ({ after, limit }) => await db.select({
12884
+ seq: events.seq,
12885
+ text
12886
+ }).from(events).leftJoin(embeddings, and(eq(embeddings.conversationId, events.conversationId), eq(embeddings.seq, events.seq), eq(embeddings.provider, embedder.provider), eq(embeddings.model, embedder.model))).where(and(eq(events.conversationId, conversationId), inArray(events.type, [...SEARCHABLE_EVENT_TYPES]), isNull(embeddings.seq), sql`${eventSearchTextSql()} ~ '[^[:space:]]'`, after ? lt(events.seq, after.seq) : void 0)).orderBy(desc(events.seq)).limit(limit),
12887
+ write: async (rows, batch) => {
12888
+ await db.insert(embeddings).values(rows.map(({ item, vector }) => ({
12889
+ conversationId,
12890
+ dimensions: batch.dimensions,
12891
+ embedding: vector,
12892
+ model: batch.model,
12893
+ provider: batch.provider,
12894
+ seq: item.seq
12895
+ }))).onConflictDoUpdate({
12896
+ target: [embeddings.conversationId, embeddings.seq],
12897
+ set: {
12898
+ dimensions: sql`excluded.dimensions`,
12899
+ embedding: sql`excluded.embedding`,
12900
+ model: sql`excluded.model`,
12901
+ provider: sql`excluded.provider`,
12902
+ createdAt: sql`now()`
12903
+ }
12904
+ });
12905
+ }
12906
+ })).embedded;
12907
+ }
12908
+ /**
12909
+ * Core task registration that stores lexemes after each completed Turn and,
12910
+ * when `embedEvents` is set, embeds events too.
12911
+ */
12912
+ function eventSearchTaskRegistration(options) {
12913
+ return {
12914
+ manifest: {
12915
+ name: "event-search",
12916
+ displayName: "Event search",
12917
+ description: "Lexemes and embeddings for Conversation history search"
12918
+ },
12919
+ tasks: { indexEvents: { async run(context) {
12920
+ const run = await context.run.load();
12921
+ await context.state.withLock(`event-search:${run.conversationId}`, EMBEDDING_LOCK_TTL_MS, async () => {
12922
+ const [lexemeResult, embeddingResult] = await Promise.allSettled([storeConversationEventLexemes(getDb(), run.conversationId), options.embedEvents ? embedConversationEvents(getDb(), createConversationEmbedder({
12923
+ cost: {
12924
+ conversationId: run.conversationId,
12925
+ turnId: run.runId
12926
+ },
12927
+ operation: "conversation_embedding"
12928
+ }), run.conversationId) : 0]);
12929
+ if (lexemeResult.status === "rejected") throw lexemeResult.reason;
12930
+ if (embeddingResult.status === "rejected") throw embeddingResult.reason;
12931
+ context.log.info("Conversation events indexed", {
12932
+ conversationId: run.conversationId,
12933
+ embedded: embeddingResult.value,
12934
+ lexemes: lexemeResult.value
12935
+ });
12936
+ });
12937
+ } } }
12938
+ };
12939
+ }
12940
+ // src/chat/briefs/registration.ts
12941
+ var registration_exports = /* @__PURE__ */ __exportAll({
12942
+ setBriefsConfig: () => setBriefsConfig,
12943
+ setEventEmbeddingsConfig: () => setEventEmbeddingsConfig
12944
+ });
12945
+ let configuredBriefs = {};
12946
+ let configuredEventEmbeddings = {};
12947
+ /** Replace app-level Brief settings and return the previous setting. */
12948
+ function setBriefsConfig(config) {
12949
+ const previous = { ...configuredBriefs };
12950
+ configuredBriefs = config ? { ...config } : {};
12951
+ return previous;
12952
+ }
12953
+ /** Return whether automatic Brief generation is enabled. */
12954
+ function isBriefsEnabled() {
12955
+ return configuredBriefs.enabled === true;
12956
+ }
12957
+ /** Replace app-level event embedding settings and return the previous setting. */
12958
+ function setEventEmbeddingsConfig(config) {
12959
+ const previous = { ...configuredEventEmbeddings };
12960
+ configuredEventEmbeddings = config ? { ...config } : {};
12961
+ return previous;
12962
+ }
12963
+ /** Return whether event embeddings and meaning search are enabled. */
12964
+ function isEventEmbeddingsEnabled() {
12965
+ return configuredEventEmbeddings.enabled === true;
12966
+ }
12967
+ /**
12968
+ * Return enabled core task registrations: Briefs, event search, and reply
12969
+ * notifications. Event search always stores lexemes, which cost no provider
12970
+ * call. It embeds events only when event embeddings are enabled.
12971
+ */
12972
+ function coreTaskRegistrations() {
12973
+ return [
12974
+ ...isBriefsEnabled() ? [briefsTaskRegistration] : [],
12975
+ eventSearchTaskRegistration({ embedEvents: isEventEmbeddingsEnabled() }),
12976
+ ...readWebPushConfig() ? [notificationsTaskRegistration] : []
12977
+ ];
12978
+ }
12979
+ // src/chat/plugins/agent-hooks.ts
12980
+ var agent_hooks_exports = /* @__PURE__ */ __exportAll({
12981
+ applyPluginFormatMarkdown: () => applyPluginFormatMarkdown,
12982
+ createPluginEventPublisher: () => createPluginEventPublisher,
12983
+ createPluginHookRunner: () => createPluginHookRunner,
12984
+ getPluginApiRoutes: () => getPluginApiRoutes,
12985
+ getPluginOperationalReports: () => getPluginOperationalReports,
12986
+ getPluginProfileReports: () => getPluginProfileReports,
12987
+ getPluginRoutes: () => getPluginRoutes,
12988
+ getPluginSlackConversationLink: () => getPluginSlackConversationLink,
12989
+ getPluginSystemPromptContributions: () => getPluginSystemPromptContributions,
12990
+ getPluginTools: () => getPluginTools,
12991
+ getPluginUserPromptContributions: () => getPluginUserPromptContributions,
12992
+ getPlugins: () => getPlugins,
12993
+ getStaticPluginToolDefinitions: () => getStaticPluginToolDefinitions,
12994
+ setPlugins: () => setPlugins,
12995
+ validatePlugins: () => validatePlugins
12996
+ });
12997
+ let registeredPlugins = [];
12998
+ const PLUGIN_NAME_RE = /^[a-z][a-z0-9-]*$/;
12999
+ const PLUGIN_TASK_NAME_RE = /^[a-z][A-Za-z0-9]*$/;
13000
+ const OPERATIONAL_REPORT_MAX_METRICS = 8;
13001
+ const OPERATIONAL_REPORT_MAX_WIDGETS = 12;
13002
+ const OPERATIONAL_REPORT_MAX_CHART_SERIES = 8;
13003
+ const OPERATIONAL_REPORT_MAX_RECORD_SETS = 8;
13004
+ const OPERATIONAL_REPORT_MAX_FIELDS = 8;
12470
13005
  const OPERATIONAL_REPORT_MAX_RECORDS = 25;
12471
13006
  const OPERATIONAL_REPORT_MAX_LABEL_LENGTH = 80;
12472
13007
  const OPERATIONAL_REPORT_MAX_VALUE_LENGTH = 160;
@@ -12701,19 +13236,40 @@ function applyPluginFormatMarkdown(text, format = {}) {
12701
13236
  }
12702
13237
  return transformed;
12703
13238
  }
13239
+ /**
13240
+ * Run one hook of each plugin at once. `start` gives the call for a plugin,
13241
+ * or nothing when the plugin has no such hook. The outcomes keep plugin
13242
+ * order, so budgets and output order do not depend on which hook ends first.
13243
+ */
13244
+ async function runPluginHooksAtOnce(plugins, start) {
13245
+ const limit = pLimit(8);
13246
+ return await Promise.all(plugins.flatMap((plugin) => {
13247
+ const run = start(plugin);
13248
+ return run ? [limit(run).then((value) => ({
13249
+ plugin,
13250
+ value
13251
+ }), (error) => ({
13252
+ error,
13253
+ plugin
13254
+ }))] : [];
13255
+ }));
13256
+ }
12704
13257
  /** Collect stable plugin prompt contributions for the static system prompt. */
12705
13258
  async function getPluginSystemPromptContributions(platform) {
12706
13259
  const contributions = [];
12707
13260
  let totalChars = 0;
12708
- for (const plugin of getPlugins()) {
12709
- const pluginName = plugin.manifest.name;
13261
+ const outcomes = await runPluginHooksAtOnce(getPlugins(), (plugin) => {
12710
13262
  const hook = plugin.hooks?.systemPrompt;
12711
- if (!hook) continue;
13263
+ return hook && (() => hook({
13264
+ ...systemPromptPluginContext(plugin),
13265
+ platform
13266
+ }));
13267
+ });
13268
+ for (const outcome of outcomes) {
13269
+ const pluginName = outcome.plugin.manifest.name;
12712
13270
  try {
12713
- const pluginContributions = await hook({
12714
- ...systemPromptPluginContext(plugin),
12715
- platform
12716
- });
13271
+ if ("error" in outcome) throw outcome.error;
13272
+ const pluginContributions = outcome.value;
12717
13273
  const result = systemPromptMessageArraySchema.safeParse(pluginContributions);
12718
13274
  if (!result.success) {
12719
13275
  logInvalidPromptContributions({
@@ -12749,12 +13305,15 @@ async function getPluginUserPromptContributions(args) {
12749
13305
  const contributions = [];
12750
13306
  let totalChars = 0;
12751
13307
  let totalContextBytes = 0;
12752
- for (const plugin of getPlugins()) {
12753
- const pluginName = plugin.manifest.name;
13308
+ const outcomes = await runPluginHooksAtOnce(getPlugins(), (plugin) => {
12754
13309
  const hook = plugin.hooks?.userPrompt;
12755
- if (!hook) continue;
13310
+ return hook && (() => withPluginHookSpan(plugin.manifest.name, "userPrompt", async (setSpanAttributes) => await hook({ ...invocationPluginContext(plugin, args.context, setSpanAttributes, args.turnId) })));
13311
+ });
13312
+ for (const outcome of outcomes) {
13313
+ const pluginName = outcome.plugin.manifest.name;
12756
13314
  try {
12757
- const rawResult = await withPluginHookSpan(pluginName, "userPrompt", async (setSpanAttributes) => await hook({ ...invocationPluginContext(plugin, args.context, setSpanAttributes, args.turnId) }));
13315
+ if ("error" in outcome) throw outcome.error;
13316
+ const rawResult = outcome.value;
12758
13317
  if (rawResult === void 0) continue;
12759
13318
  if (!Array.isArray(rawResult)) {
12760
13319
  logInvalidPromptContributions({
@@ -13282,18 +13841,20 @@ function failedOperationalReport(args) {
13282
13841
  /** Collect read-only operational summaries exposed by plugins. */
13283
13842
  async function getPluginOperationalReports(nowMs) {
13284
13843
  const reports = [];
13285
- for (const plugin of [...coreTaskRegistrations(), ...getPlugins()]) {
13286
- const pluginName = plugin.manifest.name;
13844
+ const outcomes = await runPluginHooksAtOnce([...coreTaskRegistrations(), ...getPlugins()], (plugin) => {
13287
13845
  const hook = plugin.hooks?.operationalReport;
13288
- if (!hook) continue;
13846
+ return hook && (() => hook({
13847
+ ...basePluginContext$1(plugin),
13848
+ eventStats: createPluginConversationEventStats(plugin, () => nowMs),
13849
+ nowMs,
13850
+ state: pluginReadState(createPluginState(plugin.manifest.name))
13851
+ }));
13852
+ });
13853
+ for (const outcome of outcomes) {
13854
+ const pluginName = outcome.plugin.manifest.name;
13289
13855
  try {
13290
- const state = createPluginState(pluginName);
13291
- const report = await hook({
13292
- ...basePluginContext$1(plugin),
13293
- eventStats: createPluginConversationEventStats(plugin, () => nowMs),
13294
- nowMs,
13295
- state: pluginReadState(state)
13296
- });
13856
+ if ("error" in outcome) throw outcome.error;
13857
+ const report = outcome.value;
13297
13858
  if (!report) continue;
13298
13859
  reports.push(sanitizeOperationalReport({
13299
13860
  pluginName,
@@ -13312,19 +13873,21 @@ async function getPluginOperationalReports(nowMs) {
13312
13873
  /** Collect person-scoped plugin reports for one profile subject. */
13313
13874
  async function getPluginProfileReports(args) {
13314
13875
  const reports = [];
13315
- for (const plugin of getPlugins()) {
13316
- const pluginName = plugin.manifest.name;
13876
+ const outcomes = await runPluginHooksAtOnce(getPlugins(), (plugin) => {
13317
13877
  const hook = plugin.hooks?.profileReport;
13318
- if (!hook) continue;
13878
+ return hook && (() => hook({
13879
+ ...basePluginContext$1(plugin),
13880
+ nowMs: args.nowMs,
13881
+ state: pluginReadState(createPluginState(plugin.manifest.name)),
13882
+ subject: args.subject,
13883
+ viewer: args.viewer
13884
+ }));
13885
+ });
13886
+ for (const outcome of outcomes) {
13887
+ const pluginName = outcome.plugin.manifest.name;
13319
13888
  try {
13320
- const state = createPluginState(pluginName);
13321
- const report = await hook({
13322
- ...basePluginContext$1(plugin),
13323
- nowMs: args.nowMs,
13324
- state: pluginReadState(state),
13325
- subject: args.subject,
13326
- viewer: args.viewer
13327
- });
13889
+ if ("error" in outcome) throw outcome.error;
13890
+ const report = outcome.value;
13328
13891
  if (!report) continue;
13329
13892
  reports.push(sanitizeOperationalReport({
13330
13893
  pluginName,
@@ -13545,7 +14108,8 @@ async function selectPluginGrant(input) {
13545
14108
  ...input.graphql ? { graphql: input.graphql } : void 0,
13546
14109
  method: input.method,
13547
14110
  ...input.operation ? { operation: input.operation } : void 0,
13548
- url: input.upstreamUrl.toString()
14111
+ url: input.upstreamUrl.toString(),
14112
+ ...input.withoutCredential ? { withoutCredential: true } : void 0
13549
14113
  }
13550
14114
  });
13551
14115
  return result === void 0 ? void 0 : parseGrant(result, plugin.manifest.name);
@@ -13843,6 +14407,7 @@ async function selectSandboxEgressGrant(input) {
13843
14407
  }
13844
14408
  if (!hasEgressCredentialHooks(input.provider)) return defaultGrantForProvider(input);
13845
14409
  const pluginGrant = await selectPluginGrant({
14410
+ ...input.withoutCredential ? { withoutCredential: true } : void 0,
13846
14411
  ...input.bodyText !== void 0 ? { bodyText: input.bodyText } : void 0,
13847
14412
  ...input.gitPush ? { gitPush: input.gitPush } : void 0,
13848
14413
  ...input.graphql ? { graphql: input.graphql } : void 0,
@@ -13851,6 +14416,7 @@ async function selectSandboxEgressGrant(input) {
13851
14416
  method: input.method,
13852
14417
  upstreamUrl: input.upstreamUrl
13853
14418
  });
14419
+ if (input.withoutCredential) return defaultGrantForProvider(input);
13854
14420
  if (!pluginGrant) {
13855
14421
  if (hasGenericCredentials(input.provider)) return defaultGrantForProvider(input);
13856
14422
  throw new Error(`Plugin "${input.provider}" grantForEgress must return a grant for sandbox egress`);
@@ -13948,6 +14514,47 @@ async function sandboxEgressCredentialLease(provider, selection, context) {
13948
14514
  function hasSandboxEgressLeaseTransformForHost(lease, host) {
13949
14515
  return lease.headerTransforms.some((transform) => matchesSandboxEgressDomain(host, transform.domain));
13950
14516
  }
14517
+ // src/chat/egress/response-text.ts
14518
+ const RESPONSE_BODY_TEXT_LIMIT_BYTES = 65536;
14519
+ function responseContentLength(upstream) {
14520
+ const raw = upstream.headers.get("content-length");
14521
+ if (!raw) return;
14522
+ const parsed = Number(raw);
14523
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
14524
+ }
14525
+ /** Read a copy of a response body as text, or undefined past `maxBytes`. */
14526
+ async function responseTextWithinLimit(upstream, maxBytes) {
14527
+ const limit = Math.min(Math.max(0, Math.floor(maxBytes)), RESPONSE_BODY_TEXT_LIMIT_BYTES);
14528
+ if (limit <= 0) return;
14529
+ const contentLength = responseContentLength(upstream);
14530
+ if (contentLength !== void 0 && contentLength > limit) return;
14531
+ let clone;
14532
+ try {
14533
+ clone = upstream.clone();
14534
+ } catch {
14535
+ return;
14536
+ }
14537
+ const body = clone.body;
14538
+ if (!body) return "";
14539
+ const chunks = [];
14540
+ let bytes = 0;
14541
+ try {
14542
+ for await (const value of body) {
14543
+ bytes += value.byteLength;
14544
+ if (bytes > limit) return;
14545
+ chunks.push(value);
14546
+ }
14547
+ } catch {
14548
+ return;
14549
+ }
14550
+ const combined = new Uint8Array(bytes);
14551
+ let offset = 0;
14552
+ for (const chunk of chunks) {
14553
+ combined.set(chunk, offset);
14554
+ offset += chunk.byteLength;
14555
+ }
14556
+ return new TextDecoder().decode(combined);
14557
+ }
13951
14558
  // src/chat/sandbox/egress/signals.ts
13952
14559
  /** Starts the body of the egress proxy's response for a missing credential. */
13953
14560
  const SANDBOX_EGRESS_AUTH_REQUIRED_MARKER = "junior-auth-required";
@@ -13979,7 +14586,6 @@ const DECODED_RESPONSE_HEADERS = /* @__PURE__ */ new Set(["content-encoding", "c
13979
14586
  const UPSTREAM_TOKEN_REJECTION_STATUS = 401;
13980
14587
  const UPSTREAM_PERMISSION_REJECTION_STATUS = 403;
13981
14588
  const GRANT_SELECTION_BODY_TEXT_LIMIT_BYTES = 65536;
13982
- const RESPONSE_BODY_TEXT_LIMIT_BYTES = 65536;
13983
14589
  function authRequiredResult(authRequired, responseMessage = authRequired.message) {
13984
14590
  return {
13985
14591
  authRequired,
@@ -14100,54 +14706,6 @@ function grantSelectionBodyText(body) {
14100
14706
  if (body.byteLength > GRANT_SELECTION_BODY_TEXT_LIMIT_BYTES) throw new EgressPolicyDenied("GitHub pull request review request body is too large to inspect before issuing credentials.");
14101
14707
  return new TextDecoder().decode(body);
14102
14708
  }
14103
- function responseContentLength(upstream) {
14104
- const raw = upstream.headers.get("content-length");
14105
- if (!raw) return;
14106
- const parsed = Number(raw);
14107
- return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : void 0;
14108
- }
14109
- async function responseTextWithinLimit(upstream, maxBytes) {
14110
- const limit = Math.min(Math.max(0, Math.floor(maxBytes)), RESPONSE_BODY_TEXT_LIMIT_BYTES);
14111
- if (limit <= 0) return;
14112
- const contentLength = responseContentLength(upstream);
14113
- if (contentLength !== void 0 && contentLength > limit) return;
14114
- let clone;
14115
- try {
14116
- clone = upstream.clone();
14117
- } catch {
14118
- return;
14119
- }
14120
- const body = clone.body;
14121
- if (!body) return "";
14122
- const reader = body.getReader();
14123
- const chunks = [];
14124
- let bytes = 0;
14125
- try {
14126
- while (true) {
14127
- const { done, value } = await reader.read();
14128
- if (done) break;
14129
- if (!value) continue;
14130
- bytes += value.byteLength;
14131
- if (bytes > limit) {
14132
- await reader.cancel().catch(() => void 0);
14133
- return;
14134
- }
14135
- chunks.push(value);
14136
- }
14137
- } catch {
14138
- await reader.cancel().catch(() => void 0);
14139
- return;
14140
- } finally {
14141
- reader.releaseLock();
14142
- }
14143
- const combined = new Uint8Array(bytes);
14144
- let offset = 0;
14145
- for (const chunk of chunks) {
14146
- combined.set(chunk, offset);
14147
- offset += chunk.byteLength;
14148
- }
14149
- return new TextDecoder().decode(combined);
14150
- }
14151
14709
  /**
14152
14710
  * Build the upstream request headers.
14153
14711
  *
@@ -14156,16 +14714,16 @@ async function responseTextWithinLimit(upstream, maxBytes) {
14156
14714
  * Credential lease transforms win last because they are the host-issued
14157
14715
  * authority for provider auth headers.
14158
14716
  */
14159
- function requestHeaders(request, lease, upstreamHost, tracePropagation) {
14717
+ function requestHeaders(request, headerTransforms, upstreamHost, tracePropagation) {
14160
14718
  const headers = new Headers();
14161
14719
  const mayPropagateTrace = shouldPropagateSandboxEgressTrace(upstreamHost, tracePropagation);
14162
- request.headers.forEach((value, key) => {
14720
+ for (const [key, value] of request.headers) {
14163
14721
  const normalized = key.toLowerCase();
14164
- if (HOP_BY_HOP_HEADERS.has(normalized) || PROXY_ONLY_HEADERS.has(normalized)) return;
14165
- if (TRACE_PROPAGATION_HEADERS.has(normalized) && !mayPropagateTrace) return;
14722
+ if (HOP_BY_HOP_HEADERS.has(normalized) || PROXY_ONLY_HEADERS.has(normalized)) continue;
14723
+ if (TRACE_PROPAGATION_HEADERS.has(normalized) && !mayPropagateTrace) continue;
14166
14724
  headers.append(key, value);
14167
- });
14168
- for (const transform of lease.headerTransforms) {
14725
+ }
14726
+ for (const transform of headerTransforms) {
14169
14727
  if (!matchesSandboxEgressDomain(upstreamHost, transform.domain)) continue;
14170
14728
  for (const [key, value] of Object.entries(transform.headers)) {
14171
14729
  if (TRACE_PROPAGATION_HEADERS.has(key.toLowerCase()) && !mayPropagateTrace) continue;
@@ -14176,10 +14734,10 @@ function requestHeaders(request, lease, upstreamHost, tracePropagation) {
14176
14734
  }
14177
14735
  function responseHeaders(upstream) {
14178
14736
  const headers = new Headers();
14179
- upstream.headers.forEach((value, key) => {
14737
+ for (const [key, value] of upstream.headers) {
14180
14738
  const normalized = key.toLowerCase();
14181
14739
  if (!HOP_BY_HOP_HEADERS.has(normalized) && !DECODED_RESPONSE_HEADERS.has(normalized)) headers.append(key, value);
14182
- });
14740
+ }
14183
14741
  return headers;
14184
14742
  }
14185
14743
  function leaseLogAttributes(input) {
@@ -14221,6 +14779,52 @@ async function recordSandboxPolicyDenied(input) {
14221
14779
  });
14222
14780
  }
14223
14781
  /**
14782
+ * Forward a request that gets no credential, with its own headers.
14783
+ *
14784
+ * Proxy-only and hop-by-hop headers are still stripped, and trace headers
14785
+ * follow the same propagation rules as credentialed requests.
14786
+ */
14787
+ async function forwardWithoutCredential(input) {
14788
+ const { body, deps, provider, request, upstreamUrl } = input;
14789
+ const headers = requestHeaders(request, [], upstreamUrl.hostname, deps.tracePropagation ?? {});
14790
+ const intercepted = await deps.interceptHttp?.({
14791
+ provider,
14792
+ request: new Request(upstreamUrl, {
14793
+ method: request.method,
14794
+ headers,
14795
+ ...body !== void 0 ? { body } : void 0
14796
+ }),
14797
+ upstreamUrl
14798
+ });
14799
+ if (intercepted) return intercepted;
14800
+ const upstream = await (deps.fetch ?? fetch)(upstreamUrl, {
14801
+ method: request.method,
14802
+ headers,
14803
+ ...body !== void 0 ? { body } : void 0,
14804
+ redirect: "manual"
14805
+ });
14806
+ logAudit("sandbox.egress.upstream.requested", {
14807
+ ...egressAttributes({
14808
+ egressId: input.activeEgressId,
14809
+ host: upstreamUrl.hostname,
14810
+ method: request.method,
14811
+ path: upstreamUrl.pathname,
14812
+ provider,
14813
+ status: upstream.status
14814
+ }),
14815
+ ...routingAttributes(request, upstreamUrl),
14816
+ ...credentialAuditAttributes(input.credentialContext.source),
14817
+ ...egressDecisionAttributes("allowed"),
14818
+ "app.sandbox.egress.credential_request": input.credentialRequest,
14819
+ "app.sandbox.egress.upstream_ok": upstream.ok
14820
+ });
14821
+ return new Response(upstream.body, {
14822
+ status: upstream.status,
14823
+ statusText: upstream.statusText,
14824
+ headers: responseHeaders(upstream)
14825
+ });
14826
+ }
14827
+ /**
14224
14828
  * Forward one verified sandbox egress request with host-managed credentials.
14225
14829
  *
14226
14830
  * The caller must already have authenticated the sandbox VM, checked the signed
@@ -14262,6 +14866,7 @@ async function executeCredentialedEgressRequest(input) {
14262
14866
  ...isGraphqlPost(request.method, upstreamUrl) ? { graphql: await readGraphqlRequest(body) } : void 0,
14263
14867
  ...operation ? { operation } : void 0,
14264
14868
  ...input.userOAuthOnly ? { userOAuthOnly: true } : void 0,
14869
+ ...input.withoutCredential ? { withoutCredential: true } : void 0,
14265
14870
  provider,
14266
14871
  method: request.method,
14267
14872
  upstreamUrl
@@ -14293,6 +14898,16 @@ async function executeCredentialedEgressRequest(input) {
14293
14898
  }
14294
14899
  throw error;
14295
14900
  }
14901
+ if (input.withoutCredential) return { response: await forwardWithoutCredential({
14902
+ activeEgressId,
14903
+ body,
14904
+ credentialContext,
14905
+ credentialRequest: input.withoutCredential,
14906
+ deps,
14907
+ provider,
14908
+ request,
14909
+ upstreamUrl
14910
+ }) };
14296
14911
  async function resolveLease() {
14297
14912
  try {
14298
14913
  return await sandboxEgressCredentialLease(provider, grantSelection, credentialContext);
@@ -14347,7 +14962,7 @@ async function executeCredentialedEgressRequest(input) {
14347
14962
  const fetchImpl = deps.fetch ?? fetch;
14348
14963
  let retriedAfter403 = false;
14349
14964
  while (true) {
14350
- const headers = requestHeaders(request, lease, upstreamUrl.hostname, deps.tracePropagation ?? {});
14965
+ const headers = requestHeaders(request, lease.headerTransforms, upstreamUrl.hostname, deps.tracePropagation ?? {});
14351
14966
  const intercepted = await deps.interceptHttp?.({
14352
14967
  provider,
14353
14968
  request: new Request(upstreamUrl, {
@@ -14469,200 +15084,6 @@ async function executeCredentialedEgressRequest(input) {
14469
15084
  }) };
14470
15085
  }
14471
15086
  }
14472
- // src/chat/turn-context-tag.ts
14473
- /**
14474
- * Canonical tag name for the runtime turn context block injected into Pi
14475
- * messages. Shared between prompt assembly and turn context stripping to keep
14476
- * both in sync without requiring the full prompt module.
14477
- */
14478
- const TURN_CONTEXT_TAG = "runtime-turn-context";
14479
- /** Turn context section that only session context includes. */
14480
- const SESSION_CONTEXT_SECTION_TAG = "runtime";
14481
- /**
14482
- * Named system prompt sections that list what the model can use now: the
14483
- * skills, MCP catalogs, tool guidance, Workspaces, and the tools that a Code
14484
- * Mode script can call. A Turn sends a changed section in a later system
14485
- * message (`systemSectionsUpdate`). The Turn context of older Turns held
14486
- * copies of them, which context compaction drops.
14487
- */
14488
- const CAPABILITY_SECTION_TAG = {
14489
- availableSkills: "available-skills",
14490
- activeMcpCatalogs: "active-mcp-catalogs",
14491
- toolGuidance: "tool-guidance",
14492
- workspaces: "workspaces",
14493
- scriptTools: "script-tools"
14494
- };
14495
- /**
14496
- * Turn context sections that are true only for the Turn that received them.
14497
- * Context compaction removes them from the context of earlier Turns.
14498
- */
14499
- const REQUEST_CONTEXT_SECTION_TAG = {
14500
- pluginContext: "plugin-context",
14501
- conversationNotes: "conversation-notes",
14502
- disabledTools: "disabled-tools",
14503
- userCustomization: "user-customization",
14504
- askerTimezone: "asker-timezone",
14505
- turnInput: "turn-input"
14506
- };
14507
- // src/chat/pi/transcript.ts
14508
- const RUNTIME_TURN_CONTEXT_START = `<${TURN_CONTEXT_TAG}>`;
14509
- const AGENTS_INSTRUCTIONS_START = "# AGENTS.md instructions";
14510
- function userMessageContent(message) {
14511
- const record = message;
14512
- return record.role === "user" && Array.isArray(record.content) ? record.content : void 0;
14513
- }
14514
- function isRuntimeTurnContextPart(part) {
14515
- return part !== null && typeof part === "object" && part.type === "text" && typeof part.text === "string" && (part.text.startsWith(RUNTIME_TURN_CONTEXT_START) || part.text.startsWith(AGENTS_INSTRUCTIONS_START));
14516
- }
14517
- function textPartValue(part) {
14518
- return part !== null && typeof part === "object" && part.type === "text" && typeof part.text === "string" ? part.text : void 0;
14519
- }
14520
- /**
14521
- * Whether a user message carries a Turn input, not only context: a
14522
- * `<current-instruction>` or a runtime input tag such as `<task>`.
14523
- */
14524
- function hasTurnInput(message) {
14525
- return userMessageContent(message)?.some((part) => {
14526
- const text = textPartValue(part);
14527
- return text !== void 0 && (text.includes("<current-instruction") || isRuntimeInputText(text));
14528
- }) ?? false;
14529
- }
14530
- function messageTimestamp$1(message) {
14531
- return message.timestamp;
14532
- }
14533
- /** Return whether the message is a Turn's context, paired with the instruction after it. */
14534
- function isStandaloneRuntimeContextMessage(messages, index) {
14535
- const message = messages[index];
14536
- const next = messages[index + 1];
14537
- return Boolean(message && next && userMessageContent(message) && userMessageContent(next) && messageTimestamp$1(message) === messageTimestamp$1(next) && !hasTurnInput(message) && hasTurnInput(next));
14538
- }
14539
- const EMBEDDED_THREAD_CONTEXT_PATTERN = new RegExp(`<(${[
14540
- "thread-context",
14541
- "recent-thread-messages",
14542
- "thread-compactions",
14543
- "thread-transcript",
14544
- "thread-background"
14545
- ].join("|")})(?:\\s[^>]*)?>[\\s\\S]*</\\1>`, "g");
14546
- /** Type guard for Pi SDK assistant messages. */
14547
- function isAssistantMessage(value) {
14548
- return typeof value === "object" && value !== null && value.role === "assistant";
14549
- }
14550
- /** Type guard for Pi SDK tool result messages. */
14551
- function isToolResultMessage(value) {
14552
- return typeof value === "object" && value !== null && value.role === "toolResult";
14553
- }
14554
- /** Check whether a tool result carries an error flag. */
14555
- function isToolResultError(result) {
14556
- if (!result || typeof result !== "object") return false;
14557
- return Boolean(result.isError);
14558
- }
14559
- /** Extract the tool name from a raw tool result message. */
14560
- function normalizeToolNameFromResult(result) {
14561
- if (!result || typeof result !== "object") return void 0;
14562
- const record = result;
14563
- if (typeof record.toolName === "string" && record.toolName.length > 0) return record.toolName;
14564
- if (typeof record.name === "string" && record.name.length > 0) return record.name;
14565
- }
14566
- /** Extract role string from a raw Pi message. */
14567
- function getPiMessageRole(value) {
14568
- if (!value || typeof value !== "object") return;
14569
- const role = value.role;
14570
- return typeof role === "string" ? role : void 0;
14571
- }
14572
- /** Return whether Pi can continue directly from the current history tail. */
14573
- function isContinuablePiBoundary(messages) {
14574
- let end = messages.length;
14575
- while (end > 0 && getPiMessageRole(messages[end - 1]) === "system") end -= 1;
14576
- const lastRole = getPiMessageRole(messages[end - 1]);
14577
- return lastRole === "user" || lastRole === "toolResult";
14578
- }
14579
- /** Concatenate text content parts from an assistant message. */
14580
- function extractAssistantText(message) {
14581
- return (message.content ?? []).filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join("\n");
14582
- }
14583
- /** Return assistant messages that belong to the terminal post-tool reply phase. */
14584
- function getTerminalAssistantMessages(messages) {
14585
- let lastNonAssistantIndex = -1;
14586
- for (let index = messages.length - 1; index >= 0; index -= 1) if (!isAssistantMessage(messages[index])) {
14587
- lastNonAssistantIndex = index;
14588
- break;
14589
- }
14590
- return messages.slice(lastNonAssistantIndex + 1).filter(isAssistantMessage);
14591
- }
14592
- /** Remove trailing assistant messages before committing a resumable boundary. */
14593
- function trimTrailingAssistantMessages(messages) {
14594
- let end = messages.length;
14595
- while (end > 0 && getPiMessageRole(messages[end - 1]) === "assistant") end -= 1;
14596
- return end === messages.length ? [...messages] : messages.slice(0, end);
14597
- }
14598
- /** Return whether Pi history already carries session bootstrap context. */
14599
- function hasRuntimeTurnContext(messages) {
14600
- return messages.some((message, index) => isStandaloneRuntimeContextMessage(messages, index) || userMessageContent(message)?.some(isRuntimeTurnContextPart));
14601
- }
14602
- /** Keep only volatile bootstrap messages needed by an in-turn context replacement. */
14603
- function retainRuntimeTurnContext(messages) {
14604
- return messages.flatMap((message, index) => {
14605
- if (isStandaloneRuntimeContextMessage(messages, index)) return [message];
14606
- const runtimeContent = userMessageContent(message)?.filter(isRuntimeTurnContextPart) ?? [];
14607
- return runtimeContent.length > 0 ? [{
14608
- ...message,
14609
- content: runtimeContent
14610
- }] : [];
14611
- });
14612
- }
14613
- /**
14614
- * Reduce a runtime user-turn prompt to only the current turn's instruction.
14615
- *
14616
- * Live user prompts embed prior-thread context as `<thread-context
14617
- * authority="evidence-only">` (or legacy transcript/background blocks) beside
14618
- * the `<current-instruction>` block. Those blocks hold other participants'
14619
- * verbatim messages, so completed-run projections consumed by plugins must
14620
- * expose only the instruction authored by this turn's actor — otherwise
14621
- * per-entry provenance can be defeated by reading another user's text out of an
14622
- * instruction-authority entry. Prior thread context is projected separately as
14623
- * per-author context-authority entries, so dropping it here is non-lossy for
14624
- * plugins. This is projection-only; it never touches what the model sees during
14625
- * a live run.
14626
- */
14627
- function instructionTextForProjection(text) {
14628
- const withoutContext = text.replace(EMBEDDED_THREAD_CONTEXT_PATTERN, "").trim();
14629
- return unwrapCurrentInstruction(withoutContext) ?? withoutContext;
14630
- }
14631
- /**
14632
- * Return the projected input text carried by one user message. Each Turn
14633
- * input is its own content part: a `<current-instruction>` gives its body,
14634
- * and a runtime input tag stays as it is. Other parts, such as attachments,
14635
- * are dropped. A message with no input part keeps the projection of all its
14636
- * text.
14637
- */
14638
- function getUserMessageInstructionText(message) {
14639
- if (getPiMessageRole(message) !== "user") return "";
14640
- const content = message.content;
14641
- const texts = typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => textPartValue(part) ?? []) : [];
14642
- const inputs = texts.flatMap((text) => {
14643
- const withoutContext = text.replace(EMBEDDED_THREAD_CONTEXT_PATTERN, "").trim();
14644
- if (isRuntimeInputText(withoutContext)) return [readParentAgentTask(withoutContext) ?? withoutContext];
14645
- const instruction = unwrapCurrentInstruction(withoutContext);
14646
- return instruction === void 0 ? [] : [instruction.trim()];
14647
- });
14648
- if (inputs.length > 0) return inputs.filter(Boolean).join("\n\n");
14649
- return instructionTextForProjection(texts.join("\n")).trim();
14650
- }
14651
- /** Remove runtime context from a non-model projection or explicit replacement. */
14652
- function stripRuntimeTurnContext(messages) {
14653
- return messages.flatMap((message, index) => {
14654
- if (isStandaloneRuntimeContextMessage(messages, index)) return [];
14655
- const content = userMessageContent(message);
14656
- if (!content) return [message];
14657
- const nextContent = content.filter((part) => !isRuntimeTurnContextPart(part));
14658
- if (nextContent.length === content.length) return [message];
14659
- if (nextContent.length === 0) return [];
14660
- return [{
14661
- ...message,
14662
- content: nextContent
14663
- }];
14664
- });
14665
- }
14666
15087
  // src/chat/services/persist-retry.ts
14667
15088
  /**
14668
15089
  * Shared post-delivery persist retry.
@@ -15149,7 +15570,7 @@ function normalizeActor(value) {
15149
15570
  return parseStoredSlackActor(value);
15150
15571
  }
15151
15572
  function normalizeLease(value) {
15152
- if (!isRecord$2(value)) return;
15573
+ if (!isRecord$3(value)) return;
15153
15574
  const token = toOptionalString(value["token"]);
15154
15575
  const acquiredAtMs = toOptionalNumber(value["acquiredAtMs"]);
15155
15576
  const lastCheckInAtMs = toOptionalNumber(value["lastCheckInAtMs"]);
@@ -15163,7 +15584,7 @@ function normalizeLease(value) {
15163
15584
  };
15164
15585
  }
15165
15586
  function normalizeStop(value) {
15166
- if (!isRecord$2(value)) return;
15587
+ if (!isRecord$3(value)) return;
15167
15588
  const inboundMessageIds = Array.isArray(value["inboundMessageIds"]) ? uniqueStrings(value["inboundMessageIds"].filter((id) => typeof id === "string")) : [];
15168
15589
  const runId = toOptionalString(value["runId"]);
15169
15590
  return runId ? {
@@ -15173,7 +15594,7 @@ function normalizeStop(value) {
15173
15594
  }
15174
15595
  /** Decode stored execution state. */
15175
15596
  function normalizeExecution(conversationId, value) {
15176
- if (!isRecord$2(value)) return;
15597
+ if (!isRecord$3(value)) return;
15177
15598
  const status = normalizeExecutionStatus(value["status"]);
15178
15599
  if (!status) return;
15179
15600
  const pendingMessages = [];
@@ -15204,7 +15625,7 @@ function normalizeExecution(conversationId, value) {
15204
15625
  }
15205
15626
  /** Decode current conversation records. */
15206
15627
  function normalizeConversation(conversationId, value) {
15207
- if (!isRecord$2(value) || value["schemaVersion"] !== CONVERSATION_SCHEMA_VERSION) return;
15628
+ if (!isRecord$3(value) || value["schemaVersion"] !== CONVERSATION_SCHEMA_VERSION) return;
15208
15629
  const storedConversationId = toOptionalString(value["conversationId"]);
15209
15630
  const createdAtMs = toOptionalNumber(value["createdAtMs"]);
15210
15631
  const lastActivityAtMs = toOptionalNumber(value["lastActivityAtMs"]);
@@ -15318,7 +15739,7 @@ async function withIndexLock(state, indexKey, callback) {
15318
15739
  }
15319
15740
  }
15320
15741
  function normalizeIndexEntry(value) {
15321
- if (!isRecord$2(value)) return;
15742
+ if (!isRecord$3(value)) return;
15322
15743
  const conversationId = toOptionalString(value["conversationId"]);
15323
15744
  const score = toOptionalNumber(value["score"]);
15324
15745
  if (!conversationId || typeof score !== "number") return;
@@ -17513,7 +17934,7 @@ const CONTEXT_MAX_MESSAGE_CHARS = 3200;
17513
17934
  const THREAD_CONTEXT_MAX_CHARS = 6e4;
17514
17935
  const THREAD_CONTEXT_OPEN = "<thread-context authority=\"evidence-only\">";
17515
17936
  const THREAD_CONTEXT_CLOSE = "</thread-context>";
17516
- const THREAD_CONTEXT_OMITTED_NOTE = "Older Messages of this thread are not shown. Find them with the searchConversationEvents and readConversationEvent tools.";
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.";
17517
17938
  const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
17518
17939
  /** Normalize message boundaries without changing transcript formatting. */
17519
17940
  function normalizeConversationText(text) {
@@ -18059,9 +18480,7 @@ function resolveCommitProvenance(args) {
18059
18480
  if (args.trailingMessageProvenance) {
18060
18481
  if (args.trailingMessageProvenance.length > provenance.length) throw new Error("trailing commit provenance cannot exceed committed messages");
18061
18482
  const start = provenance.length - args.trailingMessageProvenance.length;
18062
- args.trailingMessageProvenance.forEach((entry, offset) => {
18063
- if (start + offset >= matchingPrefix) provenance[start + offset] = entry;
18064
- });
18483
+ for (const [offset, entry] of args.trailingMessageProvenance.entries()) if (start + offset >= matchingPrefix) provenance[start + offset] = entry;
18065
18484
  }
18066
18485
  return provenance;
18067
18486
  }
@@ -18441,4 +18860,4 @@ async function recordGuardianActionReviewed(args) {
18441
18860
  createdAtMs: Date.now()
18442
18861
  }]);
18443
18862
  }
18444
- export { pauseLostWorkerTurn as $, notInheritedByForkChild as $a, historyItemFromPiMessage as $c, wrapSandboxSetupError as $i, getPlugins as $n, removeReactionFromMessage as $o, RESOURCE_SUBSCRIPTION_MAX_TTL_MS as $r, deleteEventAutomation as $s, buildTurnErrorResponse as $t, normalizeConversationText as A, createPluginModelCostRecorder as Aa, ToolInputError as Ac, WorkspaceValidationError as Ai, isToolResultMessage as An, confirmDispatchMailboxAppend as Ao, updateReviewItemContent as Ar, createScheduledAutomation as As, hasRunnableConversationWork as At, PluginCredentialFailureError as B, conversationViewerMarks as Ba, readAutomationTitlesByConversationId as Bc, isRetryableSandboxFailure as Bi, createUserTokenStore as Bn, markDispatchAwaitingResume as Bo, requireReviewItemLinks as Br, getDashboardLinkFilter as Bs, releaseInboundMessage as Bt, settleConversationTitleWork as C, SANDBOX_WORKSPACE_ROOT as Ca, automationVersionOf as Cc, createWorkspace as Ci, hasRuntimeTurnContext as Cn, findActorTimezone as Co, getReviewItem as Cr, normalizeSlackReplyMarkdown as Cs, deferConversationMove as Ct, isHumanConversationMessage as D, buildCommandScript as Da, AutomationConflictError as Dc, listWorkspaces as Di, isContinuablePiBoundary as Dn, readConversationAutomationRun as Do, reviewItemsNeedingUserVersionQuery as Dr, wrapBareSlackUserIds as Ds, getConversationWorkState as Dt, getConversationMessageSlackTs as E, sandboxSkillPathResolution as Ea, sameDefinitionValue as Ec, getWorkspaceByName as Ei, isAssistantMessage as En, lookupSlackUserNames as Eo, listWaitingConversations as Er, slackMentionedUserIds as Es, getConversation as Et, calculateContextCompactionTargetTokens as F, readConversationAccessFromSql as Fa, readAutomationExecutionStatusDays as Fc, create as Fi, CAPABILITY_SECTION_TAG as Fn, getDispatchRecord as Fo, canUserReadReviewItem as Fr, saveScheduledAutomation as Fs, moveIdleConversationDestination as Ft, AuthorizationPauseError as G, readConversationEventPage as Ga, conversationRangeColumns as Gc, parseOAuthStatePayload as Gi, createPluginEventPublisher as Gn, notifyAutomationBlocked as Go, activeParticipantUserIds as Gr, getDashboardTaskLink as Gs, stopConversationWork as Gt, authorizationId as H, createPluginConversationEvents as Ha, fallbackShortTitle as Hc, proxyVercelSandboxEgressRequest as Hi, resolvePluginOAuthAccount as Hn, markDispatchCompleted as Ho, reviewItemReaderForUser as Hr, getDashboardPersonLink as Hs, requestConversationWork as Ht, getAgentBackgroundCompactionMarkTokens as I, conversationHasParticipantUser as Ia, readAutomationExecutionStatusHours as Ic, hash as Ii, REQUEST_CONTEXT_SECTION_TAG as In, getDispatchTurnId as Io, isOnlyAssignee as Ir, saveScheduledAutomationInLock as Is, pruneActiveConversation as It, clearPendingAuth as J, readConversationLastEventSeq as Ja, credentialAuditAttributes as Jc, SandboxCallTimeoutError as Ji, getPluginRoutes as Jn, getSlackMessagePermalink as Jo, resolveAssignees as Jr, parseDashboardPersonLink as Js, GATED_TURN_LIMIT_WRAP_UP_MESSAGE as Jt, abandonReplacedPendingAuth as K, readConversationEventPageAfter as Ka, conversationUsageCostExpr as Kc, resolveBaseUrl as Ki, createPluginHookRunner as Kn, addReactionToMessage as Ko, automationCreatorUserId as Kr, isDashboardLink as Ks, takeDeferredConversationMove as Kt, getAgentContextCompactionTriggerTokens as L, conversationIsMemberRoot as La, readAutomationExecutionSummaries as Lc, isStale as Li, SESSION_CONTEXT_SECTION_TAG as Ln, getPluginDispatchProjection as Lo, itemNeedsUser as Lr, scheduledRunId as Ls, recordAttemptFailure as Lt, trimConversationMessages as M, canAccessConversation as Ma, emptyAutomationRunWindows as Mc, loadSnapshotsForProfile as Mi, retainRuntimeTurnContext as Mn, getDispatchConversationId as Mo, canActOnReviewItem as Mr, listScheduledAutomationsForTeam as Ms, isInvalidConversationRecordError as Mt, turnHasReply as N, canAddConversationMessages as Na, existingConversationId as Nc, setWorkspaceSnapshot as Ni, stripRuntimeTurnContext as Nn, getDispatchIdForConversation as No, canAgentChangeReviewItem as Nr, parseScheduledAutomationRow as Ns, listActiveConversationIds as Nt, latestConversationMessageSeq as O, buildNonInteractiveShellScript as Oa, automationRevision as Oc, listWorkspacesByRepository as Oi, isStandaloneRuntimeContextMessage as On, buildDispatchId as Oo, searchReviewItems as Or, truncateStatusText as Os, getConversationWorkStates as Ot, upsertConversationMessage as P, createConversationAccessReader as Pa, readAutomationExecutionByConversationId as Pc, setWorkspaceSnapshotBuild as Pi, trimTrailingAssistantMessages as Pn, getDispatchInputMessageId as Po, canReadReviewItem as Pr, readScheduledAutomation as Ps, markConversationWorkEnqueued as Pt, lostWorkerBeforeFirstSave as Q, loadForkHistory as Qa, configValueSchema as Qc, throwSandboxOperationError as Qi, getPluginUserPromptContributions as Qn, postSlackMessage as Qo, RESOURCE_SUBSCRIPTION_DEFAULT_TTL_MS as Qr, createEventAutomation as Qs, TurnToolCallLimitExceededError as Qt, getAgentContextInputLimitTokens as R, conversationIsNotUnsubscribedRoot as Ra, readAutomationExecutions as Rc, ensureDockerDaemon as Ri, TURN_CONTEXT_TAG as Rn, isTerminalDispatchStatus as Ro, readReviewItemAgentScope as Rr, withScheduledAutomationLock as Rs, recordConversationRetry as Rt, resolveConversationTitle as S, SANDBOX_SKILLS_ROOT as Sa, automationDefinition as Sc, renderToolResultNudge as Si, getUserMessageInstructionText as Sn, defaultTimezone as So, getOpenReviewItemByDedupeKey as Sr, formatSlackLink as Ss, deadLetterAttempt as St, estimateConversationMessagesTokens as T, sandboxSkillFile as Ta, readAutomationVersion as Tc, getWorkspace as Ti, instructionTextForProjection as Tn, lookupSlackUser as To, listReplyActionItems as Tr, slackMention as Ts, dropPendingMessages as Tt, AuthPausePersistenceError as U, readConversationBriefThrough as Ua, resolveTaskTitle as Uc, deliverOAuthAuthorization as Ui, agent_hooks_exports as Un, markDispatchFailed as Uo, reviewItemReaderForUserInConversation as Ur, getDashboardReviewItemLink as Us, startConversationWork as Ut, createPluginAuthOrchestration as V, viewerMarksFromParticipant as Va, recordAutomationExecution as Vc, isVercelSandboxEgressRequest as Vi, getOAuthAccountProviders as Vn, markDispatchBlocked as Vo, reviewItemNeedsSomeone as Vr, getDashboardObjectIconLink as Vs, requestAnotherSlice as Vt, AuthorizationFlowDisabledError as W, readLatestConversationBrief as Wa, conversationAggregateColumns as Wc, formatProviderLabel as Wi, applyPluginFormatMarkdown as Wn, markDispatchRunning as Wo, EVERYONE_ASSIGNEE as Wr, getDashboardSettingsLink as Ws, steerWebPendingMessages as Wt, continuableMessages as X, buildSentryConversationUrl as Xa, createPluginCache as Xc, isAbortError as Xi, getPluginSystemPromptContributions as Xn, openSlackModal as Xo, resolveChannelCapabilities as Xr, blockEventAutomation as Xs, TurnBudgetExceededError as Xt, getConversationPendingAuth as Y, readConversationMessageEventSeq as Ya, credentialAuditSource as Yc, findInErrorChain as Yi, getPluginSlackConversationLink as Yn, openSlackDirectMessage as Yo, createCodeChangePublisher as Yr, setDashboardConversationLinkOptions as Ys, TURN_LIMIT_WRAP_UP_MESSAGE as Yt, loadTurnCheckpoint as Z, FORK_INSTRUCTIONS as Za, createDurableLocationConfigurationService as Zc, isAlreadyExistsError as Zi, getPluginTools as Zn, postSlackEphemeralMessage as Zo, getSlackToolContext as Zr, collectEventAutomationMatchKeys as Zs, TurnSliceLimitExceededError as Zt, appendConversationMessages as _, createPluginEmbedder as _a, registeredEventTriggerProblems as _c, verifyEventAutomationCredentialSubject as _i, readBlockedReport as _n, createConversationEmbedder as _o, REVIEW_ITEM_REPLIED_REASON as _r, sleep$2 as _s, clearConsumedConversationWake as _t, loadProjection as a, consumeSandboxEgressAuthRequiredSignal as aa, setEventAutomationStatus as ac, createTimerWatch as ai, remindMissingAnswer as an, slackAttachmentsVersionQuery as ao, setBriefsConfig as ar, SlackActionError as as, getTurnRecord as at, persistConversationMessages as b, SANDBOX_DATA_ROOT as ba, requireEventIdentifier as bc, verifyTimerWatchCredentialSubject as bi, getPiMessageRole as bn, listConversationAnnotations as bo, countReviewItemsNeedingUserBySubject as br, SLACK_USER_MENTION_RE as bs, completeConversationWork as bt, recordAgentsInstructionsUpdated as c, parseSandboxEgressCredentialToken as ca, CORE_EVENT_NAMESPACE as cc, findMatchingWatches as ci, getAssistantReplyText as cn, readLiveAttachment as co, resolveNotificationTimezone as cr, getHeaderString as cs, CONVERSATION_WORK_CHECK_IN_INTERVAL_MS as ct, recordAuthorizationCompleted as d, resolveSandboxCommandEnvironment as da, eventCatalogEntry as dc, listWatches as di, findLegacyNoReplyMarker as dn, storeAttachment as do, readNotificationSchedule as dr, isDmChannel as ds, appendExclusiveInboundMessage as dt, WorkspaceSnapshotNotReadyError as ea, findMatchingEventAutomations as ec, RESOURCE_WATCH_TOOL_SOURCE as ei, piMessageFromHistoryItem as el, createTurnLimitGate as en, getSlackFileId as eo, getStaticPluginToolDefinitions as er, unfurlSlackLinks as es, saveTurnCheckpoint as et, recordAuthorizationRequested as f, normalizeSandboxEgressTracePropagationDomains as fa, eventGuidance as fc, takeDueTimerWatches as fi, isLegacyNoReplyMarker as fn, storeAttachments as fo, saveNotificationSchedule as fr, isSlackRequestTimeout as fs, appendInboundMessage as ft, recordToolExecutionStarted as g, PluginToolDeniedError as ga, registeredEventMatchSchema as gc, bindSlackDirectCredentialSubject as gi, REPORT_BLOCKED_TOOL_NAME as gn, searchConversations as go, createPluginReviewItems as gr, withSlackRetries as gs, claimInboundMessage as gt, recordSubscribedReplyRoute as h, workspaceRepoCheckoutPath as ha, hasEventCatalogEntries as hc, bindScheduledAutomationCredentialSubject as hi, CODE_MODE_CALL_STATUS_TEXT as hn, resolveRootVisibility as ho, projectConversationMessages as hr, streamPrivateSlackFile as hs, checkInConversationWork as ht, loadConversationProjection as i, clearSandboxEgressSignals as ia, saveEventAutomation as ic, collectEventMatchKeys as ii, readTurnAnswer as in, recordSlackAttachment as io, registration_exports as ir, slackExternalRefIdSchema as is, getStoredTurnFields as it, recordDeliveredAssistantMessage as j, createPluginLogger as ja, isToolInputError as jc, invalidateReadySnapshot as ji, normalizeToolNameFromResult as jn, createOrGetDispatch as jo, PLUGIN_REVIEW_ITEM_KEY_PREFIX as jr, deleteScheduledAutomation as js, isFinalAttempt as jt, markConversationMessage as k, runNonInteractiveCommand as ka, requireAutomationRevision as kc, updateWorkspace as ki, isToolResultError as kn, claimDispatchMailboxAppend as ko, takeReviewItem as kr, blockScheduledAutomation as ks, hasConversationStop as kt, recordAttachmentsDelivered as l, sandboxEgressSignalsResponseSchema as la, automationEventCatalog as lc, getWatch as li, sanitizeAssistantText as ln, recordUploadedAttachment as lo, deletePushSubscription as lr, getSlackClient as ls, CONVERSATION_WORK_STALE_ENQUEUE_MS as lt, recordMcpProviderConnected as m, tryWorkspaceRepoCheckoutPath as ma, eventWatchUnavailable as mc, bindEventAutomationCredentialSubject as mi, CODEMODE_TOOL_NAME as mn, AttachmentSourceUnavailableError as mo, isPausedBySlack as mr, runWithSlackInstallationToken as ms, cancelHumanFacingPendingMessages as mt, commitMessages as n, isWorkspaceSnapshotNotReadyError as na, listDeletedEventAutomationsCreatedBy as nc, cancelSubscriptions as ni, getConfigDefaults as nl, REPLY_TOOL_NAME as nn, readAttachmentVisionSummary as no, validatePlugins as nr, uploadFilesToConversation as ns, completeTurnRecord as nt, loadTurnProjection as o, consumeSandboxEgressPermissionDeniedSignal as oa, admitEventAutomationRun as oc, createWatch as oi, replyTextSchema as on, collectAttachmentGarbage as oo, readWebPushConfig as or, downloadPrivateSlackFile as os, listTurnSummaries as ot, recordGuardianActionReviewed as p, SANDBOX_RUNTIME as pa, eventNamespaceSchema as pc, turnEvents as pi, readNoReply as pn, storeDeferredAttachment as po, savePushSubscription as pr, normalizeSlackConversationId as ps, beginConversationResume as pt, canReusePendingAuthLink as q, readConversationEventPageAround as qa, JUNIOR_THREAD_STATE_TTL_MS as qc, startOAuthFlow as qi, getPluginApiRoutes as qn, deleteSlackMessage as qo, resolveAssignee as qr, parseDashboardConversationLink as qs, readInboundMessageSender as qt, loadConnectedMcpProviders as r, workspaceSnapshotNotReadyUserMessage as ra, parseEventAutomationRow as rc, cancelWatch as ri, setConfigDefaults as rl, isAnswerToolName as rn, readSlackAttachmentSource as ro, coreTaskRegistrations as rr, slackEntitySchema as rs, failTurnRecord as rt, openConversationProjection as s, createSandboxEgressCredentialToken as sa, eventAutomationRunLimitReason as sc, deliverWatch as si, decideReply as sn, isFileAttachment as so, sendPushNotificationToUser as sr, getFilePermalink as ss, recordTurnSummary as st, commitAcceptedReply as t, getWorkspaceSnapshotNotReadyError as ta, getEventAutomation as tc, STOP_WATCHING_TOOL_NAME as ti, projectConversationEvents$1 as tl, isTurnExecutionLimitExceededError as tn, matchSlackAttachments as to, setPlugins as tr, updateSlackMessage as ts, abandonTurnRecord as tt, recordAuthenticationLinked as u, buildSandboxEgressNetworkPolicy as ua, describeRegisteredEventTrigger as uc, isQuietEvent as ui, NO_REPLY_TOOL_NAME as un, requestAttachmentDeletion as uo, listPushSubscriptions as ur, isConversationScopedChannel as us, ackMessages as ut, hydrateConversationMessages as v, createPluginModel as va, registeredEventTypeSchema as vc, verifyScheduledAutomationCredentialSubject as vi, persistWithRetry as vn, saveObjectAnnotations as vo, closeReviewItem as vr, getWorkspaceTeamId as vs, clearExpiredConversationLease as vt, buildConversationContext as w, sandboxSkillDir as wa, listAutomationVersions as wc, deleteWorkspace as wi, hasTurnInput as wn, resolveUserTimezone as wo, insertReviewItem as wr, normalizeSlackStatusText as ws, drainConversationMailbox as wt, toStoredConversationMessage as x, SANDBOX_REPOS_ROOT as xa, requireValidEventTrigger as xc, createPluginState as xi, getTerminalAssistantMessages as xn, listConversationAnnotationsById as xo, dismissOpenReviewItems as xr, escapeSlackMrkdwnText as xs, countPendingConversationMessages as xt, persistConversationMessageWindow as y, SANDBOX_COMMAND_PATH as ya, registeredResourceTypeSchema as yc, verifySlackDirectCredentialSubject as yi, extractAssistantText as yn, createPluginAnnotations as yo, countOpenReviewItemsForUser as yr, runWithWorkspaceTeamId as ys, completeConversationStop as yt, createPluginEgress as z, conversationPinnedForUser as za, readAutomationRuns as zc, getSandboxProvider as zi, SANDBOX_EGRESS_AUTH_REQUIRED_MARKER as zn, listPendingDispatchMailboxAppends as zo, requireReviewItemAssignees as zr, getDashboardConversationLink as zs, releaseConversationWork as zt };
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 };