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
21/** 24-hour "HH:MM" wall-clock time. Mirrors `parseTimeOfDay` on the server. */
22const TimeOfDay = TrimmedNonEmptyString.check(
23 Schema.isPattern(/^([01]?\d|2[0-3]):([0-5]\d)$/),
24).annotate({ description: "Local wall-clock time in 24-hour HH:MM form, such as 09:30." });
25
26export const MIN_SCHEDULED_TASK_INTERVAL_MS = 60_000;
27
28const ScheduledTaskIntervalMs = Schema.Int.check(Schema.isGreaterThan(0)).annotate({
29 description: "Positive interval in milliseconds.",
30});
31
32const ScheduledTaskIntervalSchedule = Schema.Struct({
33 type: Schema.Literal("interval").annotate({
34 description: "Select interval scheduling.",
35 }),
36 everyMs: ScheduledTaskIntervalMs,
37}).annotate({
38 description: "Run repeatedly after a fixed number of milliseconds.",
39});
40
41const ScheduledTaskFixedTimeSchedule = Schema.Struct({
42 type: Schema.Literal("fixed_time").annotate({
43 description: "Select a fixed local wall-clock time.",
44 }),
45 timeOfDay: TimeOfDay,
46 weekdays: Schema.optional(
47 Schema.Array(
48 Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: 6 })).annotate({
49 description: "Weekday number where 0 is Sunday and 6 is Saturday.",
50 }),
51 ).annotate({
52 description: "Optional weekdays; omit to run every day.",
53 }),
54 ),
55}).annotate({
56 description: "Run at a fixed local wall-clock time on selected weekdays.",
57});
58
59const ScheduledTaskWebhookSignatureFields = {
60 header: TrimmedNonEmptyString.annotate({
61 description: "Request header carrying the signature, such as x-hub-signature-256.",
62 }),
63 encoding: Schema.Literals(["hex", "base64"]).annotate({
64 description: "How the HMAC-SHA256 digest is encoded in the header.",
65 }),
66 prefix: Schema.String.annotate({
67 description: "Text before the digest in the header value, such as 'sha256='. Empty for none.",
68 }),
69};
70
71export const ScheduledTaskWebhookSignature = Schema.Struct(
72 ScheduledTaskWebhookSignatureFields,
73).annotate({ description: "Optional HMAC-SHA256 signature check over the raw request body." });
74export type ScheduledTaskWebhookSignature = typeof ScheduledTaskWebhookSignature.Type;
75
76/** Matches how long the relay holds a request for an offline environment. */
77export const MAX_WEBHOOK_DELIVERY_AGE_MINUTES = 24 * 60;
78
79const WebhookMaxDeliveryAgeMinutes = Schema.Int.check(
80 Schema.isBetween({ minimum: 1, maximum: MAX_WEBHOOK_DELIVERY_AGE_MINUTES }),
81).annotate({
82 description:
83 "Skip requests the relay held longer than this many minutes while the environment was offline. Null runs every request.",
84});
85
86export function isWebhookDedupeTemplate(template: string): boolean {
87 const placeholders = /\{\{\s*(?:(?:body|headers|query)(?:\.[^{}.\s]+)*|request)\s*\}\}/g;
88 const matches = [...template.matchAll(placeholders)];
89 const remainder = template.replace(placeholders, "");
90 return matches.length > 0 && !remainder.includes("{{") && !remainder.includes("}}");
91}
92
93const WebhookDedupeTemplate = Schema.String.check(Schema.makeFilter(isWebhookDedupeTemplate));
94
95const ScheduledTaskWebhookDedupe = Schema.Struct({
96 replayKey: Schema.optional(WebhookDedupeTemplate),
97 coalesceKey: Schema.optional(WebhookDedupeTemplate),
98 coalesceWindowSeconds: Schema.optional(
99 Schema.Int.check(Schema.isBetween({ minimum: 10, maximum: 3600 })),
100 ),
101}).annotate({
102 description:
103 "Replay key template (7 days), coalesce key template, and fixed window in seconds (default 120).",
104});
105
106export const MAX_WEBHOOK_FILTERS = 16;
107
108const WebhookFilterPath = TrimmedNonEmptyString.check(
109 Schema.isPattern(/^(body|headers|query)(\.|$)/),
110).annotate({
111 description:
112 "Request value to test, in placeholder syntax without braces: headers.x-github-event, body.action, query.source. A segment ending in [] fans out over an array, so body.issue.labels[].name tests every label's name.",
113});
114
115/**
116 * Forms edit an `in` list as comma-separated text, so a value that has no
117 * comma and no surrounding whitespace survives that round trip unchanged.
118 */
119const WebhookFilterListValue = Schema.String.check(
120 Schema.isPattern(/^[^,\s](?:[^,]*[^,\s])?$/),
121).annotate({ description: "Non-empty, without commas or surrounding whitespace." });
122
123export const ScheduledTaskWebhookFilter = Schema.Union([
124 Schema.Struct({
125 path: WebhookFilterPath,
126 op: Schema.Literals(["equals", "notEquals", "startsWith"]),
127 value: Schema.String,
128 }),
129 Schema.Struct({
130 path: WebhookFilterPath,
131 op: Schema.Literal("in"),
132 value: Schema.Array(WebhookFilterListValue).check(Schema.isMinLength(1)),
133 }),
134 Schema.Struct({ path: WebhookFilterPath, op: Schema.Literal("exists") }),
135]).annotate({
136 description:
137 "Scalars compare as strings; objects and arrays only satisfy 'exists'. Every op but 'exists' fails when the path is missing. A [] wildcard path yields a list: equals, in and startsWith match when any element does, notEquals when no element equals the value, exists when the list is not empty.",
138});
139export type ScheduledTaskWebhookFilter = typeof ScheduledTaskWebhookFilter.Type;
140export type ScheduledTaskWebhookFilterOp = ScheduledTaskWebhookFilter["op"];
141
142const ScheduledTaskWebhookFilters = Schema.Array(ScheduledTaskWebhookFilter)
143 .check(Schema.isMaxLength(MAX_WEBHOOK_FILTERS))
144 .annotate({
145 description:
146 "Run only when every filter matches the request; other requests are logged as filtered. Up to 16. Omit to keep the stored filters; pass [] to clear them.",
147 });
148
149const ScheduledTaskWebhookSchedule = Schema.Struct({
150 type: Schema.Literal("webhook").annotate({
151 description: "Run when the task's webhook URL receives a request.",
152 }),
153 signature: Schema.NullOr(ScheduledTaskWebhookSignature),
154 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
155 dedupe: Schema.optional(ScheduledTaskWebhookDedupe),
156 filters: Schema.optional(ScheduledTaskWebhookFilters),
157}).annotate({
158 description:
159 "Run on each request to the task's webhook URL. The prompt may use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}} and {{request}} placeholders.",
160});
161
162const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({
163 type: Schema.Literal("webhook").annotate({
164 description: "Run when the task's webhook URL receives a request.",
165 }),
166 signature: Schema.optional(
167 Schema.NullOr(
168 Schema.Struct({
169 ...ScheduledTaskWebhookSignatureFields,
170 secret: Schema.optional(TrimmedNonEmptyString).annotate({
171 description: "Shared signing secret. Omit to keep the stored secret.",
172 }),
173 secretRef: Schema.optional(SecretRef).annotate({
174 description:
175 "A secret the user entered through request_secret, used instead of secret. It is consumed by this save.",
176 }),
177 }),
178 ),
179 ).annotate({
180 description: "Signature check; omit or null to accept requests by URL token only.",
181 }),
182 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
183 dedupe: Schema.optional(ScheduledTaskWebhookDedupe),
184 filters: Schema.optional(ScheduledTaskWebhookFilters),
185}).annotate({
186 description:
187 "Run on each request to the task's webhook URL. The prompt may use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}} and {{request}} placeholders.",
188});
189
190/**
191 * Read model for persisted schedules. Keep accepting legacy sub-minute rows so
192 * users can list, disable, edit, or delete them after the write minimum changes.
193 */
194export const ScheduledTaskSchedule = Schema.Union([
195 ScheduledTaskIntervalSchedule,
196 ScheduledTaskFixedTimeSchedule,
197 ScheduledTaskWebhookSchedule,
198]).annotate({
199 description:
200 "Structured trigger. Pass an object with type 'interval', 'fixed_time' or 'webhook'.",
201});
202export type ScheduledTaskSchedule = typeof ScheduledTaskSchedule.Type;
203
204export const ScheduledTaskUpsertSchedule = Schema.Union([
205 Schema.Struct({
206 type: Schema.Literal("interval").annotate({
207 description: "Select interval scheduling.",
208 }),
209 everyMs: ScheduledTaskIntervalMs.check(
210 Schema.isGreaterThanOrEqualTo(MIN_SCHEDULED_TASK_INTERVAL_MS),
211 ).annotate({
212 description: "Interval in milliseconds, with a minimum of 60000 (one minute).",
213 }),
214 }).annotate({
215 description: "Run repeatedly after a fixed number of milliseconds.",
216 }),
217 ScheduledTaskFixedTimeSchedule,
218 ScheduledTaskUpsertWebhookSchedule,
219]).annotate({
220 description: "Writable trigger. Pass an object with type 'interval', 'fixed_time' or 'webhook'.",
221});
222export type ScheduledTaskUpsertSchedule = typeof ScheduledTaskUpsertSchedule.Type;
223
224export const ScheduledTaskRunStatus = Schema.Literals(["never", "running", "succeeded", "failed"]);
225export type ScheduledTaskRunStatus = typeof ScheduledTaskRunStatus.Type;
226
227export const ScheduledTaskWebhookEndpoint = Schema.Struct({
228 path: TrimmedNonEmptyString,
229 url: Schema.NullOr(TrimmedNonEmptyString),
230 hasSecret: Schema.Boolean,
231});
232export type ScheduledTaskWebhookEndpoint = typeof ScheduledTaskWebhookEndpoint.Type;
233
234export const ScheduledTask = Schema.Struct({
235 id: ScheduledTaskId,
236 title: TrimmedNonEmptyString,
237 prompt: TrimmedNonEmptyString,
238 enabled: Schema.Boolean,
239 schedule: ScheduledTaskSchedule,
240 projectId: ProjectId,
241 threadId: Schema.NullOr(ThreadId),
242 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
243 modelSelection: ModelSelection,
244 runtimeMode: RuntimeMode,
245 interactionMode: ProviderInteractionMode,
246 createdBy: OrchestrationV2Actor,
247 creationSource: OrchestrationV2CreationSource,
248 createdAt: IsoDateTime,
249 updatedAt: IsoDateTime,
250 nextRunAt: Schema.NullOr(IsoDateTime),
251 lastRunAt: Schema.NullOr(IsoDateTime),
252 lastRunStatus: ScheduledTaskRunStatus,
253 lastRunError: Schema.NullOr(Schema.String),
254 runCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
255 webhook: Schema.optional(ScheduledTaskWebhookEndpoint),
256});
257export type ScheduledTask = typeof ScheduledTask.Type;
258
259export const ScheduledTaskListInput = Schema.Struct({});
260export type ScheduledTaskListInput = typeof ScheduledTaskListInput.Type;
261
262export const ScheduledTaskListResult = Schema.Struct({
263 // Trigger types grow over time; a client must not lose the whole list over
264 // one task it cannot decode.
265 tasks: ForwardCompatibleArray(ScheduledTask),
266});
267export type ScheduledTaskListResult = typeof ScheduledTaskListResult.Type;
268
269export const ScheduledTaskUpsertInput = Schema.Struct({
270 id: Schema.optional(ScheduledTaskId),
271 requireExisting: Schema.optional(Schema.Boolean).annotate({
272 description: "Reject the save if the task no longer exists, for edits from a client form.",
273 }),
274 commandId: Schema.optional(CommandId),
275 title: TrimmedNonEmptyString,
276 prompt: TrimmedNonEmptyString,
277 enabled: Schema.Boolean,
278 schedule: ScheduledTaskUpsertSchedule,
279 projectId: ProjectId,
280 threadId: Schema.optional(Schema.NullOr(ThreadId)),
281 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
282 modelSelection: ModelSelection,
283 runtimeMode: RuntimeMode,
284 interactionMode: ProviderInteractionMode,
285 createdBy: Schema.optional(OrchestrationV2Actor),
286 creationSource: Schema.optional(OrchestrationV2CreationSource),
287});
288export type ScheduledTaskUpsertInput = typeof ScheduledTaskUpsertInput.Type;
289
290export const ScheduledTaskSetEnabledInput = Schema.Struct({
291 id: ScheduledTaskId,
292 enabled: Schema.Boolean,
293});
294export type ScheduledTaskSetEnabledInput = typeof ScheduledTaskSetEnabledInput.Type;
295
296export const ScheduledTaskDeleteInput = Schema.Struct({
297 id: ScheduledTaskId,
298});
299export type ScheduledTaskDeleteInput = typeof ScheduledTaskDeleteInput.Type;
300
301export const ScheduledTaskRunNowInput = Schema.Struct({
302 id: ScheduledTaskId,
303});
304export type ScheduledTaskRunNowInput = typeof ScheduledTaskRunNowInput.Type;
305
306export const ScheduledTaskRotateWebhookTokenInput = Schema.Struct({
307 id: ScheduledTaskId,
308});
309export type ScheduledTaskRotateWebhookTokenInput = typeof ScheduledTaskRotateWebhookTokenInput.Type;
310
311export const ScheduledTaskWebhookDeliveryId = TrimmedNonEmptyString.pipe(
312 Schema.brand("ScheduledTaskWebhookDeliveryId"),
313);
314export type ScheduledTaskWebhookDeliveryId = typeof ScheduledTaskWebhookDeliveryId.Type;
315
316export const ScheduledTaskWebhookDeliveryOutcome = Schema.Literals([
317 "accepted",
318 "dispatch_failed",
319 "duplicate",
320 "coalesced",
321 "rejected_signature",
322 "disabled",
323 "rate_limited",
324 "expired",
325 "filtered",
326]);
327export type ScheduledTaskWebhookDeliveryOutcome = typeof ScheduledTaskWebhookDeliveryOutcome.Type;
328
329export const ScheduledTaskWebhookDeliverySummary = Schema.Struct({
330 id: ScheduledTaskWebhookDeliveryId,
331 taskId: ScheduledTaskId,
332 receivedAt: IsoDateTime,
333 method: TrimmedNonEmptyString,
334 contentType: Schema.NullOr(Schema.String),
335 bodyBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
336 // Any string, so an outcome added later doesn't break a client's whole list.
337 outcome: Schema.Union([ScheduledTaskWebhookDeliveryOutcome, Schema.String]),
338 signatureVerified: Schema.Boolean,
339 pendingWindow: Schema.optional(Schema.Boolean),
340 missingFields: Schema.Array(Schema.String),
341 error: Schema.NullOr(Schema.String),
342});
343export type ScheduledTaskWebhookDeliverySummary = typeof ScheduledTaskWebhookDeliverySummary.Type;
344
345export const ScheduledTaskWebhookDelivery = Schema.Struct({
346 ...ScheduledTaskWebhookDeliverySummary.fields,
347 query: Schema.String,
348 headers: Schema.Record(Schema.String, Schema.String),
349 body: Schema.String,
350 bodyTruncated: Schema.Boolean,
351 renderedPrompt: Schema.NullOr(Schema.String),
352});
353export type ScheduledTaskWebhookDelivery = typeof ScheduledTaskWebhookDelivery.Type;
354
355export const ScheduledTaskListWebhookDeliveriesInput = Schema.Struct({
356 id: ScheduledTaskId,
357 /**
358 * Sent by clients that decode any outcome. Shipped clients decode a closed
359 * list and fail on the whole response, so without it the server leaves out
360 * rows with outcomes they don't know.
361 */
362 acceptAnyOutcome: Schema.optional(Schema.Boolean),
363});
364export type ScheduledTaskListWebhookDeliveriesInput =
365 typeof ScheduledTaskListWebhookDeliveriesInput.Type;
366
367export const ScheduledTaskListWebhookDeliveriesResult = Schema.Struct({
368 deliveries: Schema.Array(ScheduledTaskWebhookDeliverySummary),
369});
370export type ScheduledTaskListWebhookDeliveriesResult =
371 typeof ScheduledTaskListWebhookDeliveriesResult.Type;
372
373export const ScheduledTaskGetWebhookDeliveryInput = Schema.Struct({
374 id: ScheduledTaskId,
375 deliveryId: ScheduledTaskWebhookDeliveryId,
376 acceptAnyOutcome: Schema.optional(Schema.Boolean),
377});
378export type ScheduledTaskGetWebhookDeliveryInput = typeof ScheduledTaskGetWebhookDeliveryInput.Type;
379
380export const ScheduledTaskGetWebhookDeliveryResult = Schema.Struct({
381 delivery: ScheduledTaskWebhookDelivery,
382});
383export type ScheduledTaskGetWebhookDeliveryResult =
384 typeof ScheduledTaskGetWebhookDeliveryResult.Type;
385
386export const ScheduledTaskMutationResult = Schema.Struct({
387 task: ScheduledTask,
388});
389export type ScheduledTaskMutationResult = typeof ScheduledTaskMutationResult.Type;
390
391export const ScheduledTaskDeleteResult = Schema.Struct({
392 id: ScheduledTaskId,
393});
394export type ScheduledTaskDeleteResult = typeof ScheduledTaskDeleteResult.Type;
395
396export const ScheduledTaskRunNowResult = Schema.Struct({
397 task: ScheduledTask,
398});
399export type ScheduledTaskRunNowResult = typeof ScheduledTaskRunNowResult.Type;
400
401export class ScheduledTaskError extends Schema.TaggedError<ScheduledTaskError>()(
402 "ScheduledTaskError",
403 {
404 message: Schema.String,
405 taskId: Schema.optional(ScheduledTaskId),
406 cause: Schema.optional(Schema.Defect()),
407 },
408) {}