@sentry/junior 0.287.0 → 0.289.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 (79) hide show
  1. package/dist/{adapter-CL-HUKgd.js → adapter-tE1wnl0T.js} +1 -1
  2. package/dist/{admin-C9urXVfi.js → admin-BmsPbmO_.js} +2 -2
  3. package/dist/{agent-runner-Bfnw551N.js → agent-runner-bvl8U5uH.js} +489 -165
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +628 -238
  8. package/dist/{app-DBY5TnfY.d.ts → app-Cu454FXq.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +550 -71
  11. package/dist/assistant-reply-1N9oxyyb.js +58 -0
  12. package/dist/{automation-DksGNDRO.js → automation-DWbjJltM.js} +2 -2
  13. package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-D36oCldp.js} +161 -90
  14. package/dist/{briefs-DaXiMWzT.js → briefs-CV-1qkXa.js} +3 -3
  15. package/dist/{catalog-runtime-BCIuBe4d.js → catalog-runtime-BNK4uJVZ.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-CkHcUMN7.js → config-DHAy7XlP.js} +363 -8
  24. package/dist/{connections-BnIj0wtx.js → connections-C3VmH3cf.js} +7 -129
  25. package/dist/{conversation-E7ZPJx2H.js → conversation-CwC8K3RZ.js} +22 -5
  26. package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-B0cuLReP.js} +1 -1
  27. package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-Bky_veSp.js} +1 -1
  28. package/dist/{credential-sync-CzMar9hq.js → credential-sync-dY9o0YSj.js} +28 -20
  29. package/dist/{db-DJ11eZqq.js → db-BS2Kql3j.js} +81 -46
  30. package/dist/{db-YDKKDxlh.d.ts → db-BebRmhsH.d.ts} +10 -2
  31. package/dist/{executor-BY9TB31g.js → executor-cc4nH86C.js} +125 -18
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BO5zU6Mt.js → logging-CtCJmt9p.js} +3 -2
  34. package/dist/{media-Cz1ZiV1U.js → media-BepyEUNm.js} +5 -1
  35. package/dist/{message-CsUbuEc8.js → message-C5VuRcP9.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +19 -41
  38. package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-KRrYUZ35.js} +2 -2
  39. package/dist/{projection-CL_YWeGf.js → projection-BFJG58TG.js} +448 -721
  40. package/dist/{prompt-BHOEQSmf.js → prompt-D15oftoL.js} +5 -5
  41. package/dist/{registry-BriFLnaJ.js → registry-C_JrgqUz.js} +1 -1
  42. package/dist/{resolve-Bt6GgAiA.js → resolve-Cn_7JfP-.js} +3 -3
  43. package/dist/{result-Bo1TZu0Q.js → result-CIbQFLp6.js} +16 -10
  44. package/dist/{runner-D3YeCQgt.js → runner-BwmaMJVO.js} +8 -8
  45. package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-BOQ8gn7i.js} +1 -1
  46. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  47. package/dist/{schema-BWE3RJEB.js → schema-Bptz19Ja.js} +72 -14
  48. package/dist/{schema-C6fsEwjo.d.ts → schema-DQaFSkZZ.d.ts} +122 -3
  49. package/dist/{service-account-DiQQuuw7.js → service-account-AGw_pANb.js} +3 -3
  50. package/dist/{service-account-r6fl0b-9.js → service-account-CLZfF8O1.js} +3 -3
  51. package/dist/{session-stop-B2Nut40V.js → session-stop-CbzKf7UI.js} +84 -31
  52. package/dist/{skills-CD5aJdzg.js → skills-CcAJBquq.js} +2 -2
  53. package/dist/{spawn-CalgZQiu.js → spawn-BvAk2vTI.js} +5 -5
  54. package/dist/{stop-kujZLbi0.js → stop-BQU4u7la.js} +893 -519
  55. package/dist/{store-DdIEUL1q.js → store-DE7NJOvQ.js} +4 -16
  56. package/dist/{task-runner-D_RDr2Hu.js → task-runner-Q_7duP_T.js} +31 -27
  57. package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-aWZLfUM8.js} +18 -9
  58. package/dist/{validation-K4pqwoVZ.js → validation-BOoPeIJR.js} +1 -1
  59. package/dist/{version-DBvhk1X9.js → version-Db0MFy61.js} +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/{viewer-DrMmFUul.js → viewer-FFEFu9In.js} +4 -4
  62. package/dist/warmup-DDzrA9Gv.js +967 -0
  63. package/dist/{work-ljRoODGu.js → work-BBJK458E.js} +16 -15
  64. package/dist/{worker-CYO1Q0Js.js → worker-2iU5RFyq.js} +7 -31
  65. package/migrations/0089_conversation_paused_status.sql +3 -0
  66. package/migrations/0090_guardian_review_time_index.sql +20 -0
  67. package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
  68. package/migrations/0092_turn_metric_actor.sql +12 -0
  69. package/migrations/0093_participant_root_actor_backfill.sql +18 -0
  70. package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
  71. package/migrations/meta/0089_snapshot.json +4372 -0
  72. package/migrations/meta/0090_snapshot.json +4388 -0
  73. package/migrations/meta/0091_snapshot.json +4410 -0
  74. package/migrations/meta/0092_snapshot.json +4446 -0
  75. package/migrations/meta/0093_snapshot.json +4446 -0
  76. package/migrations/meta/0094_snapshot.json +4452 -0
  77. package/migrations/meta/_journal.json +42 -0
  78. package/package.json +6 -5
  79. package/dist/assistant-reply-u_PRYzuz.js +0 -65
@@ -1,6 +1,6 @@
1
1
  import { v as __exportAll } from "./sentry-BRTJqumy.js";
2
- import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-BO5zU6Mt.js";
3
- import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-DF1hW0ja.js";
2
+ import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-CtCJmt9p.js";
3
+ import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-Bky_veSp.js";
4
4
  import { AwsClient } from "aws4fetch";
