@sentry/junior 0.315.0 → 0.317.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 (139) hide show
  1. package/dist/{admin-5jUYY46p.js → admin-CAugg87B.js} +1 -1
  2. package/dist/{agent-runner-C7GNLRB6.js → agent-runner-AjrEV6Qe.js} +13532 -12811
  3. package/dist/{reporting-window-C4dbzDiR.js → agent-status-BA5x3Xtp.js} +33 -1
  4. package/dist/{agent-update-delivery-BNEYQsAf.js → agent-update-delivery-B_YIZcgf.js} +10 -37
  5. package/dist/api/schema.d.ts +609 -104
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.js +373 -469
  8. package/dist/{app-D_bAXRDe.d.ts → app-MoNAsVV5.d.ts} +52 -28
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +177 -132
  11. package/dist/catalog-runtime-DfSpJZdY.js +6 -0
  12. package/dist/{change-record-Bqsa5ZXE.d.ts → change-record-BzJgLsv7.d.ts} +60 -1
  13. package/dist/{adapter-context-BlSGE44V.js → channel-access-j-YAVYK4.js} +2 -42
  14. package/dist/{chat-core-engine-CxkwRpn9.js → chat-core-engine-aH85nEHv.js} +4 -3
  15. package/dist/{child-message--2G3Ft26.js → child-message-DHjQLEd1.js} +1 -1
  16. package/dist/cli/chat.js +23 -23
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.js +5 -4
  20. package/dist/cli/snapshot-create.js +5 -2
  21. package/dist/cli/upgrade.js +27 -5
  22. package/dist/config-CHQ8X251.js +2422 -0
  23. package/dist/{continue-in-slack-BGKjIdFp.js → continue-in-slack-D-FZ8Fin.js} +2 -3
  24. package/dist/{conversation-feed-Sl8lKKmR.js → conversation-feed--9S0_PXL.js} +9 -4
  25. package/dist/{proxy-path-Dc-0jXGi.js → conversation-privacy-B1uXn5sf.js} +2 -16
  26. package/dist/{conversation-turn-BoLK9i6g.js → conversation-turn-BUE_7xaN.js} +102 -172
  27. package/dist/{create-BOycVH9h.js → create-DoDIYgtZ.js} +12 -10
  28. package/dist/{credential-sync-Mn4OdkEh.js → credential-sync-BJOqGnjV.js} +17 -12
  29. package/dist/{db-DXTOYRzR.js → db-BFmyYZtJ.js} +20276 -27398
  30. package/dist/{deployment-CG3TchWh.js → deployment-DXq9ZLU4.js} +17 -15
  31. package/dist/{engine-context-dyWlfNdD.js → engine-context-CgQ7mlHt.js} +264 -50
  32. package/dist/{html-CfXEwl_h.js → html-B3VKTGbJ.js} +6 -2
  33. package/dist/instrumentation.js +15 -7
  34. package/dist/{job-runner-CySgpi9v.js → job-runner-A1lCkybD.js} +397 -22
  35. package/dist/{lineage-tRTOcrsL.js → lineage-Bktb0UcV.js} +1 -1
  36. package/dist/{list-DXBz8SYL.js → list-Bxvg5wXf.js} +260 -698
  37. package/dist/{logging-czs0nqLC.js → logging--smS7XRK.js} +2 -2
  38. package/dist/{mailbox-turn-79Nv1JXv.js → mailbox-turn-uSXhUFc9.js} +648 -2957
  39. package/dist/{message-BTox2Cmb.js → message-BNenhsmB.js} +12 -22
  40. package/dist/{model-input-IRGa98V7.js → model-input-BReSnwHp.js} +3 -3
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +20 -6
  43. package/dist/{oauth-callback-server-NXK7AlBp.js → oauth-callback-server-CE4soEIY.js} +2 -2
  44. package/dist/{oauth-relay-6NBPSpFE.js → oauth-relay-C36gX1gH.js} +2 -2
  45. package/dist/{package-discovery-BI6T_RkD.js → package-discovery-DD9vencX.js} +1 -50
  46. package/dist/{parent-result-Dg6P6roR.js → parent-result-Ck1rFYRQ.js} +93 -106
  47. package/dist/{plugins-BXMdNdyA.js → plugins-D_Ru4CWc.js} +1 -1
  48. package/dist/profile-BQ-iBDsZ.js +4657 -0
  49. package/dist/{transcript-BHhJVY0P.js → prompt-Dv7gkpD6.js} +97 -103
  50. package/dist/proxy-path-BHYoKZdq.js +15 -0
  51. package/dist/registry-iXMT5Jmh.js +3279 -0
  52. package/dist/reports-WKHfGTsU.js +195 -0
  53. package/dist/{resolve-BUFkmxkT.js → resolve-tony4ibz.js} +9 -29
  54. package/dist/{result-DfATzX77.js → result-Bta_dlWa.js} +42 -117
  55. package/dist/run-conversation-DL6ru7iW.js +336 -0
  56. package/dist/{runner-CmKP3inb.js → runner-BstDRbD9.js} +7 -7
  57. package/dist/{sandbox-egress-signals-DYo5BsM7.js → sandbox-egress-signals-oSJMJOnn.js} +1 -1
  58. package/dist/{schema-DrBMdPmv.js → schema-DfqrHACA.js} +67 -84
  59. package/dist/sender-actors-CPglLd5R.js +83 -0
  60. package/dist/{service-account-CxTX7nnR.js → service-account-CTV_jaNu.js} +3 -1
  61. package/dist/{skills-BlHUDj7k.js → skills-BCEU41zM.js} +4 -4
  62. package/dist/{slack-conversation-unfurl-Dhe3lB1U.js → slack-conversation-unfurl-DxVmhbGP.js} +7 -6
  63. package/dist/{spawn-CfvlFdfz.js → spawn-frczVPIr.js} +11 -8
  64. package/dist/{system-prompt-table-CDCYVwqN.js → system-prompt-table-CiXy0eNR.js} +91 -70
  65. package/dist/{task-runner-DcdQJd9e.js → task-runner-C9Yc2_ae.js} +35 -49
  66. package/dist/{thread-context-DF5uDcWN.js → thread-context-CqZDKErp.js} +6 -6
  67. package/dist/topics-SRN7IVX-.js +24 -0
  68. package/dist/turn-membership-CENFf3kI.js +856 -0
  69. package/dist/{turn-wake-um5Ubd4m.js → turn-wake-BhloiI2h.js} +4 -5
  70. package/dist/{media-Cr9pGkzr.js → types-C4iC-IMC.js} +819 -777
  71. package/dist/user-customization-CvfuY9Eo.js +93 -0
  72. package/dist/users-ByG5RCEJ.js +181 -0
  73. package/dist/{validation-CJyuOPD2.js → validation-8gjfR91V.js} +1 -1
  74. package/dist/{version-Bhe7RPIe.js → version-BeZhWWBE.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{worker-D8PRgUqr.js → worker-BqMQQNRk.js} +5 -4
  77. package/migrations/20261125171254_conversation_visibility/migration.sql +4 -0
  78. package/migrations/20261125171254_conversation_visibility/snapshot.json +67 -0
  79. package/migrations/20261125171257_conversation_visibility_backfill/migration.sql +25 -0
  80. package/migrations/20261125171257_conversation_visibility_backfill/snapshot.json +9 -0
  81. package/migrations/20261125213232_drop_versions_notify/migration.sql +19 -0
  82. package/migrations/20261125213232_drop_versions_notify/snapshot.json +9 -0
  83. package/migrations/20261125225138_conversation_kind_root_thread/migration.sql +23 -0
  84. package/migrations/20261125225138_conversation_kind_root_thread/snapshot.json +55 -0
  85. package/migrations/20261125225142_conversation_kind_root_thread_backfill/migration.sql +7 -0
  86. package/migrations/20261125225142_conversation_kind_root_thread_backfill/snapshot.json +9 -0
  87. package/migrations/20261126000151_conversation_event_message_role_seq_index/migration.sql +1 -0
  88. package/migrations/20261126000151_conversation_event_message_role_seq_index/snapshot.json +69 -0
  89. package/migrations/20261126012917_merge_leaves/migration.sql +2 -0
  90. package/migrations/20261126012917_merge_leaves/snapshot.json +12 -0
  91. package/migrations/20261126025226_drop_agent_invocations/migration.sql +6 -0
  92. package/migrations/20261126025226_drop_agent_invocations/snapshot.json +9 -0
  93. package/migrations/20261126033000_space_conversations_lead_children/migration.sql +155 -0
  94. package/migrations/20261126033000_space_conversations_lead_children/snapshot.json +9 -0
  95. package/migrations/20261126144620_drop_user_message_time_index/migration.sql +1 -0
  96. package/migrations/20261126144620_drop_user_message_time_index/snapshot.json +38 -0
  97. package/migrations/20261126153100_inbox_item_subjects/migration.sql +140 -0
  98. package/migrations/20261126153100_inbox_item_subjects/snapshot.json +9 -0
  99. package/migrations/20261126153103_inbox_item_subjects_not_null/migration.sql +12 -0
  100. package/migrations/20261126153103_inbox_item_subjects_not_null/snapshot.json +9 -0
  101. package/migrations/20261126153105_inbox_item_subject_indexes/migration.sql +1 -0
  102. package/migrations/20261126153105_inbox_item_subject_indexes/snapshot.json +9 -0
  103. package/migrations/20261126153108_automation_run_conversation_index/migration.sql +1 -0
  104. package/migrations/20261126153108_automation_run_conversation_index/snapshot.json +9 -0
  105. package/migrations/20261126153159_inbox_item_subjects_schema/migration.sql +4 -0
  106. package/migrations/20261126153159_inbox_item_subjects_schema/snapshot.json +437 -0
  107. package/migrations/20261126153259_inbox_questions/migration.sql +76 -0
  108. package/migrations/20261126153259_inbox_questions/snapshot.json +9 -0
  109. package/migrations/20261126153301_inbox_questions_valid/migration.sql +3 -0
  110. package/migrations/20261126153301_inbox_questions_valid/snapshot.json +9 -0
  111. package/migrations/20261126153343_inbox_questions_schema/migration.sql +5 -0
  112. package/migrations/20261126153343_inbox_questions_schema/snapshot.json +407 -0
  113. package/migrations/20261126154025_inbox_item_owners/migration.sql +74 -0
  114. package/migrations/20261126154025_inbox_item_owners/snapshot.json +9 -0
  115. package/migrations/20261126154048_inbox_item_open_subject_key_index/migration.sql +1 -0
  116. package/migrations/20261126154048_inbox_item_open_subject_key_index/snapshot.json +9 -0
  117. package/migrations/20261126154051_drop_inbox_item_owner_indexes/migration.sql +7 -0
  118. package/migrations/20261126154051_drop_inbox_item_owner_indexes/snapshot.json +9 -0
  119. package/migrations/20261126154121_inbox_item_owners_schema/migration.sql +8 -0
  120. package/migrations/20261126154121_inbox_item_owners_schema/snapshot.json +311 -0
  121. package/migrations/20261126175601_conversation_event_turn/migration.sql +5 -0
  122. package/migrations/20261126175601_conversation_event_turn/snapshot.json +103 -0
  123. package/migrations/20261126175614_conversation_event_turn_index/migration.sql +1 -0
  124. package/migrations/20261126175614_conversation_event_turn_index/snapshot.json +62 -0
  125. package/migrations/20261126230028_merge_leaves/migration.sql +2 -0
  126. package/migrations/20261126230028_merge_leaves/snapshot.json +12 -0
  127. package/migrations/20261126231932_space_lead_holds_name/migration.sql +46 -0
  128. package/migrations/20261126231932_space_lead_holds_name/snapshot.json +58 -0
  129. package/migrations/20261127001022_merge_leaves/migration.sql +2 -0
  130. package/migrations/20261127001022_merge_leaves/snapshot.json +12 -0
  131. package/package.json +5 -5
  132. package/skills/jr-rpc/SKILL.md +3 -5
  133. package/dist/direct-url-BYgYfuIy.js +0 -22
  134. package/dist/markers-CE0HMXWT.js +0 -67
  135. package/dist/people-Cegp1Iwq.js +0 -81
  136. package/dist/start-conversation-Uh8Sk1EF.js +0 -162
  137. package/dist/turn-session-routing-GtetHsdO.js +0 -1309
  138. package/dist/user-customization-B27StpVQ.js +0 -9
  139. package/dist/web-message-id-C6P83ans.js +0 -10
@@ -19,565 +19,678 @@ function gatewayOnlyProviders(enabled, served) {
19
19
  const only = served.filter((provider) => enabled.includes(provider));
20
20
  return only.length > 0 && only.length < served.length ? only : void 0;
21
21
  }
22
- // src/chat/automations/task.ts
22
+ // src/usage-schema.ts
23
+ const usageCostSchema = z.object({
24
+ input: z.number().finite().nonnegative().optional(),
25
+ output: z.number().finite().nonnegative().optional(),
26
+ cacheRead: z.number().finite().nonnegative().optional(),
27
+ cacheWrite: z.number().finite().nonnegative().optional(),
28
+ total: z.number().finite().nonnegative().optional()
29
+ }).strict();
30
+ const usageSchema = z.object({
31
+ inputTokens: z.number().int().nonnegative().optional(),
32
+ outputTokens: z.number().int().nonnegative().optional(),
33
+ cachedInputTokens: z.number().int().nonnegative().optional(),
34
+ cacheCreationTokens: z.number().int().nonnegative().optional(),
35
+ reasoningTokens: z.number().int().nonnegative().optional(),
36
+ totalTokens: z.number().int().nonnegative().optional(),
37
+ cost: usageCostSchema.optional()
38
+ }).strict();
39
+ // src/api/schema/response.ts
40
+ /** Stable error body returned by Junior-owned REST endpoints. */
41
+ const apiErrorSchema = z.object({ error: z.string().min(1) }).strict();
23
42
  /**
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.
43
+ * Carries a content token in both directions. A custom header, not `ETag` /
44
+ * `If-None-Match`: the Vercel CDN removes `If-None-Match` before it calls the
45
+ * function, with every `Cache-Control` value, and no setting stops this. The
46
+ * CDN then answers a match with a 304 only after the function built the full
47
+ * response, so the read is not saved and the 304 does not show in app
48
+ * telemetry. A probe deployment confirmed this for `private, no-cache`,
49
+ * `no-cache`, `private, no-store`, `private, max-age=0, must-revalidate`, and
50
+ * no header. See
51
+ * https://vercel.com/docs/manage-cdn-usage#optimizing-fast-origin-transfer.
52
+ * A read that sends the token of the copy it holds gets an empty 304 while
53
+ * the content is unchanged.
27
54
  */
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;
55
+ const CONTENT_VERSION_HEADER = "x-junior-content-version";
56
+ // src/chat/scheduled-automations/cadence.ts
57
+ const FORMATTERS = /* @__PURE__ */ new Map();
58
+ function getFormatter(timezone) {
59
+ const existing = FORMATTERS.get(timezone);
60
+ if (existing) return existing;
61
+ const formatter = new Intl.DateTimeFormat("en-US", {
62
+ timeZone: timezone,
63
+ hour12: false,
64
+ year: "numeric",
65
+ month: "2-digit",
66
+ day: "2-digit",
67
+ hour: "2-digit",
68
+ minute: "2-digit",
69
+ second: "2-digit"
70
+ });
71
+ FORMATTERS.set(timezone, formatter);
72
+ return formatter;
73
+ }
74
+ function normalizeHour(hour) {
75
+ return hour === 24 ? 0 : hour;
76
+ }
77
+ function getLocalDateWeekday(date) {
78
+ return new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay();
79
+ }
80
+ function getWeekStart(date) {
81
+ return addDays(date, -((getLocalDateWeekday(date) + 6) % 7));
45
82
  }
46
83
  /**
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.
84
+ * Check that a value is an IANA time zone that this runtime knows. This module
85
+ * has no runtime imports, so the dashboard client bundle can use it.
49
86
  */
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.`;
87
+ function isValidTimeZone(timezone) {
88
+ try {
89
+ new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
90
+ return true;
91
+ } catch {
92
+ return false;
93
+ }
53
94
  }
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
95
+ /** Resolve a UTC timestamp into calendar parts for a named time zone. */
96
+ function getZonedDateTimeParts(timestampMs, timezone) {
97
+ const parts = getFormatter(timezone).formatToParts(new Date(timestampMs));
98
+ const values = new Map(parts.map((part) => [part.type, part.value]));
99
+ const year = Number(values.get("year"));
100
+ const month = Number(values.get("month"));
101
+ const day = Number(values.get("day"));
102
+ return {
103
+ year,
104
+ month,
105
+ day,
106
+ hour: normalizeHour(Number(values.get("hour"))),
107
+ minute: Number(values.get("minute")),
108
+ second: Number(values.get("second")),
109
+ weekday: getLocalDateWeekday({
110
+ year,
111
+ month,
112
+ day
113
+ })
62
114
  };
63
115
  }
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);
116
+ function getTimeZoneOffsetMs(timestampMs, timezone) {
117
+ const parts = getZonedDateTimeParts(timestampMs, timezone);
118
+ return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second) - timestampMs;
71
119
  }
72
- /**
73
- * Event type of an agent update: what a Conversation reports when a Turn
74
- * ends, it waits on a person, or it stops. A parent gets it from its child
75
- * agents, and a Watch on the Conversation gets the same Event.
76
- */
77
- const AGENT_UPDATE_EVENT_TYPE = "agent.update";
78
- const LEGACY_AGENT_REPLY_EVENT_TYPE = "agent.reply";
79
- /** True when an Event type names an agent update. */
80
- function isAgentUpdateEventType(eventType) {
81
- return eventType === "agent.update" || eventType === LEGACY_AGENT_REPLY_EVENT_TYPE;
120
+ function localDateTimeToTimestampMs(args) {
121
+ const localAsUtcMs = Date.UTC(args.date.year, args.date.month - 1, args.date.day, args.time.hour, args.time.minute, 0);
122
+ const offsets = /* @__PURE__ */ new Set();
123
+ for (const probeDeltaMs of [
124
+ -1296e5,
125
+ -432e5,
126
+ 0,
127
+ 432e5,
128
+ 1296e5
129
+ ]) offsets.add(getTimeZoneOffsetMs(localAsUtcMs + probeDeltaMs, args.timezone));
130
+ const matches = [...offsets].map((offsetMs) => localAsUtcMs - offsetMs).filter((timestampMs) => {
131
+ const parts = getZonedDateTimeParts(timestampMs, args.timezone);
132
+ return parts.year === args.date.year && parts.month === args.date.month && parts.day === args.date.day && parts.hour === args.time.hour && parts.minute === args.time.minute;
133
+ });
134
+ if (matches.length === 0) return;
135
+ return Math.min(...matches);
82
136
  }
83
- /** Event type of a message that a child agent sends to its parent. */
84
- 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.");
137
+ /** Resolve local time, rejecting DST gaps and choosing the earlier instant in a fold. */
138
+ function resolveLocalScheduleAtMs(args) {
139
+ const date = parseLocalDate(args.date);
140
+ if (!date) return;
141
+ return localDateTimeToTimestampMs({
142
+ date,
143
+ time: args.time,
144
+ timezone: args.timezone
145
+ });
110
146
  }
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."
147
+ function daysBetween(left, right) {
148
+ return Math.floor((Date.UTC(right.year, right.month - 1, right.day) - Date.UTC(left.year, left.month - 1, left.day)) / 864e5);
149
+ }
150
+ function weeklyRecurrenceMatchesDate(date, start, recurrence) {
151
+ if (compareDate(date, start) < 0) return false;
152
+ return normalizeWeekdays(recurrence.weekdays).includes(getLocalDateWeekday(date)) && Math.floor(daysBetween(getWeekStart(start), getWeekStart(date)) / 7) % recurrence.interval === 0;
153
+ }
154
+ function greatestCommonDivisor(left, right) {
155
+ let a = Math.abs(left);
156
+ let b = Math.abs(right);
157
+ while (b !== 0) [a, b] = [b, a % b];
158
+ return a;
159
+ }
160
+ function findNextRunAtMs(args) {
161
+ const start = parseLocalDate(args.recurrence.startDate);
162
+ const interval = args.recurrence.interval;
163
+ if (!start || !Number.isInteger(interval) || interval <= 0) return;
164
+ const searchFrom = compareDate(args.searchFrom, start) < 0 ? start : args.searchFrom;
165
+ if (args.recurrence.frequency === "daily") {
166
+ const offsetDays = daysBetween(start, searchFrom);
167
+ let candidateDate = addDays(start, Math.ceil(offsetDays / interval) * interval);
168
+ const gregorianCycleDays = 146097;
169
+ const candidateCount = gregorianCycleDays / greatestCommonDivisor(gregorianCycleDays, interval);
170
+ for (let attempts = 0; attempts < candidateCount; attempts += 1) {
171
+ const candidate = buildCandidate({
172
+ date: candidateDate,
173
+ recurrence: args.recurrence,
174
+ timezone: args.timezone
144
175
  });
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."
176
+ if (candidate !== void 0 && candidate > args.afterMs) return candidate;
177
+ candidateDate = addDays(candidateDate, interval);
178
+ }
179
+ return;
180
+ }
181
+ if (args.recurrence.frequency === "weekly") {
182
+ if (normalizeWeekdays(args.recurrence.weekdays).length === 0) return;
183
+ let candidateDate = searchFrom;
184
+ const gregorianCycleDays = 146097;
185
+ const cadenceDays = interval * 7;
186
+ const searchDays = gregorianCycleDays * cadenceDays / greatestCommonDivisor(gregorianCycleDays, cadenceDays);
187
+ for (let attempts = 0; attempts < searchDays; attempts += 1) {
188
+ if (weeklyRecurrenceMatchesDate(candidateDate, start, args.recurrence)) {
189
+ const candidate = buildCandidate({
190
+ date: candidateDate,
191
+ recurrence: args.recurrence,
192
+ timezone: args.timezone
193
+ });
194
+ if (candidate !== void 0 && candidate > args.afterMs) return candidate;
195
+ }
196
+ candidateDate = addDays(candidateDate, 1);
197
+ }
198
+ return;
199
+ }
200
+ if (args.recurrence.frequency === "monthly") {
201
+ const startMonth = start.year * 12 + start.month - 1;
202
+ const searchMonth = searchFrom.year * 12 + searchFrom.month - 1;
203
+ let candidateMonth = startMonth + Math.ceil((searchMonth - startMonth) / interval) * interval;
204
+ const gregorianCycleMonths = 4800;
205
+ const candidateCount = gregorianCycleMonths / greatestCommonDivisor(gregorianCycleMonths, interval);
206
+ for (let attempts = 0; attempts < candidateCount; attempts += 1) {
207
+ const candidateDate = {
208
+ year: Math.floor(candidateMonth / 12),
209
+ month: candidateMonth % 12 + 1,
210
+ day: args.recurrence.dayOfMonth ?? 0
211
+ };
212
+ if (compareDate(candidateDate, searchFrom) >= 0) {
213
+ const candidate = buildCandidate({
214
+ date: candidateDate,
215
+ recurrence: args.recurrence,
216
+ timezone: args.timezone
217
+ });
218
+ if (candidate !== void 0 && candidate > args.afterMs) return candidate;
219
+ }
220
+ candidateMonth += interval;
221
+ }
222
+ return;
223
+ }
224
+ let candidateYear = start.year + Math.ceil((searchFrom.year - start.year) / interval) * interval;
225
+ const candidateCount = 400 / greatestCommonDivisor(400, interval);
226
+ for (let attempts = 0; attempts < candidateCount; attempts += 1) {
227
+ const candidateDate = {
228
+ year: candidateYear,
229
+ month: args.recurrence.month ?? 0,
230
+ day: args.recurrence.dayOfMonth ?? 0
231
+ };
232
+ if (compareDate(candidateDate, searchFrom) >= 0) {
233
+ const candidate = buildCandidate({
234
+ date: candidateDate,
235
+ recurrence: args.recurrence,
236
+ timezone: args.timezone
148
237
  });
238
+ if (candidate !== void 0 && candidate > args.afterMs) return candidate;
149
239
  }
240
+ candidateYear += interval;
241
+ }
242
+ }
243
+ /** Compute the first recurring calendar occurrence strictly after a timestamp. */
244
+ function getFirstRunAtMs(args) {
245
+ return findNextRunAtMs({
246
+ ...args,
247
+ searchFrom: getLocalDate(args.afterMs, args.timezone)
150
248
  });
151
249
  }
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;
250
+ function compareDate(left, right) {
251
+ return Date.UTC(left.year, left.month - 1, left.day) - Date.UTC(right.year, right.month - 1, right.day);
176
252
  }
177
- /**
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.
180
- */
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);
253
+ function addDays(date, days) {
254
+ const next = new Date(Date.UTC(date.year, date.month - 1, date.day + days));
195
255
  return {
196
- requestId: answer.requestId,
197
- values,
198
- ...other ? { other } : void 0
256
+ year: next.getUTCFullYear(),
257
+ month: next.getUTCMonth() + 1,
258
+ day: next.getUTCDate()
199
259
  };
200
260
  }
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] ?? []);
261
+ function daysInMonth(year, month) {
262
+ return new Date(Date.UTC(year, month, 0)).getUTCDate();
208
263
  }
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;
264
+ function parseLocalDate(value) {
265
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
266
+ if (!match) return;
267
+ const year = Number(match[1]);
268
+ const month = Number(match[2]);
269
+ const day = Number(match[3]);
270
+ if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day) || month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return;
271
+ return {
272
+ year,
273
+ month,
274
+ day
275
+ };
212
276
  }
213
- function answerLine(text) {
214
- return text.split("\n").map((line) => line.trim()).filter(Boolean).join("\n");
277
+ function getLocalDate(timestampMs, timezone) {
278
+ const parts = getZonedDateTimeParts(timestampMs, timezone);
279
+ return {
280
+ year: parts.year,
281
+ month: parts.month,
282
+ day: parts.day
283
+ };
215
284
  }
216
- /**
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.
220
- */
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");
285
+ function normalizeWeekdays(values) {
286
+ return [...new Set((values ?? []).filter((value) => value >= 0 && value <= 6))].sort((a, b) => a - b);
231
287
  }
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();
288
+ function buildCandidate(args) {
289
+ return localDateTimeToTimestampMs({
290
+ date: args.date,
291
+ time: args.recurrence.time,
292
+ timezone: args.timezone
293
+ });
294
+ }
295
+ /** Return the next fire time after a completed run, when the task recurs. */
296
+ function getNextRunAtMs(task, scheduledForMs, afterMs = scheduledForMs) {
297
+ if (task.schedule.kind !== "recurring") return;
298
+ const recurrence = task.schedule.recurrence;
299
+ if (!recurrence || !Number.isFinite(recurrence.interval) || recurrence.interval <= 0) return;
300
+ const timezone = task.schedule.timezone;
301
+ const afterDate = getLocalDate(afterMs, timezone);
302
+ const nextScheduledDate = addDays(getLocalDate(scheduledForMs, timezone), 1);
303
+ return findNextRunAtMs({
304
+ afterMs,
305
+ recurrence,
306
+ searchFrom: compareDate(afterDate, nextScheduledDate) < 0 ? nextScheduledDate : afterDate,
307
+ timezone
308
+ });
309
+ }
310
+ // src/chat/notifications/schedule.ts
257
311
  /**
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.
312
+ * Notification hours for one user.
313
+ *
314
+ * This module imports only zod and the browser-safe cadence helpers, so the
315
+ * dashboard client bundle can use it.
262
316
  */
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",
317
+ const clockTimePattern = /^([01]\d|2[0-3]):[0-5]\d$/;
318
+ /** Saved notification hours. Weekdays use 0 for Sunday, like `Date#getDay`. */
319
+ const notificationScheduleSchema = z.object({
320
+ /**
321
+ * Follow the linked Slack user's notification schedule. The fields below
322
+ * apply only when Junior cannot read it. Absent means on.
323
+ */
324
+ followSlack: z.boolean().optional(),
325
+ /** When false, Junior sends push notifications at any time. */
326
+ workingHoursOnly: z.boolean(),
327
+ 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." }),
328
+ /** Local start time, `HH:MM`. */
329
+ start: z.string().regex(clockTimePattern),
330
+ /** Local end time, `HH:MM`. An end before the start crosses midnight. */
331
+ end: z.string().regex(clockTimePattern),
332
+ /** IANA timezone set by the user. Absent means the profile timezone. */
333
+ timezone: z.string().min(1).max(64).refine(isValidTimeZone, { message: "Unknown timezone." }).optional()
334
+ }).strict().refine((schedule) => schedule.start !== schedule.end, {
335
+ message: "Start and end must differ.",
336
+ path: ["end"]
337
+ });
338
+ /**
339
+ * Default when a user has not saved a schedule: follow Slack, else
340
+ * 09:00–18:00, Mon–Fri.
341
+ */
342
+ const DEFAULT_NOTIFICATION_SCHEDULE = {
343
+ followSlack: true,
344
+ workingHoursOnly: true,
345
+ days: [
346
+ 1,
347
+ 2,
348
+ 3,
349
+ 4,
350
+ 5
351
+ ],
352
+ start: "09:00",
353
+ end: "18:00"
354
+ };
355
+ function clockMinutes(value) {
356
+ const [hours, minutes] = value.split(":").map(Number);
357
+ return hours * 60 + minutes;
358
+ }
359
+ const weekdayIndex = {
360
+ Sun: 0,
361
+ Mon: 1,
362
+ Tue: 2,
363
+ Wed: 3,
364
+ Thu: 4,
365
+ Fri: 5,
366
+ Sat: 6
367
+ };
368
+ function localWeekdayAndMinutes(nowMs, timezone) {
369
+ const parts = new Intl.DateTimeFormat("en-US", {
338
370
  hour: "2-digit",
371
+ hourCycle: "h23",
339
372
  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;
373
+ timeZone: timezone,
374
+ weekday: "short"
375
+ }).formatToParts(new Date(nowMs));
376
+ const value = (type) => parts.find((part) => part.type === type)?.value ?? "";
377
+ const weekday = weekdayIndex[value("weekday")];
378
+ if (weekday === void 0) throw new Error(`Could not read the weekday for timezone ${timezone}`);
379
+ return {
380
+ minutes: Number(value("hour")) % 24 * 60 + Number(value("minute")),
381
+ weekday
382
+ };
347
383
  }
348
- function getLocalDateWeekday(date) {
349
- return new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay();
384
+ /**
385
+ * Return whether a notification may be sent now. A window that crosses
386
+ * midnight belongs to the day on which it starts.
387
+ */
388
+ function isWithinNotificationSchedule(schedule, timezone, nowMs) {
389
+ if (!schedule.workingHoursOnly) return true;
390
+ const { minutes, weekday } = localWeekdayAndMinutes(nowMs, timezone);
391
+ const start = clockMinutes(schedule.start);
392
+ const end = clockMinutes(schedule.end);
393
+ if (start < end) return schedule.days.includes(weekday) && minutes >= start && minutes < end;
394
+ if (minutes >= start) return schedule.days.includes(weekday);
395
+ if (minutes < end) return schedule.days.includes((weekday + 6) % 7);
396
+ return false;
350
397
  }
351
- function getWeekStart(date) {
352
- return addDays(date, -((getLocalDateWeekday(date) + 6) % 7));
398
+ // src/chat/automations/task.ts
399
+ /**
400
+ * The work of an Automation run. An Automation runs either a written
401
+ * instruction or a skill. A skill can have context: what the Automation
402
+ * needs beyond the skill.
403
+ */
404
+ /** A skill name, in the form that skill frontmatter allows. */
405
+ const automationSkillNameSchema = z.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use a skill name, such as tpm.");
406
+ /** Text of an instruction or a context, trimmed and not empty. */
407
+ const automationTaskTextSchema = z.string().trim().min(1, "Write at least one word.").max(4e3);
408
+ /** Validate the stored task of either Automation kind. */
409
+ const automationTaskSchema = z.discriminatedUnion("kind", [z.object({
410
+ kind: z.literal("instruction"),
411
+ instruction: automationTaskTextSchema
412
+ }).strict(), z.object({
413
+ kind: z.literal("skill"),
414
+ skill: automationSkillNameSchema,
415
+ /** Absent when the skill needs nothing more. */
416
+ context: automationTaskTextSchema.optional()
417
+ }).strict()]);
418
+ /** Return the written text of a task: its instruction or its context. */
419
+ function automationTaskText(task) {
420
+ return task.kind === "instruction" ? task.instruction : task.context;
353
421
  }
354
422
  /**
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.
423
+ * Describe the work in one plain text for title fallback, title generation,
424
+ * and cards, so a skill-mode Automation shows its skill. Do not store it.
357
425
  */
358
- function isValidTimeZone(timezone) {
359
- try {
360
- new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
361
- return true;
362
- } catch {
363
- return false;
364
- }
426
+ function automationTaskDescription(task) {
427
+ if (task.kind === "instruction") return task.instruction;
428
+ return task.context ? `Run the ${task.skill} skill. ${task.context}` : `Run the ${task.skill} skill.`;
365
429
  }
366
- /** Resolve a UTC timestamp into calendar parts for a named time zone. */
367
- function getZonedDateTimeParts(timestampMs, timezone) {
368
- const parts = getFormatter(timezone).formatToParts(new Date(timestampMs));
369
- const values = new Map(parts.map((part) => [part.type, part.value]));
370
- const year = Number(values.get("year"));
371
- const month = Number(values.get("month"));
372
- const day = Number(values.get("day"));
373
- return {
374
- year,
375
- month,
376
- day,
377
- hour: normalizeHour(Number(values.get("hour"))),
378
- minute: Number(values.get("minute")),
379
- second: Number(values.get("second")),
380
- weekday: getLocalDateWeekday({
381
- year,
382
- month,
383
- day
384
- })
430
+ /** Return the `instruction` and `skill` columns of a task. One is null. */
431
+ function automationTaskColumns(task) {
432
+ return task.kind === "instruction" ? {
433
+ instruction: task.instruction,
434
+ skill: null
435
+ } : {
436
+ instruction: null,
437
+ skill: task.skill
385
438
  };
386
439
  }
387
- function getTimeZoneOffsetMs(timestampMs, timezone) {
388
- const parts = getZonedDateTimeParts(timestampMs, timezone);
389
- return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second) - timestampMs;
390
- }
391
- function localDateTimeToTimestampMs(args) {
392
- const localAsUtcMs = Date.UTC(args.date.year, args.date.month - 1, args.date.day, args.time.hour, args.time.minute, 0);
393
- const offsets = /* @__PURE__ */ new Set();
394
- for (const probeDeltaMs of [
395
- -1296e5,
396
- -432e5,
397
- 0,
398
- 432e5,
399
- 1296e5
400
- ]) offsets.add(getTimeZoneOffsetMs(localAsUtcMs + probeDeltaMs, args.timezone));
401
- const matches = [...offsets].map((offsetMs) => localAsUtcMs - offsetMs).filter((timestampMs) => {
402
- const parts = getZonedDateTimeParts(timestampMs, args.timezone);
403
- return parts.year === args.date.year && parts.month === args.date.month && parts.day === args.date.day && parts.hour === args.time.hour && parts.minute === args.time.minute;
404
- });
405
- if (matches.length === 0) return;
406
- return Math.min(...matches);
440
+ // src/chat/child-agents/result-event-type.ts
441
+ /** Event namespace of the messages between a parent and its child agents. */
442
+ const AGENT_EVENT_NAMESPACE = "junior";
443
+ const LEGACY_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
444
+ /** True when an Event type names a child result that an earlier release wrote. */
445
+ function isLegacyResultEventType(eventType) {
446
+ return eventType.startsWith(LEGACY_RESULT_EVENT_TYPE_PREFIX);
407
447
  }
408
- /** Resolve local time, rejecting DST gaps and choosing the earlier instant in a fold. */
409
- function resolveLocalScheduleAtMs(args) {
410
- const date = parseLocalDate(args.date);
411
- if (!date) return;
412
- return localDateTimeToTimestampMs({
413
- date,
414
- time: args.time,
415
- timezone: args.timezone
416
- });
448
+ /**
449
+ * Event type of an agent update: what a Conversation reports when a Turn
450
+ * ends, it waits on a person, or it stops. A parent gets it from its child
451
+ * agents, and a Watch on the Conversation gets the same Event.
452
+ */
453
+ const AGENT_UPDATE_EVENT_TYPE = "agent.update";
454
+ const LEGACY_AGENT_REPLY_EVENT_TYPE = "agent.reply";
455
+ /** True when an Event type names an agent update. */
456
+ function isAgentUpdateEventType(eventType) {
457
+ return eventType === "agent.update" || eventType === LEGACY_AGENT_REPLY_EVENT_TYPE;
417
458
  }
418
- function daysBetween(left, right) {
419
- return Math.floor((Date.UTC(right.year, right.month - 1, right.day) - Date.UTC(left.year, left.month - 1, left.day)) / 864e5);
459
+ /** Event type of a message that a child agent sends to its parent. */
460
+ const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
461
+ /** Event type of a message from another top-level agent. */
462
+ const TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE = "agent.top_level_message";
463
+ /** True when an Event type names a message that another agent sent. */
464
+ function isAgentMessageEventType(eventType) {
465
+ return eventType === "agent.message" || eventType === "agent.top_level_message";
420
466
  }
421
- function weeklyRecurrenceMatchesDate(date, start, recurrence) {
422
- if (compareDate(date, start) < 0) return false;
423
- return normalizeWeekdays(recurrence.weekdays).includes(getLocalDateWeekday(date)) && Math.floor(daysBetween(getWeekStart(start), getWeekStart(date)) / 7) % recurrence.interval === 0;
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.");
424
492
  }
425
- function greatestCommonDivisor(left, right) {
426
- let a = Math.abs(left);
427
- let b = Math.abs(right);
428
- while (b !== 0) [a, b] = [b, a % b];
429
- return a;
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.");
430
511
  }
431
- function findNextRunAtMs(args) {
432
- const start = parseLocalDate(args.recurrence.startDate);
433
- const interval = args.recurrence.interval;
434
- if (!start || !Number.isInteger(interval) || interval <= 0) return;
435
- const searchFrom = compareDate(args.searchFrom, start) < 0 ? start : args.searchFrom;
436
- if (args.recurrence.frequency === "daily") {
437
- const offsetDays = daysBetween(start, searchFrom);
438
- let candidateDate = addDays(start, Math.ceil(offsetDays / interval) * interval);
439
- const gregorianCycleDays = 146097;
440
- const candidateCount = gregorianCycleDays / greatestCommonDivisor(gregorianCycleDays, interval);
441
- for (let attempts = 0; attempts < candidateCount; attempts += 1) {
442
- const candidate = buildCandidate({
443
- date: candidateDate,
444
- recurrence: args.recurrence,
445
- timezone: args.timezone
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."
446
533
  });
447
- if (candidate !== void 0 && candidate > args.afterMs) return candidate;
448
- candidateDate = addDays(candidateDate, interval);
449
- }
450
- return;
451
- }
452
- if (args.recurrence.frequency === "weekly") {
453
- if (normalizeWeekdays(args.recurrence.weekdays).length === 0) return;
454
- let candidateDate = searchFrom;
455
- const gregorianCycleDays = 146097;
456
- const cadenceDays = interval * 7;
457
- const searchDays = gregorianCycleDays * cadenceDays / greatestCommonDivisor(gregorianCycleDays, cadenceDays);
458
- for (let attempts = 0; attempts < searchDays; attempts += 1) {
459
- if (weeklyRecurrenceMatchesDate(candidateDate, start, args.recurrence)) {
460
- const candidate = buildCandidate({
461
- date: candidateDate,
462
- recurrence: args.recurrence,
463
- timezone: args.timezone
464
- });
465
- if (candidate !== void 0 && candidate > args.afterMs) return candidate;
466
- }
467
- candidateDate = addDays(candidateDate, 1);
468
- }
469
- return;
470
- }
471
- if (args.recurrence.frequency === "monthly") {
472
- const startMonth = start.year * 12 + start.month - 1;
473
- const searchMonth = searchFrom.year * 12 + searchFrom.month - 1;
474
- let candidateMonth = startMonth + Math.ceil((searchMonth - startMonth) / interval) * interval;
475
- const gregorianCycleMonths = 4800;
476
- const candidateCount = gregorianCycleMonths / greatestCommonDivisor(gregorianCycleMonths, interval);
477
- for (let attempts = 0; attempts < candidateCount; attempts += 1) {
478
- const candidateDate = {
479
- year: Math.floor(candidateMonth / 12),
480
- month: candidateMonth % 12 + 1,
481
- day: args.recurrence.dayOfMonth ?? 0
482
- };
483
- if (compareDate(candidateDate, searchFrom) >= 0) {
484
- const candidate = buildCandidate({
485
- date: candidateDate,
486
- recurrence: args.recurrence,
487
- timezone: args.timezone
488
- });
489
- if (candidate !== void 0 && candidate > args.afterMs) return candidate;
490
- }
491
- candidateMonth += interval;
492
- }
493
- return;
494
- }
495
- let candidateYear = start.year + Math.ceil((searchFrom.year - start.year) / interval) * interval;
496
- const candidateCount = 400 / greatestCommonDivisor(400, interval);
497
- for (let attempts = 0; attempts < candidateCount; attempts += 1) {
498
- const candidateDate = {
499
- year: candidateYear,
500
- month: args.recurrence.month ?? 0,
501
- day: args.recurrence.dayOfMonth ?? 0
502
- };
503
- if (compareDate(candidateDate, searchFrom) >= 0) {
504
- const candidate = buildCandidate({
505
- date: candidateDate,
506
- recurrence: args.recurrence,
507
- timezone: args.timezone
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."
508
537
  });
509
- if (candidate !== void 0 && candidate > args.afterMs) return candidate;
510
538
  }
511
- candidateYear += interval;
512
- }
513
- }
514
- /** Compute the first recurring calendar occurrence strictly after a timestamp. */
515
- function getFirstRunAtMs(args) {
516
- return findNextRunAtMs({
517
- ...args,
518
- searchFrom: getLocalDate(args.afterMs, args.timezone)
519
539
  });
520
540
  }
521
- function compareDate(left, right) {
522
- return Date.UTC(left.year, left.month - 1, left.day) - Date.UTC(right.year, right.month - 1, right.day);
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;
523
565
  }
524
- function addDays(date, days) {
525
- const next = new Date(Date.UTC(date.year, date.month - 1, date.day + days));
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);
526
584
  return {
527
- year: next.getUTCFullYear(),
528
- month: next.getUTCMonth() + 1,
529
- day: next.getUTCDate()
585
+ requestId: answer.requestId,
586
+ values,
587
+ ...other ? { other } : void 0
530
588
  };
531
589
  }
532
- function daysInMonth(year, month) {
533
- return new Date(Date.UTC(year, month, 0)).getUTCDate();
534
- }
535
- function parseLocalDate(value) {
536
- const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
537
- if (!match) return;
538
- const year = Number(match[1]);
539
- const month = Number(match[2]);
540
- const day = Number(match[3]);
541
- if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day) || month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return;
542
- return {
543
- year,
544
- month,
545
- day
546
- };
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] ?? []);
547
597
  }
548
- function getLocalDate(timestampMs, timezone) {
549
- const parts = getZonedDateTimeParts(timestampMs, timezone);
550
- return {
551
- year: parts.year,
552
- month: parts.month,
553
- day: parts.day
554
- };
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;
555
601
  }
556
- function normalizeWeekdays(values) {
557
- return [...new Set((values ?? []).filter((value) => value >= 0 && value <= 6))].sort((a, b) => a - b);
602
+ function answerLine(text) {
603
+ return text.split("\n").map((line) => line.trim()).filter(Boolean).join("\n");
558
604
  }
559
- function buildCandidate(args) {
560
- return localDateTimeToTimestampMs({
561
- date: args.date,
562
- time: args.recurrence.time,
563
- timezone: args.timezone
564
- });
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");
565
620
  }
566
- /** Return the next fire time after a completed run, when the task recurs. */
567
- function getNextRunAtMs(task, scheduledForMs, afterMs = scheduledForMs) {
568
- if (task.schedule.kind !== "recurring") return;
569
- const recurrence = task.schedule.recurrence;
570
- if (!recurrence || !Number.isFinite(recurrence.interval) || recurrence.interval <= 0) return;
571
- const timezone = task.schedule.timezone;
572
- const afterDate = getLocalDate(afterMs, timezone);
573
- const nextScheduledDate = addDays(getLocalDate(scheduledForMs, timezone), 1);
574
- return findNextRunAtMs({
575
- afterMs,
576
- recurrence,
577
- searchFrom: compareDate(afterDate, nextScheduledDate) < 0 ? nextScheduledDate : afterDate,
578
- timezone
579
- });
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;
580
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
@@ -1105,10 +1218,9 @@ const conversationReadPositionSchema = z.object({ lastReadSeq: z.number().int().
1105
1218
  // src/api/schema/conversation-kind.ts
1106
1219
  /** Where a Conversation sits in its tree. See `TERMINOLOGY.md`. */
1107
1220
  const conversationKindSchema = z.enum([
1108
- "root",
1221
+ "thread",
1109
1222
  "automation",
1110
1223
  "lead",
1111
- "thread",
1112
1224
  "task"
1113
1225
  ]);
1114
1226
  // src/api/schema/conversation-tree-state.ts
@@ -1165,7 +1277,18 @@ const spaceSchema = z.object({
1165
1277
  updatedAt: z.iso.datetime(),
1166
1278
  archivedAt: z.iso.datetime().nullable(),
1167
1279
  memberCount: z.number().int().nonnegative(),
1168
- viewerIsMember: z.boolean()
1280
+ viewerIsMember: z.boolean(),
1281
+ /** The Lead, the Space's root Conversation. */
1282
+ leadConversationId: z.string().min(1),
1283
+ /**
1284
+ * The tree states of the Space's Conversations that are not archived,
1285
+ * rolled up for the viewer: the first that applies. List rows only.
1286
+ */
1287
+ treeState: conversationTreeStateSchema.optional(),
1288
+ /**
1289
+ * The latest Turn of one of those Conversations failed. List rows only.
1290
+ */
1291
+ latestTurnFailed: z.boolean().optional()
1169
1292
  }).strict();
1170
1293
  const spaceListSchema = z.object({ spaces: z.array(spaceSchema) }).strict();
1171
1294
  // src/chat/conversations/provenance.ts
@@ -1218,74 +1341,10 @@ function instructionActors(provenance) {
1218
1341
  }
1219
1342
  return actors;
1220
1343
  }
1221
- // src/chat/conversations/history-payload.ts
1222
- const messageFieldsSchema = z.record(z.string(), z.unknown());
1223
- const replacementEntrySchema = z.object({ item: z.string() }).passthrough();
1224
- /** Identify history events that store message fields as JSON strings. */
1225
- function isEncodedHistoryType(type) {
1226
- return type === "user_message" || type === "assistant_message" || type === "tool_result" || type === "system_message" || type === "handoff" || type === "compaction";
1227
- }
1228
- /** Encode agent history before SQL can change keys or string contents. */
1229
- function encodeHistoryPayload(data) {
1230
- const { type, ...payload } = data;
1231
- if (!isEncodedHistoryType(type)) return {
1232
- schemaVersion: 1,
1233
- payload
1234
- };
1235
- if (data.type === "handoff" || data.type === "compaction") return {
1236
- schemaVersion: 2,
1237
- payload: {
1238
- ...payload,
1239
- replacementHistory: data.replacementHistory.map(({ item, ...entry }) => ({
1240
- ...entry,
1241
- item: JSON.stringify(item)
1242
- }))
1243
- }
1244
- };
1245
- const { provenance, ...message } = payload;
1246
- return {
1247
- schemaVersion: 2,
1248
- payload: {
1249
- message: JSON.stringify(message),
1250
- provenance,
1251
- model: message["model"],
1252
- provider: message["provider"],
1253
- usage: message["usage"],
1254
- toolCallId: message["toolCallId"],
1255
- stopReason: message["stopReason"],
1256
- timestamp: message["timestamp"],
1257
- toolName: message["toolName"],
1258
- isError: message["isError"]
1259
- }
1260
- };
1261
- }
1262
- /** Decode stored history for validation by the conversation event schema. */
1263
- function decodeHistoryPayload(type, payload) {
1264
- const fields = messageFieldsSchema.parse(payload);
1265
- if (type === "handoff" || type === "compaction") return {
1266
- ...fields,
1267
- replacementHistory: z.array(replacementEntrySchema).parse(fields["replacementHistory"]).map(({ item, ...entry }) => {
1268
- const parsedItem = JSON.parse(item);
1269
- return {
1270
- ...entry,
1271
- item: parsedItem
1272
- };
1273
- })
1274
- };
1275
- const message = messageFieldsSchema.parse(JSON.parse(z.string().parse(fields["message"])));
1276
- if (fields["provenance"] !== void 0) message["provenance"] = fields["provenance"];
1277
- return message;
1278
- }
1279
- // src/chat/conversations/history.ts
1280
- /**
1281
- * Durable conversation event history port.
1282
- *
1283
- * Events append under the conversation lease in stable sequence order.
1284
- * Compaction replaces the active model history without rewriting prior
1285
- * events. Unsupported stored events remain readable as opaque facts,
1286
- * while malformed known events fail loudly. Provider-specific message fields
1287
- * are validated by the Pi adapter when it restores model context.
1288
- */
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
1289
1348
  const userMessageEventDataSchema = z.object({
1290
1349
  type: z.literal("user_message"),
1291
1350
  role: z.never().optional(),
@@ -1334,10 +1393,10 @@ const compactionDetailsSchema = z.object({
1334
1393
  retainedMessageCount: z.number().int().nonnegative(),
1335
1394
  summaryChars: z.number().int().nonnegative()
1336
1395
  }).strict();
1337
- const legacyModelProfileSchema = z.string().min(1).optional();
1396
+ const legacyModelProfileSchema$1 = z.string().min(1).optional();
1338
1397
  const historyReplacementEventDataSchema = z.object({
1339
1398
  type: z.literal("compaction"),
1340
- modelProfile: legacyModelProfileSchema,
1399
+ modelProfile: legacyModelProfileSchema$1,
1341
1400
  modelId: z.string().min(1),
1342
1401
  details: compactionDetailsSchema.optional(),
1343
1402
  costUsd: z.number().finite().nonnegative().optional(),
@@ -1346,18 +1405,168 @@ const historyReplacementEventDataSchema = z.object({
1346
1405
  }).strict();
1347
1406
  const legacyHandoffEventDataSchema = z.object({
1348
1407
  type: z.literal("handoff"),
1349
- modelProfile: legacyModelProfileSchema,
1408
+ modelProfile: legacyModelProfileSchema$1,
1350
1409
  modelId: z.string().min(1),
1351
1410
  reasoningLevel: z.string().min(1).optional(),
1352
1411
  triggeringToolCallId: z.string().min(1).optional(),
1353
1412
  summary: z.string().min(1).optional(),
1354
1413
  replacementHistory: replacementHistorySchema
1355
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
+ }
1356
1431
  /** Validate an event that intentionally replaces active model history. */
1357
1432
  const historyReplacementSchema = z.object({
1358
1433
  data: historyReplacementEventDataSchema,
1359
1434
  createdAtMs: z.number().finite()
1360
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
+ */
1361
1570
  const mcpProviderConnectedEventDataSchema = z.object({
1362
1571
  type: z.literal("mcp_provider_connected"),
1363
1572
  provider: z.string().min(1),
@@ -1576,6 +1785,7 @@ const subagentEndedEventDataSchema = z.object({
1576
1785
  ]),
1577
1786
  errorCode: z.string().min(1).optional()
1578
1787
  }).strict();
1788
+ const legacyModelProfileSchema = z.string().min(1).optional();
1579
1789
  const compactionRequestedEventDataSchema = z.object({
1580
1790
  type: z.literal("compaction_requested"),
1581
1791
  markSeq: z.number().int().nonnegative(),
@@ -1622,8 +1832,7 @@ const appendableConversationEventDataSchema = z.union([
1622
1832
  /** Strict event-data contract reused by the SQL row codec. */
1623
1833
  const conversationEventDataSchema = z.union([
1624
1834
  appendableConversationEventDataSchema,
1625
- historyReplacementEventDataSchema,
1626
- legacyHandoffEventDataSchema,
1835
+ historyReplacementDataSchema,
1627
1836
  legacyTurnRoutedEventDataSchema,
1628
1837
  unownedMcpProviderConnectedEventDataSchema
1629
1838
  ]);
@@ -1679,7 +1888,7 @@ const conversationEventEnvelopeSchema = z.object({
1679
1888
  const conversationEventSchema = z.union([conversationEventEnvelopeSchema.extend({
1680
1889
  schemaVersion: z.union([z.literal(1), z.literal(2)]),
1681
1890
  data: conversationEventDataSchema
1682
- }).refine((event) => event.schemaVersion === 1 || isEncodedHistoryType(event.data.type)), conversationEventEnvelopeSchema.extend({ data: unknownConversationEventDataSchema })]);
1891
+ }).refine((event) => event.schemaVersion === 1 || isAgentHistoryType(event.data.type)), conversationEventEnvelopeSchema.extend({ data: unknownConversationEventDataSchema })]);
1683
1892
  const storedConversationEventSchema = conversationEventEnvelopeSchema.extend({
1684
1893
  type: z.string().min(1),
1685
1894
  payload: z.unknown()
@@ -1694,10 +1903,10 @@ function decodeStoredConversationEvent(value) {
1694
1903
  const stored = storedConversationEventSchema.parse(value);
1695
1904
  const { type, payload, ...envelope } = stored;
1696
1905
  const knownType = knownConversationEventTypeSchema.safeParse(type).success;
1697
- if (stored.schemaVersion === 2 && isEncodedHistoryType(type)) return conversationEventSchema.parse({
1906
+ if (stored.schemaVersion === 2 && isAgentHistoryType(type)) return conversationEventSchema.parse({
1698
1907
  ...envelope,
1699
1908
  data: {
1700
- ...decodeHistoryPayload(type, payload),
1909
+ ...decodeAgentHistoryPayload(type, payload),
1701
1910
  type
1702
1911
  }
1703
1912
  });
@@ -1726,7 +1935,7 @@ const newConversationEventSchema = z.object({
1726
1935
  idempotencyKey: z.string().min(1).optional(),
1727
1936
  createdAtMs: z.number().finite()
1728
1937
  }).strict();
1729
- // src/chat/agent-invocations/agent-types.ts
1938
+ // src/chat/child-agents/agent-types.ts
1730
1939
  /**
1731
1940
  * Child agent types. A type is plain data: when to pick it and what the child
1732
1941
  * reads with its task. Runtime code reads only these fields, never a type
@@ -2037,8 +2246,8 @@ const conversationReportMessageEventDataSchema = z.object({
2037
2246
  actorIdentity: actorIdentitySchema.optional(),
2038
2247
  /** Identity id of the author. Detail `authors` maps it to the person. */
2039
2248
  actorIdentityId: z.string().min(1).optional(),
2040
- /** Set on input that an earlier release's agent wrote, not a person. */
2041
- agentInvocationId: z.string().min(1).optional(),
2249
+ /** Set on input that a parent agent wrote, not a person. */
2250
+ fromParentAgent: z.literal(true).optional(),
2042
2251
  eventType: z.string().min(1).optional(),
2043
2252
  /** Namespace of the first Event, such as `github`. */
2044
2253
  eventNamespace: z.string().min(1).optional(),
@@ -2092,9 +2301,7 @@ const conversationReportToolCallSchema = z.object({
2092
2301
  startedAt: z.string().datetime().optional(),
2093
2302
  startedSeq: z.number().int().nonnegative().optional(),
2094
2303
  input: z.unknown().optional(),
2095
- output: z.unknown().optional(),
2096
- /** The Conversation that a completed `startConversation` call started. */
2097
- startedConversationId: z.string().min(1).optional()
2304
+ output: z.unknown().optional()
2098
2305
  }).strict().superRefine((call, context) => {
2099
2306
  if (call.startedAt === void 0 !== (call.startedSeq === void 0)) context.addIssue({
2100
2307
  code: "custom",
@@ -2425,6 +2632,10 @@ const conversationDetailReportSchema = conversationSummaryReportSchema.extend({
2425
2632
  canFork: z.boolean().optional(),
2426
2633
  /** The viewer can move this dashboard conversation to a Slack thread. */
2427
2634
  canContinueInSlack: z.literal(true).optional(),
2635
+ /** The viewer can Invite a person to this conversation. */
2636
+ canInvite: z.literal(true).optional(),
2637
+ /** Leave removes the viewer from this private conversation's access. */
2638
+ leaveEndsAccess: z.literal(true).optional(),
2428
2639
  /**
2429
2640
  * Event Turn replies stay out of the Location. Set only for a root with
2430
2641
  * a Location, when the viewer is a participant, who can change it.
@@ -2827,193 +3038,24 @@ const automationEventCatalogSchema = z.array(z.object({
2827
3038
  }).strict());
2828
3039
  const automationScheduleIntentSchema = scheduleIntentSchema;
2829
3040
  const automationSchedulePreviewSchema = scheduledAutomationSchema.pick({ schedule: true }).extend({ nextRunAtMs: z.number() }).strict();
2830
- // src/api/schema/response.ts
2831
- /** Stable error body returned by Junior-owned REST endpoints. */
2832
- const apiErrorSchema = z.object({ error: z.string().min(1) }).strict();
2833
- /**
2834
- * Carries a content token in both directions. A custom header, not `ETag` /
2835
- * `If-None-Match`: the Vercel CDN removes `If-None-Match` before it calls the
2836
- * function, with every `Cache-Control` value, and no setting stops this. The
2837
- * CDN then answers a match with a 304 only after the function built the full
2838
- * response, so the read is not saved and the 304 does not show in app
2839
- * telemetry. A probe deployment confirmed this for `private, no-cache`,
2840
- * `no-cache`, `private, no-store`, `private, max-age=0, must-revalidate`, and
2841
- * no header. See
2842
- * https://vercel.com/docs/manage-cdn-usage#optimizing-fast-origin-transfer.
2843
- * A read that sends the token of the copy it holds gets an empty 304 while
2844
- * the content is unchanged.
2845
- */
2846
- const CONTENT_VERSION_HEADER = "x-junior-content-version";
2847
- // src/chat/notifications/schedule.ts
2848
- /**
2849
- * Notification hours for one user.
2850
- *
2851
- * This module imports only zod and the browser-safe cadence helpers, so the
2852
- * dashboard client bundle can use it.
2853
- */
2854
- const clockTimePattern = /^([01]\d|2[0-3]):[0-5]\d$/;
2855
- /** Saved notification hours. Weekdays use 0 for Sunday, like `Date#getDay`. */
2856
- const notificationScheduleSchema = z.object({
2857
- /**
2858
- * Follow the linked Slack user's notification schedule. The fields below
2859
- * apply only when Junior cannot read it. Absent means on.
2860
- */
2861
- followSlack: z.boolean().optional(),
2862
- /** When false, Junior sends push notifications at any time. */
2863
- workingHoursOnly: z.boolean(),
2864
- 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." }),
2865
- /** Local start time, `HH:MM`. */
2866
- start: z.string().regex(clockTimePattern),
2867
- /** Local end time, `HH:MM`. An end before the start crosses midnight. */
2868
- end: z.string().regex(clockTimePattern),
2869
- /** IANA timezone set by the user. Absent means the profile timezone. */
2870
- timezone: z.string().min(1).max(64).refine(isValidTimeZone, { message: "Unknown timezone." }).optional()
2871
- }).strict().refine((schedule) => schedule.start !== schedule.end, {
2872
- message: "Start and end must differ.",
2873
- path: ["end"]
2874
- });
2875
- /**
2876
- * Default when a user has not saved a schedule: follow Slack, else
2877
- * 09:00–18:00, Mon–Fri.
2878
- */
2879
- const DEFAULT_NOTIFICATION_SCHEDULE = {
2880
- followSlack: true,
2881
- workingHoursOnly: true,
2882
- days: [
2883
- 1,
2884
- 2,
2885
- 3,
2886
- 4,
2887
- 5
2888
- ],
2889
- start: "09:00",
2890
- end: "18:00"
2891
- };
2892
- function clockMinutes(value) {
2893
- const [hours, minutes] = value.split(":").map(Number);
2894
- return hours * 60 + minutes;
2895
- }
2896
- const weekdayIndex = {
2897
- Sun: 0,
2898
- Mon: 1,
2899
- Tue: 2,
2900
- Wed: 3,
2901
- Thu: 4,
2902
- Fri: 5,
2903
- Sat: 6
2904
- };
2905
- function localWeekdayAndMinutes(nowMs, timezone) {
2906
- const parts = new Intl.DateTimeFormat("en-US", {
2907
- hour: "2-digit",
2908
- hourCycle: "h23",
2909
- minute: "2-digit",
2910
- timeZone: timezone,
2911
- weekday: "short"
2912
- }).formatToParts(new Date(nowMs));
2913
- const value = (type) => parts.find((part) => part.type === type)?.value ?? "";
2914
- const weekday = weekdayIndex[value("weekday")];
2915
- if (weekday === void 0) throw new Error(`Could not read the weekday for timezone ${timezone}`);
2916
- return {
2917
- minutes: Number(value("hour")) % 24 * 60 + Number(value("minute")),
2918
- weekday
2919
- };
2920
- }
2921
- /**
2922
- * Return whether a notification may be sent now. A window that crosses
2923
- * midnight belongs to the day on which it starts.
2924
- */
2925
- function isWithinNotificationSchedule(schedule, timezone, nowMs) {
2926
- if (!schedule.workingHoursOnly) return true;
2927
- const { minutes, weekday } = localWeekdayAndMinutes(nowMs, timezone);
2928
- const start = clockMinutes(schedule.start);
2929
- const end = clockMinutes(schedule.end);
2930
- if (start < end) return schedule.days.includes(weekday) && minutes >= start && minutes < end;
2931
- if (minutes >= start) return schedule.days.includes(weekday);
2932
- if (minutes < end) return schedule.days.includes((weekday + 6) % 7);
2933
- return false;
2934
- }
2935
- // src/chat/attachments/media.ts
2936
- const INPUT_IMAGE_TYPES = [
2937
- "image/png",
2938
- "image/jpeg",
2939
- "image/gif",
2940
- "image/webp"
2941
- ];
2942
- /** Video types that browsers play in a `<video>` element. */
2943
- const INLINE_VIDEO_TYPES = ["video/mp4", "video/webm"];
2944
- /** Leading bytes of each accepted image type. `null` matches any byte. */
2945
- const IMAGE_SIGNATURES = [
2946
- {
2947
- mediaType: "image/png",
2948
- bytes: [
2949
- 137,
2950
- 80,
2951
- 78,
2952
- 71,
2953
- 13,
2954
- 10,
2955
- 26,
2956
- 10
2957
- ]
2958
- },
2959
- {
2960
- mediaType: "image/jpeg",
2961
- bytes: [
2962
- 255,
2963
- 216,
2964
- 255
2965
- ]
2966
- },
2967
- {
2968
- mediaType: "image/gif",
2969
- bytes: [
2970
- 71,
2971
- 73,
2972
- 70,
2973
- 56,
2974
- 55,
2975
- 97
2976
- ]
2977
- },
2978
- {
2979
- mediaType: "image/gif",
2980
- bytes: [
2981
- 71,
2982
- 73,
2983
- 70,
2984
- 56,
2985
- 57,
2986
- 97
2987
- ]
2988
- },
2989
- {
2990
- mediaType: "image/webp",
2991
- bytes: [
2992
- 82,
2993
- 73,
2994
- 70,
2995
- 70,
2996
- null,
2997
- null,
2998
- null,
2999
- null,
3000
- 87,
3001
- 69,
3002
- 66,
3003
- 80
3004
- ]
3005
- }
3041
+ // src/chat/todos/types.ts
3042
+ /** Statuses of a To-do. `done` and `dropped` close it. */
3043
+ const TODO_STATUSES = [
3044
+ "open",
3045
+ "in_progress",
3046
+ "done",
3047
+ "dropped"
3006
3048
  ];
3007
- /**
3008
- * Detect an accepted image type from file bytes. Use this instead of a file
3009
- * name or declared content type, which can be wrong.
3010
- */
3011
- function detectImageMediaType(data) {
3012
- return IMAGE_SIGNATURES.find(({ bytes }) => data.length >= bytes.length && bytes.every((byte, index) => byte === null || data[index] === byte))?.mediaType;
3013
- }
3014
- /** Report whether a media type is a raster image accepted by vision models. */
3015
- function isVisionImageMediaType(mediaType) {
3016
- const normalized = mediaType.split(";", 1)[0]?.trim().toLowerCase();
3017
- return normalized ? INPUT_IMAGE_TYPES.some((type) => type === normalized) : false;
3049
+ /** Statuses of a To-do that is still work to do. */
3050
+ const OPEN_TODO_STATUSES = ["open", "in_progress"];
3051
+ /** Whether a To-do with this status is still work to do. */
3052
+ function isOpenTodoStatus(status) {
3053
+ return status === "open" || status === "in_progress";
3018
3054
  }
3019
- 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 };
3055
+ /** Name of the To-do registration, which namespaces its tools. */
3056
+ const TODOS_REGISTRATION_NAME = "todos";
3057
+ /** Model-facing tool that changes the To-dos, as the host names it. */
3058
+ const UPDATE_TODOS_TOOL_NAME = `${TODOS_REGISTRATION_NAME}_updateTodos`;
3059
+ /** Assignee text for the list's own agent, in tool results and blocks. */
3060
+ const SELF_TODO_ASSIGNEE = "self";
3061
+ export { activityPreviewText as $, automationTitleSchema as $t, automationVersionSchema as A, isLegacyResultEventType as An, spaceListQuerySchema as At, conversationDetailQuerySchema as B, getNextRunAtMs as Bn, annotationCard as Bt, automationScheduleIntentSchema as C, userInputRequestSchema as Cn, instructionActors as Ct, automationVersionActivateSchema as D, TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE as Dn, SPACE_NAME_MAX_CHARS as Dt, automationUpdateSchema as E, AGENT_UPDATE_EVENT_TYPE as En, SPACE_DESCRIPTION_MAX_CHARS as Et, actorIdentitySchema as F, automationTaskText as Fn, spaceVisibilitySchema as Ft, conversationParamsSchema as G, usageSchema as Gn, resolveMessageCards as Gt, conversationEventHistorySchema as H, isValidTimeZone as Hn, messageCardText as Ht, conversationActivityPreviewSchema as I, DEFAULT_NOTIFICATION_SCHEDULE as In, updateSpaceBodySchema as It, conversationReportMessageEventSchema as J, inputFileSchema as Jt, conversationReportEventDataSchema as K, gatewayOnlyProviders as Kn, MAX_ATTACHMENT_BYTES as Kt, conversationAttachmentParamsSchema as L, isWithinNotificationSchedule as Ln, conversationTreeStateSchema as Lt, scheduledAutomationSummarySchema as M, automationTaskColumns as Mn, spaceParamsSchema as Mt, CONVERSATION_DETAIL_VERSION_HEADER as N, automationTaskDescription as Nn, spaceRefSchema as Nt, automationVersionListSchema as O, isAgentMessageEventType as On, archiveSpaceBodySchema as Ot, CONVERSATION_VERSION_HEADER as P, automationTaskSchema as Pn, spaceSchema as Pt, conversationUsageSchema as Q, automationInstructionToolSchema as Qt, conversationAttachmentQuerySchema as R, notificationScheduleSchema as Rn, conversationReadPositionSchema as Rt, automationRunWindowsSchema as S, userInputQuestionSchema as Sn, contextProvenance as St, automationSummarySchema as T, AGENT_MESSAGE_EVENT_TYPE as Tn, sameActorIdentity as Tt, conversationEventPageSchema as U, CONTENT_VERSION_HEADER as Un, readMessageCardRefs as Ut, conversationDetailReportSchema as V, getZonedDateTimeParts as Vn, messageCardRef as Vt, conversationEventsQuerySchema as W, apiErrorSchema 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, automationSkillNameSchema as jn, spaceListSchema as jt, automationVersionParamsSchema as k, isAgentUpdateEventType 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, AGENT_EVENT_NAMESPACE 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, getFirstRunAtMs as zn, inboxItemChangeRecordSchema as zt };