@sentry/junior 0.295.0 → 0.297.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 (84) hide show
  1. package/dist/{admin-ifgjyfpF.js → admin-tmGIw4KS.js} +2 -2
  2. package/dist/{agent-runner-DjMTPWEO.js → agent-runner-CneTquAE.js} +468 -1947
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +7 -7
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +306 -569
  7. package/dist/{app-uiTzRbvq.d.ts → app-BJojZ7HL.d.ts} +7 -2
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +64 -44
  10. package/dist/attempt-selection-ClP3MMPr.js +61 -0
  11. package/dist/{automation-yJX3C7i3.js → automation-BrP6ImrC.js} +1 -1
  12. package/dist/{background-compaction-queue-DUkHZjmL.js → background-compaction-queue-CwfJy3Cd.js} +4 -88
  13. package/dist/{briefs-CbNYM-q2.js → briefs-uFTuhMqA.js} +3 -3
  14. package/dist/{catalog-runtime-DgouZKZm.js → catalog-runtime-0kuQqYL4.js} +1 -1
  15. package/dist/cli/chat.js +19 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-DvnTPCfp.js → config-Dj9M_nqB.js} +18 -2
  23. package/dist/{connections-CWaIVl_1.js → connections-B96JUM5o.js} +6 -6
  24. package/dist/{conversation-CMkSmi02.js → conversation-CvcBU1z2.js} +2 -16
  25. package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-BSMlGZnS.js} +1 -1
  26. package/dist/{conversation-privacy-DPjv4SnA.js → conversation-privacy-DI29jbZV.js} +1 -1
  27. package/dist/conversation-turn-CZWBr091.js +805 -0
  28. package/dist/{credential-sync-BhbaZfmO.js → credential-sync-Blhx4_xf.js} +14 -13
  29. package/dist/{db-Dts2XvLu.js → db-Br0tfAo7.js} +54 -32
  30. package/dist/{db-CCUqQe0E.d.ts → db-CrtyFRz7.d.ts} +13 -1
  31. package/dist/{executor-Ck73J0wP.js → executor-BMPipFVA.js} +19 -5
  32. package/dist/instrumentation.js +19 -2
  33. package/dist/{logging-9OAq-fdg.js → logging-CQjlDQYX.js} +1 -1
  34. package/dist/{message-CtaPzC7m.js → message-BOZEIuxy.js} +15 -13
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +3 -2
  37. package/dist/{session-stop-DkxI5vc3.js → notification-gusCgdQ6.js} +14 -933
  38. package/dist/{oauth-callback-server-C_LXY1d4.js → oauth-callback-server-V_DuMuNX.js} +2 -2
  39. package/dist/{projection-BzJQncZV.js → projection-B08mfi0u.js} +479 -145
  40. package/dist/{prompt-Cbq5b4SO.js → prompt-BlutWLNt.js} +4 -4
  41. package/dist/prompt-input-Dxn8cDC0.js +1424 -0
  42. package/dist/{registry-cbpOxO4M.js → registry-BDWgCJDf.js} +1 -1
  43. package/dist/reporting-window-DopzcOHh.js +137 -0
  44. package/dist/{resolve-t-pmRdwS.js → resolve-2Z_o_SsI.js} +3 -3
  45. package/dist/result-CAujiaci.js +463 -0
  46. package/dist/{runner-CHv9X9TH.js → runner-D2Chc02N.js} +9 -8
  47. package/dist/{sandbox-egress-signals-Yy3fSCbg.js → sandbox-egress-signals-CFoJduFj.js} +1 -1
  48. package/dist/{schema-BhneuGYv.js → schema-Bqa5NbcP.js} +22 -48
  49. package/dist/{schema-TSEisVJR.d.ts → schema-Ce2XCS7O.d.ts} +24 -107
  50. package/dist/{service-account-DjPIwCMj.js → service-account-C9kRQEb_.js} +3 -3
  51. package/dist/{service-account-C4rBP8ne.js → service-account-CERfXEVU.js} +3 -3
  52. package/dist/session-stop-B-I1rAS1.js +181 -0
  53. package/dist/{skills-BZE2DP8I.js → skills-B0m1nZ_j.js} +3 -3
  54. package/dist/{spawn-BvULxIiu.js → spawn-CwMjRRtn.js} +6 -5
  55. package/dist/{state-CO9ETDzk.js → state-DFnmLmfn.js} +2 -2
  56. package/dist/{stop-CL-rdtQb.js → stop-BCH9VNGf.js} +329 -382
  57. package/dist/{store-DgD78_NK.js → store-B59rOYbS.js} +11 -4
  58. package/dist/{task-runner-CKOj6xla.js → store-m5bmdmsP.js} +929 -1559
  59. package/dist/task-queue-N0kuCknH.js +89 -0
  60. package/dist/task-runner-COOwR8qm.js +291 -0
  61. package/dist/thread-context-Cd44z_W5.js +248 -0
  62. package/dist/turn-cancel-DDu8TOwt.js +201 -0
  63. package/dist/turn-session-routing-BlCtVFRN.js +380 -0
  64. package/dist/{turn-failure-response-BTSo6SMJ.js → turn-user-message-ygLG3ylQ.js} +183 -358
  65. package/dist/turn-wake-DmQec4AG.js +161 -0
  66. package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
  67. package/dist/{validation-CXeYgBzq.js → validation-Ba2OcUse.js} +1 -1
  68. package/dist/{version-AQa7Fr2H.js → version-KNDzIAh6.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{viewer-Bqkb678l.js → viewer-BPpuN2f9.js} +3 -3
  71. package/dist/warmup-Bskrwmk1.js +2697 -0
  72. package/dist/{worker-Hl7N292I.js → worker-B1skZlit.js} +20 -8
  73. package/migrations/0101_drop_legacy_columns.sql +12 -0
  74. package/migrations/0102_code_change_last_activity.sql +1 -0
  75. package/migrations/0103_agent_invocation_fork.sql +8 -0
  76. package/migrations/meta/0101_snapshot.json +4496 -0
  77. package/migrations/meta/0102_snapshot.json +4502 -0
  78. package/migrations/meta/0103_snapshot.json +4509 -0
  79. package/migrations/meta/_journal.json +21 -0
  80. package/package.json +5 -4
  81. package/dist/result-DhgjR3nQ.js +0 -305
  82. package/dist/result-event-type-DD6BAgT7.js +0 -11
  83. package/dist/warmup-h6u1e9n0.js +0 -1869
  84. package/dist/work-yN_GAuXY.js +0 -768
@@ -1,20 +1,21 @@
1
- import { An as resolvePluginOAuthAccount, En as createUserTokenStore, Fi as resolveBaseUrl, Ni as formatProviderLabel, Pi as parseOAuthStatePayload, Yi as postSlackMessage, Z as getConversationPendingAuth, d as recordAuthorizationCompleted, oa as getSlackClient, ot as getTurnRecord, u as recordAuthenticationLinked } from "./projection-BzJQncZV.js";
2
- import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-DvnTPCfp.js";
3
- import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-9OAq-fdg.js";
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-B08mfi0u.js";
2
+ import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-Dj9M_nqB.js";
3
+ import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-CQjlDQYX.js";
4
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-Dts2XvLu.js";
5
+ import { H as upsertLinkedIdentity, P as resolveActorIdentityId, R as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-Br0tfAo7.js";
6
6
  import { i as homeDir } from "./package-discovery-DJhGdS4c.js";
7
- import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-cbpOxO4M.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DgouZKZm.js";
9
- import { t as discoverSkills } from "./skills-BZE2DP8I.js";
10
- import { It as wakeAuthorizedTurn, Lt as wakePausedTurn, Yt as deleteWebAuthorization, a as finalizeMcpAuthorization, d as getMcpStoredOAuthCredentials, f as putMcpStoredOAuthCredentials, o as deleteMcpAuthSession, u as getMcpAuthSession, y as lookupSlackUserProfile } from "./agent-runner-DjMTPWEO.js";
7
+ import { n as buildOAuthTokenRequest, r as parseOAuthTokenResponse, u as hasRequiredOAuthScope } from "./registry-BDWgCJDf.js";
8
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-0kuQqYL4.js";
9
+ import { t as discoverSkills } from "./skills-B0m1nZ_j.js";
10
+ import { b as lookupSlackUserProfile, d as getMcpAuthSession, f as getMcpStoredOAuthCredentials, o as finalizeMcpAuthorization, p as putMcpStoredOAuthCredentials, s as deleteMcpAuthSession } from "./agent-runner-CneTquAE.js";
11
11
  import { r as acquireActiveLock } from "./locks-D-0h111u.js";
12
- import { o as readIdentityById } from "./viewer-Bqkb678l.js";
13
- import { a as getStateAdapter } from "./state-CO9ETDzk.js";
12
+ import { o as readIdentityById } from "./viewer-BPpuN2f9.js";
13
+ import { a as getStateAdapter } from "./state-DFnmLmfn.js";
14
14
  import { t as readJuniorSecret } from "./secrets-DebYU866.js";
15
- import { gt as coerceThreadConversationState, pt as getPersistedThreadState } from "./task-runner-CKOj6xla.js";
16
- import { _ as getMcpProviderErrorAttributes } from "./service-account-DjPIwCMj.js";
17
- import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-CWaIVl_1.js";
15
+ import { a as getPersistedThreadState, c as coerceThreadConversationState } from "./turn-session-routing-BlCtVFRN.js";
16
+ import { i as wakePausedTurn, r as wakeAuthorizedTurn, s as deleteWebAuthorization } from "./turn-wake-DmQec4AG.js";
17
+ import { _ as getMcpProviderErrorAttributes } from "./service-account-C9kRQEb_.js";
18
+ import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-B96JUM5o.js";
18
19
  import { n as relayLocalOAuthCallback } from "./oauth-relay-CsfIazeF.js";
19
20
  import path from "node:path";
20
21
  import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
@@ -1,8 +1,8 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-DvnTPCfp.js";
3
- import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-9OAq-fdg.js";
2
+ import { i as getChatConfig } from "./config-Dj9M_nqB.js";
3
+ import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-CQjlDQYX.js";
4
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-Ck73J0wP.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-BMPipFVA.js";
6
6
  import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-BepyEUNm.js";
7
7
  import { randomUUID } from "node:crypto";
8
8
  import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
@@ -374,13 +374,22 @@ async function getConversationIdByProviderConversation(executor, args) {
374
374
  }
375
375
  /**
376
376
  * Bind provider coordinates to a durable conversation unless another
377
- * conversation has them. Return whether they belong to this conversation.
377
+ * conversation has them. Return the conversation that has them.
378
378
  */
379
- async function claimProviderConversation(executor, args) {
380
- return ((await executor.db().insert(juniorConversationBindings).values({
379
+ async function claimProviderConversationOwner(executor, args) {
380
+ const ownerId = (await executor.db().insert(juniorConversationBindings).values({
381
381
  ...args,
382
382
  createdAt: /* @__PURE__ */ new Date()
383
- }).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args)) === args.conversationId;
383
+ }).onConflictDoNothing().returning({ conversationId: juniorConversationBindings.conversationId }))[0]?.conversationId ?? await getConversationIdByProviderConversation(executor, args);
384
+ if (!ownerId) throw new Error("Provider conversation binding disappeared during claim");
385
+ return ownerId;
386
+ }
387
+ /**
388
+ * Bind provider coordinates to a durable conversation unless another
389
+ * conversation has them. Return whether they belong to this conversation.
390
+ */
391
+ async function claimProviderConversation(executor, args) {
392
+ return await claimProviderConversationOwner(executor, args) === args.conversationId;
384
393
  }
385
394
  /** Bind provider coordinates to a durable conversation in the caller's SQL scope. */
386
395
  async function bindProviderConversation(executor, args) {
@@ -855,58 +864,65 @@ const ROOT = {
855
864
  delivery: "location",
856
865
  promptMode: "conversation",
857
866
  gated: false,
867
+ failureNotice: "none",
868
+ sessionTasks: true,
858
869
  tools: {
859
870
  agents: "children",
860
871
  reviewDesk: true,
861
872
  subscriptions: true,
862
873
  userCustomization: true,
863
- reportBlocked: false,
864
- noReply: true,
865
- finishAutomationRun: false
874
+ reply: "none",
875
+ reportBlocked: "none",
876
+ noReply: true
866
877
  }
867
878
  };
868
879
  const PERSON_IN_THREAD = {
869
880
  ...ROOT,
881
+ sessionTasks: false,
870
882
  tools: {
871
883
  ...ROOT.tools,
872
884
  agents: "none"
873
885
  }
874
886
  };
875
- const AGENT_IN_CHILD = {
887
+ const AGENT_IN_THREAD = {
876
888
  delivery: "conversation",
877
889
  promptMode: "child_agent",
878
- gated: false,
890
+ gated: true,
891
+ failureNotice: "none",
892
+ sessionTasks: false,
879
893
  tools: {
880
894
  agents: "children_and_parent",
881
895
  reviewDesk: false,
882
896
  subscriptions: false,
883
897
  userCustomization: false,
884
- reportBlocked: true,
885
- noReply: true,
886
- finishAutomationRun: false
898
+ reply: "parent",
899
+ reportBlocked: "parent",
900
+ noReply: true
887
901
  }
888
902
  };
903
+ const AGENT_IN_TASK = {
904
+ ...AGENT_IN_THREAD,
905
+ missingAnswerError: "No reply was sent.",
906
+ failureNotice: "parent"
907
+ };
889
908
  const AUTOMATION_RUN = {
890
909
  delivery: "conversation",
891
910
  promptMode: "automation",
892
911
  gated: true,
912
+ failureNotice: "none",
913
+ sessionTasks: true,
893
914
  tools: {
894
915
  ...ROOT.tools,
895
- noReply: false,
896
- finishAutomationRun: true
916
+ reply: "automation",
917
+ reportBlocked: "automation"
897
918
  }
898
919
  };
899
- /**
900
- * Return the behavior of one Turn. `automationRun` marks the dispatch Turn of
901
- * a Scheduled or Event automation run. Kind alone cannot mark it: the
902
- * dispatch Turn is the only gated Turn on an `automation` Conversation, and a
903
- * person's reply or a Watch Event Turn there runs like a Turn on a root.
904
- */
920
+ /** Return the behavior of one Turn. */
905
921
  function turnBehavior(args) {
906
- if (args.automationRun) return AUTOMATION_RUN;
907
- if (isTopLevelKind(args.kind)) return ROOT;
908
- if (!args.personInput) return AGENT_IN_CHILD;
909
- if (args.kind === "thread") return PERSON_IN_THREAD;
922
+ if (args.kind === "root") return ROOT;
923
+ if (args.kind === "automation") return args.personInput ? ROOT : AUTOMATION_RUN;
924
+ if (args.kind === "thread") return args.personInput ? PERSON_IN_THREAD : AGENT_IN_THREAD;
925
+ if (!args.personInput) return AGENT_IN_TASK;
910
926
  throw new Error("A task Conversation cannot have a person's input");
911
927
  }
912
928
  /** Return whether a Conversation of this kind has no parent. */
@@ -930,8 +946,8 @@ function deliversFinalText(dispatch) {
930
946
  * Return whether the runtime may post a failure reply or a status notice,
931
947
  * such as an auth prompt, for a run outside `finishedRunReply`. The rule is
932
948
  * the same as for a final response. A chat Turn may post, also in a thread
933
- * that an Automation Conversation owns. An Automation run posts only a
934
- * declared message; its failed execution shows on the Automation.
949
+ * that an Automation Conversation owns. An Automation run posts only its
950
+ * `reply` text; its failed execution shows on the Automation.
935
951
  */
936
952
  function postsRunNotices(dispatch) {
937
953
  return deliversFinalText(dispatch);
@@ -993,8 +1009,7 @@ function destinationUpsertFromDestination(args) {
993
1009
  };
994
1010
  }
995
1011
  function executionStatusFromValue(value) {
996
- if (value === "awaiting_resume" || value === "paused") return "paused";
997
- if (value === "failed" || value === "idle" || value === "pending" || value === "running") return value;
1012
+ if (value === "failed" || value === "idle" || value === "paused" || value === "pending" || value === "running") return value;
998
1013
  throw new Error("Conversation record execution status is invalid");
999
1014
  }
1000
1015
  function destinationFromRow(destination) {
@@ -1089,6 +1104,13 @@ var SqlStore = class {
1089
1104
  async bindProviderConversation(args) {
1090
1105
  await bindProviderConversation(this.executor, args);
1091
1106
  }
1107
+ async claimProviderConversation(args) {
1108
+ const { atMs, ...binding } = args;
1109
+ return await this.executor.transaction(async () => {
1110
+ await ensureConversationRow(this.executor, binding.conversationId, atMs, { activity: "preserve" });
1111
+ return await claimProviderConversationOwner(this.executor, binding);
1112
+ });
1113
+ }
1092
1114
  async createChild(args) {
1093
1115
  const nowMs = args.nowMs ?? now();
1094
1116
  await this.withConversationMutation(args.parentConversationId, async () => {
@@ -2078,4 +2100,4 @@ async function closeDb() {
2078
2100
  current = void 0;
2079
2101
  await previous?.db.close();
2080
2102
  }
2081
- export { rootConversationIsArchived as $, setFirstConversationLocation as A, recordGoogleSignIn as B, deliversFinalText as C, turnBehavior as D, postsRunNotices as E, saveActorAvatar as F, getConversationIdByProviderConversation as G, upsertLinkedIdentity as H, deleteProviderIdentityForSlackUser as I, agentTurnCostUsd as J, parseSessionSource as K, deleteProviderIdentityForUser as L, SYSTEM_IDENTITY_ID as M, findActorIdentityId as N, conversationKindFromRow as O, resolveActorIdentityId as P, resolveRootConversationId as Q, findUserByVerifiedEmails as R, withConversationMutationLock as S, isTopLevelKind as T, bindProviderConversation as U, saveUserTimezone as V, claimProviderConversation as W, agentTurnUsageSchema as X, agentTurnTotalTokens as Y, hasAgentTurnUsage as Z, setArchivedAt as _, getConversationStore as a, requireSlackDestination as at, userMessageQueries as b, conversationIdsWithAnnotation as c, createSqlConversationEventStore as d, conversationDetailTouch as et, eventFromRow as f, readConversationTrees as g, conversationDescendants as h, getConversationMessageSearchStore as i, parseDestination as it, startLocationThread as j, locationFromRow as k, hasAnnotationKey as l, conversationAncestors as m, db_exports as n, touchConversationDetail as nt, getDb as o, sameDestination as ot, withConversationEventLock as p, addAgentTurnUsage as q, getConversationEventStore as r, createSlackDestination as rt, getSqlExecutor as s, closeDb as t, nextDetailVersion as tt, treeHasAnnotationKey as u, loadConversationSlackTenantIds as v, isPersonInput as w, createSqlStore as x, lastMessageAtSql as y, readUserTimezone as z };
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 };
@@ -1,4 +1,4 @@
1
- import "./schema-TSEisVJR.js";
1
+ import "./schema-Ce2XCS7O.js";
2
2
  import * as z from "zod";
3
3
  import "drizzle-orm";
4
4
  import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
@@ -168,6 +168,18 @@ interface ConversationStore {
168
168
  providerTenantId: string;
169
169
  providerConversationId: string;
170
170
  }): Promise<void>;
171
+ /**
172
+ * Claim one provider conversation for the Conversation that starts in it,
173
+ * unless another Conversation started there first. Return the owner.
174
+ */
175
+ claimProviderConversation(args: {
176
+ atMs: number;
177
+ conversationId: string;
178
+ provider: string;
179
+ providerDestinationId: string;
180
+ providerTenantId: string;
181
+ providerConversationId: string;
182
+ }): Promise<string>;
171
183
  /** Read confirmed public/private visibility for one destination. */
172
184
  getDestinationVisibility(args: {
173
185
  provider: string;
@@ -1,6 +1,6 @@
1
1
  import { _ as withScope } from "./sentry-BRTJqumy.js";
2
- import "./config-DvnTPCfp.js";
3
- import { h as logWarn, p as logException } from "./logging-9OAq-fdg.js";
2
+ import "./config-Dj9M_nqB.js";
3
+ import { h as logWarn, p as logException } from "./logging-CQjlDQYX.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";
@@ -195,6 +195,8 @@ const juniorCodeChanges = pgTable("junior_code_changes", {
195
195
  id: uuid("id").primaryKey(),
196
196
  closedAt: timestamptz("closed_at"),
197
197
  conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
198
+ /** Latest push, review, or comment by a person, from the code plugin. */
199
+ lastActivityAt: timestamptz("last_activity_at"),
198
200
  mergedAt: timestamptz("merged_at"),
199
201
  number: integer("number").notNull(),
200
202
  openedAt: timestamptz("opened_at").notNull(),
@@ -456,6 +458,7 @@ const juniorAgentInvocations = pgTable("junior_agent_invocations", {
456
458
  destination: jsonb("destination_json").$type().notNull(),
457
459
  destinationVisibility: text("destination_visibility").$type(),
458
460
  agentType: text("agent_type").$type(),
461
+ fork: boolean("fork").notNull().default(false),
459
462
  reasoningLevel: text("reasoning_level").$type(),
460
463
  parentToolCallId: text("parent_tool_call_id"),
461
464
  status: text("status").$type().notNull(),
@@ -895,6 +898,12 @@ async function applyMigrations(executor, config) {
895
898
  }
896
899
  // src/db/neon.ts
897
900
  const POOL_MAX = 10;
901
+ function toWebSocketError(error, failure) {
902
+ if (error instanceof Error) return error;
903
+ 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);
905
+ return new Error(`WebSocket ${failure}: ${reason}`, event.error === void 0 ? void 0 : { cause: event.error });
906
+ }
898
907
  /**
899
908
  * Sends a pool query over Neon's SQL-over-HTTP endpoint when no idle
900
909
  * WebSocket client is free.
@@ -915,7 +924,7 @@ var OverflowPool = class extends Pool {
915
924
  super({
916
925
  connectionString: args.connectionString,
917
926
  max: POOL_MAX,
918
- idleTimeoutMillis: 6e4,
927
+ idleTimeoutMillis: 3e5,
919
928
  min: 1,
920
929
  statement_timeout: args.statementTimeoutMs
921
930
  });
@@ -950,7 +959,7 @@ var OverflowPool = class extends Pool {
950
959
  client.release();
951
960
  return;
952
961
  }
953
- logException(error, "db.pool.client.connect_failed", { "app.db.driver": "neon" });
962
+ logException(toWebSocketError(error, "connect failed"), "db.pool.client.connect_failed", { "app.db.driver": "neon" });
954
963
  });
955
964
  }
956
965
  /** Keep every pool query in `callback` on WebSocket. */
@@ -1111,7 +1120,12 @@ function createNeonJuniorSqlExecutor(args) {
1111
1120
  dispatcher
1112
1121
  });
1113
1122
  pool.on("error", (error) => {
1114
- logException(error, "db.pool.client.failed", { "app.db.driver": "neon" });
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
+ });
1115
1129
  });
1116
1130
  if (onInfo) forwardInfoMessages(pool, onInfo);
1117
1131
  return new NeonExecutor(pool, dispatcher);
@@ -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-9OAq-fdg.js";
3
- import { n as getCurrentConversationPrivacy } from "./conversation-privacy-DPjv4SnA.js";
2
+ import { B as getDeploymentTelemetryAttributes, z as getDeploymentServiceVersion } from "./logging-CQjlDQYX.js";
3
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-DI29jbZV.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";
@@ -103,6 +103,23 @@ function createGatewayRequestTimingHandlers() {
103
103
  * AI Gateway model requests onto their `gen_ai.chat` span. Telemetry must not
104
104
  * fail a request, so handler errors are dropped. Returns a function that
105
105
  * removes the subscriptions.
106
+ *
107
+ * To find where time went before the gateway saw a request, get the gateway
108
+ * latency for `gen_ai.response.id` from the AI Gateway generation API, then
109
+ * compare the phases:
110
+ * - High `queue_ms` on a reused socket, or high
111
+ * `app.ai.event_loop.utilization`: the process was busy or the pool was
112
+ * full. With a new socket, `queue_ms` includes the connect time.
113
+ * - High `connect_ms`: DNS, TCP, or TLS was slow. It is absent on a reused
114
+ * socket. It is best effort: overlapping connects to the same host usually
115
+ * record none.
116
+ * - High `body_send_ms`: the upload was slow.
117
+ * - `response_wait_ms` much larger than the gateway time to first token,
118
+ * with small Junior phases: the delay was in the network or at the Vercel
119
+ * edge. The gateway sends headers with the first token. Give Vercel
120
+ * `app.ai.gateway.vercel_id`.
121
+ * - The same `service.instance.id` on more than one slow call: they shared
122
+ * one process.
106
123
  */
107
124
  function subscribeGatewayRequestTiming() {
108
125
  const handlers = Object.entries(createGatewayRequestTimingHandlers()).map(([name, handler]) => [name, (message) => {
@@ -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-AQa7Fr2H.js";
2
+ import { t as JUNIOR_VERSION } from "./version-KNDzIAh6.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,21 +1,22 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Cn as renderUntrustedTag, Za as canAccessConversation, eo as readConversationAccessFromSql } from "./projection-BzJQncZV.js";
3
- import { n as botConfig } from "./config-DvnTPCfp.js";
4
- import { M as SYSTEM_IDENTITY_ID, a as getConversationStore, o as getDb } from "./db-Dts2XvLu.js";
5
- import { hn as toolInvocationDestination, in as AgentMessageTargetError, mn as actorFromRun, nn as AgentMessagePausedError } from "./agent-runner-DjMTPWEO.js";
6
- import { I as PARENT_AGENT_TARGET, v as getActiveAgentInvocationForConversation } from "./turn-failure-response-BTSo6SMJ.js";
7
- import { G as admitAutomatedTurn, S as EVENT_WAIT_MS, V as postAutomatedTurnLimitNoticeForConversation } from "./session-stop-DkxI5vc3.js";
8
- import { r as appendAndEnqueueInboundMessage } from "./store-DgD78_NK.js";
9
- import { a as enqueueAgentInvocation, c as createAgentInvocationForMessage, u as findChildAgentConversationId } from "./work-yN_GAuXY.js";
10
- import { r as enqueueAgentMessageToParent } from "./result-DhgjR3nQ.js";
2
+ import { go as readConversationAccessFromSql, po as canAccessConversation, zn as renderUntrustedTag } from "./projection-B08mfi0u.js";
3
+ import { n as botConfig } from "./config-Dj9M_nqB.js";
4
+ import { M as SYSTEM_IDENTITY_ID, a as getConversationStore, o as getDb } from "./db-Br0tfAo7.js";
5
+ import { Ft as actorFromRun, It as toolInvocationDestination } from "./agent-runner-CneTquAE.js";
6
+ import { I as findChildAgentConversationId, M as AgentMessagePausedError, O as createAgentInvocationForMessage, P as AgentMessageTargetError, x as enqueueAgentInvocation } from "./warmup-Bskrwmk1.js";
7
+ import { C as getActiveAgentInvocationForConversation, E as getLatestAgentInvocationForConversation, W as PARENT_AGENT_TARGET } from "./turn-user-message-ygLG3ylQ.js";
8
+ import { b as postAutomatedTurnLimitNoticeForConversation, t as EVENT_WAIT_MS, w as admitAutomatedTurn } from "./notification-gusCgdQ6.js";
9
+ import { r as appendAndEnqueueInboundMessage } from "./store-B59rOYbS.js";
10
+ import { a as enqueueAgentMessageToParent } from "./result-CAujiaci.js";
11
11
  // src/chat/agent-invocations/top-level-message.ts
12
12
  const AGENT_MESSAGE_EVENT_NAMESPACE = "junior";
13
13
  /** Event type of a message from another top-level agent. */
14
14
  const TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE = "agent.top_level_message";
15
15
  /**
16
16
  * Check that a top-level agent can message another top-level agent under
17
- * `policies/conversation-access.md`. A private Conversation is isolated, so
18
- * only public agents can message each other.
17
+ * `policies/conversation-access.md`. Public agents can message each other.
18
+ * A private agent can message only agents at its own Destination, such as
19
+ * another thread in the same private Slack channel.
19
20
  * Every target that the sender cannot reach gets the same error, so the
20
21
  * error does not show that a private Conversation exists.
21
22
  */
@@ -33,7 +34,7 @@ async function requireTopLevelAgentAccess(args) {
33
34
  requester: sender,
34
35
  target: receiver
35
36
  })) throw notReachable;
36
- if (sender.visibility !== "public") throw new AgentMessageTargetError(`"${args.to}" is a public conversation and this conversation is private. A private conversation cannot message another conversation`);
37
+ if (receiver.visibility === "public" && sender.visibility !== "public") throw new AgentMessageTargetError(`"${args.to}" is a public conversation and this conversation is private. A private conversation can message only conversations in its own channel or DM`);
37
38
  }
38
39
  function renderTopLevelMessageInput(args) {
39
40
  return renderUntrustedTag("agent-message", {
@@ -115,9 +116,10 @@ function bindMessageAgent(run, options) {
115
116
  call.signal?.throwIfAborted();
116
117
  const queue = typeof options.queue === "function" ? options.queue() : options.queue;
117
118
  if (input.to === "parent") {
118
- const sender = await getActiveAgentInvocationForConversation(run.conversationId);
119
+ const sender = await getActiveAgentInvocationForConversation(run.conversationId) ?? await getLatestAgentInvocationForConversation(run.conversationId);
119
120
  if (!sender) throw new AgentMessageTargetError("This conversation has no parent agent");
120
121
  await enqueueAgentMessageToParent({
122
+ actor,
121
123
  messageKey: `${run.turnId}:${call.toolCallId}`,
122
124
  queue,
123
125
  sender,
package/dist/nitro.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i as JuniorDashboardOptions } from "./app-uiTzRbvq.js";
1
+ import { i as JuniorDashboardOptions } from "./app-BJojZ7HL.js";
2
2
  import { n as JuniorPluginSet } from "./plugins-B_0Cr0MO.js";
3
3
  import { withSentryConfig as withSentryConfig$1 } from "@sentry/nitro";
4
4
  type SentryNitroConfig = Parameters<typeof withSentryConfig$1>[0];
package/dist/nitro.js CHANGED
@@ -1,7 +1,8 @@
1
- import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, D as JUNIOR_AUTO_ARCHIVE_CRON_SCHEDULE, F as JUNIOR_RETENTION_CRON_SCHEDULE, I as JUNIOR_RETENTION_ROUTE, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, M as JUNIOR_HEARTBEAT_CRON_SCHEDULE, N as JUNIOR_HEARTBEAT_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, j as JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE, k as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, z as getDeploymentServiceVersion } from "./logging-9OAq-fdg.js";
1
+ import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, D as JUNIOR_AUTO_ARCHIVE_CRON_SCHEDULE, F as JUNIOR_RETENTION_CRON_SCHEDULE, I as JUNIOR_RETENTION_ROUTE, L as JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE, M as JUNIOR_HEARTBEAT_CRON_SCHEDULE, N as JUNIOR_HEARTBEAT_ROUTE, O as JUNIOR_AUTO_ARCHIVE_ROUTE, P as JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE, j as JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE, k as JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE, z as getDeploymentServiceVersion } from "./logging-CQjlDQYX.js";
2
2
  import { d as resolvePackageDir, t as discoverInstalledPluginPackageContent, u as isValidPackageName } from "./package-discovery-DJhGdS4c.js";
3
- import { S as CACHE_WARMUP_QUEUE_TOPIC, _ as resolveConversationWorkQueueTopic, a as PLUGIN_TASK_QUEUE_TOPIC, f as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, t as BACKGROUND_COMPACTION_QUEUE_TOPIC } from "./background-compaction-queue-DUkHZjmL.js";
3
+ import { a as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, h as CACHE_WARMUP_QUEUE_TOPIC, t as BACKGROUND_COMPACTION_QUEUE_TOPIC, u as resolveConversationWorkQueueTopic } from "./background-compaction-queue-CwfJy3Cd.js";
4
4
  import { a as pluginRuntimeRegistrationsFromPluginSet, r as pluginCatalogConfigFromPluginSet } from "./plugins-HYh_JOdw.js";
5
+ import { t as PLUGIN_TASK_QUEUE_TOPIC } from "./task-queue-N0kuCknH.js";
5
6
  import { n as loadPluginSetFromModule, r as resolvePluginModule } from "./plugin-module-Cf5gVPWP.js";
6
7
  import path from "node:path";
7
8
  import { cpSync, existsSync, mkdirSync, readdirSync, statSync } from "node:fs";