@sentry/junior 0.300.0 → 0.302.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-context-Cx9fn9B3.js +43 -0
- package/dist/{admin-UrTniSPO.js → admin-_poE5NKL.js} +2 -2
- package/dist/{agent-runner-bY4_0UPm.js → agent-runner-CY9RvsTX.js} +1367 -10649
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +6 -7
- package/dist/api.d.ts +1 -1
- package/dist/api.js +124 -67
- package/dist/{app-D-AcIcCV.d.ts → app-BpY3wtRP.d.ts} +3 -3
- package/dist/app.d.ts +1 -1
- package/dist/app.js +71 -299
- package/dist/{automation-Dw82oQ-h.js → automation-Cva5ZOwW.js} +1 -1
- package/dist/{background-compaction-queue-B6U3060-.js → background-compaction-queue-CXFq1_Cz.js} +94 -203
- package/dist/{briefs-DqiwWu-n.js → briefs-B3NG-pid.js} +3 -3
- package/dist/{catalog-runtime-D1oYNv04.js → catalog-runtime-Dss0lSV6.js} +1 -1
- package/dist/cli/chat.js +15 -15
- 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-9nHoFiJP.js → config-CzeZiMKs.js} +2 -2
- package/dist/{connections-DZjTN3JC.js → connections-CDYhMfrs.js} +6 -6
- package/dist/{continue-in-slack-Dtv7_U42.js → continue-in-slack-7Uf05ndC.js} +5 -6
- package/dist/{conversation-Dyjq2CZ8.js → conversation-BNXfq6Lb.js} +11 -1
- package/dist/{conversation-feed-CcDxlrlQ.js → conversation-feed-Clf_cv0n.js} +2 -1
- package/dist/{conversation-privacy-D-5HTXjS.js → conversation-privacy-D9xnM5mK.js} +1 -1
- package/dist/{conversation-turn-Cxl8WZD7.js → conversation-turn-D7SEZgTG.js} +16 -17
- package/dist/{credential-sync-C49ClwDX.js → credential-sync-DoD0gW-j.js} +13 -15
- package/dist/{db-BJNo6fK5.js → db-B-gtnNjr.js} +314 -5
- package/dist/{db-2resqBh1.d.ts → db-BdsCzytP.d.ts} +1 -1
- package/dist/{executor-DBIaOeJ_.js → executor-DZg20EqU.js} +39 -4
- package/dist/install-t1KQyTUs.js +228 -0
- package/dist/instrumentation.js +2 -2
- package/dist/{state-zSilNpbi.js → legacy-web-actor-id-C-cEeWqL.js} +33 -4
- package/dist/{lineage-0dereG7H.js → lineage-C79GjoQr.js} +2 -2
- package/dist/{logging-BIclibct.js → logging-C9oDAg4M.js} +7 -3
- package/dist/{message-dkOl-Iii.js → message-BLUCzJXN.js} +8 -8
- package/dist/{model-input-CLo9TaUd.js → model-input-5jwNC45G.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +4 -3
- package/dist/{oauth-callback-server-WmpjfJgQ.js → oauth-callback-server-BBl66vCb.js} +2 -2
- package/dist/{projection-w_X-zi7v.js → projection-CIBwgD3s.js} +437 -97
- package/dist/{prompt-B1Xw46-S.js → prompt-CRQbzp5e.js} +15 -5
- package/dist/queue-DtCDaIct.js +115 -0
- package/dist/{registry-BmP5vnlj.js → registry-DdFQHZ_d.js} +1 -1
- package/dist/{resolve-goo34bJK.js → resolve-CdW4BdrK.js} +4 -229
- package/dist/{result-PVBeU0Wf.js → result-oOMv1t4O.js} +9 -9
- package/dist/{runner-DKrfvNV6.js → runner-DqitLtm-.js} +9 -9
- package/dist/{sandbox-egress-signals-DsUcqrI0.js → sandbox-egress-signals-Bw9I0yfJ.js} +1 -1
- package/dist/{schema-Dns-sTas.d.ts → schema-BIFM-U1a.d.ts} +470 -30
- package/dist/{schema-C9iNFz5n.js → schema-DnVQepWP.js} +76 -31
- package/dist/{service-account-CMAAloAL.js → service-account-B6mKAPVo.js} +3 -3
- package/dist/{service-account-CmowamcB.js → service-account-CrZftRTb.js} +257 -6
- package/dist/{session-stop-BcAXze8a.js → session-stop-DW63Z3kj.js} +1103 -1007
- package/dist/{skills-DfsazET6.js → skills-C16fz60Z.js} +2 -2
- package/dist/{slack-conversation-unfurl-CzQonuWz.js → slack-conversation-unfurl-BHhefEb7.js} +8 -7
- package/dist/{spawn-C7o0FDDp.js → spawn-D_RnFYfy.js} +6 -6
- package/dist/{stop-CFOujp8C.js → stop-7p1i08CY.js} +941 -2311
- package/dist/{store-E3x2Fg_F.js → store-C28I0CVW.js} +5 -5
- package/dist/{task-queue-D-hCqdZW.js → task-queue-BVUJbQ28.js} +3 -3
- package/dist/{task-runner-vohUPLHe.js → task-runner-CWi8j7Z6.js} +6 -8
- package/dist/{thread-context-BzvdkgI9.js → thread-context-D3-yYUd0.js} +8 -8
- package/dist/{store-Dkeis_8o.js → turn-session-routing-BFMS9ATF.js} +382 -11
- package/dist/{turn-user-message-D5RnVmxQ.js → turn-user-message-C3-O8Omt.js} +3 -3
- package/dist/{validation-BbWikeSa.js → validation-BSFKUIb4.js} +1 -1
- package/dist/{version-GVBMW2jA.js → version-BHHXNi-0.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-BpxRliyO.js → viewer-B1SO21Qa.js} +3 -3
- package/dist/warmup-Bz9bzkzN.js +13927 -0
- package/dist/{statuses-Hn-HsOph.js → web-message-id-lNodcCOI.js} +136 -1
- package/dist/{worker-Cbd-iuwZ.js → worker-BspReIIK.js} +7 -7
- package/migrations/0108_conversation_embeddings.sql +13 -0
- package/migrations/meta/0108_snapshot.json +4688 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +10 -8
- package/dist/adapter-S5UkjNK3.js +0 -303
- package/dist/reporting-window-DopzcOHh.js +0 -137
- package/dist/turn-session-routing-Bo_LxFum.js +0 -380
- package/dist/users-2bggndVg.js +0 -424
- package/dist/warmup-BW2qwnal.js +0 -3693
|
@@ -1,22 +1,21 @@
|
|
|
1
1
|
import { i as getActiveSpan, r as continueTrace, v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { A as latestConversationMessageSeq,
|
|
3
|
-
import { n as botConfig } from "./config-
|
|
4
|
-
import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-
|
|
5
|
-
import { C as isPersonInput,
|
|
6
|
-
import {
|
|
2
|
+
import { A as latestConversationMessageSeq, Di as verifyTimerWatchCredentialSubject, I as upsertConversationMessage, M as normalizeConversationText, N as recordDeliveredAssistantMessage, a as loadProjection, at as failTurnRecord, b as persistConversationMessages, bn as persistWithRetry, j as markConversationMessage, nt as saveTurnCheckpoint, st as getTurnRecord, t as commitAcceptedReply, un as getAssistantReplyText, v as hydrateConversationMessages } from "./projection-CIBwgD3s.js";
|
|
3
|
+
import { n as botConfig } from "./config-CzeZiMKs.js";
|
|
4
|
+
import { E as withSpan, S as setTags, h as logWarn, p as logException } from "./logging-C9oDAg4M.js";
|
|
5
|
+
import { C as isPersonInput, D as turnBehavior, a as getConversationStore, ft as nextDetailVersion, o as getDb, r as getConversationEventStore, s as getSqlExecutor, w as isTopLevelKind } from "./db-B-gtnNjr.js";
|
|
6
|
+
import { M as juniorConversations } from "./executor-DZg20EqU.js";
|
|
7
7
|
import { p as instructionProvenanceFor } from "./history-IjdmO_r6.js";
|
|
8
|
-
import { f as credentialContextForActor } from "./registry-
|
|
9
|
-
import {
|
|
10
|
-
import { o as isEventConversationMessage } from "./prompt-
|
|
11
|
-
import { Y as readMessageAttachments } from "./conversation-
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import { t as
|
|
18
|
-
import {
|
|
19
|
-
import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-vohUPLHe.js";
|
|
8
|
+
import { f as credentialContextForActor } from "./registry-DdFQHZ_d.js";
|
|
9
|
+
import { i as measureTurnCompactionWait } from "./agent-runner-CY9RvsTX.js";
|
|
10
|
+
import { o as isEventConversationMessage } from "./prompt-CRQbzp5e.js";
|
|
11
|
+
import { Y as readMessageAttachments } from "./conversation-BNXfq6Lb.js";
|
|
12
|
+
import { D as turnInputFactsFromConversationMessage, E as sourceFromTurnInput, I as maybePostAutomatedTurnLimitNotice, M as isEventMailboxMetadata, N as renderEventBatchInputs, O as legacyWebMailboxMetadataSchema, P as timerWatchCredentialSubject, U as recordFinishedTurnForAutomatedLimit, c as loadReviewItemInput, f as buildSteeringPiMessage, g as withoutSavedSteeringMessages, j as eventBatchMessageMeta, m as instructionForInputs, p as instructionActorFor, s as eventReviewItemInputs, x as getEventBatchDelayMs } from "./session-stop-DW63Z3kj.js";
|
|
13
|
+
import { An as supersedeOpenMailboxTurns, Gn as executeTurn, Tt as resolveConversationDestination, Vn as createWebAuthorization, Wn as AgentRunError, an as childAgentTurnOptions, bn as completeCancelledConversationTurn, ln as readParentMessage, on as isParentMessageMeta } from "./warmup-Bz9bzkzN.js";
|
|
14
|
+
import { B as blockScheduledAutomation, E as notifyAutomationBlocked, X as blockEventAutomation, a as getPersistedThreadState, c as coerceThreadConversationState, g as getDispatchRecord, i as getPersistedSandboxState, k as readAutomationExecutionByConversationId, m as getDispatchIdForConversation, s as persistThreadStateById } from "./turn-session-routing-BFMS9ATF.js";
|
|
15
|
+
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-C3-O8Omt.js";
|
|
16
|
+
import { t as readConversationLineage } from "./lineage-C79GjoQr.js";
|
|
17
|
+
import { c as buildDeliveredTurnStatePatch, l as loadPendingMessageCards, o as completeAuthPauseTurn, r as finalizeFailedTurnReplyWithEvent, t as buildTurnThreadContext } from "./thread-context-D3-yYUd0.js";
|
|
18
|
+
import { n as scheduleSessionCompletedPluginTasks, t as processPluginTask } from "./task-runner-CWi8j7Z6.js";
|
|
20
19
|
import { isDeepStrictEqual } from "node:util";
|
|
21
20
|
import { createHash } from "node:crypto";
|
|
22
21
|
import { and, eq, isNotNull, isNull } from "drizzle-orm";
|
|
@@ -1,21 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { R as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-
|
|
3
|
-
import {
|
|
1
|
+
import { $n as resolvePluginOAuthAccount, Da as postSlackMessage, Xo as getSlackClient, Z as getConversationPendingAuth, Zn as createUserTokenStore, ca as formatProviderLabel, d as recordAuthorizationCompleted, la as parseOAuthStatePayload, st as getTurnRecord, u as recordAuthenticationLinked, ua as resolveBaseUrl } from "./projection-CIBwgD3s.js";
|
|
2
|
+
import { R as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-CzeZiMKs.js";
|
|
3
|
+
import { W as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-C9oDAg4M.js";
|
|
4
4
|
import { p as parseSlackUserId } from "./actor-D2iXzvlN.js";
|
|
5
|
-
import {
|
|
6
|
-
import { r as getStateAdapter, s as acquireActiveLock } from "./adapter-S5UkjNK3.js";
|
|
5
|
+
import { H as upsertLinkedIdentity, J as getStateAdapter, P as resolveActorIdentityId, Q as acquireActiveLock, R as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-B-gtnNjr.js";
|
|
7
6
|
import { i as homeDir } from "./package-discovery-DJhGdS4c.js";
|
|
8
|
-
import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-
|
|
9
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
10
|
-
import { t as discoverSkills } from "./skills-
|
|
11
|
-
import {
|
|
12
|
-
import { o as readIdentityById } from "./viewer-
|
|
7
|
+
import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-DdFQHZ_d.js";
|
|
8
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-Dss0lSV6.js";
|
|
9
|
+
import { t as discoverSkills } from "./skills-C16fz60Z.js";
|
|
10
|
+
import { o as finalizeMcpAuthorization } from "./agent-runner-CY9RvsTX.js";
|
|
11
|
+
import { o as readIdentityById } from "./viewer-B1SO21Qa.js";
|
|
13
12
|
import { t as readJuniorSecret } from "./secrets-DebYU866.js";
|
|
14
|
-
import {
|
|
15
|
-
import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-DZjTN3JC.js";
|
|
13
|
+
import { Fn as wakePausedTurn, Hn as deleteWebAuthorization, I as lookupSlackUserProfile, Pn as wakeAuthorizedTurn } from "./warmup-Bz9bzkzN.js";
|
|
14
|
+
import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-BFMS9ATF.js";
|
|
15
|
+
import { O as getMcpProviderErrorAttributes, S as putMcpStoredOAuthCredentials, f as deleteMcpAuthSession, g as getMcpAuthSession, v as getMcpStoredOAuthCredentials } from "./service-account-CrZftRTb.js";
|
|
16
|
+
import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-CDYhMfrs.js";
|
|
19
17
|
import { n as relayLocalOAuthCallback } from "./oauth-relay-DRzq73b6.js";
|
|
20
18
|
import * as z from "zod";
|
|
21
19
|
import path from "node:path";
|
|
@@ -1,15 +1,17 @@
|
|
|
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-CzeZiMKs.js";
|
|
3
|
+
import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-C9oDAg4M.js";
|
|
4
4
|
import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-D2iXzvlN.js";
|
|
5
|
-
import { C as
|
|
5
|
+
import { C as juniorConversationMetrics, D as juniorConversationAnnotations, F as juniorDestinations, M as juniorConversations, N as juniorIdentities, P as juniorUsers, S as CONVERSATION_METRICS, T as juniorConversationEvents, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as isUserInstruction, y as juniorConversationBindings } from "./executor-DZg20EqU.js";
|
|
6
6
|
import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-IjdmO_r6.js";
|
|
7
|
-
import { l as withLock, r as getStateAdapter } from "./adapter-S5UkjNK3.js";
|
|
8
7
|
import * as z from "zod";
|
|
9
8
|
import { randomUUID } from "node:crypto";
|
|
10
9
|
import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
|
|
11
10
|
import { destinationSchema, locationSchema, sourceSchema } from "@sentry/junior-plugin-api";
|
|
12
11
|
import { alias } from "drizzle-orm/pg-core";
|
|
12
|
+
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
13
|
+
import { createRedisState } from "@chat-adapter/state-redis";
|
|
14
|
+
import { setTimeout } from "node:timers/promises";
|
|
13
15
|
// src/chat/destination.ts
|
|
14
16
|
/** Build Junior's canonical destination from Slack workspace and channel ids. */
|
|
15
17
|
function createSlackDestination(input) {
|
|
@@ -397,6 +399,304 @@ async function claimProviderConversation(executor, args) {
|
|
|
397
399
|
async function bindProviderConversation(executor, args) {
|
|
398
400
|
if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
|
|
399
401
|
}
|
|
402
|
+
// src/chat/state/locks.ts
|
|
403
|
+
const ACTIVE_LOCK_TTL_MS = 9e4;
|
|
404
|
+
const MUTATION_LOCK_TTL_MS = 1e4;
|
|
405
|
+
/**
|
|
406
|
+
* Acquire a lock for long-running work that the queued state adapter should
|
|
407
|
+
* keep alive while the owning invocation is still making progress.
|
|
408
|
+
*/
|
|
409
|
+
async function acquireActiveLock(state, threadId) {
|
|
410
|
+
return await state.acquireLock(threadId, ACTIVE_LOCK_TTL_MS);
|
|
411
|
+
}
|
|
412
|
+
/**
|
|
413
|
+
* Run work under one lock, optionally waiting for the current owner.
|
|
414
|
+
* `keepAlive` is for multi-store mutations that must retain ownership until all
|
|
415
|
+
* side effects finish; callers should still fence each blind write.
|
|
416
|
+
*/
|
|
417
|
+
async function withLock(state, key, run, options = {}) {
|
|
418
|
+
const ttlMs = options.ttlMs ?? 9e4;
|
|
419
|
+
const startedAtMs = Date.now();
|
|
420
|
+
let lock;
|
|
421
|
+
while (true) {
|
|
422
|
+
lock = await state.acquireLock(key, ttlMs);
|
|
423
|
+
if (lock) break;
|
|
424
|
+
if (Date.now() - startedAtMs >= (options.waitMs ?? 0)) return { acquired: false };
|
|
425
|
+
await setTimeout(options.retryMs ?? 25, void 0, { ref: false });
|
|
426
|
+
}
|
|
427
|
+
const heartbeat = options.keepAlive ? setInterval(() => void state.extendLock(lock, ttlMs).catch(() => void 0), Math.max(1, Math.floor(ttlMs / 3))) : void 0;
|
|
428
|
+
heartbeat?.unref();
|
|
429
|
+
try {
|
|
430
|
+
return {
|
|
431
|
+
acquired: true,
|
|
432
|
+
value: await run(lock)
|
|
433
|
+
};
|
|
434
|
+
} finally {
|
|
435
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
436
|
+
await state.releaseLock(lock);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* Prove lock ownership immediately before a blind write.
|
|
441
|
+
*
|
|
442
|
+
* Whole-record mutations must stop if their lock expired rather than overwrite
|
|
443
|
+
* state committed by a newer owner.
|
|
444
|
+
*/
|
|
445
|
+
async function fenceLock(state, lock, ttlMs = MUTATION_LOCK_TTL_MS) {
|
|
446
|
+
if (!await state.extendLock(lock, ttlMs)) throw new Error(`Lock ownership was lost before write for ${lock.threadId}`);
|
|
447
|
+
}
|
|
448
|
+
// src/chat/state/adapter.ts
|
|
449
|
+
const ACTIVE_LOCK_HEARTBEAT_MS = 3e4;
|
|
450
|
+
const REDIS_STATE_KEY_PREFIX = "chat-sdk";
|
|
451
|
+
let stateAdapter;
|
|
452
|
+
let redisStateAdapter;
|
|
453
|
+
/** Lazily connect state operations, including queued-adapter lock heartbeats. */
|
|
454
|
+
function createConnectingStateAdapter(base) {
|
|
455
|
+
const connected = async (operation) => {
|
|
456
|
+
await base.connect();
|
|
457
|
+
return await operation();
|
|
458
|
+
};
|
|
459
|
+
return {
|
|
460
|
+
appendToList: (key, value, options) => connected(() => base.appendToList(key, value, options)),
|
|
461
|
+
connect: () => base.connect(),
|
|
462
|
+
disconnect: () => base.disconnect(),
|
|
463
|
+
subscribe: (threadId) => connected(() => base.subscribe(threadId)),
|
|
464
|
+
unsubscribe: (threadId) => connected(() => base.unsubscribe(threadId)),
|
|
465
|
+
isSubscribed: (threadId) => connected(() => base.isSubscribed(threadId)),
|
|
466
|
+
acquireLock: (threadId, ttlMs) => connected(() => base.acquireLock(threadId, ttlMs)),
|
|
467
|
+
releaseLock: (lock) => connected(() => base.releaseLock(lock)),
|
|
468
|
+
extendLock: (lock, ttlMs) => connected(() => base.extendLock(lock, ttlMs)),
|
|
469
|
+
forceReleaseLock: (threadId) => connected(() => base.forceReleaseLock(threadId)),
|
|
470
|
+
enqueue: (threadId, entry, maxSize) => connected(() => base.enqueue(threadId, entry, maxSize)),
|
|
471
|
+
dequeue: (threadId) => connected(() => base.dequeue(threadId)),
|
|
472
|
+
queueDepth: (threadId) => connected(() => base.queueDepth(threadId)),
|
|
473
|
+
get: (key) => connected(() => base.get(key)),
|
|
474
|
+
getList: (key) => connected(() => base.getList(key)),
|
|
475
|
+
set: (key, value, ttlMs) => connected(() => base.set(key, value, ttlMs)),
|
|
476
|
+
setIfNotExists: (key, value, ttlMs) => connected(() => base.setIfNotExists(key, value, ttlMs)),
|
|
477
|
+
delete: (key) => connected(() => base.delete(key))
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
function createPrefixedStateAdapter(base, prefix) {
|
|
481
|
+
const prefixed = (value) => `${prefix}:${value}`;
|
|
482
|
+
const unprefixed = (value) => value.startsWith(`${prefix}:`) ? value.slice(prefix.length + 1) : value;
|
|
483
|
+
const prefixLock = (lock) => ({
|
|
484
|
+
...lock,
|
|
485
|
+
threadId: prefixed(lock.threadId)
|
|
486
|
+
});
|
|
487
|
+
const unprefixLock = (lock) => ({
|
|
488
|
+
...lock,
|
|
489
|
+
threadId: unprefixed(lock.threadId)
|
|
490
|
+
});
|
|
491
|
+
return {
|
|
492
|
+
appendToList: (key, value, options) => base.appendToList(prefixed(key), value, options),
|
|
493
|
+
connect: () => base.connect(),
|
|
494
|
+
disconnect: () => base.disconnect(),
|
|
495
|
+
subscribe: (threadId) => base.subscribe(prefixed(threadId)),
|
|
496
|
+
unsubscribe: (threadId) => base.unsubscribe(prefixed(threadId)),
|
|
497
|
+
isSubscribed: (threadId) => base.isSubscribed(prefixed(threadId)),
|
|
498
|
+
acquireLock: async (threadId, ttlMs) => {
|
|
499
|
+
const lock = await base.acquireLock(prefixed(threadId), ttlMs);
|
|
500
|
+
return lock ? unprefixLock(lock) : null;
|
|
501
|
+
},
|
|
502
|
+
releaseLock: (lock) => base.releaseLock(prefixLock(lock)),
|
|
503
|
+
extendLock: async (lock, ttlMs) => {
|
|
504
|
+
const prefixedLock = prefixLock(lock);
|
|
505
|
+
const extended = await base.extendLock(prefixedLock, ttlMs);
|
|
506
|
+
if (extended) lock.expiresAt = prefixedLock.expiresAt;
|
|
507
|
+
return extended;
|
|
508
|
+
},
|
|
509
|
+
forceReleaseLock: (threadId) => base.forceReleaseLock(prefixed(threadId)),
|
|
510
|
+
enqueue: (threadId, entry, maxSize) => base.enqueue(prefixed(threadId), entry, maxSize),
|
|
511
|
+
dequeue: (threadId) => base.dequeue(prefixed(threadId)),
|
|
512
|
+
queueDepth: (threadId) => base.queueDepth(prefixed(threadId)),
|
|
513
|
+
get: (key) => base.get(prefixed(key)),
|
|
514
|
+
getList: (key) => base.getList(prefixed(key)),
|
|
515
|
+
set: (key, value, ttlMs) => base.set(prefixed(key), value, ttlMs),
|
|
516
|
+
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(prefixed(key), value, ttlMs),
|
|
517
|
+
delete: (key) => base.delete(prefixed(key))
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
function createQueuedStateAdapter(base, options) {
|
|
521
|
+
const heartbeats = /* @__PURE__ */ new Map();
|
|
522
|
+
const shouldHeartbeatLock = (ttlMs) => ttlMs === ACTIVE_LOCK_TTL_MS;
|
|
523
|
+
const heartbeatKey = (lock) => `${lock.threadId}:${lock.token}`;
|
|
524
|
+
const stopHeartbeatByKey = (key) => {
|
|
525
|
+
const heartbeat = heartbeats.get(key);
|
|
526
|
+
if (!heartbeat) return;
|
|
527
|
+
clearInterval(heartbeat.timer);
|
|
528
|
+
heartbeats.delete(key);
|
|
529
|
+
};
|
|
530
|
+
const stopHeartbeat = (lock) => {
|
|
531
|
+
stopHeartbeatByKey(heartbeatKey(lock));
|
|
532
|
+
};
|
|
533
|
+
const stopHeartbeatsForThread = (threadId) => {
|
|
534
|
+
for (const [key, heartbeat] of heartbeats) if (heartbeat.lock.threadId === threadId) stopHeartbeatByKey(key);
|
|
535
|
+
};
|
|
536
|
+
const stopAllHeartbeats = () => {
|
|
537
|
+
for (const key of heartbeats.keys()) stopHeartbeatByKey(key);
|
|
538
|
+
};
|
|
539
|
+
const runHeartbeat = async (key) => {
|
|
540
|
+
const heartbeat = heartbeats.get(key);
|
|
541
|
+
if (!heartbeat || heartbeat.inFlight) return;
|
|
542
|
+
heartbeat.inFlight = true;
|
|
543
|
+
try {
|
|
544
|
+
if (Date.now() - heartbeat.startedAtMs >= options.activeLockMaxAgeMs) {
|
|
545
|
+
stopHeartbeatByKey(key);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
if (!await base.extendLock(heartbeat.lock, heartbeat.ttlMs)) {
|
|
549
|
+
stopHeartbeatByKey(key);
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
heartbeat.lock.expiresAt = Date.now() + heartbeat.ttlMs;
|
|
553
|
+
} catch {} finally {
|
|
554
|
+
const current = heartbeats.get(key);
|
|
555
|
+
if (current === heartbeat) current.inFlight = false;
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
const startOrUpdateHeartbeat = (lock, ttlMs) => {
|
|
559
|
+
const key = heartbeatKey(lock);
|
|
560
|
+
const existing = heartbeats.get(key);
|
|
561
|
+
if (existing) {
|
|
562
|
+
existing.ttlMs = ttlMs;
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
const timer = setInterval(() => {
|
|
566
|
+
runHeartbeat(key);
|
|
567
|
+
}, ACTIVE_LOCK_HEARTBEAT_MS);
|
|
568
|
+
timer.unref?.();
|
|
569
|
+
heartbeats.set(key, {
|
|
570
|
+
inFlight: false,
|
|
571
|
+
lock,
|
|
572
|
+
startedAtMs: Date.now(),
|
|
573
|
+
timer,
|
|
574
|
+
ttlMs
|
|
575
|
+
});
|
|
576
|
+
};
|
|
577
|
+
const acquireLock = async (threadId, ttlMs) => {
|
|
578
|
+
const lock = await base.acquireLock(threadId, ttlMs);
|
|
579
|
+
if (lock && shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
|
|
580
|
+
return lock;
|
|
581
|
+
};
|
|
582
|
+
return {
|
|
583
|
+
appendToList: (key, value, options) => base.appendToList(key, value, options),
|
|
584
|
+
connect: () => base.connect(),
|
|
585
|
+
disconnect: async () => {
|
|
586
|
+
stopAllHeartbeats();
|
|
587
|
+
await base.disconnect();
|
|
588
|
+
},
|
|
589
|
+
subscribe: (threadId) => base.subscribe(threadId),
|
|
590
|
+
unsubscribe: (threadId) => base.unsubscribe(threadId),
|
|
591
|
+
isSubscribed: (threadId) => base.isSubscribed(threadId),
|
|
592
|
+
acquireLock,
|
|
593
|
+
releaseLock: async (lock) => {
|
|
594
|
+
stopHeartbeat(lock);
|
|
595
|
+
await base.releaseLock(lock);
|
|
596
|
+
},
|
|
597
|
+
extendLock: async (lock, ttlMs) => {
|
|
598
|
+
const extended = await base.extendLock(lock, ttlMs);
|
|
599
|
+
if (extended) {
|
|
600
|
+
lock.expiresAt = Date.now() + ttlMs;
|
|
601
|
+
if (shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
|
|
602
|
+
else stopHeartbeat(lock);
|
|
603
|
+
} else stopHeartbeat(lock);
|
|
604
|
+
return extended;
|
|
605
|
+
},
|
|
606
|
+
forceReleaseLock: async (threadId) => {
|
|
607
|
+
stopHeartbeatsForThread(threadId);
|
|
608
|
+
await base.forceReleaseLock(threadId);
|
|
609
|
+
},
|
|
610
|
+
enqueue: (threadId, entry, maxSize) => base.enqueue(threadId, entry, maxSize),
|
|
611
|
+
dequeue: (threadId) => base.dequeue(threadId),
|
|
612
|
+
queueDepth: (threadId) => base.queueDepth(threadId),
|
|
613
|
+
get: (key) => base.get(key),
|
|
614
|
+
getList: (key) => base.getList(key),
|
|
615
|
+
set: (key, value, ttlMs) => base.set(key, value, ttlMs),
|
|
616
|
+
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(key, value, ttlMs),
|
|
617
|
+
delete: (key) => base.delete(key)
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
function withOptionalPrefix(base, prefix) {
|
|
621
|
+
return prefix ? createPrefixedStateAdapter(base, prefix) : base;
|
|
622
|
+
}
|
|
623
|
+
function createStateAdapter() {
|
|
624
|
+
const config = getChatConfig();
|
|
625
|
+
const activeLockMaxAgeMs = config.bot.turnTimeoutMs + ACTIVE_LOCK_TTL_MS;
|
|
626
|
+
if (config.state.adapter === "memory") {
|
|
627
|
+
redisStateAdapter = void 0;
|
|
628
|
+
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(createMemoryState(), config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
629
|
+
}
|
|
630
|
+
if (!config.state.redisUrl) throw new Error("REDIS_URL is required for durable Slack thread state");
|
|
631
|
+
const redisState = createRedisState({
|
|
632
|
+
keyPrefix: REDIS_STATE_KEY_PREFIX,
|
|
633
|
+
url: config.state.redisUrl
|
|
634
|
+
});
|
|
635
|
+
redisStateAdapter = redisState;
|
|
636
|
+
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(redisState, config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
637
|
+
}
|
|
638
|
+
function getOptionalRedisStateAdapter() {
|
|
639
|
+
getStateAdapter();
|
|
640
|
+
return redisStateAdapter;
|
|
641
|
+
}
|
|
642
|
+
async function getConnectedStateContext() {
|
|
643
|
+
const adapter = getStateAdapter();
|
|
644
|
+
await adapter.connect();
|
|
645
|
+
return {
|
|
646
|
+
redisStateAdapter: getOptionalRedisStateAdapter(),
|
|
647
|
+
stateAdapter: adapter
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
/** Return the Redis adapter only when the caller is using the default state adapter. */
|
|
651
|
+
async function getDefaultRedisStateAdapterFor(adapter) {
|
|
652
|
+
if (adapter !== stateAdapter) return;
|
|
653
|
+
const context = await getConnectedStateContext();
|
|
654
|
+
return context.stateAdapter === adapter ? context.redisStateAdapter : void 0;
|
|
655
|
+
}
|
|
656
|
+
/** The Redis key that the default Redis adapter uses for one state value key. */
|
|
657
|
+
function redisStateKey(key) {
|
|
658
|
+
const prefix = getChatConfig().state.keyPrefix;
|
|
659
|
+
return `${REDIS_STATE_KEY_PREFIX}:cache:${prefix ? `${prefix}:` : ""}${key}`;
|
|
660
|
+
}
|
|
661
|
+
/** Read state values in one Redis round trip. Other adapters read each key. */
|
|
662
|
+
async function getStateValues(state, keys) {
|
|
663
|
+
if (keys.length === 0) return [];
|
|
664
|
+
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
665
|
+
if (!redis) return await Promise.all(keys.map((key) => state.get(key)));
|
|
666
|
+
return (await redis.getClient().mGet(keys.map(redisStateKey))).map((value) => {
|
|
667
|
+
if (value === null) return null;
|
|
668
|
+
try {
|
|
669
|
+
return JSON.parse(value);
|
|
670
|
+
} catch {
|
|
671
|
+
return value;
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
}
|
|
675
|
+
/** Write state values with one TTL in one Redis round trip. */
|
|
676
|
+
async function setStateValues(state, entries, ttlMs) {
|
|
677
|
+
if (entries.length === 0) return;
|
|
678
|
+
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
679
|
+
if (!redis) {
|
|
680
|
+
await Promise.all(entries.map(({ key, value }) => state.set(key, value, ttlMs)));
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
const pipeline = redis.getClient().multi();
|
|
684
|
+
for (const { key, value } of entries) pipeline.set(redisStateKey(key), JSON.stringify(value), { PX: ttlMs });
|
|
685
|
+
await pipeline.execAsPipeline();
|
|
686
|
+
}
|
|
687
|
+
function getStateAdapter() {
|
|
688
|
+
if (!stateAdapter) stateAdapter = createStateAdapter();
|
|
689
|
+
return stateAdapter;
|
|
690
|
+
}
|
|
691
|
+
async function disconnectStateAdapter() {
|
|
692
|
+
if (!stateAdapter) return;
|
|
693
|
+
try {
|
|
694
|
+
await stateAdapter.disconnect();
|
|
695
|
+
} finally {
|
|
696
|
+
stateAdapter = void 0;
|
|
697
|
+
redisStateAdapter = void 0;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
400
700
|
// src/chat/state/cache.ts
|
|
401
701
|
const MAX_CACHE_KEY_LENGTH = 512;
|
|
402
702
|
const LOAD_WAIT_MS = 1e4;
|
|
@@ -1095,6 +1395,15 @@ function turnBehavior(args) {
|
|
|
1095
1395
|
if (!args.personInput) return AGENT_IN_TASK;
|
|
1096
1396
|
throw new Error("A task Conversation cannot have a person's input");
|
|
1097
1397
|
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Return the Turn tools of one Prompt mode. A person's Turn in a Thread also
|
|
1400
|
+
* uses the `conversation` mode with no agent tools, so this is the widest set.
|
|
1401
|
+
*/
|
|
1402
|
+
function promptModeTurnTools(mode) {
|
|
1403
|
+
if (mode === "automation") return AUTOMATION_RUN.tools;
|
|
1404
|
+
if (mode === "child_agent") return AGENT_IN_TASK.tools;
|
|
1405
|
+
return ROOT.tools;
|
|
1406
|
+
}
|
|
1098
1407
|
/** Return whether a Conversation of this kind has no parent. */
|
|
1099
1408
|
function isTopLevelKind(kind) {
|
|
1100
1409
|
return kind === "root" || kind === "automation";
|
|
@@ -2264,4 +2573,4 @@ async function closeDb() {
|
|
|
2264
2573
|
current = void 0;
|
|
2265
2574
|
await previous?.db.close();
|
|
2266
2575
|
}
|
|
2267
|
-
export {
|
|
2576
|
+
export { fenceLock as $, setFirstConversationLocation as A, recordGoogleSignIn as B, isPersonInput as C, turnBehavior as D, promptModeTurnTools as E, saveActorAvatar as F, createCache as G, upsertLinkedIdentity as H, deleteProviderIdentityForSlackUser as I, getStateAdapter as J, disconnectStateAdapter as K, deleteProviderIdentityForUser as L, SYSTEM_IDENTITY_ID as M, findActorIdentityId as N, conversationKindFromRow as O, resolveActorIdentityId as P, acquireActiveLock as Q, findUserByVerifiedEmails as R, deliversFinalText as S, postsRunNotices as T, clearCachedUser as U, saveUserTimezone as V, readCachedUserByEmail as W, setStateValues as X, getStateValues as Y, MUTATION_LOCK_TTL_MS as Z, loadConversationSlackTenantIds as _, sameDestination as _t, getConversationStore as a, agentTurnCostUsd as at, createSqlStore as b, hasAnnotationKey as c, hasAgentTurnUsage as ct, eventFromRow as d, conversationDetailTouch as dt, withLock as et, withConversationEventLock as f, nextDetailVersion as ft, setArchivedAt as g, requireSlackDestination as gt, readConversationTrees as h, parseDestination as ht, getConversationMessageSearchStore as i, addAgentTurnUsage as it, startLocationThread as j, locationFromRow as k, treeHasAnnotationKey as l, resolveRootConversationId as lt, conversationDescendants as m, createSlackDestination as mt, db_exports as n, getConversationIdByProviderConversation as nt, getDb as o, agentTurnTotalTokens as ot, conversationAncestors as p, touchConversationDetail as pt, getDefaultRedisStateAdapterFor as q, getConversationEventStore as r, parseSessionSource as rt, getSqlExecutor as s, agentTurnUsageSchema as st, closeDb as t, claimProviderConversation as tt, createSqlConversationEventStore as u, rootConversationIsArchived as ut, lastMessageAtSql as v, isTopLevelKind as w, withConversationMutationLock as x, userMessageQueries as y, readUserTimezone as z };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { _ as withScope } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import "./config-
|
|
3
|
-
import { h as logWarn, p as logException } from "./logging-
|
|
2
|
+
import "./config-CzeZiMKs.js";
|
|
3
|
+
import { h as logWarn, p as logException } from "./logging-C9oDAg4M.js";
|
|
4
4
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
5
|
import { sql } from "drizzle-orm";
|
|
6
|
-
import { bigint, boolean, check, date, doublePrecision, foreignKey, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
|
|
6
|
+
import { bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
|
|
7
7
|
import { Pool, neon } from "@neondatabase/serverless";
|
|
8
8
|
import { drizzle } from "drizzle-orm/neon-serverless";
|
|
9
9
|
import { Agent } from "undici";
|
|
@@ -392,6 +392,40 @@ const juniorConversationBriefs = pgTable("junior_conversation_briefs", {
|
|
|
392
392
|
index("junior_conversation_briefs_conversation_version_idx").on(table.conversationId, table.version.desc()),
|
|
393
393
|
index("junior_conversation_briefs_search_idx").using("gin", sql`to_tsvector('english', ${table.searchText})`)
|
|
394
394
|
]);
|
|
395
|
+
// src/db/schema/conversation-embeddings.ts
|
|
396
|
+
/**
|
|
397
|
+
* pgvector column without a fixed size, so a change of embedding model needs
|
|
398
|
+
* no migration. The dimensions column records the size of each row.
|
|
399
|
+
*/
|
|
400
|
+
const vector = customType({
|
|
401
|
+
dataType() {
|
|
402
|
+
return "vector";
|
|
403
|
+
},
|
|
404
|
+
toDriver(value) {
|
|
405
|
+
return JSON.stringify(value);
|
|
406
|
+
},
|
|
407
|
+
fromDriver(value) {
|
|
408
|
+
return value.slice(1, -1).split(",").map(Number);
|
|
409
|
+
}
|
|
410
|
+
});
|
|
411
|
+
/**
|
|
412
|
+
* One embedding per Conversation, for semantic search. Its text is the latest
|
|
413
|
+
* Brief. A derived index: the next Brief replaces the row, and deleting that
|
|
414
|
+
* Brief row deletes it.
|
|
415
|
+
*/
|
|
416
|
+
const juniorConversationEmbeddings = pgTable("junior_conversation_embeddings", {
|
|
417
|
+
conversationId: text("conversation_id").primaryKey(),
|
|
418
|
+
briefVersion: integer("brief_version").notNull(),
|
|
419
|
+
provider: text("provider").notNull(),
|
|
420
|
+
model: text("model").notNull(),
|
|
421
|
+
dimensions: integer("dimensions").notNull(),
|
|
422
|
+
embedding: vector("embedding").notNull(),
|
|
423
|
+
createdAt: timestamptz("created_at").defaultNow().notNull()
|
|
424
|
+
}, (table) => [foreignKey({
|
|
425
|
+
name: "junior_conversation_embeddings_brief_fk",
|
|
426
|
+
columns: [table.conversationId, table.briefVersion],
|
|
427
|
+
foreignColumns: [juniorConversationBriefs.conversationId, juniorConversationBriefs.version]
|
|
428
|
+
}).onDelete("cascade"), check("junior_conversation_embeddings_dimensions_check", sql`vector_dims(${table.embedding}) = ${table.dimensions}`)]);
|
|
395
429
|
// src/db/schema/conversation-bindings.ts
|
|
396
430
|
/** Provider conversation coordinates bound to Junior's opaque durable conversation id. */
|
|
397
431
|
const juniorConversationBindings = pgTable("junior_conversation_bindings", {
|
|
@@ -792,6 +826,7 @@ const juniorSqlSchema = {
|
|
|
792
826
|
juniorAgentInvocations,
|
|
793
827
|
juniorConversationEvents,
|
|
794
828
|
juniorConversationMetrics,
|
|
829
|
+
juniorConversationEmbeddings,
|
|
795
830
|
juniorConversationBriefs,
|
|
796
831
|
juniorConversationBindings,
|
|
797
832
|
juniorConversationParticipants,
|
|
@@ -1299,4 +1334,4 @@ function createJuniorSqlExecutor(args) {
|
|
|
1299
1334
|
statementTimeoutMs
|
|
1300
1335
|
});
|
|
1301
1336
|
}
|
|
1302
|
-
export {
|
|
1337
|
+
export { juniorAttachmentUploads as A, juniorConversationMetrics as C, juniorConversationAnnotations as D, juniorApiTokens as E, juniorDestinations as F, juniorArtifacts as I, juniorConversations as M, juniorIdentities as N, juniorCodeChanges as O, juniorUsers as P, CONVERSATION_METRICS as S, juniorConversationEvents as T, juniorConversationReadPositions as _, juniorPushSubscriptions as a, juniorConversationEmbeddings as b, juniorReviewItemSlackCards as c, juniorAutomationVersions as d, juniorAutomations as f, juniorAgentInvocations as g, juniorAgentBindings as h, juniorWorkspaces as i, juniorAttachments as j, juniorCodeRepositories as k, juniorReviewItems as l, juniorLocationConfigurations as m, juniorSnapshots as n, juniorReviewItemAssignees as o, juniorStats as p, juniorWorkspaceRepos as r, juniorReviewItemConversations as s, createJuniorSqlExecutor as t, juniorAutomationRuns as u, juniorConversationParticipants as v, isUserInstruction as w, juniorConversationBriefs as x, juniorConversationBindings as y };
|