@sentry/junior 0.316.0 → 0.318.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 (124) hide show
  1. package/dist/{admin-QYiDMnsu.js → admin-UOHix_5P.js} +1 -1
  2. package/dist/{agent-runner-Cr5Fhjf-.js → agent-runner-DeYymwh2.js} +13494 -13135
  3. package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
  4. package/dist/{agent-update-delivery-BY13DPSD.js → agent-update-delivery-DH8bx7jU.js} +5 -5
  5. package/dist/api/schema.d.ts +600 -130
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.js +228 -214
  8. package/dist/{app-BhvzRD__.d.ts → app-DKAOuaoC.d.ts} +33 -18
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +193 -177
  11. package/dist/{thread-context-fiMNylbg.js → auth-pause-state-f9hJM_zO.js} +6 -59
  12. package/dist/catalog-runtime-BfdAnztW.js +6 -0
  13. package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
  14. package/dist/{adapter-context-Bref7aPI.js → channel-access-A0de5lRv.js} +2 -42
  15. package/dist/{chat-core-engine-3dtlMku3.js → chat-core-engine-D3Wd7f5n.js} +6 -5
  16. package/dist/{child-message--2G3Ft26.js → child-message-peFWLcCZ.js} +2 -6
  17. package/dist/cli/chat.js +38 -30
  18. package/dist/cli/check.js +5 -5
  19. package/dist/cli/main.js +2 -2
  20. package/dist/cli/plugins.js +5 -4
  21. package/dist/cli/snapshot-create.js +4 -2
  22. package/dist/cli/upgrade.js +5 -3
  23. package/dist/context-BKF_5zzI.js +1833 -0
  24. package/dist/{continue-in-slack-DbQUFe_F.js → continue-in-slack-YxwMQVeR.js} +3 -3
  25. package/dist/{conversation-feed-B84pMjHo.js → conversation-feed-Cj7IuBtM.js} +3 -3
  26. package/dist/{proxy-path-BTmXDjfx.js → conversation-privacy-Cr_dNW1p.js} +2 -16
  27. package/dist/{conversation-turn-DzEpTIaf.js → conversation-turn-Bru4w_FD.js} +196 -80
  28. package/dist/{create-DUJBXr6E.js → create-Btl1y1rq.js} +12 -11
  29. package/dist/{credential-sync-JH_K9Adg.js → credential-sync-DTarZ63K.js} +20 -15
  30. package/dist/{db-DhzvUY23.js → db-of6e3sGt.js} +20724 -27256
  31. package/dist/{deployment-BhvrhQeh.js → deployment-C0qXa0FD.js} +17 -15
  32. package/dist/{engine-context-C9Nal48K.js → engine-context-C_QL_bMQ.js} +304 -56
  33. package/dist/{html-B_12WjKT.js → html-9_pS9SjY.js} +6 -2
  34. package/dist/instrumentation.js +15 -7
  35. package/dist/{job-runner-DO8nslyY.js → job-runner-B2XEvpif.js} +392 -26
  36. package/dist/{lineage-D3AZAJVe.js → lineage-nh4z9iQN.js} +1 -1
  37. package/dist/{list-B0zsb5Cp.js → list-HRP3TIRl.js} +238 -550
  38. package/dist/{logging-B8KEJegM.js → logging-BnOG0qz2.js} +4 -50
  39. package/dist/{session-stop-DponjDUZ.js → mailbox-turn-Byrry9o1.js} +4807 -7102
  40. package/dist/{list-mkB_GU8R.js → markers-CTTtJqYn.js} +171 -124
  41. package/dist/{message-B5fKDYzz.js → message-BRUuLgrY.js} +13 -24
  42. package/dist/{model-input-CuMWy37l.js → model-input-CFC62mf-.js} +3 -3
  43. package/dist/nitro.d.ts +1 -1
  44. package/dist/nitro.js +21 -7
  45. package/dist/{oauth-callback-server-B3Vvlydo.js → oauth-callback-server-CjnnUr4o.js} +2 -2
  46. package/dist/{oauth-relay-6ERrGPbA.js → oauth-relay-BvHFH0fV.js} +2 -2
  47. package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
  48. package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
  49. package/dist/profile-iHw1uu32.js +4657 -0
  50. package/dist/{transcript-CCi7323k.js → prompt-DEkStuxG.js} +92 -98
  51. package/dist/proxy-path-BHYoKZdq.js +15 -0
  52. package/dist/registry-Cl7Labpe.js +3279 -0
  53. package/dist/reports-C1d9azyV.js +195 -0
  54. package/dist/{resolve-D5JVvv6A.js → resolve-DC6zBuDV.js} +9 -29
  55. package/dist/{result-CS_7mo8a.js → result-DxewDuXb.js} +27 -118
  56. package/dist/run-conversation-Cz2ubZK-.js +337 -0
  57. package/dist/{runner-BzAES5W3.js → runner-99YxVN_r.js} +10 -18
  58. package/dist/{sandbox-egress-signals-Dwhk2Q5F.js → sandbox-egress-signals-CgoX5CTI.js} +1 -1
  59. package/dist/{schema-z5-wA6N4.js → schema-BTojNBr5.js} +48 -86
  60. package/dist/sender-actors-77zTQbSG.js +84 -0
  61. package/dist/{service-account-D6AsAtc1.js → service-account-YDCPSByj.js} +3 -1
  62. package/dist/{skills-DgJ9GBPR.js → skills-CleC0Hze.js} +6 -5
  63. package/dist/{slack-conversation-unfurl-Dq71EkhM.js → slack-conversation-unfurl-BNQLC12R.js} +7 -6
  64. package/dist/{spawn-BJWpdwhQ.js → spawn-DuZfodPa.js} +5 -5
  65. package/dist/{system-prompt-table-iIgpmslr.js → system-prompt-table-Ci6Ck4gk.js} +88 -69
  66. package/dist/{task-runner-BJae4JwE.js → task-runner-BJ9Up3bG.js} +30 -53
  67. package/dist/topics-BoCkoPJJ.js +21 -0
  68. package/dist/turn-membership-VT7XZh-L.js +856 -0
  69. package/dist/{turn-wake-BjDW7x-5.js → turn-wake-C7HeLHAM.js} +3 -4
  70. package/dist/{media-BebquhET.js → types-DCzTAA63.js} +629 -593
  71. package/dist/user-customization-CvfuY9Eo.js +93 -0
  72. package/dist/users-Cb9c1k9q.js +181 -0
  73. package/dist/{validation-D5WmmmhX.js → validation-BiUmWPhy.js} +1 -1
  74. package/dist/{version-CBQoanXb.js → version-VEXiEcZu.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{worker-Cyb4kF17.js → worker-ChWYQdhm.js} +5 -4
  77. package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
  78. package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
  79. package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
  80. package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
  81. package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
  82. package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
  83. package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
  84. package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
  85. package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
  86. package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
  87. package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
  88. package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
  89. package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
  90. package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
  91. package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
  92. package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
  93. package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
  94. package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
  95. package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
  96. package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
  97. package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
  98. package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
  99. package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
  100. package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
  101. package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
  102. package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
  103. package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
  104. package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
  105. package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
  106. package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
  107. package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
  108. package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
  109. package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
  110. package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
  111. package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
  112. package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
  113. package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
  114. package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
  115. package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
  116. package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
  117. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  118. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  119. package/package.json +5 -5
  120. package/dist/people-CUtFApfL.js +0 -81
  121. package/dist/start-conversation-B-LIqqNi.js +0 -162
  122. package/dist/turn-session-routing-D15orfwy.js +0 -1309
  123. package/dist/user-customization-B27StpVQ.js +0 -9
  124. package/dist/web-message-id-C6P83ans.js +0 -10
@@ -1,5 +1,24 @@
1
1
  import * as z from "zod";
2
2
  import { actorSchema, actorUserIdSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, conversationSidebarAnnotationSchema, destinationVisibilitySchema, eventMatchFieldsSchema, eventMatchSchema, eventReachSchema, eventTypeSchema, objectFactFields, objectTypeSchema, pluginEventTypeSchema, slackDestinationSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
3
+ // src/usage-schema.ts
4
+ const usageCostSchema = z.object({
5
+ input: z.number().finite().nonnegative().optional(),
6
+ output: z.number().finite().nonnegative().optional(),
7
+ cacheRead: z.number().finite().nonnegative().optional(),
8
+ cacheWrite: z.number().finite().nonnegative().optional(),
9
+ total: z.number().finite().nonnegative().optional()
10
+ }).strict();
11
+ const usageSchema = z.object({
12
+ inputTokens: z.number().int().nonnegative().optional(),
13
+ outputTokens: z.number().int().nonnegative().optional(),
14
+ cachedInputTokens: z.number().int().nonnegative().optional(),
15
+ cacheCreationTokens: z.number().int().nonnegative().optional(),
16
+ reasoningTokens: z.number().int().nonnegative().optional(),
17
+ totalTokens: z.number().int().nonnegative().optional(),
18
+ cost: usageCostSchema.optional()
19
+ }).strict();
20
+ /** The token counts of a usage record, without its cost. */
21
+ const usageTokensSchema = usageSchema.omit({ cost: true });
3
22
  // src/chat/gateway-providers/rule.ts
4
23
  /**
5
24
  * The routing rule of the "Enabled providers" admin setting.
@@ -19,55 +38,11 @@ function gatewayOnlyProviders(enabled, served) {
19
38
  const only = served.filter((provider) => enabled.includes(provider));
20
39
  return only.length > 0 && only.length < served.length ? only : void 0;
21
40
  }
22
- // src/chat/automations/task.ts
23
- /**
24
- * The work of an Automation run. An Automation runs either a written
25
- * instruction or a skill. A skill can have context: what the Automation
26
- * needs beyond the skill.
27
- */
28
- /** A skill name, in the form that skill frontmatter allows. */
29
- const automationSkillNameSchema = z.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use a skill name, such as tpm.");
30
- /** Text of an instruction or a context, trimmed and not empty. */
31
- const automationTaskTextSchema = z.string().trim().min(1, "Write at least one word.").max(4e3);
32
- /** Validate the stored task of either Automation kind. */
33
- const automationTaskSchema = z.discriminatedUnion("kind", [z.object({
34
- kind: z.literal("instruction"),
35
- instruction: automationTaskTextSchema
36
- }).strict(), z.object({
37
- kind: z.literal("skill"),
38
- skill: automationSkillNameSchema,
39
- /** Absent when the skill needs nothing more. */
40
- context: automationTaskTextSchema.optional()
41
- }).strict()]);
42
- /** Return the written text of a task: its instruction or its context. */
43
- function automationTaskText(task) {
44
- return task.kind === "instruction" ? task.instruction : task.context;
45
- }
46
- /**
47
- * Describe the work in one plain text for title fallback, title generation,
48
- * and cards, so a skill-mode Automation shows its skill. Do not store it.
49
- */
50
- function automationTaskDescription(task) {
51
- if (task.kind === "instruction") return task.instruction;
52
- return task.context ? `Run the ${task.skill} skill. ${task.context}` : `Run the ${task.skill} skill.`;
53
- }
54
- /** Return the `instruction` and `skill` columns of a task. One is null. */
55
- function automationTaskColumns(task) {
56
- return task.kind === "instruction" ? {
57
- instruction: task.instruction,
58
- skill: null
59
- } : {
60
- instruction: null,
61
- skill: task.skill
62
- };
63
- }
64
- // src/chat/agent-invocations/result-event-type.ts
65
- /** Event namespace of the messages between a parent and its child agents. */
66
- const AGENT_INVOCATION_EVENT_NAMESPACE = "junior";
67
- const AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
68
- /** True when an Event type names an agent invocation result. */
69
- function isAgentInvocationResultEventType(eventType) {
70
- return eventType.startsWith(AGENT_INVOCATION_RESULT_EVENT_TYPE_PREFIX);
41
+ // src/chat/child-agents/result-event-type.ts
42
+ const LEGACY_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
43
+ /** True when an Event type names a child result that an earlier release wrote. */
44
+ function isLegacyResultEventType(eventType) {
45
+ return eventType.startsWith(LEGACY_RESULT_EVENT_TYPE_PREFIX);
71
46
  }
72
47
  /**
73
48
  * Event type of an agent update: what a Conversation reports when a Turn
@@ -82,285 +57,66 @@ function isAgentUpdateEventType(eventType) {
82
57
  }
83
58
  /** Event type of a message that a child agent sends to its parent. */
84
59
  const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
85
- // src/chat/inbox-items/user-input-request.ts
86
- const USER_INPUT_LIMITS = {
87
- maxButtonOptions: 5,
88
- maxDescriptionChars: 200,
89
- maxFields: 4,
90
- maxLabelChars: 75,
91
- maxOptions: 10,
92
- maxTextChars: 3e3,
93
- maxQuestionChars: 3e3,
94
- minOptions: 2
95
- };
96
- const labelSchema = z.string().trim().min(1).max(USER_INPUT_LIMITS.maxLabelChars);
97
- const descriptionSchema = z.string().trim().min(1).max(USER_INPUT_LIMITS.maxDescriptionChars).optional();
98
- const optionSchema = z.object({
99
- label: labelSchema.describe("Short choice text, such as `Accept` or `Decline`. The answer uses this exact text."),
100
- description: descriptionSchema.describe("Optional short note about what this choice does."),
101
- recommended: z.boolean().optional().describe("Set true on the choice that you recommend, put that choice first, and say why in its description. A `choice` field can recommend one option.")
102
- });
103
- const fieldBase = {
104
- id: z.string().regex(/^[a-z][a-z0-9_]{0,31}$/).describe("Stable key for this field, such as `approach`."),
105
- label: labelSchema.describe("Short field name, such as `Approach`."),
106
- description: descriptionSchema.describe("Optional short help text for this field.")
107
- };
108
- function optionsSchema(minOptions) {
109
- return z.array(optionSchema).min(minOptions).max(USER_INPUT_LIMITS.maxOptions).describe("Choices in display order.");
110
- }
111
- function requestSchema(minOptions) {
112
- const userInputFieldSchema = z.discriminatedUnion("kind", [
113
- z.object({
114
- ...fieldBase,
115
- kind: z.literal("choice").describe("The person picks one option."),
116
- options: optionsSchema(minOptions)
117
- }),
118
- z.object({
119
- ...fieldBase,
120
- kind: z.literal("multi_choice").describe("The person picks any number of options."),
121
- options: optionsSchema(minOptions)
122
- }),
123
- z.object({
124
- ...fieldBase,
125
- kind: z.literal("text").describe("The person types a short answer.")
126
- })
127
- ]);
128
- return z.object({
129
- question: z.string().trim().min(1).max(USER_INPUT_LIMITS.maxQuestionChars).describe("The question, in markdown. Include the facts the person needs to decide."),
130
- fields: z.array(userInputFieldSchema).min(1).max(USER_INPUT_LIMITS.maxFields).describe("What to ask, in display order. Use one `choice` field for a simple decision.")
131
- }).superRefine((request, context) => {
132
- const ids = /* @__PURE__ */ new Set();
133
- for (const field of request.fields) {
134
- if (ids.has(field.id)) context.addIssue({
135
- code: "custom",
136
- message: "Each field needs a different id."
137
- });
138
- ids.add(field.id);
139
- if (field.kind === "text") continue;
140
- const labels = field.options.map((option) => option.label.toLowerCase());
141
- if (new Set(labels).size !== labels.length) context.addIssue({
142
- code: "custom",
143
- message: "Each choice of a field needs a different label."
144
- });
145
- if (field.kind === "choice" && field.options.filter((option) => option.recommended).length > 1) context.addIssue({
146
- code: "custom",
147
- message: "A `choice` field can recommend only one option."
148
- });
149
- }
150
- });
151
- }
152
- /** A request that an agent writes. Each choice field has two options or more. */
153
- const userInputRequestSchema = requestSchema(USER_INPUT_LIMITS.minOptions);
154
- /**
155
- * A saved request. A plugin item can have one choice, such as Resume, so a
156
- * saved choice field can have one option. Agents still need two.
157
- */
158
- const savedUserInputRequestSchema = requestSchema(1);
159
- /**
160
- * Label and help text of the free-text input that every form adds after the
161
- * fields. The text goes with the picked answers and does not replace them, so
162
- * every surface says that in the same words.
163
- */
164
- const USER_INPUT_NOTE = {
165
- label: "Anything else?",
166
- description: "Optional. This note is sent together with your answers above."
167
- };
168
- /**
169
- * Return the single choice field of a request that a surface can show as
170
- * one row of buttons, where one click is the whole answer.
171
- */
172
- function buttonUserInputField(request) {
173
- const [field, ...rest] = request.fields;
174
- if (rest.length || field?.kind !== "choice") return void 0;
175
- return field.options.length <= USER_INPUT_LIMITS.maxButtonOptions ? field : void 0;
60
+ /** Event type of a message from another top-level agent. */
61
+ const TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE = "agent.top_level_message";
62
+ /** True when an Event type names a message that another agent sent. */
63
+ function isAgentMessageEventType(eventType) {
64
+ return eventType === "agent.message" || eventType === "agent.top_level_message";
176
65
  }
66
+ // src/api/schema/response.ts
67
+ /** Stable error body returned by Junior-owned REST endpoints. */
68
+ const apiErrorSchema = z.object({ error: z.string().min(1) }).strict();
177
69
  /**
178
- * Keep only answer values that match the request: known field ids, known
179
- * option labels, one value for a `choice` field, and trimmed text.
70
+ * Carries a content token in both directions. A custom header, not `ETag` /
71
+ * `If-None-Match`: the Vercel CDN removes `If-None-Match` before it calls the
72
+ * function, with every `Cache-Control` value, and no setting stops this. The
73
+ * CDN then answers a match with a 304 only after the function built the full
74
+ * response, so the read is not saved and the 304 does not show in app
75
+ * telemetry. A probe deployment confirmed this for `private, no-cache`,
76
+ * `no-cache`, `private, no-store`, `private, max-age=0, must-revalidate`, and
77
+ * no header. See
78
+ * https://vercel.com/docs/manage-cdn-usage#optimizing-fast-origin-transfer.
79
+ * A read that sends the token of the copy it holds gets an empty 304 while
80
+ * the content is unchanged.
180
81
  */
181
- function normalizeUserInputAnswer(request, answer) {
182
- const values = {};
183
- for (const field of request.fields) {
184
- const raw = (answer.values[field.id] ?? []).map((value) => value.trim()).filter(Boolean);
185
- if (field.kind === "text") {
186
- const text = raw.join("\n").slice(0, USER_INPUT_LIMITS.maxTextChars);
187
- if (text) values[field.id] = [text];
188
- continue;
189
- }
190
- const picked = field.options.map((option) => option.label).filter((label) => raw.includes(label));
191
- const kept = field.kind === "choice" ? picked.slice(0, 1) : picked;
192
- if (kept.length) values[field.id] = kept;
193
- }
194
- const other = answer.other?.trim().slice(0, USER_INPUT_LIMITS.maxTextChars);
195
- return {
196
- requestId: answer.requestId,
197
- values,
198
- ...other ? { other } : void 0
199
- };
82
+ const CONTENT_VERSION_HEADER = "x-junior-content-version";
83
+ // src/chat/scheduled-automations/cadence.ts
84
+ const FORMATTERS = /* @__PURE__ */ new Map();
85
+ function getFormatter(timezone) {
86
+ const existing = FORMATTERS.get(timezone);
87
+ if (existing) return existing;
88
+ const formatter = new Intl.DateTimeFormat("en-US", {
89
+ timeZone: timezone,
90
+ hour12: false,
91
+ year: "numeric",
92
+ month: "2-digit",
93
+ day: "2-digit",
94
+ hour: "2-digit",
95
+ minute: "2-digit",
96
+ second: "2-digit"
97
+ });
98
+ FORMATTERS.set(timezone, formatter);
99
+ return formatter;
200
100
  }
201
- /**
202
- * Return the option labels that an answer picked, in field order. Text
203
- * fields and the note pick no option.
204
- */
205
- function answeredChoices(request, answer) {
206
- const { values } = normalizeUserInputAnswer(request, answer);
207
- return request.fields.flatMap((field) => field.kind === "text" ? [] : values[field.id] ?? []);
101
+ function normalizeHour(hour) {
102
+ return hour === 24 ? 0 : hour;
208
103
  }
209
- /** Return true when an answer has no value and no free text. */
210
- function isEmptyUserInputAnswer(answer) {
211
- return !answer.other && Object.keys(answer.values).length === 0;
104
+ function getLocalDateWeekday(date) {
105
+ return new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay();
212
106
  }
213
- function answerLine(text) {
214
- return text.split("\n").map((line) => line.trim()).filter(Boolean).join("\n");
107
+ function getWeekStart(date) {
108
+ return addDays(date, -((getLocalDateWeekday(date) + 6) % 7));
215
109
  }
216
110
  /**
217
- * Write the fields of an answer, one `Label (field_id): value` line each.
218
- * Slack, the web dashboard, and the prompt all use this text, so the model
219
- * reads one format.
111
+ * Check that a value is an IANA time zone that this runtime knows. This module
112
+ * has no runtime imports, so the dashboard client bundle can use it.
220
113
  */
221
- function formatUserInputAnswer(request, answer) {
222
- const normalized = normalizeUserInputAnswer(request, answer);
223
- const lines = [];
224
- for (const field of request.fields) {
225
- const values = normalized.values[field.id];
226
- const value = values?.length ? values.join(", ") : "(no answer)";
227
- lines.push(answerLine(`${field.label} (${field.id}): ${value}`));
228
- }
229
- if (normalized.other) lines.push(answerLine(`Other: ${normalized.other}`));
230
- return lines.join("\n");
231
- }
232
- // src/chat/inbox-items/evidence.ts
233
- /**
234
- * One source that an agent cites for an Inbox item: a link or a
235
- * Conversation, with a short label and an optional one-line note. A link
236
- * points outside Junior; a Conversation reference points to work in Junior.
237
- * The question stores the list, and the dashboard shows it beside the
238
- * answer choices.
239
- */
240
- const inboxItemEvidenceSchema = z.object({
241
- conversationId: z.string().min(1).max(500).optional(),
242
- label: z.string().min(1).max(120),
243
- note: z.string().min(1).max(200).optional(),
244
- url: z.string().min(1).max(2e3).optional()
245
- }).strict().refine((entry) => entry.url === void 0 !== (entry.conversationId === void 0), "Evidence has a `url` or a `conversationId`, not both.");
246
- /**
247
- * The question of an Inbox item with the evidence for its answer. Evidence
248
- * is part of the question, so it is stored in the `request` column.
249
- */
250
- const inboxItemRequestSchema = savedUserInputRequestSchema.safeExtend({ evidence: z.array(inboxItemEvidenceSchema).optional() });
251
- /** Validate the persisted Slack creator identity for an event automation. */
252
- const eventAutomationPrincipalSchema = z.object({
253
- slackUserId: actorUserIdSchema,
254
- fullName: z.string().optional(),
255
- userName: z.string().optional()
256
- }).strict();
257
- /**
258
- * Validate one persisted event-automation selector and its presentation
259
- * metadata. A trigger names one resource with a resource type and an
260
- * identifier, or it names neither. With neither, it runs for every resource
261
- * of the namespace that its filters match.
262
- */
263
- const eventAutomationTriggerSchema = z.object({
264
- events: z.array(eventTypeSchema).min(1),
265
- label: z.string().min(1),
266
- match: eventMatchSchema.optional(),
267
- namespace: z.string().min(1),
268
- identifier: z.string().min(1).max(300).optional(),
269
- resourceType: z.string().min(1).optional()
270
- }).strict().refine((trigger) => trigger.identifier === void 0 === (trigger.resourceType === void 0), {
271
- message: "Set both a resource type and an identifier, or leave out both to run for every resource.",
272
- path: ["identifier"]
273
- });
274
- /** Event automations target a Slack channel or DM, never a message thread. */
275
- const eventAutomationDestinationSchema = slackDestinationSchema.omit({ threadTs: true });
276
- const eventAutomationOutcomeSchema = taskOutcomeSchema.extend({ destination: eventAutomationDestinationSchema });
277
- /** Validate one persisted event automation. */
278
- const eventAutomationSchema = z.object({
279
- id: z.string().min(1),
280
- createdAtMs: z.number().finite(),
281
- createdBy: eventAutomationPrincipalSchema,
282
- /** Junior identity that created the automation. It decides ownership. */
283
- creatorIdentityId: z.string().min(1),
284
- credentialMode: z.enum(["system", "creator"]),
285
- destination: eventAutomationDestinationSchema,
286
- destinationVisibility: destinationVisibilitySchema,
287
- /** Explicit visible effects after successful work. An empty list is silent. */
288
- outcomes: z.array(eventAutomationOutcomeSchema).max(5),
289
- task: automationTaskSchema,
290
- trigger: eventAutomationTriggerSchema
291
- }).strict();
292
- // src/chat/todos/types.ts
293
- /** Statuses of a To-do. `done` and `dropped` close it. */
294
- const TODO_STATUSES = [
295
- "open",
296
- "in_progress",
297
- "done",
298
- "dropped"
299
- ];
300
- /** Statuses of a To-do that is still work to do. */
301
- const OPEN_TODO_STATUSES = ["open", "in_progress"];
302
- /** Whether a To-do with this status is still work to do. */
303
- function isOpenTodoStatus(status) {
304
- return status === "open" || status === "in_progress";
305
- }
306
- /** Model-facing tool that changes the To-dos. */
307
- const UPDATE_TODOS_TOOL_NAME = "updateTodos";
308
- /** Assignee text for the list's own agent, in tool results and blocks. */
309
- const SELF_TODO_ASSIGNEE = "self";
310
- // src/usage-schema.ts
311
- const usageCostSchema = z.object({
312
- input: z.number().finite().nonnegative().optional(),
313
- output: z.number().finite().nonnegative().optional(),
314
- cacheRead: z.number().finite().nonnegative().optional(),
315
- cacheWrite: z.number().finite().nonnegative().optional(),
316
- total: z.number().finite().nonnegative().optional()
317
- }).strict();
318
- const usageSchema = z.object({
319
- inputTokens: z.number().int().nonnegative().optional(),
320
- outputTokens: z.number().int().nonnegative().optional(),
321
- cachedInputTokens: z.number().int().nonnegative().optional(),
322
- cacheCreationTokens: z.number().int().nonnegative().optional(),
323
- reasoningTokens: z.number().int().nonnegative().optional(),
324
- totalTokens: z.number().int().nonnegative().optional(),
325
- cost: usageCostSchema.optional()
326
- }).strict();
327
- // src/chat/scheduled-automations/cadence.ts
328
- const FORMATTERS = /* @__PURE__ */ new Map();
329
- function getFormatter(timezone) {
330
- const existing = FORMATTERS.get(timezone);
331
- if (existing) return existing;
332
- const formatter = new Intl.DateTimeFormat("en-US", {
333
- timeZone: timezone,
334
- hour12: false,
335
- year: "numeric",
336
- month: "2-digit",
337
- day: "2-digit",
338
- hour: "2-digit",
339
- minute: "2-digit",
340
- second: "2-digit"
341
- });
342
- FORMATTERS.set(timezone, formatter);
343
- return formatter;
344
- }
345
- function normalizeHour(hour) {
346
- return hour === 24 ? 0 : hour;
347
- }
348
- function getLocalDateWeekday(date) {
349
- return new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay();
350
- }
351
- function getWeekStart(date) {
352
- return addDays(date, -((getLocalDateWeekday(date) + 6) % 7));
353
- }
354
- /**
355
- * Check that a value is an IANA time zone that this runtime knows. This module
356
- * has no runtime imports, so the dashboard client bundle can use it.
357
- */
358
- function isValidTimeZone(timezone) {
359
- try {
360
- new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
361
- return true;
362
- } catch {
363
- return false;
114
+ function isValidTimeZone(timezone) {
115
+ try {
116
+ new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
117
+ return true;
118
+ } catch {
119
+ return false;
364
120
  }
365
121
  }
366
122
  /** Resolve a UTC timestamp into calendar parts for a named time zone. */
@@ -578,6 +334,363 @@ function getNextRunAtMs(task, scheduledForMs, afterMs = scheduledForMs) {
578
334
  timezone
579
335
  });
580
336
  }
337
+ // src/chat/notifications/schedule.ts
338
+ /**
339
+ * Notification hours for one user.
340
+ *
341
+ * This module imports only zod and the browser-safe cadence helpers, so the
342
+ * dashboard client bundle can use it.
343
+ */
344
+ const clockTimePattern = /^([01]\d|2[0-3]):[0-5]\d$/;
345
+ /** Saved notification hours. Weekdays use 0 for Sunday, like `Date#getDay`. */
346
+ const notificationScheduleSchema = z.object({
347
+ /**
348
+ * Follow the linked Slack user's notification schedule. The fields below
349
+ * apply only when Junior cannot read it. Absent means on.
350
+ */
351
+ followSlack: z.boolean().optional(),
352
+ /** When false, Junior sends push notifications at any time. */
353
+ workingHoursOnly: z.boolean(),
354
+ days: z.array(z.number().int().min(0).max(6)).max(7).refine((days) => new Set(days).size === days.length, { message: "Days must be unique." }),
355
+ /** Local start time, `HH:MM`. */
356
+ start: z.string().regex(clockTimePattern),
357
+ /** Local end time, `HH:MM`. An end before the start crosses midnight. */
358
+ end: z.string().regex(clockTimePattern),
359
+ /** IANA timezone set by the user. Absent means the profile timezone. */
360
+ timezone: z.string().min(1).max(64).refine(isValidTimeZone, { message: "Unknown timezone." }).optional()
361
+ }).strict().refine((schedule) => schedule.start !== schedule.end, {
362
+ message: "Start and end must differ.",
363
+ path: ["end"]
364
+ });
365
+ /**
366
+ * Default when a user has not saved a schedule: follow Slack, else
367
+ * 09:00–18:00, Mon–Fri.
368
+ */
369
+ const DEFAULT_NOTIFICATION_SCHEDULE = {
370
+ followSlack: true,
371
+ workingHoursOnly: true,
372
+ days: [
373
+ 1,
374
+ 2,
375
+ 3,
376
+ 4,
377
+ 5
378
+ ],
379
+ start: "09:00",
380
+ end: "18:00"
381
+ };
382
+ function clockMinutes(value) {
383
+ const [hours, minutes] = value.split(":").map(Number);
384
+ return hours * 60 + minutes;
385
+ }
386
+ const weekdayIndex = {
387
+ Sun: 0,
388
+ Mon: 1,
389
+ Tue: 2,
390
+ Wed: 3,
391
+ Thu: 4,
392
+ Fri: 5,
393
+ Sat: 6
394
+ };
395
+ function localWeekdayAndMinutes(nowMs, timezone) {
396
+ const parts = new Intl.DateTimeFormat("en-US", {
397
+ hour: "2-digit",
398
+ hourCycle: "h23",
399
+ minute: "2-digit",
400
+ timeZone: timezone,
401
+ weekday: "short"
402
+ }).formatToParts(new Date(nowMs));
403
+ const value = (type) => parts.find((part) => part.type === type)?.value ?? "";
404
+ const weekday = weekdayIndex[value("weekday")];
405
+ if (weekday === void 0) throw new Error(`Could not read the weekday for timezone ${timezone}`);
406
+ return {
407
+ minutes: Number(value("hour")) % 24 * 60 + Number(value("minute")),
408
+ weekday
409
+ };
410
+ }
411
+ /**
412
+ * Return whether a notification may be sent now. A window that crosses
413
+ * midnight belongs to the day on which it starts.
414
+ */
415
+ function isWithinNotificationSchedule(schedule, timezone, nowMs) {
416
+ if (!schedule.workingHoursOnly) return true;
417
+ const { minutes, weekday } = localWeekdayAndMinutes(nowMs, timezone);
418
+ const start = clockMinutes(schedule.start);
419
+ const end = clockMinutes(schedule.end);
420
+ if (start < end) return schedule.days.includes(weekday) && minutes >= start && minutes < end;
421
+ if (minutes >= start) return schedule.days.includes(weekday);
422
+ if (minutes < end) return schedule.days.includes((weekday + 6) % 7);
423
+ return false;
424
+ }
425
+ // src/chat/automations/task.ts
426
+ /**
427
+ * The work of an Automation run. An Automation runs either a written
428
+ * instruction or a skill. A skill can have context: what the Automation
429
+ * needs beyond the skill.
430
+ */
431
+ /** A skill name, in the form that skill frontmatter allows. */
432
+ const automationSkillNameSchema = z.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use a skill name, such as tpm.");
433
+ /** Text of an instruction or a context, trimmed and not empty. */
434
+ const automationTaskTextSchema = z.string().trim().min(1, "Write at least one word.").max(4e3);
435
+ /** Validate the stored task of either Automation kind. */
436
+ const automationTaskSchema = z.discriminatedUnion("kind", [z.object({
437
+ kind: z.literal("instruction"),
438
+ instruction: automationTaskTextSchema
439
+ }).strict(), z.object({
440
+ kind: z.literal("skill"),
441
+ skill: automationSkillNameSchema,
442
+ /** Absent when the skill needs nothing more. */
443
+ context: automationTaskTextSchema.optional()
444
+ }).strict()]);
445
+ /** Return the written text of a task: its instruction or its context. */
446
+ function automationTaskText(task) {
447
+ return task.kind === "instruction" ? task.instruction : task.context;
448
+ }
449
+ /**
450
+ * Describe the work in one plain text for title fallback, title generation,
451
+ * and cards, so a skill-mode Automation shows its skill. Do not store it.
452
+ */
453
+ function automationTaskDescription(task) {
454
+ if (task.kind === "instruction") return task.instruction;
455
+ return task.context ? `Run the ${task.skill} skill. ${task.context}` : `Run the ${task.skill} skill.`;
456
+ }
457
+ /** Return the `instruction` and `skill` columns of a task. One is null. */
458
+ function automationTaskColumns(task) {
459
+ return task.kind === "instruction" ? {
460
+ instruction: task.instruction,
461
+ skill: null
462
+ } : {
463
+ instruction: null,
464
+ skill: task.skill
465
+ };
466
+ }
467
+ // src/chat/inbox-items/user-input-request.ts
468
+ const USER_INPUT_LIMITS = {
469
+ maxButtonOptions: 5,
470
+ maxDescriptionChars: 200,
471
+ maxFields: 4,
472
+ maxLabelChars: 75,
473
+ maxOptions: 10,
474
+ maxTextChars: 3e3,
475
+ maxQuestionChars: 3e3,
476
+ minOptions: 2
477
+ };
478
+ const labelSchema = z.string().trim().min(1).max(USER_INPUT_LIMITS.maxLabelChars);
479
+ const descriptionSchema = z.string().trim().min(1).max(USER_INPUT_LIMITS.maxDescriptionChars).optional();
480
+ const optionSchema = z.object({
481
+ label: labelSchema.describe("Short choice text, such as `Accept` or `Decline`. The answer uses this exact text."),
482
+ description: descriptionSchema.describe("Optional short note about what this choice does."),
483
+ recommended: z.boolean().optional().describe("Set true on the choice that you recommend, put that choice first, and say why in its description. A `choice` field can recommend one option.")
484
+ });
485
+ const fieldBase = {
486
+ id: z.string().regex(/^[a-z][a-z0-9_]{0,31}$/).describe("Stable key for this field, such as `approach`."),
487
+ label: labelSchema.describe("Short field name, such as `Approach`."),
488
+ description: descriptionSchema.describe("Optional short help text for this field.")
489
+ };
490
+ function optionsSchema(minOptions) {
491
+ return z.array(optionSchema).min(minOptions).max(USER_INPUT_LIMITS.maxOptions).describe("Choices in display order.");
492
+ }
493
+ function fieldsSchema(minOptions) {
494
+ const userInputFieldSchema = z.discriminatedUnion("kind", [
495
+ z.object({
496
+ ...fieldBase,
497
+ kind: z.literal("choice").describe("The person picks one option."),
498
+ options: optionsSchema(minOptions)
499
+ }),
500
+ z.object({
501
+ ...fieldBase,
502
+ kind: z.literal("multi_choice").describe("The person picks any number of options."),
503
+ options: optionsSchema(minOptions)
504
+ }),
505
+ z.object({
506
+ ...fieldBase,
507
+ kind: z.literal("text").describe("The person types a short answer.")
508
+ })
509
+ ]);
510
+ return z.array(userInputFieldSchema).min(1).max(USER_INPUT_LIMITS.maxFields).describe("What to ask, in display order. Use one `choice` field for a simple decision.");
511
+ }
512
+ /** The question of a request, in markdown. */
513
+ const userInputQuestionSchema = z.string().trim().min(1).max(USER_INPUT_LIMITS.maxQuestionChars).describe("The question, in markdown. Include the facts the person needs to decide.");
514
+ /** The fields of a request that an agent writes. */
515
+ const userInputFieldsSchema = fieldsSchema(USER_INPUT_LIMITS.minOptions);
516
+ function requestSchema(minOptions) {
517
+ return z.object({
518
+ question: userInputQuestionSchema,
519
+ fields: fieldsSchema(minOptions)
520
+ }).superRefine((request, context) => {
521
+ const ids = /* @__PURE__ */ new Set();
522
+ for (const field of request.fields) {
523
+ if (ids.has(field.id)) context.addIssue({
524
+ code: "custom",
525
+ message: "Each field needs a different id."
526
+ });
527
+ ids.add(field.id);
528
+ if (field.kind === "text") continue;
529
+ const labels = field.options.map((option) => option.label.toLowerCase());
530
+ if (new Set(labels).size !== labels.length) context.addIssue({
531
+ code: "custom",
532
+ message: "Each choice of a field needs a different label."
533
+ });
534
+ if (field.kind === "choice" && field.options.filter((option) => option.recommended).length > 1) context.addIssue({
535
+ code: "custom",
536
+ message: "A `choice` field can recommend only one option."
537
+ });
538
+ }
539
+ });
540
+ }
541
+ /** A request that an agent writes. Each choice field has two options or more. */
542
+ const userInputRequestSchema = requestSchema(USER_INPUT_LIMITS.minOptions);
543
+ /**
544
+ * A saved request. A plugin item can have one choice, such as Resume, so a
545
+ * saved choice field can have one option. Agents still need two.
546
+ */
547
+ const savedUserInputRequestSchema = requestSchema(1);
548
+ /**
549
+ * Label and help text of the free-text input that every form adds after the
550
+ * fields. The text goes with the picked answers and does not replace them, so
551
+ * every surface says that in the same words.
552
+ */
553
+ const USER_INPUT_NOTE = {
554
+ label: "Anything else?",
555
+ description: "Optional. This note is sent together with your answers above."
556
+ };
557
+ /**
558
+ * Return the single choice field of a request that a surface can show as
559
+ * one row of buttons, where one click is the whole answer.
560
+ */
561
+ function buttonUserInputField(request) {
562
+ const [field, ...rest] = request.fields;
563
+ if (rest.length || field?.kind !== "choice") return void 0;
564
+ return field.options.length <= USER_INPUT_LIMITS.maxButtonOptions ? field : void 0;
565
+ }
566
+ /**
567
+ * Keep only answer values that match the request: known field ids, known
568
+ * option labels, one value for a `choice` field, and trimmed text.
569
+ */
570
+ function normalizeUserInputAnswer(request, answer) {
571
+ const values = {};
572
+ for (const field of request.fields) {
573
+ const raw = (answer.values[field.id] ?? []).map((value) => value.trim()).filter(Boolean);
574
+ if (field.kind === "text") {
575
+ const text = raw.join("\n").slice(0, USER_INPUT_LIMITS.maxTextChars);
576
+ if (text) values[field.id] = [text];
577
+ continue;
578
+ }
579
+ const picked = field.options.map((option) => option.label).filter((label) => raw.includes(label));
580
+ const kept = field.kind === "choice" ? picked.slice(0, 1) : picked;
581
+ if (kept.length) values[field.id] = kept;
582
+ }
583
+ const other = answer.other?.trim().slice(0, USER_INPUT_LIMITS.maxTextChars);
584
+ return {
585
+ requestId: answer.requestId,
586
+ values,
587
+ ...other ? { other } : void 0
588
+ };
589
+ }
590
+ /**
591
+ * Return the option labels that an answer picked, in field order. Text
592
+ * fields and the note pick no option.
593
+ */
594
+ function answeredChoices(request, answer) {
595
+ const { values } = normalizeUserInputAnswer(request, answer);
596
+ return request.fields.flatMap((field) => field.kind === "text" ? [] : values[field.id] ?? []);
597
+ }
598
+ /** Return true when an answer has no value and no free text. */
599
+ function isEmptyUserInputAnswer(answer) {
600
+ return !answer.other && Object.keys(answer.values).length === 0;
601
+ }
602
+ function answerLine(text) {
603
+ return text.split("\n").map((line) => line.trim()).filter(Boolean).join("\n");
604
+ }
605
+ /**
606
+ * Write the fields of an answer, one `Label (field_id): value` line each.
607
+ * Slack, the web dashboard, and the prompt all use this text, so the model
608
+ * reads one format.
609
+ */
610
+ function formatUserInputAnswer(request, answer) {
611
+ const normalized = normalizeUserInputAnswer(request, answer);
612
+ const lines = [];
613
+ for (const field of request.fields) {
614
+ const values = normalized.values[field.id];
615
+ const value = values?.length ? values.join(", ") : "(no answer)";
616
+ lines.push(answerLine(`${field.label} (${field.id}): ${value}`));
617
+ }
618
+ if (normalized.other) lines.push(answerLine(`Other: ${normalized.other}`));
619
+ return lines.join("\n");
620
+ }
621
+ // src/chat/inbox-items/request.ts
622
+ /**
623
+ * One related link that an agent adds to an Inbox item: a link or a
624
+ * Conversation, with a short label and an optional one-line note. A link
625
+ * points outside Junior; a Conversation reference points to work in Junior.
626
+ * The question stores the list, and its card shows it beside the answer
627
+ * choices.
628
+ */
629
+ const inboxItemRelatedLinkSchema = z.object({
630
+ conversationId: z.string().min(1).max(500).optional(),
631
+ label: z.string().min(1).max(120),
632
+ note: z.string().min(1).max(200).optional(),
633
+ url: z.string().min(1).max(2e3).optional()
634
+ }).strict().refine((entry) => entry.url === void 0 !== (entry.conversationId === void 0), "A related link has a `url` or a `conversationId`, not both.");
635
+ /**
636
+ * The question of an Inbox item with its related links. The links are part
637
+ * of the question, so they are stored with it in `request`.
638
+ */
639
+ const inboxItemRequestSchema = savedUserInputRequestSchema.safeExtend({ related: z.array(inboxItemRelatedLinkSchema).optional() });
640
+ /**
641
+ * The request of a notice: only the related links that say what it is
642
+ * about, such as a pull request. A notice asks nothing, so it has no
643
+ * question.
644
+ */
645
+ const inboxItemNoticeRequestSchema = z.object({ related: z.array(inboxItemRelatedLinkSchema) }).strict();
646
+ /**
647
+ * Return the question of an item's request. A notice's request holds only
648
+ * related links, so it has none.
649
+ */
650
+ function inboxItemQuestion(request) {
651
+ return request && "question" in request ? request : void 0;
652
+ }
653
+ /** Validate the persisted Slack creator identity for an event automation. */
654
+ const eventAutomationPrincipalSchema = z.object({
655
+ slackUserId: actorUserIdSchema,
656
+ fullName: z.string().optional(),
657
+ userName: z.string().optional()
658
+ }).strict();
659
+ /**
660
+ * Validate one persisted event-automation selector and its presentation
661
+ * metadata. A trigger names one resource with a resource type and an
662
+ * identifier, or it names neither. With neither, it runs for every resource
663
+ * of the namespace that its filters match.
664
+ */
665
+ const eventAutomationTriggerSchema = z.object({
666
+ events: z.array(eventTypeSchema).min(1),
667
+ label: z.string().min(1),
668
+ match: eventMatchSchema.optional(),
669
+ namespace: z.string().min(1),
670
+ identifier: z.string().min(1).max(300).optional(),
671
+ resourceType: z.string().min(1).optional()
672
+ }).strict().refine((trigger) => trigger.identifier === void 0 === (trigger.resourceType === void 0), {
673
+ message: "Set both a resource type and an identifier, or leave out both to run for every resource.",
674
+ path: ["identifier"]
675
+ });
676
+ /** Event automations target a Slack channel or DM, never a message thread. */
677
+ const eventAutomationDestinationSchema = slackDestinationSchema.omit({ threadTs: true });
678
+ const eventAutomationOutcomeSchema = taskOutcomeSchema.extend({ destination: eventAutomationDestinationSchema });
679
+ /** Validate one persisted event automation. */
680
+ const eventAutomationSchema = z.object({
681
+ id: z.string().min(1),
682
+ createdAtMs: z.number().finite(),
683
+ createdBy: eventAutomationPrincipalSchema,
684
+ /** Junior identity that created the automation. It decides ownership. */
685
+ creatorIdentityId: z.string().min(1),
686
+ credentialMode: z.enum(["system", "creator"]),
687
+ destination: eventAutomationDestinationSchema,
688
+ destinationVisibility: destinationVisibilitySchema,
689
+ /** Explicit visible effects after successful work. An empty list is silent. */
690
+ outcomes: z.array(eventAutomationOutcomeSchema).max(5),
691
+ task: automationTaskSchema,
692
+ trigger: eventAutomationTriggerSchema
693
+ }).strict();
581
694
  // src/chat/scheduled-automations/schedule-intent.ts
582
695
  /**
583
696
  * Owns model-facing schedule intent and materializes it against the trusted
@@ -1165,6 +1278,8 @@ const spaceSchema = z.object({
1165
1278
  archivedAt: z.iso.datetime().nullable(),
1166
1279
  memberCount: z.number().int().nonnegative(),
1167
1280
  viewerIsMember: z.boolean(),
1281
+ /** The Lead, the Space's root Conversation. */
1282
+ leadConversationId: z.string().min(1),
1168
1283
  /**
1169
1284
  * The tree states of the Space's Conversations that are not archived,
1170
1285
  * rolled up for the viewer: the first that applies. List rows only.
@@ -1226,74 +1341,10 @@ function instructionActors(provenance) {
1226
1341
  }
1227
1342
  return actors;
1228
1343
  }
1229
- // src/chat/conversations/history-payload.ts
1230
- const messageFieldsSchema = z.record(z.string(), z.unknown());
1231
- const replacementEntrySchema = z.object({ item: z.string() }).passthrough();
1232
- /** Identify history events that store message fields as JSON strings. */
1233
- function isEncodedHistoryType(type) {
1234
- return type === "user_message" || type === "assistant_message" || type === "tool_result" || type === "system_message" || type === "handoff" || type === "compaction";
1235
- }
1236
- /** Encode agent history before SQL can change keys or string contents. */
1237
- function encodeHistoryPayload(data) {
1238
- const { type, ...payload } = data;
1239
- if (!isEncodedHistoryType(type)) return {
1240
- schemaVersion: 1,
1241
- payload
1242
- };
1243
- if (data.type === "handoff" || data.type === "compaction") return {
1244
- schemaVersion: 2,
1245
- payload: {
1246
- ...payload,
1247
- replacementHistory: data.replacementHistory.map(({ item, ...entry }) => ({
1248
- ...entry,
1249
- item: JSON.stringify(item)
1250
- }))
1251
- }
1252
- };
1253
- const { provenance, ...message } = payload;
1254
- return {
1255
- schemaVersion: 2,
1256
- payload: {
1257
- message: JSON.stringify(message),
1258
- provenance,
1259
- model: message["model"],
1260
- provider: message["provider"],
1261
- usage: message["usage"],
1262
- toolCallId: message["toolCallId"],
1263
- stopReason: message["stopReason"],
1264
- timestamp: message["timestamp"],
1265
- toolName: message["toolName"],
1266
- isError: message["isError"]
1267
- }
1268
- };
1269
- }
1270
- /** Decode stored history for validation by the conversation event schema. */
1271
- function decodeHistoryPayload(type, payload) {
1272
- const fields = messageFieldsSchema.parse(payload);
1273
- if (type === "handoff" || type === "compaction") return {
1274
- ...fields,
1275
- replacementHistory: z.array(replacementEntrySchema).parse(fields["replacementHistory"]).map(({ item, ...entry }) => {
1276
- const parsedItem = JSON.parse(item);
1277
- return {
1278
- ...entry,
1279
- item: parsedItem
1280
- };
1281
- })
1282
- };
1283
- const message = messageFieldsSchema.parse(JSON.parse(z.string().parse(fields["message"])));
1284
- if (fields["provenance"] !== void 0) message["provenance"] = fields["provenance"];
1285
- return message;
1286
- }
1287
- // src/chat/conversations/history.ts
1288
- /**
1289
- * Durable conversation event history port.
1290
- *
1291
- * Events append under the conversation lease in stable sequence order.
1292
- * Compaction replaces the active model history without rewriting prior
1293
- * events. Unsupported stored events remain readable as opaque facts,
1294
- * while malformed known events fail loudly. Provider-specific message fields
1295
- * are validated by the Pi adapter when it restores model context.
1296
- */
1344
+ // src/chat/pi/messages.ts
1345
+ /** Permissive schema for durable Pi SDK messages whose content shape may evolve. */
1346
+ const piMessageSchema = z.object({ role: z.string() }).passthrough().transform((value) => value);
1347
+ // src/core/history/items.ts
1297
1348
  const userMessageEventDataSchema = z.object({
1298
1349
  type: z.literal("user_message"),
1299
1350
  role: z.never().optional(),
@@ -1342,10 +1393,10 @@ const compactionDetailsSchema = z.object({
1342
1393
  retainedMessageCount: z.number().int().nonnegative(),
1343
1394
  summaryChars: z.number().int().nonnegative()
1344
1395
  }).strict();
1345
- const legacyModelProfileSchema = z.string().min(1).optional();
1396
+ const legacyModelProfileSchema$1 = z.string().min(1).optional();
1346
1397
  const historyReplacementEventDataSchema = z.object({
1347
1398
  type: z.literal("compaction"),
1348
- modelProfile: legacyModelProfileSchema,
1399
+ modelProfile: legacyModelProfileSchema$1,
1349
1400
  modelId: z.string().min(1),
1350
1401
  details: compactionDetailsSchema.optional(),
1351
1402
  costUsd: z.number().finite().nonnegative().optional(),
@@ -1354,18 +1405,168 @@ const historyReplacementEventDataSchema = z.object({
1354
1405
  }).strict();
1355
1406
  const legacyHandoffEventDataSchema = z.object({
1356
1407
  type: z.literal("handoff"),
1357
- modelProfile: legacyModelProfileSchema,
1408
+ modelProfile: legacyModelProfileSchema$1,
1358
1409
  modelId: z.string().min(1),
1359
1410
  reasoningLevel: z.string().min(1).optional(),
1360
1411
  triggeringToolCallId: z.string().min(1).optional(),
1361
1412
  summary: z.string().min(1).optional(),
1362
1413
  replacementHistory: replacementHistorySchema
1363
1414
  }).strict();
1415
+ /** The data of an event that replaces the active agent history. */
1416
+ const historyReplacementDataSchema = z.discriminatedUnion("type", [historyReplacementEventDataSchema, legacyHandoffEventDataSchema]);
1417
+ const typeOf = (option) => option.shape.type.value;
1418
+ /** The event types of agent history items. */
1419
+ const AGENT_HISTORY_ITEM_TYPES = agentHistoryItemSchema.options.map(typeOf);
1420
+ /** The event types of History replacements. */
1421
+ const HISTORY_REPLACEMENT_TYPES = historyReplacementDataSchema.options.map(typeOf);
1422
+ const historyReplacementTypes = new Set(HISTORY_REPLACEMENT_TYPES);
1423
+ /** True when an event type is a History replacement type. */
1424
+ function isHistoryReplacementType(type) {
1425
+ return historyReplacementTypes.has(type);
1426
+ }
1427
+ /** True when core's event data is a History replacement. */
1428
+ function isHistoryReplacement(data) {
1429
+ return isHistoryReplacementType(data.type);
1430
+ }
1364
1431
  /** Validate an event that intentionally replaces active model history. */
1365
1432
  const historyReplacementSchema = z.object({
1366
1433
  data: historyReplacementEventDataSchema,
1367
1434
  createdAtMs: z.number().finite()
1368
1435
  }).strict();
1436
+ /** Translate one Pi message into the agent history item that stores it. */
1437
+ function historyItemFromPiMessage(message, provenance) {
1438
+ const { role, ...fields } = piMessageSchema.parse(message);
1439
+ if (role === "user") return agentHistoryItemSchema.parse({
1440
+ ...fields,
1441
+ type: "user_message",
1442
+ provenance
1443
+ });
1444
+ if (role === "assistant") return agentHistoryItemSchema.parse({
1445
+ ...fields,
1446
+ type: "assistant_message"
1447
+ });
1448
+ if (role === "toolResult") return agentHistoryItemSchema.parse({
1449
+ ...fields,
1450
+ type: "tool_result"
1451
+ });
1452
+ return agentHistoryItemSchema.parse({
1453
+ ...fields,
1454
+ type: "system_message"
1455
+ });
1456
+ }
1457
+ /** Translate one agent history item into the Pi message it represents. */
1458
+ function piMessageFromHistoryItem(data) {
1459
+ if (data.type === "user_message") {
1460
+ const { type: _, provenance: __, ...fields } = data;
1461
+ return piMessageSchema.parse({
1462
+ ...fields,
1463
+ role: "user"
1464
+ });
1465
+ }
1466
+ if (data.type === "assistant_message") {
1467
+ const { type: _, ...fields } = data;
1468
+ return piMessageSchema.parse({
1469
+ ...fields,
1470
+ role: "assistant"
1471
+ });
1472
+ }
1473
+ if (data.type === "system_message") {
1474
+ const { type: _, ...fields } = data;
1475
+ return piMessageSchema.parse({
1476
+ ...fields,
1477
+ role: "system"
1478
+ });
1479
+ }
1480
+ const { type: _, ...fields } = data;
1481
+ return piMessageSchema.parse({
1482
+ ...fields,
1483
+ role: "toolResult"
1484
+ });
1485
+ }
1486
+ // src/core/history/rows.ts
1487
+ const messageFieldsSchema = z.record(z.string(), z.unknown());
1488
+ const replacementEntrySchema = z.object({ item: z.string() }).passthrough();
1489
+ const agentHistoryTypes = /* @__PURE__ */ new Set([...AGENT_HISTORY_ITEM_TYPES, ...HISTORY_REPLACEMENT_TYPES]);
1490
+ /** True when an event type is core's. Every other type is the host's. */
1491
+ function isAgentHistoryType(type) {
1492
+ return agentHistoryTypes.has(type);
1493
+ }
1494
+ /** True when event data is core's. Every other event data is the host's. */
1495
+ function isAgentHistoryData(data) {
1496
+ return isAgentHistoryType(data.type);
1497
+ }
1498
+ /** Encode core's event data as a version 2 row payload. */
1499
+ function encodeAgentHistoryPayload(data) {
1500
+ if (isHistoryReplacement(data)) {
1501
+ const { type: _, ...payload } = data;
1502
+ return {
1503
+ schemaVersion: 2,
1504
+ payload: {
1505
+ ...payload,
1506
+ replacementHistory: data.replacementHistory.map(({ item, ...entry }) => ({
1507
+ ...entry,
1508
+ item: JSON.stringify(item)
1509
+ }))
1510
+ }
1511
+ };
1512
+ }
1513
+ const { type: _, ...fields } = data;
1514
+ const { provenance, ...message } = fields;
1515
+ return {
1516
+ schemaVersion: 2,
1517
+ payload: {
1518
+ message: JSON.stringify(message),
1519
+ provenance,
1520
+ model: message["model"],
1521
+ provider: message["provider"],
1522
+ usage: message["usage"],
1523
+ toolCallId: message["toolCallId"],
1524
+ stopReason: message["stopReason"],
1525
+ timestamp: message["timestamp"],
1526
+ toolName: message["toolName"],
1527
+ isError: message["isError"]
1528
+ }
1529
+ };
1530
+ }
1531
+ /** Decode a version 2 payload of core's type into its fields, without `type`. */
1532
+ function decodeAgentHistoryPayload(type, payload) {
1533
+ const fields = messageFieldsSchema.parse(payload);
1534
+ if (isHistoryReplacementType(type)) return {
1535
+ ...fields,
1536
+ replacementHistory: z.array(replacementEntrySchema).parse(fields["replacementHistory"]).map(({ item, ...entry }) => {
1537
+ const parsedItem = JSON.parse(item);
1538
+ return {
1539
+ ...entry,
1540
+ item: parsedItem
1541
+ };
1542
+ })
1543
+ };
1544
+ const message = messageFieldsSchema.parse(JSON.parse(z.string().parse(fields["message"])));
1545
+ if (fields["provenance"] !== void 0) message["provenance"] = fields["provenance"];
1546
+ return message;
1547
+ }
1548
+ /** Decode one stored row of core's type. Throws on any other row. */
1549
+ function agentHistoryFromRow(row) {
1550
+ const { type } = row;
1551
+ if (!isAgentHistoryType(type)) throw new Error(`Event type ${type} is not agent history`);
1552
+ const fields = row.schemaVersion === 2 ? decodeAgentHistoryPayload(type, row.payload) : row.schemaVersion === 1 ? messageFieldsSchema.parse(row.payload) : void 0;
1553
+ if (fields === void 0) throw new Error(`Agent history row has unknown schema version ${row.schemaVersion}`);
1554
+ const data = {
1555
+ ...fields,
1556
+ type
1557
+ };
1558
+ return isHistoryReplacementType(type) ? historyReplacementDataSchema.parse(data) : agentHistoryItemSchema.parse(data);
1559
+ }
1560
+ // src/chat/conversations/history.ts
1561
+ /**
1562
+ * Durable conversation event history port.
1563
+ *
1564
+ * Events append under the conversation lease in stable sequence order.
1565
+ * Compaction replaces the active model history without rewriting prior
1566
+ * events. Unsupported stored events remain readable as opaque facts,
1567
+ * while malformed known events fail loudly. Provider-specific message fields
1568
+ * are validated by the Pi adapter when it restores model context.
1569
+ */
1369
1570
  const mcpProviderConnectedEventDataSchema = z.object({
1370
1571
  type: z.literal("mcp_provider_connected"),
1371
1572
  provider: z.string().min(1),
@@ -1411,18 +1612,22 @@ const guardianActionReviewedEventDataSchema = z.object({
1411
1612
  "ask",
1412
1613
  "deny"
1413
1614
  ]),
1615
+ /** Set on decisions recorded since Guardian names one rule. */
1616
+ rule: z.string().min(1).optional(),
1617
+ /** Set on decisions recorded since the record keeps why. */
1618
+ reason: z.string().min(1).optional(),
1414
1619
  riskLevel: z.enum([
1415
1620
  "low",
1416
1621
  "medium",
1417
1622
  "high",
1418
1623
  "critical"
1419
- ]),
1624
+ ]).optional(),
1420
1625
  userAuthorization: z.enum([
1421
1626
  "high",
1422
1627
  "medium",
1423
1628
  "low",
1424
1629
  "unknown"
1425
- ])
1630
+ ]).optional()
1426
1631
  }).strict();
1427
1632
  const conversationMessageRoleSchema = z.union([
1428
1633
  z.literal("user"),
@@ -1584,6 +1789,7 @@ const subagentEndedEventDataSchema = z.object({
1584
1789
  ]),
1585
1790
  errorCode: z.string().min(1).optional()
1586
1791
  }).strict();
1792
+ const legacyModelProfileSchema = z.string().min(1).optional();
1587
1793
  const compactionRequestedEventDataSchema = z.object({
1588
1794
  type: z.literal("compaction_requested"),
1589
1795
  markSeq: z.number().int().nonnegative(),
@@ -1630,8 +1836,7 @@ const appendableConversationEventDataSchema = z.union([
1630
1836
  /** Strict event-data contract reused by the SQL row codec. */
1631
1837
  const conversationEventDataSchema = z.union([
1632
1838
  appendableConversationEventDataSchema,
1633
- historyReplacementEventDataSchema,
1634
- legacyHandoffEventDataSchema,
1839
+ historyReplacementDataSchema,
1635
1840
  legacyTurnRoutedEventDataSchema,
1636
1841
  unownedMcpProviderConnectedEventDataSchema
1637
1842
  ]);
@@ -1687,7 +1892,7 @@ const conversationEventEnvelopeSchema = z.object({
1687
1892
  const conversationEventSchema = z.union([conversationEventEnvelopeSchema.extend({
1688
1893
  schemaVersion: z.union([z.literal(1), z.literal(2)]),
1689
1894
  data: conversationEventDataSchema
1690
- }).refine((event) => event.schemaVersion === 1 || isEncodedHistoryType(event.data.type)), conversationEventEnvelopeSchema.extend({ data: unknownConversationEventDataSchema })]);
1895
+ }).refine((event) => event.schemaVersion === 1 || isAgentHistoryType(event.data.type)), conversationEventEnvelopeSchema.extend({ data: unknownConversationEventDataSchema })]);
1691
1896
  const storedConversationEventSchema = conversationEventEnvelopeSchema.extend({
1692
1897
  type: z.string().min(1),
1693
1898
  payload: z.unknown()
@@ -1702,10 +1907,10 @@ function decodeStoredConversationEvent(value) {
1702
1907
  const stored = storedConversationEventSchema.parse(value);
1703
1908
  const { type, payload, ...envelope } = stored;
1704
1909
  const knownType = knownConversationEventTypeSchema.safeParse(type).success;
1705
- if (stored.schemaVersion === 2 && isEncodedHistoryType(type)) return conversationEventSchema.parse({
1910
+ if (stored.schemaVersion === 2 && isAgentHistoryType(type)) return conversationEventSchema.parse({
1706
1911
  ...envelope,
1707
1912
  data: {
1708
- ...decodeHistoryPayload(type, payload),
1913
+ ...decodeAgentHistoryPayload(type, payload),
1709
1914
  type
1710
1915
  }
1711
1916
  });
@@ -1734,7 +1939,7 @@ const newConversationEventSchema = z.object({
1734
1939
  idempotencyKey: z.string().min(1).optional(),
1735
1940
  createdAtMs: z.number().finite()
1736
1941
  }).strict();
1737
- // src/chat/agent-invocations/agent-types.ts
1942
+ // src/chat/child-agents/agent-types.ts
1738
1943
  /**
1739
1944
  * Child agent types. A type is plain data: when to pick it and what the child
1740
1945
  * reads with its task. Runtime code reads only these fields, never a type
@@ -2045,8 +2250,8 @@ const conversationReportMessageEventDataSchema = z.object({
2045
2250
  actorIdentity: actorIdentitySchema.optional(),
2046
2251
  /** Identity id of the author. Detail `authors` maps it to the person. */
2047
2252
  actorIdentityId: z.string().min(1).optional(),
2048
- /** Set on input that an earlier release's agent wrote, not a person. */
2049
- agentInvocationId: z.string().min(1).optional(),
2253
+ /** Set on input that a parent agent wrote, not a person. */
2254
+ fromParentAgent: z.literal(true).optional(),
2050
2255
  eventType: z.string().min(1).optional(),
2051
2256
  /** Namespace of the first Event, such as `github`. */
2052
2257
  eventNamespace: z.string().min(1).optional(),
@@ -2100,9 +2305,7 @@ const conversationReportToolCallSchema = z.object({
2100
2305
  startedAt: z.string().datetime().optional(),
2101
2306
  startedSeq: z.number().int().nonnegative().optional(),
2102
2307
  input: z.unknown().optional(),
2103
- output: z.unknown().optional(),
2104
- /** The Conversation that a completed `startConversation` call started. */
2105
- startedConversationId: z.string().min(1).optional()
2308
+ output: z.unknown().optional()
2106
2309
  }).strict().superRefine((call, context) => {
2107
2310
  if (call.startedAt === void 0 !== (call.startedSeq === void 0)) context.addIssue({
2108
2311
  code: "custom",
@@ -2183,18 +2386,20 @@ const conversationReportGuardianActionReviewedEventDataSchema = z.object({
2183
2386
  "ask",
2184
2387
  "deny"
2185
2388
  ]),
2389
+ rule: z.string().min(1).optional(),
2390
+ reason: z.string().min(1).optional(),
2186
2391
  riskLevel: z.enum([
2187
2392
  "low",
2188
2393
  "medium",
2189
2394
  "high",
2190
2395
  "critical"
2191
- ]),
2396
+ ]).optional(),
2192
2397
  userAuthorization: z.enum([
2193
2398
  "high",
2194
2399
  "medium",
2195
2400
  "low",
2196
2401
  "unknown"
2197
- ])
2402
+ ]).optional()
2198
2403
  }).strict();
2199
2404
  const conversationReportTurnContextEventDataSchema = z.object({
2200
2405
  type: z.literal("turn_context"),
@@ -2839,193 +3044,24 @@ const automationEventCatalogSchema = z.array(z.object({
2839
3044
  }).strict());
2840
3045
  const automationScheduleIntentSchema = scheduleIntentSchema;
2841
3046
  const automationSchedulePreviewSchema = scheduledAutomationSchema.pick({ schedule: true }).extend({ nextRunAtMs: z.number() }).strict();
2842
- // src/api/schema/response.ts
2843
- /** Stable error body returned by Junior-owned REST endpoints. */
2844
- const apiErrorSchema = z.object({ error: z.string().min(1) }).strict();
2845
- /**
2846
- * Carries a content token in both directions. A custom header, not `ETag` /
2847
- * `If-None-Match`: the Vercel CDN removes `If-None-Match` before it calls the
2848
- * function, with every `Cache-Control` value, and no setting stops this. The
2849
- * CDN then answers a match with a 304 only after the function built the full
2850
- * response, so the read is not saved and the 304 does not show in app
2851
- * telemetry. A probe deployment confirmed this for `private, no-cache`,
2852
- * `no-cache`, `private, no-store`, `private, max-age=0, must-revalidate`, and
2853
- * no header. See
2854
- * https://vercel.com/docs/manage-cdn-usage#optimizing-fast-origin-transfer.
2855
- * A read that sends the token of the copy it holds gets an empty 304 while
2856
- * the content is unchanged.
2857
- */
2858
- const CONTENT_VERSION_HEADER = "x-junior-content-version";
2859
- // src/chat/notifications/schedule.ts
2860
- /**
2861
- * Notification hours for one user.
2862
- *
2863
- * This module imports only zod and the browser-safe cadence helpers, so the
2864
- * dashboard client bundle can use it.
2865
- */
2866
- const clockTimePattern = /^([01]\d|2[0-3]):[0-5]\d$/;
2867
- /** Saved notification hours. Weekdays use 0 for Sunday, like `Date#getDay`. */
2868
- const notificationScheduleSchema = z.object({
2869
- /**
2870
- * Follow the linked Slack user's notification schedule. The fields below
2871
- * apply only when Junior cannot read it. Absent means on.
2872
- */
2873
- followSlack: z.boolean().optional(),
2874
- /** When false, Junior sends push notifications at any time. */
2875
- workingHoursOnly: z.boolean(),
2876
- days: z.array(z.number().int().min(0).max(6)).max(7).refine((days) => new Set(days).size === days.length, { message: "Days must be unique." }),
2877
- /** Local start time, `HH:MM`. */
2878
- start: z.string().regex(clockTimePattern),
2879
- /** Local end time, `HH:MM`. An end before the start crosses midnight. */
2880
- end: z.string().regex(clockTimePattern),
2881
- /** IANA timezone set by the user. Absent means the profile timezone. */
2882
- timezone: z.string().min(1).max(64).refine(isValidTimeZone, { message: "Unknown timezone." }).optional()
2883
- }).strict().refine((schedule) => schedule.start !== schedule.end, {
2884
- message: "Start and end must differ.",
2885
- path: ["end"]
2886
- });
2887
- /**
2888
- * Default when a user has not saved a schedule: follow Slack, else
2889
- * 09:00–18:00, Mon–Fri.
2890
- */
2891
- const DEFAULT_NOTIFICATION_SCHEDULE = {
2892
- followSlack: true,
2893
- workingHoursOnly: true,
2894
- days: [
2895
- 1,
2896
- 2,
2897
- 3,
2898
- 4,
2899
- 5
2900
- ],
2901
- start: "09:00",
2902
- end: "18:00"
2903
- };
2904
- function clockMinutes(value) {
2905
- const [hours, minutes] = value.split(":").map(Number);
2906
- return hours * 60 + minutes;
2907
- }
2908
- const weekdayIndex = {
2909
- Sun: 0,
2910
- Mon: 1,
2911
- Tue: 2,
2912
- Wed: 3,
2913
- Thu: 4,
2914
- Fri: 5,
2915
- Sat: 6
2916
- };
2917
- function localWeekdayAndMinutes(nowMs, timezone) {
2918
- const parts = new Intl.DateTimeFormat("en-US", {
2919
- hour: "2-digit",
2920
- hourCycle: "h23",
2921
- minute: "2-digit",
2922
- timeZone: timezone,
2923
- weekday: "short"
2924
- }).formatToParts(new Date(nowMs));
2925
- const value = (type) => parts.find((part) => part.type === type)?.value ?? "";
2926
- const weekday = weekdayIndex[value("weekday")];
2927
- if (weekday === void 0) throw new Error(`Could not read the weekday for timezone ${timezone}`);
2928
- return {
2929
- minutes: Number(value("hour")) % 24 * 60 + Number(value("minute")),
2930
- weekday
2931
- };
2932
- }
2933
- /**
2934
- * Return whether a notification may be sent now. A window that crosses
2935
- * midnight belongs to the day on which it starts.
2936
- */
2937
- function isWithinNotificationSchedule(schedule, timezone, nowMs) {
2938
- if (!schedule.workingHoursOnly) return true;
2939
- const { minutes, weekday } = localWeekdayAndMinutes(nowMs, timezone);
2940
- const start = clockMinutes(schedule.start);
2941
- const end = clockMinutes(schedule.end);
2942
- if (start < end) return schedule.days.includes(weekday) && minutes >= start && minutes < end;
2943
- if (minutes >= start) return schedule.days.includes(weekday);
2944
- if (minutes < end) return schedule.days.includes((weekday + 6) % 7);
2945
- return false;
2946
- }
2947
- // src/chat/attachments/media.ts
2948
- const INPUT_IMAGE_TYPES = [
2949
- "image/png",
2950
- "image/jpeg",
2951
- "image/gif",
2952
- "image/webp"
2953
- ];
2954
- /** Video types that browsers play in a `<video>` element. */
2955
- const INLINE_VIDEO_TYPES = ["video/mp4", "video/webm"];
2956
- /** Leading bytes of each accepted image type. `null` matches any byte. */
2957
- const IMAGE_SIGNATURES = [
2958
- {
2959
- mediaType: "image/png",
2960
- bytes: [
2961
- 137,
2962
- 80,
2963
- 78,
2964
- 71,
2965
- 13,
2966
- 10,
2967
- 26,
2968
- 10
2969
- ]
2970
- },
2971
- {
2972
- mediaType: "image/jpeg",
2973
- bytes: [
2974
- 255,
2975
- 216,
2976
- 255
2977
- ]
2978
- },
2979
- {
2980
- mediaType: "image/gif",
2981
- bytes: [
2982
- 71,
2983
- 73,
2984
- 70,
2985
- 56,
2986
- 55,
2987
- 97
2988
- ]
2989
- },
2990
- {
2991
- mediaType: "image/gif",
2992
- bytes: [
2993
- 71,
2994
- 73,
2995
- 70,
2996
- 56,
2997
- 57,
2998
- 97
2999
- ]
3000
- },
3001
- {
3002
- mediaType: "image/webp",
3003
- bytes: [
3004
- 82,
3005
- 73,
3006
- 70,
3007
- 70,
3008
- null,
3009
- null,
3010
- null,
3011
- null,
3012
- 87,
3013
- 69,
3014
- 66,
3015
- 80
3016
- ]
3017
- }
3047
+ // src/chat/todos/types.ts
3048
+ /** Statuses of a To-do. `done` and `dropped` close it. */
3049
+ const TODO_STATUSES = [
3050
+ "open",
3051
+ "in_progress",
3052
+ "done",
3053
+ "dropped"
3018
3054
  ];
3019
- /**
3020
- * Detect an accepted image type from file bytes. Use this instead of a file
3021
- * name or declared content type, which can be wrong.
3022
- */
3023
- function detectImageMediaType(data) {
3024
- return IMAGE_SIGNATURES.find(({ bytes }) => data.length >= bytes.length && bytes.every((byte, index) => byte === null || data[index] === byte))?.mediaType;
3025
- }
3026
- /** Report whether a media type is a raster image accepted by vision models. */
3027
- function isVisionImageMediaType(mediaType) {
3028
- const normalized = mediaType.split(";", 1)[0]?.trim().toLowerCase();
3029
- return normalized ? INPUT_IMAGE_TYPES.some((type) => type === normalized) : false;
3055
+ /** Statuses of a To-do that is still work to do. */
3056
+ const OPEN_TODO_STATUSES = ["open", "in_progress"];
3057
+ /** Whether a To-do with this status is still work to do. */
3058
+ function isOpenTodoStatus(status) {
3059
+ return status === "open" || status === "in_progress";
3030
3060
  }
3031
- export { conversationSummaryReportSchema as $, scheduledRunSchema as $t, automationVersionActivateSchema as A, isAgentUpdateEventType as An, spaceSchema as At, conversationAttachmentParamsSchema as B, removedCardSchema as Bt, automationRunListSchema as C, isEmptyUserInputAnswer as Cn, SPACE_NAME_MAX_CHARS as Ct, automationSchedulePreviewSchema as D, AGENT_MESSAGE_EVENT_TYPE as Dn, spaceListSchema as Dt, automationScheduleIntentSchema as E, AGENT_INVOCATION_EVENT_NAMESPACE as En, spaceListQuerySchema as Et, scheduledAutomationSummarySchema as F, automationTaskText as Fn, inboxItemChangeRecordSchema as Ft, conversationEventHistorySchema as G, messageAttachmentSchema as Gt, conversationAuxiliaryCostsSchema as H, MAX_ATTACHMENT_BYTES as Ht, CONVERSATION_DETAIL_VERSION_HEADER as I, gatewayOnlyProviders as In, annotationCard as It, conversationParamsSchema as J, automationInstructionToolSchema as Jt, conversationEventPageSchema as K, readMessageAttachments as Kt, CONVERSATION_VERSION_HEADER as L, messageCardRef as Lt, automationVersionParamsSchema as M, automationTaskColumns as Mn, updateSpaceBodySchema as Mt, automationVersionSchema as N, automationTaskDescription as Nn, conversationTreeStateSchema as Nt, automationSummarySchema as O, AGENT_UPDATE_EVENT_TYPE as On, spaceParamsSchema as Ot, eventAutomationSummarySchema as P, automationTaskSchema as Pn, conversationReadPositionSchema as Pt, conversationReportStatusSchema as Q, scheduledAutomationSchema as Qt, actorIdentitySchema as R, messageCardText as Rt, automationParamsSchema as S, formatUserInputAnswer as Sn, SPACE_DESCRIPTION_MAX_CHARS as St, automationRunWindowsSchema as T, userInputRequestSchema as Tn, createSpaceBodySchema as Tt, conversationDetailQuerySchema as U, MAX_INPUT_ATTACHMENTS as Ut, conversationAttachmentQuerySchema as V, resolveMessageCards as Vt, conversationDetailReportSchema as W, inputFileSchema as Wt, conversationReportEventSchema as X, taskOutcomeInputSchema as Xt, conversationReportEventDataSchema as Y, automationTitleSchema as Yt, conversationReportMessageEventSchema as Z, SCHEDULED_AUTOMATION_SYSTEM_ACTOR as Zt, automationLifecycleSchema as _, inboxItemRequestSchema as _n, agentInstructionProvenance as _t, DEFAULT_NOTIFICATION_SCHEDULE as a, getFirstRunAtMs as an, agentTypeInstructions as at, automationListQuerySchema as b, answeredChoices as bn, instructionProvenanceFor as bt, CONTENT_VERSION_HEADER as c, isValidTimeZone as cn, KNOWN_CONVERSATION_EVENT_TYPES as ct, automationEditSchema as d, SELF_TODO_ASSIGNEE as dn, conversationTurnFailureCodeSchema as dt, ScheduleIntentError as en, conversationSurfaceSchema as et, automationEventCatalogSchema as f, TODO_STATUSES as fn, conversationTurnFailureReasonSchema as ft, automationExecutionStatusSchema as g, eventAutomationTriggerSchema as gn, encodeHistoryPayload as gt, automationExecutionStatusDaySchema as h, eventAutomationSchema as hn, newConversationEventSchema as ht, isVisionImageMediaType as i, weekdaySchema as in, AGENT_TYPES as it, automationVersionListSchema as j, automationSkillNameSchema as jn, spaceVisibilitySchema as jt, automationUpdateSchema as k, isAgentInvocationResultEventType as kn, spaceRefSchema as kt, apiErrorSchema as l, usageSchema as ln, agentHistoryItemSchema as lt, automationExecutionSchema as m, isOpenTodoStatus as mn, historyReplacementSchema as mt, INPUT_IMAGE_TYPES as n, scheduleIntentFromTool as nn, activityPreviewText as nt, isWithinNotificationSchedule as o, getNextRunAtMs as on, agentTypeSchema as ot, automationExecutionListSchema as p, UPDATE_TODOS_TOOL_NAME as pn, decodeStoredConversationEvent as pt, conversationEventsQuerySchema as q, automationContextToolSchema as qt, detectImageMediaType as r, toolScheduleIntentSchema as rn, conversationChildAgentTotalsSchema as rt, notificationScheduleSchema as s, getZonedDateTimeParts as sn, formatAgentTypes as st, INLINE_VIDEO_TYPES as t, compileScheduleIntent as tn, conversationUsageSchema as tt, automationEditErrorSchema as u, OPEN_TODO_STATUSES as un, conversationEventDataSchema as ut, automationListItemSchema as v, USER_INPUT_LIMITS as vn, contextProvenance as vt, automationRunSchema as w, normalizeUserInputAnswer as wn, archiveSpaceBodySchema as wt, automationListSchema as x, buttonUserInputField as xn, sameActorIdentity as xt, automationListPageSchema as y, USER_INPUT_NOTE as yn, instructionActors as yt, conversationActivityPreviewSchema as z, readMessageCardRefs as zt };
3061
+ /** Name of the To-do registration, which namespaces its tools. */
3062
+ const TODOS_REGISTRATION_NAME = "todos";
3063
+ /** Model-facing tool that changes the To-dos, as the host names it. */
3064
+ const UPDATE_TODOS_TOOL_NAME = `${TODOS_REGISTRATION_NAME}_updateTodos`;
3065
+ /** Assignee text for the list's own agent, in tool results and blocks. */
3066
+ const SELF_TODO_ASSIGNEE = "self";
3067
+ export { activityPreviewText as $, automationTitleSchema as $t, automationVersionSchema as A, isWithinNotificationSchedule as An, spaceListQuerySchema as At, conversationDetailQuerySchema as B, TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE as Bn, annotationCard as Bt, automationScheduleIntentSchema as C, userInputRequestSchema as Cn, instructionActors as Ct, automationVersionActivateSchema as D, automationTaskSchema as Dn, SPACE_NAME_MAX_CHARS as Dt, automationUpdateSchema as E, automationTaskDescription as En, SPACE_DESCRIPTION_MAX_CHARS as Et, actorIdentitySchema as F, isValidTimeZone as Fn, spaceVisibilitySchema as Ft, conversationParamsSchema as G, usageSchema as Gn, resolveMessageCards as Gt, conversationEventHistorySchema as H, isAgentUpdateEventType as Hn, messageCardText as Ht, conversationActivityPreviewSchema as I, CONTENT_VERSION_HEADER as In, updateSpaceBodySchema as It, conversationReportMessageEventSchema as J, inputFileSchema as Jt, conversationReportEventDataSchema as K, usageTokensSchema as Kn, MAX_ATTACHMENT_BYTES as Kt, conversationAttachmentParamsSchema as L, apiErrorSchema as Ln, conversationTreeStateSchema as Lt, scheduledAutomationSummarySchema as M, getFirstRunAtMs as Mn, spaceParamsSchema as Mt, CONVERSATION_DETAIL_VERSION_HEADER as N, getNextRunAtMs as Nn, spaceRefSchema as Nt, automationVersionListSchema as O, automationTaskText as On, archiveSpaceBodySchema as Ot, CONVERSATION_VERSION_HEADER as P, getZonedDateTimeParts as Pn, spaceSchema as Pt, conversationUsageSchema as Q, automationInstructionToolSchema as Qt, conversationAttachmentQuerySchema as R, AGENT_MESSAGE_EVENT_TYPE as Rn, conversationReadPositionSchema as Rt, automationRunWindowsSchema as S, userInputQuestionSchema as Sn, contextProvenance as St, automationSummarySchema as T, automationTaskColumns as Tn, sameActorIdentity as Tt, conversationEventPageSchema as U, isLegacyResultEventType as Un, readMessageCardRefs as Ut, conversationDetailReportSchema as V, isAgentMessageEventType as Vn, messageCardRef as Vt, conversationEventsQuerySchema as W, gatewayOnlyProviders as Wn, removedCardSchema as Wt, conversationSummaryReportSchema as X, readMessageAttachments as Xt, conversationReportStatusSchema as Y, messageAttachmentSchema as Yt, conversationSurfaceSchema as Z, automationContextToolSchema as Zt, automationListQuerySchema as _, buttonUserInputField as _n, historyReplacementSchema as _t, UPDATE_TODOS_TOOL_NAME as a, compileScheduleIntent as an, KNOWN_CONVERSATION_EVENT_TYPES as at, automationRunListSchema as b, normalizeUserInputAnswer as bn, piMessageSchema as bt, automationEditSchema as c, weekdaySchema as cn, conversationTurnFailureReasonSchema as ct, automationExecutionSchema as d, inboxItemNoticeRequestSchema as dn, agentHistoryFromRow as dt, taskOutcomeInputSchema as en, conversationChildAgentTotalsSchema as et, automationExecutionStatusDaySchema as f, inboxItemQuestion as fn, encodeAgentHistoryPayload as ft, automationListPageSchema as g, answeredChoices as gn, historyItemFromPiMessage as gt, automationListItemSchema as h, USER_INPUT_NOTE as hn, HISTORY_REPLACEMENT_TYPES as ht, TODO_STATUSES as i, ScheduleIntentError as in, formatAgentTypes as it, eventAutomationSummarySchema as j, notificationScheduleSchema as jn, spaceListSchema as jt, automationVersionParamsSchema as k, DEFAULT_NOTIFICATION_SCHEDULE as kn, createSpaceBodySchema as kt, automationEventCatalogSchema as l, eventAutomationSchema as ln, decodeStoredConversationEvent as lt, automationLifecycleSchema as m, USER_INPUT_LIMITS as mn, AGENT_HISTORY_ITEM_TYPES as mt, SELF_TODO_ASSIGNEE as n, scheduledAutomationSchema as nn, agentTypeInstructions as nt, isOpenTodoStatus as o, scheduleIntentFromTool as on, conversationEventDataSchema as ot, automationExecutionStatusSchema as p, inboxItemRequestSchema as pn, isAgentHistoryData as pt, conversationReportEventSchema as q, MAX_INPUT_ATTACHMENTS as qt, TODOS_REGISTRATION_NAME as r, scheduledRunSchema as rn, agentTypeSchema as rt, automationEditErrorSchema as s, toolScheduleIntentSchema as sn, conversationTurnFailureCodeSchema as st, OPEN_TODO_STATUSES as t, SCHEDULED_AUTOMATION_SYSTEM_ACTOR as tn, AGENT_TYPES as tt, automationExecutionListSchema as u, eventAutomationTriggerSchema as un, newConversationEventSchema as ut, automationListSchema as v, formatUserInputAnswer as vn, isHistoryReplacement as vt, automationSchedulePreviewSchema as w, automationSkillNameSchema as wn, instructionProvenanceFor as wt, automationRunSchema as x, userInputFieldsSchema as xn, agentInstructionProvenance as xt, automationParamsSchema as y, isEmptyUserInputAnswer as yn, piMessageFromHistoryItem as yt, conversationAuxiliaryCostsSchema as z, AGENT_UPDATE_EVENT_TYPE as zn, inboxItemChangeRecordSchema as zt };