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 ScheduledTaskWebhookSignatureFields = {
49 header: TrimmedNonEmptyString.annotate({
50 description: "Header with the signature, such as x-hub-signature-256.",
51 }),
52 encoding: Schema.Literals(["hex", "base64"]),
53 prefix: Schema.String.annotate({
54 description: "Text before the digest, such as 'sha256='. Empty for none.",
55 }),
56};
57
58export const ScheduledTaskWebhookSignature = Schema.Struct(
59 ScheduledTaskWebhookSignatureFields,
60).annotate({ description: "HMAC-SHA256 check on the raw body." });
61export type ScheduledTaskWebhookSignature = typeof ScheduledTaskWebhookSignature.Type;
62
63/** Matches how long the relay holds a request for an offline environment. */
64export const MAX_WEBHOOK_DELIVERY_AGE_MINUTES = 24 * 60;
65
66const WebhookMaxDeliveryAgeMinutes = Schema.Int.check(
67 Schema.isBetween({ minimum: 1, maximum: MAX_WEBHOOK_DELIVERY_AGE_MINUTES }),
68).annotate({
69 description: "Skip requests held offline over this many minutes. Omit to run all.",
70});
71
72export function isWebhookDedupeTemplate(template: string): boolean {
73 const placeholders = /\{\{\s*(?:(?:body|headers|query)(?:\.[^{}.\s]+)*|request)\s*\}\}/g;
74 const matches = [...template.matchAll(placeholders)];
75 const remainder = template.replace(placeholders, "");
76 return matches.length > 0 && !remainder.includes("{{") && !remainder.includes("}}");
77}
78
79const WebhookDedupeTemplate = Schema.String.check(Schema.makeFilter(isWebhookDedupeTemplate));
80
81const ScheduledTaskWebhookDedupe = Schema.Struct({
82 replayKey: Schema.optional(WebhookDedupeTemplate),
83 coalesceKey: Schema.optional(WebhookDedupeTemplate),
84 coalesceWindowSeconds: Schema.optional(
85 Schema.Int.check(Schema.isBetween({ minimum: 10, maximum: 3600 })),
86 ),
87}).annotate({
88 description: "Replay and coalesce key templates. Window in seconds, default 120.",
89});
90
91export const MAX_WEBHOOK_FILTERS = 16;
92
93const WebhookFilterPath = TrimmedNonEmptyString.check(
94 Schema.isPattern(/^(body|headers|query)(\.|$)/),
95);
96
97/**
98 * Forms edit an `in` list as comma-separated text, so a value that has no
99 * comma and no surrounding whitespace survives that round trip unchanged.
100 */
101const WebhookFilterListValue = Schema.String.check(
102 Schema.isPattern(/^[^,\s](?:[^,]*[^,\s])?$/),
103).annotate({ description: "Non-empty, without commas or surrounding whitespace." });
104
105export const ScheduledTaskWebhookFilter = Schema.Union([
106 Schema.Struct({
107 path: WebhookFilterPath,
108 op: Schema.Literals(["equals", "notEquals", "startsWith"]),
109 value: Schema.String,
110 }),
111 Schema.Struct({
112 path: WebhookFilterPath,
113 op: Schema.Literal("in"),
114 value: Schema.Array(WebhookFilterListValue).check(Schema.isMinLength(1)),
115 }),
116 Schema.Struct({ path: WebhookFilterPath, op: Schema.Literal("exists") }),
117]).annotate({
118 description:
119 "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.",
120});
121export type ScheduledTaskWebhookFilter = typeof ScheduledTaskWebhookFilter.Type;
122export type ScheduledTaskWebhookFilterOp = ScheduledTaskWebhookFilter["op"];
123
124const ScheduledTaskWebhookFilters = Schema.Array(ScheduledTaskWebhookFilter)
125 .check(Schema.isMaxLength(MAX_WEBHOOK_FILTERS))
126 .annotate({
127 description: "All must match. Max 16. Omitted: keep stored. [] clears.",
128 });
129
130const ScheduledTaskWebhookSchedule = Schema.Struct({
131 type: Schema.Literal("webhook"),
132 signature: Schema.NullOr(ScheduledTaskWebhookSignature),
133 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
134 dedupe: Schema.optional(ScheduledTaskWebhookDedupe),
135 filters: Schema.optional(ScheduledTaskWebhookFilters),
136}).annotate({
137 description: "Run on each webhook request.",
138});
139
140const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({
141 type: Schema.Literal("webhook"),
142 signature: Schema.optional(
143 Schema.NullOr(
144 Schema.Struct({
145 ...ScheduledTaskWebhookSignatureFields,
146 secret: Schema.optional(TrimmedNonEmptyString).annotate({
147 description: "Default: stored secret.",
148 }),
149 secretRef: Schema.optional(SecretRef).annotate({
150 description: "From `request_secret`. Instead of `secret`. Spent by this save.",
151 }),
152 }),
153 ),
154 ).annotate({
155 description: "Omit for URL token only.",
156 }),
157 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
158 dedupe: Schema.optional(ScheduledTaskWebhookDedupe),
159 filters: Schema.optional(ScheduledTaskWebhookFilters),
160}).annotate({
161 description:
162 "Run per webhook request. Prompt can use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}}, {{request}}.",
163});
164
165/** Accept legacy sub-minute schedules so users can still manage them. */
166export const ScheduledTaskSchedule = Schema.Union([
167 ScheduledTaskIntervalSchedule,
168 ScheduledTaskFixedTimeSchedule,
169 ScheduledTaskWebhookSchedule,
170]);
171export type ScheduledTaskSchedule = typeof ScheduledTaskSchedule.Type;
172
173export const ScheduledTaskUpsertSchedule = Schema.Union([
174 Schema.Struct({
175 type: Schema.Literal("interval"),
176 everyMs: ScheduledTaskIntervalMs.check(
177 Schema.isGreaterThanOrEqualTo(MIN_SCHEDULED_TASK_INTERVAL_MS),
178 ).annotate({
179 description: "Min 60000.",
180 }),
181 }),
182 ScheduledTaskFixedTimeSchedule,
183 ScheduledTaskUpsertWebhookSchedule,
184]);
185export type ScheduledTaskUpsertSchedule = typeof ScheduledTaskUpsertSchedule.Type;
186
187export const ScheduledTaskRunStatus = Schema.Literals(["never", "running", "succeeded", "failed"]);
188export type ScheduledTaskRunStatus = typeof ScheduledTaskRunStatus.Type;
189
190export const ScheduledTaskWebhookEndpoint = Schema.Struct({
191 path: TrimmedNonEmptyString,
192 url: Schema.NullOr(TrimmedNonEmptyString),
193 hasSecret: Schema.Boolean,
194});
195export type ScheduledTaskWebhookEndpoint = typeof ScheduledTaskWebhookEndpoint.Type;
196
197export const ScheduledTask = Schema.Struct({
198 id: ScheduledTaskId,
199 title: TrimmedNonEmptyString,
200 prompt: TrimmedNonEmptyString,
201 enabled: Schema.Boolean,
202 schedule: ScheduledTaskSchedule,
203 projectId: ProjectId,
204 threadId: Schema.NullOr(ThreadId),
205 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
206 modelSelection: ModelSelection,
207 runtimeMode: RuntimeMode,
208 interactionMode: ProviderInteractionMode,
209 createdBy: OrchestrationV2Actor,
210 creationSource: OrchestrationV2CreationSource,
211 createdAt: IsoDateTime,
212 updatedAt: IsoDateTime,
213 nextRunAt: Schema.NullOr(IsoDateTime),
214 lastRunAt: Schema.NullOr(IsoDateTime),
215 lastRunStatus: ScheduledTaskRunStatus,
216 lastRunError: Schema.NullOr(Schema.String),
217 runCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
218 webhook: Schema.optional(ScheduledTaskWebhookEndpoint),
219});
220export type ScheduledTask = typeof ScheduledTask.Type;
221
222export const ScheduledTaskListInput = Schema.Struct({});
223export type ScheduledTaskListInput = typeof ScheduledTaskListInput.Type;
224
225export const ScheduledTaskListResult = Schema.Struct({
226 tasks: ForwardCompatibleArray(ScheduledTask),
227});
228export type ScheduledTaskListResult = typeof ScheduledTaskListResult.Type;
229
230export const ScheduledTaskUpsertInput = Schema.Struct({
231 id: Schema.optional(ScheduledTaskId),
232 requireExisting: Schema.optional(Schema.Boolean).annotate({
233 description: "Reject the save if the task no longer exists, for edits from a client form.",
234 }),
235 commandId: Schema.optional(CommandId),
236 title: TrimmedNonEmptyString,
237 prompt: TrimmedNonEmptyString,
238 enabled: Schema.Boolean,
239 schedule: ScheduledTaskUpsertSchedule,
240 projectId: ProjectId,
241 threadId: Schema.optional(Schema.NullOr(ThreadId)),
242 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
243 modelSelection: ModelSelection,
244 runtimeMode: RuntimeMode,
245 interactionMode: ProviderInteractionMode,
246 createdBy: Schema.optional(OrchestrationV2Actor),
247 creationSource: Schema.optional(OrchestrationV2CreationSource),
248});
249export type ScheduledTaskUpsertInput = typeof ScheduledTaskUpsertInput.Type;
250
251export const ScheduledTaskSetEnabledInput = Schema.Struct({
252 id: ScheduledTaskId,
253 enabled: Schema.Boolean,
254});
255export type ScheduledTaskSetEnabledInput = typeof ScheduledTaskSetEnabledInput.Type;
256
257export const ScheduledTaskDeleteInput = Schema.Struct({
258 id: ScheduledTaskId,
259});
260export type ScheduledTaskDeleteInput = typeof ScheduledTaskDeleteInput.Type;
261
262export const ScheduledTaskRunNowInput = Schema.Struct({
263 id: ScheduledTaskId,
264});
265export type ScheduledTaskRunNowInput = typeof ScheduledTaskRunNowInput.Type;
266
267export const ScheduledTaskRotateWebhookTokenInput = Schema.Struct({
268 id: ScheduledTaskId,
269});
270export type ScheduledTaskRotateWebhookTokenInput = typeof ScheduledTaskRotateWebhookTokenInput.Type;
271
272export const ScheduledTaskWebhookDeliveryId = TrimmedNonEmptyString.pipe(
273 Schema.brand("ScheduledTaskWebhookDeliveryId"),
274);
275export type ScheduledTaskWebhookDeliveryId = typeof ScheduledTaskWebhookDeliveryId.Type;
276
277export const ScheduledTaskWebhookDeliveryOutcome = Schema.Literals([
278 "accepted",
279 "dispatch_failed",
280 "duplicate",
281 "coalesced",
282 "rejected_signature",
283 "disabled",
284 "rate_limited",
285 "expired",
286 "filtered",
287]);
288export type ScheduledTaskWebhookDeliveryOutcome = typeof ScheduledTaskWebhookDeliveryOutcome.Type;
289
290export const ScheduledTaskWebhookDeliverySummary = Schema.Struct({
291 id: ScheduledTaskWebhookDeliveryId,
292 taskId: ScheduledTaskId,
293 receivedAt: IsoDateTime,
294 method: TrimmedNonEmptyString,
295 contentType: Schema.NullOr(Schema.String),
296 bodyBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
297 // Any string, so an outcome added later doesn't break a client's whole list.
298 outcome: Schema.Union([ScheduledTaskWebhookDeliveryOutcome, Schema.String]),
299 signatureVerified: Schema.Boolean,
300 pendingWindow: Schema.optional(Schema.Boolean),
301 missingFields: Schema.Array(Schema.String),
302 error: Schema.NullOr(Schema.String),
303});
304export type ScheduledTaskWebhookDeliverySummary = typeof ScheduledTaskWebhookDeliverySummary.Type;
305
306export const ScheduledTaskWebhookDelivery = Schema.Struct({
307 ...ScheduledTaskWebhookDeliverySummary.fields,
308 query: Schema.String,
309 headers: Schema.Record(Schema.String, Schema.String),
310 body: Schema.String,
311 bodyTruncated: Schema.Boolean,
312 renderedPrompt: Schema.NullOr(Schema.String),
313});
314export type ScheduledTaskWebhookDelivery = typeof ScheduledTaskWebhookDelivery.Type;
315
316export const ScheduledTaskListWebhookDeliveriesInput = Schema.Struct({
317 id: ScheduledTaskId,
318 /**
319 * Sent by clients that decode any outcome. Shipped clients decode a closed
320 * list and fail on the whole response, so without it the server leaves out
321 * rows with outcomes they don't know.
322 */
323 acceptAnyOutcome: Schema.optional(Schema.Boolean),
324});
325export type ScheduledTaskListWebhookDeliveriesInput =
326 typeof ScheduledTaskListWebhookDeliveriesInput.Type;
327
328export const ScheduledTaskListWebhookDeliveriesResult = Schema.Struct({
329 deliveries: Schema.Array(ScheduledTaskWebhookDeliverySummary),
330});
331export type ScheduledTaskListWebhookDeliveriesResult =
332 typeof ScheduledTaskListWebhookDeliveriesResult.Type;
333
334export const ScheduledTaskGetWebhookDeliveryInput = Schema.Struct({
335 id: ScheduledTaskId,
336 deliveryId: ScheduledTaskWebhookDeliveryId,
337 acceptAnyOutcome: Schema.optional(Schema.Boolean),
338});
339export type ScheduledTaskGetWebhookDeliveryInput = typeof ScheduledTaskGetWebhookDeliveryInput.Type;
340
341export const ScheduledTaskGetWebhookDeliveryResult = Schema.Struct({
342 delivery: ScheduledTaskWebhookDelivery,
343});
344export type ScheduledTaskGetWebhookDeliveryResult =
345 typeof ScheduledTaskGetWebhookDeliveryResult.Type;
346
347export const ScheduledTaskMutationResult = Schema.Struct({
348 task: ScheduledTask,
349});
350export type ScheduledTaskMutationResult = typeof ScheduledTaskMutationResult.Type;
351
352export const ScheduledTaskDeleteResult = Schema.Struct({
353 id: ScheduledTaskId,
354});
355export type ScheduledTaskDeleteResult = typeof ScheduledTaskDeleteResult.Type;
356
357export const ScheduledTaskRunNowResult = Schema.Struct({
358 task: ScheduledTask,
359});
360export type ScheduledTaskRunNowResult = typeof ScheduledTaskRunNowResult.Type;
361
362export class ScheduledTaskError extends Schema.TaggedError<ScheduledTaskError>()(
363 "ScheduledTaskError",
364 {
365 message: Schema.String,
366 taskId: Schema.optional(ScheduledTaskId),
367 cause: Schema.optional(Schema.Defect()),
368 },
369) {}