@sentry/junior 0.318.0 → 0.320.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 (94) hide show
  1. package/dist/{context-BKF_5zzI.js → adapter-DlLLoJKj.js} +537 -537
  2. package/dist/{admin-UOHix_5P.js → admin-BzRXDVfh.js} +1 -1
  3. package/dist/{agent-runner-DeYymwh2.js → agent-DxZ7nHfD.js} +19866 -6720
  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-CO4FU5Gg.js} +4 -5
  6. package/dist/api/schema.d.ts +45 -23
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +79 -84
  9. package/dist/{app-DKAOuaoC.d.ts → app-CHCFIIDu.d.ts} +5 -4
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +119 -194
  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-BghWqlXx.js} +1 -1
  14. package/dist/{chat-core-engine-D3Wd7f5n.js → chat-core-engine-BgfSLrDu.js} +31 -14
  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-DBlQP4PC.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-qoh95v90.js} +1 -1
  27. package/dist/{create-Btl1y1rq.js → create-jZSaDrCR.js} +115 -5
  28. package/dist/{credential-sync-DTarZ63K.js → credential-sync-Bj9-UlNE.js} +15 -18
  29. package/dist/{db-of6e3sGt.js → db-BacvswT0.js} +4602 -727
  30. package/dist/{deployment-C0qXa0FD.js → deployment-BoJkRPDt.js} +3 -3
  31. package/dist/{engine-context-C_QL_bMQ.js → engine-context-Bi3Ync5t.js} +521 -150
  32. package/dist/{html-9_pS9SjY.js → html-DW0pw5Pr.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-Dz3CdP3g.js +5016 -0
  35. package/dist/{logging-BnOG0qz2.js → logging-DsTnMqyi.js} +8 -33
  36. package/dist/{mailbox-turn-Byrry9o1.js → markers-C33gNYNE.js} +1705 -1284
  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-C-pEhAQK.js} +2 -2
  40. package/dist/{oauth-relay-BvHFH0fV.js → oauth-relay-DIXdH-io.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-iHw1uu32.js → profile-v9vA3RvH.js} +16 -18
  43. package/dist/{prompt-DEkStuxG.js → prompt-C5CW2wKO.js} +1 -1
  44. package/dist/{reports-C1d9azyV.js → reports-eBgrhPXS.js} +2 -2
  45. package/dist/{resolve-DC6zBuDV.js → resolve-HVXmbeCr.js} +5 -5
  46. package/dist/{result-DxewDuXb.js → result-BPNzgeTl.js} +20 -9
  47. package/dist/{runner-99YxVN_r.js → runner-aNSDTST6.js} +7 -8
  48. package/dist/{sandbox-egress-signals-CgoX5CTI.js → sandbox-egress-signals-nzp9Ykf7.js} +1 -1
  49. package/dist/{schema-BTojNBr5.js → schema-BlTO5M1d.js} +16 -8
  50. package/dist/{service-account-YDCPSByj.js → service-account-DWIf1t6p.js} +4 -5
  51. package/dist/{skills-CleC0Hze.js → skills-50izzzdK.js} +9 -9
  52. package/dist/{slack-conversation-unfurl-BNQLC12R.js → slack-conversation-unfurl-C6jXhVYg.js} +7 -7
  53. package/dist/storage-BtCxXiNt.js +273 -0
  54. package/dist/{system-prompt-table-Ci6Ck4gk.js → system-prompt-table-CIR1B44Z.js} +27 -85
  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-DOVo9sdU.js} +1 -1
  59. package/dist/{validation-BiUmWPhy.js → validation-CK0vuEHB.js} +4 -4
  60. package/dist/{version-VEXiEcZu.js → version-BuLVNlxB.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-ChWYQdhm.js → worker-C82kHU1R.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/migrations/20261127150242_drop_space_members/migration.sql +9 -0
  74. package/migrations/20261127150242_drop_space_members/snapshot.json +53 -0
  75. package/package.json +9 -7
  76. package/dist/auth-pause-state-f9hJM_zO.js +0 -113
  77. package/dist/catalog-runtime-BfdAnztW.js +0 -6
  78. package/dist/child-message-peFWLcCZ.js +0 -15
  79. package/dist/conversation-turn-Bru4w_FD.js +0 -1250
  80. package/dist/job-runner-B2XEvpif.js +0 -1505
  81. package/dist/lineage-nh4z9iQN.js +0 -36
  82. package/dist/list-HRP3TIRl.js +0 -12631
  83. package/dist/markers-CTTtJqYn.js +0 -342
  84. package/dist/message-BRUuLgrY.js +0 -153
  85. package/dist/model-input-CFC62mf-.js +0 -82
  86. package/dist/registry-Cl7Labpe.js +0 -3279
  87. package/dist/run-conversation-Cz2ubZK-.js +0 -337
  88. package/dist/sender-actors-77zTQbSG.js +0 -84
  89. package/dist/spawn-DuZfodPa.js +0 -45
  90. package/dist/task-runner-BJ9Up3bG.js +0 -1529
  91. package/dist/topic-CRYYBYp-.js +0 -7
  92. package/dist/topics-BoCkoPJJ.js +0 -21
  93. package/dist/turn-membership-VT7XZh-L.js +0 -856
  94. package/dist/turn-wake-C7HeLHAM.js +0 -151
@@ -1,14 +1,13 @@
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-DlLLoJKj.js";
2
+ import { $a as usdToMicroUsd, Ed as getGatewayApiKey, Ff as agentTurnCostUsd, Gr as QUEUE_SIGNATURE_MAX_AGE_MS, If as agentTurnTotalTokens, Jr as getQueueProvider, Kr as signQueueMessage, M as locationSchema, N as claimProviderConversation, O as withConversationMutationLock, Op as juniorConversationEvents, Pf as addAgentTurnUsage, Qa as microUsdToUsd, Qn as sendSlackReply, R as replaceConversationMetrics, _ as unseenEvents, a as getDb, d as createSqlConversationEventStore, ep as juniorTurnOutbox, g as readEventCursor, h as insertEventRows, j as startLocationThread, js as resolveRootVisibility, kp as juniorTurns, md as gatewayRoutingAttributes, o as getSqlExecutor, qr as verifyQueueMessage, sd as requestPrefixAttributes, ti as runWithSlackInstallation, tp as juniorTurnInbox, v as withConversationEventLock, zp as juniorConversations } from "./db-BacvswT0.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-DsTnMqyi.js";
5
+ import { h as SERVICE_INSTANCE_ID } from "./deployment-BoJkRPDt.js";
6
+ import { G as mapBounded } from "./prompt-C5CW2wKO.js";
7
+ import { a as toCanonicalInputMessage, o as toCanonicalOutputMessage, r as resolveConversationPrivacy, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-qoh95v90.js";
8
+ import { $n as normalizeConversationText, Br as TurnToolCallLimitExceededError, Fr as turnTerminalKey, J as getPersistedThreadState, K as getLocationConfigurationService, Lr as TURN_LIMIT_WRAP_UP_MESSAGE, Pr as turnStartedKey, Rr as TurnBudgetExceededError, Wn as toStoredConversationMessage, Y as persistThreadRuntimeState, Zt as getWorkspace, dn as buildDeploymentSystemPrompt, q as getPersistedSandboxState, ti as reviewToolActions } from "./markers-C33gNYNE.js";
9
+ import { A as createBashTool, D as createWriteFileTool, E as createSystemTimeTool, O as createReadFileTool, c as createAgentSandbox, dn as isRetryableSlackPostError, k as createEditFileTool, l as normalizeToolResult, n as buildSandboxInput, u as capToolResult } from "./agent-DxZ7nHfD.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";
@@ -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) {
@@ -700,6 +658,7 @@ async function findUnreadInputs({ executor }, turnId) {
700
658
  const readEvent = db.select({ one: sql`1` }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, juniorTurnInbox.conversationId), eq(juniorConversationEvents.idempotencyKey, sql`${INPUT_EVENT_KEY_PREFIX}::text || ${juniorTurnInbox.id}::text`)));
701
659
  return db.select({
702
660
  inputId: juniorTurnInbox.id,
661
+ actorIdentityId: juniorTurnInbox.actorIdentityId,
703
662
  groupKey: juniorTurnInbox.groupKey,
704
663
  payload: juniorTurnInbox.payload,
705
664
  sentAt: juniorTurnInbox.sentAt,
@@ -806,17 +765,17 @@ async function publishTurnStep(ctx, turnId, options = {}) {
806
765
  function createTurnStepConsumer(ctx, run) {
807
766
  return turnStepTopic.consumer(ctx, (message, metadata) => run({ turnId: message.turnId }, metadata));
808
767
  }
809
- // src/core/delivery/queue.ts
810
- const deliveryMessageSchema = z.object({
768
+ // src/core/turn/ended.ts
769
+ const turnEndedMessageSchema = z.object({
811
770
  conversationId: z.string().min(1),
812
771
  turnId: z.string().min(1),
813
772
  traceContext: z.object({ sentryTrace: z.string().min(1) }).strict().optional()
814
773
  }).strict();
815
- const deliveryTopic = signedTopic({
816
- topic: DELIVERY_TOPIC,
774
+ const turnEndedTopic = signedTopic({
775
+ topic: TURN_ENDED_TOPIC,
817
776
  sign: {
818
- context: "junior.delivery.v1",
819
- schema: deliveryMessageSchema,
777
+ context: "junior.turn_ended.v1",
778
+ schema: turnEndedMessageSchema,
820
779
  signatureVersion: "v1",
821
780
  parts: (message) => [
822
781
  message.conversationId,
@@ -824,24 +783,27 @@ const deliveryTopic = signedTopic({
824
783
  message.traceContext?.sentryTrace ?? ""
825
784
  ]
826
785
  },
827
- onRejected: (attributes) => logWarn("turn.delivery.queue_message.rejected", attributes),
786
+ onRejected: (attributes) => logWarn("turn.ended.queue_message.rejected", attributes),
828
787
  attributes: (message) => ({
829
788
  "app.turn.id": message.turnId,
830
789
  "gen_ai.conversation.id": message.conversationId
831
790
  })
832
791
  });
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);
792
+ /**
793
+ * Sends the message that the Turn ended, after `delayMs` if set. A handler
794
+ * that must try its work again later sends it again with a delay.
795
+ */
796
+ async function publishTurnEnded(ctx, message, options = {}) {
797
+ await turnEndedTopic.publish(ctx, message, options);
836
798
  }
837
799
  /**
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.
800
+ * Reads the messages that a Turn ended: it checks that core sent each one,
801
+ * then calls `handle`. It acknowledges a message with a bad or expired
802
+ * signature and retries one that cannot be checked yet. The host mounts the
803
+ * consumer on its queue provider.
842
804
  */
843
- function createDeliveryConsumer(ctx, run) {
844
- return deliveryTopic.consumer(ctx, (message, metadata) => run({
805
+ function readTurnEndedMessages(ctx, handle) {
806
+ return turnEndedTopic.consumer(ctx, (message, metadata) => handle({
845
807
  conversationId: message.conversationId,
846
808
  turnId: message.turnId
847
809
  }, metadata));
@@ -912,7 +874,7 @@ function replyText(row) {
912
874
  async function findTurnReplies({ executor }, conversationId, turnId) {
913
875
  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
876
  }
915
- // src/core/delivery/outbox.ts
877
+ // src/core/turn/outbox.ts
916
878
  /**
917
879
  * Adds an outbox row for each reply of the Turn that has none, but only while
918
880
  * the Turn has a Destination. Call it in the transaction that commits the
@@ -932,26 +894,6 @@ async function recordReplies({ executor }, turn) {
932
894
  state: "pending"
933
895
  }))).onConflictDoNothing({ target: [juniorTurnOutbox.conversationId, juniorTurnOutbox.eventSeq] });
934
896
  }
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
897
  // src/core/turn/state.ts
956
898
  /**
957
899
  * Turn priorities: a lower number runs first. A Turn that supersedes the
@@ -996,7 +938,9 @@ async function findTurn({ executor }, turnId) {
996
938
  conversationId: juniorTurns.conversationId,
997
939
  failureCode: juniorTurns.failureCode,
998
940
  failureReason: juniorTurns.failureReason,
999
- failureEventId: juniorTurns.failureEventId
941
+ failureEventId: juniorTurns.failureEventId,
942
+ startedAt: juniorTurns.startedAt,
943
+ endedAt: juniorTurns.endedAt
1000
944
  }).from(juniorTurns).where(eq(juniorTurns.id, turnId));
1001
945
  return turn;
1002
946
  }
@@ -1067,27 +1011,30 @@ async function isSuperseded({ executor }, turnId) {
1067
1011
  }
1068
1012
  /**
1069
1013
  * 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.
1014
+ * Conversation lock. A queued Turn has no step in flight, so it ends now and
1015
+ * moves `lease_epoch`. A running Turn moves behind the new Turn, and
1016
+ * `commitStep` or `releaseTurn` ends it, so the step's work is kept. True
1017
+ * when the Turn ended now.
1073
1018
  */
1074
1019
  async function supersedeTurn({ executor }, turnId) {
1075
1020
  const db = executor.db();
1076
- await db.update(juniorTurns).set({
1021
+ const ended = await db.update(juniorTurns).set({
1077
1022
  ...SUPERSEDED_END,
1078
1023
  leaseEpoch: sql`${juniorTurns.leaseEpoch} + 1`,
1079
1024
  updatedAt: sql`now()`
1080
- }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued")));
1025
+ }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "queued"))).returning({ id: juniorTurns.id });
1081
1026
  await db.update(juniorTurns).set({
1082
1027
  priority: TURN_PRIORITY.normal,
1083
1028
  updatedAt: sql`now()`
1084
1029
  }).where(and(eq(juniorTurns.id, turnId), eq(juniorTurns.state, "running")));
1030
+ return ended.length > 0;
1085
1031
  }
1086
1032
  /**
1087
1033
  * 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.
1034
+ * a running Turn whose lease expired, so the queue's redelivery after a crash
1035
+ * resumes it. Any other Turn gets undefined, so one of two racing claims wins,
1036
+ * and a Conversation runs one Turn at a time, in order. Each claim moves
1037
+ * `lease_epoch` and `attempts` and holds the Conversation lock.
1091
1038
  */
1092
1039
  async function claimTurn({ executor, owner, leaseMs }, turnId) {
1093
1040
  const turn = await findTurn({ executor }, turnId);
@@ -1160,15 +1107,11 @@ function promptEventKey(turnId, stepSeq, index) {
1160
1107
  return `prompt:${turnId}:${stepSeq}:${index}`;
1161
1108
  }
1162
1109
  /**
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.
1110
+ * Commits a step in one transaction: appends the prompt's new messages, with
1111
+ * the inputs the step read, then the step's messages to history, adds an
1112
+ * outbox row per new reply, and releases the lease. A Turn that continues
1113
+ * queues for a new claim. A `stale` final reply is not committed. Undefined,
1114
+ * with no write, when the lease is lost or the step is already committed.
1172
1115
  */
1173
1116
  async function commitStep({ executor }, turn, step, prompt) {
1174
1117
  const nextStep = {
@@ -1180,6 +1123,7 @@ async function commitStep({ executor }, turn, step, prompt) {
1180
1123
  };
1181
1124
  return executor.transaction(() => withConversationEventLock(executor, turn.conversationId, async () => {
1182
1125
  const outcome = await commitOutcome({ executor }, turn.turnId, step, prompt);
1126
+ if (outcome === "stale") return await requeueStep({ executor }, turn, step) ? outcome : void 0;
1183
1127
  if ((await executor.db().update(juniorTurns).set(outcome === "completed" ? {
1184
1128
  ...nextStep,
1185
1129
  state: "completed",
@@ -1211,19 +1155,41 @@ async function commitStep({ executor }, turn, step, prompt) {
1211
1155
  /**
1212
1156
  * A completed step ends the Turn only when the commit reads every unread
1213
1157
  * input. The scheduler can add an input after the step read them, and the
1214
- * Conversation lock keeps more out until the commit ends.
1158
+ * Conversation lock keeps more out until the commit ends. A final reply that
1159
+ * missed an input is `stale`, so the Turn ends with one reply to every input.
1215
1160
  */
1216
1161
  async function commitOutcome({ executor }, turnId, step, prompt) {
1217
1162
  if (step.outcome === "completed") {
1218
1163
  const read = new Set(prompt.flatMap((entry) => entry.source === "input" ? [entry.inputId] : []));
1219
1164
  if ((await findUnreadInputs({ executor }, turnId)).every((input) => read.has(input.inputId))) return "completed";
1220
1165
  }
1221
- return await isSuperseded({ executor }, turnId) ? "superseded" : "continue";
1166
+ if (await isSuperseded({ executor }, turnId)) return "superseded";
1167
+ return step.outcome === "completed" && finalReplyOf(step) ? "stale" : "continue";
1168
+ }
1169
+ function finalReplyOf(step) {
1170
+ const [message] = step.messages;
1171
+ return message?.role === "assistant" ? message : void 0;
1172
+ }
1173
+ /**
1174
+ * Queues the Turn for the same step again, with nothing committed, after a
1175
+ * stale final reply. The attempt does not count: the step did not fail. The
1176
+ * dropped reply's usage adds to the Turn's discarded usage.
1177
+ */
1178
+ async function requeueStep({ executor }, turn, step) {
1179
+ return (await executor.db().update(juniorTurns).set({
1180
+ ...await discardedUsageUpdate({ executor }, turn, extractGenAiUsageSummary(finalReplyOf(step))),
1181
+ state: "queued",
1182
+ attempts: 0,
1183
+ leaseOwner: null,
1184
+ leaseExpiresAt: null,
1185
+ updatedAt: sql`now()`
1186
+ }).where(and(leaseFence(turn), eq(juniorTurns.conversationId, turn.conversationId), eq(juniorTurns.stepSeq, turn.stepSeq))).returning({ id: juniorTurns.id })).length > 0;
1222
1187
  }
1223
1188
  /**
1224
1189
  * 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.
1190
+ * `discarded` is the usage of the model reply that the step drops. False when
1191
+ * the lease is lost. The engine calls it through `endFailedTurn`, which also
1192
+ * moves the Turn's late inputs.
1227
1193
  */
1228
1194
  async function failTurn({ executor }, lease, endReason, failure, discarded) {
1229
1195
  return (await executor.db().update(juniorTurns).set({
@@ -1243,8 +1209,8 @@ async function failTurn({ executor }, lease, endReason, failure, discarded) {
1243
1209
  * Queues a running Turn again after its invocation failed, so the queue's
1244
1210
  * retry can claim the step at once. The failed attempt still counts. A Turn
1245
1211
  * 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.
1212
+ * the usage of the failed model reply that the retry drops. Returns the
1213
+ * Turn's new state, or undefined when the lease is lost.
1248
1214
  */
1249
1215
  async function releaseTurn({ executor }, lease, discarded) {
1250
1216
  return executor.transaction(() => withConversationEventLock(executor, lease.conversationId, async () => {
@@ -1260,7 +1226,7 @@ async function releaseTurn({ executor }, lease, discarded) {
1260
1226
  } : {
1261
1227
  ...released,
1262
1228
  state: "queued"
1263
- }).where(leaseFence(lease)).returning({ id: juniorTurns.id })).length > 0;
1229
+ }).where(leaseFence(lease)).returning({ state: juniorTurns.state }))[0]?.state;
1264
1230
  }));
1265
1231
  }
1266
1232
  // src/core/turn/schedule.ts
@@ -1316,7 +1282,7 @@ async function placeInput({ executor }, { delivery, ...input }) {
1316
1282
  publish: false
1317
1283
  };
1318
1284
  }
1319
- if (choice.supersede) await supersedeTurn({ executor }, choice.supersede.turnId);
1285
+ const ended = choice.supersede && await supersedeTurn({ executor }, choice.supersede.turnId) ? choice.supersede.turnId : void 0;
1320
1286
  const turn = await createTurn({ executor }, {
1321
1287
  conversationId: input.conversationId,
1322
1288
  priority: choice.create.priority
@@ -1328,18 +1294,22 @@ async function placeInput({ executor }, { delivery, ...input }) {
1328
1294
  return {
1329
1295
  turnId: turn.turnId,
1330
1296
  created: true,
1331
- publish: openTurns.length === 0 || choice.supersede !== void 0
1297
+ publish: openTurns.length === 0 || choice.supersede !== void 0,
1298
+ ended
1332
1299
  };
1333
1300
  }
1334
1301
  /**
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.
1302
+ * Puts an input into the Turn that `assignTurn` picks, then publishes what
1303
+ * the placement calls for, such as the end of a Turn it superseded. A known
1304
+ * idempotency key writes nothing. Call it outside a transaction: it publishes
1305
+ * after its own commit, so a publish error leaves the input stored.
1340
1306
  */
1341
1307
  async function scheduleInput({ executor, queue }, input) {
1342
1308
  const placement = await withConversationEventLock(executor, input.conversationId, () => placeInput({ executor }, input));
1309
+ if (placement.ended) await publishTurnEnded({ queue }, {
1310
+ conversationId: input.conversationId,
1311
+ turnId: placement.ended
1312
+ });
1343
1313
  if (placement.publish) await publishTurnStep({ queue }, placement.turnId);
1344
1314
  return {
1345
1315
  turnId: placement.turnId,
@@ -1384,16 +1354,15 @@ async function endFailedTurn({ executor }, lease, endReason, failure, discarded)
1384
1354
  }));
1385
1355
  }
1386
1356
  /**
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.
1357
+ * Brings the queue in line with this Turn's stored state, so it is safe to
1358
+ * repeat: it says the Turn ended if it has, then publishes the Conversation's
1359
+ * open Turn if it is queued. Call it after the commit that it follows,
1360
+ * outside a transaction, so a worker that takes a message sees that commit.
1392
1361
  */
1393
1362
  async function reconcileTurn({ executor, queue }, turnId) {
1394
1363
  const turn = await findTurn({ executor }, turnId);
1395
1364
  if (!turn) return;
1396
- await publishDelivery({ queue }, {
1365
+ if (turn.state !== "queued" && turn.state !== "running") await publishTurnEnded({ queue }, {
1397
1366
  conversationId: turn.conversationId,
1398
1367
  turnId
1399
1368
  });
@@ -1439,10 +1408,19 @@ async function requestModel({ systemPrompt, messages, model }, { client, session
1439
1408
  outcome: "continue",
1440
1409
  messages: [reply]
1441
1410
  };
1442
- if (reply.stopReason === "stop" || reply.stopReason === "length") return {
1411
+ if (reply.stopReason === "stop") return {
1443
1412
  outcome: "completed",
1444
1413
  messages: [reply]
1445
1414
  };
1415
+ if (reply.stopReason === "length") return {
1416
+ outcome: "failed",
1417
+ reply,
1418
+ failure: {
1419
+ kind: "cut_off_output",
1420
+ retryable: false,
1421
+ message: "The reply hit the output token limit"
1422
+ }
1423
+ };
1446
1424
  return {
1447
1425
  outcome: "failed",
1448
1426
  reply,
@@ -1644,7 +1622,8 @@ async function advanceTurn({ executor, queue, owner, leaseMs }, message, options
1644
1622
  throw error;
1645
1623
  }
1646
1624
  }
1647
- async function runClaimedStep({ executor, queue }, claim, unread, { client, prompt, modelSettings, tools, maxAttempts }) {
1625
+ async function runClaimedStep({ executor, queue }, claim, unread, { client, prompt, modelSettings, tools, maxAttempts, compat__inputsRead }) {
1626
+ if (unread.length > 0) await compat__inputsRead?.(claim, unread);
1648
1627
  const history = await loadAgentHistory({ executor }, claim.conversationId);
1649
1628
  setActiveSpanAttributes({
1650
1629
  "app.turn.step_seq": claim.stepSeq,
@@ -1689,14 +1668,18 @@ async function runClaimedStep({ executor, queue }, claim, unread, { client, prom
1689
1668
  const discarded = (agentTurnTotalTokens(usage) ?? 0) > 0 || (agentTurnCostUsd(usage) ?? 0) > 0 ? usage : void 0;
1690
1669
  const delayMs = modelRetryDelayMs(result.failure, claim.attempts, maxAttempts);
1691
1670
  if (delayMs !== void 0) {
1692
- if (await releaseTurn({ executor }, claim, discarded)) {
1671
+ const released = await releaseTurn({ executor }, claim, discarded);
1672
+ if (released === "queued") {
1693
1673
  await publishTurnStep({ queue }, claim.turnId, { delayMs });
1694
1674
  logWarn("agent.turn.provider.retrying", {
1695
1675
  ...modelFailureAttributes(result.failure),
1696
1676
  "app.ai.provider_error.retry_attempt": claim.attempts,
1697
1677
  "app.turn.id": claim.turnId
1698
1678
  });
1699
- }
1679
+ } else if (released) await reconcileTurn({
1680
+ executor,
1681
+ queue
1682
+ }, claim.turnId);
1700
1683
  return;
1701
1684
  }
1702
1685
  const failure = captureModelFailure(result.failure);
@@ -1807,6 +1790,47 @@ const turnInputPayloadSchema = z.object({
1807
1790
  text: z.string().min(1),
1808
1791
  actor: actorSchema
1809
1792
  }).strict();
1793
+ // src/turn-steps/compat__message-id.ts
1794
+ /** The visible message id of a core Turn's input, for main's readers. */
1795
+ function compat__personMessageId(inputId) {
1796
+ return `inbox:${inputId}`;
1797
+ }
1798
+ // src/turn-steps/compat__inputs-read.ts
1799
+ /**
1800
+ * Compat: writes the person's visible `message` event for each input that a
1801
+ * step reads, and at the Turn's first step its `turn_started` event with
1802
+ * those inputs. Idempotency keys make a second run write nothing.
1803
+ */
1804
+ async function compat__writeInputsRead({ executor }, turn, inputs) {
1805
+ const messages = inputs.map((input) => {
1806
+ const messageId = compat__personMessageId(input.inputId);
1807
+ return {
1808
+ idempotencyKey: `message:${messageId}`,
1809
+ createdAtMs: input.sentAt.getTime(),
1810
+ data: {
1811
+ type: "message",
1812
+ messageId,
1813
+ role: "user",
1814
+ text: turnInputPayloadSchema.parse(input.payload).text,
1815
+ authorIdentityId: input.actorIdentityId
1816
+ }
1817
+ };
1818
+ });
1819
+ const started = turn.stepSeq === 0 ? [{
1820
+ idempotencyKey: turnStartedKey(turn.turnId),
1821
+ createdAtMs: Date.now(),
1822
+ data: {
1823
+ type: "turn_started",
1824
+ turnId: turn.turnId,
1825
+ inputMessageIds: messages.map((message) => message.data.messageId),
1826
+ surface: await turnSurface({ executor }, turn.turnId)
1827
+ }
1828
+ }] : [];
1829
+ await executor.transaction(() => createSqlConversationEventStore(executor).append(turn.conversationId, [...messages, ...started]));
1830
+ }
1831
+ async function turnSurface({ executor }, turnId) {
1832
+ return (await findTurnDestination({ executor }, turnId))?.["platform"] === "slack" ? "slack" : "api";
1833
+ }
1810
1834
  // src/turn-steps/prompt.ts
1811
1835
  function formatInput(input) {
1812
1836
  const payload = turnInputPayloadSchema.parse(input.payload);
@@ -1893,9 +1917,26 @@ async function turnStepConsumer(engineCtx, { client, bot, tools }) {
1893
1917
  prompt,
1894
1918
  modelSettings,
1895
1919
  tools,
1896
- maxAttempts: MAX_ATTEMPTS
1920
+ maxAttempts: MAX_ATTEMPTS,
1921
+ compat__inputsRead: (turn, inputs) => compat__writeInputsRead(engineCtx, turn, inputs)
1897
1922
  }));
1898
1923
  }
1924
+ // src/turn-steps/usage.ts
1925
+ /**
1926
+ * Sums the usage of the model replies in `history`, the Turn's own history,
1927
+ * and of the replies that the Turn paid for but dropped.
1928
+ */
1929
+ async function turnUsage(ctx, turnId, history) {
1930
+ const kept = extractGenAiUsageSummary(...history.filter((message) => message.role === "assistant"));
1931
+ const discarded = await findDiscardedUsage(ctx, turnId);
1932
+ const { cost: _, ...tokens } = addAgentTurnUsage(kept, discarded?.tokens) ?? {};
1933
+ const keptCostUsd = agentTurnCostUsd(kept);
1934
+ if (keptCostUsd === void 0 && !discarded?.costMicroUsd) return tokens;
1935
+ return {
1936
+ ...tokens,
1937
+ cost: { total: (keptCostUsd ?? 0) + microUsdToUsd(discarded?.costMicroUsd ?? 0) }
1938
+ };
1939
+ }
1899
1940
  // src/turn-steps/limits.ts
1900
1941
  const WRAPPED_UP = "wrapped_up";
1901
1942
  /**
@@ -1905,11 +1946,9 @@ const WRAPPED_UP = "wrapped_up";
1905
1946
  */
1906
1947
  async function checkTurnLimits(ctx, turnId, calls) {
1907
1948
  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;
1949
+ const toolCallCount = history.filter((message) => message.role === "assistant").flatMap((reply) => reply.content).filter((part) => part.type === "toolCall").length;
1910
1950
  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);
1951
+ const costUsd = agentTurnCostUsd(await turnUsage(ctx, turnId, history)) ?? 0;
1913
1952
  const overBudget = costUsd >= botConfig.maxTurnCostUsd;
1914
1953
  const overToolCalls = toolCallCount > botConfig.maxToolCallsPerTurn;
1915
1954
  const attributes = {
@@ -2049,6 +2088,338 @@ async function turnTools(turn, inputs) {
2049
2088
  close: () => sandbox.close()
2050
2089
  };
2051
2090
  }
2091
+ // src/delivery/compat__turn-ended.ts
2092
+ const SENTRY_EVENT_ID = /^[a-f0-9]{32}$/i;
2093
+ /**
2094
+ * Compat: after the sender posted a reply, writes its visible
2095
+ * `message`, the `message_handled` events, and for Slack the thread claim.
2096
+ * Call it in the transaction that marks the reply sent.
2097
+ */
2098
+ async function compat__writeReplyDelivered({ executor }, args) {
2099
+ await createSqlConversationEventStore(executor).append(args.conversationId, await compatReplyEvents({ executor }, args.conversationId, args.turnId, [args.reply]));
2100
+ const { destination } = args.reply;
2101
+ if (destination?.platform !== "slack" || !args.providerConversationId) return;
2102
+ const binding = {
2103
+ conversationId: args.conversationId,
2104
+ provider: "slack",
2105
+ providerTenantId: destination.teamId,
2106
+ providerDestinationId: destination.channelId,
2107
+ providerConversationId: args.providerConversationId
2108
+ };
2109
+ if (await claimProviderConversation(executor, binding)) await startLocationThread(executor, binding);
2110
+ }
2111
+ /**
2112
+ * Compat: writes the end event of an ended Turn once its replies are
2113
+ * settled. A Turn with no Destination gets its reply messages here, in the
2114
+ * same commit and before the end. A Turn with a pending reply waits for the
2115
+ * Turn-ended message that its delivery sends again.
2116
+ */
2117
+ async function compat__writeTurnEnded({ executor }, message) {
2118
+ const turn = await findTurn({ executor }, message.turnId);
2119
+ const endedAt = turn?.endedAt;
2120
+ if (!turn || !endedAt || !turn.startedAt) return;
2121
+ const [pending] = await executor.db().select({ id: juniorTurnOutbox.id }).from(juniorTurnOutbox).where(and(eq(juniorTurnOutbox.turnId, turn.turnId), eq(juniorTurnOutbox.state, "pending"))).limit(1);
2122
+ if (pending) return;
2123
+ const replies = await findTurnReplies({ executor }, turn.conversationId, turn.turnId);
2124
+ const undelivered = await findTurnDestination({ executor }, turn.turnId) === null ? replies.flatMap((row) => {
2125
+ const text = replyText(row);
2126
+ return text ? [{
2127
+ eventSeq: row.seq,
2128
+ text,
2129
+ createdAtMs: row.createdAt.getTime()
2130
+ }] : [];
2131
+ }) : [];
2132
+ await executor.transaction(async () => createSqlConversationEventStore(executor).append(turn.conversationId, [...await compatReplyEvents({ executor }, turn.conversationId, turn.turnId, undelivered), compatEndEvent(turn, endedAt.getTime(), replies.length > 0)]));
2133
+ }
2134
+ /**
2135
+ * Main's events for delivered replies: each reply's `message` and its
2136
+ * `message_handled`, then `message_handled` for the Turn's input messages.
2137
+ * An input message is marked only once its `message` exists, because a
2138
+ * `message_handled` before its `message` breaks main's projection.
2139
+ */
2140
+ async function compatReplyEvents({ executor }, conversationId, turnId, replies) {
2141
+ if (replies.length === 0) return [];
2142
+ const inputMessageIds = (await findTurnInputs({ executor }, turnId)).map((input) => compat__personMessageId(input.inputId));
2143
+ const stored = await executor.db().select({ key: juniorConversationEvents.idempotencyKey }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.idempotencyKey, inputMessageIds.map((id) => `message:${id}`))));
2144
+ const storedKeys = new Set(stored.map((row) => row.key));
2145
+ const handledAtMs = Date.now();
2146
+ const handled = (messageId) => ({
2147
+ idempotencyKey: `message:${messageId}:handled`,
2148
+ createdAtMs: handledAtMs,
2149
+ data: {
2150
+ type: "message_handled",
2151
+ messageId
2152
+ }
2153
+ });
2154
+ return [...replies.flatMap((reply) => {
2155
+ const message = toStoredConversationMessage({
2156
+ id: `${turnId}:assistant:${reply.eventSeq}`,
2157
+ role: "assistant",
2158
+ text: normalizeConversationText(reply.text),
2159
+ createdAtMs: reply.createdAtMs,
2160
+ author: {
2161
+ userName: botConfig.userName,
2162
+ isBot: true
2163
+ },
2164
+ ...reply.destination?.platform === "slack" ? { meta: {
2165
+ source: "slack",
2166
+ ...reply.providerMessageId ? { slackTs: reply.providerMessageId } : void 0
2167
+ } } : void 0
2168
+ });
2169
+ return [{
2170
+ idempotencyKey: `message:${message.messageId}`,
2171
+ createdAtMs: message.createdAtMs,
2172
+ data: {
2173
+ type: "message",
2174
+ messageId: message.messageId,
2175
+ role: message.role,
2176
+ text: message.text,
2177
+ ...message.meta ? { meta: message.meta } : void 0
2178
+ }
2179
+ }, handled(message.messageId)];
2180
+ }), ...inputMessageIds.filter((id) => storedKeys.has(`message:${id}`)).map(handled)];
2181
+ }
2182
+ /** Main's end event of an ended Turn, from its core state. */
2183
+ function compatEndEvent(turn, endedAtMs, replied) {
2184
+ const base = {
2185
+ idempotencyKey: turnTerminalKey(turn.turnId),
2186
+ createdAtMs: endedAtMs
2187
+ };
2188
+ if (turn.state === "failed") return {
2189
+ ...base,
2190
+ data: {
2191
+ type: "turn_failed",
2192
+ turnId: turn.turnId,
2193
+ failureCode: turn.failureCode ?? "agent_run_failed",
2194
+ ...turn.failureReason ? { failureReason: turn.failureReason } : void 0,
2195
+ ...turn.failureEventId && SENTRY_EVENT_ID.test(turn.failureEventId) ? { eventId: turn.failureEventId } : void 0
2196
+ }
2197
+ };
2198
+ return {
2199
+ ...base,
2200
+ data: {
2201
+ type: "turn_completed",
2202
+ turnId: turn.turnId,
2203
+ outcome: turn.state === "cancelled" ? "cancelled" : replied ? "success" : "no_reply"
2204
+ }
2205
+ };
2206
+ }
2207
+ // src/delivery/deliver.ts
2208
+ /**
2209
+ * A send that failed but can work on a later try. The sender sets
2210
+ * `retryAfterMs` when the provider says when to try again.
2211
+ */
2212
+ var DeliveryRetryableError = class extends Error {
2213
+ retryAfterMs;
2214
+ constructor(message, options = {}) {
2215
+ super(message, { cause: options.cause });
2216
+ this.name = "DeliveryRetryableError";
2217
+ this.retryAfterMs = options.retryAfterMs;
2218
+ }
2219
+ };
2220
+ const LOCK_MISS_DELAY_MS = 1e3;
2221
+ const MAX_DELIVERY_ATTEMPTS = 5;
2222
+ const RETRY_BASE_DELAY_MS = 1e3;
2223
+ const RETRY_MAX_DELAY_MS = 6e4;
2224
+ const tryLockResultSchema = z.object({ rows: z.tuple([z.object({ locked: z.boolean() })]) });
2225
+ /**
2226
+ * Sends the Conversation's pending outbox rows in event order, each to the
2227
+ * Destination stored on its row. To try again later, it sends the message
2228
+ * that the Turn ended again, with a delay.
2229
+ */
2230
+ async function deliverTurn({ executor, queue }, message, delivery) {
2231
+ while (true) {
2232
+ const next = await executor.transaction(() => sendNextRow({ executor }, message.conversationId, delivery));
2233
+ if (next.kind === "idle") return;
2234
+ if (next.kind === "later") {
2235
+ await publishTurnEnded({ queue }, message, { delayMs: next.delayMs });
2236
+ return;
2237
+ }
2238
+ }
2239
+ }
2240
+ /**
2241
+ * Sends the Conversation's first pending row, if this transaction gets the
2242
+ * Conversation's lock and the row's Turn has ended. A retryable failure
2243
+ * leaves the row pending, so the rows after it wait.
2244
+ */
2245
+ async function sendNextRow({ executor }, conversationId, delivery) {
2246
+ const db = executor.db();
2247
+ if (!tryLockResultSchema.parse(await db.execute(sql`select pg_try_advisory_xact_lock(hashtext(${`junior:delivery:${conversationId}`})) as locked`)).rows[0].locked) return {
2248
+ kind: "later",
2249
+ delayMs: LOCK_MISS_DELAY_MS
2250
+ };
2251
+ const [row] = await db.select({
2252
+ id: juniorTurnOutbox.id,
2253
+ turnId: juniorTurnOutbox.turnId,
2254
+ eventSeq: juniorTurnOutbox.eventSeq,
2255
+ destination: juniorTurnOutbox.destination,
2256
+ attempts: juniorTurnOutbox.attempts,
2257
+ turnState: juniorTurns.state
2258
+ }).from(juniorTurnOutbox).innerJoin(juniorTurns, eq(juniorTurns.id, juniorTurnOutbox.turnId)).where(and(eq(juniorTurnOutbox.conversationId, conversationId), eq(juniorTurnOutbox.state, "pending"))).orderBy(asc(juniorTurnOutbox.eventSeq)).limit(1);
2259
+ if (!row || row.turnState === "queued" || row.turnState === "running") return { kind: "idle" };
2260
+ const markFailed = async (error) => {
2261
+ await db.update(juniorTurnOutbox).set({
2262
+ state: "failed",
2263
+ error,
2264
+ updatedAt: /* @__PURE__ */ new Date()
2265
+ }).where(eq(juniorTurnOutbox.id, row.id));
2266
+ return { kind: "settled" };
2267
+ };
2268
+ const parsed = destinationSchema.safeParse(row.destination);
2269
+ if (!parsed.success) {
2270
+ logException(parsed.error, "turn.delivery.failed", { "gen_ai.conversation.id": conversationId });
2271
+ return markFailed("The Destination is not valid");
2272
+ }
2273
+ const destination = parsed.data;
2274
+ const [event] = await db.select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.seq, row.eventSeq)));
2275
+ const text = event ? replyText(event) : void 0;
2276
+ if (!text) return markFailed("The event is not a reply");
2277
+ let result;
2278
+ try {
2279
+ result = await delivery.send({
2280
+ conversationId,
2281
+ destination,
2282
+ text
2283
+ });
2284
+ } catch (error) {
2285
+ const attempts = row.attempts + 1;
2286
+ if (error instanceof DeliveryRetryableError && attempts < MAX_DELIVERY_ATTEMPTS) {
2287
+ await db.update(juniorTurnOutbox).set({
2288
+ attempts,
2289
+ updatedAt: /* @__PURE__ */ new Date()
2290
+ }).where(eq(juniorTurnOutbox.id, row.id));
2291
+ return {
2292
+ kind: "later",
2293
+ delayMs: retryDelayMs(error, attempts)
2294
+ };
2295
+ }
2296
+ logException(error, "turn.delivery.failed", { "gen_ai.conversation.id": conversationId });
2297
+ await db.update(juniorTurnOutbox).set({
2298
+ state: "failed",
2299
+ attempts,
2300
+ error: error instanceof Error ? error.message : String(error),
2301
+ updatedAt: /* @__PURE__ */ new Date()
2302
+ }).where(eq(juniorTurnOutbox.id, row.id));
2303
+ return { kind: "settled" };
2304
+ }
2305
+ const now = /* @__PURE__ */ new Date();
2306
+ await db.update(juniorTurnOutbox).set({
2307
+ state: "sent",
2308
+ sentAt: now,
2309
+ updatedAt: now,
2310
+ providerMessageId: result.providerMessageId ?? null
2311
+ }).where(eq(juniorTurnOutbox.id, row.id));
2312
+ await compat__writeReplyDelivered({ executor }, {
2313
+ conversationId,
2314
+ turnId: row.turnId,
2315
+ reply: {
2316
+ eventSeq: row.eventSeq,
2317
+ text,
2318
+ createdAtMs: now.getTime(),
2319
+ destination,
2320
+ ...result.providerMessageId ? { providerMessageId: result.providerMessageId } : void 0
2321
+ },
2322
+ ...result.providerConversationId ? { providerConversationId: result.providerConversationId } : void 0
2323
+ });
2324
+ return { kind: "settled" };
2325
+ }
2326
+ /**
2327
+ * The wait before the next try of a retryable send. The cap keeps a row that
2328
+ * waits for its retry well inside the sweep's stale window.
2329
+ */
2330
+ function retryDelayMs(error, attempts) {
2331
+ return Math.min(error.retryAfterMs ?? RETRY_BASE_DELAY_MS * 2 ** (attempts - 1), RETRY_MAX_DELAY_MS);
2332
+ }
2333
+ // src/delivery/slack.ts
2334
+ /**
2335
+ * Creates the sender of replies to Slack Destinations. A Slack failure that a
2336
+ * later try can fix throws `DeliveryRetryableError`.
2337
+ */
2338
+ function createSlackSender(args) {
2339
+ return async (reply) => {
2340
+ const { channelId, teamId, threadTs } = reply.destination;
2341
+ let messageIds;
2342
+ try {
2343
+ messageIds = await runWithSlackInstallation({
2344
+ adapter: args.getSlackAdapter(),
2345
+ installation: { teamId },
2346
+ task: async () => sendSlackReply({
2347
+ channelId,
2348
+ threadTs,
2349
+ conversationId: reply.conversationId,
2350
+ formatting: {
2351
+ configuration: await getLocationConfigurationService({
2352
+ platform: "slack",
2353
+ teamId,
2354
+ channelId
2355
+ }).resolveValues(),
2356
+ teamId
2357
+ },
2358
+ text: reply.text
2359
+ })
2360
+ });
2361
+ } catch (error) {
2362
+ if (isRetryableSlackPostError(error)) throw new DeliveryRetryableError("Slack did not take the reply", { cause: error });
2363
+ throw error;
2364
+ }
2365
+ const providerMessageId = messageIds.at(-1);
2366
+ const providerConversationId = threadTs ? void 0 : messageIds[0];
2367
+ return {
2368
+ ...providerMessageId ? { providerMessageId } : void 0,
2369
+ ...providerConversationId ? { providerConversationId } : void 0
2370
+ };
2371
+ };
2372
+ }
2373
+ // src/turn-steps/metrics.ts
2374
+ /**
2375
+ * Writes the metrics of an ended Turn. A rerun replaces the same rows, so a
2376
+ * Turn counts once however often its Turn-ended message arrives. A Turn that
2377
+ * never ran or has not ended writes nothing.
2378
+ */
2379
+ async function recordTurnMetrics(ctx, message) {
2380
+ const turn = await findTurn(ctx, message.turnId);
2381
+ if (!turn?.startedAt || !turn.endedAt) return;
2382
+ const [history, actorIdentityId] = await Promise.all([loadTurnAgentHistory(ctx, message.turnId), findTurnActor(ctx, message.turnId)]);
2383
+ const usage = await turnUsage(ctx, message.turnId, history);
2384
+ const { startedAt, endedAt } = turn;
2385
+ await withConversationMutationLock(ctx.executor, message.conversationId, () => replaceConversationMetrics(ctx.executor, {
2386
+ actorIdentityId,
2387
+ conversationId: message.conversationId,
2388
+ runId: message.turnId,
2389
+ occurredAtMs: startedAt.getTime(),
2390
+ updatedAtMs: endedAt.getTime(),
2391
+ durationMs: endedAt.getTime() - startedAt.getTime(),
2392
+ usage
2393
+ }));
2394
+ }
2395
+ // src/turn-steps/turn-ended.ts
2396
+ /**
2397
+ * Creates the Delivery of this deployment. It sends replies to Slack
2398
+ * Destinations. Other platforms have no sender yet, so their replies fail.
2399
+ */
2400
+ function createDeploymentDelivery(args) {
2401
+ const sendToSlack = createSlackSender(args);
2402
+ return { send: async (reply) => {
2403
+ const { destination } = reply;
2404
+ if (destination.platform === "slack") return sendToSlack({
2405
+ ...reply,
2406
+ destination
2407
+ });
2408
+ throw new Error(`No sender for ${destination.platform} Destinations`);
2409
+ } };
2410
+ }
2411
+ /**
2412
+ * The queue consumer of the messages that a Turn ended. It records the Turn's
2413
+ * metrics, then sends its replies, so a send that waits does not hold back
2414
+ * the spend. The host mounts it on `engineCtx.queue`.
2415
+ */
2416
+ function turnEndedConsumer(engineCtx, delivery) {
2417
+ return readTurnEndedMessages(engineCtx, async (message) => {
2418
+ await recordTurnMetrics(engineCtx, message);
2419
+ await deliverTurn(engineCtx, message, delivery);
2420
+ await compat__writeTurnEnded(engineCtx, message);
2421
+ });
2422
+ }
2052
2423
  // src/turn-steps/engine-context.ts
2053
2424
  /** Builds the context that core's Turn engine runs with. */
2054
2425
  function createEngineContext(config) {
@@ -2059,4 +2430,4 @@ function createEngineContext(config) {
2059
2430
  leaseMs: config.functionMaxDurationSeconds * 1e3
2060
2431
  };
2061
2432
  }
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 };
2433
+ export { createGatewayModelClient as a, findStalledTurns as c, countMetric as d, withSpan as f, turnTools as i, publishTurnEnded as l, createDeploymentDelivery as n, turnStepConsumer as o, turnEndedConsumer as r, scheduleInput as s, createEngineContext as t, publishTurnStep as u };