@sentry/junior 0.310.0 → 0.312.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 (157) hide show
  1. package/dist/{adapter-context-BhKpjpGD.js → adapter-context-BRjEWRy1.js} +2 -2
  2. package/dist/adapter-iIq7ihf7.js +259 -0
  3. package/dist/{admin-tgZEZAk2.js → admin-DhInw5K9.js} +1 -2
  4. package/dist/{agent-runner-D9cvNlQl.js → agent-runner-C9iDurwX.js} +6507 -7721
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +7 -6
  7. package/dist/api.d.ts +21 -3
  8. package/dist/api.js +1625 -535
  9. package/dist/{app-B_7Wn0en.d.ts → app-DRFrC8Mw.d.ts} +14 -10
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +454 -994
  12. package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-DrKi7w3d.js} +10 -85
  13. package/dist/callback-mFlTUWWx.js +75 -0
  14. package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-D7xapBAX.js} +1 -1
  15. package/dist/channel-access-CJGfNTdn.js +221 -0
  16. package/dist/child-message-DcsritGf.js +179 -0
  17. package/dist/cli/chat.js +18 -19
  18. package/dist/cli/check.js +23 -29
  19. package/dist/cli/init.js +1 -7
  20. package/dist/cli/main.js +3 -7
  21. package/dist/cli/plugins.js +8 -7
  22. package/dist/cli/run.d.ts +1 -2
  23. package/dist/cli/run.js +1 -2
  24. package/dist/cli/snapshot-create.js +5 -5
  25. package/dist/cli/upgrade.d.ts +1 -1
  26. package/dist/cli/upgrade.js +3 -3
  27. package/dist/{config-Dkt2Le2b.js → config-kXB2Y5tl.js} +294 -28
  28. package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-O6pV5004.js} +7 -7
  29. package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-uNOv_x68.js} +87 -24
  30. package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-L4ja1_W6.js} +1 -1
  31. package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-CeLbHqdw.js} +56 -49
  32. package/dist/{credential-sync-vGnrB0BY.js → credential-sync-I8VBGk05.js} +16 -16
  33. package/dist/{projection-jZSlEAXG.js → credentialed-Cb6E2phL.js} +16268 -16821
  34. package/dist/{db-B4Hjxr-u.d.ts → db-BbC5stfa.d.ts} +13 -6
  35. package/dist/{db-CFZggNoy.js → db-LAyyX8tk.js} +1698 -1046
  36. package/dist/{executor-BPkZDx5-.js → executor-SCub-fAq.js} +552 -181
  37. package/dist/{html-2r2KmLwi.js → html-BCZ3Xtb_.js} +6 -6
  38. package/dist/{session-stop-BfY4rhJs.js → ingest-BDf3D50j.js} +2134 -2553
  39. package/dist/{install-C-oE6C_u.js → install-DCFJFkC0.js} +2 -2
  40. package/dist/instrumentation.js +4 -4
  41. package/dist/{lineage-CsvrEFQe.js → lineage-B_m-4TJw.js} +2 -2
  42. package/dist/{stop-DYzjRf2U.js → list-CN2QA2R9.js} +1656 -685
  43. package/dist/{logging-D5gkyvnK.js → logging-dQ9ZRGQ8.js} +47 -9
  44. package/dist/media-CYm1QD8T.js +2356 -0
  45. package/dist/{message-DwvJ-I3w.js → message-DSXGj1hM.js} +19 -29
  46. package/dist/{model-input-MAq2881y.js → model-input--TrP9hYV.js} +3 -3
  47. package/dist/nitro.d.ts +1 -1
  48. package/dist/nitro.js +4 -3
  49. package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-DHCZC6B4.js} +2 -2
  50. package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-pPMGnDZt.js} +1 -1
  51. package/dist/{registry-BBkWFCl8.js → registry-CZOzddwu.js} +5 -8
  52. package/dist/{resolve-B38MkHXE.js → resolve-cKOQ14Dh.js} +3 -3
  53. package/dist/{result-BaqSZcJb.js → result-DcvEOe1r.js} +119 -93
  54. package/dist/result-event-type-BdIJuZxg.js +48 -0
  55. package/dist/rule-DAxQY-1h.js +20 -0
  56. package/dist/{runner-11h8PrHh.js → runner-DBfUW44l.js} +14 -16
  57. package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
  58. package/dist/{schema-DriSvB40.d.ts → schema-BEHKxr4I.d.ts} +861 -298
  59. package/dist/{schema-obw5jvR4.js → schema-Bk9Nm2E8.js} +344 -153
  60. package/dist/{service-account-Bx93N1n1.js → service-account-CVYsFjty.js} +3 -3
  61. package/dist/{service-account-Zc5bUcIJ.js → service-account-Ts4ulcrV.js} +68 -68
  62. package/dist/{skills-C8Npu5zO.js → skills-VTnhAJWm.js} +2 -2
  63. package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -11
  64. package/dist/{spawn-CXr58R0x.js → spawn-vxAarlX5.js} +6 -6
  65. package/dist/start-conversation-CEn2KH1A.js +941 -0
  66. package/dist/{state-CGrGVeQC.js → state-C1P3_Ywk.js} +4 -4
  67. package/dist/statuses-_cRJHXK7.js +150 -0
  68. package/dist/store-DFZaN-Ix.js +492 -0
  69. package/dist/task-queue-Cx4Lmjyk.js +90 -0
  70. package/dist/task-runner-CbTwFA6k.js +1432 -0
  71. package/dist/{thread-context-Dyj1KWaY.js → thread-context-BkAZDTX2.js} +13 -11
  72. package/dist/thread-state-DhPndWi1.js +5625 -0
  73. package/dist/{validation-DxVNIxA0.js → validation-nIzMtAVJ.js} +1 -1
  74. package/dist/{task-queue-CaZffYaH.js → vercel-queue-hW90XzbG.js} +93 -172
  75. package/dist/{version-Cr7Z71yG.js → version-Brbtz4Qf.js} +1 -1
  76. package/dist/version.js +1 -1
  77. package/dist/{warmup-C6LOZ2d2.js → warmup-BDA5myRK.js} +5832 -4567
  78. package/dist/web-message-id-C6P83ans.js +10 -0
  79. package/dist/{worker-CUBtu1Li.js → worker-D63RcaVD.js} +20 -8
  80. package/migrations/0126_artifact_drop_public.sql +8 -0
  81. package/migrations/0127_artifact_path.sql +4 -0
  82. package/migrations/0128_artifact_path_index.sql +1 -0
  83. package/migrations/0129_review_item_answered_index.sql +1 -0
  84. package/migrations/0130_review_item_status_index.sql +1 -0
  85. package/migrations/0131_brief_outcome_status.sql +1 -0
  86. package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
  87. package/migrations/0133_brief_created_at_index.sql +1 -0
  88. package/migrations/0134_slack_person_search_index.sql +1 -0
  89. package/migrations/0135_code_change_size.sql +3 -0
  90. package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
  91. package/migrations/0137_inbox_snoozes.sql +27 -0
  92. package/migrations/0138_code_change_search_index.sql +2 -0
  93. package/migrations/0139_review_item_owner.sql +22 -0
  94. package/migrations/0140_review_item_owner_index.sql +1 -0
  95. package/migrations/0141_memory_core_adoption.sql +89 -0
  96. package/migrations/0142_memory_core_indexes.sql +17 -0
  97. package/migrations/0143_todos.sql +14 -0
  98. package/migrations/0144_inbox_items.sql +32 -0
  99. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  100. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  101. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  102. package/migrations/0148_authorization_request_index.sql +1 -0
  103. package/migrations/0149_conversation_metadata.sql +10 -0
  104. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  105. package/migrations/0151_conversation_search_index.sql +1 -0
  106. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  107. package/migrations/0153_artifact_expiry.sql +1 -0
  108. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  109. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  110. package/migrations/0156_conversation_kind_lead.sql +6 -0
  111. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  112. package/migrations/meta/0126_snapshot.json +5488 -0
  113. package/migrations/meta/0127_snapshot.json +5519 -0
  114. package/migrations/meta/0128_snapshot.json +5519 -0
  115. package/migrations/meta/0129_snapshot.json +5547 -0
  116. package/migrations/meta/0130_snapshot.json +5563 -0
  117. package/migrations/meta/0131_snapshot.json +5569 -0
  118. package/migrations/meta/0132_snapshot.json +5569 -0
  119. package/migrations/meta/0133_snapshot.json +5590 -0
  120. package/migrations/meta/0134_snapshot.json +5606 -0
  121. package/migrations/meta/0135_snapshot.json +5624 -0
  122. package/migrations/meta/0136_snapshot.json +5624 -0
  123. package/migrations/meta/0137_snapshot.json +5864 -0
  124. package/migrations/meta/0138_snapshot.json +5894 -0
  125. package/migrations/meta/0139_snapshot.json +5898 -0
  126. package/migrations/meta/0140_snapshot.json +5919 -0
  127. package/migrations/meta/0141_snapshot.json +6429 -0
  128. package/migrations/meta/0142_snapshot.json +6457 -0
  129. package/migrations/meta/0143_snapshot.json +6434 -0
  130. package/migrations/meta/0144_snapshot.json +6434 -0
  131. package/migrations/meta/0145_snapshot.json +6440 -0
  132. package/migrations/meta/0146_snapshot.json +6446 -0
  133. package/migrations/meta/0147_snapshot.json +6452 -0
  134. package/migrations/meta/0148_snapshot.json +6474 -0
  135. package/migrations/meta/0149_snapshot.json +6490 -0
  136. package/migrations/meta/0150_snapshot.json +6490 -0
  137. package/migrations/meta/0151_snapshot.json +6505 -0
  138. package/migrations/meta/0152_snapshot.json +6505 -0
  139. package/migrations/meta/0153_snapshot.json +6511 -0
  140. package/migrations/meta/0154_snapshot.json +6533 -0
  141. package/migrations/meta/0155_snapshot.json +6511 -0
  142. package/migrations/meta/0156_snapshot.json +6511 -0
  143. package/migrations/meta/0157_snapshot.json +6527 -0
  144. package/migrations/meta/_journal.json +224 -0
  145. package/package.json +7 -8
  146. package/skills/design-automation-skill/SKILL.md +108 -0
  147. package/dist/briefs-DKxkoruh.js +0 -395
  148. package/dist/conversation-M9KZ5JxF.js +0 -1024
  149. package/dist/prompt-CaMyeCpA.js +0 -910
  150. package/dist/schedule-DWxZ3kja.js +0 -1146
  151. package/dist/store-D4FQ1Nml.js +0 -335
  152. package/dist/task-runner-Dm7BHbGp.js +0 -287
  153. package/dist/turn-session-routing-CD0BRCex.js +0 -263
  154. package/dist/turn-user-message-9IxeEv5v.js +0 -364
  155. package/dist/users-CaUAYMb3.js +0 -181
  156. package/dist/viewer-AHldghAD.js +0 -212
  157. package/dist/web-message-id-BT8Mg8LL.js +0 -418
