@sentry/junior 0.286.0 → 0.287.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.
Files changed (69) hide show
  1. package/dist/{adapter-JQZaJ-B_.js → adapter-CL-HUKgd.js} +1 -1
  2. package/dist/{admin-Dm2bimJ-.js → admin-C9urXVfi.js} +2 -1
  3. package/dist/{agent-runner-DGCwOEyL.js → agent-runner-Bfnw551N.js} +644 -312
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +36 -53
  8. package/dist/{app-BKq0JzWx.d.ts → app-DBY5TnfY.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +62 -29
  11. package/dist/{assistant-reply-CAPafcUY.js → assistant-reply-u_PRYzuz.js} +1 -1
  12. package/dist/{automation-B-jJN_gM.js → automation-DksGNDRO.js} +3 -6
  13. package/dist/{background-compaction-queue-Btu2oab_.js → background-compaction-queue-CYI909P5.js} +3 -3
  14. package/dist/{briefs-UMeYehUe.js → briefs-DaXiMWzT.js} +6 -5
  15. package/dist/{catalog-runtime-Bym8GVdh.js → catalog-runtime-BCIuBe4d.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-B0aAs7wC.js → config-CkHcUMN7.js} +580 -3
  24. package/dist/{connections-CQ7p0aNJ.js → connections-BnIj0wtx.js} +9 -9
  25. package/dist/{conversation-BusI2uzj.js → conversation-E7ZPJx2H.js} +8 -1
  26. package/dist/{conversation-pending-messages-DwehU0Fd.js → conversation-pending-messages-DVch6YQw.js} +2 -5
  27. package/dist/{conversation-privacy-Cd_nZZBM.js → conversation-privacy-DF1hW0ja.js} +1 -1
  28. package/dist/{credential-sync-DmiJi_At.js → credential-sync-CzMar9hq.js} +13 -13
  29. package/dist/{viewer-CH-ASQzh.js → db-DJ11eZqq.js} +37 -343
  30. package/dist/{db-C5zi4ecs.d.ts → db-YDKKDxlh.d.ts} +1 -1
  31. package/dist/{executor-Dipi2Ixl.js → executor-BY9TB31g.js} +11 -4
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-CMFhLLj4.js → logging-BO5zU6Mt.js} +1 -1
  34. package/dist/{media-B-BpXo41.js → media-Cz1ZiV1U.js} +2 -2
  35. package/dist/{message-D1xLljUF.js → message-CsUbuEc8.js} +10 -10
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-DCAFIUQr.js → oauth-callback-server-hiDKK0_n.js} +2 -2
  39. package/dist/{projection-CoeMNxJ4.js → projection-CL_YWeGf.js} +82 -160
  40. package/dist/{prompt-C9OQEfan.js → prompt-BHOEQSmf.js} +182 -2
  41. package/dist/{registry-u-sFYtx_.js → registry-BriFLnaJ.js} +1 -1
  42. package/dist/{reporting-window-B4TwyuJo.js → reporting-window-B3Ze-Qnt.js} +4 -1
  43. package/dist/{resolve-DYqgL3Eo.js → resolve-Bt6GgAiA.js} +3 -3
  44. package/dist/{result-CescSwAw.js → result-Bo1TZu0Q.js} +8 -8
  45. package/dist/{runner-Cr67a8TB.js → runner-D3YeCQgt.js} +8 -8
  46. package/dist/{sandbox-egress-signals-DLOazy5W.js → sandbox-egress-signals-CcnSPP4S.js} +1 -1
  47. package/dist/{schema-BUSi3sgv.js → schema-BWE3RJEB.js} +17 -5
  48. package/dist/{schema-Ih60j59-.d.ts → schema-C6fsEwjo.d.ts} +46 -1
  49. package/dist/{service-account-CGEqz9wG.js → service-account-DiQQuuw7.js} +3 -3
  50. package/dist/{service-account-CsKxktLk.js → service-account-r6fl0b-9.js} +3 -3
  51. package/dist/{session-stop-CGz5DByb.js → session-stop-B2Nut40V.js} +18 -18
  52. package/dist/{skills-COCqf61f.js → skills-CD5aJdzg.js} +2 -2
  53. package/dist/spawn-CalgZQiu.js +79 -0
  54. package/dist/{stop-GyFZkHuQ.js → stop-kujZLbi0.js} +56 -240
  55. package/dist/{store-D0-8plWp.js → store-DdIEUL1q.js} +3 -3
  56. package/dist/{task-runner-xPuQmEot.js → task-runner-D_RDr2Hu.js} +12 -11
  57. package/dist/{turn-failure-response-BOviBdT-.js → turn-failure-response-B5nV1Er-.js} +16 -11
  58. package/dist/{validation-DZDKorGz.js → validation-K4pqwoVZ.js} +1 -1
  59. package/dist/{version-BTIz7fGi.js → version-DBvhk1X9.js} +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/viewer-DrMmFUul.js +337 -0
  62. package/dist/{work-C75_IM5e.js → work-ljRoODGu.js} +30 -19
  63. package/dist/{worker-Dl47I729.js → worker-CYO1Q0Js.js} +5 -6
  64. package/migrations/0088_conversation_unsubscribe.sql +1 -0
  65. package/migrations/meta/0088_snapshot.json +4372 -0
  66. package/migrations/meta/_journal.json +7 -0
  67. package/package.json +4 -4
  68. package/dist/config-B9f9Lqo5.js +0 -579
  69. package/dist/spawn-C8F_iXWO.js +0 -42
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.286.0";
2
+ var version = "0.287.0";
3
3
  // src/version.ts
