@sentry/junior 0.318.0 → 0.319.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 (92) hide show
  1. package/dist/{context-BKF_5zzI.js → adapter-8_S6Birm.js} +537 -537
  2. package/dist/{admin-UOHix_5P.js → admin-EsbUON1j.js} +1 -1
  3. package/dist/{agent-runner-DeYymwh2.js → agent-CtzMl32d.js} +18608 -5452
  4. package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
  5. package/dist/{agent-update-delivery-DH8bx7jU.js → agent-update-delivery-pAvsbuGL.js} +4 -5
  6. package/dist/api/schema.d.ts +43 -23
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +70 -80
  9. package/dist/{app-DKAOuaoC.d.ts → app-tACXxJPI.d.ts} +4 -4
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +213 -91
  12. package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
  13. package/dist/{channel-access-A0de5lRv.js → channel-access-DET5hzZM.js} +1 -1
  14. package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-DpM3tMVi.js} +5 -5
  15. package/dist/cli/chat.d.ts +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.d.ts +1 -1
  20. package/dist/cli/plugins.js +8 -8
  21. package/dist/cli/snapshot-create.js +5 -5
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +3 -4
  24. package/dist/{continue-in-slack-YxwMQVeR.js → continue-in-slack-CFzDyxkH.js} +3 -3
  25. package/dist/{conversation-feed-Cj7IuBtM.js → conversation-feed-DEUdD7mb.js} +2 -106
  26. package/dist/{conversation-privacy-Cr_dNW1p.js → conversation-privacy-C2vYK55O.js} +1 -1
  27. package/dist/{create-Btl1y1rq.js → create-Ta3SEIB5.js} +115 -5
  28. package/dist/{credential-sync-DTarZ63K.js → credential-sync-DyRqDmY4.js} +15 -18
  29. package/dist/{db-of6e3sGt.js → db-BCaNWl9p.js} +4579 -717
  30. package/dist/{deployment-C0qXa0FD.js → deployment-CfOew1Tm.js} +3 -3
  31. package/dist/{engine-context-C_QL_bMQ.js → engine-context-CiExoy1B.js} +144 -149
  32. package/dist/{html-9_pS9SjY.js → html-Bb2Si1bR.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-wwDcROh9.js +5007 -0
  35. package/dist/{logging-BnOG0qz2.js → logging-BRPTXAdf.js} +8 -33
  36. package/dist/{mailbox-turn-Byrry9o1.js → markers-9QoqW5ov.js} +1675 -1255
  37. package/dist/nitro.d.ts +2 -2
  38. package/dist/nitro.js +6 -7
  39. package/dist/{oauth-callback-server-CjnnUr4o.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
  40. package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-CH2v7WiB.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-iHw1uu32.js → profile-D9LdwmZi.js} +16 -18
  43. package/dist/{prompt-DEkStuxG.js → prompt-3TqxEOtc.js} +1 -1
  44. package/dist/{reports-C1d9azyV.js → reports-K-tbtEyx.js} +2 -2
  45. package/dist/{resolve-DC6zBuDV.js → resolve-BBV2qf8A.js} +5 -5
  46. package/dist/{result-DxewDuXb.js → result-5IdGJP4M.js} +20 -9
  47. package/dist/{runner-99YxVN_r.js → runner-BK_joPlM.js} +7 -8
  48. package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
  49. package/dist/{schema-BTojNBr5.js → schema-zWGG6VC1.js} +13 -7
  50. package/dist/{service-account-YDCPSByj.js → service-account-CateFyhw.js} +4 -5
  51. package/dist/{skills-CleC0Hze.js → skills-Ccjw8h2P.js} +9 -9
  52. package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
  53. package/dist/storage-C9U7R5rM.js +273 -0
  54. package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-YBTHIFlP.js} +26 -84
  55. package/dist/topic-B2EWKKBT.js +6 -0
  56. package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
  57. package/dist/{types-DCzTAA63.js → types-BNHkJrOP.js} +25 -11
  58. package/dist/{users-Cb9c1k9q.js → users-CCRAqYb_.js} +1 -1
  59. package/dist/{validation-BiUmWPhy.js → validation-BCUpJa8K.js} +4 -4
  60. package/dist/{version-VEXiEcZu.js → version-BNm0JYj3.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-ChWYQdhm.js → worker-BhgpZ7_b.js} +4 -4
  63. package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
  64. package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
  65. package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
  66. package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
  67. package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
  68. package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
  69. package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
  70. package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
  71. package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
  72. package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
  73. package/package.json +9 -7
  74. package/dist/auth-pause-state-f9hJM_zO.js +0 -113
  75. package/dist/catalog-runtime-BfdAnztW.js +0 -6
  76. package/dist/child-message-peFWLcCZ.js +0 -15
  77. package/dist/conversation-turn-Bru4w_FD.js +0 -1250
  78. package/dist/job-runner-B2XEvpif.js +0 -1505
  79. package/dist/lineage-nh4z9iQN.js +0 -36
  80. package/dist/list-HRP3TIRl.js +0 -12631
  81. package/dist/markers-CTTtJqYn.js +0 -342
  82. package/dist/message-BRUuLgrY.js +0 -153
  83. package/dist/model-input-CFC62mf-.js +0 -82
  84. package/dist/registry-Cl7Labpe.js +0 -3279
  85. package/dist/run-conversation-Cz2ubZK-.js +0 -337
  86. package/dist/sender-actors-77zTQbSG.js +0 -84
  87. package/dist/spawn-DuZfodPa.js +0 -45
  88. package/dist/task-runner-BJ9Up3bG.js +0 -1529
  89. package/dist/topic-CRYYBYp-.js +0 -7
  90. package/dist/topics-BoCkoPJJ.js +0 -21
  91. package/dist/turn-membership-VT7XZh-L.js +0 -856
  92. package/dist/turn-wake-C7HeLHAM.js +0 -151
@@ -1,4 +1,4 @@
1
- import { t as JUNIOR_VERSION } from "./version-VEXiEcZu.js";
1
+ import { t as JUNIOR_VERSION } from "./version-BNm0JYj3.js";
2
2
  import { randomUUID } from "node:crypto";
