@sentry/junior 0.287.0 → 0.289.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.
- package/dist/{adapter-CL-HUKgd.js → adapter-tE1wnl0T.js} +1 -1
- package/dist/{admin-C9urXVfi.js → admin-BmsPbmO_.js} +2 -2
- package/dist/{agent-runner-Bfnw551N.js → agent-runner-bvl8U5uH.js} +489 -165
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +628 -238
- package/dist/{app-DBY5TnfY.d.ts → app-Cu454FXq.d.ts} +2 -2
- package/dist/app.d.ts +1 -1
- package/dist/app.js +550 -71
- package/dist/assistant-reply-1N9oxyyb.js +58 -0
- package/dist/{automation-DksGNDRO.js → automation-DWbjJltM.js} +2 -2
- package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-D36oCldp.js} +161 -90
- package/dist/{briefs-DaXiMWzT.js → briefs-CV-1qkXa.js} +3 -3
- package/dist/{catalog-runtime-BCIuBe4d.js → catalog-runtime-BNK4uJVZ.js} +1 -1
- package/dist/cli/chat.js +14 -14
- package/dist/cli/check.js +3 -3
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-CkHcUMN7.js → config-DHAy7XlP.js} +363 -8
- package/dist/{connections-BnIj0wtx.js → connections-C3VmH3cf.js} +7 -129
- package/dist/{conversation-E7ZPJx2H.js → conversation-CwC8K3RZ.js} +22 -5
- package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-B0cuLReP.js} +1 -1
- package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-Bky_veSp.js} +1 -1
- package/dist/{credential-sync-CzMar9hq.js → credential-sync-dY9o0YSj.js} +28 -20
- package/dist/{db-DJ11eZqq.js → db-BS2Kql3j.js} +81 -46
- package/dist/{db-YDKKDxlh.d.ts → db-BebRmhsH.d.ts} +10 -2
- package/dist/{executor-BY9TB31g.js → executor-cc4nH86C.js} +125 -18
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-BO5zU6Mt.js → logging-CtCJmt9p.js} +3 -2
- package/dist/{media-Cz1ZiV1U.js → media-BepyEUNm.js} +5 -1
- package/dist/{message-CsUbuEc8.js → message-C5VuRcP9.js} +9 -9
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +19 -41
- package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-KRrYUZ35.js} +2 -2
- package/dist/{projection-CL_YWeGf.js → projection-BFJG58TG.js} +448 -721
- package/dist/{prompt-BHOEQSmf.js → prompt-D15oftoL.js} +5 -5
- package/dist/{registry-BriFLnaJ.js → registry-C_JrgqUz.js} +1 -1
- package/dist/{resolve-Bt6GgAiA.js → resolve-Cn_7JfP-.js} +3 -3
- package/dist/{result-Bo1TZu0Q.js → result-CIbQFLp6.js} +16 -10
- package/dist/{runner-D3YeCQgt.js → runner-BwmaMJVO.js} +8 -8
- package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-BOQ8gn7i.js} +1 -1
- package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
- package/dist/{schema-BWE3RJEB.js → schema-Bptz19Ja.js} +72 -14
- package/dist/{schema-C6fsEwjo.d.ts → schema-DQaFSkZZ.d.ts} +122 -3
- package/dist/{service-account-DiQQuuw7.js → service-account-AGw_pANb.js} +3 -3
- package/dist/{service-account-r6fl0b-9.js → service-account-CLZfF8O1.js} +3 -3
- package/dist/{session-stop-B2Nut40V.js → session-stop-CbzKf7UI.js} +84 -31
- package/dist/{skills-CD5aJdzg.js → skills-CcAJBquq.js} +2 -2
- package/dist/{spawn-CalgZQiu.js → spawn-BvAk2vTI.js} +5 -5
- package/dist/{stop-kujZLbi0.js → stop-BQU4u7la.js} +893 -519
- package/dist/{store-DdIEUL1q.js → store-DE7NJOvQ.js} +4 -16
- package/dist/{task-runner-D_RDr2Hu.js → task-runner-Q_7duP_T.js} +31 -27
- package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-aWZLfUM8.js} +18 -9
- package/dist/{validation-K4pqwoVZ.js → validation-BOoPeIJR.js} +1 -1
- package/dist/{version-DBvhk1X9.js → version-Db0MFy61.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-DrMmFUul.js → viewer-FFEFu9In.js} +4 -4
- package/dist/warmup-DDzrA9Gv.js +967 -0
- package/dist/{work-ljRoODGu.js → work-BBJK458E.js} +16 -15
- package/dist/{worker-CYO1Q0Js.js → worker-2iU5RFyq.js} +7 -31
- package/migrations/0089_conversation_paused_status.sql +3 -0
- package/migrations/0090_guardian_review_time_index.sql +20 -0
- package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
- package/migrations/0092_turn_metric_actor.sql +12 -0
- package/migrations/0093_participant_root_actor_backfill.sql +18 -0
- package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
- package/migrations/meta/0089_snapshot.json +4372 -0
- package/migrations/meta/0090_snapshot.json +4388 -0
- package/migrations/meta/0091_snapshot.json +4410 -0
- package/migrations/meta/0092_snapshot.json +4446 -0
- package/migrations/meta/0093_snapshot.json +4446 -0
- package/migrations/meta/0094_snapshot.json +4452 -0
- package/migrations/meta/_journal.json +42 -0
- package/package.json +6 -5
- package/dist/assistant-reply-u_PRYzuz.js +0 -65
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { An as resolvePluginOAuthAccount, En as createUserTokenStore, Ji as postSlackMessage, Mi as formatProviderLabel, Ni as parseOAuthStatePayload, Pi as resolveBaseUrl, Z as getConversationPendingAuth, aa as getSlackClient, d as recordAuthorizationCompleted, ot as getTurnRecord, u as recordAuthenticationLinked } from "./projection-BFJG58TG.js";
|
|
2
|
+
import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-DHAy7XlP.js";
|
|
3
|
+
import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-CtCJmt9p.js";
|
|
4
4
|
import { p as parseSlackUserId } from "./actor-6jsm_v96.js";
|
|
5
|
-
import { D as resolveActorIdentityId, F as upsertLinkedIdentity, j as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-
|
|
5
|
+
import { D as resolveActorIdentityId, F as upsertLinkedIdentity, j as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-BS2Kql3j.js";
|
|
6
6
|
import { i as homeDir } from "./package-discovery-DJhGdS4c.js";
|
|
7
|
-
import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-
|
|
8
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
9
|
-
import { t as discoverSkills } from "./skills-
|
|
10
|
-
import { a as finalizeMcpAuthorization, d as getMcpStoredOAuthCredentials, f as putMcpStoredOAuthCredentials, o as deleteMcpAuthSession, u as getMcpAuthSession, y as lookupSlackUserProfile
|
|
7
|
+
import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-C_JrgqUz.js";
|
|
8
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-BNK4uJVZ.js";
|
|
9
|
+
import { t as discoverSkills } from "./skills-CcAJBquq.js";
|
|
10
|
+
import { It as wakeAuthorizedTurn, Lt as wakePausedTurn, Yt as deleteWebAuthorization, a as finalizeMcpAuthorization, d as getMcpStoredOAuthCredentials, f as putMcpStoredOAuthCredentials, o as deleteMcpAuthSession, u as getMcpAuthSession, y as lookupSlackUserProfile } from "./agent-runner-bvl8U5uH.js";
|
|
11
11
|
import { r as acquireActiveLock } from "./locks-D-0h111u.js";
|
|
12
|
-
import { o as readIdentityById } from "./viewer-
|
|
13
|
-
import { r as getStateAdapter } from "./adapter-
|
|
14
|
-
import {
|
|
15
|
-
import { _ as getMcpProviderErrorAttributes } from "./service-account-
|
|
16
|
-
import {
|
|
12
|
+
import { o as readIdentityById } from "./viewer-FFEFu9In.js";
|
|
13
|
+
import { r as getStateAdapter } from "./adapter-tE1wnl0T.js";
|
|
14
|
+
import { ht as getPersistedThreadState, vt as coerceThreadConversationState } from "./task-runner-Q_7duP_T.js";
|
|
15
|
+
import { _ as getMcpProviderErrorAttributes } from "./service-account-AGw_pANb.js";
|
|
16
|
+
import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-C3VmH3cf.js";
|
|
17
17
|
import { n as relayLocalOAuthCallback } from "./oauth-relay-D6xxVywK.js";
|
|
18
18
|
import path from "node:path";
|
|
19
19
|
import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
|
|
@@ -51,6 +51,11 @@ function callbackPages(botName) {
|
|
|
51
51
|
message: `This authorization link is no longer active. Return to ${botName} and retry the original request.`,
|
|
52
52
|
status: 400
|
|
53
53
|
},
|
|
54
|
+
connected: {
|
|
55
|
+
title: "Authorization complete",
|
|
56
|
+
message: `Your MCP access is connected. The request that asked for it no longer waits, so ask ${botName} again when you need it.`,
|
|
57
|
+
status: 200
|
|
58
|
+
},
|
|
54
59
|
success: {
|
|
55
60
|
title: "Authorization complete",
|
|
56
61
|
message: `Your MCP access is connected. ${botName} will continue the paused request.`,
|
|
@@ -79,7 +84,7 @@ function htmlResponse(kind, options) {
|
|
|
79
84
|
...pages.success,
|
|
80
85
|
message: `Your MCP access is connected. ${botName} will continue the paused request in the local client.`
|
|
81
86
|
} : pages[kind];
|
|
82
|
-
const footerMessage = kind === "success" && !options?.local ? `You can close this tab and return to ${botName}.` : void 0;
|
|
87
|
+
const footerMessage = (kind === "success" || kind === "connected") && !options?.local ? `You can close this tab and return to ${botName}.` : void 0;
|
|
83
88
|
return htmlCallbackResponse(page.title, page.message, page.status, { footerMessage });
|
|
84
89
|
}
|
|
85
90
|
/** Queue the exact MCP authorization attempt without changing thread state. */
|
|
@@ -102,9 +107,9 @@ async function wakeAuthorizedMcpTurn(args) {
|
|
|
102
107
|
})
|
|
103
108
|
}, args.queue);
|
|
104
109
|
}
|
|
105
|
-
async function
|
|
110
|
+
async function readMcpAuthorizationAttempt(authSession, provider) {
|
|
106
111
|
const conversationId = mcpConversationId(authSession);
|
|
107
|
-
if (!conversationId) return
|
|
112
|
+
if (!conversationId) return "expired";
|
|
108
113
|
const currentState = await getPersistedThreadState(conversationId);
|
|
109
114
|
const conversation = coerceThreadConversationState(currentState);
|
|
110
115
|
const pendingAuth = getConversationPendingAuth({
|
|
@@ -113,13 +118,14 @@ async function isCurrentMcpAuthorizationAttempt(authSession, provider) {
|
|
|
113
118
|
provider,
|
|
114
119
|
actorId: authSession.userId
|
|
115
120
|
});
|
|
116
|
-
|
|
121
|
+
if (!pendingAuth) return "ended";
|
|
122
|
+
return pendingAuth.authSessionId === authSession.authSessionId && pendingAuth.sessionId === authSession.sessionId ? "waiting" : "expired";
|
|
117
123
|
}
|
|
118
124
|
function mcpConversationId(authSession) {
|
|
119
125
|
if (authSession.destination?.platform === "local" || authSession.source?.kind === "web") return authSession.conversationId;
|
|
120
126
|
if (authSession.channelId && authSession.threadTs) return `slack:${authSession.channelId}:${authSession.threadTs}`;
|
|
121
127
|
}
|
|
122
|
-
/** Commit one shared credential mutation only while
|
|
128
|
+
/** Commit one shared credential mutation only while no newer attempt replaced this one. */
|
|
123
129
|
async function runCurrentMcpCredentialMutation(authSession, provider, mutation) {
|
|
124
130
|
const conversationId = mcpConversationId(authSession);
|
|
125
131
|
if (!conversationId) throw new McpOAuthAttemptExpiredError();
|
|
@@ -128,7 +134,7 @@ async function runCurrentMcpCredentialMutation(authSession, provider, mutation)
|
|
|
128
134
|
const lock = await acquireActiveLock(stateAdapter, conversationId);
|
|
129
135
|
if (!lock) throw new Error(`Could not acquire MCP OAuth callback lock for ${conversationId}`);
|
|
130
136
|
try {
|
|
131
|
-
if (
|
|
137
|
+
if (await readMcpAuthorizationAttempt(authSession, provider) === "expired") throw new McpOAuthAttemptExpiredError();
|
|
132
138
|
return await mutation();
|
|
133
139
|
} finally {
|
|
134
140
|
await stateAdapter.releaseLock(lock);
|
|
@@ -167,7 +173,8 @@ async function GET$1(request, provider, waitUntil, options) {
|
|
|
167
173
|
if (!code) return htmlResponse("missing_code");
|
|
168
174
|
try {
|
|
169
175
|
const pendingSession = await getMcpAuthSession(state);
|
|
170
|
-
|
|
176
|
+
const attempt = pendingSession?.provider === provider ? await readMcpAuthorizationAttempt(pendingSession, provider) : "expired";
|
|
177
|
+
if (!pendingSession || attempt === "expired") {
|
|
171
178
|
if (pendingSession) await deleteMcpAuthSession(pendingSession.authSessionId);
|
|
172
179
|
return htmlResponse("expired");
|
|
173
180
|
}
|
|
@@ -227,6 +234,7 @@ async function GET$1(request, provider, waitUntil, options) {
|
|
|
227
234
|
queue: options.conversationWorkQueue,
|
|
228
235
|
provider
|
|
229
236
|
});
|
|
237
|
+
if (attempt === "ended") return htmlResponse("connected");
|
|
230
238
|
return htmlResponse("success", { local: authSession.destination?.platform === "local" && authSession.source?.kind !== "web" });
|
|
231
239
|
} catch (callbackError) {
|
|
232
240
|
if (callbackError instanceof McpOAuthAttemptExpiredError) {
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { i as getChatConfig } from "./config-
|
|
3
|
-
import {
|
|
2
|
+
import { i as getChatConfig } from "./config-DHAy7XlP.js";
|
|
3
|
+
import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-CtCJmt9p.js";
|
|
4
4
|
import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-6jsm_v96.js";
|
|
5
|
-
import { A as juniorConversations, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, S as juniorConversationMetrics, j as juniorIdentities, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-
|
|
6
|
-
import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-
|
|
5
|
+
import { A as juniorConversations, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, S as juniorConversationMetrics, j as juniorIdentities, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-cc4nH86C.js";
|
|
6
|
+
import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-BepyEUNm.js";
|
|
7
7
|
import { randomUUID } from "node:crypto";
|
|
8
8
|
import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
|
|
9
9
|
import { destinationSchema, locationSchema, sourceSchema } from "@sentry/junior-plugin-api";
|
|
@@ -37,6 +37,32 @@ function sameDestination(left, right) {
|
|
|
37
37
|
if (left.platform === "slack" && right.platform === "slack") return left.teamId === right.teamId && left.channelId === right.channelId;
|
|
38
38
|
return false;
|
|
39
39
|
}
|
|
40
|
+
// src/chat/conversations/sql/detail-version.ts
|
|
41
|
+
/** SQL that advances `detail_version` inside a `juniorConversations` set. */
|
|
42
|
+
const nextDetailVersion = sql`${juniorConversations.detailVersion} + 1`;
|
|
43
|
+
function bumpDetailVersion(db, conversationIds) {
|
|
44
|
+
return db.update(juniorConversations).set({ detailVersion: nextDetailVersion }).where(inArray(juniorConversations.conversationId, [...conversationIds]));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Return a CTE that marks the detail report of each Conversation as changed,
|
|
48
|
+
* in the same statement as the write that it covers:
|
|
49
|
+
* `db.with(conversationDetailTouch(db, ids)).insert(table)`.
|
|
50
|
+
* Postgres runs a data-modifying CTE even when the statement does not read it,
|
|
51
|
+
* and both changes commit together.
|
|
52
|
+
*/
|
|
53
|
+
function conversationDetailTouch(db, conversationIds) {
|
|
54
|
+
return db.$with("conversation_detail_touch").as(bumpDetailVersion(db, conversationIds).returning({ conversationId: juniorConversations.conversationId }));
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Mark the detail report of each Conversation as changed, for a write that
|
|
58
|
+
* cannot carry `conversationDetailTouch`. Call it after that write, in the same
|
|
59
|
+
* transaction when there is one. A bump before the write lets a detail read
|
|
60
|
+
* store old content under the new version.
|
|
61
|
+
*/
|
|
62
|
+
async function touchConversationDetail(db, conversationIds) {
|
|
63
|
+
if (conversationIds.length === 0) return;
|
|
64
|
+
await bumpDetailVersion(db, conversationIds);
|
|
65
|
+
}
|
|
40
66
|
// src/chat/conversations/sql/participants.ts
|
|
41
67
|
/** Resolve the root conversation id that owns personal-feed membership. */
|
|
42
68
|
async function resolveRootConversationId(executor, conversationId) {
|
|
@@ -75,6 +101,24 @@ async function recordConversationParticipant(executor, args) {
|
|
|
75
101
|
});
|
|
76
102
|
return true;
|
|
77
103
|
}
|
|
104
|
+
/**
|
|
105
|
+
* Add a User as a Participant of each root that their Identity started,
|
|
106
|
+
* when that Identity gets its User after the roots exist. The root write
|
|
107
|
+
* adds a Participant only for an Identity that already has a User.
|
|
108
|
+
*/
|
|
109
|
+
async function recordStartedConversationParticipants(executor, args) {
|
|
110
|
+
const roots = await executor.db().select({
|
|
111
|
+
conversationId: juniorConversations.conversationId,
|
|
112
|
+
lastActivityAt: juniorConversations.lastActivityAt
|
|
113
|
+
}).from(juniorConversations).where(and(eq(juniorConversations.actorIdentityId, args.identityId), isNull(juniorConversations.parentConversationId)));
|
|
114
|
+
if (roots.length === 0) return;
|
|
115
|
+
const added = await executor.db().insert(juniorConversationParticipants).values(roots.map((root) => ({
|
|
116
|
+
userId: args.userId,
|
|
117
|
+
rootConversationId: root.conversationId,
|
|
118
|
+
lastMessageAt: root.lastActivityAt
|
|
119
|
+
}))).onConflictDoNothing().returning({ rootConversationId: juniorConversationParticipants.rootConversationId });
|
|
120
|
+
await touchConversationDetail(executor.db(), added.map((row) => row.rootConversationId));
|
|
121
|
+
}
|
|
78
122
|
// src/chat/usage.ts
|
|
79
123
|
const agentTurnUsageSchema = usageSchema;
|
|
80
124
|
const COMPONENT_USAGE_FIELDS = [
|
|
@@ -174,32 +218,6 @@ function addAgentTurnUsage(...usages) {
|
|
|
174
218
|
};
|
|
175
219
|
return hasAgentTurnUsage(result) ? result : void 0;
|
|
176
220
|
}
|
|
177
|
-
// src/chat/conversations/sql/detail-version.ts
|
|
178
|
-
/** SQL that advances `detail_version` inside a `juniorConversations` set. */
|
|
179
|
-
const nextDetailVersion = sql`${juniorConversations.detailVersion} + 1`;
|
|
180
|
-
function bumpDetailVersion(db, conversationIds) {
|
|
181
|
-
return db.update(juniorConversations).set({ detailVersion: nextDetailVersion }).where(inArray(juniorConversations.conversationId, [...conversationIds]));
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Return a CTE that marks the detail report of each Conversation as changed,
|
|
185
|
-
* in the same statement as the write that it covers:
|
|
186
|
-
* `db.with(conversationDetailTouch(db, ids)).insert(table)`.
|
|
187
|
-
* Postgres runs a data-modifying CTE even when the statement does not read it,
|
|
188
|
-
* and both changes commit together.
|
|
189
|
-
*/
|
|
190
|
-
function conversationDetailTouch(db, conversationIds) {
|
|
191
|
-
return db.$with("conversation_detail_touch").as(bumpDetailVersion(db, conversationIds).returning({ conversationId: juniorConversations.conversationId }));
|
|
192
|
-
}
|
|
193
|
-
/**
|
|
194
|
-
* Mark the detail report of each Conversation as changed, for a write that
|
|
195
|
-
* cannot carry `conversationDetailTouch`. Call it after that write, in the same
|
|
196
|
-
* transaction when there is one. A bump before the write lets a detail read
|
|
197
|
-
* store old content under the new version.
|
|
198
|
-
*/
|
|
199
|
-
async function touchConversationDetail(db, conversationIds) {
|
|
200
|
-
if (conversationIds.length === 0) return;
|
|
201
|
-
await bumpDetailVersion(db, conversationIds);
|
|
202
|
-
}
|
|
203
221
|
// src/chat/conversations/metrics.ts
|
|
204
222
|
function finite(value) {
|
|
205
223
|
return value !== void 0 && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
@@ -262,6 +280,7 @@ async function replaceConversationMetrics(executor, args) {
|
|
|
262
280
|
const values = CONVERSATION_METRICS.flatMap((metric) => {
|
|
263
281
|
const value = metricValues[metric];
|
|
264
282
|
return value === void 0 ? [] : [{
|
|
283
|
+
actorIdentityId: args.actorIdentityId ?? null,
|
|
265
284
|
conversationId: args.conversationId,
|
|
266
285
|
runId: args.runId,
|
|
267
286
|
metric,
|
|
@@ -353,12 +372,19 @@ function parseSessionSource(value) {
|
|
|
353
372
|
async function getConversationIdByProviderConversation(executor, args) {
|
|
354
373
|
return (await executor.db().select({ conversationId: juniorConversationBindings.conversationId }).from(juniorConversationBindings).where(and(eq(juniorConversationBindings.provider, args.provider), eq(juniorConversationBindings.providerTenantId, args.providerTenantId), eq(juniorConversationBindings.providerDestinationId, args.providerDestinationId), eq(juniorConversationBindings.providerConversationId, args.providerConversationId))).limit(1))[0]?.conversationId;
|
|
355
374
|
}
|
|
356
|
-
/**
|
|
357
|
-
|
|
358
|
-
|
|
375
|
+
/**
|
|
376
|
+
* Bind provider coordinates to a durable conversation unless another
|
|
377
|
+
* conversation has them. Return whether they belong to this conversation.
|
|
378
|
+
*/
|
|
379
|
+
async function claimProviderConversation(executor, args) {
|
|
380
|
+
return ((await executor.db().insert(juniorConversationBindings).values({
|
|
359
381
|
...args,
|
|
360
382
|
createdAt: /* @__PURE__ */ new Date()
|
|
361
|
-
}).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args))
|
|
383
|
+
}).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args)) === args.conversationId;
|
|
384
|
+
}
|
|
385
|
+
/** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
|
|
386
|
+
async function bindProviderConversation(executor, args) {
|
|
387
|
+
if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
|
|
362
388
|
}
|
|
363
389
|
// src/chat/identities/sql.ts
|
|
364
390
|
function dateFromMs$1(ms) {
|
|
@@ -447,6 +473,10 @@ async function upsertIdentityRecord(executor, identity, linkedUserId, nowMs) {
|
|
|
447
473
|
if (linkedUserId) throw new Error("Identity conflicts with linked user");
|
|
448
474
|
throw new Error("Identity upsert returned no row");
|
|
449
475
|
}
|
|
476
|
+
if (!existing?.userId && row.userId && identity.kind === "user") await recordStartedConversationParticipants(executor, {
|
|
477
|
+
identityId: row.id,
|
|
478
|
+
userId: row.userId
|
|
479
|
+
});
|
|
450
480
|
return {
|
|
451
481
|
id: row.id,
|
|
452
482
|
...row.userId ? { userId: row.userId } : void 0
|
|
@@ -872,9 +902,6 @@ function executionStatusFromValue(value) {
|
|
|
872
902
|
if (value === "failed" || value === "idle" || value === "pending" || value === "running") return value;
|
|
873
903
|
throw new Error("Conversation record execution status is invalid");
|
|
874
904
|
}
|
|
875
|
-
function executionStatusToSql(status) {
|
|
876
|
-
return status === "paused" ? "awaiting_resume" : status;
|
|
877
|
-
}
|
|
878
905
|
function destinationFromRow(destination) {
|
|
879
906
|
return parseDestination(destination?.provider === "slack" ? {
|
|
880
907
|
platform: "slack",
|
|
@@ -931,6 +958,7 @@ function conversationFromRow(readRow) {
|
|
|
931
958
|
...row.title ? { title: row.title } : void 0,
|
|
932
959
|
...msFromDate(row.transcriptPurgedAt) !== void 0 ? { transcriptPurgedAtMs: msFromDate(row.transcriptPurgedAt) } : void 0,
|
|
933
960
|
...msFromDate(row.stoppedAt) !== void 0 ? { stoppedAtMs: msFromDate(row.stoppedAt) } : void 0,
|
|
961
|
+
...msFromDate(row.deliveryPausedAt) !== void 0 ? { deliveryPausedAtMs: msFromDate(row.deliveryPausedAt) } : void 0,
|
|
934
962
|
...visibility ? { visibility } : void 0
|
|
935
963
|
};
|
|
936
964
|
}
|
|
@@ -987,7 +1015,8 @@ var SqlStore = class {
|
|
|
987
1015
|
}),
|
|
988
1016
|
kind: args.kind,
|
|
989
1017
|
parentConversationId: args.parentConversationId,
|
|
990
|
-
...location ? { location } : void 0
|
|
1018
|
+
...location ? { location } : void 0,
|
|
1019
|
+
...args.title ? { title: args.title } : void 0
|
|
991
1020
|
};
|
|
992
1021
|
await this.upsertConversation({
|
|
993
1022
|
conversation: child,
|
|
@@ -1076,6 +1105,7 @@ var SqlStore = class {
|
|
|
1076
1105
|
} });
|
|
1077
1106
|
if (args.metrics && args.execution.runId) {
|
|
1078
1107
|
await replaceConversationMetrics(this.executor, {
|
|
1108
|
+
actorIdentityId: args.actorIdentityId,
|
|
1079
1109
|
conversationId: args.conversationId,
|
|
1080
1110
|
runId: args.execution.runId,
|
|
1081
1111
|
occurredAtMs: args.createdAtMs,
|
|
@@ -1183,7 +1213,7 @@ var SqlStore = class {
|
|
|
1183
1213
|
lastActivityAt: dateFromMs(conversation.lastActivityAtMs),
|
|
1184
1214
|
updatedAt: dateFromMs(conversation.updatedAtMs),
|
|
1185
1215
|
executionUpdatedAt: conversation.execution.updatedAtMs === void 0 ? null : dateFromMs(conversation.execution.updatedAtMs),
|
|
1186
|
-
executionStatus:
|
|
1216
|
+
executionStatus: conversation.execution.status,
|
|
1187
1217
|
runId: conversation.execution.runId ?? null,
|
|
1188
1218
|
lastCheckpointAt: conversation.execution.lastCheckpointAtMs === void 0 ? null : dateFromMs(conversation.execution.lastCheckpointAtMs),
|
|
1189
1219
|
lastEnqueuedAt: conversation.execution.lastEnqueuedAtMs === void 0 ? null : dateFromMs(conversation.execution.lastEnqueuedAtMs),
|
|
@@ -1641,18 +1671,23 @@ var SqlConversationEventStore = class {
|
|
|
1641
1671
|
return (await this.readCursor(conversationId)).maxHistoryVersion ?? 0;
|
|
1642
1672
|
}
|
|
1643
1673
|
async loadCurrentHistory(conversationId) {
|
|
1644
|
-
const
|
|
1645
|
-
|
|
1646
|
-
return (await
|
|
1674
|
+
const db = this.executor.db();
|
|
1675
|
+
const currentHistoryVersion = db.select({ historyVersion: sql`max(${juniorConversationEvents.historyVersion})` }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
|
|
1676
|
+
return (await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, currentHistoryVersion))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
|
|
1647
1677
|
}
|
|
1648
1678
|
async loadByIdempotencyKey(conversationId, idempotencyKey) {
|
|
1649
1679
|
const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.idempotencyKey, idempotencyKey))).limit(1);
|
|
1650
1680
|
return row ? eventFromRow(row) : void 0;
|
|
1651
1681
|
}
|
|
1682
|
+
async loadEventsAfter(conversationId, afterSeq) {
|
|
1683
|
+
return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), gt(juniorConversationEvents.seq, afterSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
|
|
1684
|
+
}
|
|
1652
1685
|
async loadHistoryContaining(conversationId, seq, throughSeq) {
|
|
1653
|
-
const
|
|
1654
|
-
|
|
1655
|
-
|
|
1686
|
+
const db = this.executor.db();
|
|
1687
|
+
const boundaryHistoryVersion = db.select({ historyVersion: juniorConversationEvents.historyVersion }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.seq, seq)));
|
|
1688
|
+
const rows = await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, boundaryHistoryVersion), throughSeq === void 0 ? void 0 : lte(juniorConversationEvents.seq, Math.max(seq, throughSeq)))).orderBy(asc(juniorConversationEvents.seq));
|
|
1689
|
+
if (rows.length === 0) return void 0;
|
|
1690
|
+
return rows.filter((row) => throughSeq === void 0 || row.seq <= throughSeq).map(eventFromRow);
|
|
1656
1691
|
}
|
|
1657
1692
|
async loadLatestStructuredEvent(conversationId, namespace, name) {
|
|
1658
1693
|
const [row] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "structured_event"), sql`${juniorConversationEvents.payload}->>'namespace' = ${namespace}`, sql`${juniorConversationEvents.payload}->>'name' = ${name}`)).orderBy(desc(juniorConversationEvents.seq)).limit(1);
|
|
@@ -1903,4 +1938,4 @@ async function closeDb() {
|
|
|
1903
1938
|
current = void 0;
|
|
1904
1939
|
await previous?.db.close();
|
|
1905
1940
|
}
|
|
1906
|
-
export { deleteProviderIdentityForUser as A,
|
|
1941
|
+
export { sameDestination as $, deleteProviderIdentityForUser as A, addAgentTurnUsage as B, setFirstConversationLocation as C, resolveActorIdentityId as D, findActorIdentityId as E, upsertLinkedIdentity as F, resolveRootConversationId as G, agentTurnTotalTokens as H, bindProviderConversation as I, nextDetailVersion as J, rootConversationIsArchived as K, claimProviderConversation as L, readUserTimezone as M, recordGoogleSignIn as N, saveActorAvatar as O, saveUserTimezone as P, requireSlackDestination as Q, getConversationIdByProviderConversation as R, locationFromRow as S, SYSTEM_IDENTITY_ID as T, agentTurnUsageSchema as U, agentTurnCostUsd as V, hasAgentTurnUsage as W, createSlackDestination as X, touchConversationDetail as Y, parseDestination as Z, setArchivedAt as _, getConversationStore as a, withConversationMutationLock as b, conversationIdsWithAnnotation as c, createSqlConversationEventStore as d, eventFromRow as f, readConversationTrees as g, conversationDescendants as h, getConversationMessageSearchStore as i, findUserByVerifiedEmails as j, deleteProviderIdentityForSlackUser as k, hasAnnotationKey as l, conversationAncestors as m, db_exports as n, getDb as o, withConversationEventLock as p, conversationDetailTouch as q, getConversationEventStore as r, getSqlExecutor as s, closeDb as t, treeHasAnnotationKey as u, loadConversationSlackTenantIds as v, startLocationThread as w, conversationKindFromRow as x, createSqlStore as y, parseSessionSource as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./schema-
|
|
1
|
+
import "./schema-DQaFSkZZ.js";
|
|
2
2
|
import * as z from "zod";
|
|
3
3
|
import "drizzle-orm";
|
|
4
4
|
import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
|
|
@@ -124,18 +124,24 @@ interface Conversation {
|
|
|
124
124
|
transcriptPurgedAtMs?: number;
|
|
125
125
|
/** When a person stopped this Conversation. Unset when it is not stopped. */
|
|
126
126
|
stoppedAtMs?: number;
|
|
127
|
+
/** Set while a root's Event Turn replies stay out of its Location. */
|
|
128
|
+
deliveryPausedAtMs?: number;
|
|
127
129
|
/** Confirmed Conversation visibility. Undefined means no confirmation exists. */
|
|
128
130
|
visibility?: ConversationPrivacy;
|
|
129
131
|
}
|
|
130
132
|
/** Persist and read durable conversation metadata for reporting surfaces. */
|
|
131
133
|
interface ConversationStore {
|
|
132
|
-
/**
|
|
134
|
+
/**
|
|
135
|
+
* Create one Conversation with an immutable parent and kind. `title` is
|
|
136
|
+
* saved only when the child is new.
|
|
137
|
+
*/
|
|
133
138
|
createChild(args: {
|
|
134
139
|
childConversationId: string;
|
|
135
140
|
kind: Exclude<ConversationKind, "root">;
|
|
136
141
|
parentConversationId: string;
|
|
137
142
|
nowMs?: number;
|
|
138
143
|
source?: ConversationSource;
|
|
144
|
+
title?: string;
|
|
139
145
|
}): Promise<void>;
|
|
140
146
|
get(args: {
|
|
141
147
|
conversationId: string;
|
|
@@ -213,6 +219,8 @@ interface ConversationStore {
|
|
|
213
219
|
* Conversation metric fields cache totals for existing readers.
|
|
214
220
|
*/
|
|
215
221
|
recordExecution(args: {
|
|
222
|
+
/** Identity of the Turn Actor. Its metric rows record it. */
|
|
223
|
+
actorIdentityId?: string;
|
|
216
224
|
channelName?: string;
|
|
217
225
|
conversationId: string;
|
|
218
226
|
/** When this Run started. */
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import "./
|
|
2
|
-
import
|
|
1
|
+
import { _ as withScope } from "./sentry-BRTJqumy.js";
|
|
2
|
+
import "./config-DHAy7XlP.js";
|
|
3
|
+
import { p as logException } from "./logging-CtCJmt9p.js";
|
|
3
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
5
|
import { sql } from "drizzle-orm";
|
|
5
6
|
import { bigint, boolean, check, date, doublePrecision, foreignKey, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
|
|
6
|
-
import { Pool } from "@neondatabase/serverless";
|
|
7
|
+
import { Pool, neon } from "@neondatabase/serverless";
|
|
7
8
|
import { drizzle } from "drizzle-orm/neon-serverless";
|
|
8
9
|
import { migrate } from "drizzle-orm/neon-serverless/migrator";
|
|
10
|
+
import { Agent } from "undici";
|
|
9
11
|
import pg from "pg";
|
|
10
12
|
import { drizzle as drizzle$1 } from "drizzle-orm/node-postgres";
|
|
11
13
|
import { migrate as migrate$1 } from "drizzle-orm/node-postgres/migrator";
|
|
@@ -53,7 +55,7 @@ const juniorUsers = pgTable("junior_users", {
|
|
|
53
55
|
timezone: text("timezone"),
|
|
54
56
|
/** Text the user saved to change how Junior replies to them. */
|
|
55
57
|
customization: text("customization"),
|
|
56
|
-
/**
|
|
58
|
+
/** Push notification hours. Null means the default schedule. */
|
|
57
59
|
notificationSchedule: jsonb("notification_schedule").$type(),
|
|
58
60
|
/** Junior-wide admin role. Only the `junior admin` CLI changes it. */
|
|
59
61
|
isAdmin: boolean("is_admin").notNull().default(false),
|
|
@@ -127,6 +129,11 @@ const juniorConversations = pgTable("junior_conversations", {
|
|
|
127
129
|
* from its parent, clears it.
|
|
128
130
|
*/
|
|
129
131
|
stoppedAt: timestamptz("stopped_at"),
|
|
132
|
+
/**
|
|
133
|
+
* Set while a root's Event Turn replies stay out of its Location. Junior
|
|
134
|
+
* still stores them. A person's next mention in the Location clears it.
|
|
135
|
+
*/
|
|
136
|
+
deliveryPausedAt: timestamptz("delivery_paused_at"),
|
|
130
137
|
durationMs: integer("duration_ms").notNull().default(0),
|
|
131
138
|
usage: jsonb("usage_json").$type(),
|
|
132
139
|
executionDurationMs: integer("execution_duration_ms").notNull().default(0),
|
|
@@ -275,6 +282,7 @@ const juniorConversationEvents = pgTable("junior_conversation_events", {
|
|
|
275
282
|
index("junior_conversation_events_history_version_idx").on(table.conversationId, table.historyVersion, table.seq),
|
|
276
283
|
index("junior_conversation_events_type_idx").on(table.conversationId, table.type, table.seq),
|
|
277
284
|
index("junior_conversation_events_plugin_report_idx").on(sql`(${table.payload}->>'namespace')`, sql`(${table.payload}->>'name')`, table.createdAt).where(sql`${table.type} = 'structured_event'`),
|
|
285
|
+
index("junior_conversation_events_guardian_review_time_idx").on(table.createdAt).where(sql`${table.type} = 'guardian_action_reviewed'`),
|
|
278
286
|
index("junior_conversation_events_plugin_conversation_idx").on(table.conversationId, sql`(${table.payload}->>'namespace')`, sql`(${table.payload}->>'name')`, table.seq).where(sql`${table.type} = 'structured_event'`),
|
|
279
287
|
index("junior_conversation_events_actor_identity_idx").on(table.actorIdentityId, table.conversationId, table.seq),
|
|
280
288
|
index("junior_conversation_events_author_idx").on(table.conversationId, table.actorIdentityId, table.seq).where(sql`${table.actorIdentityId} is not null`),
|
|
@@ -294,11 +302,15 @@ const CONVERSATION_METRICS = [
|
|
|
294
302
|
"reasoning_tokens",
|
|
295
303
|
"cost_usd"
|
|
296
304
|
];
|
|
297
|
-
/**
|
|
305
|
+
/**
|
|
306
|
+
* One metric value for one Conversation Run. A Run is one Turn, so People
|
|
307
|
+
* spend reads the Identity of the Turn Actor from these rows.
|
|
308
|
+
*/
|
|
298
309
|
const juniorConversationMetrics = pgTable("junior_conversation_metrics", {
|
|
299
310
|
conversationId: text("conversation_id").notNull(),
|
|
300
311
|
runId: text("run_id").notNull(),
|
|
301
312
|
metric: text("metric").$type().notNull(),
|
|
313
|
+
actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
|
|
302
314
|
value: doublePrecision("value").notNull(),
|
|
303
315
|
occurredAt: timestamptz("occurred_at").notNull(),
|
|
304
316
|
updatedAt: timestamptz("updated_at").notNull()
|
|
@@ -316,6 +328,7 @@ const juniorConversationMetrics = pgTable("junior_conversation_metrics", {
|
|
|
316
328
|
columns: [table.conversationId],
|
|
317
329
|
foreignColumns: [juniorConversations.conversationId]
|
|
318
330
|
}),
|
|
331
|
+
index("junior_conversation_metrics_actor_identity_occurred_at_idx").on(table.actorIdentityId, table.occurredAt),
|
|
319
332
|
index("junior_conversation_metrics_occurred_at_metric_idx").on(table.occurredAt, table.metric)
|
|
320
333
|
]);
|
|
321
334
|
// src/db/schema/conversation-briefs.ts
|
|
@@ -364,10 +377,11 @@ const juniorConversationBindings = pgTable("junior_conversation_bindings", {
|
|
|
364
377
|
}), index("junior_conversation_bindings_conversation_idx").on(table.conversationId)]);
|
|
365
378
|
// src/db/schema/conversation-participants.ts
|
|
366
379
|
/**
|
|
367
|
-
*
|
|
368
|
-
*
|
|
369
|
-
*
|
|
370
|
-
* row
|
|
380
|
+
* One Participant: a linked user on one root conversation. Rows come from
|
|
381
|
+
* Turn Actors: the root Actor and the authors of Turn input messages, and
|
|
382
|
+
* the root Actor again when their Identity gets its User later. Thread
|
|
383
|
+
* context authors do not get a row. Access and feeds read only these rows.
|
|
384
|
+
* An unsubscribed row keeps access but leaves the active feed.
|
|
371
385
|
*/
|
|
372
386
|
const juniorConversationParticipants = pgTable("junior_conversation_participants", {
|
|
373
387
|
userId: text("user_id").notNull().references(() => juniorUsers.id),
|
|
@@ -399,7 +413,8 @@ const juniorConversationParticipants = pgTable("junior_conversation_participants
|
|
|
399
413
|
}),
|
|
400
414
|
index("junior_conversation_participants_user_activity_idx").on(table.userId, table.lastMessageAt.desc()),
|
|
401
415
|
index("junior_conversation_participants_root_idx").on(table.rootConversationId),
|
|
402
|
-
index("junior_conversation_participants_auto_archive_idx").on(table.userId).where(sql`${table.autoArchive}`)
|
|
416
|
+
index("junior_conversation_participants_auto_archive_idx").on(table.userId).where(sql`${table.autoArchive}`),
|
|
417
|
+
index("junior_conversation_participants_unsubscribed_idx").on(table.userId, table.rootConversationId).where(sql`${table.unsubscribedAt} is not null`)
|
|
403
418
|
]);
|
|
404
419
|
// src/db/schema/conversation-read-positions.ts
|
|
405
420
|
/**
|
|
@@ -757,13 +772,105 @@ const juniorSqlSchema = {
|
|
|
757
772
|
juniorWorkspaces
|
|
758
773
|
};
|
|
759
774
|
// src/db/neon.ts
|
|
775
|
+
const POOL_MAX = 10;
|
|
776
|
+
/**
|
|
777
|
+
* Sends a pool query over Neon's SQL-over-HTTP endpoint when no idle
|
|
778
|
+
* WebSocket client is free.
|
|
779
|
+
*
|
|
780
|
+
* pg-pool reuses the newest idle client, so light polling keeps one or two
|
|
781
|
+
* clients warm and the rest idle out. A parallel read batch then opens about
|
|
782
|
+
* eight WebSockets, each with a new Postgres session. An HTTP query reuses the
|
|
783
|
+
* proxy's cached backend connection, so the batch skips that handshake. The
|
|
784
|
+
* warm path stays on WebSocket. `connect()` and transactions are unchanged.
|
|
785
|
+
*/
|
|
786
|
+
var OverflowPool = class extends Pool {
|
|
787
|
+
pendingAcquires = 0;
|
|
788
|
+
webSocketOnly = new AsyncLocalStorage();
|
|
789
|
+
sql;
|
|
790
|
+
dispatcher;
|
|
791
|
+
statementTimeoutMs;
|
|
792
|
+
constructor(args) {
|
|
793
|
+
super({
|
|
794
|
+
connectionString: args.connectionString,
|
|
795
|
+
max: POOL_MAX,
|
|
796
|
+
idleTimeoutMillis: 6e4,
|
|
797
|
+
statement_timeout: args.statementTimeoutMs
|
|
798
|
+
});
|
|
799
|
+
this.sql = neon(args.connectionString, { fullResults: true });
|
|
800
|
+
this.dispatcher = args.dispatcher;
|
|
801
|
+
this.statementTimeoutMs = args.statementTimeoutMs;
|
|
802
|
+
}
|
|
803
|
+
query(input, values, callback) {
|
|
804
|
+
const query = typeof input === "string" ? { text: input } : input;
|
|
805
|
+
if (callback !== void 0 || typeof values === "function" || typeof query?.text !== "string" || "submit" in query) return super.query(input, values, callback);
|
|
806
|
+
const params = values ?? query.values ?? [];
|
|
807
|
+
if (this.webSocketOnly.getStore() || this.idleCount > this.pendingAcquires || this.totalCount === 0) return this.queryWebSocket(query, params);
|
|
808
|
+
this.growInBackground();
|
|
809
|
+
return this.queryHttp(query, params);
|
|
810
|
+
}
|
|
811
|
+
growInBackground() {
|
|
812
|
+
setImmediate(() => {
|
|
813
|
+
if (this.ending || this.idleCount > 0 || this.totalCount >= POOL_MAX) return;
|
|
814
|
+
this.connect((error, client) => {
|
|
815
|
+
if (client) {
|
|
816
|
+
client.release();
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
logException(error, "db.pool.client.connect_failed", { "app.db.driver": "neon" });
|
|
820
|
+
});
|
|
821
|
+
});
|
|
822
|
+
}
|
|
823
|
+
/** Keep every pool query in `callback` on WebSocket. */
|
|
824
|
+
async onWebSocket(callback) {
|
|
825
|
+
return await this.webSocketOnly.run(true, callback);
|
|
826
|
+
}
|
|
827
|
+
async queryWebSocket(query, params) {
|
|
828
|
+
const client = await this.acquire();
|
|
829
|
+
try {
|
|
830
|
+
const result = await client.query({
|
|
831
|
+
...query,
|
|
832
|
+
values: params
|
|
833
|
+
});
|
|
834
|
+
client.release();
|
|
835
|
+
return result;
|
|
836
|
+
} catch (error) {
|
|
837
|
+
client.release(error);
|
|
838
|
+
throw error;
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
acquire() {
|
|
842
|
+
this.pendingAcquires++;
|
|
843
|
+
return new Promise((resolve, reject) => {
|
|
844
|
+
this.connect((error, client) => {
|
|
845
|
+
this.pendingAcquires--;
|
|
846
|
+
if (client) resolve(client);
|
|
847
|
+
else reject(error);
|
|
848
|
+
});
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
async queryHttp(query, params) {
|
|
852
|
+
const fetchOptions = { dispatcher: this.dispatcher };
|
|
853
|
+
if (this.statementTimeoutMs) fetchOptions.signal = AbortSignal.timeout(this.statementTimeoutMs);
|
|
854
|
+
return await withScope(async (scope) => {
|
|
855
|
+
scope.setAttributes({ "app.db.transport": "http" });
|
|
856
|
+
return await this.sql.query(query.text, params, {
|
|
857
|
+
arrayMode: query.rowMode === "array",
|
|
858
|
+
fullResults: true,
|
|
859
|
+
types: query.types ?? this.options.types,
|
|
860
|
+
fetchOptions
|
|
861
|
+
});
|
|
862
|
+
});
|
|
863
|
+
}
|
|
864
|
+
};
|
|
760
865
|
var NeonExecutor = class {
|
|
761
866
|
transactionClient = new AsyncLocalStorage();
|
|
762
867
|
savepointId = 0;
|
|
763
868
|
isolatedQueryId = 0;
|
|
764
869
|
pool;
|
|
765
|
-
|
|
870
|
+
dispatcher;
|
|
871
|
+
constructor(pool, dispatcher) {
|
|
766
872
|
this.pool = pool;
|
|
873
|
+
this.dispatcher = dispatcher;
|
|
767
874
|
}
|
|
768
875
|
db() {
|
|
769
876
|
return drizzle(this.queryClient(), { schema: juniorSqlSchema });
|
|
@@ -847,13 +954,14 @@ var NeonExecutor = class {
|
|
|
847
954
|
const lockName = `junior:migrate:${migrationTable}`;
|
|
848
955
|
try {
|
|
849
956
|
await client.query("SELECT pg_advisory_lock(hashtext($1))", [lockName]);
|
|
850
|
-
return await callback
|
|
957
|
+
return await this.pool.onWebSocket(callback);
|
|
851
958
|
} finally {
|
|
852
959
|
client.release(true);
|
|
853
960
|
}
|
|
854
961
|
}
|
|
855
962
|
async close() {
|
|
856
963
|
await this.pool.end();
|
|
964
|
+
await this.dispatcher.close();
|
|
857
965
|
}
|
|
858
966
|
queryClient() {
|
|
859
967
|
return this.transactionClient.getStore() ?? this.pool;
|
|
@@ -861,16 +969,15 @@ var NeonExecutor = class {
|
|
|
861
969
|
};
|
|
862
970
|
/** Create the shared Neon-backed Junior SQL executor. */
|
|
863
971
|
function createNeonJuniorSqlExecutor(args) {
|
|
864
|
-
const
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
statement_timeout: args.statementTimeoutMs
|
|
972
|
+
const dispatcher = new Agent({ allowH2: true });
|
|
973
|
+
const pool = new OverflowPool({
|
|
974
|
+
...args,
|
|
975
|
+
dispatcher
|
|
869
976
|
});
|
|
870
977
|
pool.on("error", (error) => {
|
|
871
978
|
logException(error, "db.pool.client.failed", { "app.db.driver": "neon" });
|
|
872
979
|
});
|
|
873
|
-
return new NeonExecutor(pool);
|
|
980
|
+
return new NeonExecutor(pool, dispatcher);
|
|
874
981
|
}
|
|
875
982
|
// src/db/postgres.ts
|
|
876
983
|
const { Pool: Pool$1 } = pg;
|
package/dist/instrumentation.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as getClient, c as init, i as getActiveSpan, o as getGlobalScope, p as spanToJSON, s as getTraceData } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import {
|
|
3
|
-
import { n as getCurrentConversationPrivacy } from "./conversation-privacy-
|
|
2
|
+
import { B as getDeploymentTelemetryAttributes, z as getDeploymentServiceVersion } from "./logging-CtCJmt9p.js";
|
|
3
|
+
import { n as getCurrentConversationPrivacy } from "./conversation-privacy-Bky_veSp.js";
|
|
4
4
|
import { n as redactSandboxEgressProxyPath } from "./proxy-path-BHYoKZdq.js";
|
|
5
5
|
import { t as consumePrivateTraceResultMarker } from "./private-trace-result-CE7_lEdq.js";
|
|
6
6
|
import { n as promoteHttpRouteName, r as routeNameMiddleware, t as nameRequestRoute } from "./sentry-route-name-BhwWnfqj.js";
|