@sentry/junior 0.310.0 → 0.312.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adapter-context-BhKpjpGD.js → adapter-context-BRjEWRy1.js} +2 -2
- package/dist/adapter-iIq7ihf7.js +259 -0
- package/dist/{admin-tgZEZAk2.js → admin-DhInw5K9.js} +1 -2
- package/dist/{agent-runner-D9cvNlQl.js → agent-runner-C9iDurwX.js} +6507 -7721
- package/dist/api/schema.d.ts +2 -2
- package/dist/api/schema.js +7 -6
- package/dist/api.d.ts +21 -3
- package/dist/api.js +1625 -535
- package/dist/{app-B_7Wn0en.d.ts → app-DRFrC8Mw.d.ts} +14 -10
- package/dist/app.d.ts +2 -2
- package/dist/app.js +454 -994
- package/dist/{background-compaction-queue-BGHqkhkY.js → background-compaction-queue-DrKi7w3d.js} +10 -85
- package/dist/callback-mFlTUWWx.js +75 -0
- package/dist/{catalog-runtime-BxwzbLKY.js → catalog-runtime-D7xapBAX.js} +1 -1
- package/dist/channel-access-CJGfNTdn.js +221 -0
- package/dist/child-message-DcsritGf.js +179 -0
- package/dist/cli/chat.js +18 -19
- package/dist/cli/check.js +23 -29
- package/dist/cli/init.js +1 -7
- package/dist/cli/main.js +3 -7
- package/dist/cli/plugins.js +8 -7
- package/dist/cli/run.d.ts +1 -2
- package/dist/cli/run.js +1 -2
- package/dist/cli/snapshot-create.js +5 -5
- package/dist/cli/upgrade.d.ts +1 -1
- package/dist/cli/upgrade.js +3 -3
- package/dist/{config-Dkt2Le2b.js → config-kXB2Y5tl.js} +294 -28
- package/dist/{continue-in-slack-BWVwePKD.js → continue-in-slack-O6pV5004.js} +7 -7
- package/dist/{conversation-feed-Ci6YD1N-.js → conversation-feed-uNOv_x68.js} +87 -24
- package/dist/{conversation-privacy-C39g8BY4.js → conversation-privacy-L4ja1_W6.js} +1 -1
- package/dist/{conversation-turn-CBlZIH02.js → conversation-turn-CeLbHqdw.js} +56 -49
- package/dist/{credential-sync-vGnrB0BY.js → credential-sync-I8VBGk05.js} +16 -16
- package/dist/{projection-jZSlEAXG.js → credentialed-Cb6E2phL.js} +16268 -16821
- package/dist/{db-B4Hjxr-u.d.ts → db-BbC5stfa.d.ts} +13 -6
- package/dist/{db-CFZggNoy.js → db-LAyyX8tk.js} +1698 -1046
- package/dist/{executor-BPkZDx5-.js → executor-SCub-fAq.js} +552 -181
- package/dist/{html-2r2KmLwi.js → html-BCZ3Xtb_.js} +6 -6
- package/dist/{session-stop-BfY4rhJs.js → ingest-BDf3D50j.js} +2134 -2553
- package/dist/{install-C-oE6C_u.js → install-DCFJFkC0.js} +2 -2
- package/dist/instrumentation.js +4 -4
- package/dist/{lineage-CsvrEFQe.js → lineage-B_m-4TJw.js} +2 -2
- package/dist/{stop-DYzjRf2U.js → list-CN2QA2R9.js} +1656 -685
- package/dist/{logging-D5gkyvnK.js → logging-dQ9ZRGQ8.js} +47 -9
- package/dist/media-CYm1QD8T.js +2356 -0
- package/dist/{message-DwvJ-I3w.js → message-DSXGj1hM.js} +19 -29
- package/dist/{model-input-MAq2881y.js → model-input--TrP9hYV.js} +3 -3
- package/dist/nitro.d.ts +1 -1
- package/dist/nitro.js +4 -3
- package/dist/{oauth-callback-server-DIF6Li06.js → oauth-callback-server-DHCZC6B4.js} +2 -2
- package/dist/{oauth-relay-DPE-wrwO.js → oauth-relay-pPMGnDZt.js} +1 -1
- package/dist/{registry-BBkWFCl8.js → registry-CZOzddwu.js} +5 -8
- package/dist/{resolve-B38MkHXE.js → resolve-cKOQ14Dh.js} +3 -3
- package/dist/{result-BaqSZcJb.js → result-DcvEOe1r.js} +119 -93
- package/dist/result-event-type-BdIJuZxg.js +48 -0
- package/dist/rule-DAxQY-1h.js +20 -0
- package/dist/{runner-11h8PrHh.js → runner-DBfUW44l.js} +14 -16
- package/dist/{sandbox-egress-signals-CTcACAtJ.js → sandbox-egress-signals-BVF_xAm1.js} +1 -1
- package/dist/{schema-DriSvB40.d.ts → schema-BEHKxr4I.d.ts} +861 -298
- package/dist/{schema-obw5jvR4.js → schema-Bk9Nm2E8.js} +344 -153
- package/dist/{service-account-Bx93N1n1.js → service-account-CVYsFjty.js} +3 -3
- package/dist/{service-account-Zc5bUcIJ.js → service-account-Ts4ulcrV.js} +68 -68
- package/dist/{skills-C8Npu5zO.js → skills-VTnhAJWm.js} +2 -2
- package/dist/{slack-conversation-unfurl-DlRVA02H.js → slack-conversation-unfurl-fuLnF1jE.js} +9 -11
- package/dist/{spawn-CXr58R0x.js → spawn-vxAarlX5.js} +6 -6
- package/dist/start-conversation-CEn2KH1A.js +941 -0
- package/dist/{state-CGrGVeQC.js → state-C1P3_Ywk.js} +4 -4
- package/dist/statuses-_cRJHXK7.js +150 -0
- package/dist/store-DFZaN-Ix.js +492 -0
- package/dist/task-queue-Cx4Lmjyk.js +90 -0
- package/dist/task-runner-CbTwFA6k.js +1432 -0
- package/dist/{thread-context-Dyj1KWaY.js → thread-context-BkAZDTX2.js} +13 -11
- package/dist/thread-state-DhPndWi1.js +5625 -0
- package/dist/{validation-DxVNIxA0.js → validation-nIzMtAVJ.js} +1 -1
- package/dist/{task-queue-CaZffYaH.js → vercel-queue-hW90XzbG.js} +93 -172
- package/dist/{version-Cr7Z71yG.js → version-Brbtz4Qf.js} +1 -1
- package/dist/version.js +1 -1
- package/dist/{warmup-C6LOZ2d2.js → warmup-BDA5myRK.js} +5832 -4567
- package/dist/web-message-id-C6P83ans.js +10 -0
- package/dist/{worker-CUBtu1Li.js → worker-D63RcaVD.js} +20 -8
- package/migrations/0126_artifact_drop_public.sql +8 -0
- package/migrations/0127_artifact_path.sql +4 -0
- package/migrations/0128_artifact_path_index.sql +1 -0
- package/migrations/0129_review_item_answered_index.sql +1 -0
- package/migrations/0130_review_item_status_index.sql +1 -0
- package/migrations/0131_brief_outcome_status.sql +1 -0
- package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
- package/migrations/0133_brief_created_at_index.sql +1 -0
- package/migrations/0134_slack_person_search_index.sql +1 -0
- package/migrations/0135_code_change_size.sql +3 -0
- package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
- package/migrations/0137_inbox_snoozes.sql +27 -0
- package/migrations/0138_code_change_search_index.sql +2 -0
- package/migrations/0139_review_item_owner.sql +22 -0
- package/migrations/0140_review_item_owner_index.sql +1 -0
- package/migrations/0141_memory_core_adoption.sql +89 -0
- package/migrations/0142_memory_core_indexes.sql +17 -0
- package/migrations/0143_todos.sql +14 -0
- package/migrations/0144_inbox_items.sql +32 -0
- package/migrations/0145_todo_changed_by_agent.sql +1 -0
- package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
- package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
- package/migrations/0148_authorization_request_index.sql +1 -0
- package/migrations/0149_conversation_metadata.sql +10 -0
- package/migrations/0150_conversation_metadata_fill.sql +39 -0
- package/migrations/0151_conversation_search_index.sql +1 -0
- package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
- package/migrations/0153_artifact_expiry.sql +1 -0
- package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
- package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
- package/migrations/0156_conversation_kind_lead.sql +6 -0
- package/migrations/0157_conversation_lead_actor_index.sql +1 -0
- package/migrations/meta/0126_snapshot.json +5488 -0
- package/migrations/meta/0127_snapshot.json +5519 -0
- package/migrations/meta/0128_snapshot.json +5519 -0
- package/migrations/meta/0129_snapshot.json +5547 -0
- package/migrations/meta/0130_snapshot.json +5563 -0
- package/migrations/meta/0131_snapshot.json +5569 -0
- package/migrations/meta/0132_snapshot.json +5569 -0
- package/migrations/meta/0133_snapshot.json +5590 -0
- package/migrations/meta/0134_snapshot.json +5606 -0
- package/migrations/meta/0135_snapshot.json +5624 -0
- package/migrations/meta/0136_snapshot.json +5624 -0
- package/migrations/meta/0137_snapshot.json +5864 -0
- package/migrations/meta/0138_snapshot.json +5894 -0
- package/migrations/meta/0139_snapshot.json +5898 -0
- package/migrations/meta/0140_snapshot.json +5919 -0
- package/migrations/meta/0141_snapshot.json +6429 -0
- package/migrations/meta/0142_snapshot.json +6457 -0
- package/migrations/meta/0143_snapshot.json +6434 -0
- package/migrations/meta/0144_snapshot.json +6434 -0
- package/migrations/meta/0145_snapshot.json +6440 -0
- package/migrations/meta/0146_snapshot.json +6446 -0
- package/migrations/meta/0147_snapshot.json +6452 -0
- package/migrations/meta/0148_snapshot.json +6474 -0
- package/migrations/meta/0149_snapshot.json +6490 -0
- package/migrations/meta/0150_snapshot.json +6490 -0
- package/migrations/meta/0151_snapshot.json +6505 -0
- package/migrations/meta/0152_snapshot.json +6505 -0
- package/migrations/meta/0153_snapshot.json +6511 -0
- package/migrations/meta/0154_snapshot.json +6533 -0
- package/migrations/meta/0155_snapshot.json +6511 -0
- package/migrations/meta/0156_snapshot.json +6511 -0
- package/migrations/meta/0157_snapshot.json +6527 -0
- package/migrations/meta/_journal.json +224 -0
- package/package.json +7 -8
- package/skills/design-automation-skill/SKILL.md +108 -0
- package/dist/briefs-DKxkoruh.js +0 -395
- package/dist/conversation-M9KZ5JxF.js +0 -1024
- package/dist/prompt-CaMyeCpA.js +0 -910
- package/dist/schedule-DWxZ3kja.js +0 -1146
- package/dist/store-D4FQ1Nml.js +0 -335
- package/dist/task-runner-Dm7BHbGp.js +0 -287
- package/dist/turn-session-routing-CD0BRCex.js +0 -263
- package/dist/turn-user-message-9IxeEv5v.js +0 -364
- package/dist/users-CaUAYMb3.js +0 -181
- package/dist/viewer-AHldghAD.js +0 -212
- package/dist/web-message-id-BT8Mg8LL.js +0 -418
|
@@ -0,0 +1,2356 @@
|
|
|
1
|
+
import { a as conversationTurnFailureReasonSchema, h as usageSchema, i as conversationTurnFailureCodeSchema } from "./history-CYstOMKX.js";
|
|
2
|
+
import * as z from "zod";
|
|
3
|
+
import { actorUserIdSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, conversationSidebarAnnotationSchema, destinationVisibilitySchema, eventMatchFieldsSchema, eventMatchSchema, eventReachSchema, eventTypeSchema, objectFactFields, objectTypeSchema, pluginEventTypeSchema, slackDestinationSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
|
|
4
|
+
// src/chat/automations/task.ts
|
|
5
|
+
/**
|
|
6
|
+
* The work of an Automation run. An Automation runs either a written
|
|
7
|
+
* instruction or a skill. A skill can have context: what the Automation
|
|
8
|
+
* needs beyond the skill.
|
|
9
|
+
*/
|
|
10
|
+
/** A skill name, in the form that skill frontmatter allows. */
|
|
11
|
+
const automationSkillNameSchema = z.string().max(64).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use a skill name, such as tpm.");
|
|
12
|
+
/** Text of an instruction or a context, trimmed and not empty. */
|
|
13
|
+
const automationTaskTextSchema = z.string().trim().min(1, "Write at least one word.").max(4e3);
|
|
14
|
+
/** Validate the stored task of either Automation kind. */
|
|
15
|
+
const automationTaskSchema = z.discriminatedUnion("kind", [z.object({
|
|
16
|
+
kind: z.literal("instruction"),
|
|
17
|
+
instruction: automationTaskTextSchema
|
|
18
|
+
}).strict(), z.object({
|
|
19
|
+
kind: z.literal("skill"),
|
|
20
|
+
skill: automationSkillNameSchema,
|
|
21
|
+
/** Absent when the skill needs nothing more. */
|
|
22
|
+
context: automationTaskTextSchema.optional()
|
|
23
|
+
}).strict()]);
|
|
24
|
+
/** Return the written text of a task: its instruction or its context. */
|
|
25
|
+
function automationTaskText(task) {
|
|
26
|
+
return task.kind === "instruction" ? task.instruction : task.context;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Describe the work in one plain text for title fallback, title generation,
|
|
30
|
+
* and cards, so a skill-mode Automation shows its skill. Do not store it.
|
|
31
|
+
*/
|
|
32
|
+
function automationTaskDescription(task) {
|
|
33
|
+
if (task.kind === "instruction") return task.instruction;
|
|
34
|
+
return task.context ? `Run the ${task.skill} skill. ${task.context}` : `Run the ${task.skill} skill.`;
|
|
35
|
+
}
|
|
36
|
+
/** Return the `instruction` and `skill` columns of a task. One is null. */
|
|
37
|
+
function automationTaskColumns(task) {
|
|
38
|
+
return task.kind === "instruction" ? {
|
|
39
|
+
instruction: task.instruction,
|
|
40
|
+
skill: null
|
|
41
|
+
} : {
|
|
42
|
+
instruction: null,
|
|
43
|
+
skill: task.skill
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
// src/chat/inbox-items/user-input-request.ts
|
|
47
|
+
const USER_INPUT_LIMITS = {
|
|
48
|
+
maxButtonOptions: 5,
|
|
49
|
+
maxDescriptionChars: 200,
|
|
50
|
+
maxFields: 4,
|
|
51
|
+
maxLabelChars: 75,
|
|
52
|
+
maxOptions: 10,
|
|
53
|
+
maxTextChars: 3e3,
|
|
54
|
+
maxQuestionChars: 3e3,
|
|
55
|
+
minOptions: 2
|
|
56
|
+
};
|
|
57
|
+
const labelSchema = z.string().trim().min(1).max(USER_INPUT_LIMITS.maxLabelChars);
|
|
58
|
+
const descriptionSchema = z.string().trim().min(1).max(USER_INPUT_LIMITS.maxDescriptionChars).optional();
|
|
59
|
+
const optionSchema = z.object({
|
|
60
|
+
label: labelSchema.describe("Short choice text, such as `Accept` or `Decline`. The answer uses this exact text."),
|
|
61
|
+
description: descriptionSchema.describe("Optional short note about what this choice does."),
|
|
62
|
+
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.")
|
|
63
|
+
});
|
|
64
|
+
const fieldBase = {
|
|
65
|
+
id: z.string().regex(/^[a-z][a-z0-9_]{0,31}$/).describe("Stable key for this field, such as `approach`."),
|
|
66
|
+
label: labelSchema.describe("Short field name, such as `Approach`."),
|
|
67
|
+
description: descriptionSchema.describe("Optional short help text for this field.")
|
|
68
|
+
};
|
|
69
|
+
function optionsSchema(minOptions) {
|
|
70
|
+
return z.array(optionSchema).min(minOptions).max(USER_INPUT_LIMITS.maxOptions).describe("Choices in display order.");
|
|
71
|
+
}
|
|
72
|
+
function requestSchema(minOptions) {
|
|
73
|
+
const userInputFieldSchema = z.discriminatedUnion("kind", [
|
|
74
|
+
z.object({
|
|
75
|
+
...fieldBase,
|
|
76
|
+
kind: z.literal("choice").describe("The person picks one option."),
|
|
77
|
+
options: optionsSchema(minOptions)
|
|
78
|
+
}),
|
|
79
|
+
z.object({
|
|
80
|
+
...fieldBase,
|
|
81
|
+
kind: z.literal("multi_choice").describe("The person picks any number of options."),
|
|
82
|
+
options: optionsSchema(minOptions)
|
|
83
|
+
}),
|
|
84
|
+
z.object({
|
|
85
|
+
...fieldBase,
|
|
86
|
+
kind: z.literal("text").describe("The person types a short answer.")
|
|
87
|
+
})
|
|
88
|
+
]);
|
|
89
|
+
return z.object({
|
|
90
|
+
question: z.string().trim().min(1).max(USER_INPUT_LIMITS.maxQuestionChars).describe("The question, in markdown. Include the facts the person needs to decide."),
|
|
91
|
+
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.")
|
|
92
|
+
}).superRefine((request, context) => {
|
|
93
|
+
const ids = /* @__PURE__ */ new Set();
|
|
94
|
+
for (const field of request.fields) {
|
|
95
|
+
if (ids.has(field.id)) context.addIssue({
|
|
96
|
+
code: "custom",
|
|
97
|
+
message: "Each field needs a different id."
|
|
98
|
+
});
|
|
99
|
+
ids.add(field.id);
|
|
100
|
+
if (field.kind === "text") continue;
|
|
101
|
+
const labels = field.options.map((option) => option.label.toLowerCase());
|
|
102
|
+
if (new Set(labels).size !== labels.length) context.addIssue({
|
|
103
|
+
code: "custom",
|
|
104
|
+
message: "Each choice of a field needs a different label."
|
|
105
|
+
});
|
|
106
|
+
if (field.kind === "choice" && field.options.filter((option) => option.recommended).length > 1) context.addIssue({
|
|
107
|
+
code: "custom",
|
|
108
|
+
message: "A `choice` field can recommend only one option."
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** A request that an agent writes. Each choice field has two options or more. */
|
|
114
|
+
const userInputRequestSchema = requestSchema(USER_INPUT_LIMITS.minOptions);
|
|
115
|
+
/**
|
|
116
|
+
* A saved request. A plugin item can have one choice, such as Resume, so a
|
|
117
|
+
* saved choice field can have one option. Agents still need two.
|
|
118
|
+
*/
|
|
119
|
+
const savedUserInputRequestSchema = requestSchema(1);
|
|
120
|
+
/**
|
|
121
|
+
* Label and help text of the free-text input that every form adds after the
|
|
122
|
+
* fields. The text goes with the picked answers and does not replace them, so
|
|
123
|
+
* every surface says that in the same words.
|
|
124
|
+
*/
|
|
125
|
+
const USER_INPUT_NOTE = {
|
|
126
|
+
label: "Anything else?",
|
|
127
|
+
description: "Optional. This note is sent together with your answers above."
|
|
128
|
+
};
|
|
129
|
+
/**
|
|
130
|
+
* Return the single choice field of a request that a surface can show as
|
|
131
|
+
* one row of buttons, where one click is the whole answer.
|
|
132
|
+
*/
|
|
133
|
+
function buttonUserInputField(request) {
|
|
134
|
+
const [field, ...rest] = request.fields;
|
|
135
|
+
if (rest.length || field?.kind !== "choice") return void 0;
|
|
136
|
+
return field.options.length <= USER_INPUT_LIMITS.maxButtonOptions ? field : void 0;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Keep only answer values that match the request: known field ids, known
|
|
140
|
+
* option labels, one value for a `choice` field, and trimmed text.
|
|
141
|
+
*/
|
|
142
|
+
function normalizeUserInputAnswer(request, answer) {
|
|
143
|
+
const values = {};
|
|
144
|
+
for (const field of request.fields) {
|
|
145
|
+
const raw = (answer.values[field.id] ?? []).map((value) => value.trim()).filter(Boolean);
|
|
146
|
+
if (field.kind === "text") {
|
|
147
|
+
const text = raw.join("\n").slice(0, USER_INPUT_LIMITS.maxTextChars);
|
|
148
|
+
if (text) values[field.id] = [text];
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
const picked = field.options.map((option) => option.label).filter((label) => raw.includes(label));
|
|
152
|
+
const kept = field.kind === "choice" ? picked.slice(0, 1) : picked;
|
|
153
|
+
if (kept.length) values[field.id] = kept;
|
|
154
|
+
}
|
|
155
|
+
const other = answer.other?.trim().slice(0, USER_INPUT_LIMITS.maxTextChars);
|
|
156
|
+
return {
|
|
157
|
+
requestId: answer.requestId,
|
|
158
|
+
values,
|
|
159
|
+
...other ? { other } : void 0
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* Return the option labels that an answer picked, in field order. Text
|
|
164
|
+
* fields and the note pick no option.
|
|
165
|
+
*/
|
|
166
|
+
function answeredChoices(request, answer) {
|
|
167
|
+
const { values } = normalizeUserInputAnswer(request, answer);
|
|
168
|
+
return request.fields.flatMap((field) => field.kind === "text" ? [] : values[field.id] ?? []);
|
|
169
|
+
}
|
|
170
|
+
/** Return true when an answer has no value and no free text. */
|
|
171
|
+
function isEmptyUserInputAnswer(answer) {
|
|
172
|
+
return !answer.other && Object.keys(answer.values).length === 0;
|
|
173
|
+
}
|
|
174
|
+
function answerLine(text) {
|
|
175
|
+
return text.split("\n").map((line) => line.trim()).filter(Boolean).join("\n");
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Write the fields of an answer, one `Label (field_id): value` line each.
|
|
179
|
+
* Slack, the web dashboard, and the prompt all use this text, so the model
|
|
180
|
+
* reads one format.
|
|
181
|
+
*/
|
|
182
|
+
function formatUserInputAnswer(request, answer) {
|
|
183
|
+
const normalized = normalizeUserInputAnswer(request, answer);
|
|
184
|
+
const lines = [];
|
|
185
|
+
for (const field of request.fields) {
|
|
186
|
+
const values = normalized.values[field.id];
|
|
187
|
+
const value = values?.length ? values.join(", ") : "(no answer)";
|
|
188
|
+
lines.push(answerLine(`${field.label} (${field.id}): ${value}`));
|
|
189
|
+
}
|
|
190
|
+
if (normalized.other) lines.push(answerLine(`Other: ${normalized.other}`));
|
|
191
|
+
return lines.join("\n");
|
|
192
|
+
}
|
|
193
|
+
// src/chat/inbox-items/evidence.ts
|
|
194
|
+
/**
|
|
195
|
+
* One source that an agent cites for an Inbox item: a link or a
|
|
196
|
+
* Conversation, with a short label and an optional one-line note. A link
|
|
197
|
+
* points outside Junior; a Conversation reference points to work in Junior.
|
|
198
|
+
* The question stores the list, and the dashboard shows it beside the
|
|
199
|
+
* answer choices.
|
|
200
|
+
*/
|
|
201
|
+
const inboxItemEvidenceSchema = z.object({
|
|
202
|
+
conversationId: z.string().min(1).max(500).optional(),
|
|
203
|
+
label: z.string().min(1).max(120),
|
|
204
|
+
note: z.string().min(1).max(200).optional(),
|
|
205
|
+
url: z.string().min(1).max(2e3).optional()
|
|
206
|
+
}).strict().refine((entry) => entry.url === void 0 !== (entry.conversationId === void 0), "Evidence has a `url` or a `conversationId`, not both.");
|
|
207
|
+
/**
|
|
208
|
+
* The question of an Inbox item with the evidence for its answer. Evidence
|
|
209
|
+
* is part of the question, so it is stored in the `request` column.
|
|
210
|
+
*/
|
|
211
|
+
const inboxItemRequestSchema = savedUserInputRequestSchema.safeExtend({ evidence: z.array(inboxItemEvidenceSchema).optional() });
|
|
212
|
+
/** Validate the persisted Slack creator identity for an event automation. */
|
|
213
|
+
const eventAutomationPrincipalSchema = z.object({
|
|
214
|
+
slackUserId: actorUserIdSchema,
|
|
215
|
+
fullName: z.string().optional(),
|
|
216
|
+
userName: z.string().optional()
|
|
217
|
+
}).strict();
|
|
218
|
+
/**
|
|
219
|
+
* Validate one persisted event-automation selector and its presentation
|
|
220
|
+
* metadata. A trigger names one resource with a resource type and an
|
|
221
|
+
* identifier, or it names neither. With neither, it runs for every resource
|
|
222
|
+
* of the namespace that its filters match.
|
|
223
|
+
*/
|
|
224
|
+
const eventAutomationTriggerSchema = z.object({
|
|
225
|
+
events: z.array(eventTypeSchema).min(1),
|
|
226
|
+
label: z.string().min(1),
|
|
227
|
+
match: eventMatchSchema.optional(),
|
|
228
|
+
namespace: z.string().min(1),
|
|
229
|
+
identifier: z.string().min(1).max(300).optional(),
|
|
230
|
+
resourceType: z.string().min(1).optional()
|
|
231
|
+
}).strict().refine((trigger) => trigger.identifier === void 0 === (trigger.resourceType === void 0), {
|
|
232
|
+
message: "Set both a resource type and an identifier, or leave out both to run for every resource.",
|
|
233
|
+
path: ["identifier"]
|
|
234
|
+
});
|
|
235
|
+
/** Event automations target a Slack channel or DM, never a message thread. */
|
|
236
|
+
const eventAutomationDestinationSchema = slackDestinationSchema.omit({ threadTs: true });
|
|
237
|
+
const eventAutomationOutcomeSchema = taskOutcomeSchema.extend({ destination: eventAutomationDestinationSchema });
|
|
238
|
+
/** Validate one persisted event automation. */
|
|
239
|
+
const eventAutomationSchema = z.object({
|
|
240
|
+
id: z.string().min(1),
|
|
241
|
+
createdAtMs: z.number().finite(),
|
|
242
|
+
createdBy: eventAutomationPrincipalSchema,
|
|
243
|
+
/** Junior identity that created the automation. It decides ownership. */
|
|
244
|
+
creatorIdentityId: z.string().min(1),
|
|
245
|
+
credentialMode: z.enum(["system", "creator"]),
|
|
246
|
+
destination: eventAutomationDestinationSchema,
|
|
247
|
+
destinationVisibility: destinationVisibilitySchema,
|
|
248
|
+
/** Explicit visible effects after successful work. An empty list is silent. */
|
|
249
|
+
outcomes: z.array(eventAutomationOutcomeSchema).max(5),
|
|
250
|
+
task: automationTaskSchema,
|
|
251
|
+
trigger: eventAutomationTriggerSchema
|
|
252
|
+
}).strict();
|
|
253
|
+
// src/chat/scheduled-automations/cadence.ts
|
|
254
|
+
const FORMATTERS = /* @__PURE__ */ new Map();
|
|
255
|
+
function getFormatter(timezone) {
|
|
256
|
+
const existing = FORMATTERS.get(timezone);
|
|
257
|
+
if (existing) return existing;
|
|
258
|
+
const formatter = new Intl.DateTimeFormat("en-US", {
|
|
259
|
+
timeZone: timezone,
|
|
260
|
+
hour12: false,
|
|
261
|
+
year: "numeric",
|
|
262
|
+
month: "2-digit",
|
|
263
|
+
day: "2-digit",
|
|
264
|
+
hour: "2-digit",
|
|
265
|
+
minute: "2-digit",
|
|
266
|
+
second: "2-digit"
|
|
267
|
+
});
|
|
268
|
+
FORMATTERS.set(timezone, formatter);
|
|
269
|
+
return formatter;
|
|
270
|
+
}
|
|
271
|
+
function normalizeHour(hour) {
|
|
272
|
+
return hour === 24 ? 0 : hour;
|
|
273
|
+
}
|
|
274
|
+
function getLocalDateWeekday(date) {
|
|
275
|
+
return new Date(Date.UTC(date.year, date.month - 1, date.day)).getUTCDay();
|
|
276
|
+
}
|
|
277
|
+
function getWeekStart(date) {
|
|
278
|
+
return addDays(date, -((getLocalDateWeekday(date) + 6) % 7));
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* Check that a value is an IANA time zone that this runtime knows. This module
|
|
282
|
+
* has no runtime imports, so the dashboard client bundle can use it.
|
|
283
|
+
*/
|
|
284
|
+
function isValidTimeZone(timezone) {
|
|
285
|
+
try {
|
|
286
|
+
new Intl.DateTimeFormat("en-US", { timeZone: timezone }).format();
|
|
287
|
+
return true;
|
|
288
|
+
} catch {
|
|
289
|
+
return false;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
/** Resolve a UTC timestamp into calendar parts for a named time zone. */
|
|
293
|
+
function getZonedDateTimeParts(timestampMs, timezone) {
|
|
294
|
+
const parts = getFormatter(timezone).formatToParts(new Date(timestampMs));
|
|
295
|
+
const values = new Map(parts.map((part) => [part.type, part.value]));
|
|
296
|
+
const year = Number(values.get("year"));
|
|
297
|
+
const month = Number(values.get("month"));
|
|
298
|
+
const day = Number(values.get("day"));
|
|
299
|
+
return {
|
|
300
|
+
year,
|
|
301
|
+
month,
|
|
302
|
+
day,
|
|
303
|
+
hour: normalizeHour(Number(values.get("hour"))),
|
|
304
|
+
minute: Number(values.get("minute")),
|
|
305
|
+
second: Number(values.get("second")),
|
|
306
|
+
weekday: getLocalDateWeekday({
|
|
307
|
+
year,
|
|
308
|
+
month,
|
|
309
|
+
day
|
|
310
|
+
})
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
function getTimeZoneOffsetMs(timestampMs, timezone) {
|
|
314
|
+
const parts = getZonedDateTimeParts(timestampMs, timezone);
|
|
315
|
+
return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second) - timestampMs;
|
|
316
|
+
}
|
|
317
|
+
function localDateTimeToTimestampMs(args) {
|
|
318
|
+
const localAsUtcMs = Date.UTC(args.date.year, args.date.month - 1, args.date.day, args.time.hour, args.time.minute, 0);
|
|
319
|
+
const offsets = /* @__PURE__ */ new Set();
|
|
320
|
+
for (const probeDeltaMs of [
|
|
321
|
+
-1296e5,
|
|
322
|
+
-432e5,
|
|
323
|
+
0,
|
|
324
|
+
432e5,
|
|
325
|
+
1296e5
|
|
326
|
+
]) offsets.add(getTimeZoneOffsetMs(localAsUtcMs + probeDeltaMs, args.timezone));
|
|
327
|
+
const matches = [...offsets].map((offsetMs) => localAsUtcMs - offsetMs).filter((timestampMs) => {
|
|
328
|
+
const parts = getZonedDateTimeParts(timestampMs, args.timezone);
|
|
329
|
+
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;
|
|
330
|
+
});
|
|
331
|
+
if (matches.length === 0) return;
|
|
332
|
+
return Math.min(...matches);
|
|
333
|
+
}
|
|
334
|
+
/** Resolve local time, rejecting DST gaps and choosing the earlier instant in a fold. */
|
|
335
|
+
function resolveLocalScheduleAtMs(args) {
|
|
336
|
+
const date = parseLocalDate(args.date);
|
|
337
|
+
if (!date) return;
|
|
338
|
+
return localDateTimeToTimestampMs({
|
|
339
|
+
date,
|
|
340
|
+
time: args.time,
|
|
341
|
+
timezone: args.timezone
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
function daysBetween(left, right) {
|
|
345
|
+
return Math.floor((Date.UTC(right.year, right.month - 1, right.day) - Date.UTC(left.year, left.month - 1, left.day)) / 864e5);
|
|
346
|
+
}
|
|
347
|
+
function weeklyRecurrenceMatchesDate(date, start, recurrence) {
|
|
348
|
+
if (compareDate(date, start) < 0) return false;
|
|
349
|
+
return normalizeWeekdays(recurrence.weekdays).includes(getLocalDateWeekday(date)) && Math.floor(daysBetween(getWeekStart(start), getWeekStart(date)) / 7) % recurrence.interval === 0;
|
|
350
|
+
}
|
|
351
|
+
function greatestCommonDivisor(left, right) {
|
|
352
|
+
let a = Math.abs(left);
|
|
353
|
+
let b = Math.abs(right);
|
|
354
|
+
while (b !== 0) [a, b] = [b, a % b];
|
|
355
|
+
return a;
|
|
356
|
+
}
|
|
357
|
+
function findNextRunAtMs(args) {
|
|
358
|
+
const start = parseLocalDate(args.recurrence.startDate);
|
|
359
|
+
const interval = args.recurrence.interval;
|
|
360
|
+
if (!start || !Number.isInteger(interval) || interval <= 0) return;
|
|
361
|
+
const searchFrom = compareDate(args.searchFrom, start) < 0 ? start : args.searchFrom;
|
|
362
|
+
if (args.recurrence.frequency === "daily") {
|
|
363
|
+
const offsetDays = daysBetween(start, searchFrom);
|
|
364
|
+
let candidateDate = addDays(start, Math.ceil(offsetDays / interval) * interval);
|
|
365
|
+
const gregorianCycleDays = 146097;
|
|
366
|
+
const candidateCount = gregorianCycleDays / greatestCommonDivisor(gregorianCycleDays, interval);
|
|
367
|
+
for (let attempts = 0; attempts < candidateCount; attempts += 1) {
|
|
368
|
+
const candidate = buildCandidate({
|
|
369
|
+
date: candidateDate,
|
|
370
|
+
recurrence: args.recurrence,
|
|
371
|
+
timezone: args.timezone
|
|
372
|
+
});
|
|
373
|
+
if (candidate !== void 0 && candidate > args.afterMs) return candidate;
|
|
374
|
+
candidateDate = addDays(candidateDate, interval);
|
|
375
|
+
}
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (args.recurrence.frequency === "weekly") {
|
|
379
|
+
if (normalizeWeekdays(args.recurrence.weekdays).length === 0) return;
|
|
380
|
+
let candidateDate = searchFrom;
|
|
381
|
+
const gregorianCycleDays = 146097;
|
|
382
|
+
const cadenceDays = interval * 7;
|
|
383
|
+
const searchDays = gregorianCycleDays * cadenceDays / greatestCommonDivisor(gregorianCycleDays, cadenceDays);
|
|
384
|
+
for (let attempts = 0; attempts < searchDays; attempts += 1) {
|
|
385
|
+
if (weeklyRecurrenceMatchesDate(candidateDate, start, args.recurrence)) {
|
|
386
|
+
const candidate = buildCandidate({
|
|
387
|
+
date: candidateDate,
|
|
388
|
+
recurrence: args.recurrence,
|
|
389
|
+
timezone: args.timezone
|
|
390
|
+
});
|
|
391
|
+
if (candidate !== void 0 && candidate > args.afterMs) return candidate;
|
|
392
|
+
}
|
|
393
|
+
candidateDate = addDays(candidateDate, 1);
|
|
394
|
+
}
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
if (args.recurrence.frequency === "monthly") {
|
|
398
|
+
const startMonth = start.year * 12 + start.month - 1;
|
|
399
|
+
const searchMonth = searchFrom.year * 12 + searchFrom.month - 1;
|
|
400
|
+
let candidateMonth = startMonth + Math.ceil((searchMonth - startMonth) / interval) * interval;
|
|
401
|
+
const gregorianCycleMonths = 4800;
|
|
402
|
+
const candidateCount = gregorianCycleMonths / greatestCommonDivisor(gregorianCycleMonths, interval);
|
|
403
|
+
for (let attempts = 0; attempts < candidateCount; attempts += 1) {
|
|
404
|
+
const candidateDate = {
|
|
405
|
+
year: Math.floor(candidateMonth / 12),
|
|
406
|
+
month: candidateMonth % 12 + 1,
|
|
407
|
+
day: args.recurrence.dayOfMonth ?? 0
|
|
408
|
+
};
|
|
409
|
+
if (compareDate(candidateDate, searchFrom) >= 0) {
|
|
410
|
+
const candidate = buildCandidate({
|
|
411
|
+
date: candidateDate,
|
|
412
|
+
recurrence: args.recurrence,
|
|
413
|
+
timezone: args.timezone
|
|
414
|
+
});
|
|
415
|
+
if (candidate !== void 0 && candidate > args.afterMs) return candidate;
|
|
416
|
+
}
|
|
417
|
+
candidateMonth += interval;
|
|
418
|
+
}
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
let candidateYear = start.year + Math.ceil((searchFrom.year - start.year) / interval) * interval;
|
|
422
|
+
const candidateCount = 400 / greatestCommonDivisor(400, interval);
|
|
423
|
+
for (let attempts = 0; attempts < candidateCount; attempts += 1) {
|
|
424
|
+
const candidateDate = {
|
|
425
|
+
year: candidateYear,
|
|
426
|
+
month: args.recurrence.month ?? 0,
|
|
427
|
+
day: args.recurrence.dayOfMonth ?? 0
|
|
428
|
+
};
|
|
429
|
+
if (compareDate(candidateDate, searchFrom) >= 0) {
|
|
430
|
+
const candidate = buildCandidate({
|
|
431
|
+
date: candidateDate,
|
|
432
|
+
recurrence: args.recurrence,
|
|
433
|
+
timezone: args.timezone
|
|
434
|
+
});
|
|
435
|
+
if (candidate !== void 0 && candidate > args.afterMs) return candidate;
|
|
436
|
+
}
|
|
437
|
+
candidateYear += interval;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
/** Compute the first recurring calendar occurrence strictly after a timestamp. */
|
|
441
|
+
function getFirstRunAtMs(args) {
|
|
442
|
+
return findNextRunAtMs({
|
|
443
|
+
...args,
|
|
444
|
+
searchFrom: getLocalDate(args.afterMs, args.timezone)
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
function compareDate(left, right) {
|
|
448
|
+
return Date.UTC(left.year, left.month - 1, left.day) - Date.UTC(right.year, right.month - 1, right.day);
|
|
449
|
+
}
|
|
450
|
+
function addDays(date, days) {
|
|
451
|
+
const next = new Date(Date.UTC(date.year, date.month - 1, date.day + days));
|
|
452
|
+
return {
|
|
453
|
+
year: next.getUTCFullYear(),
|
|
454
|
+
month: next.getUTCMonth() + 1,
|
|
455
|
+
day: next.getUTCDate()
|
|
456
|
+
};
|
|
457
|
+
}
|
|
458
|
+
function daysInMonth(year, month) {
|
|
459
|
+
return new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
460
|
+
}
|
|
461
|
+
function parseLocalDate(value) {
|
|
462
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
463
|
+
if (!match) return;
|
|
464
|
+
const year = Number(match[1]);
|
|
465
|
+
const month = Number(match[2]);
|
|
466
|
+
const day = Number(match[3]);
|
|
467
|
+
if (!Number.isInteger(year) || !Number.isInteger(month) || !Number.isInteger(day) || month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return;
|
|
468
|
+
return {
|
|
469
|
+
year,
|
|
470
|
+
month,
|
|
471
|
+
day
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
function getLocalDate(timestampMs, timezone) {
|
|
475
|
+
const parts = getZonedDateTimeParts(timestampMs, timezone);
|
|
476
|
+
return {
|
|
477
|
+
year: parts.year,
|
|
478
|
+
month: parts.month,
|
|
479
|
+
day: parts.day
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
function normalizeWeekdays(values) {
|
|
483
|
+
return [...new Set((values ?? []).filter((value) => value >= 0 && value <= 6))].sort((a, b) => a - b);
|
|
484
|
+
}
|
|
485
|
+
function buildCandidate(args) {
|
|
486
|
+
return localDateTimeToTimestampMs({
|
|
487
|
+
date: args.date,
|
|
488
|
+
time: args.recurrence.time,
|
|
489
|
+
timezone: args.timezone
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
/** Return the next fire time after a completed run, when the task recurs. */
|
|
493
|
+
function getNextRunAtMs(task, scheduledForMs, afterMs = scheduledForMs) {
|
|
494
|
+
if (task.schedule.kind !== "recurring") return;
|
|
495
|
+
const recurrence = task.schedule.recurrence;
|
|
496
|
+
if (!recurrence || !Number.isFinite(recurrence.interval) || recurrence.interval <= 0) return;
|
|
497
|
+
const timezone = task.schedule.timezone;
|
|
498
|
+
const afterDate = getLocalDate(afterMs, timezone);
|
|
499
|
+
const nextScheduledDate = addDays(getLocalDate(scheduledForMs, timezone), 1);
|
|
500
|
+
return findNextRunAtMs({
|
|
501
|
+
afterMs,
|
|
502
|
+
recurrence,
|
|
503
|
+
searchFrom: compareDate(afterDate, nextScheduledDate) < 0 ? nextScheduledDate : afterDate,
|
|
504
|
+
timezone
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
// src/chat/scheduled-automations/schedule-intent.ts
|
|
508
|
+
/**
|
|
509
|
+
* Owns model-facing schedule intent and materializes it against the trusted
|
|
510
|
+
* server clock into the canonical schedule persisted by core.
|
|
511
|
+
*/
|
|
512
|
+
const localDateSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "Use a local date in YYYY-MM-DD format.");
|
|
513
|
+
const localTimeSchema = z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, "Use local time in HH:MM format.");
|
|
514
|
+
const timezoneSchema = z.string().min(1).max(80).describe("IANA timezone the user asked for, for example America/New_York. Omit or use null to use the creator's timezone on create, or to keep the saved timezone on update. Do not guess it from office locations.").nullable().optional();
|
|
515
|
+
/** Weekday names in `Date#getDay` order. */
|
|
516
|
+
const weekdaySchema = z.enum([
|
|
517
|
+
"sunday",
|
|
518
|
+
"monday",
|
|
519
|
+
"tuesday",
|
|
520
|
+
"wednesday",
|
|
521
|
+
"thursday",
|
|
522
|
+
"friday",
|
|
523
|
+
"saturday"
|
|
524
|
+
]);
|
|
525
|
+
const oneOffScheduleIntentSchema = z.object({
|
|
526
|
+
kind: z.literal("one_off").describe("A schedule that runs once."),
|
|
527
|
+
timezone: timezoneSchema,
|
|
528
|
+
timing: z.discriminatedUnion("type", [z.object({
|
|
529
|
+
type: z.literal("after").describe("Run after a relative delay from the server clock."),
|
|
530
|
+
value: z.number().int().positive().max(1e5),
|
|
531
|
+
unit: z.enum([
|
|
532
|
+
"second",
|
|
533
|
+
"minute",
|
|
534
|
+
"hour",
|
|
535
|
+
"day",
|
|
536
|
+
"week"
|
|
537
|
+
])
|
|
538
|
+
}).strict(), z.object({
|
|
539
|
+
type: z.literal("at").describe("Run at an explicit local calendar date and time."),
|
|
540
|
+
date: localDateSchema.describe("Requested local calendar date in YYYY-MM-DD format."),
|
|
541
|
+
time: localTimeSchema.describe("Requested local wall-clock time in HH:MM format.")
|
|
542
|
+
}).strict()]).describe("Relative delay or explicit local time for the one-off run.")
|
|
543
|
+
}).strict();
|
|
544
|
+
const recurringScheduleFields = {
|
|
545
|
+
kind: z.literal("recurring").describe("A repeating calendar schedule."),
|
|
546
|
+
frequency: z.enum([
|
|
547
|
+
"daily",
|
|
548
|
+
"weekly",
|
|
549
|
+
"monthly",
|
|
550
|
+
"yearly"
|
|
551
|
+
]).describe("Recurring tasks can run at most once per day."),
|
|
552
|
+
interval: z.number().int().positive().max(365).describe("Repeat every N frequency units. Defaults to 1.").nullable().optional(),
|
|
553
|
+
time: localTimeSchema.describe("Local wall-clock time for each occurrence in HH:MM format."),
|
|
554
|
+
weekdays: z.array(weekdaySchema).min(1).max(7).describe("Required for weekly schedules.").nullable().optional(),
|
|
555
|
+
month: z.number().int().min(1).max(12).describe("Required for yearly schedules, where January is 1.").nullable().optional(),
|
|
556
|
+
timezone: timezoneSchema
|
|
557
|
+
};
|
|
558
|
+
const dayOfMonthSchema = z.number().int().min(1).max(31).describe("Required for monthly and yearly schedules.").nullable().optional();
|
|
559
|
+
const startDateSchema = localDateSchema.describe("Optional local calendar date that anchors the recurrence. Omit to start with the next matching occurrence.").nullable().optional();
|
|
560
|
+
function checkRecurringSchedule(schedule, dayOfMonth, context) {
|
|
561
|
+
if (schedule.frequency === "weekly" && schedule.weekdays == null) context.addIssue({
|
|
562
|
+
code: "custom",
|
|
563
|
+
message: "Weekly schedules require weekdays.",
|
|
564
|
+
path: ["weekdays"]
|
|
565
|
+
});
|
|
566
|
+
if ((schedule.frequency === "monthly" || schedule.frequency === "yearly") && dayOfMonth.value == null) context.addIssue({
|
|
567
|
+
code: "custom",
|
|
568
|
+
message: `${schedule.frequency} schedules require ${dayOfMonth.key}.`,
|
|
569
|
+
path: [dayOfMonth.key]
|
|
570
|
+
});
|
|
571
|
+
if (schedule.frequency === "yearly" && schedule.month == null) context.addIssue({
|
|
572
|
+
code: "custom",
|
|
573
|
+
message: "Yearly schedules require month.",
|
|
574
|
+
path: ["month"]
|
|
575
|
+
});
|
|
576
|
+
if (schedule.frequency !== "weekly" && schedule.weekdays != null) context.addIssue({
|
|
577
|
+
code: "custom",
|
|
578
|
+
message: "weekdays applies only to weekly schedules.",
|
|
579
|
+
path: ["weekdays"]
|
|
580
|
+
});
|
|
581
|
+
if (schedule.frequency !== "monthly" && schedule.frequency !== "yearly" && dayOfMonth.value != null) context.addIssue({
|
|
582
|
+
code: "custom",
|
|
583
|
+
message: `${dayOfMonth.key} applies only to monthly or yearly schedules.`,
|
|
584
|
+
path: [dayOfMonth.key]
|
|
585
|
+
});
|
|
586
|
+
if (schedule.frequency !== "yearly" && schedule.month != null) context.addIssue({
|
|
587
|
+
code: "custom",
|
|
588
|
+
message: "month applies only to yearly schedules.",
|
|
589
|
+
path: ["month"]
|
|
590
|
+
});
|
|
591
|
+
}
|
|
592
|
+
const recurringScheduleIntentSchema = z.object({
|
|
593
|
+
...recurringScheduleFields,
|
|
594
|
+
dayOfMonth: dayOfMonthSchema,
|
|
595
|
+
startDate: startDateSchema
|
|
596
|
+
}).strict().superRefine((schedule, context) => checkRecurringSchedule(schedule, {
|
|
597
|
+
key: "dayOfMonth",
|
|
598
|
+
value: schedule.dayOfMonth
|
|
599
|
+
}, context));
|
|
600
|
+
const recurringToolScheduleIntentSchema = z.object({
|
|
601
|
+
...recurringScheduleFields,
|
|
602
|
+
day_of_month: dayOfMonthSchema,
|
|
603
|
+
start_date: startDateSchema
|
|
604
|
+
}).strict().superRefine((schedule, context) => checkRecurringSchedule(schedule, {
|
|
605
|
+
key: "day_of_month",
|
|
606
|
+
value: schedule.day_of_month
|
|
607
|
+
}, context));
|
|
608
|
+
const scheduleIntentSchema = z.union([oneOffScheduleIntentSchema, recurringScheduleIntentSchema]);
|
|
609
|
+
/** Model-facing schedule intent of the Automation tools. */
|
|
610
|
+
const toolScheduleIntentSchema = z.union([oneOffScheduleIntentSchema, recurringToolScheduleIntentSchema]);
|
|
611
|
+
/** Map a tool schedule intent to the shape that core compiles and saves. */
|
|
612
|
+
function scheduleIntentFromTool(intent) {
|
|
613
|
+
if (intent.kind === "one_off") return intent;
|
|
614
|
+
const { day_of_month, start_date, ...rest } = intent;
|
|
615
|
+
return {
|
|
616
|
+
...rest,
|
|
617
|
+
dayOfMonth: day_of_month,
|
|
618
|
+
startDate: start_date
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
const WEEKDAY_INDEX = {
|
|
622
|
+
sunday: 0,
|
|
623
|
+
monday: 1,
|
|
624
|
+
tuesday: 2,
|
|
625
|
+
wednesday: 3,
|
|
626
|
+
thursday: 4,
|
|
627
|
+
friday: 5,
|
|
628
|
+
saturday: 6
|
|
629
|
+
};
|
|
630
|
+
const DURATION_MS = {
|
|
631
|
+
second: 1e3,
|
|
632
|
+
minute: 6e4,
|
|
633
|
+
hour: 36e5,
|
|
634
|
+
day: 864e5,
|
|
635
|
+
week: 6048e5
|
|
636
|
+
};
|
|
637
|
+
function parseLocalTime(value) {
|
|
638
|
+
const [hour, minute] = value.split(":").map(Number);
|
|
639
|
+
return {
|
|
640
|
+
hour,
|
|
641
|
+
minute
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
function localDateAt(timestampMs, timezone) {
|
|
645
|
+
const parts = getZonedDateTimeParts(timestampMs, timezone);
|
|
646
|
+
return [
|
|
647
|
+
parts.year,
|
|
648
|
+
parts.month,
|
|
649
|
+
parts.day
|
|
650
|
+
].map((value, index) => index === 0 ? String(value).padStart(4, "0") : String(value).padStart(2, "0")).join("-");
|
|
651
|
+
}
|
|
652
|
+
function plural(value, unit) {
|
|
653
|
+
return value === 1 ? unit : `${unit}s`;
|
|
654
|
+
}
|
|
655
|
+
function formatWeekdays(weekdays) {
|
|
656
|
+
const labels = weekdays.map((weekday) => `${weekday[0].toUpperCase()}${weekday.slice(1)}`);
|
|
657
|
+
if (labels.length < 2) return labels[0] ?? "";
|
|
658
|
+
return `${labels.slice(0, -1).join(", ")} and ${labels.at(-1)}`;
|
|
659
|
+
}
|
|
660
|
+
function recurringDescription(schedule, timezone) {
|
|
661
|
+
const interval = schedule.interval ?? 1;
|
|
662
|
+
const cadenceUnit = {
|
|
663
|
+
daily: "day",
|
|
664
|
+
weekly: "week",
|
|
665
|
+
monthly: "month",
|
|
666
|
+
yearly: "year"
|
|
667
|
+
}[schedule.frequency];
|
|
668
|
+
const cadence = interval === 1 ? cadenceUnit : `${interval} ${cadenceUnit}s`;
|
|
669
|
+
let detail = "";
|
|
670
|
+
if (schedule.frequency === "weekly") detail = ` on ${formatWeekdays(schedule.weekdays)}`;
|
|
671
|
+
else if (schedule.frequency === "monthly") detail = ` on day ${schedule.dayOfMonth}`;
|
|
672
|
+
else if (schedule.frequency === "yearly") detail = ` on ${String(schedule.month).padStart(2, "0")}-${String(schedule.dayOfMonth).padStart(2, "0")}`;
|
|
673
|
+
return `Every ${cadence}${detail} at ${schedule.time} (${timezone})`;
|
|
674
|
+
}
|
|
675
|
+
var ScheduleIntentError = class extends Error {};
|
|
676
|
+
/** Materialize model-interpreted schedule intent against the trusted server clock. */
|
|
677
|
+
function compileScheduleIntent(args) {
|
|
678
|
+
const timezone = args.intent.timezone ?? args.defaultTimezone;
|
|
679
|
+
if (!isValidTimeZone(timezone)) throw new ScheduleIntentError("timezone must be a valid IANA time zone.");
|
|
680
|
+
if (args.intent.kind === "one_off") {
|
|
681
|
+
if (args.intent.timing.type === "after") return {
|
|
682
|
+
nextRunAtMs: args.nowMs + args.intent.timing.value * DURATION_MS[args.intent.timing.unit],
|
|
683
|
+
schedule: {
|
|
684
|
+
description: `In ${args.intent.timing.value} ${plural(args.intent.timing.value, args.intent.timing.unit)}`,
|
|
685
|
+
kind: "one_off",
|
|
686
|
+
timezone
|
|
687
|
+
}
|
|
688
|
+
};
|
|
689
|
+
const nextRunAtMs = resolveLocalScheduleAtMs({
|
|
690
|
+
date: args.intent.timing.date,
|
|
691
|
+
time: parseLocalTime(args.intent.timing.time),
|
|
692
|
+
timezone
|
|
693
|
+
});
|
|
694
|
+
if (nextRunAtMs === void 0) throw new ScheduleIntentError("The requested local date or time does not exist in that timezone.");
|
|
695
|
+
if (nextRunAtMs <= args.nowMs) throw new ScheduleIntentError("The requested one-off schedule must be in the future.");
|
|
696
|
+
return {
|
|
697
|
+
nextRunAtMs,
|
|
698
|
+
schedule: {
|
|
699
|
+
description: `Once on ${args.intent.timing.date} at ${args.intent.timing.time} (${timezone})`,
|
|
700
|
+
kind: "one_off",
|
|
701
|
+
timezone
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
}
|
|
705
|
+
const recurrence = {
|
|
706
|
+
frequency: args.intent.frequency,
|
|
707
|
+
interval: args.intent.interval ?? 1,
|
|
708
|
+
startDate: args.intent.startDate ?? localDateAt(args.nowMs, timezone),
|
|
709
|
+
time: parseLocalTime(args.intent.time),
|
|
710
|
+
...args.intent.frequency === "weekly" ? { weekdays: [...new Set(args.intent.weekdays.map((weekday) => WEEKDAY_INDEX[weekday]))].sort((left, right) => left - right) } : void 0,
|
|
711
|
+
...args.intent.frequency === "monthly" || args.intent.frequency === "yearly" ? { dayOfMonth: args.intent.dayOfMonth ?? void 0 } : void 0,
|
|
712
|
+
...args.intent.frequency === "yearly" ? { month: args.intent.month ?? void 0 } : void 0
|
|
713
|
+
};
|
|
714
|
+
const searchRecurrence = args.intent.startDate ? recurrence : {
|
|
715
|
+
...recurrence,
|
|
716
|
+
interval: 1
|
|
717
|
+
};
|
|
718
|
+
const nextRunAtMs = getFirstRunAtMs({
|
|
719
|
+
afterMs: args.nowMs,
|
|
720
|
+
recurrence: searchRecurrence,
|
|
721
|
+
timezone
|
|
722
|
+
});
|
|
723
|
+
if (nextRunAtMs === void 0) throw new ScheduleIntentError("The recurring schedule has no valid future occurrence.");
|
|
724
|
+
const materializedRecurrence = args.intent.startDate ? recurrence : {
|
|
725
|
+
...recurrence,
|
|
726
|
+
startDate: localDateAt(nextRunAtMs, timezone)
|
|
727
|
+
};
|
|
728
|
+
return {
|
|
729
|
+
nextRunAtMs,
|
|
730
|
+
schedule: {
|
|
731
|
+
description: recurringDescription(args.intent, timezone),
|
|
732
|
+
kind: "recurring",
|
|
733
|
+
recurrence: materializedRecurrence,
|
|
734
|
+
timezone
|
|
735
|
+
}
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
// src/chat/scheduled-automations/types.ts
|
|
739
|
+
/** Durable scheduled-automation domain types owned by Junior core. */
|
|
740
|
+
const scheduledAutomationStatusSchema = z.enum([
|
|
741
|
+
"active",
|
|
742
|
+
"blocked",
|
|
743
|
+
"paused",
|
|
744
|
+
"completed",
|
|
745
|
+
"deleted"
|
|
746
|
+
]);
|
|
747
|
+
const scheduledAutomationCredentialModeSchema = z.enum(["system", "creator"]);
|
|
748
|
+
const scheduledRunStatusSchema = z.enum([
|
|
749
|
+
"pending",
|
|
750
|
+
"running",
|
|
751
|
+
"completed",
|
|
752
|
+
"failed",
|
|
753
|
+
"blocked",
|
|
754
|
+
"skipped"
|
|
755
|
+
]);
|
|
756
|
+
const scheduledAutomationPrincipalSchema = z.object({
|
|
757
|
+
slackUserId: actorUserIdSchema,
|
|
758
|
+
fullName: z.string().optional(),
|
|
759
|
+
userName: z.string().optional()
|
|
760
|
+
}).strict();
|
|
761
|
+
const scheduledAutomationRecurrenceSchema = z.object({
|
|
762
|
+
dayOfMonth: z.number().optional(),
|
|
763
|
+
frequency: z.enum([
|
|
764
|
+
"daily",
|
|
765
|
+
"weekly",
|
|
766
|
+
"monthly",
|
|
767
|
+
"yearly"
|
|
768
|
+
]),
|
|
769
|
+
interval: z.number(),
|
|
770
|
+
month: z.number().optional(),
|
|
771
|
+
startDate: z.string(),
|
|
772
|
+
time: z.object({
|
|
773
|
+
hour: z.number(),
|
|
774
|
+
minute: z.number()
|
|
775
|
+
}).strict(),
|
|
776
|
+
weekdays: z.array(z.number()).optional()
|
|
777
|
+
}).strict();
|
|
778
|
+
const scheduledAutomationScheduleSchema = z.object({
|
|
779
|
+
description: z.string(),
|
|
780
|
+
kind: z.enum(["one_off", "recurring"]),
|
|
781
|
+
recurrence: scheduledAutomationRecurrenceSchema.optional(),
|
|
782
|
+
timezone: z.string()
|
|
783
|
+
}).strict();
|
|
784
|
+
const scheduledAutomationExecutionActorSchema = z.object({
|
|
785
|
+
platform: z.literal("system"),
|
|
786
|
+
name: z.string()
|
|
787
|
+
}).strict();
|
|
788
|
+
/** Scheduled automations target a Slack conversation, never one message thread. */
|
|
789
|
+
const scheduledAutomationDestinationSchema = slackDestinationSchema.omit({ threadTs: true });
|
|
790
|
+
const scheduledAutomationOutcomeSchema = z.object({
|
|
791
|
+
action: z.literal("send_message"),
|
|
792
|
+
destination: scheduledAutomationDestinationSchema
|
|
793
|
+
}).strict();
|
|
794
|
+
/** Validate the current scheduled-automation domain shape. */
|
|
795
|
+
const scheduledAutomationSchema = z.object({
|
|
796
|
+
id: z.string(),
|
|
797
|
+
conversationAccess: z.object({
|
|
798
|
+
audience: z.enum([
|
|
799
|
+
"direct",
|
|
800
|
+
"group",
|
|
801
|
+
"channel"
|
|
802
|
+
]),
|
|
803
|
+
visibility: z.enum(["private", "public"])
|
|
804
|
+
}).strict(),
|
|
805
|
+
createdAtMs: z.number(),
|
|
806
|
+
createdBy: scheduledAutomationPrincipalSchema,
|
|
807
|
+
/** Authoritative provider identity that created the task. */
|
|
808
|
+
creatorIdentityId: z.string(),
|
|
809
|
+
/** Selects system credentials or task-bound creator credential delegation. */
|
|
810
|
+
credentialMode: scheduledAutomationCredentialModeSchema,
|
|
811
|
+
destination: scheduledAutomationDestinationSchema,
|
|
812
|
+
executionActor: scheduledAutomationExecutionActorSchema.optional(),
|
|
813
|
+
lastRunAtMs: z.number().optional(),
|
|
814
|
+
nextRunAtMs: z.number().optional(),
|
|
815
|
+
originalRequest: z.string().optional(),
|
|
816
|
+
runNowAtMs: z.number().optional(),
|
|
817
|
+
schedule: scheduledAutomationScheduleSchema,
|
|
818
|
+
status: scheduledAutomationStatusSchema,
|
|
819
|
+
statusReason: z.string().optional(),
|
|
820
|
+
/** Explicit visible effects after successful work. An empty list is silent. */
|
|
821
|
+
outcomes: z.array(scheduledAutomationOutcomeSchema).max(5),
|
|
822
|
+
task: automationTaskSchema,
|
|
823
|
+
/** SQL-backed short display title generated from the task instruction. */
|
|
824
|
+
title: z.string().optional(),
|
|
825
|
+
updatedAtMs: z.number()
|
|
826
|
+
}).strict();
|
|
827
|
+
/** Validate the current scheduled-run domain shape. */
|
|
828
|
+
const scheduledRunSchema = z.object({
|
|
829
|
+
id: z.string(),
|
|
830
|
+
attempt: z.number(),
|
|
831
|
+
claimedAtMs: z.number(),
|
|
832
|
+
completedAtMs: z.number().optional(),
|
|
833
|
+
dispatchId: z.string().optional(),
|
|
834
|
+
errorMessage: z.string().optional(),
|
|
835
|
+
resultMessageTs: z.string().optional(),
|
|
836
|
+
scheduledForMs: z.number(),
|
|
837
|
+
startedAtMs: z.number().optional(),
|
|
838
|
+
status: scheduledRunStatusSchema,
|
|
839
|
+
taskId: z.string()
|
|
840
|
+
}).strict();
|
|
841
|
+
const SCHEDULED_AUTOMATION_SYSTEM_ACTOR = Object.freeze({
|
|
842
|
+
platform: "system",
|
|
843
|
+
name: "scheduled-automation"
|
|
844
|
+
});
|
|
845
|
+
// src/chat/task-outcomes-schema.ts
|
|
846
|
+
const taskMessageDestinationInputSchema = z.enum(["current_conversation", "task_creator"]).describe("Where to send the message. Use current_conversation for posts, digests, summaries, and channel reminders. Use task_creator only when the user asks for a direct reminder or notification.");
|
|
847
|
+
/** Input accepted by task authoring tools before a user becomes a DM Destination. */
|
|
848
|
+
const taskOutcomeInputSchema = z.object({
|
|
849
|
+
action: z.literal("send_message"),
|
|
850
|
+
destination: taskMessageDestinationInputSchema
|
|
851
|
+
}).strict();
|
|
852
|
+
// src/chat/automations/edit-schema.ts
|
|
853
|
+
const automationTitleSchema = z.string().trim().min(1).max(60);
|
|
854
|
+
/**
|
|
855
|
+
* Instruction input for agent tools. The run does not see the request, so the
|
|
856
|
+
* instruction names exact targets. It calls the creator "the Automation
|
|
857
|
+
* creator". It names every other person with their mention, also a requester
|
|
858
|
+
* who says "me".
|
|
859
|
+
*/
|
|
860
|
+
const automationInstructionToolSchema = automationTaskTextSchema.describe("Work to perform when the Automation runs. Say what to do, what to post, and when to post nothing. Do not say where to post: the outcomes set that, a run triggered by a Slack message replies in its thread, and each run ends with one message at most. The run does not see this conversation, so words like \"this channel\" or \"here\" will mean nothing then. Where the run reads or changes something, write the exact target, such as a channel mention, a repo, or a link. Keep every person the user means, including \"me\". Write the creator as \"the Automation creator\"; each run knows who that is. Write anyone else, including a requester who is not the creator, as their Slack mention, such as <@U123>. Preserve the user's scope, targets, and constraints. Do not add permissions or side effects the user did not request.");
|
|
861
|
+
/**
|
|
862
|
+
* Context input for agent tools. It follows the same rules as an instruction.
|
|
863
|
+
* Action review reads the stored context, not the skill, so the context also
|
|
864
|
+
* names the scope of the writes a run needs.
|
|
865
|
+
*/
|
|
866
|
+
const automationContextToolSchema = automationTaskTextSchema.describe("What a run needs beyond the skill: input values, such as a repo or who to tag; when to post nothing; and the scope of writes. Not the skill steps. Instruction rules apply: no place to post, exact targets, \"the Automation creator\", others as <@U123>.");
|
|
867
|
+
const automationEditFieldsSchema = z.object({
|
|
868
|
+
title: automationTitleSchema.optional(),
|
|
869
|
+
/** Replaces the whole task, so a mode switch drops the other mode's text. */
|
|
870
|
+
task: automationTaskSchema.optional(),
|
|
871
|
+
credentialMode: z.enum(["system", "creator"]).optional(),
|
|
872
|
+
outcomes: z.array(z.union([taskOutcomeInputSchema, taskOutcomeSchema])).max(5).optional()
|
|
873
|
+
});
|
|
874
|
+
const scheduledAutomationEditSchema = automationEditFieldsSchema.extend({ schedule: scheduleIntentSchema.optional() }).strict();
|
|
875
|
+
const eventAutomationEditSchema = automationEditFieldsSchema.extend({ trigger: eventAutomationTriggerSchema.safeExtend({
|
|
876
|
+
identifier: z.string().trim().min(1).max(300).optional(),
|
|
877
|
+
label: z.string().trim().min(1).max(500)
|
|
878
|
+
}).optional() }).strict();
|
|
879
|
+
// src/chat/attachments/input.ts
|
|
880
|
+
/**
|
|
881
|
+
* Largest file that Junior stores from Slack or the web, or loads into the
|
|
882
|
+
* sandbox.
|
|
883
|
+
*
|
|
884
|
+
* Every path streams the bytes, so this cap does not depend on function
|
|
885
|
+
* memory. It bounds transfer time and sandbox disk use.
|
|
886
|
+
*/
|
|
887
|
+
const MAX_ATTACHMENT_BYTES = 262144e3;
|
|
888
|
+
/** Most files on one web Message, as in one Slack message. */
|
|
889
|
+
const MAX_INPUT_ATTACHMENTS = 10;
|
|
890
|
+
/** File facts that a browser declares before it uploads the bytes. */
|
|
891
|
+
const inputFileSchema = z.object({
|
|
892
|
+
filename: z.string().trim().min(1).max(255),
|
|
893
|
+
contentType: z.string().trim().toLowerCase().max(127).regex(/^[a-z0-9][\w.+-]*\/[a-z0-9][\w.+-]*$/),
|
|
894
|
+
bytes: z.number().int().min(1).max(MAX_ATTACHMENT_BYTES)
|
|
895
|
+
}).strict();
|
|
896
|
+
/** Safe attachment facts shared by mailbox input and transcript messages. */
|
|
897
|
+
const messageAttachmentSchema = z.object({
|
|
898
|
+
id: z.string().min(1),
|
|
899
|
+
filename: z.string().min(1),
|
|
900
|
+
contentType: z.string().min(1),
|
|
901
|
+
bytes: z.number().int().nonnegative(),
|
|
902
|
+
/**
|
|
903
|
+
* True for a large Slack file that Junior has not stored yet. A
|
|
904
|
+
* dashboard read downloads it from Slack, so it has no preview.
|
|
905
|
+
*/
|
|
906
|
+
pending: z.literal(true).optional()
|
|
907
|
+
}).strict();
|
|
908
|
+
/** Read attachment metadata without exposing object storage keys or bytes. */
|
|
909
|
+
function readMessageAttachments(value) {
|
|
910
|
+
return messageAttachmentSchema.array().parse(value ?? []);
|
|
911
|
+
}
|
|
912
|
+
// src/chat/automations/card.ts
|
|
913
|
+
/** Saved automation facts shown with a Message, not a live status view. */
|
|
914
|
+
const automationCardSchema = z.object({
|
|
915
|
+
kind: z.literal("automation"),
|
|
916
|
+
id: z.string().min(1),
|
|
917
|
+
title: z.string().min(1).max(160),
|
|
918
|
+
url: z.string().url().nullable(),
|
|
919
|
+
instruction: z.string().max(4e3),
|
|
920
|
+
trigger: z.string().min(1),
|
|
921
|
+
warning: z.string().nullable()
|
|
922
|
+
}).strict();
|
|
923
|
+
/** Render saved card facts for text-only delivery and accessible fallbacks. */
|
|
924
|
+
function automationCardText(card) {
|
|
925
|
+
return [
|
|
926
|
+
card.title,
|
|
927
|
+
card.warning,
|
|
928
|
+
card.trigger,
|
|
929
|
+
card.instruction,
|
|
930
|
+
card.url,
|
|
931
|
+
`Automation ID: ${card.id}`
|
|
932
|
+
].filter(Boolean).join("\n");
|
|
933
|
+
}
|
|
934
|
+
// src/chat/conversations/cards.ts
|
|
935
|
+
const storedCardSchema = automationCardSchema.extend({ operation: z.enum([
|
|
936
|
+
"created",
|
|
937
|
+
"updated",
|
|
938
|
+
"deleted"
|
|
939
|
+
]).optional() });
|
|
940
|
+
/** Render each built-in card with its own text format. */
|
|
941
|
+
function messageCardText(card) {
|
|
942
|
+
switch (card.kind) {
|
|
943
|
+
case "object": return [
|
|
944
|
+
card.title,
|
|
945
|
+
card.label !== card.title ? card.label : void 0,
|
|
946
|
+
card.description,
|
|
947
|
+
card.status,
|
|
948
|
+
...objectFactFields(card.facts).map((field) => `${field.label}: ${field.value}`),
|
|
949
|
+
card.trigger,
|
|
950
|
+
card.warning,
|
|
951
|
+
card.url
|
|
952
|
+
].filter(Boolean).join("\n");
|
|
953
|
+
case "automation": return automationCardText(card);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
/** Identify a deleted object whose pending card must be omitted. */
|
|
957
|
+
const removedCardSchema = z.object({
|
|
958
|
+
plugin: z.string().min(1),
|
|
959
|
+
key: z.string().min(1)
|
|
960
|
+
}).strict();
|
|
961
|
+
/** Store only the annotation identity with a Message. */
|
|
962
|
+
const messageCardRefSchema = removedCardSchema.extend({ kind: z.literal("object") });
|
|
963
|
+
/** Remove display facts before saving or reporting a Message card. */
|
|
964
|
+
function messageCardRef(card) {
|
|
965
|
+
return card.kind === "object" ? {
|
|
966
|
+
kind: "object",
|
|
967
|
+
plugin: card.plugin,
|
|
968
|
+
key: card.key
|
|
969
|
+
} : {
|
|
970
|
+
kind: "object",
|
|
971
|
+
plugin: "junior",
|
|
972
|
+
key: card.id
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
/** Read references, including identities from older saved card snapshots. */
|
|
976
|
+
function readMessageCardRefs(value) {
|
|
977
|
+
return [...storedCardSchema.array().parse(value.cards ?? []).flatMap(({ operation, ...card }) => operation === "deleted" ? [] : [messageCardRef(card)]), ...messageCardRefSchema.strip().array().parse(value.objectCards ?? [])];
|
|
978
|
+
}
|
|
979
|
+
/** Resolve current saved facts without fetching providers or changing history. */
|
|
980
|
+
function resolveMessageCards(refs, annotations) {
|
|
981
|
+
return refs.map((ref) => {
|
|
982
|
+
const annotation = annotations.find((item) => item.kind === ref.kind && item.plugin === ref.plugin && item.key === ref.key);
|
|
983
|
+
return annotation ? annotationCard(annotation) : {
|
|
984
|
+
...ref,
|
|
985
|
+
objectType: "item",
|
|
986
|
+
title: ref.key,
|
|
987
|
+
label: ref.key,
|
|
988
|
+
url: null,
|
|
989
|
+
warning: "Saved annotation is unavailable."
|
|
990
|
+
};
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
/** Copy saved annotation facts without storage timestamps for Message delivery. */
|
|
994
|
+
function annotationCard(annotation) {
|
|
995
|
+
const { createdAt: _createdAt, updatedAt: _updatedAt, ...value } = annotation;
|
|
996
|
+
return value.kind === "object" ? value : {
|
|
997
|
+
...value,
|
|
998
|
+
kind: "object",
|
|
999
|
+
objectType: value.objectType ?? "item",
|
|
1000
|
+
title: value.label
|
|
1001
|
+
};
|
|
1002
|
+
}
|
|
1003
|
+
// src/chat/inbox-items/change-record.ts
|
|
1004
|
+
/**
|
|
1005
|
+
* The person change to an Inbox item that one message records. Each inbound
|
|
1006
|
+
* message and saved Message that reports a take, answer, or dismiss carries
|
|
1007
|
+
* its own record, so the dashboard shows what that message did, not what the
|
|
1008
|
+
* item looks like now.
|
|
1009
|
+
*
|
|
1010
|
+
* Stored Messages and queued inputs keep this shape and their
|
|
1011
|
+
* `reviewItemChange` and `reviewItemChanges` keys from before Review items
|
|
1012
|
+
* became Inbox items, so these names stay.
|
|
1013
|
+
*/
|
|
1014
|
+
const inboxItemChangeRecordSchema = z.object({
|
|
1015
|
+
kind: z.enum([
|
|
1016
|
+
"submitted",
|
|
1017
|
+
"dismissed",
|
|
1018
|
+
"taken"
|
|
1019
|
+
]),
|
|
1020
|
+
reviewItemId: z.string().min(1)
|
|
1021
|
+
}).strict();
|
|
1022
|
+
// src/api/schema/conversation-read-position.ts
|
|
1023
|
+
/**
|
|
1024
|
+
* How far the signed-in viewer has read a Conversation transcript.
|
|
1025
|
+
*
|
|
1026
|
+
* `lastReadSeq` is the event sequence of the last transcript row the viewer
|
|
1027
|
+
* saw. Reports only move it forward: the server keeps the highest value it
|
|
1028
|
+
* receives. It is never before the viewer's own latest Message.
|
|
1029
|
+
*/
|
|
1030
|
+
const conversationReadPositionSchema = z.object({ lastReadSeq: z.number().int().nonnegative() }).strict();
|
|
1031
|
+
// src/api/schema/conversation-kind.ts
|
|
1032
|
+
/** Where a Conversation sits in its tree. See `TERMINOLOGY.md`. */
|
|
1033
|
+
const conversationKindSchema = z.enum([
|
|
1034
|
+
"root",
|
|
1035
|
+
"automation",
|
|
1036
|
+
"lead",
|
|
1037
|
+
"thread",
|
|
1038
|
+
"task"
|
|
1039
|
+
]);
|
|
1040
|
+
// src/api/schema/conversation-title.ts
|
|
1041
|
+
/** Longest Conversation title that a rename can save. */
|
|
1042
|
+
const CONVERSATION_TITLE_MAX_LENGTH = 200;
|
|
1043
|
+
/** A Conversation title that a caller chooses, at creation or on rename. */
|
|
1044
|
+
const conversationTitleSchema = z.string().trim().min(1).max(200);
|
|
1045
|
+
/** A participant's new title for one Conversation. Every viewer sees it. */
|
|
1046
|
+
const renameConversationBodySchema = z.object({ title: conversationTitleSchema }).strict();
|
|
1047
|
+
/** The stored title after the rename. */
|
|
1048
|
+
const renameConversationResponseSchema = z.object({ title: z.string().min(1) }).strict();
|
|
1049
|
+
// src/api/schema/conversation-tree-state.ts
|
|
1050
|
+
/**
|
|
1051
|
+
* What a Conversation and its child Conversations need, for one viewer.
|
|
1052
|
+
* See "Viewer state" in `TERMINOLOGY.md`.
|
|
1053
|
+
*/
|
|
1054
|
+
const conversationTreeStateSchema = z.enum([
|
|
1055
|
+
"needs_you",
|
|
1056
|
+
"working",
|
|
1057
|
+
"done"
|
|
1058
|
+
]);
|
|
1059
|
+
// src/chat/agent-invocations/agent-types.ts
|
|
1060
|
+
/**
|
|
1061
|
+
* Child agent types. A type is plain data: when to pick it and what the child
|
|
1062
|
+
* reads with its task. Runtime code reads only these fields, never a type
|
|
1063
|
+
* name, so types can later come from configuration. Types do not limit tools:
|
|
1064
|
+
* Guardian reviews each child action against the root user's messages, as for
|
|
1065
|
+
* any child. A child keeps its type for later agent invocations. How a child
|
|
1066
|
+
* starts, fresh or forked from its parent's history, is not a type: see
|
|
1067
|
+
* `fork` on the agent invocation.
|
|
1068
|
+
*/
|
|
1069
|
+
const AGENT_TYPES = ["explore", "reviewer"];
|
|
1070
|
+
/**
|
|
1071
|
+
* Stored name of a child agent type. A stored name stays readable after its
|
|
1072
|
+
* type is removed; the runtime then treats the child as a
|
|
1073
|
+
* child without a type.
|
|
1074
|
+
*/
|
|
1075
|
+
const agentTypeSchema = z.string().regex(/^[a-z][a-z0-9_-]*$/);
|
|
1076
|
+
const AGENT_TYPE_DEFINITIONS = {
|
|
1077
|
+
explore: {
|
|
1078
|
+
whenToUse: "Investigation across code, docs, logs, telemetry, or the web. Use it when an answer needs reading across many files or sources and you need the conclusion with evidence, not the raw output.",
|
|
1079
|
+
instructions: "You are an explore agent. Your job is to investigate and report, so do not change anything outside your sandbox unless the task asks for it. Report what you found with exact evidence, such as paths, lines, links, and ids."
|
|
1080
|
+
},
|
|
1081
|
+
reviewer: {
|
|
1082
|
+
whenToUse: "An independent second opinion on a change, plan, or claim. Give it the evidence to judge, not your conclusion.",
|
|
1083
|
+
instructions: "You are a reviewer agent. Give an independent assessment. Do not assume that the parent's framing is correct: verify each claim against the evidence. Do not change anything outside your own sandbox. Report concrete problems ranked by severity, each with its evidence, and say clearly when you found none."
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1086
|
+
function agentTypeDefinition(type) {
|
|
1087
|
+
return type && Object.hasOwn(AGENT_TYPE_DEFINITIONS, type) ? AGENT_TYPE_DEFINITIONS[type] : void 0;
|
|
1088
|
+
}
|
|
1089
|
+
/** Model-facing list of child agent types. */
|
|
1090
|
+
function formatAgentTypes() {
|
|
1091
|
+
return AGENT_TYPES.map((type) => `- "${type}": ${AGENT_TYPE_DEFINITIONS[type].whenToUse}`).join("\n");
|
|
1092
|
+
}
|
|
1093
|
+
/** Return the instructions that a child of this type reads with its task. */
|
|
1094
|
+
function agentTypeInstructions(type) {
|
|
1095
|
+
return agentTypeDefinition(type)?.instructions;
|
|
1096
|
+
}
|
|
1097
|
+
// src/api/schema/child-agent-totals.ts
|
|
1098
|
+
/**
|
|
1099
|
+
* The part of a Conversation total that its child agents spent, at any depth.
|
|
1100
|
+
* Present only when the Conversation has child agents. The Conversation's own
|
|
1101
|
+
* part is the total minus this part.
|
|
1102
|
+
*/
|
|
1103
|
+
const conversationChildAgentTotalsSchema = z.object({
|
|
1104
|
+
auxiliaryCostUsd: z.number().finite().nonnegative().optional(),
|
|
1105
|
+
count: z.number().int().positive(),
|
|
1106
|
+
cumulativeDurationMs: z.number(),
|
|
1107
|
+
cumulativeUsage: usageSchema.optional()
|
|
1108
|
+
}).strict();
|
|
1109
|
+
// src/api/schema/object-preview-image.ts
|
|
1110
|
+
/**
|
|
1111
|
+
* One saved preview image of an object, such as a pull request screenshot,
|
|
1112
|
+
* at 1x and 2x. Both name the Junior image route, never the image host.
|
|
1113
|
+
*/
|
|
1114
|
+
const objectPreviewImageSchema = z.object({
|
|
1115
|
+
src: z.string().startsWith("/api/images/"),
|
|
1116
|
+
srcSet: z.string().min(1)
|
|
1117
|
+
}).strict();
|
|
1118
|
+
const CUT_TOKEN_RE = /<(?:[@#!][^<>]*|[a-z]+:[^\s<>|]*(?:\|[^<>]*)?|[a-z]*)$/i;
|
|
1119
|
+
/**
|
|
1120
|
+
* Cut preview text to the schema limit. The cut ends with "…" at a word
|
|
1121
|
+
* break, and never leaves half a surrogate pair or an unclosed Slack token
|
|
1122
|
+
* such as `<@U1` or `<https://…`, so mentions and links still parse.
|
|
1123
|
+
*/
|
|
1124
|
+
function activityPreviewText(text) {
|
|
1125
|
+
if (text.length <= 400) return text;
|
|
1126
|
+
let cut = text.slice(0, 399);
|
|
1127
|
+
const space = cut.search(/\s\S*$/);
|
|
1128
|
+
if (space > 0 && /\S/.test(text[cut.length])) cut = cut.slice(0, space);
|
|
1129
|
+
const last = cut.charCodeAt(cut.length - 1);
|
|
1130
|
+
if (last >= 55296 && last <= 56319) cut = cut.slice(0, -1);
|
|
1131
|
+
return `${cut.replace(CUT_TOKEN_RE, "").trimEnd()}…`;
|
|
1132
|
+
}
|
|
1133
|
+
// src/api/schema/conversation.ts
|
|
1134
|
+
/**
|
|
1135
|
+
* The status of one Conversation's own work. See `TERMINOLOGY.md` and
|
|
1136
|
+
* `conversationStatusSql`, the only place that derives it.
|
|
1137
|
+
*/
|
|
1138
|
+
const conversationReportStatusSchema = z.enum([
|
|
1139
|
+
"needs_input",
|
|
1140
|
+
"working",
|
|
1141
|
+
"done"
|
|
1142
|
+
]);
|
|
1143
|
+
const conversationSurfaceSchema = z.enum([
|
|
1144
|
+
"api",
|
|
1145
|
+
"internal",
|
|
1146
|
+
"scheduler",
|
|
1147
|
+
"slack"
|
|
1148
|
+
]);
|
|
1149
|
+
const conversationUsageSchema = usageSchema;
|
|
1150
|
+
const conversationParamsSchema = z.object({ conversationId: z.string().min(1) }).strict();
|
|
1151
|
+
const conversationAttachmentParamsSchema = z.object({
|
|
1152
|
+
attachmentId: z.string().min(1),
|
|
1153
|
+
conversationId: z.string().min(1)
|
|
1154
|
+
}).strict();
|
|
1155
|
+
const conversationAttachmentQuerySchema = z.object({
|
|
1156
|
+
/**
|
|
1157
|
+
* Send `Content-Disposition: attachment` even for a type that previews
|
|
1158
|
+
* inline, so a same-window download link saves the file.
|
|
1159
|
+
*/
|
|
1160
|
+
download: z.stringbool().optional() }).strict();
|
|
1161
|
+
const conversationDetailQuerySchema = z.object({
|
|
1162
|
+
/** Omit to get the latest three Turns, up to the default page limit. */
|
|
1163
|
+
limit: z.coerce.number().int().min(1).max(1e3).optional(),
|
|
1164
|
+
/** Also return `unreadPage` when the detail has an `unreadCursor`. */
|
|
1165
|
+
unreadPage: z.stringbool().optional(),
|
|
1166
|
+
/**
|
|
1167
|
+
* Also return `mailbox`, read before history. A sent version that still
|
|
1168
|
+
* matches gets `{ unchanged: true, mailbox }` instead of 304, so a poll
|
|
1169
|
+
* needs one request.
|
|
1170
|
+
*/
|
|
1171
|
+
mailbox: z.stringbool().optional(),
|
|
1172
|
+
/**
|
|
1173
|
+
* An `appendCursor` from an earlier detail. Events then hold only newer
|
|
1174
|
+
* events, with `appended: true`, while the cursor still applies.
|
|
1175
|
+
*/
|
|
1176
|
+
after: z.string().min(1).optional()
|
|
1177
|
+
}).strict();
|
|
1178
|
+
const conversationEventsLimitSchema = z.coerce.number().int().min(1).max(1e3).default(150);
|
|
1179
|
+
/**
|
|
1180
|
+
* Page toward the start with `before`, toward the latest with `after`, or
|
|
1181
|
+
* both ways from one event with `around`. A link target asks for the page
|
|
1182
|
+
* around one event by its `event` seq, around one `message` by its id, or
|
|
1183
|
+
* around the start of a `turn`.
|
|
1184
|
+
*/
|
|
1185
|
+
const conversationEventsQuerySchema = z.union([
|
|
1186
|
+
z.object({
|
|
1187
|
+
before: z.string().min(1),
|
|
1188
|
+
limit: conversationEventsLimitSchema
|
|
1189
|
+
}).strict(),
|
|
1190
|
+
z.object({
|
|
1191
|
+
after: z.string().min(1),
|
|
1192
|
+
limit: conversationEventsLimitSchema
|
|
1193
|
+
}).strict(),
|
|
1194
|
+
z.object({
|
|
1195
|
+
around: z.string().min(1),
|
|
1196
|
+
limit: conversationEventsLimitSchema
|
|
1197
|
+
}).strict(),
|
|
1198
|
+
z.object({
|
|
1199
|
+
event: z.coerce.number().int().min(0),
|
|
1200
|
+
limit: conversationEventsLimitSchema
|
|
1201
|
+
}).strict(),
|
|
1202
|
+
z.object({
|
|
1203
|
+
turn: z.string().min(1),
|
|
1204
|
+
limit: conversationEventsLimitSchema
|
|
1205
|
+
}).strict(),
|
|
1206
|
+
z.object({
|
|
1207
|
+
message: z.string().min(1),
|
|
1208
|
+
limit: conversationEventsLimitSchema
|
|
1209
|
+
}).strict()
|
|
1210
|
+
]);
|
|
1211
|
+
/** Client key that makes a retried send the same Message. */
|
|
1212
|
+
const idempotencyKeySchema = z.string().trim().min(1).max(200);
|
|
1213
|
+
const createConversationMessageBodySchema = z.object({
|
|
1214
|
+
idempotencyKey: idempotencyKeySchema,
|
|
1215
|
+
message: z.string().trim().max(32e3),
|
|
1216
|
+
/** Uploads from `POST /api/conversations/attachment-uploads`. */
|
|
1217
|
+
uploadIds: z.array(z.string().min(1).max(64)).max(10).optional()
|
|
1218
|
+
}).strict().refine((body) => Boolean(body.message || body.uploadIds?.length), "Add a message or a file.");
|
|
1219
|
+
const createConversationBodySchema = createConversationMessageBodySchema.safeExtend({
|
|
1220
|
+
/** Saved title. Title generation runs only when it is omitted. */
|
|
1221
|
+
title: conversationTitleSchema.optional(),
|
|
1222
|
+
/** New roots default public. Private roots stay participant-only. */
|
|
1223
|
+
visibility: z.enum(["private", "public"]).optional()
|
|
1224
|
+
});
|
|
1225
|
+
const acceptedConversationMessageSchema = z.object({
|
|
1226
|
+
conversationId: z.string().min(1),
|
|
1227
|
+
messageId: z.string().min(1),
|
|
1228
|
+
status: z.enum(["accepted", "duplicate"])
|
|
1229
|
+
}).strict();
|
|
1230
|
+
const actorIdentitySchema = z.object({
|
|
1231
|
+
/**
|
|
1232
|
+
* Junior API path of the profile photo: the person's Slack photo, then
|
|
1233
|
+
* their Google photo.
|
|
1234
|
+
*/
|
|
1235
|
+
avatarUrl: z.string().optional(),
|
|
1236
|
+
email: z.string().optional(),
|
|
1237
|
+
fullName: z.string().optional(),
|
|
1238
|
+
slackUserId: z.string().optional(),
|
|
1239
|
+
slackUserName: z.string().optional()
|
|
1240
|
+
}).strict();
|
|
1241
|
+
const conversationAuxiliaryCostsSchema = z.object({
|
|
1242
|
+
costUsd: z.number().finite().nonnegative(),
|
|
1243
|
+
operations: z.array(z.object({
|
|
1244
|
+
costUsd: z.number().finite().nonnegative(),
|
|
1245
|
+
events: z.number().int().positive(),
|
|
1246
|
+
name: z.string().min(1),
|
|
1247
|
+
namespace: z.string().min(1)
|
|
1248
|
+
}).strict()).min(1)
|
|
1249
|
+
}).strict();
|
|
1250
|
+
/** Optional reverse link from a task-triggered conversation back to its task. */
|
|
1251
|
+
const conversationSourceTaskSchema = z.object({
|
|
1252
|
+
id: z.string().min(1).optional(),
|
|
1253
|
+
kind: z.enum(["scheduled", "event"]),
|
|
1254
|
+
label: z.string().min(1).optional(),
|
|
1255
|
+
title: z.string().min(1).optional(),
|
|
1256
|
+
/** Message id of the run's trigger input, which is not from a person. */
|
|
1257
|
+
triggerMessageId: z.string().min(1).optional(),
|
|
1258
|
+
/** Short trigger text, such as an event or a schedule. */
|
|
1259
|
+
triggerLabel: z.string().min(1).optional(),
|
|
1260
|
+
/** Credential mode this run used. Unset when the run record is gone. */
|
|
1261
|
+
credentialMode: z.enum(["creator", "system"]).optional(),
|
|
1262
|
+
/** Name of the creator whose credentials this run used. */
|
|
1263
|
+
credentialUser: z.string().min(1).optional()
|
|
1264
|
+
}).strict().superRefine((value, context) => {
|
|
1265
|
+
if (Boolean(value.id) !== Boolean(value.label)) context.addIssue({
|
|
1266
|
+
code: "custom",
|
|
1267
|
+
message: "sourceTask id and label must both be set or both omitted"
|
|
1268
|
+
});
|
|
1269
|
+
});
|
|
1270
|
+
const conversationAnnotationReportSchema = conversationAnnotationInputSchema.and(z.object({
|
|
1271
|
+
plugin: z.string().min(1),
|
|
1272
|
+
createdAt: z.string().datetime(),
|
|
1273
|
+
updatedAt: z.string().datetime(),
|
|
1274
|
+
previewImages: z.array(objectPreviewImageSchema).optional()
|
|
1275
|
+
}));
|
|
1276
|
+
const conversationActivityPreviewSchema = z.object({
|
|
1277
|
+
createdAt: z.string().datetime(),
|
|
1278
|
+
mentions: z.array(actorIdentitySchema).optional(),
|
|
1279
|
+
role: z.enum(["assistant", "user"]),
|
|
1280
|
+
text: z.string().min(1).max(400)
|
|
1281
|
+
}).strict();
|
|
1282
|
+
const conversationSummaryReportSchema = z.object({
|
|
1283
|
+
displayTitle: z.string(),
|
|
1284
|
+
/**
|
|
1285
|
+
* Conversation metadata, when the viewer may see private content. A new
|
|
1286
|
+
* Conversation has none until its first Turn completes.
|
|
1287
|
+
*/
|
|
1288
|
+
summary: z.string().optional(),
|
|
1289
|
+
activityPreview: conversationActivityPreviewSchema.optional(),
|
|
1290
|
+
cumulativeDurationMs: z.number(),
|
|
1291
|
+
cumulativeUsage: conversationUsageSchema.optional(),
|
|
1292
|
+
auxiliaryCosts: conversationAuxiliaryCostsSchema.optional(),
|
|
1293
|
+
childAgentTotals: conversationChildAgentTotalsSchema.optional(),
|
|
1294
|
+
conversationId: z.string(),
|
|
1295
|
+
kind: conversationKindSchema,
|
|
1296
|
+
/** Present on Threads and Tasks. */
|
|
1297
|
+
parentConversationId: z.string().min(1).optional(),
|
|
1298
|
+
isParticipant: z.boolean(),
|
|
1299
|
+
visibility: z.enum(["private", "public"]).optional(),
|
|
1300
|
+
status: conversationReportStatusSchema,
|
|
1301
|
+
/** Feed rows and the detail only. */
|
|
1302
|
+
treeState: conversationTreeStateSchema.optional(),
|
|
1303
|
+
/**
|
|
1304
|
+
* A Conversation in the tree has an active Watch or a pending Timer.
|
|
1305
|
+
* Feed rows and the detail only.
|
|
1306
|
+
*/
|
|
1307
|
+
watching: z.boolean().optional(),
|
|
1308
|
+
/**
|
|
1309
|
+
* A Turn is queued or running. Live views poll and show thinking on it,
|
|
1310
|
+
* since `status` can read `needs_input` while a Turn runs.
|
|
1311
|
+
*/
|
|
1312
|
+
turnActive: z.boolean(),
|
|
1313
|
+
startedAt: z.string(),
|
|
1314
|
+
lastSeenAt: z.string(),
|
|
1315
|
+
lastProgressAt: z.string(),
|
|
1316
|
+
lastMessageAt: z.string().datetime().optional(),
|
|
1317
|
+
surface: conversationSurfaceSchema,
|
|
1318
|
+
actorIdentity: actorIdentitySchema.optional(),
|
|
1319
|
+
participants: z.array(actorIdentitySchema).optional(),
|
|
1320
|
+
/**
|
|
1321
|
+
* When this Conversation was archived for everyone, or null. It shows
|
|
1322
|
+
* only while it and every ancestor are unarchived.
|
|
1323
|
+
*/
|
|
1324
|
+
archivedAt: z.string().datetime().nullable().optional(),
|
|
1325
|
+
pinnedAt: z.string().datetime().nullable().optional(),
|
|
1326
|
+
/** The viewer's place in Pinned. Unset until they reorder their pins. */
|
|
1327
|
+
pinPosition: z.number().int().optional(),
|
|
1328
|
+
channel: z.string().optional(),
|
|
1329
|
+
channelName: z.string().optional(),
|
|
1330
|
+
channelNameRedacted: z.boolean().optional(),
|
|
1331
|
+
locationId: z.string().optional(),
|
|
1332
|
+
sentryTraceUrl: z.string().optional(),
|
|
1333
|
+
locationUrl: z.string().url().optional(),
|
|
1334
|
+
traceId: z.string().optional(),
|
|
1335
|
+
/**
|
|
1336
|
+
* Plugin-owned resource links for this conversation.
|
|
1337
|
+
* Present on the conversation feed when the viewer can see private content.
|
|
1338
|
+
* Clients must not fetch provider state while rendering these links.
|
|
1339
|
+
*/
|
|
1340
|
+
annotations: z.array(conversationAnnotationReportSchema).optional(),
|
|
1341
|
+
/** Plugin-selected annotations for the compact conversation row. */
|
|
1342
|
+
sidebarAnnotations: z.array(conversationSidebarAnnotationSchema).optional(),
|
|
1343
|
+
assignedWork: z.boolean().optional(),
|
|
1344
|
+
finishedWorkAt: z.string().datetime().optional(),
|
|
1345
|
+
/**
|
|
1346
|
+
* Dashboard Priority membership for this conversation summary.
|
|
1347
|
+
* Present on the conversation feed. Clients must not recompute it.
|
|
1348
|
+
*
|
|
1349
|
+
* True only when:
|
|
1350
|
+
* - unfinished work was last seen within 48 hours
|
|
1351
|
+
* - finished assigned work has conversation activity after the finish time
|
|
1352
|
+
* - there is no known work and the conversation was last seen within 3 hours
|
|
1353
|
+
*/
|
|
1354
|
+
isPriority: z.boolean().optional(),
|
|
1355
|
+
unfinishedWork: z.boolean().optional(),
|
|
1356
|
+
/**
|
|
1357
|
+
* True on the conversation feed when a Turn in the conversation or a
|
|
1358
|
+
* child waits on a person to finish an authorization that has not
|
|
1359
|
+
* expired.
|
|
1360
|
+
*/
|
|
1361
|
+
awaitingAuthorization: z.boolean().optional(),
|
|
1362
|
+
/**
|
|
1363
|
+
* True on the conversation feed when the conversation's latest Turn
|
|
1364
|
+
* failed and no newer Turn started.
|
|
1365
|
+
*/
|
|
1366
|
+
latestTurnFailed: z.boolean().optional()
|
|
1367
|
+
}).strict();
|
|
1368
|
+
/** One Event listed on a message that holds several Events. */
|
|
1369
|
+
const conversationReportMessageEventSchema = z.object({
|
|
1370
|
+
eventType: z.string().min(1),
|
|
1371
|
+
label: z.string().min(1).optional(),
|
|
1372
|
+
objectType: objectTypeSchema.optional(),
|
|
1373
|
+
trustedSummary: z.string().min(1).optional()
|
|
1374
|
+
}).strict();
|
|
1375
|
+
const conversationReportMessageEventDataSchema = z.object({
|
|
1376
|
+
type: z.literal("message"),
|
|
1377
|
+
messageId: z.string().min(1),
|
|
1378
|
+
role: z.enum([
|
|
1379
|
+
"assistant",
|
|
1380
|
+
"system",
|
|
1381
|
+
"user"
|
|
1382
|
+
]),
|
|
1383
|
+
source: z.enum(["slack", "web"]).optional(),
|
|
1384
|
+
actorIdentity: actorIdentitySchema.optional(),
|
|
1385
|
+
/** Identity id of the author. Detail `authors` maps it to the person. */
|
|
1386
|
+
actorIdentityId: z.string().min(1).optional(),
|
|
1387
|
+
/** Agent invocation whose input this is. An agent wrote it, not a person. */
|
|
1388
|
+
agentInvocationId: z.string().min(1).optional(),
|
|
1389
|
+
eventType: z.string().min(1).optional(),
|
|
1390
|
+
/** Namespace of the first Event, such as `github`. */
|
|
1391
|
+
eventNamespace: z.string().min(1).optional(),
|
|
1392
|
+
/**
|
|
1393
|
+
* Resource identifier of the first Event, such as the id of a watched
|
|
1394
|
+
* Conversation. Only for viewers who can see private content.
|
|
1395
|
+
*/
|
|
1396
|
+
eventIdentifier: z.string().min(1).optional(),
|
|
1397
|
+
eventObjectType: objectTypeSchema.optional(),
|
|
1398
|
+
explicitMention: z.boolean().optional(),
|
|
1399
|
+
quiet: z.literal(true).optional(),
|
|
1400
|
+
trustedSummary: z.string().min(1).optional(),
|
|
1401
|
+
/**
|
|
1402
|
+
* The Watch Events when several arrived together. A message that also
|
|
1403
|
+
* records Inbox item changes lists its own Event here even when it has
|
|
1404
|
+
* one.
|
|
1405
|
+
*/
|
|
1406
|
+
events: z.array(conversationReportMessageEventSchema).optional(),
|
|
1407
|
+
cards: z.array(messageCardRefSchema).optional(),
|
|
1408
|
+
/** Person changes to Inbox items that this message records. */
|
|
1409
|
+
reviewItemChanges: z.array(inboxItemChangeRecordSchema).min(1).optional(),
|
|
1410
|
+
text: z.string().optional(),
|
|
1411
|
+
attachments: z.array(messageAttachmentSchema).optional(),
|
|
1412
|
+
redacted: z.literal(true).optional()
|
|
1413
|
+
}).strict().superRefine((data, context) => {
|
|
1414
|
+
if (data.text === void 0 === (data.redacted !== true)) context.addIssue({
|
|
1415
|
+
code: "custom",
|
|
1416
|
+
message: "message content must be text or explicitly redacted"
|
|
1417
|
+
});
|
|
1418
|
+
if (data.redacted && (data.actorIdentity || data.cards || data.attachments || data.events || data.reviewItemChanges)) context.addIssue({
|
|
1419
|
+
code: "custom",
|
|
1420
|
+
message: "redacted messages must not expose actor identity, cards, attachments, events, or inbox item changes"
|
|
1421
|
+
});
|
|
1422
|
+
});
|
|
1423
|
+
const conversationReportMessageHandledEventDataSchema = z.object({
|
|
1424
|
+
type: z.literal("message_handled"),
|
|
1425
|
+
messageId: z.string().min(1)
|
|
1426
|
+
}).strict();
|
|
1427
|
+
const conversationReportToolCallSchema = z.object({
|
|
1428
|
+
toolCallId: z.string().min(1),
|
|
1429
|
+
name: z.string().min(1),
|
|
1430
|
+
status: z.enum([
|
|
1431
|
+
"running",
|
|
1432
|
+
"completed",
|
|
1433
|
+
"error"
|
|
1434
|
+
]),
|
|
1435
|
+
startedAt: z.string().datetime().optional(),
|
|
1436
|
+
startedSeq: z.number().int().nonnegative().optional(),
|
|
1437
|
+
input: z.unknown().optional(),
|
|
1438
|
+
output: z.unknown().optional(),
|
|
1439
|
+
/** The Conversation that a completed `startConversation` call started. */
|
|
1440
|
+
startedConversationId: z.string().min(1).optional()
|
|
1441
|
+
}).strict().superRefine((call, context) => {
|
|
1442
|
+
if (call.startedAt === void 0 !== (call.startedSeq === void 0)) context.addIssue({
|
|
1443
|
+
code: "custom",
|
|
1444
|
+
message: "tool start sequence and timestamp must be provided together"
|
|
1445
|
+
});
|
|
1446
|
+
});
|
|
1447
|
+
const conversationReportReasoningPartSchema = z.object({
|
|
1448
|
+
type: z.literal("reasoning"),
|
|
1449
|
+
text: z.string().min(1).optional(),
|
|
1450
|
+
redacted: z.literal(true).optional()
|
|
1451
|
+
}).strict().superRefine((data, context) => {
|
|
1452
|
+
if (data.text === void 0 === (data.redacted !== true)) context.addIssue({
|
|
1453
|
+
code: "custom",
|
|
1454
|
+
message: "reasoning content must be text or explicitly redacted"
|
|
1455
|
+
});
|
|
1456
|
+
});
|
|
1457
|
+
const conversationReportAssistantToolCallPartSchema = z.object({
|
|
1458
|
+
type: z.literal("tool_call"),
|
|
1459
|
+
toolCallId: z.string().min(1)
|
|
1460
|
+
}).strict();
|
|
1461
|
+
const conversationReportAssistantMetadataSchema = z.object({ parts: z.array(z.discriminatedUnion("type", [conversationReportReasoningPartSchema, conversationReportAssistantToolCallPartSchema])).min(1) }).strict();
|
|
1462
|
+
const conversationReportToolCallsEventDataSchema = z.object({
|
|
1463
|
+
type: z.literal("tool_calls"),
|
|
1464
|
+
calls: z.array(conversationReportToolCallSchema).min(1),
|
|
1465
|
+
assistant: conversationReportAssistantMetadataSchema.optional()
|
|
1466
|
+
}).strict().superRefine((data, context) => {
|
|
1467
|
+
if (!data.assistant) return;
|
|
1468
|
+
const callCounts = /* @__PURE__ */ new Map();
|
|
1469
|
+
for (const call of data.calls) callCounts.set(call.toolCallId, (callCounts.get(call.toolCallId) ?? 0) + 1);
|
|
1470
|
+
const partCounts = /* @__PURE__ */ new Map();
|
|
1471
|
+
for (const part of data.assistant.parts) {
|
|
1472
|
+
if (part.type !== "tool_call") continue;
|
|
1473
|
+
partCounts.set(part.toolCallId, (partCounts.get(part.toolCallId) ?? 0) + 1);
|
|
1474
|
+
}
|
|
1475
|
+
if (callCounts.size !== partCounts.size || [...callCounts].some(([toolCallId, count]) => partCounts.get(toolCallId) !== count)) context.addIssue({
|
|
1476
|
+
code: "custom",
|
|
1477
|
+
path: ["assistant", "parts"],
|
|
1478
|
+
message: "assistant tool parts must reference every call exactly once"
|
|
1479
|
+
});
|
|
1480
|
+
});
|
|
1481
|
+
const conversationReportAssistantMessageEventDataSchema = z.object({
|
|
1482
|
+
type: z.literal("assistant_message"),
|
|
1483
|
+
parts: z.array(conversationReportReasoningPartSchema)
|
|
1484
|
+
}).strict();
|
|
1485
|
+
const conversationReportTurnLifecycleEventDataSchema = z.discriminatedUnion("state", [
|
|
1486
|
+
z.object({
|
|
1487
|
+
type: z.literal("turn_lifecycle"),
|
|
1488
|
+
turnId: z.string().min(1),
|
|
1489
|
+
state: z.enum([
|
|
1490
|
+
"succeeded",
|
|
1491
|
+
"no_reply",
|
|
1492
|
+
"blocked"
|
|
1493
|
+
])
|
|
1494
|
+
}).strict(),
|
|
1495
|
+
z.object({
|
|
1496
|
+
type: z.literal("turn_lifecycle"),
|
|
1497
|
+
turnId: z.string().min(1),
|
|
1498
|
+
state: z.literal("started"),
|
|
1499
|
+
inputMessageIds: z.array(z.string().min(1)).min(1).optional()
|
|
1500
|
+
}).strict(),
|
|
1501
|
+
z.object({
|
|
1502
|
+
type: z.literal("turn_lifecycle"),
|
|
1503
|
+
turnId: z.string().min(1),
|
|
1504
|
+
state: z.literal("failed"),
|
|
1505
|
+
failureCode: conversationTurnFailureCodeSchema,
|
|
1506
|
+
failureReason: conversationTurnFailureReasonSchema.optional(),
|
|
1507
|
+
eventId: z.string().regex(/^[a-f0-9]{32}$/i).optional(),
|
|
1508
|
+
sentryEventUrl: z.string().url().optional()
|
|
1509
|
+
}).strict()
|
|
1510
|
+
]);
|
|
1511
|
+
const conversationReportGuardianActionReviewedEventDataSchema = z.object({
|
|
1512
|
+
type: z.literal("guardian_action_reviewed"),
|
|
1513
|
+
turnId: z.string().min(1),
|
|
1514
|
+
toolCallId: z.string().min(1),
|
|
1515
|
+
toolName: z.string().min(1),
|
|
1516
|
+
decision: z.enum([
|
|
1517
|
+
"allow",
|
|
1518
|
+
"ask",
|
|
1519
|
+
"deny"
|
|
1520
|
+
]),
|
|
1521
|
+
riskLevel: z.enum([
|
|
1522
|
+
"low",
|
|
1523
|
+
"medium",
|
|
1524
|
+
"high",
|
|
1525
|
+
"critical"
|
|
1526
|
+
]),
|
|
1527
|
+
userAuthorization: z.enum([
|
|
1528
|
+
"high",
|
|
1529
|
+
"medium",
|
|
1530
|
+
"low",
|
|
1531
|
+
"unknown"
|
|
1532
|
+
])
|
|
1533
|
+
}).strict();
|
|
1534
|
+
const conversationReportTurnContextEventDataSchema = z.object({
|
|
1535
|
+
type: z.literal("turn_context"),
|
|
1536
|
+
turnId: z.string().min(1),
|
|
1537
|
+
pluginName: z.string().min(1),
|
|
1538
|
+
kind: z.string().min(1),
|
|
1539
|
+
version: z.number().int().positive(),
|
|
1540
|
+
content: z.record(z.string(), z.unknown())
|
|
1541
|
+
}).strict();
|
|
1542
|
+
const conversationReportStructuredEventDataSchema = z.object({
|
|
1543
|
+
type: z.literal("structured_event"),
|
|
1544
|
+
namespace: z.string().min(1),
|
|
1545
|
+
name: z.string().min(1),
|
|
1546
|
+
version: z.number().int().positive(),
|
|
1547
|
+
turnId: z.string().min(1).optional(),
|
|
1548
|
+
presentation: conversationEventPresentationSchema
|
|
1549
|
+
}).strict();
|
|
1550
|
+
const conversationReportAttachmentsDeliveredEventDataSchema = z.object({
|
|
1551
|
+
type: z.literal("attachments_delivered"),
|
|
1552
|
+
attachments: z.array(messageAttachmentSchema).min(1)
|
|
1553
|
+
}).strict();
|
|
1554
|
+
/** Junior text that a plugin tool posted to its provider. */
|
|
1555
|
+
const conversationReportReplyPostedEventDataSchema = z.object({
|
|
1556
|
+
type: z.literal("reply_posted"),
|
|
1557
|
+
plugin: z.string().min(1),
|
|
1558
|
+
text: z.string().min(1),
|
|
1559
|
+
url: z.string().url().optional()
|
|
1560
|
+
}).strict();
|
|
1561
|
+
const conversationReportCompactionEventDataSchema = z.object({
|
|
1562
|
+
type: z.literal("compaction"),
|
|
1563
|
+
modelId: z.string().min(1).optional(),
|
|
1564
|
+
summary: z.string().min(1).optional(),
|
|
1565
|
+
details: z.object({
|
|
1566
|
+
reason: z.literal("capacity"),
|
|
1567
|
+
estimatedInputTokens: z.number().int().nonnegative(),
|
|
1568
|
+
replacementInputTokens: z.number().int().nonnegative().optional(),
|
|
1569
|
+
triggerTokens: z.number().int().nonnegative(),
|
|
1570
|
+
inputLimitTokens: z.number().int().positive(),
|
|
1571
|
+
inputMessageCount: z.number().int().nonnegative(),
|
|
1572
|
+
retainedMessageCount: z.number().int().nonnegative(),
|
|
1573
|
+
summaryChars: z.number().int().nonnegative()
|
|
1574
|
+
}).strict().optional()
|
|
1575
|
+
}).strict();
|
|
1576
|
+
const conversationReportSubagentEventDataSchema = z.object({
|
|
1577
|
+
type: z.literal("subagent"),
|
|
1578
|
+
startedSeq: z.number().int().nonnegative(),
|
|
1579
|
+
startedAt: z.string().datetime(),
|
|
1580
|
+
childConversationId: z.string().min(1),
|
|
1581
|
+
/** The child's Conversation kind. Only a Thread has its own page link. */
|
|
1582
|
+
childKind: z.enum(["thread", "task"]),
|
|
1583
|
+
subagentKind: z.string().min(1),
|
|
1584
|
+
agentName: z.string().min(1).optional(),
|
|
1585
|
+
task: z.string().min(1).optional(),
|
|
1586
|
+
title: z.string().min(1).optional(),
|
|
1587
|
+
parentToolCallId: z.string().min(1).optional(),
|
|
1588
|
+
status: z.enum([
|
|
1589
|
+
"running",
|
|
1590
|
+
"completed",
|
|
1591
|
+
"blocked",
|
|
1592
|
+
"error",
|
|
1593
|
+
"aborted"
|
|
1594
|
+
])
|
|
1595
|
+
}).strict();
|
|
1596
|
+
/** Privacy-safe event variants owned by the conversation reporting API. */
|
|
1597
|
+
const conversationReportEventDataSchema = z.discriminatedUnion("type", [
|
|
1598
|
+
conversationReportMessageEventDataSchema,
|
|
1599
|
+
conversationReportMessageHandledEventDataSchema,
|
|
1600
|
+
conversationReportAssistantMessageEventDataSchema,
|
|
1601
|
+
conversationReportToolCallsEventDataSchema,
|
|
1602
|
+
conversationReportTurnLifecycleEventDataSchema,
|
|
1603
|
+
conversationReportTurnContextEventDataSchema,
|
|
1604
|
+
conversationReportStructuredEventDataSchema,
|
|
1605
|
+
conversationReportAttachmentsDeliveredEventDataSchema,
|
|
1606
|
+
conversationReportReplyPostedEventDataSchema,
|
|
1607
|
+
conversationReportGuardianActionReviewedEventDataSchema,
|
|
1608
|
+
conversationReportCompactionEventDataSchema,
|
|
1609
|
+
conversationReportSubagentEventDataSchema
|
|
1610
|
+
]);
|
|
1611
|
+
/** One ordered, privacy-safe canonical event projected for API consumers. */
|
|
1612
|
+
const conversationReportEventSchema = z.object({
|
|
1613
|
+
seq: z.number().int().nonnegative(),
|
|
1614
|
+
createdAt: z.string().datetime(),
|
|
1615
|
+
data: conversationReportEventDataSchema,
|
|
1616
|
+
/** People mentioned in the event text, resolved at read time. */
|
|
1617
|
+
mentions: z.array(actorIdentitySchema).optional(),
|
|
1618
|
+
model: z.object({ modelId: z.string().min(1) }).strict().optional(),
|
|
1619
|
+
modelCall: z.object({
|
|
1620
|
+
provider: z.string().min(1).optional(),
|
|
1621
|
+
api: z.string().min(1).optional(),
|
|
1622
|
+
stopReason: z.string().min(1).optional(),
|
|
1623
|
+
usage: conversationUsageSchema.optional()
|
|
1624
|
+
}).strict().optional()
|
|
1625
|
+
}).strict();
|
|
1626
|
+
/** Availability of the canonical event history attached to a detail report. */
|
|
1627
|
+
const conversationEventHistorySchema = z.discriminatedUnion("status", [
|
|
1628
|
+
z.object({ status: z.literal("available") }).strict(),
|
|
1629
|
+
z.object({
|
|
1630
|
+
status: z.literal("redacted"),
|
|
1631
|
+
reason: z.literal("non_public_conversation")
|
|
1632
|
+
}).strict(),
|
|
1633
|
+
z.object({
|
|
1634
|
+
status: z.literal("expired"),
|
|
1635
|
+
expiredAt: z.string().datetime()
|
|
1636
|
+
}).strict()
|
|
1637
|
+
]);
|
|
1638
|
+
const conversationModelUsageSchema = z.object({
|
|
1639
|
+
modelId: z.string(),
|
|
1640
|
+
usage: conversationUsageSchema
|
|
1641
|
+
}).strict();
|
|
1642
|
+
/** Enforce event ordering and history visibility across paginated wire payloads. */
|
|
1643
|
+
function validateConversationEvents(report, context) {
|
|
1644
|
+
if (report.eventHistory.status === "expired" && report.events.length > 0) context.addIssue({
|
|
1645
|
+
code: "custom",
|
|
1646
|
+
path: ["events"],
|
|
1647
|
+
message: "expired event history must not contain events"
|
|
1648
|
+
});
|
|
1649
|
+
for (let index = 1; index < report.events.length; index += 1) if (report.events[index].seq <= report.events[index - 1].seq) context.addIssue({
|
|
1650
|
+
code: "custom",
|
|
1651
|
+
path: [
|
|
1652
|
+
"events",
|
|
1653
|
+
index,
|
|
1654
|
+
"seq"
|
|
1655
|
+
],
|
|
1656
|
+
message: "report event sequences must be strictly increasing"
|
|
1657
|
+
});
|
|
1658
|
+
for (const [index, event] of report.events.entries()) {
|
|
1659
|
+
if (event.data.type === "message") {
|
|
1660
|
+
if (report.eventHistory.status === "redacted" && event.data.redacted !== true) context.addIssue({
|
|
1661
|
+
code: "custom",
|
|
1662
|
+
path: [
|
|
1663
|
+
"events",
|
|
1664
|
+
index,
|
|
1665
|
+
"data"
|
|
1666
|
+
],
|
|
1667
|
+
message: "redacted event history must redact messages"
|
|
1668
|
+
});
|
|
1669
|
+
if (report.eventHistory.status === "available" && event.data.redacted === true) context.addIssue({
|
|
1670
|
+
code: "custom",
|
|
1671
|
+
path: [
|
|
1672
|
+
"events",
|
|
1673
|
+
index,
|
|
1674
|
+
"data"
|
|
1675
|
+
],
|
|
1676
|
+
message: "available event history must expose messages"
|
|
1677
|
+
});
|
|
1678
|
+
}
|
|
1679
|
+
if (report.eventHistory.status === "redacted" && event.data.type === "tool_calls" && event.data.calls.some((call) => call.input !== void 0 || call.output !== void 0)) context.addIssue({
|
|
1680
|
+
code: "custom",
|
|
1681
|
+
path: [
|
|
1682
|
+
"events",
|
|
1683
|
+
index,
|
|
1684
|
+
"data"
|
|
1685
|
+
],
|
|
1686
|
+
message: "redacted event history must redact tool payloads"
|
|
1687
|
+
});
|
|
1688
|
+
if (report.eventHistory.status === "redacted" && event.data.type === "assistant_message" && event.data.parts.some((part) => part.text !== void 0)) context.addIssue({
|
|
1689
|
+
code: "custom",
|
|
1690
|
+
path: [
|
|
1691
|
+
"events",
|
|
1692
|
+
index,
|
|
1693
|
+
"data"
|
|
1694
|
+
],
|
|
1695
|
+
message: "redacted event history must redact assistant messages"
|
|
1696
|
+
});
|
|
1697
|
+
if (report.eventHistory.status === "available" && event.data.type === "assistant_message" && event.data.parts.some((part) => part.redacted === true)) context.addIssue({
|
|
1698
|
+
code: "custom",
|
|
1699
|
+
path: [
|
|
1700
|
+
"events",
|
|
1701
|
+
index,
|
|
1702
|
+
"data"
|
|
1703
|
+
],
|
|
1704
|
+
message: "available event history must expose reasoning"
|
|
1705
|
+
});
|
|
1706
|
+
if (event.data.type === "tool_calls" && (report.eventHistory.status === "redacted" && event.data.assistant?.parts.some((part) => part.type === "reasoning" && part.text !== void 0) || report.eventHistory.status === "available" && event.data.assistant?.parts.some((part) => part.type === "reasoning" && part.redacted === true))) context.addIssue({
|
|
1707
|
+
code: "custom",
|
|
1708
|
+
path: [
|
|
1709
|
+
"events",
|
|
1710
|
+
index,
|
|
1711
|
+
"data",
|
|
1712
|
+
"assistant"
|
|
1713
|
+
],
|
|
1714
|
+
message: "assistant reasoning must match event history visibility"
|
|
1715
|
+
});
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
/** One Conversation in the agent tree of a child Conversation. */
|
|
1719
|
+
const conversationAgentTreeNodeSchema = z.object({
|
|
1720
|
+
conversationId: z.string().min(1),
|
|
1721
|
+
kind: conversationKindSchema,
|
|
1722
|
+
label: z.string().min(1),
|
|
1723
|
+
/**
|
|
1724
|
+
* Agent type of a child, such as `explore`. Absent for a root, a child
|
|
1725
|
+
* without a type, or a viewer who cannot see private content.
|
|
1726
|
+
*/
|
|
1727
|
+
agentType: agentTypeSchema.optional(),
|
|
1728
|
+
/**
|
|
1729
|
+
* The child started with its parent's history. Absent like `agentType`,
|
|
1730
|
+
* or when the child started fresh.
|
|
1731
|
+
*/
|
|
1732
|
+
fork: z.literal(true).optional()
|
|
1733
|
+
}).strict();
|
|
1734
|
+
const conversationEventPageSchema = z.object({
|
|
1735
|
+
events: z.array(conversationReportEventSchema),
|
|
1736
|
+
eventHistory: conversationEventHistorySchema,
|
|
1737
|
+
previousCursor: z.string().min(1).optional(),
|
|
1738
|
+
/** Present on `after` and `around` pages when newer events follow. */
|
|
1739
|
+
nextCursor: z.string().min(1).optional(),
|
|
1740
|
+
generatedAt: z.string()
|
|
1741
|
+
}).strict().superRefine(validateConversationEvents);
|
|
1742
|
+
/**
|
|
1743
|
+
* Carries the detail version token in both directions. A custom header, not
|
|
1744
|
+
* `ETag`, for the reason on `CONTENT_VERSION_HEADER`.
|
|
1745
|
+
*/
|
|
1746
|
+
const CONVERSATION_DETAIL_VERSION_HEADER = "x-junior-detail-version";
|
|
1747
|
+
/**
|
|
1748
|
+
* Carries the change token of the Conversation tree that a detail report was
|
|
1749
|
+
* built from. The dashboard compares it with the token of `GET /api/versions`
|
|
1750
|
+
* and asks for the report only when they differ.
|
|
1751
|
+
*/
|
|
1752
|
+
const CONVERSATION_VERSION_HEADER = "x-junior-conversation-version";
|
|
1753
|
+
const conversationDetailReportSchema = conversationSummaryReportSchema.extend({
|
|
1754
|
+
/**
|
|
1755
|
+
* The parent chain of a child Conversation, root first, with this
|
|
1756
|
+
* Conversation last. Root Conversations omit it.
|
|
1757
|
+
*/
|
|
1758
|
+
agentTree: z.array(conversationAgentTreeNodeSchema).min(2).optional(),
|
|
1759
|
+
/** The viewer's effective auto-archive choice. Participants only. */
|
|
1760
|
+
autoArchive: z.boolean().optional(),
|
|
1761
|
+
/** The viewer can fork this conversation from an assistant reply. */
|
|
1762
|
+
canFork: z.boolean().optional(),
|
|
1763
|
+
/** The viewer can move this dashboard conversation to a Slack thread. */
|
|
1764
|
+
canContinueInSlack: z.literal(true).optional(),
|
|
1765
|
+
/**
|
|
1766
|
+
* Event Turn replies stay out of the Location. Set only for a root with
|
|
1767
|
+
* a Location, when the viewer is a participant, who can change it.
|
|
1768
|
+
*/
|
|
1769
|
+
deliveryPaused: z.boolean().optional(),
|
|
1770
|
+
/**
|
|
1771
|
+
* The viewer gets this conversation in their active feed. Participants
|
|
1772
|
+
* only. False after an unsubscribe, until they mention Junior again.
|
|
1773
|
+
*/
|
|
1774
|
+
subscribed: z.boolean().optional(),
|
|
1775
|
+
/** How far the signed-in viewer has read. Absent until they read. */
|
|
1776
|
+
readPosition: conversationReadPositionSchema.optional(),
|
|
1777
|
+
/**
|
|
1778
|
+
* Pass as `after` to the events API to read from the read position.
|
|
1779
|
+
* Present only when unread events start before `events`.
|
|
1780
|
+
*/
|
|
1781
|
+
unreadCursor: z.string().min(1).optional(),
|
|
1782
|
+
/**
|
|
1783
|
+
* The `around` page of `unreadCursor`, when the request asks for it. A
|
|
1784
|
+
* reader who opens at the read position needs no second request.
|
|
1785
|
+
*/
|
|
1786
|
+
unreadPage: conversationEventPageSchema.optional(),
|
|
1787
|
+
forkedFromConversationId: z.string().optional(),
|
|
1788
|
+
/** Title of the fork source, when the viewer can open it. */
|
|
1789
|
+
forkedFromTitle: z.string().optional(),
|
|
1790
|
+
forks: z.array(z.string()).optional(),
|
|
1791
|
+
/** People named in `summary`, resolved at read time. */
|
|
1792
|
+
summaryMentions: z.array(actorIdentitySchema).optional(),
|
|
1793
|
+
modelUsage: z.array(conversationModelUsageSchema).optional(),
|
|
1794
|
+
/**
|
|
1795
|
+
* Each person who wrote in the Conversation, by each of their Identity
|
|
1796
|
+
* ids. Messages and pending messages name their author with
|
|
1797
|
+
* `actorIdentityId`.
|
|
1798
|
+
*/
|
|
1799
|
+
authors: z.record(z.string(), actorIdentitySchema).optional(),
|
|
1800
|
+
events: z.array(conversationReportEventSchema),
|
|
1801
|
+
/**
|
|
1802
|
+
* Events hold only the events after the request's `after` cursor. The
|
|
1803
|
+
* report omits `previousCursor` and `unreadCursor`: the reader keeps its
|
|
1804
|
+
* own.
|
|
1805
|
+
*/
|
|
1806
|
+
appended: z.literal(true).optional(),
|
|
1807
|
+
/**
|
|
1808
|
+
* Pass as `after` on the next detail read to get only newer events.
|
|
1809
|
+
* Absent after a purge.
|
|
1810
|
+
*/
|
|
1811
|
+
appendCursor: z.string().min(1).optional(),
|
|
1812
|
+
eventHistory: conversationEventHistorySchema,
|
|
1813
|
+
previousCursor: z.string().min(1).optional(),
|
|
1814
|
+
generatedAt: z.string(),
|
|
1815
|
+
sentryConversationUrl: z.string().optional(),
|
|
1816
|
+
sourceTask: conversationSourceTaskSchema.optional()
|
|
1817
|
+
}).strict().superRefine(validateConversationEvents);
|
|
1818
|
+
// src/api/schema/automation.ts
|
|
1819
|
+
const automationDestinationSchema = z.object({
|
|
1820
|
+
channelId: z.string().min(1),
|
|
1821
|
+
label: z.string().min(1),
|
|
1822
|
+
teamId: z.string().min(1),
|
|
1823
|
+
visibility: z.enum(["private", "public"])
|
|
1824
|
+
}).strict();
|
|
1825
|
+
/** Automation run counts for the dashboard range control (24h/7d/30d/90d). */
|
|
1826
|
+
const automationRunWindowsSchema = z.object({
|
|
1827
|
+
1: z.number().int().nonnegative(),
|
|
1828
|
+
7: z.number().int().nonnegative(),
|
|
1829
|
+
30: z.number().int().nonnegative(),
|
|
1830
|
+
90: z.number().int().nonnegative()
|
|
1831
|
+
}).strict();
|
|
1832
|
+
/** Linked Conversation cost in USD for each dashboard range. */
|
|
1833
|
+
const automationCostWindowsSchema = z.object({
|
|
1834
|
+
1: z.number().finite().nonnegative(),
|
|
1835
|
+
7: z.number().finite().nonnegative(),
|
|
1836
|
+
30: z.number().finite().nonnegative(),
|
|
1837
|
+
90: z.number().finite().nonnegative()
|
|
1838
|
+
}).strict();
|
|
1839
|
+
const automationSummaryBaseSchema = z.object({
|
|
1840
|
+
costUsd: automationCostWindowsSchema,
|
|
1841
|
+
credentialMode: z.enum(["creator", "system"]),
|
|
1842
|
+
createdAt: z.string().datetime(),
|
|
1843
|
+
createdBy: z.string().min(1),
|
|
1844
|
+
createdByAvatarUrl: z.string().optional(),
|
|
1845
|
+
createdByEmail: z.string().trim().email().optional(),
|
|
1846
|
+
destination: automationDestinationSchema,
|
|
1847
|
+
id: z.string().min(1),
|
|
1848
|
+
task: automationTaskSchema,
|
|
1849
|
+
/** People mentioned in the task text, resolved at read time. */
|
|
1850
|
+
mentions: z.array(actorIdentitySchema).optional(),
|
|
1851
|
+
lastConversationId: z.string().min(1).optional(),
|
|
1852
|
+
lastRunAt: z.string().datetime().optional(),
|
|
1853
|
+
lastRunStatus: z.enum([
|
|
1854
|
+
"blocked",
|
|
1855
|
+
"completed",
|
|
1856
|
+
"failed"
|
|
1857
|
+
]).optional(),
|
|
1858
|
+
ownedByViewer: z.boolean(),
|
|
1859
|
+
/** Newest terminal runs, oldest first, so the list can show recent health. */
|
|
1860
|
+
recentRuns: z.array(z.object({
|
|
1861
|
+
durationMs: z.number().finite().nonnegative().optional(),
|
|
1862
|
+
executedAt: z.string().datetime(),
|
|
1863
|
+
status: z.enum([
|
|
1864
|
+
"blocked",
|
|
1865
|
+
"completed",
|
|
1866
|
+
"failed"
|
|
1867
|
+
])
|
|
1868
|
+
}).strict()).max(20),
|
|
1869
|
+
runs: automationRunWindowsSchema,
|
|
1870
|
+
outcomes: z.array(taskOutcomeSchema).max(5),
|
|
1871
|
+
/** Short display title; falls back from the task when unset. */
|
|
1872
|
+
title: z.string().min(1),
|
|
1873
|
+
/** Linked Conversation cost of every run, since the Automation was created. */
|
|
1874
|
+
totalCostUsd: z.number().finite().nonnegative(),
|
|
1875
|
+
totalRuns: z.number().int().nonnegative()
|
|
1876
|
+
});
|
|
1877
|
+
const scheduledAutomationSummarySchema = automationSummaryBaseSchema.extend({
|
|
1878
|
+
kind: z.literal("scheduled"),
|
|
1879
|
+
nextRunAt: z.string().datetime().optional(),
|
|
1880
|
+
schedule: z.string().min(1),
|
|
1881
|
+
timezone: z.string().min(1),
|
|
1882
|
+
statusReason: z.string().optional(),
|
|
1883
|
+
status: z.enum([
|
|
1884
|
+
"active",
|
|
1885
|
+
"blocked",
|
|
1886
|
+
"paused",
|
|
1887
|
+
"completed"
|
|
1888
|
+
])
|
|
1889
|
+
}).strict();
|
|
1890
|
+
/** An Event trigger in plain words, the same in the dashboard and Slack. */
|
|
1891
|
+
const eventTriggerDescriptionSchema = z.object({
|
|
1892
|
+
events: z.array(z.string().min(1)).min(1),
|
|
1893
|
+
filters: z.array(z.string().min(1)),
|
|
1894
|
+
/** Why the trigger cannot work. The trigger is available when empty. */
|
|
1895
|
+
problems: z.array(z.string().min(1))
|
|
1896
|
+
}).strict();
|
|
1897
|
+
const eventAutomationSummarySchema = automationSummaryBaseSchema.extend({
|
|
1898
|
+
trigger: eventTriggerDescriptionSchema,
|
|
1899
|
+
kind: z.literal("event"),
|
|
1900
|
+
resource: z.string().min(1),
|
|
1901
|
+
source: z.string().min(1),
|
|
1902
|
+
statusReason: z.string().optional(),
|
|
1903
|
+
status: z.enum([
|
|
1904
|
+
"active",
|
|
1905
|
+
"blocked",
|
|
1906
|
+
"paused"
|
|
1907
|
+
])
|
|
1908
|
+
}).strict();
|
|
1909
|
+
const automationSummarySchema = z.discriminatedUnion("kind", [scheduledAutomationSummarySchema, eventAutomationSummarySchema]);
|
|
1910
|
+
/**
|
|
1911
|
+
* Totals that read every run of an Automation. Only the Automation page
|
|
1912
|
+
* shows them, so list rows leave them out.
|
|
1913
|
+
*/
|
|
1914
|
+
const AUTOMATION_TOTAL_FIELDS = {
|
|
1915
|
+
costUsd: true,
|
|
1916
|
+
runs: true,
|
|
1917
|
+
totalCostUsd: true,
|
|
1918
|
+
totalRuns: true
|
|
1919
|
+
};
|
|
1920
|
+
/** One list row: a summary without the totals that read every run. */
|
|
1921
|
+
const automationListItemSchema = z.discriminatedUnion("kind", [scheduledAutomationSummarySchema.omit(AUTOMATION_TOTAL_FIELDS), eventAutomationSummarySchema.omit(AUTOMATION_TOTAL_FIELDS)]);
|
|
1922
|
+
/** UTC day (`YYYY-MM-DD`) or hour (`YYYY-MM-DDTHH`) execution bucket key. */
|
|
1923
|
+
const automationMetricBucketSchema = z.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/);
|
|
1924
|
+
const automationListQuerySchema = z.object({
|
|
1925
|
+
q: z.string().trim().max(200).optional(),
|
|
1926
|
+
scope: z.enum([
|
|
1927
|
+
"all",
|
|
1928
|
+
"mine",
|
|
1929
|
+
"public",
|
|
1930
|
+
"attention"
|
|
1931
|
+
]).default("all"),
|
|
1932
|
+
type: z.enum([
|
|
1933
|
+
"all",
|
|
1934
|
+
"scheduled",
|
|
1935
|
+
"event"
|
|
1936
|
+
]).default("all"),
|
|
1937
|
+
state: z.enum([
|
|
1938
|
+
"all",
|
|
1939
|
+
"active",
|
|
1940
|
+
"blocked",
|
|
1941
|
+
"paused",
|
|
1942
|
+
"completed",
|
|
1943
|
+
"unavailable"
|
|
1944
|
+
]).default("all"),
|
|
1945
|
+
creator: z.string().max(300).optional(),
|
|
1946
|
+
/** Only the viewer's own Automations, inside any scope. */
|
|
1947
|
+
owner: z.literal("me").optional(),
|
|
1948
|
+
destination: z.string().max(300).optional(),
|
|
1949
|
+
/** Only Automations that run this skill. */
|
|
1950
|
+
skill: automationSkillNameSchema.optional(),
|
|
1951
|
+
/**
|
|
1952
|
+
* `activity` lists the latest run or creation first, and pages with
|
|
1953
|
+
* `cursor`. The other orders page with `page`.
|
|
1954
|
+
*/
|
|
1955
|
+
sort: z.enum([
|
|
1956
|
+
"newest",
|
|
1957
|
+
"oldest",
|
|
1958
|
+
"title",
|
|
1959
|
+
"activity"
|
|
1960
|
+
]).default("newest"),
|
|
1961
|
+
/** `nextCursor` of the page before, with `sort=activity`. */
|
|
1962
|
+
cursor: z.string().min(1).max(1e3).optional(),
|
|
1963
|
+
page: z.coerce.number().int().min(1).max(1e6).default(1),
|
|
1964
|
+
pageSize: z.coerce.number().int().min(1).max(100).default(25)
|
|
1965
|
+
}).strict();
|
|
1966
|
+
const automationFilterOptionSchema = z.object({
|
|
1967
|
+
value: z.string(),
|
|
1968
|
+
label: z.string()
|
|
1969
|
+
}).strict();
|
|
1970
|
+
const automationListSchema = z.object({
|
|
1971
|
+
automations: z.array(automationListItemSchema),
|
|
1972
|
+
/** Set when more rows follow `sort=activity`. Pass it as `cursor`. */
|
|
1973
|
+
nextCursor: z.string().min(1).optional(),
|
|
1974
|
+
total: z.number().int().nonnegative(),
|
|
1975
|
+
page: z.number().int().positive(),
|
|
1976
|
+
pageSize: z.number().int().positive(),
|
|
1977
|
+
counts: z.object({
|
|
1978
|
+
all: z.number().int().nonnegative(),
|
|
1979
|
+
mine: z.number().int().nonnegative(),
|
|
1980
|
+
public: z.number().int().nonnegative(),
|
|
1981
|
+
private: z.number().int().nonnegative()
|
|
1982
|
+
}).strict(),
|
|
1983
|
+
creators: z.array(automationFilterOptionSchema),
|
|
1984
|
+
destinations: z.array(automationFilterOptionSchema)
|
|
1985
|
+
}).strict();
|
|
1986
|
+
/**
|
|
1987
|
+
* One `sort=activity` page. A page after the first omits the total, counts,
|
|
1988
|
+
* and filter options, because the first page already has them.
|
|
1989
|
+
*/
|
|
1990
|
+
const automationListPageSchema = automationListSchema.partial({
|
|
1991
|
+
total: true,
|
|
1992
|
+
counts: true,
|
|
1993
|
+
creators: true,
|
|
1994
|
+
destinations: true
|
|
1995
|
+
});
|
|
1996
|
+
const automationParamsSchema = z.object({ id: z.string().min(1) }).strict();
|
|
1997
|
+
const automationExecutionStatusSchema = z.enum([
|
|
1998
|
+
"blocked",
|
|
1999
|
+
"completed",
|
|
2000
|
+
"failed"
|
|
2001
|
+
]);
|
|
2002
|
+
const automationExecutionSchema = z.object({
|
|
2003
|
+
/** Automation version that the run dispatched, when recorded. */
|
|
2004
|
+
automationVersion: z.number().int().positive().optional(),
|
|
2005
|
+
conversationId: z.string().min(1).optional(),
|
|
2006
|
+
/** Estimated model cost for the linked conversation, when known. */
|
|
2007
|
+
costUsd: z.number().finite().nonnegative().optional(),
|
|
2008
|
+
/** Accounts that the dispatched version could use. */
|
|
2009
|
+
credentialMode: z.enum(["creator", "system"]).optional(),
|
|
2010
|
+
/** Cumulative conversation runtime in milliseconds, when known. */
|
|
2011
|
+
durationMs: z.number().finite().nonnegative().optional(),
|
|
2012
|
+
/** Reason that the run failed or was blocked, when recorded. */
|
|
2013
|
+
error: z.string().min(1).optional(),
|
|
2014
|
+
executedAt: z.string().datetime(),
|
|
2015
|
+
executionId: z.string().min(1),
|
|
2016
|
+
/** Planned occurrence of a Scheduled automation run. */
|
|
2017
|
+
scheduledFor: z.string().datetime().optional(),
|
|
2018
|
+
startedAt: z.string().datetime().optional(),
|
|
2019
|
+
status: automationExecutionStatusSchema,
|
|
2020
|
+
title: z.string().min(1).optional(),
|
|
2021
|
+
/** Cumulative conversation token total, when known. */
|
|
2022
|
+
totalTokens: z.number().int().nonnegative().optional()
|
|
2023
|
+
}).strict();
|
|
2024
|
+
/** One UTC day/hour of terminal executions for a single automation, stacked by status. */
|
|
2025
|
+
const automationExecutionStatusDaySchema = z.object({
|
|
2026
|
+
blocked: z.number().int().nonnegative(),
|
|
2027
|
+
completed: z.number().int().nonnegative(),
|
|
2028
|
+
/** Linked Conversation cost of the runs in this bucket. */
|
|
2029
|
+
costUsd: z.number().finite().nonnegative(),
|
|
2030
|
+
date: automationMetricBucketSchema,
|
|
2031
|
+
failed: z.number().int().nonnegative()
|
|
2032
|
+
}).strict();
|
|
2033
|
+
const automationExecutionListSchema = z.object({
|
|
2034
|
+
executionDays: z.array(automationExecutionStatusDaySchema),
|
|
2035
|
+
executionHours: z.array(automationExecutionStatusDaySchema).optional(),
|
|
2036
|
+
executionSixHours: z.array(automationExecutionStatusDaySchema).optional(),
|
|
2037
|
+
executions: z.array(automationExecutionSchema),
|
|
2038
|
+
truncated: z.boolean()
|
|
2039
|
+
}).strict();
|
|
2040
|
+
const automationRunSchema = automationExecutionSchema.extend({
|
|
2041
|
+
kind: z.enum(["scheduled", "event"]),
|
|
2042
|
+
automationId: z.string().min(1),
|
|
2043
|
+
automationTitle: z.string().min(1)
|
|
2044
|
+
}).strict();
|
|
2045
|
+
const automationRunListSchema = z.object({
|
|
2046
|
+
runs: z.array(automationRunSchema),
|
|
2047
|
+
truncated: z.boolean()
|
|
2048
|
+
}).strict();
|
|
2049
|
+
const automationDefinitionFields = {
|
|
2050
|
+
title: z.string().nullable(),
|
|
2051
|
+
task: automationTaskSchema
|
|
2052
|
+
};
|
|
2053
|
+
const automationVersionFields = {
|
|
2054
|
+
version: z.number().int().positive(),
|
|
2055
|
+
createdAt: z.string().datetime(),
|
|
2056
|
+
/** Null for versions saved by the upgrade, because the editor is unknown. */
|
|
2057
|
+
editedBy: eventAutomationPrincipalSchema.nullable()
|
|
2058
|
+
};
|
|
2059
|
+
const scheduledAutomationVersionSchema = z.object({
|
|
2060
|
+
...automationVersionFields,
|
|
2061
|
+
kind: z.literal("scheduled"),
|
|
2062
|
+
definition: scheduledAutomationSchema.pick({
|
|
2063
|
+
credentialMode: true,
|
|
2064
|
+
destination: true,
|
|
2065
|
+
outcomes: true,
|
|
2066
|
+
schedule: true
|
|
2067
|
+
}).extend(automationDefinitionFields).strict()
|
|
2068
|
+
}).strict();
|
|
2069
|
+
const eventAutomationVersionSchema = z.object({
|
|
2070
|
+
...automationVersionFields,
|
|
2071
|
+
kind: z.literal("event"),
|
|
2072
|
+
definition: eventAutomationSchema.pick({
|
|
2073
|
+
credentialMode: true,
|
|
2074
|
+
destination: true,
|
|
2075
|
+
outcomes: true,
|
|
2076
|
+
trigger: true
|
|
2077
|
+
}).extend(automationDefinitionFields).strict()
|
|
2078
|
+
}).strict();
|
|
2079
|
+
/** One saved Automation definition. Newer versions have larger numbers. */
|
|
2080
|
+
const automationVersionSchema = z.discriminatedUnion("kind", [scheduledAutomationVersionSchema, eventAutomationVersionSchema]);
|
|
2081
|
+
/**
|
|
2082
|
+
* One version in the version history. An Event version also has its saved
|
|
2083
|
+
* trigger in plain words. The definition stays as saved, so it can be made
|
|
2084
|
+
* active again.
|
|
2085
|
+
*/
|
|
2086
|
+
const listedAutomationVersionSchema = z.discriminatedUnion("kind", [scheduledAutomationVersionSchema, eventAutomationVersionSchema.extend({ trigger: eventTriggerDescriptionSchema }).strict()]);
|
|
2087
|
+
/** Newest versions first. */
|
|
2088
|
+
const automationVersionListSchema = z.object({
|
|
2089
|
+
versions: z.array(listedAutomationVersionSchema),
|
|
2090
|
+
/** Newest version that matches the current definition. Null when none match. */
|
|
2091
|
+
activeVersion: z.number().int().positive().nullable(),
|
|
2092
|
+
truncated: z.boolean()
|
|
2093
|
+
}).strict();
|
|
2094
|
+
const automationVersionParamsSchema = automationParamsSchema.extend({ version: z.coerce.number().int().positive() }).strict();
|
|
2095
|
+
const automationRevisionSchema = z.string().regex(/^[a-f0-9]{64}$/);
|
|
2096
|
+
/** Make a saved version active. The revision is the edit read revision. */
|
|
2097
|
+
const automationVersionActivateSchema = z.object({ revision: automationRevisionSchema }).strict();
|
|
2098
|
+
/** Pause and resume do not start work. */
|
|
2099
|
+
const automationLifecycleSchema = z.object({
|
|
2100
|
+
action: z.enum(["pause", "resume"]),
|
|
2101
|
+
revision: automationRevisionSchema
|
|
2102
|
+
}).strict();
|
|
2103
|
+
const automationEditBaseSchema = scheduledAutomationSchema.pick({
|
|
2104
|
+
destination: true,
|
|
2105
|
+
createdBy: true
|
|
2106
|
+
}).extend({
|
|
2107
|
+
id: z.string().min(1),
|
|
2108
|
+
revision: automationRevisionSchema,
|
|
2109
|
+
title: z.string().nullable(),
|
|
2110
|
+
task: automationTaskSchema,
|
|
2111
|
+
credentialMode: z.enum(["system", "creator"]),
|
|
2112
|
+
outcomes: z.array(taskOutcomeSchema).max(5),
|
|
2113
|
+
/** Creator-only rules apply when false. */
|
|
2114
|
+
ownedByViewer: z.boolean()
|
|
2115
|
+
});
|
|
2116
|
+
/** Edit values for owners and public readers. Read schemas also retain legacy values. */
|
|
2117
|
+
const automationEditSchema = z.discriminatedUnion("kind", [automationEditBaseSchema.merge(scheduledAutomationSchema.pick({ schedule: true })).extend({
|
|
2118
|
+
kind: z.literal("scheduled"),
|
|
2119
|
+
nextRunAtMs: z.number().optional(),
|
|
2120
|
+
status: z.enum([
|
|
2121
|
+
"active",
|
|
2122
|
+
"blocked",
|
|
2123
|
+
"paused",
|
|
2124
|
+
"completed"
|
|
2125
|
+
])
|
|
2126
|
+
}).strict(), automationEditBaseSchema.extend({
|
|
2127
|
+
kind: z.literal("event"),
|
|
2128
|
+
trigger: eventAutomationTriggerSchema,
|
|
2129
|
+
status: z.enum([
|
|
2130
|
+
"active",
|
|
2131
|
+
"blocked",
|
|
2132
|
+
"paused"
|
|
2133
|
+
])
|
|
2134
|
+
}).strict()]);
|
|
2135
|
+
/** Partial edits require the revision returned by the edit read. */
|
|
2136
|
+
const automationUpdateSchema = z.discriminatedUnion("kind", [scheduledAutomationEditSchema.extend({
|
|
2137
|
+
kind: z.literal("scheduled"),
|
|
2138
|
+
revision: automationRevisionSchema
|
|
2139
|
+
}).strict(), eventAutomationEditSchema.extend({
|
|
2140
|
+
kind: z.literal("event"),
|
|
2141
|
+
revision: automationRevisionSchema
|
|
2142
|
+
}).strict()]);
|
|
2143
|
+
const automationEditErrorSchema = z.object({
|
|
2144
|
+
error: z.string(),
|
|
2145
|
+
code: z.enum([
|
|
2146
|
+
"invalid_edit",
|
|
2147
|
+
"conflict",
|
|
2148
|
+
"not_found"
|
|
2149
|
+
]),
|
|
2150
|
+
fields: z.record(z.string(), z.array(z.string())).optional()
|
|
2151
|
+
}).strict();
|
|
2152
|
+
/**
|
|
2153
|
+
* Catalog metadata only, one entry for each namespace. Callbacks, guidance,
|
|
2154
|
+
* and provider connections stay on the server. `events` gives the reach of
|
|
2155
|
+
* each event once, and `anyResourceFields` gives the filters of every
|
|
2156
|
+
* resource type, for a trigger with no identifier.
|
|
2157
|
+
*/
|
|
2158
|
+
const automationEventCatalogSchema = z.array(z.object({
|
|
2159
|
+
namespace: z.string(),
|
|
2160
|
+
displayName: z.string(),
|
|
2161
|
+
events: z.record(z.string(), z.object({ reach: eventReachSchema })),
|
|
2162
|
+
anyResourceFields: eventMatchFieldsSchema,
|
|
2163
|
+
resourceTypes: z.array(pluginEventTypeSchema)
|
|
2164
|
+
}).strict());
|
|
2165
|
+
const automationScheduleIntentSchema = scheduleIntentSchema;
|
|
2166
|
+
const automationSchedulePreviewSchema = scheduledAutomationSchema.pick({ schedule: true }).extend({ nextRunAtMs: z.number() }).strict();
|
|
2167
|
+
// src/api/schema/response.ts
|
|
2168
|
+
/** Stable error body returned by Junior-owned REST endpoints. */
|
|
2169
|
+
const apiErrorSchema = z.object({ error: z.string().min(1) }).strict();
|
|
2170
|
+
/**
|
|
2171
|
+
* Carries a content token in both directions. A custom header, not `ETag` /
|
|
2172
|
+
* `If-None-Match`: the Vercel CDN removes `If-None-Match` before it calls the
|
|
2173
|
+
* function, with every `Cache-Control` value, and no setting stops this. The
|
|
2174
|
+
* CDN then answers a match with a 304 only after the function built the full
|
|
2175
|
+
* response, so the read is not saved and the 304 does not show in app
|
|
2176
|
+
* telemetry. A probe deployment confirmed this for `private, no-cache`,
|
|
2177
|
+
* `no-cache`, `private, no-store`, `private, max-age=0, must-revalidate`, and
|
|
2178
|
+
* no header. See
|
|
2179
|
+
* https://vercel.com/docs/manage-cdn-usage#optimizing-fast-origin-transfer.
|
|
2180
|
+
* A read that sends the token of the copy it holds gets an empty 304 while
|
|
2181
|
+
* the content is unchanged.
|
|
2182
|
+
*/
|
|
2183
|
+
const CONTENT_VERSION_HEADER = "x-junior-content-version";
|
|
2184
|
+
// src/chat/notifications/schedule.ts
|
|
2185
|
+
/**
|
|
2186
|
+
* Notification hours for one user.
|
|
2187
|
+
*
|
|
2188
|
+
* This module imports only zod and the browser-safe cadence helpers, so the
|
|
2189
|
+
* dashboard client bundle can use it.
|
|
2190
|
+
*/
|
|
2191
|
+
const clockTimePattern = /^([01]\d|2[0-3]):[0-5]\d$/;
|
|
2192
|
+
/** Saved notification hours. Weekdays use 0 for Sunday, like `Date#getDay`. */
|
|
2193
|
+
const notificationScheduleSchema = z.object({
|
|
2194
|
+
/**
|
|
2195
|
+
* Follow the linked Slack user's notification schedule. The fields below
|
|
2196
|
+
* apply only when Junior cannot read it. Absent means on.
|
|
2197
|
+
*/
|
|
2198
|
+
followSlack: z.boolean().optional(),
|
|
2199
|
+
/** When false, Junior sends push notifications at any time. */
|
|
2200
|
+
workingHoursOnly: z.boolean(),
|
|
2201
|
+
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." }),
|
|
2202
|
+
/** Local start time, `HH:MM`. */
|
|
2203
|
+
start: z.string().regex(clockTimePattern),
|
|
2204
|
+
/** Local end time, `HH:MM`. An end before the start crosses midnight. */
|
|
2205
|
+
end: z.string().regex(clockTimePattern),
|
|
2206
|
+
/** IANA timezone set by the user. Absent means the profile timezone. */
|
|
2207
|
+
timezone: z.string().min(1).max(64).refine(isValidTimeZone, { message: "Unknown timezone." }).optional()
|
|
2208
|
+
}).strict().refine((schedule) => schedule.start !== schedule.end, {
|
|
2209
|
+
message: "Start and end must differ.",
|
|
2210
|
+
path: ["end"]
|
|
2211
|
+
});
|
|
2212
|
+
/**
|
|
2213
|
+
* Default when a user has not saved a schedule: follow Slack, else
|
|
2214
|
+
* 09:00–18:00, Mon–Fri.
|
|
2215
|
+
*/
|
|
2216
|
+
const DEFAULT_NOTIFICATION_SCHEDULE = {
|
|
2217
|
+
followSlack: true,
|
|
2218
|
+
workingHoursOnly: true,
|
|
2219
|
+
days: [
|
|
2220
|
+
1,
|
|
2221
|
+
2,
|
|
2222
|
+
3,
|
|
2223
|
+
4,
|
|
2224
|
+
5
|
|
2225
|
+
],
|
|
2226
|
+
start: "09:00",
|
|
2227
|
+
end: "18:00"
|
|
2228
|
+
};
|
|
2229
|
+
function clockMinutes(value) {
|
|
2230
|
+
const [hours, minutes] = value.split(":").map(Number);
|
|
2231
|
+
return hours * 60 + minutes;
|
|
2232
|
+
}
|
|
2233
|
+
const weekdayIndex = {
|
|
2234
|
+
Sun: 0,
|
|
2235
|
+
Mon: 1,
|
|
2236
|
+
Tue: 2,
|
|
2237
|
+
Wed: 3,
|
|
2238
|
+
Thu: 4,
|
|
2239
|
+
Fri: 5,
|
|
2240
|
+
Sat: 6
|
|
2241
|
+
};
|
|
2242
|
+
function localWeekdayAndMinutes(nowMs, timezone) {
|
|
2243
|
+
const parts = new Intl.DateTimeFormat("en-US", {
|
|
2244
|
+
hour: "2-digit",
|
|
2245
|
+
hourCycle: "h23",
|
|
2246
|
+
minute: "2-digit",
|
|
2247
|
+
timeZone: timezone,
|
|
2248
|
+
weekday: "short"
|
|
2249
|
+
}).formatToParts(new Date(nowMs));
|
|
2250
|
+
const value = (type) => parts.find((part) => part.type === type)?.value ?? "";
|
|
2251
|
+
const weekday = weekdayIndex[value("weekday")];
|
|
2252
|
+
if (weekday === void 0) throw new Error(`Could not read the weekday for timezone ${timezone}`);
|
|
2253
|
+
return {
|
|
2254
|
+
minutes: Number(value("hour")) % 24 * 60 + Number(value("minute")),
|
|
2255
|
+
weekday
|
|
2256
|
+
};
|
|
2257
|
+
}
|
|
2258
|
+
/**
|
|
2259
|
+
* Return whether a notification may be sent now. A window that crosses
|
|
2260
|
+
* midnight belongs to the day on which it starts.
|
|
2261
|
+
*/
|
|
2262
|
+
function isWithinNotificationSchedule(schedule, timezone, nowMs) {
|
|
2263
|
+
if (!schedule.workingHoursOnly) return true;
|
|
2264
|
+
const { minutes, weekday } = localWeekdayAndMinutes(nowMs, timezone);
|
|
2265
|
+
const start = clockMinutes(schedule.start);
|
|
2266
|
+
const end = clockMinutes(schedule.end);
|
|
2267
|
+
if (start < end) return schedule.days.includes(weekday) && minutes >= start && minutes < end;
|
|
2268
|
+
if (minutes >= start) return schedule.days.includes(weekday);
|
|
2269
|
+
if (minutes < end) return schedule.days.includes((weekday + 6) % 7);
|
|
2270
|
+
return false;
|
|
2271
|
+
}
|
|
2272
|
+
// src/chat/attachments/media.ts
|
|
2273
|
+
const INPUT_IMAGE_TYPES = [
|
|
2274
|
+
"image/png",
|
|
2275
|
+
"image/jpeg",
|
|
2276
|
+
"image/gif",
|
|
2277
|
+
"image/webp"
|
|
2278
|
+
];
|
|
2279
|
+
/** Video types that browsers play in a `<video>` element. */
|
|
2280
|
+
const INLINE_VIDEO_TYPES = ["video/mp4", "video/webm"];
|
|
2281
|
+
/** Leading bytes of each accepted image type. `null` matches any byte. */
|
|
2282
|
+
const IMAGE_SIGNATURES = [
|
|
2283
|
+
{
|
|
2284
|
+
mediaType: "image/png",
|
|
2285
|
+
bytes: [
|
|
2286
|
+
137,
|
|
2287
|
+
80,
|
|
2288
|
+
78,
|
|
2289
|
+
71,
|
|
2290
|
+
13,
|
|
2291
|
+
10,
|
|
2292
|
+
26,
|
|
2293
|
+
10
|
|
2294
|
+
]
|
|
2295
|
+
},
|
|
2296
|
+
{
|
|
2297
|
+
mediaType: "image/jpeg",
|
|
2298
|
+
bytes: [
|
|
2299
|
+
255,
|
|
2300
|
+
216,
|
|
2301
|
+
255
|
|
2302
|
+
]
|
|
2303
|
+
},
|
|
2304
|
+
{
|
|
2305
|
+
mediaType: "image/gif",
|
|
2306
|
+
bytes: [
|
|
2307
|
+
71,
|
|
2308
|
+
73,
|
|
2309
|
+
70,
|
|
2310
|
+
56,
|
|
2311
|
+
55,
|
|
2312
|
+
97
|
|
2313
|
+
]
|
|
2314
|
+
},
|
|
2315
|
+
{
|
|
2316
|
+
mediaType: "image/gif",
|
|
2317
|
+
bytes: [
|
|
2318
|
+
71,
|
|
2319
|
+
73,
|
|
2320
|
+
70,
|
|
2321
|
+
56,
|
|
2322
|
+
57,
|
|
2323
|
+
97
|
|
2324
|
+
]
|
|
2325
|
+
},
|
|
2326
|
+
{
|
|
2327
|
+
mediaType: "image/webp",
|
|
2328
|
+
bytes: [
|
|
2329
|
+
82,
|
|
2330
|
+
73,
|
|
2331
|
+
70,
|
|
2332
|
+
70,
|
|
2333
|
+
null,
|
|
2334
|
+
null,
|
|
2335
|
+
null,
|
|
2336
|
+
null,
|
|
2337
|
+
87,
|
|
2338
|
+
69,
|
|
2339
|
+
66,
|
|
2340
|
+
80
|
|
2341
|
+
]
|
|
2342
|
+
}
|
|
2343
|
+
];
|
|
2344
|
+
/**
|
|
2345
|
+
* Detect an accepted image type from file bytes. Use this instead of a file
|
|
2346
|
+
* name or declared content type, which can be wrong.
|
|
2347
|
+
*/
|
|
2348
|
+
function detectImageMediaType(data) {
|
|
2349
|
+
return IMAGE_SIGNATURES.find(({ bytes }) => data.length >= bytes.length && bytes.every((byte, index) => byte === null || data[index] === byte))?.mediaType;
|
|
2350
|
+
}
|
|
2351
|
+
/** Report whether a media type is a raster image accepted by vision models. */
|
|
2352
|
+
function isVisionImageMediaType(mediaType) {
|
|
2353
|
+
const normalized = mediaType.split(";", 1)[0]?.trim().toLowerCase();
|
|
2354
|
+
return normalized ? INPUT_IMAGE_TYPES.some((type) => type === normalized) : false;
|
|
2355
|
+
}
|
|
2356
|
+
export { conversationReportStatusSchema as $, formatUserInputAnswer as $t, automationVersionActivateSchema as A, automationContextToolSchema as At, conversationActivityPreviewSchema as B, toolScheduleIntentSchema as Bt, automationRunListSchema as C, removedCardSchema as Ct, automationSchedulePreviewSchema as D, inputFileSchema as Dt, automationScheduleIntentSchema as E, MAX_INPUT_ATTACHMENTS as Et, scheduledAutomationSummarySchema as F, scheduledAutomationSchema as Ft, conversationDetailReportSchema as G, isValidTimeZone as Gt, conversationAttachmentQuerySchema as H, getFirstRunAtMs as Ht, CONVERSATION_DETAIL_VERSION_HEADER as I, scheduledRunSchema as It, conversationEventsQuerySchema as J, inboxItemRequestSchema as Jt, conversationEventHistorySchema as K, eventAutomationSchema as Kt, CONVERSATION_VERSION_HEADER as L, ScheduleIntentError as Lt, automationVersionParamsSchema as M, automationTitleSchema as Mt, automationVersionSchema as N, taskOutcomeInputSchema as Nt, automationSummarySchema as O, messageAttachmentSchema as Ot, eventAutomationSummarySchema as P, SCHEDULED_AUTOMATION_SYSTEM_ACTOR as Pt, conversationReportMessageEventSchema as Q, buttonUserInputField as Qt, acceptedConversationMessageSchema as R, compileScheduleIntent as Rt, automationParamsSchema as S, readMessageCardRefs as St, automationRunWindowsSchema as T, MAX_ATTACHMENT_BYTES as Tt, conversationAuxiliaryCostsSchema as U, getNextRunAtMs as Ut, conversationAttachmentParamsSchema as V, weekdaySchema as Vt, conversationDetailQuerySchema as W, getZonedDateTimeParts as Wt, conversationReportEventDataSchema as X, USER_INPUT_NOTE as Xt, conversationParamsSchema as Y, USER_INPUT_LIMITS as Yt, conversationReportEventSchema as Z, answeredChoices as Zt, automationLifecycleSchema as _, conversationReadPositionSchema as _t, DEFAULT_NOTIFICATION_SCHEDULE as a, automationTaskDescription as an, idempotencyKeySchema as at, automationListQuerySchema as b, messageCardRef as bt, CONTENT_VERSION_HEADER as c, AGENT_TYPES as ct, automationEditSchema as d, formatAgentTypes as dt, isEmptyUserInputAnswer as en, conversationSummaryReportSchema as et, automationEventCatalogSchema as f, conversationTreeStateSchema as ft, automationExecutionStatusSchema as g, renameConversationResponseSchema as gt, automationExecutionStatusDaySchema as h, renameConversationBodySchema as ht, isVisionImageMediaType as i, automationTaskColumns as in, createConversationMessageBodySchema as it, automationVersionListSchema as j, automationInstructionToolSchema as jt, automationUpdateSchema as k, readMessageAttachments as kt, apiErrorSchema as l, agentTypeInstructions as lt, automationExecutionSchema as m, conversationTitleSchema as mt, INPUT_IMAGE_TYPES as n, userInputRequestSchema as nn, conversationUsageSchema as nt, isWithinNotificationSchedule as o, automationTaskSchema as on, activityPreviewText as ot, automationExecutionListSchema as p, CONVERSATION_TITLE_MAX_LENGTH as pt, conversationEventPageSchema as q, eventAutomationTriggerSchema as qt, detectImageMediaType as r, automationSkillNameSchema as rn, createConversationBodySchema as rt, notificationScheduleSchema as s, automationTaskText as sn, conversationChildAgentTotalsSchema as st, INLINE_VIDEO_TYPES as t, normalizeUserInputAnswer as tn, conversationSurfaceSchema as tt, automationEditErrorSchema as u, agentTypeSchema as ut, automationListItemSchema as v, inboxItemChangeRecordSchema as vt, automationRunSchema as w, resolveMessageCards as wt, automationListSchema as x, messageCardText as xt, automationListPageSchema as y, annotationCard as yt, actorIdentitySchema as z, scheduleIntentFromTool as zt };
|