@sentry/junior 0.315.0 → 0.317.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 (139) hide show
  1. package/dist/{admin-5jUYY46p.js → admin-CAugg87B.js} +1 -1
  2. package/dist/{agent-runner-C7GNLRB6.js → agent-runner-AjrEV6Qe.js} +13532 -12811
  3. package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
  4. package/dist/{agent-update-delivery-BNEYQsAf.js → agent-update-delivery-B_YIZcgf.js} +10 -37
  5. package/dist/api/schema.d.ts +609 -104
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.js +373 -469
  8. package/dist/{app-D_bAXRDe.d.ts → app-MoNAsVV5.d.ts} +52 -28
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +177 -132
  11. package/dist/catalog-runtime-DfSpJZdY.js +6 -0
  12. package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
  13. package/dist/{adapter-context-BlSGE44V.js → channel-access-j-YAVYK4.js} +2 -42
  14. package/dist/{chat-core-engine-CxkwRpn9.js → chat-core-engine-aH85nEHv.js} +4 -3
  15. package/dist/{child-message--2G3Ft26.js → child-message-DHjQLEd1.js} +1 -1
  16. package/dist/cli/chat.js +23 -23
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.js +5 -4
  20. package/dist/cli/snapshot-create.js +5 -2
  21. package/dist/cli/upgrade.js +27 -5
  22. package/dist/config-CHQ8X251.js +2422 -0
  23. package/dist/{continue-in-slack-BGKjIdFp.js → continue-in-slack-D-FZ8Fin.js} +2 -3
  24. package/dist/{conversation-feed-Sl8lKKmR.js → conversation-feed--9S0_PXL.js} +9 -4
  25. package/dist/{proxy-path-Dc-0jXGi.js → conversation-privacy-B1uXn5sf.js} +2 -16
  26. package/dist/{conversation-turn-BoLK9i6g.js → conversation-turn-BUE_7xaN.js} +102 -172
  27. package/dist/{create-BOycVH9h.js → create-DoDIYgtZ.js} +12 -10
  28. package/dist/{credential-sync-Mn4OdkEh.js → credential-sync-BJOqGnjV.js} +17 -12
  29. package/dist/{db-DXTOYRzR.js → db-BFmyYZtJ.js} +20276 -27398
  30. package/dist/{deployment-CG3TchWh.js → deployment-DXq9ZLU4.js} +17 -15
  31. package/dist/{engine-context-dyWlfNdD.js → engine-context-CgQ7mlHt.js} +264 -50
  32. package/dist/{html-CfXEwl_h.js → html-B3VKTGbJ.js} +6 -2
  33. package/dist/instrumentation.js +15 -7
  34. package/dist/{job-runner-CySgpi9v.js → job-runner-A1lCkybD.js} +397 -22
  35. package/dist/{lineage-tRTOcrsL.js → lineage-Bktb0UcV.js} +1 -1
  36. package/dist/{list-DXBz8SYL.js → list-Bxvg5wXf.js} +260 -698
  37. package/dist/{logging-czs0nqLC.js → logging--smS7XRK.js} +2 -2
  38. package/dist/{mailbox-turn-79Nv1JXv.js → mailbox-turn-uSXhUFc9.js} +648 -2957
  39. package/dist/{message-BTox2Cmb.js → message-BNenhsmB.js} +12 -22
  40. package/dist/{model-input-IRGa98V7.js → model-input-BReSnwHp.js} +3 -3
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +20 -6
  43. package/dist/{oauth-callback-server-NXK7AlBp.js → oauth-callback-server-CE4soEIY.js} +2 -2
  44. package/dist/{oauth-relay-6NBPSpFE.js → oauth-relay-C36gX1gH.js} +2 -2
  45. package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
  46. package/dist/{parent-result-Dg6P6roR.js → parent-result-Ck1rFYRQ.js} +93 -106
  47. package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
  48. package/dist/profile-BQ-iBDsZ.js +4657 -0
  49. package/dist/{transcript-BHhJVY0P.js → prompt-Dv7gkpD6.js} +97 -103
  50. package/dist/proxy-path-BHYoKZdq.js +15 -0
  51. package/dist/registry-iXMT5Jmh.js +3279 -0
  52. package/dist/reports-WKHfGTsU.js +195 -0
  53. package/dist/{resolve-BUFkmxkT.js → resolve-tony4ibz.js} +9 -29
  54. package/dist/{result-DfATzX77.js → result-Bta_dlWa.js} +42 -117
  55. package/dist/run-conversation-DL6ru7iW.js +336 -0
  56. package/dist/{runner-CmKP3inb.js → runner-BstDRbD9.js} +7 -7
  57. package/dist/{sandbox-egress-signals-DYo5BsM7.js → sandbox-egress-signals-oSJMJOnn.js} +1 -1
  58. package/dist/{schema-DrBMdPmv.js → schema-DfqrHACA.js} +67 -84
  59. package/dist/sender-actors-CPglLd5R.js +83 -0
  60. package/dist/{service-account-CxTX7nnR.js → service-account-CTV_jaNu.js} +3 -1
  61. package/dist/{skills-BlHUDj7k.js → skills-BCEU41zM.js} +4 -4
  62. package/dist/{slack-conversation-unfurl-Dhe3lB1U.js → slack-conversation-unfurl-DxVmhbGP.js} +7 -6
  63. package/dist/{spawn-CfvlFdfz.js → spawn-frczVPIr.js} +11 -8
  64. package/dist/{system-prompt-table-CDCYVwqN.js → system-prompt-table-CiXy0eNR.js} +91 -70
  65. package/dist/{task-runner-DcdQJd9e.js → task-runner-C9Yc2_ae.js} +35 -49
  66. package/dist/{thread-context-DF5uDcWN.js → thread-context-CqZDKErp.js} +6 -6
  67. package/dist/topics-SRN7IVX-.js +24 -0
  68. package/dist/turn-membership-CENFf3kI.js +856 -0
  69. package/dist/{turn-wake-um5Ubd4m.js → turn-wake-BhloiI2h.js} +4 -5
  70. package/dist/{media-Cr9pGkzr.js → types-C4iC-IMC.js} +819 -777
  71. package/dist/user-customization-CvfuY9Eo.js +93 -0
  72. package/dist/users-ByG5RCEJ.js +181 -0
  73. package/dist/{validation-CJyuOPD2.js → validation-8gjfR91V.js} +1 -1
  74. package/dist/{version-Bhe7RPIe.js → version-BeZhWWBE.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{worker-D8PRgUqr.js → worker-BqMQQNRk.js} +5 -4
  77. package/migrations/20261125171254_conversation_visibility/migration.sql +4 -0
  78. package/migrations/20261125171254_conversation_visibility/snapshot.json +67 -0
  79. package/migrations/20261125171257_conversation_visibility_backfill/migration.sql +25 -0
  80. package/migrations/20261125171257_conversation_visibility_backfill/snapshot.json +9 -0
  81. package/migrations/20261125213232_drop_versions_notify/migration.sql +19 -0
  82. package/migrations/20261125213232_drop_versions_notify/snapshot.json +9 -0
  83. package/migrations/20261125225138_conversation_kind_root_thread/migration.sql +23 -0
  84. package/migrations/20261125225138_conversation_kind_root_thread/snapshot.json +55 -0
  85. package/migrations/20261125225142_conversation_kind_root_thread_backfill/migration.sql +7 -0
  86. package/migrations/20261125225142_conversation_kind_root_thread_backfill/snapshot.json +9 -0
  87. package/migrations/20261126000151_conversation_event_message_role_seq_index/migration.sql +1 -0
  88. package/migrations/20261126000151_conversation_event_message_role_seq_index/snapshot.json +69 -0
  89. package/migrations/20261126012917_merge_leaves/migration.sql +2 -0
  90. package/migrations/20261126012917_merge_leaves/snapshot.json +12 -0
  91. package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
  92. package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
  93. package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
  94. package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
  95. package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
  96. package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
  97. package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
  98. package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
  99. package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
  100. package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
  101. package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
  102. package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
  103. package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
  104. package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
  105. package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
  106. package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
  107. package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
  108. package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
  109. package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
  110. package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
  111. package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
  112. package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
  113. package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
  114. package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
  115. package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
  116. package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
  117. package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
  118. package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
  119. package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
  120. package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
  121. package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
  122. package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
  123. package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
  124. package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
  125. package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
  126. package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
  127. package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
  128. package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
  129. package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
  130. package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
  131. package/package.json +5 -5
  132. package/skills/jr-rpc/SKILL.md +3 -5
  133. package/dist/direct-url-BYgYfuIy.js +0 -22
  134. package/dist/markers-CE0HMXWT.js +0 -67
  135. package/dist/people-Cegp1Iwq.js +0 -81
  136. package/dist/start-conversation-Uh8Sk1EF.js +0 -162
  137. package/dist/turn-session-routing-GtetHsdO.js +0 -1309
  138. package/dist/user-customization-B27StpVQ.js +0 -9
  139. package/dist/web-message-id-C6P83ans.js +0 -10
@@ -1,4 +1,4 @@
1
- import { t as JUNIOR_VERSION } from "./version-Bhe7RPIe.js";
1
+ import { t as JUNIOR_VERSION } from "./version-BeZhWWBE.js";
2
2
  import { randomUUID } from "node:crypto";
3
3
  // src/deployment.ts
4
4
  const JUNIOR_HEARTBEAT_ROUTE = "/api/internal/heartbeat";
@@ -24,23 +24,25 @@ function toOptionalTrimmed(value) {
24
24
  const trimmed = value?.trim();
25
25
  return trimmed ? trimmed : void 0;
26
26
  }
27
- /** Resolve the deployment version used for release and telemetry correlation. */
28
- function getDeploymentServiceVersion() {
29
- const configuredRelease = toOptionalTrimmed(process.env["SENTRY_RELEASE"]);
27
+ /**
28
+ * Resolve the deployment version used for release and telemetry correlation.
29
+ * Telemetry and build code call it before config loads, so it takes env.
30
+ */
31
+ function getDeploymentServiceVersion(env) {
32
+ const configuredRelease = toOptionalTrimmed(env["SENTRY_RELEASE"]);
30
33
  if (configuredRelease) return configuredRelease;
31
- const deploymentRevision = toOptionalTrimmed(process.env["VERCEL_GIT_COMMIT_SHA"]);
34
+ const deploymentRevision = toOptionalTrimmed(env["VERCEL_GIT_COMMIT_SHA"]);
32
35
  return deploymentRevision ? `${JUNIOR_VERSION}+${deploymentRevision}` : void 0;
33
36
  }
34
- /** Vercel deployment that runs this process. Unset outside Vercel. */
35
- function getDeploymentId() {
36
- return toOptionalTrimmed(process.env["VERCEL_DEPLOYMENT_ID"]);
37
- }
38
- /** Resolve deployment-scoped telemetry attributes from host environment. */
39
- function getDeploymentTelemetryAttributes() {
37
+ /**
38
+ * Resolve deployment-scoped telemetry attributes. Telemetry starts before
39
+ * config loads, so it takes env.
40
+ */
41
+ function getDeploymentTelemetryAttributes(env) {
40
42
  const attributes = {};
41
- const serviceVersion = getDeploymentServiceVersion();
42
- const deploymentId = getDeploymentId();
43
- const region = toOptionalTrimmed(process.env["VERCEL_REGION"]);
43
+ const serviceVersion = getDeploymentServiceVersion(env);
44
+ const deploymentId = toOptionalTrimmed(env["VERCEL_DEPLOYMENT_ID"]);
45
+ const region = toOptionalTrimmed(env["VERCEL_REGION"]);
44
46
  attributes["app.junior.version"] = JUNIOR_VERSION;
45
47
  attributes["service.instance.id"] = SERVICE_INSTANCE_ID;
46
48
  if (region) attributes["cloud.region"] = region;
@@ -48,4 +50,4 @@ function getDeploymentTelemetryAttributes() {
48
50
  if (deploymentId) attributes["deployment.id"] = deploymentId;
49
51
  return attributes;
50
52
  }
51
- export { getDeploymentServiceVersion as _, JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE as a, JUNIOR_HEARTBEAT_ROUTE as c, JUNIOR_RETENTION_ROUTE as d, JUNIOR_TURN_STEP_CALLBACK_ROUTE as f, getDeploymentId as g, SERVICE_INSTANCE_ID as h, JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE as i, JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE as l, LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION as m, JUNIOR_AUTO_ARCHIVE_ROUTE as n, JUNIOR_DELIVERY_CALLBACK_ROUTE as o, JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE as p, JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE as r, JUNIOR_HEARTBEAT_CRON_SCHEDULE as s, JUNIOR_AUTO_ARCHIVE_CRON_SCHEDULE as t, JUNIOR_RETENTION_CRON_SCHEDULE as u, getDeploymentTelemetryAttributes as v };
53
+ export { getDeploymentTelemetryAttributes as _, JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE as a, JUNIOR_HEARTBEAT_ROUTE as c, JUNIOR_RETENTION_ROUTE as d, JUNIOR_TURN_STEP_CALLBACK_ROUTE as f, getDeploymentServiceVersion as g, SERVICE_INSTANCE_ID as h, JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE as i, JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE as l, LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION as m, JUNIOR_AUTO_ARCHIVE_ROUTE as n, JUNIOR_DELIVERY_CALLBACK_ROUTE as o, JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE as p, JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE as r, JUNIOR_HEARTBEAT_CRON_SCHEDULE as s, JUNIOR_AUTO_ARCHIVE_CRON_SCHEDULE as t, JUNIOR_RETENTION_CRON_SCHEDULE as u };
@@ -1,12 +1,13 @@
1
- import { Bl as juniorTurns, E as locationSchema, Mi as resolveRootVisibility, Nn as getWorkspace, Rl as juniorTurnOutbox, Sp as getGatewayApiKey, Yf as resolveGatewayModel, a as getDb, aa as QUEUE_SIGNATURE_MAX_AGE_MS, ap as requestPrefixAttributes, bu as juniorConversations, ca as getQueueProvider, d as eventFromRow, m as withConversationEventLock, nf as credentialContextForActor, o as getSqlExecutor, oa as signQueueMessage, sa as verifyQueueMessage, u as createSqlConversationEventStore, up as gatewayRoutingAttributes, uu as juniorConversationEvents, zl as juniorTurnInbox } from "./db-DXTOYRzR.js";
2
- import { G as mapBounded } from "./transcript-BHhJVY0P.js";
3
- import { g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-czs0nqLC.js";
4
- import { h as SERVICE_INSTANCE_ID } from "./deployment-CG3TchWh.js";
5
- import { a as resolveConversationPrivacy, c as toCanonicalOutputMessage, l as toGenAiMessagesTraceAttributes, s as toCanonicalInputMessage } from "./proxy-path-Dc-0jXGi.js";
6
- import { bt as instructionProvenanceFor, vt as contextProvenance } from "./media-Cr9pGkzr.js";
7
- import { Rn as buildDeploymentSystemPrompt, _t as persistThreadRuntimeState, ea as historyItemFromPiMessage, gt as getPersistedThreadState, ht as getPersistedSandboxState, na as projectConversationEvents, ta as piMessageFromHistoryItem } from "./mailbox-turn-79Nv1JXv.js";
8
- import { d as createReadFileTool, g as createBashTool, l as createWriteFileTool, p as createEditFileTool, s as createSystemTimeTool } from "./job-runner-CySgpi9v.js";
9
- import { F as createAgentSandbox, I as normalizeToolResult, c as buildSandboxInput } from "./agent-runner-C7GNLRB6.js";
1
+ import { $d as juniorTurns, Bo as credentialContextForActor, Br as getQueueProvider, Lr as QUEUE_SIGNATURE_MAX_AGE_MS, M as locationSchema, Qd as juniorConversationEvents, Rr as signQueueMessage, Td as juniorTurnInbox, Xu as agentTurnCostUsd, _ as unseenEvents, a as getDb, g as readEventCursor, h as insertEventRows, lf as juniorConversations, ls as resolveRootVisibility, o as getSqlExecutor, v as withConversationEventLock, wd as juniorTurnOutbox, zr as verifyQueueMessage } from "./db-BFmyYZtJ.js";
2
+ import { C as resolveGatewayModel, F as requestPrefixAttributes, H as gatewayRoutingAttributes, et as getGatewayApiKey, t as botConfig } from "./config-CHQ8X251.js";
3
+ import { a as extractGenAiUsageSummary, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging--smS7XRK.js";
4
+ import { h as SERVICE_INSTANCE_ID } from "./deployment-DXq9ZLU4.js";
5
+ import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-B1uXn5sf.js";
6
+ import { L as mapBounded } from "./prompt-Dv7gkpD6.js";
7
+ import { St as contextProvenance, dt as agentHistoryFromRow, ft as encodeAgentHistoryPayload, gt as historyItemFromPiMessage, ht as HISTORY_REPLACEMENT_TYPES, mt as AGENT_HISTORY_ITEM_TYPES, vt as isHistoryReplacement, wt as instructionProvenanceFor, yt as piMessageFromHistoryItem } from "./types-C4iC-IMC.js";
8
+ import { Ar as TURN_LIMIT_WRAP_UP_MESSAGE, Nr as TurnToolCallLimitExceededError, Vt as getWorkspace, ht as persistThreadRuntimeState, jr as TurnBudgetExceededError, mt as getPersistedThreadState, pt as getPersistedSandboxState, qr as reviewToolActions, rn as buildDeploymentSystemPrompt } from "./mailbox-turn-uSXhUFc9.js";
9
+ import { f as createWriteFileTool, g as createEditFileTool, m as createReadFileTool, u as createSystemTimeTool, y as createBashTool } from "./job-runner-A1lCkybD.js";
10
+ import { _ as normalizeToolResult, c as buildSandboxInput, g as createAgentSandbox, v as capToolResult } from "./agent-runner-AjrEV6Qe.js";
10
11
  import { n as TURN_STEP_TOPIC, t as DELIVERY_TOPIC } from "./topic-CRYYBYp-.js";
11
12
  import * as z from "zod";
12
13
  import { streamSimple } from "@earendil-works/pi-ai/compat";
@@ -14,7 +15,7 @@ import * as Sentry from "@sentry/node";
14
15
  import { randomUUID } from "node:crypto";
15
16
  import { toToolDeclaration, validateToolArguments } from "@earendil-works/pi-ai";
16
17
  import { actorSchema, destinationSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
17
- import { and, asc, eq, exists, inArray, like, lt, lte, ne, notExists, or, sql } from "drizzle-orm";
18
+ import { and, asc, eq, exists, inArray, like, lt, lte, max, ne, notExists, or, sql } from "drizzle-orm";
18
19
  import { alias } from "drizzle-orm/pg-core";
19
20
  import { performance as performance$1 } from "node:perf_hooks";
20
21
  // src/core/model/failure.ts
@@ -353,6 +354,28 @@ function modelClient(dependencies) {
353
354
  } : { message };
354
355
  }, { spanName: `chat ${model.id}` }) };
355
356
  }
357
+ // src/core/history/read.ts
358
+ const READ_TYPES = [...AGENT_HISTORY_ITEM_TYPES, ...HISTORY_REPLACEMENT_TYPES];
359
+ /** Loads the current History version's agent history, as the model reads it. */
360
+ async function loadAgentHistory({ executor }, conversationId) {
361
+ const db = executor.db();
362
+ const currentHistoryVersionQuery = db.select({ historyVersion: max(juniorConversationEvents.historyVersion) }).from(juniorConversationEvents).where(eq(juniorConversationEvents.conversationId, conversationId));
363
+ return (await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.historyVersion, currentHistoryVersionQuery), inArray(juniorConversationEvents.type, READ_TYPES))).orderBy(asc(juniorConversationEvents.seq))).flatMap((row) => {
364
+ const data = agentHistoryFromRow(row);
365
+ return isHistoryReplacement(data) ? data.replacementHistory.map(({ item }) => piMessageFromHistoryItem(item)) : [piMessageFromHistoryItem(data)];
366
+ });
367
+ }
368
+ /**
369
+ * Loads the agent history items that one Turn wrote, oldest first, as the
370
+ * model reads them. It reads every History version, so a Turn's items stay
371
+ * its own after a History replacement.
372
+ */
373
+ async function loadTurnAgentHistory({ executor }, turnId) {
374
+ return (await executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.turnId, turnId), inArray(juniorConversationEvents.type, AGENT_HISTORY_ITEM_TYPES))).orderBy(asc(juniorConversationEvents.seq))).flatMap((row) => {
375
+ const data = agentHistoryFromRow(row);
376
+ return isHistoryReplacement(data) ? [] : [piMessageFromHistoryItem(data)];
377
+ });
378
+ }
356
379
  // src/core/prompt/layout.ts
