@sentry/junior 0.285.0 → 0.286.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 (73) hide show
  1. package/dist/{adapter-DN5AB4VU.js → adapter-JQZaJ-B_.js} +1 -1
  2. package/dist/{admin-DOITMKnn.js → admin-Dm2bimJ-.js} +1 -1
  3. package/dist/{agent-runner-BsWhHe4N.js → agent-runner-DGCwOEyL.js} +1567 -1048
  4. package/dist/api/schema.d.ts +1 -1
  5. package/dist/api/schema.js +5 -5
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +70 -92
  8. package/dist/{app-DyMs9330.d.ts → app-BKq0JzWx.d.ts} +2 -3
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +37 -40
  11. package/dist/{assistant-reply-9Jip5bsr.js → assistant-reply-CAPafcUY.js} +1 -1
  12. package/dist/{automation-Mk8aaHzy.js → automation-B-jJN_gM.js} +1 -1
  13. package/dist/{background-compaction-queue-DXkLsWoH.js → background-compaction-queue-Btu2oab_.js} +137 -3
  14. package/dist/{briefs-Cl8-nK9B.js → briefs-UMeYehUe.js} +4 -4
  15. package/dist/{catalog-runtime-Bte6jRB2.js → catalog-runtime-Bym8GVdh.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +5 -6
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{client-DDbBucBw.js → client-B0aAs7wC.js} +2 -2
  24. package/dist/{config-DqFnykQT.js → config-B9f9Lqo5.js} +1 -1
  25. package/dist/{connections-DA4LT9LL.js → connections-CQ7p0aNJ.js} +16 -50
  26. package/dist/{conversation-D8kVoCrP.js → conversation-BusI2uzj.js} +15 -6
  27. package/dist/{conversation-pending-messages-BvROq1bq.js → conversation-pending-messages-DwehU0Fd.js} +1 -1
  28. package/dist/{conversation-privacy-D0j_h70R.js → conversation-privacy-Cd_nZZBM.js} +1 -1
  29. package/dist/{credential-sync-hcsYatw-.js → credential-sync-DmiJi_At.js} +13 -13
  30. package/dist/{db-BhHZSuFw.d.ts → db-C5zi4ecs.d.ts} +4 -4
  31. package/dist/{executor-BLEMIgIZ.js → executor-Dipi2Ixl.js} +11 -17
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BfORLKoq.js → logging-CMFhLLj4.js} +1 -1
  34. package/dist/{media-Bu9C6lz0.js → media-B-BpXo41.js} +14 -2
  35. package/dist/{message-DqjuKzUx.js → message-D1xLljUF.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +2 -3
  38. package/dist/{oauth-callback-server-CFSRzu1n.js → oauth-callback-server-DCAFIUQr.js} +2 -2
  39. package/dist/{projection-DliWYrnT.js → projection-CoeMNxJ4.js} +286 -212
  40. package/dist/{prompt-BvIUzY4y.js → prompt-C9OQEfan.js} +1 -1
  41. package/dist/{registry-rC7MCxu8.js → registry-u-sFYtx_.js} +1 -1
  42. package/dist/{resolve-Biu8Qw3u.js → resolve-DYqgL3Eo.js} +3 -3
  43. package/dist/{result-DxJMCX47.js → result-CescSwAw.js} +8 -8
  44. package/dist/{runner-BQJSFLKg.js → runner-Cr67a8TB.js} +16 -12
  45. package/dist/{sandbox-egress-signals-6aMxJSDn.js → sandbox-egress-signals-DLOazy5W.js} +1 -1
  46. package/dist/{schema-BasXTvi2.js → schema-BUSi3sgv.js} +5 -5
  47. package/dist/{schema-BUviRAs8.d.ts → schema-Ih60j59-.d.ts} +44 -7
  48. package/dist/{service-account-BI5Wgx22.js → service-account-CGEqz9wG.js} +3 -3
  49. package/dist/{service-account-CAE-_1dR.js → service-account-CsKxktLk.js} +3 -3
  50. package/dist/{session-stop-CA-jOJ84.js → session-stop-CGz5DByb.js} +22 -20
  51. package/dist/{skills-B22duVJU.js → skills-COCqf61f.js} +2 -2
  52. package/dist/{spawn-BB2_4VYn.js → spawn-C8F_iXWO.js} +13 -2
  53. package/dist/{stop-DioIcEAu.js → stop-GyFZkHuQ.js} +242 -952
  54. package/dist/{store-Dn4W7qgH.js → store-D0-8plWp.js} +3 -3
  55. package/dist/{turn-session-routing-CGMKrYOj.js → task-runner-xPuQmEot.js} +1439 -993
  56. package/dist/{store-B26LV6UP.js → turn-failure-response-BOviBdT-.js} +331 -5
  57. package/dist/{validation-TzhfQABF.js → validation-DZDKorGz.js} +1 -1
  58. package/dist/{version-DSk8CFvA.js → version-BTIz7fGi.js} +1 -1
  59. package/dist/version.js +1 -1
  60. package/dist/{viewer-1Ea81s0b.js → viewer-CH-ASQzh.js} +39 -36
  61. package/dist/{work-ybG4_q5C.js → work-C75_IM5e.js} +92 -87
  62. package/dist/{worker-ccSyZRNz.js → worker-Dl47I729.js} +6 -6
  63. package/migrations/0086_shared_archive.sql +31 -0
  64. package/migrations/0087_child_location.sql +64 -0
  65. package/migrations/meta/0086_snapshot.json +4366 -0
  66. package/migrations/meta/0087_snapshot.json +4366 -0
  67. package/migrations/meta/_journal.json +14 -0
  68. package/package.json +5 -4
  69. package/dist/task-queue-Bt0IoR2i.js +0 -139
  70. package/dist/task-runner-D8lddjzp.js +0 -290
  71. package/dist/thread-state-CrFk3K_7.js +0 -173
  72. package/dist/turn-failure-response-DaJ04qVj.js +0 -224
  73. package/dist/turn-lifecycle-C2mXS7AZ.js +0 -58
@@ -1,8 +1,14 @@
1
- import { g as TURN_REASONING_LEVELS } from "./config-DqFnykQT.js";
2
- import { C as getSqlExecutor } from "./viewer-1Ea81s0b.js";
3
- import { g as juniorAgentInvocations } from "./executor-BLEMIgIZ.js";
4
- import { p as credentialContextSchema } from "./registry-rC7MCxu8.js";
1
+ import { D as buildConversationContext, Eo as listConversationAnnotations, M as markConversationMessage, Sn as buildDeterministicTurnId, q as clearPendingAuth, v as hydrateConversationMessages } from "./projection-CoeMNxJ4.js";
2
+ import { b as getProviderErrorUserMessage, g as ProviderError, v as findProviderError, y as getProviderErrorAttributes } from "./client-B0aAs7wC.js";
3
+ import { g as TURN_REASONING_LEVELS } from "./config-B9f9Lqo5.js";
4
+ import { W as isRecord, b as setSpanAttributes, t as buildTurnFailureResponse } from "./logging-CMFhLLj4.js";
5
+ import { h as parseSlackMessageTs } from "./actor-6jsm_v96.js";
6
+ import { C as getSqlExecutor, S as getDb, y as getConversationEventStore } from "./viewer-CH-ASQzh.js";
7
+ import { g as juniorAgentInvocations } from "./executor-Dipi2Ixl.js";
8
+ import { p as credentialContextSchema } from "./registry-u-sFYtx_.js";
9
+ import { F as removedCardSchema, I as resolveMessageCards, P as readMessageCardRefs } from "./conversation-BusI2uzj.js";
5
10
  import { S as AGENT_INVOCATION_PARENT_MAILBOX_STATUSES, x as AGENT_INVOCATION_MAILBOX_STATUSES } from "./reporting-window-B4TwyuJo.js";
11
+ import { _t as getPersistedThreadState, bt as coerceThreadConversationState, yt as persistThreadStateById } from "./task-runner-xPuQmEot.js";
6
12
  import { createHash } from "node:crypto";
7
13
  import * as z from "zod";
8
14
  import { and, asc, desc, eq, inArray, or, sql } from "drizzle-orm";
@@ -473,4 +479,324 @@ async function markAgentInvocationSteered(invocationId, nowMs = Date.now()) {
473
479
  function isTerminalAgentInvocation(invocation) {
474
480
  return TERMINAL_AGENT_INVOCATION_STATUSES.includes(invocation.status);
475
481
  }
476
- export { getAgentInvocationIdForEvents as A, ConversationTurnBoundaryError as B, agentNameSchema as C, agentTypeStartsWithParentHistory as D, agentTypeInstructions as E, getAgentInvocationTurnId as F, isCooperativeTurnYieldError as G, TurnInputCommitLostError as H, getChildAgentLockName as I, markTurnClosed as J, isTurnInputCommitLostError as K, getNamedAgentConversationId as L, getAgentInvocationIdForResult as M, getAgentInvocationMessageId as N, formatAgentTypes as O, getAgentInvocationResultMessageId as P, getUnnamedAgentConversationId as R, agentBindingSchema as S, AGENT_TYPES as T, TurnInputDeferredError as U, CooperativeTurnYieldError as V, getConversationTurnBoundaryError as W, markTurnFailed as X, markTurnCompleted as Y, startActiveTurn as Z, markAgentInvocationRunning as _, getAgentInvocation as a, CHILD_AGENT_RESULTS as b, invocationFromRow as c, listOpenAgentInvocations as d, listPendingAgentInvocationMailboxAppends as f, markAgentInvocationPaused as g, markAgentInvocationParentMailboxAppended as h, getActiveAgentInvocationForConversation as i, getAgentInvocationIdForMessage as j, getAgentInvocationId as k, isTerminalAgentInvocation as l, markAgentInvocationMailboxAppended as m, NON_TERMINAL_AGENT_INVOCATION_STATUSES as n, getChildAgentLabel as o, listPendingAgentInvocationResults as p, isTurnInputDeferredError as q, completeAgentInvocation as r, getLatestAgentInvocationForConversation as s, ACTIVE_AGENT_INVOCATION_STATUSES as t, listAgentInvocationsForConversation as u, markAgentInvocationSteered as v, createAgentInvocationSchema as w, PARENT_AGENT_TARGET as x, reportReplacedAgentInvocation as y, parseAgentInvocationResultMessageId as z };
482
+ // src/chat/conversations/pending-cards.ts
483
+ /**
484
+ * Add the cards that tool results selected since the last visible assistant
485
+ * Message or Turn start, scanning back from `beforeSeq`. Returns the input
486
+ * message ids of the Turn start that ended the scan.
487
+ */
488
+ async function selectTurnCards(conversationId, selection, beforeSeq) {
489
+ while (true) {
490
+ const page = await getConversationEventStore().query(conversationId, {
491
+ beforeSeq,
492
+ limit: 100,
493
+ types: [
494
+ "tool_result",
495
+ "message",
496
+ "turn_started"
497
+ ]
498
+ });
499
+ for (const event of [...page.events].reverse()) {
500
+ const data = event.data;
501
+ if (data.type === "turn_started") return data.inputMessageIds;
502
+ if (data.type === "message" && data.role === "assistant") return [];
503
+ if (data.type !== "tool_result" || data.isError || typeof data.toolName !== "string" || !isRecord(data.details)) continue;
504
+ if (data.details.timed_out === true) continue;
505
+ if (Array.isArray(data.details.removedCards)) for (const ref of removedCardSchema.array().parse(data.details.removedCards)) selection.deleted.add(JSON.stringify([ref.plugin, ref.key]));
506
+ for (const card of readMessageCardRefs(data.details)) {
507
+ const key = JSON.stringify([card.plugin, card.key]);
508
+ if (!selection.deleted.has(key) && !selection.cards.has(key)) selection.cards.set(key, card);
509
+ }
510
+ }
511
+ if (!page.hasOlder || page.events.length === 0) return [];
512
+ beforeSeq = page.events[0].seq;
513
+ }
514
+ }
515
+ /**
516
+ * Add the cards of child agents whose results started this Turn. A child
517
+ * cannot reply to people, so its parent's reply delivers its cards.
518
+ */
519
+ async function selectChildResultCards(inputMessageIds, selection) {
520
+ const events = getConversationEventStore();
521
+ for (const messageId of [...inputMessageIds].reverse()) {
522
+ const invocationId = parseAgentInvocationResultMessageId(messageId);
523
+ const invocation = invocationId ? await getAgentInvocation(invocationId) : void 0;
524
+ if (!invocation) continue;
525
+ const turnId = getAgentInvocationTurnId(invocation.invocationId);
526
+ const terminal = await events.loadByIdempotencyKey(invocation.childConversationId, `turn:${turnId}:terminal`);
527
+ if (!terminal) continue;
528
+ await selectTurnCards(invocation.childConversationId, selection, terminal.seq);
529
+ }
530
+ }
531
+ /** Select undelivered cards and load their latest saved facts. */
532
+ async function loadPendingMessageCards(conversationId) {
533
+ const selection = {
534
+ cards: /* @__PURE__ */ new Map(),
535
+ deleted: /* @__PURE__ */ new Set()
536
+ };
537
+ await selectChildResultCards(await selectTurnCards(conversationId, selection), selection);
538
+ if (selection.cards.size === 0) return [];
539
+ return resolveMessageCards([...selection.cards.values()].reverse(), await listConversationAnnotations(getDb(), conversationId));
540
+ }
541
+ // src/chat/conversations/turn-lifecycle.ts
542
+ /** Persist correlated turn lifecycle facts with retry-safe terminal exclusion. */
543
+ var ConversationTurnLifecycleService = class {
544
+ events;
545
+ constructor(events) {
546
+ this.events = events;
547
+ }
548
+ /** Record the turn start once after every input message is durable. */
549
+ async start(input) {
550
+ await this.events.append(input.conversationId, [{
551
+ idempotencyKey: `turn:${input.turnId}:started`,
552
+ createdAtMs: input.createdAtMs,
553
+ data: {
554
+ type: "turn_started",
555
+ turnId: input.turnId,
556
+ inputMessageIds: input.inputMessageIds,
557
+ surface: input.surface,
558
+ ...input.threadContextThroughSeq === void 0 ? void 0 : { threadContextThroughSeq: input.threadContextThroughSeq }
559
+ }
560
+ }]);
561
+ }
562
+ /** Return the input message ids that started a Turn, when it started. */
563
+ async loadInputMessageIds(conversationId, turnId) {
564
+ const event = await this.events.loadByIdempotencyKey(conversationId, `turn:${turnId}:started`);
565
+ return event?.data.type === "turn_started" ? event.data.inputMessageIds : void 0;
566
+ }
567
+ /** Record a completion that is not a failure once. */
568
+ async complete(input) {
569
+ await this.events.append(input.conversationId, [{
570
+ idempotencyKey: `turn:${input.turnId}:terminal`,
571
+ createdAtMs: input.createdAtMs,
572
+ data: {
573
+ type: "turn_completed",
574
+ turnId: input.turnId,
575
+ outcome: input.outcome
576
+ }
577
+ }]);
578
+ }
579
+ /** Record a classified failure once. Do not store raw error text. */
580
+ async fail(input) {
581
+ await this.events.append(input.conversationId, [{
582
+ idempotencyKey: `turn:${input.turnId}:terminal`,
583
+ createdAtMs: input.createdAtMs,
584
+ data: {
585
+ type: "turn_failed",
586
+ turnId: input.turnId,
587
+ failureCode: input.failureCode,
588
+ ...input.failureReason ? { failureReason: input.failureReason } : void 0,
589
+ ...input.eventId ? { eventId: input.eventId } : void 0
590
+ }
591
+ }]);
592
+ }
593
+ };
594
+ /** Return the Turn lifecycle that records Conversation events. */
595
+ function getTurnLifecycle() {
596
+ return new ConversationTurnLifecycleService(getConversationEventStore());
597
+ }
598
+ // src/chat/conversations/thread-context.ts
599
+ const CURSOR_TURN_LOOKBACK = 10;
600
+ async function loadThreadContextCursor(args) {
601
+ const store = getConversationEventStore();
602
+ const [started, completed] = await Promise.all([store.query(args.conversationId, {
603
+ limit: CURSOR_TURN_LOOKBACK,
604
+ types: ["turn_started"]
605
+ }), store.query(args.conversationId, {
606
+ limit: CURSOR_TURN_LOOKBACK,
607
+ types: ["turn_completed"]
608
+ })]);
609
+ const finished = new Set(completed.events.flatMap((event) => event.data.type === "turn_completed" && event.data.outcome !== "cancelled" ? [event.data.turnId] : []));
610
+ const previous = [...started.events].reverse().find((event) => event.data.type === "turn_started" && event.data.turnId !== args.turnId && finished.has(event.data.turnId));
611
+ return previous?.data.type === "turn_started" ? previous.data.threadContextThroughSeq : void 0;
612
+ }
613
+ /**
614
+ * Return the oldest cursor of the Turns that the cursor lookup reads. Messages
615
+ * after it may still be in the thread context delta of the next Turn, also
616
+ * when the latest Turns failed or the next Turn retries.
617
+ */
618
+ async function loadThreadContextTrimFloor(conversationId) {
619
+ const cursors = (await getConversationEventStore().query(conversationId, {
620
+ limit: CURSOR_TURN_LOOKBACK,
621
+ types: ["turn_started"]
622
+ })).events.flatMap((event) => event.data.type === "turn_started" && event.data.threadContextThroughSeq !== void 0 ? [event.data.threadContextThroughSeq] : []);
623
+ return cursors.length > 0 ? Math.min(...cursors) : void 0;
624
+ }
625
+ /**
626
+ * Build the thread context of one Turn prompt. With agent history, show only
627
+ * the thread Messages saved after the cursor of the previous Turn.
628
+ */
629
+ async function buildTurnThreadContext(args) {
630
+ const afterSeq = args.hasHistory ? await loadThreadContextCursor({
631
+ conversationId: args.conversationId,
632
+ turnId: args.turnId
633
+ }) : void 0;
634
+ const block = buildConversationContext(args.conversation, {
635
+ excludeMessageIds: args.excludeMessageIds,
636
+ ...args.hasHistory ? { history: { afterSeq } } : void 0
637
+ });
638
+ setSpanAttributes({
639
+ "app.thread_context.chars": block.text?.length ?? 0,
640
+ "app.thread_context.shown_messages": block.shownMessages,
641
+ "app.thread_context.omitted_messages": block.omittedMessages,
642
+ "app.thread_context.cursor": !args.hasHistory ? "no_history" : afterSeq === void 0 ? "missing" : "found"
643
+ });
644
+ return block.text;
645
+ }
646
+ // src/chat/runtime/delivered-turn-state.ts
647
+ /** Build state after destination delivery or intentional no-reply completion. */
648
+ function buildDeliveredTurnStatePatch(args) {
649
+ const conversation = structuredClone(args.conversation);
650
+ clearPendingAuth(conversation, args.sessionId);
651
+ markConversationMessage(conversation, args.userMessageId, {
652
+ replied: true,
653
+ skippedReason: void 0
654
+ });
655
+ markTurnCompleted({
656
+ conversation,
657
+ nowMs: Date.now(),
658
+ sessionId: args.sessionId
659
+ });
660
+ return {
661
+ conversation,
662
+ sandboxRef: args.reply.sandboxRef
663
+ };
664
+ }
665
+ // src/chat/runtime/turn-user-message.ts
666
+ /** Return the user message for a persisted turn/session, if one exists. */
667
+ function getTurnUserMessage(conversation, sessionId) {
668
+ for (let index = conversation.messages.length - 1; index >= 0; index -= 1) {
669
+ const message = conversation.messages[index];
670
+ if (message?.role !== "user") continue;
671
+ if (buildDeterministicTurnId(message.id) === sessionId) return message;
672
+ }
673
+ }
674
+ /** Return the persisted user-message id for a turn/session, if one exists. */
675
+ function getTurnUserMessageId(conversation, sessionId) {
676
+ return getTurnUserMessage(conversation, sessionId)?.id;
677
+ }
678
+ /** Return the Slack timestamp for the user message that a resumed turn acts on. */
679
+ function getTurnUserSlackMessageTs(message) {
680
+ return parseSlackMessageTs(message?.meta?.slackTs);
681
+ }
682
+ /** Rebuild attachment context for a resumed turn from the persisted user message. */
683
+ function getTurnUserReplyAttachmentContext(message) {
684
+ const inboundAttachmentCount = message?.meta?.attachmentCount ?? 0;
685
+ const imageAttachmentCount = message?.meta?.imageAttachmentCount ?? 0;
686
+ const imagesHydrated = message?.meta?.imagesHydrated === true;
687
+ return {
688
+ ...inboundAttachmentCount > 0 ? { inboundAttachmentCount } : void 0,
689
+ ...!imagesHydrated && imageAttachmentCount > 0 ? { omittedImageAttachmentCount: imageAttachmentCount } : void 0
690
+ };
691
+ }
692
+ // src/chat/runtime/auth-pause-state.ts
693
+ /** Mark an auth-paused turn complete after private authorization link delivery. */
694
+ function completeAuthPauseTurn(args) {
695
+ markConversationMessage(args.conversation, getTurnUserMessageId(args.conversation, args.sessionId), {
696
+ replied: true,
697
+ skippedReason: void 0
698
+ });
699
+ markTurnClosed({
700
+ conversation: args.conversation,
701
+ nowMs: Date.now(),
702
+ sessionId: args.sessionId
703
+ });
704
+ }
705
+ /** Reload thread state, mark the auth pause as parked, and persist it. */
706
+ async function persistAuthPauseTurnState(args) {
707
+ const currentState = await getPersistedThreadState(args.threadStateId);
708
+ const conversation = coerceThreadConversationState(currentState);
709
+ await hydrateConversationMessages({
710
+ conversation,
711
+ conversationId: args.threadStateId
712
+ });
713
+ completeAuthPauseTurn({
714
+ conversation,
715
+ sessionId: args.sessionId
716
+ });
717
+ await persistThreadStateById(args.threadStateId, { conversation });
718
+ }
719
+ // src/chat/interruption-marker.ts
720
+ const INTERRUPTED_MARKER = "\n\n[Response interrupted before completion]";
721
+ /** Return the marker added when a visible reply ended mid-execution. */
722
+ function getInterruptionMarker() {
723
+ return INTERRUPTED_MARKER;
724
+ }
725
+ // src/chat/services/turn-failure-response.ts
726
+ /** Require captured turn failures to carry a real Sentry event reference. */
727
+ function requireTurnFailureEventId(eventId, eventName) {
728
+ if (!eventId) throw new Error(`Sentry did not return an event ID for ${eventName}`);
729
+ return eventId;
730
+ }
731
+ function getExecutionFailureReason(reply) {
732
+ const errorMessage = reply.diagnostics.errorMessage?.trim();
733
+ if (errorMessage) return errorMessage;
734
+ if (reply.diagnostics.toolErrorCount > 0) return `${reply.diagnostics.toolErrorCount} tool result error(s)`;
735
+ if (reply.diagnostics.assistantMessageCount > 0) return "assistant returned no text";
736
+ return "empty assistant turn";
737
+ }
738
+ /** Return a fixed reason label for a failed model turn. */
739
+ function getTurnFailureReason(reply) {
740
+ if (reply.diagnostics.outcome === "success") return;
741
+ if (reply.diagnostics.outcome === "provider_error") return findProviderError(reply.diagnostics.providerError)?.kind ?? "unknown";
742
+ if (reply.diagnostics.toolErrorCount > 0) return "tool_errors";
743
+ if (reply.diagnostics.usedPrimaryText && reply.diagnostics.assistantMessageCount > 0) return "suppressed_output";
744
+ return "empty_output";
745
+ }
746
+ function getFailureCapture(reply) {
747
+ if (reply.diagnostics.outcome === "provider_error") {
748
+ const providerError = findProviderError(reply.diagnostics.providerError);
749
+ return {
750
+ eventName: "agent.turn.provider_error",
751
+ error: reply.diagnostics.providerError ?? new Error(reply.diagnostics.errorMessage ?? "Provider error without explicit message"),
752
+ attributes: providerError ? getProviderErrorAttributes(providerError) : {},
753
+ body: "Agent turn failed with provider error"
754
+ };
755
+ }
756
+ const failureReason = getExecutionFailureReason(reply);
757
+ return {
758
+ eventName: "agent.turn.execution.failed",
759
+ error: /* @__PURE__ */ new Error(`Agent turn execution failure: ${failureReason}`),
760
+ attributes: { "app.ai.execution_failure_reason": failureReason },
761
+ body: "Agent turn completed with execution failure"
762
+ };
763
+ }
764
+ /** Keep failed-turn Sentry captures and completion spans on the same keys. */
765
+ function getAgentTurnDiagnosticsAttributes(reply) {
766
+ return {
767
+ "app.ai.outcome": reply.diagnostics.outcome,
768
+ "app.ai.assistant_messages": reply.diagnostics.assistantMessageCount,
769
+ "app.ai.tool_results": reply.diagnostics.toolResultCount,
770
+ "app.ai.tool_error_results": reply.diagnostics.toolErrorCount,
771
+ "app.ai.tool_call_count": reply.diagnostics.toolCalls.length,
772
+ "app.ai.used_primary_text": reply.diagnostics.usedPrimaryText,
773
+ ...reply.automation ? { "app.automation.result": reply.automation.result } : void 0,
774
+ ...reply.diagnostics.reasoningLevel ? { "gen_ai.request.reasoning.level": reply.diagnostics.reasoningLevel } : void 0,
775
+ ...reply.diagnostics.stopReason ? { "gen_ai.response.finish_reasons": [reply.diagnostics.stopReason] } : void 0,
776
+ ...reply.diagnostics.errorMessage && reply.diagnostics.outcome !== "provider_error" ? { "exception.message": reply.diagnostics.errorMessage } : void 0
777
+ };
778
+ }
779
+ /** Enforce one captured failure response and return its structured correlation. */
780
+ function finalizeFailedTurnReplyWithEvent(args) {
781
+ if (args.reply.diagnostics.outcome === "success") return { reply: args.reply };
782
+ const failureReason = getTurnFailureReason(args.reply);
783
+ const capture = getFailureCapture(args.reply);
784
+ const eventId = requireTurnFailureEventId(args.logException(capture.error, capture.eventName, {
785
+ ...getAgentTurnDiagnosticsAttributes(args.reply),
786
+ ...args.attributes,
787
+ ...capture.attributes,
788
+ ...failureReason ? { "app.ai.failure_reason": failureReason } : void 0
789
+ }), capture.eventName);
790
+ const providerPartialText = args.reply.diagnostics.outcome === "provider_error" && args.reply.diagnostics.assistantMessageCount > 0 ? args.reply.text.trim() : "";
791
+ const providerUserMessage = args.reply.diagnostics.providerError instanceof ProviderError ? getProviderErrorUserMessage(args.reply.diagnostics.providerError) : "";
792
+ const failureText = providerUserMessage ? `${providerUserMessage} Reference: \`event_id=${eventId}\`.` : buildTurnFailureResponse(eventId);
793
+ return {
794
+ eventId,
795
+ ...failureReason ? { failureReason } : void 0,
796
+ reply: {
797
+ ...args.reply,
798
+ text: providerPartialText ? `${providerPartialText}${getInterruptionMarker()}` : failureText
799
+ }
800
+ };
801
+ }
802
+ export { parseAgentInvocationResultMessageId as $, markAgentInvocationPaused as A, agentTypeInstructions as B, isTerminalAgentInvocation as C, listPendingAgentInvocationResults as D, listPendingAgentInvocationMailboxAppends as E, PARENT_AGENT_TARGET as F, getAgentInvocationIdForMessage as G, formatAgentTypes as H, agentBindingSchema as I, getAgentInvocationResultMessageId as J, getAgentInvocationIdForResult as K, agentNameSchema as L, markAgentInvocationSteered as M, reportReplacedAgentInvocation as N, markAgentInvocationMailboxAppended as O, CHILD_AGENT_RESULTS as P, getUnnamedAgentConversationId as Q, createAgentInvocationSchema as R, invocationFromRow as S, listOpenAgentInvocations as T, getAgentInvocationId as U, agentTypeStartsWithParentHistory as V, getAgentInvocationIdForEvents as W, getChildAgentLockName as X, getAgentInvocationTurnId as Y, getNamedAgentConversationId as Z, completeAgentInvocation as _, persistAuthPauseTurnState as a, isCooperativeTurnYieldError as at, getChildAgentLabel as b, getTurnUserSlackMessageTs as c, markTurnClosed as ct, loadThreadContextTrimFloor as d, startActiveTurn as dt, ConversationTurnBoundaryError as et, ConversationTurnLifecycleService as f, NON_TERMINAL_AGENT_INVOCATION_STATUSES as g, ACTIVE_AGENT_INVOCATION_STATUSES as h, completeAuthPauseTurn as i, getConversationTurnBoundaryError as it, markAgentInvocationRunning as j, markAgentInvocationParentMailboxAppended as k, buildDeliveredTurnStatePatch as l, markTurnCompleted as lt, loadPendingMessageCards as m, getAgentTurnDiagnosticsAttributes as n, TurnInputCommitLostError as nt, getTurnUserMessage as o, isTurnInputCommitLostError as ot, getTurnLifecycle as p, getAgentInvocationMessageId as q, requireTurnFailureEventId as r, TurnInputDeferredError as rt, getTurnUserReplyAttachmentContext as s, isTurnInputDeferredError as st, finalizeFailedTurnReplyWithEvent as t, CooperativeTurnYieldError as tt, buildTurnThreadContext as u, markTurnFailed as ut, getActiveAgentInvocationForConversation as v, listAgentInvocationsForConversation as w, getLatestAgentInvocationForConversation as x, getAgentInvocation as y, AGENT_TYPES as z };
@@ -1,5 +1,5 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-Bte6jRB2.js";
2
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-Bym8GVdh.js";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  // src/chat/plugins/validation.ts
5
5
  var validation_exports = /* @__PURE__ */ __exportAll({
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.285.0";
2
+ var version = "0.286.0";
3
3
  // src/version.ts
4
4
  /** Installed Junior package version, or `unknown` when package metadata is unavailable. */
5
5
  const JUNIOR_VERSION = typeof version === "string" && version.trim() ? version : "unknown";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export { t as JUNIOR_VERSION } from "./version-DSk8CFvA.js";
1
+ export { t as JUNIOR_VERSION } from "./version-BTIz7fGi.js";
@@ -1,9 +1,9 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { i as getChatConfig } from "./config-DqFnykQT.js";
3
- import { U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-BfORLKoq.js";
2
+ import { i as getChatConfig } from "./config-B9f9Lqo5.js";
3
+ import { U as normalizeIdentityEmail, V as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-CMFhLLj4.js";
4
4
  import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-6jsm_v96.js";
5
- import { A as conversationReadColumns, E as juniorConversationAnnotations, M as juniorIdentities, N as juniorUsers, P as juniorDestinations, S as juniorConversationMetrics, j as juniorConversations, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-BLEMIgIZ.js";
6
- import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, r as detectImageMediaType, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-Bu9C6lz0.js";
5
+ import { A as juniorConversations, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, S as juniorConversationMetrics, j as juniorIdentities, t as createJuniorSqlExecutor, v as juniorConversationParticipants, w as juniorConversationEvents, x as CONVERSATION_METRICS, y as juniorConversationBindings } from "./executor-Dipi2Ixl.js";
6
+ import { d as historyReplacementSchema, f as newConversationEventSchema, p as encodeHistoryPayload, r as detectImageMediaType, s as conversationEventDataSchema, u as decodeStoredConversationEvent, y as usageSchema } from "./media-B-BpXo41.js";
7
7
  import { a as withLock } from "./locks-D-0h111u.js";
8
8
  import { createHash, randomUUID } from "node:crypto";
9
9
  import { and, asc, desc, eq, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, or, sql } from "drizzle-orm";
@@ -63,10 +63,7 @@ async function recordConversationParticipant(executor, args) {
63
63
  lastMessageAt: at
64
64
  }).onConflictDoUpdate({
65
65
  target: [juniorConversationParticipants.userId, juniorConversationParticipants.rootConversationId],
66
- set: {
67
- lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)`,
68
- ...args.restoreArchive ? { archivedAt: null } : void 0
69
- }
66
+ set: { lastMessageAt: sql`greatest(${juniorConversationParticipants.lastMessageAt}, excluded.last_message_at)` }
70
67
  });
71
68
  return true;
72
69
  }
@@ -916,7 +913,7 @@ function conversationFromRow(readRow) {
916
913
  },
917
914
  kind: conversationKindFromRow(row),
918
915
  ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0,
919
- ...row.childArchivedAt ? { childArchivedAtMs: row.childArchivedAt.getTime() } : void 0,
916
+ ...row.archivedAt ? { archivedAtMs: row.archivedAt.getTime() } : void 0,
920
917
  ...destination ? { destination } : void 0,
921
918
  ...location ? { location } : void 0,
922
919
  ...actor ? { actor } : void 0,
@@ -971,7 +968,9 @@ var SqlStore = class {
971
968
  if (existing.kind !== args.kind) throw new Error(`Conversation kind changed for ${args.childConversationId}`);
972
969
  return;
973
970
  }
974
- if (!await this.get({ conversationId: args.parentConversationId })) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
971
+ const parentRow = await this.readConversationRow(args.parentConversationId);
972
+ if (!parentRow) throw new Error(`Conversation parent is missing for ${args.childConversationId}`);
973
+ const { location } = conversationFromRow(parentRow);
975
974
  const child = {
976
975
  ...emptyConversation({
977
976
  conversationId: args.childConversationId,
@@ -979,9 +978,13 @@ var SqlStore = class {
979
978
  source: args.source
980
979
  }),
981
980
  kind: args.kind,
982
- parentConversationId: args.parentConversationId
981
+ parentConversationId: args.parentConversationId,
982
+ ...location ? { location } : void 0
983
983
  };
984
- await this.upsertConversation({ conversation: child });
984
+ await this.upsertConversation({
985
+ conversation: child,
986
+ destinationId: parentRow.conversation.destinationId ?? void 0
987
+ });
985
988
  });
986
989
  });
987
990
  }
@@ -1082,7 +1085,7 @@ var SqlStore = class {
1082
1085
  }
1083
1086
  async listByActivity(args = {}) {
1084
1087
  const rows = await this.executor.db().select({
1085
- conversation: conversationReadColumns(),
1088
+ conversation: juniorConversations,
1086
1089
  destination: juniorDestinations,
1087
1090
  actorIdentity: juniorIdentities,
1088
1091
  actorUserDisplayName: juniorUsers.displayName
@@ -1120,7 +1123,7 @@ var SqlStore = class {
1120
1123
  }
1121
1124
  async readConversationRow(conversationId) {
1122
1125
  return (await this.executor.db().select({
1123
- conversation: conversationReadColumns(),
1126
+ conversation: juniorConversations,
1124
1127
  destination: juniorDestinations,
1125
1128
  actorIdentity: juniorIdentities,
1126
1129
  actorUserDisplayName: juniorUsers.displayName
@@ -1141,7 +1144,7 @@ var SqlStore = class {
1141
1144
  conversationId: conversation.conversationId,
1142
1145
  destination: conversation.destination,
1143
1146
  ...conversation.visibility ? { visibility: conversation.visibility } : void 0
1144
- }), conversation.updatedAtMs);
1147
+ }), conversation.updatedAtMs) ?? args.destinationId;
1145
1148
  const location = locationForWrite({
1146
1149
  destination: conversation.destination,
1147
1150
  destinationId,
@@ -1376,13 +1379,13 @@ function sanitizePostgresJson(value) {
1376
1379
  async function readConversationTrees(db, rootConversationIds) {
1377
1380
  if (rootConversationIds.length === 0) return /* @__PURE__ */ new Map();
1378
1381
  const rows = await db.select({
1379
- childArchivedAt: juniorConversations.childArchivedAt,
1382
+ archivedAt: juniorConversations.archivedAt,
1380
1383
  conversationId: juniorConversations.conversationId,
1381
1384
  kind: juniorConversations.kind,
1382
1385
  parentConversationId: juniorConversations.parentConversationId
1383
1386
  }).from(juniorConversations).where(inArray(juniorConversations.rootConversationId, [...rootConversationIds]));
1384
1387
  return new Map(rows.map((row) => [row.conversationId, {
1385
- childArchivedAt: row.childArchivedAt,
1388
+ archivedAt: row.archivedAt,
1386
1389
  conversationId: row.conversationId,
1387
1390
  kind: conversationKindFromRow(row),
1388
1391
  ...row.parentConversationId ? { parentConversationId: row.parentConversationId } : void 0
@@ -1422,29 +1425,33 @@ function conversationDescendants(tree, conversationId) {
1422
1425
  }
1423
1426
  return descendants;
1424
1427
  }
1425
- /** Set or clear the shared archive of the given child Conversations. */
1426
- async function setChildArchivedAt(db, conversationIds, archivedAt) {
1428
+ /** Set or clear the shared archive of the given Conversations. */
1429
+ async function setArchivedAt(db, conversationIds, archivedAt) {
1427
1430
  if (conversationIds.length === 0) return;
1428
1431
  await db.update(juniorConversations).set({
1429
- childArchivedAt: archivedAt,
1432
+ archivedAt,
1430
1433
  detailVersion: nextDetailVersion
1431
1434
  }).where(inArray(juniorConversations.conversationId, [...conversationIds]));
1432
1435
  }
1433
1436
  /**
1434
- * Restore one archived child and its archived ancestor children, so the child
1435
- * shows again. Its descendants keep their archive. A root has no child
1436
- * archive, so this changes nothing for a root.
1437
+ * Restore one archived Conversation and its archived ancestors, so it shows
1438
+ * again. Its descendants keep their archive.
1437
1439
  */
1438
- async function restoreArchivedChildPath(db, conversationId) {
1440
+ async function restoreArchivedPath(db, conversationId) {
1439
1441
  const [row] = await db.select({
1442
+ archivedAt: juniorConversations.archivedAt,
1440
1443
  parentConversationId: juniorConversations.parentConversationId,
1441
1444
  rootConversationId: juniorConversations.rootConversationId
1442
1445
  }).from(juniorConversations).where(eq(juniorConversations.conversationId, conversationId)).limit(1);
1443
- if (!row?.parentConversationId || !row.rootConversationId) return;
1446
+ if (!row) return;
1447
+ if (!row.parentConversationId || !row.rootConversationId) {
1448
+ if (row.archivedAt) await setArchivedAt(db, [conversationId], null);
1449
+ return;
1450
+ }
1444
1451
  const tree = await readConversationTrees(db, [row.rootConversationId]);
1445
1452
  const node = tree.get(conversationId);
1446
1453
  if (!node) return;
1447
- await setChildArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.kind !== "root" && entry.childArchivedAt).map((entry) => entry.conversationId), null);
1454
+ await setArchivedAt(db, [node, ...conversationAncestors(tree, conversationId)].filter((entry) => entry.archivedAt).map((entry) => entry.conversationId), null);
1448
1455
  }
1449
1456
  // src/chat/conversations/sql/event-lock.ts
1450
1457
  /** Serialize event sequence allocation with other conversation writes. */
@@ -1577,20 +1584,18 @@ var SqlConversationEventStore = class {
1577
1584
  */
1578
1585
  async recordTurnInputParticipants(conversationId, inputMessageIds) {
1579
1586
  const rows = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "message"), inArray(sql`${juniorConversationEvents.payload}->>'messageId'`, [...inputMessageIds])));
1580
- let restoresChild = false;
1587
+ let restores = false;
1581
1588
  for (const row of rows) {
1582
1589
  const { data } = eventFromRow(row);
1583
1590
  if (!row.actorIdentityId || data.type !== "message") continue;
1584
- const restoreArchive = eventUnarchivesConversation(data);
1585
1591
  const isPerson = await recordConversationParticipant(this.executor, {
1586
1592
  actorIdentityId: row.actorIdentityId,
1587
1593
  conversationId,
1588
- atMs: row.createdAt.getTime(),
1589
- restoreArchive
1594
+ atMs: row.createdAt.getTime()
1590
1595
  });
1591
- restoresChild ||= isPerson && restoreArchive;
1596
+ restores ||= isPerson && eventUnarchivesConversation(data);
1592
1597
  }
1593
- if (restoresChild) await restoreArchivedChildPath(this.executor.db(), conversationId);
1598
+ if (restores) await restoreArchivedPath(this.executor.db(), conversationId);
1594
1599
  }
1595
1600
  async replaceHistory(conversationId, replacement, options = {}) {
1596
1601
  const parsed = historyReplacementSchema.parse(replacement);
@@ -1638,11 +1643,9 @@ var SqlConversationEventStore = class {
1638
1643
  }
1639
1644
  async loadMessageHistory(conversationId) {
1640
1645
  const [compactionRow] = await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), eq(juniorConversationEvents.type, "messages_summarized"))).orderBy(desc(juniorConversationEvents.seq)).limit(1);
1641
- const compaction = compactionRow ? messagesSummarizedEventFromRow(compactionRow) : void 0;
1642
- const historyFromSeq = compaction?.data.historyFromSeq ?? 0;
1646
+ const historyFromSeq = compactionRow ? messagesSummarizedEventFromRow(compactionRow).data.historyFromSeq : 0;
1643
1647
  return {
1644
1648
  events: (await this.executor.db().select().from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), inArray(juniorConversationEvents.type, messageHistoryEventTypes), gte(juniorConversationEvents.seq, historyFromSeq))).orderBy(asc(juniorConversationEvents.seq))).map(eventFromRow),
1645
- compaction,
1646
1649
  historyFromSeq
1647
1650
  };
1648
1651
  }
@@ -2206,4 +2209,4 @@ async function readIdentityByIdFromSql(db, identityId) {
2206
2209
  async function readIdentityById(identityId) {
2207
2210
  return await readIdentityByIdFromSql(getDb(), identityId);
2208
2211
  }
2209
- export { parseSessionSource as $, conversationAncestors as A, startLocationThread as B, getSqlExecutor as C, createSqlConversationEventStore as D, treeHasAnnotationKey as E, createSqlStore as F, deleteProviderIdentityForSlackUser as G, SYSTEM_IDENTITY_ID as H, withConversationMutationLock as I, readUserTimezone as J, deleteProviderIdentityForUser as K, conversationKindFromRow as L, readConversationTrees as M, setChildArchivedAt as N, eventFromRow as O, loadConversationSlackTenantIds as P, bindProviderConversation as Q, locationFromRow as R, getDb as S, hasAnnotationKey as T, resolveActorIdentityId as U, visibilityFromLocationRow as V, saveActorAvatar as W, saveUserTimezone as X, recordGoogleSignIn as Y, upsertLinkedIdentity as Z, closeDb as _, readActorIdentityFromSql as a, agentTurnTotalTokens as at, getConversationMessageSearchStore as b, readViewerAvatarUrl as c, resolveRootConversationId as ct, updateViewerDisplayName as d, requireSlackDestination as dt, conversationDetailTouch as et, identityAvatarUrl as f, sameDestination as ft, createCache as g, readUserAvatarUrls as h, readActorIdentity as i, agentTurnCostUsd as it, conversationDescendants as j, withConversationEventLock as k, resolveViewerUser as l, createSlackDestination as lt, readAvatarImage as m, findUserByEmailFromSql as n, touchConversationDetail as nt, readIdentityById as o, agentTurnUsageSchema as ot, parseAvatarUrl as p, findUserByVerifiedEmails as q, listAdminUsersFromSql as r, addAgentTurnUsage as rt, readIdentityByIdFromSql as s, hasAgentTurnUsage as st, findUserByEmail as t, nextDetailVersion as tt, setUserAdminFromSql as u, parseDestination as ut, db_exports as v, conversationIdsWithAnnotation as w, getConversationStore as x, getConversationEventStore as y, setFirstConversationLocation as z };
2212
+ export { conversationDetailTouch as $, conversationAncestors as A, startLocationThread as B, getSqlExecutor as C, createSqlConversationEventStore as D, treeHasAnnotationKey as E, createSqlStore as F, deleteProviderIdentityForUser as G, resolveActorIdentityId as H, withConversationMutationLock as I, recordGoogleSignIn as J, findUserByVerifiedEmails as K, conversationKindFromRow as L, readConversationTrees as M, setArchivedAt as N, eventFromRow as O, loadConversationSlackTenantIds as P, parseSessionSource as Q, locationFromRow as R, getDb as S, hasAnnotationKey as T, saveActorAvatar as U, SYSTEM_IDENTITY_ID as V, deleteProviderIdentityForSlackUser as W, upsertLinkedIdentity as X, saveUserTimezone as Y, bindProviderConversation as Z, closeDb as _, readActorIdentityFromSql as a, agentTurnUsageSchema as at, getConversationMessageSearchStore as b, readViewerAvatarUrl as c, createSlackDestination as ct, updateViewerDisplayName as d, sameDestination as dt, nextDetailVersion as et, identityAvatarUrl as f, createCache as g, readUserAvatarUrls as h, readActorIdentity as i, agentTurnTotalTokens as it, conversationDescendants as j, withConversationEventLock as k, resolveViewerUser as l, parseDestination as lt, readAvatarImage as m, findUserByEmailFromSql as n, addAgentTurnUsage as nt, readIdentityById as o, hasAgentTurnUsage as ot, parseAvatarUrl as p, readUserTimezone as q, listAdminUsersFromSql as r, agentTurnCostUsd as rt, readIdentityByIdFromSql as s, resolveRootConversationId as st, findUserByEmail as t, touchConversationDetail as tt, setUserAdminFromSql as u, requireSlackDestination as ut, db_exports as v, conversationIdsWithAnnotation as w, getConversationStore as x, getConversationEventStore as y, setFirstConversationLocation as z };