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

scheduledTask.ts

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