357
380
  const inputFormats = /* @__PURE__ */ new WeakMap();
358
381
  /**
@@ -623,6 +646,22 @@ async function loadWithTimeout(source, values, signal) {
623
646
  signal.removeEventListener("abort", stopStep);
624
647
  }
625
648
  }
649
+ // src/core/turn/failure.ts
650
+ /**
651
+ * Thrown by host code that runs in a step, such as a tool hook, the tools
652
+ * builder or the prompt layout, to end the Turn as failed now. Core stores
653
+ * `failure` and does not run the step again. Any other error makes the queue
654
+ * retry the step. An optional loader's errors never fail the step, so one
655
+ * from an optional loader does nothing.
656
+ */
657
+ var TurnFailedError = class extends Error {
658
+ failure;
659
+ constructor(message, failure) {
660
+ super(message);
661
+ this.name = "TurnFailedError";
662
+ this.failure = failure;
663
+ }
664
+ };
626
665
  // src/core/turn/inbox.ts
627
666
  /**
628
667
  * Finds the Turn of the input that has this idempotency key in the
@@ -807,6 +846,23 @@ function createDeliveryConsumer(ctx, run) {
807
846
  turnId: message.turnId
808
847
  }, metadata));
809
848
  }
849
+ // src/core/history/write.ts
850
+ /**
851
+ * Appends the agent history items that one Turn writes, in order, at the
852
+ * current History version. Skips an item whose idempotency key is already
853
+ * stored. Call it under `withConversationEventLock`.
854
+ */
855
+ async function appendAgentHistory(executor, conversationId, turnId, items) {
856
+ const pending = await unseenEvents(executor, conversationId, items);
857
+ if (pending.length === 0) return;
858
+ await insertEventRows(executor, conversationId, await readEventCursor(executor, conversationId), pending.map(({ item, idempotencyKey, createdAtMs }) => ({
859
+ type: item.type,
860
+ ...encodeAgentHistoryPayload(item),
861
+ idempotencyKey,
862
+ turnId,
863
+ createdAtMs
864
+ })));
865
+ }
810
866
  // src/core/turn/replies.ts