5
5
  import { del, get, put } from "@vercel/blob";
6
6
  import { calculateCost, completeSimple, getEnvApiKey, getModels, registerApiProvider } from "@earendil-works/pi-ai/compat";
@@ -8,6 +8,7 @@ import { stream as streamAnthropic, streamSimple as streamSimpleAnthropic } from
8
8
  import { createGatewayProvider } from "@ai-sdk/gateway";
9
9
  import { getVercelOidcToken } from "@vercel/oidc";
10
10
  import { Experimental_DecisionRefusalError, NoObjectGeneratedError, embedMany, experimental_decide, generateObject, rerank } from "ai";
11
+ import { createHash } from "node:crypto";
11
12
  import * as z from "zod";
12
13
  // src/chat/optional-string.ts
13
14
  /**
@@ -514,6 +515,354 @@ function hasCompactedConversationContext(messages) {
514
515
  return content.some((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string" && isCompactionSummaryText(part.text));
515
516
  });
516
517
  }
518
+ // src/chat/services/image-dimensions.ts
519
+ const HEADER_BASE64_CHARS = 65536;
520
+ const READERS = {
521
+ "image/png": readPng,
522
+ "image/jpeg": readJpeg,
523
+ "image/gif": readGif,
524
+ "image/webp": readWebp
525
+ };
526
+ /**
527
+ * Read the pixel size from an image header without decoding the image.
528
+ * Returns undefined when the type is unknown or the header is not valid.
529
+ */
530
+ function readImageDimensions(image) {
531
+ const read = READERS[image.mimeType.toLowerCase()];
532
+ if (!read) return void 0;
533
+ const prefix = Buffer.from(image.data.slice(0, HEADER_BASE64_CHARS), "base64");
534
+ const canReadMore = read === readJpeg && image.data.length > HEADER_BASE64_CHARS;
535
+ const dimensions = read(prefix) ?? (canReadMore ? read(Buffer.from(image.data, "base64")) : void 0);
536
+ return dimensions && dimensions.width > 0 && dimensions.height > 0 ? dimensions : void 0;
537
+ }
538
+ function hasAscii(bytes, offset, text) {
539
+ return bytes.toString("latin1", offset, offset + text.length) === text;
540
+ }
541
+ function readPng(bytes) {
542
+ if (bytes.length < 24) return void 0;
543
+ if (bytes.readUInt32BE(0) !== 2303741511 || !hasAscii(bytes, 12, "IHDR")) return;
544
+ return {
545
+ width: bytes.readUInt32BE(16),
546
+ height: bytes.readUInt32BE(20)
547
+ };
548
+ }
549
+ function readGif(bytes) {
550
+ if (bytes.length < 10) return void 0;
551
+ if (!hasAscii(bytes, 0, "GIF87a") && !hasAscii(bytes, 0, "GIF89a")) return;
552
+ return {
553
+ width: bytes.readUInt16LE(6),
554
+ height: bytes.readUInt16LE(8)
555
+ };
556
+ }
557
+ function readJpeg(bytes) {
558
+ if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216) return;
559
+ let offset = 2;
560
+ while (offset + 4 <= bytes.length) {
561
+ if (bytes[offset] !== 255) return void 0;
562
+ const marker = bytes[offset + 1];
563
+ if (marker === 255) {
564
+ offset += 1;
565
+ continue;
566
+ }
567
+ if (marker === 1 || marker >= 208 && marker <= 215) {
568
+ offset += 2;
569
+ continue;
570
+ }
571
+ const length = bytes.readUInt16BE(offset + 2);
572
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
573
+ if (offset + 9 > bytes.length) return void 0;
574
+ return {
575
+ height: bytes.readUInt16BE(offset + 5),
576
+ width: bytes.readUInt16BE(offset + 7)
577
+ };
578
+ }
579
+ if (length < 2) return void 0;
580
+ offset += 2 + length;
581
+ }
582
+ }
583
+ function readWebp(bytes) {
584
+ if (bytes.length < 30) return void 0;
585
+ if (!hasAscii(bytes, 0, "RIFF") || !hasAscii(bytes, 8, "WEBP")) return;
586
+ if (hasAscii(bytes, 12, "VP8 ")) {
587
+ if (bytes.readUIntBE(23, 3) !== 10289450) return void 0;
588
+ return {
589
+ width: bytes.readUInt16LE(26) & 16383,
590
+ height: bytes.readUInt16LE(28) & 16383
591
+ };
592
+ }
593
+ if (hasAscii(bytes, 12, "VP8L")) {
594
+ if (bytes[20] !== 47) return void 0;
595
+ const bits = bytes.readUInt32LE(21);
596
+ return {
597
+ width: (bits & 16383) + 1,
598
+ height: (bits >>> 14 & 16383) + 1
599
+ };
600
+ }
601
+ if (hasAscii(bytes, 12, "VP8X")) return {
602
+ width: bytes.readUIntLE(24, 3) + 1,
603
+ height: bytes.readUIntLE(27, 3) + 1
604
+ };
605
+ }
606
+ // src/chat/services/token-estimate.ts
607
+ const CLAUDE_TOKEN_ESTIMATE = {
608
+ charsPerToken: 2.5,
609
+ toolResultOverheadTokens: 150
610
+ };
611
+ const DEFAULT_TOKEN_ESTIMATE = {
612
+ charsPerToken: 4,
613
+ toolResultOverheadTokens: 0
614
+ };
615
+ const IMAGE_CHARS = 4800;
616
+ const CLAUDE_HIGH_RES_IMAGE = {
617
+ maxEdge: 2576,
618
+ maxTokens: 4784
619
+ };
620
+ const CLAUDE_STANDARD_IMAGE = {
621
+ maxEdge: 1568,
622
+ maxTokens: 1568
623
+ };
624
+ const CLAUDE_STANDARD_IMAGE_MODEL = /^anthropic\/claude-(?:3\b|[a-z]+-4(?:\.[0-6])?(?![.\d]))/;
625
+ const CLAUDE_IMAGE_PATCH_PX = 28;
626
+ function getTokenEstimateProfile(modelId) {
627
+ return modelId.startsWith("anthropic/") ? CLAUDE_TOKEN_ESTIMATE : DEFAULT_TOKEN_ESTIMATE;
628
+ }
629
+ function tokensForChars(chars, profile) {
630
+ return Math.ceil(chars / profile.charsPerToken);
631
+ }
632
+ function messageChars(message) {
633
+ switch (message.role) {
634
+ case "user":
635
+ case "toolResult": return contentChars(message.content);
636
+ case "assistant": {
637
+ let chars = 0;
638
+ for (const block of message.content) if (block.type === "text") chars += block.text.length;
639
+ else if (block.type === "thinking") chars += block.thinking.length;
640
+ else chars += block.name.length + JSON.stringify(block.arguments).length;
641
+ return chars;
642
+ }
643
+ default: return 0;
644
+ }
645
+ }
646
+ function contentChars(content) {
647
+ if (typeof content === "string") return content.length;
648
+ return content.reduce((chars, block) => chars + (block.type === "text" ? block.text.length : 0), 0);
649
+ }
650
+ function messageImages(message) {
651
+ if (message.role !== "user" && message.role !== "toolResult") return [];
652
+ if (typeof message.content === "string") return [];
653
+ return message.content.filter((block) => block.type === "image");
654
+ }
655
+ function claudeImagePatches(width, height) {
656
+ return Math.ceil(width / CLAUDE_IMAGE_PATCH_PX) * Math.ceil(height / CLAUDE_IMAGE_PATCH_PX);
657
+ }
658
+ function roundHalfToEven(value) {
659
+ const floor = Math.floor(value);
660
+ if (value - floor !== .5) return Math.round(value);
661
+ return floor % 2 === 0 ? floor : floor + 1;
662
+ }
663
+ /**
664
+ * The size Claude resizes an image to before it counts patches. This is the
665
+ * reference implementation in "How Claude resizes and pads images" in
666
+ * https://platform.claude.com/docs/en/build-with-claude/vision-coordinates:
667
+ * the largest aspect-preserving size whose padded edges and patch count fit
668
+ * the tier limits.
669
+ */
670
+ function claudeResizedImageSize(width, height, limits) {
671
+ const fits = (w, h) => Math.ceil(w / CLAUDE_IMAGE_PATCH_PX) * CLAUDE_IMAGE_PATCH_PX <= limits.maxEdge && Math.ceil(h / CLAUDE_IMAGE_PATCH_PX) * CLAUDE_IMAGE_PATCH_PX <= limits.maxEdge && claudeImagePatches(w, h) <= limits.maxTokens;
672
+ if (fits(width, height)) return [width, height];
673
+ if (height > width) {
674
+ const [resizedHeight, resizedWidth] = claudeResizedImageSize(height, width, limits);
675
+ return [resizedWidth, resizedHeight];
676
+ }
677
+ const aspectRatio = width / height;
678
+ const shortEdge = (longEdge) => Math.max(roundHalfToEven(longEdge / aspectRatio), 1);
679
+ let low = 1;
680
+ let high = width;
681
+ while (low + 1 < high) {
682
+ const mid = Math.floor((low + high) / 2);
683
+ if (fits(mid, shortEdge(mid))) low = mid;
684
+ else high = mid;
685
+ }
686
+ return [low, shortEdge(low)];
687
+ }
688
+ /**
689
+ * Estimate one image for a model with the rule that `estimateMessagesTokens`
690
+ * uses. `sized` is false when the image used the flat per-image value.
691
+ */
692
+ function estimateImageTokens(image, modelId) {
693
+ const dimensions = modelId.startsWith("anthropic/") ? readImageDimensions(image) : void 0;
694
+ if (!dimensions) return {
695
+ tokens: tokensForChars(IMAGE_CHARS, getTokenEstimateProfile(modelId)),
696
+ sized: false
697
+ };
698
+ const limits = CLAUDE_STANDARD_IMAGE_MODEL.test(modelId) ? CLAUDE_STANDARD_IMAGE : CLAUDE_HIGH_RES_IMAGE;
699
+ const [width, height] = claudeResizedImageSize(dimensions.width, dimensions.height, limits);
700
+ return {
701
+ tokens: claudeImagePatches(width, height),
702
+ sized: true
703
+ };
704
+ }
705
+ /** Estimate text tokens for local budgets that have no model. */
706
+ function estimateTextTokens(text) {
707
+ return tokensForChars(text.length, DEFAULT_TOKEN_ESTIMATE);
708
+ }
709
+ /** Convert a local text token budget to the characters it allows. */
710
+ function textCharsForTokens(tokens) {
711
+ return tokens * DEFAULT_TOKEN_ESTIMATE.charsPerToken;
712
+ }
713
+ /**
714
+ * Estimate messages from their text size at the model's characters per token,
715
+ * plus the tokens of each image.
716
+ */
717
+ function estimateMessagesTokens(messages, modelId) {
718
+ const profile = getTokenEstimateProfile(modelId);
719
+ return messages.reduce((total, message) => {
720
+ const overhead = message.role === "toolResult" ? profile.toolResultOverheadTokens : 0;
721
+ const images = messageImages(message).reduce((tokens, image) => tokens + estimateImageTokens(image, modelId).tokens, 0);
722
+ return total + tokensForChars(messageChars(message), profile) + images + overhead;
723
+ }, 0);
724
+ }
725
+ /** Estimate the tokens that the system prompt and tool definitions add to a model request. */
726
+ function estimateRequestOverheadTokens(systemPrompt, tools, modelId) {
727
+ const definitions = tools.map(({ name, description, parameters }) => ({
728
+ name,
729
+ description,
730
+ parameters
731
+ }));
732
+ return tokensForChars(systemPrompt.length + JSON.stringify(definitions).length, getTokenEstimateProfile(modelId));
733
+ }
734
+ // src/chat/pi/request-prefix-attributes.ts
735
+ const HASH_HEX_CHARS = 16;
736
+ const MESSAGE_SEPARATOR = "\n";
737
+ function withoutCacheControl(key, value) {
738
+ return key === "cache_control" ? void 0 : value;
739
+ }
740
+ function canonicalMessageValue(key, value) {
741
+ if (key === "content" && typeof value === "string") return [{
742
+ type: "text",
743
+ text: value
744
+ }];
745
+ return withoutCacheControl(key, value);
746
+ }
747
+ function digest(hash) {
748
+ return hash.digest("hex").slice(0, HASH_HEX_CHARS);
749
+ }
750
+ function hashJson(value, replacer = withoutCacheControl) {
751
+ return digest(createHash("sha256").update(JSON.stringify(value, replacer)));
752
+ }
753
+ function lastAssistantIndex(messages) {
754
+ for (let index = messages.length - 1; index >= 0; index--) {
755
+ const message = messages[index];
756
+ if (typeof message === "object" && message !== null && message.role === "assistant") return index;
757
+ }
758
+ return -1;
759
+ }
760
+ function messagesHashes(messages) {
761
+ const lastReply = lastAssistantIndex(messages);
762
+ const hash = createHash("sha256");
763
+ let beforeLastReply;
764
+ for (const [index, message] of messages.entries()) {
765
+ if (index === lastReply) beforeLastReply = digest(hash.copy());
766
+ hash.update(JSON.stringify(message, canonicalMessageValue)).update(MESSAGE_SEPARATOR);
767
+ }
768
+ return {
769
+ full: digest(hash),
770
+ beforeLastReply
771
+ };
772
+ }
773
+ function sortedKeys(_key, value) {
774
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return value;
775
+ return Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));
776
+ }
777
+ function prefixHash(parts) {
778
+ return digest(createHash("sha256").update(parts.map((part) => part ?? "").join("\n")));
779
+ }
780
+ function readableString(value, key) {
781
+ if (typeof value !== "object" || value === null) return;
782
+ const field = value[key];
783
+ return typeof field === "string" ? field : void 0;
784
+ }
785
+ function requestImages(messages) {
786
+ const images = [];
787
+ const visit = (content) => {
788
+ if (!Array.isArray(content)) return;
789
+ for (const block of content) {
790
+ if (typeof block !== "object" || block === null) continue;
791
+ const { type, source, content: nested } = block;
792
+ if (type === "image") images.push({
793
+ type: "image",
794
+ data: readableString(source, "data") ?? "",
795
+ mimeType: readableString(source, "media_type") ?? ""
796
+ });
797
+ else if (type === "tool_result") visit(nested);
798
+ }
799
+ };
800
+ for (const message of messages) visit(message?.content);
801
+ return images;
802
+ }
803
+ function imageAttributes(messages, model) {
804
+ const images = Array.isArray(messages) ? requestImages(messages) : [];
805
+ if (images.length === 0) return {};
806
+ const modelId = typeof model === "string" ? model : "";
807
+ let estimate = 0;
808
+ let unsized = 0;
809
+ for (const image of images) {
810
+ const { tokens, sized } = estimateImageTokens(image, modelId);
811
+ estimate += tokens;
812
+ if (!sized) unsized += 1;
813
+ }
814
+ return {
815
+ "app.ai.request.images.count": images.length,
816
+ "app.ai.request.images.estimate": estimate,
817
+ "app.ai.request.images.unsized": unsized
818
+ };
819
+ }
820
+ function payloadAttributes(payload) {
821
+ const { model, system, tools, messages, thinking, output_config } = payload;
822
+ const systemHash = system !== void 0 ? hashJson(system) : void 0;
823
+ const toolsHash = Array.isArray(tools) ? hashJson(tools) : void 0;
824
+ const messagesHash = Array.isArray(messages) ? messagesHashes(messages) : void 0;
825
+ const settingsHash = hashJson({
826
+ thinking,
827
+ output_config
828
+ }, sortedKeys);
829
+ const prefixParts = [
830
+ typeof model === "string" ? model : void 0,
831
+ settingsHash,
832
+ toolsHash,
833
+ systemHash
834
+ ];
835
+ const thinkingType = readableString(thinking, "type");
836
+ const effort = readableString(output_config, "effort");
837
+ return {
838
+ ...systemHash ? { "app.ai.request.system_instructions.hash": systemHash } : void 0,
839
+ "app.ai.request.tools.count": Array.isArray(tools) ? tools.length : 0,
840
+ ...toolsHash ? { "app.ai.request.tools.hash": toolsHash } : void 0,
841
+ ...Array.isArray(messages) ? { "app.ai.request.messages.count": messages.length } : void 0,
842
+ ...messagesHash ? { "app.ai.request.messages.hash": messagesHash.full } : void 0,
843
+ ...messagesHash?.beforeLastReply ? { "app.ai.request.messages.before_last_reply.hash": messagesHash.beforeLastReply } : void 0,
844
+ "app.ai.request.prefix.hash": prefixHash([...prefixParts, messagesHash?.full]),
845
+ ...messagesHash?.beforeLastReply ? { "app.ai.request.prefix.before_last_reply.hash": prefixHash([...prefixParts, messagesHash.beforeLastReply]) } : void 0,
846
+ ...thinkingType ? { "app.ai.request.thinking.type": thinkingType } : void 0,
847
+ ...effort ? { "app.ai.request.effort": effort } : void 0,
848
+ ...imageAttributes(messages, model)
849
+ };
850
+ }
851
+ /**
852
+ * Hashes of the cache prefix parts of one provider request body, plus its
853
+ * thinking and effort settings, to tell a changed cache prefix apart from an
854
+ * expired cache. Also counts and estimates the request's images.
855
+ * Pass the payload that Pi gives to `onPayload`. Never throws: telemetry must
856
+ * not fail the request.
857
+ */
858
+ function requestPrefixAttributes(payload) {
859
+ if (typeof payload !== "object" || payload === null) return {};
860
+ try {
861
+ return payloadAttributes(payload);
862
+ } catch {
863
+ return {};
864
+ }
865
+ }
517
866
  // src/chat/pi/client.ts