4
4
  /** Installed Junior package version, or `unknown` when package metadata is unavailable. */
5
5
  const JUNIOR_VERSION = typeof version === "string" && version.trim() ? version : "unknown";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export { t as JUNIOR_VERSION } from "./version-BTIz7fGi.js";
1
+ export { t as JUNIOR_VERSION } from "./version-DBvhk1X9.js";
@@ -0,0 +1,337 @@
1
+ import { U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-BO5zU6Mt.js";
2
+ import { E as findActorIdentityId, o as getDb } from "./db-DJ11eZqq.js";
3
+ import { M as juniorUsers, j as juniorIdentities } from "./executor-BY9TB31g.js";
4
+ import { r as detectImageMediaType } from "./media-Cz1ZiV1U.js";
5
+ import { a as withLock } from "./locks-D-0h111u.js";
6
+ import { createHash, randomUUID } from "node:crypto";
7
+ import { and, asc, eq, inArray, isNotNull } from "drizzle-orm";
8
+ import { identitySchema, userSchema } from "@sentry/junior-plugin-api";
9
+ // src/chat/state/cache.ts
10
+ const MAX_CACHE_KEY_LENGTH = 512;
11
+ const LOAD_WAIT_MS = 1e4;
12
+ /**
13
+ * Create a cache in the state adapter under `junior:cache:{namespace}:`.
14
+ * Entries are wrapped, so `null` and `false` values are cache hits.
15
+ */
16
+ function createCache(state, namespace) {
17
+ return { async getOrLoad(key, load, options) {
18
+ if (!key.trim()) throw new Error("Cache key is required");
19
+ if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
20
+ const cacheKey = `junior:cache:${namespace}:${key}`;
21
+ const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
22
+ await state.connect();
23
+ const hit = await cached();
24
+ if (hit) return hit.value;
25
+ const attempt = await withLock(state, `${cacheKey}:load`, async () => {
26
+ const loadedMeanwhile = await cached();
27
+ if (loadedMeanwhile) return loadedMeanwhile.value;
28
+ const entry = await load();
29
+ if (entry.ttlMs !== void 0) {
30
+ if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
31
+ await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
32
+ }
33
+ return entry.value;
34
+ }, {
35
+ keepAlive: true,
36
+ waitMs: LOAD_WAIT_MS
37
+ });
38
+ if (attempt.acquired) return attempt.value;
39
+ return (await load()).value;
40
+ } };
41
+ }
42
+ // src/chat/identities/avatar.ts
43
+ /**
44
+ * Profile photos of people, saved on their native Slack and Google
45
+ * identities. Junior serves each photo from its own API, so browsers never
46
+ * load a photo from Slack or Google.
47
+ */
48
+ const AVATAR_HOSTS = {
49
+ slack: ["avatars.slack-edge.com"],
50
+ [GOOGLE_IDENTITY_PROVIDER]: ["googleusercontent.com"]
51
+ };
52
+ const AVATAR_PROVIDERS = Object.keys(AVATAR_HOSTS);
53
+ const AVATAR_CACHE_TTL_MS = 864e5;
54
+ const AVATAR_FAILURE_TTL_MS = 3e5;
55
+ const AVATAR_FETCH_TIMEOUT_MS = 5e3;
56
+ const MAX_AVATAR_BYTES = 1048576;
57
+ const AVATAR_EDGE_PX = 96;
58
+ const MAX_AVATAR_REDIRECTS = 3;
59
+ /**
60
+ * Return the URL when it is HTTPS on a photo host of the provider or a
61
+ * subdomain. Junior fetches only these URLs.
62
+ */
63
+ function parseAvatarUrl(value, provider) {
64
+ const hosts = AVATAR_HOSTS[provider];
65
+ if (!hosts || !value || !URL.canParse(value)) return void 0;
66
+ const url = new URL(value);
67
+ if (url.protocol !== "https:" || url.username || url.password) return;
68
+ const host = url.hostname.toLowerCase();
69
+ return hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`)) ? url.href : void 0;
70
+ }
71
+ function avatarUrlHash(url) {
72
+ return createHash("sha256").update(url).digest("hex");
73
+ }
74
+ function avatarVersion(url) {
75
+ return avatarUrlHash(url).slice(0, 16);
76
+ }
77
+ function avatarPath(identityId, avatarUrl) {
78
+ return `/api/people/avatars/${encodeURIComponent(identityId)}?v=${avatarVersion(avatarUrl)}`;
79
+ }
80
+ /**
81
+ * Read the photo path of each user: the Slack photo, then the Google photo.
82
+ * Users without a photo are not in the map.
83
+ */
84
+ async function readUserAvatarUrls(db, userIds) {
85
+ if (userIds.length === 0) return /* @__PURE__ */ new Map();
86
+ const rows = await db.select({
87
+ avatarUrl: juniorIdentities.avatarUrl,
88
+ identityId: juniorIdentities.id,
89
+ provider: juniorIdentities.provider,
90
+ updatedAt: juniorIdentities.updatedAt,
91
+ userId: juniorIdentities.userId
92
+ }).from(juniorIdentities).where(and(inArray(juniorIdentities.userId, [...new Set(userIds)]), eq(juniorIdentities.kind, "user"), inArray(juniorIdentities.provider, AVATAR_PROVIDERS), isNotNull(juniorIdentities.avatarUrl)));
93
+ const rank = (row) => AVATAR_PROVIDERS.indexOf(row.provider);
94
+ rows.sort((left, right) => rank(left) - rank(right) || right.updatedAt.getTime() - left.updatedAt.getTime());
95
+ const avatars = /* @__PURE__ */ new Map();
96
+ for (const row of rows) if (row.userId && row.avatarUrl && !avatars.has(row.userId)) avatars.set(row.userId, avatarPath(row.identityId, row.avatarUrl));
97
+ return avatars;
98
+ }
99
+ /**
100
+ * Return the photo path for one Identity row. A linked Identity uses the
101
+ * photo of its user. An Identity without a user uses its own photo.
102
+ */
103
+ function identityAvatarUrl(row, userAvatarUrls) {
104
+ if (row.userId) return userAvatarUrls.get(row.userId);
105
+ return row.avatarUrl ? avatarPath(row.identityId, row.avatarUrl) : void 0;
106
+ }
107
+ async function readBoundedBody(response, maxBytes) {
108
+ if (!response.body) return /* @__PURE__ */ new Uint8Array();
109
+ const reader = response.body.getReader();
110
+ const chunks = [];
111
+ let total = 0;
112
+ while (true) {
113
+ const { done, value } = await reader.read();
114
+ if (done) return Buffer.concat(chunks);
115
+ total += value.byteLength;
116
+ if (total > maxBytes) {
117
+ await reader.cancel();
118
+ return;
119
+ }
120
+ chunks.push(value);
121
+ }
122
+ }
123
+ function avatarFetchFailed(host, attributes) {
124
+ logWarn("avatar.fetch.failed", {
125
+ "server.address": host,
126
+ ...attributes
127
+ });
128
+ return null;
129
+ }
130
+ async function fetchAvatarResponse(url, provider, signal) {
131
+ let current = url;
132
+ for (let redirects = 0;; redirects += 1) {
133
+ const response = await fetch(current, {
134
+ redirect: "manual",
135
+ signal
136
+ });
137
+ const location = response.headers.get("location");
138
+ if (response.status < 300 || response.status >= 400 || !location) return response;
139
+ await response.body?.cancel();
140
+ const next = URL.canParse(location, current) ? parseAvatarUrl(new URL(location, current).href, provider) : void 0;
141
+ if (!next) return "redirect_off_host";
142
+ if (redirects >= MAX_AVATAR_REDIRECTS) return "too_many_redirects";
143
+ current = next;
144
+ }
145
+ }
146
+ async function fetchAvatarImage(url, provider) {
147
+ const host = new URL(url).hostname;
148
+ let data;
149
+ try {
150
+ const response = await fetchAvatarResponse(url, provider, AbortSignal.timeout(AVATAR_FETCH_TIMEOUT_MS));
151
+ if (typeof response === "string") return avatarFetchFailed(host, { "app.reason": response });
152
+ if (!response.ok) {
153
+ await response.body?.cancel();
154
+ return avatarFetchFailed(host, { "http.response.status_code": response.status });
155
+ }
156
+ data = await readBoundedBody(response, MAX_AVATAR_BYTES);
157
+ } catch (error) {
158
+ return avatarFetchFailed(host, { "exception.message": error instanceof Error ? error.message : String(error) });
159
+ }
160
+ if (!data) return avatarFetchFailed(host, { "app.reason": "too_large" });
161
+ const contentType = detectImageMediaType(data);
162
+ if (!contentType) return avatarFetchFailed(host, { "app.reason": "not_an_image" });
163
+ try {
164
+ return {
165
+ contentType: "image/webp",
166
+ data: await shrinkAvatar(data)
167
+ };
168
+ } catch (error) {
169
+ logWarn("avatar.resize.failed", {
170
+ "server.address": host,
171
+ "exception.message": error instanceof Error ? error.message : String(error)
172
+ });
173
+ return {
174
+ contentType,
175
+ data: Buffer.from(data).toString("base64")
176
+ };
177
+ }
178
+ }
179
+ async function shrinkAvatar(data) {
180
+ const { default: sharp } = await import("sharp");
181
+ return (await sharp(data).rotate().resize({
182
+ width: AVATAR_EDGE_PX,
183
+ height: AVATAR_EDGE_PX,
184
+ withoutEnlargement: true
185
+ }).webp({ quality: 80 }).toBuffer()).toString("base64");
186
+ }
187
+ /**
188
+ * Read the saved photo of one Identity and its version. Junior fetches it
189
+ * from the provider once, resizes it, and keeps it in the state cache for a
190
+ * day. Return undefined when the Identity has no photo or the provider does
191
+ * not return one.
192
+ */
193
+ async function readAvatarImage(db, state, identityId) {
194
+ const [row] = await db.select({
195
+ avatarUrl: juniorIdentities.avatarUrl,
196
+ provider: juniorIdentities.provider
197
+ }).from(juniorIdentities).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1);
198
+ const url = row ? parseAvatarUrl(row.avatarUrl, row.provider) : void 0;
199
+ if (!row?.avatarUrl || !url) return void 0;
200
+ const key = `avatar:${AVATAR_EDGE_PX}:${avatarUrlHash(url)}`;
201
+ const image = await createCache(state, "core").getOrLoad(key, async () => {
202
+ const loaded = await fetchAvatarImage(url, row.provider);
203
+ return {
204
+ value: loaded,
205
+ ttlMs: loaded ? AVATAR_CACHE_TTL_MS : AVATAR_FAILURE_TTL_MS
206
+ };
207
+ });
208
+ return image ? {
209
+ image,
210
+ version: avatarVersion(row.avatarUrl)
211
+ } : void 0;
212
+ }
213
+ // src/chat/plugins/viewer.ts
214
+ function identityFromRow(row) {
215
+ return identitySchema.parse({
216
+ id: row.id,
217
+ provider: row.provider,
218
+ providerSubjectId: row.providerSubjectId,
219
+ ...row.providerTenantId ? { providerTenantId: row.providerTenantId } : void 0,
220
+ ...row.displayName ? { displayName: row.displayName } : void 0,
221
+ ...row.handle ? { handle: row.handle } : void 0
222
+ });
223
+ }
224
+ async function readUserById(db, userRow) {
225
+ 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)));
226
+ }
227
+ function userFromRows(userRow, identityRows) {
228
+ return userSchema.parse({
229
+ email: userRow.primaryEmail,
230
+ id: userRow.id,
231
+ identities: identityRows.map(identityFromRow),
232
+ ...userRow.displayName ? { displayName: userRow.displayName } : void 0,
233
+ ...userRow.isAdmin ? { isAdmin: true } : void 0
234
+ });
235
+ }
236
+ async function readUserByNormalizedEmail(db, normalizedEmail) {
237
+ const rows = await db.select({
238
+ user: juniorUsers,
239
+ identity: juniorIdentities
240
+ }).from(juniorUsers).leftJoin(juniorIdentities, and(eq(juniorIdentities.userId, juniorUsers.id), eq(juniorIdentities.kind, "user"))).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).orderBy(asc(juniorIdentities.provider), asc(juniorIdentities.providerTenantId), asc(juniorIdentities.providerSubjectId));
241
+ const userRow = rows[0]?.user;
242
+ if (!userRow) return void 0;
243
+ return userFromRows(userRow, rows.flatMap((row) => row.identity ? [row.identity] : []));
244
+ }
245
+ /** Resolve or create the canonical user for one verified viewer email. */
246
+ async function resolveViewerUserFromSql(db, email) {
247
+ const normalizedEmail = normalizeIdentityEmail(email);
248
+ if (!normalizedEmail) return void 0;
249
+ const existing = await readUserByNormalizedEmail(db, normalizedEmail);
250
+ if (existing) return existing;
251
+ const now = /* @__PURE__ */ new Date();
252
+ const userRow = (await db.insert(juniorUsers).values({
253
+ id: randomUUID(),
254
+ primaryEmail: email.trim(),
255
+ primaryEmailNormalized: normalizedEmail,
256
+ displayName: null,
257
+ createdAt: now,
258
+ updatedAt: now
259
+ }).onConflictDoNothing({ target: juniorUsers.primaryEmailNormalized }).returning())[0] ?? (await db.select().from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0];
260
+ return userRow ? await readUserById(db, userRow) : void 0;
261
+ }
262
+ /** Resolve or create the canonical user for one authenticated viewer. */
263
+ async function resolveViewerUser(email) {
264
+ return await resolveViewerUserFromSql(getDb(), email);
265
+ }
266
+ /** Read one existing canonical user by verified email without creating a row. */
267
+ async function findUserByEmailFromSql(db, email) {
268
+ const normalizedEmail = normalizeIdentityEmail(email);
269
+ if (!normalizedEmail) return void 0;
270
+ return await readUserByNormalizedEmail(db, normalizedEmail);
271
+ }
272
+ /** Read one existing canonical user by verified email without creating a row. */
273
+ async function findUserByEmail(email) {
274
+ return await findUserByEmailFromSql(getDb(), email);
275
+ }
276
+ /** Update one canonical user's display name in SQL. */
277
+ async function updateViewerDisplayNameFromSql(db, userId, displayName) {
278
+ const userRow = (await db.update(juniorUsers).set({
279
+ displayName,
280
+ updatedAt: /* @__PURE__ */ new Date()
281
+ }).where(eq(juniorUsers.id, userId)).returning())[0];
282
+ return userRow ? await readUserById(db, userRow) : void 0;
283
+ }
284
+ /** Read the photo path of one canonical user: Slack, then Google. */
285
+ async function readViewerAvatarUrl(userId) {
286
+ return (await readUserAvatarUrls(getDb(), [userId])).get(userId);
287
+ }
288
+ /** Update one canonical user's display name. */
289
+ async function updateViewerDisplayName(userId, displayName) {
290
+ return await updateViewerDisplayNameFromSql(getDb(), userId, displayName);
291
+ }
292
+ /**
293
+ * Grant or revoke the Junior-wide admin role for one email.
294
+ *
295
+ * Granting creates the canonical user when needed, so an operator can grant
296
+ * admin before that person first signs in. Revoking never creates a user.
297
+ */
298
+ async function setUserAdminFromSql(db, email, isAdmin) {
299
+ const user = isAdmin ? await resolveViewerUserFromSql(db, email) : await findUserByEmailFromSql(db, email);
300
+ if (!user) return void 0;
301
+ const userRow = (await db.update(juniorUsers).set({
302
+ isAdmin,
303
+ updatedAt: /* @__PURE__ */ new Date()
304
+ }).where(eq(juniorUsers.id, user.id)).returning())[0];
305
+ return userRow ? await readUserById(db, userRow) : void 0;
306
+ }
307
+ /** List every Junior admin by primary email. */
308
+ async function listAdminUsersFromSql(db) {
309
+ const rows = await db.select().from(juniorUsers).where(eq(juniorUsers.isAdmin, true)).orderBy(asc(juniorUsers.primaryEmailNormalized));
310
+ return await Promise.all(rows.map((row) => readUserById(db, row)));
311
+ }
312
+ /** Resolve the stored identity and linked user for one runtime actor. */
313
+ async function readActorIdentityFromSql(db, actor) {
314
+ const identityId = await findActorIdentityId(db, actor);
315
+ return identityId ? await readIdentityByIdFromSql(db, identityId) : void 0;
316
+ }
317
+ /** Resolve the stored identity and linked user for one runtime actor. */
318
+ async function readActorIdentity(actor) {
319
+ return await readActorIdentityFromSql(getDb(), actor);
320
+ }
321
+ /** Read one stored identity and its linked user by identity id. */
322
+ async function readIdentityByIdFromSql(db, identityId) {
323
+ const row = (await db.select({
324
+ identity: juniorIdentities,
325
+ user: juniorUsers
326
+ }).from(juniorIdentities).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(eq(juniorIdentities.id, identityId), eq(juniorIdentities.kind, "user"))).limit(1))[0];
327
+ if (!row) return void 0;
328
+ return {
329
+ identity: identityFromRow(row.identity),
330
+ ...row.user ? { user: await readUserById(db, row.user) } : void 0
331
+ };
332
+ }
333
+ /** Read one stored identity and its linked user by identity id. */
334
+ async function readIdentityById(identityId) {
335
+ return await readIdentityByIdFromSql(getDb(), identityId);
336
+ }
337
+ export { readActorIdentityFromSql as a, readViewerAvatarUrl as c, updateViewerDisplayName as d, identityAvatarUrl as f, createCache as g, readUserAvatarUrls as h, readActorIdentity as i, resolveViewerUser as l, readAvatarImage as m, findUserByEmailFromSql as n, readIdentityById as o, parseAvatarUrl as p, listAdminUsersFromSql as r, readIdentityByIdFromSql as s, findUserByEmail as t, setUserAdminFromSql as u };
@@ -1,15 +1,15 @@
1
- import { $ as pauseLostWorkerTurn, Q as lostWorkerBeforeFirstSave, Qt as getTerminalAssistantMessages, U as AuthorizationFlowDisabledError, et as saveTurnCheckpoint, go as loadForkHistory, hn as escapeClosingTags, it as getTurnRecord, qt as isTurnExecutionLimitExceededError, rt as failTurnRecord, s as openConversationProjection, tt as abandonTurnRecord, v as hydrateConversationMessages, vn as renderTag, z as PluginCredentialFailureError } from "./projection-CoeMNxJ4.js";
2
- import { n as botConfig } from "./config-B9f9Lqo5.js";
3
- import { C as getSqlExecutor, V as SYSTEM_IDENTITY_ID, x as getConversationStore, y as getConversationEventStore } from "./viewer-CH-ASQzh.js";
4
- import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-Dipi2Ixl.js";
5
- import { m as agentInstructionProvenance, v as sameActorIdentity } from "./media-B-BpXo41.js";
6
- import { Ct as recordSubagentStarted, Dt as executeTurn, Et as AgentRunError, Ft as AgentInvocationLimitError, Lt as AgentMessageQueueFullError, Ot as finishTurn, St as recordSubagentEnded, Tt as supersedeOpenMailboxTurns, xt as stopChildAgentsOf, zt as AgentNameInUseError } from "./agent-runner-DGCwOEyL.js";
7
- import { A as markAgentInvocationPaused, B as agentTypeInstructions, C as isTerminalAgentInvocation, I as agentBindingSchema, M as markAgentInvocationSteered, N as reportReplacedAgentInvocation, O as markAgentInvocationMailboxAppended, Q as getUnnamedAgentConversationId, R as createAgentInvocationSchema, T as listOpenAgentInvocations, U as getAgentInvocationId, V as agentTypeStartsWithParentHistory, X as getChildAgentLockName, Y as getAgentInvocationTurnId, Z as getNamedAgentConversationId, _ as completeAgentInvocation, f as ConversationTurnLifecycleService, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, h as ACTIVE_AGENT_INVOCATION_STATUSES, it as getConversationTurnBoundaryError, j as markAgentInvocationRunning, nt as TurnInputCommitLostError, ot as isTurnInputCommitLostError, q as getAgentInvocationMessageId, v as getActiveAgentInvocationForConversation, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation, y as getAgentInvocation } from "./turn-failure-response-BOviBdT-.js";
8
- import { n as getAssistantReplyText } from "./assistant-reply-CAPafcUY.js";
9
- import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, K as recordFinishedTurnForAutomatedLimit, X as buildSteeringPiMessage, Z as instructionForInputs, at as readBlockedReport, h as parseWebMessages, i as resumeStoppedConversationTree, p as listActiveMailboxTurns, q as resetAutomatedTurnLimit, u as getActiveConversationTurnId } from "./session-stop-CGz5DByb.js";
10
- import { S as getTurnRequestDeadline } from "./background-compaction-queue-Btu2oab_.js";
11
- import { r as appendAndEnqueueInboundMessage } from "./store-D0-8plWp.js";
12
- import { _t as getPersistedThreadState, bt as coerceThreadConversationState, gt as getPersistedSandboxState, yt as persistThreadStateById } from "./task-runner-xPuQmEot.js";
1
+ import { $ as pauseLostWorkerTurn, Q as lostWorkerBeforeFirstSave, Qt as getTerminalAssistantMessages, U as AuthorizationFlowDisabledError, et as saveTurnCheckpoint, hn as escapeClosingTags, it as getTurnRecord, qt as isTurnExecutionLimitExceededError, rt as failTurnRecord, s as openConversationProjection, tt as abandonTurnRecord, v as hydrateConversationMessages, yn as renderTag, yo as loadForkHistory, z as PluginCredentialFailureError } from "./projection-CL_YWeGf.js";
2
+ import { n as botConfig } from "./config-CkHcUMN7.js";
3
+ import { T as SYSTEM_IDENTITY_ID, a as getConversationStore, r as getConversationEventStore, s as getSqlExecutor } from "./db-DJ11eZqq.js";
4
+ import { g as juniorAgentInvocations, h as juniorAgentBindings } from "./executor-BY9TB31g.js";
5
+ import { h as contextProvenance, m as agentInstructionProvenance, v as sameActorIdentity } from "./media-Cz1ZiV1U.js";
6
+ import { At as recordSubagentStarted, Ft as finishTurn, Ht as AgentInvocationLimitError, Kt as AgentNameInUseError, Mt as supersedeOpenMailboxTurns, Nt as AgentRunError, Ot as stopChildAgentsOf, Pt as executeTurn, Wt as AgentMessageQueueFullError, kt as recordSubagentEnded } from "./agent-runner-Bfnw551N.js";
7
+ import { $ as getUnnamedAgentConversationId, A as markAgentInvocationPaused, C as isTerminalAgentInvocation, H as agentTypeStartsWithParentHistory, J as getAgentInvocationMessageId, L as agentBindingSchema, M as markAgentInvocationSteered, N as reportReplacedAgentInvocation, O as markAgentInvocationMailboxAppended, Q as getNamedAgentConversationId, T as listOpenAgentInvocations, V as agentTypeInstructions, W as getAgentInvocationId, X as getAgentInvocationTurnId, Z as getChildAgentLockName, _ as completeAgentInvocation, at as getConversationTurnBoundaryError, f as ConversationTurnLifecycleService, g as NON_TERMINAL_AGENT_INVOCATION_STATUSES, h as ACTIVE_AGENT_INVOCATION_STATUSES, j as markAgentInvocationRunning, rt as TurnInputCommitLostError, st as isTurnInputCommitLostError, v as getActiveAgentInvocationForConversation, w as listAgentInvocationsForConversation, x as getLatestAgentInvocationForConversation, y as getAgentInvocation, z as createAgentInvocationSchema } from "./turn-failure-response-B5nV1Er-.js";
8
+ import { n as getAssistantReplyText } from "./assistant-reply-u_PRYzuz.js";
9
+ import { $ as withoutSavedSteeringMessages, B as maybePostAutomatedTurnLimitNotice, K as recordFinishedTurnForAutomatedLimit, X as buildSteeringPiMessage, Z as instructionForInputs, at as readBlockedReport, h as parseWebMessages, i as resumeStoppedConversationTree, p as listActiveMailboxTurns, q as resetAutomatedTurnLimit, u as getActiveConversationTurnId } from "./session-stop-B2Nut40V.js";
10
+ import { S as getTurnRequestDeadline } from "./background-compaction-queue-CYI909P5.js";
11
+ import { r as appendAndEnqueueInboundMessage } from "./store-DdIEUL1q.js";
12
+ import { _t as getPersistedThreadState, bt as coerceThreadConversationState, gt as getPersistedSandboxState, yt as persistThreadStateById } from "./task-runner-D_RDr2Hu.js";
13
13
  import { isDeepStrictEqual } from "node:util";
14
14
  import * as z from "zod";
15
15
  import { and, eq } from "drizzle-orm";
@@ -105,7 +105,8 @@ async function createAgentInvocation(rawInput, nowMs = Date.now()) {
105
105
  return await getSqlExecutor().withLock(lockName, async () => {
106
106
  const existing = await getAgentInvocation(invocationId);
107
107
  if (existing) {
108
- if (!sameCreateInput(existing, input)) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
108
+ const child = await getConversationStore().get({ conversationId: existing.childConversationId });
109
+ if (!sameCreateInput(existing, input) || child?.kind !== input.kind) throw new Error(`Agent invocation idempotency key was reused with different input for ${invocationId}`);
109
110
  return existing;
110
111
  }
111
112
  const open = await listOpenAgentInvocations(input.parentConversationId);
@@ -120,7 +121,7 @@ async function createAgentInvocation(rawInput, nowMs = Date.now()) {
120
121
  });
121
122
  await getConversationStore().createChild({
122
123
  childConversationId,
123
- kind: "task",
124
+ kind: input.kind,
124
125
  parentConversationId: input.parentConversationId,
125
126
  nowMs,
126
127
  source: "internal"
@@ -342,6 +343,13 @@ function agentInvocationInputText(invocation) {
342
343
  const typeInstructions = agentTypeInstructions(invocation.agentType);
343
344
  return renderTag("parent-agent-task", {}, [...typeInstructions ? [escapeClosingTags(typeInstructions), ""] : [], escapeClosingTags(invocation.input)]);
344
345
  }
346
+ /**
347
+ * A parent agent task or message is the child's instruction. Another input,
348
+ * such as a result of the child's own child agent or an Event, is context.
349
+ */
350
+ function agentInvocationProvenance(invocation) {
351
+ return invocation.parentToolCallId ? agentInstructionProvenance : contextProvenance;
352
+ }
345
353
  /** Resolve invocation execution from mailbox input or durable active state. */
346
354
  async function resolveAgentInvocationId(context) {
347
355
  const mailboxInvocationId = invocationIdFromMessages(context.attempt.messages);
@@ -382,7 +390,7 @@ function createAgentMessageSteeringDrain(context, running) {
382
390
  const saved = (await getTurnRecord(running.childConversationId, turnId))?.piMessages ?? [];
383
391
  const messages = withoutSavedSteeringMessages(saved, joining.map((candidate) => ({
384
392
  kind: "runtime",
385
- provenance: agentInstructionProvenance,
393
+ provenance: agentInvocationProvenance(candidate),
386
394
  text: agentInvocationInputText(candidate),
387
395
  timestampMs: candidate.createdAtMs
388
396
  })), buildSteeringPiMessage);
@@ -675,10 +683,13 @@ function createAgentInvocationWorker(agentRunner, options = {}) {
675
683
  parentConversationId: invocation.parentConversationId,
676
684
  turnId,
677
685
  runId: invocation.invocationId,
678
- instruction: instructionForInputs([{
679
- kind: "runtime",
680
- text: agentInvocationInputText(invocation)
681
- }]),
686
+ instruction: {
687
+ ...instructionForInputs([{
688
+ kind: "runtime",
689
+ text: agentInvocationInputText(invocation)
690
+ }]),
691
+ provenance: agentInvocationProvenance(invocation)
692
+ },
682
693
  history,
683
694
  actor: invocation.actor,
684
695
  credentialContext: invocation.credentialContext,
@@ -1,10 +1,9 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Dt as isInvalidConversationRecordError, Et as isFinalAttempt, wt as hasConversationStop } from "./projection-CoeMNxJ4.js";
3
- import { x as isProviderRetryError } from "./client-B0aAs7wC.js";
4
- import { i as getChatConfig } from "./config-B9f9Lqo5.js";
5
- import { T as withLogContext, b as setSpanAttributes, h as logWarn, m as logInfo, p as logException } from "./logging-CMFhLLj4.js";
6
- import { C as ConversationQueueMessageRejectedError, S as getTurnRequestDeadline } from "./background-compaction-queue-Btu2oab_.js";
7
- import { E as startConversationWork, S as releaseConversationWork, _ as getConversationWorkState, b as recordAttemptFailure, c as clearConsumedConversationWake, d as completeConversationWork, f as countPendingConversationMessages, h as ensureConversationWake, i as beginConversationResume, m as drainConversationMailbox, o as checkInConversationWork, p as deadLetterAttempt, t as ackMessages, u as completeConversationStop, w as requestAnotherSlice, x as recordConversationRetry } from "./store-D0-8plWp.js";
2
+ import { Dt as isInvalidConversationRecordError, Et as isFinalAttempt, wt as hasConversationStop } from "./projection-CL_YWeGf.js";
3
+ import { i as getChatConfig, z as isProviderRetryError } from "./config-CkHcUMN7.js";
4
+ import { T as withLogContext, b as setSpanAttributes, h as logWarn, m as logInfo, p as logException } from "./logging-BO5zU6Mt.js";
5
+ import { C as ConversationQueueMessageRejectedError, S as getTurnRequestDeadline } from "./background-compaction-queue-CYI909P5.js";
6
+ import { E as startConversationWork, S as releaseConversationWork, _ as getConversationWorkState, b as recordAttemptFailure, c as clearConsumedConversationWake, d as completeConversationWork, f as countPendingConversationMessages, h as ensureConversationWake, i as beginConversationResume, m as drainConversationMailbox, o as checkInConversationWork, p as deadLetterAttempt, t as ackMessages, u as completeConversationStop, w as requestAnotherSlice, x as recordConversationRetry } from "./store-DdIEUL1q.js";
8
7
  // src/chat/task-execution/attempt-selection.ts
9
8
  function selectContiguousTurnBatch(messages) {
10
9
  const first = messages[0];
@@ -0,0 +1 @@
1
+ ALTER TABLE "junior_conversation_participants" ADD COLUMN "unsubscribed_at" timestamp with time zone;