@sentry/junior 0.306.0 → 0.307.1

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-HrBTD8rJ.js} +2 -2
  2. package/dist/{admin-BLLdLnXh.js → admin-B78_KmfR.js} +2 -2
  3. package/dist/{agent-runner-BaLjEjPR.js → agent-runner-DxivxUYd.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-HlljT9ql.js +231 -0
  12. package/dist/{briefs-DvyzXfrF.js → briefs-DR8mp-TK.js} +2 -2
  13. package/dist/{catalog-runtime-B1R-nHd3.js → catalog-runtime-Se9idiDR.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-DY5c1E0l.js} +74 -38
  24. package/dist/{connections-CDhsqPcC.js → connections-C-SqzubG.js} +10 -8
  25. package/dist/{continue-in-slack-BXQizz9o.js → continue-in-slack-DNkrrWuQ.js} +5 -5
  26. package/dist/{conversation-privacy-YE54gMN8.js → conversation-privacy-CVj9vSrP.js} +1 -1
  27. package/dist/{conversation-turn-BzdmrHb0.js → conversation-turn-CkzrIfJ2.js} +19 -47
  28. package/dist/{credential-sync-Cdm-e1vJ.js → credential-sync-B9CIkgOT.js} +28 -28
  29. package/dist/{db-DV2ZUb1Y.js → db-C21CyyTE.js} +140 -11
  30. package/dist/{db-pH357Dkt.d.ts → db-C41UgdBj.d.ts} +1 -1
  31. package/dist/{executor-CjNhwwnj.js → executor-DfNoVVGd.js} +93 -32
  32. package/dist/{install-DbD7C5td.js → install-lYZs8UCL.js} +2 -2
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{lineage-BFdIPb3o.js → lineage-BJTSY53A.js} +2 -2
  35. package/dist/{logging-oYpJYr-S.js → logging-DjW7LjgJ.js} +1 -1
  36. package/dist/{message-BBPcMKJY.js → message-BPPZpdoZ.js} +8 -8
  37. package/dist/{model-input-DYYF3a8B.js → model-input-DKqiLFGa.js} +3 -3
  38. package/dist/nitro.d.ts +2 -2
  39. package/dist/nitro.js +12 -5
  40. package/dist/{oauth-callback-server-C7Q987su.js → oauth-callback-server-OJP8Y4Ca.js} +2 -2
  41. package/dist/{oauth-relay-DAmfVmJu.js → oauth-relay-KwDz41Z3.js} +1 -1
  42. package/dist/{plugins-B_0Cr0MO.d.ts → plugins-fBrz8PCV.d.ts} +2 -0
  43. package/dist/{projection-CWXDE0f6.js → projection-D47mlszd.js} +1112 -693
  44. package/dist/{prompt-P3eRqO8C.js → prompt-DuWH_YIb.js} +3 -3
  45. package/dist/{registry-1pzXmplY.js → registry-yht0oxq6.js} +19 -9
  46. package/dist/{resolve-n87oXY-d.js → resolve-gZ-hVMYl.js} +3 -3
  47. package/dist/{result-BmF9v9bv.js → result-CP99Ok0_.js} +13 -11
  48. package/dist/{runner-4j7ZsxP5.js → runner-eVlnUkY7.js} +9 -9
  49. package/dist/{sandbox-egress-signals-BRQI8HvT.js → sandbox-egress-signals-DZL_0lnG.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-CZneZHh7.js} +8 -6
  54. package/dist/{service-account-BDQ9xzta.js → service-account-tI3LBg2_.js} +3 -3
  55. package/dist/{session-stop-BQxgHR4X.js → session-stop-D3S7mSkX.js} +36 -23
  56. package/dist/{skills-CPf4vNuC.js → skills-Bm6uSO9V.js} +32 -28
  57. package/dist/{slack-conversation-unfurl-B1KEptUg.js → slack-conversation-unfurl-BeBvg3xU.js} +10 -10
  58. package/dist/{spawn-CjGddiAU.js → spawn-vhMAmLuh.js} +6 -6
  59. package/dist/{state-9wfj6aSD.js → state-3Yiy2FvP.js} +4 -4
  60. package/dist/{stop-CsQGuN5n.js → stop-Bh53GUoX.js} +146 -158
  61. package/dist/{store-Dz3YZ7gQ.js → store-BZJdHYR7.js} +5 -5
  62. package/dist/{background-compaction-queue-D2wzxtGU.js → task-queue-BEl5G38v.js} +164 -180
  63. package/dist/{task-runner-frzlUvFD.js → task-runner-C6Bujc6h.js} +11 -8
  64. package/dist/{thread-context-C4QuZlM8.js → thread-context-DxMQGGd_.js} +6 -6
  65. package/dist/{turn-session-routing-BXaubz2w.js → turn-session-routing-CmQY0T60.js} +24 -5
  66. package/dist/{turn-user-message-DNC0eRZ7.js → turn-user-message-Dfbr3Ud9.js} +3 -3
  67. package/dist/{users-XCCKn3xW.js → users-6rSdqXXk.js} +1 -1
  68. package/dist/{validation-L5fdjmFX.js → validation--hsjOLRL.js} +1 -1
  69. package/dist/{version-BFmuwgxP.js → version-9iMT25Hq.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-DKOeHpv3.js → viewer-De1vmuEA.js} +3 -3
  72. package/dist/{warmup-mTMIatCV.js → warmup-C0IblNtf.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-CiyRr2q7.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,25 +1,24 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { A as normalizeConversationText, Do as readConversationAutomationRun, Go as notifyAutomationBlocked, No as getDispatchIdForConversation, O as latestConversationMessageSeq, P as upsertConversationMessage, Xs as blockEventAutomation, a as loadProjection, at as getTurnRecord, b as persistConversationMessages, bi as verifyTimerWatchCredentialSubject, cn as getAssistantReplyText, et as saveTurnCheckpoint, j as recordDeliveredAssistantMessage, k as markConversationMessage, ks as blockScheduledAutomation, rt as failTurnRecord, t as commitAcceptedReply, v as hydrateConversationMessages, vn as persistWithRetry } from "./projection-CWXDE0f6.js";
3
- import { E as isTopLevelKind, T as isPersonInput, _t as nextDetailVersion, a as getConversationStore, k as turnBehavior, o as getDb, r as getConversationEventStore, s as getSqlExecutor } from "./db-DV2ZUb1Y.js";
4
- import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-oYpJYr-S.js";
2
+ import { A as normalizeConversationText, O as latestConversationMessageSeq, P as upsertConversationMessage, Vo as readConversationAutomationRun, Ws as blockScheduledAutomation, a as loadProjection, as as notifyAutomationBlocked, at as getTurnRecord, b as persistConversationMessages, cn as getAssistantReplyText, dc as blockEventAutomation, et as saveTurnCheckpoint, j as recordDeliveredAssistantMessage, ji as verifyTimerWatchCredentialSubject, k as markConversationMessage, qo as getDispatchIdForConversation, rt as failTurnRecord, t as commitAcceptedReply, v as hydrateConversationMessages, vn as persistWithRetry } from "./projection-D47mlszd.js";
3
+ import { E as isTopLevelKind, T as isPersonInput, a as getConversationStore, k as turnBehavior, o as getDb, r as getConversationEventStore } from "./db-C21CyyTE.js";
4
+ import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-DjW7LjgJ.js";
5
5
  import { tt as readMessageAttachments } from "./conversation--f85g4zL.js";
6
- import { F as juniorConversations } from "./executor-CjNhwwnj.js";
7
- import { a as buildDeliveredTurnStatePatch, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-C4QuZlM8.js";
8
- import { Bn as AgentRunError, En as supersedeOpenMailboxTurns, Et as resolveConversationDestination, Ln as createWebAuthorization, Vn as executeTurn, an as readParentMessage, gn as completeCancelledConversationTurn, nn as isParentMessageMeta, tn as childAgentTurnOptions } from "./warmup-mTMIatCV.js";
9
- import { R as buildDeterministicTurnId, _ as ConversationTurnLifecycleService, d as isTurnInputCommitLostError, g as startActiveTurn, h as markTurnFailed, l as getConversationTurnBoundaryError, s as TurnInputCommitLostError, t as getTurnUserMessage } from "./turn-user-message-DNC0eRZ7.js";
10
- import { f as credentialContextForActor } from "./registry-1pzXmplY.js";
6
+ import { L as finalizeFailedTurnReplyWithEvent, O as isConversationDeliveryPaused, i as measureTurnCompactionWait } from "./agent-runner-DxivxUYd.js";
7
+ import { a as buildDeliveredTurnStatePatch, o as loadPendingMessageCards, r as completeAuthPauseTurn, t as buildTurnThreadContext } from "./thread-context-DxMQGGd_.js";
8
+ import { En as supersedeOpenMailboxTurns, Et as resolveConversationDestination, Hn as executeTurn, Rn as createWebAuthorization, Vn as AgentRunError, an as readParentMessage, gn as completeCancelledConversationTurn, nn as isParentMessageMeta, tn as childAgentTurnOptions } from "./warmup-C0IblNtf.js";
9
+ import { R as buildDeterministicTurnId, _ as ConversationTurnLifecycleService, d as isTurnInputCommitLostError, g as startActiveTurn, h as markTurnFailed, l as getConversationTurnBoundaryError, s as TurnInputCommitLostError, t as getTurnUserMessage } from "./turn-user-message-Dfbr3Ud9.js";
10
+ import { p as credentialContextForActor } from "./registry-yht0oxq6.js";
11
11
  import { i as getActiveSpan, r as continueTrace } from "./sentry-CPbZjomA.js";
12
- import { N as finalizeFailedTurnReplyWithEvent, i as measureTurnCompactionWait } from "./agent-runner-BaLjEjPR.js";
13
- import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, s as persistThreadStateById } from "./turn-session-routing-BXaubz2w.js";
14
- import { n as botConfig } from "./config-DUD-zMvp.js";
15
- import { B as renderEventBatchInputs, D as getEventBatchDelayMs, M as sourceFromTurnInput, N as turnInputFactsFromConversationMessage, P as legacyWebMailboxMetadataSchema, Q as maybePostAutomatedTurnLimitNotice, R as eventBatchMessageMeta, V as timerWatchCredentialSubject, c as loadReviewItemInput, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, m as instructionForInputs, p as instructionActorFor, s as eventReviewItemInputs, st as recordFinishedTurnForAutomatedLimit, z as isEventMailboxMetadata } from "./session-stop-BQxgHR4X.js";
16
- import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-frzlUvFD.js";
12
+ import { a as getPersistedThreadState, c as coerceThreadConversationState, i as getPersistedSandboxState, s as persistThreadStateById } from "./turn-session-routing-CmQY0T60.js";
13
+ import { n as botConfig } from "./config-DY5c1E0l.js";
14
+ import { B as renderEventBatchInputs, D as getEventBatchDelayMs, M as sourceFromTurnInput, N as turnInputFactsFromConversationMessage, P as legacyWebMailboxMetadataSchema, Q as maybePostAutomatedTurnLimitNotice, R as eventBatchMessageMeta, V as timerWatchCredentialSubject, c as loadReviewItemInput, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, m as instructionForInputs, p as instructionActorFor, s as eventReviewItemInputs, st as recordFinishedTurnForAutomatedLimit, z as isEventMailboxMetadata } from "./session-stop-D3S7mSkX.js";
15
+ import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-C6Bujc6h.js";
17
16
  import { p as instructionProvenanceFor } from "./history-N7IVbUom.js";
18
- import { s as isEventConversationMessage } from "./prompt-P3eRqO8C.js";
19
- import { t as readConversationLineage } from "./lineage-BFdIPb3o.js";
17
+ import { s as isEventConversationMessage } from "./prompt-DuWH_YIb.js";
18
+ import { t as readConversationLineage } from "./lineage-BJTSY53A.js";
19
+ import pLimit from "p-limit";
20
20
  import { isDeepStrictEqual } from "node:util";
21
21
  import { createHash } from "node:crypto";
22
- import { and, eq, isNotNull, isNull } from "drizzle-orm";
23
22
  // src/chat/task-execution/turn-telemetry.ts
24
23
  /** Read the turn input timing facts from a mailbox batch, oldest first. */
25
24
  function turnInputTelemetry(messages) {
@@ -98,34 +97,6 @@ async function blockRunAutomation(conversationId, blocked) {
98
97
  reason: blocked.missing
99
98
  });
100
99
  }
101
- // src/chat/conversations/delivery-pause.ts
102
- /** True when the Conversation is a root that delivers to a Location. */
103
- function canPauseConversationDelivery(conversation) {
104
- return isTopLevelKind(conversation.kind) && conversation.location !== void 0;
105
- }
106
- const rootConversation = (conversationId) => and(eq(juniorConversations.conversationId, conversationId), isNull(juniorConversations.parentConversationId));
107
- /**
108
- * Stop Delivery of a root's Event Turn replies to its Location. Returns false
109
- * when Delivery was already paused or the root does not exist.
110
- */
111
- async function pauseConversationDelivery(conversationId) {
112
- return (await getSqlExecutor().db().update(juniorConversations).set({
113
- deliveryPausedAt: /* @__PURE__ */ new Date(),
114
- detailVersion: nextDetailVersion
115
- }).where(and(rootConversation(conversationId), isNull(juniorConversations.deliveryPausedAt))).returning({ conversationId: juniorConversations.conversationId })).length > 0;
116
- }
117
- /** Deliver a root's Event Turn replies to its Location again. */
118
- async function resumeConversationDelivery(conversationId) {
119
- await getSqlExecutor().db().update(juniorConversations).set({
120
- deliveryPausedAt: null,
121
- detailVersion: nextDetailVersion
122
- }).where(and(rootConversation(conversationId), isNotNull(juniorConversations.deliveryPausedAt)));
123
- }
124
- /** True while a root's Event Turn replies stay out of its Location. */
125
- async function isConversationDeliveryPaused(conversationId) {
126
- const [row] = await getSqlExecutor().db().select({ pausedAt: juniorConversations.deliveryPausedAt }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
127
- return Boolean(row?.pausedAt);
128
- }
129
100
  // src/chat/task-execution/assistant-message.ts
130
101
  /** Store one assistant Message and its Agent history. */
131
102
  async function commitAssistantMessage(args) {
@@ -158,7 +129,8 @@ async function commitAssistantMessage(args) {
158
129
  * attachments keeps one empty input, so the prompt still has an instruction.
159
130
  */
160
131
  async function webTurnInputs(messages) {
161
- const flat = (await Promise.all(messages.map(async (message) => {
132
+ const limit = pLimit(8);
133
+ const flat = (await Promise.all(messages.map((message) => limit(async () => {
162
134
  const reviewItem = await loadReviewItemInput(message.reviewItemChange);
163
135
  if (reviewItem) return [{
164
136
  kind: "runtime",
@@ -169,7 +141,7 @@ async function webTurnInputs(messages) {
169
141
  kind: "person",
170
142
  text
171
143
  }] : [];
172
- }))).flat();
144
+ })))).flat();
173
145
  return flat.length ? flat : [{
174
146
  kind: "person",
175
147
  text: ""
@@ -797,4 +769,4 @@ function createConversationTurnWorker(agentRunner, deliverMessage, deliverToPare
797
769
  });
798
770
  };
799
771
  }
800
- export { resumeConversationDelivery as a, withTurnSpan as c, pauseConversationDelivery as i, createConversationTurnWorker as n, getTurnInputSpanAttributes as o, canPauseConversationDelivery as r, turnInputTelemetry as s, conversation_turn_exports as t };
772
+ export { withTurnSpan as a, turnInputTelemetry as i, createConversationTurnWorker as n, getTurnInputSpanAttributes as r, conversation_turn_exports as t };
@@ -1,21 +1,21 @@
1
- import { Bn as createUserTokenStore, Gi as parseOAuthStatePayload, Hn as resolvePluginOAuthAccount, Ki as resolveBaseUrl, Qo as postSlackMessage, Wi as formatProviderLabel, Y as getConversationPendingAuth, at as getTurnRecord, d as recordAuthorizationCompleted, ls as getSlackClient, u as recordAuthenticationLinked } from "./projection-CWXDE0f6.js";
2
- import { V as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-DUD-zMvp.js";
3
- import { W as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-oYpJYr-S.js";
1
+ import { H as authorizationId, Sn as resolvePluginOAuthAccount, Y as getConversationPendingAuth, at as getTurnRecord, bn as createUserTokenStore, d as recordAuthorizationCompleted, fs as postSlackMessage, na as parseOAuthStatePayload, ra as resolveBaseUrl, ta as formatProviderLabel, u as recordAuthenticationLinked, ws as getSlackClient } from "./projection-D47mlszd.js";
2
+ import { V as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-DY5c1E0l.js";
3
+ import { W as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-DjW7LjgJ.js";
4
4
  import { p as parseSlackUserId } from "./actor-D2iXzvlN.js";
5
- import { $ as getStateAdapter, H as findUserByVerifiedEmails, I as resolveActorIdentityId, q as upsertLinkedIdentity, rt as acquireActiveLock, s as getSqlExecutor } from "./db-DV2ZUb1Y.js";
5
+ import { $ as getStateAdapter, H as findUserByVerifiedEmails, I as resolveActorIdentityId, q as upsertLinkedIdentity, rt as acquireActiveLock, s as getSqlExecutor } from "./db-C21CyyTE.js";
6
6
  import { i as homeDir } from "./package-discovery-x4AvVhMj.js";
7
- import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-1pzXmplY.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-B1R-nHd3.js";
9
- import { t as discoverSkills } from "./skills-CPf4vNuC.js";
10
- import { o as finalizeMcpAuthorization } from "./agent-runner-BaLjEjPR.js";
11
- import { O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, f as deleteMcpAuthSession, g as getMcpAuthSession, v as getMcpStoredOAuthCredentials } from "./service-account-DzQiOmqa.js";
12
- import { o as readIdentityById } from "./viewer-DKOeHpv3.js";
13
- import { t as readJuniorSecret } from "./secrets-DHaJ5TTn.js";
14
- import { An as wakeAuthorizedTurn, Rn as deleteWebAuthorization, jn as wakePausedTurn } from "./warmup-mTMIatCV.js";
15
- import { i as lookupSlackUserProfile } from "./users-XCCKn3xW.js";
16
- import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-BXaubz2w.js";
17
- import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-CDhsqPcC.js";
18
- import { n as relayLocalOAuthCallback } from "./oauth-relay-DAmfVmJu.js";
7
+ import { t as discoverSkills } from "./skills-Bm6uSO9V.js";
8
+ import { d as hasRequiredOAuthScope, n as buildOAuthTokenRequest, r as parseOAuthTokenResponse } from "./registry-yht0oxq6.js";
9
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Se9idiDR.js";
10
+ import { o as finalizeMcpAuthorization } from "./agent-runner-DxivxUYd.js";
11
+ import { O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, f as deleteMcpAuthSession, g as getMcpAuthSession, v as getMcpStoredOAuthCredentials } from "./service-account-CZneZHh7.js";
12
+ import { o as readIdentityById } from "./viewer-De1vmuEA.js";
13
+ import { d as readJuniorSecret } from "./task-queue-BEl5G38v.js";
14
+ import { Mn as wakePausedTurn, jn as wakeAuthorizedTurn, zn as deleteWebAuthorization } from "./warmup-C0IblNtf.js";
15
+ import { i as lookupSlackUserProfile } from "./users-6rSdqXXk.js";
16
+ import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-CmQY0T60.js";
17
+ import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-C-SqzubG.js";
18
+ import { n as relayLocalOAuthCallback } from "./oauth-relay-KwDz41Z3.js";
19
19
  import * as z from "zod";
20
20
  import path from "node:path";
21
21
  import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
@@ -75,9 +75,6 @@ var McpOAuthAttemptExpiredError = class extends Error {
75
75
  this.name = "McpOAuthAttemptExpiredError";
76
76
  }
77
77
  };
78
- function mcpAuthorizationId(args) {
79
- return `${args.sessionId}:mcp:${args.provider}`;
80
- }
81
78
  function htmlResponse(kind, options) {
82
79
  const botName = botConfig.userName;
83
80
  const pages = callbackPages(botName);
@@ -102,7 +99,8 @@ async function wakeAuthorizedMcpTurn(args) {
102
99
  authSessionId: authSession.authSessionId,
103
100
  configuration: authSession.configuration,
104
101
  toolChannelId: authSession.toolChannelId,
105
- authorizationId: mcpAuthorizationId({
102
+ authorizationId: authorizationId({
103
+ kind: "mcp",
106
104
  provider,
107
105
  sessionId: authSession.sessionId
108
106
  })
@@ -191,7 +189,8 @@ async function GET$1(request, provider, waitUntil, options) {
191
189
  conversationId: authSession.conversationId,
192
190
  provider,
193
191
  actorId: authSession.userId,
194
- authorizationId: mcpAuthorizationId({
192
+ authorizationId: authorizationId({
193
+ kind: "mcp",
195
194
  provider,
196
195
  sessionId: authSession.sessionId
197
196
  }),
@@ -218,7 +217,8 @@ async function GET$1(request, provider, waitUntil, options) {
218
217
  kind: "mcp",
219
218
  provider,
220
219
  actorId: authSession.userId,
221
- authorizationId: mcpAuthorizationId({
220
+ authorizationId: authorizationId({
221
+ kind: "mcp",
222
222
  provider,
223
223
  sessionId: authSession.sessionId
224
224
  })
@@ -398,9 +398,6 @@ function oauthTokenErrorAttributes(provider, endpoint, status) {
398
398
  ...status !== void 0 ? { "http.response.status_code": status } : void 0
399
399
  };
400
400
  }
401
- function pluginAuthorizationId(args) {
402
- return `${args.sessionId}:plugin:${args.provider}`;
403
- }
404
401
  /** Return the Junior user of the person who started the OAuth connection. */
405
402
  async function resolveOAuthActorUserId(actor) {
406
403
  const identityActor = actor.platform === "web" ? actor : await slackProfileActor(actor);
@@ -466,7 +463,8 @@ async function wakeAuthorizedPluginTurn(stored, options) {
466
463
  provider: stored.provider,
467
464
  actorId: stored.userId,
468
465
  scope: stored.scope,
469
- authorizationId: pluginAuthorizationId({
466
+ authorizationId: authorizationId({
467
+ kind: "plugin",
470
468
  provider: stored.provider,
471
469
  sessionId: turnId
472
470
  })
@@ -577,7 +575,8 @@ async function GET(request, provider, waitUntil, options) {
577
575
  providerLabel,
578
576
  ...account?.label ? { accountLabel: account.label } : void 0,
579
577
  ...stored.resumeSessionId ? {
580
- authorizationId: pluginAuthorizationId({
578
+ authorizationId: authorizationId({
579
+ kind: "plugin",
581
580
  provider,
582
581
  sessionId: stored.resumeSessionId
583
582
  }),
@@ -605,7 +604,8 @@ async function GET(request, provider, waitUntil, options) {
605
604
  kind: "plugin",
606
605
  provider: stored.provider,
607
606
  actorId: stored.userId,
608
- authorizationId: pluginAuthorizationId({
607
+ authorizationId: authorizationId({
608
+ kind: "plugin",
609
609
  provider: stored.provider,
610
610
  sessionId: stored.resumeSessionId
611
611
  })
@@ -1,9 +1,9 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { i as getChatConfig } from "./config-DUD-zMvp.js";
2
+ import { i as getChatConfig } from "./config-DY5c1E0l.js";
3
3
  import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-D2iXzvlN.js";
4
- import { D as juniorConversationEvents, E as isUserInstruction, F as juniorConversations, I as juniorIdentities, L as juniorUsers, N as juniorAttachments, P as juniorMessageAttachments, R as juniorDestinations, T as juniorConversationMetrics, b as juniorConversationParticipants, k as juniorConversationAnnotations, t as createJuniorSqlExecutor, w as CONVERSATION_METRICS, x as juniorConversationBindings } from "./executor-CjNhwwnj.js";
4
+ import { A as juniorConversationEvents, B as juniorUsers, D as CONVERSATION_METRICS, I as juniorAttachments, L as juniorMessageAttachments, M as juniorConversationAnnotations, O as juniorConversationMetrics, R as juniorConversations, S as juniorConversationBindings, V as juniorDestinations, k as isUserInstruction, p as juniorAutomationRuns, t as createJuniorSqlExecutor, x as juniorConversationParticipants, z as juniorIdentities } from "./executor-DfNoVVGd.js";
5
5
  import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-N7IVbUom.js";
6
- import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-oYpJYr-S.js";
6
+ import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-DjW7LjgJ.js";
7
7
  import * as z from "zod";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
@@ -222,6 +222,132 @@ function addAgentTurnUsage(...usages) {
222
222
  };
223
223
  return hasAgentTurnUsage(result) ? result : void 0;
224
224
  }
225
+ // src/api/conversations/aggregate.ts
226
+ function usageTokenValue(source, field) {
227
+ return sql`CASE
228
+ WHEN ${source.usage}->>${field} IS NOT NULL
229
+ THEN (${source.usage}->>${field})::double precision
230
+ ELSE NULL
231
+ END`;
232
+ }
233
+ function tokenValue(source) {
234
+ return sql`
235
+ CASE
236
+ WHEN COALESCE(
237
+ ${source.usage}->>'inputTokens',
238
+ ${source.usage}->>'outputTokens',
239
+ ${source.usage}->>'cachedInputTokens',
240
+ ${source.usage}->>'cacheCreationTokens'
241
+ ) IS NOT NULL
242
+ THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
243
+ + COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
244
+ + COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
245
+ + COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
246
+ WHEN ${source.usage}->>'totalTokens' IS NOT NULL
247
+ THEN (${source.usage}->>'totalTokens')::double precision
248
+ ELSE NULL
249
+ END
250
+ `;
251
+ }
252
+ function costValue(source) {
253
+ return conversationUsageCostExpr(source.usage);
254
+ }
255
+ /** Read one conversation row's usage cost as a SQL expression. */
256
+ function conversationUsageCostExpr(usage) {
257
+ return sql`
258
+ CASE
259
+ WHEN ${usage}->'cost'->>'total' IS NOT NULL
260
+ THEN (${usage}->'cost'->>'total')::double precision
261
+ WHEN COALESCE(
262
+ ${usage}->'cost'->>'input',
263
+ ${usage}->'cost'->>'output',
264
+ ${usage}->'cost'->>'cacheRead',
265
+ ${usage}->'cost'->>'cacheWrite'
266
+ ) IS NOT NULL
267
+ THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
268
+ + COALESCE((${usage}->'cost'->>'output')::double precision, 0)
269
+ + COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
270
+ + COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
271
+ ELSE NULL
272
+ END
273
+ `;
274
+ }
275
+ /** Select complete conversation metrics inside the database instead of materializing source rows. */
276
+ function conversationAggregateColumns(sources) {
277
+ const metrics = sources?.metrics ?? juniorConversations;
278
+ const roots = sources?.roots ?? juniorConversations;
279
+ const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
280
+ return {
281
+ active: sql`${conversationCount} FILTER (
282
+ WHERE ${roots.executionStatus} NOT IN ('idle', 'failed')
283
+ )::integer`,
284
+ conversations: sql`${conversationCount}::integer`,
285
+ cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
286
+ cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
287
+ costUsd: sql`SUM(${costValue(metrics)})::double precision`,
288
+ durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
289
+ failed: sql`${conversationCount} FILTER (
290
+ WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
291
+ )::integer`,
292
+ inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
293
+ tokens: sql`SUM(${tokenValue(metrics)})::double precision`
294
+ };
295
+ }
296
+ /** Select the complete first/last activity range for a grouped conversation aggregate. */
297
+ function conversationRangeColumns() {
298
+ return {
299
+ firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
300
+ lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
301
+ };
302
+ }
303
+ // src/db/micro-usd.ts
304
+ /**
305
+ * Postgres stores every money value as whole micro-USD, in a `bigint` column
306
+ * or an integer metric value named `*_micro_usd`. Integer sums are exact and
307
+ * do not depend on row order. Round once where a USD amount is stored, and
308
+ * convert to USD once where the API returns it. `pnpm money-units:check`
309
+ * keeps money scales in this file.
310
+ */
311
+ const MICRO_USD_PER_USD = 1e6;
312
+ /** Round a USD amount to whole micro-USD for storage. */
313
+ function usdToMicroUsd(usd) {
314
+ return Math.round(usd * MICRO_USD_PER_USD);
315
+ }
316
+ /** Convert stored micro-USD to USD for an API response. */
317
+ function microUsdToUsd(microUsd) {
318
+ return microUsd / MICRO_USD_PER_USD;
319
+ }
320
+ /** SQL that rounds a USD amount to whole micro-USD. */
321
+ function usdToMicroUsdSql(usd) {
322
+ return sql`round(${usd} * 1000000)::bigint`;
323
+ }
324
+ /** SQL that converts micro-USD to USD, for usage JSON in USD. */
325
+ function microUsdToUsdSql(microUsd) {
326
+ return sql`(${microUsd}) / 1000000.0::double precision`;
327
+ }
328
+ /**
329
+ * SQL that reads a micro-USD value or sum as an exact integer. Postgres
330
+ * returns `bigint` as text, so this maps it to a number.
331
+ */
332
+ function microUsdSql(microUsd) {
333
+ return sql`(${microUsd})::bigint`.mapWith(Number);
334
+ }
335
+ // src/chat/automations/run-cost.ts
336
+ /**
337
+ * SQL for a Conversation's usage cost in whole micro-USD, the unit of a run's
338
+ * `cost_micro_usd`.
339
+ */
340
+ function costMicroUsdExpr(usage) {
341
+ return usdToMicroUsdSql(conversationUsageCostExpr(usage));
342
+ }
343
+ /**
344
+ * SQL that reads the cost of one Conversation, for the `cost_micro_usd` of its
345
+ * run. Set it in each run write that links a run to its Conversation, because
346
+ * the Conversation can record usage before its run row exists.
347
+ */
348
+ function conversationCostOf(conversationId) {
349
+ return sql`(select ${costMicroUsdExpr(juniorConversations.usage)} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
350
+ }
225
351
  // src/chat/conversations/metrics.ts
226
352
  function finite(value) {
227
353
  return value !== void 0 && Number.isFinite(value) && value >= 0 ? value : void 0;
@@ -229,6 +355,7 @@ function finite(value) {
229
355
  /** Convert one Run summary to metric rows. */
230
356
  function conversationMetricValues(args) {
231
357
  const usage = args.usage;
358
+ const costUsd = agentTurnCostUsd(usage);
232
359
  return {
233
360
  duration_ms: Math.max(0, args.durationMs),
234
361
  total_tokens: agentTurnTotalTokens(usage),
@@ -237,7 +364,7 @@ function conversationMetricValues(args) {
237
364
  cached_input_tokens: finite(usage?.cachedInputTokens),
238
365
  cache_creation_tokens: finite(usage?.cacheCreationTokens),
239
366
  reasoning_tokens: finite(usage?.reasoningTokens),
240
- cost_usd: agentTurnCostUsd(usage)
367
+ cost_micro_usd: costUsd === void 0 ? void 0 : usdToMicroUsd(costUsd)
241
368
  };
242
369
  }
243
370
  /**
@@ -260,12 +387,12 @@ async function readConversationRunMetrics(executor, args) {
260
387
  cacheCreationTokens: values.get("cache_creation_tokens")
261
388
  };
262
389
  const hasComponents = Object.values(components).some((value) => value !== void 0);
263
- const costUsd = values.get("cost_usd");
390
+ const costMicroUsd = values.get("cost_micro_usd");
264
391
  const usage = Object.fromEntries(Object.entries({
265
392
  ...components,
266
393
  reasoningTokens: values.get("reasoning_tokens"),
267
394
  totalTokens: hasComponents ? void 0 : values.get("total_tokens"),
268
- cost: costUsd === void 0 ? void 0 : { total: costUsd }
395
+ cost: costMicroUsd === void 0 ? void 0 : { total: microUsdToUsd(costMicroUsd) }
269
396
  }).filter(([, value]) => value !== void 0));
270
397
  return {
271
398
  durationMs,
@@ -313,9 +440,10 @@ async function replaceConversationMetrics(executor, args) {
313
440
  or ${metric("cached_input_tokens")} is not null
314
441
  or ${metric("cache_creation_tokens")} is not null
315
442
  `;
316
- const cost = sql`case when ${metric("cost_usd")} is null then null
317
- else jsonb_build_object('total', ${metric("cost_usd")}) end`;
318
- await executor.db().update(juniorConversations).set({
443
+ const cost = sql`case when ${metric("cost_micro_usd")} is null then null
444
+ else jsonb_build_object('total', ${microUsdToUsdSql(metric("cost_micro_usd"))}) end`;
445
+ const db = executor.db();
446
+ const usageUpdate = db.$with("conversation_usage_update").as(db.update(juniorConversations).set({
319
447
  durationMs: sql`coalesce(${metric("duration_ms")}, 0)`,
320
448
  usage: sql`case
321
449
  when ${totalTokens} is not null
@@ -337,7 +465,8 @@ async function replaceConversationMetrics(executor, args) {
337
465
  ))
338
466
  end`,
339
467
  detailVersion: nextDetailVersion
340
- }).where(eq(juniorConversations.conversationId, args.conversationId));
468
+ }).where(eq(juniorConversations.conversationId, args.conversationId)).returning({ costMicroUsd: costMicroUsdExpr(juniorConversations.usage).as("cost_micro_usd") }));
469
+ await db.with(usageUpdate).update(juniorAutomationRuns).set({ costMicroUsd: sql`(select ${usageUpdate.costMicroUsd} from ${usageUpdate})` }).where(eq(juniorAutomationRuns.conversationId, args.conversationId));
341
470
  }
342
471
  // src/chat/source.ts
343
472
  /**
@@ -2815,4 +2944,4 @@ async function closeDb() {
2815
2944
  current = void 0;
2816
2945
  await previous?.db.close();
2817
2946
  }
2818
- export { getStateAdapter as $, conversationKindFromRow as A, findLinkedSlackUser as B, withConversationMutationLock as C, postsRunNotices as D, isTopLevelKind as E, findActorIdentityId as F, recordGoogleSignIn as G, findUserByVerifiedEmails as H, resolveActorIdentityId as I, clearCachedUser as J, saveUserTimezone as K, saveActorAvatar as L, setFirstConversationLocation as M, startLocationThread as N, promptModeTurnTools as O, SYSTEM_IDENTITY_ID as P, getDefaultRedisStateAdapterFor as Q, deleteProviderIdentityForSlackUser as R, createSqlStore as S, sameDestination as St, isPersonInput as T, linkedSlackUser as U, findSlackUserByPrimaryEmail as V, readUserTimezone as W, createCache as X, readCachedUserByEmail as Y, disconnectStateAdapter as Z, readConversationTrees as _, nextDetailVersion as _t, getConversationStore as a, withLock as at, lastMessageAtSql as b, parseDestination as bt, hasAnnotationKey as c, parseSessionSource as ct, eventFromRow as d, agentTurnTotalTokens as dt, getStateValues as et, copyMessageLinks as f, agentTurnUsageSchema as ft, conversationDescendants as g, conversationDetailTouch as gt, conversationAncestors as h, rootConversationIsArchived as ht, getConversationMessageSearchStore as i, fenceLock as it, locationFromRow as j, turnBehavior as k, treeHasAnnotationKey as l, addAgentTurnUsage as lt, withConversationEventLock as m, resolveRootConversationId as mt, db_exports as n, MUTATION_LOCK_TTL_MS as nt, getDb as o, claimProviderConversation as ot, deleteMessageLinks as p, hasAgentTurnUsage as pt, upsertLinkedIdentity as q, getConversationEventStore as r, acquireActiveLock as rt, getSqlExecutor as s, getConversationIdByProviderConversation as st, closeDb as t, setStateValues as tt, createSqlConversationEventStore as u, agentTurnCostUsd as ut, setArchivedAt as v, touchConversationDetail as vt, deliversFinalText as w, userMessageQueries as x, requireSlackDestination as xt, loadConversationSlackTenantIds as y, createSlackDestination as yt, deleteProviderIdentityForUser as z };
2947
+ export { getStateAdapter as $, conversationKindFromRow as A, findLinkedSlackUser as B, withConversationMutationLock as C, conversationDetailTouch as Ct, postsRunNotices as D, parseDestination as Dt, isTopLevelKind as E, createSlackDestination as Et, findActorIdentityId as F, recordGoogleSignIn as G, findUserByVerifiedEmails as H, resolveActorIdentityId as I, clearCachedUser as J, saveUserTimezone as K, saveActorAvatar as L, setFirstConversationLocation as M, startLocationThread as N, promptModeTurnTools as O, requireSlackDestination as Ot, SYSTEM_IDENTITY_ID as P, getDefaultRedisStateAdapterFor as Q, deleteProviderIdentityForSlackUser as R, createSqlStore as S, rootConversationIsArchived as St, isPersonInput as T, touchConversationDetail as Tt, linkedSlackUser as U, findSlackUserByPrimaryEmail as V, readUserTimezone as W, createCache as X, readCachedUserByEmail as Y, disconnectStateAdapter as Z, readConversationTrees as _, agentTurnCostUsd as _t, getConversationStore as a, withLock as at, lastMessageAtSql as b, hasAgentTurnUsage as bt, hasAnnotationKey as c, parseSessionSource as ct, eventFromRow as d, microUsdToUsd as dt, getStateValues as et, copyMessageLinks as f, usdToMicroUsd as ft, conversationDescendants as g, addAgentTurnUsage as gt, conversationAncestors as h, conversationUsageCostExpr as ht, getConversationMessageSearchStore as i, fenceLock as it, locationFromRow as j, turnBehavior as k, sameDestination as kt, treeHasAnnotationKey as l, conversationCostOf as lt, withConversationEventLock as m, conversationRangeColumns as mt, db_exports as n, MUTATION_LOCK_TTL_MS as nt, getDb as o, claimProviderConversation as ot, deleteMessageLinks as p, conversationAggregateColumns as pt, upsertLinkedIdentity as q, getConversationEventStore as r, acquireActiveLock as rt, getSqlExecutor as s, getConversationIdByProviderConversation as st, closeDb as t, setStateValues as tt, createSqlConversationEventStore as u, microUsdSql as ut, setArchivedAt as v, agentTurnTotalTokens as vt, deliversFinalText as w, nextDetailVersion as wt, userMessageQueries as x, resolveRootConversationId as xt, loadConversationSlackTenantIds as y, agentTurnUsageSchema as yt, deleteProviderIdentityForUser as z };
@@ -1,4 +1,4 @@
1
- import "./schema-CVbIjrF3.js";
1
+ import "./schema-CRXcj4fj.js";
2
2
  import * as z from "zod";
3
3
  import "@earendil-works/pi-ai";
4
4
  import "drizzle-orm";