@@ -1,7 +1,7 @@
1
- import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
1
  import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
3
- import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-D5gkyvnK.js";
4
- import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-C39g8BY4.js";
2
+ import { E as withSpan, g as normalizeGenAiFinishReason, h as logWarn, i as extractGenAiUsageAttributes, p as logException, v as serializeGenAiAttribute } from "./logging-dQ9ZRGQ8.js";
3
+ import { a as toCanonicalInputMessage, n as getCurrentConversationPrivacy, o as toCanonicalOutputMessage, s as toGenAiMessagesTraceAttributes } from "./conversation-privacy-L4ja1_W6.js";
4
+ import { t as gatewayOnlyProviders } from "./rule-DAxQY-1h.js";
5
5
  import { AwsClient } from "aws4fetch";
6
6
  import { del, get, issueSignedToken, presignUrl, put } from "@vercel/blob";
7
7
  import * as z from "zod";
@@ -13,6 +13,7 @@ import { Experimental_DecisionRefusalError, NoImageGeneratedError, NoObjectGener
13
13
  import { createHash } from "node:crypto";
14
14
  import { renderSystemMessageUpdate } from "@earendil-works/pi-ai";
15
15
  import { escapeClosingTags, escapeTagText, escapeTagTextAndQuotes, findTag, readTag, renderTag, startsWithTag, unescapeClosingTags, unescapeTagText } from "@sentry/junior-plugin-api";
16
+ import { setTimeout } from "node:timers/promises";
16
17
  // src/chat/optional-string.ts
17
18
  /**
18
19
  * Normalize optional env-style strings so blank values do not masquerade as
@@ -502,7 +503,7 @@ const PERMISSION_PATTERN = /permission denied|forbidden|not authorized|authoriza
502
503
  const INVALID_REQUEST_PATTERN = /context.?length|context.?window|validation (?:error|failed)|bad request|unsupported model|invalid model|unknown (?:ai gateway )?model|mismatched api/i;
503
504
  const CAPACITY_PATTERN = /overloaded|at capacity|capacity exceeded/i;
504
505
  const TIMEOUT_PATTERN = /timed? out|timeout|gateway timeout/i;
505
- const NETWORK_PATTERN = /network.?error|connection (?:error|refused|lost|closed)|fetch failed|socket (?:hang up|closed)|stream ended before/i;
506
+ const NETWORK_PATTERN = /network.?error|connection (?:error|refused|lost|closed)|fetch failed|cannot connect to api|socket (?:hang up|closed)|stream ended before/i;
506
507
  const SERVER_PATTERN = /service(?: temporarily)?[ _-]?unavailable|server.?error|internal.?error|bad gateway|upstream (?:request )?failed/i;
507
508
  const TERMINAL_KINDS = /* @__PURE__ */ new Set([
508
509
  "auth",
@@ -538,6 +539,7 @@ function extractTransportKind(error, depth = 0) {
538
539
  const code = typeof providerError.code === "string" ? providerError.code.toUpperCase() : void 0;
539
540
  if (code && TIMEOUT_ERROR_CODES.has(code)) return "timeout";
540
541
  if (code && NETWORK_ERROR_CODES.has(code)) return "network";
542
+ if (depth > 0 && NETWORK_PATTERN.test(providerError.message)) return "network";
541
543
  return extractTransportKind(providerError.cause, depth + 1);
542
544
  }
543
545
  function extractStatus(error, message) {
@@ -576,19 +578,27 @@ function classifyProviderError(status, message, transportKind) {
576
578
  if (status !== void 0 && status >= 400) return "invalid_request";
577
579
  return "unknown";
578
580
  }
581
+ /**
582
+ * The AI SDK retries a call and then throws `AI_RetryError`. The error of
583
+ * its last attempt has the status and the transport cause.
584
+ */
585
+ function lastAttemptError(error) {
586
+ return error instanceof Error && error.name === "AI_RetryError" && "lastError" in error ? error.lastError : error;
587
+ }
579
588
  /** Normalize SDK, Gateway, and Pi failures into one provider error contract. */
580
589
  function createProviderError(error, options = {}) {
581
590
  if (error instanceof ProviderError) return error;
582
591
  const message = providerMessage(error);
583
- const status = extractStatus(error, message);
584
- const kind = options.kind ?? classifyProviderError(status, message, extractTransportKind(error));
592
+ const attempt = lastAttemptError(error);
593
+ const status = extractStatus(attempt, message);
594
+ const kind = options.kind ?? classifyProviderError(status, message, extractTransportKind(attempt));
585
595
  const retryable = !TERMINAL_KINDS.has(kind) && (options.retryable ?? RETRYABLE_KINDS.has(kind));
586
596
  return new ProviderError({
587
597
  cause: error,
588
598
  kind,
589
599
  modelId: options.modelId,
590
600
  retryable,
591
- retryAfterMs: extractRetryAfterMs(error, message),
601
+ retryAfterMs: extractRetryAfterMs(attempt, message),
592
602
  status
593
603
  });
594
604
  }
@@ -618,25 +628,49 @@ function findProviderError(error) {
618
628
  current = current.cause;
619
629
  }
620
630
  }
621
- const TEMPORARY_PROVIDER_ERROR = "The model provider had a temporary connection problem. Please try again.";
631
+ const PROVIDER_NAMES = {
632
+ anthropic: "Anthropic",
633
+ google: "Google",
634
+ openai: "OpenAI",
635
+ xai: "xAI"
636
+ };
637
+ /**
638
+ * Name the failing model for user copy, such as `OpenAI (gpt-6-luna)`. A
639
+ * model that serves another step, such as action review, says so, because
640
+ * the person did not pick it.
641
+ */
642
+ function providerSubject(modelId, purpose) {
643
+ const slash = modelId?.indexOf("/") ?? -1;
644
+ if (!modelId || slash <= 0) return purpose ? `The model provider used for ${purpose}` : "The model provider";
645
+ const vendor = modelId.slice(0, slash);
646
+ const model = modelId.slice(slash + 1);
647
+ const details = purpose ? `${model}, used for ${purpose}` : model;
648
+ return `${PROVIDER_NAMES[vendor] ?? vendor} (${details})`;
649
+ }
650
+ const UPSTREAM = "This is an upstream provider problem, not something you did. Please try again shortly.";
622
651
  const PROVIDER_ERROR_MESSAGES = {
623
- capacity: "The selected model is temporarily unavailable because it is at capacity. Please try again shortly.",
624
- rate_limit: "The model is rate-limited. Please try again shortly.",
625
- timeout: TEMPORARY_PROVIDER_ERROR,
626
- network: TEMPORARY_PROVIDER_ERROR,
627
- server: TEMPORARY_PROVIDER_ERROR,
628
- auth: "The model provider rejected the configured credentials. This needs an administrator or configuration fix.",
629
- permission: "The model provider denied access to this model or request. Ask an administrator to check model access, organization policy, and region availability.",
630
- quota: "The model provider's usage quota has been exhausted. This needs an administrator or billing configuration fix.",
631
- content_policy: "The model provider blocked this request under its content policy. Please revise the request and try again.",
632
- invalid_request: "The model provider rejected this request as invalid. Please revise the request or ask an administrator to check the model configuration.",
633
- invalid_response: "The model provider returned an invalid response. Please try again.",
634
- unknown: "The model provider returned an error. Please try again."
652
+ capacity: (subject) => `${subject} is at capacity right now. ${UPSTREAM}`,
653
+ rate_limit: (subject) => `${subject} is rate-limiting requests right now. Please try again shortly.`,
654
+ timeout: (subject) => `${subject} is timing out right now. ${UPSTREAM}`,
655
+ network: (subject) => `${subject} cannot be reached right now. ${UPSTREAM}`,
656
+ server: (subject) => `${subject} is returning errors right now. ${UPSTREAM}`,
657
+ auth: (subject) => `${subject} rejected the configured credentials. This needs an administrator or configuration fix.`,
658
+ permission: (subject) => `${subject} denied access to this model or request. Ask an administrator to check model access, organization policy, and region availability.`,
659
+ quota: (subject) => `${subject} reports that the usage quota is exhausted. This needs an administrator or billing configuration fix.`,
660
+ content_policy: (subject) => `${subject} blocked this request under its content policy. Please revise the request and try again.`,
661
+ invalid_request: (subject) => `${subject} rejected this request as invalid. Please revise the request or ask an administrator to check the model configuration.`,
662
+ invalid_response: (subject) => `${subject} returned an invalid response. ${UPSTREAM}`,
663
+ unknown: (subject) => `${subject} returned an error. ${UPSTREAM}`
635
664
  };
636
- /** Return stable, sanitized copy suitable for a terminal user response. */
637
- function getProviderErrorUserMessage(error) {
638
- if (error.kind === "rate_limit" && error.retryAfterMs) return `The model is rate-limited. Please try again in about ${Math.max(1, Math.ceil(error.retryAfterMs / 1e3))} seconds.`;
639
- return PROVIDER_ERROR_MESSAGES[error.kind];
665
+ /**
666
+ * Return stable, sanitized copy suitable for a terminal user response. It
667
+ * names the provider and model, and `purpose` names the step that the model
668
+ * serves when it is not the agent model.
669
+ */
670
+ function getProviderErrorUserMessage(error, options = {}) {
671
+ const subject = providerSubject(error.modelId, options.purpose);
672
+ if (error.kind === "rate_limit" && error.retryAfterMs) return `${subject} is rate-limiting requests right now. Please try again in about ${Math.max(1, Math.ceil(error.retryAfterMs / 1e3))} seconds.`;
673
+ return PROVIDER_ERROR_MESSAGES[error.kind](subject);
640
674
  }
641
675
  /** Return safe structured fields for terminal failure telemetry. */
642
676
  function getProviderErrorAttributes(error) {
@@ -666,6 +700,7 @@ const RUNTIME_INPUT_TAGS = [
666
700
  "agent-result",
667
701
  "agent-message",
668
702
  "parent-agent-task",
703
+ "inbox-item-answer",
669
704
  "review-item-answer",
670
705
  "review-item-dismissed",
671
706
  "relayed-review-item-answer",
@@ -775,6 +810,50 @@ function hasCompactedConversationContext(messages) {
775
810
  return content.some((part) => part && typeof part === "object" && part.type === "text" && typeof part.text === "string" && isCompactionSummaryText(part.text));
776
811
  });
777
812
  }
813
+ // src/chat/pi/gateway-routing-attributes.ts
814
+ const providerAttemptSchema = z.object({
815
+ success: z.boolean().optional(),
816
+ credentialType: z.string().optional(),
817
+ inferenceEndpoint: z.object({ geoRegion: z.string().optional() }).optional()
818
+ });
819
+ const routingSchema = z.object({
820
+ finalProvider: z.string().optional(),
821
+ totalProviderAttemptCount: z.number().optional(),
822
+ clientSessionIdSource: z.string().optional(),
823
+ affinity: z.object({
824
+ pinned: z.boolean().optional(),
825
+ pinnedProvider: z.string().optional(),
826
+ outcome: z.string().optional()
827
+ }).optional(),
828
+ modelAttempts: z.array(z.object({ providerAttempts: z.array(providerAttemptSchema).optional() })).optional()
829
+ });
830
+ const messageDeltaSchema = z.object({
831
+ type: z.literal("message_delta"),
832
+ provider_metadata: z.object({ gateway: z.object({ routing: routingSchema }) })
833
+ });
834
+ /**
835
+ * Read the AI Gateway routing of one Anthropic Messages stream event as
836
+ * `app.ai.gateway.*` span attributes. Returns undefined for any other event.
837
+ */
838
+ function gatewayRoutingAttributes(event) {
839
+ const parsed = messageDeltaSchema.safeParse(event);
840
+ if (!parsed.success) return;
841
+ const routing = parsed.data.provider_metadata.gateway.routing;
842
+ const served = routing.modelAttempts?.flatMap((attempt) => attempt.providerAttempts ?? []).find((attempt) => attempt.success === true);
843
+ const attributes = {};
844
+ const set = (key, value) => {
845
+ if (value !== void 0) attributes[`app.ai.gateway.${key}`] = value;
846
+ };
847
+ set("provider", routing.finalProvider);
848
+ set("credential_type", served?.credentialType);
849
+ set("region", served?.inferenceEndpoint?.geoRegion);
850
+ set("provider_attempts", routing.totalProviderAttemptCount);
851
+ set("session_id_source", routing.clientSessionIdSource);
852
+ set("affinity.pinned", routing.affinity?.pinned);
853
+ set("affinity.pinned_provider", routing.affinity?.pinnedProvider);
854
+ set("affinity.outcome", routing.affinity?.outcome);
855
+ return attributes;
856
+ }
778
857
  // src/chat/services/image-dimensions.ts
779
858
  const HEADER_BASE64_CHARS = 65536;
780
859
  const READERS = {
@@ -1140,11 +1219,194 @@ function requestPrefixAttributes(payload) {
1140
1219
  return {};
1141
1220
  }
1142
1221
  }
1222
+ // src/chat/state/locks.ts
1223
+ const ACTIVE_LOCK_TTL_MS = 9e4;
1224
+ const MUTATION_LOCK_TTL_MS = 1e4;
1225
+ /**
1226
+ * Acquire a lock for long-running work that the queued state adapter should
1227
+ * keep alive while the owning invocation is still making progress.
1228
+ */
1229
+ async function acquireActiveLock(state, threadId) {
1230
+ return await state.acquireLock(threadId, ACTIVE_LOCK_TTL_MS);
1231
+ }
1232
+ /**
1233
+ * Run work under one lock, optionally waiting for the current owner.
1234
+ * `keepAlive` is for multi-store mutations that must retain ownership until all
1235
+ * side effects finish; callers should still fence each blind write.
1236
+ */
1237
+ async function withLock(state, key, run, options = {}) {
1238
+ const ttlMs = options.ttlMs ?? 9e4;
1239
+ const startedAtMs = Date.now();
1240
+ let lock;
1241
+ while (true) {
1242
+ lock = await state.acquireLock(key, ttlMs);
1243
+ if (lock) break;
1244
+ if (Date.now() - startedAtMs >= (options.waitMs ?? 0)) return { acquired: false };
1245
+ await setTimeout(options.retryMs ?? 25, void 0, { ref: false });
1246
+ }
1247
+ const heartbeat = options.keepAlive ? setInterval(() => void state.extendLock(lock, ttlMs).catch(() => void 0), Math.max(1, Math.floor(ttlMs / 3))) : void 0;
1248
+ heartbeat?.unref();
1249
+ try {
1250
+ return {
1251
+ acquired: true,
1252
+ value: await run(lock)
1253
+ };
1254
+ } finally {
1255
+ if (heartbeat) clearInterval(heartbeat);
1256
+ await state.releaseLock(lock);
1257
+ }
1258
+ }
1259
+ /**
1260
+ * Prove lock ownership immediately before a blind write.
1261
+ *
1262
+ * Whole-record mutations must stop if their lock expired rather than overwrite
1263
+ * state committed by a newer owner.
1264
+ */
1265
+ async function fenceLock(state, lock, ttlMs = MUTATION_LOCK_TTL_MS) {
1266
+ if (!await state.extendLock(lock, ttlMs)) throw new Error(`Lock ownership was lost before write for ${lock.threadId}`);
1267
+ }
1268
+ // src/chat/state/cache.ts
1269
+ const MAX_CACHE_KEY_LENGTH = 512;
1270
+ const LOAD_WAIT_MS = 1e4;
1271
+ /** The prefix of every state key of one cache namespace. */
1272
+ function cacheKeyPrefix(namespace) {
1273
+ return `junior:cache:${namespace}:`;
1274
+ }
1275
+ /**
1276
+ * Create a cache in the state adapter under `junior:cache:{namespace}:`.
1277
+ * Entries are wrapped, so `null` and `false` values are cache hits.
1278
+ */
1279
+ function createCache(state, namespace) {
1280
+ return { async getOrLoad(key, load, options) {
1281
+ if (!key.trim()) throw new Error("Cache key is required");
1282
+ if (key.length > MAX_CACHE_KEY_LENGTH) throw new Error("Cache key exceeds the maximum length");
1283
+ const cacheKey = `${cacheKeyPrefix(namespace)}${key}`;
1284
+ const cached = async () => options?.refresh ? void 0 : await state.get(cacheKey) ?? void 0;
1285
+ await state.connect();
1286
+ const hit = await cached();
1287
+ if (hit) return hit.value;
1288
+ const attempt = await withLock(state, `${cacheKey}:load`, async () => {
1289
+ const loadedMeanwhile = await cached();
1290
+ if (loadedMeanwhile) return loadedMeanwhile.value;
1291
+ const entry = await load();
1292
+ if (entry.ttlMs !== void 0) {
1293
+ if (!(entry.ttlMs > 0)) throw new Error("Cache ttlMs must be positive");
1294
+ await state.set(cacheKey, { value: entry.value }, entry.ttlMs);
1295
+ }
1296
+ return entry.value;
1297
+ }, {
1298
+ keepAlive: true,
1299
+ waitMs: LOAD_WAIT_MS
1300
+ });
1301
+ if (attempt.acquired) return attempt.value;
1302
+ return (await load()).value;
1303
+ } };
1304
+ }
1305
+ // src/chat/gateway-providers/routing.ts
1306
+ const ENABLED_PROVIDERS_KEY = "junior:gateway:enabled_providers";
1307
+ const MODEL_ENDPOINTS_URL = "https://ai-gateway.vercel.sh/v1/models";
1308
+ const SERVED_PROVIDERS_CACHE_NAMESPACE = "gateway-served-providers";
1309
+ const SERVED_PROVIDERS_TTL_MS = 36e5;
1310
+ const ENDPOINTS_TIMEOUT_MS = 5e3;
1311
+ const PROVIDER_SLUGS = { vertexAnthropic: "vertex" };
1312
+ const LOCAL_TTL_MS = 6e4;
1313
+ const localEnabledProviders = /* @__PURE__ */ new Map();
1314
+ const localServedProviders = /* @__PURE__ */ new Map();
1315
+ function readLocal(entries, key, load) {
1316
+ const entry = entries.get(key);
1317
+ if (entry && entry.expiresAtMs > Date.now()) return entry.value;
1318
+ const value = load();
1319
+ entries.set(key, {
1320
+ value,
1321
+ expiresAtMs: Date.now() + LOCAL_TTL_MS
1322
+ });
1323
+ value.catch(() => {
1324
+ if (entries.get(key)?.value === value) entries.delete(key);
1325
+ });
1326
+ return value;
1327
+ }
1328
+ const enabledProvidersSchema = z.array(z.string());
1329
+ const messagesBodySchema = z.looseObject({ providerOptions: z.looseObject({ gateway: z.looseObject({}).optional() }).optional() });
1330
+ const modelEndpointsSchema = z.object({ data: z.object({ endpoints: z.array(z.object({ provider_name: z.string() })) }) });
1331
+ /** Read the enabled providers. Null means every provider is enabled. */
1332
+ async function readEnabledProviders(state) {
1333
+ const stored = await state.get(ENABLED_PROVIDERS_KEY);
1334
+ return stored === null ? null : enabledProvidersSchema.parse(stored);
1335
+ }
1336
+ /**
1337
+ * Save the enabled providers. Null enables every provider again.
1338
+ *
1339
+ * Model calls in this process see the change right away. Other processes see
1340
+ * it when their local copy expires.
1341
+ */
1342
+ async function saveEnabledProviders(state, enabled) {
1343
+ if (enabled === null) await state.delete(ENABLED_PROVIDERS_KEY);
1344
+ else await state.set(ENABLED_PROVIDERS_KEY, [...new Set(enabled)].sort());
1345
+ localEnabledProviders.clear();
1346
+ }
1347
+ async function fetchServedProviders(modelId) {
1348
+ const path = modelId.split("/").map(encodeURIComponent).join("/");
1349
+ const response = await fetch(`${MODEL_ENDPOINTS_URL}/${path}/endpoints`, { signal: AbortSignal.timeout(ENDPOINTS_TIMEOUT_MS) });
1350
+ if (response.status === 404) return [];
1351
+ if (!response.ok) throw new Error(`AI Gateway endpoints returned ${response.status}`);
1352
+ const { data } = modelEndpointsSchema.parse(await response.json());
1353
+ const slugs = data.endpoints.map(({ provider_name }) => PROVIDER_SLUGS[provider_name] ?? provider_name);
1354
+ return [...new Set(slugs)];
1355
+ }
1356
+ /** List the providers that AI Gateway can route one model to. */
1357
+ async function readServedProviders(state, modelId) {
1358
+ return await createCache(state, SERVED_PROVIDERS_CACHE_NAMESPACE).getOrLoad(modelId, async () => ({
1359
+ value: await fetchServedProviders(modelId),
1360
+ ttlMs: SERVED_PROVIDERS_TTL_MS
1361
+ }));
1362
+ }
1363
+ async function gatewayOnlyForModel(modelId) {
1364
+ const { getStateAdapter } = await import("./adapter-iIq7ihf7.js").then((n) => n.t);
1365
+ const state = getStateAdapter();
1366
+ const enabled = await readLocal(localEnabledProviders, "enabled", () => readEnabledProviders(state));
1367
+ if (enabled === null) return void 0;
1368
+ let served;
1369
+ try {
1370
+ served = await readLocal(localServedProviders, modelId, () => readServedProviders(state, modelId));
1371
+ } catch (error) {
1372
+ logWarn("ai.gateway.served_providers.failed", {
1373
+ "gen_ai.request.model": modelId,
1374
+ "exception.message": error instanceof Error ? error.message : String(error)
1375
+ });
1376
+ return;
1377
+ }
1378
+ return gatewayOnlyProviders(enabled, served);
1379
+ }
1380
+ function withGatewayOnly(payload, only) {
1381
+ const body = messagesBodySchema.parse(payload);
1382
+ return {
1383
+ ...body,
1384
+ providerOptions: {
1385
+ ...body.providerOptions,
1386
+ gateway: {
1387
+ ...body.providerOptions?.gateway,
1388
+ only
1389
+ }
1390
+ }
1391
+ };
1392
+ }
1393
+ /**
1394
+ * Wrap a Pi Messages stream so each request body carries the `only` list of
1395
+ * the enabled providers. AI Gateway reads it from
1396
+ * `providerOptions.gateway.only` in the Messages API body.
1397
+ */
1398
+ function withEnabledGatewayProviders(stream) {
1399
+ return (model, context, options) => stream(model, context, Object.assign({}, options, { onPayload: async (payload, payloadModel) => {
1400
+ const replaced = await options?.onPayload?.(payload, payloadModel);
1401
+ const only = await gatewayOnlyForModel(model.id);
1402
+ return only ? withGatewayOnly(replaced ?? payload, only) : replaced;
1403
+ } }));
1404
+ }
1143
1405
  // src/chat/pi/client.ts
1144
1406
  registerApiProvider({
1145
1407
  api: "anthropic-messages",
1146
- stream: streamAnthropic,
1147
- streamSimple: streamSimpleAnthropic
1408
+ stream: withEnabledGatewayProviders(streamAnthropic),
1409
+ streamSimple: withEnabledGatewayProviders(streamSimpleAnthropic)
1148
1410
  });
1149
1411
  const GATEWAY_PROVIDER = "vercel-ai-gateway";
1150
1412
  const GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh";
@@ -1356,6 +1618,10 @@ async function completeText(params) {
1356
1618
  onResponse: (response) => {
1357
1619
  const vercelId = response.headers["x-vercel-id"];
1358
1620
  if (vercelId) setSpanAttributes({ "app.ai.gateway.vercel_id": vercelId });
1621
+ },
1622
+ onProviderStreamEvent: (event) => {
1623
+ const routing = gatewayRoutingAttributes(event);
1624
+ if (routing) setSpanAttributes(routing);
1359
1625
  }
1360
1626
  });
1361
1627
  } catch (error) {
@@ -1732,7 +1998,6 @@ function toPiReasoningLevel(level) {
1732
1998
  return level === "none" ? "off" : level;
1733
1999
  }
1734
2000
  // src/chat/config.ts
1735
- var config_exports = /* @__PURE__ */ __exportAll({ botConfig: () => botConfig });
1736
2001
  const MIN_AGENT_TURN_TIMEOUT_MS = 1e4;
1737
2002
  const DEFAULT_AGENT_TURN_TIMEOUT_MS = 72e4;
1738
2003
  const MAX_SLICES_PER_TURN = 100;
@@ -1933,6 +2198,7 @@ function readChatConfig(env = process.env, functionMaxDurationSeconds = DEFAULT_
1933
2198
  queue: readQueueConfig(env),
1934
2199
  functionMaxDurationSeconds: resolvedFunctionMaxDurationSeconds,
1935
2200
  cacheWarmingEnabled: parseKillSwitch("JUNIOR_CACHE_WARMING_ENABLED", env["JUNIOR_CACHE_WARMING_ENABLED"]),
2201
+ idleCompactionEnabled: parseKillSwitch("JUNIOR_IDLE_COMPACTION_ENABLED", env["JUNIOR_IDLE_COMPACTION_ENABLED"]),
1936
2202
  conversationWorkEnabled: parseKillSwitch("JUNIOR_CONVERSATION_WORK_ENABLED", env["JUNIOR_CONVERSATION_WORK_ENABLED"]),
1937
2203
  conversationWorkSoftYieldAfterMs: resolveConversationWorkSoftYieldAfterMs(resolvedFunctionMaxDurationSeconds),
1938
2204
  encryption: readEncryptionKeyring(env),
@@ -2062,4 +2328,4 @@ function setSlackReactionConfig(overrides) {
2062
2328
  if (overrides.processingReactionEmoji !== void 0) chatConfig.slack.processingReactionEmoji = parseReactionEmoji("processingReactionEmoji", overrides.processingReactionEmoji, chatConfig.slack.processingReactionEmoji);
2063
2329
  if (overrides.completedReactionEmoji !== void 0) chatConfig.slack.completedReactionEmoji = parseReactionEmoji("completedReactionEmoji", overrides.completedReactionEmoji, chatConfig.slack.completedReactionEmoji);
2064
2330
  }
2065
- export { getProviderErrorAttributes as $, searchWeb as A, renderCurrentInstruction as B, completeObject as C, generateImages as D, gatewayCostUsd as E, textCharsForTokens as F, readParentAgentTask as G, THREAD_CONTEXT_TAGS as H, COMPACTION_SUMMARY_PREFIX as I, renderUntrustedTag as J, renderParentAgentTask as K, hasCompactedConversationContext as L, estimateMessagesTokens as M, estimateRequestOverheadTokens as N, rerankTexts as O, estimateTextTokens as P, findProviderError as Q, isCompactionSummaryText as R, completeDecision as S, embedTexts as T, authorAttrs as U, unwrapCurrentInstruction as V, isRuntimeInputText as W, createAssistantProviderError as X, ProviderError as Y, createProviderError as Z, TURN_REASONING_LEVELS as _, getRuntimeMetadata as a, bufferBody as at, GEN_AI_PROVIDER_NAME as b, getSlackClientSecret as c, restoreRuntimeConfig as d, getProviderErrorUserMessage as et, setBotModelConfig as f, snapshotRuntimeConfig as g, setSlackReactionConfig as h, getChatConfig as i, resolveGatewayCredential as it, requestPrefixAttributes as j, resolveGatewayModel as k, getSlackSigningSecret as l, setRuntimeLimits as m, botConfig as n, isProviderRetryError as nt, getSlackBotToken as o, getAttachmentStorage as ot, setBotName as p, renderThreadContext as q, config_exports as r, getGatewayApiKey as rt, getSlackClientId as s, toOptionalTrimmed as st, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as t, isProviderRefusal as tt, resetRuntimeConfig as u, toPiReasoningLevel as v, completeText as w, GEN_AI_SERVER_ADDRESS as x, normalizeSlackEmojiName as y, hasCurrentInstruction as z };
2331
+ export { authorAttrs as $, readEnabledProviders as A, requestPrefixAttributes as B, completeText as C, rerankTexts as D, generateImages as E, ACTIVE_LOCK_TTL_MS as F, gatewayRoutingAttributes as G, estimateRequestOverheadTokens as H, MUTATION_LOCK_TTL_MS as I, isCompactionSummaryText as J, COMPACTION_SUMMARY_PREFIX as K, acquireActiveLock as L, saveEnabledProviders as M, cacheKeyPrefix as N, resolveGatewayModel as O, createCache as P, THREAD_CONTEXT_TAGS as Q, fenceLock as R, completeObject as S, gatewayCostUsd as T, estimateTextTokens as U, estimateMessagesTokens as V, textCharsForTokens as W, renderCurrentInstruction as X, hasCurrentInstruction as Y, unwrapCurrentInstruction as Z, toPiReasoningLevel as _, toOptionalTrimmed as _t, getSlackBotToken as a, ProviderError as at, GEN_AI_SERVER_ADDRESS as b, getSlackSigningSecret as c, findProviderError as ct, setBotModelConfig as d, isProviderRefusal as dt, isRuntimeInputText as et, setBotName as f, isProviderRetryError as ft, TURN_REASONING_LEVELS as g, getAttachmentStorage as gt, snapshotRuntimeConfig as h, bufferBody as ht, getRuntimeMetadata as i, renderUntrustedTag as it, readServedProviders as j, searchWeb as k, resetRuntimeConfig as l, getProviderErrorAttributes as lt, setSlackReactionConfig as m, resolveGatewayCredential as mt, botConfig as n, renderParentAgentTask as nt, getSlackClientId as o, createAssistantProviderError as ot, setRuntimeLimits as p, getGatewayApiKey as pt, hasCompactedConversationContext as q, getChatConfig as r, renderThreadContext as rt, getSlackClientSecret as s, createProviderError as st, DEFAULT_SQL_STATEMENT_TIMEOUT_MS as t, readParentAgentTask as tt, restoreRuntimeConfig as u, getProviderErrorUserMessage as ut, normalizeSlackEmojiName as v, embedTexts as w, completeDecision as x, GEN_AI_PROVIDER_NAME as y, withLock as z };
@@ -1,9 +1,10 @@
1
- import { Bs as formatSlackLink, Lt as moveIdleConversationDestination, ao as readLatestConversationBrief, ds as getSlackMessagePermalink, hs as postSlackMessage, ic as getDashboardConversationLink, us as deleteSlackMessage, zs as escapeSlackMrkdwnText } from "./projection-jZSlEAXG.js";
2
- import { C as withConversationMutationLock, N as setFirstConversationLocation, a as getConversationStore, ct as claimProviderConversation, lt as getConversationIdByProviderConversation, o as getDb, s as getSqlExecutor, tt as getStateAdapter } from "./db-CFZggNoy.js";
1
+ import { B as claimProviderConversation, R as setFirstConversationLocation, V as getConversationIdByProviderConversation, a as getConversationStore, o as getDb, s as getSqlExecutor, w as withConversationMutationLock } from "./db-LAyyX8tk.js";
2
+ import { Gr as deleteSlackMessage, Kr as getSlackMessagePermalink, Xr as postSlackMessage, ai as escapeSlackMrkdwnText, oi as formatSlackLink, wi as getDashboardConversationLink } from "./credentialed-Cb6E2phL.js";
3
3
  import { u as parseSlackChannelId, v as parseSlackMessageTs } from "./actor-BsBdxDXQ.js";
4
- import { mr as joinPublicChannelForRead, pr as checkSlackChannelReadAccess } from "./warmup-C6LOZ2d2.js";
5
- import "./store-D4FQ1Nml.js";
6
- import { V as juniorDestinations } from "./executor-BPkZDx5-.js";
4
+ import { n as joinPublicChannelForRead, t as checkSlackChannelReadAccess } from "./channel-access-CJGfNTdn.js";
5
+ import { i as getStateAdapter } from "./adapter-iIq7ihf7.js";
6
+ import { on as moveIdleConversationDestination } from "./thread-state-DhPndWi1.js";
7
+ import { q as juniorDestinations } from "./executor-SCub-fAq.js";
7
8
  import { and, eq } from "drizzle-orm";
8
9
  // src/chat/slack/continue-in-slack.ts
9
10
  /** Refusal for a move that cannot wait for the active Run. */
@@ -27,10 +28,9 @@ function canContinueInSlack(conversation, access) {
27
28
  async function movedMessageText(conversation, actorName) {
28
29
  const title = conversation.title ?? "Untitled conversation";
29
30
  const url = getDashboardConversationLink(conversation.conversationId);
30
- const brief = await readLatestConversationBrief(getDb(), conversation.conversationId);
31
31
  return [
32
32
  `*${url ? formatSlackLink(url, title) : escapeSlackMrkdwnText(title)}*`,
33
- ...brief ? [`> ${escapeSlackMrkdwnText(brief.content.summary)}`] : [],
33
+ ...conversation.summary ? [`> ${escapeSlackMrkdwnText(conversation.summary)}`] : [],
34
34
  `${escapeSlackMrkdwnText(actorName)} moved this conversation here from the dashboard. Mention me in this thread to continue.`
35
35
  ].join("\n");
36
36
  }
@@ -1,20 +1,19 @@
1
- import { P as briefOutcomeStatusSchema, W as reviewItemChangeRecordSchema, et as messageAttachmentSchema, i as actorIdentitySchema, u as conversationDetailReportSchema, y as conversationSummaryReportSchema } from "./conversation-M9KZ5JxF.js";
1
+ import { G as conversationDetailReportSchema, Ot as messageAttachmentSchema, et as conversationSummaryReportSchema, vt as inboxItemChangeRecordSchema, z as actorIdentitySchema } from "./media-CYm1QD8T.js";
2
2
  import * as z from "zod";
3
3
  // src/api/objects/cards.ts
4
4
  const MAX_LABEL_CHARS = 256;
5
5
  const MAX_FACT_CHARS = 160;
6
6
  const conversationStates = {
7
- active: "running",
8
- completed: "idle",
9
- failed: "failed",
10
- stopped: "stopped"
7
+ done: "done",
8
+ needs_input: "needs input",
9
+ working: "working"
11
10
  };
12
11
  function personName(person) {
13
12
  return person.fullName ?? person.slackUserName ?? person.email;
14
13
  }
15
14
  /**
16
- * Build the card of one Conversation that the viewer may read. Give `brief`
17
- * only when the viewer may see the Brief.
15
+ * Build the card of one Conversation that the viewer may read. Give
16
+ * `description` only when the viewer may see private content.
18
17
  */
19
18
  function conversationObjectCard(args) {
20
19
  const { summary } = args;
@@ -27,7 +26,7 @@ function conversationObjectCard(args) {
27
26
  title: summary.displayTitle.slice(0, 512),
28
27
  url: args.url,
29
28
  status: summary.archivedAt ? "archived" : conversationStates[summary.status],
30
- ...args.brief ? { description: args.brief.slice(0, 4e3) } : void 0,
29
+ ...args.description ? { description: args.description.slice(0, 4e3) } : void 0,
31
30
  facts: {
32
31
  type: "conversation",
33
32
  ...participants.length > 0 ? { participants } : void 0,
@@ -231,8 +230,8 @@ const conversationPendingMessageSchema = z.object({
231
230
  /** People mentioned in the text, resolved at read time. */
232
231
  mentions: z.array(actorIdentitySchema).optional(),
233
232
  attachments: z.array(messageAttachmentSchema).optional(),
234
- /** Review item change that this Message records. */
235
- reviewItemChange: reviewItemChangeRecordSchema.optional(),
233
+ /** Inbox item change that this Message records. */
234
+ reviewItemChange: inboxItemChangeRecordSchema.optional(),
236
235
  redacted: z.literal(true).optional()
237
236
  }).strict().superRefine((data, context) => {
238
237
  if (data.text === void 0 === (data.redacted !== true)) context.addIssue({
@@ -241,7 +240,7 @@ const conversationPendingMessageSchema = z.object({
241
240
  });
242
241
  if (data.redacted && (data.actorIdentity || data.attachments || data.mentions || data.reviewItemChange)) context.addIssue({
243
242
  code: "custom",
244
- message: "redacted pending messages must not expose actor identity, attachments, mentions, or a review item"
243
+ message: "redacted pending messages must not expose actor identity, attachments, mentions, or an inbox item"
245
244
  });
246
245
  });
247
246
  /** Participant-only authorization prompt for a parked web turn. */
@@ -269,12 +268,12 @@ const conversationUnchangedDetailWithMailboxSchema = z.object({
269
268
  }).strict();
270
269
  /** Optional filters for cancelling accepted mailbox rows. */
271
270
  const cancelConversationPendingMessagesBodySchema = z.object({
272
- inboundMessageIds: z.array(z.string().min(1)).min(1).optional(),
273
- receivedBefore: z.string().datetime().optional()
271
+ inboundMessageIds: z.array(z.string().min(1)).min(1).optional().describe("Drop only these waiting messages."),
272
+ receivedBefore: z.string().datetime().optional().describe("Drop only the waiting messages received before this time.")
274
273
  }).strict();
275
274
  /** Result of cancelling accepted human-facing mailbox rows. */
276
275
  const cancelConversationPendingMessagesResponseSchema = z.object({
277
- cancelledCount: z.number().int().nonnegative(),
276
+ cancelledCount: z.number().int().nonnegative().describe("Messages dropped."),
278
277
  cancelledInboundMessageIds: z.array(z.string().min(1)),
279
278
  conversationId: z.string().min(1)
280
279
  }).strict();
@@ -285,16 +284,71 @@ const steerConversationPendingMessagesResponseSchema = z.object({
285
284
  conversationId: z.string().min(1),
286
285
  steeredInboundMessageIds: z.array(z.string().min(1))
287
286
  }).strict();
288
- // src/api/schema/conversation-feed.ts
287
+ // src/api/schema/conversation-archive.ts
288
+ /**
289
+ * Archive or restore one conversation. `applyToChildren` applies to a child
290
+ * only: archive refuses while a descendant is unarchived unless it is true,
291
+ * and restore also restores the descendants archived with the child when it
292
+ * is true. A root archive is per viewer and writes no child rows.
293
+ */
294
+ const archiveConversationBodySchema = z.object({
295
+ applyToChildren: z.boolean().optional().describe("On archive, true also archives every child of this conversation at any depth; without it, the archive fails while any of its children is not archived. On restore, true also restores the children that were archived with this conversation."),
296
+ archived: z.boolean().default(true).describe("False restores an archived conversation."),
297
+ lastSeenAt: z.string().datetime().describe("`lastSeenAt` from searchConversations or getConversation. The archive fails when the conversation has newer activity.")
298
+ }).strict();
299
+ const archiveConversationResponseSchema = z.object({ archivedAt: z.string().datetime().nullable().describe("Null when the conversation is not archived.") }).strict();
300
+ /** Viewer's auto-archive choice for one conversation. */
301
+ const conversationAutoArchiveSchema = z.object({ autoArchive: z.boolean().describe("True lets auto-archive archive the conversation for everyone after its work is done. False keeps it from auto-archive for everyone.") }).strict();
302
+ /** Result of archiving all of the viewer's done conversations once. */
303
+ const archiveDoneConversationsResponseSchema = z.object({ archived: z.number().int().nonnegative().describe("Conversations archived.") }).strict();
304
+ // src/api/schema/conversation-pin.ts
305
+ /** Pin or unpin one Conversation for the signed-in viewer. */
306
+ const pinConversationBodySchema = z.object({ pinned: z.boolean().default(true).describe("False unpins the conversation.") }).strict();
307
+ /** The viewer's pin time after the change, or null when unpinned. */
308
+ const pinConversationResponseSchema = z.object({ pinnedAt: z.string().datetime().nullable().describe("Null when the conversation is not pinned.") }).strict();
309
+ /**
310
+ * The viewer's full Pinned order, first to last. Each pin takes its index as
311
+ * its new place.
312
+ */
313
+ const reorderPinnedConversationsBodySchema = z.object({ conversationIds: z.array(z.string().min(1)).min(1).max(500).refine((ids) => new Set(ids).size === ids.length, { message: "Each Conversation can appear once." }) }).strict();
314
+ /** The pinned Conversations that got a new place, in order. */
315
+ const reorderPinnedConversationsResponseSchema = z.object({ conversationIds: z.array(z.string()) }).strict();
316
+ // src/api/schema/conversation-subscription.ts
317
+ /** Subscribe to or unsubscribe from one Conversation for the viewer. */
318
+ const conversationSubscriptionBodySchema = z.object({ subscribed: z.boolean().describe("False unsubscribes you.") }).strict();
319
+ /**
320
+ * The viewer's subscription after the change. `archivedAt` is set when the
321
+ * viewer was the last subscriber, so the unsubscribe archived the
322
+ * Conversation for everyone.
323
+ */
324
+ const conversationSubscriptionResponseSchema = z.object({
325
+ archivedAt: z.string().datetime().nullable().describe("Set when the conversation is archived for everyone."),
326
+ subscribed: z.boolean()
327
+ }).strict();
328
+ /** Invite one mentioned person, by Slack user id, to a public Conversation. */
329
+ const conversationInviteBodySchema = z.object({ slackUserId: z.string().min(1).max(64) }).strict();
330
+ /** `added` is false when the person was already a Participant. */
331
+ const conversationInviteResponseSchema = z.object({ added: z.boolean() }).strict();
332
+ // src/api/schema/conversation-stop.ts
333
+ /** One queued web message from the viewer that a stop removed. */
334
+ const stoppedConversationMessageSchema = z.object({
335
+ inboundMessageId: z.string().min(1),
336
+ text: z.string().min(1)
337
+ }).strict();
289
338
  /**
290
- * The part of a Conversation's latest Brief that a feed row shows: what the
291
- * work is about and how it stands.
339
+ * Result of stopping the active Turn.
340
+ *
341
+ * `stoppedInboundMessageIds` lists every queued human message the stop
342
+ * removes. `stoppedMessages` holds only the viewer's own web text, so the
343
+ * dashboard can return it to the composer.
292
344
  */
293
- const conversationFeedBriefSchema = z.object({
294
- intent: z.string(),
295
- status: briefOutcomeStatusSchema,
296
- summary: z.string()
345
+ const stopConversationTurnResponseSchema = z.object({
346
+ conversationId: z.string().min(1),
347
+ status: z.enum(["no_work", "requested"]).describe("`requested` when the running turn was asked to stop. `no_work` when no turn was running. Child agents are stopped in both cases."),
348
+ stoppedInboundMessageIds: z.array(z.string().min(1)).describe("Messages that waited for the turn and were dropped."),
349
+ stoppedMessages: z.array(stoppedConversationMessageSchema).describe("Your own dropped messages, with their text.")
297
350
  }).strict();
351
+ // src/api/schema/conversation-feed.ts
298
352
  const conversationFeedIncludeSchema = z.enum(["links", "media"]);
299
353
  /** Query of `GET /api/conversations`. */
300
354
  const conversationFeedQuerySchema = z.object({
@@ -321,11 +375,18 @@ const conversationFeedMediaSchema = z.object({
321
375
  id: z.string().min(1)
322
376
  }).strict();
323
377
  /**
378
+ * The viewer's newest answer to an Inbox item that the Conversation added:
379
+ * when it closed and the options they picked. A text answer has no choices.
380
+ */
381
+ const conversationFeedViewerAnswerSchema = z.object({
382
+ choices: z.array(z.string()),
383
+ closedAt: z.string().datetime()
384
+ }).strict();
385
+ /**
324
386
  * A root in the feed, or one of its visible Threads. A Thread nests under
325
387
  * its nearest visible Thread ancestor, or under the root. Tasks never show.
326
388
  */
327
389
  const conversationFeedItemSchema = conversationSummaryReportSchema.extend({
328
- brief: conversationFeedBriefSchema.optional(),
329
390
  /**
330
391
  * Web links from the Conversation's recent messages, newest first, for
331
392
  * the row to resolve into cards. URLs only: never message text. Only
@@ -334,7 +395,9 @@ const conversationFeedItemSchema = conversationSummaryReportSchema.extend({
334
395
  links: z.array(z.url()).max(3).optional(),
335
396
  /** Only with `include=media`. */
336
397
  media: z.array(conversationFeedMediaSchema).max(3).optional(),
337
- threads: z.lazy(() => z.array(conversationFeedItemSchema)).optional()
398
+ threads: z.lazy(() => z.array(conversationFeedItemSchema)).optional(),
399
+ /** Only on the viewer's own feed. */
400
+ viewerAnswer: conversationFeedViewerAnswerSchema.optional()
338
401
  });
339
402
  const conversationFeedSchema = z.object({
340
403
  conversations: z.array(conversationFeedItemSchema),
@@ -343,4 +406,4 @@ const conversationFeedSchema = z.object({
343
406
  /** Present when older conversations follow this page. */
344
407
  nextCursor: z.string().optional()
345
408
  }).strict();
346
- export { skillReportSchema as C, personObjectCard as D, messageObjectCard as E, webPageObjectCard as O, skillDetailReportSchema as S, conversationObjectCard as T, pluginPackageContentItemReportSchema as _, cancelConversationPendingMessagesResponseSchema as a, pluginsSchema as b, conversationPendingMessageDeliverySchema as c, conversationUnchangedDetailWithMailboxSchema as d, steerConversationPendingMessagesBodySchema as f, pluginOperationalReportSchema as g, pluginOperationalReportFeedSchema as h, cancelConversationPendingMessagesBodySchema as i, conversationPendingMessageSchema as l, healthReportSchema as m, conversationFeedQuerySchema as n, conversationDetailWithMailboxReportSchema as o, steerConversationPendingMessagesResponseSchema as p, conversationFeedSchema as r, conversationPendingAuthorizationSchema as s, conversationFeedBriefSchema as t, conversationPendingMessagesReportSchema as u, pluginPackageContentReportSchema as v, skillReportsSchema as w, runtimeInfoReportSchema as x, pluginSchema as y };
409
+ export { pluginPackageContentReportSchema as A, webPageObjectCard as B, conversationUnchangedDetailWithMailboxSchema as C, pluginOperationalReportFeedSchema as D, healthReportSchema as E, skillReportSchema as F, skillReportsSchema as I, conversationObjectCard as L, pluginsSchema as M, runtimeInfoReportSchema as N, pluginOperationalReportSchema as O, skillDetailReportSchema as P, messageObjectCard as R, conversationPendingMessagesReportSchema as S, steerConversationPendingMessagesResponseSchema as T, cancelConversationPendingMessagesResponseSchema as _, conversationInviteResponseSchema as a, conversationPendingMessageDeliverySchema as b, pinConversationBodySchema as c, reorderPinnedConversationsResponseSchema as d, archiveConversationBodySchema as f, cancelConversationPendingMessagesBodySchema as g, conversationAutoArchiveSchema as h, conversationInviteBodySchema as i, pluginSchema as j, pluginPackageContentItemReportSchema as k, pinConversationResponseSchema as l, archiveDoneConversationsResponseSchema as m, conversationFeedSchema as n, conversationSubscriptionBodySchema as o, archiveConversationResponseSchema as p, stopConversationTurnResponseSchema as r, conversationSubscriptionResponseSchema as s, conversationFeedQuerySchema as t, reorderPinnedConversationsBodySchema as u, conversationDetailWithMailboxReportSchema as v, steerConversationPendingMessagesBodySchema as w, conversationPendingMessageSchema as x, conversationPendingAuthorizationSchema as y, personObjectCard as z };