Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

scheduledTask.ts

402 lines15.3 KB

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