@sentry/junior 0.293.0 → 0.294.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 (72) hide show
  1. package/dist/{adapter-CMJfmHso.js → adapter-DxLhJEnO.js} +1 -1
  2. package/dist/{admin-uuecrKuD.js → admin-vt8aSiCD.js} +2 -2
  3. package/dist/{agent-runner-DHq1pjUg.js → agent-runner-DJu7w6mI.js} +68 -33
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +48 -28
  8. package/dist/{app-fWzCHFIb.d.ts → app--a5RLOrr.d.ts} +4 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +60 -69
  11. package/dist/{assistant-reply-CIApSfor.js → assistant-reply-iTtEdDyc.js} +1 -1
  12. package/dist/{automation-BE3z19VN.js → automation-BM-OBsKW.js} +1 -1
  13. package/dist/{background-compaction-queue-D7ncdEa6.js → background-compaction-queue-D2j-0XkH.js} +4 -4
  14. package/dist/{briefs-NpgMEFh1.js → briefs-JOAoCb6d.js} +3 -3
  15. package/dist/{catalog-runtime-DwbTyNRD.js → catalog-runtime-CLMA9AXd.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +7 -74
  23. package/dist/{config-B4b-NXH5.js → config-mIZeGEWv.js} +17 -7
  24. package/dist/{connections-Dz_AQg5p.js → connections-XhdVg7OR.js} +6 -6
  25. package/dist/{conversation-CtjR1Zcx.js → conversation-CDWejM4R.js} +1 -0
  26. package/dist/{conversation-pending-messages-1Kad1Mif.js → conversation-pending-messages-Dh2tfbaw.js} +1 -1
  27. package/dist/{conversation-privacy-DRsSgLGO.js → conversation-privacy-C6h-X2cZ.js} +1 -1
  28. package/dist/{credential-sync-ClCnnGVj.js → credential-sync-zigBlXS3.js} +13 -13
  29. package/dist/{db-CoA7_Xqu.js → db--xuNV7g6.js} +99 -6
  30. package/dist/{db-BbpttyKH.d.ts → db-DV5AbcGM.d.ts} +8 -6
  31. package/dist/{executor-SWyHhit0.js → executor-BItuRqAR.js} +58 -9
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BN5drSEZ.js → logging-Cb6MGvdt.js} +1 -1
  34. package/dist/{message-D4qjpW1C.js → message-BTGgSmaH.js} +9 -9
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +2 -2
  37. package/dist/{oauth-callback-server-Xi-mTLOV.js → oauth-callback-server-Dvh1aOIi.js} +2 -2
  38. package/dist/{projection-DXl4ftyL.js → projection-DLQgfO5N.js} +15 -96
  39. package/dist/{prompt-Dmx6IfWZ.js → prompt-qp_LdxLX.js} +5 -6
  40. package/dist/{registry-DosVt9f9.js → registry-MtwokaqW.js} +1 -1
  41. package/dist/{resolve-BDjWJC9s.js → resolve-BnJA0UNE.js} +3 -3
  42. package/dist/{result-CaAFpf4B.js → result-ChL-1KyW.js} +8 -8
  43. package/dist/{runner-h96Mkss6.js → runner-BONN7Dp2.js} +8 -8
  44. package/dist/{sandbox-egress-signals-rK91BW7i.js → sandbox-egress-signals-nmlmI5Ab.js} +1 -1
  45. package/dist/{schema-CHsBmXIj.d.ts → schema-DgvcyJ1y.d.ts} +38 -1
  46. package/dist/{schema-C_v8wb80.js → schema-yr0ccDni.js} +29 -4
  47. package/dist/{service-account-WUMVuqVL.js → service-account-Bd0lBaGr.js} +3 -3
  48. package/dist/{service-account-BpGpScaT.js → service-account-kio5nXSD.js} +3 -3
  49. package/dist/{session-stop-xYK15HUu.js → session-stop-CeCXL3j9.js} +11 -11
  50. package/dist/{skills-DHApyCjj.js → skills-e3DDNlKO.js} +2 -2
  51. package/dist/{spawn-BQQrwGNe.js → spawn--cRxITWQ.js} +5 -5
  52. package/dist/{stop-CBeD6_Gs.js → stop-Iai5N2PU.js} +25 -26
  53. package/dist/{store-xtibD98L.js → store-C8LsaJwS.js} +3 -3
  54. package/dist/{task-runner-BYPN4BEO.js → task-runner-Dw7exu0-.js} +11 -11
  55. package/dist/{turn-failure-response-jNVl00MD.js → turn-failure-response-BqTTx3XG.js} +8 -8
  56. package/dist/{validation-DGeB_moV.js → validation-BrGahtnv.js} +1 -1
  57. package/dist/{version-C6nqU3Qc.js → version-Bdqhx8Qh.js} +1 -1
  58. package/dist/version.js +1 -1
  59. package/dist/{viewer-9KLQibjn.js → viewer-CjRFHR5U.js} +3 -3
  60. package/dist/{warmup-7S6z068f.js → warmup-DuxCtzKC.js} +69 -23
  61. package/dist/{work-xwX6unUE.js → work-BWBG1EGV.js} +11 -11
  62. package/dist/{worker-CiCCfwd4.js → worker-DAnBIVMs.js} +6 -6
  63. package/migrations/0062_plugin_report_index.sql +1 -20
  64. package/migrations/0078_plugin_conversation_index.sql +1 -20
  65. package/migrations/0079_conversation_event_author_index.sql +1 -20
  66. package/migrations/0080_conversation_event_latest_message_indexes.sql +2 -27
  67. package/migrations/0090_guardian_review_time_index.sql +1 -20
  68. package/migrations/0091_conversation_participant_unsubscribed_index.sql +1 -20
  69. package/migrations/0097_conversation_kind_automation.sql +6 -0
  70. package/migrations/meta/0097_snapshot.json +4490 -0
  71. package/migrations/meta/_journal.json +7 -0
  72. package/package.json +4 -4
