@sentry/junior 0.303.0 → 0.305.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 (82) hide show
  1. package/dist/{adapter-context-BdVnSuY5.js → adapter-context-BpvbUki8.js} +2 -2
  2. package/dist/{admin-AfeAdS3J.js → admin-CoDt35ny.js} +5 -5
  3. package/dist/{agent-runner-BP8_DLUv.js → agent-runner-C5d6rY5g.js} +600 -389
  4. package/dist/api/schema.d.ts +1 -1
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +59 -61
  8. package/dist/{app-Dd9v1mNx.d.ts → app-Cs157Zc5.d.ts} +5 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +86 -82
  11. package/dist/{automation-D9MvhOWY.js → automation-CuA3yEcD.js} +1 -1
  12. package/dist/{background-compaction-queue-xaE05jxH.js → background-compaction-queue-BTqMIfTA.js} +7 -3
  13. package/dist/{briefs-D8i-dKTp.js → briefs-BRdznF7c.js} +11 -8
  14. package/dist/{catalog-runtime-d1EM6Z0V.js → catalog-runtime-J52Tej47.js} +1 -1
  15. package/dist/cli/chat.js +15 -15
  16. package/dist/cli/check.js +5 -5
  17. package/dist/cli/init.js +1 -1
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +4 -4
  23. package/dist/{config-oGM7KA9M.js → config-CBZp0udd.js} +101 -7
  24. package/dist/{connections-BlikzEJv.js → connections-BYmuJ6Vm.js} +6 -6
  25. package/dist/{continue-in-slack-BZnYifiG.js → continue-in-slack-Cvot6S38.js} +8 -8
  26. package/dist/{conversation-CY1jnBiC.js → conversation-BOqdRtUx.js} +4 -12
  27. package/dist/{conversation-feed-BZJRk6UV.js → conversation-feed-CgpgP7yi.js} +35 -2
  28. package/dist/{conversation-privacy-Cx515ddM.js → conversation-privacy-D2pOzBNl.js} +10 -2
  29. package/dist/{conversation-turn-DAhRdX4m.js → conversation-turn-CI8WDpnK.js} +17 -17
  30. package/dist/{credential-sync-DfhmWFeo.js → credential-sync-COqnZ1Dx.js} +14 -14
  31. package/dist/{db-C-2tFxk3.js → db-DU84dCVu.js} +169 -6
  32. package/dist/{db-DPqcEM9_.d.ts → db-zbN5ZV_o.d.ts} +2 -2
  33. package/dist/{executor-NVfS8aQ2.js → executor-CFyrgOu1.js} +43 -9
  34. package/dist/{history-UZ3M2M9r.js → history-m2-ceTTX.js} +8 -2
  35. package/dist/{install-CHLrpRZc.js → install-CQ76CfRw.js} +2 -2
  36. package/dist/instrumentation.js +7 -3
  37. package/dist/{lineage-HGLhd_-N.js → lineage-DLd2UxVP.js} +2 -2
  38. package/dist/{logging-DiyqRLBx.js → logging-BPNTQVFu.js} +1 -1
  39. package/dist/{message-CkCOcbFH.js → message-BWJLeQ5e.js} +8 -8
  40. package/dist/{model-input-DmoPPtPE.js → model-input-DoM9Ht-d.js} +2 -2
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +5 -5
  43. package/dist/{oauth-callback-server-CIf_6YmA.js → oauth-callback-server-DeHbnAQl.js} +2 -2
  44. package/dist/{projection-DBq8tsA5.js → projection-CcFBVFUo.js} +552 -63
  45. package/dist/{prompt-D2KlJopL.js → prompt-C5LREK2p.js} +185 -12
  46. package/dist/{queue-DFaOscp5.js → queue-B2AAL3ym.js} +4 -4
  47. package/dist/{registry-Bu0Z9BEO.js → registry-BjZZqKqi.js} +1 -1
  48. package/dist/{resolve-DXuA3G0g.js → resolve-CeJgXuH1.js} +3 -3
  49. package/dist/{result-DpiNseDA.js → result-icDrueyB.js} +8 -8
  50. package/dist/{runner-iu1heRFv.js → runner-nVfMkMMB.js} +9 -9
  51. package/dist/{sandbox-egress-signals-2HFYDcQf.js → sandbox-egress-signals-H9vQ5qRf.js} +1 -1
  52. package/dist/{schema-DvfX3Gq_.js → schema-Bx0Mlo32.js} +3 -3
  53. package/dist/{schema-DHMOaRzC.d.ts → schema-CKcu-IK6.d.ts} +43 -11
  54. package/dist/{service-account-BcT5LR7V.js → service-account-DU5865XA.js} +6 -5
  55. package/dist/{service-account-xYkaQTrw.js → service-account-Dw06p3zm.js} +5 -5
  56. package/dist/{session-stop-BLLp1IP_.js → session-stop-uotLtp4g.js} +181 -59
  57. package/dist/{skills-CNAGH4ju.js → skills-Bex1EaO5.js} +2 -2
  58. package/dist/{slack-conversation-unfurl-DYnqe5ci.js → slack-conversation-unfurl-EPG3riWF.js} +12 -11
  59. package/dist/{spawn-cGasWW33.js → spawn-CoD3vDuS.js} +6 -6
  60. package/dist/{state-CDS6h_Wv.js → state-nCR4Muhn.js} +4 -4
  61. package/dist/{stop-DMMA67yT.js → stop-BFVd0P0m.js} +170 -65
  62. package/dist/{store-Dgs7Oe44.js → store-Ca6G962n.js} +5 -5
  63. package/dist/{task-queue-DcF0nhhz.js → task-queue-BLPZU6kC.js} +3 -3
  64. package/dist/{task-runner-BGXF7Fo7.js → task-runner-xsOPIxCZ.js} +7 -7
  65. package/dist/{thread-context-BPky1KBe.js → thread-context-BOvZhsKK.js} +8 -8
  66. package/dist/{turn-session-routing-DGvn9MSl.js → turn-session-routing-2bW2qfeb.js} +8 -8
  67. package/dist/{turn-user-message-19CkuUvM.js → turn-user-message-BrhuyYrH.js} +3 -3
  68. package/dist/{validation-lu1DgjNQ.js → validation-BnY9K5WB.js} +1 -1
  69. package/dist/{version-Uo3c94Dx.js → version-qROlRQGF.js} +1 -1
  70. package/dist/version.js +1 -1
  71. package/dist/{viewer-BPQHMx3-.js → viewer-CxUiOraX.js} +3 -3
  72. package/dist/{warmup-H8uLvW9e.js → warmup--Gkz7iB-.js} +79 -476
  73. package/dist/{worker-B-pM_-3K.js → worker-DJ8d9fmD.js} +7 -7
  74. package/migrations/0111_attachment_kinds.sql +14 -0
  75. package/migrations/0112_attachment_url_fill.sql +51 -0
  76. package/migrations/0113_attachment_url_index.sql +1 -0
  77. package/migrations/meta/0099_snapshot.json +102 -326
  78. package/migrations/meta/0111_snapshot.json +5011 -0
  79. package/migrations/meta/0112_snapshot.json +5011 -0
  80. package/migrations/meta/0113_snapshot.json +5033 -0
  81. package/migrations/meta/_journal.json +21 -0
  82. package/package.json +7 -7