3
3
  // src/deployment.ts
4
4
  const JUNIOR_HEARTBEAT_ROUTE = "/api/internal/heartbeat";
@@ -13,7 +13,7 @@ const JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE = "/api/internal/workspace/sn
13
13
  const JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE = "/api/internal/cache/warmups";
14
14
  const JUNIOR_CONTEXT_COMPACTION_CALLBACK_ROUTE = "/api/internal/context/compactions";
15
15
  const JUNIOR_TURN_STEP_CALLBACK_ROUTE = "/api/internal/turn/steps";
16
- const JUNIOR_DELIVERY_CALLBACK_ROUTE = "/api/internal/turn/deliveries";
16
+ const JUNIOR_TURN_ENDED_CALLBACK_ROUTE = "/api/internal/turn/ended";
17
17
  const LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION = "api/internal/agent/continue.ts";
18
18
  /**
19
19
  * One id per process. Fluid compute runs many invocations in one process, so
@@ -50,4 +50,4 @@ function getDeploymentTelemetryAttributes(env) {
50
50
  if (deploymentId) attributes["deployment.id"] = deploymentId;
51
51
  return attributes;
52
52
  }
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 };
53
+ export { getDeploymentTelemetryAttributes as _, JUNIOR_CONVERSATION_WORK_CALLBACK_ROUTE as a, JUNIOR_PLUGIN_TASK_CALLBACK_ROUTE as c, JUNIOR_TURN_ENDED_CALLBACK_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_RETENTION_CRON_SCHEDULE as l, LEGACY_JUNIOR_CONVERSATION_WORK_FUNCTION as m, JUNIOR_AUTO_ARCHIVE_ROUTE as n, JUNIOR_HEARTBEAT_CRON_SCHEDULE as o, JUNIOR_WORKSPACE_SNAPSHOT_JOB_CALLBACK_ROUTE as p, JUNIOR_CACHE_WARMUP_CALLBACK_ROUTE as r, JUNIOR_HEARTBEAT_ROUTE as s, JUNIOR_AUTO_ARCHIVE_CRON_SCHEDULE as t, JUNIOR_RETENTION_ROUTE as u };
@@ -1,19 +1,18 @@
1
- import { $ as resolveGatewayModel, L as botConfig, n as credentialContextForActor } from "./context-BKF_5zzI.js";
2
- import { Ad as juniorTurnOutbox, Br as QUEUE_SIGNATURE_MAX_AGE_MS, Hr as verifyQueueMessage, Ja as usdToMicroUsd, Ku as gatewayRoutingAttributes, M as locationSchema, Ur as getQueueProvider, Vr as signQueueMessage, _ as unseenEvents, a as getDb, af as juniorTurns, dd as agentTurnCostUsd, fd as agentTurnTotalTokens, g as readEventCursor, h as insertEventRows, hf as juniorConversations, id as getGatewayApiKey, if as juniorConversationEvents, jd as juniorTurnInbox, o as getSqlExecutor, ps as resolveRootVisibility, qa as microUsdToUsd, ud as addAgentTurnUsage, v as withConversationEventLock, zu as requestPrefixAttributes } from "./db-of6e3sGt.js";
3
- import { Kn as usageTokensSchema, 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-DCzTAA63.js";
4
- import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-BnOG0qz2.js";
5
- import { h as SERVICE_INSTANCE_ID } from "./deployment-C0qXa0FD.js";
6
- import { G as mapBounded } from "./prompt-DEkStuxG.js";
7
- import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-Cr_dNW1p.js";
8
- import { Kr as reviewToolActions, Or as TURN_LIMIT_WRAP_UP_MESSAGE, Wt as getWorkspace, ft as getPersistedSandboxState, in as buildDeploymentSystemPrompt, jr as TurnToolCallLimitExceededError, kr as TurnBudgetExceededError, mt as persistThreadRuntimeState, pt as getPersistedThreadState } from "./mailbox-turn-Byrry9o1.js";
9
- import { f as createWriteFileTool, g as createEditFileTool, m as createReadFileTool, u as createSystemTimeTool, y as createBashTool } from "./job-runner-B2XEvpif.js";
10
- import { _ as normalizeToolResult, c as buildSandboxInput, g as createAgentSandbox, v as capToolResult } from "./agent-runner-DeYymwh2.js";
11
- import { n as TURN_STEP_TOPIC, t as DELIVERY_TOPIC } from "./topic-CRYYBYp-.js";
1
+ import { $ as resolveGatewayModel, L as botConfig, f as credentialContextForActor } from "./adapter-8_S6Birm.js";
2
+ import { $a as microUsdToUsd, Ap as juniorTurns, Bp as juniorConversations, Dd as getGatewayApiKey, Ff as addAgentTurnUsage, If as agentTurnCostUsd, Jr as verifyQueueMessage, Kr as QUEUE_SIGNATURE_MAX_AGE_MS, Lf as agentTurnTotalTokens, M as locationSchema, Ms as resolveRootVisibility, Yr as getQueueProvider, _ as unseenEvents, a as getDb, cd as requestPrefixAttributes, eo as usdToMicroUsd, g as readEventCursor, h as insertEventRows, hd as gatewayRoutingAttributes, kp as juniorConversationEvents, np as juniorTurnInbox, o as getSqlExecutor, qr as signQueueMessage, tp as juniorTurnOutbox, v as withConversationEventLock } from "./db-BCaNWl9p.js";
3
+ import { St as contextProvenance, dt as agentHistoryFromRow, ft as encodeAgentHistoryPayload, gt as historyItemFromPiMessage, ht as HISTORY_REPLACEMENT_TYPES, mt as AGENT_HISTORY_ITEM_TYPES, qn as usageTokensSchema, vt as isHistoryReplacement, wt as instructionProvenanceFor, yt as piMessageFromHistoryItem } from "./types-BNHkJrOP.js";
4
+ import { _ as serializeGenAiAttribute, f as logException, h as normalizeGenAiFinishReason, i as extractGenAiUsageSummary, m as logWarn, r as extractGenAiUsageAttributes } from "./logging-BRPTXAdf.js";
5
+ import { h as SERVICE_INSTANCE_ID } from "./deployment-CfOew1Tm.js";
6
+ import { G as mapBounded } from "./prompt-3TqxEOtc.js";
7
+ import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-C2vYK55O.js";
8
+ import { $r as reviewToolActions, Fr as TURN_LIMIT_WRAP_UP_MESSAGE, Ir as TurnBudgetExceededError, J as getPersistedSandboxState, Qt as getWorkspace, Rr as TurnToolCallLimitExceededError, X as persistThreadRuntimeState, Y as getPersistedThreadState, fn as buildDeploymentSystemPrompt } from "./markers-9QoqW5ov.js";
9
+ import { D as createReadFileTool, E as createWriteFileTool, O as createEditFileTool, T as createSystemTimeTool, c as createAgentSandbox, k as createBashTool, l as normalizeToolResult, n as buildSandboxInput, u as capToolResult } from "./agent-CtzMl32d.js";
10
+ import { n as TURN_STEP_TOPIC, t as TURN_ENDED_TOPIC } from "./topic-B2EWKKBT.js";
12
11
  import * as z from "zod";
13
12
  import { streamSimple } from "@earendil-works/pi-ai/compat";
14
13
  import { and, asc, eq, exists, inArray, like, lt, lte, max, ne, notExists, or, sql } from "drizzle-orm";
15
14
  import { alias } from "drizzle-orm/pg-core";
16
- import { actorSchema, destinationSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
15
+ import { actorSchema, markdownNodes, parseMarkdown } from "@sentry/junior-plugin-api";
17
16
  import * as Sentry from "@sentry/node";
18
17
  import { randomUUID } from "node:crypto";
19
18
  import { toToolDeclaration, validateToolArguments } from "@earendil-works/pi-ai";
@@ -400,60 +399,11 @@ function inputFormatOf(item) {
400
399
  return inputFormats.get(item);
401
400
  }
402
401
  /**
403
- * Checks a layout and returns the copy that core builds each prompt from. It
404
- * throws on an empty or repeated system prompt section name, on two
405
- * fragments with one name, on one fragment used twice, on two loaders with
406
- * one label, and unless the messages hold exactly one `inputs()` fragment.
407
- * It freezes the system prompt sections and the messages list.
408
- *
409
- * The rules:
410
- * - Loaders do all of the I/O. Core runs each needed loader once per step.
411
- * - Fragments are pure. `enabled` and `format` do no I/O, and read no clock
412
- * and no random value, so the same inputs give the same prompt. Their
413
- * messages have no timestamp: core gives each one the step's time, and
414
- * each input its send time.
415
- * - Message fragments only append. Their messages go after the history, and
416
- * a later step sees them in its history. Core builds them only for a step
417
- * that sends a model request, not for a step that runs tool calls.
418
- * - The `inputs()` fragment sets where the Turn's unread inputs go.
419
- * - The system prompt holds no Conversation data. The host builds its
420
- * sections once at startup, so the model provider can cache that part of
421
- * the request.
422
- * - Tools and model settings are not in the layout. They belong to the Turn,
423
- * and the step gets them separately.
424
- *
402
+ * Checks a layout (rules above) and returns the frozen copy core builds from.
403
+ * Throws on repeated or empty names, reused fragments, or not one `inputs()`.
425
404
  * @example
426
- * // At startup:
427
- * const soul = await readFile("SOUL.md", "utf8");
428
- * const memories = loader(
429
- * "memories",
430
- * (ctx, signal) => memoryStore.recall(ctx.turn.conversationId, signal),
431
- * { timeoutMs: 2_000, optional: true },
432
- * );
433
- * const recalled = fragment("recalled-memories", {
434
- * loader: memories,
435
- * // Recall only for a step that has new inputs.
436
- * enabled: (ctx) => ctx.inputs.length > 0,
437
- * format: (notes): FragmentMessage | Skip =>
438
- * notes && notes.length > 0
439
- * ? { role: "user", content: notes.join("\n") }
440
- * : skip("no memories"),
441
- * });
442
- * const layout = definePromptLayout({
443
- * systemPrompt: [
444
- * { name: "identity", text: "You are Junior, Sentry's Slack bot." },
445
- * { name: "personality", text: soul },
446
- * ],
447
- * messages: [
448
- * recalled,
449
- * inputs({
450
- * format: (input) => ({
451
- * message: { role: "user", content: String(input.payload["text"]) },
452
- * provenance: { authority: "instruction" },
453
- * }),
454
- * }),
455
- * ],
456
- * });
405
+ * const layout = definePromptLayout({ systemPrompt: [identity],
406
+ * messages: [recalledMemories, inputs({ format: formatInput })] });
457
407
  */