@@ -1,7 +1,7 @@
1
- import { Fa as SANDBOX_RUNTIME, ki as create } from "../projection-DXl4ftyL.js";
2
- import { n as pluginCatalogRuntime } from "../catalog-runtime-DwbTyNRD.js";
3
- import { t as disconnectStateAdapter } from "../adapter-CMJfmHso.js";
4
- import { n as resolve } from "../resolve-BDjWJC9s.js";
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";
5
5
  // src/cli/snapshot-create.ts
6
6
  const DEFAULT_TIMEOUT_MS = 6e5;
7
7
  function progressMessage(phase) {
@@ -1,4 +1,4 @@
1
- import "../db-BbpttyKH.js";
1
+ import "../db-DV5AbcGM.js";
2
2
  import { n as JuniorPluginSet } from "../plugins-DtmjkTza.js";
3
3
  interface UpgradeIo {
4
4
  info: (line: string) => void;
@@ -1,6 +1,6 @@
1
- import { i as getChatConfig } from "../config-B4b-NXH5.js";
2
- import { t as createJuniorSqlExecutor } from "../executor-SWyHhit0.js";
3
- import { t as createPluginCatalogRuntime } from "../registry-DosVt9f9.js";
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";
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";
@@ -8,69 +8,6 @@ import { createHash } from "node:crypto";
8
8
  import { readMigrationFiles } from "drizzle-orm/migrator";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { createJiti } from "jiti";
11
- // src/db/concurrent-indexes.ts
12
- const CONCURRENT_INDEX_MARKER = "-- junior:concurrent-index";
13
- const INDEX_STATEMENT = /^CREATE INDEX "([a-z0-9_]+)" ON "([a-z0-9_]+)" .+;$/;
14
- function markedIndexes(migration) {
15
- const lines = migration.sql.join("").split("\n").map((line) => line.trim());
16
- const indexes = [];
17
- for (const [index, line] of lines.entries()) {
18
- if (line !== CONCURRENT_INDEX_MARKER) continue;
19
- const statement = lines[index + 1] ?? "";
20
- const match = INDEX_STATEMENT.exec(statement);
21
- if (!match?.[1] || !match[2]) throw new Error(`Migration ${migration.folderMillis}: the line after "${CONCURRENT_INDEX_MARKER}" must be one CREATE INDEX statement on one line.`);
22
- indexes.push({
23
- name: match[1],
24
- statement,
25
- table: match[2]
26
- });
27
- }
28
- return indexes;
29
- }
30
- /** Remove the schema name so indexes on same-name tables compare equal. */
31
- function withoutSchema(definition) {
32
- return definition.replace(/ ON [^ ]+\./, " ON ");
33
- }
34
- async function readIndexState(executor, name) {
35
- const [row] = await executor.query(`SELECT pg_get_indexdef(indexrelid) AS definition,
36
- indisvalid AND indisready AS usable
37
- FROM pg_index
38
- WHERE indexrelid = to_regclass($1)`, [name]);
39
- return row;
40
- }
41
- async function expectedDefinition(executor, index) {
42
- return await executor.transaction(async () => {
43
- await executor.execute(`CREATE TEMPORARY TABLE "${index.table}" (LIKE "${index.table}") ON COMMIT DROP`);
44
- await executor.execute(index.statement);
45
- const [row] = await executor.query(`SELECT pg_get_indexdef(format('pg_temp.%I', $1::text)::regclass) AS definition`, [index.name]);
46
- if (!row) throw new Error(`Index ${index.name} was not built on the empty copy.`);
47
- return withoutSchema(row.definition);
48
- });
49
- }
50
- async function buildConcurrentIndex(executor, index) {
51
- const [table] = await executor.query(`SELECT to_regclass($1) IS NOT NULL AS "exists"`, [index.table]);
52
- if (!table?.exists) return;
53
- const expected = await expectedDefinition(executor, index);
54
- let state = await readIndexState(executor, index.name);
55
- if (state && !state.usable) {
56
- await executor.execute(`DROP INDEX CONCURRENTLY IF EXISTS "${index.name}"`);
57
- state = void 0;
58
- }
59
- if (!state) {
60
- await executor.execute(index.statement.replace(/^CREATE INDEX /, "CREATE INDEX CONCURRENTLY "));
61
- state = await readIndexState(executor, index.name);
62
- }
63
- if (!state?.usable || withoutSchema(state.definition) !== expected) throw new Error(`Index ${index.name} does not match its migration. Expected "${expected}", found "${state?.definition ?? "no index"}". Drop the index, then run junior upgrade again.`);
64
- }
65
- /**
66
- * Build the marked indexes of pending migrations before the transactional
67
- * migrate, so that the migrate does not block writes to existing tables.
68
- * Call it while the migration lock is held.
69
- */
70
- async function buildPendingConcurrentIndexes(executor, migrations, appliedAt) {
71
- const pending = migrations.filter((migration) => appliedAt === void 0 || migration.folderMillis > appliedAt);
72
- for (const index of pending.flatMap(markedIndexes)) await buildConcurrentIndex(executor, index);
73
- }
74
11
  // src/db/postgres-error.ts
75
12
  /** Return whether an unknown PostgreSQL failure has the requested SQLSTATE. */
76
13
  function isPostgresErrorCode(error, code) {
@@ -142,7 +79,6 @@ async function migrateSchema(executor) {
142
79
  const lockedState = await loadCoreMigrationState(executor);
143
80
  if (isCurrentMigrationState(lockedState, latestMigration.folderMillis)) return migrationResult(migrations, lockedState);
144
81
  assertSupportedMigrationState(lockedState);
145
- await buildPendingConcurrentIndexes(executor, migrations, lockedState.appliedAt);
146
82
  await executor.migrate({
147
83
  migrationsFolder,
148
84
  migrationsTable: MIGRATIONS_TABLE
@@ -257,13 +193,10 @@ async function migratePluginSchemas(executor, roots, options = {}) {
257
193
  table
258
194
  });
259
195
  const existing = appliedCount(migrations, currentTime);
260
- if (existing < migrations.length) {
261
- await buildPendingConcurrentIndexes(executor, migrations, currentTime);
262
- await executor.migrate({
263
- migrationsFolder: root.dir,
264
- migrationsTable: table
265
- });
266
- }
196
+ if (existing < migrations.length) await executor.migrate({
197
+ migrationsFolder: root.dir,
198
+ migrationsTable: table
199
+ });
267
200
  return {
268
201
  existing,
269
202
  migrated: migrations.length - existing,
@@ -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-BN5drSEZ.js";
3
- import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DRsSgLGO.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";
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";
@@ -401,6 +401,18 @@ function createProviderError(error, options = {}) {
401
401
  status
402
402
  });
403
403
  }
404
+ const REFUSAL_STOP_REASONS = /* @__PURE__ */ new Set(["refusal", "sensitive"]);
405
+ /** Return whether the provider refused to answer a Pi assistant message. */
406
+ function isProviderRefusal(message) {
407
+ return message.rawStopReason !== void 0 && REFUSAL_STOP_REASONS.has(message.rawStopReason);
408
+ }
409
+ /** Normalize a failed Pi assistant message. A provider refusal is a content policy block. */
410
+ function createAssistantProviderError(message, options = {}) {
411
+ return createProviderError(message.errorMessage ?? "", {
412
+ ...options,
413
+ ...isProviderRefusal(message) ? { kind: "content_policy" } : void 0
414
+ });
415
+ }
404
416
  /** Return whether a provider-boundary error should be retried. */
405
417
  function isProviderRetryError(error) {
406
418
  return error instanceof ProviderError && error.retryable;
@@ -1043,7 +1055,6 @@ async function completeText(params) {
1043
1055
  ...hasCompactedConversationContext(params.messages) ? { "gen_ai.conversation.compacted": true } : void 0,
1044
1056
  "app.conversation.privacy": effectivePrivacy,
1045
1057
  ...params.thinkingLevel ? { "gen_ai.request.reasoning.level": params.thinkingLevel } : void 0,
1046
- ...params.temperature !== void 0 ? { "gen_ai.request.temperature": params.temperature } : void 0,
1047
1058
  ...params.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": params.maxTokens } : void 0
1048
1059
  };
1049
1060
  const startAttributes = {
@@ -1063,7 +1074,6 @@ async function completeText(params) {
1063
1074
  ...params.tools ? { tools: params.tools } : void 0
1064
1075
  }, {
1065
1076
  apiKey,
1066
- temperature: params.temperature,
1067
1077
  maxTokens: params.maxTokens,
1068
1078
  reasoning: params.thinkingLevel,
1069
1079
  cacheRetention: params.cacheRetention,
@@ -1166,7 +1176,6 @@ async function completeObject(params) {
1166
1176
  schema: params.schema,
1167
1177
  prompt: params.prompt,
1168
1178
  ...params.system !== void 0 ? { system: params.system } : void 0,
1169
- ...params.temperature !== void 0 ? { temperature: params.temperature } : void 0,
1170
1179
  ...params.maxTokens !== void 0 ? { maxOutputTokens: params.maxTokens } : void 0,
1171
1180
  ...params.signal !== void 0 ? { abortSignal: params.signal } : void 0
1172
1181
  });
@@ -1185,7 +1194,6 @@ async function completeObject(params) {
1185
1194
  "server.port": 443,
1186
1195
  "gen_ai.provider.auth_mode": credential.mode,
1187
1196
  ...params.thinkingLevel ? { "gen_ai.request.reasoning.level": params.thinkingLevel } : void 0,
1188
- ...params.temperature !== void 0 ? { "gen_ai.request.temperature": params.temperature } : void 0,
1189
1197
  ...params.maxTokens !== void 0 ? { "gen_ai.request.max_tokens": params.maxTokens } : void 0
1190
1198
  });
1191
1199
  } catch (error) {
@@ -1552,6 +1560,7 @@ function readBotConfig(env, functionMaxDurationSeconds) {
1552
1560
  embeddingModelId: validateEmbeddingModelId(env.AI_EMBEDDING_MODEL) ?? DEFAULT_EMBEDDING_MODEL_ID,
1553
1561
  rerankingModelId: toOptionalTrimmed(env.AI_RERANKING_MODEL) ?? DEFAULT_RERANKING_MODEL_ID,
1554
1562
  loadingMessages: parseLoadingMessages(env.JUNIOR_LOADING_MESSAGES),
1563
+ refusalFallbackModelId: validateGatewayModelId(env.AI_REFUSAL_FALLBACK_MODEL),
1555
1564
  visionModelId: env.AI_VISION_MODEL === void 0 ? DEFAULT_VISION_MODEL_ID : validateGatewayModelId(env.AI_VISION_MODEL),
1556
1565
  maxAgentDepth: 0,
1557
1566
  maxSlicesPerTurn: MAX_SLICES_PER_TURN,
@@ -1715,6 +1724,7 @@ function setBotModelConfig(config) {
1715
1724
  if (config.rerankingModelId !== void 0) botConfig.rerankingModelId = requireModelId("rerankingModelId", config.rerankingModelId, toOptionalTrimmed);
1716
1725
  if (config.imageGenerationModelId !== void 0) botConfig.imageGenerationModelId = requireModelId("imageGenerationModelId", config.imageGenerationModelId, validateEmbeddingModelId);
1717
1726
  if (config.visionModelId !== void 0) botConfig.visionModelId = requireModelId("visionModelId", config.visionModelId, validateGatewayModelId);
1727
+ if (config.refusalFallbackModelId !== void 0) botConfig.refusalFallbackModelId = requireModelId("refusalFallbackModelId", config.refusalFallbackModelId, validateGatewayModelId);
1718
1728
  if (config.webSearchModelId !== void 0) botConfig.webSearchModelId = requireModelId("webSearchModelId", config.webSearchModelId, validateGatewayModelId);
1719
1729
  }
1720
1730
  /** Apply Slack reaction emoji overrides from createApp() options, validating names. */
@@ -1722,4 +1732,4 @@ function setSlackReactionConfig(overrides) {
1722
1732
  if (overrides.processingReactionEmoji !== void 0) chatConfig.slack.processingReactionEmoji = parseReactionEmoji("processingReactionEmoji", overrides.processingReactionEmoji, chatConfig.slack.processingReactionEmoji);
1723
1733
  if (overrides.completedReactionEmoji !== void 0) chatConfig.slack.completedReactionEmoji = parseReactionEmoji("completedReactionEmoji", overrides.completedReactionEmoji, chatConfig.slack.completedReactionEmoji);
1724
1734
  }
1725
- export { estimateTextTokens as A, createProviderError as B, completeText as C, requestPrefixAttributes as D, resolveGatewayModel as E, renderCurrentInstruction as F, getGatewayApiKey as G, getProviderErrorAttributes as H, unwrapCurrentInstruction as I, toOptionalTrimmed as J, resolveGatewayCredential as K, escapeXml as L, COMPACTION_SUMMARY_PREFIX as M, hasCompactedConversationContext as N, estimateMessagesTokens as O, isCompactionSummaryText as P, escapeXmlText as R, completeObject as S, rerankTexts as T, getProviderErrorUserMessage as U, findProviderError as V, isProviderRetryError as W, toPiReasoningLevel as _, getRuntimeMetadata as a, GEN_AI_SERVER_ADDRESS as b, getSlackClientSecret as c, restoreRuntimeConfig as d, setBotModelConfig as f, TURN_REASONING_LEVELS as g, snapshotRuntimeConfig as h, getChatConfig as i, textCharsForTokens as j, estimateRequestOverheadTokens as k, getSlackSigningSecret as l, setSlackReactionConfig as m, botConfig as n, getSlackBotToken as o, setRuntimeLimits as p, getAttachmentStorage as q, config_exports as r, getSlackClientId as s, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as t, resetRuntimeConfig as u, normalizeSlackEmojiName as v, embedTexts as w, completeDecision as x, GEN_AI_PROVIDER_NAME as y, ProviderError as z };
1735
+ export { estimateTextTokens as A, createAssistantProviderError as B, completeText as C, requestPrefixAttributes as D, resolveGatewayModel as E, renderCurrentInstruction as F, isProviderRefusal as G, findProviderError as H, unwrapCurrentInstruction as I, resolveGatewayCredential as J, isProviderRetryError as K, escapeXml as L, COMPACTION_SUMMARY_PREFIX as M, hasCompactedConversationContext as N, estimateMessagesTokens as O, isCompactionSummaryText as P, escapeXmlText as R, completeObject as S, rerankTexts as T, getProviderErrorAttributes as U, createProviderError as V, getProviderErrorUserMessage as W, toOptionalTrimmed as X, getAttachmentStorage as Y, toPiReasoningLevel as _, getRuntimeMetadata as a, GEN_AI_SERVER_ADDRESS as b, getSlackClientSecret as c, restoreRuntimeConfig as d, setBotModelConfig as f, TURN_REASONING_LEVELS as g, snapshotRuntimeConfig as h, getChatConfig as i, textCharsForTokens as j, estimateRequestOverheadTokens as k, getSlackSigningSecret as l, setSlackReactionConfig as m, botConfig as n, getSlackBotToken as o, setRuntimeLimits as p, getGatewayApiKey as q, config_exports as r, getSlackClientId as s, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as t, resetRuntimeConfig as u, normalizeSlackEmojiName as v, embedTexts as w, completeDecision as x, GEN_AI_PROVIDER_NAME as y, ProviderError as z };
@@ -1,9 +1,9 @@
1
- import { Bi as startOAuthFlow } from "./projection-DXl4ftyL.js";
2
- import { n as botConfig } from "./config-B4b-NXH5.js";
3
- import { A as deleteProviderIdentityForUser, k as deleteProviderIdentityForSlackUser, s as getSqlExecutor } from "./db-CoA7_Xqu.js";
4
- import { u as hasRequiredOAuthScope } from "./registry-DosVt9f9.js";
5
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DwbTyNRD.js";
6
- import { c as deleteMcpServerSessionId, l as deleteMcpStoredOAuthCredentials, s as deleteMcpAuthSessionsForUserProvider } from "./agent-runner-DHq1pjUg.js";
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";
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. */
@@ -305,6 +305,7 @@ const conversationReportStatusSchema = z.enum([
305
305
  /** Where a Conversation sits in its tree. See `TERMINOLOGY.md`. */
306
306
  const conversationKindSchema = z.enum([
307
307
  "root",
308
+ "automation",
308
309
  "thread",
309
310
  "task"
310
311
  ]);
@@ -1,4 +1,4 @@
1
- import { P as reviewItemChangeRecordSchema, U as messageAttachmentSchema, i as actorIdentitySchema, l as conversationDetailReportSchema } from "./conversation-CtjR1Zcx.js";
1
+ import { P as reviewItemChangeRecordSchema, U as messageAttachmentSchema, i as actorIdentitySchema, l as conversationDetailReportSchema } from "./conversation-CDWejM4R.js";
2
2
  import * as z from "zod";
3
3
  // src/reporting-schema.ts
4
4
  const healthReportSchema = z.object({
@@ -1,4 +1,4 @@
1
- import { h as logWarn } from "./logging-BN5drSEZ.js";
1
+ import { h as logWarn } from "./logging-Cb6MGvdt.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,19 +1,19 @@
1
- import { $i as postSlackMessage, An as createUserTokenStore, Li as formatProviderLabel, Pn as resolvePluginOAuthAccount, Ri as parseOAuthStatePayload, Z as getConversationPendingAuth, d as recordAuthorizationCompleted, ot as getTurnRecord, u as recordAuthenticationLinked, ua as getSlackClient, zi as resolveBaseUrl } from "./projection-DXl4ftyL.js";
2
- import { L as escapeXml, a as getRuntimeMetadata, n as botConfig } from "./config-B4b-NXH5.js";
3
- import { U as isNativeIdentityProvider, _ as runBestEffort, h as logWarn, p as logException } from "./logging-BN5drSEZ.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-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";
4
4
  import { p as parseSlackUserId } from "./actor-6jsm_v96.js";
5
- import { D as resolveActorIdentityId, F as upsertLinkedIdentity, j as findUserByVerifiedEmails, s as getSqlExecutor } from "./db-CoA7_Xqu.js";
5
+ import { B as upsertLinkedIdentity, I as findUserByVerifiedEmails, M as resolveActorIdentityId, s as getSqlExecutor } from "./db--xuNV7g6.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-DosVt9f9.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DwbTyNRD.js";
9
- import { t as discoverSkills } from "./skills-DHApyCjj.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-DHq1pjUg.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";
11
11
  import { r as acquireActiveLock } from "./locks-D-0h111u.js";
12
- import { o as readIdentityById } from "./viewer-9KLQibjn.js";
13
- import { r as getStateAdapter } from "./adapter-CMJfmHso.js";
14
- import { gt as coerceThreadConversationState, pt as getPersistedThreadState } from "./task-runner-BYPN4BEO.js";
15
- import { _ as getMcpProviderErrorAttributes } from "./service-account-BpGpScaT.js";
16
- import { i as readConnectedOAuthTokens, s as htmlCallbackResponse } from "./connections-Dz_AQg5p.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
17
  import { n as relayLocalOAuthCallback } from "./oauth-relay-D6xxVywK.js";
18
18
  import path from "node:path";
19
19
  import { createHmac, createSecretKey, timingSafeEqual } from "node:crypto";
@@ -1,8 +1,8 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-B4b-NXH5.js";
3
- import { H as GOOGLE_IDENTITY_PROVIDER, W as normalizeIdentityEmail, h as logWarn } from "./logging-BN5drSEZ.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";
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-SWyHhit0.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";
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";
@@ -838,12 +838,105 @@ async function ensureConversationRow(executor, conversationId, atMs, options = {
838
838
  }
839
839
  });
840
840
  }
841
+ const CONVERSATION_KINDS = /* @__PURE__ */ new Set([
842
+ "root",
843
+ "automation",
844
+ "thread",
845
+ "task"
846
+ ]);
841
847
  /** Decode a stored kind. A null kind comes from a writer of an older deploy. */
842
848
  function conversationKindFromRow(row) {
843
849
  const kind = row.kind ?? (row.parentConversationId ? "task" : "root");
844
- if (kind !== "root" && kind !== "thread" && kind !== "task") throw new Error("Conversation record kind is invalid");
850
+ if (!CONVERSATION_KINDS.has(kind)) throw new Error("Conversation record kind is invalid");
845
851
  return kind;
846
852
  }
853
+ // src/chat/conversations/kind-behavior.ts
854
+ const ROOT = {
855
+ delivery: "location",
856
+ promptMode: "conversation",
857
+ gated: false,
858
+ tools: {
859
+ agents: "children",
860
+ reviewDesk: true,
861
+ subscriptions: true,
862
+ userCustomization: true,
863
+ reportBlocked: false,
864
+ noReply: true,
865
+ finishAutomationRun: false
866
+ }
867
+ };
868
+ const PERSON_IN_THREAD = {
869
+ ...ROOT,
870
+ tools: {
871
+ ...ROOT.tools,
872
+ agents: "none"
873
+ }
874
+ };
875
+ const AGENT_IN_CHILD = {
876
+ delivery: "conversation",
877
+ promptMode: "child_agent",
878
+ gated: false,
879
+ tools: {
880
+ agents: "children_and_parent",
881
+ reviewDesk: false,
882
+ subscriptions: false,
883
+ userCustomization: false,
884
+ reportBlocked: true,
885
+ noReply: true,
886
+ finishAutomationRun: false
887
+ }
888
+ };
889
+ const AUTOMATION_RUN = {
890
+ delivery: "conversation",
891
+ promptMode: "automation",
892
+ gated: true,
893
+ tools: {
894
+ ...ROOT.tools,
895
+ noReply: false,
896
+ finishAutomationRun: true
897
+ }
898
+ };
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.
905
+ */
906
+ function turnBehavior(args) {
907
+ if (args.automationRun) return AUTOMATION_RUN;
908
+ if (isTopLevelKind(args.kind)) return ROOT;
909
+ if (!args.personInput) return AGENT_IN_CHILD;
910
+ if (args.kind === "thread") return PERSON_IN_THREAD;
911
+ throw new Error("A task Conversation cannot have a person's input");
912
+ }
913
+ /** Return whether a Conversation of this kind has no parent. */
914
+ function isTopLevelKind(kind) {
915
+ return kind === "root" || kind === "automation";
916
+ }
917
+ /** Return whether a person sent input from this Source. */
918
+ function isPersonInput(source) {
919
+ return source === "web" || source === "slack";
920
+ }
921
+ /**
922
+ * Return whether the runtime delivers the final response of a Slack or
923
+ * dispatch run. Only root Conversations reach these paths, so only an
924
+ * Automation run keeps its final response in the Conversation. A dispatch
925
+ * with no outcomes delivers nothing.
926
+ */
927
+ function deliversFinalText(dispatch) {
928
+ return dispatch?.outcomes?.length !== 0 && !dispatch?.declaresResult;
929
+ }
930
+ /**
931
+ * Return whether the runtime may post a failure reply or a status notice,
932
+ * such as an auth prompt, for a run outside `finishedRunReply`. The rule is
933
+ * the same as for a final response. A chat Turn may post, also in a thread
934
+ * that an Automation Conversation owns. An Automation run posts only a
935
+ * declared message; its failed execution shows on the Automation.
936
+ */
937
+ function postsRunNotices(dispatch) {
938
+ return deliversFinalText(dispatch);
939
+ }
847
940
  // src/chat/conversations/sql/store.ts
848
941
  const CONVERSATION_MUTATION_LOCK_PREFIX = "junior_conversation";
849
942
  /** Serialize one conversation's durable mutations inside a SQL transaction. */
@@ -1173,7 +1266,7 @@ var SqlStore = class {
1173
1266
  /** Upsert the conversation row while preserving previously discovered nullable metadata fields. */
1174
1267
  async upsertConversation(args) {
1175
1268
  const { conversation } = args;
1176
- if (conversation.kind === "root" !== !conversation.parentConversationId) throw new Error(`Conversation ${conversation.conversationId} kind does not match its parent`);
1269
+ if (isTopLevelKind(conversation.kind) !== !conversation.parentConversationId) throw new Error(`Conversation ${conversation.conversationId} kind does not match its parent`);
1177
1270
  if (!conversation.parentConversationId && !conversation.destination) {
1178
1271
  if (!await this.get({ conversationId: conversation.conversationId })) throw new Error(`Conversation ${conversation.conversationId} requires a destination at create`);
1179
1272
  }
@@ -1941,4 +2034,4 @@ async function closeDb() {
1941
2034
  current = void 0;
1942
2035
  await previous?.db.close();
1943
2036
  }
1944
- export { sameDestination as $, deleteProviderIdentityForUser as A, addAgentTurnUsage as B, setFirstConversationLocation as C, resolveActorIdentityId as D, findActorIdentityId as E, upsertLinkedIdentity as F, resolveRootConversationId as G, agentTurnTotalTokens as H, bindProviderConversation as I, nextDetailVersion as J, rootConversationIsArchived as K, claimProviderConversation as L, readUserTimezone as M, recordGoogleSignIn as N, saveActorAvatar as O, saveUserTimezone as P, requireSlackDestination as Q, getConversationIdByProviderConversation as R, locationFromRow as S, SYSTEM_IDENTITY_ID as T, agentTurnUsageSchema as U, agentTurnCostUsd as V, hasAgentTurnUsage as W, createSlackDestination as X, touchConversationDetail as Y, parseDestination as Z, setArchivedAt as _, getConversationStore as a, withConversationMutationLock as b, conversationIdsWithAnnotation as c, createSqlConversationEventStore as d, eventFromRow as f, readConversationTrees as g, conversationDescendants as h, getConversationMessageSearchStore as i, findUserByVerifiedEmails as j, deleteProviderIdentityForSlackUser as k, hasAnnotationKey as l, conversationAncestors as m, db_exports as n, getDb as o, withConversationEventLock as p, conversationDetailTouch as q, getConversationEventStore as r, getSqlExecutor as s, closeDb as t, treeHasAnnotationKey as u, loadConversationSlackTenantIds as v, startLocationThread as w, conversationKindFromRow as x, createSqlStore as y, parseSessionSource as z };
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 };
@@ -1,4 +1,4 @@
1
- import "./schema-CHsBmXIj.js";
1
+ import "./schema-DgvcyJ1y.js";
2
2
  import * as z from "zod";
3
3
  import "drizzle-orm";
4
4
  import { Destination, Source, locationSchema } from "@sentry/junior-plugin-api";
@@ -53,11 +53,13 @@ type Usage = z.output<typeof usageSchema>;
53
53
  type AgentTurnUsage = Usage;
54
54
  type ConversationSource = "api" | "internal" | "local" | "plugin" | "event" | "scheduler" | "slack" | "web";
55
55
  /**
56
- * Where a Conversation sits in its tree. A root has no parent. A Thread is a
57
- * child that people can message. A Task is a child that only its parent
58
- * messages. A Conversation never changes kind.
56
+ * Where a Conversation sits in its tree. A root and an Automation run have no
57
+ * parent. A Thread is a child that people can message. A Task is a child that
58
+ * only its parent messages. A Conversation never changes kind.
59
59
  */
60
- type ConversationKind = "root" | "thread" | "task";
60
+ type ConversationKind = "root" | "automation" | "thread" | "task";
61
+ /** The kind of a Conversation that has a parent. */
62
+ type ChildConversationKind = "thread" | "task";
61
63
  type ConversationStatus = "paused" | "failed" | "idle" | "pending" | "running";
62
64
  /** Cumulative duration and usage that one Run reported. */
63
65
  interface ConversationRunMetrics {
@@ -137,7 +139,7 @@ interface ConversationStore {
137
139
  */
138
140
  createChild(args: {
139
141
  childConversationId: string;
140
- kind: Exclude<ConversationKind, "root">;
142
+ kind: ChildConversationKind;
141
143
  parentConversationId: string;
142
144
  nowMs?: number;
143
145
  source?: ConversationSource;
@@ -1,6 +1,6 @@
1
1
  import { _ as withScope } from "./sentry-BRTJqumy.js";
2
- import "./config-B4b-NXH5.js";
3
- import { h as logWarn, p as logException } from "./logging-BN5drSEZ.js";
2
+ import "./config-mIZeGEWv.js";
3
+ import { h as logWarn, p as logException } from "./logging-Cb6MGvdt.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";
@@ -140,8 +140,8 @@ const juniorConversations = pgTable("junior_conversations", {
140
140
  metricRunId: text("metric_run_id"),
141
141
  detailVersion: integer("detail_version").notNull().default(0)
142
142
  }, (table) => [
143
- check("junior_conversations_kind_check", sql`${table.kind} in ('root', 'thread', 'task')`),
144
- check("junior_conversations_kind_parent_check", sql`${table.kind} is null or ((${table.kind} = 'root') = (${table.parentConversationId} is null))`),
143
+ check("junior_conversations_kind_check", sql`${table.kind} in ('root', 'automation', 'thread', 'task')`),
144
+ check("junior_conversations_kind_parent_check", sql`${table.kind} is null or ((${table.kind} in ('root', 'automation')) = (${table.parentConversationId} is null))`),
145
145
  index("junior_conversations_last_activity_idx").on(table.lastActivityAt.desc(), table.conversationId),
146
146
  index("junior_conversations_active_idx").using("btree", sql`coalesce(${table.executionUpdatedAt}, ${table.updatedAt})`, table.conversationId).where(sql`${table.executionStatus} <> 'idle'`),
147
147
  index("junior_conversations_destination_activity_idx").on(table.destinationId, table.lastActivityAt.desc()),
@@ -795,6 +795,29 @@ const LOCK_TIMEOUT_MS = 5e3;
795
795
  const LOCK_ATTEMPTS = 5;
796
796
  const LOCK_RETRY_DELAY_MS = 5e3;
797
797
  const LOCK_NOT_AVAILABLE = "55P03";
798
+ const MIGRATION_LOCK_POLL_MS = 1e3;
799
+ const CONCURRENT_STATEMENT = /^(?:CREATE (?:UNIQUE )?INDEX|DROP INDEX|REINDEX)\b[^;]*\bCONCURRENTLY\b/i;
800
+ const CONCURRENT_INDEX = /^CREATE (?:UNIQUE )?INDEX CONCURRENTLY IF NOT EXISTS "([a-z0-9_]+)" /i;
801
+ /** Statement text without its leading comment lines. */
802
+ function sqlOf(statement) {
803
+ return statement.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").trim();
804
+ }
805
+ /**
806
+ * Index builds of a migration that only builds indexes concurrently, or
807
+ * undefined for a migration that runs in a transaction.
808
+ */
809
+ function concurrentIndexes(tag, statements) {
810
+ const sql = statements.map(sqlOf).filter(Boolean);
811
+ if (!sql.some((statement) => CONCURRENT_STATEMENT.test(statement))) return;
812
+ return sql.map((statement) => {
813
+ const name = CONCURRENT_INDEX.exec(statement)?.[1];
814
+ if (!name) throw new Error(`Migration ${tag}: a migration that uses CONCURRENTLY must contain only CREATE [UNIQUE] INDEX CONCURRENTLY IF NOT EXISTS "name" statements.`);
815
+ return {
816
+ name,
817
+ statement
818
+ };
819
+ });
820
+ }
798
821
  function isLockTimeout(error) {
799
822
  let current = error;
800
823
  for (let depth = 0; current instanceof Error && depth < 5; depth += 1) {
@@ -803,6 +826,15 @@ function isLockTimeout(error) {
803
826
  }
804
827
  return false;
805
828
  }
829
+ /**
830
+ * Wait for the migration lock by polling `pg_try_advisory_lock`. A session
831
+ * blocked in `pg_advisory_lock` holds a snapshot, and `CREATE INDEX
832
+ * CONCURRENTLY` waits for every older snapshot, so a second migrator that
833
+ * blocked there would deadlock with the build of the first.
834
+ */
835
+ async function waitForMigrationLock(tryLock) {
836
+ while (!await tryLock()) await new Promise((resolve) => setTimeout(resolve, MIGRATION_LOCK_POLL_MS));
837
+ }
806
838
  async function retryOnLockTimeout(tag, apply) {
807
839
  for (let attempt = 1;; attempt += 1) try {
808
840
  await apply();
@@ -823,7 +855,8 @@ async function retryOnLockTimeout(tag, apply) {
823
855
  * (drizzle-orm#3249), so locks from earlier migrations stay held while later
824
856
  * migrations wait for theirs. That can deadlock with live traffic. This keeps
825
857
  * Drizzle's journal table and skip rule, so existing databases are unaffected.
826
- * A migration that waits too long for a lock rolls back and runs again.
858
+ * A migration that waits too long for a lock rolls back and runs again. A
859
+ * migration that only builds indexes concurrently runs outside a transaction.
827
860
  */
828
861
  async function applyMigrations(executor, config) {
829
862
  const schema = config.migrationsSchema ?? "drizzle";
@@ -834,11 +867,23 @@ async function applyMigrations(executor, config) {
834
867
  const appliedAt = Number(last?.createdAt ?? 0);
835
868
  for (const migration of readMigrationFiles(config)) {
836
869
  if (migration.folderMillis <= appliedAt) continue;
837
- await retryOnLockTimeout(String(migration.folderMillis), async () => {
870
+ const tag = String(migration.folderMillis);
871
+ const recordApplied = () => executor.execute(`INSERT INTO ${table} (hash, created_at) VALUES ($1, $2)`, [migration.hash, migration.folderMillis]);
872
+ const indexes = concurrentIndexes(tag, migration.sql);
873
+ if (indexes) {
874
+ for (const { name, statement } of indexes) {
875
+ const [state] = await executor.query(`SELECT indisvalid AND indisready AS usable FROM pg_index WHERE indexrelid = to_regclass($1)`, [name]);
876
+ if (state && !state.usable) await executor.execute(`DROP INDEX CONCURRENTLY IF EXISTS "${name}"`);
877
+ await executor.execute(statement);
878
+ }
879
+ await recordApplied();
880
+ continue;
881
+ }
882
+ await retryOnLockTimeout(tag, async () => {
838
883
  await executor.transaction(async () => {
839
884
  await executor.execute(`SET LOCAL lock_timeout = ${LOCK_TIMEOUT_MS}`);
840
885
  for (const statement of migration.sql) await executor.execute(statement);
841
- await executor.execute(`INSERT INTO ${table} (hash, created_at) VALUES ($1, $2)`, [migration.hash, migration.folderMillis]);
886
+ await recordApplied();
842
887
  });
843
888
  });
844
889
  }
@@ -1036,7 +1081,9 @@ var NeonExecutor = class {
1036
1081
  const client = await this.pool.connect();
1037
1082
  const lockName = `junior:migrate:${migrationTable}`;
1038
1083
  try {
1039
- await client.query("SELECT pg_advisory_lock(hashtext($1))", [lockName]);
1084
+ await waitForMigrationLock(async () => {
1085
+ return (await client.query("SELECT pg_try_advisory_lock(hashtext($1)) AS locked", [lockName])).rows[0]?.locked === true;
1086
+ });
1040
1087
  return await this.pool.onWebSocket(callback);
1041
1088
  } finally {
1042
1089
  client.release(true);
@@ -1155,7 +1202,9 @@ var PostgresExecutor = class {
1155
1202
  const client = await this.pool.connect();
1156
1203
  const lockName = `junior:migrate:${migrationTable}`;
1157
1204
  try {
1158
- await client.query("SELECT pg_advisory_lock(hashtext($1))", [lockName]);
1205
+ await waitForMigrationLock(async () => {
1206
+ return (await client.query("SELECT pg_try_advisory_lock(hashtext($1)) AS locked", [lockName])).rows[0]?.locked === true;
1207
+ });
1159
1208
  return await callback();
1160
1209
  } finally {
1161
1210
  client.release(true);
@@ -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-BN5drSEZ.js";
3
- import { n as getCurrentConversationPrivacy } from "./conversation-privacy-DRsSgLGO.js";
2
+ import { B as getDeploymentTelemetryAttributes, z as getDeploymentServiceVersion } from "./logging-Cb6MGvdt.js";
3
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-C6h-X2cZ.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-C6nqU3Qc.js";
2
+ import { t as JUNIOR_VERSION } from "./version-Bdqhx8Qh.js";
3
3
  import path from "node:path";
4
4
  import { styleText } from "node:util";
5
5
  import { ConfigError, configureSync, getConfig, getLogger } from "@logtape/logtape";
@@ -1,13 +1,13 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { Dn as renderUntrustedTag, io as readConversationAccessFromSql, to as canAccessConversation } from "./projection-DXl4ftyL.js";
3
- import { n as botConfig } from "./config-B4b-NXH5.js";
4
- import { T as SYSTEM_IDENTITY_ID, a as getConversationStore, o as getDb } from "./db-CoA7_Xqu.js";
5
- import { hn as toolInvocationDestination, in as AgentMessageTargetError, mn as actorFromRun, nn as AgentMessagePausedError } from "./agent-runner-DHq1pjUg.js";
6
- import { I as PARENT_AGENT_TARGET, v as getActiveAgentInvocationForConversation } from "./turn-failure-response-jNVl00MD.js";
7
- import { G as admitAutomatedTurn, S as EVENT_WAIT_MS, V as postAutomatedTurnLimitNoticeForConversation } from "./session-stop-xYK15HUu.js";
8
- import { r as appendAndEnqueueInboundMessage } from "./store-xtibD98L.js";
9
- import { a as enqueueAgentInvocation, c as createAgentInvocationForMessage, u as findChildAgentConversationId } from "./work-xwX6unUE.js";
10
- import { r as enqueueAgentMessageToParent } from "./result-CaAFpf4B.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";
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. */