@sentry/junior 0.75.0 → 0.76.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +1 -1
  2. package/bin/junior.mjs +4 -66
  3. package/dist/agent-hooks-ZOE7RIED.js +37 -0
  4. package/dist/api-reference.d.ts +2 -0
  5. package/dist/app.js +364 -135
  6. package/dist/build/virtual-config.d.ts +2 -2
  7. package/dist/chat/agent-dispatch/runner.d.ts +2 -0
  8. package/dist/chat/config.d.ts +1 -0
  9. package/dist/chat/credentials/state-adapter-token-store.d.ts +2 -0
  10. package/dist/chat/credentials/user-token-store.d.ts +17 -12
  11. package/dist/chat/db.d.ts +8 -0
  12. package/dist/chat/mcp/auth-store.d.ts +2 -1
  13. package/dist/chat/mcp/oauth.d.ts +2 -1
  14. package/dist/chat/oauth-flow.d.ts +3 -1
  15. package/dist/chat/pi/client.d.ts +15 -7
  16. package/dist/chat/plugins/agent-hooks.d.ts +7 -0
  17. package/dist/chat/plugins/auth/oauth-request.d.ts +11 -7
  18. package/dist/chat/plugins/model.d.ts +9 -0
  19. package/dist/chat/plugins/prompt.d.ts +5 -0
  20. package/dist/chat/plugins/task-callback.d.ts +5 -0
  21. package/dist/chat/plugins/task-message.d.ts +23 -0
  22. package/dist/chat/plugins/task-queue.d.ts +5 -0
  23. package/dist/chat/plugins/task-runner.d.ts +12 -0
  24. package/dist/chat/plugins/task-signing.d.ts +31 -0
  25. package/dist/chat/prompt.d.ts +4 -0
  26. package/dist/chat/requester.d.ts +6 -5
  27. package/dist/chat/respond-helpers.d.ts +2 -0
  28. package/dist/chat/respond.d.ts +4 -2
  29. package/dist/chat/runtime/agent-continue-runner.d.ts +4 -0
  30. package/dist/chat/runtime/reply-executor.d.ts +5 -1
  31. package/dist/chat/runtime/slack-resume.d.ts +10 -2
  32. package/dist/chat/sentry.d.ts +1 -0
  33. package/dist/chat/services/mcp-auth-orchestration.d.ts +2 -1
  34. package/dist/chat/services/plugin-auth-orchestration.d.ts +2 -1
  35. package/dist/chat/services/subscribed-decision.d.ts +2 -2
  36. package/dist/chat/services/turn-session-record.d.ts +11 -7
  37. package/dist/chat/slack/footer.d.ts +1 -1
  38. package/dist/chat/state/turn-session.d.ts +8 -5
  39. package/dist/chat/tools/agent-tools.d.ts +8 -1
  40. package/dist/chat/tools/slack/context.d.ts +2 -2
  41. package/dist/chat/tools/types.d.ts +4 -4
  42. package/dist/chat/vercel-queue-client.d.ts +3 -0
  43. package/dist/{chunk-C3AM4Z4J.js → chunk-2ECJXSVQ.js} +5 -5
  44. package/dist/{chunk-OJODNL2P.js → chunk-4SCWV7TJ.js} +2 -2
  45. package/dist/chunk-4UO6FK4G.js +64 -0
  46. package/dist/{chunk-BNJIEFQC.js → chunk-56TBVRJG.js} +2 -2
  47. package/dist/{chunk-OK4KKR7B.js → chunk-EJN6G5A2.js} +28 -12
  48. package/dist/{chunk-TQ74BATR.js → chunk-FFGXUXMD.js} +435 -111
  49. package/dist/{chunk-XJHDZUGD.js → chunk-JBASI5VV.js} +4 -4
  50. package/dist/chunk-KNFROR7R.js +127 -0
  51. package/dist/{chunk-VNTLUFTY.js → chunk-KOIMO7S3.js} +126 -87
  52. package/dist/chunk-MLKGABMK.js +9 -0
  53. package/dist/{chunk-NPVUAXUE.js → chunk-NFTMTIP3.js} +303 -33
  54. package/dist/chunk-NYKJ3KON.js +1082 -0
  55. package/dist/{chunk-SJHUF3DP.js → chunk-OJ53FYVG.js} +2 -10
  56. package/dist/{chunk-62FUNJYS.js → chunk-Q6XFTRV5.js} +54 -3
  57. package/dist/{chunk-UJ7OTHPO.js → chunk-R6Z5XWY3.js} +12 -670
  58. package/dist/chunk-RV5RYIJW.js +56 -0
  59. package/dist/{chunk-EE6PJWY4.js → chunk-SG5WAA7H.js} +7 -5
  60. package/dist/chunk-ST6YNAXG.js +54 -0
  61. package/dist/{chunk-FCZO7LAR.js → chunk-T77LUIX3.js} +139 -153
  62. package/dist/{chunk-EIYL7I4S.js → chunk-VALUBQ7R.js} +22 -30
  63. package/dist/{chunk-OZSPLAQ4.js → chunk-XBBC6W45.js} +1 -1
  64. package/dist/{chunk-ZNNTSPNF.js → chunk-Y5OFBCBZ.js} +1 -1
  65. package/dist/{chunk-74HO27II.js → chunk-Z4CIQ3EB.js} +5 -1
  66. package/dist/{chunk-2RWFUS5F.js → chunk-ZLMBNBUG.js} +101 -44
  67. package/dist/{chunk-JEELK46E.js → chunk-ZQB37HUX.js} +11 -11
  68. package/dist/cli/chat.js +52 -23
  69. package/dist/cli/check.js +7 -7
  70. package/dist/cli/env.js +4 -53
  71. package/dist/cli/init.js +6 -1
  72. package/dist/cli/main.js +84 -0
  73. package/dist/cli/plugins.js +244 -0
  74. package/dist/cli/run.js +5 -52
  75. package/dist/cli/snapshot-warmup.js +9 -9
  76. package/dist/cli/upgrade.js +167 -48
  77. package/dist/db-7A7PFRGL.js +17 -0
  78. package/dist/deployment.d.ts +1 -0
  79. package/dist/instrumentation.js +14 -18
  80. package/dist/nitro.d.ts +1 -1
  81. package/dist/nitro.js +43 -22
  82. package/dist/plugins-PZMDS7AT.js +15 -0
  83. package/dist/plugins.d.ts +4 -2
  84. package/dist/{registry-NLZFIW23.js → registry-OIPAJU2O.js} +6 -6
  85. package/dist/reporting.js +34 -26
  86. package/dist/{runner-LUQZ5G67.js → runner-7Z4D6AKV.js} +76 -23
  87. package/dist/sentry-4CP5NNQ5.js +31 -0
  88. package/dist/validation-SLA6IGF7.js +15 -0
  89. package/dist/vercel.js +1 -1
  90. package/package.json +8 -7
  91. package/dist/agent-hooks-2HEB4C3Q.js +0 -33
  92. package/dist/chat/conversations/configured.d.ts +0 -7
  93. package/dist/chat/conversations/state.d.ts +0 -4
  94. package/dist/chat/plugins/db.d.ts +0 -31
  95. package/dist/chunk-2KG3PWR4.js +0 -17
  96. package/dist/chunk-D7NFH5GD.js +0 -570
  97. package/dist/chunk-MCMROINU.js +0 -12
  98. package/dist/chunk-WBZ4M5N5.js +0 -59
  99. package/dist/db-A3ILH67H.js +0 -20
  100. package/dist/plugins-OMJKLRJ2.js +0 -13
  101. package/dist/validation-VMCPP3YO.js +0 -15
