@sentry/junior 0.294.0 → 0.295.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 (77) hide show
  1. package/dist/{admin-vt8aSiCD.js → admin-ifgjyfpF.js} +2 -2
  2. package/dist/{agent-runner-DJu7w6mI.js → agent-runner-DjMTPWEO.js} +147 -90
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +5 -5
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +52 -28
  7. package/dist/{app--a5RLOrr.d.ts → app-uiTzRbvq.d.ts} +3 -3
  8. package/dist/app.d.ts +2 -2
  9. package/dist/app.js +33 -34
  10. package/dist/{automation-BM-OBsKW.js → automation-yJX3C7i3.js} +3 -3
  11. package/dist/{background-compaction-queue-D2j-0XkH.js → background-compaction-queue-DUkHZjmL.js} +7 -9
  12. package/dist/{briefs-JOAoCb6d.js → briefs-CbNYM-q2.js} +3 -3
  13. package/dist/{catalog-runtime-CLMA9AXd.js → catalog-runtime-DgouZKZm.js} +1 -1
  14. package/dist/cli/chat.d.ts +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +2 -0
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +4 -4
  21. package/dist/cli/snapshot-create.js +4 -4
  22. package/dist/cli/upgrade.d.ts +2 -2
  23. package/dist/cli/upgrade.js +3 -3
  24. package/dist/{config-mIZeGEWv.js → config-DvnTPCfp.js} +43 -2
  25. package/dist/{connections-XhdVg7OR.js → connections-CWaIVl_1.js} +6 -6
  26. package/dist/{conversation-CDWejM4R.js → conversation-CMkSmi02.js} +2 -11
  27. package/dist/{conversation-pending-messages-Dh2tfbaw.js → conversation-feed-BVAOga0H.js} +27 -2
  28. package/dist/{conversation-privacy-C6h-X2cZ.js → conversation-privacy-DPjv4SnA.js} +1 -1
  29. package/dist/{credential-sync-zigBlXS3.js → credential-sync-BhbaZfmO.js} +16 -15
  30. package/dist/{db-DV5AbcGM.d.ts → db-CCUqQe0E.d.ts} +6 -1
  31. package/dist/{db--xuNV7g6.js → db-Dts2XvLu.js} +54 -10
  32. package/dist/{executor-BItuRqAR.js → executor-Ck73J0wP.js} +8 -3
  33. package/dist/instrumentation.js +2 -2
  34. package/dist/{logging-Cb6MGvdt.js → logging-9OAq-fdg.js} +2 -1
  35. package/dist/{message-BTGgSmaH.js → message-CtaPzC7m.js} +9 -9
  36. package/dist/nitro.d.ts +2 -2
  37. package/dist/nitro.js +2 -2
  38. package/dist/{oauth-callback-server-Dvh1aOIi.js → oauth-callback-server-C_LXY1d4.js} +2 -2
  39. package/dist/{oauth-relay-D6xxVywK.js → oauth-relay-CsfIazeF.js} +2 -1
  40. package/dist/{plugins-DtmjkTza.d.ts → plugins-B_0Cr0MO.d.ts} +0 -1
  41. package/dist/{projection-DLQgfO5N.js → projection-BzJQncZV.js} +248 -77
  42. package/dist/{prompt-qp_LdxLX.js → prompt-Cbq5b4SO.js} +4 -4
  43. package/dist/{registry-MtwokaqW.js → registry-cbpOxO4M.js} +3 -13
  44. package/dist/{resolve-BnJA0UNE.js → resolve-t-pmRdwS.js} +3 -3
  45. package/dist/{result-ChL-1KyW.js → result-DhgjR3nQ.js} +8 -8
  46. package/dist/{runner-BONN7Dp2.js → runner-CHv9X9TH.js} +8 -8
  47. package/dist/{sandbox-egress-signals-nmlmI5Ab.js → sandbox-egress-signals-Yy3fSCbg.js} +1 -1
  48. package/dist/{schema-yr0ccDni.js → schema-BhneuGYv.js} +13 -6
  49. package/dist/{schema-DgvcyJ1y.d.ts → schema-TSEisVJR.d.ts} +50 -14
  50. package/dist/secrets-DebYU866.js +18 -0
  51. package/dist/{service-account-Bd0lBaGr.js → service-account-C4rBP8ne.js} +3 -3
  52. package/dist/{service-account-kio5nXSD.js → service-account-DjPIwCMj.js} +42 -26
  53. package/dist/{session-stop-CeCXL3j9.js → session-stop-DkxI5vc3.js} +20 -775
  54. package/dist/{skills-e3DDNlKO.js → skills-BZE2DP8I.js} +2 -2
  55. package/dist/{spawn--cRxITWQ.js → spawn-BvULxIiu.js} +5 -5
  56. package/dist/{adapter-DxLhJEnO.js → state-CO9ETDzk.js} +132 -2
  57. package/dist/{stop-Iai5N2PU.js → stop-CL-rdtQb.js} +84 -30
  58. package/dist/{store-C8LsaJwS.js → store-DgD78_NK.js} +3 -3
  59. package/dist/{task-runner-Dw7exu0-.js → task-runner-CKOj6xla.js} +11 -11
  60. package/dist/{turn-failure-response-BqTTx3XG.js → turn-failure-response-BTSo6SMJ.js} +8 -8
  61. package/dist/{validation-BrGahtnv.js → validation-CXeYgBzq.js} +1 -1
  62. package/dist/{version-Bdqhx8Qh.js → version-AQa7Fr2H.js} +1 -1
  63. package/dist/version.js +1 -1
  64. package/dist/{viewer-CjRFHR5U.js → viewer-Bqkb678l.js} +3 -3
  65. package/dist/warmup-h6u1e9n0.js +1869 -0
  66. package/dist/{work-BWBG1EGV.js → work-yN_GAuXY.js} +11 -11
  67. package/dist/{worker-DAnBIVMs.js → worker-Hl7N292I.js} +6 -6
  68. package/migrations/0098_review_item_plugin_actions.sql +5 -0
  69. package/migrations/0099_conversation_last_message_at.sql +1 -0
  70. package/migrations/0100_automation_task_kind_repair.sql +48 -0
  71. package/migrations/meta/0098_snapshot.json +4490 -0
  72. package/migrations/meta/0099_snapshot.json +4720 -0
  73. package/migrations/meta/0100_snapshot.json +4496 -0
  74. package/migrations/meta/_journal.json +21 -0
  75. package/package.json +5 -5
  76. package/dist/assistant-reply-iTtEdDyc.js +0 -58
  77. package/dist/warmup-DuxCtzKC.js +0 -1039
