@sentry/junior 0.293.0 → 0.295.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/{admin-uuecrKuD.js → admin-ifgjyfpF.js} +2 -2
- package/dist/{agent-runner-DHq1pjUg.js → agent-runner-DjMTPWEO.js} +192 -100
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +5 -5
- package/dist/api.d.ts +1 -1
- package/dist/api.js +73 -29
- package/dist/{app-fWzCHFIb.d.ts → app-uiTzRbvq.d.ts} +5 -3
- package/dist/app.d.ts +2 -2
- package/dist/app.js +64 -74
- package/dist/{automation-BE3z19VN.js → automation-yJX3C7i3.js} +3 -3
- package/dist/{background-compaction-queue-D7ncdEa6.js → background-compaction-queue-DUkHZjmL.js} +7 -9
- package/dist/{briefs-NpgMEFh1.js → briefs-CbNYM-q2.js} +3 -3
- package/dist/{catalog-runtime-DwbTyNRD.js → catalog-runtime-DgouZKZm.js} +1 -1
- package/dist/cli/chat.d.ts +1 -1
- package/dist/cli/chat.js +15 -15
- package/dist/cli/check.js +3 -3
- package/dist/cli/init.js +2 -0
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.d.ts +1 -1
- package/dist/cli/plugins.js +4 -4
- package/dist/cli/snapshot-create.js +4 -4
- package/dist/cli/upgrade.d.ts +2 -2
- package/dist/cli/upgrade.js +7 -74
- package/dist/{config-B4b-NXH5.js → config-DvnTPCfp.js} +58 -7
- package/dist/{connections-Dz_AQg5p.js → connections-CWaIVl_1.js} +6 -6
- package/dist/{conversation-CtjR1Zcx.js → conversation-CMkSmi02.js} +3 -11
- package/dist/{conversation-pending-messages-1Kad1Mif.js → conversation-feed-BVAOga0H.js} +27 -2
- package/dist/{conversation-privacy-DRsSgLGO.js → conversation-privacy-DPjv4SnA.js} +1 -1
- package/dist/{credential-sync-ClCnnGVj.js → credential-sync-BhbaZfmO.js} +16 -15
- package/dist/{db-BbpttyKH.d.ts → db-CCUqQe0E.d.ts} +13 -6
- package/dist/{db-CoA7_Xqu.js → db-Dts2XvLu.js} +144 -7
- package/dist/{executor-SWyHhit0.js → executor-Ck73J0wP.js} +64 -10
- package/dist/instrumentation.js +2 -2
- package/dist/{logging-BN5drSEZ.js → logging-9OAq-fdg.js} +2 -1
- package/dist/{message-D4qjpW1C.js → message-CtaPzC7m.js} +9 -9
- package/dist/nitro.d.ts +2 -2
- package/dist/nitro.js +2 -2
- package/dist/{oauth-callback-server-Xi-mTLOV.js → oauth-callback-server-C_LXY1d4.js} +2 -2
- package/dist/{oauth-relay-D6xxVywK.js → oauth-relay-CsfIazeF.js} +2 -1
- package/dist/{plugins-DtmjkTza.d.ts → plugins-B_0Cr0MO.d.ts} +0 -1
- package/dist/{projection-DXl4ftyL.js → projection-BzJQncZV.js} +251 -161
- package/dist/{prompt-Dmx6IfWZ.js → prompt-Cbq5b4SO.js} +5 -6
- package/dist/{registry-DosVt9f9.js → registry-cbpOxO4M.js} +3 -13
- package/dist/{resolve-BDjWJC9s.js → resolve-t-pmRdwS.js} +3 -3
- package/dist/{result-CaAFpf4B.js → result-DhgjR3nQ.js} +8 -8
- package/dist/{runner-h96Mkss6.js → runner-CHv9X9TH.js} +8 -8
- package/dist/{sandbox-egress-signals-rK91BW7i.js → sandbox-egress-signals-Yy3fSCbg.js} +1 -1
- package/dist/{schema-C_v8wb80.js → schema-BhneuGYv.js} +39 -7
- package/dist/{schema-CHsBmXIj.d.ts → schema-TSEisVJR.d.ts} +87 -14
- package/dist/secrets-DebYU866.js +18 -0
- package/dist/{service-account-WUMVuqVL.js → service-account-C4rBP8ne.js} +3 -3
- package/dist/{service-account-BpGpScaT.js → service-account-DjPIwCMj.js} +42 -26
- package/dist/{session-stop-xYK15HUu.js → session-stop-DkxI5vc3.js} +20 -775
- package/dist/{skills-DHApyCjj.js → skills-BZE2DP8I.js} +2 -2
- package/dist/{spawn-BQQrwGNe.js → spawn-BvULxIiu.js} +5 -5
- package/dist/{adapter-CMJfmHso.js → state-CO9ETDzk.js} +132 -2
- package/dist/{stop-CBeD6_Gs.js → stop-CL-rdtQb.js} +85 -32
- package/dist/{store-xtibD98L.js → store-DgD78_NK.js} +3 -3
- package/dist/{task-runner-BYPN4BEO.js → task-runner-CKOj6xla.js} +11 -11
- package/dist/{turn-failure-response-jNVl00MD.js → turn-failure-response-BTSo6SMJ.js} +8 -8
- package/dist/{validation-DGeB_moV.js → validation-CXeYgBzq.js} +1 -1
- package/dist/{version-C6nqU3Qc.js → version-AQa7Fr2H.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{viewer-9KLQibjn.js → viewer-Bqkb678l.js} +3 -3
- package/dist/warmup-h6u1e9n0.js +1869 -0
- package/dist/{work-xwX6unUE.js → work-yN_GAuXY.js} +11 -11
- package/dist/{worker-CiCCfwd4.js → worker-Hl7N292I.js} +6 -6
- package/migrations/0062_plugin_report_index.sql +1 -20
- package/migrations/0078_plugin_conversation_index.sql +1 -20
- package/migrations/0079_conversation_event_author_index.sql +1 -20
- package/migrations/0080_conversation_event_latest_message_indexes.sql +2 -27
- package/migrations/0090_guardian_review_time_index.sql +1 -20
- package/migrations/0091_conversation_participant_unsubscribed_index.sql +1 -20
- package/migrations/0097_conversation_kind_automation.sql +6 -0
- package/migrations/0098_review_item_plugin_actions.sql +5 -0
- package/migrations/0099_conversation_last_message_at.sql +1 -0
- package/migrations/0100_automation_task_kind_repair.sql +48 -0
- package/migrations/meta/0097_snapshot.json +4490 -0
- package/migrations/meta/0098_snapshot.json +4490 -0
- package/migrations/meta/0099_snapshot.json +4720 -0
- package/migrations/meta/0100_snapshot.json +4496 -0
- package/migrations/meta/_journal.json +28 -0
- package/package.json +5 -5
- package/dist/assistant-reply-CIApSfor.js +0 -58
- package/dist/warmup-7S6z068f.js +0 -993
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-
|
|
3
|
-
import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-
|
|
2
|
+
import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-9OAq-fdg.js";
|
|
3
|
+
import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DPjv4SnA.js";
|
|
4
4
|
import { AwsClient } from "aws4fetch";
|
|
5
5
|
import { del, get, put } from "@vercel/blob";
|
|
6
6
|
import { calculateCost, completeSimple, getEnvApiKey, getModels, registerApiProvider } from "@earendil-works/pi-ai/compat";
|
|
@@ -207,6 +207,46 @@ function readAttachmentStorageConfig(env) {
|
|
|
207
207
|
default: throw new Error("JUNIOR_ATTACHMENT_STORAGE_PROVIDER must be vercel-blob, s3, or memory");
|
|
208
208
|
}
|
|
209
209
|
}
|
|
210
|
+
// src/chat/encryption/keyring.ts
|
|
211
|
+
/**
|
|
212
|
+
* Encryption keys for secrets that Junior keeps at rest.
|
|
213
|
+
*
|
|
214
|
+
* `JUNIOR_ENCRYPTION_KEYS` lists `<id>:<key>` entries, comma-separated. Each
|
|
215
|
+
* key is 32 random bytes in base64 or base64url. `JUNIOR_ENCRYPTION_KEY_ID`
|
|
216
|
+
* names the key for new values; it is optional when there is one key. All
|
|
217
|
+
* listed keys decrypt. The config fails at startup when a key is invalid, an
|
|
218
|
+
* id repeats, or the active id is not in the list.
|
|
219
|
+
*/
|
|
220
|
+
const KEY_BYTES = 32;
|
|
221
|
+
const KEY_ID_PATTERN = /^[A-Za-z0-9._-]{1,32}$/;
|
|
222
|
+
const KEY_MATERIAL_PATTERN = /^[A-Za-z0-9+/_-]+={0,2}$/;
|
|
223
|
+
function parseKey(entry, index) {
|
|
224
|
+
const separator = entry.indexOf(":");
|
|
225
|
+
const id = entry.slice(0, separator).trim();
|
|
226
|
+
const material = entry.slice(separator + 1).trim();
|
|
227
|
+
if (separator < 0 || !KEY_ID_PATTERN.test(id)) throw new Error(`JUNIOR_ENCRYPTION_KEYS entry ${index + 1} must be <id>:<key> with an id of letters, digits, ".", "_", or "-"`);
|
|
228
|
+
const key = KEY_MATERIAL_PATTERN.test(material) ? Buffer.from(material, "base64") : Buffer.alloc(0);
|
|
229
|
+
if (key.length !== KEY_BYTES) throw new Error(`JUNIOR_ENCRYPTION_KEYS key "${id}" must be ${KEY_BYTES} bytes in base64`);
|
|
230
|
+
return {
|
|
231
|
+
id,
|
|
232
|
+
key
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/** Parse and check the encryption keyring from environment variables. */
|
|
236
|
+
function readEncryptionKeyring(env) {
|
|
237
|
+
const entries = (env.JUNIOR_ENCRYPTION_KEYS ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
|
|
238
|
+
if (entries.length === 0) throw new Error("JUNIOR_ENCRYPTION_KEYS is required. Generate a key with: node -e \"console.log('k1:' + require('node:crypto').randomBytes(32).toString('base64url'))\"");
|
|
239
|
+
const keys = entries.map(parseKey);
|
|
240
|
+
if (new Set(keys.map((key) => key.id)).size !== keys.length) throw new Error("JUNIOR_ENCRYPTION_KEYS must not repeat a key id");
|
|
241
|
+
const activeId = env.JUNIOR_ENCRYPTION_KEY_ID?.trim() || (keys.length === 1 ? keys[0]?.id : void 0);
|
|
242
|
+
if (!activeId) throw new Error("JUNIOR_ENCRYPTION_KEY_ID is required when JUNIOR_ENCRYPTION_KEYS has more than one key");
|
|
243
|
+
const active = keys.find((key) => key.id === activeId);
|
|
244
|
+
if (!active) throw new Error(`JUNIOR_ENCRYPTION_KEY_ID "${activeId}" is not in JUNIOR_ENCRYPTION_KEYS`);
|
|
245
|
+
return {
|
|
246
|
+
active,
|
|
247
|
+
keys
|
|
248
|
+
};
|
|
249
|
+
}
|
|
210
250
|
// src/chat/queue/config.ts
|
|
211
251
|
/** Jobs that one BullMQ worker runs at the same time, for each queue topic. */
|
|
212
252
|
const DEFAULT_BULLMQ_WORKER_CONCURRENCY = 4;
|
|
@@ -401,6 +441,18 @@ function createProviderError(error, options = {}) {
|
|
|
401
441
|
status
|
|
402
442
|
});
|
|
403
443
|
}
|
|
444
|
+
const REFUSAL_STOP_REASONS = /* @__PURE__ */ new Set(["refusal", "sensitive"]);
|
|
445
|
+
/** Return whether the provider refused to answer a Pi assistant message. */
|
|
446
|
+
function isProviderRefusal(message) {
|
|
447
|
+
return message.rawStopReason !== void 0 && REFUSAL_STOP_REASONS.has(message.rawStopReason);
|
|
448
|
+
}
|
|
449
|
+
/** Normalize a failed Pi assistant message. A provider refusal is a content policy block. */
|
|
450
|
+
function createAssistantProviderError(message, options = {}) {
|
|
451
|
+
return createProviderError(message.errorMessage ?? "", {
|
|
452
|
+
...options,
|
|
453
|
+
...isProviderRefusal(message) ? { kind: "content_policy" } : void 0
|
|
454
|
+
});
|
|
455
|
+
}
|
|
404
456
|
/** Return whether a provider-boundary error should be retried. */
|
|
405
457
|
function isProviderRetryError(error) {
|
|
406
458
|
return error instanceof ProviderError && error.retryable;
|
|
@@ -1043,7 +1095,6 @@ async function completeText(params) {
|
|
|
1043
1095
|
...hasCompactedConversationContext(params.messages) ? { "gen_ai.conversation.compacted": true } : void 0,
|
|
1044
1096
|
"app.conversation.privacy": effectivePrivacy,
|
|
1045
1097
|
...params.thinkingLevel ? { "gen_ai.request.reasoning.level": params.thinkingLevel } : void 0,
|
|
1046
|
-
...params.temperature !== void 0 ? { "gen_ai.request.temperature": params.temperature } : void 0,
|
|
1047
1098
|
...params.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": params.maxTokens } : void 0
|
|
1048
1099
|
};
|
|
1049
1100
|
const startAttributes = {
|
|
@@ -1063,7 +1114,6 @@ async function completeText(params) {
|
|
|
1063
1114
|
...params.tools ? { tools: params.tools } : void 0
|
|
1064
1115
|
}, {
|
|
1065
1116
|
apiKey,
|
|
1066
|
-
temperature: params.temperature,
|
|
1067
1117
|
maxTokens: params.maxTokens,
|
|
1068
1118
|
reasoning: params.thinkingLevel,
|
|
1069
1119
|
cacheRetention: params.cacheRetention,
|
|
@@ -1166,7 +1216,6 @@ async function completeObject(params) {
|
|
|
1166
1216
|
schema: params.schema,
|
|
1167
1217
|
prompt: params.prompt,
|
|
1168
1218
|
...params.system !== void 0 ? { system: params.system } : void 0,
|
|
1169
|
-
...params.temperature !== void 0 ? { temperature: params.temperature } : void 0,
|
|
1170
1219
|
...params.maxTokens !== void 0 ? { maxOutputTokens: params.maxTokens } : void 0,
|
|
1171
1220
|
...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
|
|
1172
1221
|
});
|
|
@@ -1185,7 +1234,6 @@ async function completeObject(params) {
|
|
|
1185
1234
|
"server.port": 443,
|
|
1186
1235
|
"gen_ai.provider.auth_mode": credential.mode,
|
|
1187
1236
|
...params.thinkingLevel ? { "gen_ai.request.reasoning.level": params.thinkingLevel } : void 0,
|
|
1188
|
-
...params.temperature !== void 0 ? { "gen_ai.request.temperature": params.temperature } : void 0,
|
|
1189
1237
|
...params.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": params.maxTokens } : void 0
|
|
1190
1238
|
});
|
|
1191
1239
|
} catch (error) {
|
|
@@ -1552,6 +1600,7 @@ function readBotConfig(env, functionMaxDurationSeconds) {
|
|
|
1552
1600
|
embeddingModelId: validateEmbeddingModelId(env.AI_EMBEDDING_MODEL) ?? DEFAULT_EMBEDDING_MODEL_ID,
|
|
1553
1601
|
rerankingModelId: toOptionalTrimmed(env.AI_RERANKING_MODEL) ?? DEFAULT_RERANKING_MODEL_ID,
|
|
1554
1602
|
loadingMessages: parseLoadingMessages(env.JUNIOR_LOADING_MESSAGES),
|
|
1603
|
+
refusalFallbackModelId: validateGatewayModelId(env.AI_REFUSAL_FALLBACK_MODEL),
|
|
1555
1604
|
visionModelId: env.AI_VISION_MODEL === void 0 ? DEFAULT_VISION_MODEL_ID : validateGatewayModelId(env.AI_VISION_MODEL),
|
|
1556
1605
|
maxAgentDepth: 0,
|
|
1557
1606
|
maxSlicesPerTurn: MAX_SLICES_PER_TURN,
|
|
@@ -1605,6 +1654,7 @@ function readChatConfig(env = process.env, functionMaxDurationSeconds = DEFAULT_
|
|
|
1605
1654
|
cacheWarmingEnabled: parseKillSwitch("JUNIOR_CACHE_WARMING_ENABLED", env.JUNIOR_CACHE_WARMING_ENABLED),
|
|
1606
1655
|
conversationWorkEnabled: parseKillSwitch("JUNIOR_CONVERSATION_WORK_ENABLED", env.JUNIOR_CONVERSATION_WORK_ENABLED),
|
|
1607
1656
|
conversationWorkSoftYieldAfterMs: resolveConversationWorkSoftYieldAfterMs(resolvedFunctionMaxDurationSeconds),
|
|
1657
|
+
encryption: readEncryptionKeyring(env),
|
|
1608
1658
|
sql: {
|
|
1609
1659
|
databaseUrl,
|
|
1610
1660
|
driver: readSqlDriver(env, databaseUrl),
|
|
@@ -1715,6 +1765,7 @@ function setBotModelConfig(config) {
|
|
|
1715
1765
|
if (config.rerankingModelId !== void 0) botConfig.rerankingModelId = requireModelId("rerankingModelId", config.rerankingModelId, toOptionalTrimmed);
|
|
1716
1766
|
if (config.imageGenerationModelId !== void 0) botConfig.imageGenerationModelId = requireModelId("imageGenerationModelId", config.imageGenerationModelId, validateEmbeddingModelId);
|
|
1717
1767
|
if (config.visionModelId !== void 0) botConfig.visionModelId = requireModelId("visionModelId", config.visionModelId, validateGatewayModelId);
|
|
1768
|
+
if (config.refusalFallbackModelId !== void 0) botConfig.refusalFallbackModelId = requireModelId("refusalFallbackModelId", config.refusalFallbackModelId, validateGatewayModelId);
|
|
1718
1769
|
if (config.webSearchModelId !== void 0) botConfig.webSearchModelId = requireModelId("webSearchModelId", config.webSearchModelId, validateGatewayModelId);
|
|
1719
1770
|
}
|
|
1720
1771
|
/** Apply Slack reaction emoji overrides from createApp() options, validating names. */
|
|
@@ -1722,4 +1773,4 @@ function setSlackReactionConfig(overrides) {
|
|
|
1722
1773
|
if (overrides.processingReactionEmoji !== void 0) chatConfig.slack.processingReactionEmoji = parseReactionEmoji("processingReactionEmoji", overrides.processingReactionEmoji, chatConfig.slack.processingReactionEmoji);
|
|
1723
1774
|
if (overrides.completedReactionEmoji !== void 0) chatConfig.slack.completedReactionEmoji = parseReactionEmoji("completedReactionEmoji", overrides.completedReactionEmoji, chatConfig.slack.completedReactionEmoji);
|
|
1724
1775
|
}
|
|
1725
|
-
export { estimateTextTokens as A,
|
|
1776
|
+
export { estimateTextTokens as A, createAssistantProviderError as B, completeText as C, requestPrefixAttributes as D, resolveGatewayModel as E, renderCurrentInstruction as F, isProviderRefusal as G, findProviderError as H, unwrapCurrentInstruction as I, resolveGatewayCredential as J, isProviderRetryError as K, escapeXml as L, COMPACTION_SUMMARY_PREFIX as M, hasCompactedConversationContext as N, estimateMessagesTokens as O, isCompactionSummaryText as P, escapeXmlText as R, completeObject as S, rerankTexts as T, getProviderErrorAttributes as U, createProviderError as V, getProviderErrorUserMessage as W, toOptionalTrimmed as X, getAttachmentStorage as Y, toPiReasoningLevel as _, getRuntimeMetadata as a, GEN_AI_SERVER_ADDRESS as b, getSlackClientSecret as c, restoreRuntimeConfig as d, setBotModelConfig as f, TURN_REASONING_LEVELS as g, snapshotRuntimeConfig as h, getChatConfig as i, textCharsForTokens as j, estimateRequestOverheadTokens as k, getSlackSigningSecret as l, setSlackReactionConfig as m, botConfig as n, getSlackBotToken as o, setRuntimeLimits as p, getGatewayApiKey as q, config_exports as r, getSlackClientId as s, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as t, resetRuntimeConfig as u, normalizeSlackEmojiName as v, embedTexts as w, completeDecision as x, GEN_AI_PROVIDER_NAME as y, ProviderError as z };
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { n as botConfig } from "./config-
|
|
3
|
-
import {
|
|
4
|
-
import { u as hasRequiredOAuthScope } from "./registry-
|
|
5
|
-
import { n as pluginCatalogRuntime } from "./catalog-runtime-
|
|
6
|
-
import { c as deleteMcpServerSessionId, l as deleteMcpStoredOAuthCredentials, s as deleteMcpAuthSessionsForUserProvider } from "./agent-runner-
|
|
1
|
+
import { Ii as startOAuthFlow } from "./projection-BzJQncZV.js";
|
|
2
|
+
import { n as botConfig } from "./config-DvnTPCfp.js";
|
|
3
|
+
import { I as deleteProviderIdentityForSlackUser, L as deleteProviderIdentityForUser, s as getSqlExecutor } from "./db-Dts2XvLu.js";
|
|
4
|
+
import { u as hasRequiredOAuthScope } from "./registry-cbpOxO4M.js";
|
|
5
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-DgouZKZm.js";
|
|
6
|
+
import { c as deleteMcpServerSessionId, l as deleteMcpStoredOAuthCredentials, s as deleteMcpAuthSessionsForUserProvider } from "./agent-runner-DjMTPWEO.js";
|
|
7
7
|
import { randomBytes } from "node:crypto";
|
|
8
8
|
// src/handlers/oauth-html.ts
|
|
9
9
|
/** Build pre-escaped callback HTML with the shared response security policy. */
|
|
@@ -305,6 +305,7 @@ const conversationReportStatusSchema = z.enum([
|
|
|
305
305
|
/** Where a Conversation sits in its tree. See `TERMINOLOGY.md`. */
|
|
306
306
|
const conversationKindSchema = z.enum([
|
|
307
307
|
"root",
|
|
308
|
+
"automation",
|
|
308
309
|
"thread",
|
|
309
310
|
"task"
|
|
310
311
|
]);
|
|
@@ -455,6 +456,7 @@ const conversationSummaryReportSchema = z.object({
|
|
|
455
456
|
startedAt: z.string(),
|
|
456
457
|
lastSeenAt: z.string(),
|
|
457
458
|
lastProgressAt: z.string(),
|
|
459
|
+
lastMessageAt: z.string().datetime().optional(),
|
|
458
460
|
surface: conversationSurfaceSchema,
|
|
459
461
|
actorIdentity: actorIdentitySchema.optional(),
|
|
460
462
|
participants: z.array(actorIdentitySchema).optional(),
|
|
@@ -955,14 +957,4 @@ const conversationDetailReportSchema = conversationSummaryReportSchema.extend({
|
|
|
955
957
|
sentryConversationUrl: z.string().optional(),
|
|
956
958
|
sourceTask: conversationSourceTaskSchema.optional()
|
|
957
959
|
}).strict().superRefine(validateConversationEvents);
|
|
958
|
-
|
|
959
|
-
* A root in the feed, or one of its visible Threads. A Thread nests under
|
|
960
|
-
* its nearest visible Thread ancestor, or under the root. Tasks never show.
|
|
961
|
-
*/
|
|
962
|
-
const conversationFeedItemSchema = conversationSummaryReportSchema.extend({ threads: z.lazy(() => z.array(conversationFeedItemSchema)).optional() });
|
|
963
|
-
const conversationFeedSchema = z.object({
|
|
964
|
-
conversations: z.array(conversationFeedItemSchema),
|
|
965
|
-
source: z.literal("conversation_index"),
|
|
966
|
-
generatedAt: z.string()
|
|
967
|
-
}).strict();
|
|
968
|
-
export { renameConversationBodySchema as A, resolveMessageCards as B, createConversationBodySchema as C, conversationChildAgentTotalsSchema as D, forkConversationResponseSchema as E, annotationCard as F, briefCodeChangeSchema as G, MAX_INPUT_IMAGE_BYTES as H, messageCardRef as I, briefResourceLabel as J, briefLinkSchema as K, messageCardText as L, conversationReadPositionSchema as M, conversationReadReportSchema as N, CONVERSATION_TITLE_MAX_LENGTH as O, reviewItemChangeRecordSchema as P, readMessageCardRefs as R, conversationUsageSchema as S, forkConversationBodySchema as T, messageAttachmentSchema as U, MAX_INPUT_IMAGES as V, readMessageAttachments as W, parseBriefInput as X, conversationBriefSchema as Y, parseStoredBrief as Z, conversationReportEventSchema as _, conversationActivityPreviewSchema as a, conversationSummaryReportSchema as b, conversationDetailQuerySchema as c, conversationEventPageSchema as d, conversationEventsQuerySchema as f, conversationReportEventDataSchema as g, conversationParamsSchema as h, actorIdentitySchema as i, renameConversationResponseSchema as j, conversationTitleSchema as k, conversationDetailReportSchema as l, conversationFeedSchema as m, CONVERSATION_VERSION_HEADER as n, conversationAttachmentParamsSchema as o, conversationFeedQuerySchema as p, briefOutcomeStatusSchema as q, acceptedConversationMessageSchema as r, conversationAuxiliaryCostsSchema as s, CONVERSATION_DETAIL_VERSION_HEADER as t, conversationEventHistorySchema as u, conversationReportMessageEventSchema as v, createConversationMessageBodySchema as w, conversationSurfaceSchema as x, conversationReportStatusSchema as y, removedCardSchema as z };
|
|
960
|
+
export { renameConversationResponseSchema as A, MAX_INPUT_IMAGES as B, createConversationMessageBodySchema as C, CONVERSATION_TITLE_MAX_LENGTH as D, conversationChildAgentTotalsSchema as E, messageCardRef as F, briefLinkSchema as G, messageAttachmentSchema as H, messageCardText as I, conversationBriefSchema as J, briefOutcomeStatusSchema as K, readMessageCardRefs as L, conversationReadReportSchema as M, reviewItemChangeRecordSchema as N, conversationTitleSchema as O, annotationCard as P, removedCardSchema as R, createConversationBodySchema as S, forkConversationResponseSchema as T, readMessageAttachments as U, MAX_INPUT_IMAGE_BYTES as V, briefCodeChangeSchema as W, parseStoredBrief as X, parseBriefInput as Y, conversationReportMessageEventSchema as _, conversationActivityPreviewSchema as a, conversationSurfaceSchema as b, conversationDetailQuerySchema as c, conversationEventPageSchema as d, conversationEventsQuerySchema as f, conversationReportEventSchema as g, conversationReportEventDataSchema as h, actorIdentitySchema as i, conversationReadPositionSchema as j, renameConversationBodySchema as k, conversationDetailReportSchema as l, conversationParamsSchema as m, CONVERSATION_VERSION_HEADER as n, conversationAttachmentParamsSchema as o, conversationFeedQuerySchema as p, briefResourceLabel as q, acceptedConversationMessageSchema as r, conversationAuxiliaryCostsSchema as s, CONVERSATION_DETAIL_VERSION_HEADER as t, conversationEventHistorySchema as u, conversationReportStatusSchema as v, forkConversationBodySchema as w, conversationUsageSchema as x, conversationSummaryReportSchema as y, resolveMessageCards as z };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { H as messageAttachmentSchema, K as briefOutcomeStatusSchema, N as reviewItemChangeRecordSchema, i as actorIdentitySchema, l as conversationDetailReportSchema, y as conversationSummaryReportSchema } from "./conversation-CMkSmi02.js";
|
|
2
2
|
import * as z from "zod";
|
|
3
3
|
// src/reporting-schema.ts
|
|
4
4
|
const healthReportSchema = z.object({
|
|
@@ -21,6 +21,8 @@ const skillReportSchema = z.object({
|
|
|
21
21
|
disableModelInvocation: z.boolean().optional()
|
|
22
22
|
}).strict();
|
|
23
23
|
const skillReportsSchema = z.array(skillReportSchema);
|
|
24
|
+
/** One skill with its authored SKILL.md body, without frontmatter. */
|
|
25
|
+
const skillDetailReportSchema = skillReportSchema.extend({ body: z.string() }).strict();
|
|
24
26
|
const pluginPackageContentItemReportSchema = z.object({
|
|
25
27
|
dir: z.string(),
|
|
26
28
|
hasMigrationsDir: z.boolean(),
|
|
@@ -178,4 +180,27 @@ const steerConversationPendingMessagesResponseSchema = z.object({
|
|
|
178
180
|
conversationId: z.string().min(1),
|
|
179
181
|
steeredInboundMessageIds: z.array(z.string().min(1))
|
|
180
182
|
}).strict();
|
|
181
|
-
|
|
183
|
+
// src/api/schema/conversation-feed.ts
|
|
184
|
+
/**
|
|
185
|
+
* The part of a Conversation's latest Brief that a feed row shows: what the
|
|
186
|
+
* work is about and how it stands.
|
|
187
|
+
*/
|
|
188
|
+
const conversationFeedBriefSchema = z.object({
|
|
189
|
+
intent: z.string(),
|
|
190
|
+
status: briefOutcomeStatusSchema,
|
|
191
|
+
summary: z.string()
|
|
192
|
+
}).strict();
|
|
193
|
+
/**
|
|
194
|
+
* A root in the feed, or one of its visible Threads. A Thread nests under
|
|
195
|
+
* its nearest visible Thread ancestor, or under the root. Tasks never show.
|
|
196
|
+
*/
|
|
197
|
+
const conversationFeedItemSchema = conversationSummaryReportSchema.extend({
|
|
198
|
+
brief: conversationFeedBriefSchema.optional(),
|
|
199
|
+
threads: z.lazy(() => z.array(conversationFeedItemSchema)).optional()
|
|
200
|
+
});
|
|
201
|
+
const conversationFeedSchema = z.object({
|
|
202
|
+
conversations: z.array(conversationFeedItemSchema),
|
|
203
|
+
source: z.literal("conversation_index"),
|
|
204
|
+
generatedAt: z.string()
|
|
205
|
+
}).strict();
|
|
206
|
+
export { skillReportsSchema as C, skillReportSchema as S, pluginPackageContentReportSchema as _, conversationDetailWithMailboxReportSchema as a, runtimeInfoReportSchema as b, conversationPendingMessageSchema as c, steerConversationPendingMessagesBodySchema as d, steerConversationPendingMessagesResponseSchema as f, pluginPackageContentItemReportSchema as g, pluginOperationalReportSchema as h, cancelConversationPendingMessagesResponseSchema as i, conversationPendingMessagesReportSchema as l, pluginOperationalReportFeedSchema as m, conversationFeedSchema as n, conversationPendingAuthorizationSchema as o, healthReportSchema as p, cancelConversationPendingMessagesBodySchema as r, conversationPendingMessageDeliverySchema as s, conversationFeedBriefSchema as t, conversationUnchangedDetailWithMailboxSchema as u, pluginSchema as v, skillDetailReportSchema as x, pluginsSchema as y };
|
|
@@ -1,20 +1,21 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-
|
|
3
|
-
import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-
|
|
1
|
+
import { An as resolvePluginOAuthAccount, En as createUserTokenStore, Fi as resolveBaseUrl, Ni as formatProviderLabel, Pi as parseOAuthStatePayload, Yi as postSlackMessage, Z as getConversationPendingAuth, d as recordAuthorizationCompleted, oa as getSlackClient, ot as getTurnRecord, u as recordAuthenticationLinked } from "./projection-BzJQncZV.js";
|
|
2
|
+
import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-DvnTPCfp.js";
|
|
3
|
+
import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-9OAq-fdg.js";
|
|
4
4
|
import { p as parseSlackUserId } from "./actor-6jsm_v96.js";
|
|
5
|
-
import {
|
|
5
|
+
import { H as upsertLinkedIdentity, P as resolveActorIdentityId, R as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-Dts2XvLu.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 { 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-
|
|
7
|
+
import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-cbpOxO4M.js";
|
|
8
|
+
import { n as pluginCatalogRuntime } from "./catalog-runtime-DgouZKZm.js";
|
|
9
|
+
import { t as discoverSkills } from "./skills-BZE2DP8I.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-DjMTPWEO.js";
|
|
11
11
|
import { r as acquireActiveLock } from "./locks-D-0h111u.js";
|
|
12
|
-
import { o as readIdentityById } from "./viewer-
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
12
|
+
import { o as readIdentityById } from "./viewer-Bqkb678l.js";
|
|
13
|
+
import { a as getStateAdapter } from "./state-CO9ETDzk.js";
|
|
14
|
+
import { t as readJuniorSecret } from "./secrets-DebYU866.js";
|
|
15
|
+
import { gt as coerceThreadConversationState, pt as getPersistedThreadState } from "./task-runner-CKOj6xla.js";
|
|
16
|
+
import { _ as getMcpProviderErrorAttributes } from "./service-account-DjPIwCMj.js";
|
|
17
|
+
import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-CWaIVl_1.js";
|
|
18
|
+
import { n as relayLocalOAuthCallback } from "./oauth-relay-CsfIazeF.js";
|
|
18
19
|
import path from "node:path";
|
|
19
20
|
import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
|
|
20
21
|
import * as z from "zod";
|
|
@@ -639,7 +640,7 @@ const localCredentialSyncSchema = z.object({
|
|
|
639
640
|
tokens: pluginStoredTokensSchema
|
|
640
641
|
}).strict();
|
|
641
642
|
function syncSecret() {
|
|
642
|
-
const secret =
|
|
643
|
+
const secret = readJuniorSecret();
|
|
643
644
|
if (!secret) throw new Error("Local credential sync requires JUNIOR_SECRET");
|
|
644
645
|
return secret;
|
|
645
646
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import "./schema-
|
|
1
|
+
import "./schema-TSEisVJR.js";
|
|
2
2
|
import * as z from "zod";
|
|
3
3
|
import "drizzle-orm";
|
|
4
4
|
import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
|
|
@@ -53,11 +53,13 @@ type Usage = z.output<typeof usageSchema>;
|
|
|
53
53
|
type AgentTurnUsage = Usage;
|
|
54
54
|
type ConversationSource = "api" | "internal" | "local" | "plugin" | "event" | "scheduler" | "slack" | "web";
|
|
55
55
|
/**
|
|
56
|
-
* Where a Conversation sits in its tree. A root
|
|
57
|
-
* child that people can message. A Task is a child that
|
|
58
|
-
* messages. A Conversation never changes kind.
|
|
56
|
+
* Where a Conversation sits in its tree. A root and an Automation run have no
|
|
57
|
+
* parent. A Thread is a child that people can message. A Task is a child that
|
|
58
|
+
* only its parent messages. A Conversation never changes kind.
|
|
59
59
|
*/
|
|
60
|
-
type ConversationKind = "root" | "thread" | "task";
|
|
60
|
+
type ConversationKind = "root" | "automation" | "thread" | "task";
|
|
61
|
+
/** The kind of a Conversation that has a parent. */
|
|
62
|
+
type ChildConversationKind = "thread" | "task";
|
|
61
63
|
type ConversationStatus = "paused" | "failed" | "idle" | "pending" | "running";
|
|
62
64
|
/** Cumulative duration and usage that one Run reported. */
|
|
63
65
|
interface ConversationRunMetrics {
|
|
@@ -137,7 +139,7 @@ interface ConversationStore {
|
|
|
137
139
|
*/
|
|
138
140
|
createChild(args: {
|
|
139
141
|
childConversationId: string;
|
|
140
|
-
kind:
|
|
142
|
+
kind: ChildConversationKind;
|
|
141
143
|
parentConversationId: string;
|
|
142
144
|
nowMs?: number;
|
|
143
145
|
source?: ConversationSource;
|
|
@@ -207,6 +209,11 @@ interface ConversationStore {
|
|
|
207
209
|
/** Source normalized to a stable session locator; set-once when absent. */
|
|
208
210
|
sessionSource?: Source;
|
|
209
211
|
title?: string;
|
|
212
|
+
/**
|
|
213
|
+
* Kind of a new Conversation. Default `root`. An existing Conversation
|
|
214
|
+
* keeps its kind.
|
|
215
|
+
*/
|
|
216
|
+
kind?: "root" | "automation";
|
|
210
217
|
/**
|
|
211
218
|
* Current visibility from its owner, such as a Slack event channel type. It
|
|
212
219
|
* replaces the visibility of the shared Destination row. Omit it for saved
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { v as __exportAll } from "./sentry-BRTJqumy.js";
|
|
2
|
-
import { i as getChatConfig } from "./config-
|
|
3
|
-
import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-
|
|
2
|
+
import { i as getChatConfig } from "./config-DvnTPCfp.js";
|
|
3
|
+
import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-9OAq-fdg.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-
|
|
5
|
+
import { A as juniorConversations, C as isUserInstruction, 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-Ck73J0wP.js";
|
|
6
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";
|
|
@@ -838,12 +838,104 @@ async function ensureConversationRow(executor, conversationId, atMs, options = {
|
|
|
838
838
|
}
|
|
839
839
|
});
|
|
840
840
|
}
|
|
841
|
+
const CONVERSATION_KINDS = /* @__PURE__ */ new Set([
|
|
842
|
+
"root",
|
|
843
|
+
"automation",
|
|
844
|
+
"thread",
|
|
845
|
+
"task"
|
|
846
|
+
]);
|
|
841
847
|
/** Decode a stored kind. A null kind comes from a writer of an older deploy. */
|
|
842
848
|
function conversationKindFromRow(row) {
|
|
843
849
|
const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
|
|
844
|
-
if (kind
|
|
850
|
+
if (!CONVERSATION_KINDS.has(kind)) throw new Error("Conversation record kind is invalid");
|
|
845
851
|
return kind;
|
|
846
852
|
}
|
|
853
|
+
// src/chat/conversations/kind-behavior.ts
|
|
854
|
+
const ROOT = {
|
|
855
|
+
delivery: "location",
|
|
856
|
+
promptMode: "conversation",
|
|
857
|
+
gated: false,
|
|
858
|
+
tools: {
|
|
859
|
+
agents: "children",
|
|
860
|
+
reviewDesk: true,
|
|
861
|
+
subscriptions: true,
|
|
862
|
+
userCustomization: true,
|
|
863
|
+
reportBlocked: false,
|
|
864
|
+
noReply: true,
|
|
865
|
+
finishAutomationRun: false
|
|
866
|
+
}
|
|
867
|
+
};
|
|
868
|
+
const PERSON_IN_THREAD = {
|
|
869
|
+
...ROOT,
|
|
870
|
+
tools: {
|
|
871
|
+
...ROOT.tools,
|
|
872
|
+
agents: "none"
|
|
873
|
+
}
|
|
874
|
+
};
|
|
875
|
+
const AGENT_IN_CHILD = {
|
|
876
|
+
delivery: "conversation",
|
|
877
|
+
promptMode: "child_agent",
|
|
878
|
+
gated: false,
|
|
879
|
+
tools: {
|
|
880
|
+
agents: "children_and_parent",
|
|
881
|
+
reviewDesk: false,
|
|
882
|
+
subscriptions: false,
|
|
883
|
+
userCustomization: false,
|
|
884
|
+
reportBlocked: true,
|
|
885
|
+
noReply: true,
|
|
886
|
+
finishAutomationRun: false
|
|
887
|
+
}
|
|
888
|
+
};
|
|
889
|
+
const AUTOMATION_RUN = {
|
|
890
|
+
delivery: "conversation",
|
|
891
|
+
promptMode: "automation",
|
|
892
|
+
gated: true,
|
|
893
|
+
tools: {
|
|
894
|
+
...ROOT.tools,
|
|
895
|
+
noReply: false,
|
|
896
|
+
finishAutomationRun: true
|
|
897
|
+
}
|
|
898
|
+
};
|
|
899
|
+
/**
|
|
900
|
+
* Return the behavior of one Turn. `automationRun` marks the dispatch Turn of
|
|
901
|
+
* a Scheduled or Event automation run. Kind alone cannot mark it: the
|
|
902
|
+
* dispatch Turn is the only gated Turn on an `automation` Conversation, and a
|
|
903
|
+
* person's reply or a Watch Event Turn there runs like a Turn on a root.
|
|
904
|
+
*/
|
|
905
|
+
function turnBehavior(args) {
|
|
906
|
+
if (args.automationRun) return AUTOMATION_RUN;
|
|
907
|
+
if (isTopLevelKind(args.kind)) return ROOT;
|
|
908
|
+
if (!args.personInput) return AGENT_IN_CHILD;
|
|
909
|
+
if (args.kind === "thread") return PERSON_IN_THREAD;
|
|
910
|
+
throw new Error("A task Conversation cannot have a person's input");
|
|
911
|
+
}
|
|
912
|
+
/** Return whether a Conversation of this kind has no parent. */
|
|
913
|
+
function isTopLevelKind(kind) {
|
|
914
|
+
return kind === "root" || kind === "automation";
|
|
915
|
+
}
|
|
916
|
+
/** Return whether a person sent input from this Source. */
|
|
917
|
+
function isPersonInput(source) {
|
|
918
|
+
return source === "web" || source === "slack";
|
|
919
|
+
}
|
|
920
|
+
/**
|
|
921
|
+
* Return whether the runtime delivers the final response of a Slack or
|
|
922
|
+
* dispatch run. Only root Conversations reach these paths, so only an
|
|
923
|
+
* Automation run keeps its final response in the Conversation. A dispatch
|
|
924
|
+
* with no outcomes delivers nothing.
|
|
925
|
+
*/
|
|
926
|
+
function deliversFinalText(dispatch) {
|
|
927
|
+
return dispatch?.outcomes?.length !== 0 && !dispatch?.declaresResult;
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Return whether the runtime may post a failure reply or a status notice,
|
|
931
|
+
* such as an auth prompt, for a run outside `finishedRunReply`. The rule is
|
|
932
|
+
* the same as for a final response. A chat Turn may post, also in a thread
|
|
933
|
+
* that an Automation Conversation owns. An Automation run posts only a
|
|
934
|
+
* declared message; its failed execution shows on the Automation.
|
|
935
|
+
*/
|
|
936
|
+
function postsRunNotices(dispatch) {
|
|
937
|
+
return deliversFinalText(dispatch);
|
|
938
|
+
}
|
|
847
939
|
// src/chat/conversations/sql/store.ts
|
|
848
940
|
const CONVERSATION_MUTATION_LOCK_PREFIX = "junior_conversation";
|
|
849
941
|
/** Serialize one conversation's durable mutations inside a SQL transaction. */
|
|
@@ -970,7 +1062,7 @@ function emptyConversation(args) {
|
|
|
970
1062
|
schemaVersion: 1,
|
|
971
1063
|
conversationId: args.conversationId,
|
|
972
1064
|
createdAtMs: args.nowMs,
|
|
973
|
-
kind: "root",
|
|
1065
|
+
kind: args.kind ?? "root",
|
|
974
1066
|
lastActivityAtMs: args.nowMs,
|
|
975
1067
|
updatedAtMs: args.nowMs,
|
|
976
1068
|
...args.destination ? { destination: args.destination } : void 0,
|
|
@@ -1050,6 +1142,7 @@ var SqlStore = class {
|
|
|
1050
1142
|
const current = existing ?? emptyConversation({
|
|
1051
1143
|
conversationId: args.conversationId,
|
|
1052
1144
|
destination: args.destination,
|
|
1145
|
+
kind: args.kind,
|
|
1053
1146
|
nowMs,
|
|
1054
1147
|
source: args.source,
|
|
1055
1148
|
...sessionSource ? { sessionSource } : void 0
|
|
@@ -1173,7 +1266,7 @@ var SqlStore = class {
|
|
|
1173
1266
|
/** Upsert the conversation row while preserving previously discovered nullable metadata fields. */
|
|
1174
1267
|
async upsertConversation(args) {
|
|
1175
1268
|
const { conversation } = args;
|
|
1176
|
-
if (conversation.kind
|
|
1269
|
+
if (isTopLevelKind(conversation.kind) !== !conversation.parentConversationId) throw new Error(`Conversation ${conversation.conversationId} kind does not match its parent`);
|
|
1177
1270
|
if (!conversation.parentConversationId && !conversation.destination) {
|
|
1178
1271
|
if (!await this.get({ conversationId: conversation.conversationId })) throw new Error(`Conversation ${conversation.conversationId} requires a destination at create`);
|
|
1179
1272
|
}
|
|
@@ -1295,6 +1388,49 @@ var SqlStore = class {
|
|
|
1295
1388
|
function createSqlStore(executor) {
|
|
1296
1389
|
return new SqlStore(executor);
|
|
1297
1390
|
}
|
|
1391
|
+
// src/chat/conversations/sql/last-message.ts
|
|
1392
|
+
/**
|
|
1393
|
+
* Return a query for the newest event of one type in the outer Conversation
|
|
1394
|
+
* that matches the filter. It walks the message role or user message time
|
|
1395
|
+
* index from the newest event. The user message index has only matching
|
|
1396
|
+
* entries, so that read stops at the first one.
|
|
1397
|
+
*/
|
|
1398
|
+
function latestEventAtQuery(db, type, filter) {
|
|
1399
|
+
return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1);
|
|
1400
|
+
}
|
|
1401
|
+
/**
|
|
1402
|
+
* Return queries for the latest user instruction and the latest true user
|
|
1403
|
+
* Message of the outer Conversation.
|
|
1404
|
+
*/
|
|
1405
|
+
function userMessageQueries(db) {
|
|
1406
|
+
const payload = juniorConversationEvents.payload;
|
|
1407
|
+
const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
|
|
1408
|
+
return {
|
|
1409
|
+
instruction: latestEventAtQuery(db, "user_message", isUserInstruction(payload)),
|
|
1410
|
+
message: latestEventAtQuery(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`)
|
|
1411
|
+
};
|
|
1412
|
+
}
|
|
1413
|
+
/**
|
|
1414
|
+
* Return SQL for when the outer Conversation last got a Message that a
|
|
1415
|
+
* reader would notice: a true user message or a Junior reply that the
|
|
1416
|
+
* transcript shows. Tools, status, Events, quiet replies, and progress acks
|
|
1417
|
+
* (`meta.progress`) do not count. It is null when there is no such Message.
|
|
1418
|
+
*/
|
|
1419
|
+
function lastMessageAtSql(db) {
|
|
1420
|
+
const payload = juniorConversationEvents.payload;
|
|
1421
|
+
const { instruction, message } = userMessageQueries(db);
|
|
1422
|
+
const reply = latestEventAtQuery(db, "message", sql`${payload}->>'role' = 'assistant' and (${payload}->'meta'->>'quiet') is distinct from 'true' and (${payload}->'meta'->>'progress') is distinct from 'true'`);
|
|
1423
|
+
return sql`greatest((${instruction}), (${message}), (${reply}))`.mapWith(juniorConversations.lastMessageAt);
|
|
1424
|
+
}
|
|
1425
|
+
/**
|
|
1426
|
+
* Store `lastMessageAtSql` on the Conversation row. Event appends call this
|
|
1427
|
+
* in their transaction when they add a Message, so feed reads take the time
|
|
1428
|
+
* from the row.
|
|
1429
|
+
*/
|
|
1430
|
+
async function refreshLastMessageAt(executor, conversationId) {
|
|
1431
|
+
const db = executor.db();
|
|
1432
|
+
await db.update(juniorConversations).set({ lastMessageAt: lastMessageAtSql(db) }).where(eq(juniorConversations.conversationId, conversationId));
|
|
1433
|
+
}
|
|
1298
1434
|
// src/chat/conversations/sql/event-actor.ts
|
|
1299
1435
|
function isRecord(value) {
|
|
1300
1436
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
@@ -1621,6 +1757,7 @@ var SqlConversationEventStore = class {
|
|
|
1621
1757
|
}
|
|
1622
1758
|
const db = this.executor.db();
|
|
1623
1759
|
await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(rows);
|
|
1760
|
+
if (pending.some((event) => event.data.type === "message" || event.data.type === "user_message")) await refreshLastMessageAt(this.executor, conversationId);
|
|
1624
1761
|
for (const event of pending) if (event.data.type === "turn_started") await this.recordTurnInputParticipants(conversationId, event.data.inputMessageIds);
|
|
1625
1762
|
return rows.map((row) => ({
|
|
1626
1763
|
seq: row.seq,
|
|
@@ -1941,4 +2078,4 @@ async function closeDb() {
|
|
|
1941
2078
|
current = void 0;
|
|
1942
2079
|
await previous?.db.close();
|
|
1943
2080
|
}
|
|
1944
|
-
export {
|
|
2081
|
+
export { rootConversationIsArchived as $, setFirstConversationLocation as A, recordGoogleSignIn as B, deliversFinalText as C, turnBehavior as D, postsRunNotices as E, saveActorAvatar as F, getConversationIdByProviderConversation as G, upsertLinkedIdentity as H, deleteProviderIdentityForSlackUser as I, agentTurnCostUsd as J, parseSessionSource as K, deleteProviderIdentityForUser as L, SYSTEM_IDENTITY_ID as M, findActorIdentityId as N, conversationKindFromRow as O, resolveActorIdentityId as P, resolveRootConversationId as Q, findUserByVerifiedEmails as R, withConversationMutationLock as S, isTopLevelKind as T, bindProviderConversation as U, saveUserTimezone as V, claimProviderConversation as W, agentTurnUsageSchema as X, agentTurnTotalTokens as Y, hasAgentTurnUsage as Z, setArchivedAt as _, getConversationStore as a, requireSlackDestination as at, userMessageQueries as b, conversationIdsWithAnnotation as c, createSqlConversationEventStore as d, conversationDetailTouch as et, eventFromRow as f, readConversationTrees as g, conversationDescendants as h, getConversationMessageSearchStore as i, parseDestination as it, startLocationThread as j, locationFromRow as k, hasAnnotationKey as l, conversationAncestors as m, db_exports as n, touchConversationDetail as nt, getDb as o, sameDestination as ot, withConversationEventLock as p, addAgentTurnUsage as q, getConversationEventStore as r, createSlackDestination as rt, getSqlExecutor as s, closeDb as t, nextDetailVersion as tt, treeHasAnnotationKey as u, loadConversationSlackTenantIds as v, isPersonInput as w, createSqlStore as x, lastMessageAtSql as y, readUserTimezone as z };
|