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

scheduledTask.ts

329 lines12.1 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​
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​
86const ScheduledTaskWebhookSchedule = Schema.Struct({
87 type: Schema.Literal("webhook").annotate({
88 description: "Run when the task's webhook URL receives a request.",
89 }),
90 signature: Schema.NullOr(ScheduledTaskWebhookSignature),
91 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
92}).annotate({
93 description:
94 "Run on each request to the task's webhook URL. The prompt may use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}} and {{request}} placeholders.",
95});
96​
97const ScheduledTaskUpsertWebhookSchedule = Schema.Struct({
98 type: Schema.Literal("webhook").annotate({
99 description: "Run when the task's webhook URL receives a request.",
100 }),
101 signature: Schema.optional(
102 Schema.NullOr(
103 Schema.Struct({
104 ...ScheduledTaskWebhookSignatureFields,
105 secret: Schema.optional(TrimmedNonEmptyString).annotate({
106 description: "Shared signing secret. Omit to keep the stored secret.",
107 }),
108 secretRef: Schema.optional(SecretRef).annotate({
109 description:
110 "A secret the user entered through request_secret, used instead of secret. It is consumed by this save.",
111 }),
112 }),
113 ),
114 ).annotate({
115 description: "Signature check; omit or null to accept requests by URL token only.",
116 }),
117 maxDeliveryAgeMinutes: Schema.optional(Schema.NullOr(WebhookMaxDeliveryAgeMinutes)),
118}).annotate({
119 description:
120 "Run on each request to the task's webhook URL. The prompt may use {{body.path}}, {{headers.name}}, {{query.name}}, {{body}} and {{request}} placeholders.",
121});
122​
123/**
124 * Read model for persisted schedules. Keep accepting legacy sub-minute rows so
125 * users can list, disable, edit, or delete them after the write minimum changes.
126 */
127export const ScheduledTaskSchedule = Schema.Union([
128 ScheduledTaskIntervalSchedule,
129 ScheduledTaskFixedTimeSchedule,
130 ScheduledTaskWebhookSchedule,
131]).annotate({
132 description:
133 "Structured trigger. Pass an object with type 'interval', 'fixed_time' or 'webhook'.",
134});
135export type ScheduledTaskSchedule = typeof ScheduledTaskSchedule.Type;
136​
137export const ScheduledTaskUpsertSchedule = Schema.Union([
138 Schema.Struct({
139 type: Schema.Literal("interval").annotate({
140 description: "Select interval scheduling.",
141 }),
142 everyMs: ScheduledTaskIntervalMs.check(
143 Schema.isGreaterThanOrEqualTo(MIN_SCHEDULED_TASK_INTERVAL_MS),
144 ).annotate({
145 description: "Interval in milliseconds, with a minimum of 60000 (one minute).",
146 }),
147 }).annotate({
148 description: "Run repeatedly after a fixed number of milliseconds.",
149 }),
150 ScheduledTaskFixedTimeSchedule,
151 ScheduledTaskUpsertWebhookSchedule,
152]).annotate({
153 description: "Writable trigger. Pass an object with type 'interval', 'fixed_time' or 'webhook'.",
154});
155export type ScheduledTaskUpsertSchedule = typeof ScheduledTaskUpsertSchedule.Type;
156​
157export const ScheduledTaskRunStatus = Schema.Literals(["never", "running", "succeeded", "failed"]);
158export type ScheduledTaskRunStatus = typeof ScheduledTaskRunStatus.Type;
159​
160export const ScheduledTaskWebhookEndpoint = Schema.Struct({
161 path: TrimmedNonEmptyString,
162 url: Schema.NullOr(TrimmedNonEmptyString),
163 hasSecret: Schema.Boolean,
164});
165export type ScheduledTaskWebhookEndpoint = typeof ScheduledTaskWebhookEndpoint.Type;
166​
167export const ScheduledTask = Schema.Struct({
168 id: ScheduledTaskId,
169 title: TrimmedNonEmptyString,
170 prompt: TrimmedNonEmptyString,
171 enabled: Schema.Boolean,
172 schedule: ScheduledTaskSchedule,
173 projectId: ProjectId,
174 threadId: Schema.NullOr(ThreadId),
175 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
176 modelSelection: ModelSelection,
177 runtimeMode: RuntimeMode,
178 interactionMode: ProviderInteractionMode,
179 createdBy: OrchestrationV2Actor,
180 creationSource: OrchestrationV2CreationSource,
181 createdAt: IsoDateTime,
182 updatedAt: IsoDateTime,
183 nextRunAt: Schema.NullOr(IsoDateTime),
184 lastRunAt: Schema.NullOr(IsoDateTime),
185 lastRunStatus: ScheduledTaskRunStatus,
186 lastRunError: Schema.NullOr(Schema.String),
187 runCount: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
188 webhook: Schema.optional(ScheduledTaskWebhookEndpoint),
189});
190export type ScheduledTask = typeof ScheduledTask.Type;
191​
192export const ScheduledTaskListInput = Schema.Struct({});
193export type ScheduledTaskListInput = typeof ScheduledTaskListInput.Type;
194​
195export const ScheduledTaskListResult = Schema.Struct({
196 // Trigger types grow over time; a client must not lose the whole list over
197 // one task it cannot decode.
198 tasks: ForwardCompatibleArray(ScheduledTask),
199});
200export type ScheduledTaskListResult = typeof ScheduledTaskListResult.Type;
201​
202export const ScheduledTaskUpsertInput = Schema.Struct({
203 id: Schema.optional(ScheduledTaskId),
204 requireExisting: Schema.optional(Schema.Boolean).annotate({
205 description: "Reject the save if the task no longer exists, for edits from a client form.",
206 }),
207 commandId: Schema.optional(CommandId),
208 title: TrimmedNonEmptyString,
209 prompt: TrimmedNonEmptyString,
210 enabled: Schema.Boolean,
211 schedule: ScheduledTaskUpsertSchedule,
212 projectId: ProjectId,
213 threadId: Schema.optional(Schema.NullOr(ThreadId)),
214 workspaceStrategy: OrchestrationV2ThreadLaunchWorkspaceStrategy,
215 modelSelection: ModelSelection,
216 runtimeMode: RuntimeMode,
217 interactionMode: ProviderInteractionMode,
218 createdBy: Schema.optional(OrchestrationV2Actor),
219 creationSource: Schema.optional(OrchestrationV2CreationSource),
220});
221export type ScheduledTaskUpsertInput = typeof ScheduledTaskUpsertInput.Type;
222​
223export const ScheduledTaskSetEnabledInput = Schema.Struct({
224 id: ScheduledTaskId,
225 enabled: Schema.Boolean,
226});
227export type ScheduledTaskSetEnabledInput = typeof ScheduledTaskSetEnabledInput.Type;
228​
229export const ScheduledTaskDeleteInput = Schema.Struct({
230 id: ScheduledTaskId,
231});
232export type ScheduledTaskDeleteInput = typeof ScheduledTaskDeleteInput.Type;
233​
234export const ScheduledTaskRunNowInput = Schema.Struct({
235 id: ScheduledTaskId,
236});
237export type ScheduledTaskRunNowInput = typeof ScheduledTaskRunNowInput.Type;
238​
239export const ScheduledTaskRotateWebhookTokenInput = Schema.Struct({
240 id: ScheduledTaskId,
241});
242export type ScheduledTaskRotateWebhookTokenInput = typeof ScheduledTaskRotateWebhookTokenInput.Type;
243​
244export const ScheduledTaskWebhookDeliveryId = TrimmedNonEmptyString.pipe(
245 Schema.brand("ScheduledTaskWebhookDeliveryId"),
246);
247export type ScheduledTaskWebhookDeliveryId = typeof ScheduledTaskWebhookDeliveryId.Type;
248​
249export const ScheduledTaskWebhookDeliveryOutcome = Schema.Literals([
250 "accepted",
251 "dispatch_failed",
252 "rejected_signature",
253 "disabled",
254 "rate_limited",
255 "expired",
256]);
257export type ScheduledTaskWebhookDeliveryOutcome = typeof ScheduledTaskWebhookDeliveryOutcome.Type;
258​
259export const ScheduledTaskWebhookDeliverySummary = Schema.Struct({
260 id: ScheduledTaskWebhookDeliveryId,
261 taskId: ScheduledTaskId,
262 receivedAt: IsoDateTime,
263 method: TrimmedNonEmptyString,
264 contentType: Schema.NullOr(Schema.String),
265 bodyBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
266 outcome: ScheduledTaskWebhookDeliveryOutcome,
267 signatureVerified: Schema.Boolean,
268 missingFields: Schema.Array(Schema.String),
269 error: Schema.NullOr(Schema.String),
270});
271export type ScheduledTaskWebhookDeliverySummary = typeof ScheduledTaskWebhookDeliverySummary.Type;
272​
273export const ScheduledTaskWebhookDelivery = Schema.Struct({
274 ...ScheduledTaskWebhookDeliverySummary.fields,
275 query: Schema.String,
276 headers: Schema.Record(Schema.String, Schema.String),
277 body: Schema.String,
278 bodyTruncated: Schema.Boolean,
279 renderedPrompt: Schema.NullOr(Schema.String),
280});
281export type ScheduledTaskWebhookDelivery = typeof ScheduledTaskWebhookDelivery.Type;
282​
283export const ScheduledTaskListWebhookDeliveriesInput = Schema.Struct({
284 id: ScheduledTaskId,
285});
286export type ScheduledTaskListWebhookDeliveriesInput =
287 typeof ScheduledTaskListWebhookDeliveriesInput.Type;
288​
289export const ScheduledTaskListWebhookDeliveriesResult = Schema.Struct({
290 deliveries: Schema.Array(ScheduledTaskWebhookDeliverySummary),
291});
292export type ScheduledTaskListWebhookDeliveriesResult =
293 typeof ScheduledTaskListWebhookDeliveriesResult.Type;
294​
295export const ScheduledTaskGetWebhookDeliveryInput = Schema.Struct({
296 id: ScheduledTaskId,
297 deliveryId: ScheduledTaskWebhookDeliveryId,
298});
299export type ScheduledTaskGetWebhookDeliveryInput = typeof ScheduledTaskGetWebhookDeliveryInput.Type;
300​
301export const ScheduledTaskGetWebhookDeliveryResult = Schema.Struct({
302 delivery: ScheduledTaskWebhookDelivery,
303});
304export type ScheduledTaskGetWebhookDeliveryResult =
305 typeof ScheduledTaskGetWebhookDeliveryResult.Type;
306​
307export const ScheduledTaskMutationResult = Schema.Struct({
308 task: ScheduledTask,
309});
310export type ScheduledTaskMutationResult = typeof ScheduledTaskMutationResult.Type;
311​
312export const ScheduledTaskDeleteResult = Schema.Struct({
313 id: ScheduledTaskId,
314});
315export type ScheduledTaskDeleteResult = typeof ScheduledTaskDeleteResult.Type;
316​
317export const ScheduledTaskRunNowResult = Schema.Struct({
318 task: ScheduledTask,
319});
320export type ScheduledTaskRunNowResult = typeof ScheduledTaskRunNowResult.Type;
321​
322export class ScheduledTaskError extends Schema.TaggedError<ScheduledTaskError>()(
323 "ScheduledTaskError",
324 {
325 message: Schema.String,
326 taskId: Schema.optional(ScheduledTaskId),
327 cause: Schema.optional(Schema.Defect()),
328 },
329) {}