@@ -1,30 +1,25 @@
1
1
  import {
2
- parseDestination,
3
- sameDestination
4
- } from "./chunk-WBZ4M5N5.js";
5
- import {
6
- juniorConversations,
7
- juniorDestinations,
8
- juniorIdentities
9
- } from "./chunk-D7NFH5GD.js";
2
+ JUNIOR_THREAD_STATE_TTL_MS
3
+ } from "./chunk-Z4CIQ3EB.js";
10
4
  import {
11
5
  getDefaultRedisStateAdapterFor,
12
6
  getStateAdapter
13
- } from "./chunk-ZNNTSPNF.js";
7
+ } from "./chunk-Y5OFBCBZ.js";
8
+ import {
9
+ parseDestination,
10
+ sameDestination
11
+ } from "./chunk-Q6XFTRV5.js";
14
12
  import {
15
13
  getChatConfig
16
- } from "./chunk-FCZO7LAR.js";
14
+ } from "./chunk-T77LUIX3.js";
17
15
  import {
18
16
  parseStoredSlackRequester
19
- } from "./chunk-EIYL7I4S.js";
17
+ } from "./chunk-VALUBQ7R.js";
20
18
  import {
21
19
  isRecord,
22
20
  toOptionalNumber,
23
21
  toOptionalString
24
- } from "./chunk-OK4KKR7B.js";
25
-
26
- // src/chat/state/ttl.ts
27
- var JUNIOR_THREAD_STATE_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
22
+ } from "./chunk-EJN6G5A2.js";
28
23
 
29
24
  // src/chat/task-execution/state.ts
30
25
  import { randomUUID } from "crypto";
@@ -1058,666 +1053,14 @@ async function listConversationsByActivity(args = {}) {
1058
1053
  return conversations;
1059
1054
  }
1060
1055
 
