@sentry/junior 0.318.0 → 0.319.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/{context-BKF_5zzI.js → adapter-8_S6Birm.js} +537 -537
- package/dist/{admin-UOHix_5P.js → admin-EsbUON1j.js} +1 -1
- package/dist/{agent-runner-DeYymwh2.js → agent-CtzMl32d.js} +18608 -5452
- package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
- package/dist/{agent-update-delivery-DH8bx7jU.js → agent-update-delivery-pAvsbuGL.js} +4 -5
- package/dist/api/schema.d.ts +43 -23
- package/dist/api/schema.js +4 -4
- package/dist/api.js +70 -80
- package/dist/{app-DKAOuaoC.d.ts → app-tACXxJPI.d.ts} +4 -4
- package/dist/app.d.ts +2 -2
- package/dist/app.js +213 -91
- package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
- package/dist/{channel-access-A0de5lRv.js → channel-access-DET5hzZM.js} +1 -1
- package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-DpM3tMVi.js} +5 -5
- package/dist/cli/chat.d.ts +1 -1
- package/dist/cli/chat.js +23 -23
- package/dist/cli/check.js +5 -5
- package/dist/cli/main.js +2 -2
- package/dist/cli/plugins.d.ts +1 -1
- package/dist/cli/plugins.js +8 -8
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -4
- package/dist/{continue-in-slack-YxwMQVeR.js → continue-in-slack-CFzDyxkH.js} +3 -3
- package/dist/{conversation-feed-Cj7IuBtM.js → conversation-feed-DEUdD7mb.js} +2 -106
- package/dist/{conversation-privacy-Cr_dNW1p.js → conversation-privacy-C2vYK55O.js} +1 -1
- package/dist/{create-Btl1y1rq.js → create-Ta3SEIB5.js} +115 -5
- package/dist/{credential-sync-DTarZ63K.js → credential-sync-DyRqDmY4.js} +15 -18
- package/dist/{db-of6e3sGt.js → db-BCaNWl9p.js} +4579 -717
- package/dist/{deployment-C0qXa0FD.js → deployment-CfOew1Tm.js} +3 -3
- package/dist/{engine-context-C_QL_bMQ.js → engine-context-CiExoy1B.js} +144 -149
- package/dist/{html-9_pS9SjY.js → html-Bb2Si1bR.js} +6 -8
- package/dist/instrumentation.js +7 -23
- package/dist/list-wwDcROh9.js +5007 -0
- package/dist/{logging-BnOG0qz2.js → logging-BRPTXAdf.js} +8 -33
- package/dist/{mailbox-turn-Byrry9o1.js → markers-9QoqW5ov.js} +1675 -1255
- package/dist/nitro.d.ts +2 -2
- package/dist/nitro.js +6 -7
- package/dist/{oauth-callback-server-CjnnUr4o.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
- package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-CH2v7WiB.js} +1 -1
- package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
- package/dist/{profile-iHw1uu32.js → profile-D9LdwmZi.js} +16 -18
- package/dist/{prompt-DEkStuxG.js → prompt-3TqxEOtc.js} +1 -1
- package/dist/{reports-C1d9azyV.js → reports-K-tbtEyx.js} +2 -2
- package/dist/{resolve-DC6zBuDV.js → resolve-BBV2qf8A.js} +5 -5
- package/dist/{result-DxewDuXb.js → result-5IdGJP4M.js} +20 -9
- package/dist/{runner-99YxVN_r.js → runner-BK_joPlM.js} +7 -8
- package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
- package/dist/{schema-BTojNBr5.js → schema-zWGG6VC1.js} +13 -7
- package/dist/{service-account-YDCPSByj.js → service-account-CateFyhw.js} +4 -5
- package/dist/{skills-CleC0Hze.js → skills-Ccjw8h2P.js} +9 -9
- package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
- package/dist/storage-C9U7R5rM.js +273 -0
- package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-YBTHIFlP.js} +26 -84
- package/dist/topic-B2EWKKBT.js +6 -0
- package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
- package/dist/{types-DCzTAA63.js → types-BNHkJrOP.js} +25 -11
- package/dist/{users-Cb9c1k9q.js → users-CCRAqYb_.js} +1 -1
- package/dist/{validation-BiUmWPhy.js → validation-BCUpJa8K.js} +4 -4
- package/dist/{version-VEXiEcZu.js → version-BNm0JYj3.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{worker-ChWYQdhm.js → worker-BhgpZ7_b.js} +4 -4
- package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
- package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
- package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
- package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
- package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
- package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
- package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
- package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
- package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
- package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
- package/package.json +9 -7
- package/dist/auth-pause-state-f9hJM_zO.js +0 -113
- package/dist/catalog-runtime-BfdAnztW.js +0 -6
- package/dist/child-message-peFWLcCZ.js +0 -15
- package/dist/conversation-turn-Bru4w_FD.js +0 -1250
- package/dist/job-runner-B2XEvpif.js +0 -1505
- package/dist/lineage-nh4z9iQN.js +0 -36
- package/dist/list-HRP3TIRl.js +0 -12631
- package/dist/markers-CTTtJqYn.js +0 -342
- package/dist/message-BRUuLgrY.js +0 -153
- package/dist/model-input-CFC62mf-.js +0 -82
- package/dist/registry-Cl7Labpe.js +0 -3279
- package/dist/run-conversation-Cz2ubZK-.js +0 -337
- package/dist/sender-actors-77zTQbSG.js +0 -84
- package/dist/spawn-DuZfodPa.js +0 -45
- package/dist/task-runner-BJ9Up3bG.js +0 -1529
- package/dist/topic-CRYYBYp-.js +0 -7
- package/dist/topics-BoCkoPJJ.js +0 -21
- package/dist/turn-membership-VT7XZh-L.js +0 -856
- package/dist/turn-wake-C7HeLHAM.js +0 -151
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
-
import {
|
|
3
|
-
import { G as mapBounded } from "./prompt-
|
|
2
|
+
import { _ as toOptionalTrimmed } from "./topics-DxuKurCX.js";
|
|
3
|
+
import { G as mapBounded } from "./prompt-3TqxEOtc.js";
|
|
4
4
|
import * as z from "zod";
|
|
5
5
|
import { calculateCost, completeSimple, getEnvApiKey, getModels, registerApiProvider } from "@earendil-works/pi-ai/compat";
|
|
6
6
|
import { stream as streamAnthropic, streamSimple as streamSimpleAnthropic } from "@earendil-works/pi-ai/api/anthropic-messages";
|
|
@@ -1239,161 +1239,453 @@ function parseSlackUserId(value) {
|
|
|
1239
1239
|
const parsed = slackUserIdSchema.safeParse(value.trim());
|
|
1240
1240
|
return parsed.success ? parsed.data : void 0;
|
|
1241
1241
|
}
|
|
1242
|
-
// src/chat/
|
|
1243
|
-
const ACTIVE_LOCK_TTL_MS = 9e4;
|
|
1244
|
-
const MUTATION_LOCK_TTL_MS = 1e4;
|
|
1242
|
+
// src/chat/actor.ts
|
|
1245
1243
|
/**
|
|
1246
|
-
*
|
|
1247
|
-
*
|
|
1244
|
+
* Canonical actor identity.
|
|
1245
|
+
*
|
|
1246
|
+
* Runtime actors are platform-scoped actors. Stored Slack actor parsing
|
|
1247
|
+
* remains explicit so durable conversation metadata is not repaired on read.
|
|
1248
1248
|
*/
|
|
1249
|
-
|
|
1250
|
-
|
|
1249
|
+
const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
|
|
1250
|
+
const EMAIL_PATTERN = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
|
1251
|
+
const exactStoredStringSchema = z.string().min(1).refine((value) => value === value.trim());
|
|
1252
|
+
const storedSlackActorSchema = z.object({
|
|
1253
|
+
email: exactStoredStringSchema.optional(),
|
|
1254
|
+
fullName: exactStoredStringSchema.optional(),
|
|
1255
|
+
platform: z.literal("slack").optional(),
|
|
1256
|
+
slackUserId: exactStoredStringSchema.optional(),
|
|
1257
|
+
slackUserName: exactStoredStringSchema.optional(),
|
|
1258
|
+
teamId: exactStoredStringSchema.optional()
|
|
1259
|
+
}).strict();
|
|
1260
|
+
/** Return whether an actor is a platform-scoped user actor. */
|
|
1261
|
+
function isUserActor(actor) {
|
|
1262
|
+
return Boolean(actor && "userId" in actor);
|
|
1251
1263
|
}
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
* side effects finish; callers should still fence each blind write.
|
|
1256
|
-
*/
|
|
1257
|
-
async function withLock(state, key, run, options = {}) {
|
|
1258
|
-
const ttlMs = options.ttlMs ?? 9e4;
|
|
1259
|
-
const startedAtMs = Date.now();
|
|
1260
|
-
let lock;
|
|
1261
|
-
while (true) {
|
|
1262
|
-
lock = await state.acquireLock(key, ttlMs);
|
|
1263
|
-
if (lock) break;
|
|
1264
|
-
if (Date.now() - startedAtMs >= (options.waitMs ?? 0)) return { acquired: false };
|
|
1265
|
-
await setTimeout(options.retryMs ?? 25, void 0, { ref: false });
|
|
1266
|
-
}
|
|
1267
|
-
const heartbeat = options.keepAlive ? setInterval(() => void state.extendLock(lock, ttlMs).catch(() => void 0), Math.max(1, Math.floor(ttlMs / 3))) : void 0;
|
|
1268
|
-
heartbeat?.unref();
|
|
1269
|
-
try {
|
|
1270
|
-
return {
|
|
1271
|
-
acquired: true,
|
|
1272
|
-
value: await run(lock)
|
|
1273
|
-
};
|
|
1274
|
-
} finally {
|
|
1275
|
-
if (heartbeat) clearInterval(heartbeat);
|
|
1276
|
-
await state.releaseLock(lock);
|
|
1277
|
-
}
|
|
1264
|
+
function clean(value) {
|
|
1265
|
+
const trimmed = value?.trim();
|
|
1266
|
+
return trimmed ? trimmed : void 0;
|
|
1278
1267
|
}
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
*
|
|
1282
|
-
* Whole-record mutations must stop if their lock expired rather than overwrite
|
|
1283
|
-
* state committed by a newer owner.
|
|
1284
|
-
*/
|
|
1285
|
-
async function fenceLock(state, lock, ttlMs = MUTATION_LOCK_TTL_MS) {
|
|
1286
|
-
if (!await state.extendLock(lock, ttlMs)) throw new Error(`Lock ownership was lost before write for ${lock.threadId}`);
|
|
1268
|
+
function isSyntheticActorUserId(value) {
|
|
1269
|
+
return value.toLowerCase() === "unknown";
|
|
1287
1270
|
}
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1271
|
+
/** Return whether a value has the shape of a Slack user id. */
|
|
1272
|
+
function isSlackUserId(value) {
|
|
1273
|
+
return SLACK_USER_ID_DISPLAY_PATTERN.test(value);
|
|
1274
|
+
}
|
|
1275
|
+
function cleanActorDisplayName(value, userId) {
|
|
1276
|
+
const displayName = clean(value);
|
|
1277
|
+
if (!displayName) return;
|
|
1278
|
+
if (displayName.toLowerCase() === "unknown") return;
|
|
1279
|
+
if (userId && displayName === userId) return;
|
|
1280
|
+
return isSlackUserId(displayName) ? void 0 : displayName;
|
|
1281
|
+
}
|
|
1282
|
+
function cleanActorEmail(value) {
|
|
1283
|
+
const email = clean(value);
|
|
1284
|
+
return email && EMAIL_PATTERN.test(email) ? email : void 0;
|
|
1285
|
+
}
|
|
1286
|
+
/** Keep actor ids exact at platform boundaries before they enter owned state. */
|
|
1287
|
+
function parseActorUserId(value) {
|
|
1288
|
+
if (typeof value !== "string" || value.length === 0) return;
|
|
1289
|
+
if (value !== value.trim() || isSyntheticActorUserId(value)) return;
|
|
1290
|
+
return value;
|
|
1291
|
+
}
|
|
1292
|
+
/** Assert persisted actor ids without read-side repair. */
|
|
1293
|
+
function isActorUserId(value) {
|
|
1294
|
+
return parseActorUserId(value) === value;
|
|
1295
|
+
}
|
|
1296
|
+
/** Build Junior's canonical platform actor from exact actor ids and profile data. */
|
|
1297
|
+
function createActor(input, context) {
|
|
1298
|
+
const platform = context.platform ?? input?.platform;
|
|
1299
|
+
if (!platform) return;
|
|
1300
|
+
const contextUserId = parseActorUserId(context.userId);
|
|
1301
|
+
if (context.userId !== void 0 && !contextUserId) return;
|
|
1302
|
+
const inputUserId = parseActorUserId(input?.userId);
|
|
1303
|
+
if (input?.userId !== void 0 && !inputUserId) return;
|
|
1304
|
+
const actorUserId = contextUserId ?? inputUserId;
|
|
1305
|
+
if (!actorUserId) return;
|
|
1306
|
+
const contextTeamId = parseSlackTeamId(context.teamId);
|
|
1307
|
+
if (context.teamId !== void 0 && !contextTeamId) return;
|
|
1308
|
+
const inputTeamId = parseSlackTeamId(input?.teamId);
|
|
1309
|
+
if (input?.teamId !== void 0 && !inputTeamId) return;
|
|
1310
|
+
const actorTeamId = contextTeamId ?? inputTeamId;
|
|
1311
|
+
if (platform === "slack" && !actorTeamId) return;
|
|
1312
|
+
const canUseInputProfile = (!contextUserId || !inputUserId || contextUserId === inputUserId) && (platform !== "slack" || !contextTeamId || !inputTeamId || contextTeamId === inputTeamId);
|
|
1313
|
+
const actor = {
|
|
1314
|
+
...canUseInputProfile && cleanActorEmail(input?.email) ? { email: cleanActorEmail(input?.email) } : void 0,
|
|
1315
|
+
...canUseInputProfile && cleanActorDisplayName(input?.fullName, actorUserId) ? { fullName: cleanActorDisplayName(input?.fullName, actorUserId) } : void 0,
|
|
1316
|
+
platform,
|
|
1317
|
+
userId: actorUserId,
|
|
1318
|
+
...canUseInputProfile && cleanActorDisplayName(input?.userName, actorUserId) ? { userName: cleanActorDisplayName(input?.userName, actorUserId) } : void 0
|
|
1319
|
+
};
|
|
1320
|
+
if (platform === "slack") return {
|
|
1321
|
+
...actor,
|
|
1322
|
+
platform,
|
|
1323
|
+
teamId: actorTeamId
|
|
1299
1324
|
};
|
|
1300
1325
|
return {
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
disconnect: () => base.disconnect(),
|
|
1304
|
-
subscribe: (threadId) => connected(() => base.subscribe(threadId)),
|
|
1305
|
-
unsubscribe: (threadId) => connected(() => base.unsubscribe(threadId)),
|
|
1306
|
-
isSubscribed: (threadId) => connected(() => base.isSubscribed(threadId)),
|
|
1307
|
-
acquireLock: (threadId, ttlMs) => connected(() => base.acquireLock(threadId, ttlMs)),
|
|
1308
|
-
releaseLock: (lock) => connected(() => base.releaseLock(lock)),
|
|
1309
|
-
extendLock: (lock, ttlMs) => connected(() => base.extendLock(lock, ttlMs)),
|
|
1310
|
-
forceReleaseLock: (threadId) => connected(() => base.forceReleaseLock(threadId)),
|
|
1311
|
-
enqueue: (threadId, entry, maxSize) => connected(() => base.enqueue(threadId, entry, maxSize)),
|
|
1312
|
-
dequeue: (threadId) => connected(() => base.dequeue(threadId)),
|
|
1313
|
-
queueDepth: (threadId) => connected(() => base.queueDepth(threadId)),
|
|
1314
|
-
get: (key) => connected(() => base.get(key)),
|
|
1315
|
-
getList: (key) => connected(() => base.getList(key)),
|
|
1316
|
-
set: (key, value, ttlMs) => connected(() => base.set(key, value, ttlMs)),
|
|
1317
|
-
setIfNotExists: (key, value, ttlMs) => connected(() => base.setIfNotExists(key, value, ttlMs)),
|
|
1318
|
-
delete: (key) => connected(() => base.delete(key))
|
|
1326
|
+
...actor,
|
|
1327
|
+
platform
|
|
1319
1328
|
};
|
|
1320
1329
|
}
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
const
|
|
1324
|
-
const
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1330
|
+
/** Build Junior's canonical actor from Slack profile data. */
|
|
1331
|
+
function createSlackActor(teamId, userId, profile) {
|
|
1332
|
+
const actorUserId = parseActorUserId(userId);
|
|
1333
|
+
const actorTeamId = parseSlackTeamId(teamId);
|
|
1334
|
+
if (!actorTeamId || !actorUserId) throw new Error("Slack actor requires team and user ids");
|
|
1335
|
+
const actor = createActor({
|
|
1336
|
+
email: profile?.email,
|
|
1337
|
+
fullName: profile?.fullName,
|
|
1338
|
+
platform: "slack",
|
|
1339
|
+
teamId: actorTeamId,
|
|
1340
|
+
userId: actorUserId,
|
|
1341
|
+
userName: profile?.userName
|
|
1342
|
+
}, {
|
|
1343
|
+
teamId: actorTeamId,
|
|
1344
|
+
userId: actorUserId
|
|
1331
1345
|
});
|
|
1346
|
+
if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
|
|
1347
|
+
return actor;
|
|
1348
|
+
}
|
|
1349
|
+
/** Parse a serialized Slack actor that crossed a runtime boundary. */
|
|
1350
|
+
function parseStoredSlackActor(value) {
|
|
1351
|
+
const parsed = storedSlackActorSchema.safeParse(value);
|
|
1352
|
+
if (!parsed.success) return;
|
|
1353
|
+
if (parsed.data.slackUserId !== void 0 && !parseActorUserId(parsed.data.slackUserId)) return;
|
|
1354
|
+
if (parsed.data.teamId !== void 0 && !parseSlackTeamId(parsed.data.teamId)) return;
|
|
1355
|
+
if ((parsed.data.platform !== void 0 || parsed.data.teamId !== void 0) && (!parsed.data.platform || !parsed.data.teamId)) return;
|
|
1356
|
+
return parsed.data;
|
|
1357
|
+
}
|
|
1358
|
+
/** Convert a runtime Slack actor into its durable session shape. */
|
|
1359
|
+
function toStoredSlackActor(actor) {
|
|
1332
1360
|
return {
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
acquireLock: async (threadId, ttlMs) => {
|
|
1340
|
-
const lock = await base.acquireLock(prefixed(threadId), ttlMs);
|
|
1341
|
-
return lock ? unprefixLock(lock) : null;
|
|
1342
|
-
},
|
|
1343
|
-
releaseLock: (lock) => base.releaseLock(prefixLock(lock)),
|
|
1344
|
-
extendLock: async (lock, ttlMs) => {
|
|
1345
|
-
const prefixedLock = prefixLock(lock);
|
|
1346
|
-
const extended = await base.extendLock(prefixedLock, ttlMs);
|
|
1347
|
-
if (extended) lock.expiresAt = prefixedLock.expiresAt;
|
|
1348
|
-
return extended;
|
|
1349
|
-
},
|
|
1350
|
-
forceReleaseLock: (threadId) => base.forceReleaseLock(prefixed(threadId)),
|
|
1351
|
-
enqueue: (threadId, entry, maxSize) => base.enqueue(prefixed(threadId), entry, maxSize),
|
|
1352
|
-
dequeue: (threadId) => base.dequeue(prefixed(threadId)),
|
|
1353
|
-
queueDepth: (threadId) => base.queueDepth(prefixed(threadId)),
|
|
1354
|
-
get: (key) => base.get(prefixed(key)),
|
|
1355
|
-
getList: (key) => base.getList(prefixed(key)),
|
|
1356
|
-
set: (key, value, ttlMs) => base.set(prefixed(key), value, ttlMs),
|
|
1357
|
-
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(prefixed(key), value, ttlMs),
|
|
1358
|
-
delete: (key) => base.delete(prefixed(key))
|
|
1361
|
+
...actor.email ? { email: actor.email } : void 0,
|
|
1362
|
+
...actor.fullName ? { fullName: actor.fullName } : void 0,
|
|
1363
|
+
platform: actor.platform,
|
|
1364
|
+
slackUserId: actor.userId,
|
|
1365
|
+
...actor.userName ? { slackUserName: actor.userName } : void 0,
|
|
1366
|
+
teamId: actor.teamId
|
|
1359
1367
|
};
|
|
1360
1368
|
}
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
}
|
|
1371
|
-
const
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1369
|
+
/**
|
|
1370
|
+
* Resolve a Slack resume actor from stored profile data and the active actor.
|
|
1371
|
+
*
|
|
1372
|
+
* TODO(dcramer): Require Actor and remove ID-only construction after no
|
|
1373
|
+
* deployed Turn cursor can omit Actor.
|
|
1374
|
+
*/
|
|
1375
|
+
function createSlackResumeActor(args) {
|
|
1376
|
+
if (args.actor) {
|
|
1377
|
+
if (args.actor.platform !== "slack" || args.actor.teamId !== args.teamId || args.actor.userId !== args.userId) throw new Error("Stored Slack actor did not match resume actor");
|
|
1378
|
+
}
|
|
1379
|
+
const actor = createActor(args.actor, {
|
|
1380
|
+
platform: "slack",
|
|
1381
|
+
teamId: args.teamId,
|
|
1382
|
+
userId: args.userId
|
|
1383
|
+
});
|
|
1384
|
+
if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
|
|
1385
|
+
return actor;
|
|
1386
|
+
}
|
|
1387
|
+
// src/chat/credentials/context.ts
|
|
1388
|
+
const exactActorIdSchema = z.string().refine((value) => parseActorUserId(value) === value);
|
|
1389
|
+
const exactNonBlankStringSchema = z.string().min(1).refine((value) => value === value.trim());
|
|
1390
|
+
const slackDirectCredentialSubjectBindingSchema = z.object({
|
|
1391
|
+
type: z.literal("slack-direct-conversation"),
|
|
1392
|
+
teamId: z.string().min(1),
|
|
1393
|
+
channelId: z.string().min(1),
|
|
1394
|
+
signature: z.string().min(1)
|
|
1395
|
+
}).strict();
|
|
1396
|
+
const scheduledAutomationCredentialSubjectBindingSchema = z.object({
|
|
1397
|
+
type: z.literal("scheduled-automation"),
|
|
1398
|
+
plugin: z.string().min(1),
|
|
1399
|
+
taskId: exactNonBlankStringSchema,
|
|
1400
|
+
signature: z.string().min(1)
|
|
1401
|
+
}).strict();
|
|
1402
|
+
const eventAutomationCredentialSubjectBindingSchema = z.object({
|
|
1403
|
+
type: z.literal("event-automation"),
|
|
1404
|
+
plugin: z.string().min(1),
|
|
1405
|
+
taskId: exactNonBlankStringSchema,
|
|
1406
|
+
signature: z.string().min(1)
|
|
1407
|
+
}).strict();
|
|
1408
|
+
const timerWatchCredentialSubjectBindingSchema = z.object({
|
|
1409
|
+
type: z.literal("timer-watch"),
|
|
1410
|
+
conversationId: exactNonBlankStringSchema,
|
|
1411
|
+
watchId: exactNonBlankStringSchema,
|
|
1412
|
+
signature: z.string().min(1)
|
|
1413
|
+
}).strict();
|
|
1414
|
+
z.discriminatedUnion("type", [
|
|
1415
|
+
slackDirectCredentialSubjectBindingSchema,
|
|
1416
|
+
scheduledAutomationCredentialSubjectBindingSchema,
|
|
1417
|
+
eventAutomationCredentialSubjectBindingSchema,
|
|
1418
|
+
timerWatchCredentialSubjectBindingSchema
|
|
1419
|
+
]);
|
|
1420
|
+
const credentialUserActorSchema = z.object({
|
|
1421
|
+
type: z.literal("user"),
|
|
1422
|
+
userId: exactActorIdSchema
|
|
1423
|
+
}).strict();
|
|
1424
|
+
const credentialSystemActorSchema = z.object({
|
|
1425
|
+
platform: z.literal("system"),
|
|
1426
|
+
name: exactActorIdSchema
|
|
1427
|
+
}).strict();
|
|
1428
|
+
const credentialSubjectSchema = z.discriminatedUnion("allowedWhen", [
|
|
1429
|
+
z.object({
|
|
1430
|
+
type: z.literal("user"),
|
|
1431
|
+
userId: exactActorIdSchema,
|
|
1432
|
+
allowedWhen: z.literal("private-direct-conversation"),
|
|
1433
|
+
binding: slackDirectCredentialSubjectBindingSchema
|
|
1434
|
+
}).strict(),
|
|
1435
|
+
z.object({
|
|
1436
|
+
type: z.literal("user"),
|
|
1437
|
+
userId: exactActorIdSchema,
|
|
1438
|
+
allowedWhen: z.literal("scheduled-automation"),
|
|
1439
|
+
taskId: exactNonBlankStringSchema,
|
|
1440
|
+
binding: scheduledAutomationCredentialSubjectBindingSchema
|
|
1441
|
+
}).strict().refine((subject) => subject.binding.taskId === subject.taskId, {
|
|
1442
|
+
message: "Scheduled automation credential subject requires task binding",
|
|
1443
|
+
path: ["binding"]
|
|
1444
|
+
}),
|
|
1445
|
+
z.object({
|
|
1446
|
+
type: z.literal("user"),
|
|
1447
|
+
userId: exactActorIdSchema,
|
|
1448
|
+
allowedWhen: z.literal("event-automation"),
|
|
1449
|
+
taskId: exactNonBlankStringSchema,
|
|
1450
|
+
binding: eventAutomationCredentialSubjectBindingSchema
|
|
1451
|
+
}).strict().refine((subject) => subject.binding.taskId === subject.taskId, {
|
|
1452
|
+
message: "Event automation credential subject requires task binding",
|
|
1453
|
+
path: ["binding"]
|
|
1454
|
+
}),
|
|
1455
|
+
z.object({
|
|
1456
|
+
type: z.literal("user"),
|
|
1457
|
+
userId: exactActorIdSchema,
|
|
1458
|
+
allowedWhen: z.literal("timer-watch"),
|
|
1459
|
+
binding: timerWatchCredentialSubjectBindingSchema
|
|
1460
|
+
}).strict()
|
|
1461
|
+
]);
|
|
1462
|
+
const credentialContextSchema = z.union([z.object({ actor: credentialUserActorSchema }).strict(), z.object({
|
|
1463
|
+
actor: credentialSystemActorSchema,
|
|
1464
|
+
subject: credentialSubjectSchema.optional()
|
|
1465
|
+
}).strict()]);
|
|
1466
|
+
/**
|
|
1467
|
+
* Build credential authority from the run actor.
|
|
1468
|
+
*
|
|
1469
|
+
* `actor` is the rich execution principal. This projects the credential stub
|
|
1470
|
+
* tools/auth need from it:
|
|
1471
|
+
* - user actor → `{ actor: { type: "user", userId } }`
|
|
1472
|
+
* - system actor → `{ actor: systemActor, subject? }`
|
|
1473
|
+
*
|
|
1474
|
+
* They only diverge when a system run carries an explicit delegated `subject`
|
|
1475
|
+
* (scheduled/event-automation creator credentials). Callers should set `actor` first,
|
|
1476
|
+
* then derive this — do not hand-build parallel shapes.
|
|
1477
|
+
*/
|
|
1478
|
+
function credentialContextForActor(actor, subject) {
|
|
1479
|
+
if (actor.platform === "system") return subject ? {
|
|
1480
|
+
actor,
|
|
1481
|
+
subject
|
|
1482
|
+
} : { actor };
|
|
1483
|
+
if (subject) throw new TypeError("Delegated credential subjects require a system actor");
|
|
1484
|
+
return { actor: {
|
|
1485
|
+
type: "user",
|
|
1486
|
+
userId: actor.userId
|
|
1487
|
+
} };
|
|
1488
|
+
}
|
|
1489
|
+
/**
|
|
1490
|
+
* Name the person accountable for credential authority in logs.
|
|
1491
|
+
*
|
|
1492
|
+
* `userId` is the user actor, or the owner of delegated credentials when the
|
|
1493
|
+
* system acts for an Automation or Watch. `actorType` says who acted.
|
|
1494
|
+
*/
|
|
1495
|
+
function credentialLogContext(context) {
|
|
1496
|
+
if ("type" in context.actor) return {
|
|
1497
|
+
userId: context.actor.userId,
|
|
1498
|
+
actorType: "user",
|
|
1499
|
+
actorId: context.actor.userId
|
|
1500
|
+
};
|
|
1501
|
+
const subject = "subject" in context ? context.subject : void 0;
|
|
1502
|
+
return {
|
|
1503
|
+
actorType: "system",
|
|
1504
|
+
actorId: context.actor.name,
|
|
1505
|
+
...subject ? {
|
|
1506
|
+
userId: subject.userId,
|
|
1507
|
+
credentialAllowedWhen: subject.allowedWhen,
|
|
1508
|
+
..."taskId" in subject ? { taskId: subject.taskId } : void 0
|
|
1509
|
+
} : void 0
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* Name the run's people in logs: the accountable person and who acted.
|
|
1514
|
+
*
|
|
1515
|
+
* A user actor is the accountable person. A system actor names the owner of
|
|
1516
|
+
* delegated credentials, when the run has them.
|
|
1517
|
+
*/
|
|
1518
|
+
function actorLogContext(actor, credentialContext) {
|
|
1519
|
+
const credential = credentialContext ? credentialLogContext(credentialContext) : {};
|
|
1520
|
+
if (!isUserActor(actor)) return credential;
|
|
1521
|
+
return {
|
|
1522
|
+
...credential,
|
|
1523
|
+
userId: actor.userId,
|
|
1524
|
+
userName: actor.userName,
|
|
1525
|
+
userEmail: actor.email,
|
|
1526
|
+
userFullName: actor.fullName
|
|
1527
|
+
};
|
|
1528
|
+
}
|
|
1529
|
+
/** Return the user whose OAuth token may satisfy this credential request. */
|
|
1530
|
+
function credentialUserSubjectId(context) {
|
|
1531
|
+
if ("type" in context.actor) return context.actor.userId;
|
|
1532
|
+
return "subject" in context ? context.subject?.userId : void 0;
|
|
1533
|
+
}
|
|
1534
|
+
// src/chat/state/locks.ts
|
|
1535
|
+
const ACTIVE_LOCK_TTL_MS = 9e4;
|
|
1536
|
+
const MUTATION_LOCK_TTL_MS = 1e4;
|
|
1537
|
+
/**
|
|
1538
|
+
* Acquire a lock for long-running work that the queued state adapter should
|
|
1539
|
+
* keep alive while the owning invocation is still making progress.
|
|
1540
|
+
*/
|
|
1541
|
+
async function acquireActiveLock(state, threadId) {
|
|
1542
|
+
return await state.acquireLock(threadId, ACTIVE_LOCK_TTL_MS);
|
|
1543
|
+
}
|
|
1544
|
+
/**
|
|
1545
|
+
* Run work under one lock, optionally waiting for the current owner.
|
|
1546
|
+
* `keepAlive` is for multi-store mutations that must retain ownership until all
|
|
1547
|
+
* side effects finish; callers should still fence each blind write.
|
|
1548
|
+
*/
|
|
1549
|
+
async function withLock(state, key, run, options = {}) {
|
|
1550
|
+
const ttlMs = options.ttlMs ?? 9e4;
|
|
1551
|
+
const startedAtMs = Date.now();
|
|
1552
|
+
let lock;
|
|
1553
|
+
while (true) {
|
|
1554
|
+
lock = await state.acquireLock(key, ttlMs);
|
|
1555
|
+
if (lock) break;
|
|
1556
|
+
if (Date.now() - startedAtMs >= (options.waitMs ?? 0)) return { acquired: false };
|
|
1557
|
+
await setTimeout(options.retryMs ?? 25, void 0, { ref: false });
|
|
1558
|
+
}
|
|
1559
|
+
const heartbeat = options.keepAlive ? setInterval(() => void state.extendLock(lock, ttlMs).catch(() => void 0), Math.max(1, Math.floor(ttlMs / 3))) : void 0;
|
|
1560
|
+
heartbeat?.unref();
|
|
1561
|
+
try {
|
|
1562
|
+
return {
|
|
1563
|
+
acquired: true,
|
|
1564
|
+
value: await run(lock)
|
|
1565
|
+
};
|
|
1566
|
+
} finally {
|
|
1567
|
+
if (heartbeat) clearInterval(heartbeat);
|
|
1568
|
+
await state.releaseLock(lock);
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* Prove lock ownership immediately before a blind write.
|
|
1573
|
+
*
|
|
1574
|
+
* Whole-record mutations must stop if their lock expired rather than overwrite
|
|
1575
|
+
* state committed by a newer owner.
|
|
1576
|
+
*/
|
|
1577
|
+
async function fenceLock(state, lock, ttlMs = MUTATION_LOCK_TTL_MS) {
|
|
1578
|
+
if (!await state.extendLock(lock, ttlMs)) throw new Error(`Lock ownership was lost before write for ${lock.threadId}`);
|
|
1579
|
+
}
|
|
1580
|
+
// src/chat/state/adapter.ts
|
|
1581
|
+
var adapter_exports = /* @__PURE__ */ __exportAll({ getStateAdapter: () => getStateAdapter });
|
|
1582
|
+
const ACTIVE_LOCK_HEARTBEAT_MS = 3e4;
|
|
1583
|
+
const REDIS_STATE_KEY_PREFIX = "chat-sdk";
|
|
1584
|
+
let stateAdapter;
|
|
1585
|
+
let redisStateAdapter;
|
|
1586
|
+
/** Lazily connect state operations, including queued-adapter lock heartbeats. */
|
|
1587
|
+
function createConnectingStateAdapter(base) {
|
|
1588
|
+
const connected = async (operation) => {
|
|
1589
|
+
await base.connect();
|
|
1590
|
+
return await operation();
|
|
1591
|
+
};
|
|
1592
|
+
return {
|
|
1593
|
+
appendToList: (key, value, options) => connected(() => base.appendToList(key, value, options)),
|
|
1594
|
+
connect: () => base.connect(),
|
|
1595
|
+
disconnect: () => base.disconnect(),
|
|
1596
|
+
subscribe: (threadId) => connected(() => base.subscribe(threadId)),
|
|
1597
|
+
unsubscribe: (threadId) => connected(() => base.unsubscribe(threadId)),
|
|
1598
|
+
isSubscribed: (threadId) => connected(() => base.isSubscribed(threadId)),
|
|
1599
|
+
acquireLock: (threadId, ttlMs) => connected(() => base.acquireLock(threadId, ttlMs)),
|
|
1600
|
+
releaseLock: (lock) => connected(() => base.releaseLock(lock)),
|
|
1601
|
+
extendLock: (lock, ttlMs) => connected(() => base.extendLock(lock, ttlMs)),
|
|
1602
|
+
forceReleaseLock: (threadId) => connected(() => base.forceReleaseLock(threadId)),
|
|
1603
|
+
enqueue: (threadId, entry, maxSize) => connected(() => base.enqueue(threadId, entry, maxSize)),
|
|
1604
|
+
dequeue: (threadId) => connected(() => base.dequeue(threadId)),
|
|
1605
|
+
queueDepth: (threadId) => connected(() => base.queueDepth(threadId)),
|
|
1606
|
+
get: (key) => connected(() => base.get(key)),
|
|
1607
|
+
getList: (key) => connected(() => base.getList(key)),
|
|
1608
|
+
set: (key, value, ttlMs) => connected(() => base.set(key, value, ttlMs)),
|
|
1609
|
+
setIfNotExists: (key, value, ttlMs) => connected(() => base.setIfNotExists(key, value, ttlMs)),
|
|
1610
|
+
delete: (key) => connected(() => base.delete(key))
|
|
1611
|
+
};
|
|
1612
|
+
}
|
|
1613
|
+
function createPrefixedStateAdapter(base, prefix) {
|
|
1614
|
+
const prefixed = (value) => `${prefix}:${value}`;
|
|
1615
|
+
const unprefixed = (value) => value.startsWith(`${prefix}:`) ? value.slice(prefix.length + 1) : value;
|
|
1616
|
+
const prefixLock = (lock) => ({
|
|
1617
|
+
...lock,
|
|
1618
|
+
threadId: prefixed(lock.threadId)
|
|
1619
|
+
});
|
|
1620
|
+
const unprefixLock = (lock) => ({
|
|
1621
|
+
...lock,
|
|
1622
|
+
threadId: unprefixed(lock.threadId)
|
|
1623
|
+
});
|
|
1624
|
+
return {
|
|
1625
|
+
appendToList: (key, value, options) => base.appendToList(prefixed(key), value, options),
|
|
1626
|
+
connect: () => base.connect(),
|
|
1627
|
+
disconnect: () => base.disconnect(),
|
|
1628
|
+
subscribe: (threadId) => base.subscribe(prefixed(threadId)),
|
|
1629
|
+
unsubscribe: (threadId) => base.unsubscribe(prefixed(threadId)),
|
|
1630
|
+
isSubscribed: (threadId) => base.isSubscribed(prefixed(threadId)),
|
|
1631
|
+
acquireLock: async (threadId, ttlMs) => {
|
|
1632
|
+
const lock = await base.acquireLock(prefixed(threadId), ttlMs);
|
|
1633
|
+
return lock ? unprefixLock(lock) : null;
|
|
1634
|
+
},
|
|
1635
|
+
releaseLock: (lock) => base.releaseLock(prefixLock(lock)),
|
|
1636
|
+
extendLock: async (lock, ttlMs) => {
|
|
1637
|
+
const prefixedLock = prefixLock(lock);
|
|
1638
|
+
const extended = await base.extendLock(prefixedLock, ttlMs);
|
|
1639
|
+
if (extended) lock.expiresAt = prefixedLock.expiresAt;
|
|
1640
|
+
return extended;
|
|
1641
|
+
},
|
|
1642
|
+
forceReleaseLock: (threadId) => base.forceReleaseLock(prefixed(threadId)),
|
|
1643
|
+
enqueue: (threadId, entry, maxSize) => base.enqueue(prefixed(threadId), entry, maxSize),
|
|
1644
|
+
dequeue: (threadId) => base.dequeue(prefixed(threadId)),
|
|
1645
|
+
queueDepth: (threadId) => base.queueDepth(prefixed(threadId)),
|
|
1646
|
+
get: (key) => base.get(prefixed(key)),
|
|
1647
|
+
getList: (key) => base.getList(prefixed(key)),
|
|
1648
|
+
set: (key, value, ttlMs) => base.set(prefixed(key), value, ttlMs),
|
|
1649
|
+
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(prefixed(key), value, ttlMs),
|
|
1650
|
+
delete: (key) => base.delete(prefixed(key))
|
|
1651
|
+
};
|
|
1652
|
+
}
|
|
1653
|
+
function createQueuedStateAdapter(base, options) {
|
|
1654
|
+
const heartbeats = /* @__PURE__ */ new Map();
|
|
1655
|
+
const shouldHeartbeatLock = (ttlMs) => ttlMs === ACTIVE_LOCK_TTL_MS;
|
|
1656
|
+
const heartbeatKey = (lock) => `${lock.threadId}:${lock.token}`;
|
|
1657
|
+
const stopHeartbeatByKey = (key) => {
|
|
1658
|
+
const heartbeat = heartbeats.get(key);
|
|
1659
|
+
if (!heartbeat) return;
|
|
1660
|
+
clearInterval(heartbeat.timer);
|
|
1661
|
+
heartbeats.delete(key);
|
|
1662
|
+
};
|
|
1663
|
+
const stopHeartbeat = (lock) => {
|
|
1664
|
+
stopHeartbeatByKey(heartbeatKey(lock));
|
|
1665
|
+
};
|
|
1666
|
+
const stopHeartbeatsForThread = (threadId) => {
|
|
1667
|
+
for (const [key, heartbeat] of heartbeats) if (heartbeat.lock.threadId === threadId) stopHeartbeatByKey(key);
|
|
1668
|
+
};
|
|
1669
|
+
const stopAllHeartbeats = () => {
|
|
1670
|
+
for (const key of heartbeats.keys()) stopHeartbeatByKey(key);
|
|
1671
|
+
};
|
|
1672
|
+
const runHeartbeat = async (key) => {
|
|
1673
|
+
const heartbeat = heartbeats.get(key);
|
|
1674
|
+
if (!heartbeat || heartbeat.inFlight) return;
|
|
1675
|
+
heartbeat.inFlight = true;
|
|
1676
|
+
try {
|
|
1677
|
+
if (Date.now() - heartbeat.startedAtMs >= options.activeLockMaxAgeMs) {
|
|
1678
|
+
stopHeartbeatByKey(key);
|
|
1679
|
+
return;
|
|
1680
|
+
}
|
|
1681
|
+
if (!await base.extendLock(heartbeat.lock, heartbeat.ttlMs)) {
|
|
1682
|
+
stopHeartbeatByKey(key);
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
heartbeat.lock.expiresAt = Date.now() + heartbeat.ttlMs;
|
|
1686
|
+
} catch {} finally {
|
|
1687
|
+
const current = heartbeats.get(key);
|
|
1688
|
+
if (current === heartbeat) current.inFlight = false;
|
|
1397
1689
|
}
|
|
1398
1690
|
};
|
|
1399
1691
|
const startOrUpdateHeartbeat = (lock, ttlMs) => {
|
|
@@ -1427,407 +1719,115 @@ function createQueuedStateAdapter(base, options) {
|
|
|
1427
1719
|
stopAllHeartbeats();
|
|
1428
1720
|
await base.disconnect();
|
|
1429
1721
|
},
|
|
1430
|
-
subscribe: (threadId) => base.subscribe(threadId),
|
|
1431
|
-
unsubscribe: (threadId) => base.unsubscribe(threadId),
|
|
1432
|
-
isSubscribed: (threadId) => base.isSubscribed(threadId),
|
|
1433
|
-
acquireLock,
|
|
1434
|
-
releaseLock: async (lock) => {
|
|
1435
|
-
stopHeartbeat(lock);
|
|
1436
|
-
await base.releaseLock(lock);
|
|
1437
|
-
},
|
|
1438
|
-
extendLock: async (lock, ttlMs) => {
|
|
1439
|
-
const extended = await base.extendLock(lock, ttlMs);
|
|
1440
|
-
if (extended) {
|
|
1441
|
-
lock.expiresAt = Date.now() + ttlMs;
|
|
1442
|
-
if (shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
|
|
1443
|
-
else stopHeartbeat(lock);
|
|
1444
|
-
} else stopHeartbeat(lock);
|
|
1445
|
-
return extended;
|
|
1446
|
-
},
|
|
1447
|
-
forceReleaseLock: async (threadId) => {
|
|
1448
|
-
stopHeartbeatsForThread(threadId);
|
|
1449
|
-
await base.forceReleaseLock(threadId);
|
|
1450
|
-
},
|
|
1451
|
-
enqueue: (threadId, entry, maxSize) => base.enqueue(threadId, entry, maxSize),
|
|
1452
|
-
dequeue: (threadId) => base.dequeue(threadId),
|
|
1453
|
-
queueDepth: (threadId) => base.queueDepth(threadId),
|
|
1454
|
-
get: (key) => base.get(key),
|
|
1455
|
-
getList: (key) => base.getList(key),
|
|
1456
|
-
set: (key, value, ttlMs) => base.set(key, value, ttlMs),
|
|
1457
|
-
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(key, value, ttlMs),
|
|
1458
|
-
delete: (key) => base.delete(key)
|
|
1459
|
-
};
|
|
1460
|
-
}
|
|
1461
|
-
function withOptionalPrefix(base, prefix) {
|
|
1462
|
-
return prefix ? createPrefixedStateAdapter(base, prefix) : base;
|
|
1463
|
-
}
|
|
1464
|
-
function createStateAdapter() {
|
|
1465
|
-
const config = getChatConfig();
|
|
1466
|
-
const activeLockMaxAgeMs = config.bot.turnTimeoutMs + ACTIVE_LOCK_TTL_MS;
|
|
1467
|
-
if (config.state.adapter === "memory") {
|
|
1468
|
-
redisStateAdapter = void 0;
|
|
1469
|
-
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(createMemoryState(), config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
1470
|
-
}
|
|
1471
|
-
if (!config.state.redisUrl) throw new Error("REDIS_URL is required for durable Slack thread state");
|
|
1472
|
-
const redisState = createRedisState({
|
|
1473
|
-
keyPrefix: REDIS_STATE_KEY_PREFIX,
|
|
1474
|
-
url: config.state.redisUrl
|
|
1475
|
-
});
|
|
1476
|
-
redisStateAdapter = redisState;
|
|
1477
|
-
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(redisState, config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
1478
|
-
}
|
|
1479
|
-
function getOptionalRedisStateAdapter() {
|
|
1480
|
-
getStateAdapter();
|
|
1481
|
-
return redisStateAdapter;
|
|
1482
|
-
}
|
|
1483
|
-
async function getConnectedStateContext() {
|
|
1484
|
-
const adapter = getStateAdapter();
|
|
1485
|
-
await adapter.connect();
|
|
1486
|
-
return {
|
|
1487
|
-
redisStateAdapter: getOptionalRedisStateAdapter(),
|
|
1488
|
-
stateAdapter: adapter
|
|
1489
|
-
};
|
|
1490
|
-
}
|
|
1491
|
-
/** Return the Redis adapter only when the caller is using the default state adapter. */
|
|
1492
|
-
async function getDefaultRedisStateAdapterFor(adapter) {
|
|
1493
|
-
if (adapter !== stateAdapter) return;
|
|
1494
|
-
const context = await getConnectedStateContext();
|
|
1495
|
-
return context.stateAdapter === adapter ? context.redisStateAdapter : void 0;
|
|
1496
|
-
}
|
|
1497
|
-
/** The Redis key that the default Redis adapter uses for one state value key. */
|
|
1498
|
-
function redisStateKey(key) {
|
|
1499
|
-
const prefix = getChatConfig().state.keyPrefix;
|
|
1500
|
-
return `${REDIS_STATE_KEY_PREFIX}:cache:${prefix ? `${prefix}:` : ""}${key}`;
|
|
1501
|
-
}
|
|
1502
|
-
/** Read state values in one Redis round trip. Other adapters read each key. */
|
|
1503
|
-
async function getStateValues(state, keys) {
|
|
1504
|
-
if (keys.length === 0) return [];
|
|
1505
|
-
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
1506
|
-
if (!redis) return await mapBounded(keys, (key) => state.get(key));
|
|
1507
|
-
return (await redis.getClient().mGet(keys.map(redisStateKey))).map((value) => {
|
|
1508
|
-
if (value === null) return null;
|
|
1509
|
-
try {
|
|
1510
|
-
return JSON.parse(value);
|
|
1511
|
-
} catch {
|
|
1512
|
-
return value;
|
|
1513
|
-
}
|
|
1514
|
-
});
|
|
1515
|
-
}
|
|
1516
|
-
/** Write state values with one TTL in one Redis round trip. */
|
|
1517
|
-
async function setStateValues(state, entries, ttlMs) {
|
|
1518
|
-
if (entries.length === 0) return;
|
|
1519
|
-
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
1520
|
-
if (!redis) {
|
|
1521
|
-
await mapBounded(entries, ({ key, value }) => state.set(key, value, ttlMs));
|
|
1522
|
-
return;
|
|
1523
|
-
}
|
|
1524
|
-
const pipeline = redis.getClient().multi();
|
|
1525
|
-
for (const { key, value } of entries) pipeline.set(redisStateKey(key), JSON.stringify(value), { PX: ttlMs });
|
|
1526
|
-
await pipeline.execAsPipeline();
|
|
1527
|
-
}
|
|
1528
|
-
function getStateAdapter() {
|
|
1529
|
-
if (!stateAdapter) stateAdapter = createStateAdapter();
|
|
1530
|
-
return stateAdapter;
|
|
1531
|
-
}
|
|
1532
|
-
async function disconnectStateAdapter() {
|
|
1533
|
-
if (!stateAdapter) return;
|
|
1534
|
-
try {
|
|
1535
|
-
await stateAdapter.disconnect();
|
|
1536
|
-
} finally {
|
|
1537
|
-
stateAdapter = void 0;
|
|
1538
|
-
redisStateAdapter = void 0;
|
|
1539
|
-
}
|
|
1540
|
-
}
|
|
1541
|
-
// src/chat/actor.ts
|
|
1542
|
-
/**
|
|
1543
|
-
* Canonical actor identity.
|
|
1544
|
-
*
|
|
1545
|
-
* Runtime actors are platform-scoped actors. Stored Slack actor parsing
|
|
1546
|
-
* remains explicit so durable conversation metadata is not repaired on read.
|
|
1547
|
-
*/
|
|
1548
|
-
const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
|
|
1549
|
-
const EMAIL_PATTERN = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
|
1550
|
-
const exactStoredStringSchema = z.string().min(1).refine((value) => value === value.trim());
|
|
1551
|
-
const storedSlackActorSchema = z.object({
|
|
1552
|
-
email: exactStoredStringSchema.optional(),
|
|
1553
|
-
fullName: exactStoredStringSchema.optional(),
|
|
1554
|
-
platform: z.literal("slack").optional(),
|
|
1555
|
-
slackUserId: exactStoredStringSchema.optional(),
|
|
1556
|
-
slackUserName: exactStoredStringSchema.optional(),
|
|
1557
|
-
teamId: exactStoredStringSchema.optional()
|
|
1558
|
-
}).strict();
|
|
1559
|
-
/** Return whether an actor is a platform-scoped user actor. */
|
|
1560
|
-
function isUserActor(actor) {
|
|
1561
|
-
return Boolean(actor && "userId" in actor);
|
|
1562
|
-
}
|
|
1563
|
-
function clean(value) {
|
|
1564
|
-
const trimmed = value?.trim();
|
|
1565
|
-
return trimmed ? trimmed : void 0;
|
|
1566
|
-
}
|
|
1567
|
-
function isSyntheticActorUserId(value) {
|
|
1568
|
-
return value.toLowerCase() === "unknown";
|
|
1569
|
-
}
|
|
1570
|
-
/** Return whether a value has the shape of a Slack user id. */
|
|
1571
|
-
function isSlackUserId(value) {
|
|
1572
|
-
return SLACK_USER_ID_DISPLAY_PATTERN.test(value);
|
|
1573
|
-
}
|
|
1574
|
-
function cleanActorDisplayName(value, userId) {
|
|
1575
|
-
const displayName = clean(value);
|
|
1576
|
-
if (!displayName) return;
|
|
1577
|
-
if (displayName.toLowerCase() === "unknown") return;
|
|
1578
|
-
if (userId && displayName === userId) return;
|
|
1579
|
-
return isSlackUserId(displayName) ? void 0 : displayName;
|
|
1580
|
-
}
|
|
1581
|
-
function cleanActorEmail(value) {
|
|
1582
|
-
const email = clean(value);
|
|
1583
|
-
return email && EMAIL_PATTERN.test(email) ? email : void 0;
|
|
1584
|
-
}
|
|
1585
|
-
/** Keep actor ids exact at platform boundaries before they enter owned state. */
|
|
1586
|
-
function parseActorUserId(value) {
|
|
1587
|
-
if (typeof value !== "string" || value.length === 0) return;
|
|
1588
|
-
if (value !== value.trim() || isSyntheticActorUserId(value)) return;
|
|
1589
|
-
return value;
|
|
1590
|
-
}
|
|
1591
|
-
/** Assert persisted actor ids without read-side repair. */
|
|
1592
|
-
function isActorUserId(value) {
|
|
1593
|
-
return parseActorUserId(value) === value;
|
|
1594
|
-
}
|
|
1595
|
-
/** Build Junior's canonical platform actor from exact actor ids and profile data. */
|
|
1596
|
-
function createActor(input, context) {
|
|
1597
|
-
const platform = context.platform ?? input?.platform;
|
|
1598
|
-
if (!platform) return;
|
|
1599
|
-
const contextUserId = parseActorUserId(context.userId);
|
|
1600
|
-
if (context.userId !== void 0 && !contextUserId) return;
|
|
1601
|
-
const inputUserId = parseActorUserId(input?.userId);
|
|
1602
|
-
if (input?.userId !== void 0 && !inputUserId) return;
|
|
1603
|
-
const actorUserId = contextUserId ?? inputUserId;
|
|
1604
|
-
if (!actorUserId) return;
|
|
1605
|
-
const contextTeamId = parseSlackTeamId(context.teamId);
|
|
1606
|
-
if (context.teamId !== void 0 && !contextTeamId) return;
|
|
1607
|
-
const inputTeamId = parseSlackTeamId(input?.teamId);
|
|
1608
|
-
if (input?.teamId !== void 0 && !inputTeamId) return;
|
|
1609
|
-
const actorTeamId = contextTeamId ?? inputTeamId;
|
|
1610
|
-
if (platform === "slack" && !actorTeamId) return;
|
|
1611
|
-
const canUseInputProfile = (!contextUserId || !inputUserId || contextUserId === inputUserId) && (platform !== "slack" || !contextTeamId || !inputTeamId || contextTeamId === inputTeamId);
|
|
1612
|
-
const actor = {
|
|
1613
|
-
...canUseInputProfile && cleanActorEmail(input?.email) ? { email: cleanActorEmail(input?.email) } : void 0,
|
|
1614
|
-
...canUseInputProfile && cleanActorDisplayName(input?.fullName, actorUserId) ? { fullName: cleanActorDisplayName(input?.fullName, actorUserId) } : void 0,
|
|
1615
|
-
platform,
|
|
1616
|
-
userId: actorUserId,
|
|
1617
|
-
...canUseInputProfile && cleanActorDisplayName(input?.userName, actorUserId) ? { userName: cleanActorDisplayName(input?.userName, actorUserId) } : void 0
|
|
1618
|
-
};
|
|
1619
|
-
if (platform === "slack") return {
|
|
1620
|
-
...actor,
|
|
1621
|
-
platform,
|
|
1622
|
-
teamId: actorTeamId
|
|
1623
|
-
};
|
|
1624
|
-
return {
|
|
1625
|
-
...actor,
|
|
1626
|
-
platform
|
|
1627
|
-
};
|
|
1628
|
-
}
|
|
1629
|
-
/** Build Junior's canonical actor from Slack profile data. */
|
|
1630
|
-
function createSlackActor(teamId, userId, profile) {
|
|
1631
|
-
const actorUserId = parseActorUserId(userId);
|
|
1632
|
-
const actorTeamId = parseSlackTeamId(teamId);
|
|
1633
|
-
if (!actorTeamId || !actorUserId) throw new Error("Slack actor requires team and user ids");
|
|
1634
|
-
const actor = createActor({
|
|
1635
|
-
email: profile?.email,
|
|
1636
|
-
fullName: profile?.fullName,
|
|
1637
|
-
platform: "slack",
|
|
1638
|
-
teamId: actorTeamId,
|
|
1639
|
-
userId: actorUserId,
|
|
1640
|
-
userName: profile?.userName
|
|
1641
|
-
}, {
|
|
1642
|
-
teamId: actorTeamId,
|
|
1643
|
-
userId: actorUserId
|
|
1644
|
-
});
|
|
1645
|
-
if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
|
|
1646
|
-
return actor;
|
|
1647
|
-
}
|
|
1648
|
-
/** Parse a serialized Slack actor that crossed a runtime boundary. */
|
|
1649
|
-
function parseStoredSlackActor(value) {
|
|
1650
|
-
const parsed = storedSlackActorSchema.safeParse(value);
|
|
1651
|
-
if (!parsed.success) return;
|
|
1652
|
-
if (parsed.data.slackUserId !== void 0 && !parseActorUserId(parsed.data.slackUserId)) return;
|
|
1653
|
-
if (parsed.data.teamId !== void 0 && !parseSlackTeamId(parsed.data.teamId)) return;
|
|
1654
|
-
if ((parsed.data.platform !== void 0 || parsed.data.teamId !== void 0) && (!parsed.data.platform || !parsed.data.teamId)) return;
|
|
1655
|
-
return parsed.data;
|
|
1656
|
-
}
|
|
1657
|
-
/** Convert a runtime Slack actor into its durable session shape. */
|
|
1658
|
-
function toStoredSlackActor(actor) {
|
|
1659
|
-
return {
|
|
1660
|
-
...actor.email ? { email: actor.email } : void 0,
|
|
1661
|
-
...actor.fullName ? { fullName: actor.fullName } : void 0,
|
|
1662
|
-
platform: actor.platform,
|
|
1663
|
-
slackUserId: actor.userId,
|
|
1664
|
-
...actor.userName ? { slackUserName: actor.userName } : void 0,
|
|
1665
|
-
teamId: actor.teamId
|
|
1722
|
+
subscribe: (threadId) => base.subscribe(threadId),
|
|
1723
|
+
unsubscribe: (threadId) => base.unsubscribe(threadId),
|
|
1724
|
+
isSubscribed: (threadId) => base.isSubscribed(threadId),
|
|
1725
|
+
acquireLock,
|
|
1726
|
+
releaseLock: async (lock) => {
|
|
1727
|
+
stopHeartbeat(lock);
|
|
1728
|
+
await base.releaseLock(lock);
|
|
1729
|
+
},
|
|
1730
|
+
extendLock: async (lock, ttlMs) => {
|
|
1731
|
+
const extended = await base.extendLock(lock, ttlMs);
|
|
1732
|
+
if (extended) {
|
|
1733
|
+
lock.expiresAt = Date.now() + ttlMs;
|
|
1734
|
+
if (shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
|
|
1735
|
+
else stopHeartbeat(lock);
|
|
1736
|
+
} else stopHeartbeat(lock);
|
|
1737
|
+
return extended;
|
|
1738
|
+
},
|
|
1739
|
+
forceReleaseLock: async (threadId) => {
|
|
1740
|
+
stopHeartbeatsForThread(threadId);
|
|
1741
|
+
await base.forceReleaseLock(threadId);
|
|
1742
|
+
},
|
|
1743
|
+
enqueue: (threadId, entry, maxSize) => base.enqueue(threadId, entry, maxSize),
|
|
1744
|
+
dequeue: (threadId) => base.dequeue(threadId),
|
|
1745
|
+
queueDepth: (threadId) => base.queueDepth(threadId),
|
|
1746
|
+
get: (key) => base.get(key),
|
|
1747
|
+
getList: (key) => base.getList(key),
|
|
1748
|
+
set: (key, value, ttlMs) => base.set(key, value, ttlMs),
|
|
1749
|
+
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(key, value, ttlMs),
|
|
1750
|
+
delete: (key) => base.delete(key)
|
|
1666
1751
|
};
|
|
1667
1752
|
}
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1753
|
+
function withOptionalPrefix(base, prefix) {
|
|
1754
|
+
return prefix ? createPrefixedStateAdapter(base, prefix) : base;
|
|
1755
|
+
}
|
|
1756
|
+
function createStateAdapter() {
|
|
1757
|
+
const config = getChatConfig();
|
|
1758
|
+
const activeLockMaxAgeMs = config.bot.turnTimeoutMs + ACTIVE_LOCK_TTL_MS;
|
|
1759
|
+
if (config.state.adapter === "memory") {
|
|
1760
|
+
redisStateAdapter = void 0;
|
|
1761
|
+
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(createMemoryState(), config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
1677
1762
|
}
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1763
|
+
if (!config.state.redisUrl) throw new Error("REDIS_URL is required for durable Slack thread state");
|
|
1764
|
+
const redisState = createRedisState({
|
|
1765
|
+
keyPrefix: REDIS_STATE_KEY_PREFIX,
|
|
1766
|
+
url: config.state.redisUrl
|
|
1682
1767
|
});
|
|
1683
|
-
|
|
1684
|
-
return
|
|
1768
|
+
redisStateAdapter = redisState;
|
|
1769
|
+
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(redisState, config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
1685
1770
|
}
|
|
1686
|
-
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
const slackDirectCredentialSubjectBindingSchema = z.object({
|
|
1690
|
-
type: z.literal("slack-direct-conversation"),
|
|
1691
|
-
teamId: z.string().min(1),
|
|
1692
|
-
channelId: z.string().min(1),
|
|
1693
|
-
signature: z.string().min(1)
|
|
1694
|
-
}).strict();
|
|
1695
|
-
const scheduledAutomationCredentialSubjectBindingSchema = z.object({
|
|
1696
|
-
type: z.literal("scheduled-automation"),
|
|
1697
|
-
plugin: z.string().min(1),
|
|
1698
|
-
taskId: exactNonBlankStringSchema,
|
|
1699
|
-
signature: z.string().min(1)
|
|
1700
|
-
}).strict();
|
|
1701
|
-
const eventAutomationCredentialSubjectBindingSchema = z.object({
|
|
1702
|
-
type: z.literal("event-automation"),
|
|
1703
|
-
plugin: z.string().min(1),
|
|
1704
|
-
taskId: exactNonBlankStringSchema,
|
|
1705
|
-
signature: z.string().min(1)
|
|
1706
|
-
}).strict();
|
|
1707
|
-
const timerWatchCredentialSubjectBindingSchema = z.object({
|
|
1708
|
-
type: z.literal("timer-watch"),
|
|
1709
|
-
conversationId: exactNonBlankStringSchema,
|
|
1710
|
-
watchId: exactNonBlankStringSchema,
|
|
1711
|
-
signature: z.string().min(1)
|
|
1712
|
-
}).strict();
|
|
1713
|
-
z.discriminatedUnion("type", [
|
|
1714
|
-
slackDirectCredentialSubjectBindingSchema,
|
|
1715
|
-
scheduledAutomationCredentialSubjectBindingSchema,
|
|
1716
|
-
eventAutomationCredentialSubjectBindingSchema,
|
|
1717
|
-
timerWatchCredentialSubjectBindingSchema
|
|
1718
|
-
]);
|
|
1719
|
-
const credentialUserActorSchema = z.object({
|
|
1720
|
-
type: z.literal("user"),
|
|
1721
|
-
userId: exactActorIdSchema
|
|
1722
|
-
}).strict();
|
|
1723
|
-
const credentialSystemActorSchema = z.object({
|
|
1724
|
-
platform: z.literal("system"),
|
|
1725
|
-
name: exactActorIdSchema
|
|
1726
|
-
}).strict();
|
|
1727
|
-
const credentialSubjectSchema = z.discriminatedUnion("allowedWhen", [
|
|
1728
|
-
z.object({
|
|
1729
|
-
type: z.literal("user"),
|
|
1730
|
-
userId: exactActorIdSchema,
|
|
1731
|
-
allowedWhen: z.literal("private-direct-conversation"),
|
|
1732
|
-
binding: slackDirectCredentialSubjectBindingSchema
|
|
1733
|
-
}).strict(),
|
|
1734
|
-
z.object({
|
|
1735
|
-
type: z.literal("user"),
|
|
1736
|
-
userId: exactActorIdSchema,
|
|
1737
|
-
allowedWhen: z.literal("scheduled-automation"),
|
|
1738
|
-
taskId: exactNonBlankStringSchema,
|
|
1739
|
-
binding: scheduledAutomationCredentialSubjectBindingSchema
|
|
1740
|
-
}).strict().refine((subject) => subject.binding.taskId === subject.taskId, {
|
|
1741
|
-
message: "Scheduled automation credential subject requires task binding",
|
|
1742
|
-
path: ["binding"]
|
|
1743
|
-
}),
|
|
1744
|
-
z.object({
|
|
1745
|
-
type: z.literal("user"),
|
|
1746
|
-
userId: exactActorIdSchema,
|
|
1747
|
-
allowedWhen: z.literal("event-automation"),
|
|
1748
|
-
taskId: exactNonBlankStringSchema,
|
|
1749
|
-
binding: eventAutomationCredentialSubjectBindingSchema
|
|
1750
|
-
}).strict().refine((subject) => subject.binding.taskId === subject.taskId, {
|
|
1751
|
-
message: "Event automation credential subject requires task binding",
|
|
1752
|
-
path: ["binding"]
|
|
1753
|
-
}),
|
|
1754
|
-
z.object({
|
|
1755
|
-
type: z.literal("user"),
|
|
1756
|
-
userId: exactActorIdSchema,
|
|
1757
|
-
allowedWhen: z.literal("timer-watch"),
|
|
1758
|
-
binding: timerWatchCredentialSubjectBindingSchema
|
|
1759
|
-
}).strict()
|
|
1760
|
-
]);
|
|
1761
|
-
const credentialContextSchema = z.union([z.object({ actor: credentialUserActorSchema }).strict(), z.object({
|
|
1762
|
-
actor: credentialSystemActorSchema,
|
|
1763
|
-
subject: credentialSubjectSchema.optional()
|
|
1764
|
-
}).strict()]);
|
|
1765
|
-
/**
|
|
1766
|
-
* Build credential authority from the run actor.
|
|
1767
|
-
*
|
|
1768
|
-
* `actor` is the rich execution principal. This projects the credential stub
|
|
1769
|
-
* tools/auth need from it:
|
|
1770
|
-
* - user actor → `{ actor: { type: "user", userId } }`
|
|
1771
|
-
* - system actor → `{ actor: systemActor, subject? }`
|
|
1772
|
-
*
|
|
1773
|
-
* They only diverge when a system run carries an explicit delegated `subject`
|
|
1774
|
-
* (scheduled/event-automation creator credentials). Callers should set `actor` first,
|
|
1775
|
-
* then derive this — do not hand-build parallel shapes.
|
|
1776
|
-
*/
|
|
1777
|
-
function credentialContextForActor(actor, subject) {
|
|
1778
|
-
if (actor.platform === "system") return subject ? {
|
|
1779
|
-
actor,
|
|
1780
|
-
subject
|
|
1781
|
-
} : { actor };
|
|
1782
|
-
if (subject) throw new TypeError("Delegated credential subjects require a system actor");
|
|
1783
|
-
return { actor: {
|
|
1784
|
-
type: "user",
|
|
1785
|
-
userId: actor.userId
|
|
1786
|
-
} };
|
|
1771
|
+
function getOptionalRedisStateAdapter() {
|
|
1772
|
+
getStateAdapter();
|
|
1773
|
+
return redisStateAdapter;
|
|
1787
1774
|
}
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
* `userId` is the user actor, or the owner of delegated credentials when the
|
|
1792
|
-
* system acts for an Automation or Watch. `actorType` says who acted.
|
|
1793
|
-
*/
|
|
1794
|
-
function credentialLogContext(context) {
|
|
1795
|
-
if ("type" in context.actor) return {
|
|
1796
|
-
userId: context.actor.userId,
|
|
1797
|
-
actorType: "user",
|
|
1798
|
-
actorId: context.actor.userId
|
|
1799
|
-
};
|
|
1800
|
-
const subject = "subject" in context ? context.subject : void 0;
|
|
1775
|
+
async function getConnectedStateContext() {
|
|
1776
|
+
const adapter = getStateAdapter();
|
|
1777
|
+
await adapter.connect();
|
|
1801
1778
|
return {
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
...subject ? {
|
|
1805
|
-
userId: subject.userId,
|
|
1806
|
-
credentialAllowedWhen: subject.allowedWhen,
|
|
1807
|
-
..."taskId" in subject ? { taskId: subject.taskId } : void 0
|
|
1808
|
-
} : void 0
|
|
1779
|
+
redisStateAdapter: getOptionalRedisStateAdapter(),
|
|
1780
|
+
stateAdapter: adapter
|
|
1809
1781
|
};
|
|
1810
1782
|
}
|
|
1811
|
-
/**
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
*/
|
|
1817
|
-
function actorLogContext(actor, credentialContext) {
|
|
1818
|
-
const credential = credentialContext ? credentialLogContext(credentialContext) : {};
|
|
1819
|
-
if (!isUserActor(actor)) return credential;
|
|
1820
|
-
return {
|
|
1821
|
-
...credential,
|
|
1822
|
-
userId: actor.userId,
|
|
1823
|
-
userName: actor.userName,
|
|
1824
|
-
userEmail: actor.email,
|
|
1825
|
-
userFullName: actor.fullName
|
|
1826
|
-
};
|
|
1783
|
+
/** Return the Redis adapter only when the caller is using the default state adapter. */
|
|
1784
|
+
async function getDefaultRedisStateAdapterFor(adapter) {
|
|
1785
|
+
if (adapter !== stateAdapter) return;
|
|
1786
|
+
const context = await getConnectedStateContext();
|
|
1787
|
+
return context.stateAdapter === adapter ? context.redisStateAdapter : void 0;
|
|
1827
1788
|
}
|
|
1828
|
-
/**
|
|
1829
|
-
function
|
|
1830
|
-
|
|
1831
|
-
return
|
|
1789
|
+
/** The Redis key that the default Redis adapter uses for one state value key. */
|
|
1790
|
+
function redisStateKey(key) {
|
|
1791
|
+
const prefix = getChatConfig().state.keyPrefix;
|
|
1792
|
+
return `${REDIS_STATE_KEY_PREFIX}:cache:${prefix ? `${prefix}:` : ""}${key}`;
|
|
1793
|
+
}
|
|
1794
|
+
/** Read state values in one Redis round trip. Other adapters read each key. */
|
|
1795
|
+
async function getStateValues(state, keys) {
|
|
1796
|
+
if (keys.length === 0) return [];
|
|
1797
|
+
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
1798
|
+
if (!redis) return await mapBounded(keys, (key) => state.get(key));
|
|
1799
|
+
return (await redis.getClient().mGet(keys.map(redisStateKey))).map((value) => {
|
|
1800
|
+
if (value === null) return null;
|
|
1801
|
+
try {
|
|
1802
|
+
return JSON.parse(value);
|
|
1803
|
+
} catch {
|
|
1804
|
+
return value;
|
|
1805
|
+
}
|
|
1806
|
+
});
|
|
1807
|
+
}
|
|
1808
|
+
/** Write state values with one TTL in one Redis round trip. */
|
|
1809
|
+
async function setStateValues(state, entries, ttlMs) {
|
|
1810
|
+
if (entries.length === 0) return;
|
|
1811
|
+
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
1812
|
+
if (!redis) {
|
|
1813
|
+
await mapBounded(entries, ({ key, value }) => state.set(key, value, ttlMs));
|
|
1814
|
+
return;
|
|
1815
|
+
}
|
|
1816
|
+
const pipeline = redis.getClient().multi();
|
|
1817
|
+
for (const { key, value } of entries) pipeline.set(redisStateKey(key), JSON.stringify(value), { PX: ttlMs });
|
|
1818
|
+
await pipeline.execAsPipeline();
|
|
1819
|
+
}
|
|
1820
|
+
function getStateAdapter() {
|
|
1821
|
+
if (!stateAdapter) stateAdapter = createStateAdapter();
|
|
1822
|
+
return stateAdapter;
|
|
1823
|
+
}
|
|
1824
|
+
async function disconnectStateAdapter() {
|
|
1825
|
+
if (!stateAdapter) return;
|
|
1826
|
+
try {
|
|
1827
|
+
await stateAdapter.disconnect();
|
|
1828
|
+
} finally {
|
|
1829
|
+
stateAdapter = void 0;
|
|
1830
|
+
redisStateAdapter = void 0;
|
|
1831
|
+
}
|
|
1832
1832
|
}
|
|
1833
|
-
export { resolveGatewayModel as $, slackBotIdSchema as A, getSlackBotToken as B,
|
|
1833
|
+
export { resolveGatewayModel as $, slackBotIdSchema as A, getSlackBotToken as B, parseActorUserId as C, parseSlackChannelReferenceId as D, parseSlackChannelId as E, slackMessageTsFromMs as F, loadConfig as G, getSlackClientSecret as H, slackMessageTsSchema as I, normalizeSlackEmojiName as J, parseEnvList as K, botConfig as L, slackTeamIdSchema as M, slackUserIdSchema as N, parseSlackTeamId as O, parseSlackMessageTs as P, findGatewayModel as Q, getChatConfig as R, isUserActor as S, toStoredSlackActor as T, getSlackSigningSecret as U, getSlackClientId as V, installChatConfig as W, toPiReasoningLevel as X, TURN_REASONING_LEVELS as Y, GATEWAY_PROVIDER as Z, createActor as _, getStateValues as a, streamSimpleAnthropic as at, isActorUserId as b, acquireActiveLock as c, actorLogContext as d, calculateCost as et, credentialContextForActor as f, credentialUserSubjectId as g, credentialSubjectSchema as h, getStateAdapter as i, streamAnthropic as it, slackChannelIdSchema as j, parseSlackUserId as k, fenceLock as l, credentialLogContext as m, disconnectStateAdapter as n, getEnvApiKey as nt, setStateValues as o, credentialContextSchema as p, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as q, getDefaultRedisStateAdapterFor as r, registerApiProvider as rt, MUTATION_LOCK_TTL_MS as s, adapter_exports as t, completeSimple as tt, withLock as u, createSlackActor as v, parseStoredSlackActor as w, isSlackUserId as x, createSlackResumeActor as y, getRuntimeMetadata as z };
|