@eum-agent/automation-schedule 0.0.0-stage → 1.0.1
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/dist/index.js +1367 -0
- package/package.json +49 -3
- package/ui/ui.js +2716 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1367 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { fileURLToPath } from "node:url";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { Cron } from "croner";
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
//#region src/guidance.ts
|
|
7
|
+
const GUIDANCE = {
|
|
8
|
+
title: "Scheduled tasks",
|
|
9
|
+
entries: [
|
|
10
|
+
{
|
|
11
|
+
tools: ["schedule_create"],
|
|
12
|
+
text: "`schedule_create` sets yourself a task for later — once, every N minutes, or on a cron in a time zone. When you promise to follow up, schedule it rather than only saying so. `this-session` continues here; `new-session` runs as background work. Pass `rule` as an object, such as {\"kind\":\"interval\",\"everyMinutes\":15} or {\"kind\":\"cron\",\"expression\":\"0 9 * * *\",\"timezone\":\"Asia/Singapore\"}. Keep `scope` to what the runs need: the user sees it."
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
tools: ["schedule_list"],
|
|
16
|
+
text: "`schedule_list` shows bounded task summaries without instructions. Continue with next.arguments."
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
tools: ["schedule_read"],
|
|
20
|
+
text: "`schedule_read` reads explicit instruction or scope fields for listed ids. Follow next.arguments for exact continuation; reading scope grants no authority."
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
tools: ["schedule_update"],
|
|
24
|
+
text: "`schedule_update` changes a task you created. Its `rule` uses the same object fields: `kind`, with `at` for once, `everyMinutes` for interval, or `expression` and `timezone` for cron."
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
tools: ["schedule_delete"],
|
|
28
|
+
text: "`schedule_delete` removes an ids array of tasks you created atomically. Supply one stable UUID operationId; retry the complete intent with that same ID. Unknown or unowned tasks refuse the whole collection. Previously opened sessions remain."
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
};
|
|
32
|
+
//#endregion
|
|
33
|
+
//#region src/output-schema.ts
|
|
34
|
+
/** Validates complete owner business results and bounded recoverable delivery failures. */
|
|
35
|
+
/** Adds the standard failure envelope and bounded text refusals to an owner's result schema. */
|
|
36
|
+
function toolOutputSchema(body, input, name) {
|
|
37
|
+
return z.union([
|
|
38
|
+
body,
|
|
39
|
+
z.strictObject({
|
|
40
|
+
ok: z.literal(false),
|
|
41
|
+
error: z.strictObject({
|
|
42
|
+
code: z.string().min(1).max(128),
|
|
43
|
+
message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 }),
|
|
44
|
+
retryable: z.boolean(),
|
|
45
|
+
field: z.string().max(256).optional(),
|
|
46
|
+
maximum: z.number().finite().optional()
|
|
47
|
+
}),
|
|
48
|
+
next: z.strictObject({
|
|
49
|
+
tool: z.literal(name),
|
|
50
|
+
arguments: input
|
|
51
|
+
}).nullable(),
|
|
52
|
+
execution: z.strictObject({ state: z.enum([
|
|
53
|
+
"not-started",
|
|
54
|
+
"committed",
|
|
55
|
+
"unknown"
|
|
56
|
+
]) }).optional()
|
|
57
|
+
}),
|
|
58
|
+
z.string().max(1024)
|
|
59
|
+
]);
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
//#region src/source/rules.ts
|
|
63
|
+
/**
|
|
64
|
+
* Schedule rules: what one is, whether it is valid, and when it runs next.
|
|
65
|
+
*
|
|
66
|
+
* The one place a rule becomes a time. Cron expressions and time zones go
|
|
67
|
+
* through croner, because daylight-saving edges are where a hand-written
|
|
68
|
+
* reading goes wrong; the other two kinds are arithmetic.
|
|
69
|
+
*
|
|
70
|
+
* Every refusal starts `invalid rule:` and is written before anything is
|
|
71
|
+
* stored.
|
|
72
|
+
*/
|
|
73
|
+
/** When a scheduled task runs: once, every N minutes from an anchor, or on a
|
|
74
|
+
* cron expression read in an IANA time zone. */
|
|
75
|
+
const ScheduleRule = z.discriminatedUnion("kind", [
|
|
76
|
+
z.object({
|
|
77
|
+
kind: z.literal("once"),
|
|
78
|
+
at: z.number().int()
|
|
79
|
+
}),
|
|
80
|
+
z.object({
|
|
81
|
+
kind: z.literal("interval"),
|
|
82
|
+
everyMinutes: z.number().int().min(5),
|
|
83
|
+
anchor: z.number().int()
|
|
84
|
+
}),
|
|
85
|
+
z.object({
|
|
86
|
+
kind: z.literal("cron"),
|
|
87
|
+
expression: z.string().min(1).max(200),
|
|
88
|
+
timezone: z.string().min(1).max(100)
|
|
89
|
+
})
|
|
90
|
+
]);
|
|
91
|
+
const MINUTE = 6e4;
|
|
92
|
+
/** How far ahead a cron expression's spacing is checked. */
|
|
93
|
+
const SPACING_SAMPLE = 100;
|
|
94
|
+
function invalid(reason) {
|
|
95
|
+
return /* @__PURE__ */ new Error(`invalid rule: ${reason}`);
|
|
96
|
+
}
|
|
97
|
+
function cronOf(rule) {
|
|
98
|
+
try {
|
|
99
|
+
new Intl.DateTimeFormat("en-US", { timeZone: rule.timezone });
|
|
100
|
+
} catch {
|
|
101
|
+
throw invalid(`unknown time zone ${rule.timezone}`);
|
|
102
|
+
}
|
|
103
|
+
try {
|
|
104
|
+
return new Cron(rule.expression, {
|
|
105
|
+
timezone: rule.timezone,
|
|
106
|
+
paused: true
|
|
107
|
+
});
|
|
108
|
+
} catch (error) {
|
|
109
|
+
throw invalid(error instanceof Error ? error.message : String(error));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
/** The first time strictly after `after` the rule runs, or `null` for none. */
|
|
113
|
+
function nextRun(rule, after) {
|
|
114
|
+
switch (rule.kind) {
|
|
115
|
+
case "once": return rule.at > after ? rule.at : null;
|
|
116
|
+
case "interval": {
|
|
117
|
+
const every = rule.everyMinutes * MINUTE;
|
|
118
|
+
if (rule.anchor > after) return rule.anchor;
|
|
119
|
+
const steps = Math.floor((after - rule.anchor) / every) + 1;
|
|
120
|
+
return rule.anchor + steps * every;
|
|
121
|
+
}
|
|
122
|
+
case "cron": {
|
|
123
|
+
const next = cronOf(rule).nextRun(new Date(after));
|
|
124
|
+
return next === null ? null : next.getTime();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Throws `invalid rule: …` for a rule that cannot be stored now. */
|
|
129
|
+
function validateRule(rule, now) {
|
|
130
|
+
switch (rule.kind) {
|
|
131
|
+
case "once":
|
|
132
|
+
if (rule.at <= now) throw invalid("the time has passed");
|
|
133
|
+
return;
|
|
134
|
+
case "interval":
|
|
135
|
+
if (rule.everyMinutes * MINUTE < 3e5) throw invalid("runs less than 5 minutes apart");
|
|
136
|
+
return;
|
|
137
|
+
case "cron": {
|
|
138
|
+
const runs = cronOf(rule).nextRuns(SPACING_SAMPLE, new Date(now));
|
|
139
|
+
if (runs.length === 0) throw invalid("the expression never runs");
|
|
140
|
+
for (let i = 1; i < runs.length; i += 1) if (runs[i].getTime() - runs[i - 1].getTime() < 3e5) throw invalid("runs less than 5 minutes apart");
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
/** The next `count` times, after validating the rule. */
|
|
145
|
+
function previewRule(rule, now, count = 3) {
|
|
146
|
+
validateRule(rule, now);
|
|
147
|
+
const out = [];
|
|
148
|
+
let after = now;
|
|
149
|
+
for (let i = 0; i < count; i += 1) {
|
|
150
|
+
const next = nextRun(rule, after);
|
|
151
|
+
if (next === null) break;
|
|
152
|
+
out.push(next);
|
|
153
|
+
after = next;
|
|
154
|
+
}
|
|
155
|
+
return out;
|
|
156
|
+
}
|
|
157
|
+
//#endregion
|
|
158
|
+
//#region src/source/config.ts
|
|
159
|
+
/**
|
|
160
|
+
* A scheduled task's `config`: its rule, and whether a time missed while the
|
|
161
|
+
* gateway or this plugin was away is made up once. The core stores this as
|
|
162
|
+
* the source hands it back from `configSchema` and reads none of it; the
|
|
163
|
+
* rule's own checks (the 5-minute floor, a time already past, an unknown
|
|
164
|
+
* zone, an unreadable cron) run here, so a refusal reads `invalid rule: …`
|
|
165
|
+
* wherever the definition was written from.
|
|
166
|
+
*/
|
|
167
|
+
const ScheduleConfig$1 = z.object({
|
|
168
|
+
rule: ScheduleRule,
|
|
169
|
+
catchUp: z.boolean().default(true)
|
|
170
|
+
}).superRefine((config, check) => {
|
|
171
|
+
try {
|
|
172
|
+
validateRule(config.rule, Date.now());
|
|
173
|
+
} catch (error) {
|
|
174
|
+
check.addIssue({
|
|
175
|
+
code: "custom",
|
|
176
|
+
message: error instanceof Error ? error.message : String(error)
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
});
|
|
180
|
+
/** The config as stored, read back without judging the rule against now: a
|
|
181
|
+
* one-off that has run is still a valid record of when it ran. */
|
|
182
|
+
const StoredScheduleConfig = z.object({
|
|
183
|
+
rule: ScheduleRule,
|
|
184
|
+
catchUp: z.boolean().default(true)
|
|
185
|
+
});
|
|
186
|
+
function storedConfig(raw) {
|
|
187
|
+
const parsed = StoredScheduleConfig.safeParse(raw);
|
|
188
|
+
return parsed.success ? parsed.data : void 0;
|
|
189
|
+
}
|
|
190
|
+
//#endregion
|
|
191
|
+
//#region src/source/loop.ts
|
|
192
|
+
/**
|
|
193
|
+
* The schedule loop: one timer, set for the earliest due task or thirty
|
|
194
|
+
* seconds from now, whichever comes first. Each wake reconciles the
|
|
195
|
+
* next-run table against the source's enabled definitions, then judges every
|
|
196
|
+
* due task by how late it is — on time within a minute, otherwise missed (the
|
|
197
|
+
* gateway or this plugin was away, or the machine slept) and run once as a
|
|
198
|
+
* catch-up or skipped — and sets its next time from now, so however many
|
|
199
|
+
* times were missed, at most one run makes up for them.
|
|
200
|
+
*
|
|
201
|
+
* Reconciling decides where a next time comes from: a definition this table
|
|
202
|
+
* has not seen, one whose config changed, and one that was switched off when
|
|
203
|
+
* last seen are counted from now (no catch-up for a task someone just
|
|
204
|
+
* switched on); one that stayed enabled keeps its stored time, which is how a
|
|
205
|
+
* time missed while this plugin was off is noticed when it comes back.
|
|
206
|
+
*/
|
|
207
|
+
/** Later than this and a run counts as missed. */
|
|
208
|
+
const ON_TIME_MS = 6e4;
|
|
209
|
+
/** The loop never sleeps longer than this, so a late timer after sleep is
|
|
210
|
+
* noticed within half a minute. */
|
|
211
|
+
const MAX_SLEEP_MS = 3e4;
|
|
212
|
+
function hashOf(config) {
|
|
213
|
+
return createHash("sha256").update(JSON.stringify(config ?? null)).digest("hex");
|
|
214
|
+
}
|
|
215
|
+
/** Creates one schedule loop; explicit ticks also work before its timer starts. */
|
|
216
|
+
function createScheduleLoop(deps) {
|
|
217
|
+
const now = deps.now ?? (() => Date.now());
|
|
218
|
+
const setTimer = deps.setTimer ?? ((fn, ms) => {
|
|
219
|
+
const handle = setTimeout(fn, ms);
|
|
220
|
+
handle.unref?.();
|
|
221
|
+
return { cancel: () => clearTimeout(handle) };
|
|
222
|
+
});
|
|
223
|
+
let timer;
|
|
224
|
+
let running = false;
|
|
225
|
+
let stopped = false;
|
|
226
|
+
let generation = 0;
|
|
227
|
+
let ticking = Promise.resolve();
|
|
228
|
+
function reconcile(definitions) {
|
|
229
|
+
let touched = false;
|
|
230
|
+
const at = now();
|
|
231
|
+
const enabled = /* @__PURE__ */ new Set();
|
|
232
|
+
for (const definition of definitions) {
|
|
233
|
+
enabled.add(definition.id);
|
|
234
|
+
const config = storedConfig(definition.config);
|
|
235
|
+
if (config === void 0) continue;
|
|
236
|
+
const hash = hashOf(definition.config);
|
|
237
|
+
const row = deps.store.get(definition.id);
|
|
238
|
+
if (row !== void 0 && row.configHash === hash && row.seenEnabled) continue;
|
|
239
|
+
deps.store.put({
|
|
240
|
+
definitionId: definition.id,
|
|
241
|
+
nextAt: nextRun(config.rule, at),
|
|
242
|
+
configHash: hash,
|
|
243
|
+
seenEnabled: true
|
|
244
|
+
});
|
|
245
|
+
touched = true;
|
|
246
|
+
}
|
|
247
|
+
for (const row of deps.store.all()) if (!enabled.has(row.definitionId) && row.seenEnabled) {
|
|
248
|
+
deps.store.put({
|
|
249
|
+
...row,
|
|
250
|
+
seenEnabled: false
|
|
251
|
+
});
|
|
252
|
+
touched = true;
|
|
253
|
+
}
|
|
254
|
+
return touched;
|
|
255
|
+
}
|
|
256
|
+
async function wake(admittedGeneration) {
|
|
257
|
+
const definitions = deps.host.definitions();
|
|
258
|
+
let touched = reconcile(definitions);
|
|
259
|
+
const at = now();
|
|
260
|
+
const byId = new Map(definitions.map((one) => [one.id, one]));
|
|
261
|
+
for (const row of deps.store.all()) {
|
|
262
|
+
if (!row.seenEnabled || row.nextAt === null || row.nextAt > at) continue;
|
|
263
|
+
const definition = byId.get(row.definitionId);
|
|
264
|
+
const config = definition === void 0 ? void 0 : storedConfig(definition.config);
|
|
265
|
+
if (config === void 0) continue;
|
|
266
|
+
const scheduledAt = row.nextAt;
|
|
267
|
+
const late = at - scheduledAt > ON_TIME_MS;
|
|
268
|
+
deps.store.setNext(row.definitionId, nextRun(config.rule, at));
|
|
269
|
+
touched = true;
|
|
270
|
+
try {
|
|
271
|
+
if (late && !config.catchUp) {
|
|
272
|
+
deps.host.skip(row.definitionId, {
|
|
273
|
+
kind: "catch-up",
|
|
274
|
+
scheduledAt,
|
|
275
|
+
reason: "missed"
|
|
276
|
+
});
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
await deps.host.fire(row.definitionId, {
|
|
280
|
+
kind: late ? "catch-up" : "scheduled",
|
|
281
|
+
scheduledAt
|
|
282
|
+
});
|
|
283
|
+
} catch (error) {
|
|
284
|
+
deps.log?.(`scheduled task ${row.definitionId} did not run: ${error instanceof Error ? error.message : String(error)}`);
|
|
285
|
+
}
|
|
286
|
+
if (stopped || admittedGeneration !== generation) return;
|
|
287
|
+
}
|
|
288
|
+
if (touched) deps.changed?.();
|
|
289
|
+
}
|
|
290
|
+
function arm() {
|
|
291
|
+
timer?.cancel();
|
|
292
|
+
if (!running) return;
|
|
293
|
+
let earliest = null;
|
|
294
|
+
for (const row of deps.store.all()) {
|
|
295
|
+
if (!row.seenEnabled || row.nextAt === null) continue;
|
|
296
|
+
if (earliest === null || row.nextAt < earliest) earliest = row.nextAt;
|
|
297
|
+
}
|
|
298
|
+
const wait = earliest === null ? MAX_SLEEP_MS : Math.max(0, Math.min(earliest - now(), MAX_SLEEP_MS));
|
|
299
|
+
timer = setTimer(() => {
|
|
300
|
+
loop.tick();
|
|
301
|
+
}, wait);
|
|
302
|
+
}
|
|
303
|
+
const loop = {
|
|
304
|
+
tick() {
|
|
305
|
+
const admittedGeneration = generation;
|
|
306
|
+
ticking = ticking.then(() => {
|
|
307
|
+
if (!stopped && admittedGeneration === generation) return wake(admittedGeneration);
|
|
308
|
+
}).catch((error) => deps.log?.(`schedule loop failed: ${String(error)}`)).finally(() => {
|
|
309
|
+
if (admittedGeneration === generation) arm();
|
|
310
|
+
});
|
|
311
|
+
return ticking;
|
|
312
|
+
},
|
|
313
|
+
start() {
|
|
314
|
+
stopped = false;
|
|
315
|
+
running = true;
|
|
316
|
+
loop.tick();
|
|
317
|
+
},
|
|
318
|
+
stop() {
|
|
319
|
+
generation++;
|
|
320
|
+
stopped = true;
|
|
321
|
+
running = false;
|
|
322
|
+
timer?.cancel();
|
|
323
|
+
timer = void 0;
|
|
324
|
+
return ticking;
|
|
325
|
+
},
|
|
326
|
+
next() {
|
|
327
|
+
const out = {};
|
|
328
|
+
for (const row of deps.store.all()) if (row.seenEnabled) out[row.definitionId] = row.nextAt;
|
|
329
|
+
return out;
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
return loop;
|
|
333
|
+
}
|
|
334
|
+
//#endregion
|
|
335
|
+
//#region src/source/next-runs.ts
|
|
336
|
+
function toRow(raw) {
|
|
337
|
+
return {
|
|
338
|
+
definitionId: raw.definition_id,
|
|
339
|
+
nextAt: raw.next_at,
|
|
340
|
+
configHash: raw.config_hash,
|
|
341
|
+
seenEnabled: raw.seen_enabled === 1
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
function openNextRuns(ctx) {
|
|
345
|
+
const storage = ctx.storage.open();
|
|
346
|
+
const table = storage.tableName("next_run");
|
|
347
|
+
storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (
|
|
348
|
+
definition_id TEXT NOT NULL PRIMARY KEY,
|
|
349
|
+
next_at INTEGER,
|
|
350
|
+
config_hash TEXT NOT NULL,
|
|
351
|
+
seen_enabled INTEGER NOT NULL CHECK (seen_enabled IN (0, 1))
|
|
352
|
+
) STRICT`);
|
|
353
|
+
const selectOne = storage.db.prepare(`SELECT * FROM ${table} WHERE definition_id = ?`);
|
|
354
|
+
const selectAll = storage.db.prepare(`SELECT * FROM ${table} ORDER BY definition_id`);
|
|
355
|
+
const upsert = storage.db.prepare(`INSERT INTO ${table} (definition_id, next_at, config_hash, seen_enabled) VALUES (?, ?, ?, ?)
|
|
356
|
+
ON CONFLICT (definition_id) DO UPDATE SET next_at = excluded.next_at,
|
|
357
|
+
config_hash = excluded.config_hash, seen_enabled = excluded.seen_enabled`);
|
|
358
|
+
const updateNext = storage.db.prepare(`UPDATE ${table} SET next_at = ? WHERE definition_id = ?`);
|
|
359
|
+
return {
|
|
360
|
+
get(definitionId) {
|
|
361
|
+
const raw = selectOne.get(definitionId);
|
|
362
|
+
return raw === void 0 ? void 0 : toRow(raw);
|
|
363
|
+
},
|
|
364
|
+
all: () => selectAll.all().map(toRow),
|
|
365
|
+
put(row) {
|
|
366
|
+
upsert.run(row.definitionId, row.nextAt, row.configHash, row.seenEnabled ? 1 : 0);
|
|
367
|
+
},
|
|
368
|
+
setNext(definitionId, nextAt) {
|
|
369
|
+
updateNext.run(nextAt, definitionId);
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
/** An in-memory table, for a runtime without a database and for tests. */
|
|
374
|
+
function memoryNextRuns() {
|
|
375
|
+
const rows = /* @__PURE__ */ new Map();
|
|
376
|
+
return {
|
|
377
|
+
get: (id) => rows.get(id),
|
|
378
|
+
all: () => [...rows.values()].sort((a, b) => a.definitionId.localeCompare(b.definitionId)),
|
|
379
|
+
put: (row) => {
|
|
380
|
+
rows.set(row.definitionId, row);
|
|
381
|
+
},
|
|
382
|
+
setNext: (id, nextAt) => {
|
|
383
|
+
const row = rows.get(id);
|
|
384
|
+
if (row !== void 0) rows.set(id, {
|
|
385
|
+
...row,
|
|
386
|
+
nextAt
|
|
387
|
+
});
|
|
388
|
+
}
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
//#endregion
|
|
392
|
+
//#region src/source/index.ts
|
|
393
|
+
const SOURCE_KIND = "schedule";
|
|
394
|
+
const SOURCE_LABEL = "计划任务";
|
|
395
|
+
const NextRunsPayload = z.object({ next: z.record(z.string(), z.number().nullable()) });
|
|
396
|
+
/** Registers schedule reading and a source whose withdrawal joins admitted scheduling work. */
|
|
397
|
+
function registerScheduleSource(ctx) {
|
|
398
|
+
let store;
|
|
399
|
+
try {
|
|
400
|
+
store = openNextRuns(ctx);
|
|
401
|
+
} catch {
|
|
402
|
+
store = memoryNextRuns();
|
|
403
|
+
}
|
|
404
|
+
let loop;
|
|
405
|
+
const frame = ctx.client.registerFrame({
|
|
406
|
+
name: "nextRunsChanged",
|
|
407
|
+
delivery: "broadcast",
|
|
408
|
+
payload: NextRunsPayload
|
|
409
|
+
});
|
|
410
|
+
const announce = () => frame.emit({ next: { ...loop?.next() ?? {} } });
|
|
411
|
+
ctx.triggers.registerSource({
|
|
412
|
+
kind: SOURCE_KIND,
|
|
413
|
+
label: SOURCE_LABEL,
|
|
414
|
+
configSchema: ScheduleConfig$1,
|
|
415
|
+
start(host) {
|
|
416
|
+
loop = createScheduleLoop({
|
|
417
|
+
host,
|
|
418
|
+
store,
|
|
419
|
+
changed: announce,
|
|
420
|
+
log: (message) => ctx.log.emit({
|
|
421
|
+
level: "warn",
|
|
422
|
+
event: "plugin.event",
|
|
423
|
+
fields: { localCode: "MESSAGE" }
|
|
424
|
+
})
|
|
425
|
+
});
|
|
426
|
+
const off = host.onChanged(() => void loop?.tick());
|
|
427
|
+
loop.start();
|
|
428
|
+
return () => {
|
|
429
|
+
off();
|
|
430
|
+
const current = loop;
|
|
431
|
+
loop = void 0;
|
|
432
|
+
return current?.stop();
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
});
|
|
436
|
+
ctx.client.registerMethod({
|
|
437
|
+
name: "preview",
|
|
438
|
+
description: "The next three times a rule would run; an invalid rule is refused.",
|
|
439
|
+
params: z.strictObject({ rule: ScheduleRule }),
|
|
440
|
+
result: z.object({ times: z.array(z.number()) }),
|
|
441
|
+
handle: ({ rule }) => ({ times: previewRule(rule, Date.now()) })
|
|
442
|
+
});
|
|
443
|
+
ctx.client.registerMethod({
|
|
444
|
+
name: "nextRuns",
|
|
445
|
+
description: "When each enabled scheduled task runs next, by definition id; null for never.",
|
|
446
|
+
params: z.strictObject({}),
|
|
447
|
+
result: NextRunsPayload,
|
|
448
|
+
handle: () => ({ next: { ...loop?.next() ?? {} } })
|
|
449
|
+
});
|
|
450
|
+
return { next: () => loop?.next() ?? {} };
|
|
451
|
+
}
|
|
452
|
+
//#endregion
|
|
453
|
+
//#region src/cursor-cache.ts
|
|
454
|
+
const bytesOf = (value) => 2048 + 2 * (value.content?.length ?? 0);
|
|
455
|
+
/** Owns metadata snapshots; each query and all successor positions share one opaque host lease. */
|
|
456
|
+
var QueryCursorCache = class extends Map {
|
|
457
|
+
pending = /* @__PURE__ */ new Map();
|
|
458
|
+
roots = /* @__PURE__ */ new Map();
|
|
459
|
+
resources;
|
|
460
|
+
facts;
|
|
461
|
+
timer;
|
|
462
|
+
/** Measures only retained metadata; source IO uses a separate bounded reservation. */
|
|
463
|
+
constructor(facts, resources) {
|
|
464
|
+
super();
|
|
465
|
+
this.facts = facts;
|
|
466
|
+
this.resources = resources;
|
|
467
|
+
}
|
|
468
|
+
retained(root) {
|
|
469
|
+
let bytes = 0;
|
|
470
|
+
for (const state of this.values()) if (this.facts(state).initial === root.initial) bytes += bytesOf(this.facts(state));
|
|
471
|
+
return bytes;
|
|
472
|
+
}
|
|
473
|
+
total(root) {
|
|
474
|
+
return 2048 + 2 * JSON.stringify(root.initial).length + this.retained(root) + root.ioBytes + root.pendingBytes;
|
|
475
|
+
}
|
|
476
|
+
settle(root) {
|
|
477
|
+
if (root.released) return;
|
|
478
|
+
if (root.active === 0 && this.retained(root) === 0) {
|
|
479
|
+
root.released = true;
|
|
480
|
+
root.closing = true;
|
|
481
|
+
this.roots.delete(root.initial);
|
|
482
|
+
root.lease.close("completed");
|
|
483
|
+
if (!this.roots.size && this.timer) {
|
|
484
|
+
clearInterval(this.timer);
|
|
485
|
+
this.timer = void 0;
|
|
486
|
+
}
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
const released = root.heldBytes - this.total(root);
|
|
490
|
+
if (released > 0) {
|
|
491
|
+
root.lease.reduce({
|
|
492
|
+
bytes: released,
|
|
493
|
+
scratchBytes: 0
|
|
494
|
+
});
|
|
495
|
+
root.heldBytes -= released;
|
|
496
|
+
}
|
|
497
|
+
if (root.active === 0 && this.retained(root) > 0) root.lease.retain({
|
|
498
|
+
reason: "public-cursor",
|
|
499
|
+
idleMs: 6e5,
|
|
500
|
+
maxAgeMs: 36e5
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
invalidate(root) {
|
|
504
|
+
if (root.released) return;
|
|
505
|
+
root.closing = true;
|
|
506
|
+
for (const [key, state] of this) if (this.facts(state).initial === root.initial) super.delete(key);
|
|
507
|
+
root.pendingBytes = 0;
|
|
508
|
+
root.lease.close("abandoned");
|
|
509
|
+
}
|
|
510
|
+
async enter(call, initial, sourceBytes) {
|
|
511
|
+
const now = performance.now();
|
|
512
|
+
for (const root of this.roots.values()) if (now - root.used > 6e5 || now - root.created > 36e5) this.invalidate(root);
|
|
513
|
+
let root = this.roots.get(initial);
|
|
514
|
+
if (root?.closing || root?.lease.signal.aborted) throw new Error("cursor_invalid");
|
|
515
|
+
if (!root) {
|
|
516
|
+
const resources = this.resources;
|
|
517
|
+
if (!resources) throw new Error("query_resources_unavailable");
|
|
518
|
+
const initialBytes = sourceBytes + 2048 + 2 * JSON.stringify(initial).length;
|
|
519
|
+
root = {
|
|
520
|
+
initial,
|
|
521
|
+
lease: await resources.reserve(call, {
|
|
522
|
+
bytes: sourceBytes + 2048 + 2 * JSON.stringify(initial).length,
|
|
523
|
+
scratchBytes: 0,
|
|
524
|
+
cleanup: async () => {
|
|
525
|
+
const current = this.roots.get(initial);
|
|
526
|
+
for (const [id, value] of this) if (this.facts(value).initial === initial) super.delete(id);
|
|
527
|
+
if (current) {
|
|
528
|
+
current.released = true;
|
|
529
|
+
current.closing = true;
|
|
530
|
+
this.roots.delete(initial);
|
|
531
|
+
}
|
|
532
|
+
return { status: "complete" };
|
|
533
|
+
}
|
|
534
|
+
}),
|
|
535
|
+
created: now,
|
|
536
|
+
used: now,
|
|
537
|
+
active: 0,
|
|
538
|
+
ioBytes: 0,
|
|
539
|
+
pendingBytes: 0,
|
|
540
|
+
closing: false,
|
|
541
|
+
released: false,
|
|
542
|
+
heldBytes: initialBytes,
|
|
543
|
+
call
|
|
544
|
+
};
|
|
545
|
+
this.roots.set(initial, root);
|
|
546
|
+
this.timer ??= setInterval(() => {
|
|
547
|
+
const current = performance.now();
|
|
548
|
+
for (const candidate of this.roots.values()) if (current - candidate.used > 6e5 || current - candidate.created > 36e5) this.invalidate(candidate);
|
|
549
|
+
}, 6e4);
|
|
550
|
+
this.timer.unref();
|
|
551
|
+
}
|
|
552
|
+
root.lease.signal.throwIfAborted();
|
|
553
|
+
root.call = call;
|
|
554
|
+
const additional = this.total(root) + sourceBytes - root.heldBytes;
|
|
555
|
+
if (additional > 0) {
|
|
556
|
+
await root.lease.grow(call, {
|
|
557
|
+
bytes: additional,
|
|
558
|
+
scratchBytes: 0
|
|
559
|
+
});
|
|
560
|
+
root.heldBytes += additional;
|
|
561
|
+
}
|
|
562
|
+
root.active++;
|
|
563
|
+
root.ioBytes += sourceBytes;
|
|
564
|
+
root.used = now;
|
|
565
|
+
let finished = false;
|
|
566
|
+
return () => {
|
|
567
|
+
if (finished) return;
|
|
568
|
+
finished = true;
|
|
569
|
+
root.active--;
|
|
570
|
+
root.ioBytes -= sourceBytes;
|
|
571
|
+
root.pendingBytes = 0;
|
|
572
|
+
this.settle(root);
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/** Runs source acquisition under the actual authenticated call, releasing only after its cleanup. */
|
|
576
|
+
async runExclusive(input, call, action, sourceBytes = 4194304) {
|
|
577
|
+
const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
|
|
578
|
+
const saved = cursor === void 0 ? void 0 : this.get(cursor);
|
|
579
|
+
if (cursor !== void 0 && saved === void 0) return action();
|
|
580
|
+
const initial = saved === void 0 ? input : this.facts(saved).initial;
|
|
581
|
+
const existing = this.roots.get(initial);
|
|
582
|
+
if (existing && (existing.call.sessionId !== call.sessionId || JSON.stringify(existing.call.address) !== JSON.stringify(call.address) || existing.call.historyGeneration !== call.historyGeneration)) return action();
|
|
583
|
+
let finish;
|
|
584
|
+
try {
|
|
585
|
+
finish = await this.enter(call, initial, sourceBytes);
|
|
586
|
+
return await this.roots.get(initial).lease.withUse(call, action);
|
|
587
|
+
} catch (error) {
|
|
588
|
+
if (this.resources?.isAdmissionFailure(error)) throw error;
|
|
589
|
+
if (!(error instanceof Error) || ![
|
|
590
|
+
"query_limit_exceeded",
|
|
591
|
+
"query_resources_unavailable",
|
|
592
|
+
"cursor_invalid"
|
|
593
|
+
].includes(error.message)) throw error;
|
|
594
|
+
return {
|
|
595
|
+
content: JSON.stringify({
|
|
596
|
+
ok: false,
|
|
597
|
+
error: {
|
|
598
|
+
code: error.message,
|
|
599
|
+
message: "Shared query capacity or authority is unavailable; restart after releasing older queries.",
|
|
600
|
+
retryable: false
|
|
601
|
+
},
|
|
602
|
+
next: null
|
|
603
|
+
}),
|
|
604
|
+
isError: true
|
|
605
|
+
};
|
|
606
|
+
} finally {
|
|
607
|
+
finish?.();
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
/** Joins same-cursor preparation before revalidating and replaying its accepted exact page. */
|
|
611
|
+
async run(input, call, action, sourceBytes = 4194304) {
|
|
612
|
+
const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
|
|
613
|
+
if (cursor === void 0) return this.runExclusive(input, call, action, sourceBytes);
|
|
614
|
+
const previous = this.pending.get(cursor);
|
|
615
|
+
let unlock;
|
|
616
|
+
const gate = new Promise((resolve) => {
|
|
617
|
+
unlock = resolve;
|
|
618
|
+
});
|
|
619
|
+
this.pending.set(cursor, gate);
|
|
620
|
+
try {
|
|
621
|
+
await previous;
|
|
622
|
+
call.signal.throwIfAborted();
|
|
623
|
+
return await this.runExclusive(input, call, action, sourceBytes);
|
|
624
|
+
} finally {
|
|
625
|
+
unlock();
|
|
626
|
+
if (this.pending.get(cursor) === gate) this.pending.delete(cursor);
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
/** Applies the same resource lifecycle to a native model-tool registration. */
|
|
630
|
+
wrap(tool, sourceBytes = 4194304) {
|
|
631
|
+
const execute = tool.execute;
|
|
632
|
+
return {
|
|
633
|
+
...tool,
|
|
634
|
+
execute: (input, call) => this.run(input, call, async () => await execute(input, call), sourceBytes)
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
/** Accounts an exact candidate before accepting or retaining its snapshot. */
|
|
638
|
+
async prepare(initial, content) {
|
|
639
|
+
const root = this.roots.get(initial);
|
|
640
|
+
if (!root || root.closing) throw new Error("cursor_invalid");
|
|
641
|
+
root.lease.signal.throwIfAborted();
|
|
642
|
+
const bytes = 2048 + 2 * content.length;
|
|
643
|
+
const additional = this.total(root) - root.pendingBytes + bytes - root.heldBytes;
|
|
644
|
+
if (additional > 0) {
|
|
645
|
+
await root.lease.grow(root.call, {
|
|
646
|
+
bytes: additional,
|
|
647
|
+
scratchBytes: 0
|
|
648
|
+
});
|
|
649
|
+
root.heldBytes += additional;
|
|
650
|
+
}
|
|
651
|
+
root.pendingBytes = bytes;
|
|
652
|
+
}
|
|
653
|
+
/** Awaits metadata admission before installing a new cursor. */
|
|
654
|
+
async save(key, value) {
|
|
655
|
+
const root = this.roots.get(this.facts(value).initial);
|
|
656
|
+
if (!root || root.closing) throw new Error("cursor_invalid");
|
|
657
|
+
root.lease.signal.throwIfAborted();
|
|
658
|
+
const old = super.get(key);
|
|
659
|
+
const required = this.total(root) + bytesOf(this.facts(value)) - (old === void 0 ? 0 : bytesOf(this.facts(old)));
|
|
660
|
+
if (required > root.heldBytes) {
|
|
661
|
+
const bytes = required - root.heldBytes;
|
|
662
|
+
await root.lease.grow(root.call, {
|
|
663
|
+
bytes,
|
|
664
|
+
scratchBytes: 0
|
|
665
|
+
});
|
|
666
|
+
root.heldBytes += bytes;
|
|
667
|
+
}
|
|
668
|
+
super.set(key, value);
|
|
669
|
+
return this;
|
|
670
|
+
}
|
|
671
|
+
delete(key) {
|
|
672
|
+
const value = super.get(key), deleted = super.delete(key);
|
|
673
|
+
if (value !== void 0) {
|
|
674
|
+
const root = this.roots.get(this.facts(value).initial);
|
|
675
|
+
if (root) this.settle(root);
|
|
676
|
+
}
|
|
677
|
+
return deleted;
|
|
678
|
+
}
|
|
679
|
+
/** Drops retained metadata before releasing its shared reservation. */
|
|
680
|
+
clear() {
|
|
681
|
+
for (const root of [...this.roots.values()]) this.invalidate(root);
|
|
682
|
+
}
|
|
683
|
+
};
|
|
684
|
+
/** Applies a tighter owner-local memory ceiling while preserving shared resident accounting. */
|
|
685
|
+
function trimCursorCache(entries, retained) {
|
|
686
|
+
let bytes = 0;
|
|
687
|
+
for (const entry of entries.values()) bytes += bytesOf(retained(entry));
|
|
688
|
+
while (bytes > 8388608 || entries.size > 1024) {
|
|
689
|
+
const oldest = entries.entries().next().value;
|
|
690
|
+
if (!oldest) break;
|
|
691
|
+
bytes -= bytesOf(retained(oldest[1]));
|
|
692
|
+
entries.delete(oldest[0]);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
//#endregion
|
|
696
|
+
//#region src/schedule/pages.ts
|
|
697
|
+
/** Metadata pages use keyset reads; explicit details use only the requested definitions. */
|
|
698
|
+
const Tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired delivery tokens; the host may allocate fewer.");
|
|
699
|
+
const Continue = z.strictObject({
|
|
700
|
+
cursor: z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque continuation from next.arguments. Use alone, without changing the query."),
|
|
701
|
+
outputTokens: Tokens
|
|
702
|
+
});
|
|
703
|
+
const Start = z.strictObject({
|
|
704
|
+
limit: z.number().int().min(1).max(100).default(50).describe("Maximum summaries per call: default 50, hard maximum 100."),
|
|
705
|
+
outputTokens: Tokens
|
|
706
|
+
});
|
|
707
|
+
const ListInput = z.union([Start, Continue]);
|
|
708
|
+
const Summary = z.strictObject({
|
|
709
|
+
id: z.string(),
|
|
710
|
+
name: z.string(),
|
|
711
|
+
enabled: z.boolean(),
|
|
712
|
+
nextRun: z.string().nullable(),
|
|
713
|
+
scopeSummary: z.strictObject({ detailsAvailable: z.literal(true) })
|
|
714
|
+
});
|
|
715
|
+
const effective = z.strictObject({ outputTokens: z.number().int().nonnegative() });
|
|
716
|
+
const ListOutput = z.strictObject({
|
|
717
|
+
ok: z.literal(true),
|
|
718
|
+
complete: z.boolean(),
|
|
719
|
+
items: z.array(Summary),
|
|
720
|
+
next: z.strictObject({
|
|
721
|
+
tool: z.literal("schedule_list"),
|
|
722
|
+
arguments: Continue
|
|
723
|
+
}).nullable(),
|
|
724
|
+
effective
|
|
725
|
+
});
|
|
726
|
+
function failure$1(code, message, next = null) {
|
|
727
|
+
return {
|
|
728
|
+
content: JSON.stringify({
|
|
729
|
+
ok: false,
|
|
730
|
+
error: {
|
|
731
|
+
code,
|
|
732
|
+
message,
|
|
733
|
+
retryable: next !== null
|
|
734
|
+
},
|
|
735
|
+
next
|
|
736
|
+
}),
|
|
737
|
+
isError: true
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
function cursorStore(resources) {
|
|
741
|
+
const states = new QueryCursorCache((state) => ({
|
|
742
|
+
initial: state.query.initial,
|
|
743
|
+
content: state.result && "content" in state.result ? state.result.content : void 0
|
|
744
|
+
}), resources);
|
|
745
|
+
return {
|
|
746
|
+
wrap: (tool) => states.wrap(tool),
|
|
747
|
+
prepare: (initial, content) => states.prepare(initial, content),
|
|
748
|
+
trim() {
|
|
749
|
+
trimCursorCache(states, (state) => ({
|
|
750
|
+
initial: state.query.initial,
|
|
751
|
+
content: state.result && "content" in state.result ? state.result.content : void 0
|
|
752
|
+
}));
|
|
753
|
+
},
|
|
754
|
+
get(cursor, ctx) {
|
|
755
|
+
const saved = states.get(cursor);
|
|
756
|
+
return saved?.sessionId === ctx.sessionId && saved.address === JSON.stringify(ctx.address) && saved.generation === ctx.historyGeneration ? saved : void 0;
|
|
757
|
+
},
|
|
758
|
+
async set(cursor, query, ctx, created = performance.now()) {
|
|
759
|
+
const now = performance.now();
|
|
760
|
+
for (const [key, state] of states) if (now - state.created > 36e5 || state.sessionId === ctx.sessionId && state.generation !== ctx.historyGeneration) states.delete(key);
|
|
761
|
+
while (states.size >= 1024) {
|
|
762
|
+
const oldest = states.keys().next().value;
|
|
763
|
+
if (oldest) states.delete(oldest);
|
|
764
|
+
}
|
|
765
|
+
await states.save(cursor, {
|
|
766
|
+
query,
|
|
767
|
+
sessionId: ctx.sessionId,
|
|
768
|
+
address: JSON.stringify(ctx.address),
|
|
769
|
+
generation: ctx.historyGeneration,
|
|
770
|
+
created,
|
|
771
|
+
used: now
|
|
772
|
+
});
|
|
773
|
+
trimCursorCache(states, (state) => ({
|
|
774
|
+
initial: state.query.initial,
|
|
775
|
+
content: state.result && "content" in state.result ? state.result.content : void 0
|
|
776
|
+
}));
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
function expired(state) {
|
|
782
|
+
const now = performance.now();
|
|
783
|
+
return now - state.used > 6e5 || now - state.created > 36e5;
|
|
784
|
+
}
|
|
785
|
+
function replay(state, ctx, tool, input) {
|
|
786
|
+
if (!state.result) return void 0;
|
|
787
|
+
const cost = ctx.output.measure(state.result);
|
|
788
|
+
if (cost > ctx.output.outputTokens) return failure$1("page_too_small", "Saved exact page needs a larger independent allowance.", cost <= ctx.output.maximumTokens ? {
|
|
789
|
+
tool,
|
|
790
|
+
arguments: {
|
|
791
|
+
...input,
|
|
792
|
+
outputTokens: cost
|
|
793
|
+
}
|
|
794
|
+
} : null);
|
|
795
|
+
state.used = performance.now();
|
|
796
|
+
ctx.output.acceptExact(state.result);
|
|
797
|
+
return state.result;
|
|
798
|
+
}
|
|
799
|
+
/** Returns stable summary pages without loading instruction/configuration bodies. */
|
|
800
|
+
function listSchedulesTool(triggers, next = () => ({}), resources) {
|
|
801
|
+
const cursors = cursorStore(resources);
|
|
802
|
+
return cursors.wrap({
|
|
803
|
+
name: "schedule_list",
|
|
804
|
+
preload: false,
|
|
805
|
+
description: "List readable scheduled-task summaries without instructions or scopes. Use schedule_read for details. Follow next.arguments unchanged; concurrent definition changes require restarting.",
|
|
806
|
+
inputSchema: ListInput,
|
|
807
|
+
outputSchema: toolOutputSchema(ListOutput, ListInput, "schedule_list"),
|
|
808
|
+
deliveryKind: "exact-page",
|
|
809
|
+
async execute(input, ctx) {
|
|
810
|
+
ctx.signal.throwIfAborted();
|
|
811
|
+
let saved, query;
|
|
812
|
+
if ("cursor" in input) {
|
|
813
|
+
saved = cursors.get(input.cursor, ctx);
|
|
814
|
+
if (!saved) return failure$1("cursor_invalid", "Cursor does not belong to the current effective session.");
|
|
815
|
+
query = saved.query;
|
|
816
|
+
if (expired(saved)) return failure$1("cursor_expired", "Start the summary query again.", {
|
|
817
|
+
tool: "schedule_list",
|
|
818
|
+
arguments: query.initial
|
|
819
|
+
});
|
|
820
|
+
} else query = {
|
|
821
|
+
initial: input,
|
|
822
|
+
version: triggers.page(ctx, { limit: 1 }).queryVersion
|
|
823
|
+
};
|
|
824
|
+
const source = triggers.page(ctx, {
|
|
825
|
+
after: query.after,
|
|
826
|
+
limit: query.initial.limit
|
|
827
|
+
});
|
|
828
|
+
if (source.queryVersion !== query.version) return failure$1("source_changed", "Schedule definitions changed; start again.", {
|
|
829
|
+
tool: "schedule_list",
|
|
830
|
+
arguments: query.initial
|
|
831
|
+
});
|
|
832
|
+
const cached = saved && replay(saved, ctx, "schedule_list", input);
|
|
833
|
+
if (cached) return cached;
|
|
834
|
+
const times = next(), cursor = randomUUID();
|
|
835
|
+
const build = (count) => ({ content: JSON.stringify({
|
|
836
|
+
ok: true,
|
|
837
|
+
complete: count === source.items.length && source.complete,
|
|
838
|
+
items: source.items.slice(0, count).map((row) => ({
|
|
839
|
+
id: row.id,
|
|
840
|
+
name: row.name,
|
|
841
|
+
enabled: row.enabled,
|
|
842
|
+
nextRun: times[row.id] === void 0 || times[row.id] === null ? null : new Date(times[row.id]).toISOString(),
|
|
843
|
+
scopeSummary: { detailsAvailable: true }
|
|
844
|
+
})),
|
|
845
|
+
next: count === source.items.length && source.complete ? null : {
|
|
846
|
+
tool: "schedule_list",
|
|
847
|
+
arguments: { cursor }
|
|
848
|
+
},
|
|
849
|
+
effective: { outputTokens: ctx.output.outputTokens }
|
|
850
|
+
}) });
|
|
851
|
+
let count = source.items.length, result = build(count);
|
|
852
|
+
while (count > 0 && ctx.output.measure(result) > ctx.output.outputTokens) result = build(--count);
|
|
853
|
+
if (count === 0 && source.items.length > 0 || ctx.output.measure(result) > ctx.output.outputTokens) {
|
|
854
|
+
const cost = ctx.output.measure(build(Math.min(1, source.items.length)));
|
|
855
|
+
return failure$1("page_too_small", "A complete summary does not fit.", cost <= ctx.output.maximumTokens ? {
|
|
856
|
+
tool: "schedule_list",
|
|
857
|
+
arguments: {
|
|
858
|
+
...input,
|
|
859
|
+
outputTokens: cost
|
|
860
|
+
}
|
|
861
|
+
} : null);
|
|
862
|
+
}
|
|
863
|
+
if (!(count === source.items.length && source.complete) && !await cursors.set(cursor, {
|
|
864
|
+
...query,
|
|
865
|
+
after: source.items[count - 1]?.id
|
|
866
|
+
}, ctx, saved?.created)) return failure$1("step_budget_exhausted", "Summary cursor capacity is full.");
|
|
867
|
+
await cursors.prepare(query.initial, result.content);
|
|
868
|
+
ctx.output.acceptExact(result);
|
|
869
|
+
if (saved) {
|
|
870
|
+
saved.result = result;
|
|
871
|
+
cursors.trim();
|
|
872
|
+
saved.used = performance.now();
|
|
873
|
+
}
|
|
874
|
+
return result;
|
|
875
|
+
}
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
const Field = z.enum(["instruction", "scopes"]);
|
|
879
|
+
const ReadStart = z.strictObject({
|
|
880
|
+
ids: z.array(z.string().min(1).max(200).describe("Readable schedule id from schedule_list.")).min(1).max(16).describe("Ordered schedule ids, maximum 16. Duplicate ids remain independent members."),
|
|
881
|
+
fields: z.array(Field).min(1).max(2).default(["instruction", "scopes"]).describe("Explicit detail fields. Scopes are JSON text and never grant authority; default instruction and scopes."),
|
|
882
|
+
outputTokens: Tokens
|
|
883
|
+
});
|
|
884
|
+
const ReadInput = z.union([ReadStart, Continue]);
|
|
885
|
+
const Chunk = z.strictObject({
|
|
886
|
+
index: z.number().int().nonnegative(),
|
|
887
|
+
id: z.string(),
|
|
888
|
+
field: Field,
|
|
889
|
+
content: z.string(),
|
|
890
|
+
offset: z.number().int().nonnegative(),
|
|
891
|
+
length: z.number().int().nonnegative(),
|
|
892
|
+
complete: z.boolean()
|
|
893
|
+
});
|
|
894
|
+
const ReadOutput = z.strictObject({
|
|
895
|
+
ok: z.literal(true),
|
|
896
|
+
complete: z.boolean(),
|
|
897
|
+
items: z.array(Chunk),
|
|
898
|
+
next: z.strictObject({
|
|
899
|
+
tool: z.literal("schedule_read"),
|
|
900
|
+
arguments: Continue
|
|
901
|
+
}).nullable(),
|
|
902
|
+
effective
|
|
903
|
+
});
|
|
904
|
+
/** Returns exact revision-bound instruction/scope fragments for requested definitions only. */
|
|
905
|
+
function readScheduleTool(triggers, resources) {
|
|
906
|
+
const cursors = cursorStore(resources);
|
|
907
|
+
return cursors.wrap({
|
|
908
|
+
name: "schedule_read",
|
|
909
|
+
preload: false,
|
|
910
|
+
description: "Read instructions or scope details for 1–16 readable schedule ids. Long text is delivered as exact Unicode fragments. Copy next.arguments to continue before claiming the complete query was read. Reading scopes does not authorize execution.",
|
|
911
|
+
inputSchema: ReadInput,
|
|
912
|
+
outputSchema: toolOutputSchema(ReadOutput, ReadInput, "schedule_read"),
|
|
913
|
+
deliveryKind: "exact-page",
|
|
914
|
+
async execute(input, ctx) {
|
|
915
|
+
ctx.signal.throwIfAborted();
|
|
916
|
+
const version = triggers.page(ctx, { limit: 1 }).queryVersion;
|
|
917
|
+
let saved, query;
|
|
918
|
+
if ("cursor" in input) {
|
|
919
|
+
saved = cursors.get(input.cursor, ctx);
|
|
920
|
+
if (!saved) return failure$1("cursor_invalid", "Cursor does not belong to the current effective session.");
|
|
921
|
+
query = saved.query;
|
|
922
|
+
if (expired(saved)) return failure$1("cursor_expired", "Start the detail query again.", {
|
|
923
|
+
tool: "schedule_read",
|
|
924
|
+
arguments: query.initial
|
|
925
|
+
});
|
|
926
|
+
} else query = {
|
|
927
|
+
initial: input,
|
|
928
|
+
version,
|
|
929
|
+
index: 0,
|
|
930
|
+
field: 0,
|
|
931
|
+
offset: 0
|
|
932
|
+
};
|
|
933
|
+
if (version !== query.version) return failure$1("source_changed", "Schedule definitions changed; start again.", {
|
|
934
|
+
tool: "schedule_read",
|
|
935
|
+
arguments: query.initial
|
|
936
|
+
});
|
|
937
|
+
const cached = saved && replay(saved, ctx, "schedule_read", input);
|
|
938
|
+
if (cached) return cached;
|
|
939
|
+
const id = query.initial.ids[query.index], field = query.initial.fields[query.field];
|
|
940
|
+
const source = triggers.get(ctx, id);
|
|
941
|
+
if (!source) return failure$1("source_changed", "A requested schedule is absent or inaccessible; refresh the summary list.");
|
|
942
|
+
if (triggers.page(ctx, { limit: 1 }).queryVersion !== query.version) return failure$1("source_changed", "Schedule changed while reading; restart.", {
|
|
943
|
+
tool: "schedule_read",
|
|
944
|
+
arguments: query.initial
|
|
945
|
+
});
|
|
946
|
+
const window = unicodeWindow(field === "instruction" ? source.instruction : JSON.stringify(source.scope), query.offset, Math.min(32768, Math.max(1, ctx.output.outputTokens * 4)));
|
|
947
|
+
const points = window.points, cursor = randomUUID();
|
|
948
|
+
const build = (count) => {
|
|
949
|
+
const fieldComplete = window.complete && count === points.length;
|
|
950
|
+
const complete = fieldComplete && query.field + 1 === query.initial.fields.length && query.index + 1 === query.initial.ids.length;
|
|
951
|
+
return { content: JSON.stringify({
|
|
952
|
+
ok: true,
|
|
953
|
+
complete,
|
|
954
|
+
items: [{
|
|
955
|
+
index: query.index,
|
|
956
|
+
id,
|
|
957
|
+
field,
|
|
958
|
+
content: points.slice(0, count).join(""),
|
|
959
|
+
offset: query.offset,
|
|
960
|
+
length: count,
|
|
961
|
+
complete: fieldComplete
|
|
962
|
+
}],
|
|
963
|
+
next: complete ? null : {
|
|
964
|
+
tool: "schedule_read",
|
|
965
|
+
arguments: { cursor }
|
|
966
|
+
},
|
|
967
|
+
effective: { outputTokens: ctx.output.outputTokens }
|
|
968
|
+
}) };
|
|
969
|
+
};
|
|
970
|
+
let low = 0, high = points.length;
|
|
971
|
+
while (low < high) {
|
|
972
|
+
const middle = Math.ceil((low + high) / 2);
|
|
973
|
+
if (ctx.output.measure(build(middle)) <= ctx.output.outputTokens) low = middle;
|
|
974
|
+
else high = middle - 1;
|
|
975
|
+
}
|
|
976
|
+
const result = build(low);
|
|
977
|
+
if (low === 0 && points.length > 0 || ctx.output.measure(result) > ctx.output.outputTokens) {
|
|
978
|
+
const cost = ctx.output.measure(build(Math.min(1, points.length)));
|
|
979
|
+
return failure$1("page_too_small", "The detail envelope and one code point do not fit.", cost <= ctx.output.maximumTokens ? {
|
|
980
|
+
tool: "schedule_read",
|
|
981
|
+
arguments: {
|
|
982
|
+
...input,
|
|
983
|
+
outputTokens: cost
|
|
984
|
+
}
|
|
985
|
+
} : null);
|
|
986
|
+
}
|
|
987
|
+
const fieldComplete = window.complete && low === points.length;
|
|
988
|
+
const memberComplete = fieldComplete && query.field + 1 === query.initial.fields.length;
|
|
989
|
+
if (!(memberComplete && query.index + 1 === query.initial.ids.length) && !await cursors.set(cursor, {
|
|
990
|
+
...query,
|
|
991
|
+
index: memberComplete ? query.index + 1 : query.index,
|
|
992
|
+
field: memberComplete ? 0 : fieldComplete ? query.field + 1 : query.field,
|
|
993
|
+
offset: fieldComplete ? 0 : query.offset + low
|
|
994
|
+
}, ctx, saved?.created)) return failure$1("step_budget_exhausted", "Detail cursor capacity is full.");
|
|
995
|
+
await cursors.prepare(query.initial, result.content);
|
|
996
|
+
ctx.output.acceptExact(result);
|
|
997
|
+
if (saved) {
|
|
998
|
+
saved.result = result;
|
|
999
|
+
cursors.trim();
|
|
1000
|
+
saved.used = performance.now();
|
|
1001
|
+
}
|
|
1002
|
+
return result;
|
|
1003
|
+
}
|
|
1004
|
+
});
|
|
1005
|
+
}
|
|
1006
|
+
/** Builds a bounded Unicode window without allocating an array for the complete source. */
|
|
1007
|
+
function unicodeWindow(text, offset, maximum) {
|
|
1008
|
+
let unit = 0, skipped = 0;
|
|
1009
|
+
while (unit < text.length && skipped < offset) {
|
|
1010
|
+
unit += text.codePointAt(unit) > 65535 ? 2 : 1;
|
|
1011
|
+
skipped++;
|
|
1012
|
+
}
|
|
1013
|
+
const points = [];
|
|
1014
|
+
while (unit < text.length && points.length < maximum) {
|
|
1015
|
+
const size = text.codePointAt(unit) > 65535 ? 2 : 1;
|
|
1016
|
+
points.push(text.slice(unit, unit + size));
|
|
1017
|
+
unit += size;
|
|
1018
|
+
}
|
|
1019
|
+
return {
|
|
1020
|
+
points,
|
|
1021
|
+
complete: unit === text.length
|
|
1022
|
+
};
|
|
1023
|
+
}
|
|
1024
|
+
//#endregion
|
|
1025
|
+
//#region src/schedule/settings.ts
|
|
1026
|
+
/** The most tasks a limit may name short of no limit. */
|
|
1027
|
+
const AGENT_LIMIT_CEILING = 1e3;
|
|
1028
|
+
/** The settings on the wire and on disk. `agentLimit` `0` is no limit. */
|
|
1029
|
+
const ScheduleSettings = z.strictObject({ agentLimit: z.number().int().min(0).max(AGENT_LIMIT_CEILING) });
|
|
1030
|
+
const DEFAULT_SCHEDULE_SETTINGS = { agentLimit: 20 };
|
|
1031
|
+
const LOCAL_TABLE = "settings";
|
|
1032
|
+
const KEY = "schedule";
|
|
1033
|
+
function openScheduleSettings(ctx) {
|
|
1034
|
+
const storage = ctx.storage.open();
|
|
1035
|
+
const table = storage.tableName(LOCAL_TABLE);
|
|
1036
|
+
storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (
|
|
1037
|
+
key TEXT NOT NULL,
|
|
1038
|
+
value TEXT NOT NULL,
|
|
1039
|
+
updated_at INTEGER NOT NULL,
|
|
1040
|
+
PRIMARY KEY (key)
|
|
1041
|
+
) STRICT`);
|
|
1042
|
+
return {
|
|
1043
|
+
read() {
|
|
1044
|
+
const row = storage.db.prepare(`SELECT value FROM ${table} WHERE key = ?`).get(KEY);
|
|
1045
|
+
if (row === void 0) return DEFAULT_SCHEDULE_SETTINGS;
|
|
1046
|
+
const parsed = parse(row.value);
|
|
1047
|
+
if (parsed !== void 0) return parsed;
|
|
1048
|
+
ctx.log.emit({
|
|
1049
|
+
level: "error",
|
|
1050
|
+
event: "plugin.event",
|
|
1051
|
+
fields: { localCode: "SCHEDULED_TASK_SETTINGS_COULD_NOT_BE_READ_USING_THE_DEFAULTS" }
|
|
1052
|
+
});
|
|
1053
|
+
return DEFAULT_SCHEDULE_SETTINGS;
|
|
1054
|
+
},
|
|
1055
|
+
write(settings) {
|
|
1056
|
+
storage.db.prepare(`INSERT INTO ${table} (key, value, updated_at) VALUES (?, ?, ?)
|
|
1057
|
+
ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`).run(KEY, JSON.stringify(settings), Date.now());
|
|
1058
|
+
return settings;
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
function parse(raw) {
|
|
1063
|
+
if (typeof raw !== "string") return void 0;
|
|
1064
|
+
try {
|
|
1065
|
+
const read = ScheduleSettings.safeParse(JSON.parse(raw));
|
|
1066
|
+
return read.success ? read.data : void 0;
|
|
1067
|
+
} catch {
|
|
1068
|
+
return;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
//#endregion
|
|
1072
|
+
//#region src/schedule/index.ts
|
|
1073
|
+
const Receipt = z.strictObject({
|
|
1074
|
+
ok: z.literal(true),
|
|
1075
|
+
committed: z.literal(true),
|
|
1076
|
+
id: z.string(),
|
|
1077
|
+
enabled: z.boolean(),
|
|
1078
|
+
nextRunAt: z.string().nullable(),
|
|
1079
|
+
changedFields: z.array(z.string())
|
|
1080
|
+
});
|
|
1081
|
+
const TRIGGERS_SERVICE = "triggers";
|
|
1082
|
+
const OnceRule = z.object({
|
|
1083
|
+
kind: z.literal("once").describe("Run once at the supplied at timestamp."),
|
|
1084
|
+
at: z.string().describe("Required for once: ISO 8601 date-time with offset, e.g. 2026-09-27T09:00:00+08:00")
|
|
1085
|
+
});
|
|
1086
|
+
const IntervalRule = z.object({
|
|
1087
|
+
kind: z.literal("interval").describe("Repeat at everyMinutes, minimum five minutes."),
|
|
1088
|
+
everyMinutes: z.number().int().min(5).describe("Required for interval: minutes between runs, at least 5")
|
|
1089
|
+
});
|
|
1090
|
+
const CronRule = z.object({
|
|
1091
|
+
kind: z.literal("cron").describe("Repeat using a five-field expression in the supplied timezone."),
|
|
1092
|
+
expression: z.string().min(1).describe("Required for cron: five fields, e.g. 0 9 * * 1-5"),
|
|
1093
|
+
timezone: z.string().min(1).describe("Required for cron: IANA time zone, e.g. Asia/Singapore")
|
|
1094
|
+
});
|
|
1095
|
+
const Rule = z.object({
|
|
1096
|
+
kind: z.enum([
|
|
1097
|
+
"once",
|
|
1098
|
+
"interval",
|
|
1099
|
+
"cron"
|
|
1100
|
+
]).describe("Select once with at, interval with everyMinutes, or cron with expression and timezone."),
|
|
1101
|
+
at: OnceRule.shape.at.optional(),
|
|
1102
|
+
everyMinutes: IntervalRule.shape.everyMinutes.optional(),
|
|
1103
|
+
expression: CronRule.shape.expression.optional(),
|
|
1104
|
+
timezone: CronRule.shape.timezone.optional()
|
|
1105
|
+
}, { error: "rule must be a JSON object, for example {\"kind\":\"interval\",\"everyMinutes\":15}" }).meta({
|
|
1106
|
+
description: "Schedule rule object. Use kind once with at; interval with everyMinutes; or cron with expression and timezone.",
|
|
1107
|
+
examples: [{
|
|
1108
|
+
kind: "interval",
|
|
1109
|
+
everyMinutes: 15
|
|
1110
|
+
}, {
|
|
1111
|
+
kind: "cron",
|
|
1112
|
+
expression: "0 9 * * *",
|
|
1113
|
+
timezone: "Asia/Singapore"
|
|
1114
|
+
}]
|
|
1115
|
+
}).pipe(z.discriminatedUnion("kind", [
|
|
1116
|
+
OnceRule,
|
|
1117
|
+
IntervalRule,
|
|
1118
|
+
CronRule
|
|
1119
|
+
]));
|
|
1120
|
+
const Scope = z.array(z.object({
|
|
1121
|
+
kind: z.enum([
|
|
1122
|
+
"read",
|
|
1123
|
+
"write",
|
|
1124
|
+
"network",
|
|
1125
|
+
"web-host"
|
|
1126
|
+
]).describe("Permission kind requested for the scheduled run; scope never bypasses approval."),
|
|
1127
|
+
target: z.string().min(1).describe("absolute path, * for network, or a host")
|
|
1128
|
+
})).max(100).describe("Requested run permissions, at most 100 entries; changes require approval.");
|
|
1129
|
+
const CreateInput = z.object({
|
|
1130
|
+
name: z.string().trim().min(1).max(80).describe("Task display name, 1–80 UTF-16 code units after trimming."),
|
|
1131
|
+
rule: Rule,
|
|
1132
|
+
instruction: z.string().trim().min(1).max(8e3).describe("Instruction executed when due, 1–8000 UTF-16 code units after trimming."),
|
|
1133
|
+
target: z.enum(["this-session", "new-session"]).default("this-session").describe("Deliver the run to this session or create a new session; default this-session."),
|
|
1134
|
+
catchUp: z.boolean().optional().describe("Whether missed due runs execute after startup; creation defaults to true, update omission retains current behavior."),
|
|
1135
|
+
scope: Scope.optional()
|
|
1136
|
+
});
|
|
1137
|
+
const UpdateInput = z.object({
|
|
1138
|
+
id: z.string().min(1).describe("Exact readable task id from schedule_list."),
|
|
1139
|
+
name: z.string().trim().min(1).max(80).optional().describe("Replacement task name, 1–80 UTF-16 code units after trimming; omit to retain."),
|
|
1140
|
+
rule: Rule.optional(),
|
|
1141
|
+
instruction: z.string().trim().min(1).max(8e3).optional().describe("Replacement instruction, 1–8000 UTF-16 code units after trimming; omit to retain."),
|
|
1142
|
+
target: z.enum(["this-session", "new-session"]).optional().describe("Replacement run destination; omit to retain."),
|
|
1143
|
+
catchUp: z.boolean().optional().describe("Whether missed due runs execute after startup; creation defaults to true, update omission retains current behavior."),
|
|
1144
|
+
scope: Scope.optional()
|
|
1145
|
+
});
|
|
1146
|
+
const DeleteInput = z.object({
|
|
1147
|
+
operationId: z.uuid().describe("New UUID; reuse only for an identical retry of this deletion."),
|
|
1148
|
+
ids: z.array(z.string().min(1)).min(1).max(64).describe("Readable task ids to delete, 1–64, under one approval.")
|
|
1149
|
+
}).strict().refine((input) => new TextEncoder().encode(JSON.stringify(input)).byteLength <= 8388608, "batch input exceeds 8 MiB");
|
|
1150
|
+
function toRule(rule, now) {
|
|
1151
|
+
switch (rule.kind) {
|
|
1152
|
+
case "once": {
|
|
1153
|
+
const at = Date.parse(rule.at);
|
|
1154
|
+
if (Number.isNaN(at)) throw new Error(`invalid rule: ${rule.at} is not a date-time`);
|
|
1155
|
+
return {
|
|
1156
|
+
kind: "once",
|
|
1157
|
+
at
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
case "interval": return {
|
|
1161
|
+
kind: "interval",
|
|
1162
|
+
everyMinutes: rule.everyMinutes,
|
|
1163
|
+
anchor: now
|
|
1164
|
+
};
|
|
1165
|
+
case "cron": return rule;
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
/** One line a person reads in the approval: when this runs. */
|
|
1169
|
+
function describeRule(rule) {
|
|
1170
|
+
switch (rule.kind) {
|
|
1171
|
+
case "once": return `once at ${new Date(rule.at).toISOString()}`;
|
|
1172
|
+
case "interval": return `every ${rule.everyMinutes} minutes`;
|
|
1173
|
+
case "cron": return `cron ${rule.expression} (${rule.timezone})`;
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
function answer(outcome, next, changedFields) {
|
|
1177
|
+
switch (outcome.kind) {
|
|
1178
|
+
case "ask": return outcome.result;
|
|
1179
|
+
case "refused": return {
|
|
1180
|
+
content: outcome.message,
|
|
1181
|
+
isError: true
|
|
1182
|
+
};
|
|
1183
|
+
case "done": return { content: JSON.stringify({
|
|
1184
|
+
ok: true,
|
|
1185
|
+
committed: true,
|
|
1186
|
+
id: outcome.trigger.id,
|
|
1187
|
+
enabled: outcome.trigger.enabled,
|
|
1188
|
+
nextRunAt: next()[outcome.trigger.id] == null ? null : new Date(next()[outcome.trigger.id]).toISOString(),
|
|
1189
|
+
changedFields
|
|
1190
|
+
}) };
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
function failure(error) {
|
|
1194
|
+
const text = (error instanceof Error ? error.message : String(error)).slice(0, 512);
|
|
1195
|
+
const last = text.charCodeAt(text.length - 1);
|
|
1196
|
+
return {
|
|
1197
|
+
content: last >= 55296 && last <= 56319 ? text.slice(0, -1) : text,
|
|
1198
|
+
isError: true
|
|
1199
|
+
};
|
|
1200
|
+
}
|
|
1201
|
+
function createScheduleTool(triggers, agentLimit, next = () => ({})) {
|
|
1202
|
+
return {
|
|
1203
|
+
name: "schedule_create",
|
|
1204
|
+
preload: false,
|
|
1205
|
+
description: "Schedule a task for yourself: at `rule` time, `instruction` is delivered to you as a new turn, in this session (`this-session`, the default) or in a new background session each run (`new-session`). The user may be asked to approve it. `scope` pre-authorizes paths, network or hosts for a new-session task’s runs and is always shown to the user.",
|
|
1206
|
+
inputSchema: CreateInput,
|
|
1207
|
+
outputSchema: toolOutputSchema(Receipt, CreateInput, "schedule_create"),
|
|
1208
|
+
deliveryKind: "receipt",
|
|
1209
|
+
async execute(input, ctx) {
|
|
1210
|
+
try {
|
|
1211
|
+
const limit = agentLimit();
|
|
1212
|
+
if (limit > 0) {
|
|
1213
|
+
if (triggers.countCreated(ctx) >= limit) return failure(/* @__PURE__ */ new Error(`this agent already has ${limit} scheduled tasks in this workspace; delete one first`));
|
|
1214
|
+
}
|
|
1215
|
+
const rule = toRule(input.rule, Date.now());
|
|
1216
|
+
return answer(triggers.create(ctx, {
|
|
1217
|
+
kind: SOURCE_KIND,
|
|
1218
|
+
name: input.name,
|
|
1219
|
+
config: {
|
|
1220
|
+
rule,
|
|
1221
|
+
catchUp: input.catchUp ?? true
|
|
1222
|
+
},
|
|
1223
|
+
summary: describeRule(rule),
|
|
1224
|
+
instruction: input.instruction,
|
|
1225
|
+
target: input.target,
|
|
1226
|
+
...input.scope === void 0 ? {} : { scope: input.scope }
|
|
1227
|
+
}), next, Object.keys(input));
|
|
1228
|
+
} catch (error) {
|
|
1229
|
+
return failure(error);
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
function updateScheduleTool(triggers, next = () => ({})) {
|
|
1235
|
+
return {
|
|
1236
|
+
name: "schedule_update",
|
|
1237
|
+
preload: false,
|
|
1238
|
+
description: "Change a scheduled task you created. Changing what it does, when, where, or widening its scope may ask the user.",
|
|
1239
|
+
inputSchema: UpdateInput,
|
|
1240
|
+
outputSchema: toolOutputSchema(Receipt, UpdateInput, "schedule_update"),
|
|
1241
|
+
deliveryKind: "receipt",
|
|
1242
|
+
async execute(input, ctx) {
|
|
1243
|
+
try {
|
|
1244
|
+
const { id, rule, catchUp, ...rest } = input;
|
|
1245
|
+
const patch = Object.fromEntries(Object.entries(rest).filter(([, value]) => value !== void 0));
|
|
1246
|
+
const current = storedConfig(triggers.get(ctx, id)?.config);
|
|
1247
|
+
const config = current === void 0 || !(rule !== void 0 || catchUp !== void 0) ? void 0 : {
|
|
1248
|
+
rule: rule === void 0 ? current.rule : toRule(rule, Date.now()),
|
|
1249
|
+
catchUp: catchUp ?? current.catchUp
|
|
1250
|
+
};
|
|
1251
|
+
return answer(triggers.update(ctx, id, {
|
|
1252
|
+
...patch,
|
|
1253
|
+
...config === void 0 ? {} : { config },
|
|
1254
|
+
...current === void 0 ? {} : { summary: describeRule((config ?? current).rule) }
|
|
1255
|
+
}), next, Object.keys(input).filter((key) => key !== "id"));
|
|
1256
|
+
} catch (error) {
|
|
1257
|
+
return failure(error);
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
};
|
|
1261
|
+
}
|
|
1262
|
+
/** Deletes an owned schedule collection atomically and returns its durable operation receipt. */
|
|
1263
|
+
function deleteScheduleTool(triggers) {
|
|
1264
|
+
return {
|
|
1265
|
+
name: "schedule_delete",
|
|
1266
|
+
preload: false,
|
|
1267
|
+
description: "Delete 1–64 scheduled tasks you created in one atomic operation. Supply a stable UUID operationId and ids array; retry the same intent with the same ID. Unknown or unowned tasks refuse the whole collection. Sessions already opened stay.",
|
|
1268
|
+
inputSchema: DeleteInput,
|
|
1269
|
+
outputSchema: toolOutputSchema(z.strictObject({
|
|
1270
|
+
operationState: z.literal("committed"),
|
|
1271
|
+
operationId: z.uuid(),
|
|
1272
|
+
value: z.strictObject({ removed: z.array(z.string()) })
|
|
1273
|
+
}), DeleteInput, "schedule_delete"),
|
|
1274
|
+
deliveryKind: "receipt",
|
|
1275
|
+
async execute(input, ctx) {
|
|
1276
|
+
try {
|
|
1277
|
+
return { content: JSON.stringify(triggers.removeMany(ctx, input.ids, input.operationId)) };
|
|
1278
|
+
} catch (error) {
|
|
1279
|
+
return failure(error);
|
|
1280
|
+
}
|
|
1281
|
+
}
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
function registerScheduleTools(ctx, register, agentLimit = () => DEFAULT_SCHEDULE_SETTINGS.agentLimit, next = () => ({})) {
|
|
1285
|
+
const triggers = ctx.services.get(TRIGGERS_SERVICE);
|
|
1286
|
+
register(createScheduleTool(triggers, agentLimit, next));
|
|
1287
|
+
register(listSchedulesTool(triggers, next, ctx.services.get("query-resources")));
|
|
1288
|
+
register(readScheduleTool(triggers, ctx.services.get("query-resources")));
|
|
1289
|
+
register(updateScheduleTool(triggers, next));
|
|
1290
|
+
register(deleteScheduleTool(triggers));
|
|
1291
|
+
}
|
|
1292
|
+
//#endregion
|
|
1293
|
+
//#region src/tool-names.ts
|
|
1294
|
+
/** Canonical names shared by tool registration and browser presentation. */
|
|
1295
|
+
const TOOL_NAMES = [
|
|
1296
|
+
"schedule_create",
|
|
1297
|
+
"schedule_list",
|
|
1298
|
+
"schedule_read",
|
|
1299
|
+
"schedule_update",
|
|
1300
|
+
"schedule_delete"
|
|
1301
|
+
];
|
|
1302
|
+
//#endregion
|
|
1303
|
+
//#region src/index.ts
|
|
1304
|
+
/**
|
|
1305
|
+
* `@eum-agent/automation-schedule` — creating, listing, changing and deleting scheduled
|
|
1306
|
+
* tasks over the host's `triggers` service, as one plugin.
|
|
1307
|
+
*
|
|
1308
|
+
* Members live under `src/`: `schedule/` (the four `schedule_*` tools and the
|
|
1309
|
+
* settings `schedule_create` reads), plus `ui.tsx`, the browser module holding
|
|
1310
|
+
* the settings category. None of them is a plugin; this file is the only one, and it is what a person's
|
|
1311
|
+
* `config.json` names, what `plugin list` prints, and what the loader imports.
|
|
1312
|
+
*
|
|
1313
|
+
* `@eum-agent/plugin` is the only workspace package any file here imports, and
|
|
1314
|
+
* only its types: everything reached at runtime arrived through `ctx`.
|
|
1315
|
+
*/
|
|
1316
|
+
/**
|
|
1317
|
+
* This plugin's slice of `config.json`.
|
|
1318
|
+
*
|
|
1319
|
+
* `disabled` turns one tool off while the rest of the package stays on —
|
|
1320
|
+
* `enabled: false` on the declaration turns off every one of them. Strict and
|
|
1321
|
+
* enumerated: a misspelled tool name is a load failure naming the field, not
|
|
1322
|
+
* a line that quietly does nothing. The scheduled-task settings are not here:
|
|
1323
|
+
* they are kept by the plugin itself (`schedule/settings.ts`), so changing
|
|
1324
|
+
* them reloads nothing.
|
|
1325
|
+
*/
|
|
1326
|
+
const ScheduleConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
|
|
1327
|
+
/** Where this package's browser module is, or nothing when it has not been
|
|
1328
|
+
* built. Computed in this entry, which sits one directory below the package
|
|
1329
|
+
* root in source and in the output alike. */
|
|
1330
|
+
function browserModule() {
|
|
1331
|
+
const path = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
1332
|
+
return existsSync(path) ? path : void 0;
|
|
1333
|
+
}
|
|
1334
|
+
const schedulePlugin = {
|
|
1335
|
+
name: "@eum-agent/automation-schedule",
|
|
1336
|
+
requires: ["query-resources", "triggers"],
|
|
1337
|
+
configSchema: ScheduleConfig,
|
|
1338
|
+
apply(ctx, config) {
|
|
1339
|
+
const disabled = new Set(config.disabled);
|
|
1340
|
+
const register = (tool) => disabled.has(tool.name) ? void 0 : ctx.tools.register(tool);
|
|
1341
|
+
const settings = openScheduleSettings(ctx);
|
|
1342
|
+
let current = settings.read();
|
|
1343
|
+
registerScheduleTools(ctx, register, () => current.agentLimit, registerScheduleSource(ctx).next);
|
|
1344
|
+
ctx.client.registerMethod({
|
|
1345
|
+
name: "getScheduleSettings",
|
|
1346
|
+
description: "The scheduled-task settings: tasks one agent may create per workspace (0 is no limit).",
|
|
1347
|
+
params: z.strictObject({}),
|
|
1348
|
+
result: ScheduleSettings,
|
|
1349
|
+
handle: () => current
|
|
1350
|
+
});
|
|
1351
|
+
ctx.client.registerMethod({
|
|
1352
|
+
name: "setScheduleSettings",
|
|
1353
|
+
description: "Replaces the scheduled-task settings; the next schedule_create call uses them.",
|
|
1354
|
+
params: ScheduleSettings,
|
|
1355
|
+
result: ScheduleSettings,
|
|
1356
|
+
handle(next) {
|
|
1357
|
+
current = settings.write(next);
|
|
1358
|
+
return current;
|
|
1359
|
+
}
|
|
1360
|
+
});
|
|
1361
|
+
ctx.tools.guide(GUIDANCE);
|
|
1362
|
+
const uiModule = browserModule();
|
|
1363
|
+
if (uiModule !== void 0) ctx.client.registerUi({ module: uiModule });
|
|
1364
|
+
}
|
|
1365
|
+
};
|
|
1366
|
+
//#endregion
|
|
1367
|
+
export { AGENT_LIMIT_CEILING, DEFAULT_SCHEDULE_SETTINGS, ScheduleConfig, ScheduleSettings, TOOL_NAMES, schedulePlugin as default, schedulePlugin, registerScheduleTools };
|