@sentry/junior 0.310.0 → 0.311.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-B1wujchl.js +259 -0
- package/dist/{adapter-context-BhKpjpGD.js → adapter-context-G2M0y6rP.js} +2 -2
- package/dist/{admin-tgZEZAk2.js → admin-DCiBhUT1.js} +1 -2
- package/dist/{agent-runner-D9cvNlQl.js → agent-runner-BVHPUIc8.js} +543 -1703
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -6
- package/dist/api.d.ts +21 -3
- package/dist/api.js +1479 -372
- package/dist/{app-B_7Wn0en.d.ts → app-Cw5Vy6H6.d.ts} +14 -3
- package/dist/app.d.ts +2 -2
- package/dist/app.js +232 -506
- package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
- package/dist/{briefs-DKxkoruh.js → briefs-BDjnug6Y.js} +3 -3
- package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-DMY3VV-D.js} +1 -1
- package/dist/cli/chat.js +16 -16
- package/dist/cli/check.js +23 -29
- package/dist/cli/init.js +1 -6
- package/dist/cli/main.js +3 -3
- package/dist/cli/plugins.js +8 -7
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-Dkt2Le2b.js → config-BrXDQefC.js} +239 -5
- package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-DNXSC9So.js} +6 -5
- package/dist/{conversation-M9KZ5JxF.js → conversation-ca__NDQW.js} +47 -8
- package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-DkinDu5o.js} +15 -6
- package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-DxttrKb9.js} +1 -1
- package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-DWw7Xhdr.js} +41 -38
- package/dist/{credential-sync-vGnrB0BY.js → credential-sync-Bk8wGb8Y.js} +15 -16
- package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
- package/dist/{db-CFZggNoy.js → db-DTxzH7u5.js} +1609 -1040
- package/dist/{executor-BPkZDx5-.js → executor-DqTiYj9S.js} +450 -99
- package/dist/{html-2r2KmLwi.js → html-B9Sl4Axb.js} +6 -6
- package/dist/{install-C-oE6C_u.js → install-Sg4ePfLl.js} +2 -2
- package/dist/instrumentation.js +3 -3
- package/dist/{lineage-CsvrEFQe.js → lineage-BHAMpNKr.js} +2 -2
- package/dist/{logging-D5gkyvnK.js → logging-FjclQsXu.js} +47 -9
- package/dist/{message-DwvJ-I3w.js → message-CJ7_RL50.js} +5 -8
- package/dist/{model-input-MAq2881y.js → model-input-CMLh4Cwq.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +3 -3
- package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-RVcbiDjL.js} +2 -2
- package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-Bu9kkaQu.js} +1 -1
- package/dist/{projection-jZSlEAXG.js → projection-Cns7XwWa.js} +9445 -5574
- package/dist/{prompt-CaMyeCpA.js → prompt-CDqcsDYC.js} +4 -4
- package/dist/{registry-BBkWFCl8.js → registry-BPwuOP2O.js} +5 -8
- package/dist/{resolve-B38MkHXE.js → resolve-BK29bBry.js} +3 -3
- package/dist/rule-DAxQY-1h.js +20 -0
- package/dist/{runner-11h8PrHh.js → runner-BcAE-cJm.js} +10 -10
- package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
- package/dist/{schedule-DWxZ3kja.js → schedule-BLJ476XQ.js} +209 -43
- package/dist/{schema-obw5jvR4.js → schema-BLgSZXcL.js} +255 -49
- package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
- package/dist/{service-account-Zc5bUcIJ.js → service-account-gN0zqf0S.js} +68 -68
- package/dist/{service-account-Bx93N1n1.js → service-account-iJoCtkHR.js} +3 -3
- package/dist/{skills-C8Npu5zO.js → skills-BoZ80epJ.js} +2 -2
- package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
- package/dist/{spawn-CXr58R0x.js → spawn-Dk92r7mX.js} +5 -6
- package/dist/{state-CGrGVeQC.js → state-DH3Cmgp3.js} +4 -4
- package/dist/{stop-DYzjRf2U.js → stop-CYsfc0Ed.js} +1063 -313
- package/dist/{store-D4FQ1Nml.js → store-DmmMIrQi.js} +5 -5
- package/dist/{task-queue-CaZffYaH.js → task-queue-C_zldF5J.js} +3 -3
- package/dist/{task-runner-Dm7BHbGp.js → task-runner-C7oCJQIx.js} +20 -13
- package/dist/{thread-context-Dyj1KWaY.js → thread-context-BW2BsQbH.js} +13 -11
- package/dist/{turn-session-routing-CD0BRCex.js → turn-session-routing-Xh_2nSQe.js} +52 -54
- package/dist/{validation-DxVNIxA0.js → validation-DrJd0nnq.js} +1 -1
- package/dist/{version-Cr7Z71yG.js → version-CNKZ8owc.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-C6LOZ2d2.js → warmup-BWdHew2H.js} +14287 -7195
- package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
- package/dist/{worker-CUBtu1Li.js → worker-t9qpu_Zx.js} +7 -8
- package/migrations/0126_artifact_drop_public.sql +8 -0
- package/migrations/0127_artifact_path.sql +4 -0
- package/migrations/0128_artifact_path_index.sql +1 -0
- package/migrations/0129_review_item_answered_index.sql +1 -0
- package/migrations/0130_review_item_status_index.sql +1 -0
- package/migrations/0131_brief_outcome_status.sql +1 -0
- package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
- package/migrations/0133_brief_created_at_index.sql +1 -0
- package/migrations/0134_slack_person_search_index.sql +1 -0
- package/migrations/0135_code_change_size.sql +3 -0
- package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
- package/migrations/0137_inbox_snoozes.sql +27 -0
- package/migrations/0138_code_change_search_index.sql +2 -0
- package/migrations/0139_review_item_owner.sql +22 -0
- package/migrations/0140_review_item_owner_index.sql +1 -0
- package/migrations/0141_memory_core_adoption.sql +89 -0
- package/migrations/0142_memory_core_indexes.sql +17 -0
- package/migrations/meta/0126_snapshot.json +5488 -0
- package/migrations/meta/0127_snapshot.json +5519 -0
- package/migrations/meta/0128_snapshot.json +5519 -0
- package/migrations/meta/0129_snapshot.json +5547 -0
- package/migrations/meta/0130_snapshot.json +5563 -0
- package/migrations/meta/0131_snapshot.json +5569 -0
- package/migrations/meta/0132_snapshot.json +5569 -0
- package/migrations/meta/0133_snapshot.json +5590 -0
- package/migrations/meta/0134_snapshot.json +5606 -0
- package/migrations/meta/0135_snapshot.json +5624 -0
- package/migrations/meta/0136_snapshot.json +5624 -0
- package/migrations/meta/0137_snapshot.json +5864 -0
- package/migrations/meta/0138_snapshot.json +5894 -0
- package/migrations/meta/0139_snapshot.json +5898 -0
- package/migrations/meta/0140_snapshot.json +5919 -0
- package/migrations/meta/0141_snapshot.json +6429 -0
- package/migrations/meta/0142_snapshot.json +6457 -0
- package/migrations/meta/_journal.json +120 -1
- package/package.json +6 -7
- package/dist/result-BaqSZcJb.js +0 -548
- package/dist/session-stop-BfY4rhJs.js +0 -4255
- package/dist/turn-user-message-9IxeEv5v.js +0 -364
- package/dist/users-CaUAYMb3.js +0 -181
- package/dist/viewer-AHldghAD.js +0 -212
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
|
|
2
|
-
import { i as getChatConfig } from "./config-
|
|
2
|
+
import { F as createCache, P as cacheKeyPrefix, i as getChatConfig } from "./config-BrXDQefC.js";
|
|
3
3
|
import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-BsBdxDXQ.js";
|
|
4
|
-
import { A as
|
|
4
|
+
import { A as juniorConversationMetrics, B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, M as juniorConversationEvents, O as juniorConversationBriefs, P as juniorConversationAnnotations, S as juniorConversationReadPositions, U as juniorIdentities, V as juniorMessageAttachments, _ as juniorAutomationRuns, f as juniorReviewItemAssignees, g as juniorAutomations, h as juniorReviewItems, j as isUserInstruction, k as CONVERSATION_METRICS, p as juniorReviewItemConversations, q as juniorDestinations, t as createJuniorSqlExecutor, w as juniorConversationBindings } from "./executor-DqTiYj9S.js";
|
|
5
5
|
import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-CYstOMKX.js";
|
|
6
|
-
import {
|
|
6
|
+
import { t as canExposeConversationPayload } from "./conversation-privacy-DxttrKb9.js";
|
|
7
7
|
import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
|
|
8
|
+
import { J as normalizeIdentityEmail, K as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-FjclQsXu.js";
|
|
9
|
+
import { i as getStateAdapter } from "./adapter-B1wujchl.js";
|
|
8
10
|
import * as z from "zod";
|
|
9
11
|
import { createHash, randomUUID } from "node:crypto";
|
|
10
|
-
import { destinationSchema, locationSchema, sourceSchema } from "@sentry/junior-plugin-api";
|
|
11
|
-
import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
|
|
12
|
+
import { PluginToolInputError, destinationSchema, identitySchema, locationSchema, sourceSchema, userSchema } from "@sentry/junior-plugin-api";
|
|
13
|
+
import { and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, or, sql } from "drizzle-orm";
|
|
12
14
|
import { alias } from "drizzle-orm/pg-core";
|
|
13
|
-
import { createMemoryState } from "@chat-adapter/state-memory";
|
|
14
|
-
import { createRedisState } from "@chat-adapter/state-redis";
|
|
15
|
-
import { setTimeout } from "node:timers/promises";
|
|
16
15
|
// src/chat/destination.ts
|
|
17
16
|
/** Build Junior's canonical destination from Slack workspace and channel ids. */
|
|
18
17
|
function createSlackDestination(input) {
|
|
@@ -223,1068 +222,1644 @@ function addAgentTurnUsage(...usages) {
|
|
|
223
222
|
};
|
|
224
223
|
return hasAgentTurnUsage(result) ? result : void 0;
|
|
225
224
|
}
|
|
226
|
-
// src/api/conversations/
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
225
|
+
// src/api/conversations/membership.ts
|
|
226
|
+
/**
|
|
227
|
+
* Select the person's participant row on the outer `juniorConversations`
|
|
228
|
+
* root, with an optional extra condition.
|
|
229
|
+
*/
|
|
230
|
+
function memberParticipantRow(member, condition) {
|
|
231
|
+
const rows = getDb().select({ rootConversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants);
|
|
232
|
+
const onRoot = eq(juniorConversationParticipants.rootConversationId, juniorConversations.conversationId);
|
|
233
|
+
return "userId" in member ? rows.where(and(onRoot, eq(juniorConversationParticipants.userId, member.userId), condition)) : rows.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(onRoot, eq(juniorUsers.primaryEmailNormalized, member.email), condition));
|
|
233
234
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
WHEN COALESCE(
|
|
238
|
-
${source.usage}->>'inputTokens',
|
|
239
|
-
${source.usage}->>'outputTokens',
|
|
240
|
-
${source.usage}->>'cachedInputTokens',
|
|
241
|
-
${source.usage}->>'cacheCreationTokens'
|
|
242
|
-
) IS NOT NULL
|
|
243
|
-
THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
|
|
244
|
-
+ COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
|
|
245
|
-
+ COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
|
|
246
|
-
+ COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
|
|
247
|
-
WHEN ${source.usage}->>'totalTokens' IS NOT NULL
|
|
248
|
-
THEN (${source.usage}->>'totalTokens')::double precision
|
|
249
|
-
ELSE NULL
|
|
250
|
-
END
|
|
251
|
-
`;
|
|
235
|
+
/** True when the viewer is a materialized participant on this root conversation. */
|
|
236
|
+
function conversationHasParticipantUser(userId) {
|
|
237
|
+
return exists(memberParticipantRow({ userId }));
|
|
252
238
|
}
|
|
253
|
-
|
|
254
|
-
|
|
239
|
+
/**
|
|
240
|
+
* True when the viewer may find the outer root conversation by a link to
|
|
241
|
+
* it: its Destination, joined as `juniorDestinations`, is public, or the
|
|
242
|
+
* viewer is a Participant.
|
|
243
|
+
*/
|
|
244
|
+
function rootVisibleToViewer(viewerUserId) {
|
|
245
|
+
return or(eq(juniorDestinations.visibility, "public"), viewerUserId ? conversationHasParticipantUser(viewerUserId) : void 0);
|
|
255
246
|
}
|
|
256
|
-
/**
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
${usage}->'cost'->>'cacheRead',
|
|
266
|
-
${usage}->'cost'->>'cacheWrite'
|
|
267
|
-
) IS NOT NULL
|
|
268
|
-
THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
|
|
269
|
-
+ COALESCE((${usage}->'cost'->>'output')::double precision, 0)
|
|
270
|
-
+ COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
|
|
271
|
-
+ COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
|
|
272
|
-
ELSE NULL
|
|
273
|
-
END
|
|
274
|
-
`;
|
|
247
|
+
/**
|
|
248
|
+
* True when the person is a Participant of the conversation. Feeds filter
|
|
249
|
+
* with this id set instead of a per-row membership check, so Postgres reads
|
|
250
|
+
* only that person's conversations, not every root.
|
|
251
|
+
*/
|
|
252
|
+
function conversationIsMemberRoot(member) {
|
|
253
|
+
const participating = getDb().select({ conversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants);
|
|
254
|
+
const memberRoots = "userId" in member ? participating.where(eq(juniorConversationParticipants.userId, member.userId)) : participating.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(eq(juniorUsers.primaryEmailNormalized, member.email));
|
|
255
|
+
return inArray(juniorConversations.conversationId, memberRoots);
|
|
275
256
|
}
|
|
276
|
-
/**
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
WHERE ${roots.executionStatus} NOT IN ('idle', 'failed')
|
|
284
|
-
)::integer`,
|
|
285
|
-
conversations: sql`${conversationCount}::integer`,
|
|
286
|
-
cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
|
|
287
|
-
cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
|
|
288
|
-
costUsd: sql`SUM(${costValue(metrics)})::double precision`,
|
|
289
|
-
durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
|
|
290
|
-
failed: sql`${conversationCount} FILTER (
|
|
291
|
-
WHERE ${roots.executionStatus} = 'failed' AND ${roots.stoppedAt} IS NULL
|
|
292
|
-
)::integer`,
|
|
293
|
-
inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
|
|
294
|
-
tokens: sql`SUM(${tokenValue(metrics)})::double precision`
|
|
295
|
-
};
|
|
257
|
+
/**
|
|
258
|
+
* True when the person has not unsubscribed from the conversation. The
|
|
259
|
+
* active feed uses it, so a conversation that someone else carries on
|
|
260
|
+
* leaves the feed of a person who left it.
|
|
261
|
+
*/
|
|
262
|
+
function conversationIsNotUnsubscribedRoot(member) {
|
|
263
|
+
return not(exists(memberParticipantRow(member, isNotNull(juniorConversationParticipants.unsubscribedAt))));
|
|
296
264
|
}
|
|
297
|
-
/**
|
|
298
|
-
|
|
265
|
+
/**
|
|
266
|
+
* Read the roots among a bounded set where one person is a Participant, each
|
|
267
|
+
* with their pin marks. An unpinned root maps to empty marks.
|
|
268
|
+
*/
|
|
269
|
+
async function readMemberParticipants(db, conversationIds, member) {
|
|
270
|
+
if (!member || conversationIds.length === 0) return /* @__PURE__ */ new Map();
|
|
271
|
+
const listed = inArray(juniorConversationParticipants.rootConversationId, [...conversationIds]);
|
|
272
|
+
const query = db.select({
|
|
273
|
+
pinnedAt: juniorConversationParticipants.pinnedAt,
|
|
274
|
+
pinPosition: juniorConversationParticipants.pinPosition,
|
|
275
|
+
rootConversationId: juniorConversationParticipants.rootConversationId
|
|
276
|
+
}).from(juniorConversationParticipants);
|
|
277
|
+
const rows = "userId" in member ? await query.where(and(eq(juniorConversationParticipants.userId, member.userId), listed)) : await query.innerJoin(juniorUsers, eq(juniorUsers.id, juniorConversationParticipants.userId)).where(and(eq(juniorUsers.primaryEmailNormalized, member.email), listed));
|
|
278
|
+
return new Map(rows.map((row) => [row.rootConversationId, viewerMarksFromParticipant(row) ?? {}]));
|
|
279
|
+
}
|
|
280
|
+
/** Project one participant row into marks, or undefined when it has none. */
|
|
281
|
+
function viewerMarksFromParticipant(row) {
|
|
282
|
+
if (!row.pinnedAt) return void 0;
|
|
299
283
|
return {
|
|
300
|
-
|
|
301
|
-
|
|
284
|
+
pinnedAtMs: row.pinnedAt.getTime(),
|
|
285
|
+
...row.pinPosition !== null ? { pinPosition: row.pinPosition } : void 0
|
|
302
286
|
};
|
|
303
287
|
}
|
|
304
|
-
|
|
288
|
+
/** True when one user pinned this root. Feeds sort these rows first. */
|
|
289
|
+
function conversationPinnedForUser(userId) {
|
|
290
|
+
return exists(memberParticipantRow({ userId }, isNotNull(juniorConversationParticipants.pinnedAt)));
|
|
291
|
+
}
|
|
292
|
+
/** Find which of the supplied roots include the linked viewer as a participant. */
|
|
293
|
+
async function conversationIdsWithParticipantUser(db, conversationIds, userId) {
|
|
294
|
+
if (conversationIds.length === 0) return /* @__PURE__ */ new Set();
|
|
295
|
+
const rows = await db.select({ rootConversationId: juniorConversationParticipants.rootConversationId }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.userId, userId), inArray(juniorConversationParticipants.rootConversationId, [...conversationIds])));
|
|
296
|
+
return new Set(rows.map((row) => row.rootConversationId));
|
|
297
|
+
}
|
|
298
|
+
// src/api/conversations/access.ts
|
|
299
|
+
const rootConversation = alias(juniorConversations, "access_root_conversation");
|
|
300
|
+
const rootDestination = alias(juniorDestinations, "access_root_destination");
|
|
301
|
+
/** Resolve viewer access for a bounded set of persisted conversations. */
|
|
302
|
+
async function readConversationAccessFromSql(db, conversationIds, viewer) {
|
|
303
|
+
const rows = await readConversationAccessRows(db, conversationIds);
|
|
304
|
+
const membershipConversationIds = /* @__PURE__ */ new Set();
|
|
305
|
+
for (const row of rows) {
|
|
306
|
+
membershipConversationIds.add(row.conversationId);
|
|
307
|
+
if (row.storedRootConversationId) membershipConversationIds.add(row.storedRootConversationId);
|
|
308
|
+
}
|
|
309
|
+
return conversationAccessFromRows(rows, viewer !== void 0 ? await conversationIdsWithParticipantUser(db, [...membershipConversationIds], viewer.id) : /* @__PURE__ */ new Set());
|
|
310
|
+
}
|
|
305
311
|
/**
|
|
306
|
-
*
|
|
307
|
-
*
|
|
308
|
-
*
|
|
309
|
-
* convert to USD once where the API returns it. `pnpm money-units:check`
|
|
310
|
-
* keeps money scales in this file.
|
|
312
|
+
* Read the stored tree and root Destination of each conversation. A caller
|
|
313
|
+
* that reads the viewer's participant rows itself passes these rows to
|
|
314
|
+
* `conversationAccessFromRows`.
|
|
311
315
|
*/
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
function microUsdToUsdSql(microUsd) {
|
|
327
|
-
return sql`(${microUsd}) / 1000000.0::double precision`;
|
|
316
|
+
async function readConversationAccessRows(db, conversationIds) {
|
|
317
|
+
if (conversationIds.length === 0) return [];
|
|
318
|
+
return await db.select({
|
|
319
|
+
conversationId: juniorConversations.conversationId,
|
|
320
|
+
parentConversationId: juniorConversations.parentConversationId,
|
|
321
|
+
storedRootConversationId: juniorConversations.rootConversationId,
|
|
322
|
+
rootConversationId: rootConversation.conversationId,
|
|
323
|
+
rootParentConversationId: rootConversation.parentConversationId,
|
|
324
|
+
rootRootConversationId: rootConversation.rootConversationId,
|
|
325
|
+
destinationId: rootDestination.id,
|
|
326
|
+
visibility: rootDestination.visibility,
|
|
327
|
+
provider: rootDestination.provider,
|
|
328
|
+
providerTenantId: rootDestination.providerTenantId
|
|
329
|
+
}).from(juniorConversations).leftJoin(rootConversation, eq(rootConversation.conversationId, juniorConversations.rootConversationId)).leftJoin(rootDestination, eq(rootDestination.id, rootConversation.destinationId)).where(inArray(juniorConversations.conversationId, [...conversationIds]));
|
|
328
330
|
}
|
|
329
331
|
/**
|
|
330
|
-
*
|
|
331
|
-
*
|
|
332
|
+
* Resolve access from `readConversationAccessRows`. `participantRootIds`
|
|
333
|
+
* holds the viewer's participant roots among the conversations and their
|
|
334
|
+
* stored roots, and is empty without a viewer.
|
|
332
335
|
*/
|
|
333
|
-
function
|
|
334
|
-
return
|
|
336
|
+
function conversationAccessFromRows(rows, participantRootIds) {
|
|
337
|
+
return new Map(rows.map((row) => {
|
|
338
|
+
const validRootConversationId = row.rootConversationId !== null && row.rootConversationId === row.storedRootConversationId && row.rootRootConversationId === row.rootConversationId && row.rootParentConversationId === null && (row.parentConversationId !== null || row.storedRootConversationId === row.conversationId) ? row.rootConversationId ?? void 0 : void 0;
|
|
339
|
+
const visibility = validRootConversationId === void 0 ? null : row.visibility;
|
|
340
|
+
const isParticipant = row.parentConversationId === null && participantRootIds.has(row.conversationId) || validRootConversationId !== void 0 && participantRootIds.has(validRootConversationId);
|
|
341
|
+
const canViewPrivateContent = isParticipant || validRootConversationId !== void 0 && canExposeConversationPayload({ visibility: visibility ?? void 0 });
|
|
342
|
+
return [row.conversationId, {
|
|
343
|
+
canViewPrivateContent,
|
|
344
|
+
...validRootConversationId !== void 0 && row.destinationId ? { destinationId: row.destinationId } : void 0,
|
|
345
|
+
isParticipant,
|
|
346
|
+
...validRootConversationId !== void 0 ? { rootConversationId: validRootConversationId } : void 0,
|
|
347
|
+
visibility,
|
|
348
|
+
...validRootConversationId !== void 0 && row.provider !== null && row.providerTenantId ? { tenant: {
|
|
349
|
+
provider: row.provider,
|
|
350
|
+
providerTenantId: row.providerTenantId
|
|
351
|
+
} } : void 0
|
|
352
|
+
}];
|
|
353
|
+
}));
|
|
335
354
|
}
|
|
336
|
-
// src/chat/automations/run-cost.ts
|
|
337
355
|
/**
|
|
338
|
-
*
|
|
339
|
-
*
|
|
356
|
+
* Whether the viewer may add a Message to a Conversation. A signed-in person
|
|
357
|
+
* joins a public Conversation by posting in it, the same as a public Slack
|
|
358
|
+
* thread: their first Turn adds their Participant row. A private one takes
|
|
359
|
+
* Messages only from its Participants.
|
|
340
360
|
*/
|
|
341
|
-
function
|
|
342
|
-
return
|
|
361
|
+
function canAddConversationMessages(access) {
|
|
362
|
+
return Boolean(access?.isParticipant || access?.visibility === "public");
|
|
343
363
|
}
|
|
344
364
|
/**
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
* the Conversation can record usage before its run row exists.
|
|
365
|
+
* The Slack workspace of a Conversation that the viewer can read. A mention
|
|
366
|
+
* in it must name a Slack user of that workspace.
|
|
348
367
|
*/
|
|
349
|
-
function
|
|
350
|
-
return
|
|
351
|
-
}
|
|
352
|
-
// src/chat/conversations/metrics.ts
|
|
353
|
-
function finite(value) {
|
|
354
|
-
return value !== void 0 && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
368
|
+
function readableSlackTeamId(access) {
|
|
369
|
+
return access?.canViewPrivateContent && access.tenant?.provider === "slack" ? access.tenant.providerTenantId : void 0;
|
|
355
370
|
}
|
|
356
|
-
/**
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
371
|
+
/**
|
|
372
|
+
* Read access for one request. Each id is read at most once, so the parts of
|
|
373
|
+
* one response that need the same Conversation share a query.
|
|
374
|
+
*/
|
|
375
|
+
function createConversationAccessReader(db, viewer) {
|
|
376
|
+
const byId = /* @__PURE__ */ new Map();
|
|
377
|
+
return async (conversationIds) => {
|
|
378
|
+
const missing = [...new Set(conversationIds)].filter((id) => !byId.has(id));
|
|
379
|
+
if (missing.length > 0) {
|
|
380
|
+
const read = readConversationAccessFromSql(db, missing, viewer);
|
|
381
|
+
for (const id of missing) byId.set(id, read.then((access) => access.get(id)));
|
|
382
|
+
}
|
|
383
|
+
const entries = await Promise.all(conversationIds.map(async (id) => [id, await byId.get(id)]));
|
|
384
|
+
return new Map(entries.flatMap(([id, access]) => access ? [[id, access]] : []));
|
|
369
385
|
};
|
|
370
386
|
}
|
|
371
387
|
/**
|
|
372
|
-
*
|
|
388
|
+
* Apply `policies/conversation-access.md`: whether work in the `requester`
|
|
389
|
+
* Conversation may read or find the data of the `target` Conversation. The
|
|
390
|
+
* person of the Turn does not change the result. A public Conversation is
|
|
391
|
+
* reachable from any Conversation, on any surface and in any provider tenant.
|
|
392
|
+
* A private Conversation is reachable only from its own tree and from
|
|
393
|
+
* Conversations at the same Destination, which have the same audience.
|
|
394
|
+
*/
|
|
395
|
+
function canAccessConversation(args) {
|
|
396
|
+
const { requester, target } = args;
|
|
397
|
+
if (requester.rootConversationId !== void 0 && requester.rootConversationId === target.rootConversationId) return true;
|
|
398
|
+
if (requester.destinationId !== void 0 && requester.destinationId === target.destinationId) return true;
|
|
399
|
+
return target.visibility === "public";
|
|
400
|
+
}
|
|
401
|
+
// src/chat/tools/execution/tool-input-error.ts
|
|
402
|
+
/** Thrown when a tool fails due to invalid model/user input, not a system error. */
|
|
403
|
+
var ToolInputError = class extends Error {
|
|
404
|
+
constructor(message, options) {
|
|
405
|
+
super(message, options);
|
|
406
|
+
this.name = "ToolInputError";
|
|
407
|
+
}
|
|
408
|
+
};
|
|
409
|
+
/** Whether an error is an expected tool input failure that is not a Sentry exception. */
|
|
410
|
+
function isToolInputError(error) {
|
|
411
|
+
return error instanceof ToolInputError || error instanceof PluginToolInputError || error instanceof Error && error.name === "PluginToolInputError";
|
|
412
|
+
}
|
|
413
|
+
// src/chat/identities/user-cache.ts
|
|
414
|
+
/**
|
|
415
|
+
* Cache of each User and their user Identities. Every signed-in request
|
|
416
|
+
* resolves its viewer, and person cards read the people that a message
|
|
417
|
+
* links to, so these reads go to the state cache instead of the database.
|
|
373
418
|
*
|
|
374
|
-
*
|
|
419
|
+
* Every write to a cached column or to a user Identity must call
|
|
420
|
+
* `clearCachedUser`. The other columns of a User, such as the timezone or
|
|
421
|
+
* the customization, are not in the cache.
|
|
375
422
|
*/
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
423
|
+
const USER_TTL_MS = 864e5;
|
|
424
|
+
const MISSING_TTL_MS = 6e4;
|
|
425
|
+
const SETTLE_MS = 1e4;
|
|
426
|
+
/** The cache namespace of every key in this cache. */
|
|
427
|
+
const USER_CACHE_NAMESPACE = "identities";
|
|
428
|
+
const cachedUserSchema = z.object({
|
|
429
|
+
identities: z.array(z.object({
|
|
430
|
+
avatarUrl: z.string().nullable(),
|
|
431
|
+
displayName: z.string().nullable(),
|
|
432
|
+
handle: z.string().nullable(),
|
|
433
|
+
id: z.string(),
|
|
434
|
+
provider: z.string(),
|
|
435
|
+
providerSubjectId: z.string(),
|
|
436
|
+
providerTenantId: z.string(),
|
|
437
|
+
updatedAt: z.coerce.date()
|
|
438
|
+
})),
|
|
439
|
+
user: z.object({
|
|
440
|
+
displayName: z.string().nullable(),
|
|
441
|
+
id: z.string(),
|
|
442
|
+
isAdmin: z.boolean(),
|
|
443
|
+
primaryEmail: z.string()
|
|
444
|
+
})
|
|
445
|
+
});
|
|
446
|
+
const versionSchema = z.object({
|
|
447
|
+
token: z.string(),
|
|
448
|
+
writtenAtMs: z.number()
|
|
449
|
+
});
|
|
450
|
+
function versionKey(userId) {
|
|
451
|
+
return `${cacheKeyPrefix(USER_CACHE_NAMESPACE)}version:${userId}`;
|
|
452
|
+
}
|
|
453
|
+
function cache() {
|
|
454
|
+
return createCache(getStateAdapter(), USER_CACHE_NAMESPACE);
|
|
455
|
+
}
|
|
456
|
+
async function readVersion(userId) {
|
|
457
|
+
const state = getStateAdapter();
|
|
458
|
+
const stored = versionSchema.safeParse(await state.get(versionKey(userId)));
|
|
459
|
+
if (stored.success) return stored.data;
|
|
460
|
+
const created = {
|
|
461
|
+
token: randomUUID(),
|
|
462
|
+
writtenAtMs: 0
|
|
389
463
|
};
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
464
|
+
if (await state.setIfNotExists(versionKey(userId), created, 2 * USER_TTL_MS)) return created;
|
|
465
|
+
return versionSchema.parse(await state.get(versionKey(userId)));
|
|
466
|
+
}
|
|
467
|
+
async function loadUser(db, userId) {
|
|
468
|
+
const rows = await db.select({
|
|
469
|
+
avatarUrl: juniorIdentities.avatarUrl,
|
|
470
|
+
displayName: juniorIdentities.displayName,
|
|
471
|
+
handle: juniorIdentities.handle,
|
|
472
|
+
identityId: juniorIdentities.id,
|
|
473
|
+
provider: juniorIdentities.provider,
|
|
474
|
+
providerSubjectId: juniorIdentities.providerSubjectId,
|
|
475
|
+
providerTenantId: juniorIdentities.providerTenantId,
|
|
476
|
+
updatedAt: juniorIdentities.updatedAt,
|
|
477
|
+
userDisplayName: juniorUsers.displayName,
|
|
478
|
+
userId: juniorUsers.id,
|
|
479
|
+
userIsAdmin: juniorUsers.isAdmin,
|
|
480
|
+
userPrimaryEmail: juniorUsers.primaryEmail
|
|
481
|
+
}).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.id, userId)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
|
|
482
|
+
const first = rows[0];
|
|
483
|
+
if (!first) return null;
|
|
398
484
|
return {
|
|
399
|
-
|
|
400
|
-
|
|
485
|
+
identities: rows.flatMap((row) => row.identityId && row.provider && row.providerSubjectId && row.providerTenantId !== null && row.updatedAt ? [{
|
|
486
|
+
avatarUrl: row.avatarUrl,
|
|
487
|
+
displayName: row.displayName,
|
|
488
|
+
handle: row.handle,
|
|
489
|
+
id: row.identityId,
|
|
490
|
+
provider: row.provider,
|
|
491
|
+
providerSubjectId: row.providerSubjectId,
|
|
492
|
+
providerTenantId: row.providerTenantId,
|
|
493
|
+
updatedAt: row.updatedAt
|
|
494
|
+
}] : []),
|
|
495
|
+
user: {
|
|
496
|
+
displayName: first.userDisplayName,
|
|
497
|
+
id: first.userId,
|
|
498
|
+
isAdmin: first.userIsAdmin,
|
|
499
|
+
primaryEmail: first.userPrimaryEmail
|
|
500
|
+
}
|
|
401
501
|
};
|
|
402
502
|
}
|
|
403
|
-
/**
|
|
404
|
-
async function
|
|
405
|
-
const
|
|
406
|
-
|
|
407
|
-
await
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
503
|
+
/** Read one User and their user Identities by User id. */
|
|
504
|
+
async function readCachedUser(db, userId) {
|
|
505
|
+
const version = await readVersion(userId);
|
|
506
|
+
const settled = Date.now() - version.writtenAtMs >= SETTLE_MS;
|
|
507
|
+
const cached = await cache().getOrLoad(`user:${userId}:${version.token}`, async () => {
|
|
508
|
+
const value = await loadUser(db, userId);
|
|
509
|
+
if (!settled) return { value };
|
|
510
|
+
return {
|
|
511
|
+
value,
|
|
512
|
+
ttlMs: value ? USER_TTL_MS : MISSING_TTL_MS
|
|
513
|
+
};
|
|
514
|
+
});
|
|
515
|
+
return cached ? cachedUserSchema.parse(cached) : void 0;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Read one User and their user Identities by normalized primary email. A
|
|
519
|
+
* primary email never changes, so the email to User id entry stays valid.
|
|
520
|
+
* A missing User is not cached: a first sign-in can create it at any time.
|
|
521
|
+
*/
|
|
522
|
+
async function readCachedUserByEmail(db, normalizedEmail) {
|
|
523
|
+
const userId = await cache().getOrLoad(emailKey(normalizedEmail), async () => {
|
|
524
|
+
const id = (await db.select({ id: juniorUsers.id }).from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0]?.id ?? null;
|
|
525
|
+
return id ? {
|
|
526
|
+
value: id,
|
|
527
|
+
ttlMs: USER_TTL_MS
|
|
528
|
+
} : { value: null };
|
|
529
|
+
});
|
|
530
|
+
return userId ? await readCachedUser(db, userId) : void 0;
|
|
531
|
+
}
|
|
532
|
+
function emailKey(normalizedEmail) {
|
|
533
|
+
return `email:${normalizedEmail}`;
|
|
534
|
+
}
|
|
535
|
+
/** Clear the cached User after a write to their row or user Identities. */
|
|
536
|
+
async function clearCachedUser(userId) {
|
|
537
|
+
await getStateAdapter().set(versionKey(userId), {
|
|
538
|
+
token: randomUUID(),
|
|
539
|
+
writtenAtMs: Date.now()
|
|
540
|
+
}, 2 * USER_TTL_MS);
|
|
541
|
+
}
|
|
542
|
+
// src/chat/identities/sql.ts
|
|
543
|
+
function dateFromMs$1(ms) {
|
|
544
|
+
return new Date(ms);
|
|
545
|
+
}
|
|
546
|
+
function tenantId$1(value) {
|
|
547
|
+
return value ?? "";
|
|
548
|
+
}
|
|
549
|
+
async function upsertUser(executor, args) {
|
|
550
|
+
const id = (await executor.db().insert(juniorUsers).values({
|
|
551
|
+
id: randomUUID(),
|
|
552
|
+
primaryEmail: args.email,
|
|
553
|
+
primaryEmailNormalized: args.emailNormalized,
|
|
554
|
+
displayName: args.displayName ?? null,
|
|
555
|
+
createdAt: dateFromMs$1(args.nowMs),
|
|
556
|
+
updatedAt: dateFromMs$1(args.nowMs)
|
|
557
|
+
}).onConflictDoUpdate({
|
|
558
|
+
target: juniorUsers.primaryEmailNormalized,
|
|
559
|
+
set: {
|
|
560
|
+
displayName: sql`coalesce(${juniorUsers.displayName}, excluded.display_name)`,
|
|
561
|
+
updatedAt: sql`excluded.updated_at`
|
|
562
|
+
}
|
|
563
|
+
}).returning({ id: juniorUsers.id }))[0]?.id;
|
|
564
|
+
if (!id) throw new Error("User identity upsert returned no row");
|
|
565
|
+
return id;
|
|
566
|
+
}
|
|
567
|
+
async function existingIdentity(executor, identity) {
|
|
568
|
+
return (await executor.db().select().from(juniorIdentities).where(and(eq(juniorIdentities.provider, identity.provider), eq(juniorIdentities.providerTenantId, tenantId$1(identity.providerTenantId)), eq(juniorIdentities.providerSubjectId, identity.providerSubjectId))))[0];
|
|
569
|
+
}
|
|
570
|
+
async function upsertIdentityRecord(executor, identity, linkedUserId, nowMs) {
|
|
571
|
+
const emailNormalized = normalizeIdentityEmail(identity.email);
|
|
572
|
+
const email = emailNormalized ? identity.email?.trim() || emailNormalized : void 0;
|
|
573
|
+
const existing = await existingIdentity(executor, identity);
|
|
574
|
+
const userEmailNormalized = existing?.emailVerified && existing.emailNormalized ? existing.emailNormalized : identity.emailVerified ? emailNormalized : void 0;
|
|
575
|
+
const userEmail = existing?.emailVerified && existing.email ? existing.email : email ?? userEmailNormalized;
|
|
576
|
+
const verifiedUserId = identity.kind === "user" && userEmailNormalized ? await upsertUser(executor, {
|
|
577
|
+
email: userEmail ?? userEmailNormalized,
|
|
578
|
+
emailNormalized: userEmailNormalized,
|
|
579
|
+
nowMs,
|
|
580
|
+
...existing?.displayName || identity.displayName ? { displayName: existing?.displayName ?? identity.displayName } : void 0
|
|
581
|
+
}) : void 0;
|
|
582
|
+
if (existing?.userId && verifiedUserId && existing.userId !== verifiedUserId) throw new Error("Identity verified email conflicts with linked user");
|
|
583
|
+
if (linkedUserId && verifiedUserId && linkedUserId !== verifiedUserId) throw new Error("Linked identity conflicts with verified email user");
|
|
584
|
+
if (existing?.userId && linkedUserId && existing.userId !== linkedUserId) throw new Error("Identity conflicts with linked user");
|
|
585
|
+
const userId = existing?.userId ?? linkedUserId ?? verifiedUserId;
|
|
586
|
+
const row = (await executor.db().insert(juniorIdentities).values({
|
|
587
|
+
id: randomUUID(),
|
|
588
|
+
userId: userId ?? null,
|
|
589
|
+
kind: identity.kind,
|
|
590
|
+
provider: identity.provider,
|
|
591
|
+
providerTenantId: tenantId$1(identity.providerTenantId),
|
|
592
|
+
providerSubjectId: identity.providerSubjectId,
|
|
593
|
+
displayName: identity.displayName ?? null,
|
|
594
|
+
handle: identity.handle ?? null,
|
|
595
|
+
email: email ?? null,
|
|
596
|
+
emailNormalized: emailNormalized ?? null,
|
|
597
|
+
emailVerified: Boolean(identity.emailVerified && emailNormalized),
|
|
598
|
+
avatarUrl: identity.avatarUrl ?? null,
|
|
599
|
+
metadata: identity.metadata ?? null,
|
|
600
|
+
createdAt: dateFromMs$1(nowMs),
|
|
601
|
+
updatedAt: dateFromMs$1(nowMs)
|
|
602
|
+
}).onConflictDoUpdate({
|
|
603
|
+
target: [
|
|
604
|
+
juniorIdentities.provider,
|
|
605
|
+
juniorIdentities.providerTenantId,
|
|
606
|
+
juniorIdentities.providerSubjectId
|
|
607
|
+
],
|
|
608
|
+
set: {
|
|
609
|
+
kind: sql`excluded.kind`,
|
|
610
|
+
userId: sql`coalesce(${juniorIdentities.userId}, excluded.user_id)`,
|
|
611
|
+
displayName: linkedUserId ? sql`coalesce(excluded.display_name, ${juniorIdentities.displayName})` : sql`coalesce(${juniorIdentities.displayName}, excluded.display_name)`,
|
|
612
|
+
handle: linkedUserId ? sql`coalesce(excluded.handle, ${juniorIdentities.handle})` : sql`coalesce(${juniorIdentities.handle}, excluded.handle)`,
|
|
613
|
+
email: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.email}, excluded.email) when excluded.email_verified then excluded.email else coalesce(${juniorIdentities.email}, excluded.email) end`,
|
|
614
|
+
emailNormalized: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) when excluded.email_verified then excluded.email_normalized else coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) end`,
|
|
615
|
+
emailVerified: sql`${juniorIdentities.emailVerified} OR excluded.email_verified`,
|
|
616
|
+
avatarUrl: identity.avatarUrl === void 0 ? sql`${juniorIdentities.avatarUrl}` : sql`excluded.avatar_url`,
|
|
617
|
+
metadata: sql`coalesce(${juniorIdentities.metadata}, excluded.metadata_json)`,
|
|
618
|
+
updatedAt: sql`excluded.updated_at`
|
|
619
|
+
},
|
|
620
|
+
...linkedUserId ? { setWhere: sql`${juniorIdentities.userId} IS NULL OR ${juniorIdentities.userId} = excluded.user_id` } : void 0
|
|
621
|
+
}).returning({
|
|
622
|
+
id: juniorIdentities.id,
|
|
623
|
+
userId: juniorIdentities.userId
|
|
624
|
+
}))[0];
|
|
625
|
+
if (!row) {
|
|
626
|
+
if (linkedUserId) throw new Error("Identity conflicts with linked user");
|
|
627
|
+
throw new Error("Identity upsert returned no row");
|
|
628
|
+
}
|
|
629
|
+
const previousUserId = existing?.userId;
|
|
630
|
+
await Promise.all([row.userId ? clearCachedUser(row.userId) : void 0, previousUserId && previousUserId !== row.userId ? clearCachedUser(previousUserId) : void 0]);
|
|
631
|
+
if (!existing?.userId && row.userId && identity.kind === "user") await recordStartedConversationParticipants(executor, {
|
|
632
|
+
identityId: row.id,
|
|
633
|
+
userId: row.userId
|
|
634
|
+
});
|
|
635
|
+
return {
|
|
636
|
+
id: row.id,
|
|
637
|
+
...row.userId ? { userId: row.userId } : void 0
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
/** Read the saved timezone for one user. */
|
|
641
|
+
async function readUserTimezone(db, userId) {
|
|
642
|
+
return (await db.select({ timezone: juniorUsers.timezone }).from(juniorUsers).where(eq(juniorUsers.id, userId)).limit(1))[0]?.timezone ?? void 0;
|
|
643
|
+
}
|
|
644
|
+
/** Save the IANA timezone for one user. */
|
|
645
|
+
async function saveUserTimezone(db, userId, timezone, nowMs) {
|
|
646
|
+
await db.update(juniorUsers).set({
|
|
647
|
+
timezone,
|
|
648
|
+
updatedAt: dateFromMs$1(nowMs)
|
|
649
|
+
}).where(and(eq(juniorUsers.id, userId), sql`${juniorUsers.timezone} is distinct from ${timezone}`));
|
|
650
|
+
}
|
|
651
|
+
/** Return the Slack user most recently linked to a Junior user. */
|
|
652
|
+
async function linkedSlackUser(db, userId) {
|
|
653
|
+
const row = (await db.select({
|
|
654
|
+
teamId: juniorIdentities.providerTenantId,
|
|
655
|
+
slackUserId: juniorIdentities.providerSubjectId
|
|
656
|
+
}).from(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"))).orderBy(desc(juniorIdentities.updatedAt)).limit(1))[0];
|
|
657
|
+
return row?.teamId ? {
|
|
658
|
+
teamId: row.teamId,
|
|
659
|
+
userId: row.slackUserId
|
|
660
|
+
} : void 0;
|
|
661
|
+
}
|
|
662
|
+
/** Persist one provider identity observation and link verified emails to users. */
|
|
663
|
+
async function upsertIdentity(executor, identity, nowMs = Date.now()) {
|
|
664
|
+
return await upsertIdentityRecord(executor, identity, void 0, nowMs);
|
|
665
|
+
}
|
|
666
|
+
/**
|
|
667
|
+
* Persist one provider identity after a trusted account-linking flow.
|
|
668
|
+
* Callers must use provider-verified account data, such as GitHub's authenticated
|
|
669
|
+
* user response, never identity claims inferred from content such as Git commits.
|
|
670
|
+
*/
|
|
671
|
+
async function upsertLinkedIdentity(executor, userId, identity, nowMs = Date.now()) {
|
|
672
|
+
return await upsertIdentityRecord(executor, identity, userId, nowMs);
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* Find the one user whose primary email is in a provider-verified email list.
|
|
676
|
+
* Return undefined when no user or more than one user matches.
|
|
677
|
+
*/
|
|
678
|
+
async function findUserByVerifiedEmails(executor, emails) {
|
|
679
|
+
const normalized = new Set(emails.map((email) => normalizeIdentityEmail(email) ?? ""));
|
|
680
|
+
normalized.delete("");
|
|
681
|
+
if (normalized.size === 0) return void 0;
|
|
682
|
+
const rows = await executor.db().select({
|
|
683
|
+
email: juniorUsers.primaryEmail,
|
|
684
|
+
userId: juniorUsers.id
|
|
685
|
+
}).from(juniorUsers).where(inArray(juniorUsers.primaryEmailNormalized, Array.from(normalized))).limit(2);
|
|
686
|
+
return rows.length === 1 ? rows[0] : void 0;
|
|
687
|
+
}
|
|
688
|
+
const linkedSlackIdentity = alias(juniorIdentities, "linked_slack_identity");
|
|
689
|
+
const linkedSlackUserColumns = {
|
|
690
|
+
displayName: juniorUsers.displayName,
|
|
691
|
+
email: juniorUsers.primaryEmail,
|
|
692
|
+
slackUserId: linkedSlackIdentity.providerSubjectId,
|
|
693
|
+
userId: juniorUsers.id
|
|
694
|
+
};
|
|
695
|
+
function singleLinkedSlackUser(rows) {
|
|
696
|
+
const [row] = rows;
|
|
697
|
+
if (rows.length !== 1 || !row) return void 0;
|
|
698
|
+
return {
|
|
699
|
+
slackUserId: row.slackUserId,
|
|
700
|
+
user: {
|
|
701
|
+
id: row.userId,
|
|
702
|
+
email: row.email,
|
|
703
|
+
...row.displayName ? { displayName: row.displayName } : void 0
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
/**
|
|
708
|
+
* Find the one Slack user in a workspace who is linked to an exact provider
|
|
709
|
+
* Identity, and the User behind both.
|
|
710
|
+
*
|
|
711
|
+
* Only the provider account id from an account-linking flow matches. Handles,
|
|
712
|
+
* emails, and display names never match. Return undefined when no Slack user
|
|
713
|
+
* or more than one Slack user matches.
|
|
714
|
+
*/
|
|
715
|
+
async function findLinkedSlackUser(executor, args) {
|
|
716
|
+
return singleLinkedSlackUser(await executor.db().select(linkedSlackUserColumns).from(juniorIdentities).innerJoin(linkedSlackIdentity, and(eq(linkedSlackIdentity.userId, juniorIdentities.userId), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, args.slackTeamId))).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, args.provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, args.providerSubjectId))).limit(2));
|
|
717
|
+
}
|
|
718
|
+
/**
|
|
719
|
+
* Find the one Slack user in a workspace whose User has this primary email.
|
|
720
|
+
*
|
|
721
|
+
* The caller must have verified that the person sent from this address.
|
|
722
|
+
* Return undefined when no Slack user or more than one Slack user matches.
|
|
723
|
+
*/
|
|
724
|
+
async function findSlackUserByPrimaryEmail(executor, args) {
|
|
725
|
+
return singleLinkedSlackUser(await executor.db().select(linkedSlackUserColumns).from(juniorUsers).innerJoin(linkedSlackIdentity, eq(linkedSlackIdentity.userId, juniorUsers.id)).where(and(eq(juniorUsers.primaryEmailNormalized, args.normalizedEmail), eq(linkedSlackIdentity.kind, "user"), eq(linkedSlackIdentity.provider, "slack"), eq(linkedSlackIdentity.providerTenantId, args.slackTeamId))).limit(2));
|
|
726
|
+
}
|
|
727
|
+
/** Remove one exact provider identity owned by a workspace Slack user. */
|
|
728
|
+
async function deleteProviderIdentityForSlackUser(executor, slackTeamId, slackUserId, provider, providerSubjectId) {
|
|
729
|
+
const userId = (await executor.db().select({ userId: juniorIdentities.userId }).from(juniorIdentities).where(and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"), eq(juniorIdentities.providerTenantId, slackTeamId), eq(juniorIdentities.providerSubjectId, slackUserId))).limit(1))[0]?.userId;
|
|
730
|
+
if (!userId) return;
|
|
731
|
+
await deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId);
|
|
732
|
+
}
|
|
733
|
+
/** Remove one exact provider identity owned by a user. */
|
|
734
|
+
async function deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId) {
|
|
735
|
+
await executor.db().delete(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, providerSubjectId)));
|
|
736
|
+
await clearCachedUser(userId);
|
|
737
|
+
}
|
|
738
|
+
/**
|
|
739
|
+
* Save one Google sign-in. Link the Google identity to the user of its
|
|
740
|
+
* verified email, and set its sign-in time. Return the previous sign-in
|
|
741
|
+
* time, if any.
|
|
742
|
+
*/
|
|
743
|
+
async function recordGoogleSignIn(executor, account, nowMs = Date.now()) {
|
|
744
|
+
const stored = await upsertIdentity(executor, {
|
|
745
|
+
kind: "user",
|
|
746
|
+
provider: GOOGLE_IDENTITY_PROVIDER,
|
|
747
|
+
providerSubjectId: account.subject,
|
|
748
|
+
email: account.email,
|
|
749
|
+
emailVerified: true,
|
|
750
|
+
displayName: account.displayName,
|
|
751
|
+
avatarUrl: account.avatarUrl ?? null
|
|
752
|
+
}, nowMs);
|
|
753
|
+
const [previous] = await executor.db().select({ signedInAt: juniorIdentities.signedInAt }).from(juniorIdentities).where(eq(juniorIdentities.id, stored.id)).limit(1);
|
|
754
|
+
await executor.db().update(juniorIdentities).set({ signedInAt: dateFromMs$1(nowMs) }).where(eq(juniorIdentities.id, stored.id));
|
|
755
|
+
return previous?.signedInAt?.getTime();
|
|
756
|
+
}
|
|
757
|
+
// src/chat/identities/actor.ts
|
|
758
|
+
/**
|
|
759
|
+
* Resolve runtime Actors to the Identity rows that Junior stores for them.
|
|
760
|
+
*
|
|
761
|
+
* The Conversation store, OAuth, the viewer, and message events use this
|
|
762
|
+
* module, so they agree on one Identity per person. The key for each Actor
|
|
763
|
+
* stays private here, so it can change without changing callers.
|
|
764
|
+
*/
|
|
765
|
+
/**
|
|
766
|
+
* The fixed id of the one system Identity: kind `system`, provider `junior`,
|
|
767
|
+
* an empty tenant, and subject `system`. A migration creates the row, so
|
|
768
|
+
* callers use this id without a database read.
|
|
769
|
+
*/
|
|
770
|
+
const SYSTEM_IDENTITY_ID = "system";
|
|
771
|
+
/**
|
|
772
|
+
* Return whether an Actor uses the system Identity.
|
|
773
|
+
*
|
|
774
|
+
* `SystemActor.name` is provenance, not part of the Identity. A LocalActor
|
|
775
|
+
* uses the system Identity because the local runner has no per-person user id.
|
|
776
|
+
*/
|
|
777
|
+
function usesSystemIdentity(actor) {
|
|
778
|
+
return actor.platform === "local" || actor.platform === "system";
|
|
779
|
+
}
|
|
780
|
+
/** Return the Identity key for one Slack or web Actor. */
|
|
781
|
+
function identityKey(actor) {
|
|
782
|
+
switch (actor.platform) {
|
|
783
|
+
case "slack": return {
|
|
784
|
+
kind: "user",
|
|
785
|
+
provider: "slack",
|
|
786
|
+
providerTenantId: actor.teamId,
|
|
787
|
+
providerSubjectId: actor.userId,
|
|
788
|
+
...actor.fullName ? { displayName: actor.fullName } : void 0,
|
|
789
|
+
...actor.userName ? { handle: actor.userName } : void 0,
|
|
790
|
+
...actor.email ? {
|
|
791
|
+
email: actor.email,
|
|
792
|
+
emailVerified: true
|
|
793
|
+
} : void 0,
|
|
794
|
+
metadata: { platform: "slack" }
|
|
795
|
+
};
|
|
796
|
+
case "web": {
|
|
797
|
+
const email = normalizeIdentityEmail(actor.email);
|
|
798
|
+
if (!email) return;
|
|
799
|
+
return {
|
|
800
|
+
kind: "user",
|
|
801
|
+
provider: "junior",
|
|
802
|
+
providerSubjectId: email,
|
|
803
|
+
email,
|
|
804
|
+
emailVerified: true,
|
|
805
|
+
...actor.fullName ? { displayName: actor.fullName } : void 0,
|
|
806
|
+
metadata: { platform: "web" }
|
|
807
|
+
};
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* Return the Identity id for one Actor. Save a Slack or web Identity first.
|
|
813
|
+
* Return undefined only for a web Actor without a verified email.
|
|
814
|
+
*/
|
|
815
|
+
async function resolveActorIdentityId(executor, actor, nowMs = Date.now()) {
|
|
816
|
+
if (usesSystemIdentity(actor)) return SYSTEM_IDENTITY_ID;
|
|
817
|
+
const key = identityKey(actor);
|
|
818
|
+
return key ? (await upsertIdentity(executor, key, nowMs)).id : void 0;
|
|
819
|
+
}
|
|
820
|
+
/** Save the profile photo on the Identity of one Slack Actor. Null clears it. */
|
|
821
|
+
async function saveActorAvatar(executor, actor, avatarUrl, nowMs = Date.now()) {
|
|
822
|
+
const key = identityKey(actor);
|
|
823
|
+
if (key) await upsertIdentity(executor, {
|
|
824
|
+
...key,
|
|
825
|
+
avatarUrl
|
|
826
|
+
}, nowMs);
|
|
827
|
+
}
|
|
828
|
+
/** Find the stored Identity id for one Actor without writing. */
|
|
829
|
+
async function findActorIdentityId(db, actor) {
|
|
830
|
+
if (usesSystemIdentity(actor)) return SYSTEM_IDENTITY_ID;
|
|
831
|
+
const key = identityKey(actor);
|
|
832
|
+
if (!key) return;
|
|
833
|
+
return (await db.select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, key.provider), eq(juniorIdentities.providerTenantId, key.providerTenantId ?? ""), eq(juniorIdentities.providerSubjectId, key.providerSubjectId))).limit(1))[0]?.id;
|
|
834
|
+
}
|
|
835
|
+
// src/chat/identities/avatar.ts
|
|
836
|
+
/**
|
|
837
|
+
* Profile photos of people, saved on their native Slack and Google
|
|
838
|
+
* identities. `/api/people/avatars/:identityId` serves each photo through
|
|
839
|
+
* the shared image route code, so browsers never load a photo from Slack or
|
|
840
|
+
* Google.
|
|
841
|
+
*/
|
|
842
|
+
const AVATAR_HOSTS = {
|
|
843
|
+
slack: ["avatars.slack-edge.com"],
|
|
844
|
+
[GOOGLE_IDENTITY_PROVIDER]: ["googleusercontent.com"]
|
|
845
|
+
};
|
|
846
|
+
const AVATAR_PROVIDERS = Object.keys(AVATAR_HOSTS);
|
|
847
|
+
/**
|
|
848
|
+
* Return the URL when it is HTTPS on a photo host of the provider or a
|
|
849
|
+
* subdomain. Junior fetches only these URLs.
|
|
850
|
+
*/
|
|
851
|
+
function parseAvatarUrl(value, provider) {
|
|
852
|
+
const hosts = AVATAR_HOSTS[provider];
|
|
853
|
+
if (!hosts || !value || !URL.canParse(value)) return void 0;
|
|
854
|
+
const url = new URL(value);
|
|
855
|
+
if (url.protocol !== "https:" || url.username || url.password) return;
|
|
856
|
+
const host = url.hostname.toLowerCase();
|
|
857
|
+
return hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`)) ? url.href : void 0;
|
|
858
|
+
}
|
|
859
|
+
function avatarVersion(url) {
|
|
860
|
+
return createHash("sha256").update(url).digest("hex").slice(0, 16);
|
|
861
|
+
}
|
|
862
|
+
function avatarPath(identityId, avatarUrl) {
|
|
863
|
+
return `/api/people/avatars/${encodeURIComponent(identityId)}?v=${avatarVersion(avatarUrl)}`;
|
|
864
|
+
}
|
|
865
|
+
/**
|
|
866
|
+
* Match the user Identities that hold a photo, for a read that joins them to
|
|
867
|
+
* the Identities of other rows.
|
|
868
|
+
*/
|
|
869
|
+
function hasUserPhoto(identities) {
|
|
870
|
+
return and(eq(identities.kind, "user"), inArray(identities.provider, AVATAR_PROVIDERS), isNotNull(identities.avatarUrl));
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Read the photo path of each user: the Slack photo, then the Google photo.
|
|
874
|
+
* Users without a photo are not in the map.
|
|
875
|
+
*/
|
|
876
|
+
async function readUserAvatarUrls(db, userIds) {
|
|
877
|
+
if (userIds.length === 0) return /* @__PURE__ */ new Map();
|
|
878
|
+
return userAvatarUrlsFromIdentities(await db.select({
|
|
879
|
+
avatarUrl: juniorIdentities.avatarUrl,
|
|
880
|
+
identityId: juniorIdentities.id,
|
|
881
|
+
provider: juniorIdentities.provider,
|
|
882
|
+
updatedAt: juniorIdentities.updatedAt,
|
|
883
|
+
userId: juniorIdentities.userId
|
|
884
|
+
}).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), hasUserPhoto(juniorIdentities))));
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* Pick the photo path of each user from their user Identities, for a caller
|
|
888
|
+
* that already read them: the Slack photo, then the Google photo.
|
|
889
|
+
*/
|
|
890
|
+
function userAvatarUrlsFromIdentities(rows) {
|
|
891
|
+
const rank = (row) => AVATAR_PROVIDERS.indexOf(row.provider);
|
|
892
|
+
const ranked = rows.filter((row) => rank(row) >= 0).sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
|
|
893
|
+
const avatars = /* @__PURE__ */ new Map();
|
|
894
|
+
for (const row of ranked) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
|
|
895
|
+
return avatars;
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Pick the photo path of each user from rows that joined their photo
|
|
899
|
+
* Identities with `hasUserPhoto`: the Slack photo, then the Google photo.
|
|
900
|
+
*/
|
|
901
|
+
function userAvatarUrlsFromJoinedPhotos(rows) {
|
|
902
|
+
return userAvatarUrlsFromIdentities(rows.flatMap(({ photo, userId }) => photo?.identityId && photo.provider && photo.updatedAt ? [{
|
|
903
|
+
avatarUrl: photo.avatarUrl,
|
|
904
|
+
identityId: photo.identityId,
|
|
905
|
+
provider: photo.provider,
|
|
906
|
+
updatedAt: photo.updatedAt,
|
|
907
|
+
userId
|
|
908
|
+
}] : []));
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* Return the photo path for one Identity row. A linked Identity uses the
|
|
912
|
+
* photo of its user. An Identity without a user uses its own photo.
|
|
913
|
+
*/
|
|
914
|
+
function identityAvatarUrl(row, userAvatarUrls) {
|
|
915
|
+
if (row.userId) return userAvatarUrls.get(row.userId);
|
|
916
|
+
return row.avatarUrl ? avatarPath(row.identityId, row.avatarUrl) : void 0;
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Return how to fetch the photo of one user Identity, or nothing when it has
|
|
920
|
+
* no photo on a photo host of its provider. A redirect cannot leave the
|
|
921
|
+
* photo hosts of the provider.
|
|
922
|
+
*/
|
|
923
|
+
async function readAvatarFetch(db, identityId) {
|
|
924
|
+
const [row] = await db.select({
|
|
925
|
+
avatarUrl: juniorIdentities.avatarUrl,
|
|
926
|
+
provider: juniorIdentities.provider
|
|
927
|
+
}).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
|
|
928
|
+
const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
|
|
929
|
+
const hosts = row && AVATAR_HOSTS[row.provider];
|
|
930
|
+
return url && hosts ? {
|
|
931
|
+
hosts,
|
|
932
|
+
url
|
|
933
|
+
} : void 0;
|
|
934
|
+
}
|
|
935
|
+
// src/chat/plugins/viewer.ts
|
|
936
|
+
function identityFromRow(row) {
|
|
937
|
+
return identitySchema.parse({
|
|
938
|
+
id: row.id,
|
|
939
|
+
provider: row.provider,
|
|
940
|
+
providerSubjectId: row.providerSubjectId,
|
|
941
|
+
...row.providerTenantId ? { providerTenantId: row.providerTenantId } : void 0,
|
|
942
|
+
...row.displayName ? { displayName: row.displayName } : void 0,
|
|
943
|
+
...row.handle ? { handle: row.handle } : void 0
|
|
411
944
|
});
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
}
|
|
945
|
+
}
|
|
946
|
+
async function readUserById(db, userRow) {
|
|
947
|
+
return userFromRows(userRow, await db.select().from(juniorIdentities).where(and(eq(juniorIdentities.userId, userRow.id), eq(juniorIdentities.kind, "user"))).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId)));
|
|
948
|
+
}
|
|
949
|
+
function userFromRows(userRow, identityRows) {
|
|
950
|
+
return userSchema.parse({
|
|
951
|
+
email: userRow.primaryEmail,
|
|
952
|
+
id: userRow.id,
|
|
953
|
+
identities: identityRows.map(identityFromRow),
|
|
954
|
+
...userRow.displayName ? { displayName: userRow.displayName } : void 0,
|
|
955
|
+
...userRow.isAdmin ? { isAdmin: true } : void 0
|
|
423
956
|
});
|
|
424
|
-
if (values.length > 0) await executor.db().insert(juniorConversationMetrics).values(values);
|
|
425
|
-
const metric = (name) => sql`(
|
|
426
|
-
select sum(${juniorConversationMetrics.value})
|
|
427
|
-
from ${juniorConversationMetrics}
|
|
428
|
-
where ${juniorConversationMetrics.conversationId} = ${args.conversationId}
|
|
429
|
-
and ${juniorConversationMetrics.metric} = ${name}
|
|
430
|
-
)`;
|
|
431
|
-
const totalTokens = metric("total_tokens");
|
|
432
|
-
const componentTokens = sql`
|
|
433
|
-
coalesce(${metric("input_tokens")}, 0)
|
|
434
|
-
+ coalesce(${metric("output_tokens")}, 0)
|
|
435
|
-
+ coalesce(${metric("cached_input_tokens")}, 0)
|
|
436
|
-
+ coalesce(${metric("cache_creation_tokens")}, 0)
|
|
437
|
-
`;
|
|
438
|
-
const hasComponents = sql`
|
|
439
|
-
${metric("input_tokens")} is not null
|
|
440
|
-
or ${metric("output_tokens")} is not null
|
|
441
|
-
or ${metric("cached_input_tokens")} is not null
|
|
442
|
-
or ${metric("cache_creation_tokens")} is not null
|
|
443
|
-
`;
|
|
444
|
-
const cost = sql`case when ${metric("cost_micro_usd")} is null then null
|
|
445
|
-
else jsonb_build_object('total', ${microUsdToUsdSql(metric("cost_micro_usd"))}) end`;
|
|
446
|
-
const db = executor.db();
|
|
447
|
-
const usageUpdate = db.$with("conversation_usage_update").as(db.update(juniorConversations).set({
|
|
448
|
-
durationMs: sql`coalesce(${metric("duration_ms")}, 0)`,
|
|
449
|
-
usage: sql`case
|
|
450
|
-
when ${totalTokens} is not null
|
|
451
|
-
and (${hasComponents})
|
|
452
|
-
and ${totalTokens} <> ${componentTokens}
|
|
453
|
-
then jsonb_strip_nulls(jsonb_build_object(
|
|
454
|
-
'totalTokens', ${totalTokens},
|
|
455
|
-
'reasoningTokens', ${metric("reasoning_tokens")},
|
|
456
|
-
'cost', ${cost}
|
|
457
|
-
))
|
|
458
|
-
else jsonb_strip_nulls(jsonb_build_object(
|
|
459
|
-
'totalTokens', ${totalTokens},
|
|
460
|
-
'inputTokens', ${metric("input_tokens")},
|
|
461
|
-
'outputTokens', ${metric("output_tokens")},
|
|
462
|
-
'cachedInputTokens', ${metric("cached_input_tokens")},
|
|
463
|
-
'cacheCreationTokens', ${metric("cache_creation_tokens")},
|
|
464
|
-
'reasoningTokens', ${metric("reasoning_tokens")},
|
|
465
|
-
'cost', ${cost}
|
|
466
|
-
))
|
|
467
|
-
end`,
|
|
468
|
-
detailVersion: nextDetailVersion
|
|
469
|
-
}).where(eq(juniorConversations.conversationId, args.conversationId)).returning({ costMicroUsd: costMicroUsdExpr(juniorConversations.usage).as("cost_micro_usd") }));
|
|
470
|
-
await db.with(usageUpdate).update(juniorAutomationRuns).set({ costMicroUsd: sql`(select ${usageUpdate.costMicroUsd} from ${usageUpdate})` }).where(eq(juniorAutomationRuns.conversationId, args.conversationId));
|
|
471
957
|
}
|
|
472
|
-
|
|
958
|
+
async function readUserByNormalizedEmail(db, normalizedEmail) {
|
|
959
|
+
const cached = await readCachedUserByEmail(db, normalizedEmail);
|
|
960
|
+
return cached ? userFromRows(cached.user, cached.identities) : void 0;
|
|
961
|
+
}
|
|
962
|
+
/** Resolve or create the canonical user for one verified viewer email. */
|
|
963
|
+
async function resolveViewerUserFromSql(db, email) {
|
|
964
|
+
const normalizedEmail = normalizeIdentityEmail(email);
|
|
965
|
+
if (!normalizedEmail) return void 0;
|
|
966
|
+
const existing = await readUserByNormalizedEmail(db, normalizedEmail);
|
|
967
|
+
if (existing) return existing;
|
|
968
|
+
const now = /* @__PURE__ */ new Date();
|
|
969
|
+
const userRow = (await db.insert(juniorUsers).values({
|
|
970
|
+
id: randomUUID(),
|
|
971
|
+
primaryEmail: email.trim(),
|
|
972
|
+
primaryEmailNormalized: normalizedEmail,
|
|
973
|
+
displayName: null,
|
|
974
|
+
createdAt: now,
|
|
975
|
+
updatedAt: now
|
|
976
|
+
}).onConflictDoNothing({ target: juniorUsers.primaryEmailNormalized }).returning())[0] ?? (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
|
|
977
|
+
return userRow ? await readUserById(db, userRow) : void 0;
|
|
978
|
+
}
|
|
979
|
+
/** Resolve or create the canonical user for one authenticated viewer. */
|
|
980
|
+
async function resolveViewerUser(email) {
|
|
981
|
+
return await resolveViewerUserFromSql(getDb(), email);
|
|
982
|
+
}
|
|
983
|
+
/** Read one existing canonical user by verified email without creating a row. */
|
|
984
|
+
async function findUserByEmailFromSql(db, email) {
|
|
985
|
+
const normalizedEmail = normalizeIdentityEmail(email);
|
|
986
|
+
if (!normalizedEmail) return void 0;
|
|
987
|
+
return await readUserByNormalizedEmail(db, normalizedEmail);
|
|
988
|
+
}
|
|
989
|
+
/** Read one existing canonical user by verified email without creating a row. */
|
|
990
|
+
async function findUserByEmail(email) {
|
|
991
|
+
return await findUserByEmailFromSql(getDb(), email);
|
|
992
|
+
}
|
|
993
|
+
/** Update one canonical user's display name in SQL. */
|
|
994
|
+
async function updateViewerDisplayNameFromSql(db, userId, displayName) {
|
|
995
|
+
const rows = await db.update(juniorUsers).set({
|
|
996
|
+
displayName,
|
|
997
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
998
|
+
}).where(eq(juniorUsers.id, userId)).returning();
|
|
999
|
+
await clearCachedUser(userId);
|
|
1000
|
+
const userRow = rows[0];
|
|
1001
|
+
return userRow ? await readUserById(db, userRow) : void 0;
|
|
1002
|
+
}
|
|
1003
|
+
/** Read the photo path of one canonical user: Slack, then Google. */
|
|
1004
|
+
async function readViewerAvatarUrl(userId) {
|
|
1005
|
+
return (await readUserAvatarUrls(getDb(), [userId])).get(userId);
|
|
1006
|
+
}
|
|
1007
|
+
/** Update one canonical user's display name. */
|
|
1008
|
+
async function updateViewerDisplayName(userId, displayName) {
|
|
1009
|
+
return await updateViewerDisplayNameFromSql(getDb(), userId, displayName);
|
|
1010
|
+
}
|
|
473
1011
|
/**
|
|
474
|
-
*
|
|
475
|
-
*
|
|
1012
|
+
* Grant or revoke the Junior-wide admin role for one email.
|
|
1013
|
+
*
|
|
1014
|
+
* Granting creates the canonical user when needed, so an operator can grant
|
|
1015
|
+
* admin before that person first signs in. Revoking never creates a user.
|
|
476
1016
|
*/
|
|
477
|
-
function
|
|
478
|
-
|
|
479
|
-
if (
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
1017
|
+
async function setUserAdminFromSql(db, email, isAdmin) {
|
|
1018
|
+
const user = isAdmin ? await resolveViewerUserFromSql(db, email) : await findUserByEmailFromSql(db, email);
|
|
1019
|
+
if (!user) return void 0;
|
|
1020
|
+
const rows = await db.update(juniorUsers).set({
|
|
1021
|
+
isAdmin,
|
|
1022
|
+
updatedAt: /* @__PURE__ */ new Date()
|
|
1023
|
+
}).where(eq(juniorUsers.id, user.id)).returning();
|
|
1024
|
+
await clearCachedUser(user.id);
|
|
1025
|
+
const userRow = rows[0];
|
|
1026
|
+
return userRow ? await readUserById(db, userRow) : void 0;
|
|
1027
|
+
}
|
|
1028
|
+
/** List every Junior admin by primary email. */
|
|
1029
|
+
async function listAdminUsersFromSql(db) {
|
|
1030
|
+
const rows = await db.select().from(juniorUsers).where(eq(juniorUsers.isAdmin, true)).orderBy(asc(juniorUsers.primaryEmailNormalized));
|
|
1031
|
+
if (rows.length === 0) return [];
|
|
1032
|
+
const identityRows = await db.select().from(juniorIdentities).where(and(inArray(juniorIdentities.userId, rows.map((row) => row.id)), eq(juniorIdentities.kind, "user"))).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
|
|
1033
|
+
return rows.map((row) => userFromRows(row, identityRows.filter((identity) => identity.userId === row.id)));
|
|
1034
|
+
}
|
|
1035
|
+
/** Resolve the stored identity and linked user for one runtime actor. */
|
|
1036
|
+
async function readActorIdentityFromSql(db, actor) {
|
|
1037
|
+
const identityId = await findActorIdentityId(db, actor);
|
|
1038
|
+
return identityId ? await readIdentityByIdFromSql(db, identityId) : void 0;
|
|
1039
|
+
}
|
|
1040
|
+
/** Resolve the stored identity and linked user for one runtime actor. */
|
|
1041
|
+
async function readActorIdentity(actor) {
|
|
1042
|
+
return await readActorIdentityFromSql(getDb(), actor);
|
|
1043
|
+
}
|
|
1044
|
+
/** Read one stored identity and its linked user by identity id. */
|
|
1045
|
+
async function readIdentityByIdFromSql(db, identityId) {
|
|
1046
|
+
const row = (await db.select({
|
|
1047
|
+
identity: juniorIdentities,
|
|
1048
|
+
user: juniorUsers
|
|
1049
|
+
}).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1))[0];
|
|
1050
|
+
if (!row) return void 0;
|
|
1051
|
+
return {
|
|
1052
|
+
identity: identityFromRow(row.identity),
|
|
1053
|
+
...row.user ? { user: await readUserById(db, row.user) } : void 0
|
|
483
1054
|
};
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
1055
|
+
}
|
|
1056
|
+
/** Read one stored identity and its linked user by identity id. */
|
|
1057
|
+
async function readIdentityById(identityId) {
|
|
1058
|
+
return await readIdentityByIdFromSql(getDb(), identityId);
|
|
1059
|
+
}
|
|
1060
|
+
// src/chat/review-items/assignees.ts
|
|
1061
|
+
/** Text that the agent writes to assign Everyone. */
|
|
1062
|
+
const EVERYONE_ASSIGNEE = "everyone";
|
|
1063
|
+
/**
|
|
1064
|
+
* Resolve one assignee: Everyone, an email, or a mention. A mention must be
|
|
1065
|
+
* in the tenant of the item.
|
|
1066
|
+
*/
|
|
1067
|
+
async function resolveAssignee(db, value, tenant, findMentionedUserId) {
|
|
1068
|
+
const text = value.trim();
|
|
1069
|
+
if (text.toLowerCase() === "everyone") return { everyone: true };
|
|
1070
|
+
const mentionedUserId = await findMentionedUserId(text, tenant);
|
|
1071
|
+
if (mentionedUserId) return { userId: mentionedUserId };
|
|
1072
|
+
if (text.includes("@")) {
|
|
1073
|
+
const user = await findUserByEmailFromSql(db, text);
|
|
1074
|
+
if (!user) throw new ToolInputError(`No User has the email ${text}.`);
|
|
1075
|
+
return { userId: user.id };
|
|
1076
|
+
}
|
|
1077
|
+
throw new ToolInputError(`Unknown assignee ${JSON.stringify(text)}. Use ${EVERYONE_ASSIGNEE}, an email, or a mention such as <@U123>.`);
|
|
1078
|
+
}
|
|
1079
|
+
/** Resolve the assignees of a Review item. One is required. */
|
|
1080
|
+
async function resolveAssignees(db, values, tenant, findMentionedUserId) {
|
|
1081
|
+
if (values.length === 0) throw new ToolInputError("A review item needs at least one assignee.");
|
|
1082
|
+
const resolved = await mapBounded(values, (value) => resolveAssignee(db, value, tenant, findMentionedUserId));
|
|
1083
|
+
return {
|
|
1084
|
+
everyone: resolved.some((assignee) => "everyone" in assignee),
|
|
1085
|
+
userIds: [...new Set(resolved.flatMap((assignee) => "userId" in assignee ? [assignee.userId] : []))]
|
|
488
1086
|
};
|
|
489
|
-
|
|
490
|
-
|
|
1087
|
+
}
|
|
1088
|
+
async function participantUserIds(db, conversationIds, condition) {
|
|
1089
|
+
return (await db.select({ userId: juniorConversationParticipants.userId }).from(juniorConversationParticipants).innerJoin(juniorConversations, eq(juniorConversationParticipants.rootConversationId, sql`coalesce(${juniorConversations.rootConversationId}, ${juniorConversations.conversationId})`)).where(and(inArray(juniorConversations.conversationId, [...conversationIds]), condition))).map((row) => row.userId);
|
|
1090
|
+
}
|
|
1091
|
+
/** Return which of the Users are Participants of any of the Conversations. */
|
|
1092
|
+
async function conversationParticipantUserIds(db, conversationIds, userIds) {
|
|
1093
|
+
if (conversationIds.length === 0 || userIds.length === 0) return /* @__PURE__ */ new Set();
|
|
1094
|
+
return new Set(await participantUserIds(db, conversationIds, inArray(juniorConversationParticipants.userId, [...userIds])));
|
|
1095
|
+
}
|
|
1096
|
+
/**
|
|
1097
|
+
* Return the active Participants of a Conversation: the people who have not
|
|
1098
|
+
* unsubscribed from it.
|
|
1099
|
+
*/
|
|
1100
|
+
async function activeParticipantUserIds(db, conversationId) {
|
|
1101
|
+
return await participantUserIds(db, [conversationId], isNull(juniorConversationParticipants.unsubscribedAt));
|
|
1102
|
+
}
|
|
1103
|
+
/** Return the User who created an Automation, if Junior knows them. */
|
|
1104
|
+
async function automationCreatorUserId(db, automationId) {
|
|
1105
|
+
const [row] = await db.select({ userId: juniorIdentities.userId }).from(juniorAutomations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorAutomations.creatorIdentityId)).where(eq(juniorAutomations.id, automationId)).limit(1);
|
|
1106
|
+
return row?.userId ?? void 0;
|
|
1107
|
+
}
|
|
1108
|
+
// src/chat/review-items/access.ts
|
|
1109
|
+
/** Return whether two tenants are the same. Two missing tenants match. */
|
|
1110
|
+
function isSameTenant(a, b) {
|
|
1111
|
+
return a?.provider === b?.provider && a?.providerTenantId === b?.providerTenantId;
|
|
1112
|
+
}
|
|
1113
|
+
/**
|
|
1114
|
+
* The reader for one person: items assigned to them, and public items in the
|
|
1115
|
+
* provider tenants of their identities.
|
|
1116
|
+
*/
|
|
1117
|
+
function reviewItemReaderForUser(user) {
|
|
491
1118
|
return {
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
1119
|
+
tenants: user.identities.flatMap((identity) => identity.providerTenantId ? [{
|
|
1120
|
+
provider: identity.provider,
|
|
1121
|
+
providerTenantId: identity.providerTenantId
|
|
1122
|
+
}] : []),
|
|
1123
|
+
userId: user.id
|
|
497
1124
|
};
|
|
498
1125
|
}
|
|
499
|
-
/**
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
1126
|
+
/**
|
|
1127
|
+
* SQL: a Conversation owns the Review item. The Conversation status and
|
|
1128
|
+
* feeds read the items that each Conversation owns.
|
|
1129
|
+
*/
|
|
1130
|
+
function reviewItemOwnedByConversation(conversationId) {
|
|
1131
|
+
return and(eq(juniorReviewItems.ownerKind, "conversation"), eq(juniorReviewItems.ownerId, conversationId));
|
|
503
1132
|
}
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
return (await executor.db().select({ conversationId: juniorConversationBindings.conversationId }).from(juniorConversationBindings).where(and(eq(juniorConversationBindings.provider, args.provider), eq(juniorConversationBindings.providerTenantId, args.providerTenantId), eq(juniorConversationBindings.providerDestinationId, args.providerDestinationId), eq(juniorConversationBindings.providerConversationId, args.providerConversationId))).limit(1))[0]?.conversationId;
|
|
1133
|
+
/** SQL: the Review item has this assigned User. */
|
|
1134
|
+
function reviewItemAssignedTo(userId) {
|
|
1135
|
+
return sql`exists (select 1 from ${juniorReviewItemAssignees} where ${juniorReviewItemAssignees.itemId} = ${juniorReviewItems.id} and ${juniorReviewItemAssignees.userId} = ${userId})`;
|
|
508
1136
|
}
|
|
509
1137
|
/**
|
|
510
|
-
*
|
|
511
|
-
*
|
|
1138
|
+
* SQL: the Review item needs this User. Only an open `action` item that is
|
|
1139
|
+
* assigned to the User needs them. A notice, an item for Everyone, and an
|
|
1140
|
+
* item without assignees need no one. An assigned User can always see the
|
|
1141
|
+
* item, so this rule needs no visibility check. The nav count and the
|
|
1142
|
+
* "Waiting on you" marker use this rule.
|
|
512
1143
|
*/
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
...args,
|
|
516
|
-
createdAt: /* @__PURE__ */ new Date()
|
|
517
|
-
}).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args);
|
|
518
|
-
if (!ownerId) throw new Error("Provider conversation binding disappeared during claim");
|
|
519
|
-
return ownerId;
|
|
1144
|
+
function reviewItemNeedsUser(userId) {
|
|
1145
|
+
return and(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.kind, "action"), reviewItemAssignedTo(userId));
|
|
520
1146
|
}
|
|
521
1147
|
/**
|
|
522
|
-
*
|
|
523
|
-
*
|
|
1148
|
+
* SQL: the Review item needs some person: an open `action` item with an
|
|
1149
|
+
* assigned User. It is `reviewItemNeedsUser` for any User.
|
|
524
1150
|
*/
|
|
525
|
-
|
|
526
|
-
return
|
|
1151
|
+
function reviewItemNeedsSomeone() {
|
|
1152
|
+
return and(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.kind, "action"), sql`exists (select 1 from ${juniorReviewItemAssignees} where ${juniorReviewItemAssignees.itemId} = ${juniorReviewItems.id})`);
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* SQL: the Review item waits for a person's input: an open `action` item,
|
|
1156
|
+
* whoever it is assigned to. An item with no assignees still waits for
|
|
1157
|
+
* anyone who can answer it. The Conversation that added it shows
|
|
1158
|
+
* `needs_input`. `junior_review_items_open_action_added_by_idx` has this
|
|
1159
|
+
* predicate.
|
|
1160
|
+
*/
|
|
1161
|
+
function reviewItemNeedsInput() {
|
|
1162
|
+
return and(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.kind, "action"));
|
|
1163
|
+
}
|
|
1164
|
+
/**
|
|
1165
|
+
* SQL: the Review item is not assigned only to other people. It is assigned
|
|
1166
|
+
* to this User, to Everyone, or to no one. This is the assignee rule of
|
|
1167
|
+
* `canActOnReviewItem`; keep the two the same.
|
|
1168
|
+
*/
|
|
1169
|
+
function reviewItemForUser(userId) {
|
|
1170
|
+
return or(eq(juniorReviewItems.assignedToEveryone, true), sql`not exists (select 1 from ${juniorReviewItemAssignees} where ${juniorReviewItemAssignees.itemId} = ${juniorReviewItems.id})`, reviewItemAssignedTo(userId));
|
|
1171
|
+
}
|
|
1172
|
+
/** SQL: the Review item links this Conversation. */
|
|
1173
|
+
function reviewItemLinkedTo(conversationId) {
|
|
1174
|
+
return sql`exists (select 1 from ${juniorReviewItemConversations} where ${juniorReviewItemConversations.itemId} = ${juniorReviewItems.id} and ${juniorReviewItemConversations.conversationId} = ${conversationId})`;
|
|
1175
|
+
}
|
|
1176
|
+
function publicIn(tenants) {
|
|
1177
|
+
return tenants.map((tenant) => and(eq(juniorReviewItems.visibility, "public"), eq(juniorReviewItems.provider, tenant.provider), eq(juniorReviewItems.providerTenantId, tenant.providerTenantId)));
|
|
1178
|
+
}
|
|
1179
|
+
/**
|
|
1180
|
+
* SQL form of `canReadReviewItem`, for search. Keep the two the same; the
|
|
1181
|
+
* Review item access test checks that they agree.
|
|
1182
|
+
*/
|
|
1183
|
+
function reviewItemVisibleTo(reader) {
|
|
1184
|
+
return or(...publicIn(reader.tenants ?? []), ...reader.userId ? [reviewItemAssignedTo(reader.userId)] : [], ...reader.conversationId ? [reviewItemLinkedTo(reader.conversationId)] : [], ...reader.automationId ? [eq(juniorReviewItems.automationId, reader.automationId)] : []) ?? sql`false`;
|
|
1185
|
+
}
|
|
1186
|
+
/** Return whether a reader can see one Review item. */
|
|
1187
|
+
function canReadReviewItem(item, reader) {
|
|
1188
|
+
return item.visibility === "public" && item.tenant !== void 0 && (reader.tenants ?? []).some((tenant) => isSameTenant(tenant, item.tenant)) || reader.userId !== void 0 && item.assignees.some((assignee) => assignee.userId === reader.userId) || reader.conversationId !== void 0 && item.conversationIds.includes(reader.conversationId) || reader.automationId !== void 0 && item.automationId === reader.automationId;
|
|
1189
|
+
}
|
|
1190
|
+
/**
|
|
1191
|
+
* Return whether a person can read one Review item: by the reader rule, or
|
|
1192
|
+
* because they take part in a Conversation that the item links. The second
|
|
1193
|
+
* part is the person rule of `policies/conversation-access.md`; it lets the
|
|
1194
|
+
* Conversation view show its items. Viewing a public Conversation is not
|
|
1195
|
+
* enough: a private item stays private when its Conversation becomes public.
|
|
1196
|
+
*/
|
|
1197
|
+
async function canUserReadReviewItem(item, user) {
|
|
1198
|
+
if (canReadReviewItem(item, reviewItemReaderForUser(user))) return true;
|
|
1199
|
+
const access = await readConversationAccessFromSql(getDb(), item.conversationIds, user);
|
|
1200
|
+
return item.conversationIds.some((id) => access.get(id)?.isParticipant === true);
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* The reader for one person who looks at one Conversation: the person's
|
|
1204
|
+
* reader, plus the items linked to the Conversation when they take part in
|
|
1205
|
+
* it. It is the list form of `canUserReadReviewItem`.
|
|
1206
|
+
*/
|
|
1207
|
+
async function reviewItemReaderForUserInConversation(user, conversationId) {
|
|
1208
|
+
const reader = reviewItemReaderForUser(user);
|
|
1209
|
+
return (await readConversationAccessFromSql(getDb(), [conversationId], user)).get(conversationId)?.isParticipant ? {
|
|
1210
|
+
...reader,
|
|
1211
|
+
conversationId
|
|
1212
|
+
} : reader;
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Read the scope of an agent. The agent reads as its Conversation and
|
|
1216
|
+
* Automation, not as its Actor: an assignment lets a person see the item on
|
|
1217
|
+
* the Inbox, not let an agent read it into another Conversation.
|
|
1218
|
+
*/
|
|
1219
|
+
async function readReviewItemAgentScope(context) {
|
|
1220
|
+
const actor = await context.resolveActorIdentity?.();
|
|
1221
|
+
const user = actor?.user;
|
|
1222
|
+
const automationId = context.source.kind === "scheduled_automation" || context.source.kind === "event_automation" ? context.source.automationId : void 0;
|
|
1223
|
+
const current = (await readConversationAccessFromSql(getDb(), [context.conversationId], user)).get(context.conversationId);
|
|
1224
|
+
const tenant = current?.tenant;
|
|
1225
|
+
return {
|
|
1226
|
+
actorIsPerson: actor !== void 0,
|
|
1227
|
+
inPrivateConversation: current?.visibility !== "public",
|
|
1228
|
+
reader: {
|
|
1229
|
+
conversationId: context.conversationId,
|
|
1230
|
+
...automationId ? { automationId } : void 0,
|
|
1231
|
+
...tenant ? { tenants: [tenant] } : void 0
|
|
1232
|
+
},
|
|
1233
|
+
...tenant ? { tenant } : void 0,
|
|
1234
|
+
...user ? { user } : void 0
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
/**
|
|
1238
|
+
* Dedupe keys with this prefix belong to plugins. Only the plugin that added
|
|
1239
|
+
* the item, or a person, can change it. An agent cannot use the prefix.
|
|
1240
|
+
*/
|
|
1241
|
+
const PLUGIN_REVIEW_ITEM_KEY_PREFIX = "plugin:";
|
|
1242
|
+
/**
|
|
1243
|
+
* Dedupe keys with this prefix belong to Automation alerts, which core adds
|
|
1244
|
+
* and closes. An agent cannot use the prefix.
|
|
1245
|
+
*/
|
|
1246
|
+
const AUTOMATION_REVIEW_ITEM_KEY_PREFIX = "automation:";
|
|
1247
|
+
/** Return the plugin that owns a dedupe key, or undefined for an agent's key. */
|
|
1248
|
+
function reviewItemPlugin(dedupeKey) {
|
|
1249
|
+
if (!dedupeKey.startsWith("plugin:")) return void 0;
|
|
1250
|
+
return dedupeKey.slice(7).split(":", 1)[0] || void 0;
|
|
1251
|
+
}
|
|
1252
|
+
/** Return whether the item is an Automation alert. Core takes its answer. */
|
|
1253
|
+
function isAutomationAlertItem(item) {
|
|
1254
|
+
return item.dedupeKey.startsWith(AUTOMATION_REVIEW_ITEM_KEY_PREFIX);
|
|
1255
|
+
}
|
|
1256
|
+
/** Return whether a plugin added the item. Its answer goes to the plugin. */
|
|
1257
|
+
function isPluginReviewItem(item) {
|
|
1258
|
+
return reviewItemPlugin(item.dedupeKey) !== void 0;
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Whether an agent can change an item. Only an agent in the tenant of the
|
|
1262
|
+
* item can change it. A public item changes only from a public
|
|
1263
|
+
* Conversation, so private content never reaches its readers. A private
|
|
1264
|
+
* item changes only from the Conversation or Automation that added it. An
|
|
1265
|
+
* agent never changes an item that a plugin added, or an item that another
|
|
1266
|
+
* owner kind, such as an Automation, owns.
|
|
1267
|
+
*/
|
|
1268
|
+
function canAgentChangeReviewItem(item, scope) {
|
|
1269
|
+
if (item.dedupeKey.startsWith("plugin:")) return false;
|
|
1270
|
+
if (item.owner.kind !== "conversation") return false;
|
|
1271
|
+
if (!isSameTenant(item.tenant, scope.tenant)) return false;
|
|
1272
|
+
if (item.visibility === "public") return !scope.inPrivateConversation;
|
|
1273
|
+
return item.owner.id === scope.reader.conversationId || scope.reader.automationId !== void 0 && item.automationId === scope.reader.automationId;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Check the Conversations that an agent links. Every link must be in the
|
|
1277
|
+
* tenant of the item. `allowedIds` (the current Conversation and the links
|
|
1278
|
+
* that the item already has) always pass. A private item gets no other
|
|
1279
|
+
* links. A public item can get other links only to public Conversations.
|
|
1280
|
+
*/
|
|
1281
|
+
async function requireReviewItemLinks(args) {
|
|
1282
|
+
const access = await readConversationAccessFromSql(getDb(), args.conversationIds, args.scope.user);
|
|
1283
|
+
for (const conversationId of args.conversationIds) {
|
|
1284
|
+
const conversation = access.get(conversationId);
|
|
1285
|
+
if (!conversation || !isSameTenant(conversation.tenant, args.tenant)) throw new ToolInputError(`Conversation ${conversationId} is not found.`);
|
|
1286
|
+
if (args.allowedIds.has(conversationId)) continue;
|
|
1287
|
+
if (args.visibility === "private") throw new ToolInputError("A private item links only to the Conversation that added it.");
|
|
1288
|
+
if (conversation.visibility !== "public") throw new ToolInputError(conversation.canViewPrivateContent ? `Conversation ${conversationId} is private. Only public Conversations can be linked.` : `Conversation ${conversationId} is not found.`);
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* Check who an agent assigns a private item to. It cannot go to Everyone.
|
|
1293
|
+
* Each User must be the current Actor, a Participant of one of the given
|
|
1294
|
+
* Conversations (the current one and, for an existing item, the one that
|
|
1295
|
+
* added it), or the creator of the Automation that added the item. An
|
|
1296
|
+
* Automation run often has no Actor and no people yet, and its creator wrote
|
|
1297
|
+
* the work. A public item can go to anyone.
|
|
1298
|
+
*/
|
|
1299
|
+
async function requireReviewItemAssignees(args) {
|
|
1300
|
+
if (args.visibility === "public") return;
|
|
1301
|
+
if (args.assignees.everyone) throw new ToolInputError("A private item cannot be assigned to Everyone. Assign Users instead.");
|
|
1302
|
+
const creatorId = args.automationId ? await automationCreatorUserId(getDb(), args.automationId) : void 0;
|
|
1303
|
+
const others = args.assignees.userIds.filter((id) => id !== args.scope.user?.id && id !== creatorId);
|
|
1304
|
+
const inConversation = await conversationParticipantUserIds(getDb(), args.conversationIds, others);
|
|
1305
|
+
if (others.some((id) => !inConversation.has(id))) throw new ToolInputError("A private item can be assigned only to people in its Conversation.");
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* Return whether a User can act on an open Review item: an assigned User,
|
|
1309
|
+
* anyone for an item assigned to Everyone, and anyone for an item with no
|
|
1310
|
+
* assignees. The caller checks that the User can see the item.
|
|
1311
|
+
* `reviewItemForUser` is the SQL form of the assignee rule.
|
|
1312
|
+
*/
|
|
1313
|
+
function canActOnReviewItem(item, userId) {
|
|
1314
|
+
if (item.status !== "open") return false;
|
|
1315
|
+
if (item.assignedToEveryone) return true;
|
|
1316
|
+
if (item.assignees.length === 0) return true;
|
|
1317
|
+
return item.assignees.some((assignee) => assignee.userId === userId);
|
|
1318
|
+
}
|
|
1319
|
+
/**
|
|
1320
|
+
* Return whether a Review item needs a User: an open `action` item that is
|
|
1321
|
+
* assigned to them. `reviewItemNeedsUser` is the SQL form; keep the two the
|
|
1322
|
+
* same.
|
|
1323
|
+
*/
|
|
1324
|
+
function itemNeedsUser(item, userId) {
|
|
1325
|
+
return item.status === "open" && item.kind === "action" && item.assignees.some((assignee) => assignee.userId === userId);
|
|
1326
|
+
}
|
|
1327
|
+
/** Return whether a User is already the only assignee, so take does nothing. */
|
|
1328
|
+
function isOnlyAssignee(item, userId) {
|
|
1329
|
+
return !item.assignedToEveryone && item.assignees.length === 1 && item.assignees[0]?.userId === userId;
|
|
1330
|
+
}
|
|
1331
|
+
// src/chat/conversations/sql/authorization-wait.ts
|
|
1332
|
+
/**
|
|
1333
|
+
* How long a person can finish an authorization. The MCP auth session and the
|
|
1334
|
+
* dashboard connect prompt expire after this time, so the parked Turn cannot
|
|
1335
|
+
* resume after it.
|
|
1336
|
+
*/
|
|
1337
|
+
const AUTHORIZATION_WAIT_MS = 864e5;
|
|
1338
|
+
/**
|
|
1339
|
+
* The request and the events that end its wait: the person connected, or a
|
|
1340
|
+
* Turn started or ended after the request. A stop or new input ends the
|
|
1341
|
+
* parked Turn with `turn_completed`. A child agent invocation that needs a
|
|
1342
|
+
* connection abandons its Turn and ends it as `blocked`, so nothing resumes
|
|
1343
|
+
* it and its parent gets the result instead.
|
|
1344
|
+
*/
|
|
1345
|
+
const AUTHORIZATION_WAIT_EVENT_TYPES = [
|
|
1346
|
+
"authorization_requested",
|
|
1347
|
+
"authorization_completed",
|
|
1348
|
+
"turn_started",
|
|
1349
|
+
"turn_completed",
|
|
1350
|
+
"turn_failed"
|
|
1351
|
+
];
|
|
1352
|
+
/** The oldest request that still waits, on the app clock. */
|
|
1353
|
+
function authorizationWaitStart() {
|
|
1354
|
+
return (/* @__PURE__ */ new Date(Date.now() - AUTHORIZATION_WAIT_MS)).toISOString();
|
|
1355
|
+
}
|
|
1356
|
+
/**
|
|
1357
|
+
* SQL: the Conversation waits on a person to finish an authorization. A Turn
|
|
1358
|
+
* that needs a connection parks with execution `idle`, so only the durable
|
|
1359
|
+
* `authorization_requested` event shows the wait: it is the newest of these
|
|
1360
|
+
* events and has not expired. Build it for each query: it binds the app
|
|
1361
|
+
* clock, which also dated the request.
|
|
1362
|
+
*/
|
|
1363
|
+
function awaitsAuthorization(conversationId) {
|
|
1364
|
+
return authorizationWait(conversationId, sql`true`);
|
|
1365
|
+
}
|
|
1366
|
+
/**
|
|
1367
|
+
* SQL: the Conversation waits on this User to finish an authorization. The
|
|
1368
|
+
* request names the person by their User id, or by the Slack user id of
|
|
1369
|
+
* one of their Identities. Build it for each query, as `awaitsAuthorization`.
|
|
1370
|
+
*/
|
|
1371
|
+
function awaitsAuthorizationFrom(conversationId, userId) {
|
|
1372
|
+
const actorId = sql`${juniorConversationEvents.payload}->>'actorId'`;
|
|
1373
|
+
return authorizationWait(conversationId, sql`(${actorId} = ${userId} or ${actorId} in (select ${juniorIdentities.providerSubjectId} from ${juniorIdentities} where ${and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, "slack"))}))`);
|
|
1374
|
+
}
|
|
1375
|
+
/** SQL: the newest wait event is a live request that `requester` matches. */
|
|
1376
|
+
function authorizationWait(conversationId, requester) {
|
|
1377
|
+
const events = juniorConversationEvents;
|
|
1378
|
+
return sql`coalesce((
|
|
1379
|
+
select ${events.type} = 'authorization_requested'
|
|
1380
|
+
and ${events.createdAt} > ${authorizationWaitStart()}::timestamptz
|
|
1381
|
+
and ${requester}
|
|
1382
|
+
from ${events}
|
|
1383
|
+
where ${events.conversationId} = ${conversationId}
|
|
1384
|
+
and ${events.type} in (${sql.join(AUTHORIZATION_WAIT_EVENT_TYPES.map((type) => sql`${type}`), sql`, `)})
|
|
1385
|
+
order by ${events.seq} desc
|
|
1386
|
+
limit 1
|
|
1387
|
+
), false)`;
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* SQL: the root or a child Conversation of `rootConversationId` waits on a
|
|
1391
|
+
* person to finish an authorization.
|
|
1392
|
+
*/
|
|
1393
|
+
function treeAwaitsAuthorization(rootConversationId) {
|
|
1394
|
+
const tree = alias(juniorConversations, "authorization_tree");
|
|
1395
|
+
return sql`exists (
|
|
1396
|
+
select 1 from ${juniorConversations} as ${tree}
|
|
1397
|
+
where (${tree.conversationId} = ${rootConversationId}
|
|
1398
|
+
or ${tree.rootConversationId} = ${rootConversationId})
|
|
1399
|
+
and ${awaitsAuthorization(tree.conversationId)}
|
|
1400
|
+
)`;
|
|
1401
|
+
}
|
|
1402
|
+
// src/chat/conversations/sql/conversation-row.ts
|
|
1403
|
+
/**
|
|
1404
|
+
* Establish the conversation metadata row on first contact for content writes
|
|
1405
|
+
* (conversation events, visible transcript) that can land before activity has
|
|
1406
|
+
* created the row, and whose tables FK to it.
|
|
1407
|
+
*
|
|
1408
|
+
* First contact creates the row; every later content write advances the
|
|
1409
|
+
* activity clock so retention mirrors append-refresh semantics (each content
|
|
1410
|
+
* append refreshes the retention window). Background observations may opt out
|
|
1411
|
+
* and leave an existing row unchanged. The timestamp is content-intrinsic (the
|
|
1412
|
+
* first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
|
|
1413
|
+
* imported historical write — which carries an old timestamp — can never
|
|
1414
|
+
* regress `last_activity_at`.
|
|
1415
|
+
*/
|
|
1416
|
+
async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
|
|
1417
|
+
const at = new Date(atMs);
|
|
1418
|
+
const insert = executor.db().insert(juniorConversations).values({
|
|
1419
|
+
conversationId,
|
|
1420
|
+
createdAt: at,
|
|
1421
|
+
lastActivityAt: at,
|
|
1422
|
+
updatedAt: at,
|
|
1423
|
+
executionStatus: "idle",
|
|
1424
|
+
kind: "root"
|
|
1425
|
+
});
|
|
1426
|
+
if (options.activity === "preserve") {
|
|
1427
|
+
await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
|
|
1428
|
+
return;
|
|
1429
|
+
}
|
|
1430
|
+
await insert.onConflictDoUpdate({
|
|
1431
|
+
target: juniorConversations.conversationId,
|
|
1432
|
+
set: {
|
|
1433
|
+
lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
|
|
1434
|
+
updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
|
|
1435
|
+
transcriptPurgedAt: null,
|
|
1436
|
+
detailVersion: nextDetailVersion
|
|
1437
|
+
}
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
const CONVERSATION_KINDS = /* @__PURE__ */ new Set([
|
|
1441
|
+
"root",
|
|
1442
|
+
"automation",
|
|
1443
|
+
"thread",
|
|
1444
|
+
"task"
|
|
1445
|
+
]);
|
|
1446
|
+
/** Decode a stored kind. A null kind comes from a writer of an older deploy. */
|
|
1447
|
+
function conversationKindFromRow(row) {
|
|
1448
|
+
const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
|
|
1449
|
+
if (!CONVERSATION_KINDS.has(kind)) throw new Error("Conversation record kind is invalid");
|
|
1450
|
+
return kind;
|
|
527
1451
|
}
|
|
528
|
-
/**
|
|
529
|
-
|
|
530
|
-
|
|
1452
|
+
/** SQL for the kind of a row, with the same null fallback as `conversationKindFromRow`. */
|
|
1453
|
+
function conversationKindSql(conversation) {
|
|
1454
|
+
return sql`coalesce(${conversation.kind}, case when ${conversation.parentConversationId} is null then 'root' else 'task' end)`;
|
|
1455
|
+
}
|
|
1456
|
+
// src/chat/conversations/sql/status.ts
|
|
1457
|
+
const ACTIVE_EXECUTION_STATUSES = [
|
|
1458
|
+
"pending",
|
|
1459
|
+
"running",
|
|
1460
|
+
"paused",
|
|
1461
|
+
"awaiting_resume"
|
|
1462
|
+
];
|
|
1463
|
+
/** SQL: a Turn of the Conversation is queued or running. */
|
|
1464
|
+
function conversationIsActiveSql(conversation) {
|
|
1465
|
+
return sql`${conversation.executionStatus} in (${sql.raw(ACTIVE_EXECUTION_STATUSES.map((status) => `'${status}'`).join(", "))})`;
|
|
531
1466
|
}
|
|
532
|
-
// src/chat/state/locks.ts
|
|
533
|
-
const ACTIVE_LOCK_TTL_MS = 9e4;
|
|
534
|
-
const MUTATION_LOCK_TTL_MS = 1e4;
|
|
535
1467
|
/**
|
|
536
|
-
*
|
|
537
|
-
*
|
|
1468
|
+
* Whether a Turn is queued or running, for a row that is already read. It
|
|
1469
|
+
* matches `conversationIsActiveSql`. Live views poll on it; `status` can
|
|
1470
|
+
* read `needs_input` meanwhile.
|
|
538
1471
|
*/
|
|
539
|
-
|
|
540
|
-
return
|
|
1472
|
+
function executionIsActive(executionStatus) {
|
|
1473
|
+
return ACTIVE_EXECUTION_STATUSES.includes(executionStatus);
|
|
541
1474
|
}
|
|
542
1475
|
/**
|
|
543
|
-
*
|
|
544
|
-
*
|
|
545
|
-
*
|
|
1476
|
+
* SQL: the latest Turn of the Conversation failed with no newer input.
|
|
1477
|
+
* Execution is `failed`, or the newest Turn lifecycle Event is
|
|
1478
|
+
* `turn_failed`. Events are durable; the Redis Turn record expires. Stats
|
|
1479
|
+
* count it; the status reads it as input that the starter needs to give.
|
|
546
1480
|
*/
|
|
547
|
-
|
|
548
|
-
const
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
heartbeat?.unref();
|
|
559
|
-
try {
|
|
560
|
-
return {
|
|
561
|
-
acquired: true,
|
|
562
|
-
value: await run(lock)
|
|
563
|
-
};
|
|
564
|
-
} finally {
|
|
565
|
-
if (heartbeat) clearInterval(heartbeat);
|
|
566
|
-
await state.releaseLock(lock);
|
|
567
|
-
}
|
|
1481
|
+
function conversationTurnFailedSql(conversation) {
|
|
1482
|
+
const newestSeq = (type) => sql`(select max(${juniorConversationEvents.seq}) from ${juniorConversationEvents} where ${and(eq(juniorConversationEvents.conversationId, conversation.conversationId), eq(juniorConversationEvents.type, type))})`;
|
|
1483
|
+
return sql`(${conversation.executionStatus} = 'failed' or ${newestSeq("turn_failed")} > coalesce(greatest(${newestSeq("turn_started")}, ${newestSeq("turn_completed")}), -1))`;
|
|
1484
|
+
}
|
|
1485
|
+
const DELIVERY_PAUSE_START = sql.raw(`'2026-11-10T02:48:39Z'::timestamptz`);
|
|
1486
|
+
const starterRoot = alias(juniorConversations, "status_starter_root");
|
|
1487
|
+
const starterIdentity = alias(juniorIdentities, "status_starter_identity");
|
|
1488
|
+
const replyReader = alias(juniorIdentities, "status_reply_reader");
|
|
1489
|
+
/** SQL: the User id of the Conversation's starter, the User of its root's actor. */
|
|
1490
|
+
function conversationStarterUserIdSql(conversation) {
|
|
1491
|
+
return sql`(select ${starterIdentity.userId} from ${juniorConversations} as ${starterRoot} join ${juniorIdentities} as ${starterIdentity} on ${eq(starterIdentity.id, starterRoot.actorIdentityId)} where ${eq(starterRoot.conversationId, sql`coalesce(${conversation.rootConversationId}, ${conversation.conversationId})`)})`;
|
|
568
1492
|
}
|
|
569
1493
|
/**
|
|
570
|
-
*
|
|
1494
|
+
* SQL: the work of the Conversation waits on its starter. The starter is
|
|
1495
|
+
* the User of the root's actor: the person whose message started the root,
|
|
1496
|
+
* or the creator of an Automation run. A Task reports to its parent, so
|
|
1497
|
+
* only a root, an Automation run, or a Thread waits on its starter. A stop
|
|
1498
|
+
* ends what the Conversation waits on, and a queued or running Turn is
|
|
1499
|
+
* `working`, not waiting. One of these applies:
|
|
571
1500
|
*
|
|
572
|
-
*
|
|
573
|
-
*
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
const
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
};
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
enqueue: (threadId, entry, maxSize) => connected(() => base.enqueue(threadId, entry, maxSize)),
|
|
601
|
-
dequeue: (threadId) => connected(() => base.dequeue(threadId)),
|
|
602
|
-
queueDepth: (threadId) => connected(() => base.queueDepth(threadId)),
|
|
603
|
-
get: (key) => connected(() => base.get(key)),
|
|
604
|
-
getList: (key) => connected(() => base.getList(key)),
|
|
605
|
-
set: (key, value, ttlMs) => connected(() => base.set(key, value, ttlMs)),
|
|
606
|
-
setIfNotExists: (key, value, ttlMs) => connected(() => base.setIfNotExists(key, value, ttlMs)),
|
|
607
|
-
delete: (key) => connected(() => base.delete(key))
|
|
608
|
-
};
|
|
609
|
-
}
|
|
610
|
-
function createPrefixedStateAdapter(base, prefix) {
|
|
611
|
-
const prefixed = (value) => `${prefix}:${value}`;
|
|
612
|
-
const unprefixed = (value) => value.startsWith(`${prefix}:`) ? value.slice(prefix.length + 1) : value;
|
|
613
|
-
const prefixLock = (lock) => ({
|
|
614
|
-
...lock,
|
|
615
|
-
threadId: prefixed(lock.threadId)
|
|
616
|
-
});
|
|
617
|
-
const unprefixLock = (lock) => ({
|
|
618
|
-
...lock,
|
|
619
|
-
threadId: unprefixed(lock.threadId)
|
|
620
|
-
});
|
|
621
|
-
return {
|
|
622
|
-
appendToList: (key, value, options) => base.appendToList(prefixed(key), value, options),
|
|
623
|
-
connect: () => base.connect(),
|
|
624
|
-
disconnect: () => base.disconnect(),
|
|
625
|
-
subscribe: (threadId) => base.subscribe(prefixed(threadId)),
|
|
626
|
-
unsubscribe: (threadId) => base.unsubscribe(prefixed(threadId)),
|
|
627
|
-
isSubscribed: (threadId) => base.isSubscribed(prefixed(threadId)),
|
|
628
|
-
acquireLock: async (threadId, ttlMs) => {
|
|
629
|
-
const lock = await base.acquireLock(prefixed(threadId), ttlMs);
|
|
630
|
-
return lock ? unprefixLock(lock) : null;
|
|
631
|
-
},
|
|
632
|
-
releaseLock: (lock) => base.releaseLock(prefixLock(lock)),
|
|
633
|
-
extendLock: async (lock, ttlMs) => {
|
|
634
|
-
const prefixedLock = prefixLock(lock);
|
|
635
|
-
const extended = await base.extendLock(prefixedLock, ttlMs);
|
|
636
|
-
if (extended) lock.expiresAt = prefixedLock.expiresAt;
|
|
637
|
-
return extended;
|
|
638
|
-
},
|
|
639
|
-
forceReleaseLock: (threadId) => base.forceReleaseLock(prefixed(threadId)),
|
|
640
|
-
enqueue: (threadId, entry, maxSize) => base.enqueue(prefixed(threadId), entry, maxSize),
|
|
641
|
-
dequeue: (threadId) => base.dequeue(prefixed(threadId)),
|
|
642
|
-
queueDepth: (threadId) => base.queueDepth(prefixed(threadId)),
|
|
643
|
-
get: (key) => base.get(prefixed(key)),
|
|
644
|
-
getList: (key) => base.getList(prefixed(key)),
|
|
645
|
-
set: (key, value, ttlMs) => base.set(prefixed(key), value, ttlMs),
|
|
646
|
-
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(prefixed(key), value, ttlMs),
|
|
647
|
-
delete: (key) => base.delete(prefixed(key))
|
|
648
|
-
};
|
|
649
|
-
}
|
|
650
|
-
function createQueuedStateAdapter(base, options) {
|
|
651
|
-
const heartbeats = /* @__PURE__ */ new Map();
|
|
652
|
-
const shouldHeartbeatLock = (ttlMs) => ttlMs === ACTIVE_LOCK_TTL_MS;
|
|
653
|
-
const heartbeatKey = (lock) => `${lock.threadId}:${lock.token}`;
|
|
654
|
-
const stopHeartbeatByKey = (key) => {
|
|
655
|
-
const heartbeat = heartbeats.get(key);
|
|
656
|
-
if (!heartbeat) return;
|
|
657
|
-
clearInterval(heartbeat.timer);
|
|
658
|
-
heartbeats.delete(key);
|
|
659
|
-
};
|
|
660
|
-
const stopHeartbeat = (lock) => {
|
|
661
|
-
stopHeartbeatByKey(heartbeatKey(lock));
|
|
662
|
-
};
|
|
663
|
-
const stopHeartbeatsForThread = (threadId) => {
|
|
664
|
-
for (const [key, heartbeat] of heartbeats) if (heartbeat.lock.threadId === threadId) stopHeartbeatByKey(key);
|
|
665
|
-
};
|
|
666
|
-
const stopAllHeartbeats = () => {
|
|
667
|
-
for (const key of heartbeats.keys()) stopHeartbeatByKey(key);
|
|
668
|
-
};
|
|
669
|
-
const runHeartbeat = async (key) => {
|
|
670
|
-
const heartbeat = heartbeats.get(key);
|
|
671
|
-
if (!heartbeat || heartbeat.inFlight) return;
|
|
672
|
-
heartbeat.inFlight = true;
|
|
673
|
-
try {
|
|
674
|
-
if (Date.now() - heartbeat.startedAtMs >= options.activeLockMaxAgeMs) {
|
|
675
|
-
stopHeartbeatByKey(key);
|
|
676
|
-
return;
|
|
677
|
-
}
|
|
678
|
-
if (!await base.extendLock(heartbeat.lock, heartbeat.ttlMs)) {
|
|
679
|
-
stopHeartbeatByKey(key);
|
|
680
|
-
return;
|
|
681
|
-
}
|
|
682
|
-
heartbeat.lock.expiresAt = Date.now() + heartbeat.ttlMs;
|
|
683
|
-
} catch {} finally {
|
|
684
|
-
const current = heartbeats.get(key);
|
|
685
|
-
if (current === heartbeat) current.inFlight = false;
|
|
686
|
-
}
|
|
687
|
-
};
|
|
688
|
-
const startOrUpdateHeartbeat = (lock, ttlMs) => {
|
|
689
|
-
const key = heartbeatKey(lock);
|
|
690
|
-
const existing = heartbeats.get(key);
|
|
691
|
-
if (existing) {
|
|
692
|
-
existing.ttlMs = ttlMs;
|
|
693
|
-
return;
|
|
694
|
-
}
|
|
695
|
-
const timer = setInterval(() => {
|
|
696
|
-
runHeartbeat(key);
|
|
697
|
-
}, ACTIVE_LOCK_HEARTBEAT_MS);
|
|
698
|
-
timer.unref?.();
|
|
699
|
-
heartbeats.set(key, {
|
|
700
|
-
inFlight: false,
|
|
701
|
-
lock,
|
|
702
|
-
startedAtMs: Date.now(),
|
|
703
|
-
timer,
|
|
704
|
-
ttlMs
|
|
705
|
-
});
|
|
706
|
-
};
|
|
707
|
-
const acquireLock = async (threadId, ttlMs) => {
|
|
708
|
-
const lock = await base.acquireLock(threadId, ttlMs);
|
|
709
|
-
if (lock && shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
|
|
710
|
-
return lock;
|
|
711
|
-
};
|
|
712
|
-
return {
|
|
713
|
-
appendToList: (key, value, options) => base.appendToList(key, value, options),
|
|
714
|
-
connect: () => base.connect(),
|
|
715
|
-
disconnect: async () => {
|
|
716
|
-
stopAllHeartbeats();
|
|
717
|
-
await base.disconnect();
|
|
718
|
-
},
|
|
719
|
-
subscribe: (threadId) => base.subscribe(threadId),
|
|
720
|
-
unsubscribe: (threadId) => base.unsubscribe(threadId),
|
|
721
|
-
isSubscribed: (threadId) => base.isSubscribed(threadId),
|
|
722
|
-
acquireLock,
|
|
723
|
-
releaseLock: async (lock) => {
|
|
724
|
-
stopHeartbeat(lock);
|
|
725
|
-
await base.releaseLock(lock);
|
|
726
|
-
},
|
|
727
|
-
extendLock: async (lock, ttlMs) => {
|
|
728
|
-
const extended = await base.extendLock(lock, ttlMs);
|
|
729
|
-
if (extended) {
|
|
730
|
-
lock.expiresAt = Date.now() + ttlMs;
|
|
731
|
-
if (shouldHeartbeatLock(ttlMs)) startOrUpdateHeartbeat(lock, ttlMs);
|
|
732
|
-
else stopHeartbeat(lock);
|
|
733
|
-
} else stopHeartbeat(lock);
|
|
734
|
-
return extended;
|
|
735
|
-
},
|
|
736
|
-
forceReleaseLock: async (threadId) => {
|
|
737
|
-
stopHeartbeatsForThread(threadId);
|
|
738
|
-
await base.forceReleaseLock(threadId);
|
|
739
|
-
},
|
|
740
|
-
enqueue: (threadId, entry, maxSize) => base.enqueue(threadId, entry, maxSize),
|
|
741
|
-
dequeue: (threadId) => base.dequeue(threadId),
|
|
742
|
-
queueDepth: (threadId) => base.queueDepth(threadId),
|
|
743
|
-
get: (key) => base.get(key),
|
|
744
|
-
getList: (key) => base.getList(key),
|
|
745
|
-
set: (key, value, ttlMs) => base.set(key, value, ttlMs),
|
|
746
|
-
setIfNotExists: (key, value, ttlMs) => base.setIfNotExists(key, value, ttlMs),
|
|
747
|
-
delete: (key) => base.delete(key)
|
|
748
|
-
};
|
|
749
|
-
}
|
|
750
|
-
function withOptionalPrefix(base, prefix) {
|
|
751
|
-
return prefix ? createPrefixedStateAdapter(base, prefix) : base;
|
|
752
|
-
}
|
|
753
|
-
function createStateAdapter() {
|
|
754
|
-
const config = getChatConfig();
|
|
755
|
-
const activeLockMaxAgeMs = config.bot.turnTimeoutMs + ACTIVE_LOCK_TTL_MS;
|
|
756
|
-
if (config.state.adapter === "memory") {
|
|
757
|
-
redisStateAdapter = void 0;
|
|
758
|
-
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(createMemoryState(), config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
759
|
-
}
|
|
760
|
-
if (!config.state.redisUrl) throw new Error("REDIS_URL is required for durable Slack thread state");
|
|
761
|
-
const redisState = createRedisState({
|
|
762
|
-
keyPrefix: REDIS_STATE_KEY_PREFIX,
|
|
763
|
-
url: config.state.redisUrl
|
|
764
|
-
});
|
|
765
|
-
redisStateAdapter = redisState;
|
|
766
|
-
return createQueuedStateAdapter(createConnectingStateAdapter(withOptionalPrefix(redisState, config.state.keyPrefix)), { activeLockMaxAgeMs });
|
|
767
|
-
}
|
|
768
|
-
function getOptionalRedisStateAdapter() {
|
|
769
|
-
getStateAdapter();
|
|
770
|
-
return redisStateAdapter;
|
|
771
|
-
}
|
|
772
|
-
async function getConnectedStateContext() {
|
|
773
|
-
const adapter = getStateAdapter();
|
|
774
|
-
await adapter.connect();
|
|
775
|
-
return {
|
|
776
|
-
redisStateAdapter: getOptionalRedisStateAdapter(),
|
|
777
|
-
stateAdapter: adapter
|
|
778
|
-
};
|
|
779
|
-
}
|
|
780
|
-
/** Return the Redis adapter only when the caller is using the default state adapter. */
|
|
781
|
-
async function getDefaultRedisStateAdapterFor(adapter) {
|
|
782
|
-
if (adapter !== stateAdapter) return;
|
|
783
|
-
const context = await getConnectedStateContext();
|
|
784
|
-
return context.stateAdapter === adapter ? context.redisStateAdapter : void 0;
|
|
785
|
-
}
|
|
786
|
-
/** The Redis key that the default Redis adapter uses for one state value key. */
|
|
787
|
-
function redisStateKey(key) {
|
|
788
|
-
const prefix = getChatConfig().state.keyPrefix;
|
|
789
|
-
return `${REDIS_STATE_KEY_PREFIX}:cache:${prefix ? `${prefix}:` : ""}${key}`;
|
|
790
|
-
}
|
|
791
|
-
/** Read state values in one Redis round trip. Other adapters read each key. */
|
|
792
|
-
async function getStateValues(state, keys) {
|
|
793
|
-
if (keys.length === 0) return [];
|
|
794
|
-
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
795
|
-
if (!redis) return await mapBounded(keys, (key) => state.get(key));
|
|
796
|
-
return (await redis.getClient().mGet(keys.map(redisStateKey))).map((value) => {
|
|
797
|
-
if (value === null) return null;
|
|
798
|
-
try {
|
|
799
|
-
return JSON.parse(value);
|
|
800
|
-
} catch {
|
|
801
|
-
return value;
|
|
802
|
-
}
|
|
803
|
-
});
|
|
804
|
-
}
|
|
805
|
-
/** Write state values with one TTL in one Redis round trip. */
|
|
806
|
-
async function setStateValues(state, entries, ttlMs) {
|
|
807
|
-
if (entries.length === 0) return;
|
|
808
|
-
const redis = await getDefaultRedisStateAdapterFor(state);
|
|
809
|
-
if (!redis) {
|
|
810
|
-
await mapBounded(entries, ({ key, value }) => state.set(key, value, ttlMs));
|
|
811
|
-
return;
|
|
812
|
-
}
|
|
813
|
-
const pipeline = redis.getClient().multi();
|
|
814
|
-
for (const { key, value } of entries) pipeline.set(redisStateKey(key), JSON.stringify(value), { PX: ttlMs });
|
|
815
|
-
await pipeline.execAsPipeline();
|
|
816
|
-
}
|
|
817
|
-
function getStateAdapter() {
|
|
818
|
-
if (!stateAdapter) stateAdapter = createStateAdapter();
|
|
819
|
-
return stateAdapter;
|
|
820
|
-
}
|
|
821
|
-
async function disconnectStateAdapter() {
|
|
822
|
-
if (!stateAdapter) return;
|
|
823
|
-
try {
|
|
824
|
-
await stateAdapter.disconnect();
|
|
825
|
-
} finally {
|
|
826
|
-
stateAdapter = void 0;
|
|
827
|
-
redisStateAdapter = void 0;
|
|
828
|
-
}
|
|
829
|
-
}
|
|
830
|
-
// src/chat/state/cache.ts
|
|
831
|
-
const MAX_CACHE_KEY_LENGTH = 512;
|
|
832
|
-
const LOAD_WAIT_MS = 1e4;
|
|
833
|
-
/** The prefix of every state key of one cache namespace. */
|
|
834
|
-
function cacheKeyPrefix(namespace) {
|
|
835
|
-
return `junior:cache:${namespace}:`;
|
|
836
|
-
}
|
|
837
|
-
/**
|
|
838
|
-
* Create a cache in the state adapter under `junior:cache:{namespace}:`.
|
|
839
|
-
* Entries are wrapped, so `null` and `false` values are cache hits.
|
|
840
|
-
*/
|
|
841
|
-
function createCache(state, namespace) {
|
|
842
|
-
return { async getOrLoad(key, load, options) {
|
|
843
|
-
if (!key.trim()) throw new Error("Cache key is required");
|
|
844
|
-
if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
|
|
845
|
-
const cacheKey = `${cacheKeyPrefix(namespace)}${key}`;
|
|
846
|
-
const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
|
|
847
|
-
await state.connect();
|
|
848
|
-
const hit = await cached();
|
|
849
|
-
if (hit) return hit.value;
|
|
850
|
-
const attempt = await withLock(state, `${cacheKey}:load`, async () => {
|
|
851
|
-
const loadedMeanwhile = await cached();
|
|
852
|
-
if (loadedMeanwhile) return loadedMeanwhile.value;
|
|
853
|
-
const entry = await load();
|
|
854
|
-
if (entry.ttlMs !== void 0) {
|
|
855
|
-
if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
|
|
856
|
-
await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
|
|
857
|
-
}
|
|
858
|
-
return entry.value;
|
|
859
|
-
}, {
|
|
860
|
-
keepAlive: true,
|
|
861
|
-
waitMs: LOAD_WAIT_MS
|
|
862
|
-
});
|
|
863
|
-
if (attempt.acquired) return attempt.value;
|
|
864
|
-
return (await load()).value;
|
|
865
|
-
} };
|
|
1501
|
+
* - The latest Turn failed.
|
|
1502
|
+
* - The latest Brief outcome is `partial` or `blocked`.
|
|
1503
|
+
* - The latest assistant Message is an answer that the starter has not
|
|
1504
|
+
* read. It is an answer when the latest Brief is `answered` or does not
|
|
1505
|
+
* cover it. A `done` Brief that covers it needs no read. The starter read
|
|
1506
|
+
* it when Slack accepted it for a root's Location, when the starter
|
|
1507
|
+
* wrote a later Message, or when their dashboard read position reaches it.
|
|
1508
|
+
* With no starter, nobody reads it, so an answer does not wait.
|
|
1509
|
+
*/
|
|
1510
|
+
function conversationWaitsOnStarterSql(conversation) {
|
|
1511
|
+
const id = conversation.conversationId;
|
|
1512
|
+
const latestBrief = (column) => sql`(select ${column} from ${juniorConversationBriefs} where ${eq(juniorConversationBriefs.conversationId, id)} order by ${desc(juniorConversationBriefs.version)} limit 1)`;
|
|
1513
|
+
const briefStatus = latestBrief(sql`${juniorConversationBriefs.content}->'outcome'->>'status'`);
|
|
1514
|
+
const briefThroughSeq = latestBrief(sql`${juniorConversationBriefs.throughSeq}`);
|
|
1515
|
+
const latestReply = (column) => sql`(select ${column} from ${juniorConversationEvents} where ${and(eq(juniorConversationEvents.conversationId, id), eq(juniorConversationEvents.type, "message"), sql`${juniorConversationEvents.payload}->>'role' = 'assistant'`)} order by ${desc(juniorConversationEvents.seq)} limit 1)`;
|
|
1516
|
+
const replySeq = latestReply(sql`${juniorConversationEvents.seq}`);
|
|
1517
|
+
const replyInSlack = latestReply(sql`coalesce(${juniorConversationEvents.payload}->'meta'->>'source' = 'slack', ${juniorConversationEvents.createdAt} < ${DELIVERY_PAUSE_START})`);
|
|
1518
|
+
const starterUserId = conversationStarterUserIdSql(conversation);
|
|
1519
|
+
const readByStarter = or(and(sql`${conversation.parentConversationId} is null`, sql`${conversation.location} is not null`, sql`coalesce(${replyInSlack}, false)`), sql`exists (select 1 from ${juniorConversationEvents} join ${juniorIdentities} as ${replyReader} on ${eq(replyReader.id, juniorConversationEvents.actorIdentityId)} where ${and(eq(juniorConversationEvents.conversationId, id), eq(juniorConversationEvents.type, "message"), gt(juniorConversationEvents.seq, replySeq), eq(replyReader.userId, starterUserId))})`, sql`exists (select 1 from ${juniorConversationReadPositions} where ${and(eq(juniorConversationReadPositions.conversationId, id), eq(juniorConversationReadPositions.userId, starterUserId), gte(juniorConversationReadPositions.lastReadSeq, replySeq))})`);
|
|
1520
|
+
const unreadAnswer = sql`${replySeq} is not null and ${starterUserId} is not null and (coalesce(${briefStatus}, 'answered') = 'answered' or ${briefThroughSeq} < ${replySeq}) and not (${readByStarter})`;
|
|
1521
|
+
return sql`(${conversation.stoppedAt} is null
|
|
1522
|
+
and ${conversationKindSql(conversation)} <> 'task'
|
|
1523
|
+
and not ${conversationIsActiveSql(conversation)}
|
|
1524
|
+
and (
|
|
1525
|
+
${conversationTurnFailedSql(conversation)}
|
|
1526
|
+
or ${briefStatus} in ('partial', 'blocked')
|
|
1527
|
+
or (${unreadAnswer})
|
|
1528
|
+
))`;
|
|
866
1529
|
}
|
|
867
|
-
// src/chat/identities/user-cache.ts
|
|
868
1530
|
/**
|
|
869
|
-
*
|
|
870
|
-
*
|
|
871
|
-
*
|
|
1531
|
+
* SQL for the status of one Conversation's own work, shared by everyone.
|
|
1532
|
+
* This is the only place that derives it; readers, counts, and feed tokens
|
|
1533
|
+
* select it. When more than one applies: `needs_input` > `working` > `done`.
|
|
872
1534
|
*
|
|
873
|
-
*
|
|
874
|
-
*
|
|
875
|
-
* the
|
|
1535
|
+
* - `needs_input`: an open action Review item that this Conversation added
|
|
1536
|
+
* waits on its assignees or Everyone, a Turn waits on a person to sign in
|
|
1537
|
+
* (`awaitsAuthorization`), or the work waits on its starter
|
|
1538
|
+
* (`conversationWaitsOnStarterSql`).
|
|
1539
|
+
* - `working`: a Turn is queued or running (`conversationIsActiveSql`).
|
|
1540
|
+
* - `done`: anything else, such as a `done` Brief, a read answer, a stop,
|
|
1541
|
+
* or an idle Conversation.
|
|
876
1542
|
*/
|
|
877
|
-
|
|
878
|
-
const
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
avatarUrl: z.string().nullable(),
|
|
885
|
-
displayName: z.string().nullable(),
|
|
886
|
-
handle: z.string().nullable(),
|
|
887
|
-
id: z.string(),
|
|
888
|
-
provider: z.string(),
|
|
889
|
-
providerSubjectId: z.string(),
|
|
890
|
-
providerTenantId: z.string(),
|
|
891
|
-
updatedAt: z.coerce.date()
|
|
892
|
-
})),
|
|
893
|
-
user: z.object({
|
|
894
|
-
displayName: z.string().nullable(),
|
|
895
|
-
id: z.string(),
|
|
896
|
-
isAdmin: z.boolean(),
|
|
897
|
-
primaryEmail: z.string()
|
|
898
|
-
})
|
|
899
|
-
});
|
|
900
|
-
const versionSchema = z.object({
|
|
901
|
-
token: z.string(),
|
|
902
|
-
writtenAtMs: z.number()
|
|
903
|
-
});
|
|
904
|
-
function versionKey(userId) {
|
|
905
|
-
return `${cacheKeyPrefix(USER_CACHE_NAMESPACE)}version:${userId}`;
|
|
906
|
-
}
|
|
907
|
-
function cache() {
|
|
908
|
-
return createCache(getStateAdapter(), USER_CACHE_NAMESPACE);
|
|
909
|
-
}
|
|
910
|
-
async function readVersion(userId) {
|
|
911
|
-
const state = getStateAdapter();
|
|
912
|
-
const stored = versionSchema.safeParse(await state.get(versionKey(userId)));
|
|
913
|
-
if (stored.success) return stored.data;
|
|
914
|
-
const created = {
|
|
915
|
-
token: randomUUID(),
|
|
916
|
-
writtenAtMs: 0
|
|
917
|
-
};
|
|
918
|
-
if (await state.setIfNotExists(versionKey(userId), created, 2 * USER_TTL_MS)) return created;
|
|
919
|
-
return versionSchema.parse(await state.get(versionKey(userId)));
|
|
920
|
-
}
|
|
921
|
-
async function loadUser(db, userId) {
|
|
922
|
-
const rows = await db.select({
|
|
923
|
-
avatarUrl: juniorIdentities.avatarUrl,
|
|
924
|
-
displayName: juniorIdentities.displayName,
|
|
925
|
-
handle: juniorIdentities.handle,
|
|
926
|
-
identityId: juniorIdentities.id,
|
|
927
|
-
provider: juniorIdentities.provider,
|
|
928
|
-
providerSubjectId: juniorIdentities.providerSubjectId,
|
|
929
|
-
providerTenantId: juniorIdentities.providerTenantId,
|
|
930
|
-
updatedAt: juniorIdentities.updatedAt,
|
|
931
|
-
userDisplayName: juniorUsers.displayName,
|
|
932
|
-
userId: juniorUsers.id,
|
|
933
|
-
userIsAdmin: juniorUsers.isAdmin,
|
|
934
|
-
userPrimaryEmail: juniorUsers.primaryEmail
|
|
935
|
-
}).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.id, userId)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
|
|
936
|
-
const first = rows[0];
|
|
937
|
-
if (!first) return null;
|
|
938
|
-
return {
|
|
939
|
-
identities: rows.flatMap((row) => row.identityId && row.provider && row.providerSubjectId && row.providerTenantId !== null && row.updatedAt ? [{
|
|
940
|
-
avatarUrl: row.avatarUrl,
|
|
941
|
-
displayName: row.displayName,
|
|
942
|
-
handle: row.handle,
|
|
943
|
-
id: row.identityId,
|
|
944
|
-
provider: row.provider,
|
|
945
|
-
providerSubjectId: row.providerSubjectId,
|
|
946
|
-
providerTenantId: row.providerTenantId,
|
|
947
|
-
updatedAt: row.updatedAt
|
|
948
|
-
}] : []),
|
|
949
|
-
user: {
|
|
950
|
-
displayName: first.userDisplayName,
|
|
951
|
-
id: first.userId,
|
|
952
|
-
isAdmin: first.userIsAdmin,
|
|
953
|
-
primaryEmail: first.userPrimaryEmail
|
|
954
|
-
}
|
|
955
|
-
};
|
|
956
|
-
}
|
|
957
|
-
/** Read one User and their user Identities by User id. */
|
|
958
|
-
async function readCachedUser(db, userId) {
|
|
959
|
-
const version = await readVersion(userId);
|
|
960
|
-
const settled = Date.now() - version.writtenAtMs >= SETTLE_MS;
|
|
961
|
-
const cached = await cache().getOrLoad(`user:${userId}:${version.token}`, async () => {
|
|
962
|
-
const value = await loadUser(db, userId);
|
|
963
|
-
if (!settled) return { value };
|
|
964
|
-
return {
|
|
965
|
-
value,
|
|
966
|
-
ttlMs: value ? USER_TTL_MS : MISSING_TTL_MS
|
|
967
|
-
};
|
|
968
|
-
});
|
|
969
|
-
return cached ? cachedUserSchema.parse(cached) : void 0;
|
|
1543
|
+
function conversationStatusSql(conversation) {
|
|
1544
|
+
const needsInput = sql`exists (select 1 from ${juniorReviewItems} where ${and(reviewItemOwnedByConversation(conversation.conversationId), reviewItemNeedsInput())})`;
|
|
1545
|
+
return sql`case
|
|
1546
|
+
when ${needsInput} or ${awaitsAuthorization(conversation.conversationId)} or ${conversationWaitsOnStarterSql(conversation)} then 'needs_input'
|
|
1547
|
+
when ${conversationIsActiveSql(conversation)} then 'working'
|
|
1548
|
+
else 'done'
|
|
1549
|
+
end`;
|
|
970
1550
|
}
|
|
971
1551
|
/**
|
|
972
|
-
*
|
|
973
|
-
*
|
|
974
|
-
* A missing User is not cached: a first sign-in can create it at any time.
|
|
1552
|
+
* SQL: the Conversation's work waits on this User as its starter. See
|
|
1553
|
+
* `conversationWaitsOnStarterSql`.
|
|
975
1554
|
*/
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
const id = (await db.select({ id: juniorUsers.id }).from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0]?.id ?? null;
|
|
979
|
-
return id ? {
|
|
980
|
-
value: id,
|
|
981
|
-
ttlMs: USER_TTL_MS
|
|
982
|
-
} : { value: null };
|
|
983
|
-
});
|
|
984
|
-
return userId ? await readCachedUser(db, userId) : void 0;
|
|
985
|
-
}
|
|
986
|
-
function emailKey(normalizedEmail) {
|
|
987
|
-
return `email:${normalizedEmail}`;
|
|
1555
|
+
function conversationWaitsOnUserSql(conversation, userId) {
|
|
1556
|
+
return sql`(${conversationStarterUserIdSql(conversation)} = ${userId} and ${conversationWaitsOnStarterSql(conversation)})`;
|
|
988
1557
|
}
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
1558
|
+
// src/api/conversations/aggregate.ts
|
|
1559
|
+
function usageTokenValue(source, field) {
|
|
1560
|
+
return sql`CASE
|
|
1561
|
+
WHEN ${source.usage}->>${field} IS NOT NULL
|
|
1562
|
+
THEN (${source.usage}->>${field})::double precision
|
|
1563
|
+
ELSE NULL
|
|
1564
|
+
END`;
|
|
995
1565
|
}
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
1566
|
+
function tokenValue(source) {
|
|
1567
|
+
return sql`
|
|
1568
|
+
CASE
|
|
1569
|
+
WHEN COALESCE(
|
|
1570
|
+
${source.usage}->>'inputTokens',
|
|
1571
|
+
${source.usage}->>'outputTokens',
|
|
1572
|
+
${source.usage}->>'cachedInputTokens',
|
|
1573
|
+
${source.usage}->>'cacheCreationTokens'
|
|
1574
|
+
) IS NOT NULL
|
|
1575
|
+
THEN COALESCE((${source.usage}->>'inputTokens')::double precision, 0)
|
|
1576
|
+
+ COALESCE((${source.usage}->>'outputTokens')::double precision, 0)
|
|
1577
|
+
+ COALESCE((${source.usage}->>'cachedInputTokens')::double precision, 0)
|
|
1578
|
+
+ COALESCE((${source.usage}->>'cacheCreationTokens')::double precision, 0)
|
|
1579
|
+
WHEN ${source.usage}->>'totalTokens' IS NOT NULL
|
|
1580
|
+
THEN (${source.usage}->>'totalTokens')::double precision
|
|
1581
|
+
ELSE NULL
|
|
1582
|
+
END
|
|
1583
|
+
`;
|
|
999
1584
|
}
|
|
1000
|
-
function
|
|
1001
|
-
return
|
|
1585
|
+
function costValue(source) {
|
|
1586
|
+
return conversationUsageCostExpr(source.usage);
|
|
1002
1587
|
}
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1588
|
+
/** Read one conversation row's usage cost as a SQL expression. */
|
|
1589
|
+
function conversationUsageCostExpr(usage) {
|
|
1590
|
+
return sql`
|
|
1591
|
+
CASE
|
|
1592
|
+
WHEN ${usage}->'cost'->>'total' IS NOT NULL
|
|
1593
|
+
THEN (${usage}->'cost'->>'total')::double precision
|
|
1594
|
+
WHEN COALESCE(
|
|
1595
|
+
${usage}->'cost'->>'input',
|
|
1596
|
+
${usage}->'cost'->>'output',
|
|
1597
|
+
${usage}->'cost'->>'cacheRead',
|
|
1598
|
+
${usage}->'cost'->>'cacheWrite'
|
|
1599
|
+
) IS NOT NULL
|
|
1600
|
+
THEN COALESCE((${usage}->'cost'->>'input')::double precision, 0)
|
|
1601
|
+
+ COALESCE((${usage}->'cost'->>'output')::double precision, 0)
|
|
1602
|
+
+ COALESCE((${usage}->'cost'->>'cacheRead')::double precision, 0)
|
|
1603
|
+
+ COALESCE((${usage}->'cost'->>'cacheWrite')::double precision, 0)
|
|
1604
|
+
ELSE NULL
|
|
1605
|
+
END
|
|
1606
|
+
`;
|
|
1020
1607
|
}
|
|
1021
|
-
|
|
1022
|
-
|
|
1608
|
+
/** Select complete conversation metrics inside the database instead of materializing source rows. */
|
|
1609
|
+
function conversationAggregateColumns(sources) {
|
|
1610
|
+
const metrics = sources?.metrics ?? juniorConversations;
|
|
1611
|
+
const roots = sources?.roots ?? juniorConversations;
|
|
1612
|
+
const conversationCount = sources ? sql`COUNT(DISTINCT ${roots.conversationId})` : sql`COUNT(*)`;
|
|
1613
|
+
return {
|
|
1614
|
+
active: sql`${conversationCount} FILTER (
|
|
1615
|
+
WHERE ${conversationIsActiveSql(roots)}
|
|
1616
|
+
)::integer`,
|
|
1617
|
+
conversations: sql`${conversationCount}::integer`,
|
|
1618
|
+
cachedInputTokens: sql`SUM(${usageTokenValue(metrics, "cachedInputTokens")})::double precision`,
|
|
1619
|
+
cacheCreationTokens: sql`SUM(${usageTokenValue(metrics, "cacheCreationTokens")})::double precision`,
|
|
1620
|
+
costUsd: sql`SUM(${costValue(metrics)})::double precision`,
|
|
1621
|
+
durationMs: sql`COALESCE(SUM(${metrics.durationMs}), 0)::double precision`,
|
|
1622
|
+
failed: sql`${conversationCount} FILTER (
|
|
1623
|
+
WHERE ${conversationTurnFailedSql(roots)} AND ${roots.stoppedAt} IS NULL
|
|
1624
|
+
)::integer`,
|
|
1625
|
+
inputTokens: sql`SUM(${usageTokenValue(metrics, "inputTokens")})::double precision`,
|
|
1626
|
+
tokens: sql`SUM(${tokenValue(metrics)})::double precision`
|
|
1627
|
+
};
|
|
1023
1628
|
}
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
const email = emailNormalized ? identity.email?.trim() || emailNormalized : void 0;
|
|
1027
|
-
const existing = await existingIdentity(executor, identity);
|
|
1028
|
-
const userEmailNormalized = existing?.emailVerified && existing.emailNormalized ? existing.emailNormalized : identity.emailVerified ? emailNormalized : void 0;
|
|
1029
|
-
const userEmail = existing?.emailVerified && existing.email ? existing.email : email ?? userEmailNormalized;
|
|
1030
|
-
const verifiedUserId = identity.kind === "user" && userEmailNormalized ? await upsertUser(executor, {
|
|
1031
|
-
email: userEmail ?? userEmailNormalized,
|
|
1032
|
-
emailNormalized: userEmailNormalized,
|
|
1033
|
-
nowMs,
|
|
1034
|
-
...existing?.displayName || identity.displayName ? { displayName: existing?.displayName ?? identity.displayName } : void 0
|
|
1035
|
-
}) : void 0;
|
|
1036
|
-
if (existing?.userId && verifiedUserId && existing.userId !== verifiedUserId) throw new Error("Identity verified email conflicts with linked user");
|
|
1037
|
-
if (linkedUserId && verifiedUserId && linkedUserId !== verifiedUserId) throw new Error("Linked identity conflicts with verified email user");
|
|
1038
|
-
if (existing?.userId && linkedUserId && existing.userId !== linkedUserId) throw new Error("Identity conflicts with linked user");
|
|
1039
|
-
const userId = existing?.userId ?? linkedUserId ?? verifiedUserId;
|
|
1040
|
-
const row = (await executor.db().insert(juniorIdentities).values({
|
|
1041
|
-
id: randomUUID(),
|
|
1042
|
-
userId: userId ?? null,
|
|
1043
|
-
kind: identity.kind,
|
|
1044
|
-
provider: identity.provider,
|
|
1045
|
-
providerTenantId: tenantId$1(identity.providerTenantId),
|
|
1046
|
-
providerSubjectId: identity.providerSubjectId,
|
|
1047
|
-
displayName: identity.displayName ?? null,
|
|
1048
|
-
handle: identity.handle ?? null,
|
|
1049
|
-
email: email ?? null,
|
|
1050
|
-
emailNormalized: emailNormalized ?? null,
|
|
1051
|
-
emailVerified: Boolean(identity.emailVerified && emailNormalized),
|
|
1052
|
-
avatarUrl: identity.avatarUrl ?? null,
|
|
1053
|
-
metadata: identity.metadata ?? null,
|
|
1054
|
-
createdAt: dateFromMs$1(nowMs),
|
|
1055
|
-
updatedAt: dateFromMs$1(nowMs)
|
|
1056
|
-
}).onConflictDoUpdate({
|
|
1057
|
-
target: [
|
|
1058
|
-
juniorIdentities.provider,
|
|
1059
|
-
juniorIdentities.providerTenantId,
|
|
1060
|
-
juniorIdentities.providerSubjectId
|
|
1061
|
-
],
|
|
1062
|
-
set: {
|
|
1063
|
-
kind: sql`excluded.kind`,
|
|
1064
|
-
userId: sql`coalesce(${juniorIdentities.userId}, excluded.user_id)`,
|
|
1065
|
-
displayName: linkedUserId ? sql`coalesce(excluded.display_name, ${juniorIdentities.displayName})` : sql`coalesce(${juniorIdentities.displayName}, excluded.display_name)`,
|
|
1066
|
-
handle: linkedUserId ? sql`coalesce(excluded.handle, ${juniorIdentities.handle})` : sql`coalesce(${juniorIdentities.handle}, excluded.handle)`,
|
|
1067
|
-
email: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.email}, excluded.email) when excluded.email_verified then excluded.email else coalesce(${juniorIdentities.email}, excluded.email) end`,
|
|
1068
|
-
emailNormalized: sql`case when ${juniorIdentities.emailVerified} then coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) when excluded.email_verified then excluded.email_normalized else coalesce(${juniorIdentities.emailNormalized}, excluded.email_normalized) end`,
|
|
1069
|
-
emailVerified: sql`${juniorIdentities.emailVerified} OR excluded.email_verified`,
|
|
1070
|
-
avatarUrl: identity.avatarUrl === void 0 ? sql`${juniorIdentities.avatarUrl}` : sql`excluded.avatar_url`,
|
|
1071
|
-
metadata: sql`coalesce(${juniorIdentities.metadata}, excluded.metadata_json)`,
|
|
1072
|
-
updatedAt: sql`excluded.updated_at`
|
|
1073
|
-
},
|
|
1074
|
-
...linkedUserId ? { setWhere: sql`${juniorIdentities.userId} IS NULL OR ${juniorIdentities.userId} = excluded.user_id` } : void 0
|
|
1075
|
-
}).returning({
|
|
1076
|
-
id: juniorIdentities.id,
|
|
1077
|
-
userId: juniorIdentities.userId
|
|
1078
|
-
}))[0];
|
|
1079
|
-
if (!row) {
|
|
1080
|
-
if (linkedUserId) throw new Error("Identity conflicts with linked user");
|
|
1081
|
-
throw new Error("Identity upsert returned no row");
|
|
1082
|
-
}
|
|
1083
|
-
const previousUserId = existing?.userId;
|
|
1084
|
-
await Promise.all([row.userId ? clearCachedUser(row.userId) : void 0, previousUserId && previousUserId !== row.userId ? clearCachedUser(previousUserId) : void 0]);
|
|
1085
|
-
if (!existing?.userId && row.userId && identity.kind === "user") await recordStartedConversationParticipants(executor, {
|
|
1086
|
-
identityId: row.id,
|
|
1087
|
-
userId: row.userId
|
|
1088
|
-
});
|
|
1629
|
+
/** Select the complete first/last activity range for a grouped conversation aggregate. */
|
|
1630
|
+
function conversationRangeColumns() {
|
|
1089
1631
|
return {
|
|
1090
|
-
|
|
1091
|
-
|
|
1632
|
+
firstSeenAt: sql`MIN(${juniorConversations.createdAt})`.mapWith(juniorConversations.createdAt),
|
|
1633
|
+
lastSeenAt: sql`MAX(${juniorConversations.lastActivityAt})`.mapWith(juniorConversations.lastActivityAt)
|
|
1092
1634
|
};
|
|
1093
1635
|
}
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1636
|
+
// src/db/micro-usd.ts
|
|
1637
|
+
/**
|
|
1638
|
+
* Postgres stores every money value as whole micro-USD, in a `bigint` column
|
|
1639
|
+
* or an integer metric value named `*_micro_usd`. Integer sums are exact and
|
|
1640
|
+
* do not depend on row order. Round once where a USD amount is stored, and
|
|
1641
|
+
* convert to USD once where the API returns it. `pnpm money-units:check`
|
|
1642
|
+
* keeps money scales in this file.
|
|
1643
|
+
*/
|
|
1644
|
+
const MICRO_USD_PER_USD = 1e6;
|
|
1645
|
+
/** Round a USD amount to whole micro-USD for storage. */
|
|
1646
|
+
function usdToMicroUsd(usd) {
|
|
1647
|
+
return Math.round(usd * MICRO_USD_PER_USD);
|
|
1097
1648
|
}
|
|
1098
|
-
/**
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
timezone,
|
|
1102
|
-
updatedAt: dateFromMs$1(nowMs)
|
|
1103
|
-
}).where(and(eq(juniorUsers.id, userId), sql`${juniorUsers.timezone} is distinct from ${timezone}`));
|
|
1649
|
+
/** Convert stored micro-USD to USD for an API response. */
|
|
1650
|
+
function microUsdToUsd(microUsd) {
|
|
1651
|
+
return microUsd / MICRO_USD_PER_USD;
|
|
1104
1652
|
}
|
|
1105
|
-
/**
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
teamId: juniorIdentities.providerTenantId,
|
|
1109
|
-
slackUserId: juniorIdentities.providerSubjectId
|
|
1110
|
-
}).from(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.kind, "user"), eq(juniorIdentities.provider, "slack"))).orderBy(desc(juniorIdentities.updatedAt)).limit(1))[0];
|
|
1111
|
-
return row?.teamId ? {
|
|
1112
|
-
teamId: row.teamId,
|
|
1113
|
-
userId: row.slackUserId
|
|
1114
|
-
} : void 0;
|
|
1653
|
+
/** SQL that rounds a USD amount to whole micro-USD. */
|
|
1654
|
+
function usdToMicroUsdSql(usd) {
|
|
1655
|
+
return sql`round(${usd} * 1000000)::bigint`;
|
|
1115
1656
|
}
|
|
1116
|
-
/**
|
|
1117
|
-
|
|
1118
|
-
return
|
|
1657
|
+
/** SQL that converts micro-USD to USD, for usage JSON in USD. */
|
|
1658
|
+
function microUsdToUsdSql(microUsd) {
|
|
1659
|
+
return sql`(${microUsd}) / 1000000.0::double precision`;
|
|
1119
1660
|
}
|
|
1120
1661
|
/**
|
|
1121
|
-
*
|
|
1122
|
-
*
|
|
1123
|
-
* user response, never identity claims inferred from content such as Git commits.
|
|
1662
|
+
* SQL that reads a micro-USD value or sum as an exact integer. Postgres
|
|
1663
|
+
* returns `bigint` as text, so this maps it to a number.
|
|
1124
1664
|
*/
|
|
1125
|
-
|
|
1126
|
-
return
|
|
1665
|
+
function microUsdSql(microUsd) {
|
|
1666
|
+
return sql`(${microUsd})::bigint`.mapWith(Number);
|
|
1127
1667
|
}
|
|
1668
|
+
// src/chat/automations/run-cost.ts
|
|
1128
1669
|
/**
|
|
1129
|
-
*
|
|
1130
|
-
*
|
|
1670
|
+
* SQL for a Conversation's usage cost in whole micro-USD, the unit of a run's
|
|
1671
|
+
* `cost_micro_usd`.
|
|
1131
1672
|
*/
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
normalized.delete("");
|
|
1135
|
-
if (normalized.size === 0) return void 0;
|
|
1136
|
-
const rows = await executor.db().select({
|
|
1137
|
-
email: juniorUsers.primaryEmail,
|
|
1138
|
-
userId: juniorUsers.id
|
|
1139
|
-
}).from(juniorUsers).where(inArray(juniorUsers.primaryEmailNormalized, Array.from(normalized))).limit(2);
|
|
1140
|
-
return rows.length === 1 ? rows[0] : void 0;
|
|
1673
|
+
function costMicroUsdExpr(usage) {
|
|
1674
|
+
return usdToMicroUsdSql(conversationUsageCostExpr(usage));
|
|
1141
1675
|
}
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
}
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1676
|
+
/**
|
|
1677
|
+
* SQL that reads the cost of one Conversation, for the `cost_micro_usd` of its
|
|
1678
|
+
* run. Set it in each run write that links a run to its Conversation, because
|
|
1679
|
+
* the Conversation can record usage before its run row exists.
|
|
1680
|
+
*/
|
|
1681
|
+
function conversationCostOf(conversationId) {
|
|
1682
|
+
return sql`(select ${costMicroUsdExpr(juniorConversations.usage)} from ${juniorConversations} where ${juniorConversations.conversationId} = ${conversationId})`;
|
|
1683
|
+
}
|
|
1684
|
+
// src/chat/conversations/metrics.ts
|
|
1685
|
+
function finite(value) {
|
|
1686
|
+
return value !== void 0 && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
1687
|
+
}
|
|
1688
|
+
/** Convert one Run summary to metric rows. */
|
|
1689
|
+
function conversationMetricValues(args) {
|
|
1690
|
+
const usage = args.usage;
|
|
1691
|
+
const costUsd = agentTurnCostUsd(usage);
|
|
1152
1692
|
return {
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1693
|
+
duration_ms: Math.max(0, args.durationMs),
|
|
1694
|
+
total_tokens: agentTurnTotalTokens(usage),
|
|
1695
|
+
input_tokens: finite(usage?.inputTokens),
|
|
1696
|
+
output_tokens: finite(usage?.outputTokens),
|
|
1697
|
+
cached_input_tokens: finite(usage?.cachedInputTokens),
|
|
1698
|
+
cache_creation_tokens: finite(usage?.cacheCreationTokens),
|
|
1699
|
+
reasoning_tokens: finite(usage?.reasoningTokens),
|
|
1700
|
+
cost_micro_usd: costUsd === void 0 ? void 0 : usdToMicroUsd(costUsd)
|
|
1159
1701
|
};
|
|
1160
1702
|
}
|
|
1161
1703
|
/**
|
|
1162
|
-
*
|
|
1163
|
-
* Identity, and the User behind both.
|
|
1704
|
+
* Read one Run's stored totals from its metric rows.
|
|
1164
1705
|
*
|
|
1165
|
-
*
|
|
1166
|
-
* emails, and display names never match. Return undefined when no Slack user
|
|
1167
|
-
* or more than one Slack user matches.
|
|
1706
|
+
* Returns undefined when the Run has no rows. Cost keeps only its total.
|
|
1168
1707
|
*/
|
|
1169
|
-
async function
|
|
1170
|
-
|
|
1708
|
+
async function readConversationRunMetrics(executor, args) {
|
|
1709
|
+
const rows = await executor.db().select({
|
|
1710
|
+
metric: juniorConversationMetrics.metric,
|
|
1711
|
+
value: juniorConversationMetrics.value
|
|
1712
|
+
}).from(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId)));
|
|
1713
|
+
const values = new Map(rows.map((row) => [row.metric, row.value]));
|
|
1714
|
+
const durationMs = values.get("duration_ms");
|
|
1715
|
+
if (durationMs === void 0) return void 0;
|
|
1716
|
+
const components = {
|
|
1717
|
+
inputTokens: values.get("input_tokens"),
|
|
1718
|
+
outputTokens: values.get("output_tokens"),
|
|
1719
|
+
cachedInputTokens: values.get("cached_input_tokens"),
|
|
1720
|
+
cacheCreationTokens: values.get("cache_creation_tokens")
|
|
1721
|
+
};
|
|
1722
|
+
const hasComponents = Object.values(components).some((value) => value !== void 0);
|
|
1723
|
+
const costMicroUsd = values.get("cost_micro_usd");
|
|
1724
|
+
const usage = Object.fromEntries(Object.entries({
|
|
1725
|
+
...components,
|
|
1726
|
+
reasoningTokens: values.get("reasoning_tokens"),
|
|
1727
|
+
totalTokens: hasComponents ? void 0 : values.get("total_tokens"),
|
|
1728
|
+
cost: costMicroUsd === void 0 ? void 0 : { total: microUsdToUsd(costMicroUsd) }
|
|
1729
|
+
}).filter(([, value]) => value !== void 0));
|
|
1730
|
+
return {
|
|
1731
|
+
durationMs,
|
|
1732
|
+
...Object.keys(usage).length > 0 ? { usage } : void 0
|
|
1733
|
+
};
|
|
1734
|
+
}
|
|
1735
|
+
/** Replace one Run's metric rows and refresh its Conversation totals. */
|
|
1736
|
+
async function replaceConversationMetrics(executor, args) {
|
|
1737
|
+
const [current] = await executor.db().select({ updatedAt: juniorConversationMetrics.updatedAt }).from(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId))).limit(1);
|
|
1738
|
+
if (current && current.updatedAt.getTime() > args.updatedAtMs) return;
|
|
1739
|
+
await executor.db().delete(juniorConversationMetrics).where(and(eq(juniorConversationMetrics.conversationId, args.conversationId), eq(juniorConversationMetrics.runId, args.runId)));
|
|
1740
|
+
const metricValues = conversationMetricValues({
|
|
1741
|
+
durationMs: args.durationMs,
|
|
1742
|
+
usage: args.usage
|
|
1743
|
+
});
|
|
1744
|
+
const values = CONVERSATION_METRICS.flatMap((metric) => {
|
|
1745
|
+
const value = metricValues[metric];
|
|
1746
|
+
return value === void 0 ? [] : [{
|
|
1747
|
+
actorIdentityId: args.actorIdentityId ?? null,
|
|
1748
|
+
conversationId: args.conversationId,
|
|
1749
|
+
runId: args.runId,
|
|
1750
|
+
metric,
|
|
1751
|
+
value,
|
|
1752
|
+
occurredAt: new Date(args.occurredAtMs),
|
|
1753
|
+
updatedAt: new Date(args.updatedAtMs)
|
|
1754
|
+
}];
|
|
1755
|
+
});
|
|
1756
|
+
if (values.length > 0) await executor.db().insert(juniorConversationMetrics).values(values);
|
|
1757
|
+
const metric = (name) => sql`(
|
|
1758
|
+
select sum(${juniorConversationMetrics.value})
|
|
1759
|
+
from ${juniorConversationMetrics}
|
|
1760
|
+
where ${juniorConversationMetrics.conversationId} = ${args.conversationId}
|
|
1761
|
+
and ${juniorConversationMetrics.metric} = ${name}
|
|
1762
|
+
)`;
|
|
1763
|
+
const totalTokens = metric("total_tokens");
|
|
1764
|
+
const componentTokens = sql`
|
|
1765
|
+
coalesce(${metric("input_tokens")}, 0)
|
|
1766
|
+
+ coalesce(${metric("output_tokens")}, 0)
|
|
1767
|
+
+ coalesce(${metric("cached_input_tokens")}, 0)
|
|
1768
|
+
+ coalesce(${metric("cache_creation_tokens")}, 0)
|
|
1769
|
+
`;
|
|
1770
|
+
const hasComponents = sql`
|
|
1771
|
+
${metric("input_tokens")} is not null
|
|
1772
|
+
or ${metric("output_tokens")} is not null
|
|
1773
|
+
or ${metric("cached_input_tokens")} is not null
|
|
1774
|
+
or ${metric("cache_creation_tokens")} is not null
|
|
1775
|
+
`;
|
|
1776
|
+
const cost = sql`case when ${metric("cost_micro_usd")} is null then null
|
|
1777
|
+
else jsonb_build_object('total', ${microUsdToUsdSql(metric("cost_micro_usd"))}) end`;
|
|
1778
|
+
const db = executor.db();
|
|
1779
|
+
const usageUpdate = db.$with("conversation_usage_update").as(db.update(juniorConversations).set({
|
|
1780
|
+
durationMs: sql`coalesce(${metric("duration_ms")}, 0)`,
|
|
1781
|
+
usage: sql`case
|
|
1782
|
+
when ${totalTokens} is not null
|
|
1783
|
+
and (${hasComponents})
|
|
1784
|
+
and ${totalTokens} <> ${componentTokens}
|
|
1785
|
+
then jsonb_strip_nulls(jsonb_build_object(
|
|
1786
|
+
'totalTokens', ${totalTokens},
|
|
1787
|
+
'reasoningTokens', ${metric("reasoning_tokens")},
|
|
1788
|
+
'cost', ${cost}
|
|
1789
|
+
))
|
|
1790
|
+
else jsonb_strip_nulls(jsonb_build_object(
|
|
1791
|
+
'totalTokens', ${totalTokens},
|
|
1792
|
+
'inputTokens', ${metric("input_tokens")},
|
|
1793
|
+
'outputTokens', ${metric("output_tokens")},
|
|
1794
|
+
'cachedInputTokens', ${metric("cached_input_tokens")},
|
|
1795
|
+
'cacheCreationTokens', ${metric("cache_creation_tokens")},
|
|
1796
|
+
'reasoningTokens', ${metric("reasoning_tokens")},
|
|
1797
|
+
'cost', ${cost}
|
|
1798
|
+
))
|
|
1799
|
+
end`,
|
|
1800
|
+
detailVersion: nextDetailVersion
|
|
1801
|
+
}).where(eq(juniorConversations.conversationId, args.conversationId)).returning({ costMicroUsd: costMicroUsdExpr(juniorConversations.usage).as("cost_micro_usd") }));
|
|
1802
|
+
await db.with(usageUpdate).update(juniorAutomationRuns).set({ costMicroUsd: sql`(select ${usageUpdate.costMicroUsd} from ${usageUpdate})` }).where(eq(juniorAutomationRuns.conversationId, args.conversationId));
|
|
1171
1803
|
}
|
|
1804
|
+
// src/chat/source.ts
|
|
1172
1805
|
/**
|
|
1173
|
-
*
|
|
1174
|
-
*
|
|
1175
|
-
* The caller must have verified that the person sent from this address.
|
|
1176
|
-
* Return undefined when no Slack user or more than one Slack user matches.
|
|
1806
|
+
* Normalize a Turn Source into legacy provider fields stored on a Conversation.
|
|
1807
|
+
* System Sources do not contain a Conversation Location.
|
|
1177
1808
|
*/
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1809
|
+
function normalizeSessionSource(value) {
|
|
1810
|
+
if (!value) return;
|
|
1811
|
+
if (value.kind === "local") return {
|
|
1812
|
+
kind: "local",
|
|
1813
|
+
visibility: value.visibility,
|
|
1814
|
+
conversationId: value.conversationId
|
|
1815
|
+
};
|
|
1816
|
+
if (value.kind === "web") return {
|
|
1817
|
+
kind: "web",
|
|
1818
|
+
visibility: value.visibility,
|
|
1819
|
+
conversationId: value.conversationId
|
|
1820
|
+
};
|
|
1821
|
+
if (value.kind === "event" || value.kind === "scheduled_automation" || value.kind === "event_automation" || value.kind === "plugin_dispatch" || value.kind === "agent_invocation") return;
|
|
1822
|
+
const threadTs = value.threadTs?.trim();
|
|
1823
|
+
return {
|
|
1824
|
+
kind: "slack",
|
|
1825
|
+
visibility: value.visibility,
|
|
1826
|
+
teamId: value.teamId,
|
|
1827
|
+
channelId: value.channelId,
|
|
1828
|
+
...threadTs ? { threadTs } : void 0
|
|
1829
|
+
};
|
|
1186
1830
|
}
|
|
1187
|
-
/**
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1831
|
+
/** Parse a serialized Source into legacy provider fields stored on a Conversation. */
|
|
1832
|
+
function parseSessionSource(value) {
|
|
1833
|
+
const parsed = sourceSchema.safeParse(value);
|
|
1834
|
+
return parsed.success ? normalizeSessionSource(parsed.data) : void 0;
|
|
1191
1835
|
}
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
*/
|
|
1197
|
-
async function recordGoogleSignIn(executor, account, nowMs = Date.now()) {
|
|
1198
|
-
const stored = await upsertIdentity(executor, {
|
|
1199
|
-
kind: "user",
|
|
1200
|
-
provider: GOOGLE_IDENTITY_PROVIDER,
|
|
1201
|
-
providerSubjectId: account.subject,
|
|
1202
|
-
email: account.email,
|
|
1203
|
-
emailVerified: true,
|
|
1204
|
-
displayName: account.displayName,
|
|
1205
|
-
avatarUrl: account.avatarUrl ?? null
|
|
1206
|
-
}, nowMs);
|
|
1207
|
-
const [previous] = await executor.db().select({ signedInAt: juniorIdentities.signedInAt }).from(juniorIdentities).where(eq(juniorIdentities.id, stored.id)).limit(1);
|
|
1208
|
-
await executor.db().update(juniorIdentities).set({ signedInAt: dateFromMs$1(nowMs) }).where(eq(juniorIdentities.id, stored.id));
|
|
1209
|
-
return previous?.signedInAt?.getTime();
|
|
1836
|
+
// src/chat/conversations/sql/bindings.ts
|
|
1837
|
+
/** Resolve the durable conversation bound to provider-owned coordinates. */
|
|
1838
|
+
async function getConversationIdByProviderConversation(executor, args) {
|
|
1839
|
+
return (await executor.db().select({ conversationId: juniorConversationBindings.conversationId }).from(juniorConversationBindings).where(and(eq(juniorConversationBindings.provider, args.provider), eq(juniorConversationBindings.providerTenantId, args.providerTenantId), eq(juniorConversationBindings.providerDestinationId, args.providerDestinationId), eq(juniorConversationBindings.providerConversationId, args.providerConversationId))).limit(1))[0]?.conversationId;
|
|
1210
1840
|
}
|
|
1211
|
-
// src/chat/identities/actor.ts
|
|
1212
|
-
/**
|
|
1213
|
-
* Resolve runtime Actors to the Identity rows that Junior stores for them.
|
|
1214
|
-
*
|
|
1215
|
-
* The Conversation store, OAuth, the viewer, and message events use this
|
|
1216
|
-
* module, so they agree on one Identity per person. The key for each Actor
|
|
1217
|
-
* stays private here, so it can change without changing callers.
|
|
1218
|
-
*/
|
|
1219
|
-
/**
|
|
1220
|
-
* The fixed id of the one system Identity: kind `system`, provider `junior`,
|
|
1221
|
-
* an empty tenant, and subject `system`. A migration creates the row, so
|
|
1222
|
-
* callers use this id without a database read.
|
|
1223
|
-
*/
|
|
1224
|
-
const SYSTEM_IDENTITY_ID = "system";
|
|
1225
1841
|
/**
|
|
1226
|
-
*
|
|
1227
|
-
*
|
|
1228
|
-
* `SystemActor.name` is provenance, not part of the Identity. A LocalActor
|
|
1229
|
-
* uses the system Identity because the local runner has no per-person user id.
|
|
1842
|
+
* Bind provider coordinates to a durable conversation unless another
|
|
1843
|
+
* conversation has them. Return the conversation that has them.
|
|
1230
1844
|
*/
|
|
1231
|
-
function
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
kind: "user",
|
|
1239
|
-
provider: "slack",
|
|
1240
|
-
providerTenantId: actor.teamId,
|
|
1241
|
-
providerSubjectId: actor.userId,
|
|
1242
|
-
...actor.fullName ? { displayName: actor.fullName } : void 0,
|
|
1243
|
-
...actor.userName ? { handle: actor.userName } : void 0,
|
|
1244
|
-
...actor.email ? {
|
|
1245
|
-
email: actor.email,
|
|
1246
|
-
emailVerified: true
|
|
1247
|
-
} : void 0,
|
|
1248
|
-
metadata: { platform: "slack" }
|
|
1249
|
-
};
|
|
1250
|
-
case "web": {
|
|
1251
|
-
const email = normalizeIdentityEmail(actor.email);
|
|
1252
|
-
if (!email) return;
|
|
1253
|
-
return {
|
|
1254
|
-
kind: "user",
|
|
1255
|
-
provider: "junior",
|
|
1256
|
-
providerSubjectId: email,
|
|
1257
|
-
email,
|
|
1258
|
-
emailVerified: true,
|
|
1259
|
-
...actor.fullName ? { displayName: actor.fullName } : void 0,
|
|
1260
|
-
metadata: { platform: "web" }
|
|
1261
|
-
};
|
|
1262
|
-
}
|
|
1263
|
-
}
|
|
1845
|
+
async function claimProviderConversationOwner(executor, args) {
|
|
1846
|
+
const ownerId = (await executor.db().insert(juniorConversationBindings).values({
|
|
1847
|
+
...args,
|
|
1848
|
+
createdAt: /* @__PURE__ */ new Date()
|
|
1849
|
+
}).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args);
|
|
1850
|
+
if (!ownerId) throw new Error("Provider conversation binding disappeared during claim");
|
|
1851
|
+
return ownerId;
|
|
1264
1852
|
}
|
|
1265
1853
|
/**
|
|
1266
|
-
*
|
|
1267
|
-
*
|
|
1854
|
+
* Bind provider coordinates to a durable conversation unless another
|
|
1855
|
+
* conversation has them. Return whether they belong to this conversation.
|
|
1268
1856
|
*/
|
|
1269
|
-
async function
|
|
1270
|
-
|
|
1271
|
-
const key = identityKey(actor);
|
|
1272
|
-
return key ? (await upsertIdentity(executor, key, nowMs)).id : void 0;
|
|
1273
|
-
}
|
|
1274
|
-
/** Save the profile photo on the Identity of one Slack Actor. Null clears it. */
|
|
1275
|
-
async function saveActorAvatar(executor, actor, avatarUrl, nowMs = Date.now()) {
|
|
1276
|
-
const key = identityKey(actor);
|
|
1277
|
-
if (key) await upsertIdentity(executor, {
|
|
1278
|
-
...key,
|
|
1279
|
-
avatarUrl
|
|
1280
|
-
}, nowMs);
|
|
1857
|
+
async function claimProviderConversation(executor, args) {
|
|
1858
|
+
return await claimProviderConversationOwner(executor, args) === args.conversationId;
|
|
1281
1859
|
}
|
|
1282
|
-
/**
|
|
1283
|
-
async function
|
|
1284
|
-
if (
|
|
1285
|
-
const key = identityKey(actor);
|
|
1286
|
-
if (!key) return;
|
|
1287
|
-
return (await db.select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, key.provider), eq(juniorIdentities.providerTenantId, key.providerTenantId ?? ""), eq(juniorIdentities.providerSubjectId, key.providerSubjectId))).limit(1))[0]?.id;
|
|
1860
|
+
/** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
|
|
1861
|
+
async function bindProviderConversation(executor, args) {
|
|
1862
|
+
if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
|
|
1288
1863
|
}
|
|
1289
1864
|
// src/chat/conversations/sql/actor-identity.ts
|
|
1290
1865
|
/**
|
|
@@ -1460,56 +2035,6 @@ async function startLocationThread(executor, binding) {
|
|
|
1460
2035
|
detailVersion: nextDetailVersion
|
|
1461
2036
|
}).where(and(eq(juniorConversations.conversationId, binding.conversationId), sql`${location}->>'provider' = ${binding.provider}`, sql`${location}->>'teamId' = ${binding.providerTenantId}`, sql`${location}->>'channelId' = ${binding.providerDestinationId}`, isNull(sql`${location}->>'threadTs'`)));
|
|
1462
2037
|
}
|
|
1463
|
-
// src/chat/conversations/sql/conversation-row.ts
|
|
1464
|
-
/**
|
|
1465
|
-
* Establish the conversation metadata row on first contact for content writes
|
|
1466
|
-
* (conversation events, visible transcript) that can land before activity has
|
|
1467
|
-
* created the row, and whose tables FK to it.
|
|
1468
|
-
*
|
|
1469
|
-
* First contact creates the row; every later content write advances the
|
|
1470
|
-
* activity clock so retention mirrors append-refresh semantics (each content
|
|
1471
|
-
* append refreshes the retention window). Background observations may opt out
|
|
1472
|
-
* and leave an existing row unchanged. The timestamp is content-intrinsic (the
|
|
1473
|
-
* first item's `createdAtMs`), and `greatest(...)` guarantees a backfilled or
|
|
1474
|
-
* imported historical write — which carries an old timestamp — can never
|
|
1475
|
-
* regress `last_activity_at`.
|
|
1476
|
-
*/
|
|
1477
|
-
async function ensureConversationRow(executor, conversationId, atMs, options = {}) {
|
|
1478
|
-
const at = new Date(atMs);
|
|
1479
|
-
const insert = executor.db().insert(juniorConversations).values({
|
|
1480
|
-
conversationId,
|
|
1481
|
-
createdAt: at,
|
|
1482
|
-
lastActivityAt: at,
|
|
1483
|
-
updatedAt: at,
|
|
1484
|
-
executionStatus: "idle",
|
|
1485
|
-
kind: "root"
|
|
1486
|
-
});
|
|
1487
|
-
if (options.activity === "preserve") {
|
|
1488
|
-
await insert.onConflictDoNothing({ target: juniorConversations.conversationId });
|
|
1489
|
-
return;
|
|
1490
|
-
}
|
|
1491
|
-
await insert.onConflictDoUpdate({
|
|
1492
|
-
target: juniorConversations.conversationId,
|
|
1493
|
-
set: {
|
|
1494
|
-
lastActivityAt: sql`greatest(${juniorConversations.lastActivityAt}, excluded.last_activity_at)`,
|
|
1495
|
-
updatedAt: sql`greatest(${juniorConversations.updatedAt}, excluded.updated_at)`,
|
|
1496
|
-
transcriptPurgedAt: null,
|
|
1497
|
-
detailVersion: nextDetailVersion
|
|
1498
|
-
}
|
|
1499
|
-
});
|
|
1500
|
-
}
|
|
1501
|
-
const CONVERSATION_KINDS = /* @__PURE__ */ new Set([
|
|
1502
|
-
"root",
|
|
1503
|
-
"automation",
|
|
1504
|
-
"thread",
|
|
1505
|
-
"task"
|
|
1506
|
-
]);
|
|
1507
|
-
/** Decode a stored kind. A null kind comes from a writer of an older deploy. */
|
|
1508
|
-
function conversationKindFromRow(row) {
|
|
1509
|
-
const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
|
|
1510
|
-
if (!CONVERSATION_KINDS.has(kind)) throw new Error("Conversation record kind is invalid");
|
|
1511
|
-
return kind;
|
|
1512
|
-
}
|
|
1513
2038
|
// src/chat/conversations/kind-behavior.ts
|
|
1514
2039
|
const ROOT = {
|
|
1515
2040
|
delivery: "location",
|
|
@@ -1521,7 +2046,7 @@ const ROOT = {
|
|
|
1521
2046
|
sessionTasks: true,
|
|
1522
2047
|
tools: {
|
|
1523
2048
|
agents: "children",
|
|
1524
|
-
|
|
2049
|
+
inbox: true,
|
|
1525
2050
|
subscriptions: true,
|
|
1526
2051
|
userCustomization: true,
|
|
1527
2052
|
reply: "none",
|
|
@@ -1549,7 +2074,7 @@ const CHILD_AGENT_TURN = {
|
|
|
1549
2074
|
sessionTasks: false,
|
|
1550
2075
|
tools: {
|
|
1551
2076
|
agents: "children_and_parent",
|
|
1552
|
-
|
|
2077
|
+
inbox: false,
|
|
1553
2078
|
subscriptions: false,
|
|
1554
2079
|
userCustomization: false,
|
|
1555
2080
|
reply: "parent",
|
|
@@ -1564,7 +2089,7 @@ const AGENT_IN_THREAD = {
|
|
|
1564
2089
|
};
|
|
1565
2090
|
const THREAD_TOOLS = {
|
|
1566
2091
|
...AGENT_IN_THREAD.tools,
|
|
1567
|
-
|
|
2092
|
+
inbox: PERSON_IN_THREAD.tools.inbox,
|
|
1568
2093
|
subscriptions: PERSON_IN_THREAD.tools.subscriptions,
|
|
1569
2094
|
userCustomization: PERSON_IN_THREAD.tools.userCustomization
|
|
1570
2095
|
};
|
|
@@ -1620,6 +2145,39 @@ function isTopLevelKind(kind) {
|
|
|
1620
2145
|
function isPersonInput(source) {
|
|
1621
2146
|
return source === "web" || source === "slack";
|
|
1622
2147
|
}
|
|
2148
|
+
/** Narrow a Source to one that a person sent input from. */
|
|
2149
|
+
function isPersonSource(source) {
|
|
2150
|
+
return isPersonInput(source.kind);
|
|
2151
|
+
}
|
|
2152
|
+
/**
|
|
2153
|
+
* Return the chat platform of a Source that a person writes from, or
|
|
2154
|
+
* undefined for a runtime Source, such as an event or an Automation.
|
|
2155
|
+
*/
|
|
2156
|
+
function personSourcePlatform(source) {
|
|
2157
|
+
switch (source.kind) {
|
|
2158
|
+
case "slack":
|
|
2159
|
+
case "local":
|
|
2160
|
+
case "web": return source.kind;
|
|
2161
|
+
case "event":
|
|
2162
|
+
case "scheduled_automation":
|
|
2163
|
+
case "event_automation":
|
|
2164
|
+
case "plugin_dispatch":
|
|
2165
|
+
case "agent_invocation": return;
|
|
2166
|
+
}
|
|
2167
|
+
}
|
|
2168
|
+
/** Return a short label that names a Source, such as `slack:T1:C1`. */
|
|
2169
|
+
function sourceLabel(source) {
|
|
2170
|
+
switch (source.kind) {
|
|
2171
|
+
case "slack": return `slack:${source.teamId}:${source.channelId}`;
|
|
2172
|
+
case "web":
|
|
2173
|
+
case "local": return `${source.kind}:${source.conversationId}`;
|
|
2174
|
+
case "event": return `event:${source.namespace}:${source.eventKey}`;
|
|
2175
|
+
case "scheduled_automation":
|
|
2176
|
+
case "event_automation":
|
|
2177
|
+
case "plugin_dispatch":
|
|
2178
|
+
case "agent_invocation": return source.kind;
|
|
2179
|
+
}
|
|
2180
|
+
}
|
|
1623
2181
|
/**
|
|
1624
2182
|
* Return whether the runtime delivers the final response of a Slack or
|
|
1625
2183
|
* dispatch run. Only root Conversations reach these paths, so only an
|
|
@@ -1753,6 +2311,7 @@ function conversationFromRow(readRow) {
|
|
|
1753
2311
|
},
|
|
1754
2312
|
kind: conversationKindFromRow(row),
|
|
1755
2313
|
...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
|
|
2314
|
+
...row.rootConversationId ? { rootConversationId: row.rootConversationId } : void 0,
|
|
1756
2315
|
...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
|
|
1757
2316
|
...destination ? { destination } : void 0,
|
|
1758
2317
|
...location ? { location } : void 0,
|
|
@@ -2149,19 +2708,15 @@ async function refreshLastMessageAt(executor, conversationId) {
|
|
|
2149
2708
|
await db.update(juniorConversations).set({ lastMessageAt: lastMessageAtSql(db) }).where(eq(juniorConversations.conversationId, conversationId));
|
|
2150
2709
|
}
|
|
2151
2710
|
// src/chat/conversations/sql/event-actor.ts
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2711
|
+
const authorMetaSchema = z.object({ author: z.object({
|
|
2712
|
+
email: z.string().optional().catch(void 0),
|
|
2713
|
+
fullName: z.string().optional().catch(void 0),
|
|
2714
|
+
isBot: z.boolean().optional().catch(void 0),
|
|
2715
|
+
userId: z.string().optional().catch(void 0),
|
|
2716
|
+
userName: z.string().optional().catch(void 0)
|
|
2717
|
+
}) });
|
|
2155
2718
|
function readAuthor(meta) {
|
|
2156
|
-
|
|
2157
|
-
const author = meta["author"];
|
|
2158
|
-
return {
|
|
2159
|
-
...typeof author["email"] === "string" ? { email: author["email"] } : void 0,
|
|
2160
|
-
...typeof author["fullName"] === "string" ? { fullName: author["fullName"] } : void 0,
|
|
2161
|
-
...typeof author["isBot"] === "boolean" ? { isBot: author["isBot"] } : void 0,
|
|
2162
|
-
...typeof author["userId"] === "string" ? { userId: author["userId"] } : void 0,
|
|
2163
|
-
...typeof author["userName"] === "string" ? { userName: author["userName"] } : void 0
|
|
2164
|
-
};
|
|
2719
|
+
return authorMetaSchema.safeParse(meta).data?.author ?? {};
|
|
2165
2720
|
}
|
|
2166
2721
|
/** Read the Slack workspace that owns a conversation, when it has one. */
|
|
2167
2722
|
async function loadConversationSlackTenantId(executor, conversationId) {
|
|
@@ -2177,12 +2732,19 @@ async function loadConversationSlackTenantIds(executor, conversationIds) {
|
|
|
2177
2732
|
}).from(juniorConversations).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(inArray(juniorConversations.conversationId, [...conversationIds]));
|
|
2178
2733
|
const tenants = /* @__PURE__ */ new Map();
|
|
2179
2734
|
for (const row of rows) {
|
|
2180
|
-
const
|
|
2181
|
-
const tenantId = row.providerTenantId?.trim() || (sessionSource?.kind === "slack" ? sessionSource.teamId : void 0);
|
|
2735
|
+
const tenantId = conversationSlackTenantId(row);
|
|
2182
2736
|
if (tenantId) tenants.set(row.conversationId, tenantId);
|
|
2183
2737
|
}
|
|
2184
2738
|
return tenants;
|
|
2185
2739
|
}
|
|
2740
|
+
/**
|
|
2741
|
+
* Return the Slack workspace that owns a conversation, from its Destination
|
|
2742
|
+
* tenant or its stored Slack session source.
|
|
2743
|
+
*/
|
|
2744
|
+
function conversationSlackTenantId(row) {
|
|
2745
|
+
const sessionSource = parseSessionSource(row.sessionSource);
|
|
2746
|
+
return row.providerTenantId?.trim() || (sessionSource?.kind === "slack" ? sessionSource.teamId : void 0);
|
|
2747
|
+
}
|
|
2186
2748
|
async function findIdentityIdByProviderSubject(executor, args) {
|
|
2187
2749
|
return (await executor.db().select({ id: juniorIdentities.id }).from(juniorIdentities).where(and(eq(juniorIdentities.provider, args.provider), eq(juniorIdentities.providerSubjectId, args.providerSubjectId), args.providerTenantId === void 0 ? void 0 : eq(juniorIdentities.providerTenantId, args.providerTenantId))).limit(1))[0]?.id;
|
|
2188
2750
|
}
|
|
@@ -2276,13 +2838,15 @@ async function readConversationTrees(db, rootConversationIds) {
|
|
|
2276
2838
|
archivedAt: juniorConversations.archivedAt,
|
|
2277
2839
|
conversationId: juniorConversations.conversationId,
|
|
2278
2840
|
kind: juniorConversations.kind,
|
|
2279
|
-
parentConversationId: juniorConversations.parentConversationId
|
|
2841
|
+
parentConversationId: juniorConversations.parentConversationId,
|
|
2842
|
+
rootConversationId: juniorConversations.rootConversationId
|
|
2280
2843
|
}).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, [...rootConversationIds]));
|
|
2281
2844
|
return new Map(rows.map((row) => [row.conversationId, {
|
|
2282
2845
|
archivedAt: row.archivedAt,
|
|
2283
2846
|
conversationId: row.conversationId,
|
|
2284
2847
|
kind: conversationKindFromRow(row),
|
|
2285
|
-
...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
|
|
2848
|
+
...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
|
|
2849
|
+
...row.rootConversationId ? { rootConversationId: row.rootConversationId } : void 0
|
|
2286
2850
|
}]));
|
|
2287
2851
|
}
|
|
2288
2852
|
/** List the ancestors of one Conversation, nearest first, root last. */
|
|
@@ -2733,6 +3297,11 @@ var SqlConversationEventStore = class {
|
|
|
2733
3297
|
async loadEventsOfType(conversationId, type) {
|
|
2734
3298
|
return (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, type))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
|
|
2735
3299
|
}
|
|
3300
|
+
async loadCurrentEventsOfType(conversationId, type) {
|
|
3301
|
+
const db = this.executor.db();
|
|
3302
|
+
const currentHistoryVersion = db.select({ historyVersion: sql`max(${juniorConversationEvents.historyVersion})` }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
|
|
3303
|
+
return (await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, currentHistoryVersion), eq(juniorConversationEvents.type, type))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow);
|
|
3304
|
+
}
|
|
2736
3305
|
async query(conversationId, query) {
|
|
2737
3306
|
if (query.limit < 1) throw new Error("Conversation event query limit must be at least 1");
|
|
2738
3307
|
if (query.afterSeq !== void 0 && query.beforeSeq !== void 0 && query.afterSeq >= query.beforeSeq) return {
|
|
@@ -2954,4 +3523,4 @@ async function closeDb() {
|
|
|
2954
3523
|
current = void 0;
|
|
2955
3524
|
await previous?.db.close();
|
|
2956
3525
|
}
|
|
2957
|
-
export {
|
|
3526
|
+
export { conversationKindFromRow as $, deleteProviderIdentityForUser as $t, personSourcePlatform as A, rootConversationIsArchived as An, resolveAssignees as At, parseSessionSource as B, setUserAdminFromSql as Bt, createSqlStore as C, viewerMarksFromParticipant as Cn, reviewItemReaderForUser as Ct, isPersonInput as D, agentTurnUsageSchema as Dn, activeParticipantUserIds as Dt, dispatchInstructionsInvokeSkills as E, agentTurnTotalTokens as En, EVERYONE_ASSIGNEE as Et, locationFromRow as F, parseDestination as Fn, readActorIdentityFromSql as Ft, conversationAggregateColumns as G, readAvatarFetch as Gt, microUsdSql as H, hasUserPhoto as Ht, setFirstConversationLocation as I, requireSlackDestination as In, readIdentityById as It, conversationIsActiveSql as J, userAvatarUrlsFromJoinedPhotos as Jt, conversationRangeColumns as K, readUserAvatarUrls as Kt, startLocationThread as L, sameDestination as Ln, readIdentityByIdFromSql as Lt, promptModeTurnTools as M, nextDetailVersion as Mn, findUserByEmailFromSql as Mt, sourceLabel as N, touchConversationDetail as Nn, listAdminUsersFromSql as Nt, isPersonSource as O, hasAgentTurnUsage as On, automationCreatorUserId as Ot, turnBehavior as P, createSlackDestination as Pn, readActorIdentity as Pt, executionIsActive as Q, deleteProviderIdentityForSlackUser as Qt, claimProviderConversation as R, readViewerAvatarUrl as Rt, userMessageQueries as S, rootVisibleToViewer as Sn, reviewItemPlugin as St, deliversFinalText as T, agentTurnCostUsd as Tn, reviewItemVisibleTo as Tt, microUsdToUsd as U, identityAvatarUrl as Ut, conversationCostOf as V, updateViewerDisplayName as Vt, usdToMicroUsd as W, parseAvatarUrl as Wt, conversationTurnFailedSql as X, resolveActorIdentityId as Xt, conversationStatusSql as Y, SYSTEM_IDENTITY_ID as Yt, conversationWaitsOnUserSql as Z, saveActorAvatar as Zt, readConversationTrees as _, readableSlackTeamId as _n, reviewItemLinkedTo as _t, getConversationStore as a, recordGoogleSignIn as an, canAgentChangeReviewItem as at, loadConversationSlackTenantIds as b, conversationPinnedForUser as bn, reviewItemNeedsUser as bt, hasAnnotationKey as c, readCachedUserByEmail as cn, isAutomationAlertItem as ct, eventFromRow as d, canAccessConversation as dn, itemNeedsUser as dt, findLinkedSlackUser as en, awaitsAuthorizationFrom as et, copyMessageLinks as f, canAddConversationMessages as fn, readReviewItemAgentScope as ft, conversationDescendants as g, readConversationAccessRows as gn, reviewItemForUser as gt, conversationAncestors as h, readConversationAccessFromSql as hn, reviewItemAssignedTo as ht, getConversationMessageSearchStore as i, readUserTimezone as in, canActOnReviewItem as it, postsRunNotices as j, conversationDetailTouch as jn, findUserByEmail as jt, isTopLevelKind as k, resolveRootConversationId as kn, resolveAssignee as kt, treeHasAnnotationKey as l, ToolInputError as ln, isOnlyAssignee as lt, withConversationEventLock as m, createConversationAccessReader as mn, requireReviewItemLinks as mt, db_exports as n, findUserByVerifiedEmails as nn, AUTOMATION_REVIEW_ITEM_KEY_PREFIX as nt, getDb as o, saveUserTimezone as on, canReadReviewItem as ot, deleteMessageLinks as p, conversationAccessFromRows as pn, requireReviewItemAssignees as pt, conversationUsageCostExpr as q, userAvatarUrlsFromIdentities as qt, getConversationEventStore as r, linkedSlackUser as rn, PLUGIN_REVIEW_ITEM_KEY_PREFIX as rt, getSqlExecutor as s, upsertLinkedIdentity as sn, canUserReadReviewItem as st, closeDb as t, findSlackUserByPrimaryEmail as tn, treeAwaitsAuthorization as tt, createSqlConversationEventStore as u, isToolInputError as un, isPluginReviewItem as ut, setArchivedAt as v, conversationIsMemberRoot as vn, reviewItemNeedsInput as vt, withConversationMutationLock as w, addAgentTurnUsage as wn, reviewItemReaderForUserInConversation as wt, lastMessageAtSql as x, readMemberParticipants as xn, reviewItemOwnedByConversation as xt, conversationSlackTenantId as y, conversationIsNotUnsubscribedRoot as yn, reviewItemNeedsSomeone as yt, getConversationIdByProviderConversation as z, resolveViewerUser as zt };
|