@@ -1,11 +1,11 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { i as getChatConfig } from "./config-oGM7KA9M.js";
2
+ import { i as getChatConfig } from "./config-CBZp0udd.js";
3
3
  import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-D2iXzvlN.js";
4
- import { C as juniorConversationMetrics, D as juniorConversationAnnotations, F as juniorDestinations, M as juniorConversations, N as juniorIdentities, P as juniorUsers, S as CONVERSATION_METRICS, T as juniorConversationEvents, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as isUserInstruction, y as juniorConversationBindings } from "./executor-NVfS8aQ2.js";
5
- import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-UZ3M2M9r.js";
6
- import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-DiyqRLBx.js";
4
+ import { C as juniorConversationMetrics, D as juniorConversationAnnotations, F as juniorUsers, I as juniorDestinations, M as juniorMessageAttachments, N as juniorConversations, P as juniorIdentities, S as CONVERSATION_METRICS, T as juniorConversationEvents, j as juniorAttachments, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as isUserInstruction, y as juniorConversationBindings } from "./executor-CFyrgOu1.js";
5
+ import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-m2-ceTTX.js";
6
+ import { G as normalizeIdentityEmail, U as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-BPNTQVFu.js";
7
7
  import * as z from "zod";
8
- import { randomUUID } from "node:crypto";
8
+ import { createHash, randomUUID } from "node:crypto";
9
9
  import { and, asc, desc, eq, gt, gte, inArray, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
10
10
  import { destinationSchema, locationSchema, sourceSchema } from "@sentry/junior-plugin-api";
11
11
  import { alias } from "drizzle-orm/pg-core";
@@ -2136,6 +2136,168 @@ async function restoreArchivedPath(db, conversationId) {
2136
2136
  async function withConversationEventLock(executor, conversationId, callback) {
2137
2137
  return executor.withLock(`junior_conversation:${conversationId}`, callback);
2138
2138
  }
2139
+ // src/chat/conversations/message-links.ts
2140
+ /**
2141
+ * Web link matches in message text. Slack wraps links as <url|label>, and
2142
+ * Markdown as (url), so a match stops at those delimiters. Trailing
2143
+ * punctuation is dropped. Readers parse a link before they show it.
2144
+ *
2145
+ * Migration `0112_attachment_url_fill` runs these patterns in Postgres to
2146
+ * fill links for older messages, so they use only syntax that JavaScript and
2147
+ * Postgres read the same way. The whitespace set is the one that JavaScript
2148
+ * `\s` matches, spelled out, because Postgres `\s` depends on the locale.
2149
+ */
2150
+ const MESSAGE_URL_PATTERN = String.raw`https?://[^\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff<>|"'\u0060]+`;
2151
+ const TRAILING_PUNCTUATION_PATTERN = String.raw`[.,;:!?)\]}*_~]+$`;
2152
+ /**
2153
+ * Longest link, in UTF-8 bytes, that a message stores. The unique index on
2154
+ * `(conversation_id, url)` holds the whole link, and a Postgres btree entry
2155
+ * cannot pass about 2.7 kB. Migration `0112_attachment_url_fill` uses the
2156
+ * same limit.
2157
+ */
2158
+ const MAX_LINK_BYTES = 2048;
2159
+ const messageUrlPattern = new RegExp(MESSAGE_URL_PATTERN, "g");
2160
+ const trailingPunctuation = new RegExp(TRAILING_PUNCTUATION_PATTERN);
2161
+ /**
2162
+ * Id of a Conversation's `url` Attachment. A repeat of the link in the
2163
+ * Conversation gets the same id. A link never holds a space, so the space
2164
+ * keeps the two parts apart. Migration `0112_attachment_url_fill` computes
2165
+ * the same id in SQL.
2166
+ */
2167
+ function urlAttachmentId(conversationId, url) {
2168
+ return createHash("sha256").update(`${conversationId} ${url}`).digest("hex");
2169
+ }
2170
+ /**
2171
+ * The links of one stored event payload, first match of each link only. Only
2172
+ * messages count, and a channel message that did not mention Junior stays
2173
+ * out, as in the transcript.
2174
+ */
2175
+ function messageLinks(event) {
2176
+ const { meta, text } = event.payload;
2177
+ if (event.type !== "message" || typeof text !== "string") return [];
2178
+ const mention = meta !== null && typeof meta === "object" && !Array.isArray(meta) && "explicitMention" in meta ? meta.explicitMention : void 0;
2179
+ if (mention === false || mention === "false") return [];
2180
+ const links = /* @__PURE__ */ new Map();
2181
+ let position = 0;
2182
+ for (const match of text.matchAll(messageUrlPattern)) {
2183
+ position += 1;
2184
+ const url = match[0].replace(trailingPunctuation, "");
2185
+ if (links.has(url) || Buffer.byteLength(url) > MAX_LINK_BYTES) continue;
2186
+ links.set(url, {
2187
+ conversationId: event.conversationId,
2188
+ createdAt: event.createdAt,
2189
+ position,
2190
+ seq: event.seq,
2191
+ url
2192
+ });
2193
+ }
2194
+ return [...links.values()];
2195
+ }
2196
+ /**
2197
+ * The links that a batch of new event rows writes. Links keep the seq of the
2198
+ * first save of their message, like the transcript, and an edit replaces
2199
+ * them. `storedMessageSeqs` maps the Message ids that the batch edits to
2200
+ * their stored seqs; `replacedSeqs` names the stored seqs whose links go.
2201
+ */
2202
+ function batchMessageLinks(rows, storedMessageSeqs) {
2203
+ const seqById = new Map(storedMessageSeqs);
2204
+ const linksBySeq = /* @__PURE__ */ new Map();
2205
+ const replacedSeqs = /* @__PURE__ */ new Set();
2206
+ for (const row of rows) {
2207
+ const { messageId } = row.payload;
2208
+ if (row.type === "message") {
2209
+ if (typeof messageId === "string" && !seqById.has(messageId)) seqById.set(messageId, row.seq);
2210
+ linksBySeq.set(row.seq, messageLinks(row));
2211
+ continue;
2212
+ }
2213
+ if (row.type !== "message_updated" || typeof messageId !== "string") continue;
2214
+ const seq = seqById.get(messageId);
2215
+ if (seq === void 0) continue;
2216
+ if (storedMessageSeqs.get(messageId) === seq) replacedSeqs.add(seq);
2217
+ linksBySeq.set(seq, messageLinks({
2218
+ ...row,
2219
+ seq,
2220
+ type: "message"
2221
+ }));
2222
+ }
2223
+ return {
2224
+ links: [...linksBySeq.values()].flat(),
2225
+ replacedSeqs: [...replacedSeqs]
2226
+ };
2227
+ }
2228
+ // src/chat/conversations/sql/message-links.ts
2229
+ /**
2230
+ * The stored seqs of the Messages that new `message_updated` rows edit, so
2231
+ * their links can be replaced. An edit of a Message that is not stored yet
2232
+ * finds no seq here.
2233
+ */
2234
+ async function readEditedMessageSeqs(executor, conversationId, rows) {
2235
+ const messageIds = rows.flatMap(({ payload, type }) => type === "message_updated" && typeof payload["messageId"] === "string" ? [payload["messageId"]] : []);
2236
+ if (messageIds.length === 0) return /* @__PURE__ */ new Map();
2237
+ const e = juniorConversationEvents;
2238
+ const messageId = sql`${e.payload}->>'messageId'`;
2239
+ const stored = await executor.db().select({
2240
+ messageId,
2241
+ seq: e.seq
2242
+ }).from(e).where(and(eq(e.conversationId, conversationId), eq(e.type, "message"), inArray(messageId, messageIds))).orderBy(desc(e.seq));
2243
+ return new Map(stored.map((row) => [row.messageId, row.seq]));
2244
+ }
2245
+ /**
2246
+ * Store the web links of new message events as `url` Attachments of their
2247
+ * Conversation, and where each message uses them. Call it in the transaction
2248
+ * that inserts the events, so a message is never stored without its links.
2249
+ */
2250
+ async function writeMessageLinks(executor, conversationId, rows) {
2251
+ const { links, replacedSeqs } = batchMessageLinks(rows, await readEditedMessageSeqs(executor, conversationId, rows));
2252
+ const db = executor.db();
2253
+ if (replacedSeqs.length > 0) await db.delete(juniorMessageAttachments).where(and(eq(juniorMessageAttachments.conversationId, conversationId), inArray(juniorMessageAttachments.seq, replacedSeqs)));
2254
+ await insertLinks(executor, conversationId, links);
2255
+ }
2256
+ async function insertLinks(executor, conversationId, links) {
2257
+ if (links.length === 0) return;
2258
+ const db = executor.db();
2259
+ const withIds = links.map((link) => ({
2260
+ ...link,
2261
+ attachmentId: urlAttachmentId(conversationId, link.url)
2262
+ }));
2263
+ const attachments = new Map(withIds.map((link) => [link.attachmentId, {
2264
+ conversationId,
2265
+ createdAt: link.createdAt,
2266
+ id: link.attachmentId,
2267
+ kind: "url",
2268
+ url: link.url
2269
+ }]));
2270
+ await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorAttachments).values([...attachments.values()]).onConflictDoNothing({ target: juniorAttachments.id });
2271
+ await db.insert(juniorMessageAttachments).values(withIds.map(({ attachmentId, position, seq }) => ({
2272
+ attachmentId,
2273
+ conversationId,
2274
+ position,
2275
+ seq
2276
+ }))).onConflictDoNothing();
2277
+ }
2278
+ /**
2279
+ * Copy the links of the copied messages into a fork. Copies keep their seq,
2280
+ * and the fork gets its own `url` Attachments.
2281
+ */
2282
+ async function copyMessageLinks(executor, args) {
2283
+ if (args.seqs.length === 0) return;
2284
+ const m = juniorMessageAttachments;
2285
+ const a = juniorAttachments;
2286
+ const links = await executor.db().select({
2287
+ createdAt: a.createdAt,
2288
+ position: m.position,
2289
+ seq: m.seq,
2290
+ url: a.url
2291
+ }).from(m).innerJoin(a, eq(a.id, m.attachmentId)).where(and(eq(m.conversationId, args.sourceConversationId), inArray(m.seq, [...args.seqs]), isNull(a.deleteRequestedAt)));
2292
+ await insertLinks(executor, args.conversationId, links.flatMap(({ url, ...link }) => url === null ? [] : [{
2293
+ ...link,
2294
+ url
2295
+ }]));
2296
+ }
2297
+ /** Delete where purged messages use Attachments, with the messages. */
2298
+ async function deleteMessageLinks(executor, conversationIds) {
2299
+ await executor.db().delete(juniorMessageAttachments).where(inArray(juniorMessageAttachments.conversationId, [...conversationIds]));
2300
+ }
2139
2301
  // src/chat/conversations/sql/history.ts
2140
2302
  const messageHistoryEventTypes = [
2141
2303
  "message",
@@ -2258,6 +2420,7 @@ var SqlConversationEventStore = class {
2258
2420
  }
2259
2421
  const db = this.executor.db();
2260
2422
  await db.with(conversationDetailTouch(db, [conversationId])).insert(juniorConversationEvents).values(rows);
2423
+ await writeMessageLinks(this.executor, conversationId, rows);
2261
2424
  if (pending.some((event) => event.data.type === "message" || event.data.type === "user_message")) await refreshLastMessageAt(this.executor, conversationId);
2262
2425
  for (const event of pending) if (event.data.type === "turn_started") await this.recordTurnInputParticipants(conversationId, event.data.inputMessageIds);
2263
2426
  return rows.map((row) => ({
@@ -2573,4 +2736,4 @@ async function closeDb() {
2573
2736
  current = void 0;
2574
2737
  await previous?.db.close();
2575
2738
  }
2576
- export { fenceLock as $, setFirstConversationLocation as A, recordGoogleSignIn as B, isPersonInput as C, turnBehavior as D, promptModeTurnTools as E, saveActorAvatar as F, createCache as G, upsertLinkedIdentity as H, deleteProviderIdentityForSlackUser as I, getStateAdapter as J, disconnectStateAdapter as K, deleteProviderIdentityForUser as L, SYSTEM_IDENTITY_ID as M, findActorIdentityId as N, conversationKindFromRow as O, resolveActorIdentityId as P, acquireActiveLock as Q, findUserByVerifiedEmails as R, deliversFinalText as S, postsRunNotices as T, clearCachedUser as U, saveUserTimezone as V, readCachedUserByEmail as W, setStateValues as X, getStateValues as Y, MUTATION_LOCK_TTL_MS as Z, loadConversationSlackTenantIds as _, sameDestination as _t, getConversationStore as a, agentTurnCostUsd as at, createSqlStore as b, hasAnnotationKey as c, hasAgentTurnUsage as ct, eventFromRow as d, conversationDetailTouch as dt, withLock as et, withConversationEventLock as f, nextDetailVersion as ft, setArchivedAt as g, requireSlackDestination as gt, readConversationTrees as h, parseDestination as ht, getConversationMessageSearchStore as i, addAgentTurnUsage as it, startLocationThread as j, locationFromRow as k, treeHasAnnotationKey as l, resolveRootConversationId as lt, conversationDescendants as m, createSlackDestination as mt, db_exports as n, getConversationIdByProviderConversation as nt, getDb as o, agentTurnTotalTokens as ot, conversationAncestors as p, touchConversationDetail as pt, getDefaultRedisStateAdapterFor as q, getConversationEventStore as r, parseSessionSource as rt, getSqlExecutor as s, agentTurnUsageSchema as st, closeDb as t, claimProviderConversation as tt, createSqlConversationEventStore as u, rootConversationIsArchived as ut, lastMessageAtSql as v, isTopLevelKind as w, withConversationMutationLock as x, userMessageQueries as y, readUserTimezone as z };
2739
+ export { MUTATION_LOCK_TTL_MS as $, conversationKindFromRow as A, findUserByVerifiedEmails as B, withConversationMutationLock as C, postsRunNotices as D, isTopLevelKind as E, findActorIdentityId as F, clearCachedUser as G, recordGoogleSignIn as H, resolveActorIdentityId as I, disconnectStateAdapter as J, readCachedUserByEmail as K, saveActorAvatar as L, setFirstConversationLocation as M, startLocationThread as N, promptModeTurnTools as O, SYSTEM_IDENTITY_ID as P, setStateValues as Q, deleteProviderIdentityForSlackUser as R, createSqlStore as S, isPersonInput as T, saveUserTimezone as U, readUserTimezone as V, upsertLinkedIdentity as W, getStateAdapter as X, getDefaultRedisStateAdapterFor as Y, getStateValues as Z, readConversationTrees as _, parseDestination as _t, getConversationStore as a, parseSessionSource as at, lastMessageAtSql as b, hasAnnotationKey as c, agentTurnTotalTokens as ct, eventFromRow as d, resolveRootConversationId as dt, acquireActiveLock as et, copyMessageLinks as f, rootConversationIsArchived as ft, conversationDescendants as g, createSlackDestination as gt, conversationAncestors as h, touchConversationDetail as ht, getConversationMessageSearchStore as i, getConversationIdByProviderConversation as it, locationFromRow as j, turnBehavior as k, treeHasAnnotationKey as l, agentTurnUsageSchema as lt, withConversationEventLock as m, nextDetailVersion as mt, db_exports as n, withLock as nt, getDb as o, addAgentTurnUsage as ot, deleteMessageLinks as p, conversationDetailTouch as pt, createCache as q, getConversationEventStore as r, claimProviderConversation as rt, getSqlExecutor as s, agentTurnCostUsd as st, closeDb as t, fenceLock as tt, createSqlConversationEventStore as u, hasAgentTurnUsage as ut, setArchivedAt as v, requireSlackDestination as vt, deliversFinalText as w, userMessageQueries as x, loadConversationSlackTenantIds as y, sameDestination as yt, deleteProviderIdentityForUser as z };
@@ -1,10 +1,10 @@
1
- import "./schema-DHMOaRzC.js";
1
+ import "./schema-CKcu-IK6.js";
2
2
  import * as z from "zod";
3
+ import "@earendil-works/pi-ai";
3
4
  import "drizzle-orm";
4
5
  import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
5
6
  import "drizzle-orm/pg-core";
6
7
  import "drizzle-orm/migrator";
7
- import "@earendil-works/pi-ai";
8
8
  import "drizzle-orm/pg-core/session";
9
9
  type ConversationPrivacy = "public" | "private";
10
10
  /** Validated Location associated with a Conversation. */
@@ -1,6 +1,6 @@
1
- import { h as logWarn, p as logException } from "./logging-DiyqRLBx.js";
1
+ import { h as logWarn, p as logException } from "./logging-BPNTQVFu.js";
2
2
  import { _ as withScope } from "./sentry-CPbZjomA.js";
3
- import "./config-oGM7KA9M.js";
3
+ import "./config-CBZp0udd.js";
4
4
  import { AsyncLocalStorage } from "node:async_hooks";
5
5
  import { sql } from "drizzle-orm";
6
6
  import { bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
@@ -162,12 +162,18 @@ const juniorConversations = pgTable("junior_conversations", {
162
162
  index("junior_conversations_root_idx").on(table.rootConversationId)
163
163
  ]);
164
164
  // src/db/schema/attachments.ts
165
- /** Durable metadata for files owned by one conversation. */
165
+ /**
166
+ * What a Message carries: a stored file (`file`) or a web link that its text
167
+ * names (`url`). Rows are owned by one Conversation, and a repeat of the same
168
+ * thing in that Conversation reuses its row.
169
+ */
166
170
  const juniorAttachments = pgTable("junior_attachments", {
167
171
  id: text("id").primaryKey(),
172
+ /** `file` or `url`. Only `file` rows have storage and file fields. */
173
+ kind: text("kind").notNull().default("file"),
168
174
  conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
169
175
  /** Service that stores the file bytes. */
170
- storageProvider: text("storage_provider").notNull(),
176
+ storageProvider: text("storage_provider"),
171
177
  /**
172
178
  * Object key of the stored bytes. Null for a file that Junior records
173
179
  * without storing, such as a large Slack file.
@@ -177,9 +183,15 @@ const juniorAttachments = pgTable("junior_attachments", {
177
183
  provider: text("provider"),
178
184
  /** File id assigned by the source provider. */
179
185
  providerId: text("provider_id"),
180
- filename: text("filename").notNull(),
181
- contentType: text("content_type").notNull(),
182
- bytes: integer("bytes").notNull(),
186
+ /**
187
+ * File name of a file. The column keeps its old name until no worker
188
+ * that reads `filename` runs.
189
+ */
190
+ title: text("filename"),
191
+ contentType: text("content_type"),
192
+ bytes: integer("bytes"),
193
+ /** Web link of a `url` row, as its message text wrote it. */
194
+ url: text("url"),
183
195
  /** Digest of the stored bytes. Null when `storage_key` is null. */
184
196
  sha256: text("sha256"),
185
197
  visionSummary: text("vision_summary"),
@@ -189,9 +201,30 @@ const juniorAttachments = pgTable("junior_attachments", {
189
201
  }, (table) => [
190
202
  index("junior_attachments_conversation_idx").on(table.conversationId),
191
203
  index("junior_attachments_provider_idx").on(table.conversationId, table.provider, table.providerId),
192
- index("junior_attachments_gc_idx").on(table.storageProvider, table.deleteRequestedAt, table.createdAt)
204
+ index("junior_attachments_gc_idx").on(table.storageProvider, table.deleteRequestedAt, table.createdAt),
205
+ uniqueIndex("junior_attachments_conversation_url_idx").on(table.conversationId, table.url).where(sql`${table.url} IS NOT NULL`)
193
206
  ]);
194
207
  /**
208
+ * Where each stored message event uses an Attachment. `seq` is the seq of the
209
+ * first save of its message, as in the transcript. `position` is the 1-based
210
+ * order of a link in the message text, and null for an Attachment that is not
211
+ * in the text. No foreign keys, so creating the table locks no existing
212
+ * table.
213
+ */
214
+ const juniorMessageAttachments = pgTable("junior_message_attachments", {
215
+ conversationId: text("conversation_id").notNull(),
216
+ seq: integer("seq").notNull(),
217
+ attachmentId: text("attachment_id").notNull(),
218
+ position: integer("position")
219
+ }, (table) => [primaryKey({
220
+ name: "junior_message_attachments_pk",
221
+ columns: [
222
+ table.conversationId,
223
+ table.seq,
224
+ table.attachmentId
225
+ ]
226
+ })]);
227
+ /**
195
228
  * Browser uploads that wait for a web Message.
196
229
  *
197
230
  * A row binds one object key to the viewer, Conversation, and Message
@@ -824,6 +857,7 @@ const juniorSqlSchema = {
824
857
  juniorArtifacts,
825
858
  juniorAttachmentUploads,
826
859
  juniorAttachments,
860
+ juniorMessageAttachments,
827
861
  juniorCodeChanges,
828
862
  juniorCodeRepositories,
829
863
  juniorConversationAnnotations,
@@ -1340,4 +1374,4 @@ function createJuniorSqlExecutor(args) {
1340
1374
  statementTimeoutMs
1341
1375
  });
1342
1376
  }
1343
- export { juniorAttachmentUploads as A, juniorConversationMetrics as C, juniorConversationAnnotations as D, juniorApiTokens as E, juniorDestinations as F, juniorArtifacts as I, juniorConversations as M, juniorIdentities as N, juniorCodeChanges as O, juniorUsers as P, CONVERSATION_METRICS as S, juniorConversationEvents as T, juniorConversationReadPositions as _, juniorPushSubscriptions as a, juniorConversationEmbeddings as b, juniorReviewItemSlackCards as c, juniorAutomationVersions as d, juniorAutomations as f, juniorAgentInvocations as g, juniorAgentBindings as h, juniorWorkspaces as i, juniorAttachments as j, juniorCodeRepositories 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, isUserInstruction as w, juniorConversationBriefs as x, juniorConversationBindings as y };
1377
+ export { juniorAttachmentUploads as A, juniorConversationMetrics as C, juniorConversationAnnotations as D, juniorApiTokens as E, juniorUsers as F, juniorDestinations as I, juniorArtifacts as L, juniorMessageAttachments as M, juniorConversations as N, juniorCodeChanges as O, juniorIdentities as P, CONVERSATION_METRICS as S, juniorConversationEvents as T, juniorConversationReadPositions as _, juniorPushSubscriptions as a, juniorConversationEmbeddings as b, juniorReviewItemSlackCards as c, juniorAutomationVersions as d, juniorAutomations as f, juniorAgentInvocations as g, juniorAgentBindings as h, juniorWorkspaces as i, juniorAttachments as j, juniorCodeRepositories 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, isUserInstruction as w, juniorConversationBriefs as x, juniorConversationBindings as y };
@@ -72,7 +72,7 @@ const messageFieldsSchema = z.record(z.string(), z.unknown());
72
72
  const replacementEntrySchema = z.object({ item: z.string() }).passthrough();
73
73
  /** Identify history events that store message fields as JSON strings. */
74
74
  function isEncodedHistoryType(type) {
75
- return type === "user_message" || type === "assistant_message" || type === "tool_result" || type === "handoff" || type === "compaction";
75
+ return type === "user_message" || type === "assistant_message" || type === "tool_result" || type === "system_message" || type === "handoff" || type === "compaction";
76
76
  }
77
77
  /** Encode agent history before SQL can change keys or string contents. */
78
78
  function encodeHistoryPayload(data) {
@@ -144,6 +144,10 @@ const toolResultEventDataSchema = z.object({
144
144
  type: z.literal("tool_result"),
145
145
  role: z.never().optional()
146
146
  }).passthrough();
147
+ const systemMessageEventDataSchema = z.object({
148
+ type: z.literal("system_message"),
149
+ role: z.never().optional()
150
+ }).passthrough();
147
151
  /**
148
152
  * One replayable agent-history item. Junior owns `type` and user provenance,
149
153
  * forbids the provider `role` discriminator, and leaves preserved message
@@ -152,7 +156,8 @@ const toolResultEventDataSchema = z.object({
152
156
  const agentHistoryItemSchema = z.discriminatedUnion("type", [
153
157
  userMessageEventDataSchema,
154
158
  assistantMessageEventDataSchema,
155
- toolResultEventDataSchema
159
+ toolResultEventDataSchema,
160
+ systemMessageEventDataSchema
156
161
  ]);
157
162
  const nativeReplacementHistoryItemSchema = z.object({
158
163
  item: agentHistoryItemSchema,
@@ -468,6 +473,7 @@ const KNOWN_CONVERSATION_EVENT_TYPES = [
468
473
  "user_message",
469
474
  "assistant_message",
470
475
  "tool_result",
476
+ "system_message",
471
477
  "mcp_provider_connected",
472
478
  "mcp_provider_connected_unowned",
473
479
  "authorization_requested",
@@ -1,5 +1,5 @@
1
- import { _o as runNonInteractiveCommand, do as SANDBOX_WORKSPACE_ROOT, so as SANDBOX_COMMAND_PATH } from "./projection-DBq8tsA5.js";
2
- import { E as withSpan, b as setSpanAttributes } from "./logging-DiyqRLBx.js";
1
+ import { ao as SANDBOX_COMMAND_PATH, ho as runNonInteractiveCommand, lo as SANDBOX_WORKSPACE_ROOT } from "./projection-CcFBVFUo.js";
2
+ import { E as withSpan, b as setSpanAttributes } from "./logging-BPNTQVFu.js";
3
3
  // src/chat/sandbox/resources.ts
4
4
  let configuredResources;
5
5
  function resourcesFromEnv() {
@@ -1,10 +1,10 @@
1
1
  import { a as getClient, c as init, i as getActiveSpan, o as getGlobalScope, p as spanToJSON, s as getTraceData } from "./sentry-CPbZjomA.js";
2
- import { n as getCurrentConversationPrivacy } from "./conversation-privacy-Cx515ddM.js";
2
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-D2pOzBNl.js";
3
3
  import { n as isPushServiceHost } from "./push-endpoint-CO-nomUd.js";
4
4
  import { n as redactSandboxEgressProxyPath } from "./proxy-path-BHYoKZdq.js";
5
5
  import { n as promoteHttpRouteName, r as routeNameMiddleware, t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
6
6
  import { t as consumePrivateTraceResultMarker } from "./private-trace-result-CE7_lEdq.js";
7
- import { B as getDeploymentServiceVersion, V as getDeploymentTelemetryAttributes } from "./logging-DiyqRLBx.js";
7
+ import { B as getDeploymentServiceVersion, V as getDeploymentTelemetryAttributes } from "./logging-BPNTQVFu.js";
8
8
  import { performance } from "node:perf_hooks";
9
9
  import { subscribe, unsubscribe } from "node:diagnostics_channel";
10
10
  // src/chat/pi/gateway-request-timing.ts
@@ -274,7 +274,10 @@ function scrubContainer(container) {
274
274
  scrubSensitiveUrlAttributes(container.data);
275
275
  scrubSensitiveUrlAttributes(container.attributes);
276
276
  }
277
- /** Remove private conversation payloads and boundary secrets from error events. */
277
+ /**
278
+ * Remove private conversation payloads and boundary secrets from error and
279
+ * user feedback events.
280
+ */
278
281
  function scrubPrivateSentryEvent(event) {
279
282
  scrubContainer(event);
280
283
  scrubSensitiveRequest(event.request);
@@ -394,6 +397,7 @@ function initSentry() {
394
397
  integrations: (defaultIntegrations) => defaultIntegrations.filter((integration) => !MANUAL_GEN_AI_INTEGRATIONS.has(integration.name))
395
398
  });
396
399
  getGlobalScope().setAttributes(deploymentSpanAttributes);
400
+ getGlobalScope().addEventProcessor((event) => event.type === "feedback" ? scrubPrivateSentryEvent(event) : event);
397
401
  subscribeGatewayRequestTiming();
398
402
  }
399
403
  export { getBrowserSentryConfig, initSentry, nameRequestRoute, routeNameMiddleware };
@@ -1,5 +1,5 @@
1
- import { O as conversationKindFromRow, o as getDb } from "./db-C-2tFxk3.js";
2
- import { M as juniorConversations } from "./executor-NVfS8aQ2.js";
1
+ import { A as conversationKindFromRow, o as getDb } from "./db-DU84dCVu.js";
2
+ import { N as juniorConversations } from "./executor-CFyrgOu1.js";
3
3
  import { desc, eq, sql } from "drizzle-orm";
4
4
  // src/chat/conversations/lineage.ts
5
5
  /**
@@ -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-CPbZjomA.js";
2
- import { t as JUNIOR_VERSION } from "./version-Uo3c94Dx.js";
2
+ import { t as JUNIOR_VERSION } from "./version-qROlRQGF.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,12 +1,12 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { A as actorFromRun, j as toolInvocationDestination } from "./agent-runner-BP8_DLUv.js";
3
- import { An as PARENT_AGENT_TARGET, Cn as createAgentInvocationForMessage, Dn as AgentMessageTargetError, En as AgentMessagePausedError, Gt as getActiveAgentInvocationForConversation, Jt as getLatestAgentInvocationForConversation, On as findChildAgentConversationId, hn as enqueueAgentInvocation, in as readChildConversationSender } from "./warmup-H8uLvW9e.js";
4
- import { a as enqueueAgentMessageToParent } from "./result-DpiNseDA.js";
5
- import { Co as readConversationAccessFromSql, Jn as renderUntrustedTag, bo as canAccessConversation } from "./projection-DBq8tsA5.js";
6
- import { n as botConfig } from "./config-oGM7KA9M.js";
7
- import { M as SYSTEM_IDENTITY_ID, a as getConversationStore, o as getDb } from "./db-C-2tFxk3.js";
8
- import { H as admitAutomatedTurn, L as postAutomatedTurnLimitNoticeForConversation, k as EVENT_WAIT_MS } from "./session-stop-BLLp1IP_.js";
9
- import { r as appendAndEnqueueInboundMessage } from "./store-Dgs7Oe44.js";
2
+ import { M as toolInvocationDestination, j as actorFromRun } from "./agent-runner-C5d6rY5g.js";
3
+ import { Cn as AgentMessagePausedError, Dn as PARENT_AGENT_TARGET, Gt as getLatestAgentInvocationForConversation, Ht as getActiveAgentInvocationForConversation, Tn as findChildAgentConversationId, bn as createAgentInvocationForMessage, fn as enqueueAgentInvocation, tn as readChildConversationSender, wn as AgentMessageTargetError } from "./warmup--Gkz7iB-.js";
4
+ import { a as enqueueAgentMessageToParent } from "./result-icDrueyB.js";
5
+ import { Kn as renderUntrustedTag, vo as canAccessConversation, xo as readConversationAccessFromSql } from "./projection-CcFBVFUo.js";
6
+ import { n as botConfig } from "./config-CBZp0udd.js";
7
+ import { P as SYSTEM_IDENTITY_ID, a as getConversationStore, o as getDb } from "./db-DU84dCVu.js";
8
+ import { L as postAutomatedTurnLimitNoticeForConversation, W as admitAutomatedTurn, k as EVENT_WAIT_MS } from "./session-stop-uotLtp4g.js";
9
+ import { r as appendAndEnqueueInboundMessage } from "./store-Ca6G962n.js";
10
10
  // src/chat/agent-invocations/top-level-message.ts
11
11
  const AGENT_MESSAGE_EVENT_NAMESPACE = "junior";
12
12
  /** Event type of a message from another top-level agent. */
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { s as getSqlExecutor } from "./db-C-2tFxk3.js";
2
+ import { s as getSqlExecutor } from "./db-DU84dCVu.js";
3
3
  import { h as isVisionImageMediaType, m as detectImageMediaType } from "./web-message-id-lNodcCOI.js";
4
- import { Nt as readLiveAttachment } from "./warmup-H8uLvW9e.js";
4
+ import { Jo as readLiveAttachment } from "./projection-CcFBVFUo.js";
5
5
  // src/chat/attachments/model-input.ts
6
6
  var model_input_exports = /* @__PURE__ */ __exportAll({ loadInputAttachments: () => loadInputAttachments });
7
7
  /** Largest file that Slack and web send to the model in the prompt. */
package/dist/nitro.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as JuniorPluginSet } from "./plugins-B_0Cr0MO.js";
2
- import { i as JuniorDashboardOptions } from "./app-Dd9v1mNx.js";
2
+ import { i as JuniorDashboardOptions } from "./app-Cs157Zc5.js";
3
3
  import { withSentryConfig as withSentryConfig$1 } from "@sentry/nitro";
4
4
  type SentryNitroConfig = Parameters<typeof withSentryConfig$1>[0];
5
5
  type SentryNitroOptions = NonNullable<Parameters<typeof withSentryConfig$1>[1]>;
package/dist/nitro.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { d as resolvePackageDir, t as discoverInstalledPluginPackageContent, u as isValidPackageName } from "./package-discovery-x4AvVhMj.js";
2
2
  import { a as pluginRuntimeRegistrationsFromPluginSet, r as pluginCatalogConfigFromPluginSet } from "./plugins-Bkk0XRo2.js";
3
- import { o as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, t as CACHE_WARMUP_QUEUE_TOPIC } from "./queue-DFaOscp5.js";
4
- import { t as PLUGIN_TASK_QUEUE_TOPIC } from "./task-queue-DcF0nhhz.js";
5
- import { s as resolveConversationWorkQueueTopic, t as BACKGROUND_COMPACTION_QUEUE_TOPIC } from "./background-compaction-queue-xaE05jxH.js";
6
- import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, B as getDeploymentServiceVersion, 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 } from "./logging-DiyqRLBx.js";
3
+ import { o as WORKSPACE_SNAPSHOT_JOB_QUEUE_TOPIC, t as CACHE_WARMUP_QUEUE_TOPIC } from "./queue-B2AAL3ym.js";
4
+ import { t as PLUGIN_TASK_QUEUE_TOPIC } from "./task-queue-BLPZU6kC.js";
5
+ import { s as resolveConversationWorkQueueTopic, t as BACKGROUND_COMPACTION_QUEUE_TOPIC } from "./background-compaction-queue-BTqMIfTA.js";
6
+ import { A as JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE, B as getDeploymentServiceVersion, 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 } from "./logging-BPNTQVFu.js";
7
7
  import { n as loadPluginSetFromModule, r as resolvePluginModule } from "./plugin-module-Cv2ETe8Y.js";
8
8
  import path from "node:path";
9
9
  import { cpSync, existsSync, mkdirSync, readdirSync, statSync } from "node:fs";
@@ -121,7 +121,7 @@ function copyIfExists(source, target) {
121
121
  function dashboardAssetPath(packageDir, fileName) {
122
122
  const candidates = [path.join(packageDir, fileName), path.join(packageDir, "dist", fileName)];
123
123
  for (const candidate of candidates) if (existsSync(candidate)) return candidate;
124
- throw new Error(`Junior dashboard asset ${fileName} was not built; run pnpm --filter @sentry/junior-dashboard build before building Nitro`);
124
+ throw new Error(`Dashboard asset ${fileName} was not built; run pnpm --filter @sentry/junior-dashboard build before building Nitro`);
125
125
  }
126
126
  function copyRootIntoServerOutput(cwd, serverRoot, root) {
127
127
  copyIfExists(root, resolveServerOutputPath(cwd, serverRoot, root));
@@ -1,5 +1,5 @@
1
- import { a as GET, n as syncLocalOAuthCredential, r as GET$1 } from "./credential-sync-DfhmWFeo.js";
2
- import { Zn as createUserTokenStore } from "./projection-DBq8tsA5.js";
1
+ import { a as GET, n as syncLocalOAuthCredential, r as GET$1 } from "./credential-sync-COqnZ1Dx.js";
2
+ import { Yn as createUserTokenStore } from "./projection-CcFBVFUo.js";
3
3
  import { createServer } from "node:http";
4
4
  // src/chat/local/oauth-callback-server.ts
5
5
  const LOCAL_OAUTH_TIMEOUT_MS = 6e5;