811
867
  const LEGACY_NO_REPLY_MARKERS = ["[[NO_REPLY]]", "[[QUIET]]"];
812
868
  const THINKING_BLOCK_PATTERN = /[ \t]*<thinking\b[^>]*>[\s\S]*?<\/thinking>[ \t]*(?:\r?\n)?/gi;
@@ -846,7 +902,8 @@ function turnEventKeyPrefix(turnId) {
846
902
  }
847
903
  /** The text that a message event delivers, or undefined when it is no reply. */
848
904
  function replyText(row) {
849
- const { data } = eventFromRow(row);
905
+ if (row.type !== "assistant_message") return;
906
+ const data = agentHistoryFromRow(row);
850
907
  if (data.type !== "assistant_message") return;
851
908
  const message = piMessageFromHistoryItem(data);
852
909
  return message.role === "assistant" ? assistantReplyText(message) : void 0;
@@ -1017,6 +1074,7 @@ async function claimTurn({ executor, owner, leaseMs }, turnId) {
1017
1074
  leaseExpiresAt: leaseExpiry(leaseMs),
1018
1075
  leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
1019
1076
  attempts: sql`${juniorTurns.attempts} + 1`,
1077
+ startedAt: sql`coalesce(${juniorTurns.startedAt}, now())`,
1020
1078
  updatedAt: sql`now()`
1021
1079
  }).where(and(eq(juniorTurns.id, turnId), or(and(eq(juniorTurns.state, "queued"), notExists(turnAhead({ executor }))), and(eq(juniorTurns.state, "running"), lte(juniorTurns.leaseExpiresAt, sql`now()`))))).returning({
1022
1080
  turnId: juniorTurns.id,
@@ -1109,16 +1167,16 @@ async function commitStep({ executor }, turn, step, prompt) {
1109
1167
  ...nextStep,
1110
1168
  state: "queued"
1111
1169
  }).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length === 0) return;