458
408
  function definePromptLayout(layout) {
459
409
  const sectionNames = /* @__PURE__ */ new Set();
@@ -680,7 +630,15 @@ async function findInputTurn({ executor }, args) {
680
630
  */
681
631
  async function findTurnDestination({ executor }, turnId) {
682
632
  const [input] = await executor.db().select({ destination: juniorTurnInbox.destination }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
683
- return input?.destination ? destinationSchema.parse(input.destination) : null;
633
+ return input?.destination ?? null;
634
+ }
635
+ /**
636
+ * Finds who a Turn acts for: the sender of its first input. Undefined when
637
+ * the Turn has no input.
638
+ */
639
+ async function findTurnActor({ executor }, turnId) {
640
+ const [input] = await executor.db().select({ actorIdentityId: juniorTurnInbox.actorIdentityId }).from(juniorTurnInbox).where(eq(juniorTurnInbox.turnId, turnId)).orderBy(asc(juniorTurnInbox.createdAt), asc(juniorTurnInbox.id)).limit(1);
641
+ return input?.actorIdentityId;
684
642
  }
685
643
  /** Finds every input of a Turn, oldest first. */
686
644
  async function findTurnInputs({ executor }, turnId) {
@@ -806,17 +764,17 @@ async function publishTurnStep(ctx, turnId, options = {}) {
806
764
  function createTurnStepConsumer(ctx, run) {
807
765
  return turnStepTopic.consumer(ctx, (message, metadata) => run({ turnId: message.turnId }, metadata));
808
766
  }
809
- // src/core/delivery/queue.ts
810
- const deliveryMessageSchema = z.object({
767
+ // src/core/turn/ended.ts
768
+ const turnEndedMessageSchema = z.object({
811
769
  conversationId: z.string().min(1),
812
770
  turnId: z.string().min(1),
813
771
  traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
814
772
  }).strict();
815
- const deliveryTopic = signedTopic({
816
- topic: DELIVERY_TOPIC,
773
+ const turnEndedTopic = signedTopic({
774
+ topic: TURN_ENDED_TOPIC,
817
775
  sign: {
818
- context: "junior.delivery.v1",
819
- schema: deliveryMessageSchema,
776
+ context: "junior.turn_ended.v1",
777
+ schema: turnEndedMessageSchema,
820
778
  signatureVersion: "v1",
821
779
  parts: (message) => [
822
780
  message.conversationId,
@@ -824,24 +782,27 @@ const deliveryTopic = signedTopic({
824
782
  message.traceContext?.sentryTrace ?? ""
825
783
  ]
826
784
  },
827
- onRejected: (attributes) => logWarn("turn.delivery.queue_message.rejected", attributes),
785
+ onRejected: (attributes) => logWarn("turn.ended.queue_message.rejected", attributes),
828
786
  attributes: (message) => ({
829
787
  "app.turn.id": message.turnId,
830
788
  "gen_ai.conversation.id": message.conversationId
831
789
  })
832
790
  });
833
- /** Sends a message that delivers the Turn's replies, after `delayMs` if set. */
834
- async function publishDelivery(ctx, message, options = {}) {
835
- await deliveryTopic.publish(ctx, message, options);
791
+ /**
792
+ * Sends the message that the Turn ended, after `delayMs` if set. A handler
793
+ * that must try its work again later sends it again with a delay.
794
+ */
795
+ async function publishTurnEnded(ctx, message, options = {}) {
796
+ await turnEndedTopic.publish(ctx, message, options);
836
797
  }
837
798
  /**
838
- * Builds the queue consumer of delivery messages. It acknowledges a message
839
- * with a bad or expired signature and retries one that cannot be checked yet.
840
- * The outbox rows hold the delivery state, so a retry only sends what is
841
- * left. The host mounts the consumer on its queue provider.
799
+ * Reads the messages that a Turn ended: it checks that core sent each one,
800
+ * then calls `handle`. It acknowledges a message with a bad or expired
801
+ * signature and retries one that cannot be checked yet. The host mounts the
802
+ * consumer on its queue provider.
842
803
  */
843
- function createDeliveryConsumer(ctx, run) {
844
- return deliveryTopic.consumer(ctx, (message, metadata) => run({
804
+ function readTurnEndedMessages(ctx, handle) {
805
+ return turnEndedTopic.consumer(ctx, (message, metadata) => handle({
845
806
  conversationId: message.conversationId,
846
807
  turnId: message.turnId
847
808
  }, metadata));
@@ -912,7 +873,7 @@ function replyText(row) {
912
873
  async function findTurnReplies({ executor }, conversationId, turnId) {
913
874
  return (await executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "assistant_message"), like(juniorConversationEvents.idempotencyKey, `${turnEventKeyPrefix(turnId)}%`))).orderBy(asc(juniorConversationEvents.seq))).filter((row) => replyText(row) !== void 0);
914
875
  }
915
- // src/core/delivery/outbox.ts
876
+ // src/core/turn/outbox.ts
916
877
  /**
917
878
  * Adds an outbox row for each reply of the Turn that has none, but only while
918
879
  * the Turn has a Destination. Call it in the transaction that commits the
@@ -932,26 +893,6 @@ async function recordReplies({ executor }, turn) {
932
893
  state: "pending"
933
894
  }))).onConflictDoNothing({ target: [juniorTurnOutbox.conversationId, juniorTurnOutbox.eventSeq] });
934
895
  }
935
- /**
936
- * Finds Conversations whose first pending reply has not changed for
937
- * `staleMs`, so no delivery message is likely to reach it. A row behind a
938
- * first row that is still retried waits; it is not stalled.
939
- */
940
- async function findStalledDeliveries({ executor }, { staleMs, limit }) {
941
- const staleBefore = sql`now() - make_interval(secs => ${staleMs / 1e3})`;
942
- const earlier = alias(juniorTurnOutbox, "earlier");
943
- const rows = await executor.db().select({
944
- conversationId: juniorTurnOutbox.conversationId,
945
- turnId: juniorTurnOutbox.turnId,
946
- updatedAt: juniorTurnOutbox.updatedAt
947
- }).from(juniorTurnOutbox).where(and(eq(juniorTurnOutbox.state, "pending"), lt(juniorTurnOutbox.createdAt, staleBefore), lt(juniorTurnOutbox.updatedAt, staleBefore), notExists(executor.db().select({ one: sql`1` }).from(earlier).where(and(eq(earlier.conversationId, juniorTurnOutbox.conversationId), eq(earlier.state, "pending"), lt(earlier.eventSeq, juniorTurnOutbox.eventSeq)))))).limit(limit);
948
- const nowMs = Date.now();
949
- return rows.map((row) => ({
950
- conversationId: row.conversationId,
951
- turnId: row.turnId,
952
- stalledMs: Math.max(0, nowMs - row.updatedAt.getTime())
953
- }));
954
- }
955
896
  // src/core/turn/state.ts
956
897
  /**
957
898
  * Turn priorities: a lower number runs first. A Turn that supersedes the
@@ -996,7 +937,9 @@ async function findTurn({ executor }, turnId) {
996
937
  conversationId: juniorTurns.conversationId,
997
938
  failureCode: juniorTurns.failureCode,
998
939
  failureReason: juniorTurns.failureReason,
999
- failureEventId: juniorTurns.failureEventId
940
+ failureEventId: juniorTurns.failureEventId,
941
+ startedAt: juniorTurns.startedAt,
942
+ endedAt: juniorTurns.endedAt
1000
943
  }).from(juniorTurns).where(eq(juniorTurns.id, turnId));
1001
944
  return turn;
1002
945
  }
@@ -1067,27 +1010,30 @@ async function isSuperseded({ executor }, turnId) {
1067
1010
  }
1068
1011
  /**
1069
1012
  * Makes way for a Turn that supersedes this one. Call it under the
1070
- * Conversation lock. A queued Turn has no step in flight, so it ends now. A
1071
- * running Turn moves behind the new Turn, and `commitStep` ends it when its
1072
- * step commits, so the step's work is kept.
1013
+ * Conversation lock. A queued Turn has no step in flight, so it ends now and
1014
+ * moves `lease_epoch`. A running Turn moves behind the new Turn, and
1015
+ * `commitStep` or `releaseTurn` ends it, so the step's work is kept. True
1016
+ * when the Turn ended now.
1073
1017
  */
1074
1018
  async function supersedeTurn({ executor }, turnId) {
1075
1019
  const db = executor.db();
1076
- await db.update(juniorTurns).set({
1020
+ const ended = await db.update(juniorTurns).set({
1077
1021
  ...SUPERSEDED_END,
1078
1022
  leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
1079
1023
  updatedAt: sql`now()`
1080
- }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued")));
1024
+ }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued"))).returning({ id: juniorTurns.id });
1081
1025
  await db.update(juniorTurns).set({
1082
1026
  priority: TURN_PRIORITY.normal,
1083
1027
  updatedAt: sql`now()`
1084
1028
  }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "running")));
1029
+ return ended.length > 0;
1085
1030
  }
1086
1031
  /**
1087
1032
  * Claims a Turn to run its next step: the Conversation's next queued Turn, or
1088
- * a running Turn whose lease expired. Returns undefined for any other Turn, so
1089
- * of two concurrent claims only one gets the Turn, and a Turn waits while
1090
- * another Turn of its Conversation runs. It holds the Conversation lock.
1033
+ * a running Turn whose lease expired, so the queue's redelivery after a crash
1034
+ * resumes it. Any other Turn gets undefined, so one of two racing claims wins,
1035
+ * and a Conversation runs one Turn at a time, in order. Each claim moves
1036
+ * `lease_epoch` and `attempts` and holds the Conversation lock.
1091
1037
  */
1092
1038
  async function claimTurn({ executor, owner, leaseMs }, turnId) {
1093
1039
  const turn = await findTurn({ executor }, turnId);
@@ -1160,15 +1106,11 @@ function promptEventKey(turnId, stepSeq, index) {
1160
1106
  return `prompt:${turnId}:${stepSeq}:${index}`;
1161
1107
  }
1162
1108
  /**
1163
- * Commits a step in one transaction: it appends the prompt's new messages in
1164
- * layout order, which hold the inputs that the step read, then the step's
1165
- * messages keyed by Turn and step, to the Conversation history, adds an
1166
- * outbox row for each new reply and releases the lease. A Turn that
1167
- * continues goes back to queued for its next step, which needs a new claim.
1168
- * A Turn that the step completed ends, unless it still has unread inputs:
1169
- * then it continues, so the next step reads them.
1170
- * Returns what the Turn does next. Undefined when the lease is lost or the
1171
- * step is already committed, and then nothing is written.
1109
+ * Commits a step in one transaction: appends the prompt's new messages, with
1110
+ * the inputs the step read, then the step's messages to history, adds an
1111
+ * outbox row per new reply, and releases the lease. A Turn that continues
1112
+ * queues for a new claim. A `stale` final reply is not committed. Undefined,
1113
+ * with no write, when the lease is lost or the step is already committed.
1172
1114
  */
1173
1115
  async function commitStep({ executor }, turn, step, prompt) {
1174
1116
  const nextStep = {
@@ -1180,6 +1122,7 @@ async function commitStep({ executor }, turn, step, prompt) {
1180
1122
  };
1181
1123
  return executor.transaction(() => withConversationEventLock(executor, turn.conversationId, async () => {
1182
1124
  const outcome = await commitOutcome({ executor }, turn.turnId, step, prompt);
1125
+ if (outcome === "stale") return await requeueStep({ executor }, turn, step) ? outcome : void 0;
1183
1126
  if ((await executor.db().update(juniorTurns).set(outcome === "completed" ? {
1184
1127
  ...nextStep,
1185
1128
  state: "completed",
@@ -1211,19 +1154,41 @@ async function commitStep({ executor }, turn, step, prompt) {
1211
1154
  /**
1212
1155
  * A completed step ends the Turn only when the commit reads every unread
1213
1156
  * input. The scheduler can add an input after the step read them, and the
1214
- * Conversation lock keeps more out until the commit ends.
1157
+ * Conversation lock keeps more out until the commit ends. A final reply that
1158
+ * missed an input is `stale`, so the Turn ends with one reply to every input.
1215
1159
  */
1216
1160
  async function commitOutcome({ executor }, turnId, step, prompt) {
1217
1161
  if (step.outcome === "completed") {
1218
1162
  const read = new Set(prompt.flatMap((entry) => entry.source === "input" ? [entry.inputId] : []));
1219
1163
  if ((await findUnreadInputs({ executor }, turnId)).every((input) => read.has(input.inputId))) return "completed";
1220
1164
  }
1221
- return await isSuperseded({ executor }, turnId) ? "superseded" : "continue";
1165
+ if (await isSuperseded({ executor }, turnId)) return "superseded";
1166
+ return step.outcome === "completed" && finalReplyOf(step) ? "stale" : "continue";
1167
+ }
1168
+ function finalReplyOf(step) {
1169
+ const [message] = step.messages;
1170
+ return message?.role === "assistant" ? message : void 0;
1171
+ }
1172
+ /**
1173
+ * Queues the Turn for the same step again, with nothing committed, after a
1174
+ * stale final reply. The attempt does not count: the step did not fail. The
1175
+ * dropped reply's usage adds to the Turn's discarded usage.
1176
+ */
1177
+ async function requeueStep({ executor }, turn, step) {
1178
+ return (await executor.db().update(juniorTurns).set({
1179
+ ...await discardedUsageUpdate({ executor }, turn, extractGenAiUsageSummary(finalReplyOf(step))),
1180
+ state: "queued",
1181
+ attempts: 0,
1182
+ leaseOwner: null,
1183
+ leaseExpiresAt: null,
1184
+ updatedAt: sql`now()`
1185
+ }).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length > 0;
1222
1186
  }
1223
1187
  /**
1224
1188
  * Ends a running Turn as failed, with the reason and the failure details.
1225
- * False when the lease is lost. The engine calls it through `endFailedTurn`,
1226
- * which also moves the Turn's late inputs.
1189
+ * `discarded` is the usage of the model reply that the step drops. False when
1190
+ * the lease is lost. The engine calls it through `endFailedTurn`, which also
1191
+ * moves the Turn's late inputs.
1227
1192
  */
1228
1193
  async function failTurn({ executor }, lease, endReason, failure, discarded) {
1229
1194
  return (await executor.db().update(juniorTurns).set({
@@ -1243,8 +1208,8 @@ async function failTurn({ executor }, lease, endReason, failure, discarded) {
1243
1208
  * Queues a running Turn again after its invocation failed, so the queue's
1244
1209
  * retry can claim the step at once. The failed attempt still counts. A Turn
1245
1210
  * that another Turn supersedes ends instead, like at a commit. `discarded` is
1246
- * the usage of the failed model reply that the retry drops. False when the
1247
- * lease is lost.
1211
+ * the usage of the failed model reply that the retry drops. Returns the
1212
+ * Turn's new state, or undefined when the lease is lost.
1248
1213
  */
1249
1214
  async function releaseTurn({ executor }, lease, discarded) {
1250
1215
  return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
@@ -1260,7 +1225,7 @@ async function releaseTurn({ executor }, lease, discarded) {
1260
1225
  } : {
1261
1226
  ...released,
1262
1227
  state: "queued"
1263
- }).where(leaseFence(lease)).returning({ id: juniorTurns.id })).length > 0;
1228
+ }).where(leaseFence(lease)).returning({ state: juniorTurns.state }))[0]?.state;
1264
1229
  }));
1265
1230
  }
1266
1231
  // src/core/turn/schedule.ts
@@ -1316,7 +1281,7 @@ async function placeInput({ executor }, { delivery, ...input }) {
1316
1281
  publish: false
1317
1282
  };
1318
1283
  }
1319
- if (choice.supersede) await supersedeTurn({ executor }, choice.supersede.turnId);
1284
+ const ended = choice.supersede && await supersedeTurn({ executor }, choice.supersede.turnId) ? choice.supersede.turnId : void 0;
1320
1285
  const turn = await createTurn({ executor }, {
1321
1286
  conversationId: input.conversationId,
1322
1287
  priority: choice.create.priority
@@ -1328,18 +1293,22 @@ async function placeInput({ executor }, { delivery, ...input }) {
1328
1293
  return {
1329
1294
  turnId: turn.turnId,
1330
1295
  created: true,
1331
- publish: openTurns.length === 0 || choice.supersede !== void 0
1296
+ publish: openTurns.length === 0 || choice.supersede !== void 0,
1297
+ ended
1332
1298
  };
1333
1299
  }
1334
1300
  /**
1335
- * Puts an input into the Turn that `assignTurn` picks, and publishes a Turn
1336
- * that the input created when no other Turn is open or when it supersedes
1337
- * one. An input with a known idempotency key writes nothing. Call it outside
1338
- * a transaction: it publishes after its own commit, and a publish error
1339
- * reaches the caller with the input already stored.
1301
+ * Puts an input into the Turn that `assignTurn` picks, then publishes what
1302
+ * the placement calls for, such as the end of a Turn it superseded. A known
1303
+ * idempotency key writes nothing. Call it outside a transaction: it publishes
1304
+ * after its own commit, so a publish error leaves the input stored.
1340
1305
  */
1341
1306
  async function scheduleInput({ executor, queue }, input) {
1342
1307
  const placement = await withConversationEventLock(executor, input.conversationId, () => placeInput({ executor }, input));
1308
+ if (placement.ended) await publishTurnEnded({ queue }, {
1309
+ conversationId: input.conversationId,
1310
+ turnId: placement.ended
1311
+ });
1343
1312
  if (placement.publish) await publishTurnStep({ queue }, placement.turnId);
1344
1313
  return {
1345
1314
  turnId: placement.turnId,
@@ -1384,16 +1353,15 @@ async function endFailedTurn({ executor }, lease, endReason, failure, discarded)
1384
1353
  }));
1385
1354
  }
1386
1355
  /**
1387
- * Brings delivery and the queue in line with this Turn's stored state. Safe
1388
- * to repeat. It publishes the Turn's delivery message, then publishes the
1389
- * Conversation's open Turn if it is queued. What it does depends only on the
1390
- * stored state, not on why it runs. Call it outside a transaction, after the
1391
- * commit that it follows, so a worker that takes a message sees that commit.
1356
+ * Brings the queue in line with this Turn's stored state, so it is safe to
1357
+ * repeat: it says the Turn ended if it has, then publishes the Conversation's
1358
+ * open Turn if it is queued. Call it after the commit that it follows,
1359
+ * outside a transaction, so a worker that takes a message sees that commit.
1392
1360
  */
1393
1361
  async function reconcileTurn({ executor, queue }, turnId) {
1394
1362
  const turn = await findTurn({ executor }, turnId);
1395
1363
  if (!turn) return;
1396
- await publishDelivery({ queue }, {
1364
+ if (turn.state !== "queued" && turn.state !== "running") await publishTurnEnded({ queue }, {
1397
1365
  conversationId: turn.conversationId,
1398
1366
  turnId
1399
1367
  });
@@ -1439,10 +1407,19 @@ async function requestModel({ systemPrompt, messages, model }, { client, session
1439
1407
  outcome: "continue",
1440
1408
  messages: [reply]
1441
1409
  };
1442
- if (reply.stopReason === "stop" || reply.stopReason === "length") return {
1410
+ if (reply.stopReason === "stop") return {
1443
1411
  outcome: "completed",
1444
1412
  messages: [reply]
1445
1413
  };
1414
+ if (reply.stopReason === "length") return {
1415
+ outcome: "failed",
1416
+ reply,
1417
+ failure: {
1418
+ kind: "cut_off_output",
1419
+ retryable: false,
1420
+ message: "The reply hit the output token limit"
1421
+ }
1422
+ };
1446
1423
  return {
1447
1424
  outcome: "failed",
1448
1425
  reply,
@@ -1689,14 +1666,18 @@ async function runClaimedStep({ executor, queue }, claim, unread, { client, prom
1689
1666
  const discarded = (agentTurnTotalTokens(usage) ?? 0) > 0 || (agentTurnCostUsd(usage) ?? 0) > 0 ? usage : void 0;
1690
1667
  const delayMs = modelRetryDelayMs(result.failure, claim.attempts, maxAttempts);
1691
1668
  if (delayMs !== void 0) {
1692
- if (await releaseTurn({ executor }, claim, discarded)) {
1669
+ const released = await releaseTurn({ executor }, claim, discarded);
1670
+ if (released === "queued") {
1693
1671
  await publishTurnStep({ queue }, claim.turnId, { delayMs });
1694
1672
  logWarn("agent.turn.provider.retrying", {
1695
1673
  ...modelFailureAttributes(result.failure),
1696
1674
  "app.ai.provider_error.retry_attempt": claim.attempts,
1697
1675
  "app.turn.id": claim.turnId
1698
1676
  });
1699
- }
1677
+ } else if (released) await reconcileTurn({
1678
+ executor,
1679
+ queue
1680
+ }, claim.turnId);
1700
1681
  return;
1701
1682
  }
1702
1683
  const failure = captureModelFailure(result.failure);
@@ -1896,6 +1877,22 @@ async function turnStepConsumer(engineCtx, { client, bot, tools }) {
1896
1877
  maxAttempts: MAX_ATTEMPTS
1897
1878
  }));
1898
1879
  }
1880
+ // src/turn-steps/usage.ts
1881
+ /**
1882
+ * Sums the usage of the model replies in `history`, the Turn's own history,
1883
+ * and of the replies that the Turn paid for but dropped.
1884
+ */
1885
+ async function turnUsage(ctx, turnId, history) {
1886
+ const kept = extractGenAiUsageSummary(...history.filter((message) => message.role === "assistant"));
1887
+ const discarded = await findDiscardedUsage(ctx, turnId);
1888
+ const { cost: _, ...tokens } = addAgentTurnUsage(kept, discarded?.tokens) ?? {};
1889
+ const keptCostUsd = agentTurnCostUsd(kept);
1890
+ if (keptCostUsd === void 0 && !discarded?.costMicroUsd) return tokens;
1891
+ return {
1892
+ ...tokens,
1893
+ cost: { total: (keptCostUsd ?? 0) + microUsdToUsd(discarded?.costMicroUsd ?? 0) }
1894
+ };
1895
+ }
1899
1896
  // src/turn-steps/limits.ts
1900
1897
  const WRAPPED_UP = "wrapped_up";
1901
1898
  /**
@@ -1905,11 +1902,9 @@ const WRAPPED_UP = "wrapped_up";
1905
1902
  */
1906
1903
  async function checkTurnLimits(ctx, turnId, calls) {
1907
1904
  const history = await loadTurnAgentHistory(ctx, turnId);
1908
- const replies = history.filter((message) => message.role === "assistant");
1909
- const toolCallCount = replies.flatMap((reply) => reply.content).filter((part) => part.type === "toolCall").length;
1905
+ const toolCallCount = history.filter((message) => message.role === "assistant").flatMap((reply) => reply.content).filter((part) => part.type === "toolCall").length;
1910
1906
  const results = history.filter((message) => message.role === "toolResult");
1911
- const discarded = await findDiscardedUsage(ctx, turnId);
1912
- const costUsd = (agentTurnCostUsd(extractGenAiUsageSummary(...replies)) ?? 0) + microUsdToUsd(discarded?.costMicroUsd ?? 0);
1907
+ const costUsd = agentTurnCostUsd(await turnUsage(ctx, turnId, history)) ?? 0;
1913
1908
  const overBudget = costUsd >= botConfig.maxTurnCostUsd;
1914
1909
  const overToolCalls = toolCallCount > botConfig.maxToolCallsPerTurn;
1915
1910
  const attributes = {
@@ -2059,4 +2054,4 @@ function createEngineContext(config) {
2059
2054
  leaseMs: config.functionMaxDurationSeconds * 1e3
2060
2055
  };
2061
2056
  }
2062
- export { scheduleInput as a, replyText as c, publishTurnStep as d, countMetric as f, turnStepConsumer as i, createDeliveryConsumer as l, turnTools as n, findStalledTurns as o, withSpan as p, createGatewayModelClient as r, findStalledDeliveries as s, createEngineContext as t, publishDelivery as u };
2057
+ export { turnStepConsumer as a, findTurn as c, readTurnEndedMessages as d, publishTurnStep as f, withSpan as g, countMetric as h, createGatewayModelClient as i, replyText as l, loadTurnAgentHistory as m, turnTools as n, scheduleInput as o, findTurnActor as p, turnUsage as r, findStalledTurns as s, createEngineContext as t, publishTurnEnded as u };
@@ -1,9 +1,7 @@
1
- import { L as botConfig } from "./context-BKF_5zzI.js";
2
- import { nc as deleteProviderIdentityForSlackUser, o as getSqlExecutor, rc as deleteProviderIdentityForUser } from "./db-of6e3sGt.js";
3
- import { G as mapBounded } from "./prompt-DEkStuxG.js";
4
- import { ii as startOAuthFlow } from "./mailbox-turn-Byrry9o1.js";
5
- import { S as deleteMcpStoredOAuthCredentials, b as deleteMcpAuthSessionsForUserProvider, m as hasRequiredOAuthScope, x as deleteMcpServerSessionId } from "./registry-Cl7Labpe.js";
6
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BfdAnztW.js";
1
+ import { L as botConfig } from "./adapter-8_S6Birm.js";
2
+ import { Cc as deleteProviderIdentityForUser, Fd as getAppContext, Sc as deleteProviderIdentityForSlackUser, Xd as hasRequiredOAuthScope, if as deleteMcpStoredOAuthCredentials, nf as deleteMcpAuthSessionsForUserProvider, o as getSqlExecutor, rf as deleteMcpServerSessionId } from "./db-BCaNWl9p.js";
3
+ import { G as mapBounded } from "./prompt-3TqxEOtc.js";
4
+ import { di as startOAuthFlow } from "./markers-9QoqW5ov.js";
7
5
  import { randomBytes } from "node:crypto";
8
6
  // src/handlers/oauth-html.ts
9
7
  /** Build pre-escaped callback HTML with the shared response security policy. */
@@ -188,12 +186,12 @@ async function readConnectedOAuthTokens(userId, plugin, userTokenStore) {
188
186
  return stored && hasRequiredOAuthScope(stored.scope, plugin.manifest.oauth?.scope) ? stored : void 0;
189
187
  }
190
188
  function connectablePlugin(provider) {
191
- const plugin = pluginCatalogRuntime.getDefinition(provider);
189
+ const plugin = getAppContext().catalog.getDefinition(provider);
192
190
  return plugin?.manifest.oauth ? plugin : void 0;
193
191
  }
194
192
  /** List OAuth plugins and the user's connection state for each one. */
195
193
  async function listConnections(userId, userTokenStore) {
196
- const plugins = pluginCatalogRuntime.getProviders().filter((plugin) => Boolean(plugin.manifest.oauth));
194
+ const plugins = getAppContext().catalog.getProviders().filter((plugin) => Boolean(plugin.manifest.oauth));
197
195
  return await mapBounded(plugins, async (plugin) => {
198
196
  const tokens = await readConnectedOAuthTokens(userId, plugin, userTokenStore);
199
197
  const account = tokens?.account;
@@ -1,10 +1,10 @@
1
1
  import { a as getClient, c as init, i as getActiveSpan, o as getGlobalScope, p as spanToJSON, s as getTraceData, u as sentry_exports } from "./sentry-CPbZjomA.js";
2
- import { n as getCurrentConversationPrivacy } from "./conversation-privacy-Cr_dNW1p.js";
2
+ import { n as getCurrentConversationPrivacy } from "./conversation-privacy-C2vYK55O.js";
3
3
  import { n as isPushServiceHost } from "./push-endpoint-CO-nomUd.js";
4
4
  import { n as redactSandboxEgressProxyPath } from "./proxy-path-BHYoKZdq.js";
5
5
  import { n as promoteHttpRouteName, r as routeNameMiddleware, t as nameRequestRoute } from "./sentry-route-name-C6EIzAGP.js";
6
6
  import { t as consumePrivateTraceResultMarker } from "./private-trace-result-CE7_lEdq.js";
7
- import { _ as getDeploymentTelemetryAttributes, g as getDeploymentServiceVersion } from "./deployment-C0qXa0FD.js";
7
+ import { _ as getDeploymentTelemetryAttributes, g as getDeploymentServiceVersion } from "./deployment-CfOew1Tm.js";
8
8
  import { performance } from "node:perf_hooks";
9
9
  import { subscribe, unsubscribe } from "node:diagnostics_channel";
10
10
  // src/chat/pi/gateway-request-timing.ts
@@ -99,27 +99,11 @@ function createGatewayRequestTimingHandlers() {
99
99
  };
100
100
  }
101
101
  /**
102
- * Subscribes to undici's diagnostics channels and writes the HTTP phases of
103
- * AI Gateway model requests onto their `gen_ai.chat` span. Telemetry must not
104
- * fail a request, so handler errors are dropped. Returns a function that
105
- * removes the subscriptions.
106
- *
107
- * To find where time went before the gateway saw a request, get the gateway
108
- * latency for `gen_ai.response.id` from the AI Gateway generation API, then
109
- * compare the phases:
110
- * - High `queue_ms` on a reused socket, or high
111
- * `app.ai.event_loop.utilization`: the process was busy or the pool was
112
- * full. With a new socket, `queue_ms` includes the connect time.
113
- * - High `connect_ms`: DNS, TCP, or TLS was slow. It is absent on a reused
114
- * socket. It is best effort: overlapping connects to the same host usually
115
- * record none.
116
- * - High `body_send_ms`: the upload was slow.
117
- * - `response_wait_ms` much larger than the gateway time to first token,
118
- * with small Junior phases: the delay was in the network or at the Vercel
119
- * edge. The gateway sends headers with the first token. Give Vercel
120
- * `app.ai.gateway.vercel_id`.
121
- * - The same `service.instance.id` on more than one slow call: they shared
122
- * one process.
102
+ * Writes the undici HTTP phases of AI Gateway requests onto their `gen_ai.chat`
103
+ * span and returns an unsubscribe function. Handler errors are dropped, so
104
+ * telemetry never fails a request. On a new socket `queue_ms` holds connect
105
+ * time, and `connect_ms` is best effort. The gateway sends headers with the
106
+ * first token, so a long `response_wait_ms` points at the network or edge.
123
107
  */
124
108
  function subscribeGatewayRequestTiming() {
125
109
  const handlers = Object.entries(createGatewayRequestTimingHandlers()).map(([name, handler]) => [name, (message) => {