@bridgebrew/scheduler 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/browser/browser.tsx +17 -0
- package/browser/scheduled-screen.tsx +1327 -0
- package/browser/tsconfig.json +14 -0
- package/core.ts +580 -0
- package/docs/en/index.mdx +105 -0
- package/docs/en/meta.json +4 -0
- package/docs/meta.json +4 -0
- package/package.json +332 -4
- package/rules.ts +122 -0
- package/server.ts +201 -0
- package/tasks.ts +843 -0
- package/tsconfig.json +1 -0
- package/view.ts +98 -0
- package/README.md +0 -3
package/docs/meta.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,334 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bridgebrew/scheduler",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Durable time for the workspace's plugins: entries that fire at an instant or on a recurrence.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"bridge-plugin"
|
|
8
|
+
],
|
|
9
|
+
"type": "module",
|
|
10
|
+
"files": [
|
|
11
|
+
"*.json",
|
|
12
|
+
"*.ts",
|
|
13
|
+
"browser/",
|
|
14
|
+
"docs/",
|
|
15
|
+
"!**/*.test.ts",
|
|
16
|
+
"!**/*.test.tsx"
|
|
17
|
+
],
|
|
18
|
+
"bridge": {
|
|
19
|
+
"kind": "service",
|
|
20
|
+
"category": "standard",
|
|
21
|
+
"title": "Scheduler",
|
|
22
|
+
"icon": "alarm-clock",
|
|
23
|
+
"domain": "automation",
|
|
24
|
+
"server": "./server.ts",
|
|
25
|
+
"browser": "./browser/browser.tsx",
|
|
26
|
+
"implements": [
|
|
27
|
+
"scheduler"
|
|
28
|
+
],
|
|
29
|
+
"requires": {
|
|
30
|
+
"storage": {}
|
|
31
|
+
},
|
|
32
|
+
"screen": {
|
|
33
|
+
"id": "scheduled",
|
|
34
|
+
"title": "Scheduled",
|
|
35
|
+
"icon": "alarm-clock",
|
|
36
|
+
"item": "A scheduled task's id, or new for a new one"
|
|
37
|
+
},
|
|
38
|
+
"settings": {
|
|
39
|
+
"type": "object",
|
|
40
|
+
"properties": {
|
|
41
|
+
"timeZone": {
|
|
42
|
+
"type": "string",
|
|
43
|
+
"title": "Time zone",
|
|
44
|
+
"description": "The time zone of repeating schedules.",
|
|
45
|
+
"x-bridge-details": "Those that follow you (a daily 9:00, a birthday), as an IANA name such as Europe/Paris. Empty: this computer's zone.",
|
|
46
|
+
"default": "",
|
|
47
|
+
"applies": "live"
|
|
48
|
+
},
|
|
49
|
+
"runDeadline": {
|
|
50
|
+
"type": "integer",
|
|
51
|
+
"title": "Run deadline (minutes)",
|
|
52
|
+
"description": "How long a scheduled task's run, or a plugin's scheduled delivery, has before it is stopped.",
|
|
53
|
+
"x-bridge-details": "Past it, the run is told to stop and recorded as timed out; three failed or timed-out runs in a row suspend the task.",
|
|
54
|
+
"minimum": 1,
|
|
55
|
+
"default": 10,
|
|
56
|
+
"applies": "live"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
"tools": {
|
|
61
|
+
"schedule_task": {
|
|
62
|
+
"description": "Schedule a task to run an action later: give action { type, input } (list_action_types lists the types and their form), or prompt alone to send a prompt into this session (an agent) or the session given (a person). An interval (everyMs) is elapsed time, at least 60000 ms; a fixed_time is a wall time (HH:MM) in the scheduler's time zone, on the weekdays given (0 is Sunday; every day without them). list_scheduled_tasks shows when it runs next.",
|
|
63
|
+
"method": "POST",
|
|
64
|
+
"path": "/scheduler/tasks",
|
|
65
|
+
"input": {
|
|
66
|
+
"type": "object",
|
|
67
|
+
"properties": {
|
|
68
|
+
"schedule": {
|
|
69
|
+
"type": "object",
|
|
70
|
+
"properties": {
|
|
71
|
+
"type": {
|
|
72
|
+
"type": "string",
|
|
73
|
+
"enum": [
|
|
74
|
+
"interval",
|
|
75
|
+
"fixed_time"
|
|
76
|
+
]
|
|
77
|
+
},
|
|
78
|
+
"everyMs": {
|
|
79
|
+
"type": "integer",
|
|
80
|
+
"minimum": 60000,
|
|
81
|
+
"description": "With interval: how often, in milliseconds (at least 60000)."
|
|
82
|
+
},
|
|
83
|
+
"timeOfDay": {
|
|
84
|
+
"type": "string",
|
|
85
|
+
"pattern": "^([01]\\d|2[0-3]):[0-5]\\d$",
|
|
86
|
+
"description": "With fixed_time: the wall time, HH:MM, in the scheduler's time zone."
|
|
87
|
+
},
|
|
88
|
+
"weekdays": {
|
|
89
|
+
"type": "array",
|
|
90
|
+
"items": {
|
|
91
|
+
"type": "integer",
|
|
92
|
+
"minimum": 0,
|
|
93
|
+
"maximum": 6
|
|
94
|
+
},
|
|
95
|
+
"description": "With fixed_time: the weekdays (0 is Sunday); every day without them."
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
"required": [
|
|
99
|
+
"type"
|
|
100
|
+
],
|
|
101
|
+
"additionalProperties": false
|
|
102
|
+
},
|
|
103
|
+
"action": {
|
|
104
|
+
"type": "object",
|
|
105
|
+
"properties": {
|
|
106
|
+
"type": {
|
|
107
|
+
"type": "string",
|
|
108
|
+
"description": "The action type (list_action_types), such as sessions.prompt."
|
|
109
|
+
},
|
|
110
|
+
"input": {
|
|
111
|
+
"type": "object",
|
|
112
|
+
"description": "The action's input, as list_action_types' input schema says."
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
"required": [
|
|
116
|
+
"type"
|
|
117
|
+
],
|
|
118
|
+
"additionalProperties": false
|
|
119
|
+
},
|
|
120
|
+
"prompt": {
|
|
121
|
+
"type": "string",
|
|
122
|
+
"description": "With no action: what the agent does at each run, as a user would write it, into this session."
|
|
123
|
+
},
|
|
124
|
+
"session": {
|
|
125
|
+
"type": "string",
|
|
126
|
+
"description": "With prompt from the UI: the session it runs in (list_sessions)."
|
|
127
|
+
},
|
|
128
|
+
"title": {
|
|
129
|
+
"type": "string",
|
|
130
|
+
"description": "How the task is listed; the action's own title without it."
|
|
131
|
+
},
|
|
132
|
+
"enabled": {
|
|
133
|
+
"type": "boolean",
|
|
134
|
+
"description": "False: listed but paused until resumed."
|
|
135
|
+
},
|
|
136
|
+
"bindToCurrentThread": {
|
|
137
|
+
"type": "boolean",
|
|
138
|
+
"description": "False: each run starts a new session with the calling session's harness, project, model, effort and permissions (Ask excepted). True or absent: the run goes into the calling session."
|
|
139
|
+
},
|
|
140
|
+
"clientRequestId": {
|
|
141
|
+
"type": "string",
|
|
142
|
+
"description": "An id of your own: the same one again returns this task instead of creating another."
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
"required": [
|
|
146
|
+
"schedule"
|
|
147
|
+
],
|
|
148
|
+
"additionalProperties": false
|
|
149
|
+
}
|
|
150
|
+
},
|
|
151
|
+
"list_scheduled_tasks": {
|
|
152
|
+
"description": "List this workspace's scheduled tasks, each with its action, its subject, its schedule, its state (waiting, running, off, or suspended with suspendedReason after three failed runs in a row), when it runs next (nextRunAt), whether its action type is available, its last run (lastRunStatus: never, succeeded, failed or timed_out; lastRunAt, lastRunError, lastRunSummary), its failures in a row and how many times it ran. Filter with subjectDomain and subjectId.",
|
|
153
|
+
"method": "GET",
|
|
154
|
+
"path": "/scheduler/tasks",
|
|
155
|
+
"input": {
|
|
156
|
+
"type": "object",
|
|
157
|
+
"properties": {
|
|
158
|
+
"subjectDomain": {
|
|
159
|
+
"type": "string",
|
|
160
|
+
"description": "Only the tasks whose subject is in this domain (sessions/sessions, say)."
|
|
161
|
+
},
|
|
162
|
+
"subjectId": {
|
|
163
|
+
"type": "string",
|
|
164
|
+
"description": "Only the tasks whose subject has this id."
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
"additionalProperties": false
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
"update_scheduled_task": {
|
|
171
|
+
"description": "Change a scheduled task (its id from list_scheduled_tasks): a new title or action keeps its next run; a new schedule, a pause (enabled false) or a resume moves it. Answers the task.",
|
|
172
|
+
"method": "POST",
|
|
173
|
+
"path": "/scheduler/tasks/update",
|
|
174
|
+
"input": {
|
|
175
|
+
"type": "object",
|
|
176
|
+
"properties": {
|
|
177
|
+
"scheduledTaskId": {
|
|
178
|
+
"type": "string",
|
|
179
|
+
"description": "The task's id (list_scheduled_tasks)."
|
|
180
|
+
},
|
|
181
|
+
"title": {
|
|
182
|
+
"type": "string",
|
|
183
|
+
"description": "How the task is listed."
|
|
184
|
+
},
|
|
185
|
+
"schedule": {
|
|
186
|
+
"type": "object",
|
|
187
|
+
"properties": {
|
|
188
|
+
"type": {
|
|
189
|
+
"type": "string",
|
|
190
|
+
"enum": [
|
|
191
|
+
"interval",
|
|
192
|
+
"fixed_time"
|
|
193
|
+
]
|
|
194
|
+
},
|
|
195
|
+
"everyMs": {
|
|
196
|
+
"type": "integer",
|
|
197
|
+
"minimum": 60000,
|
|
198
|
+
"description": "With interval: how often, in milliseconds (at least 60000)."
|
|
199
|
+
},
|
|
200
|
+
"timeOfDay": {
|
|
201
|
+
"type": "string",
|
|
202
|
+
"pattern": "^([01]\\d|2[0-3]):[0-5]\\d$",
|
|
203
|
+
"description": "With fixed_time: the wall time, HH:MM, in the scheduler's time zone."
|
|
204
|
+
},
|
|
205
|
+
"weekdays": {
|
|
206
|
+
"type": "array",
|
|
207
|
+
"items": {
|
|
208
|
+
"type": "integer",
|
|
209
|
+
"minimum": 0,
|
|
210
|
+
"maximum": 6
|
|
211
|
+
},
|
|
212
|
+
"description": "With fixed_time: the weekdays (0 is Sunday); every day without them."
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
"required": [
|
|
216
|
+
"type"
|
|
217
|
+
],
|
|
218
|
+
"additionalProperties": false
|
|
219
|
+
},
|
|
220
|
+
"enabled": {
|
|
221
|
+
"type": "boolean",
|
|
222
|
+
"description": "False pauses it; true plans it again from now."
|
|
223
|
+
},
|
|
224
|
+
"action": {
|
|
225
|
+
"type": "object",
|
|
226
|
+
"properties": {
|
|
227
|
+
"type": {
|
|
228
|
+
"type": "string",
|
|
229
|
+
"description": "The action type (list_action_types)."
|
|
230
|
+
},
|
|
231
|
+
"input": {
|
|
232
|
+
"type": "object",
|
|
233
|
+
"description": "The action's input, as list_action_types' input schema says."
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
"required": [
|
|
237
|
+
"type"
|
|
238
|
+
],
|
|
239
|
+
"additionalProperties": false
|
|
240
|
+
}
|
|
241
|
+
},
|
|
242
|
+
"required": [
|
|
243
|
+
"scheduledTaskId"
|
|
244
|
+
],
|
|
245
|
+
"additionalProperties": false
|
|
246
|
+
}
|
|
247
|
+
},
|
|
248
|
+
"delete_scheduled_task": {
|
|
249
|
+
"description": "Delete a scheduled task for good (its id from list_scheduled_tasks): nothing of it runs again.",
|
|
250
|
+
"method": "POST",
|
|
251
|
+
"path": "/scheduler/tasks/delete",
|
|
252
|
+
"input": {
|
|
253
|
+
"type": "object",
|
|
254
|
+
"properties": {
|
|
255
|
+
"scheduledTaskId": {
|
|
256
|
+
"type": "string",
|
|
257
|
+
"description": "The task's id (list_scheduled_tasks)."
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
"required": [
|
|
261
|
+
"scheduledTaskId"
|
|
262
|
+
],
|
|
263
|
+
"additionalProperties": false
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
"run_scheduled_task_now": {
|
|
267
|
+
"description": "Run a scheduled task now, even off or suspended (it lifts no suspension), and answer the task at once, running; asked during a run, it runs once more after it. Its next planned run stays.",
|
|
268
|
+
"method": "POST",
|
|
269
|
+
"path": "/scheduler/tasks/run",
|
|
270
|
+
"input": {
|
|
271
|
+
"type": "object",
|
|
272
|
+
"properties": {
|
|
273
|
+
"scheduledTaskId": {
|
|
274
|
+
"type": "string",
|
|
275
|
+
"description": "The task's id (list_scheduled_tasks)."
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
"required": [
|
|
279
|
+
"scheduledTaskId"
|
|
280
|
+
],
|
|
281
|
+
"additionalProperties": false
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
"resume_scheduled_task": {
|
|
285
|
+
"description": "Resume a suspended scheduled task (its id from list_scheduled_tasks): its failures are reset and it waits for its next slot from now; nothing missed is replayed. Answers the task.",
|
|
286
|
+
"method": "POST",
|
|
287
|
+
"path": "/scheduler/tasks/resume",
|
|
288
|
+
"input": {
|
|
289
|
+
"type": "object",
|
|
290
|
+
"properties": {
|
|
291
|
+
"scheduledTaskId": {
|
|
292
|
+
"type": "string",
|
|
293
|
+
"description": "The task's id (list_scheduled_tasks)."
|
|
294
|
+
}
|
|
295
|
+
},
|
|
296
|
+
"required": [
|
|
297
|
+
"scheduledTaskId"
|
|
298
|
+
],
|
|
299
|
+
"additionalProperties": false
|
|
300
|
+
}
|
|
301
|
+
},
|
|
302
|
+
"list_action_types": {
|
|
303
|
+
"description": "List the action types a scheduled task can run, each with its title, description, icon and input form schema (the fields a task takes).",
|
|
304
|
+
"method": "GET",
|
|
305
|
+
"path": "/scheduler/actions",
|
|
306
|
+
"input": {
|
|
307
|
+
"type": "object",
|
|
308
|
+
"properties": {},
|
|
309
|
+
"additionalProperties": false
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
},
|
|
313
|
+
"provenance": "official"
|
|
314
|
+
},
|
|
315
|
+
"dependencies": {
|
|
316
|
+
"@bridgebrew/plugin-manager": "0.0.2",
|
|
317
|
+
"rrule-temporal": "2.2.8",
|
|
318
|
+
"temporal-polyfill": "1.0.5",
|
|
319
|
+
"zod": "4.6.5"
|
|
320
|
+
},
|
|
321
|
+
"peerDependencies": {
|
|
322
|
+
"@bridge/ui": ">=0.0.1",
|
|
323
|
+
"cordis": "4.0.0-rc.11",
|
|
324
|
+
"react": "19.3.0"
|
|
325
|
+
},
|
|
326
|
+
"releaseStage": "dev",
|
|
327
|
+
"scripts": {
|
|
328
|
+
"test": "node ../bridge/node_modules/vitest/vitest.mjs run --config ../scripts/vitest.config.ts",
|
|
329
|
+
"typecheck": "bridge plugin check ."
|
|
330
|
+
},
|
|
331
|
+
"engines": {
|
|
332
|
+
"bridge": ">=0.0.1-nightly.20261117.1"
|
|
333
|
+
}
|
|
334
|
+
}
|
package/rules.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Recurrence rules (research-012): RFC 5545 iCalendar text (`DTSTART` + `RRULE`, `EXDATE`, `RDATE`), expanded by
|
|
2
|
+
// `rrule-temporal` (RFC 5545 and RFC 7529 `SKIP`, zones and DST through `Temporal`). The rest of the scheduler sees
|
|
3
|
+
// instants in milliseconds only: `Temporal` stays in this file.
|
|
4
|
+
// A rule's zone is its `DTSTART;TZID=`; without one (floating) it takes `zone` (the scheduler's `timeZone` setting,
|
|
5
|
+
// read at each computation, so it follows the user). An all-day rule (`DTSTART;VALUE=DATE:`) fires at `time` on its
|
|
6
|
+
// day (default 00:00). `offset` moves every fire from its occurrence: `days` on the calendar (a wall time stays the
|
|
7
|
+
// same), `minutes` in elapsed time ('15 minutes before': `{ minutes: -15 }`).
|
|
8
|
+
// What the library does at a DST change: a daily 09:00 stays 09:00 local; a wall time that does not exist (02:30 on the
|
|
9
|
+
// spring-forward day) is skipped that day; one that exists twice fires at the first.
|
|
10
|
+
import { RRuleTemporal } from 'rrule-temporal';
|
|
11
|
+
import { Temporal } from 'temporal-polyfill';
|
|
12
|
+
import { z } from 'zod';
|
|
13
|
+
|
|
14
|
+
export const rule = z.strictObject({
|
|
15
|
+
ical: z.string().min(1).max(4096),
|
|
16
|
+
time: z
|
|
17
|
+
.string()
|
|
18
|
+
.regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'time is HH:mm')
|
|
19
|
+
.optional(),
|
|
20
|
+
offset: z
|
|
21
|
+
.strictObject({
|
|
22
|
+
days: z.number().int().min(-366).max(366).optional(),
|
|
23
|
+
minutes: z.number().int().min(-527_040).max(527_040).optional(),
|
|
24
|
+
})
|
|
25
|
+
.optional(),
|
|
26
|
+
});
|
|
27
|
+
export type Rule = z.infer<typeof rule>;
|
|
28
|
+
|
|
29
|
+
/** A rule ready to answer instants (ms). */
|
|
30
|
+
export interface Compiled {
|
|
31
|
+
/** The first fire strictly after `after`, `undefined` once the series ended. */
|
|
32
|
+
next(after: number): number | undefined;
|
|
33
|
+
/** The fires in `(after, until]`, in order, at most `take`. */
|
|
34
|
+
between(after: number, until: number, take: number): number[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The rule's text with its lines normalized (CRLF, folded lines). */
|
|
38
|
+
const lines = (ical: string) =>
|
|
39
|
+
ical
|
|
40
|
+
.replace(/\r\n/g, '\n')
|
|
41
|
+
.replace(/\n[ \t]/g, '')
|
|
42
|
+
.split('\n')
|
|
43
|
+
.map((line) => line.trim())
|
|
44
|
+
.filter(Boolean);
|
|
45
|
+
|
|
46
|
+
/** `ical` compiled for floating zone `zone`; throws a readable `Error` for a rule the library refuses or that has no
|
|
47
|
+
* `DTSTART` / `RRULE`. */
|
|
48
|
+
export function compile({ ical, time, offset }: Rule, zone: string): Compiled {
|
|
49
|
+
const text = lines(ical);
|
|
50
|
+
const start = text.find((line) => /^DTSTART[;:]/i.test(line));
|
|
51
|
+
if (!start) throw new Error('a rule needs a DTSTART line');
|
|
52
|
+
if (!text.some((line) => /^RRULE:/i.test(line))) throw new Error('a rule needs an RRULE line');
|
|
53
|
+
const allDay = /VALUE=DATE[;:]/i.test(start);
|
|
54
|
+
if (time !== undefined && !allDay)
|
|
55
|
+
throw new Error('time is for an all-day rule (DTSTART;VALUE=DATE:…)');
|
|
56
|
+
const floats = !/TZID=/i.test(start);
|
|
57
|
+
let library: RRuleTemporal;
|
|
58
|
+
try {
|
|
59
|
+
library = new RRuleTemporal({ rruleString: text.join('\n'), ...(floats && { tzid: zone }) });
|
|
60
|
+
} catch (error) {
|
|
61
|
+
throw new Error(
|
|
62
|
+
`the rule does not parse: ${error instanceof Error ? error.message : String(error)}`,
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
const [hour, minute] = (time ?? '00:00').split(':').map(Number) as [number, number];
|
|
66
|
+
/** An occurrence's fire instant. */
|
|
67
|
+
const fire = (occurrence: Temporal.ZonedDateTime) => {
|
|
68
|
+
let at = Temporal.ZonedDateTime.from(occurrence.toString());
|
|
69
|
+
if (allDay) at = at.withPlainTime({ hour, minute });
|
|
70
|
+
if (offset?.days) at = at.add({ days: offset.days });
|
|
71
|
+
if (offset?.minutes) at = at.add({ minutes: offset.minutes });
|
|
72
|
+
return at.epochMilliseconds;
|
|
73
|
+
};
|
|
74
|
+
/** How far a fire may be from its occurrence: the window to look back for occurrences whose fire is still ahead. */
|
|
75
|
+
const reach =
|
|
76
|
+
(Math.abs(offset?.days ?? 0) + 2) * 86_400_000 + Math.abs(offset?.minutes ?? 0) * 60_000;
|
|
77
|
+
/** The fires of the occurrences from `from` on, in occurrence order (at most `max`). */
|
|
78
|
+
function* fires(from: number, max: number) {
|
|
79
|
+
let cursor: Temporal.ZonedDateTime | null = library.next(new Date(from), true);
|
|
80
|
+
for (let seen = 0; cursor && seen < max; seen++) {
|
|
81
|
+
yield fire(cursor);
|
|
82
|
+
cursor = library.next(cursor, false);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
next: (after) => {
|
|
87
|
+
// Offsets keep the order of fires but a fire may precede a later occurrence's by less than `reach`.
|
|
88
|
+
let found: number | undefined;
|
|
89
|
+
for (const at of fires(after - reach, 100_000)) {
|
|
90
|
+
if (found !== undefined && at > found + reach) break;
|
|
91
|
+
if (at > after && (found === undefined || at < found)) found = at;
|
|
92
|
+
}
|
|
93
|
+
return found;
|
|
94
|
+
},
|
|
95
|
+
between: (after, until, take) => {
|
|
96
|
+
const taken: number[] = [];
|
|
97
|
+
for (const at of fires(after - reach, 100_000)) {
|
|
98
|
+
if (at > until + reach) break;
|
|
99
|
+
if (at > after && at <= until) taken.push(at);
|
|
100
|
+
if (taken.length >= take * 2 + 10) break;
|
|
101
|
+
}
|
|
102
|
+
return taken.sort((a, b) => a - b).slice(0, take);
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Whether `value` is floating: its `DTSTART` has no `TZID`, so it follows the scheduler's zone. */
|
|
108
|
+
export const floating = (value: Rule) =>
|
|
109
|
+
!/TZID=/i.test(lines(value.ical).find((line) => /^DTSTART[;:]/i.test(line)) ?? '');
|
|
110
|
+
|
|
111
|
+
/** The host's own zone: the `timeZone` setting's default. */
|
|
112
|
+
export const systemZone = () => Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
113
|
+
|
|
114
|
+
/** Whether `zone` is an IANA zone this runtime knows. */
|
|
115
|
+
export const knownZone = (zone: string) => {
|
|
116
|
+
try {
|
|
117
|
+
Temporal.Now.zonedDateTimeISO(zone);
|
|
118
|
+
return true;
|
|
119
|
+
} catch {
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
};
|
package/server.ts
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
// The scheduler plugin (research-012): durable time for every plugin of the workspace. An entry is owned by the plugin
|
|
2
|
+
// that made it (its caller's plugin key), points to an object by `ref` `{ domain, id }` (any domain; a plain value, not a
|
|
3
|
+
// declared storage reference), is unique per `(owner, ref, key)`, and fires at one instant `at` or on a recurrence
|
|
4
|
+
// `rule` (RFC 5545 text, `rules.ts`). `for` marks a person's entry (absent: a service entry; nothing sets it yet, it
|
|
5
|
+
// is room for several users). Entries live in the domain `scheduler/entries` on `root`, survive restarts, and are
|
|
6
|
+
// caught up at start: a one-shot entry fires once, late; a rule per its `catchUp` (`last`, the default: once for the
|
|
7
|
+
// latest missed occurrence with `missed` counted; `all`: each, 100 at most; `skip`: none). Delivery goes to the owner's
|
|
8
|
+
// handler (`handle`), at least once: an occurrence is marked fired once the handler resolved, retried after a throw, and
|
|
9
|
+
// waits while the owner has none (not loaded). After each delivery the node event `scheduler/due` `{ node, owner, ref,
|
|
10
|
+
// key, scheduledFor, firedAt, late, missed }` (never `data`) tells whoever listens. A fired one-shot entry stays 30 days
|
|
11
|
+
// (`firedAt`, no `next`), then is purged. Floating rules take the `timeZone` setting (default: the host's zone), and
|
|
12
|
+
// move when it changes.
|
|
13
|
+
// Scheduled tasks (research-040, revision): a task is a schedule and a typed action, in the domain `scheduler/tasks` on
|
|
14
|
+
// `root` (`tasks.ts`). A plugin registers its action types on this service (`action`); an enabled task is planned on one
|
|
15
|
+
// entry of the scheduler's own (owner `scheduler`, key `task`), and a run happens at each delivery, never retried.
|
|
16
|
+
// Optional for its clients: a plugin that can live without it keeps `scheduler` out of `inject` and registers its
|
|
17
|
+
// handler in `ctx.inject(['scheduler'], (sub) => sub.scheduler.handle(sub, fn))` and its action types with
|
|
18
|
+
// `sub.scheduler.action(sub, type)`, reading `ctx.get('scheduler', false)` in its routes (`sessions` does, for snooze
|
|
19
|
+
// and its `sessions.prompt` action).
|
|
20
|
+
import type { Context } from 'cordis';
|
|
21
|
+
import {
|
|
22
|
+
createScheduler,
|
|
23
|
+
entryValue,
|
|
24
|
+
realClock,
|
|
25
|
+
type Clock,
|
|
26
|
+
type Due,
|
|
27
|
+
type Entry,
|
|
28
|
+
type ListQuery,
|
|
29
|
+
type Reference,
|
|
30
|
+
type ScheduleInput,
|
|
31
|
+
} from './core.ts';
|
|
32
|
+
import { knownZone, systemZone, type Rule } from './rules.ts';
|
|
33
|
+
import { createTasks, taskSchema, type Router } from './tasks.ts';
|
|
34
|
+
|
|
35
|
+
export type { Due, Entry, ListQuery, Reference, Rule, ScheduleInput };
|
|
36
|
+
|
|
37
|
+
export const name = 'scheduler';
|
|
38
|
+
export const inject = ['router', 'storage', 'nodes'];
|
|
39
|
+
|
|
40
|
+
/** A type of action a plugin registers on the scheduler (`action`): its form, and how a task runs it. */
|
|
41
|
+
export interface ActionType {
|
|
42
|
+
/** Its name within the plugin: registered as `<plugin>.<name>` (`sessions.prompt`). */
|
|
43
|
+
name: string;
|
|
44
|
+
title: string;
|
|
45
|
+
description?: string;
|
|
46
|
+
icon?: string;
|
|
47
|
+
/** A JSON Schema object: the task form and the agents' tools read it. */
|
|
48
|
+
input: Record<string, unknown>;
|
|
49
|
+
/** The input a task stores, or `invalid_body` (400) when it is not one. */
|
|
50
|
+
parse(input: unknown): unknown;
|
|
51
|
+
/** The default title of a task with this input. */
|
|
52
|
+
titleOf?(input: unknown): string;
|
|
53
|
+
/** What the task acts on, for listing by subject. */
|
|
54
|
+
subject?(input: unknown): { domain: string; id: string } | undefined;
|
|
55
|
+
/** The input of this type for a prompt scheduled from session `session` (that session's own, say): the type makes
|
|
56
|
+
* it, never the scheduler. A throw is answered as it is (a `not_found`, say). */
|
|
57
|
+
fromSession?(session: string, prompt: string): Promise<unknown>;
|
|
58
|
+
/** The choices of an `x-bridge-options` field of the form, by its kind; `input` is what the form holds now
|
|
59
|
+
* (unknown, possibly partial or empty), so a choice may follow an earlier field. */
|
|
60
|
+
options?(kind: string, input?: unknown): Promise<{ value: string; label: string }[]>;
|
|
61
|
+
/** Runs the action once, at `at` (the scheduler's clock) in its `zone`; `summary` is recorded on the task. A throw
|
|
62
|
+
* with `code: 'gone'` (what it acts on no longer exists) suspends the task. `signal` aborts at the run's deadline:
|
|
63
|
+
* stop there, as the task stays running until this resolves and its answer is refused. */
|
|
64
|
+
run(
|
|
65
|
+
input: unknown,
|
|
66
|
+
task: { taskId: string; title: string; at: string; zone?: string; signal?: AbortSignal },
|
|
67
|
+
): Promise<{ summary?: string } | void>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The `scheduler` service. Writes take the caller's context: its plugin is the owner. */
|
|
71
|
+
export interface SchedulerService {
|
|
72
|
+
/** Creates or replaces the caller's entry for `(ref, key)`; refused `invalid_entry`, `invalid_rule`, `rule_ended`
|
|
73
|
+
* (400). */
|
|
74
|
+
schedule(caller: Context, input: ScheduleInput): Promise<Entry>;
|
|
75
|
+
/** Removes the caller's entries for `ref` (one `key`, or all); resolves to how many. */
|
|
76
|
+
cancel(caller: Context, input: { ref: Reference; key?: string }): Promise<number>;
|
|
77
|
+
/** Entries matching every field given, anyone's: pending first by `next`, then fired ones, newest first. */
|
|
78
|
+
list(query?: ListQuery): Promise<Entry[]>;
|
|
79
|
+
/** A rule's fires in `[from, to)`, at most `take` (1000 at most): schedules nothing (a calendar view). */
|
|
80
|
+
occurrences(rule: Rule, range: { from: string; to: string; take?: number }): string[];
|
|
81
|
+
/** The caller's delivery, removed when the caller disposes; its due entries are delivered now. */
|
|
82
|
+
handle(caller: Context, fn: (due: Due) => unknown): void;
|
|
83
|
+
/** Registers an action type as `<caller plugin>.<name>`, removed when the caller disposes. */
|
|
84
|
+
action(caller: Context, type: ActionType): void;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
declare module 'cordis' {
|
|
88
|
+
interface Context {
|
|
89
|
+
scheduler: SchedulerService;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const pluginKey = Symbol.for('bridge.pluginKey');
|
|
94
|
+
const ownerOf = (caller: Context) => {
|
|
95
|
+
// oxlint-disable-next-line bridge/no-new-unchecked-cast -- typing: the kernel sets the plugin key symbol on every plugin context
|
|
96
|
+
const key = (caller as unknown as Record<symbol, unknown>)[pluginKey];
|
|
97
|
+
if (typeof key !== 'string') throw new Error('the scheduler takes a plugin context');
|
|
98
|
+
return key;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
export async function apply(ctx: Context, config?: { clock?: Clock }) {
|
|
102
|
+
const entries = await ctx.storage.objects(ctx, {
|
|
103
|
+
name: 'entries',
|
|
104
|
+
schema: entryValue,
|
|
105
|
+
version: 1,
|
|
106
|
+
indexes: ['next', 'owner'],
|
|
107
|
+
});
|
|
108
|
+
const records = await ctx.storage.objects(ctx, {
|
|
109
|
+
name: 'tasks',
|
|
110
|
+
schema: taskSchema,
|
|
111
|
+
version: 1,
|
|
112
|
+
});
|
|
113
|
+
const logger = ctx.logger('scheduler');
|
|
114
|
+
const clock = config?.clock ?? realClock;
|
|
115
|
+
const zone = () => {
|
|
116
|
+
const value = ctx.nodes.settings(name, 'root')?.values.timeZone?.value;
|
|
117
|
+
return typeof value === 'string' && value && knownZone(value) ? value : systemZone();
|
|
118
|
+
};
|
|
119
|
+
/** The `runDeadline` setting (minutes), in ms: how long a delivery or a task's run has. */
|
|
120
|
+
const deadline = () => {
|
|
121
|
+
const value = ctx.nodes.settings(name, 'root')?.values.runDeadline?.value;
|
|
122
|
+
return (typeof value === 'number' && value >= 1 ? value : 10) * 60_000;
|
|
123
|
+
};
|
|
124
|
+
const scheduler = await createScheduler({
|
|
125
|
+
store: {
|
|
126
|
+
all: async () =>
|
|
127
|
+
(await entries.query({ node: 'root' })).map(({ id, value }) => ({ ...value, id })),
|
|
128
|
+
create: async (value) => (await entries.create(ctx, value, { node: 'root' })).id,
|
|
129
|
+
update: async (id, value) => {
|
|
130
|
+
await entries.update(ctx, id, value);
|
|
131
|
+
},
|
|
132
|
+
remove: (id) => entries.purge(ctx, id),
|
|
133
|
+
},
|
|
134
|
+
clock,
|
|
135
|
+
zone,
|
|
136
|
+
deadline,
|
|
137
|
+
emit: (payload) => ctx.nodes.emit('scheduler/due', payload),
|
|
138
|
+
log: (message) => logger.warn(message),
|
|
139
|
+
});
|
|
140
|
+
ctx.effect(() => () => scheduler.dispose());
|
|
141
|
+
ctx.nodes.on(ctx, 'settings/changed', ({ plugin }: { plugin: string }) => {
|
|
142
|
+
if (plugin === name) return scheduler.rezone();
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const actions = new Map<string, ActionType>();
|
|
146
|
+
ctx.provide('scheduler', {
|
|
147
|
+
action: (caller, type) => {
|
|
148
|
+
const key = `${ownerOf(caller)}.${type.name}`;
|
|
149
|
+
actions.set(key, type);
|
|
150
|
+
caller.effect(() => () => actions.delete(key));
|
|
151
|
+
},
|
|
152
|
+
schedule: (caller, input) => scheduler.schedule(ownerOf(caller), input),
|
|
153
|
+
cancel: (caller, input) => scheduler.cancel(ownerOf(caller), input),
|
|
154
|
+
list: async (query) => scheduler.list(query),
|
|
155
|
+
occurrences: (rule, range) => scheduler.occurrences(rule, range),
|
|
156
|
+
handle: (caller, fn) => {
|
|
157
|
+
const owner = ownerOf(caller);
|
|
158
|
+
caller.effect(() => scheduler.handle(owner, fn));
|
|
159
|
+
},
|
|
160
|
+
} satisfies SchedulerService);
|
|
161
|
+
|
|
162
|
+
// The router is there in a host; a plugin's own test may apply this without one.
|
|
163
|
+
const router: Router | undefined = 'router' in ctx ? (ctx.router as Router) : undefined;
|
|
164
|
+
// Read the tasks before any delivery: a run's re-read then finds them loaded.
|
|
165
|
+
await records.query({ node: 'root', include: 'subtree' });
|
|
166
|
+
const tasks = createTasks({
|
|
167
|
+
ctx,
|
|
168
|
+
clock,
|
|
169
|
+
records,
|
|
170
|
+
actions,
|
|
171
|
+
planner: scheduler,
|
|
172
|
+
router,
|
|
173
|
+
zone,
|
|
174
|
+
deadline,
|
|
175
|
+
log: (what) => (error) => logger.warn(`${what}: ${messageOf(error)}`),
|
|
176
|
+
// `%s`: a title holding `%` is text, and the trailing object is the line's data with its subject.
|
|
177
|
+
history: (id, level, message, data) =>
|
|
178
|
+
logger[level]('%s', message, { subject: `task:${id}`, ...data }),
|
|
179
|
+
key: (() => {
|
|
180
|
+
try {
|
|
181
|
+
return ownerOf(ctx);
|
|
182
|
+
} catch {
|
|
183
|
+
return name; // a plugin's own test, without a host
|
|
184
|
+
}
|
|
185
|
+
})(),
|
|
186
|
+
});
|
|
187
|
+
// The scheduler's own entries (its tasks): its handler runs the action, with the scheduler's context. Registered on
|
|
188
|
+
// the next turn, so a plugin that loads with the scheduler registers its action types first (a delivery for a type
|
|
189
|
+
// still missing is thrown and retried by the core).
|
|
190
|
+
let stopped = false;
|
|
191
|
+
ctx.effect(() => () => {
|
|
192
|
+
stopped = true;
|
|
193
|
+
tasks.stop();
|
|
194
|
+
});
|
|
195
|
+
setImmediate(() => {
|
|
196
|
+
if (stopped) return;
|
|
197
|
+
ctx.effect(() => scheduler.handle(name, (due) => tasks.due(due)));
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
|