Open History to see the last commit
1import * as Schema from "effect/Schema";
2
3import {
4 CommandId,
5 ForwardCompatibleArray,
6 IsoDateTime,
7 ProjectId,
8 ScheduledTaskId,
9 SecretRef,
10 ThreadId,
11 TrimmedNonEmptyString,
12} from "./baseSchemas.ts";
13import { ModelSelection } from "./modelSelection.ts";
14import {
15 OrchestrationV2Actor,
16 OrchestrationV2CreationSource,
17 OrchestrationV2ThreadLaunchWorkspaceStrategy,
18} from "./orchestrationV2.ts";
19import { ProviderInteractionMode, RuntimeMode } from "./providerPolicy.ts";
20
21const TimeOfDay = TrimmedNonEmptyString.check(
22 Schema.isPattern(/^([01]?\d|2[0-3]):([0-5]\d)$/),
23).annotate({ description: "Local time as HH:MM, such as 09:30." });
24
25export const MIN_SCHEDULED_TASK_INTERVAL_MS = 60_000;
26
27const ScheduledTaskIntervalMs = Schema.Int.check(Schema.isGreaterThan(0));
28
29const ScheduledTaskIntervalSchedule = Schema.Struct({
30 type: Schema.Literal("interval"),
31 everyMs: ScheduledTaskIntervalMs,
32});
33
34const ScheduledTaskFixedTimeSchedule = Schema.Struct({
35 type: Schema.Literal("fixed_time"),
36 timeOfDay: TimeOfDay,
37 weekdays: Schema.optional(
38 Schema.Array(
39 Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 6 })).annotate({
40 description: "Weekday. 0 is Sunday, 6 is Saturday.",
41 }),
42 ).annotate({
43 description: "Default: every day.",
44 }),
45 ),
46});
47
48const ISO_WITH_OFFSET =
49 /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
50
51const YEAR_0000 = Date.parse("0000-01-01T00:00:00Z");
52const YEAR_10000 = Date.parse("+010000-01-01T00:00:00Z");
53
54/** Date.parse rolls impossible days like Feb 30 into the next month, so check the day too. */
55function isIsoWithOffset(value: string): boolean {
56 const match = ISO_WITH_OFFSET.exec(value);
57 // The server stores UTC, which must stay a four-digit year to decode again.
58 const time = Date.parse(value);
59 if (!match || !(time >= YEAR_0000 && time < YEAR_10000)) return false;
60 const [year, month, day] = [Number(match[1]), Number(match[2]), Number(match[3])];
61 const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
62 const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
63 return days !== undefined && day >= 1 && day <= days;
64}
65
66// Checked by filter, not pattern, to keep the MCP tool schema small.
67const ScheduledTaskOnceSchedule = Schema.Struct({
68 type: Schema.Literal("once"),
69 runAt: TrimmedNonEmptyString.check(
70 Schema.makeFilter(
71 (value) => isIsoWithOffset(value) || "Expected an ISO date and time with an offset.",
72 ),
73 ),
74});
75
76const ScheduledTaskWebhookSignatureFields = {
77 header: TrimmedNonEmptyString.annotate({
78 description: "Header with the signature, such as x-hub-signature-256.",
79 }),
80 encoding: Schema.Literals(["hex", "base64"]),
81 prefix: Schema.String.annotate({
82 description: "Text before the digest, such as 'sha256='. Empty for none.",
83 }),
84};
85
86export const ScheduledTaskWebhookSignature = Schema.Struct(
87 ScheduledTaskWebhookSignatureFields,
88).annotate({ description: "HMAC-SHA256 check on the raw body." });
89export type ScheduledTaskWebhookSignature = typeof ScheduledTaskWebhookSignature.Type;
90
91/** Matches how long the relay holds a request for an offline environment. */
92export const MAX_WEBHOOK_DELIVERY_AGE_MINUTES = 24 * 60;
93
94const WebhookMaxDeliveryAgeMinutes = Schema.Int.check(
95 Schema.isBetween({ minimum: 1, maximum: MAX_WEBHOOK_DELIVERY_AGE_MINUTES }),
96).annotate({
97 description: "Skip requests held offline over this many minutes. Omit to run all.",
98});
99
100export function isWebhookDedupeTemplate(template: string): boolean {
101 const placeholders = /\{\{([^{}]*)\}\}/g;
102 const matches = [...template.matchAll(placeholders)];
103 const remainder = template.replace(placeholders, "");
104 return (
105 matches.length > 0 &&
106 matches.every(([, expression]) =>
107 /^(?:(?:body|headers|query)(?:\.\s*[^.\s][^.]*)*|request)$/.test(expression!.trim()),
108 ) &&
109 !remainder.includes("{{") &&
110 !remainder.includes("}}")
111 );
112}
113
114const WebhookDedupeTemplate = Schema.String.check(
115 Schema.makeFilter(
116 (value) =>
117 isWebhookDedupeTemplate(value) ||
118 "Expected at least one request placeholder ({{body.<path>}}, {{headers.<name>}}, {{query.<name>}} or {{request}}), such as {{body.id}}.",
119 ),
120);
121
122const ScheduledTaskWebhookDedupe = Schema.Struct({
123 replayKey: Schema.optional(WebhookDedupeTemplate),
124 coalesceKey: Schema.optional(WebhookDedupeTemplate),
125 coalesceWindowSeconds: Schema.optional(
126 Schema.Int.check(Schema.isBetween({ minimum: 10, maximum: 3600 })),
127 ),
128}).annotate({
129 description: "Key templates such as {{body.id}}. Window in seconds, default 120.",
130});
131
132export const MAX_WEBHOOK_FILTERS = 16;
133
134const WebhookFilterPath = TrimmedNonEmptyString.check(
135 Schema.isPattern(/^(body|headers|query)(\.|$)/),
136);
137
138/**
139 * Forms edit an `in` list as comma-separated text, so a value that has no
140 * comma and no surrounding whitespace survives that round trip unchanged.
141 */
142const WebhookFilterListValue = Schema.String.check(
143 Schema.isPattern(/^[^,\s](?:[^,]*[^,\s])?$/),
144).annotate({ description: "Non-empty, without commas or surrounding whitespace." });
145
146export const ScheduledTaskWebhookFilter = Schema.Union([
147 Schema.Struct({
148 path: WebhookFilterPath,
149 op: Schema.Literals(["equals", "notEquals", "startsWith"]),
150 value: Schema.String,
151 }),
152 Schema.Struct({
153 path: WebhookFilterPath,
154 op: Schema.Literal("in"),
155 value: Schema.Array(WebhookFilterListValue).check(Schema.isMinLength(1)),
156 }),
157 Schema.Struct({ path: WebhookFilterPath, op: Schema.Literal("exists") }),
158]).annotate({
159 description:
160 "Path: `headers.x-event` or `body.action`. String compare. Objects pass only 'exists'. A `[]` segment matches any array item. `notEquals` passes only if no item equals.",
161});
162export type ScheduledTaskWebhookFilter = typeof ScheduledTaskWebhookFilter.Type;
163export type ScheduledTaskWebhookFilterOp = ScheduledTaskWebhookFilter["op"];
164
165const ScheduledTaskWebhookFilters = Schema.Array(ScheduledTaskWebhookFilter)
166 .check(Schema.isMaxLength(MAX_WEBHOOK_FILTERS))
167 .annotate({
168 description: "All must match. Max 16. Omitted: keep stored. [] clears.",
169 });
170
171const ScheduledTaskWebhookSchedule = Schema.Struct({
172 type: Schema.Literal("webhook"),
173 signature: Schema.NullOr(ScheduledTaskWebhookSignature),
174 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
175 dedupe: Schema.optional(ScheduledTaskWebhookDedupe),
176 filters: Schema.optional(ScheduledTaskWebhookFilters),
177}).annotate({
178 description: "Run on each webhook request.",
179});
180
181const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({
182 type: Schema.Literal("webhook"),
183 signature: Schema.optional(
184 Schema.NullOr(
185 Schema.Struct({
186 ...ScheduledTaskWebhookSignatureFields,
187 secret: Schema.optional(TrimmedNonEmptyString).annotate({
188 description: "Default: stored secret.",
189 }),
190 secretRef: Schema.optional(SecretRef).annotate({
191 description: "From `request_secret`. Instead of `secret`. Spent by this save.",
192 }),
193 }),
194 ),
195 ).annotate({
196 description: "Omit for URL token only.",
197 }),
198 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
199 dedupe: Schema.optional(ScheduledTaskWebhookDedupe),
200 filters: Schema.optional(ScheduledTaskWebhookFilters),
201}).annotate({
202 description:
203 "Run per webhook request. Prompt can use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}}, {{request}}.",
204});
205
206/** Accept legacy sub-minute schedules so users can still manage them. */
207export const ScheduledTaskSchedule = Schema.Union([
208 ScheduledTaskIntervalSchedule,
209 ScheduledTaskFixedTimeSchedule,
210 ScheduledTaskOnceSchedule,
211 ScheduledTaskWebhookSchedule,
212]);
213export type ScheduledTaskSchedule = typeof ScheduledTaskSchedule.Type;
214
215export const ScheduledTaskUpsertSchedule = Schema.Union([
216 Schema.Struct({
217 type: Schema.Literal("interval"),
218 everyMs: ScheduledTaskIntervalMs.check(
219 Schema.isGreaterThanOrEqualTo(MIN_SCHEDULED_TASK_INTERVAL_MS),
220 ).annotate({
221 description: "Min 60000.",
222 }),
223 }),
224 ScheduledTaskFixedTimeSchedule,
225 ScheduledTaskOnceSchedule,
226 ScheduledTaskUpsertWebhookSchedule,
227]);
228export type ScheduledTaskUpsertSchedule = typeof ScheduledTaskUpsertSchedule.Type;
229
230export const ScheduledTaskRunStatus = Schema.Literals(["never", "running", "succeeded", "failed"]);
231export type ScheduledTaskRunStatus = typeof ScheduledTaskRunStatus.Type;
232
233export const ScheduledTaskWebhookEndpoint = Schema.Struct({
234 path: TrimmedNonEmptyString,
235 url: Schema.NullOr(TrimmedNonEmptyString),
236 hasSecret: Schema.Boolean,
237});
238export type ScheduledTaskWebhookEndpoint = typeof ScheduledTaskWebhookEndpoint.Type;
239
240/**
241 * Where runs go. One-thread modes launch their thread on the first run and keep it; `fresh_session`
242 * starts each later run in a new provider session there.
243 */
244export const ScheduledTaskThreadMode = Schema.Literals(["new_thread", "continue", "fresh_session"]);
245export type ScheduledTaskThreadMode = typeof ScheduledTaskThreadMode.Type;
246
247/** Servers before thread modes omit it; their bound tasks continue the conversation. */
248export function scheduledTaskThreadMode(
249 task: Pick<ScheduledTask, "threadId" | "threadMode">,
250): ScheduledTaskThreadMode {
251 return task.threadMode ?? (task.threadId === null ? "new_thread" : "continue");
252}
253
254export const ScheduledTask = Schema.Struct({
255 id: ScheduledTaskId,
256 title: TrimmedNonEmptyString,
257 prompt: TrimmedNonEmptyString,
258 enabled: Schema.Boolean,
259 schedule: ScheduledTaskSchedule,
260 projectId: ProjectId,
261 threadId: Schema.NullOr(ThreadId),
262 threadMode: Schema.optional(ScheduledTaskThreadMode),
263 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
264 modelSelection: ModelSelection,
265 runtimeMode: RuntimeMode,
266 interactionMode: ProviderInteractionMode,
267 createdBy: OrchestrationV2Actor,
268 creationSource: OrchestrationV2CreationSource,
269 createdAt: IsoDateTime,
270 updatedAt: IsoDateTime,
271 nextRunAt: Schema.NullOr(IsoDateTime),
272 lastRunAt: Schema.NullOr(IsoDateTime),
273 lastRunStatus: ScheduledTaskRunStatus,
274 lastRunError: Schema.NullOr(Schema.String),
275 runCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
276 webhook: Schema.optional(ScheduledTaskWebhookEndpoint),
277 /** Why the task cannot run regardless of `enabled`, such as a managed policy refusing webhooks. */
278 blockedByPolicy: Schema.optionalKey(Schema.String),
279});
280export type ScheduledTask = typeof ScheduledTask.Type;
281
282export const ScheduledTaskListInput = Schema.Struct({});
283export type ScheduledTaskListInput = typeof ScheduledTaskListInput.Type;
284
285export const ScheduledTaskListResult = Schema.Struct({
286 tasks: ForwardCompatibleArray(ScheduledTask),
287 /** The server's IANA zone for fixed-time schedules. Absent from older servers. */
288 timeZone: Schema.optional(TrimmedNonEmptyString),
289});
290export type ScheduledTaskListResult = typeof ScheduledTaskListResult.Type;
291
292export const ScheduledTaskUpsertInput = Schema.Struct({
293 id: Schema.optional(ScheduledTaskId),
294 requireExisting: Schema.optional(Schema.Boolean).annotate({
295 description:
296 "Reject the save if the task no longer exists, for edits based on an earlier read.",
297 }),
298 commandId: Schema.optional(CommandId),
299 title: TrimmedNonEmptyString,
300 prompt: TrimmedNonEmptyString,
301 enabled: Schema.Boolean,
302 schedule: ScheduledTaskUpsertSchedule,
303 projectId: ProjectId,
304 /** Omitted or null: keep the stored thread, which a first run may have bound since the form opened. */
305 threadId: Schema.optional(Schema.NullOr(ThreadId)),
306 /** True with no `threadId`: the user cleared the thread, so the next run starts one. */
307 unbindThread: Schema.optional(Schema.Boolean),
308 /** Omitted: keep the stored mode, or derive it from `threadId` for a new or rebound task. */
309 threadMode: Schema.optional(ScheduledTaskThreadMode),
310 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
311 modelSelection: ModelSelection,
312 runtimeMode: RuntimeMode,
313 interactionMode: ProviderInteractionMode,
314 createdBy: Schema.optional(OrchestrationV2Actor),
315 creationSource: Schema.optional(OrchestrationV2CreationSource),
316});
317export type ScheduledTaskUpsertInput = typeof ScheduledTaskUpsertInput.Type;
318
319export const ScheduledTaskSetEnabledInput = Schema.Struct({
320 id: ScheduledTaskId,
321 enabled: Schema.Boolean,
322});
323export type ScheduledTaskSetEnabledInput = typeof ScheduledTaskSetEnabledInput.Type;
324
325export const ScheduledTaskDeleteInput = Schema.Struct({
326 id: ScheduledTaskId,
327});
328export type ScheduledTaskDeleteInput = typeof ScheduledTaskDeleteInput.Type;
329
330export const ScheduledTaskRunNowInput = Schema.Struct({
331 id: ScheduledTaskId,
332});
333export type ScheduledTaskRunNowInput = typeof ScheduledTaskRunNowInput.Type;
334
335export const ScheduledTaskRotateWebhookTokenInput = Schema.Struct({
336 id: ScheduledTaskId,
337});
338export type ScheduledTaskRotateWebhookTokenInput = typeof ScheduledTaskRotateWebhookTokenInput.Type;
339
340export const ScheduledTaskWebhookDeliveryId = TrimmedNonEmptyString.pipe(
341 Schema.brand("ScheduledTaskWebhookDeliveryId"),
342);
343export type ScheduledTaskWebhookDeliveryId = typeof ScheduledTaskWebhookDeliveryId.Type;
344
345export const ScheduledTaskWebhookDeliveryOutcome = Schema.Literals([
346 "accepted",
347 "dispatch_failed",
348 "duplicate",
349 "coalesced",
350 "rejected_signature",
351 "disabled",
352 "rate_limited",
353 "expired",
354 "filtered",
355]);
356export type ScheduledTaskWebhookDeliveryOutcome = typeof ScheduledTaskWebhookDeliveryOutcome.Type;
357
358export const ScheduledTaskWebhookDeliverySummary = Schema.Struct({
359 id: ScheduledTaskWebhookDeliveryId,
360 taskId: ScheduledTaskId,
361 receivedAt: IsoDateTime,
362 method: TrimmedNonEmptyString,
363 contentType: Schema.NullOr(Schema.String),
364 bodyBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
365 // Any string, so an outcome added later doesn't break a client's whole list.
366 outcome: Schema.Union([ScheduledTaskWebhookDeliveryOutcome, Schema.String]),
367 signatureVerified: Schema.Boolean,
368 pendingWindow: Schema.optional(Schema.Boolean),
369 missingFields: Schema.Array(Schema.String),
370 error: Schema.NullOr(Schema.String),
371});
372export type ScheduledTaskWebhookDeliverySummary = typeof ScheduledTaskWebhookDeliverySummary.Type;
373
374export const ScheduledTaskWebhookDelivery = Schema.Struct({
375 ...ScheduledTaskWebhookDeliverySummary.fields,
376 query: Schema.String,
377 headers: Schema.Record(Schema.String, Schema.String),
378 body: Schema.String,
379 bodyTruncated: Schema.Boolean,
380 renderedPrompt: Schema.NullOr(Schema.String),
381});
382export type ScheduledTaskWebhookDelivery = typeof ScheduledTaskWebhookDelivery.Type;
383
384export const ScheduledTaskListWebhookDeliveriesInput = Schema.Struct({
385 id: ScheduledTaskId,
386 /**
387 * Sent by clients that decode any outcome. Shipped clients decode a closed
388 * list and fail on the whole response, so without it the server leaves out
389 * rows with outcomes they don't know.
390 */
391 acceptAnyOutcome: Schema.optional(Schema.Boolean),
392});
393export type ScheduledTaskListWebhookDeliveriesInput =
394 typeof ScheduledTaskListWebhookDeliveriesInput.Type;
395
396export const ScheduledTaskListWebhookDeliveriesResult = Schema.Struct({
397 deliveries: Schema.Array(ScheduledTaskWebhookDeliverySummary),
398});
399export type ScheduledTaskListWebhookDeliveriesResult =
400 typeof ScheduledTaskListWebhookDeliveriesResult.Type;
401
402export const ScheduledTaskGetWebhookDeliveryInput = Schema.Struct({
403 id: ScheduledTaskId,
404 deliveryId: ScheduledTaskWebhookDeliveryId,
405 acceptAnyOutcome: Schema.optional(Schema.Boolean),
406});
407export type ScheduledTaskGetWebhookDeliveryInput = typeof ScheduledTaskGetWebhookDeliveryInput.Type;
408
409export const ScheduledTaskGetWebhookDeliveryResult = Schema.Struct({
410 delivery: ScheduledTaskWebhookDelivery,
411});
412export type ScheduledTaskGetWebhookDeliveryResult =
413 typeof ScheduledTaskGetWebhookDeliveryResult.Type;
414
415export const ScheduledTaskMutationResult = Schema.Struct({
416 task: ScheduledTask,
417});
418export type ScheduledTaskMutationResult = typeof ScheduledTaskMutationResult.Type;
419
420export const ScheduledTaskDeleteResult = Schema.Struct({
421 id: ScheduledTaskId,
422});
423export type ScheduledTaskDeleteResult = typeof ScheduledTaskDeleteResult.Type;
424
425export const ScheduledTaskRunNowResult = Schema.Struct({
426 task: ScheduledTask,
427});
428export type ScheduledTaskRunNowResult = typeof ScheduledTaskRunNowResult.Type;
429
430export class ScheduledTaskError extends Schema.TaggedError<ScheduledTaskError>()(
431 "ScheduledTaskError",
432 {
433 message: Schema.String,
434 taskId: Schema.optional(ScheduledTaskId),
435 cause: Schema.optional(Schema.Defect()),
436 },
437) {}