@eum-agent/automation-schedule 1.0.0 → 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 +712 -75
- package/package.json +4 -4
- package/ui/ui.js +212 -150
package/dist/index.js
CHANGED
|
@@ -2,16 +2,7 @@ import { existsSync } from "node:fs";
|
|
|
2
2
|
import { fileURLToPath } from "node:url";
|
|
3
3
|
import { z } from "zod";
|
|
4
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
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
15
6
|
//#region src/guidance.ts
|
|
16
7
|
const GUIDANCE = {
|
|
17
8
|
title: "Scheduled tasks",
|
|
@@ -22,7 +13,11 @@ const GUIDANCE = {
|
|
|
22
13
|
},
|
|
23
14
|
{
|
|
24
15
|
tools: ["schedule_list"],
|
|
25
|
-
text: "`schedule_list` shows
|
|
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."
|
|
26
21
|
},
|
|
27
22
|
{
|
|
28
23
|
tools: ["schedule_update"],
|
|
@@ -30,11 +25,40 @@ const GUIDANCE = {
|
|
|
30
25
|
},
|
|
31
26
|
{
|
|
32
27
|
tools: ["schedule_delete"],
|
|
33
|
-
text: "`schedule_delete` removes
|
|
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."
|
|
34
29
|
}
|
|
35
30
|
]
|
|
36
31
|
};
|
|
37
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
|
|
38
62
|
//#region src/source/rules.ts
|
|
39
63
|
/**
|
|
40
64
|
* Schedule rules: what one is, whether it is valid, and when it runs next.
|
|
@@ -188,6 +212,7 @@ const MAX_SLEEP_MS = 3e4;
|
|
|
188
212
|
function hashOf(config) {
|
|
189
213
|
return createHash("sha256").update(JSON.stringify(config ?? null)).digest("hex");
|
|
190
214
|
}
|
|
215
|
+
/** Creates one schedule loop; explicit ticks also work before its timer starts. */
|
|
191
216
|
function createScheduleLoop(deps) {
|
|
192
217
|
const now = deps.now ?? (() => Date.now());
|
|
193
218
|
const setTimer = deps.setTimer ?? ((fn, ms) => {
|
|
@@ -197,6 +222,8 @@ function createScheduleLoop(deps) {
|
|
|
197
222
|
});
|
|
198
223
|
let timer;
|
|
199
224
|
let running = false;
|
|
225
|
+
let stopped = false;
|
|
226
|
+
let generation = 0;
|
|
200
227
|
let ticking = Promise.resolve();
|
|
201
228
|
function reconcile(definitions) {
|
|
202
229
|
let touched = false;
|
|
@@ -226,7 +253,7 @@ function createScheduleLoop(deps) {
|
|
|
226
253
|
}
|
|
227
254
|
return touched;
|
|
228
255
|
}
|
|
229
|
-
async function wake() {
|
|
256
|
+
async function wake(admittedGeneration) {
|
|
230
257
|
const definitions = deps.host.definitions();
|
|
231
258
|
let touched = reconcile(definitions);
|
|
232
259
|
const at = now();
|
|
@@ -256,6 +283,7 @@ function createScheduleLoop(deps) {
|
|
|
256
283
|
} catch (error) {
|
|
257
284
|
deps.log?.(`scheduled task ${row.definitionId} did not run: ${error instanceof Error ? error.message : String(error)}`);
|
|
258
285
|
}
|
|
286
|
+
if (stopped || admittedGeneration !== generation) return;
|
|
259
287
|
}
|
|
260
288
|
if (touched) deps.changed?.();
|
|
261
289
|
}
|
|
@@ -274,17 +302,26 @@ function createScheduleLoop(deps) {
|
|
|
274
302
|
}
|
|
275
303
|
const loop = {
|
|
276
304
|
tick() {
|
|
277
|
-
|
|
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
|
+
});
|
|
278
311
|
return ticking;
|
|
279
312
|
},
|
|
280
313
|
start() {
|
|
314
|
+
stopped = false;
|
|
281
315
|
running = true;
|
|
282
316
|
loop.tick();
|
|
283
317
|
},
|
|
284
318
|
stop() {
|
|
319
|
+
generation++;
|
|
320
|
+
stopped = true;
|
|
285
321
|
running = false;
|
|
286
322
|
timer?.cancel();
|
|
287
323
|
timer = void 0;
|
|
324
|
+
return ticking;
|
|
288
325
|
},
|
|
289
326
|
next() {
|
|
290
327
|
const out = {};
|
|
@@ -356,6 +393,7 @@ function memoryNextRuns() {
|
|
|
356
393
|
const SOURCE_KIND = "schedule";
|
|
357
394
|
const SOURCE_LABEL = "计划任务";
|
|
358
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. */
|
|
359
397
|
function registerScheduleSource(ctx) {
|
|
360
398
|
let store;
|
|
361
399
|
try {
|
|
@@ -379,14 +417,19 @@ function registerScheduleSource(ctx) {
|
|
|
379
417
|
host,
|
|
380
418
|
store,
|
|
381
419
|
changed: announce,
|
|
382
|
-
log: (message) => ctx.log.
|
|
420
|
+
log: (message) => ctx.log.emit({
|
|
421
|
+
level: "warn",
|
|
422
|
+
event: "plugin.event",
|
|
423
|
+
fields: { localCode: "MESSAGE" }
|
|
424
|
+
})
|
|
383
425
|
});
|
|
384
426
|
const off = host.onChanged(() => void loop?.tick());
|
|
385
427
|
loop.start();
|
|
386
428
|
return () => {
|
|
387
429
|
off();
|
|
388
|
-
loop
|
|
430
|
+
const current = loop;
|
|
389
431
|
loop = void 0;
|
|
432
|
+
return current?.stop();
|
|
390
433
|
};
|
|
391
434
|
}
|
|
392
435
|
});
|
|
@@ -407,6 +450,578 @@ function registerScheduleSource(ctx) {
|
|
|
407
450
|
return { next: () => loop?.next() ?? {} };
|
|
408
451
|
}
|
|
409
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
|
|
410
1025
|
//#region src/schedule/settings.ts
|
|
411
1026
|
/** The most tasks a limit may name short of no limit. */
|
|
412
1027
|
const AGENT_LIMIT_CEILING = 1e3;
|
|
@@ -430,7 +1045,11 @@ function openScheduleSettings(ctx) {
|
|
|
430
1045
|
if (row === void 0) return DEFAULT_SCHEDULE_SETTINGS;
|
|
431
1046
|
const parsed = parse(row.value);
|
|
432
1047
|
if (parsed !== void 0) return parsed;
|
|
433
|
-
ctx.log.
|
|
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
|
+
});
|
|
434
1053
|
return DEFAULT_SCHEDULE_SETTINGS;
|
|
435
1054
|
},
|
|
436
1055
|
write(settings) {
|
|
@@ -451,17 +1070,25 @@ function parse(raw) {
|
|
|
451
1070
|
}
|
|
452
1071
|
//#endregion
|
|
453
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
|
+
});
|
|
454
1081
|
const TRIGGERS_SERVICE = "triggers";
|
|
455
1082
|
const OnceRule = z.object({
|
|
456
|
-
kind: z.literal("once"),
|
|
1083
|
+
kind: z.literal("once").describe("Run once at the supplied at timestamp."),
|
|
457
1084
|
at: z.string().describe("Required for once: ISO 8601 date-time with offset, e.g. 2026-09-27T09:00:00+08:00")
|
|
458
1085
|
});
|
|
459
1086
|
const IntervalRule = z.object({
|
|
460
|
-
kind: z.literal("interval"),
|
|
1087
|
+
kind: z.literal("interval").describe("Repeat at everyMinutes, minimum five minutes."),
|
|
461
1088
|
everyMinutes: z.number().int().min(5).describe("Required for interval: minutes between runs, at least 5")
|
|
462
1089
|
});
|
|
463
1090
|
const CronRule = z.object({
|
|
464
|
-
kind: z.literal("cron"),
|
|
1091
|
+
kind: z.literal("cron").describe("Repeat using a five-field expression in the supplied timezone."),
|
|
465
1092
|
expression: z.string().min(1).describe("Required for cron: five fields, e.g. 0 9 * * 1-5"),
|
|
466
1093
|
timezone: z.string().min(1).describe("Required for cron: IANA time zone, e.g. Asia/Singapore")
|
|
467
1094
|
});
|
|
@@ -470,7 +1097,7 @@ const Rule = z.object({
|
|
|
470
1097
|
"once",
|
|
471
1098
|
"interval",
|
|
472
1099
|
"cron"
|
|
473
|
-
]),
|
|
1100
|
+
]).describe("Select once with at, interval with everyMinutes, or cron with expression and timezone."),
|
|
474
1101
|
at: OnceRule.shape.at.optional(),
|
|
475
1102
|
everyMinutes: IntervalRule.shape.everyMinutes.optional(),
|
|
476
1103
|
expression: CronRule.shape.expression.optional(),
|
|
@@ -496,27 +1123,30 @@ const Scope = z.array(z.object({
|
|
|
496
1123
|
"write",
|
|
497
1124
|
"network",
|
|
498
1125
|
"web-host"
|
|
499
|
-
]),
|
|
1126
|
+
]).describe("Permission kind requested for the scheduled run; scope never bypasses approval."),
|
|
500
1127
|
target: z.string().min(1).describe("absolute path, * for network, or a host")
|
|
501
|
-
})).max(100);
|
|
1128
|
+
})).max(100).describe("Requested run permissions, at most 100 entries; changes require approval.");
|
|
502
1129
|
const CreateInput = z.object({
|
|
503
|
-
name: z.string().trim().min(1).max(80),
|
|
1130
|
+
name: z.string().trim().min(1).max(80).describe("Task display name, 1–80 UTF-16 code units after trimming."),
|
|
504
1131
|
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(),
|
|
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."),
|
|
508
1135
|
scope: Scope.optional()
|
|
509
1136
|
});
|
|
510
1137
|
const UpdateInput = z.object({
|
|
511
|
-
id: z.string().min(1),
|
|
512
|
-
name: z.string().trim().min(1).max(80).optional(),
|
|
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."),
|
|
513
1140
|
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(),
|
|
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."),
|
|
517
1144
|
scope: Scope.optional()
|
|
518
1145
|
});
|
|
519
|
-
const DeleteInput = z.object({
|
|
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");
|
|
520
1150
|
function toRule(rule, now) {
|
|
521
1151
|
switch (rule.kind) {
|
|
522
1152
|
case "once": {
|
|
@@ -543,53 +1173,44 @@ function describeRule(rule) {
|
|
|
543
1173
|
case "cron": return `cron ${rule.expression} (${rule.timezone})`;
|
|
544
1174
|
}
|
|
545
1175
|
}
|
|
546
|
-
function
|
|
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) {
|
|
1176
|
+
function answer(outcome, next, changedFields) {
|
|
567
1177
|
switch (outcome.kind) {
|
|
568
1178
|
case "ask": return outcome.result;
|
|
569
1179
|
case "refused": return {
|
|
570
1180
|
content: outcome.message,
|
|
571
1181
|
isError: true
|
|
572
1182
|
};
|
|
573
|
-
case "
|
|
574
|
-
|
|
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
|
+
}) };
|
|
575
1191
|
}
|
|
576
1192
|
}
|
|
577
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);
|
|
578
1196
|
return {
|
|
579
|
-
content:
|
|
1197
|
+
content: last >= 55296 && last <= 56319 ? text.slice(0, -1) : text,
|
|
580
1198
|
isError: true
|
|
581
1199
|
};
|
|
582
1200
|
}
|
|
583
1201
|
function createScheduleTool(triggers, agentLimit, next = () => ({})) {
|
|
584
1202
|
return {
|
|
585
1203
|
name: "schedule_create",
|
|
1204
|
+
preload: false,
|
|
586
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.",
|
|
587
1206
|
inputSchema: CreateInput,
|
|
1207
|
+
outputSchema: toolOutputSchema(Receipt, CreateInput, "schedule_create"),
|
|
1208
|
+
deliveryKind: "receipt",
|
|
588
1209
|
async execute(input, ctx) {
|
|
589
1210
|
try {
|
|
590
1211
|
const limit = agentLimit();
|
|
591
1212
|
if (limit > 0) {
|
|
592
|
-
if (triggers.
|
|
1213
|
+
if (triggers.countCreated(ctx) >= limit) return failure(/* @__PURE__ */ new Error(`this agent already has ${limit} scheduled tasks in this workspace; delete one first`));
|
|
593
1214
|
}
|
|
594
1215
|
const rule = toRule(input.rule, Date.now());
|
|
595
1216
|
return answer(triggers.create(ctx, {
|
|
@@ -603,33 +1224,26 @@ function createScheduleTool(triggers, agentLimit, next = () => ({})) {
|
|
|
603
1224
|
instruction: input.instruction,
|
|
604
1225
|
target: input.target,
|
|
605
1226
|
...input.scope === void 0 ? {} : { scope: input.scope }
|
|
606
|
-
}), next);
|
|
1227
|
+
}), next, Object.keys(input));
|
|
607
1228
|
} catch (error) {
|
|
608
1229
|
return failure(error);
|
|
609
1230
|
}
|
|
610
1231
|
}
|
|
611
1232
|
};
|
|
612
1233
|
}
|
|
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
1234
|
function updateScheduleTool(triggers, next = () => ({})) {
|
|
624
1235
|
return {
|
|
625
1236
|
name: "schedule_update",
|
|
1237
|
+
preload: false,
|
|
626
1238
|
description: "Change a scheduled task you created. Changing what it does, when, where, or widening its scope may ask the user.",
|
|
627
1239
|
inputSchema: UpdateInput,
|
|
1240
|
+
outputSchema: toolOutputSchema(Receipt, UpdateInput, "schedule_update"),
|
|
1241
|
+
deliveryKind: "receipt",
|
|
628
1242
|
async execute(input, ctx) {
|
|
629
1243
|
try {
|
|
630
1244
|
const { id, rule, catchUp, ...rest } = input;
|
|
631
1245
|
const patch = Object.fromEntries(Object.entries(rest).filter(([, value]) => value !== void 0));
|
|
632
|
-
const current = storedConfig(triggers.
|
|
1246
|
+
const current = storedConfig(triggers.get(ctx, id)?.config);
|
|
633
1247
|
const config = current === void 0 || !(rule !== void 0 || catchUp !== void 0) ? void 0 : {
|
|
634
1248
|
rule: rule === void 0 ? current.rule : toRule(rule, Date.now()),
|
|
635
1249
|
catchUp: catchUp ?? current.catchUp
|
|
@@ -638,31 +1252,54 @@ function updateScheduleTool(triggers, next = () => ({})) {
|
|
|
638
1252
|
...patch,
|
|
639
1253
|
...config === void 0 ? {} : { config },
|
|
640
1254
|
...current === void 0 ? {} : { summary: describeRule((config ?? current).rule) }
|
|
641
|
-
}), next);
|
|
1255
|
+
}), next, Object.keys(input).filter((key) => key !== "id"));
|
|
642
1256
|
} catch (error) {
|
|
643
1257
|
return failure(error);
|
|
644
1258
|
}
|
|
645
1259
|
}
|
|
646
1260
|
};
|
|
647
1261
|
}
|
|
1262
|
+
/** Deletes an owned schedule collection atomically and returns its durable operation receipt. */
|
|
648
1263
|
function deleteScheduleTool(triggers) {
|
|
649
1264
|
return {
|
|
650
1265
|
name: "schedule_delete",
|
|
651
|
-
|
|
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.",
|
|
652
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",
|
|
653
1275
|
async execute(input, ctx) {
|
|
654
|
-
|
|
1276
|
+
try {
|
|
1277
|
+
return { content: JSON.stringify(triggers.removeMany(ctx, input.ids, input.operationId)) };
|
|
1278
|
+
} catch (error) {
|
|
1279
|
+
return failure(error);
|
|
1280
|
+
}
|
|
655
1281
|
}
|
|
656
1282
|
};
|
|
657
1283
|
}
|
|
658
1284
|
function registerScheduleTools(ctx, register, agentLimit = () => DEFAULT_SCHEDULE_SETTINGS.agentLimit, next = () => ({})) {
|
|
659
1285
|
const triggers = ctx.services.get(TRIGGERS_SERVICE);
|
|
660
1286
|
register(createScheduleTool(triggers, agentLimit, next));
|
|
661
|
-
register(listSchedulesTool(triggers, next));
|
|
1287
|
+
register(listSchedulesTool(triggers, next, ctx.services.get("query-resources")));
|
|
1288
|
+
register(readScheduleTool(triggers, ctx.services.get("query-resources")));
|
|
662
1289
|
register(updateScheduleTool(triggers, next));
|
|
663
1290
|
register(deleteScheduleTool(triggers));
|
|
664
1291
|
}
|
|
665
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
|
|
666
1303
|
//#region src/index.ts
|
|
667
1304
|
/**
|
|
668
1305
|
* `@eum-agent/automation-schedule` — creating, listing, changing and deleting scheduled
|
|
@@ -696,7 +1333,7 @@ function browserModule() {
|
|
|
696
1333
|
}
|
|
697
1334
|
const schedulePlugin = {
|
|
698
1335
|
name: "@eum-agent/automation-schedule",
|
|
699
|
-
requires: ["triggers"],
|
|
1336
|
+
requires: ["query-resources", "triggers"],
|
|
700
1337
|
configSchema: ScheduleConfig,
|
|
701
1338
|
apply(ctx, config) {
|
|
702
1339
|
const disabled = new Set(config.disabled);
|