@sentry/junior 0.298.0 → 0.300.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 (95) hide show
  1. package/dist/{actor-6jsm_v96.js → actor-D2iXzvlN.js} +2 -1
  2. package/dist/{state-CSuA2J1V.js → adapter-S5UkjNK3.js} +53 -136
  3. package/dist/{admin-BF3DbYGf.js → admin-UrTniSPO.js} +2 -2
  4. package/dist/{agent-runner-Q9GkoerG.js → agent-runner-bY4_0UPm.js} +1444 -1478
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -7
  7. package/dist/api.d.ts +1 -1
  8. package/dist/api.js +382 -68
  9. package/dist/{app-DOg_mCtV.d.ts → app-D-AcIcCV.d.ts} +17 -4
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +148 -483
  12. package/dist/{automation-Cn8qmbdr.js → automation-Dw82oQ-h.js} +2 -2
  13. package/dist/{background-compaction-queue-BZhGFOK6.js → background-compaction-queue-B6U3060-.js} +9 -5
  14. package/dist/{briefs-CQrCRF6-.js → briefs-DqiwWu-n.js} +4 -4
  15. package/dist/{catalog-runtime-DZeD2WbL.js → catalog-runtime-D1oYNv04.js} +1 -1
  16. package/dist/cli/chat.js +17 -17
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +5 -5
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-BOByVnxe.js → config-9nHoFiJP.js} +117 -12
  24. package/dist/{connections-BNN5cJam.js → connections-DZjTN3JC.js} +6 -6
  25. package/dist/continue-in-slack-Dtv7_U42.js +176 -0
  26. package/dist/{conversation-DCkzvxqB.js → conversation-Dyjq2CZ8.js} +36 -13
  27. package/dist/{conversation-feed-CMA12Rjs.js → conversation-feed-CcDxlrlQ.js} +109 -3
  28. package/dist/{conversation-privacy-C0eRxsgb.js → conversation-privacy-D-5HTXjS.js} +1 -1
  29. package/dist/{conversation-turn-D9qvcDX6.js → conversation-turn-Cxl8WZD7.js} +85 -68
  30. package/dist/{credential-sync-B_iUpxGL.js → credential-sync-C49ClwDX.js} +18 -18
  31. package/dist/{db-DoMcnYol.d.ts → db-2resqBh1.d.ts} +1 -1
  32. package/dist/{db-CoMNr2Zm.js → db-BJNo6fK5.js} +176 -12
  33. package/dist/{executor-C-m8VrzX.js → executor-DBIaOeJ_.js} +47 -13
  34. package/dist/{media-BepyEUNm.js → history-IjdmO_r6.js} +1 -85
  35. package/dist/instrumentation.js +14 -5
  36. package/dist/lineage-0dereG7H.js +37 -0
  37. package/dist/{logging-CJTi5niy.js → logging-BIclibct.js} +1 -1
  38. package/dist/{message-Q6_5DAWR.js → message-dkOl-Iii.js} +9 -10
  39. package/dist/model-input-CLo9TaUd.js +82 -0
  40. package/dist/nitro.d.ts +1 -1
  41. package/dist/nitro.js +17 -9
  42. package/dist/{oauth-callback-server-CH5XAyo-.js → oauth-callback-server-WmpjfJgQ.js} +2 -2
  43. package/dist/{plugins-HYh_JOdw.js → plugins-BBX07Jzt.js} +1 -1
  44. package/dist/{projection-BgwEE36_.js → projection-w_X-zi7v.js} +1035 -692
  45. package/dist/{prompt-DXc9DYT9.js → prompt-B1Xw46-S.js} +4 -4
  46. package/dist/{registry-9XwqSnM-.js → registry-BmP5vnlj.js} +4 -4
  47. package/dist/{resolve-DUIAbcRL.js → resolve-goo34bJK.js} +3 -3
  48. package/dist/{result-C2Vn8QGn.js → result-PVBeU0Wf.js} +158 -69
  49. package/dist/{runner-CXGtw-Mc.js → runner-DKrfvNV6.js} +9 -9
  50. package/dist/{sandbox-egress-signals-Di3S_dO7.js → sandbox-egress-signals-DsUcqrI0.js} +1 -1
  51. package/dist/{schema-Dyp7racy.js → schema-C9iNFz5n.js} +51 -7
  52. package/dist/{schema-BnbZ-rKv.d.ts → schema-Dns-sTas.d.ts} +1285 -761
  53. package/dist/{service-account-DM3KBBeG.js → service-account-CMAAloAL.js} +3 -3
  54. package/dist/{service-account-GzAMUQ8a.js → service-account-CmowamcB.js} +4 -4
  55. package/dist/session-stop-BcAXze8a.js +3330 -0
  56. package/dist/{skills-DCK9SD_l.js → skills-DfsazET6.js} +3 -3
  57. package/dist/slack-conversation-unfurl-CzQonuWz.js +370 -0
  58. package/dist/spawn-C7o0FDDp.js +73 -0
  59. package/dist/state-zSilNpbi.js +132 -0
  60. package/dist/{user-input-request-CXNIov9n.js → statuses-Hn-HsOph.js} +115 -26
  61. package/dist/{stop-Dh2DfwpK.js → stop-CFOujp8C.js} +9105 -6007
  62. package/dist/{store-DrA17Fbz.js → store-Dkeis_8o.js} +10 -10
  63. package/dist/{store-B1zepKG8.js → store-E3x2Fg_F.js} +24 -4
  64. package/dist/{task-queue-D1rXWfFN.js → task-queue-D-hCqdZW.js} +4 -4
  65. package/dist/{task-runner-CT4M8oDz.js → task-runner-vohUPLHe.js} +10 -10
  66. package/dist/{thread-context-DnqUkbzN.js → thread-context-BzvdkgI9.js} +18 -18
  67. package/dist/{turn-session-routing-VXDVXLRl.js → turn-session-routing-Bo_LxFum.js} +5 -5
  68. package/dist/turn-user-message-D5RnVmxQ.js +355 -0
  69. package/dist/users-2bggndVg.js +424 -0
  70. package/dist/{validation-zxAJBDDy.js → validation-BbWikeSa.js} +1 -1
  71. package/dist/{version-DcZ40a0g.js → version-GVBMW2jA.js} +1 -1
  72. package/dist/version.js +1 -1
  73. package/dist/{viewer-CgiGjW10.js → viewer-BpxRliyO.js} +36 -163
  74. package/dist/{warmup-CwKbxQLl.js → warmup-BW2qwnal.js} +1140 -145
  75. package/dist/{worker-CbDUzaBA.js → worker-Cbd-iuwZ.js} +25 -20
  76. package/migrations/0104_code_change_draft.sql +1 -0
  77. package/migrations/0105_attachment_uploads.sql +14 -0
  78. package/migrations/0106_conversation_agent_config.sql +1 -0
  79. package/migrations/0107_attachment_deferred_download.sql +2 -0
  80. package/migrations/meta/0104_snapshot.json +4516 -0
  81. package/migrations/meta/0105_snapshot.json +4611 -0
  82. package/migrations/meta/0106_snapshot.json +4617 -0
  83. package/migrations/meta/0107_snapshot.json +4617 -0
  84. package/migrations/meta/_journal.json +28 -0
  85. package/package.json +10 -8
  86. package/dist/attempt-selection-ClP3MMPr.js +0 -61
  87. package/dist/locks-D-0h111u.js +0 -48
  88. package/dist/notification-Bv25xbj0.js +0 -1284
  89. package/dist/prompt-input-BUr4J9RO.js +0 -1424
  90. package/dist/session-stop-D4i7e6iT.js +0 -181
  91. package/dist/spawn-6cX6xE9G.js +0 -80
  92. package/dist/turn-cancel-l460pfGW.js +0 -201
  93. package/dist/turn-user-message-BSPmkm7X.js +0 -608
  94. package/dist/turn-wake-DVFVXyhX.js +0 -161
  95. package/dist/{oauth-relay-CsfIazeF.js → oauth-relay-DRzq73b6.js} +1 -1