@@ -1,5 +1,5 @@
1
- import { l as completeObject, n as briefEntriesFromReportEvents, s as generateBrief, t as BRIEF_PROMPT } from "./prompt-qp_LdxLX.js";
2
- import { G as briefCodeChangeSchema, J as briefResourceLabel, X as parseBriefInput, d as conversationEventPageSchema, l as conversationDetailReportSchema } from "./conversation-CDWejM4R.js";
1
+ import { l as completeObject, n as briefEntriesFromReportEvents, s as generateBrief, t as BRIEF_PROMPT } from "./prompt-Cbq5b4SO.js";
2
+ import { W as briefCodeChangeSchema, Y as parseBriefInput, d as conversationEventPageSchema, l as conversationDetailReportSchema, q as briefResourceLabel } from "./conversation-CMkSmi02.js";
3
3
  import { CLI_USAGE } from "./cli/run.js";
4
4
  import path from "node:path";
5
5
  import * as z from "zod";
@@ -262,7 +262,7 @@ async function parseRunOptions(argv) {
262
262
  * token.
263
263
  */
264
264
  async function configuredBriefModelId() {
265
- const { botConfig } = await import("./config-mIZeGEWv.js").then((n) => n.r);
265
+ const { botConfig } = await import("./config-DvnTPCfp.js").then((n) => n.r);
266
266
  return botConfig.fastModelId;
267
267
  }
268
268
  function apiUrl(baseUrl, pathname) {
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { t as createPluginCatalogRuntime } from "./registry-MtwokaqW.js";
2
+ import { t as createPluginCatalogRuntime } from "./registry-cbpOxO4M.js";
3
3
  // src/chat/plugins/catalog-runtime.ts
4
4
  var catalog_runtime_exports = /* @__PURE__ */ __exportAll({ pluginCatalogRuntime: () => pluginCatalogRuntime });
5
5
  const pluginCatalogRuntime = createPluginCatalogRuntime();
@@ -1,4 +1,4 @@
1
- import { n as JuniorPluginSet } from "../plugins-DtmjkTza.js";
1
+ import { n as JuniorPluginSet } from "../plugins-B_0Cr0MO.js";
2
2
  export declare const CHAT_USAGE = "usage: junior chat\n junior chat -p <message>";
3
3
  export type ChatCommandOptions = {
4
4
  mode: "interactive";
package/dist/cli/chat.js CHANGED
@@ -1,4 +1,4 @@
1
- import { n as executeAgentRun, t as createAgentRunner } from "../agent-runner-DJu7w6mI.js";
1
+ import { n as executeAgentRun, t as createAgentRunner } from "../agent-runner-DjMTPWEO.js";
2
2
  import { t as loadAppPluginSet } from "../plugin-module-Cf5gVPWP.js";
3
3
  import path from "node:path";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -99,10 +99,10 @@ async function loadLocalPluginSet() {
99
99
  async function configureLocalChatPlugins(pluginSet) {
100
100
  const [pluginsModule, agentHooksModule, catalogRuntimeModule, validationModule, databaseModule] = await Promise.all([
101
101
  import("../plugins-HYh_JOdw.js").then((n) => n.o),
102
- import("../projection-DLQgfO5N.js").then((n) => n.jn),
103
- import("../catalog-runtime-CLMA9AXd.js").then((n) => n.t),
104
- import("../validation-BrGahtnv.js").then((n) => n.r),
105
- import("../db--xuNV7g6.js").then((n) => n.n)
102
+ import("../projection-BzJQncZV.js").then((n) => n.jn),
103
+ import("../catalog-runtime-DgouZKZm.js").then((n) => n.t),
104
+ import("../validation-CXeYgBzq.js").then((n) => n.r),
105
+ import("../db-Dts2XvLu.js").then((n) => n.n)
106
106
  ]);
107
107
  const resolvedPluginSet = pluginSet === void 0 ? await loadLocalPluginSet() : pluginSet ?? void 0;
108
108
  const plugins = pluginsModule.pluginRuntimeRegistrationsFromPluginSet(resolvedPluginSet);
@@ -152,18 +152,18 @@ function localDevServerUrl() {
152
152
  async function prepareLocalChatRun(io, pluginSet) {
153
153
  defaultStateAdapterForLocalChat();
154
154
  await configureLocalChatPlugins(pluginSet);
155
- const { setBriefsConfig } = await import("../projection-DLQgfO5N.js").then((n) => n.Wn);
155
+ const { setBriefsConfig } = await import("../projection-BzJQncZV.js").then((n) => n.Wn);
156
156
  setBriefsConfig({ enabled: true });
157
- const { runLocalAgentTurn } = await import("../runner-BONN7Dp2.js");
158
- const { startLocalOAuthCallbackServer } = await import("../oauth-callback-server-Dvh1aOIi.js");
159
- const { createLocalOAuthState } = await import("../oauth-relay-D6xxVywK.js").then((n) => n.t);
160
- const { createLocalSandboxEgressSignalTransport } = await import("../sandbox-egress-signals-nmlmI5Ab.js");
161
- const { bindSpawnAgent } = await import("../spawn--cRxITWQ.js").then((n) => n.n);
162
- const { bindMessageAgent } = await import("../message-BTGgSmaH.js").then((n) => n.n);
163
- const { createChildConversationWorker } = await import("../result-ChL-1KyW.js").then((n) => n.i);
164
- const { skipInputAfterConversationStop } = await import("../session-stop-CeCXL3j9.js").then((n) => n.a);
157
+ const { runLocalAgentTurn } = await import("../runner-CHv9X9TH.js");
158
+ const { startLocalOAuthCallbackServer } = await import("../oauth-callback-server-C_LXY1d4.js");
159
+ const { createLocalOAuthState } = await import("../oauth-relay-CsfIazeF.js").then((n) => n.t);
160
+ const { createLocalSandboxEgressSignalTransport } = await import("../sandbox-egress-signals-Yy3fSCbg.js");
161
+ const { bindSpawnAgent } = await import("../spawn-BvULxIiu.js").then((n) => n.n);
162
+ const { bindMessageAgent } = await import("../message-CtaPzC7m.js").then((n) => n.n);
163
+ const { createChildConversationWorker } = await import("../result-DhgjR3nQ.js").then((n) => n.i);
164
+ const { skipInputAfterConversationStop } = await import("../session-stop-DkxI5vc3.js").then((n) => n.a);
165
165
  const { createLocalConversationWork } = await import("../conversation-work-BaT_T6EB.js");
166
- const { processConversationWork } = await import("../worker-DAnBIVMs.js").then((n) => n.n);
166
+ const { processConversationWork } = await import("../worker-Hl7N292I.js").then((n) => n.n);
167
167
  let agentRunner;
168
168
  const localConversationWork = createLocalConversationWork(async (message) => {
169
169
  if (!agentRunner) throw new Error("Local agent runner is not ready");
package/dist/cli/check.js CHANGED
@@ -1,6 +1,6 @@
1
- import { N as JUNIOR_HEARTBEAT_ROUTE, R as LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION, j as JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE } from "../logging-Cb6MGvdt.js";
2
- import { v as parseInlinePluginManifest, y as parsePluginManifest } from "../registry-MtwokaqW.js";
3
- import { i as parseSkillFile } from "../skills-e3DDNlKO.js";
1
+ import { N as JUNIOR_HEARTBEAT_ROUTE, R as LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION, j as JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE } from "../logging-9OAq-fdg.js";
2
+ import { v as parseInlinePluginManifest, y as parsePluginManifest } from "../registry-cbpOxO4M.js";
3
+ import { i as parseSkillFile } from "../skills-BZE2DP8I.js";
4
4
  import path from "node:path";
5
5
  import fs from "node:fs/promises";
6
6
  import { pathToFileURL } from "node:url";
package/dist/cli/init.js CHANGED
@@ -158,6 +158,8 @@ async function runInit(dir, log = console.log) {
158
158
  fs.writeFileSync(path.join(target, ".env.example"), `SLACK_BOT_TOKEN=
159
159
  SLACK_SIGNING_SECRET=
160
160
  JUNIOR_SECRET=
161
+ JUNIOR_ENCRYPTION_KEYS=
162
+ JUNIOR_ENCRYPTION_KEY_ID=
161
163
  JUNIOR_BOT_NAME=
162
164
  AI_MODEL=
163
165
  AI_FAST_MODEL=
package/dist/cli/main.js CHANGED
@@ -45,13 +45,13 @@ async function runChat(argv, pluginSet) {
45
45
  return await (await import("./chat.js")).runChat(argv, void 0, { pluginSet });
46
46
  }
47
47
  async function runAdmin(argv) {
48
- return await (await import("../admin-vt8aSiCD.js")).runAdmin(argv);
48
+ return await (await import("../admin-ifgjyfpF.js")).runAdmin(argv);
49
49
  }
50
50
  async function runServiceAccount(argv) {
51
- return await (await import("../service-account-Bd0lBaGr.js")).runServiceAccount(argv);
51
+ return await (await import("../service-account-C4rBP8ne.js")).runServiceAccount(argv);
52
52
  }
53
53
  async function runBriefs(argv) {
54
- return await (await import("../briefs-JOAoCb6d.js")).runBriefs(argv);
54
+ return await (await import("../briefs-CbNYM-q2.js")).runBriefs(argv);
55
55
  }
56
56
  function topLevelCommand(argv) {
57
57
  return (argv[0] === "--" ? argv.slice(1) : argv)[0];
@@ -1,4 +1,4 @@
1
- import { n as JuniorPluginSet } from "../plugins-DtmjkTza.js";
1
+ import { n as JuniorPluginSet } from "../plugins-B_0Cr0MO.js";
2
2
  import { PluginCliIo } from "@sentry/junior-plugin-api";
3
3
  export type PluginCommandIo = PluginCliIo;
4
4
  export interface CliPluginCommandDispatcher {
@@ -1,7 +1,7 @@
1
- import { Hn as validatePlugins, Vn as setPlugins, Xa as createPluginLogger } from "../projection-DLQgfO5N.js";
2
- import { o as getDb } from "../db--xuNV7g6.js";
3
- import { n as pluginCatalogRuntime } from "../catalog-runtime-CLMA9AXd.js";
4
- import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "../validation-BrGahtnv.js";
1
+ import { Hn as validatePlugins, Vn as setPlugins, Xa as createPluginLogger } from "../projection-BzJQncZV.js";
2
+ import { o as getDb } from "../db-Dts2XvLu.js";
3
+ import { n as pluginCatalogRuntime } from "../catalog-runtime-DgouZKZm.js";
4
+ import { n as validatePluginRegistrations, t as validatePluginEgressCredentialHooks } from "../validation-CXeYgBzq.js";
5
5
  import { a as pluginRuntimeRegistrationsFromPluginSet, i as pluginCliRegistrationsFromPluginSet, r as pluginCatalogConfigFromPluginSet } from "../plugins-HYh_JOdw.js";
6
6
  import { t as loadAppPluginSet } from "../plugin-module-Cf5gVPWP.js";
7
7
  import { stderr, stdout } from "node:process";
@@ -1,7 +1,7 @@
1
- import { Ti as create, ja as SANDBOX_RUNTIME } from "../projection-DLQgfO5N.js";
2
- import { n as pluginCatalogRuntime } from "../catalog-runtime-CLMA9AXd.js";
3
- import { t as disconnectStateAdapter } from "../adapter-DxLhJEnO.js";
4
- import { n as resolve } from "../resolve-BnJA0UNE.js";
1
+ import { Ti as create, ja as SANDBOX_RUNTIME } from "../projection-BzJQncZV.js";
2
+ import { n as pluginCatalogRuntime } from "../catalog-runtime-DgouZKZm.js";
3
+ import { r as disconnectStateAdapter } from "../state-CO9ETDzk.js";
4
+ import { n as resolve } from "../resolve-t-pmRdwS.js";
5
5
  // src/cli/snapshot-create.ts
6
6
  const DEFAULT_TIMEOUT_MS = 6e5;
7
7
  function progressMessage(phase) {
@@ -1,5 +1,5 @@
1
- import "../db-DV5AbcGM.js";
2
- import { n as JuniorPluginSet } from "../plugins-DtmjkTza.js";
1
+ import "../db-CCUqQe0E.js";
2
+ import { n as JuniorPluginSet } from "../plugins-B_0Cr0MO.js";
3
3
  interface UpgradeIo {
4
4
  info: (line: string) => void;
5
5
  }
@@ -1,6 +1,6 @@
1
- import { i as getChatConfig } from "../config-mIZeGEWv.js";
2
- import { t as createJuniorSqlExecutor } from "../executor-BItuRqAR.js";
3
- import { t as createPluginCatalogRuntime } from "../registry-MtwokaqW.js";
1
+ import { i as getChatConfig } from "../config-DvnTPCfp.js";
2
+ import { t as createJuniorSqlExecutor } from "../executor-Ck73J0wP.js";
3
+ import { t as createPluginCatalogRuntime } from "../registry-cbpOxO4M.js";
4
4
  import { n as pluginCatalogConfigFromEnv, r as pluginCatalogConfigFromPluginSet, t as defineJuniorPlugins } from "../plugins-HYh_JOdw.js";
5
5
  import { t as loadAppPluginSet } from "../plugin-module-Cf5gVPWP.js";
6
6
  import { basename, dirname, join, resolve } from "node:path";
@@ -1,6 +1,6 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-Cb6MGvdt.js";
3
- import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-C6h-X2cZ.js";
2
+ import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-9OAq-fdg.js";
3
+ import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DPjv4SnA.js";
4
4
  import { AwsClient } from "aws4fetch";
5
5
  import { del, get, put } from "@vercel/blob";
6
6
  import { calculateCost, completeSimple, getEnvApiKey, getModels, registerApiProvider } from "@earendil-works/pi-ai/compat";
@@ -207,6 +207,46 @@ function readAttachmentStorageConfig(env) {
207
207
  default: throw new Error("JUNIOR_ATTACHMENT_STORAGE_PROVIDER must be vercel-blob, s3, or memory");
208
208
  }
209
209
  }
210
+ // src/chat/encryption/keyring.ts
211
+ /**
212
+ * Encryption keys for secrets that Junior keeps at rest.
213
+ *
214
+ * `JUNIOR_ENCRYPTION_KEYS` lists `<id>:<key>` entries, comma-separated. Each
215
+ * key is 32 random bytes in base64 or base64url. `JUNIOR_ENCRYPTION_KEY_ID`
216
+ * names the key for new values; it is optional when there is one key. All
217
+ * listed keys decrypt. The config fails at startup when a key is invalid, an
218
+ * id repeats, or the active id is not in the list.
219
+ */
220
+ const KEY_BYTES = 32;
221
+ const KEY_ID_PATTERN = /^[A-Za-z0-9._-]{1,32}$/;
222
+ const KEY_MATERIAL_PATTERN = /^[A-Za-z0-9+/_-]+={0,2}$/;
223
+ function parseKey(entry, index) {
224
+ const separator = entry.indexOf(":");
225
+ const id = entry.slice(0, separator).trim();
226
+ const material = entry.slice(separator + 1).trim();
227
+ if (separator < 0 || !KEY_ID_PATTERN.test(id)) throw new Error(`JUNIOR_ENCRYPTION_KEYS entry ${index + 1} must be <id>:<key> with an id of letters, digits, ".", "_", or "-"`);
228
+ const key = KEY_MATERIAL_PATTERN.test(material) ? Buffer.from(material, "base64") : Buffer.alloc(0);
229
+ if (key.length !== KEY_BYTES) throw new Error(`JUNIOR_ENCRYPTION_KEYS key "${id}" must be ${KEY_BYTES} bytes in base64`);
230
+ return {
231
+ id,
232
+ key
233
+ };
234
+ }
235
+ /** Parse and check the encryption keyring from environment variables. */
236
+ function readEncryptionKeyring(env) {
237
+ const entries = (env.JUNIOR_ENCRYPTION_KEYS ?? "").split(",").map((entry) => entry.trim()).filter(Boolean);
238
+ if (entries.length === 0) throw new Error("JUNIOR_ENCRYPTION_KEYS is required. Generate a key with: node -e \"console.log('k1:' + require('node:crypto').randomBytes(32).toString('base64url'))\"");
239
+ const keys = entries.map(parseKey);
240
+ if (new Set(keys.map((key) => key.id)).size !== keys.length) throw new Error("JUNIOR_ENCRYPTION_KEYS must not repeat a key id");
241
+ const activeId = env.JUNIOR_ENCRYPTION_KEY_ID?.trim() || (keys.length === 1 ? keys[0]?.id : void 0);
242
+ if (!activeId) throw new Error("JUNIOR_ENCRYPTION_KEY_ID is required when JUNIOR_ENCRYPTION_KEYS has more than one key");
243
+ const active = keys.find((key) => key.id === activeId);
244
+ if (!active) throw new Error(`JUNIOR_ENCRYPTION_KEY_ID "${activeId}" is not in JUNIOR_ENCRYPTION_KEYS`);
245
+ return {
246
+ active,
247
+ keys
248
+ };
249
+ }
210
250
  // src/chat/queue/config.ts
211
251
  /** Jobs that one BullMQ worker runs at the same time, for each queue topic. */
212
252
  const DEFAULT_BULLMQ_WORKER_CONCURRENCY = 4;
@@ -1614,6 +1654,7 @@ function readChatConfig(env = process.env, functionMaxDurationSeconds = DEFAULT_
1614
1654
  cacheWarmingEnabled: parseKillSwitch("JUNIOR_CACHE_WARMING_ENABLED", env.JUNIOR_CACHE_WARMING_ENABLED),
1615
1655
  conversationWorkEnabled: parseKillSwitch("JUNIOR_CONVERSATION_WORK_ENABLED", env.JUNIOR_CONVERSATION_WORK_ENABLED),
1616
1656
  conversationWorkSoftYieldAfterMs: resolveConversationWorkSoftYieldAfterMs(resolvedFunctionMaxDurationSeconds),
1657
+ encryption: readEncryptionKeyring(env),
1617
1658
  sql: {
1618
1659
  databaseUrl,
1619
1660
  driver: readSqlDriver(env, databaseUrl),
@@ -1,9 +1,9 @@
1
- import { Ii as startOAuthFlow } from "./projection-DLQgfO5N.js";
2
- import { n as botConfig } from "./config-mIZeGEWv.js";
3
- import { F as deleteProviderIdentityForUser, P as deleteProviderIdentityForSlackUser, s as getSqlExecutor } from "./db--xuNV7g6.js";
4
- import { u as hasRequiredOAuthScope } from "./registry-MtwokaqW.js";
5
- import { n as pluginCatalogRuntime } from "./catalog-runtime-CLMA9AXd.js";
6
- import { c as deleteMcpServerSessionId, l as deleteMcpStoredOAuthCredentials, s as deleteMcpAuthSessionsForUserProvider } from "./agent-runner-DJu7w6mI.js";
1
+ import { Ii as startOAuthFlow } from "./projection-BzJQncZV.js";
2
+ import { n as botConfig } from "./config-DvnTPCfp.js";
3
+ import { I as deleteProviderIdentityForSlackUser, L as deleteProviderIdentityForUser, s as getSqlExecutor } from "./db-Dts2XvLu.js";
4
+ import { u as hasRequiredOAuthScope } from "./registry-cbpOxO4M.js";
5
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DgouZKZm.js";
6
+ import { c as deleteMcpServerSessionId, l as deleteMcpStoredOAuthCredentials, s as deleteMcpAuthSessionsForUserProvider } from "./agent-runner-DjMTPWEO.js";
7
7
  import { randomBytes } from "node:crypto";
8
8
  // src/handlers/oauth-html.ts
9
9
  /** Build pre-escaped callback HTML with the shared response security policy. */
@@ -456,6 +456,7 @@ const conversationSummaryReportSchema = z.object({
456
456
  startedAt: z.string(),
457
457
  lastSeenAt: z.string(),
458
458
  lastProgressAt: z.string(),
459
+ lastMessageAt: z.string().datetime().optional(),
459
460
  surface: conversationSurfaceSchema,
460
461
  actorIdentity: actorIdentitySchema.optional(),
461
462
  participants: z.array(actorIdentitySchema).optional(),
@@ -956,14 +957,4 @@ const conversationDetailReportSchema = conversationSummaryReportSchema.extend({
956
957
  sentryConversationUrl: z.string().optional(),
957
958
  sourceTask: conversationSourceTaskSchema.optional()
958
959
  }).strict().superRefine(validateConversationEvents);
959
- /**
960
- * A root in the feed, or one of its visible Threads. A Thread nests under
961
- * its nearest visible Thread ancestor, or under the root. Tasks never show.
962
- */
963
- const conversationFeedItemSchema = conversationSummaryReportSchema.extend({ threads: z.lazy(() => z.array(conversationFeedItemSchema)).optional() });
964
- const conversationFeedSchema = z.object({
965
- conversations: z.array(conversationFeedItemSchema),
966
- source: z.literal("conversation_index"),
967
- generatedAt: z.string()
968
- }).strict();
969
- export { renameConversationBodySchema as A, resolveMessageCards as B, createConversationBodySchema as C, conversationChildAgentTotalsSchema as D, forkConversationResponseSchema as E, annotationCard as F, briefCodeChangeSchema as G, MAX_INPUT_IMAGE_BYTES as H, messageCardRef as I, briefResourceLabel as J, briefLinkSchema as K, messageCardText as L, conversationReadPositionSchema as M, conversationReadReportSchema as N, CONVERSATION_TITLE_MAX_LENGTH as O, reviewItemChangeRecordSchema as P, readMessageCardRefs as R, conversationUsageSchema as S, forkConversationBodySchema as T, messageAttachmentSchema as U, MAX_INPUT_IMAGES as V, readMessageAttachments as W, parseBriefInput as X, conversationBriefSchema as Y, parseStoredBrief as Z, conversationReportEventSchema as _, conversationActivityPreviewSchema as a, conversationSummaryReportSchema as b, conversationDetailQuerySchema as c, conversationEventPageSchema as d, conversationEventsQuerySchema as f, conversationReportEventDataSchema as g, conversationParamsSchema as h, actorIdentitySchema as i, renameConversationResponseSchema as j, conversationTitleSchema as k, conversationDetailReportSchema as l, conversationFeedSchema as m, CONVERSATION_VERSION_HEADER as n, conversationAttachmentParamsSchema as o, conversationFeedQuerySchema as p, briefOutcomeStatusSchema as q, acceptedConversationMessageSchema as r, conversationAuxiliaryCostsSchema as s, CONVERSATION_DETAIL_VERSION_HEADER as t, conversationEventHistorySchema as u, conversationReportMessageEventSchema as v, createConversationMessageBodySchema as w, conversationSurfaceSchema as x, conversationReportStatusSchema as y, removedCardSchema as z };
960
+ export { renameConversationResponseSchema as A, MAX_INPUT_IMAGES as B, createConversationMessageBodySchema as C, CONVERSATION_TITLE_MAX_LENGTH as D, conversationChildAgentTotalsSchema as E, messageCardRef as F, briefLinkSchema as G, messageAttachmentSchema as H, messageCardText as I, conversationBriefSchema as J, briefOutcomeStatusSchema as K, readMessageCardRefs as L, conversationReadReportSchema as M, reviewItemChangeRecordSchema as N, conversationTitleSchema as O, annotationCard as P, removedCardSchema as R, createConversationBodySchema as S, forkConversationResponseSchema as T, readMessageAttachments as U, MAX_INPUT_IMAGE_BYTES as V, briefCodeChangeSchema as W, parseStoredBrief as X, parseBriefInput as Y, conversationReportMessageEventSchema as _, conversationActivityPreviewSchema as a, conversationSurfaceSchema as b, conversationDetailQuerySchema as c, conversationEventPageSchema as d, conversationEventsQuerySchema as f, conversationReportEventSchema as g, conversationReportEventDataSchema as h, actorIdentitySchema as i, conversationReadPositionSchema as j, renameConversationBodySchema as k, conversationDetailReportSchema as l, conversationParamsSchema as m, CONVERSATION_VERSION_HEADER as n, conversationAttachmentParamsSchema as o, conversationFeedQuerySchema as p, briefResourceLabel as q, acceptedConversationMessageSchema as r, conversationAuxiliaryCostsSchema as s, CONVERSATION_DETAIL_VERSION_HEADER as t, conversationEventHistorySchema as u, conversationReportStatusSchema as v, forkConversationBodySchema as w, conversationUsageSchema as x, conversationSummaryReportSchema as y, resolveMessageCards as z };
@@ -1,4 +1,4 @@
1
- import { P as reviewItemChangeRecordSchema, U as messageAttachmentSchema, i as actorIdentitySchema, l as conversationDetailReportSchema } from "./conversation-CDWejM4R.js";
1
+ import { H as messageAttachmentSchema, K as briefOutcomeStatusSchema, N as reviewItemChangeRecordSchema, i as actorIdentitySchema, l as conversationDetailReportSchema, y as conversationSummaryReportSchema } from "./conversation-CMkSmi02.js";
2
2
  import * as z from "zod";
3
3
  // src/reporting-schema.ts
4
4
  const healthReportSchema = z.object({
@@ -21,6 +21,8 @@ const skillReportSchema = z.object({
21
21
  disableModelInvocation: z.boolean().optional()
22
22
  }).strict();
23
23
  const skillReportsSchema = z.array(skillReportSchema);
24
+ /** One skill with its authored SKILL.md body, without frontmatter. */
25
+ const skillDetailReportSchema = skillReportSchema.extend({ body: z.string() }).strict();
24
26
  const pluginPackageContentItemReportSchema = z.object({
25
27
  dir: z.string(),
26
28
  hasMigrationsDir: z.boolean(),
@@ -178,4 +180,27 @@ const steerConversationPendingMessagesResponseSchema = z.object({
178
180
  conversationId: z.string().min(1),
179
181
  steeredInboundMessageIds: z.array(z.string().min(1))
180
182
  }).strict();
181
- export { pluginsSchema as _, conversationPendingMessageDeliverySchema as a, skillReportsSchema as b, conversationUnchangedDetailWithMailboxSchema as c, healthReportSchema as d, pluginOperationalReportFeedSchema as f, pluginSchema as g, pluginPackageContentReportSchema as h, conversationPendingAuthorizationSchema as i, steerConversationPendingMessagesBodySchema as l, pluginPackageContentItemReportSchema as m, cancelConversationPendingMessagesResponseSchema as n, conversationPendingMessageSchema as o, pluginOperationalReportSchema as p, conversationDetailWithMailboxReportSchema as r, conversationPendingMessagesReportSchema as s, cancelConversationPendingMessagesBodySchema as t, steerConversationPendingMessagesResponseSchema as u, runtimeInfoReportSchema as v, skillReportSchema as y };
183
+ // src/api/schema/conversation-feed.ts
184
+ /**
185
+ * The part of a Conversation's latest Brief that a feed row shows: what the
186
+ * work is about and how it stands.
187
+ */
188
+ const conversationFeedBriefSchema = z.object({
189
+ intent: z.string(),
190
+ status: briefOutcomeStatusSchema,
191
+ summary: z.string()
192
+ }).strict();
193
+ /**
194
+ * A root in the feed, or one of its visible Threads. A Thread nests under
195
+ * its nearest visible Thread ancestor, or under the root. Tasks never show.
196
+ */
197
+ const conversationFeedItemSchema = conversationSummaryReportSchema.extend({
198
+ brief: conversationFeedBriefSchema.optional(),
199
+ threads: z.lazy(() => z.array(conversationFeedItemSchema)).optional()
200
+ });
201
+ const conversationFeedSchema = z.object({
202
+ conversations: z.array(conversationFeedItemSchema),
203
+ source: z.literal("conversation_index"),
204
+ generatedAt: z.string()
205
+ }).strict();
206
+ export { skillReportsSchema as C, skillReportSchema as S, pluginPackageContentReportSchema as _, conversationDetailWithMailboxReportSchema as a, runtimeInfoReportSchema as b, conversationPendingMessageSchema as c, steerConversationPendingMessagesBodySchema as d, steerConversationPendingMessagesResponseSchema as f, pluginPackageContentItemReportSchema as g, pluginOperationalReportSchema as h, cancelConversationPendingMessagesResponseSchema as i, conversationPendingMessagesReportSchema as l, pluginOperationalReportFeedSchema as m, conversationFeedSchema as n, conversationPendingAuthorizationSchema as o, healthReportSchema as p, cancelConversationPendingMessagesBodySchema as r, conversationPendingMessageDeliverySchema as s, conversationFeedBriefSchema as t, conversationUnchangedDetailWithMailboxSchema as u, pluginSchema as v, skillDetailReportSchema as x, pluginsSchema as y };
@@ -1,4 +1,4 @@
1
- import { h as logWarn } from "./logging-Cb6MGvdt.js";
1
+ import { h as logWarn } from "./logging-9OAq-fdg.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  // src/chat/conversation-privacy.ts
4
4
  const SAFE_METADATA_KEY_LIMIT = 20;
@@ -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-DLQgfO5N.js";
2
- import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-mIZeGEWv.js";
3
- import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-Cb6MGvdt.js";
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";
4
4
  import { p as parseSlackUserId } from "./actor-6jsm_v96.js";
5
- import { B as upsertLinkedIdentity, I as findUserByVerifiedEmails, M as resolveActorIdentityId, s as getSqlExecutor } from "./db--xuNV7g6.js";
5
+ import { H as upsertLinkedIdentity, P as resolveActorIdentityId, R as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-Dts2XvLu.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-MtwokaqW.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-CLMA9AXd.js";
9
- import { t as discoverSkills } from "./skills-e3DDNlKO.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-DJu7w6mI.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";
11
11
  import { r as acquireActiveLock } from "./locks-D-0h111u.js";
12
- import { o as readIdentityById } from "./viewer-CjRFHR5U.js";
13
- import { r as getStateAdapter } from "./adapter-DxLhJEnO.js";
14
- import { gt as coerceThreadConversationState, pt as getPersistedThreadState } from "./task-runner-Dw7exu0-.js";
15
- import { _ as getMcpProviderErrorAttributes } from "./service-account-kio5nXSD.js";
16
- import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-XhdVg7OR.js";
17
- import { n as relayLocalOAuthCallback } from "./oauth-relay-D6xxVywK.js";
12
+ import { o as readIdentityById } from "./viewer-Bqkb678l.js";
13
+ import { a as getStateAdapter } from "./state-CO9ETDzk.js";
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";
18
+ import { n as relayLocalOAuthCallback } from "./oauth-relay-CsfIazeF.js";
18
19
  import path from "node:path";
19
20
  import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
20
21
  import * as z from "zod";
@@ -639,7 +640,7 @@ const localCredentialSyncSchema = z.object({
639
640
  tokens: pluginStoredTokensSchema
640
641
  }).strict();
641
642
  function syncSecret() {
642
- const secret = process.env.JUNIOR_SECRET?.trim();
643
+ const secret = readJuniorSecret();
643
644
  if (!secret) throw new Error("Local credential sync requires JUNIOR_SECRET");
644
645
  return secret;
645
646
  }
@@ -1,4 +1,4 @@
1
- import "./schema-DgvcyJ1y.js";
1
+ import "./schema-TSEisVJR.js";
2
2
  import * as z from "zod";
3
3
  import "drizzle-orm";
4
4
  import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
@@ -209,6 +209,11 @@ interface ConversationStore {
209
209
  /** Source normalized to a stable session locator; set-once when absent. */
210
210
  sessionSource?: Source;
211
211
  title?: string;
212
+ /**
213
+ * Kind of a new Conversation. Default `root`. An existing Conversation
214
+ * keeps its kind.
215
+ */
216
+ kind?: "root" | "automation";
212
217
  /**
213
218
  * Current visibility from its owner, such as a Slack event channel type. It
214
219
  * replaces the visibility of the shared Destination row. Omit it for saved
@@ -1,8 +1,8 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-mIZeGEWv.js";
3
- import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-Cb6MGvdt.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";
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, 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-BItuRqAR.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";
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";
@@ -897,11 +897,10 @@ const AUTOMATION_RUN = {
897
897
  }
898
898
  };
899
899
  /**
900
- * Return the behavior of one Turn. `automationRun` marks a Scheduled or Event
901
- * automation run. It is a temporary bridge until Conversation kind
902
- * `automation` replaces it.
903
- *
904
- * TODO(dcramer): Remove `automationRun` when kind `automation` ships.
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.
905
904
  */
906
905
  function turnBehavior(args) {
907
906
  if (args.automationRun) return AUTOMATION_RUN;
@@ -1063,7 +1062,7 @@ function emptyConversation(args) {
1063
1062
  schemaVersion: 1,
1064
1063
  conversationId: args.conversationId,
1065
1064
  createdAtMs: args.nowMs,
1066
- kind: "root",
1065
+ kind: args.kind ?? "root",
1067
1066
  lastActivityAtMs: args.nowMs,
1068
1067
  updatedAtMs: args.nowMs,
1069
1068
  ...args.destination ? { destination: args.destination } : void 0,
@@ -1143,6 +1142,7 @@ var SqlStore = class {
1143
1142
  const current = existing ?? emptyConversation({
1144
1143
  conversationId: args.conversationId,
1145
1144
  destination: args.destination,
1145
+ kind: args.kind,
1146
1146
  nowMs,
1147
1147
  source: args.source,
1148
1148
  ...sessionSource ? { sessionSource } : void 0
@@ -1388,6 +1388,49 @@ var SqlStore = class {
1388
1388
  function createSqlStore(executor) {
1389
1389
  return new SqlStore(executor);
1390
1390
  }
1391
+ // src/chat/conversations/sql/last-message.ts
1392
+ /**
1393
+ * Return a query for the newest event of one type in the outer Conversation
1394
+ * that matches the filter. It walks the message role or user message time
1395
+ * index from the newest event. The user message index has only matching
1396
+ * entries, so that read stops at the first one.
1397
+ */
1398
+ function latestEventAtQuery(db, type, filter) {
1399
+ return db.select({ createdAt: juniorConversationEvents.createdAt }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorConversations.conversationId), eq(juniorConversationEvents.type, type), filter)).orderBy(desc(juniorConversationEvents.createdAt), desc(juniorConversationEvents.seq)).limit(1);
1400
+ }
1401
+ /**
1402
+ * Return queries for the latest user instruction and the latest true user
1403
+ * Message of the outer Conversation.
1404
+ */
1405
+ function userMessageQueries(db) {
1406
+ const payload = juniorConversationEvents.payload;
1407
+ const authorKind = sql`(${db.select({ kind: juniorIdentities.kind }).from(juniorIdentities).where(eq(juniorIdentities.id, juniorConversationEvents.actorIdentityId))})`;
1408
+ return {
1409
+ instruction: latestEventAtQuery(db, "user_message", isUserInstruction(payload)),
1410
+ message: latestEventAtQuery(db, "message", sql`${payload}->>'role' = 'user' and ${authorKind} = 'user'`)
1411
+ };
1412
+ }
1413
+ /**
1414
+ * Return SQL for when the outer Conversation last got a Message that a
1415
+ * reader would notice: a true user message or a Junior reply that the
1416
+ * transcript shows. Tools, status, Events, quiet replies, and progress acks
1417
+ * (`meta.progress`) do not count. It is null when there is no such Message.
1418
+ */
1419
+ function lastMessageAtSql(db) {
1420
+ const payload = juniorConversationEvents.payload;
1421
+ const { instruction, message } = userMessageQueries(db);
1422
+ const reply = latestEventAtQuery(db, "message", sql`${payload}->>'role' = 'assistant' and (${payload}->'meta'->>'quiet') is distinct from 'true' and (${payload}->'meta'->>'progress') is distinct from 'true'`);
1423
+ return sql`greatest((${instruction}), (${message}), (${reply}))`.mapWith(juniorConversations.lastMessageAt);
1424
+ }
1425
+ /**
1426
+ * Store `lastMessageAtSql` on the Conversation row. Event appends call this
1427
+ * in their transaction when they add a Message, so feed reads take the time
1428
+ * from the row.
1429
+ */
1430
+ async function refreshLastMessageAt(executor, conversationId) {
1431
+ const db = executor.db();
1432
+ await db.update(juniorConversations).set({ lastMessageAt: lastMessageAtSql(db) }).where(eq(juniorConversations.conversationId, conversationId));
1433
+ }
1391
1434
  // src/chat/conversations/sql/event-actor.ts
1392
1435
  function isRecord(value) {
1393
1436
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -1714,6 +1757,7 @@ var SqlConversationEventStore = class {
1714
1757
  }
1715
1758
  const db = this.executor.db();
1716
1759
  await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(rows);
1760
+ if (pending.some((event) => event.data.type === "message" || event.data.type === "user_message")) await refreshLastMessageAt(this.executor, conversationId);
1717
1761
  for (const event of pending) if (event.data.type === "turn_started") await this.recordTurnInputParticipants(conversationId, event.data.inputMessageIds);
1718
1762
  return rows.map((row) => ({
1719
1763
  seq: row.seq,
@@ -2034,4 +2078,4 @@ async function closeDb() {
2034
2078
  current = void 0;
2035
2079
  await previous?.db.close();
2036
2080
  }
2037
- export { nextDetailVersion as $, SYSTEM_IDENTITY_ID as A, upsertLinkedIdentity as B, isTopLevelKind as C, locationFromRow as D, conversationKindFromRow as E, deleteProviderIdentityForUser as F, addAgentTurnUsage as G, claimProviderConversation as H, findUserByVerifiedEmails as I, agentTurnUsageSchema as J, agentTurnCostUsd as K, readUserTimezone as L, resolveActorIdentityId as M, saveActorAvatar as N, setFirstConversationLocation as O, deleteProviderIdentityForSlackUser as P, conversationDetailTouch as Q, recordGoogleSignIn as R, isPersonInput as S, turnBehavior as T, getConversationIdByProviderConversation as U, bindProviderConversation as V, parseSessionSource as W, resolveRootConversationId as X, hasAgentTurnUsage as Y, rootConversationIsArchived as Z, setArchivedAt as _, getConversationStore as a, withConversationMutationLock as b, conversationIdsWithAnnotation as c, createSqlConversationEventStore as d, touchConversationDetail as et, eventFromRow as f, readConversationTrees as g, conversationDescendants as h, getConversationMessageSearchStore as i, sameDestination as it, findActorIdentityId as j, startLocationThread as k, hasAnnotationKey as l, conversationAncestors as m, db_exports as n, parseDestination as nt, getDb as o, withConversationEventLock as p, agentTurnTotalTokens as q, getConversationEventStore as r, requireSlackDestination as rt, getSqlExecutor as s, closeDb as t, createSlackDestination as tt, treeHasAnnotationKey as u, loadConversationSlackTenantIds as v, postsRunNotices as w, deliversFinalText as x, createSqlStore as y, saveUserTimezone as z };
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 };
@@ -1,6 +1,6 @@
1
1
  import { _ as withScope } from "./sentry-BRTJqumy.js";
2
- import "./config-mIZeGEWv.js";
3
- import { h as logWarn, p as logException } from "./logging-Cb6MGvdt.js";
2
+ import "./config-DvnTPCfp.js";
3
+ import { h as logWarn, p as logException } from "./logging-9OAq-fdg.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";
@@ -108,6 +108,11 @@ const juniorConversations = pgTable("junior_conversations", {
108
108
  title: text("title"),
109
109
  createdAt: timestamptz("created_at").notNull(),
110
110
  lastActivityAt: timestamptz("last_activity_at").notNull(),
111
+ /**
112
+ * The newest Message that a reader would notice (`refreshLastMessageAt`).
113
+ * Null until the Conversation has one.
114
+ */
115
+ lastMessageAt: timestamptz("last_message_at"),
111
116
  updatedAt: timestamptz("updated_at").notNull(),
112
117
  executionUpdatedAt: timestamptz("execution_updated_at"),
113
118
  executionStatus: text("execution_status").$type().notNull(),
@@ -644,7 +649,7 @@ const juniorReviewItems = pgTable("junior_review_items", {
644
649
  createdAt: timestamptz("created_at").notNull(),
645
650
  updatedAt: timestamptz("updated_at").notNull()
646
651
  }, (table) => [
647
- check("junior_review_items_kind_check", sql`(${table.kind} = 'notice' and ${table.request} is null and ${table.answer} is null) or (${table.kind} = 'action' and ${table.request} is not null)`),
652
+ check("junior_review_items_kind_check", sql`(${table.kind} = 'notice' and ${table.request} is null and ${table.answer} is null) or (${table.kind} = 'action' and (${table.request} is not null or (${table.dedupeKey} like 'plugin:%' and ${table.answer} is null)))`),
648
653
  check("junior_review_items_status_check", sql`(${table.status} = 'open' and ${table.closedAt} is null) or (${table.status} in ('done', 'dismissed') and ${table.closedAt} is not null)`),
649
654
  check("junior_review_items_tenant_check", sql`(${table.provider} is null) = (${table.providerTenantId} is null)`),
650
655
  check("junior_review_items_visibility_check", sql`${table.visibility} = 'public' or not ${table.assignedToEveryone}`),
@@ -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-Cb6MGvdt.js";
3
- import { n as getCurrentConversationPrivacy } from "./conversation-privacy-C6h-X2cZ.js";
2
+ import { B as getDeploymentTelemetryAttributes, z as getDeploymentServiceVersion } from "./logging-9OAq-fdg.js";
3
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-DPjv4SnA.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";
@@ -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-Bdqhx8Qh.js";
2
+ import { t as JUNIOR_VERSION } from "./version-AQa7Fr2H.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";
@@ -1240,6 +1240,7 @@ function extractGenAiUsageAttributes(...sources) {
1240
1240
  ...outputTokens !== void 0 ? { "gen_ai.usage.output_tokens": outputTokens } : void 0,
1241
1241
  ...cachedInputTokens !== void 0 ? { "gen_ai.usage.cache_read.input_tokens": cachedInputTokens } : void 0,
1242
1242
  ...cacheCreationTokens !== void 0 ? { "gen_ai.usage.cache_creation.input_tokens": cacheCreationTokens } : void 0,
1243
+ ...cachedInputTokens !== void 0 && semanticInputTokens ? { "gen_ai.usage.cache_hit_ratio": cachedInputTokens / semanticInputTokens } : void 0,
1243
1244
  ...reasoningTokens !== void 0 ? { "gen_ai.usage.reasoning.output_tokens": reasoningTokens } : void 0,
1244
1245
  ...cost?.input !== void 0 ? { "app.cost.input_usd": cost.input } : void 0,
1245
1246
  ...cost?.output !== void 0 ? { "app.cost.output_usd": cost.output } : void 0,
@@ -1,13 +1,13 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Cn as renderUntrustedTag, Za as canAccessConversation, eo as readConversationAccessFromSql } from "./projection-DLQgfO5N.js";
3
- import { n as botConfig } from "./config-mIZeGEWv.js";
4
- import { A as SYSTEM_IDENTITY_ID, a as getConversationStore, o as getDb } from "./db--xuNV7g6.js";
5
- import { hn as toolInvocationDestination, in as AgentMessageTargetError, mn as actorFromRun, nn as AgentMessagePausedError } from "./agent-runner-DJu7w6mI.js";
6
- import { I as PARENT_AGENT_TARGET, v as getActiveAgentInvocationForConversation } from "./turn-failure-response-BqTTx3XG.js";
7
- import { G as admitAutomatedTurn, S as EVENT_WAIT_MS, V as postAutomatedTurnLimitNoticeForConversation } from "./session-stop-CeCXL3j9.js";
8
- import { r as appendAndEnqueueInboundMessage } from "./store-C8LsaJwS.js";
9
- import { a as enqueueAgentInvocation, c as createAgentInvocationForMessage, u as findChildAgentConversationId } from "./work-BWBG1EGV.js";
10
- import { r as enqueueAgentMessageToParent } from "./result-ChL-1KyW.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";
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. */