@sentry/junior 0.311.0 → 0.313.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 (120) hide show
  1. package/dist/{adapter-B1wujchl.js → adapter-CYAvJzZS.js} +1 -1
  2. package/dist/{adapter-context-G2M0y6rP.js → adapter-context-CVsHoVSf.js} +2 -2
  3. package/dist/{admin-DCiBhUT1.js → admin-Cyhb4TwZ.js} +1 -1
  4. package/dist/{agent-runner-BVHPUIc8.js → agent-runner-B5y9MsT-.js} +3487 -3493
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.d.ts +2 -2
  8. package/dist/api.js +294 -311
  9. package/dist/{app-Cw5Vy6H6.d.ts → app-DA8-hCMj.d.ts} +2 -9
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +336 -604
  12. package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-iZXadLV3.js} +60 -85
  13. package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-kkE3hvCX.js} +1 -1
  14. package/dist/channel-access-mt7K6dPh.js +221 -0
  15. package/dist/cli/chat.js +18 -19
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +0 -1
  18. package/dist/cli/main.js +3 -7
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/run.d.ts +1 -2
  21. package/dist/cli/run.js +1 -2
  22. package/dist/cli/snapshot-create.js +5 -5
  23. package/dist/cli/upgrade.d.ts +1 -1
  24. package/dist/cli/upgrade.js +3 -3
  25. package/dist/{config-BrXDQefC.js → config-CWbwKj0j.js} +59 -27
  26. package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-CxyFzdlF.js} +7 -8
  27. package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-BEXLD3Me.js} +86 -21
  28. package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-BrMiDN61.js} +1 -1
  29. package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-B35eu0uz.js} +78 -56
  30. package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-DWTOEQrm.js} +15 -15
  31. package/dist/{projection-Cns7XwWa.js → credentialed-Dyv8b-lu.js} +16306 -20732
  32. package/dist/{db-7ETESH44.d.ts → db-DYGcXYl3.d.ts} +11 -6
  33. package/dist/{db-DTxzH7u5.js → db-PwSRzWWn.js} +181 -100
  34. package/dist/{executor-DqTiYj9S.js → executor-CgWyWfYz.js} +117 -99
  35. package/dist/{html-B9Sl4Axb.js → html-DidUcRhI.js} +6 -6
  36. package/dist/ingest-B0AggUEC.js +7931 -0
  37. package/dist/{install-Sg4ePfLl.js → install-2urLLXNt.js} +2 -2
  38. package/dist/instrumentation.js +3 -3
  39. package/dist/{lineage-BHAMpNKr.js → lineage-BXplQAVH.js} +2 -2
  40. package/dist/{stop-CYsfc0Ed.js → list-DyIyReSV.js} +709 -475
  41. package/dist/{logging-FjclQsXu.js → logging-DNt-qOIO.js} +1 -1
  42. package/dist/{schedule-BLJ476XQ.js → media-B0pZJ0bG.js} +1058 -11
  43. package/dist/{message-CJ7_RL50.js → message-Z5YKC-Af.js} +35 -28
  44. package/dist/{model-input-CMLh4Cwq.js → model-input-BhPJYdSV.js} +3 -3
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +4 -3
  47. package/dist/{oauth-callback-server-RVcbiDjL.js → oauth-callback-server-ByvDdcdY.js} +2 -2
  48. package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-D-kK0yoN.js} +1 -1
  49. package/dist/{registry-BPwuOP2O.js → registry-POH4bZC4.js} +1 -1
  50. package/dist/reporting-window-C4dbzDiR.js +124 -0
  51. package/dist/request-deadline-BUiRYQYj.js +24 -0
  52. package/dist/{resolve-BK29bBry.js → resolve-CWtBNSKP.js} +3 -3
  53. package/dist/{runner-BcAE-cJm.js → runner-CsZ_VRxp.js} +14 -16
  54. package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
  55. package/dist/{schema-DYcJeV7d.d.ts → schema-DBf18QPS.d.ts} +2773 -3630
  56. package/dist/{schema-BLgSZXcL.js → schema-DojR2uCL.js} +106 -121
  57. package/dist/{service-account-iJoCtkHR.js → service-account-CDYb9hfX.js} +3 -3
  58. package/dist/{service-account-gN0zqf0S.js → service-account-o15pZWcJ.js} +5 -5
  59. package/dist/{skills-BoZ80epJ.js → skills-B0jP4whm.js} +2 -2
  60. package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-D26t9kBC.js} +9 -9
  61. package/dist/{spawn-Dk92r7mX.js → spawn-BjljgExZ.js} +14 -32
  62. package/dist/start-conversation-DbVujrwO.js +755 -0
  63. package/dist/{state-DH3Cmgp3.js → state-BTawTCme.js} +4 -4
  64. package/dist/statuses-BKwqCPhj.js +69 -0
  65. package/dist/store-CjXrp-Up.js +492 -0
  66. package/dist/task-queue-Cwlatjz3.js +90 -0
  67. package/dist/task-runner--Ke8KSMf.js +1432 -0
  68. package/dist/{thread-context-BW2BsQbH.js → thread-context-B8exINEe.js} +6 -7
  69. package/dist/turn-membership-DTR3SaKD.js +5859 -0
  70. package/dist/{validation-DrJd0nnq.js → validation-Ce0qbMlT.js} +1 -1
  71. package/dist/{task-queue-C_zldF5J.js → vercel-queue-q4z8w5QO.js} +93 -172
  72. package/dist/{version-CNKZ8owc.js → version-DFh4n9nr.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{warmup-BWdHew2H.js → warmup-D5hzqTcp.js} +4853 -13605
  75. package/dist/web-message-id-C6P83ans.js +10 -0
  76. package/dist/{worker-t9qpu_Zx.js → worker-CDg9Lbpg.js} +20 -7
  77. package/migrations/0143_todos.sql +14 -0
  78. package/migrations/0144_inbox_items.sql +32 -0
  79. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  80. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  81. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  82. package/migrations/0148_authorization_request_index.sql +1 -0
  83. package/migrations/0149_conversation_metadata.sql +10 -0
  84. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  85. package/migrations/0151_conversation_search_index.sql +1 -0
  86. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  87. package/migrations/0153_artifact_expiry.sql +1 -0
  88. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  89. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  90. package/migrations/0156_conversation_kind_lead.sql +6 -0
  91. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  92. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  93. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  94. package/migrations/meta/0143_snapshot.json +6434 -0
  95. package/migrations/meta/0144_snapshot.json +6434 -0
  96. package/migrations/meta/0145_snapshot.json +6440 -0
  97. package/migrations/meta/0146_snapshot.json +6446 -0
  98. package/migrations/meta/0147_snapshot.json +6452 -0
  99. package/migrations/meta/0148_snapshot.json +6474 -0
  100. package/migrations/meta/0149_snapshot.json +6490 -0
  101. package/migrations/meta/0150_snapshot.json +6490 -0
  102. package/migrations/meta/0151_snapshot.json +6505 -0
  103. package/migrations/meta/0152_snapshot.json +6505 -0
  104. package/migrations/meta/0153_snapshot.json +6511 -0
  105. package/migrations/meta/0154_snapshot.json +6533 -0
  106. package/migrations/meta/0155_snapshot.json +6511 -0
  107. package/migrations/meta/0156_snapshot.json +6511 -0
  108. package/migrations/meta/0157_snapshot.json +6527 -0
  109. package/migrations/meta/0158_snapshot.json +6515 -0
  110. package/migrations/meta/0159_snapshot.json +6515 -0
  111. package/migrations/meta/_journal.json +120 -1
  112. package/package.json +6 -6
  113. package/skills/design-automation-skill/SKILL.md +108 -0
  114. package/dist/briefs-BDjnug6Y.js +0 -395
  115. package/dist/conversation-ca__NDQW.js +0 -1063
  116. package/dist/prompt-CDqcsDYC.js +0 -910
  117. package/dist/store-DmmMIrQi.js +0 -335
  118. package/dist/task-runner-C7oCJQIx.js +0 -294
  119. package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
  120. package/dist/web-message-id-Ch5dPq-a.js +0 -306
@@ -1,6 +1,6 @@
1
- import { i as actorIdentitySchema } from "./conversation-ca__NDQW.js";
1
+ import { a as conversationTurnFailureReasonSchema, h as usageSchema, i as conversationTurnFailureCodeSchema } from "./history-CYstOMKX.js";
2
2
  import * as z from "zod";
3
- import { actorUserIdSchema, destinationVisibilitySchema, eventMatchFieldsSchema, eventMatchSchema, eventReachSchema, eventTypeSchema, pluginEventTypeSchema, slackDestinationSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
3
+ import { actorUserIdSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, conversationSidebarAnnotationSchema, destinationVisibilitySchema, eventMatchFieldsSchema, eventMatchSchema, eventReachSchema, eventTypeSchema, objectFactFields, objectTypeSchema, pluginEventTypeSchema, slackDestinationSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
4
4
  // src/chat/automations/task.ts
5
5
  /**
6
6
  * The work of an Automation run. An Automation runs either a written
@@ -43,7 +43,7 @@ function automationTaskColumns(task) {
43
43
  skill: task.skill
44
44
  };
45
45
  }
46
- // src/chat/tools/runtime/user-input-request.ts
46
+ // src/chat/inbox-items/user-input-request.ts
47
47
  const USER_INPUT_LIMITS = {
48
48
  maxButtonOptions: 5,
49
49
  maxDescriptionChars: 200,
@@ -190,25 +190,25 @@ function formatUserInputAnswer(request, answer) {
190
190
  if (normalized.other) lines.push(answerLine(`Other: ${normalized.other}`));
191
191
  return lines.join("\n");
192
192
  }
193
- // src/chat/review-items/evidence.ts
193
+ // src/chat/inbox-items/evidence.ts
194
194
  /**
195
- * One source that an agent cites for a Review item: a link or a
195
+ * One source that an agent cites for an Inbox item: a link or a
196
196
  * Conversation, with a short label and an optional one-line note. A link
197
197
  * points outside Junior; a Conversation reference points to work in Junior.
198
198
  * The question stores the list, and the dashboard shows it beside the
199
199
  * answer choices.
200
200
  */
201
- const reviewItemEvidenceSchema = z.object({
201
+ const inboxItemEvidenceSchema = z.object({
202
202
  conversationId: z.string().min(1).max(500).optional(),
203
203
  label: z.string().min(1).max(120),
204
204
  note: z.string().min(1).max(200).optional(),
205
205
  url: z.string().min(1).max(2e3).optional()
206
206
  }).strict().refine((entry) => entry.url === void 0 !== (entry.conversationId === void 0), "Evidence has a `url` or a `conversationId`, not both.");
207
207
  /**
208
- * The question of a Review item with the evidence for its answer. Evidence
208
+ * The question of an Inbox item with the evidence for its answer. Evidence
209
209
  * is part of the question, so it is stored in the `request` column.
210
210
  */
211
- const reviewItemRequestSchema = savedUserInputRequestSchema.safeExtend({ evidence: z.array(reviewItemEvidenceSchema).optional() });
211
+ const inboxItemRequestSchema = savedUserInputRequestSchema.safeExtend({ evidence: z.array(inboxItemEvidenceSchema).optional() });
212
212
  /** Validate the persisted Slack creator identity for an event automation. */
213
213
  const eventAutomationPrincipalSchema = z.object({
214
214
  slackUserId: actorUserIdSchema,
@@ -858,8 +858,12 @@ const automationTitleSchema = z.string().trim().min(1).max(60);
858
858
  * who says "me".
859
859
  */
860
860
  const automationInstructionToolSchema = automationTaskTextSchema.describe("Work to perform when the Automation runs. Say what to do, what to post, and when to post nothing. Do not say where to post: the outcomes set that, a run triggered by a Slack message replies in its thread, and each run ends with one message at most. The run does not see this conversation, so words like \"this channel\" or \"here\" will mean nothing then. Where the run reads or changes something, write the exact target, such as a channel mention, a repo, or a link. Keep every person the user means, including \"me\". Write the creator as \"the Automation creator\"; each run knows who that is. Write anyone else, including a requester who is not the creator, as their Slack mention, such as <@U123>. Preserve the user's scope, targets, and constraints. Do not add permissions or side effects the user did not request.");
861
- /** Context input for agent tools. It follows the same rules as an instruction. */
862
- const automationContextToolSchema = automationTaskTextSchema.describe("What a skill run needs beyond the skill, such as a repo, a threshold, or who to tag. Leave out what the skill says. Use instruction rules: do not say where to post, write exact targets, call the creator \"the Automation creator\", and tag others as <@U123>.");
861
+ /**
862
+ * Context input for agent tools. It follows the same rules as an instruction.
863
+ * Action review reads the stored context, not the skill, so the context also
864
+ * names the scope of the writes a run needs.
865
+ */
866
+ const automationContextToolSchema = automationTaskTextSchema.describe("What a run needs beyond the skill: input values, such as a repo or who to tag; when to post nothing; and the scope of writes. Not the skill steps. Instruction rules apply: no place to post, exact targets, \"the Automation creator\", others as <@U123>.");
863
867
  const automationEditFieldsSchema = z.object({
864
868
  title: automationTitleSchema.optional(),
865
869
  /** Replaces the whole task, so a mode switch drops the other mode's text. */
@@ -872,6 +876,948 @@ const eventAutomationEditSchema = automationEditFieldsSchema.extend({ trigger: e
872
876
  identifier: z.string().trim().min(1).max(300).optional(),
873
877
  label: z.string().trim().min(1).max(500)
874
878
  }).optional() }).strict();
879
+ // src/chat/attachments/input.ts
880
+ /**
881
+ * Largest file that Junior stores from Slack or the web, or loads into the
882
+ * sandbox.
883
+ *
884
+ * Every path streams the bytes, so this cap does not depend on function
885
+ * memory. It bounds transfer time and sandbox disk use.
886
+ */
887
+ const MAX_ATTACHMENT_BYTES = 262144e3;
888
+ /** Most files on one web Message, as in one Slack message. */
889
+ const MAX_INPUT_ATTACHMENTS = 10;
890
+ /** File facts that a browser declares before it uploads the bytes. */
891
+ const inputFileSchema = z.object({
892
+ filename: z.string().trim().min(1).max(255),
893
+ contentType: z.string().trim().toLowerCase().max(127).regex(/^[a-z0-9][\w.+-]*\/[a-z0-9][\w.+-]*$/),
894
+ bytes: z.number().int().min(1).max(MAX_ATTACHMENT_BYTES)
895
+ }).strict();
896
+ /** Safe attachment facts shared by mailbox input and transcript messages. */
897
+ const messageAttachmentSchema = z.object({
898
+ id: z.string().min(1),
899
+ filename: z.string().min(1),
900
+ contentType: z.string().min(1),
901
+ bytes: z.number().int().nonnegative(),
902
+ /**
903
+ * True for a large Slack file that Junior has not stored yet. A
904
+ * dashboard read downloads it from Slack, so it has no preview.
905
+ */
906
+ pending: z.literal(true).optional()
907
+ }).strict();
908
+ /** Read attachment metadata without exposing object storage keys or bytes. */
909
+ function readMessageAttachments(value) {
910
+ return messageAttachmentSchema.array().parse(value ?? []);
911
+ }
912
+ // src/chat/automations/card.ts
913
+ /** Saved automation facts shown with a Message, not a live status view. */
914
+ const automationCardSchema = z.object({
915
+ kind: z.literal("automation"),
916
+ id: z.string().min(1),
917
+ title: z.string().min(1).max(160),
918
+ url: z.string().url().nullable(),
919
+ instruction: z.string().max(4e3),
920
+ trigger: z.string().min(1),
921
+ warning: z.string().nullable()
922
+ }).strict();
923
+ /** Render saved card facts for text-only delivery and accessible fallbacks. */
924
+ function automationCardText(card) {
925
+ return [
926
+ card.title,
927
+ card.warning,
928
+ card.trigger,
929
+ card.instruction,
930
+ card.url,
931
+ `Automation ID: ${card.id}`
932
+ ].filter(Boolean).join("\n");
933
+ }
934
+ // src/chat/conversations/cards.ts
935
+ const storedCardSchema = automationCardSchema.extend({ operation: z.enum([
936
+ "created",
937
+ "updated",
938
+ "deleted"
939
+ ]).optional() });
940
+ /** Render each built-in card with its own text format. */
941
+ function messageCardText(card) {
942
+ switch (card.kind) {
943
+ case "object": return [
944
+ card.title,
945
+ card.label !== card.title ? card.label : void 0,
946
+ card.description,
947
+ card.status,
948
+ ...objectFactFields(card.facts).map((field) => `${field.label}: ${field.value}`),
949
+ card.trigger,
950
+ card.warning,
951
+ card.url
952
+ ].filter(Boolean).join("\n");
953
+ case "automation": return automationCardText(card);
954
+ }
955
+ }
956
+ /** Identify a deleted object whose pending card must be omitted. */
957
+ const removedCardSchema = z.object({
958
+ plugin: z.string().min(1),
959
+ key: z.string().min(1)
960
+ }).strict();
961
+ /** Store only the annotation identity with a Message. */
962
+ const messageCardRefSchema = removedCardSchema.extend({ kind: z.literal("object") });
963
+ /** Remove display facts before saving or reporting a Message card. */
964
+ function messageCardRef(card) {
965
+ return card.kind === "object" ? {
966
+ kind: "object",
967
+ plugin: card.plugin,
968
+ key: card.key
969
+ } : {
970
+ kind: "object",
971
+ plugin: "junior",
972
+ key: card.id
973
+ };
974
+ }
975
+ /** Read references, including identities from older saved card snapshots. */
976
+ function readMessageCardRefs(value) {
977
+ return [...storedCardSchema.array().parse(value.cards ?? []).flatMap(({ operation, ...card }) => operation === "deleted" ? [] : [messageCardRef(card)]), ...messageCardRefSchema.strip().array().parse(value.objectCards ?? [])];
978
+ }
979
+ /** Resolve current saved facts without fetching providers or changing history. */
980
+ function resolveMessageCards(refs, annotations) {
981
+ return refs.map((ref) => {
982
+ const annotation = annotations.find((item) => item.kind === ref.kind && item.plugin === ref.plugin && item.key === ref.key);
983
+ return annotation ? annotationCard(annotation) : {
984
+ ...ref,
985
+ objectType: "item",
986
+ title: ref.key,
987
+ label: ref.key,
988
+ url: null,
989
+ warning: "Saved annotation is unavailable."
990
+ };
991
+ });
992
+ }
993
+ /** Copy saved annotation facts without storage timestamps for Message delivery. */
994
+ function annotationCard(annotation) {
995
+ const { createdAt: _createdAt, updatedAt: _updatedAt, ...value } = annotation;
996
+ return value.kind === "object" ? value : {
997
+ ...value,
998
+ kind: "object",
999
+ objectType: value.objectType ?? "item",
1000
+ title: value.label
1001
+ };
1002
+ }
1003
+ // src/chat/inbox-items/change-record.ts
1004
+ /**
1005
+ * The person change to an Inbox item that one message records. Each inbound
1006
+ * message and saved Message that reports a take, answer, or dismiss carries
1007
+ * its own record, so the dashboard shows what that message did, not what the
1008
+ * item looks like now.
1009
+ *
1010
+ * Stored Messages and queued inputs keep this shape and their
1011
+ * `reviewItemChange` and `reviewItemChanges` keys from before Review items
1012
+ * became Inbox items, so these names stay.
1013
+ */
1014
+ const inboxItemChangeRecordSchema = z.object({
1015
+ kind: z.enum([
1016
+ "submitted",
1017
+ "dismissed",
1018
+ "taken"
1019
+ ]),
1020
+ reviewItemId: z.string().min(1)
1021
+ }).strict();
1022
+ // src/api/schema/conversation-read-position.ts
1023
+ /**
1024
+ * How far the signed-in viewer has read a Conversation transcript.
1025
+ *
1026
+ * `lastReadSeq` is the event sequence of the last transcript row the viewer
1027
+ * saw. Reports only move it forward: the server keeps the highest value it
1028
+ * receives. It is never before the viewer's own latest Message.
1029
+ */
1030
+ const conversationReadPositionSchema = z.object({ lastReadSeq: z.number().int().nonnegative() }).strict();
1031
+ // src/api/schema/conversation-kind.ts
1032
+ /** Where a Conversation sits in its tree. See `TERMINOLOGY.md`. */
1033
+ const conversationKindSchema = z.enum([
1034
+ "root",
1035
+ "automation",
1036
+ "lead",
1037
+ "thread",
1038
+ "task"
1039
+ ]);
1040
+ // src/api/schema/conversation-title.ts
1041
+ /** Longest Conversation title that a rename can save. */
1042
+ const CONVERSATION_TITLE_MAX_LENGTH = 200;
1043
+ /** A Conversation title that a caller chooses, at creation or on rename. */
1044
+ const conversationTitleSchema = z.string().trim().min(1).max(200);
1045
+ /** A participant's new title for one Conversation. Every viewer sees it. */
1046
+ const renameConversationBodySchema = z.object({ title: conversationTitleSchema }).strict();
1047
+ /** The stored title after the rename. */
1048
+ const renameConversationResponseSchema = z.object({ title: z.string().min(1) }).strict();
1049
+ // src/api/schema/conversation-tree-state.ts
1050
+ /**
1051
+ * What a Conversation and its child Conversations need, for one viewer.
1052
+ * See "Viewer state" in `TERMINOLOGY.md`.
1053
+ */
1054
+ const conversationTreeStateSchema = z.enum([
1055
+ "needs_you",
1056
+ "working",
1057
+ "done"
1058
+ ]);
1059
+ // src/chat/agent-invocations/agent-types.ts
1060
+ /**
1061
+ * Child agent types. A type is plain data: when to pick it and what the child
1062
+ * reads with its task. Runtime code reads only these fields, never a type
1063
+ * name, so types can later come from configuration. Types do not limit tools:
1064
+ * Guardian reviews each child action against the root user's messages, as for
1065
+ * any child. A child keeps its type for later agent invocations. How a child
1066
+ * starts, fresh or forked from its parent's history, is not a type: see
1067
+ * `fork` on the agent invocation.
1068
+ */
1069
+ const AGENT_TYPES = ["explore", "reviewer"];
1070
+ /**
1071
+ * Stored name of a child agent type. A stored name stays readable after its
1072
+ * type is removed; the runtime then treats the child as a
1073
+ * child without a type.
1074
+ */
1075
+ const agentTypeSchema = z.string().regex(/^[a-z][a-z0-9_-]*$/);
1076
+ const AGENT_TYPE_DEFINITIONS = {
1077
+ explore: {
1078
+ whenToUse: "Investigation across code, docs, logs, telemetry, or the web. Use it when an answer needs reading across many files or sources and you need the conclusion with evidence, not the raw output.",
1079
+ instructions: "You are an explore agent. Investigate, and do not change anything outside your sandbox unless the task asks for it. Back your answer with exact evidence, such as paths, lines, links, and ids."
1080
+ },
1081
+ reviewer: {
1082
+ whenToUse: "An independent second opinion on a change, plan, or claim. Give it the evidence to judge, not your conclusion.",
1083
+ instructions: "You are a reviewer agent. Give an independent assessment. Do not assume that the parent's framing is correct: verify each claim against the evidence. Do not change anything outside your own sandbox. Report concrete problems ranked by severity, each with its evidence, and say clearly when you found none."
1084
+ }
1085
+ };
1086
+ function agentTypeDefinition(type) {
1087
+ return type && Object.hasOwn(AGENT_TYPE_DEFINITIONS, type) ? AGENT_TYPE_DEFINITIONS[type] : void 0;
1088
+ }
1089
+ /** Model-facing list of child agent types. */
1090
+ function formatAgentTypes() {
1091
+ return AGENT_TYPES.map((type) => `- "${type}": ${AGENT_TYPE_DEFINITIONS[type].whenToUse}`).join("\n");
1092
+ }
1093
+ /** Return the instructions that a child of this type reads with its task. */
1094
+ function agentTypeInstructions(type) {
1095
+ return agentTypeDefinition(type)?.instructions;
1096
+ }
1097
+ // src/api/schema/child-agent-totals.ts
1098
+ /**
1099
+ * The part of a Conversation total that its child agents spent, at any depth.
1100
+ * Present only when the Conversation has child agents. The Conversation's own
1101
+ * part is the total minus this part.
1102
+ */
1103
+ const conversationChildAgentTotalsSchema = z.object({
1104
+ auxiliaryCostUsd: z.number().finite().nonnegative().optional(),
1105
+ count: z.number().int().positive(),
1106
+ cumulativeDurationMs: z.number(),
1107
+ cumulativeUsage: usageSchema.optional()
1108
+ }).strict();
1109
+ // src/api/schema/object-preview-image.ts
1110
+ /**
1111
+ * One saved preview image of an object, such as a pull request screenshot,
1112
+ * at 1x and 2x. Both name the Junior image route, never the image host.
1113
+ */
1114
+ const objectPreviewImageSchema = z.object({
1115
+ src: z.string().startsWith("/api/images/"),
1116
+ srcSet: z.string().min(1)
1117
+ }).strict();
1118
+ const CUT_TOKEN_RE = /<(?:[@#!][^<>]*|[a-z]+:[^\s<>|]*(?:\|[^<>]*)?|[a-z]*)$/i;
1119
+ /**
1120
+ * Cut preview text to the schema limit. The cut ends with "…" at a word
1121
+ * break, and never leaves half a surrogate pair or an unclosed Slack token
1122
+ * such as `<@U1` or `<https://…`, so mentions and links still parse.
1123
+ */
1124
+ function activityPreviewText(text) {
1125
+ if (text.length <= 400) return text;
1126
+ let cut = text.slice(0, 399);
1127
+ const space = cut.search(/\s\S*$/);
1128
+ if (space > 0 && /\S/.test(text[cut.length])) cut = cut.slice(0, space);
1129
+ const last = cut.charCodeAt(cut.length - 1);
1130
+ if (last >= 55296 && last <= 56319) cut = cut.slice(0, -1);
1131
+ return `${cut.replace(CUT_TOKEN_RE, "").trimEnd()}…`;
1132
+ }
1133
+ // src/api/schema/conversation.ts
1134
+ /**
1135
+ * The status of one Conversation's own work. See `TERMINOLOGY.md` and
1136
+ * `conversationStatusSql`, the only place that derives it.
1137
+ */
1138
+ const conversationReportStatusSchema = z.enum([
1139
+ "needs_input",
1140
+ "working",
1141
+ "done"
1142
+ ]);
1143
+ const conversationSurfaceSchema = z.enum([
1144
+ "api",
1145
+ "internal",
1146
+ "scheduler",
1147
+ "slack"
1148
+ ]);
1149
+ const conversationUsageSchema = usageSchema;
1150
+ const conversationParamsSchema = z.object({ conversationId: z.string().min(1) }).strict();
1151
+ const conversationAttachmentParamsSchema = z.object({
1152
+ attachmentId: z.string().min(1),
1153
+ conversationId: z.string().min(1)
1154
+ }).strict();
1155
+ const conversationAttachmentQuerySchema = z.object({
1156
+ /**
1157
+ * Send `Content-Disposition: attachment` even for a type that previews
1158
+ * inline, so a same-window download link saves the file.
1159
+ */
1160
+ download: z.stringbool().optional() }).strict();
1161
+ const conversationDetailQuerySchema = z.object({
1162
+ /** Omit to get the latest three Turns, up to the default page limit. */
1163
+ limit: z.coerce.number().int().min(1).max(1e3).optional(),
1164
+ /** Also return `unreadPage` when the detail has an `unreadCursor`. */
1165
+ unreadPage: z.stringbool().optional(),
1166
+ /**
1167
+ * Also return `mailbox`, read before history. A sent version that still
1168
+ * matches gets `{ unchanged: true, mailbox }` instead of 304, so a poll
1169
+ * needs one request.
1170
+ */
1171
+ mailbox: z.stringbool().optional(),
1172
+ /**
1173
+ * An `appendCursor` from an earlier detail. Events then hold only newer
1174
+ * events, with `appended: true`, while the cursor still applies.
1175
+ */
1176
+ after: z.string().min(1).optional()
1177
+ }).strict();
1178
+ const conversationEventsLimitSchema = z.coerce.number().int().min(1).max(1e3).default(150);
1179
+ /**
1180
+ * Page toward the start with `before`, toward the latest with `after`, or
1181
+ * both ways from one event with `around`. A link target asks for the page
1182
+ * around one event by its `event` seq, around one `message` by its id, or
1183
+ * around the start of a `turn`.
1184
+ */
1185
+ const conversationEventsQuerySchema = z.union([
1186
+ z.object({
1187
+ before: z.string().min(1),
1188
+ limit: conversationEventsLimitSchema
1189
+ }).strict(),
1190
+ z.object({
1191
+ after: z.string().min(1),
1192
+ limit: conversationEventsLimitSchema
1193
+ }).strict(),
1194
+ z.object({
1195
+ around: z.string().min(1),
1196
+ limit: conversationEventsLimitSchema
1197
+ }).strict(),
1198
+ z.object({
1199
+ event: z.coerce.number().int().min(0),
1200
+ limit: conversationEventsLimitSchema
1201
+ }).strict(),
1202
+ z.object({
1203
+ turn: z.string().min(1),
1204
+ limit: conversationEventsLimitSchema
1205
+ }).strict(),
1206
+ z.object({
1207
+ message: z.string().min(1),
1208
+ limit: conversationEventsLimitSchema
1209
+ }).strict()
1210
+ ]);
1211
+ /** Client key that makes a retried send the same Message. */
1212
+ const idempotencyKeySchema = z.string().trim().min(1).max(200);
1213
+ const createConversationMessageBodySchema = z.object({
1214
+ idempotencyKey: idempotencyKeySchema,
1215
+ message: z.string().trim().max(32e3),
1216
+ /** Uploads from `POST /api/conversations/attachment-uploads`. */
1217
+ uploadIds: z.array(z.string().min(1).max(64)).max(10).optional()
1218
+ }).strict().refine((body) => Boolean(body.message || body.uploadIds?.length), "Add a message or a file.");
1219
+ const createConversationBodySchema = createConversationMessageBodySchema.safeExtend({
1220
+ /** Saved title. Title generation runs only when it is omitted. */
1221
+ title: conversationTitleSchema.optional(),
1222
+ /** New roots default public. Private roots stay participant-only. */
1223
+ visibility: z.enum(["private", "public"]).optional()
1224
+ });
1225
+ const acceptedConversationMessageSchema = z.object({
1226
+ conversationId: z.string().min(1),
1227
+ messageId: z.string().min(1),
1228
+ status: z.enum(["accepted", "duplicate"])
1229
+ }).strict();
1230
+ const actorIdentitySchema = z.object({
1231
+ /**
1232
+ * Junior API path of the profile photo: the person's Slack photo, then
1233
+ * their Google photo.
1234
+ */
1235
+ avatarUrl: z.string().optional(),
1236
+ email: z.string().optional(),
1237
+ fullName: z.string().optional(),
1238
+ slackUserId: z.string().optional(),
1239
+ slackUserName: z.string().optional()
1240
+ }).strict();
1241
+ const conversationAuxiliaryCostsSchema = z.object({
1242
+ costUsd: z.number().finite().nonnegative(),
1243
+ operations: z.array(z.object({
1244
+ costUsd: z.number().finite().nonnegative(),
1245
+ events: z.number().int().positive(),
1246
+ name: z.string().min(1),
1247
+ namespace: z.string().min(1)
1248
+ }).strict()).min(1)
1249
+ }).strict();
1250
+ /** Optional reverse link from a task-triggered conversation back to its task. */
1251
+ const conversationSourceTaskSchema = z.object({
1252
+ id: z.string().min(1).optional(),
1253
+ kind: z.enum(["scheduled", "event"]),
1254
+ label: z.string().min(1).optional(),
1255
+ title: z.string().min(1).optional(),
1256
+ /** Message id of the run's trigger input, which is not from a person. */
1257
+ triggerMessageId: z.string().min(1).optional(),
1258
+ /** Short trigger text, such as an event or a schedule. */
1259
+ triggerLabel: z.string().min(1).optional(),
1260
+ /** Credential mode this run used. Unset when the run record is gone. */
1261
+ credentialMode: z.enum(["creator", "system"]).optional(),
1262
+ /** Name of the creator whose credentials this run used. */
1263
+ credentialUser: z.string().min(1).optional()
1264
+ }).strict().superRefine((value, context) => {
1265
+ if (Boolean(value.id) !== Boolean(value.label)) context.addIssue({
1266
+ code: "custom",
1267
+ message: "sourceTask id and label must both be set or both omitted"
1268
+ });
1269
+ });
1270
+ const conversationAnnotationReportSchema = conversationAnnotationInputSchema.and(z.object({
1271
+ plugin: z.string().min(1),
1272
+ createdAt: z.string().datetime(),
1273
+ updatedAt: z.string().datetime(),
1274
+ previewImages: z.array(objectPreviewImageSchema).optional()
1275
+ }));
1276
+ const conversationActivityPreviewSchema = z.object({
1277
+ createdAt: z.string().datetime(),
1278
+ mentions: z.array(actorIdentitySchema).optional(),
1279
+ role: z.enum(["assistant", "user"]),
1280
+ text: z.string().min(1).max(400)
1281
+ }).strict();
1282
+ const conversationSummaryReportSchema = z.object({
1283
+ displayTitle: z.string(),
1284
+ /**
1285
+ * Conversation metadata, when the viewer may see private content. A new
1286
+ * Conversation has none until its first Turn completes.
1287
+ */
1288
+ summary: z.string().optional(),
1289
+ activityPreview: conversationActivityPreviewSchema.optional(),
1290
+ cumulativeDurationMs: z.number(),
1291
+ cumulativeUsage: conversationUsageSchema.optional(),
1292
+ auxiliaryCosts: conversationAuxiliaryCostsSchema.optional(),
1293
+ childAgentTotals: conversationChildAgentTotalsSchema.optional(),
1294
+ conversationId: z.string(),
1295
+ kind: conversationKindSchema,
1296
+ /** Present on Threads and Tasks. */
1297
+ parentConversationId: z.string().min(1).optional(),
1298
+ isParticipant: z.boolean(),
1299
+ visibility: z.enum(["private", "public"]).optional(),
1300
+ status: conversationReportStatusSchema,
1301
+ /** Feed rows and the detail only. */
1302
+ treeState: conversationTreeStateSchema.optional(),
1303
+ /**
1304
+ * A Conversation in the tree has an active Watch or a pending Timer.
1305
+ * Feed rows and the detail only.
1306
+ */
1307
+ watching: z.boolean().optional(),
1308
+ /**
1309
+ * A Turn is queued or running. Live views poll and show thinking on it,
1310
+ * since `status` can read `needs_input` while a Turn runs.
1311
+ */
1312
+ turnActive: z.boolean(),
1313
+ startedAt: z.string(),
1314
+ lastSeenAt: z.string(),
1315
+ lastProgressAt: z.string(),
1316
+ lastMessageAt: z.string().datetime().optional(),
1317
+ surface: conversationSurfaceSchema,
1318
+ actorIdentity: actorIdentitySchema.optional(),
1319
+ participants: z.array(actorIdentitySchema).optional(),
1320
+ /**
1321
+ * When this Conversation was archived for everyone, or null. It shows
1322
+ * only while it and every ancestor are unarchived.
1323
+ */
1324
+ archivedAt: z.string().datetime().nullable().optional(),
1325
+ pinnedAt: z.string().datetime().nullable().optional(),
1326
+ /** The viewer's place in Pinned. Unset until they reorder their pins. */
1327
+ pinPosition: z.number().int().optional(),
1328
+ channel: z.string().optional(),
1329
+ channelName: z.string().optional(),
1330
+ channelNameRedacted: z.boolean().optional(),
1331
+ locationId: z.string().optional(),
1332
+ sentryTraceUrl: z.string().optional(),
1333
+ locationUrl: z.string().url().optional(),
1334
+ traceId: z.string().optional(),
1335
+ /**
1336
+ * Plugin-selected annotations for the compact conversation row. The feed
1337
+ * sends only these; the detail also sends the full `annotations`.
1338
+ */
1339
+ sidebarAnnotations: z.array(conversationSidebarAnnotationSchema).optional(),
1340
+ assignedWork: z.boolean().optional(),
1341
+ finishedWorkAt: z.string().datetime().optional(),
1342
+ /**
1343
+ * Dashboard Priority membership for this conversation summary.
1344
+ * Present on the conversation feed. Clients must not recompute it.
1345
+ *
1346
+ * True only when:
1347
+ * - unfinished work was last seen within 48 hours
1348
+ * - finished assigned work has conversation activity after the finish time
1349
+ * - there is no known work and the conversation was last seen within 3 hours
1350
+ */
1351
+ isPriority: z.boolean().optional(),
1352
+ unfinishedWork: z.boolean().optional(),
1353
+ /**
1354
+ * True on the conversation feed when a Turn in the conversation or a
1355
+ * child waits on a person to finish an authorization that has not
1356
+ * expired.
1357
+ */
1358
+ awaitingAuthorization: z.boolean().optional(),
1359
+ /**
1360
+ * True on the conversation feed when the conversation's latest Turn
1361
+ * failed and no newer Turn started.
1362
+ */
1363
+ latestTurnFailed: z.boolean().optional()
1364
+ }).strict();
1365
+ /** One Event listed on a message that holds several Events. */
1366
+ const conversationReportMessageEventSchema = z.object({
1367
+ eventType: z.string().min(1),
1368
+ label: z.string().min(1).optional(),
1369
+ objectType: objectTypeSchema.optional(),
1370
+ trustedSummary: z.string().min(1).optional()
1371
+ }).strict();
1372
+ const conversationReportMessageEventDataSchema = z.object({
1373
+ type: z.literal("message"),
1374
+ messageId: z.string().min(1),
1375
+ role: z.enum([
1376
+ "assistant",
1377
+ "system",
1378
+ "user"
1379
+ ]),
1380
+ source: z.enum(["slack", "web"]).optional(),
1381
+ actorIdentity: actorIdentitySchema.optional(),
1382
+ /** Identity id of the author. Detail `authors` maps it to the person. */
1383
+ actorIdentityId: z.string().min(1).optional(),
1384
+ /** Agent invocation whose input this is. An agent wrote it, not a person. */
1385
+ agentInvocationId: z.string().min(1).optional(),
1386
+ eventType: z.string().min(1).optional(),
1387
+ /** Namespace of the first Event, such as `github`. */
1388
+ eventNamespace: z.string().min(1).optional(),
1389
+ /**
1390
+ * Resource identifier of the first Event, such as the id of a watched
1391
+ * Conversation. Only for viewers who can see private content.
1392
+ */
1393
+ eventIdentifier: z.string().min(1).optional(),
1394
+ eventObjectType: objectTypeSchema.optional(),
1395
+ explicitMention: z.boolean().optional(),
1396
+ quiet: z.literal(true).optional(),
1397
+ trustedSummary: z.string().min(1).optional(),
1398
+ /**
1399
+ * The Watch Events when several arrived together. A message that also
1400
+ * records Inbox item changes lists its own Event here even when it has
1401
+ * one.
1402
+ */
1403
+ events: z.array(conversationReportMessageEventSchema).optional(),
1404
+ cards: z.array(messageCardRefSchema).optional(),
1405
+ /** Person changes to Inbox items that this message records. */
1406
+ reviewItemChanges: z.array(inboxItemChangeRecordSchema).min(1).optional(),
1407
+ text: z.string().optional(),
1408
+ attachments: z.array(messageAttachmentSchema).optional(),
1409
+ redacted: z.literal(true).optional()
1410
+ }).strict().superRefine((data, context) => {
1411
+ if (data.text === void 0 === (data.redacted !== true)) context.addIssue({
1412
+ code: "custom",
1413
+ message: "message content must be text or explicitly redacted"
1414
+ });
1415
+ if (data.redacted && (data.actorIdentity || data.cards || data.attachments || data.events || data.reviewItemChanges)) context.addIssue({
1416
+ code: "custom",
1417
+ message: "redacted messages must not expose actor identity, cards, attachments, events, or inbox item changes"
1418
+ });
1419
+ });
1420
+ const conversationReportMessageHandledEventDataSchema = z.object({
1421
+ type: z.literal("message_handled"),
1422
+ messageId: z.string().min(1)
1423
+ }).strict();
1424
+ const conversationReportToolCallSchema = z.object({
1425
+ toolCallId: z.string().min(1),
1426
+ name: z.string().min(1),
1427
+ status: z.enum([
1428
+ "running",
1429
+ "completed",
1430
+ "error"
1431
+ ]),
1432
+ startedAt: z.string().datetime().optional(),
1433
+ startedSeq: z.number().int().nonnegative().optional(),
1434
+ input: z.unknown().optional(),
1435
+ output: z.unknown().optional(),
1436
+ /** The Conversation that a completed `startConversation` call started. */
1437
+ startedConversationId: z.string().min(1).optional()
1438
+ }).strict().superRefine((call, context) => {
1439
+ if (call.startedAt === void 0 !== (call.startedSeq === void 0)) context.addIssue({
1440
+ code: "custom",
1441
+ message: "tool start sequence and timestamp must be provided together"
1442
+ });
1443
+ });
1444
+ const conversationReportReasoningPartSchema = z.object({
1445
+ type: z.literal("reasoning"),
1446
+ text: z.string().min(1).optional(),
1447
+ redacted: z.literal(true).optional()
1448
+ }).strict().superRefine((data, context) => {
1449
+ if (data.text === void 0 === (data.redacted !== true)) context.addIssue({
1450
+ code: "custom",
1451
+ message: "reasoning content must be text or explicitly redacted"
1452
+ });
1453
+ });
1454
+ const conversationReportAssistantToolCallPartSchema = z.object({
1455
+ type: z.literal("tool_call"),
1456
+ toolCallId: z.string().min(1)
1457
+ }).strict();
1458
+ const conversationReportAssistantMetadataSchema = z.object({ parts: z.array(z.discriminatedUnion("type", [conversationReportReasoningPartSchema, conversationReportAssistantToolCallPartSchema])).min(1) }).strict();
1459
+ const conversationReportToolCallsEventDataSchema = z.object({
1460
+ type: z.literal("tool_calls"),
1461
+ calls: z.array(conversationReportToolCallSchema).min(1),
1462
+ assistant: conversationReportAssistantMetadataSchema.optional()
1463
+ }).strict().superRefine((data, context) => {
1464
+ if (!data.assistant) return;
1465
+ const callCounts = /* @__PURE__ */ new Map();
1466
+ for (const call of data.calls) callCounts.set(call.toolCallId, (callCounts.get(call.toolCallId) ?? 0) + 1);
1467
+ const partCounts = /* @__PURE__ */ new Map();
1468
+ for (const part of data.assistant.parts) {
1469
+ if (part.type !== "tool_call") continue;
1470
+ partCounts.set(part.toolCallId, (partCounts.get(part.toolCallId) ?? 0) + 1);
1471
+ }
1472
+ if (callCounts.size !== partCounts.size || [...callCounts].some(([toolCallId, count]) => partCounts.get(toolCallId) !== count)) context.addIssue({
1473
+ code: "custom",
1474
+ path: ["assistant", "parts"],
1475
+ message: "assistant tool parts must reference every call exactly once"
1476
+ });
1477
+ });
1478
+ const conversationReportAssistantMessageEventDataSchema = z.object({
1479
+ type: z.literal("assistant_message"),
1480
+ parts: z.array(conversationReportReasoningPartSchema)
1481
+ }).strict();
1482
+ const conversationReportTurnLifecycleEventDataSchema = z.discriminatedUnion("state", [
1483
+ z.object({
1484
+ type: z.literal("turn_lifecycle"),
1485
+ turnId: z.string().min(1),
1486
+ state: z.enum([
1487
+ "succeeded",
1488
+ "no_reply",
1489
+ "blocked"
1490
+ ])
1491
+ }).strict(),
1492
+ z.object({
1493
+ type: z.literal("turn_lifecycle"),
1494
+ turnId: z.string().min(1),
1495
+ state: z.literal("started"),
1496
+ inputMessageIds: z.array(z.string().min(1)).min(1).optional()
1497
+ }).strict(),
1498
+ z.object({
1499
+ type: z.literal("turn_lifecycle"),
1500
+ turnId: z.string().min(1),
1501
+ state: z.literal("failed"),
1502
+ failureCode: conversationTurnFailureCodeSchema,
1503
+ failureReason: conversationTurnFailureReasonSchema.optional(),
1504
+ eventId: z.string().regex(/^[a-f0-9]{32}$/i).optional(),
1505
+ sentryEventUrl: z.string().url().optional()
1506
+ }).strict()
1507
+ ]);
1508
+ const conversationReportGuardianActionReviewedEventDataSchema = z.object({
1509
+ type: z.literal("guardian_action_reviewed"),
1510
+ turnId: z.string().min(1),
1511
+ toolCallId: z.string().min(1),
1512
+ toolName: z.string().min(1),
1513
+ decision: z.enum([
1514
+ "allow",
1515
+ "ask",
1516
+ "deny"
1517
+ ]),
1518
+ riskLevel: z.enum([
1519
+ "low",
1520
+ "medium",
1521
+ "high",
1522
+ "critical"
1523
+ ]),
1524
+ userAuthorization: z.enum([
1525
+ "high",
1526
+ "medium",
1527
+ "low",
1528
+ "unknown"
1529
+ ])
1530
+ }).strict();
1531
+ const conversationReportTurnContextEventDataSchema = z.object({
1532
+ type: z.literal("turn_context"),
1533
+ turnId: z.string().min(1),
1534
+ pluginName: z.string().min(1),
1535
+ kind: z.string().min(1),
1536
+ version: z.number().int().positive(),
1537
+ content: z.record(z.string(), z.unknown())
1538
+ }).strict();
1539
+ const conversationReportStructuredEventDataSchema = z.object({
1540
+ type: z.literal("structured_event"),
1541
+ namespace: z.string().min(1),
1542
+ name: z.string().min(1),
1543
+ version: z.number().int().positive(),
1544
+ turnId: z.string().min(1).optional(),
1545
+ presentation: conversationEventPresentationSchema
1546
+ }).strict();
1547
+ const conversationReportAttachmentsDeliveredEventDataSchema = z.object({
1548
+ type: z.literal("attachments_delivered"),
1549
+ attachments: z.array(messageAttachmentSchema).min(1)
1550
+ }).strict();
1551
+ /** Junior text that a plugin tool posted to its provider. */
1552
+ const conversationReportReplyPostedEventDataSchema = z.object({
1553
+ type: z.literal("reply_posted"),
1554
+ plugin: z.string().min(1),
1555
+ text: z.string().min(1),
1556
+ url: z.string().url().optional()
1557
+ }).strict();
1558
+ const conversationReportCompactionEventDataSchema = z.object({
1559
+ type: z.literal("compaction"),
1560
+ modelId: z.string().min(1).optional(),
1561
+ summary: z.string().min(1).optional(),
1562
+ details: z.object({
1563
+ reason: z.literal("capacity"),
1564
+ estimatedInputTokens: z.number().int().nonnegative(),
1565
+ replacementInputTokens: z.number().int().nonnegative().optional(),
1566
+ triggerTokens: z.number().int().nonnegative(),
1567
+ inputLimitTokens: z.number().int().positive(),
1568
+ inputMessageCount: z.number().int().nonnegative(),
1569
+ retainedMessageCount: z.number().int().nonnegative(),
1570
+ summaryChars: z.number().int().nonnegative()
1571
+ }).strict().optional()
1572
+ }).strict();
1573
+ const conversationReportSubagentEventDataSchema = z.object({
1574
+ type: z.literal("subagent"),
1575
+ startedSeq: z.number().int().nonnegative(),
1576
+ startedAt: z.string().datetime(),
1577
+ childConversationId: z.string().min(1),
1578
+ /** The child's Conversation kind. Only a Thread has its own page link. */
1579
+ childKind: z.enum(["thread", "task"]),
1580
+ subagentKind: z.string().min(1),
1581
+ agentName: z.string().min(1).optional(),
1582
+ task: z.string().min(1).optional(),
1583
+ title: z.string().min(1).optional(),
1584
+ parentToolCallId: z.string().min(1).optional(),
1585
+ status: z.enum([
1586
+ "running",
1587
+ "completed",
1588
+ "blocked",
1589
+ "error",
1590
+ "aborted"
1591
+ ])
1592
+ }).strict();
1593
+ /** Privacy-safe event variants owned by the conversation reporting API. */
1594
+ const conversationReportEventDataSchema = z.discriminatedUnion("type", [
1595
+ conversationReportMessageEventDataSchema,
1596
+ conversationReportMessageHandledEventDataSchema,
1597
+ conversationReportAssistantMessageEventDataSchema,
1598
+ conversationReportToolCallsEventDataSchema,
1599
+ conversationReportTurnLifecycleEventDataSchema,
1600
+ conversationReportTurnContextEventDataSchema,
1601
+ conversationReportStructuredEventDataSchema,
1602
+ conversationReportAttachmentsDeliveredEventDataSchema,
1603
+ conversationReportReplyPostedEventDataSchema,
1604
+ conversationReportGuardianActionReviewedEventDataSchema,
1605
+ conversationReportCompactionEventDataSchema,
1606
+ conversationReportSubagentEventDataSchema
1607
+ ]);
1608
+ /** One ordered, privacy-safe canonical event projected for API consumers. */
1609
+ const conversationReportEventSchema = z.object({
1610
+ seq: z.number().int().nonnegative(),
1611
+ createdAt: z.string().datetime(),
1612
+ data: conversationReportEventDataSchema,
1613
+ /** People mentioned in the event text, resolved at read time. */
1614
+ mentions: z.array(actorIdentitySchema).optional(),
1615
+ model: z.object({ modelId: z.string().min(1) }).strict().optional(),
1616
+ modelCall: z.object({
1617
+ provider: z.string().min(1).optional(),
1618
+ api: z.string().min(1).optional(),
1619
+ stopReason: z.string().min(1).optional(),
1620
+ usage: conversationUsageSchema.optional()
1621
+ }).strict().optional()
1622
+ }).strict();
1623
+ /** Availability of the canonical event history attached to a detail report. */
1624
+ const conversationEventHistorySchema = z.discriminatedUnion("status", [
1625
+ z.object({ status: z.literal("available") }).strict(),
1626
+ z.object({
1627
+ status: z.literal("redacted"),
1628
+ reason: z.literal("non_public_conversation")
1629
+ }).strict(),
1630
+ z.object({
1631
+ status: z.literal("expired"),
1632
+ expiredAt: z.string().datetime()
1633
+ }).strict()
1634
+ ]);
1635
+ const conversationModelUsageSchema = z.object({
1636
+ modelId: z.string(),
1637
+ usage: conversationUsageSchema
1638
+ }).strict();
1639
+ /** Enforce event ordering and history visibility across paginated wire payloads. */
1640
+ function validateConversationEvents(report, context) {
1641
+ if (report.eventHistory.status === "expired" && report.events.length > 0) context.addIssue({
1642
+ code: "custom",
1643
+ path: ["events"],
1644
+ message: "expired event history must not contain events"
1645
+ });
1646
+ for (let index = 1; index < report.events.length; index += 1) if (report.events[index].seq <= report.events[index - 1].seq) context.addIssue({
1647
+ code: "custom",
1648
+ path: [
1649
+ "events",
1650
+ index,
1651
+ "seq"
1652
+ ],
1653
+ message: "report event sequences must be strictly increasing"
1654
+ });
1655
+ for (const [index, event] of report.events.entries()) {
1656
+ if (event.data.type === "message") {
1657
+ if (report.eventHistory.status === "redacted" && event.data.redacted !== true) context.addIssue({
1658
+ code: "custom",
1659
+ path: [
1660
+ "events",
1661
+ index,
1662
+ "data"
1663
+ ],
1664
+ message: "redacted event history must redact messages"
1665
+ });
1666
+ if (report.eventHistory.status === "available" && event.data.redacted === true) context.addIssue({
1667
+ code: "custom",
1668
+ path: [
1669
+ "events",
1670
+ index,
1671
+ "data"
1672
+ ],
1673
+ message: "available event history must expose messages"
1674
+ });
1675
+ }
1676
+ if (report.eventHistory.status === "redacted" && event.data.type === "tool_calls" && event.data.calls.some((call) => call.input !== void 0 || call.output !== void 0)) context.addIssue({
1677
+ code: "custom",
1678
+ path: [
1679
+ "events",
1680
+ index,
1681
+ "data"
1682
+ ],
1683
+ message: "redacted event history must redact tool payloads"
1684
+ });
1685
+ if (report.eventHistory.status === "redacted" && event.data.type === "assistant_message" && event.data.parts.some((part) => part.text !== void 0)) context.addIssue({
1686
+ code: "custom",
1687
+ path: [
1688
+ "events",
1689
+ index,
1690
+ "data"
1691
+ ],
1692
+ message: "redacted event history must redact assistant messages"
1693
+ });
1694
+ if (report.eventHistory.status === "available" && event.data.type === "assistant_message" && event.data.parts.some((part) => part.redacted === true)) context.addIssue({
1695
+ code: "custom",
1696
+ path: [
1697
+ "events",
1698
+ index,
1699
+ "data"
1700
+ ],
1701
+ message: "available event history must expose reasoning"
1702
+ });
1703
+ if (event.data.type === "tool_calls" && (report.eventHistory.status === "redacted" && event.data.assistant?.parts.some((part) => part.type === "reasoning" && part.text !== void 0) || report.eventHistory.status === "available" && event.data.assistant?.parts.some((part) => part.type === "reasoning" && part.redacted === true))) context.addIssue({
1704
+ code: "custom",
1705
+ path: [
1706
+ "events",
1707
+ index,
1708
+ "data",
1709
+ "assistant"
1710
+ ],
1711
+ message: "assistant reasoning must match event history visibility"
1712
+ });
1713
+ }
1714
+ }
1715
+ /** One Conversation in the agent tree of a child Conversation. */
1716
+ const conversationAgentTreeNodeSchema = z.object({
1717
+ conversationId: z.string().min(1),
1718
+ kind: conversationKindSchema,
1719
+ label: z.string().min(1),
1720
+ /**
1721
+ * Agent type of a child, such as `explore`. Absent for a root, a child
1722
+ * without a type, or a viewer who cannot see private content.
1723
+ */
1724
+ agentType: agentTypeSchema.optional(),
1725
+ /**
1726
+ * The child started with its parent's history. Absent like `agentType`,
1727
+ * or when the child started fresh.
1728
+ */
1729
+ fork: z.literal(true).optional()
1730
+ }).strict();
1731
+ const conversationEventPageSchema = z.object({
1732
+ events: z.array(conversationReportEventSchema),
1733
+ eventHistory: conversationEventHistorySchema,
1734
+ previousCursor: z.string().min(1).optional(),
1735
+ /** Present on `after` and `around` pages when newer events follow. */
1736
+ nextCursor: z.string().min(1).optional(),
1737
+ generatedAt: z.string()
1738
+ }).strict().superRefine(validateConversationEvents);
1739
+ /**
1740
+ * Carries the detail version token in both directions. A custom header, not
1741
+ * `ETag`, for the reason on `CONTENT_VERSION_HEADER`.
1742
+ */
1743
+ const CONVERSATION_DETAIL_VERSION_HEADER = "x-junior-detail-version";
1744
+ /**
1745
+ * Carries the change token of the Conversation tree that a detail report was
1746
+ * built from. The dashboard compares it with the token of `GET /api/versions`
1747
+ * and asks for the report only when they differ.
1748
+ */
1749
+ const CONVERSATION_VERSION_HEADER = "x-junior-conversation-version";
1750
+ const conversationDetailReportSchema = conversationSummaryReportSchema.extend({
1751
+ /**
1752
+ * The parent chain of a child Conversation, root first, with this
1753
+ * Conversation last. Root Conversations omit it.
1754
+ */
1755
+ agentTree: z.array(conversationAgentTreeNodeSchema).min(2).optional(),
1756
+ /**
1757
+ * Plugin-owned annotations of this Conversation and its tree, when the
1758
+ * viewer can see private content. Clients must not fetch provider state
1759
+ * while rendering them.
1760
+ */
1761
+ annotations: z.array(conversationAnnotationReportSchema).optional(),
1762
+ /** The viewer's effective auto-archive choice. Participants only. */
1763
+ autoArchive: z.boolean().optional(),
1764
+ /** The viewer can fork this conversation from an assistant reply. */
1765
+ canFork: z.boolean().optional(),
1766
+ /** The viewer can move this dashboard conversation to a Slack thread. */
1767
+ canContinueInSlack: z.literal(true).optional(),
1768
+ /**
1769
+ * Event Turn replies stay out of the Location. Set only for a root with
1770
+ * a Location, when the viewer is a participant, who can change it.
1771
+ */
1772
+ deliveryPaused: z.boolean().optional(),
1773
+ /**
1774
+ * The viewer gets this conversation in their active feed. Participants
1775
+ * only. False after an unsubscribe, until they mention Junior again.
1776
+ */
1777
+ subscribed: z.boolean().optional(),
1778
+ /** How far the signed-in viewer has read. Absent until they read. */
1779
+ readPosition: conversationReadPositionSchema.optional(),
1780
+ /**
1781
+ * Pass as `after` to the events API to read from the read position.
1782
+ * Present only when unread events start before `events`.
1783
+ */
1784
+ unreadCursor: z.string().min(1).optional(),
1785
+ /**
1786
+ * The `around` page of `unreadCursor`, when the request asks for it. A
1787
+ * reader who opens at the read position needs no second request.
1788
+ */
1789
+ unreadPage: conversationEventPageSchema.optional(),
1790
+ forkedFromConversationId: z.string().optional(),
1791
+ /** Title of the fork source, when the viewer can open it. */
1792
+ forkedFromTitle: z.string().optional(),
1793
+ forks: z.array(z.string()).optional(),
1794
+ /** People named in `summary`, resolved at read time. */
1795
+ summaryMentions: z.array(actorIdentitySchema).optional(),
1796
+ modelUsage: z.array(conversationModelUsageSchema).optional(),
1797
+ /**
1798
+ * Each person who wrote in the Conversation, by each of their Identity
1799
+ * ids. Messages and pending messages name their author with
1800
+ * `actorIdentityId`.
1801
+ */
1802
+ authors: z.record(z.string(), actorIdentitySchema).optional(),
1803
+ events: z.array(conversationReportEventSchema),
1804
+ /**
1805
+ * Events hold only the events after the request's `after` cursor. The
1806
+ * report omits `previousCursor` and `unreadCursor`: the reader keeps its
1807
+ * own.
1808
+ */
1809
+ appended: z.literal(true).optional(),
1810
+ /**
1811
+ * Pass as `after` on the next detail read to get only newer events.
1812
+ * Absent after a purge.
1813
+ */
1814
+ appendCursor: z.string().min(1).optional(),
1815
+ eventHistory: conversationEventHistorySchema,
1816
+ previousCursor: z.string().min(1).optional(),
1817
+ generatedAt: z.string(),
1818
+ sentryConversationUrl: z.string().optional(),
1819
+ sourceTask: conversationSourceTaskSchema.optional()
1820
+ }).strict().superRefine(validateConversationEvents);
875
1821
  // src/api/schema/automation.ts
876
1822
  const automationDestinationSchema = z.object({
877
1823
  channelId: z.string().min(1),
@@ -1221,6 +2167,23 @@ const automationEventCatalogSchema = z.array(z.object({
1221
2167
  }).strict());
1222
2168
  const automationScheduleIntentSchema = scheduleIntentSchema;
1223
2169
  const automationSchedulePreviewSchema = scheduledAutomationSchema.pick({ schedule: true }).extend({ nextRunAtMs: z.number() }).strict();
2170
+ // src/api/schema/response.ts
2171
+ /** Stable error body returned by Junior-owned REST endpoints. */
2172
+ const apiErrorSchema = z.object({ error: z.string().min(1) }).strict();
2173
+ /**
2174
+ * Carries a content token in both directions. A custom header, not `ETag` /
2175
+ * `If-None-Match`: the Vercel CDN removes `If-None-Match` before it calls the
2176
+ * function, with every `Cache-Control` value, and no setting stops this. The
2177
+ * CDN then answers a match with a 304 only after the function built the full
2178
+ * response, so the read is not saved and the 304 does not show in app
2179
+ * telemetry. A probe deployment confirmed this for `private, no-cache`,
2180
+ * `no-cache`, `private, no-store`, `private, max-age=0, must-revalidate`, and
2181
+ * no header. See
2182
+ * https://vercel.com/docs/manage-cdn-usage#optimizing-fast-origin-transfer.
2183
+ * A read that sends the token of the copy it holds gets an empty 304 while
2184
+ * the content is unchanged.
2185
+ */
2186
+ const CONTENT_VERSION_HEADER = "x-junior-content-version";
1224
2187
  // src/chat/notifications/schedule.ts
1225
2188
  /**
1226
2189
  * Notification hours for one user.
@@ -1309,4 +2272,88 @@ function isWithinNotificationSchedule(schedule, timezone, nowMs) {
1309
2272
  if (minutes < end) return schedule.days.includes((weekday + 6) % 7);
1310
2273
  return false;
1311
2274
  }
1312
- export { formatUserInputAnswer as $, automationContextToolSchema as A, toolScheduleIntentSchema as B, automationUpdateSchema as C, automationVersionSchema as D, automationVersionParamsSchema as E, scheduledAutomationSchema as F, isValidTimeZone as G, getFirstRunAtMs as H, scheduledRunSchema as I, reviewItemRequestSchema as J, eventAutomationSchema as K, ScheduleIntentError as L, automationTitleSchema as M, taskOutcomeInputSchema as N, eventAutomationSummarySchema as O, SCHEDULED_AUTOMATION_SYSTEM_ACTOR as P, buttonUserInputField as Q, compileScheduleIntent as R, automationSummarySchema as S, automationVersionListSchema as T, getNextRunAtMs as U, weekdaySchema as V, getZonedDateTimeParts as W, USER_INPUT_NOTE as X, USER_INPUT_LIMITS as Y, answeredChoices as Z, automationRunListSchema as _, automationEditSchema as a, automationTaskDescription as at, automationScheduleIntentSchema as b, automationExecutionSchema as c, automationLifecycleSchema as d, isEmptyUserInputAnswer as et, automationListItemSchema as f, automationParamsSchema as g, automationListSchema as h, automationEditErrorSchema as i, automationTaskColumns as it, automationInstructionToolSchema as j, scheduledAutomationSummarySchema as k, automationExecutionStatusDaySchema as l, automationListQuerySchema as m, isWithinNotificationSchedule as n, userInputRequestSchema as nt, automationEventCatalogSchema as o, automationTaskSchema as ot, automationListPageSchema as p, eventAutomationTriggerSchema as q, notificationScheduleSchema as r, automationSkillNameSchema as rt, automationExecutionListSchema as s, automationTaskText as st, DEFAULT_NOTIFICATION_SCHEDULE as t, normalizeUserInputAnswer as tt, automationExecutionStatusSchema as u, automationRunSchema as v, automationVersionActivateSchema as w, automationSchedulePreviewSchema as x, automationRunWindowsSchema as y, scheduleIntentFromTool as z };
2275
+ // src/chat/attachments/media.ts
2276
+ const INPUT_IMAGE_TYPES = [
2277
+ "image/png",
2278
+ "image/jpeg",
2279
+ "image/gif",
2280
+ "image/webp"
2281
+ ];
2282
+ /** Video types that browsers play in a `<video>` element. */
2283
+ const INLINE_VIDEO_TYPES = ["video/mp4", "video/webm"];
2284
+ /** Leading bytes of each accepted image type. `null` matches any byte. */
2285
+ const IMAGE_SIGNATURES = [
2286
+ {
2287
+ mediaType: "image/png",
2288
+ bytes: [
2289
+ 137,
2290
+ 80,
2291
+ 78,
2292
+ 71,
2293
+ 13,
2294
+ 10,
2295
+ 26,
2296
+ 10
2297
+ ]
2298
+ },
2299
+ {
2300
+ mediaType: "image/jpeg",
2301
+ bytes: [
2302
+ 255,
2303
+ 216,
2304
+ 255
2305
+ ]
2306
+ },
2307
+ {
2308
+ mediaType: "image/gif",
2309
+ bytes: [
2310
+ 71,
2311
+ 73,
2312
+ 70,
2313
+ 56,
2314
+ 55,
2315
+ 97
2316
+ ]
2317
+ },
2318
+ {
2319
+ mediaType: "image/gif",
2320
+ bytes: [
2321
+ 71,
2322
+ 73,
2323
+ 70,
2324
+ 56,
2325
+ 57,
2326
+ 97
2327
+ ]
2328
+ },
2329
+ {
2330
+ mediaType: "image/webp",
2331
+ bytes: [
2332
+ 82,
2333
+ 73,
2334
+ 70,
2335
+ 70,
2336
+ null,
2337
+ null,
2338
+ null,
2339
+ null,
2340
+ 87,
2341
+ 69,
2342
+ 66,
2343
+ 80
2344
+ ]
2345
+ }
2346
+ ];
2347
+ /**
2348
+ * Detect an accepted image type from file bytes. Use this instead of a file
2349
+ * name or declared content type, which can be wrong.
2350
+ */
2351
+ function detectImageMediaType(data) {
2352
+ return IMAGE_SIGNATURES.find(({ bytes }) => data.length >= bytes.length && bytes.every((byte, index) => byte === null || data[index] === byte))?.mediaType;
2353
+ }
2354
+ /** Report whether a media type is a raster image accepted by vision models. */
2355
+ function isVisionImageMediaType(mediaType) {
2356
+ const normalized = mediaType.split(";", 1)[0]?.trim().toLowerCase();
2357
+ return normalized ? INPUT_IMAGE_TYPES.some((type) => type === normalized) : false;
2358
+ }
2359
+ export { conversationReportStatusSchema as $, formatUserInputAnswer as $t, automationVersionActivateSchema as A, automationContextToolSchema as At, conversationActivityPreviewSchema as B, toolScheduleIntentSchema as Bt, automationRunListSchema as C, removedCardSchema as Ct, automationSchedulePreviewSchema as D, inputFileSchema as Dt, automationScheduleIntentSchema as E, MAX_INPUT_ATTACHMENTS as Et, scheduledAutomationSummarySchema as F, scheduledAutomationSchema as Ft, conversationDetailReportSchema as G, isValidTimeZone as Gt, conversationAttachmentQuerySchema as H, getFirstRunAtMs as Ht, CONVERSATION_DETAIL_VERSION_HEADER as I, scheduledRunSchema as It, conversationEventsQuerySchema as J, inboxItemRequestSchema as Jt, conversationEventHistorySchema as K, eventAutomationSchema as Kt, CONVERSATION_VERSION_HEADER as L, ScheduleIntentError as Lt, automationVersionParamsSchema as M, automationTitleSchema as Mt, automationVersionSchema as N, taskOutcomeInputSchema as Nt, automationSummarySchema as O, messageAttachmentSchema as Ot, eventAutomationSummarySchema as P, SCHEDULED_AUTOMATION_SYSTEM_ACTOR as Pt, conversationReportMessageEventSchema as Q, buttonUserInputField as Qt, acceptedConversationMessageSchema as R, compileScheduleIntent as Rt, automationParamsSchema as S, readMessageCardRefs as St, automationRunWindowsSchema as T, MAX_ATTACHMENT_BYTES as Tt, conversationAuxiliaryCostsSchema as U, getNextRunAtMs as Ut, conversationAttachmentParamsSchema as V, weekdaySchema as Vt, conversationDetailQuerySchema as W, getZonedDateTimeParts as Wt, conversationReportEventDataSchema as X, USER_INPUT_NOTE as Xt, conversationParamsSchema as Y, USER_INPUT_LIMITS as Yt, conversationReportEventSchema as Z, answeredChoices as Zt, automationLifecycleSchema as _, conversationReadPositionSchema as _t, DEFAULT_NOTIFICATION_SCHEDULE as a, automationTaskDescription as an, idempotencyKeySchema as at, automationListQuerySchema as b, messageCardRef as bt, CONTENT_VERSION_HEADER as c, AGENT_TYPES as ct, automationEditSchema as d, formatAgentTypes as dt, isEmptyUserInputAnswer as en, conversationSummaryReportSchema as et, automationEventCatalogSchema as f, conversationTreeStateSchema as ft, automationExecutionStatusSchema as g, renameConversationResponseSchema as gt, automationExecutionStatusDaySchema as h, renameConversationBodySchema as ht, isVisionImageMediaType as i, automationTaskColumns as in, createConversationMessageBodySchema as it, automationVersionListSchema as j, automationInstructionToolSchema as jt, automationUpdateSchema as k, readMessageAttachments as kt, apiErrorSchema as l, agentTypeInstructions as lt, automationExecutionSchema as m, conversationTitleSchema as mt, INPUT_IMAGE_TYPES as n, userInputRequestSchema as nn, conversationUsageSchema as nt, isWithinNotificationSchedule as o, automationTaskSchema as on, activityPreviewText as ot, automationExecutionListSchema as p, CONVERSATION_TITLE_MAX_LENGTH as pt, conversationEventPageSchema as q, eventAutomationTriggerSchema as qt, detectImageMediaType as r, automationSkillNameSchema as rn, createConversationBodySchema as rt, notificationScheduleSchema as s, automationTaskText as sn, conversationChildAgentTotalsSchema as st, INLINE_VIDEO_TYPES as t, normalizeUserInputAnswer as tn, conversationSurfaceSchema as tt, automationEditErrorSchema as u, agentTypeSchema as ut, automationListItemSchema as v, inboxItemChangeRecordSchema as vt, automationRunSchema as w, resolveMessageCards as wt, automationListSchema as x, messageCardText as xt, automationListPageSchema as y, annotationCard as yt, actorIdentitySchema as z, scheduleIntentFromTool as zt };