1061
- // src/chat/conversations/state.ts
1062
- function createStateConversationStore(state) {
1063
- return {
1064
- get: (args) => getConversation({ ...args, state }),
1065
- recordActivity: (args) => recordConversationActivity({ ...args, state }),
1066
- recordExecution: async () => {
1067
- },
1068
- listByActivity: (args) => listConversationsByActivity({ ...args, state })
1069
- };
1070
- }
1071
-
1072
- // src/chat/conversations/sql/store.ts
1073
- import { randomUUID as randomUUID2 } from "crypto";
1074
- import { asc, desc, eq, sql } from "drizzle-orm";
1075
-
1076
- // src/chat/conversations/sql/migrations.ts
1077
- import { createHash } from "crypto";
1078
- import { z } from "zod";
1079
- var MIGRATION_LOCK_NAME = "junior_conversation_schema";
1080
- var migrationRecordSchema = z.object({
1081
- id: z.string().min(1),
1082
- checksum: z.string().min(1)
1083
- }).strict();
1084
- function checksumStatements(statements) {
1085
- const hash = createHash("sha256");
1086
- for (const statement of statements) {
1087
- hash.update(statement);
1088
- hash.update("\0");
1089
- }
1090
- return hash.digest("hex");
1091
- }
1092
- function defineMigration(id, statements) {
1093
- return {
1094
- id,
1095
- checksum: checksumStatements(statements),
1096
- statements
1097
- };
1098
- }
1099
- var createMigrationTable = `
1100
- CREATE TABLE IF NOT EXISTS junior_schema_migrations (
1101
- id TEXT PRIMARY KEY,
1102
- checksum TEXT NOT NULL,
1103
- applied_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
1104
- )
1105
- `;
1106
- var coreMetadataStatements = [
1107
- `
1108
- CREATE TABLE IF NOT EXISTS junior_identities (
1109
- id TEXT PRIMARY KEY,
1110
- kind TEXT NOT NULL,
1111
- provider TEXT NOT NULL,
1112
- provider_tenant_id TEXT NOT NULL DEFAULT '',
1113
- provider_subject_id TEXT NOT NULL,
1114
- display_name TEXT,
1115
- handle TEXT,
1116
- email TEXT,
1117
- avatar_url TEXT,
1118
- metadata_json JSONB,
1119
- created_at TIMESTAMPTZ NOT NULL,
1120
- updated_at TIMESTAMPTZ NOT NULL
1121
- )
1122
- `,
1123
- `
1124
- CREATE UNIQUE INDEX IF NOT EXISTS junior_identities_provider_subject_uidx
1125
- ON junior_identities (provider, provider_tenant_id, provider_subject_id)
1126
- `,
1127
- `
1128
- CREATE INDEX IF NOT EXISTS junior_identities_kind_provider_idx
1129
- ON junior_identities (kind, provider)
1130
- `,
1131
- `
1132
- CREATE TABLE IF NOT EXISTS junior_destinations (
1133
- id TEXT PRIMARY KEY,
1134
- provider TEXT NOT NULL,
1135
- provider_tenant_id TEXT NOT NULL DEFAULT '',
1136
- provider_destination_id TEXT NOT NULL,
1137
- kind TEXT NOT NULL,
1138
- parent_destination_id TEXT,
1139
- display_name TEXT,
1140
- visibility TEXT NOT NULL DEFAULT 'unknown',
1141
- metadata_json JSONB,
1142
- created_at TIMESTAMPTZ NOT NULL,
1143
- updated_at TIMESTAMPTZ NOT NULL
1144
- )
1145
- `,
1146
- `
1147
- CREATE UNIQUE INDEX IF NOT EXISTS junior_destinations_provider_destination_uidx
1148
- ON junior_destinations (provider, provider_tenant_id, provider_destination_id)
1149
- `,
1150
- `
1151
- CREATE INDEX IF NOT EXISTS junior_destinations_provider_kind_idx
1152
- ON junior_destinations (provider, kind)
1153
- `,
1154
- `
1155
- CREATE TABLE IF NOT EXISTS junior_conversations (
1156
- conversation_id TEXT PRIMARY KEY,
1157
- schema_version INTEGER NOT NULL DEFAULT 1,
1158
- source TEXT,
1159
- origin_type TEXT,
1160
- origin_id TEXT,
1161
- origin_run_id TEXT,
1162
- destination_id TEXT REFERENCES junior_destinations (id),
1163
- destination_json JSONB,
1164
- actor_identity_id TEXT REFERENCES junior_identities (id),
1165
- requester_identity_id TEXT REFERENCES junior_identities (id),
1166
- creator_identity_id TEXT REFERENCES junior_identities (id),
1167
- credential_subject_identity_id TEXT REFERENCES junior_identities (id),
1168
- requester_json JSONB,
1169
- channel_name TEXT,
1170
- title TEXT,
1171
- created_at TIMESTAMPTZ NOT NULL,
1172
- last_activity_at TIMESTAMPTZ NOT NULL,
1173
- updated_at TIMESTAMPTZ NOT NULL,
1174
- execution_updated_at TIMESTAMPTZ,
1175
- execution_status TEXT NOT NULL,
1176
- run_id TEXT,
1177
- last_checkpoint_at TIMESTAMPTZ,
1178
- last_enqueued_at TIMESTAMPTZ
1179
- )
1180
- `,
1181
- `
1182
- CREATE INDEX IF NOT EXISTS junior_conversations_last_activity_idx
1183
- ON junior_conversations (last_activity_at DESC, conversation_id)
1184
- `,
1185
- `
1186
- CREATE INDEX IF NOT EXISTS junior_conversations_active_idx
1187
- ON junior_conversations (coalesce(execution_updated_at, updated_at) ASC, conversation_id)
1188
- WHERE execution_status <> 'idle'
1189
- `,
1190
- `
1191
- CREATE INDEX IF NOT EXISTS junior_conversations_destination_activity_idx
1192
- ON junior_conversations (destination_id, last_activity_at DESC)
1193
- `,
1194
- `
1195
- CREATE INDEX IF NOT EXISTS junior_conversations_actor_activity_idx
1196
- ON junior_conversations (actor_identity_id, last_activity_at DESC)
1197
- `,
1198
- `
1199
- CREATE INDEX IF NOT EXISTS junior_conversations_requester_activity_idx
1200
- ON junior_conversations (requester_identity_id, last_activity_at DESC)
1201
- `,
1202
- `
1203
- CREATE INDEX IF NOT EXISTS junior_conversations_origin_idx
1204
- ON junior_conversations (origin_type, origin_id, last_activity_at DESC)
1205
- `
1206
- ];
1207
- var migrations = [
1208
- defineMigration("0001_conversation_core", coreMetadataStatements)
1209
- ];
1210
- function parseStoredMigrationRecord(value) {
1211
- return migrationRecordSchema.parse(value);
1212
- }
1213
- async function listAppliedMigrations(executor) {
1214
- const rows = await executor.query(
1215
- "SELECT id, checksum FROM junior_schema_migrations ORDER BY id ASC"
1216
- );
1217
- const records = /* @__PURE__ */ new Map();
1218
- for (const row of rows) {
1219
- const record = parseStoredMigrationRecord(row);
1220
- records.set(record.id, record);
1221
- }
1222
- return records;
1223
- }
1224
- async function applyMigration(executor, migration) {
1225
- await executor.transaction(async () => {
1226
- for (const statement of migration.statements) {
1227
- await executor.execute(statement);
1228
- }
1229
- await executor.execute(
1230
- "INSERT INTO junior_schema_migrations (id, checksum) VALUES ($1, $2)",
1231
- [migration.id, migration.checksum]
1232
- );
1233
- });
1234
- }
1235
- async function migrateSchema(executor, migrationList = migrations) {
1236
- await executor.withLock(MIGRATION_LOCK_NAME, async () => {
1237
- await executor.execute(createMigrationTable);
1238
- const applied = await listAppliedMigrations(executor);
1239
- for (const migration of migrationList) {
1240
- const existing = applied.get(migration.id);
1241
- if (existing) {
1242
- if (existing.checksum !== migration.checksum) {
1243
- throw new Error(
1244
- `Conversation migration ${migration.id} checksum changed`
1245
- );
1246
- }
1247
- continue;
1248
- }
1249
- await applyMigration(executor, migration);
1250
- }
1251
- });
1252
- }
1253
-
1254
- // src/chat/conversations/sql/store.ts
1255
- var CONVERSATION_MUTATION_LOCK_PREFIX = "junior_conversation";
1256
- function now2() {
1257
- return Date.now();
1258
- }
1259
- function dateFromMs(ms) {
1260
- return new Date(ms);
1261
- }
1262
- function tenantId(value) {
1263
- return value ?? "";
1264
- }
1265
- function msFromDate(value) {
1266
- if (value === null || value === void 0) {
1267
- return void 0;
1268
- }
1269
- const date = value instanceof Date ? value : new Date(value);
1270
- return date.getTime();
1271
- }
1272
- function requiredMsFromDate(value) {
1273
- const ms = msFromDate(value);
1274
- if (typeof ms !== "number" || Number.isNaN(ms)) {
1275
- throw new Error("Conversation record timestamp is invalid");
1276
- }
1277
- return ms;
1278
- }
1279
- function sourceFromValue(value) {
1280
- if (value === "api" || value === "internal" || value === "local" || value === "plugin" || value === "scheduler" || value === "slack") {
1281
- return value;
1282
- }
1283
- return void 0;
1284
- }
1285
- function identityFromRequester(requester) {
1286
- if (!requester?.slackUserId) {
1287
- return void 0;
1288
- }
1289
- return {
1290
- kind: "user",
1291
- provider: "slack",
1292
- providerTenantId: requester.teamId,
1293
- providerSubjectId: requester.slackUserId,
1294
- ...requester.fullName ? { displayName: requester.fullName } : {},
1295
- ...requester.slackUserName ? { handle: requester.slackUserName } : {},
1296
- ...requester.email ? { email: requester.email } : {},
1297
- metadata: { platform: "slack" }
1298
- };
1299
- }
1300
- function systemIdentityFromSource(source) {
1301
- if (source === "scheduler") {
1302
- return {
1303
- kind: "system",
1304
- provider: "junior",
1305
- providerSubjectId: "scheduler",
1306
- displayName: "Junior Scheduler"
1307
- };
1308
- }
1309
- if (source === "local") {
1310
- return {
1311
- kind: "system",
1312
- provider: "junior",
1313
- providerSubjectId: "local-cli",
1314
- displayName: "Local CLI"
1315
- };
1316
- }
1317
- return void 0;
1318
- }
1319
- function actorIdentityForConversation(conversation) {
1320
- return identityFromRequester(conversation.requester) ?? systemIdentityFromSource(conversation.source);
1321
- }
1322
- function originTypeFromSource(source) {
1323
- return source;
1324
- }
1325
- function localWorkspaceFromConversationId(conversationId) {
1326
- const match = /^local:([^:]+):/.exec(conversationId);
1327
- return match?.[1];
1328
- }
1329
- function destinationUpsertFromDestination(args) {
1330
- const { destination } = args;
1331
- if (!destination) {
1332
- return void 0;
1333
- }
1334
- if (destination.platform === "slack") {
1335
- const channelId = destination.channelId;
1336
- const channelKind = channelId.startsWith("D") ? "dm" : channelId.startsWith("G") ? "group" : "channel";
1337
- const visibility = channelId.startsWith("D") ? "direct" : channelId.startsWith("G") ? "private" : "public";
1338
- return {
1339
- kind: channelKind,
1340
- provider: "slack",
1341
- providerTenantId: destination.teamId,
1342
- providerDestinationId: channelId,
1343
- visibility,
1344
- ...args.channelName ? { displayName: args.channelName } : {},
1345
- metadata: { platform: "slack" }
1346
- };
1347
- }
1348
- return {
1349
- kind: "local_conversation",
1350
- provider: "local",
1351
- providerTenantId: localWorkspaceFromConversationId(destination.conversationId) ?? localWorkspaceFromConversationId(args.conversationId ?? ""),
1352
- providerDestinationId: destination.conversationId,
1353
- visibility: "direct",
1354
- metadata: { platform: "local" }
1355
- };
1356
- }
1357
- function executionStatusFromValue(value) {
1358
- if (value === "awaiting_resume" || value === "idle" || value === "pending" || value === "running") {
1359
- return value;
1360
- }
1361
- throw new Error("Conversation record execution status is invalid");
1362
- }
1363
- function conversationFromRow(row) {
1364
- if (row.schemaVersion !== 1) {
1365
- throw new Error("Conversation record schema version is invalid");
1366
- }
1367
- const destination = row.destination === void 0 || row.destination === null ? void 0 : parseDestination(row.destination);
1368
- const requester = parseStoredSlackRequester(row.requester);
1369
- if (row.destination !== void 0 && row.destination !== null && !destination) {
1370
- throw new Error("Conversation record destination is invalid");
1371
- }
1372
- if (row.requester !== void 0 && row.requester !== null && !requester) {
1373
- throw new Error("Conversation record requester is invalid");
1374
- }
1375
- const source = row.source === void 0 || row.source === null ? void 0 : sourceFromValue(row.source);
1376
- if (row.source !== void 0 && row.source !== null && !source) {
1377
- throw new Error("Conversation record source is invalid");
1378
- }
1379
- const execution = {
1380
- status: executionStatusFromValue(row.executionStatus),
1381
- lastCheckpointAtMs: msFromDate(row.lastCheckpointAt),
1382
- lastEnqueuedAtMs: msFromDate(row.lastEnqueuedAt),
1383
- ...row.runId ? { runId: row.runId } : {},
1384
- updatedAtMs: msFromDate(row.executionUpdatedAt) ?? requiredMsFromDate(row.updatedAt)
1385
- };
1386
- return {
1387
- schemaVersion: 1,
1388
- conversationId: row.conversationId,
1389
- createdAtMs: requiredMsFromDate(row.createdAt),
1390
- lastActivityAtMs: requiredMsFromDate(row.lastActivityAt),
1391
- updatedAtMs: requiredMsFromDate(row.updatedAt),
1392
- execution,
1393
- ...destination ? { destination } : {},
1394
- ...requester ? { requester } : {},
1395
- ...row.channelName ? { channelName: row.channelName } : {},
1396
- ...source ? { source } : {},
1397
- ...row.title ? { title: row.title } : {}
1398
- };
1399
- }
1400
- function emptyConversation2(args) {
1401
- return {
1402
- schemaVersion: 1,
1403
- conversationId: args.conversationId,
1404
- createdAtMs: args.nowMs,
1405
- lastActivityAtMs: args.nowMs,
1406
- updatedAtMs: args.nowMs,
1407
- ...args.destination ? { destination: args.destination } : {},
1408
- ...args.source ? { source: args.source } : {},
1409
- execution: {
1410
- status: "idle",
1411
- updatedAtMs: args.nowMs
1412
- }
1413
- };
1414
- }
1415
- function assertSameConversationDestination2(args) {
1416
- if (!args.current || sameDestination(args.current, args.next)) {
1417
- return;
1418
- }
1419
- throw new Error(
1420
- `Conversation destination changed for ${args.conversationId}`
1421
- );
1422
- }
1423
- var SqlStore = class {
1424
- constructor(executor, migrationExecutor) {
1425
- this.executor = executor;
1426
- this.migrationExecutor = migrationExecutor;
1427
- }
1428
- executor;
1429
- migrationExecutor;
1430
- schemaReady;
1431
- /** Apply SQL schema migrations before runtime uses this store. */
1432
- async migrate() {
1433
- if (!this.schemaReady) {
1434
- this.schemaReady = migrateSchema(this.migrationExecutor);
1435
- }
1436
- const schemaReady = this.schemaReady;
1437
- try {
1438
- await schemaReady;
1439
- } catch (error) {
1440
- if (this.schemaReady === schemaReady) {
1441
- this.schemaReady = void 0;
1442
- }
1443
- throw error;
1444
- }
1445
- }
1446
- async get(args) {
1447
- const row = await this.readConversationRow(args.conversationId);
1448
- if (!row) {
1449
- return void 0;
1450
- }
1451
- return conversationFromRow(row);
1452
- }
1453
- async recordActivity(args) {
1454
- const nowMs = args.nowMs ?? now2();
1455
- const activityAtMs = args.activityAtMs ?? nowMs;
1456
- await this.withConversationMutation(args.conversationId, async () => {
1457
- const existing = await this.get({
1458
- conversationId: args.conversationId
1459
- });
1460
- if (existing && args.destination) {
1461
- assertSameConversationDestination2({
1462
- conversationId: args.conversationId,
1463
- current: existing.destination,
1464
- next: args.destination
1465
- });
1466
- }
1467
- const current = existing ?? emptyConversation2({
1468
- conversationId: args.conversationId,
1469
- destination: args.destination,
1470
- nowMs,
1471
- source: args.source
1472
- });
1473
- await this.upsertConversation({
1474
- conversation: {
1475
- ...current,
1476
- destination: current.destination ?? args.destination,
1477
- source: current.source ?? args.source,
1478
- channelName: current.channelName ?? args.channelName,
1479
- requester: current.requester ?? args.requester,
1480
- title: current.title ?? args.title,
1481
- lastActivityAtMs: Math.max(current.lastActivityAtMs, activityAtMs),
1482
- updatedAtMs: nowMs,
1483
- execution: {
1484
- ...current.execution,
1485
- updatedAtMs: current.execution.updatedAtMs ?? nowMs
1486
- }
1487
- }
1488
- });
1489
- });
1490
- }
1491
- async recordExecution(args) {
1492
- await this.withConversationMutation(args.conversationId, async () => {
1493
- await this.upsertConversation({
1494
- conversation: {
1495
- schemaVersion: 1,
1496
- conversationId: args.conversationId,
1497
- createdAtMs: args.createdAtMs,
1498
- lastActivityAtMs: args.lastActivityAtMs,
1499
- updatedAtMs: args.updatedAtMs,
1500
- ...args.channelName ? { channelName: args.channelName } : {},
1501
- ...args.destination ? { destination: args.destination } : {},
1502
- ...args.requester ? { requester: args.requester } : {},
1503
- ...args.source ? { source: args.source } : {},
1504
- ...args.title ? { title: args.title } : {},
1505
- execution: args.execution
1506
- }
1507
- });
1508
- });
1509
- }
1510
- /** Copy one conversation record into SQL during backfill. */
1511
- async backfillConversation(conversation) {
1512
- await this.withConversationMutation(
1513
- conversation.conversationId,
1514
- async () => {
1515
- const existing = await this.get({
1516
- conversationId: conversation.conversationId
1517
- });
1518
- const sourceExecutionAtMs = conversation.execution.updatedAtMs ?? conversation.updatedAtMs;
1519
- const existingExecutionAtMs = existing === void 0 ? void 0 : existing.execution.updatedAtMs ?? existing.updatedAtMs;
1520
- const refreshExecutionFromSource = existingExecutionAtMs === void 0 || sourceExecutionAtMs >= existingExecutionAtMs;
1521
- const mergedConversation = existing ? {
1522
- ...conversation,
1523
- channelName: existing.channelName ?? conversation.channelName,
1524
- createdAtMs: Math.min(
1525
- existing.createdAtMs,
1526
- conversation.createdAtMs
1527
- ),
1528
- destination: existing.destination ?? conversation.destination,
1529
- lastActivityAtMs: Math.max(
1530
- existing.lastActivityAtMs,
1531
- conversation.lastActivityAtMs
1532
- ),
1533
- requester: existing.requester ?? conversation.requester,
1534
- source: existing.source ?? conversation.source,
1535
- title: existing.title ?? conversation.title,
1536
- updatedAtMs: Math.max(
1537
- existing.updatedAtMs,
1538
- conversation.updatedAtMs
1539
- ),
1540
- execution: refreshExecutionFromSource ? conversation.execution : existing.execution
1541
- } : conversation;
1542
- await this.upsertConversation({ conversation: mergedConversation });
1543
- }
1544
- );
1545
- }
1546
- async listByActivity(args = {}) {
1547
- const rows = await this.executor.db().select().from(juniorConversations).orderBy(
1548
- desc(juniorConversations.lastActivityAt),
1549
- asc(juniorConversations.conversationId)
1550
- ).limit(Math.max(0, args.limit ?? 1e4)).offset(Math.max(0, args.offset ?? 0));
1551
- const conversations = [];
1552
- for (const row of rows) {
1553
- conversations.push(conversationFromRow(row));
1554
- }
1555
- return conversations;
1556
- }
1557
- /** Serialize all durable mutations for one conversation inside a SQL transaction. */
1558
- async withConversationMutation(conversationId, callback) {
1559
- return await this.executor.withLock(
1560
- `${CONVERSATION_MUTATION_LOCK_PREFIX}:${conversationId}`,
1561
- async () => await this.executor.transaction(callback)
1562
- );
1563
- }
1564
- async readConversationRow(conversationId) {
1565
- const rows = await this.executor.db().select().from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId));
1566
- return rows[0];
1567
- }
1568
- /** Upsert the conversation row while preserving previously discovered nullable metadata fields. */
1569
- async upsertConversation(args) {
1570
- const { conversation } = args;
1571
- const incomingExecutionVersion = sql`coalesce(excluded.execution_updated_at, excluded.updated_at)`;
1572
- const currentExecutionVersion = sql`coalesce(${juniorConversations.executionUpdatedAt}, ${juniorConversations.updatedAt})`;
1573
- const incomingExecutionIsFresh = sql`${incomingExecutionVersion} >= ${currentExecutionVersion}`;
1574
- const destinationId = await this.upsertDestination(
1575
- destinationUpsertFromDestination({
1576
- channelName: conversation.channelName,
1577
- conversationId: conversation.conversationId,
1578
- destination: conversation.destination
1579
- }),
1580
- conversation.updatedAtMs
1581
- );
1582
- const requesterIdentityId = await this.upsertIdentity(
1583
- identityFromRequester(conversation.requester),
1584
- conversation.updatedAtMs
1585
- );
1586
- const actorIdentityId = await this.upsertIdentity(
1587
- actorIdentityForConversation(conversation),
1588
- conversation.updatedAtMs
1589
- );
1590
- await this.executor.db().insert(juniorConversations).values({
1591
- conversationId: conversation.conversationId,
1592
- schemaVersion: 1,
1593
- source: conversation.source ?? null,
1594
- originType: originTypeFromSource(conversation.source) ?? null,
1595
- originId: null,
1596
- originRunId: null,
1597
- destinationId: destinationId ?? null,
1598
- destination: conversation.destination ?? null,
1599
- actorIdentityId: actorIdentityId ?? null,
1600
- requesterIdentityId: requesterIdentityId ?? null,
1601
- creatorIdentityId: null,
1602
- credentialSubjectIdentityId: null,
1603
- requester: conversation.requester ?? null,
1604
- channelName: conversation.channelName ?? null,
1605
- title: conversation.title ?? null,
1606
- createdAt: dateFromMs(conversation.createdAtMs),
1607
- lastActivityAt: dateFromMs(conversation.lastActivityAtMs),
1608
- updatedAt: dateFromMs(conversation.updatedAtMs),
1609
- executionUpdatedAt: conversation.execution.updatedAtMs === void 0 ? null : dateFromMs(conversation.execution.updatedAtMs),
1610
- executionStatus: conversation.execution.status,
1611
- runId: conversation.execution.runId ?? null,
1612
- lastCheckpointAt: conversation.execution.lastCheckpointAtMs === void 0 ? null : dateFromMs(conversation.execution.lastCheckpointAtMs),
1613
- lastEnqueuedAt: conversation.execution.lastEnqueuedAtMs === void 0 ? null : dateFromMs(conversation.execution.lastEnqueuedAtMs)
1614
- }).onConflictDoUpdate({
1615
- target: juniorConversations.conversationId,
1616
- set: {
1617
- source: sql`coalesce(excluded.source, ${juniorConversations.source})`,
1618
- originType: sql`coalesce(excluded.origin_type, ${juniorConversations.originType})`,
1619
- originId: sql`coalesce(excluded.origin_id, ${juniorConversations.originId})`,
1620
- originRunId: sql`coalesce(excluded.origin_run_id, ${juniorConversations.originRunId})`,
1621
- destinationId: sql`coalesce(excluded.destination_id, ${juniorConversations.destinationId})`,
1622
- destination: sql`coalesce(excluded.destination_json, ${juniorConversations.destination})`,
1623
- actorIdentityId: sql`coalesce(excluded.actor_identity_id, ${juniorConversations.actorIdentityId})`,
1624
- requesterIdentityId: sql`coalesce(excluded.requester_identity_id, ${juniorConversations.requesterIdentityId})`,
1625
- creatorIdentityId: sql`coalesce(excluded.creator_identity_id, ${juniorConversations.creatorIdentityId})`,
1626
- credentialSubjectIdentityId: sql`coalesce(excluded.credential_subject_identity_id, ${juniorConversations.credentialSubjectIdentityId})`,
1627
- requester: sql`coalesce(excluded.requester_json, ${juniorConversations.requester})`,
1628
- channelName: sql`coalesce(excluded.channel_name, ${juniorConversations.channelName})`,
1629
- title: sql`coalesce(excluded.title, ${juniorConversations.title})`,
1630
- createdAt: sql`least(${juniorConversations.createdAt}, excluded.created_at)`,
1631
- lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
1632
- updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
1633
- executionUpdatedAt: sql`case when ${incomingExecutionIsFresh} then excluded.execution_updated_at else ${juniorConversations.executionUpdatedAt} end`,
1634
- executionStatus: sql`case when ${incomingExecutionIsFresh} then excluded.execution_status else ${juniorConversations.executionStatus} end`,
1635
- runId: sql`case when ${incomingExecutionIsFresh} then excluded.run_id else ${juniorConversations.runId} end`,
1636
- lastCheckpointAt: sql`case when ${incomingExecutionIsFresh} then excluded.last_checkpoint_at else ${juniorConversations.lastCheckpointAt} end`,
1637
- lastEnqueuedAt: sql`case when ${incomingExecutionIsFresh} then excluded.last_enqueued_at else ${juniorConversations.lastEnqueuedAt} end`
1638
- }
1639
- });
1640
- }
1641
- async upsertIdentity(identity, nowMs) {
1642
- if (!identity) {
1643
- return void 0;
1644
- }
1645
- const rows = await this.executor.db().insert(juniorIdentities).values({
1646
- id: randomUUID2(),
1647
- kind: identity.kind,
1648
- provider: identity.provider,
1649
- providerTenantId: tenantId(identity.providerTenantId),
1650
- providerSubjectId: identity.providerSubjectId,
1651
- displayName: identity.displayName ?? null,
1652
- handle: identity.handle ?? null,
1653
- email: identity.email ?? null,
1654
- avatarUrl: null,
1655
- metadata: identity.metadata ?? null,
1656
- createdAt: dateFromMs(nowMs),
1657
- updatedAt: dateFromMs(nowMs)
1658
- }).onConflictDoUpdate({
1659
- target: [
1660
- juniorIdentities.provider,
1661
- juniorIdentities.providerTenantId,
1662
- juniorIdentities.providerSubjectId
1663
- ],
1664
- set: {
1665
- kind: sql`excluded.kind`,
1666
- displayName: sql`coalesce(excluded.display_name, ${juniorIdentities.displayName})`,
1667
- handle: sql`coalesce(excluded.handle, ${juniorIdentities.handle})`,
1668
- email: sql`coalesce(excluded.email, ${juniorIdentities.email})`,
1669
- avatarUrl: sql`coalesce(excluded.avatar_url, ${juniorIdentities.avatarUrl})`,
1670
- metadata: sql`coalesce(excluded.metadata_json, ${juniorIdentities.metadata})`,
1671
- updatedAt: sql`excluded.updated_at`
1672
- }
1673
- }).returning({ id: juniorIdentities.id });
1674
- return rows[0]?.id;
1675
- }
1676
- async upsertDestination(destination, nowMs) {
1677
- if (!destination) {
1678
- return void 0;
1679
- }
1680
- const rows = await this.executor.db().insert(juniorDestinations).values({
1681
- id: randomUUID2(),
1682
- provider: destination.provider,
1683
- providerTenantId: tenantId(destination.providerTenantId),
1684
- providerDestinationId: destination.providerDestinationId,
1685
- kind: destination.kind,
1686
- parentDestinationId: null,
1687
- displayName: destination.displayName ?? null,
1688
- visibility: destination.visibility,
1689
- metadata: destination.metadata ?? null,
1690
- createdAt: dateFromMs(nowMs),
1691
- updatedAt: dateFromMs(nowMs)
1692
- }).onConflictDoUpdate({
1693
- target: [
1694
- juniorDestinations.provider,
1695
- juniorDestinations.providerTenantId,
1696
- juniorDestinations.providerDestinationId
1697
- ],
1698
- set: {
1699
- kind: sql`excluded.kind`,
1700
- displayName: sql`coalesce(excluded.display_name, ${juniorDestinations.displayName})`,
1701
- visibility: sql`excluded.visibility`,
1702
- metadata: sql`coalesce(excluded.metadata_json, ${juniorDestinations.metadata})`,
1703
- updatedAt: sql`excluded.updated_at`
1704
- }
1705
- }).returning({ id: juniorDestinations.id });
1706
- return rows[0]?.id;
1707
- }
1708
- };
1709
- function createSqlStore(executor) {
1710
- return new SqlStore(executor, executor);
1711
- }
1712
-
1713
1056
  export {
1714
- JUNIOR_THREAD_STATE_TTL_MS,
1715
1057
  CONVERSATION_WORK_CHECK_IN_INTERVAL_MS,
1716
1058
  CONVERSATION_WORK_STALE_ENQUEUE_MS,
1717
1059
  getConversation,
1718
1060
  getConversationWorkState,
1719
1061
  appendInboundMessage,
1720
1062
  requestConversationWork,
1063
+ recordConversationActivity,
1721
1064
  markConversationWorkEnqueued,
1722
1065
  startConversationWork,
1723
1066
  checkInConversationWork,
@@ -1729,6 +1072,5 @@ export {
1729
1072
  clearExpiredConversationLease,
1730
1073
  removeActiveConversation,
1731
1074
  listActiveConversationIds,
1732
- createStateConversationStore,
1733
- createSqlStore
1075
+ listConversationsByActivity
1734
1076
  };