@@ -1,25 +1,25 @@
1
- import { Hn as createUserTokenStore, Kn as resolvePluginOAuthAccount, Sa as getSlackClient, Xi as parseOAuthStatePayload, Yi as formatProviderLabel, Z as getConversationPendingAuth, Zi as resolveBaseUrl, d as recordAuthorizationCompleted, da as postSlackMessage, ot as getTurnRecord, u as recordAuthenticationLinked } from "./projection-BgwEE36_.js";
2
- import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-BOByVnxe.js";
3
- import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-CJTi5niy.js";
4
- import { p as parseSlackUserId } from "./actor-6jsm_v96.js";
5
- import { H as upsertLinkedIdentity, P as resolveActorIdentityId, R as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-CoMNr2Zm.js";
1
+ import { Jo as getSlackClient, Ta as postSlackMessage, Z as getConversationPendingAuth, Zn as createUserTokenStore, ca as parseOAuthStatePayload, d as recordAuthorizationCompleted, la as resolveBaseUrl, sa as formatProviderLabel, st as getTurnRecord, tr as resolvePluginOAuthAccount, u as recordAuthenticationLinked } from "./projection-w_X-zi7v.js";
2
+ import { R as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-9nHoFiJP.js";
3
+ import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-BIclibct.js";
4
+ import { p as parseSlackUserId } from "./actor-D2iXzvlN.js";
5
+ import { L as findUserByVerifiedEmails, N as resolveActorIdentityId, V as upsertLinkedIdentity, s as getSqlExecutor } from "./db-BJNo6fK5.js";
6
+ import { r as getStateAdapter, s as acquireActiveLock } from "./adapter-S5UkjNK3.js";
6
7
  import { i as homeDir } from "./package-discovery-DJhGdS4c.js";
7
- import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-9XwqSnM-.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DZeD2WbL.js";
9
- import { t as discoverSkills } from "./skills-DCK9SD_l.js";
10
- import { b as lookupSlackUserProfile, d as getMcpAuthSession, f as getMcpStoredOAuthCredentials, o as finalizeMcpAuthorization, p as putMcpStoredOAuthCredentials, s as deleteMcpAuthSession } from "./agent-runner-Q9GkoerG.js";
11
- import { r as acquireActiveLock } from "./locks-D-0h111u.js";
12
- import { o as readIdentityById } from "./viewer-CgiGjW10.js";
13
- import { a as getStateAdapter } from "./state-CSuA2J1V.js";
8
+ import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-BmP5vnlj.js";
9
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-D1oYNv04.js";
10
+ import { t as discoverSkills } from "./skills-DfsazET6.js";
11
+ import { d as getMcpAuthSession, f as getMcpStoredOAuthCredentials, o as finalizeMcpAuthorization, p as putMcpStoredOAuthCredentials, s as deleteMcpAuthSession } from "./agent-runner-bY4_0UPm.js";
12
+ import { o as readIdentityById } from "./viewer-BpxRliyO.js";
14
13
  import { t as readJuniorSecret } from "./secrets-DebYU866.js";
15
- import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-VXDVXLRl.js";
16
- import { i as wakePausedTurn, r as wakeAuthorizedTurn, s as deleteWebAuthorization } from "./turn-wake-DVFVXyhX.js";
17
- import { _ as getMcpProviderErrorAttributes } from "./service-account-GzAMUQ8a.js";
18
- import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-BNN5cJam.js";
19
- import { n as relayLocalOAuthCallback } from "./oauth-relay-CsfIazeF.js";
14
+ import { Ct as deleteWebAuthorization, gt as wakePausedTurn, ht as wakeAuthorizedTurn } from "./warmup-BW2qwnal.js";
15
+ import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-Bo_LxFum.js";
16
+ import { _ as getMcpProviderErrorAttributes } from "./service-account-CmowamcB.js";
17
+ import { r as lookupSlackUserProfile } from "./users-2bggndVg.js";
18
+ import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-DZjTN3JC.js";
19
+ import { n as relayLocalOAuthCallback } from "./oauth-relay-DRzq73b6.js";
20
+ import * as z from "zod";
20
21
  import path from "node:path";
21
22
  import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
22
- import * as z from "zod";
23
23
  import { pluginStoredTokensSchema } from "@sentry/junior-plugin-api";
24
24
  import fs from "node:fs";
25
25
  // src/handlers/mcp-oauth-callback.ts
@@ -1,4 +1,4 @@
1
- import "./schema-BnbZ-rKv.js";
1
+ import "./schema-Dns-sTas.js";
2
2
  import * as z from "zod";
3
3
  import "drizzle-orm";
4
4
  import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
@@ -1,9 +1,11 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-BOByVnxe.js";
3
- import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-CJTi5niy.js";
4
- import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-6jsm_v96.js";
5
- import { A as juniorConversations, C as isUserInstruction, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, S as juniorConversationMetrics, j as juniorIdentities, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-C-m8VrzX.js";
6
- import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-BepyEUNm.js";
2
+ import { i as getChatConfig } from "./config-9nHoFiJP.js";
3
+ import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-BIclibct.js";
4
+ import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-D2iXzvlN.js";
5
+ import { C as isUserInstruction, E as juniorConversationAnnotations, M as juniorIdentities, N as juniorUsers, P as juniorDestinations, S as juniorConversationMetrics, j as juniorConversations, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-DBIaOeJ_.js";
6
+ import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-IjdmO_r6.js";
7
+ import { l as withLock, r as getStateAdapter } from "./adapter-S5UkjNK3.js";
8
+ import * as z from "zod";
7
9
  import { randomUUID } from "node:crypto";
8
10
  import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
9
11
  import { destinationSchema, locationSchema, sourceSchema } from "@sentry/junior-plugin-api";
@@ -395,6 +397,172 @@ async function claimProviderConversation(executor, args) {
395
397
  async function bindProviderConversation(executor, args) {
396
398
  if (!await claimProviderConversation(executor, args)) throw new Error("Provider conversation is already bound to another conversation");
397
399
  }
400
+ // src/chat/state/cache.ts
401
+ const MAX_CACHE_KEY_LENGTH = 512;
402
+ const LOAD_WAIT_MS = 1e4;
403
+ /** The prefix of every state key of one cache namespace. */
404
+ function cacheKeyPrefix(namespace) {
405
+ return `junior:cache:${namespace}:`;
406
+ }
407
+ /**
408
+ * Create a cache in the state adapter under `junior:cache:{namespace}:`.
409
+ * Entries are wrapped, so `null` and `false` values are cache hits.
410
+ */
411
+ function createCache(state, namespace) {
412
+ return { async getOrLoad(key, load, options) {
413
+ if (!key.trim()) throw new Error("Cache key is required");
414
+ if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
415
+ const cacheKey = `${cacheKeyPrefix(namespace)}${key}`;
416
+ const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
417
+ await state.connect();
418
+ const hit = await cached();
419
+ if (hit) return hit.value;
420
+ const attempt = await withLock(state, `${cacheKey}:load`, async () => {
421
+ const loadedMeanwhile = await cached();
422
+ if (loadedMeanwhile) return loadedMeanwhile.value;
423
+ const entry = await load();
424
+ if (entry.ttlMs !== void 0) {
425
+ if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
426
+ await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
427
+ }
428
+ return entry.value;
429
+ }, {
430
+ keepAlive: true,
431
+ waitMs: LOAD_WAIT_MS
432
+ });
433
+ if (attempt.acquired) return attempt.value;
434
+ return (await load()).value;
435
+ } };
436
+ }
437
+ // src/chat/identities/user-cache.ts
438
+ /**
439
+ * Cache of each User and their user Identities. Every signed-in request
440
+ * resolves its viewer, and person cards read the people that a message
441
+ * links to, so these reads go to the state cache instead of the database.
442
+ *
443
+ * Every write to a cached column or to a user Identity must call
444
+ * `clearCachedUser`. The other columns of a User, such as the timezone or
445
+ * the customization, are not in the cache.
446
+ */
447
+ const USER_TTL_MS = 864e5;
448
+ const MISSING_TTL_MS = 6e4;
449
+ const SETTLE_MS = 1e4;
450
+ /** The cache namespace of every key in this cache. */
451
+ const USER_CACHE_NAMESPACE = "identities";
452
+ const cachedUserSchema = z.object({
453
+ identities: z.array(z.object({
454
+ avatarUrl: z.string().nullable(),
455
+ displayName: z.string().nullable(),
456
+ handle: z.string().nullable(),
457
+ id: z.string(),
458
+ provider: z.string(),
459
+ providerSubjectId: z.string(),
460
+ providerTenantId: z.string(),
461
+ updatedAt: z.coerce.date()
462
+ })),
463
+ user: z.object({
464
+ displayName: z.string().nullable(),
465
+ id: z.string(),
466
+ isAdmin: z.boolean(),
467
+ primaryEmail: z.string()
468
+ })
469
+ });
470
+ const versionSchema = z.object({
471
+ token: z.string(),
472
+ writtenAtMs: z.number()
473
+ });
474
+ function versionKey(userId) {
475
+ return `${cacheKeyPrefix(USER_CACHE_NAMESPACE)}version:${userId}`;
476
+ }
477
+ function cache() {
478
+ return createCache(getStateAdapter(), USER_CACHE_NAMESPACE);
479
+ }
480
+ async function readVersion(userId) {
481
+ const state = getStateAdapter();
482
+ const stored = versionSchema.safeParse(await state.get(versionKey(userId)));
483
+ if (stored.success) return stored.data;
484
+ const created = {
485
+ token: randomUUID(),
486
+ writtenAtMs: 0
487
+ };
488
+ if (await state.setIfNotExists(versionKey(userId), created, 2 * USER_TTL_MS)) return created;
489
+ return versionSchema.parse(await state.get(versionKey(userId)));
490
+ }
491
+ async function loadUser(db, userId) {
492
+ const rows = await db.select({
493
+ avatarUrl: juniorIdentities.avatarUrl,
494
+ displayName: juniorIdentities.displayName,
495
+ handle: juniorIdentities.handle,
496
+ identityId: juniorIdentities.id,
497
+ provider: juniorIdentities.provider,
498
+ providerSubjectId: juniorIdentities.providerSubjectId,
499
+ providerTenantId: juniorIdentities.providerTenantId,
500
+ updatedAt: juniorIdentities.updatedAt,
501
+ userDisplayName: juniorUsers.displayName,
502
+ userId: juniorUsers.id,
503
+ userIsAdmin: juniorUsers.isAdmin,
504
+ userPrimaryEmail: juniorUsers.primaryEmail
505
+ }).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));
506
+ const first = rows[0];
507
+ if (!first) return null;
508
+ return {
509
+ identities: rows.flatMap((row) => row.identityId && row.provider && row.providerSubjectId && row.providerTenantId !== null && row.updatedAt ? [{
510
+ avatarUrl: row.avatarUrl,
511
+ displayName: row.displayName,
512
+ handle: row.handle,
513
+ id: row.identityId,
514
+ provider: row.provider,
515
+ providerSubjectId: row.providerSubjectId,
516
+ providerTenantId: row.providerTenantId,
517
+ updatedAt: row.updatedAt
518
+ }] : []),
519
+ user: {
520
+ displayName: first.userDisplayName,
521
+ id: first.userId,
522
+ isAdmin: first.userIsAdmin,
523
+ primaryEmail: first.userPrimaryEmail
524
+ }
525
+ };
526
+ }
527
+ /** Read one User and their user Identities by User id. */
528
+ async function readCachedUser(db, userId) {
529
+ const version = await readVersion(userId);
530
+ const settled = Date.now() - version.writtenAtMs >= SETTLE_MS;
531
+ const cached = await cache().getOrLoad(`user:${userId}:${version.token}`, async () => {
532
+ const value = await loadUser(db, userId);
533
+ if (!settled) return { value };
534
+ return {
535
+ value,
536
+ ttlMs: value ? USER_TTL_MS : MISSING_TTL_MS
537
+ };
538
+ });
539
+ return cached ? cachedUserSchema.parse(cached) : void 0;
540
+ }
541
+ /**
542
+ * Read one User and their user Identities by normalized primary email. A
543
+ * primary email never changes, so the email to User id entry stays valid.
544
+ * A missing User is not cached: a first sign-in can create it at any time.
545
+ */
546
+ async function readCachedUserByEmail(db, normalizedEmail) {
547
+ const userId = await cache().getOrLoad(emailKey(normalizedEmail), async () => {
548
+ const id = (await db.select({ id: juniorUsers.id }).from(juniorUsers).where(eq(juniorUsers.primaryEmailNormalized, normalizedEmail)).limit(1))[0]?.id ?? null;
549
+ return id ? {
550
+ value: id,
551
+ ttlMs: USER_TTL_MS
552
+ } : { value: null };
553
+ });
554
+ return userId ? await readCachedUser(db, userId) : void 0;
555
+ }
556
+ function emailKey(normalizedEmail) {
557
+ return `email:${normalizedEmail}`;
558
+ }
559
+ /** Clear the cached User after a write to their row or user Identities. */
560
+ async function clearCachedUser(userId) {
561
+ await getStateAdapter().set(versionKey(userId), {
562
+ token: randomUUID(),
563
+ writtenAtMs: Date.now()
564
+ }, 2 * USER_TTL_MS);
565
+ }
398
566
  // src/chat/identities/sql.ts
399
567
  function dateFromMs$1(ms) {
400
568
  return new Date(ms);
@@ -482,6 +650,7 @@ async function upsertIdentityRecord(executor, identity, linkedUserId, nowMs) {
482
650
  if (linkedUserId) throw new Error("Identity conflicts with linked user");
483
651
  throw new Error("Identity upsert returned no row");
484
652
  }
653
+ for (const changedUserId of /* @__PURE__ */ new Set([existing?.userId, row.userId])) if (changedUserId) await clearCachedUser(changedUserId);
485
654
  if (!existing?.userId && row.userId && identity.kind === "user") await recordStartedConversationParticipants(executor, {
486
655
  identityId: row.id,
487
656
  userId: row.userId
@@ -537,6 +706,7 @@ async function deleteProviderIdentityForSlackUser(executor, slackTeamId, slackUs
537
706
  /** Remove one exact provider identity owned by a user. */
538
707
  async function deleteProviderIdentityForUser(executor, userId, provider, providerSubjectId) {
539
708
  await executor.db().delete(juniorIdentities).where(and(eq(juniorIdentities.userId, userId), eq(juniorIdentities.provider, provider), eq(juniorIdentities.providerTenantId, ""), eq(juniorIdentities.providerSubjectId, providerSubjectId)));
709
+ await clearCachedUser(userId);
540
710
  }
541
711
  /**
542
712
  * Save one Google sign-in. Link the Google identity to the user of its
@@ -1970,12 +2140,6 @@ function treeHasAnnotationKey(rootConversationId, key) {
1970
2140
  where ${and(eq(annotated.rootConversationId, rootConversationId), annotationKeyMatches(key))}
1971
2141
  )`;
1972
2142
  }
1973
- /** Return the IDs in `conversationIds` that have an Annotation with `key`. */
1974
- async function conversationIdsWithAnnotation(db, conversationIds, key) {
1975
- if (conversationIds.length === 0) return /* @__PURE__ */ new Set();
1976
- const rows = await db.selectDistinct({ conversationId: juniorConversationAnnotations.conversationId }).from(juniorConversationAnnotations).where(and(inArray(juniorConversationAnnotations.conversationId, [...conversationIds]), annotationKeyMatches(key)));
1977
- return new Set(rows.map((row) => row.conversationId));
1978
- }
1979
2143
  // src/chat/conversations/sql/message-search.ts
1980
2144
  const EXCERPT_WITHOUT_QUERY_CHARS = 240;
1981
2145
  var SqlConversationMessageSearchStore = class {
@@ -2100,4 +2264,4 @@ async function closeDb() {
2100
2264
  current = void 0;
2101
2265
  await previous?.db.close();
2102
2266
  }
2103
- export { conversationDetailTouch as $, setFirstConversationLocation as A, recordGoogleSignIn as B, deliversFinalText as C, turnBehavior as D, postsRunNotices as E, saveActorAvatar as F, parseSessionSource as G, upsertLinkedIdentity as H, deleteProviderIdentityForSlackUser as I, agentTurnTotalTokens as J, addAgentTurnUsage as K, deleteProviderIdentityForUser as L, SYSTEM_IDENTITY_ID as M, findActorIdentityId as N, conversationKindFromRow as O, resolveActorIdentityId as P, rootConversationIsArchived as Q, findUserByVerifiedEmails as R, withConversationMutationLock as S, isTopLevelKind as T, claimProviderConversation as U, saveUserTimezone as V, getConversationIdByProviderConversation as W, hasAgentTurnUsage as X, agentTurnUsageSchema as Y, resolveRootConversationId as Z, setArchivedAt as _, getConversationStore as a, sameDestination as at, userMessageQueries as b, conversationIdsWithAnnotation as c, createSqlConversationEventStore as d, nextDetailVersion as et, eventFromRow as f, readConversationTrees as g, conversationDescendants as h, getConversationMessageSearchStore as i, requireSlackDestination as it, startLocationThread as j, locationFromRow as k, hasAnnotationKey as l, conversationAncestors as m, db_exports as n, createSlackDestination as nt, getDb as o, withConversationEventLock as p, agentTurnCostUsd as q, getConversationEventStore as r, parseDestination as rt, getSqlExecutor as s, closeDb as t, touchConversationDetail as tt, treeHasAnnotationKey as u, loadConversationSlackTenantIds as v, isPersonInput as w, createSqlStore as x, lastMessageAtSql as y, readUserTimezone as z };
2267
+ export { resolveRootConversationId as $, startLocationThread as A, saveUserTimezone as B, isPersonInput as C, conversationKindFromRow as D, turnBehavior as E, deleteProviderIdentityForSlackUser as F, claimProviderConversation as G, clearCachedUser as H, deleteProviderIdentityForUser as I, addAgentTurnUsage as J, getConversationIdByProviderConversation as K, findUserByVerifiedEmails as L, findActorIdentityId as M, resolveActorIdentityId as N, locationFromRow as O, saveActorAvatar as P, hasAgentTurnUsage as Q, readUserTimezone as R, deliversFinalText as S, postsRunNotices as T, readCachedUserByEmail as U, upsertLinkedIdentity as V, createCache as W, agentTurnTotalTokens as X, agentTurnCostUsd as Y, agentTurnUsageSchema as Z, loadConversationSlackTenantIds as _, getConversationStore as a, parseDestination as at, createSqlStore as b, hasAnnotationKey as c, eventFromRow as d, rootConversationIsArchived as et, withConversationEventLock as f, setArchivedAt as g, readConversationTrees as h, getConversationMessageSearchStore as i, createSlackDestination as it, SYSTEM_IDENTITY_ID as j, setFirstConversationLocation as k, treeHasAnnotationKey as l, conversationDescendants as m, db_exports as n, nextDetailVersion as nt, getDb as o, requireSlackDestination as ot, conversationAncestors as p, parseSessionSource as q, getConversationEventStore as r, touchConversationDetail as rt, getSqlExecutor as s, sameDestination as st, closeDb as t, conversationDetailTouch as tt, createSqlConversationEventStore as u, lastMessageAtSql as v, isTopLevelKind as w, withConversationMutationLock as x, userMessageQueries as y, recordGoogleSignIn as z };
@@ -1,6 +1,6 @@
1
1
  import { _ as withScope } from "./sentry-BRTJqumy.js";
2
- import "./config-BOByVnxe.js";
3
- import { h as logWarn, p as logException } from "./logging-CJTi5niy.js";
2
+ import "./config-9nHoFiJP.js";
3
+ import { h as logWarn, p as logException } from "./logging-BIclibct.js";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  import { sql } from "drizzle-orm";
6
6
  import { bigint, boolean, check, date, doublePrecision, foreignKey, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
@@ -121,6 +121,7 @@ const juniorConversations = pgTable("junior_conversations", {
121
121
  lastEnqueuedAt: timestamptz("last_enqueued_at"),
122
122
  parentConversationId: text("parent_conversation_id").references(() => juniorConversations.conversationId),
123
123
  kind: text("kind").$type(),
124
+ agentConfig: jsonb("agent_config_json").$type(),
124
125
  archivedAt: timestamptz("archived_at"),
125
126
  legacyChildArchivedAt: timestamptz("child_archived_at"),
126
127
  forkedFromConversationId: text("forked_from_conversation_id").references(() => juniorConversations.conversationId, { onDelete: "set null" }),
@@ -162,7 +163,11 @@ const juniorAttachments = pgTable("junior_attachments", {
162
163
  conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
163
164
  /** Service that stores the file bytes. */
164
165
  storageProvider: text("storage_provider").notNull(),
165
- storageKey: text("storage_key").notNull(),
166
+ /**
167
+ * Object key of the stored bytes. Null for a file that Junior records
168
+ * without storing, such as a large Slack file.
169
+ */
170
+ storageKey: text("storage_key"),
166
171
  /** Provider that supplied the file. */
167
172
  provider: text("provider"),
168
173
  /** File id assigned by the source provider. */
@@ -170,7 +175,8 @@ const juniorAttachments = pgTable("junior_attachments", {
170
175
  filename: text("filename").notNull(),
171
176
  contentType: text("content_type").notNull(),
172
177
  bytes: integer("bytes").notNull(),
173
- sha256: text("sha256").notNull(),
178
+ /** Digest of the stored bytes. Null when `storage_key` is null. */
179
+ sha256: text("sha256"),
174
180
  visionSummary: text("vision_summary"),
175
181
  createdAt: timestamptz("created_at").notNull(),
176
182
  /** Set when conversation purge marks the attachment unavailable. */
@@ -180,6 +186,28 @@ const juniorAttachments = pgTable("junior_attachments", {
180
186
  index("junior_attachments_provider_idx").on(table.conversationId, table.provider, table.providerId),
181
187
  index("junior_attachments_gc_idx").on(table.storageProvider, table.deleteRequestedAt, table.createdAt)
182
188
  ]);
189
+ /**
190
+ * Browser uploads that wait for a web Message.
191
+ *
192
+ * A row binds one object key to the viewer, Conversation, and Message
193
+ * idempotency key that asked for it. A Message turns the upload into a
194
+ * `junior_attachments` row with the same id. Cleanup deletes the object of an
195
+ * upload that no Message used.
196
+ */
197
+ const juniorAttachmentUploads = pgTable("junior_attachment_uploads", {
198
+ id: text("id").primaryKey(),
199
+ /** No foreign key: a new Conversation has no row until its first send. */
200
+ conversationId: text("conversation_id").notNull(),
201
+ userId: text("user_id").notNull(),
202
+ idempotencyKey: text("idempotency_key").notNull(),
203
+ storageProvider: text("storage_provider").notNull(),
204
+ storageKey: text("storage_key").notNull(),
205
+ filename: text("filename").notNull(),
206
+ contentType: text("content_type").notNull(),
207
+ /** Size that the browser declared and the upload target allows. */
208
+ bytes: integer("bytes").notNull(),
209
+ createdAt: timestamptz("created_at").notNull()
210
+ }, (table) => [index("junior_attachment_uploads_gc_idx").on(table.storageProvider, table.createdAt)]);
183
211
  // src/db/schema/code.ts
184
212
  /** Repository known to Junior through an installed code plugin. */
185
213
  const juniorCodeRepositories = pgTable("junior_code_repositories", {
@@ -195,6 +223,7 @@ const juniorCodeChanges = pgTable("junior_code_changes", {
195
223
  id: uuid("id").primaryKey(),
196
224
  closedAt: timestamptz("closed_at"),
197
225
  conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
226
+ draft: boolean("draft").notNull().default(false),
198
227
  /** Latest push, review, or comment by a person, from the code plugin. */
199
228
  lastActivityAt: timestamptz("last_activity_at"),
200
229
  mergedAt: timestamptz("merged_at"),
@@ -753,6 +782,7 @@ const juniorSnapshots = pgTable("junior_snapshots", {
753
782
  // src/db/schema.ts
754
783
  const juniorSqlSchema = {
755
784
  juniorArtifacts,
785
+ juniorAttachmentUploads,
756
786
  juniorAttachments,
757
787
  juniorCodeChanges,
758
788
  juniorCodeRepositories,
@@ -901,9 +931,18 @@ const POOL_MAX = 10;
901
931
  function toWebSocketError(error, failure) {
902
932
  if (error instanceof Error) return error;
903
933
  const event = error ?? {};
904
- const reason = typeof event.message === "string" && event.message || event.error instanceof Error && event.error.message || typeof event.type === "string" && event.type || String(error);
934
+ const cause = event.error instanceof Error ? event.error : void 0;
935
+ const reason = typeof event.message === "string" && event.message || cause?.message || cause && `${cause.name} (no message)` || typeof event.type === "string" && event.type || String(error);
905
936
  return new Error(`WebSocket ${failure}: ${reason}`, event.error === void 0 ? void 0 : { cause: event.error });
906
937
  }
938
+ function warnWebSocketFailure(name, error, failure) {
939
+ const reported = toWebSocketError(error, failure);
940
+ logWarn(name, {
941
+ "app.db.driver": "neon",
942
+ "error.type": reported.name,
943
+ "exception.message": reported.message
944
+ });
945
+ }
907
946
  /**
908
947
  * Sends a pool query over Neon's SQL-over-HTTP endpoint when no idle
909
948
  * WebSocket client is free.
@@ -959,7 +998,7 @@ var OverflowPool = class extends Pool {
959
998
  client.release();
960
999
  return;
961
1000
  }
962
- logException(toWebSocketError(error, "connect failed"), "db.pool.client.connect_failed", { "app.db.driver": "neon" });
1001
+ warnWebSocketFailure("db.pool.client.connect_failed", error, "connect failed");
963
1002
  });
964
1003
  }
965
1004
  /** Keep every pool query in `callback` on WebSocket. */
@@ -1120,12 +1159,7 @@ function createNeonJuniorSqlExecutor(args) {
1120
1159
  dispatcher
1121
1160
  });
1122
1161
  pool.on("error", (error) => {
1123
- const failure = toWebSocketError(error, "idle client failed");
1124
- logWarn("db.pool.client.failed", {
1125
- "app.db.driver": "neon",
1126
- "error.type": failure.name,
1127
- "exception.message": failure.message
1128
- });
1162
+ warnWebSocketFailure("db.pool.client.failed", error, "idle client failed");
1129
1163
  });
1130
1164
  if (onInfo) forwardInfoMessages(pool, onInfo);
1131
1165
  return new NeonExecutor(pool, dispatcher);
@@ -1265,4 +1299,4 @@ function createJuniorSqlExecutor(args) {
1265
1299
  statementTimeoutMs
1266
1300
  });
1267
1301
  }
1268
- export { juniorConversations as A, isUserInstruction as C, juniorCodeChanges as D, juniorConversationAnnotations as E, juniorUsers as M, juniorDestinations as N, juniorCodeRepositories as O, juniorArtifacts as P, juniorConversationMetrics as S, juniorApiTokens as T, juniorConversationReadPositions as _, juniorPushSubscriptions as a, juniorConversationBriefs as b, juniorReviewItemSlackCards as c, juniorAutomationVersions as d, juniorAutomations as f, juniorAgentInvocations as g, juniorAgentBindings as h, juniorWorkspaces as i, juniorIdentities as j, juniorAttachments as k, juniorReviewItems as l, juniorLocationConfigurations as m, juniorSnapshots as n, juniorReviewItemAssignees as o, juniorStats as p, juniorWorkspaceRepos as r, juniorReviewItemConversations as s, createJuniorSqlExecutor as t, juniorAutomationRuns as u, juniorConversationParticipants as v, juniorConversationEvents as w, CONVERSATION_METRICS as x, juniorConversationBindings as y };
1302
+ export { juniorAttachments as A, isUserInstruction as C, juniorCodeChanges as D, juniorConversationAnnotations as E, juniorArtifacts as F, juniorIdentities as M, juniorUsers as N, juniorCodeRepositories as O, juniorDestinations as P, juniorConversationMetrics as S, juniorApiTokens as T, juniorConversationReadPositions as _, juniorPushSubscriptions as a, juniorConversationBriefs as b, juniorReviewItemSlackCards as c, juniorAutomationVersions as d, juniorAutomations as f, juniorAgentInvocations as g, juniorAgentBindings as h, juniorWorkspaces as i, juniorConversations as j, juniorAttachmentUploads as k, juniorReviewItems as l, juniorLocationConfigurations as m, juniorSnapshots as n, juniorReviewItemAssignees as o, juniorStats as p, juniorWorkspaceRepos as r, juniorReviewItemConversations as s, createJuniorSqlExecutor as t, juniorAutomationRuns as u, juniorConversationParticipants as v, juniorConversationEvents as w, CONVERSATION_METRICS as x, juniorConversationBindings as y };
@@ -555,88 +555,4 @@ const newConversationEventSchema = z.object({
555
555
  idempotencyKey: z.string().min(1).optional(),
556
556
  createdAtMs: z.number().finite()
557
557
  }).strict();
558
- // src/chat/attachments/media.ts
559
- const INPUT_IMAGE_TYPES = [
560
- "image/png",
561
- "image/jpeg",
562
- "image/gif",
563
- "image/webp"
564
- ];
565
- /** Video types that browsers play in a `<video>` element. */
566
- const INLINE_VIDEO_TYPES = ["video/mp4", "video/webm"];
567
- /** Leading bytes of each accepted image type. `null` matches any byte. */
568
- const IMAGE_SIGNATURES = [
569
- {
570
- mediaType: "image/png",
571
- bytes: [
572
- 137,
573
- 80,
574
- 78,
575
- 71,
576
- 13,
577
- 10,
578
- 26,
579
- 10
580
- ]
581
- },
582
- {
583
- mediaType: "image/jpeg",
584
- bytes: [
585
- 255,
586
- 216,
587
- 255
588
- ]
589
- },
590
- {
591
- mediaType: "image/gif",
592
- bytes: [
593
- 71,
594
- 73,
595
- 70,
596
- 56,
597
- 55,
598
- 97
599
- ]
600
- },
601
- {
602
- mediaType: "image/gif",
603
- bytes: [
604
- 71,
605
- 73,
606
- 70,
607
- 56,
608
- 57,
609
- 97
610
- ]
611
- },
612
- {
613
- mediaType: "image/webp",
614
- bytes: [
615
- 82,
616
- 73,
617
- 70,
618
- 70,
619
- null,
620
- null,
621
- null,
622
- null,
623
- 87,
624
- 69,
625
- 66,
626
- 80
627
- ]
628
- }
629
- ];
630
- /**
631
- * Detect an accepted image type from file bytes. Use this instead of a file
632
- * name or declared content type, which can be wrong.
633
- */
634
- function detectImageMediaType(data) {
635
- return IMAGE_SIGNATURES.find(({ bytes }) => data.length >= bytes.length && bytes.every((byte, index) => byte === null || data[index] === byte))?.mediaType;
636
- }
637
- /** Report whether a media type is a raster image accepted by vision models. */
638
- function isVisionImageMediaType(mediaType) {
639
- const normalized = mediaType.split(";", 1)[0]?.trim().toLowerCase();
640
- return normalized ? INPUT_IMAGE_TYPES.some((type) => type === normalized) : false;
641
- }
642
- export { instructionProvenanceFor as _, KNOWN_CONVERSATION_EVENT_TYPES as a, conversationTurnFailureCodeSchema as c, historyReplacementSchema as d, newConversationEventSchema as f, instructionActors as g, contextProvenance as h, isVisionImageMediaType as i, conversationTurnFailureReasonSchema as l, agentInstructionProvenance as m, INPUT_IMAGE_TYPES as n, agentHistoryItemSchema as o, encodeHistoryPayload as p, detectImageMediaType as r, conversationEventDataSchema as s, INLINE_VIDEO_TYPES as t, decodeStoredConversationEvent as u, sameActorIdentity as v, usageSchema as y };
558
+ export { conversationTurnFailureReasonSchema as a, newConversationEventSchema as c, contextProvenance as d, instructionActors as f, usageSchema as h, conversationTurnFailureCodeSchema as i, encodeHistoryPayload as l, sameActorIdentity as m, agentHistoryItemSchema as n, decodeStoredConversationEvent as o, instructionProvenanceFor as p, conversationEventDataSchema as r, historyReplacementSchema as s, KNOWN_CONVERSATION_EVENT_TYPES as t, agentInstructionProvenance as u };
@@ -1,6 +1,6 @@
1
1
  import { a as getClient, c as init, i as getActiveSpan, o as getGlobalScope, p as spanToJSON, s as getTraceData } from "./sentry-BRTJqumy.js";
2
- import { B as getDeploymentTelemetryAttributes, z as getDeploymentServiceVersion } from "./logging-CJTi5niy.js";
3
- import { n as getCurrentConversationPrivacy } from "./conversation-privacy-C0eRxsgb.js";
2
+ import { B as getDeploymentTelemetryAttributes, z as getDeploymentServiceVersion } from "./logging-BIclibct.js";
3
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-D-5HTXjS.js";
4
4
  import { n as redactSandboxEgressProxyPath } from "./proxy-path-BHYoKZdq.js";
5
5
  import { t as consumePrivateTraceResultMarker } from "./private-trace-result-CE7_lEdq.js";
6
6
  import { n as promoteHttpRouteName, r as routeNameMiddleware, t as nameRequestRoute } from "./sentry-route-name-BhwWnfqj.js";
@@ -162,7 +162,7 @@ const SECRET_HEADER_NAMES = /* @__PURE__ */ new Set([
162
162
  "x-slack-signature"
163
163
  ]);
164
164
  const SDK_REQUEST_HEADER_PREFIX = "http.request.header.";
165
- const URL_SPAN_NAME = /^([A-Z]+ )((?:https?:\/\/|\/)\S*)$/;
165
+ const SPAN_METHOD = /^[A-Z]+$/;
166
166
  /**
167
167
  * Drop the query and fragment, hide the sandbox egress credential token, and
168
168
  * keep only the host of a push endpoint.
@@ -174,8 +174,17 @@ function scrubUrl(value) {
174
174
  return redactSandboxEgressProxyPath(url);
175
175
  }
176
176
  function scrubSpanName(name) {
177
- const match = URL_SPAN_NAME.exec(name);
178
- return match ? `${match[1]}${scrubUrl(match[2] ?? "")}` : name;
177
+ const space = name.indexOf(" ");
178
+ if (space < 1) return name;
179
+ const method = name.slice(0, space);
180
+ const target = name.slice(space + 1);
181
+ const isUrl = [
182
+ "https://",
183
+ "http://",
184
+ "/"
185
+ ].some((prefix) => target.startsWith(prefix));
186
+ if (!SPAN_METHOD.test(method) || !isUrl || /\s/.test(target)) return name;
187
+ return `${method} ${scrubUrl(target)}`;
179
188
  }
180
189
  function isSecretHeaderAttribute(key) {
181
190
  const lowerKey = key.toLowerCase();
@@ -0,0 +1,37 @@
1
+ import { D as conversationKindFromRow, o as getDb } from "./db-BJNo6fK5.js";
2
+ import { j as juniorConversations } from "./executor-DBIaOeJ_.js";
3
+ import { desc, eq, sql } from "drizzle-orm";
4
+ // src/chat/conversations/lineage.ts
5
+ /**
6
+ * Read the parent chain of a Conversation in one query, root first, with the
7
+ * Conversation last. Returns an empty list when the Conversation is missing.
8
+ *
9
+ * The chain stops at a parent that is missing or that is already in the
10
+ * chain. Then the first entry still has a `parentConversationId`, so callers
11
+ * can tell a broken chain from one that ends at a root.
12
+ */
13
+ async function readConversationLineage(conversationId) {
14
+ const lineage = sql`(
15
+ with recursive lineage(conversation_id, parent_conversation_id, depth, path) as (
16
+ select selected.conversation_id, selected.parent_conversation_id, 0, array[selected.conversation_id]
17
+ from junior_conversations selected
18
+ where selected.conversation_id = ${conversationId}
19
+ union all
20
+ select parent.conversation_id, parent.parent_conversation_id, lineage.depth + 1, lineage.path || parent.conversation_id
21
+ from junior_conversations parent
22
+ join lineage on parent.conversation_id = lineage.parent_conversation_id
23
+ where parent.conversation_id <> all(lineage.path)
24
+ )
25
+ select conversation_id, depth from lineage
26
+ ) conversation_lineage`;
27
+ return (await getDb().select({
28
+ conversationId: juniorConversations.conversationId,
29
+ kind: juniorConversations.kind,
30
+ parentConversationId: juniorConversations.parentConversationId
31
+ }).from(juniorConversations).innerJoin(lineage, eq(sql`conversation_lineage.conversation_id`, juniorConversations.conversationId)).orderBy(desc(sql`conversation_lineage.depth`))).map((row) => ({
32
+ conversationId: row.conversationId,
33
+ kind: conversationKindFromRow(row),
34
+ ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
35
+ }));
36
+ }
37
+ export { readConversationLineage as t };
@@ -1,5 +1,5 @@
1
1
  import { _ as withScope, d as setTag, f as setUser, h as startSpan, i as getActiveSpan, l as logger, n as captureMessage, p as spanToJSON, s as getTraceData, t as captureException } from "./sentry-BRTJqumy.js";
2
- import { t as JUNIOR_VERSION } from "./version-DcZ40a0g.js";
2
+ import { t as JUNIOR_VERSION } from "./version-GVBMW2jA.js";
3
3
  import path from "node:path";
4
4
  import { styleText } from "node:util";
5
5
  import { ConfigError, configureSync, getConfig, getLogger } from "@logtape/logtape";
@@ -1,13 +1,12 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { go as readConversationAccessFromSql, po as canAccessConversation, zn as renderUntrustedTag } from "./projection-BgwEE36_.js";
3
- import { n as botConfig } from "./config-BOByVnxe.js";
4
- import { M as SYSTEM_IDENTITY_ID, a as getConversationStore, o as getDb } from "./db-CoMNr2Zm.js";
5
- import { Ft as actorFromRun, It as toolInvocationDestination } from "./agent-runner-Q9GkoerG.js";
6
- import { I as findChildAgentConversationId, M as AgentMessagePausedError, O as createAgentInvocationForMessage, P as AgentMessageTargetError, x as enqueueAgentInvocation } from "./warmup-CwKbxQLl.js";
7
- import { C as getActiveAgentInvocationForConversation, E as getLatestAgentInvocationForConversation, W as PARENT_AGENT_TARGET } from "./turn-user-message-BSPmkm7X.js";
8
- import { b as postAutomatedTurnLimitNoticeForConversation, t as EVENT_WAIT_MS, w as admitAutomatedTurn } from "./notification-Bv25xbj0.js";
9
- import { r as appendAndEnqueueInboundMessage } from "./store-B1zepKG8.js";
10
- import { a as enqueueAgentMessageToParent } from "./result-C2Vn8QGn.js";
2
+ import { Jn as renderUntrustedTag, go as canAccessConversation, yo as readConversationAccessFromSql } from "./projection-w_X-zi7v.js";
3
+ import { n as botConfig } from "./config-9nHoFiJP.js";
4
+ import { a as getConversationStore, j as SYSTEM_IDENTITY_ID, o as getDb } from "./db-BJNo6fK5.js";
5
+ import { Ft as toolInvocationDestination, Pt as actorFromRun } from "./agent-runner-bY4_0UPm.js";
6
+ import { M as EVENT_WAIT_MS, Z as postAutomatedTurnLimitNoticeForConversation, tt as admitAutomatedTurn } from "./session-stop-BcAXze8a.js";
7
+ import { A as readChildConversationSender, H as enqueueAgentInvocation, Z as createAgentInvocationForMessage, at as findChildAgentConversationId, g as getActiveAgentInvocationForConversation, lt as PARENT_AGENT_TARGET, rt as AgentMessageTargetError, tt as AgentMessagePausedError, y as getLatestAgentInvocationForConversation } from "./warmup-BW2qwnal.js";
8
+ import { r as appendAndEnqueueInboundMessage } from "./store-E3x2Fg_F.js";
9
+ import { a as enqueueAgentMessageToParent } from "./result-PVBeU0Wf.js";
11
10
  // src/chat/agent-invocations/top-level-message.ts
12
11
  const AGENT_MESSAGE_EVENT_NAMESPACE = "junior";
13
12
  /** Event type of a message from another top-level agent. */
@@ -116,7 +115,7 @@ function bindMessageAgent(run, options) {
116
115
  call.signal?.throwIfAborted();
117
116
  const queue = typeof options.queue === "function" ? options.queue() : options.queue;
118
117
  if (input.to === "parent") {
119
- const sender = await getActiveAgentInvocationForConversation(run.conversationId) ?? await getLatestAgentInvocationForConversation(run.conversationId);
118
+ const sender = await getActiveAgentInvocationForConversation(run.conversationId) ?? await getLatestAgentInvocationForConversation(run.conversationId) ?? await readChildConversationSender(run.conversationId);
120
119
  if (!sender) throw new AgentMessageTargetError("This conversation has no parent agent");
121
120
  await enqueueAgentMessageToParent({
122
121
  actor,