518
867
  registerApiProvider({
519
868
  api: "anthropic-messages",
@@ -710,7 +1059,8 @@ async function completeText(params) {
710
1059
  try {
711
1060
  message = await completeSimple(model, {
712
1061
  systemPrompt: params.system,
713
- messages: params.messages
1062
+ messages: params.messages,
1063
+ ...params.tools ? { tools: params.tools } : void 0
714
1064
  }, {
715
1065
  apiKey,
716
1066
  temperature: params.temperature,
@@ -718,7 +1068,11 @@ async function completeText(params) {
718
1068
  reasoning: params.thinkingLevel,
719
1069
  cacheRetention: params.cacheRetention,
720
1070
  signal: params.signal,
721
- metadata: params.metadata
1071
+ metadata: params.metadata,
1072
+ sessionId: params.sessionId,
1073
+ onPayload: (payload) => {
1074
+ setSpanAttributes(requestPrefixAttributes(payload));
1075
+ }
722
1076
  });
723
1077
  } catch (error) {
724
1078
  throw createProviderError(error, { modelId: params.modelId });
@@ -1143,11 +1497,11 @@ function parseOptionalPositiveInteger(envName, rawValue) {
1143
1497
  if (!Number.isSafeInteger(value) || value <= 0 || String(value) !== trimmed) throw new Error(`${envName} must be a positive integer`);
1144
1498
  return value;
1145
1499
  }
1146
- function parseConversationWorkEnabled(rawValue) {
1500
+ function parseKillSwitch(name, rawValue) {
1147
1501
  const value = toOptionalTrimmed(rawValue)?.toLowerCase();
1148
1502
  if (value === void 0 || value === "true") return true;
1149
1503
  if (value === "false") return false;
1150
- throw new Error("JUNIOR_CONVERSATION_WORK_ENABLED must be true or false");
1504
+ throw new Error(`${name} must be true or false`);
1151
1505
  }
1152
1506
  const DEFAULT_MODEL_ID = resolveGatewayModel("anthropic/claude-opus-5.5").id;
1153
1507
  const DEFAULT_REASONING_LEVEL = "high";
@@ -1248,7 +1602,8 @@ function readChatConfig(env = process.env, functionMaxDurationSeconds = DEFAULT_
1248
1602
  bot: readBotConfig(env, resolvedFunctionMaxDurationSeconds),
1249
1603
  queue: readQueueConfig(env),
1250
1604
  functionMaxDurationSeconds: resolvedFunctionMaxDurationSeconds,
1251
- conversationWorkEnabled: parseConversationWorkEnabled(env.JUNIOR_CONVERSATION_WORK_ENABLED),
1605
+ cacheWarmingEnabled: parseKillSwitch("JUNIOR_CACHE_WARMING_ENABLED", env.JUNIOR_CACHE_WARMING_ENABLED),
1606
+ conversationWorkEnabled: parseKillSwitch("JUNIOR_CONVERSATION_WORK_ENABLED", env.JUNIOR_CONVERSATION_WORK_ENABLED),
1252
1607
  conversationWorkSoftYieldAfterMs: resolveConversationWorkSoftYieldAfterMs(resolvedFunctionMaxDurationSeconds),
1253
1608
  sql: {
1254
1609
  databaseUrl,
@@ -1367,4 +1722,4 @@ function setSlackReactionConfig(overrides) {
1367
1722
  if (overrides.processingReactionEmoji !== void 0) chatConfig.slack.processingReactionEmoji = parseReactionEmoji("processingReactionEmoji", overrides.processingReactionEmoji, chatConfig.slack.processingReactionEmoji);
1368
1723
  if (overrides.completedReactionEmoji !== void 0) chatConfig.slack.completedReactionEmoji = parseReactionEmoji("completedReactionEmoji", overrides.completedReactionEmoji, chatConfig.slack.completedReactionEmoji);
1369
1724
  }
1370
- export { renderCurrentInstruction as A, getGatewayApiKey as B, completeText as C, COMPACTION_SUMMARY_PREFIX as D, resolveGatewayModel as E, createProviderError as F, getAttachmentStorage as H, findProviderError as I, getProviderErrorAttributes as L, escapeXml as M, escapeXmlText as N, hasCompactedConversationContext as O, ProviderError as P, getProviderErrorUserMessage as R, completeObject as S, rerankTexts as T, toOptionalTrimmed as U, resolveGatewayCredential as V, toPiReasoningLevel as _, getRuntimeMetadata as a, GEN_AI_SERVER_ADDRESS as b, getSlackClientSecret as c, restoreRuntimeConfig as d, setBotModelConfig as f, TURN_REASONING_LEVELS as g, snapshotRuntimeConfig as h, getChatConfig as i, unwrapCurrentInstruction as j, isCompactionSummaryText as k, getSlackSigningSecret as l, setSlackReactionConfig as m, botConfig as n, getSlackBotToken as o, setRuntimeLimits as p, config_exports as r, getSlackClientId as s, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as t, resetRuntimeConfig as u, normalizeSlackEmojiName as v, embedTexts as w, completeDecision as x, GEN_AI_PROVIDER_NAME as y, isProviderRetryError as z };
1725
+ export { estimateTextTokens as A, createProviderError as B, completeText as C, requestPrefixAttributes as D, resolveGatewayModel as E, renderCurrentInstruction as F, getGatewayApiKey as G, getProviderErrorAttributes as H, unwrapCurrentInstruction as I, toOptionalTrimmed as J, resolveGatewayCredential as K, escapeXml as L, COMPACTION_SUMMARY_PREFIX as M, hasCompactedConversationContext as N, estimateMessagesTokens as O, isCompactionSummaryText as P, escapeXmlText as R, completeObject as S, rerankTexts as T, getProviderErrorUserMessage as U, findProviderError as V, isProviderRetryError as W, toPiReasoningLevel as _, getRuntimeMetadata as a, GEN_AI_SERVER_ADDRESS as b, getSlackClientSecret as c, restoreRuntimeConfig as d, setBotModelConfig as f, TURN_REASONING_LEVELS as g, snapshotRuntimeConfig as h, getChatConfig as i, textCharsForTokens as j, estimateRequestOverheadTokens as k, getSlackSigningSecret as l, setSlackReactionConfig as m, botConfig as n, getSlackBotToken as o, setRuntimeLimits as p, getAttachmentStorage as q, config_exports as r, getSlackClientId as s, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as t, resetRuntimeConfig as u, normalizeSlackEmojiName as v, embedTexts as w, completeDecision as x, GEN_AI_PROVIDER_NAME as y, ProviderError as z };
@@ -1,132 +1,10 @@
1
- import { Bi as startOAuthFlow, Z as loadTurnCheckpoint, it as getTurnRecord, rt as failTurnRecord } from "./projection-CL_YWeGf.js";
2
- import { n as botConfig } from "./config-CkHcUMN7.js";
3
- import { A as deleteProviderIdentityForUser, a as getConversationStore, k as deleteProviderIdentityForSlackUser, r as getConversationEventStore, s as getSqlExecutor } from "./db-DJ11eZqq.js";
4
- import { u as hasRequiredOAuthScope } from "./registry-BriFLnaJ.js";
5
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BCIuBe4d.js";
6
- import { c as deleteMcpServerSessionId, l as deleteMcpStoredOAuthCredentials, s as deleteMcpAuthSessionsForUserProvider } from "./agent-runner-Bfnw551N.js";
7
- import { _ as getVercelConversationWorkQueue } from "./background-compaction-queue-CYI909P5.js";
8
- import { T as requestConversationWork, h as ensureConversationWake } from "./store-DdIEUL1q.js";
9
- import { mt as resolveTurnSessionRouting } from "./task-runner-D_RDr2Hu.js";
1
+ import { Fi as startOAuthFlow } from "./projection-BFJG58TG.js";
2
+ import { n as botConfig } from "./config-DHAy7XlP.js";
3
+ import { A as deleteProviderIdentityForUser, k as deleteProviderIdentityForSlackUser, s as getSqlExecutor } from "./db-BS2Kql3j.js";
4
+ import { u as hasRequiredOAuthScope } from "./registry-C_JrgqUz.js";
5
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BNK4uJVZ.js";
6
+ import { c as deleteMcpServerSessionId, l as deleteMcpStoredOAuthCredentials, s as deleteMcpAuthSessionsForUserProvider } from "./agent-runner-bvl8U5uH.js";
10
7
  import { randomBytes } from "node:crypto";
11
- import * as z from "zod";
12
- // src/chat/task-execution/authorized-turn.ts
13
- /**
14
- * OAuth callbacks save readiness, not agent history. The conversation worker
15
- * consumes this event under its lease before it resumes the paused Turn.
16
- */
17
- const authorizationSchema = z.object({
18
- kind: z.enum(["mcp", "plugin"]),
19
- provider: z.string().min(1),
20
- actorId: z.string().min(1),
21
- authorizationId: z.string().min(1),
22
- authSessionId: z.string().optional(),
23
- scope: z.string().optional(),
24
- configuration: z.record(z.string(), z.unknown()).optional(),
25
- toolChannelId: z.string().optional()
26
- });
27
- function authorizationKey(turn) {
28
- return `turn:${turn.turnId}:authorization:${turn.version}`;
29
- }
30
- /** Save authorization for this parked boundary without changing model history. */
31
- async function recordTurnAuthorization(args) {
32
- const turn = await getTurnRecord(args.conversationId, args.turnId);
33
- if (!turn || turn.state !== "paused" || turn.resumeReason !== "auth") return;
34
- await getConversationEventStore().append(args.conversationId, [{
35
- idempotencyKey: authorizationKey(turn),
36
- createdAtMs: Date.now(),
37
- data: {
38
- type: "structured_event",
39
- namespace: "junior",
40
- name: "turn_authorized",
41
- version: 1,
42
- turnId: turn.turnId,
43
- content: authorizationSchema.parse(args)
44
- }
45
- }], { activity: "preserve" });
46
- return {
47
- conversationId: args.conversationId,
48
- destination: args.destination,
49
- turnId: turn.turnId,
50
- expectedVersion: turn.version
51
- };
52
- }
53
- /** Read authorization for the exact pause; a later auth pause needs its own callback. */
54
- async function getTurnAuthorization(turn) {
55
- const event = await getConversationEventStore().loadByIdempotencyKey(turn.conversationId, authorizationKey(turn));
56
- if (event?.data.type !== "structured_event") return void 0;
57
- return authorizationSchema.parse(event.data.content);
58
- }
59
- // src/chat/task-execution/turn-wake.ts
60
- /** Build the worker input for a paused turn. */
61
- async function getPausedTurnRequest(args) {
62
- const turn = (await loadTurnCheckpoint({
63
- conversationId: args.conversationId,
64
- turnId: args.turnId
65
- })).record;
66
- if (!turn || turn.state !== "paused" || turn.resumeReason !== "timeout" && turn.resumeReason !== "yield" && turn.resumeReason !== "retry" && !(turn.resumeReason === "auth" && await getTurnAuthorization(turn)) || turn.resumeReason === "timeout" && turn.sliceId < 2) return;
67
- let routing;
68
- try {
69
- routing = await resolveTurnSessionRouting({
70
- conversationId: args.conversationId,
71
- conversationStore: args.conversationStore
72
- });
73
- } catch (error) {
74
- await failTurnRecord({
75
- conversationId: args.conversationId,
76
- expectedVersion: turn.version,
77
- turnId: args.turnId,
78
- errorMessage: error instanceof Error ? error.message : String(error)
79
- });
80
- return;
81
- }
82
- return {
83
- conversationId: args.conversationId,
84
- destination: routing.destination,
85
- turnId: args.turnId,
86
- expectedVersion: turn.version,
87
- traceContext: turn.traceContext
88
- };
89
- }
90
- /** Wake the conversation worker for a paused turn. */
91
- async function wakePausedTurn(request, options = {}) {
92
- const nowMs = options.nowMs ?? Date.now();
93
- const conversation = await (options.conversationStore ?? getConversationStore()).get({ conversationId: request.conversationId });
94
- await requestConversationWork({
95
- conversationId: request.conversationId,
96
- destination: conversation && conversation.kind !== "root" ? void 0 : request.destination,
97
- nowMs,
98
- state: options.state
99
- });
100
- const queue = options.queue ?? getVercelConversationWorkQueue();
101
- await ensureConversationWake({
102
- conversationId: request.conversationId,
103
- idempotencyKey: [
104
- "agent-continue",
105
- request.conversationId,
106
- request.turnId,
107
- request.expectedVersion,
108
- nowMs
109
- ].join(":"),
110
- nowMs,
111
- queue,
112
- state: options.state
113
- });
114
- }
115
- /** Create paused Turn operations for one app. */
116
- function createPausedTurns(options = {}) {
117
- return {
118
- get: (args) => getPausedTurnRequest({
119
- ...args,
120
- conversationStore: options.conversationStore
121
- }),
122
- wake: (request) => wakePausedTurn(request, options)
123
- };
124
- }
125
- /** Record completed authorization and wake the sole execution owner. */
126
- async function wakeAuthorizedTurn(args, queue) {
127
- const request = await recordTurnAuthorization(args);
128
- if (request) await wakePausedTurn(request, { queue });
129
- }
130
8
  // src/handlers/oauth-html.ts
131
9
  /** Build pre-escaped callback HTML with the shared response security policy. */
132
10
  function htmlCallbackResponse(title, message, status, options = {}) {
@@ -367,4 +245,4 @@ async function disconnectConnection(userId, provider, userTokenStore) {
367
245
  if (tokens?.account) await deleteProviderIdentityForUser(getSqlExecutor(), userId, provider, tokens.account.id);
368
246
  await unlinkProvider(userId, provider, userTokenStore);
369
247
  }
370
- export { startConnection as a, createPausedTurns as c, wakePausedTurn as d, getTurnAuthorization as f, readConnectedOAuthTokens as i, getPausedTurnRequest as l, isConnectableProvider as n, unlinkProvider as o, listConnections as r, htmlCallbackResponse as s, disconnectConnection as t, wakeAuthorizedTurn as u };
248
+ export { startConnection as a, readConnectedOAuthTokens as i, isConnectableProvider as n, unlinkProvider as o, listConnections as r, htmlCallbackResponse as s, disconnectConnection as t };
@@ -1,4 +1,4 @@
1
- import { c as conversationTurnFailureCodeSchema, l as conversationTurnFailureReasonSchema, n as INPUT_IMAGE_TYPES, y as usageSchema } from "./media-Cz1ZiV1U.js";
1
+ import { c as conversationTurnFailureCodeSchema, l as conversationTurnFailureReasonSchema, n as INPUT_IMAGE_TYPES, y as usageSchema } from "./media-BepyEUNm.js";
2
2
  import * as z from "zod";
3
3
  import { codeChangeStateSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, conversationSidebarAnnotationSchema, objectFactFields, objectTypeSchema } from "@sentry/junior-plugin-api";
4
4
  // src/chat/briefs/schema.ts
@@ -274,6 +274,15 @@ const conversationReadPositionSchema = z.object({ lastReadSeq: z.number().int().
274
274
  * flag from this, so it does not refetch the feed after each report.
275
275
  */
276
276
  const conversationReadReportSchema = conversationReadPositionSchema.extend({ unreadReply: z.boolean() }).strict();
277
+ // src/api/schema/conversation-title.ts
278
+ /** Longest Conversation title that a rename can save. */
279
+ const CONVERSATION_TITLE_MAX_LENGTH = 200;
280
+ /** A Conversation title that a caller chooses, at creation or on rename. */
281
+ const conversationTitleSchema = z.string().trim().min(1).max(200);
282
+ /** A participant's new title for one Conversation. Every viewer sees it. */
283
+ const renameConversationBodySchema = z.object({ title: conversationTitleSchema }).strict();
284
+ /** The stored title after the rename. */
285
+ const renameConversationResponseSchema = z.object({ title: z.string().min(1) }).strict();
277
286
  // src/api/schema/child-agent-totals.ts
278
287
  /**
279
288
  * The part of a Conversation total that its child agents spent, at any depth.
@@ -367,9 +376,12 @@ const createConversationMessageBodySchema = z.object({
367
376
  message: z.string().trim().max(32e3),
368
377
  images: z.array(inputImageSchema).max(3).optional()
369
378
  }).strict().refine((body) => Boolean(body.message || body.images?.length), "Add a message or an image.").refine((body) => (body.images ?? []).reduce((sum, image) => sum + image.data.length, 0) <= MAX_INPUT_IMAGE_BYTES * 4 / 3, "Images must total 3 MB or less.");
370
- const createConversationBodySchema = createConversationMessageBodySchema.safeExtend({
371
- /** New roots default public. Private roots stay participant-only. */
372
- visibility: z.enum(["private", "public"]).optional() });
379
+ const createConversationBodySchema = createConversationMessageBodySchema.safeExtend({
380
+ /** Saved title. Title generation runs only when it is omitted. */
381
+ title: conversationTitleSchema.optional(),
382
+ /** New roots default public. Private roots stay participant-only. */
383
+ visibility: z.enum(["private", "public"]).optional()
384
+ });
373
385
  const acceptedConversationMessageSchema = z.object({
374
386
  conversationId: z.string().min(1),
375
387
  messageId: z.string().min(1),
@@ -880,6 +892,11 @@ const conversationDetailReportSchema = conversationSummaryReportSchema.extend({
880
892
  /** The viewer can move this dashboard conversation to a Slack thread. */
881
893
  canContinueInSlack: z.literal(true).optional(),
882
894
  /**
895
+ * Event Turn replies stay out of the Location. Set only for a root with
896
+ * a Location, when the viewer is a participant, who can change it.
897
+ */
898
+ deliveryPaused: z.boolean().optional(),
899
+ /**
883
900
  * The viewer gets this conversation in their active feed. Participants
884
901
  * only. False after an unsubscribe, until they mention Junior again.
885
902
  */
@@ -942,4 +959,4 @@ const conversationFeedSchema = z.object({
942
959
  source: z.literal("conversation_index"),
943
960
  generatedAt: z.string()
944
961
  }).strict();
945
- export { reviewItemChangeRecordSchema as A, readMessageAttachments as B, createConversationBodySchema as C, conversationChildAgentTotalsSchema as D, forkConversationResponseSchema as E, removedCardSchema as F, conversationBriefSchema as G, briefLinkSchema as H, resolveMessageCards as I, parseBriefInput as K, MAX_INPUT_IMAGES as L, messageCardRef as M, messageCardText as N, conversationReadPositionSchema as O, readMessageCardRefs as P, MAX_INPUT_IMAGE_BYTES as R, conversationUsageSchema as S, forkConversationBodySchema as T, briefOutcomeStatusSchema as U, briefCodeChangeSchema as V, briefResourceLabel as W, conversationReportEventSchema as _, conversationActivityPreviewSchema as a, conversationSummaryReportSchema as b, conversationDetailQuerySchema as c, conversationEventPageSchema as d, conversationEventsQuerySchema as f, conversationReportEventDataSchema as g, conversationParamsSchema as h, actorIdentitySchema as i, annotationCard as j, conversationReadReportSchema as k, conversationDetailReportSchema as l, conversationFeedSchema as m, CONVERSATION_VERSION_HEADER as n, conversationAttachmentParamsSchema as o, conversationFeedQuerySchema as p, parseStoredBrief as q, acceptedConversationMessageSchema as r, conversationAuxiliaryCostsSchema as s, CONVERSATION_DETAIL_VERSION_HEADER as t, conversationEventHistorySchema as u, conversationReportMessageEventSchema as v, createConversationMessageBodySchema as w, conversationSurfaceSchema as x, conversationReportStatusSchema as y, messageAttachmentSchema as z };
962
+ export { renameConversationBodySchema as A, resolveMessageCards as B, createConversationBodySchema as C, conversationChildAgentTotalsSchema as D, forkConversationResponseSchema as E, annotationCard as F, briefCodeChangeSchema as G, MAX_INPUT_IMAGE_BYTES as H, messageCardRef as I, briefResourceLabel as J, briefLinkSchema as K, messageCardText as L, conversationReadPositionSchema as M, conversationReadReportSchema as N, CONVERSATION_TITLE_MAX_LENGTH as O, reviewItemChangeRecordSchema as P, readMessageCardRefs as R, conversationUsageSchema as S, forkConversationBodySchema as T, messageAttachmentSchema as U, MAX_INPUT_IMAGES as V, readMessageAttachments as W, parseBriefInput as X, conversationBriefSchema as Y, parseStoredBrief as Z, conversationReportEventSchema as _, conversationActivityPreviewSchema as a, conversationSummaryReportSchema as b, conversationDetailQuerySchema as c, conversationEventPageSchema as d, conversationEventsQuerySchema as f, conversationReportEventDataSchema as g, conversationParamsSchema as h, actorIdentitySchema as i, renameConversationResponseSchema as j, conversationTitleSchema as k, conversationDetailReportSchema as l, conversationFeedSchema as m, CONVERSATION_VERSION_HEADER as n, conversationAttachmentParamsSchema as o, conversationFeedQuerySchema as p, briefOutcomeStatusSchema as q, acceptedConversationMessageSchema as r, conversationAuxiliaryCostsSchema as s, CONVERSATION_DETAIL_VERSION_HEADER as t, conversationEventHistorySchema as u, conversationReportMessageEventSchema as v, createConversationMessageBodySchema as w, conversationSurfaceSchema as x, conversationReportStatusSchema as y, removedCardSchema as z };
@@ -1,4 +1,4 @@
1
- import { A as reviewItemChangeRecordSchema, i as actorIdentitySchema, l as conversationDetailReportSchema, z as messageAttachmentSchema } from "./conversation-E7ZPJx2H.js";
1
+ import { P as reviewItemChangeRecordSchema, U as messageAttachmentSchema, i as actorIdentitySchema, l as conversationDetailReportSchema } from "./conversation-CwC8K3RZ.js";
2
2
  import * as z from "zod";
3
3
  // src/reporting-schema.ts
4
4
  const healthReportSchema = z.object({
@@ -1,4 +1,4 @@
1
- import { h as logWarn } from "./logging-BO5zU6Mt.js";
1
+ import { h as logWarn } from "./logging-CtCJmt9p.js";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  // src/chat/conversation-privacy.ts
4
4
  const SAFE_METADATA_KEY_LIMIT = 20;