@eum-agent/automation-schedule 0.0.0-stage → 1.0.0

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.
Files changed (4) hide show
  1. package/dist/index.js +730 -0
  2. package/package.json +49 -3
  3. package/ui/ui.js +2654 -0
  4. package/README.md +0 -3
package/dist/index.js ADDED
@@ -0,0 +1,730 @@
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 } from "node:crypto";
6
+ //#region src/tool-names.ts
7
+ /** Canonical names shared by tool registration and browser presentation. */
8
+ const TOOL_NAMES = [
9
+ "schedule_create",
10
+ "schedule_list",
11
+ "schedule_update",
12
+ "schedule_delete"
13
+ ];
14
+ //#endregion
15
+ //#region src/guidance.ts
16
+ const GUIDANCE = {
17
+ title: "Scheduled tasks",
18
+ entries: [
19
+ {
20
+ tools: ["schedule_create"],
21
+ 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."
22
+ },
23
+ {
24
+ tools: ["schedule_list"],
25
+ text: "`schedule_list` shows your scheduled tasks."
26
+ },
27
+ {
28
+ tools: ["schedule_update"],
29
+ 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."
30
+ },
31
+ {
32
+ tools: ["schedule_delete"],
33
+ text: "`schedule_delete` removes a task you created once it is no longer needed."
34
+ }
35
+ ]
36
+ };
37
+ //#endregion
38
+ //#region src/source/rules.ts
39
+ /**
40
+ * Schedule rules: what one is, whether it is valid, and when it runs next.
41
+ *
42
+ * The one place a rule becomes a time. Cron expressions and time zones go
43
+ * through croner, because daylight-saving edges are where a hand-written
44
+ * reading goes wrong; the other two kinds are arithmetic.
45
+ *
46
+ * Every refusal starts `invalid rule:` and is written before anything is
47
+ * stored.
48
+ */
49
+ /** When a scheduled task runs: once, every N minutes from an anchor, or on a
50
+ * cron expression read in an IANA time zone. */
51
+ const ScheduleRule = z.discriminatedUnion("kind", [
52
+ z.object({
53
+ kind: z.literal("once"),
54
+ at: z.number().int()
55
+ }),
56
+ z.object({
57
+ kind: z.literal("interval"),
58
+ everyMinutes: z.number().int().min(5),
59
+ anchor: z.number().int()
60
+ }),
61
+ z.object({
62
+ kind: z.literal("cron"),
63
+ expression: z.string().min(1).max(200),
64
+ timezone: z.string().min(1).max(100)
65
+ })
66
+ ]);
67
+ const MINUTE = 6e4;
68
+ /** How far ahead a cron expression's spacing is checked. */
69
+ const SPACING_SAMPLE = 100;
70
+ function invalid(reason) {
71
+ return /* @__PURE__ */ new Error(`invalid rule: ${reason}`);
72
+ }
73
+ function cronOf(rule) {
74
+ try {
75
+ new Intl.DateTimeFormat("en-US", { timeZone: rule.timezone });
76
+ } catch {
77
+ throw invalid(`unknown time zone ${rule.timezone}`);
78
+ }
79
+ try {
80
+ return new Cron(rule.expression, {
81
+ timezone: rule.timezone,
82
+ paused: true
83
+ });
84
+ } catch (error) {
85
+ throw invalid(error instanceof Error ? error.message : String(error));
86
+ }
87
+ }
88
+ /** The first time strictly after `after` the rule runs, or `null` for none. */
89
+ function nextRun(rule, after) {
90
+ switch (rule.kind) {
91
+ case "once": return rule.at > after ? rule.at : null;
92
+ case "interval": {
93
+ const every = rule.everyMinutes * MINUTE;
94
+ if (rule.anchor > after) return rule.anchor;
95
+ const steps = Math.floor((after - rule.anchor) / every) + 1;
96
+ return rule.anchor + steps * every;
97
+ }
98
+ case "cron": {
99
+ const next = cronOf(rule).nextRun(new Date(after));
100
+ return next === null ? null : next.getTime();
101
+ }
102
+ }
103
+ }
104
+ /** Throws `invalid rule: …` for a rule that cannot be stored now. */
105
+ function validateRule(rule, now) {
106
+ switch (rule.kind) {
107
+ case "once":
108
+ if (rule.at <= now) throw invalid("the time has passed");
109
+ return;
110
+ case "interval":
111
+ if (rule.everyMinutes * MINUTE < 3e5) throw invalid("runs less than 5 minutes apart");
112
+ return;
113
+ case "cron": {
114
+ const runs = cronOf(rule).nextRuns(SPACING_SAMPLE, new Date(now));
115
+ if (runs.length === 0) throw invalid("the expression never runs");
116
+ 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");
117
+ }
118
+ }
119
+ }
120
+ /** The next `count` times, after validating the rule. */
121
+ function previewRule(rule, now, count = 3) {
122
+ validateRule(rule, now);
123
+ const out = [];
124
+ let after = now;
125
+ for (let i = 0; i < count; i += 1) {
126
+ const next = nextRun(rule, after);
127
+ if (next === null) break;
128
+ out.push(next);
129
+ after = next;
130
+ }
131
+ return out;
132
+ }
133
+ //#endregion
134
+ //#region src/source/config.ts
135
+ /**
136
+ * A scheduled task's `config`: its rule, and whether a time missed while the
137
+ * gateway or this plugin was away is made up once. The core stores this as
138
+ * the source hands it back from `configSchema` and reads none of it; the
139
+ * rule's own checks (the 5-minute floor, a time already past, an unknown
140
+ * zone, an unreadable cron) run here, so a refusal reads `invalid rule: …`
141
+ * wherever the definition was written from.
142
+ */
143
+ const ScheduleConfig$1 = z.object({
144
+ rule: ScheduleRule,
145
+ catchUp: z.boolean().default(true)
146
+ }).superRefine((config, check) => {
147
+ try {
148
+ validateRule(config.rule, Date.now());
149
+ } catch (error) {
150
+ check.addIssue({
151
+ code: "custom",
152
+ message: error instanceof Error ? error.message : String(error)
153
+ });
154
+ }
155
+ });
156
+ /** The config as stored, read back without judging the rule against now: a
157
+ * one-off that has run is still a valid record of when it ran. */
158
+ const StoredScheduleConfig = z.object({
159
+ rule: ScheduleRule,
160
+ catchUp: z.boolean().default(true)
161
+ });
162
+ function storedConfig(raw) {
163
+ const parsed = StoredScheduleConfig.safeParse(raw);
164
+ return parsed.success ? parsed.data : void 0;
165
+ }
166
+ //#endregion
167
+ //#region src/source/loop.ts
168
+ /**
169
+ * The schedule loop: one timer, set for the earliest due task or thirty
170
+ * seconds from now, whichever comes first. Each wake reconciles the
171
+ * next-run table against the source's enabled definitions, then judges every
172
+ * due task by how late it is — on time within a minute, otherwise missed (the
173
+ * gateway or this plugin was away, or the machine slept) and run once as a
174
+ * catch-up or skipped — and sets its next time from now, so however many
175
+ * times were missed, at most one run makes up for them.
176
+ *
177
+ * Reconciling decides where a next time comes from: a definition this table
178
+ * has not seen, one whose config changed, and one that was switched off when
179
+ * last seen are counted from now (no catch-up for a task someone just
180
+ * switched on); one that stayed enabled keeps its stored time, which is how a
181
+ * time missed while this plugin was off is noticed when it comes back.
182
+ */
183
+ /** Later than this and a run counts as missed. */
184
+ const ON_TIME_MS = 6e4;
185
+ /** The loop never sleeps longer than this, so a late timer after sleep is
186
+ * noticed within half a minute. */
187
+ const MAX_SLEEP_MS = 3e4;
188
+ function hashOf(config) {
189
+ return createHash("sha256").update(JSON.stringify(config ?? null)).digest("hex");
190
+ }
191
+ function createScheduleLoop(deps) {
192
+ const now = deps.now ?? (() => Date.now());
193
+ const setTimer = deps.setTimer ?? ((fn, ms) => {
194
+ const handle = setTimeout(fn, ms);
195
+ handle.unref?.();
196
+ return { cancel: () => clearTimeout(handle) };
197
+ });
198
+ let timer;
199
+ let running = false;
200
+ let ticking = Promise.resolve();
201
+ function reconcile(definitions) {
202
+ let touched = false;
203
+ const at = now();
204
+ const enabled = /* @__PURE__ */ new Set();
205
+ for (const definition of definitions) {
206
+ enabled.add(definition.id);
207
+ const config = storedConfig(definition.config);
208
+ if (config === void 0) continue;
209
+ const hash = hashOf(definition.config);
210
+ const row = deps.store.get(definition.id);
211
+ if (row !== void 0 && row.configHash === hash && row.seenEnabled) continue;
212
+ deps.store.put({
213
+ definitionId: definition.id,
214
+ nextAt: nextRun(config.rule, at),
215
+ configHash: hash,
216
+ seenEnabled: true
217
+ });
218
+ touched = true;
219
+ }
220
+ for (const row of deps.store.all()) if (!enabled.has(row.definitionId) && row.seenEnabled) {
221
+ deps.store.put({
222
+ ...row,
223
+ seenEnabled: false
224
+ });
225
+ touched = true;
226
+ }
227
+ return touched;
228
+ }
229
+ async function wake() {
230
+ const definitions = deps.host.definitions();
231
+ let touched = reconcile(definitions);
232
+ const at = now();
233
+ const byId = new Map(definitions.map((one) => [one.id, one]));
234
+ for (const row of deps.store.all()) {
235
+ if (!row.seenEnabled || row.nextAt === null || row.nextAt > at) continue;
236
+ const definition = byId.get(row.definitionId);
237
+ const config = definition === void 0 ? void 0 : storedConfig(definition.config);
238
+ if (config === void 0) continue;
239
+ const scheduledAt = row.nextAt;
240
+ const late = at - scheduledAt > ON_TIME_MS;
241
+ deps.store.setNext(row.definitionId, nextRun(config.rule, at));
242
+ touched = true;
243
+ try {
244
+ if (late && !config.catchUp) {
245
+ deps.host.skip(row.definitionId, {
246
+ kind: "catch-up",
247
+ scheduledAt,
248
+ reason: "missed"
249
+ });
250
+ continue;
251
+ }
252
+ await deps.host.fire(row.definitionId, {
253
+ kind: late ? "catch-up" : "scheduled",
254
+ scheduledAt
255
+ });
256
+ } catch (error) {
257
+ deps.log?.(`scheduled task ${row.definitionId} did not run: ${error instanceof Error ? error.message : String(error)}`);
258
+ }
259
+ }
260
+ if (touched) deps.changed?.();
261
+ }
262
+ function arm() {
263
+ timer?.cancel();
264
+ if (!running) return;
265
+ let earliest = null;
266
+ for (const row of deps.store.all()) {
267
+ if (!row.seenEnabled || row.nextAt === null) continue;
268
+ if (earliest === null || row.nextAt < earliest) earliest = row.nextAt;
269
+ }
270
+ const wait = earliest === null ? MAX_SLEEP_MS : Math.max(0, Math.min(earliest - now(), MAX_SLEEP_MS));
271
+ timer = setTimer(() => {
272
+ loop.tick();
273
+ }, wait);
274
+ }
275
+ const loop = {
276
+ tick() {
277
+ ticking = ticking.then(wake).catch((error) => deps.log?.(`schedule loop failed: ${String(error)}`)).finally(arm);
278
+ return ticking;
279
+ },
280
+ start() {
281
+ running = true;
282
+ loop.tick();
283
+ },
284
+ stop() {
285
+ running = false;
286
+ timer?.cancel();
287
+ timer = void 0;
288
+ },
289
+ next() {
290
+ const out = {};
291
+ for (const row of deps.store.all()) if (row.seenEnabled) out[row.definitionId] = row.nextAt;
292
+ return out;
293
+ }
294
+ };
295
+ return loop;
296
+ }
297
+ //#endregion
298
+ //#region src/source/next-runs.ts
299
+ function toRow(raw) {
300
+ return {
301
+ definitionId: raw.definition_id,
302
+ nextAt: raw.next_at,
303
+ configHash: raw.config_hash,
304
+ seenEnabled: raw.seen_enabled === 1
305
+ };
306
+ }
307
+ function openNextRuns(ctx) {
308
+ const storage = ctx.storage.open();
309
+ const table = storage.tableName("next_run");
310
+ storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (
311
+ definition_id TEXT NOT NULL PRIMARY KEY,
312
+ next_at INTEGER,
313
+ config_hash TEXT NOT NULL,
314
+ seen_enabled INTEGER NOT NULL CHECK (seen_enabled IN (0, 1))
315
+ ) STRICT`);
316
+ const selectOne = storage.db.prepare(`SELECT * FROM ${table} WHERE definition_id = ?`);
317
+ const selectAll = storage.db.prepare(`SELECT * FROM ${table} ORDER BY definition_id`);
318
+ const upsert = storage.db.prepare(`INSERT INTO ${table} (definition_id, next_at, config_hash, seen_enabled) VALUES (?, ?, ?, ?)
319
+ ON CONFLICT (definition_id) DO UPDATE SET next_at = excluded.next_at,
320
+ config_hash = excluded.config_hash, seen_enabled = excluded.seen_enabled`);
321
+ const updateNext = storage.db.prepare(`UPDATE ${table} SET next_at = ? WHERE definition_id = ?`);
322
+ return {
323
+ get(definitionId) {
324
+ const raw = selectOne.get(definitionId);
325
+ return raw === void 0 ? void 0 : toRow(raw);
326
+ },
327
+ all: () => selectAll.all().map(toRow),
328
+ put(row) {
329
+ upsert.run(row.definitionId, row.nextAt, row.configHash, row.seenEnabled ? 1 : 0);
330
+ },
331
+ setNext(definitionId, nextAt) {
332
+ updateNext.run(nextAt, definitionId);
333
+ }
334
+ };
335
+ }
336
+ /** An in-memory table, for a runtime without a database and for tests. */
337
+ function memoryNextRuns() {
338
+ const rows = /* @__PURE__ */ new Map();
339
+ return {
340
+ get: (id) => rows.get(id),
341
+ all: () => [...rows.values()].sort((a, b) => a.definitionId.localeCompare(b.definitionId)),
342
+ put: (row) => {
343
+ rows.set(row.definitionId, row);
344
+ },
345
+ setNext: (id, nextAt) => {
346
+ const row = rows.get(id);
347
+ if (row !== void 0) rows.set(id, {
348
+ ...row,
349
+ nextAt
350
+ });
351
+ }
352
+ };
353
+ }
354
+ //#endregion
355
+ //#region src/source/index.ts
356
+ const SOURCE_KIND = "schedule";
357
+ const SOURCE_LABEL = "计划任务";
358
+ const NextRunsPayload = z.object({ next: z.record(z.string(), z.number().nullable()) });
359
+ function registerScheduleSource(ctx) {
360
+ let store;
361
+ try {
362
+ store = openNextRuns(ctx);
363
+ } catch {
364
+ store = memoryNextRuns();
365
+ }
366
+ let loop;
367
+ const frame = ctx.client.registerFrame({
368
+ name: "nextRunsChanged",
369
+ delivery: "broadcast",
370
+ payload: NextRunsPayload
371
+ });
372
+ const announce = () => frame.emit({ next: { ...loop?.next() ?? {} } });
373
+ ctx.triggers.registerSource({
374
+ kind: SOURCE_KIND,
375
+ label: SOURCE_LABEL,
376
+ configSchema: ScheduleConfig$1,
377
+ start(host) {
378
+ loop = createScheduleLoop({
379
+ host,
380
+ store,
381
+ changed: announce,
382
+ log: (message) => ctx.log.warn(message)
383
+ });
384
+ const off = host.onChanged(() => void loop?.tick());
385
+ loop.start();
386
+ return () => {
387
+ off();
388
+ loop?.stop();
389
+ loop = void 0;
390
+ };
391
+ }
392
+ });
393
+ ctx.client.registerMethod({
394
+ name: "preview",
395
+ description: "The next three times a rule would run; an invalid rule is refused.",
396
+ params: z.strictObject({ rule: ScheduleRule }),
397
+ result: z.object({ times: z.array(z.number()) }),
398
+ handle: ({ rule }) => ({ times: previewRule(rule, Date.now()) })
399
+ });
400
+ ctx.client.registerMethod({
401
+ name: "nextRuns",
402
+ description: "When each enabled scheduled task runs next, by definition id; null for never.",
403
+ params: z.strictObject({}),
404
+ result: NextRunsPayload,
405
+ handle: () => ({ next: { ...loop?.next() ?? {} } })
406
+ });
407
+ return { next: () => loop?.next() ?? {} };
408
+ }
409
+ //#endregion
410
+ //#region src/schedule/settings.ts
411
+ /** The most tasks a limit may name short of no limit. */
412
+ const AGENT_LIMIT_CEILING = 1e3;
413
+ /** The settings on the wire and on disk. `agentLimit` `0` is no limit. */
414
+ const ScheduleSettings = z.strictObject({ agentLimit: z.number().int().min(0).max(AGENT_LIMIT_CEILING) });
415
+ const DEFAULT_SCHEDULE_SETTINGS = { agentLimit: 20 };
416
+ const LOCAL_TABLE = "settings";
417
+ const KEY = "schedule";
418
+ function openScheduleSettings(ctx) {
419
+ const storage = ctx.storage.open();
420
+ const table = storage.tableName(LOCAL_TABLE);
421
+ storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (
422
+ key TEXT NOT NULL,
423
+ value TEXT NOT NULL,
424
+ updated_at INTEGER NOT NULL,
425
+ PRIMARY KEY (key)
426
+ ) STRICT`);
427
+ return {
428
+ read() {
429
+ const row = storage.db.prepare(`SELECT value FROM ${table} WHERE key = ?`).get(KEY);
430
+ if (row === void 0) return DEFAULT_SCHEDULE_SETTINGS;
431
+ const parsed = parse(row.value);
432
+ if (parsed !== void 0) return parsed;
433
+ ctx.log.error("scheduled-task settings could not be read; using the defaults");
434
+ return DEFAULT_SCHEDULE_SETTINGS;
435
+ },
436
+ write(settings) {
437
+ storage.db.prepare(`INSERT INTO ${table} (key, value, updated_at) VALUES (?, ?, ?)
438
+ ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at`).run(KEY, JSON.stringify(settings), Date.now());
439
+ return settings;
440
+ }
441
+ };
442
+ }
443
+ function parse(raw) {
444
+ if (typeof raw !== "string") return void 0;
445
+ try {
446
+ const read = ScheduleSettings.safeParse(JSON.parse(raw));
447
+ return read.success ? read.data : void 0;
448
+ } catch {
449
+ return;
450
+ }
451
+ }
452
+ //#endregion
453
+ //#region src/schedule/index.ts
454
+ const TRIGGERS_SERVICE = "triggers";
455
+ const OnceRule = z.object({
456
+ kind: z.literal("once"),
457
+ at: z.string().describe("Required for once: ISO 8601 date-time with offset, e.g. 2026-09-27T09:00:00+08:00")
458
+ });
459
+ const IntervalRule = z.object({
460
+ kind: z.literal("interval"),
461
+ everyMinutes: z.number().int().min(5).describe("Required for interval: minutes between runs, at least 5")
462
+ });
463
+ const CronRule = z.object({
464
+ kind: z.literal("cron"),
465
+ expression: z.string().min(1).describe("Required for cron: five fields, e.g. 0 9 * * 1-5"),
466
+ timezone: z.string().min(1).describe("Required for cron: IANA time zone, e.g. Asia/Singapore")
467
+ });
468
+ const Rule = z.object({
469
+ kind: z.enum([
470
+ "once",
471
+ "interval",
472
+ "cron"
473
+ ]),
474
+ at: OnceRule.shape.at.optional(),
475
+ everyMinutes: IntervalRule.shape.everyMinutes.optional(),
476
+ expression: CronRule.shape.expression.optional(),
477
+ timezone: CronRule.shape.timezone.optional()
478
+ }, { error: "rule must be a JSON object, for example {\"kind\":\"interval\",\"everyMinutes\":15}" }).meta({
479
+ description: "Schedule rule object. Use kind once with at; interval with everyMinutes; or cron with expression and timezone.",
480
+ examples: [{
481
+ kind: "interval",
482
+ everyMinutes: 15
483
+ }, {
484
+ kind: "cron",
485
+ expression: "0 9 * * *",
486
+ timezone: "Asia/Singapore"
487
+ }]
488
+ }).pipe(z.discriminatedUnion("kind", [
489
+ OnceRule,
490
+ IntervalRule,
491
+ CronRule
492
+ ]));
493
+ const Scope = z.array(z.object({
494
+ kind: z.enum([
495
+ "read",
496
+ "write",
497
+ "network",
498
+ "web-host"
499
+ ]),
500
+ target: z.string().min(1).describe("absolute path, * for network, or a host")
501
+ })).max(100);
502
+ const CreateInput = z.object({
503
+ name: z.string().trim().min(1).max(80),
504
+ rule: Rule,
505
+ instruction: z.string().trim().min(1).max(8e3),
506
+ target: z.enum(["this-session", "new-session"]).default("this-session"),
507
+ catchUp: z.boolean().optional(),
508
+ scope: Scope.optional()
509
+ });
510
+ const UpdateInput = z.object({
511
+ id: z.string().min(1),
512
+ name: z.string().trim().min(1).max(80).optional(),
513
+ rule: Rule.optional(),
514
+ instruction: z.string().trim().min(1).max(8e3).optional(),
515
+ target: z.enum(["this-session", "new-session"]).optional(),
516
+ catchUp: z.boolean().optional(),
517
+ scope: Scope.optional()
518
+ });
519
+ const DeleteInput = z.object({ id: z.string().min(1) });
520
+ function toRule(rule, now) {
521
+ switch (rule.kind) {
522
+ case "once": {
523
+ const at = Date.parse(rule.at);
524
+ if (Number.isNaN(at)) throw new Error(`invalid rule: ${rule.at} is not a date-time`);
525
+ return {
526
+ kind: "once",
527
+ at
528
+ };
529
+ }
530
+ case "interval": return {
531
+ kind: "interval",
532
+ everyMinutes: rule.everyMinutes,
533
+ anchor: now
534
+ };
535
+ case "cron": return rule;
536
+ }
537
+ }
538
+ /** One line a person reads in the approval: when this runs. */
539
+ function describeRule(rule) {
540
+ switch (rule.kind) {
541
+ case "once": return `once at ${new Date(rule.at).toISOString()}`;
542
+ case "interval": return `every ${rule.everyMinutes} minutes`;
543
+ case "cron": return `cron ${rule.expression} (${rule.timezone})`;
544
+ }
545
+ }
546
+ function view(trigger, next) {
547
+ const config = storedConfig(trigger.config);
548
+ const nextAt = next()[trigger.id] ?? null;
549
+ return {
550
+ id: trigger.id,
551
+ name: trigger.name,
552
+ rule: config?.rule ?? null,
553
+ catchUp: config?.catchUp ?? true,
554
+ instruction: trigger.instruction,
555
+ target: trigger.target,
556
+ enabled: trigger.enabled,
557
+ nextRunAt: nextAt === null ? null : new Date(nextAt).toISOString(),
558
+ scope: trigger.scope,
559
+ createdBy: trigger.createdBy.kind,
560
+ lastRun: trigger.lastRun === null ? null : {
561
+ state: trigger.lastRun.state,
562
+ reason: trigger.lastRun.reason
563
+ }
564
+ };
565
+ }
566
+ function answer(outcome, next) {
567
+ switch (outcome.kind) {
568
+ case "ask": return outcome.result;
569
+ case "refused": return {
570
+ content: outcome.message,
571
+ isError: true
572
+ };
573
+ case "removed": return { content: "the scheduled task was deleted" };
574
+ case "done": return { content: JSON.stringify(view(outcome.trigger, next)) };
575
+ }
576
+ }
577
+ function failure(error) {
578
+ return {
579
+ content: error instanceof Error ? error.message : String(error),
580
+ isError: true
581
+ };
582
+ }
583
+ function createScheduleTool(triggers, agentLimit, next = () => ({})) {
584
+ return {
585
+ name: "schedule_create",
586
+ 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.",
587
+ inputSchema: CreateInput,
588
+ async execute(input, ctx) {
589
+ try {
590
+ const limit = agentLimit();
591
+ if (limit > 0) {
592
+ if (triggers.list(ctx).filter((task) => task.createdBy.kind === "agent" && task.createdBy.agentId === ctx.address.agentId).length >= limit) return failure(/* @__PURE__ */ new Error(`this agent already has ${limit} scheduled tasks in this workspace; delete one first`));
593
+ }
594
+ const rule = toRule(input.rule, Date.now());
595
+ return answer(triggers.create(ctx, {
596
+ kind: SOURCE_KIND,
597
+ name: input.name,
598
+ config: {
599
+ rule,
600
+ catchUp: input.catchUp ?? true
601
+ },
602
+ summary: describeRule(rule),
603
+ instruction: input.instruction,
604
+ target: input.target,
605
+ ...input.scope === void 0 ? {} : { scope: input.scope }
606
+ }), next);
607
+ } catch (error) {
608
+ return failure(error);
609
+ }
610
+ }
611
+ };
612
+ }
613
+ function listSchedulesTool(triggers, next = () => ({})) {
614
+ return {
615
+ name: "schedule_list",
616
+ description: "List the scheduled tasks of this agent in this workspace, including ones the user made (read-only for you).",
617
+ inputSchema: z.object({}),
618
+ async execute(_input, ctx) {
619
+ return { content: JSON.stringify(triggers.list(ctx).map((one) => view(one, next))) };
620
+ }
621
+ };
622
+ }
623
+ function updateScheduleTool(triggers, next = () => ({})) {
624
+ return {
625
+ name: "schedule_update",
626
+ description: "Change a scheduled task you created. Changing what it does, when, where, or widening its scope may ask the user.",
627
+ inputSchema: UpdateInput,
628
+ async execute(input, ctx) {
629
+ try {
630
+ const { id, rule, catchUp, ...rest } = input;
631
+ const patch = Object.fromEntries(Object.entries(rest).filter(([, value]) => value !== void 0));
632
+ const current = storedConfig(triggers.list(ctx).find((one) => one.id === id)?.config);
633
+ const config = current === void 0 || !(rule !== void 0 || catchUp !== void 0) ? void 0 : {
634
+ rule: rule === void 0 ? current.rule : toRule(rule, Date.now()),
635
+ catchUp: catchUp ?? current.catchUp
636
+ };
637
+ return answer(triggers.update(ctx, id, {
638
+ ...patch,
639
+ ...config === void 0 ? {} : { config },
640
+ ...current === void 0 ? {} : { summary: describeRule((config ?? current).rule) }
641
+ }), next);
642
+ } catch (error) {
643
+ return failure(error);
644
+ }
645
+ }
646
+ };
647
+ }
648
+ function deleteScheduleTool(triggers) {
649
+ return {
650
+ name: "schedule_delete",
651
+ description: "Delete a scheduled task you created. Sessions it already opened stay.",
652
+ inputSchema: DeleteInput,
653
+ async execute(input, ctx) {
654
+ return answer(triggers.remove(ctx, input.id), () => ({}));
655
+ }
656
+ };
657
+ }
658
+ function registerScheduleTools(ctx, register, agentLimit = () => DEFAULT_SCHEDULE_SETTINGS.agentLimit, next = () => ({})) {
659
+ const triggers = ctx.services.get(TRIGGERS_SERVICE);
660
+ register(createScheduleTool(triggers, agentLimit, next));
661
+ register(listSchedulesTool(triggers, next));
662
+ register(updateScheduleTool(triggers, next));
663
+ register(deleteScheduleTool(triggers));
664
+ }
665
+ //#endregion
666
+ //#region src/index.ts
667
+ /**
668
+ * `@eum-agent/automation-schedule` — creating, listing, changing and deleting scheduled
669
+ * tasks over the host's `triggers` service, as one plugin.
670
+ *
671
+ * Members live under `src/`: `schedule/` (the four `schedule_*` tools and the
672
+ * settings `schedule_create` reads), plus `ui.tsx`, the browser module holding
673
+ * the settings category. None of them is a plugin; this file is the only one, and it is what a person's
674
+ * `config.json` names, what `plugin list` prints, and what the loader imports.
675
+ *
676
+ * `@eum-agent/plugin` is the only workspace package any file here imports, and
677
+ * only its types: everything reached at runtime arrived through `ctx`.
678
+ */
679
+ /**
680
+ * This plugin's slice of `config.json`.
681
+ *
682
+ * `disabled` turns one tool off while the rest of the package stays on —
683
+ * `enabled: false` on the declaration turns off every one of them. Strict and
684
+ * enumerated: a misspelled tool name is a load failure naming the field, not
685
+ * a line that quietly does nothing. The scheduled-task settings are not here:
686
+ * they are kept by the plugin itself (`schedule/settings.ts`), so changing
687
+ * them reloads nothing.
688
+ */
689
+ const ScheduleConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
690
+ /** Where this package's browser module is, or nothing when it has not been
691
+ * built. Computed in this entry, which sits one directory below the package
692
+ * root in source and in the output alike. */
693
+ function browserModule() {
694
+ const path = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
695
+ return existsSync(path) ? path : void 0;
696
+ }
697
+ const schedulePlugin = {
698
+ name: "@eum-agent/automation-schedule",
699
+ requires: ["triggers"],
700
+ configSchema: ScheduleConfig,
701
+ apply(ctx, config) {
702
+ const disabled = new Set(config.disabled);
703
+ const register = (tool) => disabled.has(tool.name) ? void 0 : ctx.tools.register(tool);
704
+ const settings = openScheduleSettings(ctx);
705
+ let current = settings.read();
706
+ registerScheduleTools(ctx, register, () => current.agentLimit, registerScheduleSource(ctx).next);
707
+ ctx.client.registerMethod({
708
+ name: "getScheduleSettings",
709
+ description: "The scheduled-task settings: tasks one agent may create per workspace (0 is no limit).",
710
+ params: z.strictObject({}),
711
+ result: ScheduleSettings,
712
+ handle: () => current
713
+ });
714
+ ctx.client.registerMethod({
715
+ name: "setScheduleSettings",
716
+ description: "Replaces the scheduled-task settings; the next schedule_create call uses them.",
717
+ params: ScheduleSettings,
718
+ result: ScheduleSettings,
719
+ handle(next) {
720
+ current = settings.write(next);
721
+ return current;
722
+ }
723
+ });
724
+ ctx.tools.guide(GUIDANCE);
725
+ const uiModule = browserModule();
726
+ if (uiModule !== void 0) ctx.client.registerUi({ module: uiModule });
727
+ }
728
+ };
729
+ //#endregion
730
+ export { AGENT_LIMIT_CEILING, DEFAULT_SCHEDULE_SETTINGS, ScheduleConfig, ScheduleSettings, TOOL_NAMES, schedulePlugin as default, schedulePlugin, registerScheduleTools };