1112
- await createSqlConversationEventStore(executor).append(turn.conversationId, [...prompt.map((entry, index) => entry.source === "input" ? {
1113
- data: historyItemFromPiMessage(entry.message, entry.provenance),
1170
+ await appendAgentHistory(executor, turn.conversationId, turn.turnId, [...prompt.map((entry, index) => entry.source === "input" ? {
1171
+ item: historyItemFromPiMessage(entry.message, entry.provenance),
1114
1172
  idempotencyKey: inputEventKey(entry.inputId),
1115
1173
  createdAtMs: entry.message.timestamp
1116
1174
  } : {
1117
- data: historyItemFromPiMessage(entry.message, contextProvenance),
1175
+ item: historyItemFromPiMessage(entry.message, contextProvenance),
1118
1176
  idempotencyKey: promptEventKey(turn.turnId, turn.stepSeq, index),
1119
1177
  createdAtMs: entry.message.timestamp
1120
1178
  }), ...step.messages.map((message, index) => ({
1121
- data: historyItemFromPiMessage(message, contextProvenance),
1179
+ item: historyItemFromPiMessage(message, contextProvenance),
1122
1180
  idempotencyKey: stepEventKey(turn.turnId, turn.stepSeq, index),
1123
1181
  createdAtMs: message.timestamp
1124
1182
  }))]);
@@ -1394,41 +1452,82 @@ function collectPendingToolCalls(messages) {
1394
1452
  };
1395
1453
  }
1396
1454
  async function runToolCalls(pending, input) {
1397
- const results = await Promise.all(pending.calls.map((call) => runToolCall(call, pending.truncated, input)));
1455
+ const hooks = input.hooks ?? {};
1456
+ const checked = await Promise.all(pending.calls.map(async (call) => {
1457
+ const check = checkToolCall(call, pending.truncated, input);
1458
+ if ("run" in check || !hooks.beforeCall) return check;
1459
+ const result = await hooks.beforeCall(check.call, input.signal);
1460
+ return result ? replaced(check, result) : check;
1461
+ }));
1462
+ if (input.signal.aborted) throw input.signal.reason;
1463
+ const ready = checked.flatMap((check) => "run" in check ? [] : [check.call]);
1464
+ const batchResults = hooks.beforeBatch && ready.length > 0 ? await hooks.beforeBatch(ready, input.signal) : /* @__PURE__ */ new Map();
1465
+ if (input.signal.aborted) throw input.signal.reason;
1466
+ const allowed = checked.map((check) => {
1467
+ const result = batchResults.get(check.call.id);
1468
+ return result && !("run" in check) ? replaced(check, result) : check;
1469
+ });
1470
+ const results = await Promise.all(allowed.map((check) => runToolCall(check, hooks, input)));
1398
1471
  if (input.signal.aborted) throw input.signal.reason;
1399
1472
  return {
1400
1473
  outcome: results.every(({ result }) => result.endsTurn === true) ? "completed" : "continue",
1401
1474
  messages: results.map(({ result, call }) => toResultMessage(call, result))
1402
1475
  };
1403
1476
  }
1404
- function runToolCall(call, truncated, input) {
1477
+ /** A call that a before hook stopped: it does not run, and gets `result`. */
1478
+ function replaced({ call }, result) {
1479
+ return {
1480
+ call,
1481
+ run: {
1482
+ status: "replaced",
1483
+ result
1484
+ }
1485
+ };
1486
+ }
1487
+ function runToolCall(check, { afterCall }, input) {
1488
+ const { call } = check;
1405
1489
  return withSpan("gen_ai.execute_tool", {
1406
1490
  "gen_ai.operation.name": "execute_tool",
1407
1491
  "gen_ai.tool.name": call.name,
1408
1492
  "gen_ai.tool.call.id": call.id,
1409
1493
  "gen_ai.tool.type": "function"
1410
1494
  }, async (span) => {
1411
- const { status, result } = await executeToolCall(call, truncated, input);
1495
+ const { status, result } = "run" in check ? check.run : await executeToolCall(check, input);
1412
1496
  span.setAttribute("app.tool_call.outcome", status);
1413
1497
  return {
1414
1498
  call,
1415
- result
1499
+ result: afterCall ? await afterCall(call, result, input.signal) : result
1416
1500
  };
1417
1501
  });
1418
1502
  }
1419
- async function executeToolCall(call, truncated, input) {
1420
- if (input.skipDanglingToolCalls) return danglingRun(call, input);
1421
- if (truncated) return errorRun("truncated", `Tool call "${call.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`);
1503
+ /** Finds the call's tool and checks its arguments, without running it. */
1504
+ function checkToolCall(call, truncated, input) {
1505
+ const skip = (run) => ({
1506
+ call,
1507
+ run
1508
+ });
1509
+ if (input.skipDanglingToolCalls) return skip(danglingRun(call, input));
1510
+ if (truncated) return skip(errorRun("truncated", `Tool call "${call.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`));
1422
1511
  const tool = input.tools.find((candidate) => candidate.name === call.name);
1423
- if (!tool) return errorRun("not_found", `Tool ${call.name} not found`);
1424
- if (input.replay && tool.replay === "never") return errorRun("replay_skipped", "This call was interrupted before its result was saved, so it may have run. Check its effect before you call it again.");
1512
+ if (!tool) return skip(errorRun("not_found", `Tool ${call.name} not found`));
1513
+ if (input.replay && tool.replay === "never") return skip(errorRun("replay_skipped", "This call was interrupted before its result was saved, so it may have run. Check its effect before you call it again."));
1425
1514
  let args;
1426
1515
  try {
1427
1516
  args = validateToolArguments(tool, call);
1428
1517
  } catch (error) {
1429
- return errorRun("invalid_arguments", errorText(error));
1518
+ return skip(errorRun("invalid_arguments", errorText(error)));
1430
1519
  }
1431
- if (!isJsonObject(args)) return errorRun("invalid_arguments", "Tool arguments must be a JSON object");
1520
+ if (!isJsonObject(args)) return skip(errorRun("invalid_arguments", "Tool arguments must be a JSON object"));
1521
+ return {
1522
+ call: {
1523
+ ...call,
1524
+ arguments: args
1525
+ },
1526
+ tool,
1527
+ args
1528
+ };
1529
+ }
1530
+ async function executeToolCall({ call, tool, args }, input) {
1432
1531
  try {
1433
1532
  const result = await tool.execute(args, {
1434
1533
  callId: call.id,
@@ -1518,30 +1617,35 @@ async function advanceTurn({ executor, queue, owner, leaseMs }, message, options
1518
1617
  }
1519
1618
  }
1520
1619
  async function runClaimedStep({ executor, queue }, claim, unread, { client, prompt, modelSettings, tools, maxAttempts }) {
1521
- const events = await createSqlConversationEventStore(executor).loadCurrentHistory(claim.conversationId);
1620
+ const history = await loadAgentHistory({ executor }, claim.conversationId);
1522
1621
  setActiveSpanAttributes({
1523
1622
  "app.turn.step_seq": claim.stepSeq,
1524
1623
  "gen_ai.conversation.id": claim.conversationId
1525
1624
  });
1526
- const history = projectConversationEvents(events).messages;
1527
- const stepTools = await tools(claim, await findTurnInputs({ executor }, claim.turnId));
1528
- const step = await whileLeased({ executor }, claim, (signal) => runStep({
1529
- history,
1530
- request: async () => ({
1531
- ...await assemblePrompt(await prompt(claim), {
1532
- turn: claim,
1533
- history,
1534
- inputs: unread
1535
- }, { signal }),
1536
- model: await modelSettings(claim)
1537
- }),
1538
- tools: stepTools.definitions,
1539
- client,
1540
- session: claim.conversationId,
1541
- replay: claim.attempts > 1,
1542
- skipDanglingToolCalls: claim.stepSeq === 0,
1543
- signal
1544
- })).finally(() => stepTools.close());
1625
+ const step = await endTurnOnTurnFailedError({
1626
+ executor,
1627
+ queue
1628
+ }, claim, async () => {
1629
+ const stepTools = await tools(claim, await findTurnInputs({ executor }, claim.turnId));
1630
+ return whileLeased({ executor }, claim, (signal) => runStep({
1631
+ history,
1632
+ request: async () => ({
1633
+ ...await assemblePrompt(await prompt(claim), {
1634
+ turn: claim,
1635
+ history,
1636
+ inputs: unread
1637
+ }, { signal }),
1638
+ model: await modelSettings(claim)
1639
+ }),
1640
+ tools: stepTools.definitions,
1641
+ hooks: stepTools.hooks,
1642
+ client,
1643
+ session: claim.conversationId,
1644
+ replay: claim.attempts > 1,
1645
+ skipDanglingToolCalls: claim.stepSeq === 0,
1646
+ signal
1647
+ })).finally(() => stepTools.close());
1648
+ });
1545
1649
  if (!step) return;
1546
1650
  const { result, newMessages } = step;
1547
1651
  switch (result.outcome) {
@@ -1575,6 +1679,32 @@ async function runClaimedStep({ executor, queue }, claim, unread, { client, prom
1575
1679
  default: throw new Error(`Unhandled step result: ${JSON.stringify(result)}`);
1576
1680
  }
1577
1681
  }
1682
+ /**
1683
+ * Runs `run`, the step and the host code it calls. A `TurnFailedError` from
1684
+ * the host ends the Turn as failed with its failure, and gives undefined.
1685
+ * Other errors reach `advanceTurn`, which releases the lease for a retry.
1686
+ */
1687
+ async function endTurnOnTurnFailedError({ executor, queue }, claim, run) {
1688
+ try {
1689
+ return await run();
1690
+ } catch (error) {
1691
+ const failed = findTurnFailedError(error);
1692
+ if (!failed) throw error;
1693
+ if (await endFailedTurn({ executor }, claim, failed.message, failed.failure)) await reconcileTurn({
1694
+ executor,
1695
+ queue
1696
+ }, claim.turnId);
1697
+ return;
1698
+ }
1699
+ }
1700
+ /**
1701
+ * The `TurnFailedError` that `error` is or wraps. `assemblePrompt` wraps a
1702
+ * fragment's or a required loader's error, with the original as `cause`, so
1703
+ * that the error names the fragment or loader.
1704
+ */
1705
+ function findTurnFailedError(error) {
1706
+ for (let cause = error; cause instanceof Error; cause = cause.cause) if (cause instanceof TurnFailedError) return cause;
1707
+ }
1578
1708
  const MODEL_RETRY_BASE_DELAY_MS = 2e3;
1579
1709
  const MODEL_RETRY_MAX_DELAY_MS = 6e4;
1580
1710
  /**
@@ -1736,6 +1866,86 @@ async function turnStepConsumer(engineCtx, { client, bot, tools }) {
1736
1866
  maxAttempts: MAX_ATTEMPTS
1737
1867
  }));
1738
1868
  }
1869
+ // src/turn-steps/limits.ts
1870
+ const WRAPPED_UP = "wrapped_up";
1871
+ /**
1872
+ * Checks one tool batch of a Turn against main's limits. Undefined when the
1873
+ * batch may run. The first time the Turn is over a limit, gives the wrap-up
1874
+ * result for each call. After that, throws `TurnFailedError`.
1875
+ */
1876
+ async function checkTurnLimits(ctx, turnId, calls) {
1877
+ const history = await loadTurnAgentHistory(ctx, turnId);
1878
+ const replies = history.filter((message) => message.role === "assistant");
1879
+ const toolCallCount = replies.flatMap((reply) => reply.content).filter((part) => part.type === "toolCall").length;
1880
+ const results = history.filter((message) => message.role === "toolResult");
1881
+ const costUsd = agentTurnCostUsd(extractGenAiUsageSummary(...replies)) ?? 0;
1882
+ const overBudget = costUsd >= botConfig.maxTurnCostUsd;
1883
+ const overToolCalls = toolCallCount > botConfig.maxToolCallsPerTurn;
1884
+ const attributes = {
1885
+ "app.ai.cost.total_usd": costUsd,
1886
+ "app.ai.tool_call_count": toolCallCount
1887
+ };
1888
+ if (results.some((result) => isWrapUp(result.details))) {
1889
+ const error = overToolCalls && !overBudget ? new TurnToolCallLimitExceededError(botConfig.maxToolCallsPerTurn) : new TurnBudgetExceededError(botConfig.maxTurnCostUsd);
1890
+ const failure = { failureCode: "agent_run_failed" };
1891
+ const eventId = logException(error, "agent.turn.limit.exceeded", {
1892
+ ...attributes,
1893
+ "app.turn.id": turnId
1894
+ });
1895
+ if (eventId) failure.eventId = eventId;
1896
+ throw new TurnFailedError(error.message, failure);
1897
+ }
1898
+ if (!overBudget && !overToolCalls) return;
1899
+ logWarn("agent.turn.limit.wrapped_up", attributes);
1900
+ return new Map(calls.map((call) => [call.id, {
1901
+ content: [{
1902
+ type: "text",
1903
+ text: TURN_LIMIT_WRAP_UP_MESSAGE
1904
+ }],
1905
+ details: { turnLimit: WRAPPED_UP },
1906
+ isError: true
1907
+ }]));
1908
+ }
1909
+ function isWrapUp(details) {
1910
+ return typeof details === "object" && details !== null && "turnLimit" in details && details.turnLimit === WRAPPED_UP;
1911
+ }
1912
+ // src/turn-steps/tool-hooks.ts
1913
+ /**
1914
+ * Builds the tool hooks of one step. A batch past the Turn's limits does not
1915
+ * run. Core has no Guardian yet, so a call that needs review gets main's
1916
+ * "review unavailable" error and does not run. Calls that need no review run.
1917
+ */
1918
+ function turnToolHooks(options) {
1919
+ return {
1920
+ async beforeBatch(calls, signal) {
1921
+ const limited = await checkTurnLimits(options.ctx, options.turnId, calls);
1922
+ if (limited) return limited;
1923
+ const reviews = await Promise.all(calls.map(async (call) => {
1924
+ const tool = options.tools.get(call.name);
1925
+ if (!tool) throw new Error(`Tool ${call.name} has no definition`);
1926
+ const action = {
1927
+ toolCallId: call.id,
1928
+ toolName: call.name,
1929
+ tool,
1930
+ input: call.arguments
1931
+ };
1932
+ const results = await reviewToolActions([action], void 0, signal);
1933
+ return [call.id, results.get(call.id)];
1934
+ }));
1935
+ return new Map(reviews.flatMap(([callId, review]) => review && !review.allowed ? [[callId, {
1936
+ content: [{
1937
+ type: "text",
1938
+ text: review.error.message
1939
+ }],
1940
+ isError: true
1941
+ }]] : []));
1942
+ },
1943
+ afterCall: (call, result) => capToolResult(result, {
1944
+ toolCallId: call.id,
1945
+ workspace: options.workspace
1946
+ })
1947
+ };
1948
+ }
1739
1949
  // src/turn-steps/tools.ts
1740
1950
  function storedDetails(details) {
1741
1951
  return details === void 0 ? void 0 : z.json().parse(JSON.parse(JSON.stringify(details)));
@@ -1784,23 +1994,27 @@ async function turnTools(turn, inputs) {
1784
1994
  traceContext: { conversationId: turn.conversationId },
1785
1995
  conversationId: turn.conversationId,
1786
1996
  credentialEgress: credentialContextForActor(actor),
1787
- actor,
1788
- configurationValues: {},
1789
- getActiveSkill: () => null,
1790
1997
  prepareSandbox: () => {},
1791
1998
  onSandboxRefChanged: () => {},
1792
1999
  persistSandboxRef: (sandboxRef) => persistThreadRuntimeState(turn.conversationId, { sandboxRef })
1793
2000
  });
1794
2001
  const systemTime = createSystemTimeTool();
2002
+ const sandboxTools = Object.entries(SANDBOX_TOOLS).map(([name, create]) => [name, create()]);
1795
2003
  return {
1796
2004
  definitions: [coreTool("systemTime", systemTime, (input, { callId, signal }) => Promise.resolve(systemTime.execute(input, {
1797
2005
  signal,
1798
2006
  toolCallId: callId
1799
- }))), ...Object.entries(SANDBOX_TOOLS).map(([name, create]) => coreTool(name, create(), (input, { signal }) => sandbox.tools.execute({
2007
+ }))), ...sandboxTools.map(([name, tool]) => coreTool(name, tool, (input, { signal }) => sandbox.tools.execute({
1800
2008
  toolName: name,
1801
2009
  input: buildSandboxInput(name, sandboxInputSchema.parse(input)),
1802
2010
  signal
1803
2011
  })))],
2012
+ hooks: turnToolHooks({
2013
+ ctx: { executor: getSqlExecutor() },
2014
+ turnId: turn.turnId,
2015
+ tools: new Map([["systemTime", systemTime], ...sandboxTools]),
2016
+ workspace: sandbox.workspace
2017
+ }),
1804
2018
  close: () => sandbox.close()
1805
2019
  };
1806
2020
  }
@@ -1,5 +1,9 @@
1
- import { Af as botConfig, Ar as pluginCatalogRuntime, Jr as deleteMcpServerSessionId, Vr as hasRequiredOAuthScope, Yr as deleteMcpStoredOAuthCredentials, ml as deleteProviderIdentityForUser, o as getSqlExecutor, pl as deleteProviderIdentityForSlackUser, qr as deleteMcpAuthSessionsForUserProvider, rr as startOAuthFlow } from "./db-DXTOYRzR.js";
2
- import { G as mapBounded } from "./transcript-BHhJVY0P.js";
1
+ import { lc as deleteProviderIdentityForSlackUser, o as getSqlExecutor, uc as deleteProviderIdentityForUser } from "./db-BFmyYZtJ.js";
2
+ import { t as botConfig } from "./config-CHQ8X251.js";
3
+ import { L as mapBounded } from "./prompt-Dv7gkpD6.js";
4
+ import { ai as startOAuthFlow } from "./mailbox-turn-uSXhUFc9.js";
5
+ import { S as deleteMcpStoredOAuthCredentials, b as deleteMcpAuthSessionsForUserProvider, m as hasRequiredOAuthScope, x as deleteMcpServerSessionId } from "./registry-iXMT5Jmh.js";
6
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.js";
3
7
  import { randomBytes } from "node:crypto";
4
8
  // src/handlers/oauth-html.ts
5
9
  /** Build pre-escaped callback HTML with the shared response security policy. */
@@ -1,9 +1,10 @@
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 { i as getCurrentConversationPrivacy, n as redactSandboxEgressProxyPath } from "./proxy-path-Dc-0jXGi.js";
1
+ import { a as getClient, c as init, i as getActiveSpan, o as getGlobalScope, p as spanToJSON, s as getTraceData, u as sentry_exports } from "./sentry-CPbZjomA.js";
2
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-B1uXn5sf.js";
3
3
  import { n as isPushServiceHost } from "./push-endpoint-CO-nomUd.js";
4
+ import { n as redactSandboxEgressProxyPath } from "./proxy-path-BHYoKZdq.js";
4
5
  import { n as promoteHttpRouteName, r as routeNameMiddleware, t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
5
6
  import { t as consumePrivateTraceResultMarker } from "./private-trace-result-CE7_lEdq.js";
6
- import { _ as getDeploymentServiceVersion, v as getDeploymentTelemetryAttributes } from "./deployment-CG3TchWh.js";
7
+ import { _ as getDeploymentTelemetryAttributes, g as getDeploymentServiceVersion } from "./deployment-DXq9ZLU4.js";
7
8
  import { performance } from "node:perf_hooks";
8
9
  import { subscribe, unsubscribe } from "node:diagnostics_channel";
9
10
  // src/chat/pi/gateway-request-timing.ts
@@ -300,6 +301,13 @@ function scrubPrivateSentryLog(log) {
300
301
  return log;
301
302
  }
302
303
  // src/instrumentation.ts
304
+ const RATE_LIMIT_HEADERS = [
305
+ "x-ratelimit-limit",
306
+ "x-ratelimit-remaining",
307
+ "x-ratelimit-reset",
308
+ "x-ratelimit-resource",
309
+ "x-ratelimit-used"
310
+ ];
303
311
  const MANUAL_GEN_AI_INTEGRATIONS = /* @__PURE__ */ new Set([
304
312
  "Anthropic_AI",
305
313
  "Google_GenAI",
@@ -350,7 +358,7 @@ function getBrowserSentryConfig() {
350
358
  baggage: trace.baggage,
351
359
  dsn,
352
360
  environment: getEnvironment(),
353
- release: getDeploymentServiceVersion(),
361
+ release: getDeploymentServiceVersion(process.env),
354
362
  sentryTrace: trace["sentry-trace"],
355
363
  tracesSampleRate: getTracesSampleRate()
356
364
  };
@@ -360,8 +368,8 @@ function initSentry() {
360
368
  if (getClient()) return;
361
369
  const dsn = process.env["SENTRY_DSN"];
362
370
  const enableLogs = getBoolean(process.env["SENTRY_ENABLE_LOGS"], Boolean(dsn || process.env["SENTRY_SPOTLIGHT"]?.trim()));
363
- const serviceVersion = getDeploymentServiceVersion();
364
- const deploymentSpanAttributes = getDeploymentTelemetryAttributes();
371
+ const serviceVersion = getDeploymentServiceVersion(process.env);
372
+ const deploymentSpanAttributes = getDeploymentTelemetryAttributes(process.env);
365
373
  init({
366
374
  dsn,
367
375
  environment: getEnvironment(),
@@ -394,7 +402,7 @@ function initSentry() {
394
402
  beforeSend: scrubPrivateSentryEvent,
395
403
  beforeSendLog: enableLogs ? scrubPrivateSentryLog : () => null,
396
404
  beforeSendSpan: scrubPrivateSentrySpan,
397
- integrations: (defaultIntegrations) => defaultIntegrations.filter((integration) => !MANUAL_GEN_AI_INTEGRATIONS.has(integration.name) && integration.name !== "Dedupe")
405
+ integrations: (defaultIntegrations) => [...defaultIntegrations.filter((integration) => !MANUAL_GEN_AI_INTEGRATIONS.has(integration.name) && integration.name !== "Dedupe" && integration.name !== "NodeFetch"), sentry_exports.nativeNodeFetchIntegration({ headersToSpanAttributes: { responseHeaders: RATE_LIMIT_HEADERS } })]
398
406
  });
399
407
  getGlobalScope().setAttributes(deploymentSpanAttributes);
400
408
  getGlobalScope().addEventProcessor((event) => event.type === "feedback" ? scrubPrivateSentryEvent(event) : event);