@eum-agent/automation-schedule 1.1.0 → 1.2.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.
- package/dist/index.js +645 -290
- package/package.json +4 -4
- package/ui/ui.js +5062 -131
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { existsSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
2
3
|
import { fileURLToPath } from "node:url";
|
|
3
4
|
import { z } from "zod";
|
|
4
5
|
import { Cron } from "croner";
|
|
@@ -9,7 +10,7 @@ const GUIDANCE = {
|
|
|
9
10
|
entries: [
|
|
10
11
|
{
|
|
11
12
|
tools: ["schedule_create"],
|
|
12
|
-
text: "`schedule_create` sets yourself a task for later
|
|
13
|
+
text: "`schedule_create` sets yourself a task for later \u2014 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
|
},
|
|
14
15
|
{
|
|
15
16
|
tools: ["schedule_list"],
|
|
@@ -30,48 +31,123 @@ const GUIDANCE = {
|
|
|
30
31
|
]
|
|
31
32
|
};
|
|
32
33
|
//#endregion
|
|
34
|
+
//#region src/body-document.ts
|
|
35
|
+
const LocalBodyRefSchema = z.strictObject({
|
|
36
|
+
bodyId: z.uuid(),
|
|
37
|
+
codec: z.enum([
|
|
38
|
+
"utf8-text",
|
|
39
|
+
"json",
|
|
40
|
+
"opaque"
|
|
41
|
+
]),
|
|
42
|
+
formatVersion: z.literal(1),
|
|
43
|
+
byteLength: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
44
|
+
sha256: z.string().regex(/^[a-f0-9]{64}$/)
|
|
45
|
+
});
|
|
46
|
+
async function captureTextBody(text, ctx) {
|
|
47
|
+
ctx.signal.throwIfAborted();
|
|
48
|
+
const writer = await ctx.openBody("utf8-text", ctx.signal);
|
|
49
|
+
const encoder = new TextEncoder();
|
|
50
|
+
let offset = 0;
|
|
51
|
+
let index = 0;
|
|
52
|
+
try {
|
|
53
|
+
while (index < text.length) {
|
|
54
|
+
ctx.signal.throwIfAborted();
|
|
55
|
+
const chunk = /* @__PURE__ */ new Uint8Array(65536);
|
|
56
|
+
let end = Math.min(text.length, index + 32768);
|
|
57
|
+
if (end < text.length && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--;
|
|
58
|
+
const { read, written } = encoder.encodeInto(text.slice(index, end), chunk);
|
|
59
|
+
if (!read) throw new Error("text_encoding_failed");
|
|
60
|
+
await writer.write(offset, chunk.subarray(0, written), ctx.signal);
|
|
61
|
+
offset += written;
|
|
62
|
+
index += read;
|
|
63
|
+
}
|
|
64
|
+
return (await writer.seal(ctx.signal)).body;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
await writer.abort();
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function createTextDocuments(render) {
|
|
71
|
+
const documents = /* @__PURE__ */ new WeakMap();
|
|
72
|
+
const prepare = (value, ctx) => {
|
|
73
|
+
const key = typeof value === "object" && value !== null ? value : void 0;
|
|
74
|
+
const prior = key ? documents.get(key) : void 0;
|
|
75
|
+
if (prior) return prior;
|
|
76
|
+
const work = (async () => {
|
|
77
|
+
const input = render(value);
|
|
78
|
+
const literals = input.nodes.filter((node) => node.kind === "literal");
|
|
79
|
+
const lengths = literals.map((node) => new TextEncoder().encode(node.text).byteLength);
|
|
80
|
+
if (literals.length === input.nodes.length && (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384 || input.nodes.length > 256)) {
|
|
81
|
+
const body = await captureTextBody(literals.map((node) => node.text).join(""), ctx);
|
|
82
|
+
return {
|
|
83
|
+
formatVersion: 1,
|
|
84
|
+
rendererVersion: 1,
|
|
85
|
+
nodes: [{
|
|
86
|
+
id: "text",
|
|
87
|
+
kind: "text-range",
|
|
88
|
+
body,
|
|
89
|
+
startByte: 0,
|
|
90
|
+
endByte: body.byteLength
|
|
91
|
+
}]
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
if (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384) {
|
|
95
|
+
const nodes = [];
|
|
96
|
+
const all = lengths.reduce((sum, length) => sum + length, 0) > 16384;
|
|
97
|
+
for (const node of input.nodes) {
|
|
98
|
+
if (node.kind !== "literal" || !all && new TextEncoder().encode(node.text).byteLength <= 4096) {
|
|
99
|
+
nodes.push(node);
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
const body = await captureTextBody(node.text, ctx);
|
|
103
|
+
nodes.push({
|
|
104
|
+
id: node.id,
|
|
105
|
+
kind: "text-range",
|
|
106
|
+
body,
|
|
107
|
+
startByte: 0,
|
|
108
|
+
endByte: body.byteLength
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
...input,
|
|
113
|
+
nodes
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return input;
|
|
117
|
+
})();
|
|
118
|
+
if (key) documents.set(key, work);
|
|
119
|
+
return work;
|
|
120
|
+
};
|
|
121
|
+
return {
|
|
122
|
+
prepare,
|
|
123
|
+
formatModel: prepare
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
//#endregion
|
|
33
127
|
//#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
128
|
function toolOutputSchema(body, input, name) {
|
|
37
|
-
return z.union([
|
|
38
|
-
|
|
39
|
-
z.strictObject({
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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()
|
|
129
|
+
return z.union([body, z.strictObject({
|
|
130
|
+
ok: z.literal(false),
|
|
131
|
+
error: z.strictObject({
|
|
132
|
+
code: z.string().min(1).max(128),
|
|
133
|
+
message: z.string().refine((value) => [...value].length <= 512).meta({ maxLength: 512 }),
|
|
134
|
+
retryable: z.boolean(),
|
|
135
|
+
field: z.string().max(256).optional(),
|
|
136
|
+
maximum: z.number().finite().optional()
|
|
57
137
|
}),
|
|
58
|
-
z.
|
|
59
|
-
|
|
138
|
+
next: z.strictObject({
|
|
139
|
+
tool: z.literal(name),
|
|
140
|
+
arguments: input
|
|
141
|
+
}).nullable(),
|
|
142
|
+
execution: z.strictObject({ state: z.enum([
|
|
143
|
+
"not-started",
|
|
144
|
+
"committed",
|
|
145
|
+
"unknown"
|
|
146
|
+
]) }).optional()
|
|
147
|
+
})]);
|
|
60
148
|
}
|
|
61
149
|
//#endregion
|
|
62
|
-
//#region src/
|
|
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. */
|
|
150
|
+
//#region src/tool-data.ts
|
|
75
151
|
const ScheduleRule = z.discriminatedUnion("kind", [
|
|
76
152
|
z.object({
|
|
77
153
|
kind: z.literal("once"),
|
|
@@ -88,8 +164,79 @@ const ScheduleRule = z.discriminatedUnion("kind", [
|
|
|
88
164
|
timezone: z.string().min(1).max(100)
|
|
89
165
|
})
|
|
90
166
|
]);
|
|
167
|
+
const ScheduleReceiptSchema = z.strictObject({
|
|
168
|
+
ok: z.literal(true),
|
|
169
|
+
committed: z.literal(true),
|
|
170
|
+
id: z.string(),
|
|
171
|
+
name: z.string(),
|
|
172
|
+
rule: ScheduleRule.nullable(),
|
|
173
|
+
catchUp: z.boolean().nullable(),
|
|
174
|
+
updatedAt: z.number(),
|
|
175
|
+
enabled: z.boolean(),
|
|
176
|
+
nextRunAt: z.string().nullable(),
|
|
177
|
+
nextRunKnown: z.boolean(),
|
|
178
|
+
changedFields: z.array(z.string())
|
|
179
|
+
});
|
|
180
|
+
const ScheduleDeleteSchema = z.strictObject({
|
|
181
|
+
operationState: z.literal("committed"),
|
|
182
|
+
operationId: z.uuid(),
|
|
183
|
+
value: z.strictObject({ removed: z.array(z.string()) })
|
|
184
|
+
});
|
|
185
|
+
z.strictObject({
|
|
186
|
+
ok: z.literal(false),
|
|
187
|
+
error: z.strictObject({
|
|
188
|
+
code: z.string(),
|
|
189
|
+
message: z.string().max(1024),
|
|
190
|
+
retryable: z.boolean()
|
|
191
|
+
}),
|
|
192
|
+
next: z.unknown()
|
|
193
|
+
});
|
|
194
|
+
const Continue$1 = z.strictObject({
|
|
195
|
+
cursor: z.string(),
|
|
196
|
+
outputTokens: z.number().optional()
|
|
197
|
+
});
|
|
198
|
+
const ScheduleField = z.enum(["instruction", "scopes"]);
|
|
199
|
+
const Summary = z.strictObject({
|
|
200
|
+
id: z.string(),
|
|
201
|
+
name: z.string(),
|
|
202
|
+
enabled: z.boolean(),
|
|
203
|
+
nextRun: z.string().nullable(),
|
|
204
|
+
paused: z.literal("session-archived").nullable(),
|
|
205
|
+
scopeSummary: z.strictObject({ detailsAvailable: z.literal(true) })
|
|
206
|
+
});
|
|
207
|
+
const effective = z.strictObject({ outputTokens: z.number().int().nonnegative() });
|
|
208
|
+
const ScheduleListDataSchema = z.strictObject({
|
|
209
|
+
ok: z.literal(true),
|
|
210
|
+
complete: z.boolean(),
|
|
211
|
+
items: z.array(Summary),
|
|
212
|
+
next: z.strictObject({
|
|
213
|
+
tool: z.literal("schedule_list"),
|
|
214
|
+
arguments: Continue$1
|
|
215
|
+
}).nullable(),
|
|
216
|
+
effective
|
|
217
|
+
});
|
|
218
|
+
const Chunk = z.strictObject({
|
|
219
|
+
index: z.number().int().nonnegative(),
|
|
220
|
+
id: z.string(),
|
|
221
|
+
field: ScheduleField,
|
|
222
|
+
body: LocalBodyRefSchema,
|
|
223
|
+
startByte: z.number().int().nonnegative(),
|
|
224
|
+
endByte: z.number().int().nonnegative(),
|
|
225
|
+
offset: z.number().int().nonnegative(),
|
|
226
|
+
length: z.number().int().nonnegative(),
|
|
227
|
+
complete: z.boolean()
|
|
228
|
+
});
|
|
229
|
+
const ScheduleReadDataSchema = z.strictObject({
|
|
230
|
+
ok: z.literal(true),
|
|
231
|
+
complete: z.boolean(),
|
|
232
|
+
items: z.array(Chunk),
|
|
233
|
+
next: z.strictObject({
|
|
234
|
+
tool: z.literal("schedule_read"),
|
|
235
|
+
arguments: Continue$1
|
|
236
|
+
}).nullable(),
|
|
237
|
+
effective
|
|
238
|
+
});
|
|
91
239
|
const MINUTE = 6e4;
|
|
92
|
-
/** How far ahead a cron expression's spacing is checked. */
|
|
93
240
|
const SPACING_SAMPLE = 100;
|
|
94
241
|
function invalid(reason) {
|
|
95
242
|
return /* @__PURE__ */ new Error(`invalid rule: ${reason}`);
|
|
@@ -109,7 +256,6 @@ function cronOf(rule) {
|
|
|
109
256
|
throw invalid(error instanceof Error ? error.message : String(error));
|
|
110
257
|
}
|
|
111
258
|
}
|
|
112
|
-
/** The first time strictly after `after` the rule runs, or `null` for none. */
|
|
113
259
|
function nextRun(rule, after) {
|
|
114
260
|
switch (rule.kind) {
|
|
115
261
|
case "once": return rule.at > after ? rule.at : null;
|
|
@@ -125,7 +271,6 @@ function nextRun(rule, after) {
|
|
|
125
271
|
}
|
|
126
272
|
}
|
|
127
273
|
}
|
|
128
|
-
/** Throws `invalid rule: …` for a rule that cannot be stored now. */
|
|
129
274
|
function validateRule(rule, now) {
|
|
130
275
|
switch (rule.kind) {
|
|
131
276
|
case "once":
|
|
@@ -141,7 +286,6 @@ function validateRule(rule, now) {
|
|
|
141
286
|
}
|
|
142
287
|
}
|
|
143
288
|
}
|
|
144
|
-
/** The next `count` times, after validating the rule. */
|
|
145
289
|
function previewRule(rule, now, count = 3) {
|
|
146
290
|
validateRule(rule, now);
|
|
147
291
|
const out = [];
|
|
@@ -156,14 +300,6 @@ function previewRule(rule, now, count = 3) {
|
|
|
156
300
|
}
|
|
157
301
|
//#endregion
|
|
158
302
|
//#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
303
|
const ScheduleConfig$1 = z.object({
|
|
168
304
|
rule: ScheduleRule,
|
|
169
305
|
catchUp: z.boolean().default(true)
|
|
@@ -177,8 +313,6 @@ const ScheduleConfig$1 = z.object({
|
|
|
177
313
|
});
|
|
178
314
|
}
|
|
179
315
|
});
|
|
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
316
|
const StoredScheduleConfig = z.object({
|
|
183
317
|
rule: ScheduleRule,
|
|
184
318
|
catchUp: z.boolean().default(true)
|
|
@@ -189,30 +323,11 @@ function storedConfig(raw) {
|
|
|
189
323
|
}
|
|
190
324
|
//#endregion
|
|
191
325
|
//#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
326
|
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
327
|
const MAX_SLEEP_MS = 3e4;
|
|
212
328
|
function hashOf(config) {
|
|
213
329
|
return createHash("sha256").update(JSON.stringify(config ?? null)).digest("hex");
|
|
214
330
|
}
|
|
215
|
-
/** Creates one schedule loop; explicit ticks also work before its timer starts. */
|
|
216
331
|
function createScheduleLoop(deps) {
|
|
217
332
|
const now = deps.now ?? (() => Date.now());
|
|
218
333
|
const setTimer = deps.setTimer ?? ((fn, ms) => {
|
|
@@ -225,6 +340,33 @@ function createScheduleLoop(deps) {
|
|
|
225
340
|
let stopped = false;
|
|
226
341
|
let generation = 0;
|
|
227
342
|
let ticking = Promise.resolve();
|
|
343
|
+
let known = /* @__PURE__ */ new Map();
|
|
344
|
+
function pausedNow(definition, reenabled) {
|
|
345
|
+
const sessionId = deps.sessionOf?.(definition);
|
|
346
|
+
const targets = deps.targets;
|
|
347
|
+
if (sessionId === void 0 || targets === void 0 || deps.targetState === void 0) {
|
|
348
|
+
targets?.remove(definition.id);
|
|
349
|
+
return false;
|
|
350
|
+
}
|
|
351
|
+
const state = deps.targetState(sessionId);
|
|
352
|
+
if (state === "missing") return false;
|
|
353
|
+
const row = targets.get(definition.id);
|
|
354
|
+
const previous = row?.sessionId === sessionId ? row : void 0;
|
|
355
|
+
const open = state !== "closed";
|
|
356
|
+
const reopened = open && previous?.epoch != null && state > previous.epoch;
|
|
357
|
+
let pausedAt = previous?.pausedAt ?? null;
|
|
358
|
+
if (!open) pausedAt ??= now();
|
|
359
|
+
else if (reenabled) pausedAt = null;
|
|
360
|
+
else if (reopened) pausedAt ??= now();
|
|
361
|
+
const epoch = open ? state : previous?.epoch ?? null;
|
|
362
|
+
if (previous?.epoch !== epoch || previous.pausedAt !== pausedAt) targets.put({
|
|
363
|
+
definitionId: definition.id,
|
|
364
|
+
sessionId,
|
|
365
|
+
epoch,
|
|
366
|
+
pausedAt
|
|
367
|
+
});
|
|
368
|
+
return pausedAt !== null;
|
|
369
|
+
}
|
|
228
370
|
function reconcile(definitions) {
|
|
229
371
|
let touched = false;
|
|
230
372
|
const at = now();
|
|
@@ -235,9 +377,11 @@ function createScheduleLoop(deps) {
|
|
|
235
377
|
if (config === void 0) continue;
|
|
236
378
|
const hash = hashOf(definition.config);
|
|
237
379
|
const row = deps.store.get(definition.id);
|
|
380
|
+
pausedNow(definition, row !== void 0 && !row.seenEnabled);
|
|
238
381
|
if (row !== void 0 && row.configHash === hash && row.seenEnabled) continue;
|
|
239
382
|
deps.store.put({
|
|
240
383
|
definitionId: definition.id,
|
|
384
|
+
workspaceId: definition.workspaceId,
|
|
241
385
|
nextAt: nextRun(config.rule, at),
|
|
242
386
|
configHash: hash,
|
|
243
387
|
seenEnabled: true
|
|
@@ -258,6 +402,7 @@ function createScheduleLoop(deps) {
|
|
|
258
402
|
let touched = reconcile(definitions);
|
|
259
403
|
const at = now();
|
|
260
404
|
const byId = new Map(definitions.map((one) => [one.id, one]));
|
|
405
|
+
known = byId;
|
|
261
406
|
for (const row of deps.store.all()) {
|
|
262
407
|
if (!row.seenEnabled || row.nextAt === null || row.nextAt > at) continue;
|
|
263
408
|
const definition = byId.get(row.definitionId);
|
|
@@ -268,6 +413,14 @@ function createScheduleLoop(deps) {
|
|
|
268
413
|
deps.store.setNext(row.definitionId, nextRun(config.rule, at));
|
|
269
414
|
touched = true;
|
|
270
415
|
try {
|
|
416
|
+
if (pausedNow(definition, false)) {
|
|
417
|
+
if (config.rule.kind === "once") deps.host.skip(row.definitionId, {
|
|
418
|
+
kind: late ? "catch-up" : "scheduled",
|
|
419
|
+
scheduledAt,
|
|
420
|
+
reason: "session-archived"
|
|
421
|
+
});
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
271
424
|
if (late && !config.catchUp) {
|
|
272
425
|
deps.host.skip(row.definitionId, {
|
|
273
426
|
kind: "catch-up",
|
|
@@ -280,8 +433,8 @@ function createScheduleLoop(deps) {
|
|
|
280
433
|
kind: late ? "catch-up" : "scheduled",
|
|
281
434
|
scheduledAt
|
|
282
435
|
});
|
|
283
|
-
} catch
|
|
284
|
-
deps.log?.(
|
|
436
|
+
} catch {
|
|
437
|
+
deps.log?.("SCHEDULED_TASK_RUN_FAILED");
|
|
285
438
|
}
|
|
286
439
|
if (stopped || admittedGeneration !== generation) return;
|
|
287
440
|
}
|
|
@@ -305,7 +458,7 @@ function createScheduleLoop(deps) {
|
|
|
305
458
|
const admittedGeneration = generation;
|
|
306
459
|
ticking = ticking.then(() => {
|
|
307
460
|
if (!stopped && admittedGeneration === generation) return wake(admittedGeneration);
|
|
308
|
-
}).catch((
|
|
461
|
+
}).catch(() => deps.log?.("SCHEDULE_LOOP_FAILED")).finally(() => {
|
|
309
462
|
if (admittedGeneration === generation) arm();
|
|
310
463
|
});
|
|
311
464
|
return ticking;
|
|
@@ -327,15 +480,46 @@ function createScheduleLoop(deps) {
|
|
|
327
480
|
const out = {};
|
|
328
481
|
for (const row of deps.store.all()) if (row.seenEnabled) out[row.definitionId] = row.nextAt;
|
|
329
482
|
return out;
|
|
483
|
+
},
|
|
484
|
+
paused() {
|
|
485
|
+
const out = {};
|
|
486
|
+
for (const row of deps.targets?.all() ?? []) if (row.pausedAt !== null && known.has(row.definitionId)) out[row.definitionId] = "session-archived";
|
|
487
|
+
return out;
|
|
488
|
+
},
|
|
489
|
+
resume(definitionId) {
|
|
490
|
+
const definition = known.get(definitionId);
|
|
491
|
+
const config = definition === void 0 ? void 0 : storedConfig(definition.config);
|
|
492
|
+
const sessionId = definition === void 0 ? void 0 : deps.sessionOf?.(definition);
|
|
493
|
+
if (definition === void 0 || config === void 0) throw new Error("no such trigger");
|
|
494
|
+
const row = deps.targets?.get(definitionId);
|
|
495
|
+
if (sessionId === void 0 || row === void 0 || row.pausedAt === null) return;
|
|
496
|
+
const state = deps.targetState?.(sessionId);
|
|
497
|
+
if (state === "closed") throw new Error(`session_archived: session ${sessionId} is still archived`);
|
|
498
|
+
deps.targets.put({
|
|
499
|
+
...row,
|
|
500
|
+
sessionId,
|
|
501
|
+
epoch: typeof state === "number" ? state : row.epoch,
|
|
502
|
+
pausedAt: null
|
|
503
|
+
});
|
|
504
|
+
deps.store.put({
|
|
505
|
+
definitionId,
|
|
506
|
+
workspaceId: definition.workspaceId,
|
|
507
|
+
nextAt: nextRun(config.rule, now()),
|
|
508
|
+
configHash: hashOf(definition.config),
|
|
509
|
+
seenEnabled: true
|
|
510
|
+
});
|
|
511
|
+
deps.changed?.();
|
|
512
|
+
arm();
|
|
330
513
|
}
|
|
331
514
|
};
|
|
332
515
|
return loop;
|
|
333
516
|
}
|
|
334
517
|
//#endregion
|
|
335
518
|
//#region src/source/next-runs.ts
|
|
336
|
-
function toRow(raw) {
|
|
519
|
+
function toRow$1(raw) {
|
|
337
520
|
return {
|
|
338
521
|
definitionId: raw.definition_id,
|
|
522
|
+
workspaceId: raw.workspace_id,
|
|
339
523
|
nextAt: raw.next_at,
|
|
340
524
|
configHash: raw.config_hash,
|
|
341
525
|
seenEnabled: raw.seen_enabled === 1
|
|
@@ -346,31 +530,33 @@ function openNextRuns(ctx) {
|
|
|
346
530
|
const table = storage.tableName("next_run");
|
|
347
531
|
storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (
|
|
348
532
|
definition_id TEXT NOT NULL PRIMARY KEY,
|
|
533
|
+
workspace_id TEXT NOT NULL,
|
|
349
534
|
next_at INTEGER,
|
|
350
535
|
config_hash TEXT NOT NULL,
|
|
351
536
|
seen_enabled INTEGER NOT NULL CHECK (seen_enabled IN (0, 1))
|
|
352
537
|
) STRICT`);
|
|
353
538
|
const selectOne = storage.db.prepare(`SELECT * FROM ${table} WHERE definition_id = ?`);
|
|
354
539
|
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)
|
|
356
|
-
|
|
540
|
+
const upsert = storage.db.prepare(`INSERT INTO ${table} (definition_id, workspace_id, next_at, config_hash, seen_enabled)
|
|
541
|
+
VALUES (?, ?, ?, ?, ?)
|
|
542
|
+
ON CONFLICT (definition_id) DO UPDATE SET workspace_id = excluded.workspace_id,
|
|
543
|
+
next_at = excluded.next_at,
|
|
357
544
|
config_hash = excluded.config_hash, seen_enabled = excluded.seen_enabled`);
|
|
358
545
|
const updateNext = storage.db.prepare(`UPDATE ${table} SET next_at = ? WHERE definition_id = ?`);
|
|
359
546
|
return {
|
|
360
547
|
get(definitionId) {
|
|
361
548
|
const raw = selectOne.get(definitionId);
|
|
362
|
-
return raw === void 0 ? void 0 : toRow(raw);
|
|
549
|
+
return raw === void 0 ? void 0 : toRow$1(raw);
|
|
363
550
|
},
|
|
364
|
-
all: () => selectAll.all().map(toRow),
|
|
551
|
+
all: () => selectAll.all().map(toRow$1),
|
|
365
552
|
put(row) {
|
|
366
|
-
upsert.run(row.definitionId, row.nextAt, row.configHash, row.seenEnabled ? 1 : 0);
|
|
553
|
+
upsert.run(row.definitionId, row.workspaceId, row.nextAt, row.configHash, row.seenEnabled ? 1 : 0);
|
|
367
554
|
},
|
|
368
555
|
setNext(definitionId, nextAt) {
|
|
369
556
|
updateNext.run(nextAt, definitionId);
|
|
370
557
|
}
|
|
371
558
|
};
|
|
372
559
|
}
|
|
373
|
-
/** An in-memory table, for a runtime without a database and for tests. */
|
|
374
560
|
function memoryNextRuns() {
|
|
375
561
|
const rows = /* @__PURE__ */ new Map();
|
|
376
562
|
return {
|
|
@@ -389,25 +575,119 @@ function memoryNextRuns() {
|
|
|
389
575
|
};
|
|
390
576
|
}
|
|
391
577
|
//#endregion
|
|
578
|
+
//#region src/source/retention.ts
|
|
579
|
+
function createScheduleRetention(storage, { deleteWhere, prepareDeletion }) {
|
|
580
|
+
const runs = storage.tableName("next_run");
|
|
581
|
+
const targets = storage.tableName("session_target");
|
|
582
|
+
return {
|
|
583
|
+
purgeSessions(sessionIds, cursor, budget) {
|
|
584
|
+
const ids = JSON.stringify(sessionIds);
|
|
585
|
+
const bound = "session_id IN (SELECT value FROM json_each(?))";
|
|
586
|
+
return prepareDeletion([deleteWhere(storage.db, runs, `definition_id IN (SELECT definition_id FROM ${targets} WHERE ${bound})`, ids), deleteWhere(storage.db, targets, bound, ids)], cursor, budget);
|
|
587
|
+
},
|
|
588
|
+
purgeWorkspace: (workspaceId, cursor, budget) => prepareDeletion([deleteWhere(storage.db, targets, `definition_id IN (SELECT definition_id FROM ${runs} WHERE workspace_id = ?)`, workspaceId), deleteWhere(storage.db, runs, "workspace_id = ?", workspaceId)], cursor, budget)
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
//#endregion
|
|
592
|
+
//#region src/source/targets.ts
|
|
593
|
+
function toRow(raw) {
|
|
594
|
+
return {
|
|
595
|
+
definitionId: raw.definition_id,
|
|
596
|
+
sessionId: raw.session_id,
|
|
597
|
+
epoch: raw.epoch,
|
|
598
|
+
pausedAt: raw.paused_at
|
|
599
|
+
};
|
|
600
|
+
}
|
|
601
|
+
function openSessionTargets(ctx) {
|
|
602
|
+
const storage = ctx.storage.open();
|
|
603
|
+
const table = storage.tableName("session_target");
|
|
604
|
+
storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (
|
|
605
|
+
definition_id TEXT NOT NULL PRIMARY KEY,
|
|
606
|
+
session_id TEXT NOT NULL,
|
|
607
|
+
epoch INTEGER CHECK (epoch IS NULL OR epoch >= 1),
|
|
608
|
+
paused_at INTEGER
|
|
609
|
+
) STRICT`);
|
|
610
|
+
const selectOne = storage.db.prepare(`SELECT definition_id, session_id, epoch, paused_at FROM ${table} WHERE definition_id = ?`);
|
|
611
|
+
const selectAll = storage.db.prepare(`SELECT definition_id, session_id, epoch, paused_at FROM ${table} ORDER BY definition_id`);
|
|
612
|
+
const upsert = storage.db.prepare(`INSERT INTO ${table} (definition_id, session_id, epoch, paused_at) VALUES (?, ?, ?, ?)
|
|
613
|
+
ON CONFLICT (definition_id) DO UPDATE SET session_id = excluded.session_id,
|
|
614
|
+
epoch = excluded.epoch, paused_at = excluded.paused_at`);
|
|
615
|
+
const deleteOne = storage.db.prepare(`DELETE FROM ${table} WHERE definition_id = ?`);
|
|
616
|
+
return {
|
|
617
|
+
get(definitionId) {
|
|
618
|
+
const raw = selectOne.get(definitionId);
|
|
619
|
+
return raw === void 0 ? void 0 : toRow(raw);
|
|
620
|
+
},
|
|
621
|
+
all: () => selectAll.all().map(toRow),
|
|
622
|
+
put(row) {
|
|
623
|
+
upsert.run(row.definitionId, row.sessionId, row.epoch, row.pausedAt);
|
|
624
|
+
},
|
|
625
|
+
remove(definitionId) {
|
|
626
|
+
deleteOne.run(definitionId);
|
|
627
|
+
}
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
function memorySessionTargets() {
|
|
631
|
+
const rows = /* @__PURE__ */ new Map();
|
|
632
|
+
return {
|
|
633
|
+
get: (id) => rows.get(id),
|
|
634
|
+
all: () => [...rows.values()].sort((a, b) => a.definitionId.localeCompare(b.definitionId)),
|
|
635
|
+
put: (row) => {
|
|
636
|
+
rows.set(row.definitionId, row);
|
|
637
|
+
},
|
|
638
|
+
remove: (id) => {
|
|
639
|
+
rows.delete(id);
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
}
|
|
643
|
+
//#endregion
|
|
392
644
|
//#region src/source/index.ts
|
|
393
645
|
const SOURCE_KIND = "schedule";
|
|
394
|
-
const SOURCE_LABEL = "
|
|
395
|
-
const NextRunsPayload = z.object({
|
|
396
|
-
|
|
646
|
+
const SOURCE_LABEL = "\u8ba1\u5212\u4efb\u52a1";
|
|
647
|
+
const NextRunsPayload = z.object({
|
|
648
|
+
next: z.record(z.string(), z.number().nullable()),
|
|
649
|
+
paused: z.record(z.string(), z.literal("session-archived"))
|
|
650
|
+
});
|
|
651
|
+
function sessionOf(definition) {
|
|
652
|
+
const target = definition.target;
|
|
653
|
+
return target?.kind === "session" ? target.sessionId : void 0;
|
|
654
|
+
}
|
|
397
655
|
function registerScheduleSource(ctx) {
|
|
398
656
|
let store;
|
|
657
|
+
let durable = true;
|
|
399
658
|
try {
|
|
400
659
|
store = openNextRuns(ctx);
|
|
401
660
|
} catch {
|
|
402
661
|
store = memoryNextRuns();
|
|
662
|
+
durable = false;
|
|
403
663
|
}
|
|
664
|
+
let targets;
|
|
665
|
+
try {
|
|
666
|
+
targets = openSessionTargets(ctx);
|
|
667
|
+
} catch {
|
|
668
|
+
targets = memorySessionTargets();
|
|
669
|
+
durable = false;
|
|
670
|
+
}
|
|
671
|
+
if (durable) ctx.retention.register(createScheduleRetention(ctx.storage.open(), ctx.retention));
|
|
672
|
+
const lifecycle = ctx.services.get("session-lifecycle");
|
|
673
|
+
const targetState = (sessionId) => {
|
|
674
|
+
try {
|
|
675
|
+
return lifecycle.enter(sessionId).executionEpoch;
|
|
676
|
+
} catch (error) {
|
|
677
|
+
return (error instanceof Error ? error.message : String(error)).startsWith("session_archived") ? "closed" : "missing";
|
|
678
|
+
}
|
|
679
|
+
};
|
|
404
680
|
let loop;
|
|
405
681
|
const frame = ctx.client.registerFrame({
|
|
406
682
|
name: "nextRunsChanged",
|
|
407
683
|
delivery: "broadcast",
|
|
408
684
|
payload: NextRunsPayload
|
|
409
685
|
});
|
|
410
|
-
const
|
|
686
|
+
const snapshot = () => ({
|
|
687
|
+
next: { ...loop?.next() ?? {} },
|
|
688
|
+
paused: { ...loop?.paused() ?? {} }
|
|
689
|
+
});
|
|
690
|
+
const announce = () => frame.emit(snapshot());
|
|
411
691
|
ctx.triggers.registerSource({
|
|
412
692
|
kind: SOURCE_KIND,
|
|
413
693
|
label: SOURCE_LABEL,
|
|
@@ -416,11 +696,14 @@ function registerScheduleSource(ctx) {
|
|
|
416
696
|
loop = createScheduleLoop({
|
|
417
697
|
host,
|
|
418
698
|
store,
|
|
699
|
+
targets,
|
|
700
|
+
sessionOf,
|
|
701
|
+
targetState,
|
|
419
702
|
changed: announce,
|
|
420
|
-
log: (
|
|
421
|
-
level: "
|
|
703
|
+
log: (localCode) => ctx.log.emit({
|
|
704
|
+
level: "error",
|
|
422
705
|
event: "plugin.event",
|
|
423
|
-
fields: { localCode
|
|
706
|
+
fields: { localCode }
|
|
424
707
|
})
|
|
425
708
|
});
|
|
426
709
|
const off = host.onChanged(() => void loop?.tick());
|
|
@@ -442,24 +725,116 @@ function registerScheduleSource(ctx) {
|
|
|
442
725
|
});
|
|
443
726
|
ctx.client.registerMethod({
|
|
444
727
|
name: "nextRuns",
|
|
445
|
-
description: "When each enabled scheduled task runs next, by definition id
|
|
728
|
+
description: "When each enabled scheduled task runs next, by definition id (null for never), and which tasks are paused because the session they run in was archived.",
|
|
446
729
|
params: z.strictObject({}),
|
|
447
730
|
result: NextRunsPayload,
|
|
448
|
-
handle:
|
|
731
|
+
handle: snapshot
|
|
449
732
|
});
|
|
450
|
-
|
|
733
|
+
ctx.client.registerMethod({
|
|
734
|
+
name: "resumeTask",
|
|
735
|
+
description: "Clears the archive pause of a task that runs in an existing session, counting its next time from now; refused while that session is still archived.",
|
|
736
|
+
params: z.strictObject({ id: z.string().min(1) }),
|
|
737
|
+
result: NextRunsPayload,
|
|
738
|
+
handle: ({ id }) => {
|
|
739
|
+
if (loop === void 0) throw new Error("no such trigger");
|
|
740
|
+
loop.resume(id);
|
|
741
|
+
return snapshot();
|
|
742
|
+
}
|
|
743
|
+
});
|
|
744
|
+
return {
|
|
745
|
+
next: () => loop?.next() ?? {},
|
|
746
|
+
paused: () => loop?.paused() ?? {}
|
|
747
|
+
};
|
|
748
|
+
}
|
|
749
|
+
//#endregion
|
|
750
|
+
//#region src/tool-document.ts
|
|
751
|
+
function scheduleResult(data, action, state = "committed") {
|
|
752
|
+
const value = data;
|
|
753
|
+
const count = value.items?.length ?? value.value?.removed.length ?? 0;
|
|
754
|
+
return {
|
|
755
|
+
data,
|
|
756
|
+
execution: { state },
|
|
757
|
+
isError: !!value.error,
|
|
758
|
+
...value.error ? { error: {
|
|
759
|
+
code: value.error.code,
|
|
760
|
+
retryable: value.error.retryable
|
|
761
|
+
} } : {},
|
|
762
|
+
presentation: {
|
|
763
|
+
type: `schedule-${action}`,
|
|
764
|
+
schemaVersion: 1,
|
|
765
|
+
state: value.error ? "error" : value.complete === false || value.nextRunKnown === false ? "partial" : "ready",
|
|
766
|
+
summary: (value.error?.message ?? (value.id ? `${value.id} \u00b7 ${value.enabled ? "enabled" : "disabled"}` : `${count} scheduled task result(s)`)).slice(0, 512),
|
|
767
|
+
fields: {
|
|
768
|
+
...value.id ? {
|
|
769
|
+
id: value.id,
|
|
770
|
+
enabled: value.enabled ?? false,
|
|
771
|
+
nextRunAt: value.nextRunAt ?? null
|
|
772
|
+
} : {},
|
|
773
|
+
...value.operationId ? { operationId: value.operationId } : {},
|
|
774
|
+
count
|
|
775
|
+
},
|
|
776
|
+
actions: [],
|
|
777
|
+
bodyRefs: value.items?.flatMap((item) => item.body ? [item.body] : []) ?? []
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
}
|
|
781
|
+
function scheduleDocument(value) {
|
|
782
|
+
const data = value;
|
|
783
|
+
const nodes = [];
|
|
784
|
+
if (data.error) nodes.push({
|
|
785
|
+
id: "failure",
|
|
786
|
+
kind: "literal",
|
|
787
|
+
text: `${data.error.code}: ${data.error.message}\n`
|
|
788
|
+
});
|
|
789
|
+
else if (data.id) nodes.push({
|
|
790
|
+
id: "receipt",
|
|
791
|
+
kind: "literal",
|
|
792
|
+
text: `Schedule ${data.name ?? ""} (${data.id}): ${data.enabled ? "enabled" : "disabled"}; next run ${data.nextRunKnown === false ? "unavailable" : data.nextRunAt ?? "none"}. Rule: ${data.rule ? data.rule.kind === "once" ? new Date(data.rule.at).toISOString() : data.rule.kind === "interval" ? `every ${data.rule.everyMinutes} minutes` : `${data.rule.expression} (${data.rule.timezone})` : "unavailable"}. Changed: ${data.changedFields?.join(", ")}.\n`
|
|
793
|
+
});
|
|
794
|
+
else if (data.value) nodes.push({
|
|
795
|
+
id: "removed",
|
|
796
|
+
kind: "literal",
|
|
797
|
+
text: `Schedule deletion ${data.operationId} committed. Removed: ${data.value.removed.join(", ")}. Existing sessions remain.\n`
|
|
798
|
+
});
|
|
799
|
+
else for (const [index, item] of (data.items ?? []).entries()) {
|
|
800
|
+
nodes.push({
|
|
801
|
+
id: `identity-${index}`,
|
|
802
|
+
kind: "literal",
|
|
803
|
+
text: item.body ? `Schedule ${item.id}; ${item.field}; code points ${item.offset}..${(item.offset ?? 0) + (item.length ?? 0)}${item.complete ? "" : " (partial)"}.\n` : `${item.name} (${item.id}): ${item.enabled ? "enabled" : "disabled"}; ${item.paused === "session-archived" ? "paused: session archived; " : ""}next run ${item.nextRun ?? "none"}.\n`
|
|
804
|
+
});
|
|
805
|
+
if (item.body) nodes.push({
|
|
806
|
+
id: `field-${index}`,
|
|
807
|
+
kind: "text-range",
|
|
808
|
+
body: item.body,
|
|
809
|
+
startByte: item.startByte,
|
|
810
|
+
endByte: item.endByte
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
if (!nodes.length) nodes.push({
|
|
814
|
+
id: "empty",
|
|
815
|
+
kind: "literal",
|
|
816
|
+
text: "No matching schedules.\n"
|
|
817
|
+
});
|
|
818
|
+
if (data.next) nodes.push({
|
|
819
|
+
id: "next",
|
|
820
|
+
kind: "literal",
|
|
821
|
+
text: `\nContinue with ${JSON.stringify(data.next)}\n`
|
|
822
|
+
});
|
|
823
|
+
return {
|
|
824
|
+
formatVersion: 1,
|
|
825
|
+
rendererVersion: 1,
|
|
826
|
+
nodes
|
|
827
|
+
};
|
|
451
828
|
}
|
|
452
829
|
//#endregion
|
|
453
830
|
//#region src/cursor-cache.ts
|
|
454
|
-
const bytesOf = (value) => 2048 + 2 * (value.
|
|
455
|
-
/** Owns metadata snapshots; each query and all successor positions share one opaque host lease. */
|
|
831
|
+
const bytesOf = (value) => 2048 + 2 * JSON.stringify(value.metadata ?? null).length;
|
|
456
832
|
var QueryCursorCache = class extends Map {
|
|
457
833
|
pending = /* @__PURE__ */ new Map();
|
|
458
834
|
roots = /* @__PURE__ */ new Map();
|
|
459
835
|
resources;
|
|
460
836
|
facts;
|
|
461
837
|
timer;
|
|
462
|
-
/** Measures only retained metadata; source IO uses a separate bounded reservation. */
|
|
463
838
|
constructor(facts, resources) {
|
|
464
839
|
super();
|
|
465
840
|
this.facts = facts;
|
|
@@ -572,7 +947,6 @@ var QueryCursorCache = class extends Map {
|
|
|
572
947
|
this.settle(root);
|
|
573
948
|
};
|
|
574
949
|
}
|
|
575
|
-
/** Runs source acquisition under the actual authenticated call, releasing only after its cleanup. */
|
|
576
950
|
async runExclusive(input, call, action, sourceBytes = 4194304) {
|
|
577
951
|
const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
|
|
578
952
|
const saved = cursor === void 0 ? void 0 : this.get(cursor);
|
|
@@ -592,7 +966,7 @@ var QueryCursorCache = class extends Map {
|
|
|
592
966
|
"cursor_invalid"
|
|
593
967
|
].includes(error.message)) throw error;
|
|
594
968
|
return {
|
|
595
|
-
|
|
969
|
+
data: {
|
|
596
970
|
ok: false,
|
|
597
971
|
error: {
|
|
598
972
|
code: error.message,
|
|
@@ -600,14 +974,14 @@ var QueryCursorCache = class extends Map {
|
|
|
600
974
|
retryable: false
|
|
601
975
|
},
|
|
602
976
|
next: null
|
|
603
|
-
}
|
|
977
|
+
},
|
|
978
|
+
execution: { state: "not-started" },
|
|
604
979
|
isError: true
|
|
605
980
|
};
|
|
606
981
|
} finally {
|
|
607
982
|
finish?.();
|
|
608
983
|
}
|
|
609
984
|
}
|
|
610
|
-
/** Joins same-cursor preparation before revalidating and replaying its accepted exact page. */
|
|
611
985
|
async run(input, call, action, sourceBytes = 4194304) {
|
|
612
986
|
const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
|
|
613
987
|
if (cursor === void 0) return this.runExclusive(input, call, action, sourceBytes);
|
|
@@ -626,7 +1000,6 @@ var QueryCursorCache = class extends Map {
|
|
|
626
1000
|
if (this.pending.get(cursor) === gate) this.pending.delete(cursor);
|
|
627
1001
|
}
|
|
628
1002
|
}
|
|
629
|
-
/** Applies the same resource lifecycle to a native model-tool registration. */
|
|
630
1003
|
wrap(tool, sourceBytes = 4194304) {
|
|
631
1004
|
const execute = tool.execute;
|
|
632
1005
|
return {
|
|
@@ -634,12 +1007,11 @@ var QueryCursorCache = class extends Map {
|
|
|
634
1007
|
execute: (input, call) => this.run(input, call, async () => await execute(input, call), sourceBytes)
|
|
635
1008
|
};
|
|
636
1009
|
}
|
|
637
|
-
|
|
638
|
-
async prepare(initial, content) {
|
|
1010
|
+
async prepare(initial, metadata) {
|
|
639
1011
|
const root = this.roots.get(initial);
|
|
640
1012
|
if (!root || root.closing) throw new Error("cursor_invalid");
|
|
641
1013
|
root.lease.signal.throwIfAborted();
|
|
642
|
-
const bytes = 2048 + 2 *
|
|
1014
|
+
const bytes = 2048 + 2 * JSON.stringify(metadata).length;
|
|
643
1015
|
const additional = this.total(root) - root.pendingBytes + bytes - root.heldBytes;
|
|
644
1016
|
if (additional > 0) {
|
|
645
1017
|
await root.lease.grow(root.call, {
|
|
@@ -650,7 +1022,6 @@ var QueryCursorCache = class extends Map {
|
|
|
650
1022
|
}
|
|
651
1023
|
root.pendingBytes = bytes;
|
|
652
1024
|
}
|
|
653
|
-
/** Awaits metadata admission before installing a new cursor. */
|
|
654
1025
|
async save(key, value) {
|
|
655
1026
|
const root = this.roots.get(this.facts(value).initial);
|
|
656
1027
|
if (!root || root.closing) throw new Error("cursor_invalid");
|
|
@@ -676,12 +1047,10 @@ var QueryCursorCache = class extends Map {
|
|
|
676
1047
|
}
|
|
677
1048
|
return deleted;
|
|
678
1049
|
}
|
|
679
|
-
/** Drops retained metadata before releasing its shared reservation. */
|
|
680
1050
|
clear() {
|
|
681
1051
|
for (const root of [...this.roots.values()]) this.invalidate(root);
|
|
682
1052
|
}
|
|
683
1053
|
};
|
|
684
|
-
/** Applies a tighter owner-local memory ceiling while preserving shared resident accounting. */
|
|
685
1054
|
function trimCursorCache(entries, retained) {
|
|
686
1055
|
let bytes = 0;
|
|
687
1056
|
for (const entry of entries.values()) bytes += bytesOf(retained(entry));
|
|
@@ -694,7 +1063,6 @@ function trimCursorCache(entries, retained) {
|
|
|
694
1063
|
}
|
|
695
1064
|
//#endregion
|
|
696
1065
|
//#region src/schedule/pages.ts
|
|
697
|
-
/** Metadata pages use keyset reads; explicit details use only the requested definitions. */
|
|
698
1066
|
const Tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired delivery tokens; the host may allocate fewer.");
|
|
699
1067
|
const Continue = z.strictObject({
|
|
700
1068
|
cursor: z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque continuation from next.arguments. Use alone, without changing the query."),
|
|
@@ -705,27 +1073,9 @@ const Start = z.strictObject({
|
|
|
705
1073
|
outputTokens: Tokens
|
|
706
1074
|
});
|
|
707
1075
|
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
1076
|
function failure$1(code, message, next = null) {
|
|
727
1077
|
return {
|
|
728
|
-
|
|
1078
|
+
data: {
|
|
729
1079
|
ok: false,
|
|
730
1080
|
error: {
|
|
731
1081
|
code,
|
|
@@ -733,22 +1083,35 @@ function failure$1(code, message, next = null) {
|
|
|
733
1083
|
retryable: next !== null
|
|
734
1084
|
},
|
|
735
1085
|
next
|
|
736
|
-
}
|
|
1086
|
+
},
|
|
1087
|
+
execution: { state: "not-started" },
|
|
737
1088
|
isError: true
|
|
738
1089
|
};
|
|
739
1090
|
}
|
|
740
1091
|
function cursorStore(resources) {
|
|
741
1092
|
const states = new QueryCursorCache((state) => ({
|
|
742
1093
|
initial: state.query.initial,
|
|
743
|
-
|
|
1094
|
+
metadata: state.selection
|
|
744
1095
|
}), resources);
|
|
745
1096
|
return {
|
|
746
|
-
wrap: (tool) =>
|
|
747
|
-
|
|
1097
|
+
wrap: (tool) => {
|
|
1098
|
+
const wrapped = states.wrap(tool);
|
|
1099
|
+
return {
|
|
1100
|
+
...wrapped,
|
|
1101
|
+
async execute(input, ctx) {
|
|
1102
|
+
const result = await wrapped.execute(input, ctx);
|
|
1103
|
+
if (!("data" in result) || !result.isError) return result;
|
|
1104
|
+
const prepared = scheduleResult(result.data, tool.name === "schedule_list" ? "list" : "read", result.execution.state);
|
|
1105
|
+
await accept(ctx, prepared, ctx.signal);
|
|
1106
|
+
return prepared;
|
|
1107
|
+
}
|
|
1108
|
+
};
|
|
1109
|
+
},
|
|
1110
|
+
prepare: (initial, metadata) => states.prepare(initial, metadata),
|
|
748
1111
|
trim() {
|
|
749
1112
|
trimCursorCache(states, (state) => ({
|
|
750
1113
|
initial: state.query.initial,
|
|
751
|
-
|
|
1114
|
+
metadata: state.selection
|
|
752
1115
|
}));
|
|
753
1116
|
},
|
|
754
1117
|
get(cursor, ctx) {
|
|
@@ -772,7 +1135,7 @@ function cursorStore(resources) {
|
|
|
772
1135
|
});
|
|
773
1136
|
trimCursorCache(states, (state) => ({
|
|
774
1137
|
initial: state.query.initial,
|
|
775
|
-
|
|
1138
|
+
metadata: state.selection
|
|
776
1139
|
}));
|
|
777
1140
|
return true;
|
|
778
1141
|
}
|
|
@@ -782,30 +1145,16 @@ function expired(state) {
|
|
|
782
1145
|
const now = performance.now();
|
|
783
1146
|
return now - state.used > 6e5 || now - state.created > 36e5;
|
|
784
1147
|
}
|
|
785
|
-
function
|
|
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) {
|
|
1148
|
+
function listSchedulesTool(triggers, next = () => ({}), resources, paused = () => ({})) {
|
|
801
1149
|
const cursors = cursorStore(resources);
|
|
802
1150
|
return cursors.wrap({
|
|
803
1151
|
name: "schedule_list",
|
|
804
1152
|
preload: false,
|
|
805
1153
|
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
1154
|
inputSchema: ListInput,
|
|
807
|
-
outputSchema: toolOutputSchema(
|
|
1155
|
+
outputSchema: toolOutputSchema(ScheduleListDataSchema, ListInput, "schedule_list"),
|
|
808
1156
|
deliveryKind: "exact-page",
|
|
1157
|
+
formatModel: documents.formatModel,
|
|
809
1158
|
async execute(input, ctx) {
|
|
810
1159
|
ctx.signal.throwIfAborted();
|
|
811
1160
|
let saved, query;
|
|
@@ -829,10 +1178,8 @@ function listSchedulesTool(triggers, next = () => ({}), resources) {
|
|
|
829
1178
|
tool: "schedule_list",
|
|
830
1179
|
arguments: query.initial
|
|
831
1180
|
});
|
|
832
|
-
const
|
|
833
|
-
|
|
834
|
-
const times = next(), cursor = randomUUID();
|
|
835
|
-
const build = (count) => ({ content: JSON.stringify({
|
|
1181
|
+
const times = saved?.selection?.times ?? next(), pauses = saved?.selection?.paused ?? paused(), cursor = saved?.selection?.cursor ?? randomUUID();
|
|
1182
|
+
const build = (count) => scheduleResult({
|
|
836
1183
|
ok: true,
|
|
837
1184
|
complete: count === source.items.length && source.complete,
|
|
838
1185
|
items: source.items.slice(0, count).map((row) => ({
|
|
@@ -840,18 +1187,19 @@ function listSchedulesTool(triggers, next = () => ({}), resources) {
|
|
|
840
1187
|
name: row.name,
|
|
841
1188
|
enabled: row.enabled,
|
|
842
1189
|
nextRun: times[row.id] === void 0 || times[row.id] === null ? null : new Date(times[row.id]).toISOString(),
|
|
1190
|
+
paused: pauses[row.id] ?? null,
|
|
843
1191
|
scopeSummary: { detailsAvailable: true }
|
|
844
1192
|
})),
|
|
845
1193
|
next: count === source.items.length && source.complete ? null : {
|
|
846
1194
|
tool: "schedule_list",
|
|
847
1195
|
arguments: { cursor }
|
|
848
1196
|
},
|
|
849
|
-
effective: { outputTokens: ctx.output.outputTokens }
|
|
850
|
-
}
|
|
851
|
-
let count = source.items.length, result = build(count);
|
|
852
|
-
while (count > 0 &&
|
|
853
|
-
if (count === 0 && source.items.length > 0 ||
|
|
854
|
-
const cost =
|
|
1197
|
+
effective: { outputTokens: saved?.selection?.outputTokens ?? ctx.output.outputTokens }
|
|
1198
|
+
}, "list");
|
|
1199
|
+
let count = saved?.selection?.count ?? source.items.length, result = build(count);
|
|
1200
|
+
while (!saved?.selection && count > 0 && await measure(ctx, result, ctx.signal) > ctx.output.outputTokens) result = build(--count);
|
|
1201
|
+
if (count === 0 && source.items.length > 0 || await measure(ctx, result, ctx.signal) > ctx.output.outputTokens) {
|
|
1202
|
+
const cost = await measure(ctx, build(Math.min(1, source.items.length)), ctx.signal);
|
|
855
1203
|
return failure$1("page_too_small", "A complete summary does not fit.", cost <= ctx.output.maximumTokens ? {
|
|
856
1204
|
tool: "schedule_list",
|
|
857
1205
|
arguments: {
|
|
@@ -860,14 +1208,20 @@ function listSchedulesTool(triggers, next = () => ({}), resources) {
|
|
|
860
1208
|
}
|
|
861
1209
|
} : null);
|
|
862
1210
|
}
|
|
863
|
-
if (!(count === source.items.length && source.complete) && !await cursors.set(cursor, {
|
|
1211
|
+
if (!(count === source.items.length && source.complete) && !saved?.selection && !await cursors.set(cursor, {
|
|
864
1212
|
...query,
|
|
865
1213
|
after: source.items[count - 1]?.id
|
|
866
1214
|
}, ctx, saved?.created)) return failure$1("step_budget_exhausted", "Summary cursor capacity is full.");
|
|
867
|
-
await cursors.prepare(query.initial, result.
|
|
868
|
-
ctx.
|
|
1215
|
+
await cursors.prepare(query.initial, result.data);
|
|
1216
|
+
await accept(ctx, result, ctx.signal);
|
|
869
1217
|
if (saved) {
|
|
870
|
-
saved.
|
|
1218
|
+
saved.selection ??= {
|
|
1219
|
+
count,
|
|
1220
|
+
cursor,
|
|
1221
|
+
outputTokens: ctx.output.outputTokens,
|
|
1222
|
+
times: Object.fromEntries(source.items.slice(0, count).map((row) => [row.id, times[row.id] ?? null])),
|
|
1223
|
+
paused: pauses
|
|
1224
|
+
};
|
|
871
1225
|
cursors.trim();
|
|
872
1226
|
saved.used = performance.now();
|
|
873
1227
|
}
|
|
@@ -875,42 +1229,22 @@ function listSchedulesTool(triggers, next = () => ({}), resources) {
|
|
|
875
1229
|
}
|
|
876
1230
|
});
|
|
877
1231
|
}
|
|
878
|
-
const Field = z.enum(["instruction", "scopes"]);
|
|
879
1232
|
const ReadStart = z.strictObject({
|
|
880
1233
|
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(
|
|
1234
|
+
fields: z.array(ScheduleField).min(1).max(2).default(["instruction", "scopes"]).describe("Explicit detail fields. Scopes are JSON text and never grant authority; default instruction and scopes."),
|
|
882
1235
|
outputTokens: Tokens
|
|
883
1236
|
});
|
|
884
1237
|
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
1238
|
function readScheduleTool(triggers, resources) {
|
|
906
1239
|
const cursors = cursorStore(resources);
|
|
907
1240
|
return cursors.wrap({
|
|
908
1241
|
name: "schedule_read",
|
|
909
1242
|
preload: false,
|
|
910
|
-
description: "Read instructions or scope details for 1
|
|
1243
|
+
description: "Read instructions or scope details for 1\u201316 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
1244
|
inputSchema: ReadInput,
|
|
912
|
-
outputSchema: toolOutputSchema(
|
|
1245
|
+
outputSchema: toolOutputSchema(ScheduleReadDataSchema, ReadInput, "schedule_read"),
|
|
913
1246
|
deliveryKind: "exact-page",
|
|
1247
|
+
formatModel: documents.formatModel,
|
|
914
1248
|
async execute(input, ctx) {
|
|
915
1249
|
ctx.signal.throwIfAborted();
|
|
916
1250
|
const version = triggers.page(ctx, { limit: 1 }).queryVersion;
|
|
@@ -934,8 +1268,6 @@ function readScheduleTool(triggers, resources) {
|
|
|
934
1268
|
tool: "schedule_read",
|
|
935
1269
|
arguments: query.initial
|
|
936
1270
|
});
|
|
937
|
-
const cached = saved && replay(saved, ctx, "schedule_read", input);
|
|
938
|
-
if (cached) return cached;
|
|
939
1271
|
const id = query.initial.ids[query.index], field = query.initial.fields[query.field];
|
|
940
1272
|
const source = triggers.get(ctx, id);
|
|
941
1273
|
if (!source) return failure$1("source_changed", "A requested schedule is absent or inaccessible; refresh the summary list.");
|
|
@@ -943,19 +1275,29 @@ function readScheduleTool(triggers, resources) {
|
|
|
943
1275
|
tool: "schedule_read",
|
|
944
1276
|
arguments: query.initial
|
|
945
1277
|
});
|
|
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
|
|
1278
|
+
const window = unicodeWindow(field === "instruction" ? source.instruction : JSON.stringify(source.scope), query.offset, saved?.selection?.count ?? Math.min(32768, Math.max(1, ctx.output.outputTokens * 4)));
|
|
1279
|
+
const body = await captureTextBody(window.points.join(""), ctx);
|
|
1280
|
+
ctx.signal.throwIfAborted();
|
|
1281
|
+
if (triggers.page(ctx, { limit: 1 }).queryVersion !== query.version) return failure$1("source_changed", "Schedule definition changed while capturing its original field; restart.", {
|
|
1282
|
+
tool: "schedule_read",
|
|
1283
|
+
arguments: query.initial
|
|
1284
|
+
});
|
|
1285
|
+
const byteEnds = [0];
|
|
1286
|
+
for (const point of window.points) byteEnds.push(byteEnds.at(-1) + Buffer.byteLength(point));
|
|
1287
|
+
const points = window.points, cursor = saved?.selection?.cursor ?? randomUUID();
|
|
948
1288
|
const build = (count) => {
|
|
949
1289
|
const fieldComplete = window.complete && count === points.length;
|
|
950
1290
|
const complete = fieldComplete && query.field + 1 === query.initial.fields.length && query.index + 1 === query.initial.ids.length;
|
|
951
|
-
return
|
|
1291
|
+
return scheduleResult({
|
|
952
1292
|
ok: true,
|
|
953
1293
|
complete,
|
|
954
1294
|
items: [{
|
|
955
1295
|
index: query.index,
|
|
956
1296
|
id,
|
|
957
1297
|
field,
|
|
958
|
-
|
|
1298
|
+
body,
|
|
1299
|
+
startByte: 0,
|
|
1300
|
+
endByte: byteEnds[count],
|
|
959
1301
|
offset: query.offset,
|
|
960
1302
|
length: count,
|
|
961
1303
|
complete: fieldComplete
|
|
@@ -964,18 +1306,18 @@ function readScheduleTool(triggers, resources) {
|
|
|
964
1306
|
tool: "schedule_read",
|
|
965
1307
|
arguments: { cursor }
|
|
966
1308
|
},
|
|
967
|
-
effective: { outputTokens: ctx.output.outputTokens }
|
|
968
|
-
})
|
|
1309
|
+
effective: { outputTokens: saved?.selection?.outputTokens ?? ctx.output.outputTokens }
|
|
1310
|
+
}, "read");
|
|
969
1311
|
};
|
|
970
|
-
let low = 0, high = points.length;
|
|
1312
|
+
let low = saved?.selection?.count ?? 0, high = points.length;
|
|
971
1313
|
while (low < high) {
|
|
972
1314
|
const middle = Math.ceil((low + high) / 2);
|
|
973
|
-
if (
|
|
1315
|
+
if (await measure(ctx, build(middle), ctx.signal) <= ctx.output.outputTokens) low = middle;
|
|
974
1316
|
else high = middle - 1;
|
|
975
1317
|
}
|
|
976
1318
|
const result = build(low);
|
|
977
|
-
if (low === 0 && points.length > 0 ||
|
|
978
|
-
const cost =
|
|
1319
|
+
if (low === 0 && points.length > 0 || await measure(ctx, result, ctx.signal) > ctx.output.outputTokens) {
|
|
1320
|
+
const cost = await measure(ctx, build(Math.min(1, points.length)), ctx.signal);
|
|
979
1321
|
return failure$1("page_too_small", "The detail envelope and one code point do not fit.", cost <= ctx.output.maximumTokens ? {
|
|
980
1322
|
tool: "schedule_read",
|
|
981
1323
|
arguments: {
|
|
@@ -986,16 +1328,20 @@ function readScheduleTool(triggers, resources) {
|
|
|
986
1328
|
}
|
|
987
1329
|
const fieldComplete = window.complete && low === points.length;
|
|
988
1330
|
const memberComplete = fieldComplete && query.field + 1 === query.initial.fields.length;
|
|
989
|
-
if (!(memberComplete && query.index + 1 === query.initial.ids.length) && !await cursors.set(cursor, {
|
|
1331
|
+
if (!(memberComplete && query.index + 1 === query.initial.ids.length) && !saved?.selection && !await cursors.set(cursor, {
|
|
990
1332
|
...query,
|
|
991
1333
|
index: memberComplete ? query.index + 1 : query.index,
|
|
992
1334
|
field: memberComplete ? 0 : fieldComplete ? query.field + 1 : query.field,
|
|
993
1335
|
offset: fieldComplete ? 0 : query.offset + low
|
|
994
1336
|
}, ctx, saved?.created)) return failure$1("step_budget_exhausted", "Detail cursor capacity is full.");
|
|
995
|
-
await cursors.prepare(query.initial, result.
|
|
996
|
-
ctx.
|
|
1337
|
+
await cursors.prepare(query.initial, result.data);
|
|
1338
|
+
await accept(ctx, result, ctx.signal);
|
|
997
1339
|
if (saved) {
|
|
998
|
-
saved.
|
|
1340
|
+
saved.selection ??= {
|
|
1341
|
+
count: low,
|
|
1342
|
+
cursor,
|
|
1343
|
+
outputTokens: ctx.output.outputTokens
|
|
1344
|
+
};
|
|
999
1345
|
cursors.trim();
|
|
1000
1346
|
saved.used = performance.now();
|
|
1001
1347
|
}
|
|
@@ -1003,7 +1349,6 @@ function readScheduleTool(triggers, resources) {
|
|
|
1003
1349
|
}
|
|
1004
1350
|
});
|
|
1005
1351
|
}
|
|
1006
|
-
/** Builds a bounded Unicode window without allocating an array for the complete source. */
|
|
1007
1352
|
function unicodeWindow(text, offset, maximum) {
|
|
1008
1353
|
let unit = 0, skipped = 0;
|
|
1009
1354
|
while (unit < text.length && skipped < offset) {
|
|
@@ -1021,11 +1366,16 @@ function unicodeWindow(text, offset, maximum) {
|
|
|
1021
1366
|
complete: unit === text.length
|
|
1022
1367
|
};
|
|
1023
1368
|
}
|
|
1369
|
+
const documents = createTextDocuments(scheduleDocument);
|
|
1370
|
+
async function measure(ctx, result, _signal) {
|
|
1371
|
+
return ctx.output.measure(result, await documents.prepare(result.data, ctx), ctx.signal);
|
|
1372
|
+
}
|
|
1373
|
+
async function accept(ctx, result, _signal) {
|
|
1374
|
+
await ctx.output.acceptExact(result, await documents.prepare(result.data, ctx), ctx.signal);
|
|
1375
|
+
}
|
|
1024
1376
|
//#endregion
|
|
1025
1377
|
//#region src/schedule/settings.ts
|
|
1026
|
-
/** The most tasks a limit may name short of no limit. */
|
|
1027
1378
|
const AGENT_LIMIT_CEILING = 1e3;
|
|
1028
|
-
/** The settings on the wire and on disk. `agentLimit` `0` is no limit. */
|
|
1029
1379
|
const ScheduleSettings = z.strictObject({ agentLimit: z.number().int().min(0).max(AGENT_LIMIT_CEILING) });
|
|
1030
1380
|
const DEFAULT_SCHEDULE_SETTINGS = { agentLimit: 20 };
|
|
1031
1381
|
const LOCAL_TABLE = "settings";
|
|
@@ -1070,14 +1420,6 @@ function parse(raw) {
|
|
|
1070
1420
|
}
|
|
1071
1421
|
//#endregion
|
|
1072
1422
|
//#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
1423
|
const TRIGGERS_SERVICE = "triggers";
|
|
1082
1424
|
const OnceRule = z.object({
|
|
1083
1425
|
kind: z.literal("once").describe("Run once at the supplied at timestamp."),
|
|
@@ -1092,6 +1434,11 @@ const CronRule = z.object({
|
|
|
1092
1434
|
expression: z.string().min(1).describe("Required for cron: five fields, e.g. 0 9 * * 1-5"),
|
|
1093
1435
|
timezone: z.string().min(1).describe("Required for cron: IANA time zone, e.g. Asia/Singapore")
|
|
1094
1436
|
});
|
|
1437
|
+
const RuleVariant = z.discriminatedUnion("kind", [
|
|
1438
|
+
OnceRule,
|
|
1439
|
+
IntervalRule,
|
|
1440
|
+
CronRule
|
|
1441
|
+
]);
|
|
1095
1442
|
const Rule = z.object({
|
|
1096
1443
|
kind: z.enum([
|
|
1097
1444
|
"once",
|
|
@@ -1104,6 +1451,7 @@ const Rule = z.object({
|
|
|
1104
1451
|
timezone: CronRule.shape.timezone.optional()
|
|
1105
1452
|
}, { error: "rule must be a JSON object, for example {\"kind\":\"interval\",\"everyMinutes\":15}" }).meta({
|
|
1106
1453
|
description: "Schedule rule object. Use kind once with at; interval with everyMinutes; or cron with expression and timezone.",
|
|
1454
|
+
allOf: [z.toJSONSchema(RuleVariant, { io: "input" })],
|
|
1107
1455
|
examples: [{
|
|
1108
1456
|
kind: "interval",
|
|
1109
1457
|
everyMinutes: 15
|
|
@@ -1112,11 +1460,7 @@ const Rule = z.object({
|
|
|
1112
1460
|
expression: "0 9 * * *",
|
|
1113
1461
|
timezone: "Asia/Singapore"
|
|
1114
1462
|
}]
|
|
1115
|
-
}).pipe(
|
|
1116
|
-
OnceRule,
|
|
1117
|
-
IntervalRule,
|
|
1118
|
-
CronRule
|
|
1119
|
-
]));
|
|
1463
|
+
}).pipe(RuleVariant);
|
|
1120
1464
|
const Scope = z.array(z.object({
|
|
1121
1465
|
kind: z.enum([
|
|
1122
1466
|
"read",
|
|
@@ -1127,25 +1471,25 @@ const Scope = z.array(z.object({
|
|
|
1127
1471
|
target: z.string().min(1).describe("absolute path, * for network, or a host")
|
|
1128
1472
|
})).max(100).describe("Requested run permissions, at most 100 entries; changes require approval.");
|
|
1129
1473
|
const CreateInput = z.object({
|
|
1130
|
-
name: z.string().trim().min(1).max(80).describe("Task display name, 1
|
|
1474
|
+
name: z.string().trim().min(1).max(80).describe("Task display name, 1\u201380 UTF-16 code units after trimming."),
|
|
1131
1475
|
rule: Rule,
|
|
1132
|
-
instruction: z.string().trim().min(1).max(8e3).describe("Instruction executed when due, 1
|
|
1476
|
+
instruction: z.string().trim().min(1).max(8e3).describe("Instruction executed when due, 1\u20138000 UTF-16 code units after trimming."),
|
|
1133
1477
|
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
1478
|
catchUp: z.boolean().optional().describe("Whether missed due runs execute after startup; creation defaults to true, update omission retains current behavior."),
|
|
1135
1479
|
scope: Scope.optional()
|
|
1136
1480
|
});
|
|
1137
1481
|
const UpdateInput = z.object({
|
|
1138
1482
|
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
|
|
1483
|
+
name: z.string().trim().min(1).max(80).optional().describe("Replacement task name, 1\u201380 UTF-16 code units after trimming; omit to retain."),
|
|
1140
1484
|
rule: Rule.optional(),
|
|
1141
|
-
instruction: z.string().trim().min(1).max(8e3).optional().describe("Replacement instruction, 1
|
|
1485
|
+
instruction: z.string().trim().min(1).max(8e3).optional().describe("Replacement instruction, 1\u20138000 UTF-16 code units after trimming; omit to retain."),
|
|
1142
1486
|
target: z.enum(["this-session", "new-session"]).optional().describe("Replacement run destination; omit to retain."),
|
|
1143
1487
|
catchUp: z.boolean().optional().describe("Whether missed due runs execute after startup; creation defaults to true, update omission retains current behavior."),
|
|
1144
1488
|
scope: Scope.optional()
|
|
1145
1489
|
});
|
|
1146
1490
|
const DeleteInput = z.object({
|
|
1147
1491
|
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
|
|
1492
|
+
ids: z.array(z.string().min(1)).min(1).max(64).describe("Readable task ids to delete, 1\u201364, under one approval.")
|
|
1149
1493
|
}).strict().refine((input) => new TextEncoder().encode(JSON.stringify(input)).byteLength <= 8388608, "batch input exceeds 8 MiB");
|
|
1150
1494
|
function toRule(rule, now) {
|
|
1151
1495
|
switch (rule.kind) {
|
|
@@ -1165,7 +1509,6 @@ function toRule(rule, now) {
|
|
|
1165
1509
|
case "cron": return rule;
|
|
1166
1510
|
}
|
|
1167
1511
|
}
|
|
1168
|
-
/** One line a person reads in the approval: when this runs. */
|
|
1169
1512
|
function describeRule(rule) {
|
|
1170
1513
|
switch (rule.kind) {
|
|
1171
1514
|
case "once": return `once at ${new Date(rule.at).toISOString()}`;
|
|
@@ -1173,46 +1516,75 @@ function describeRule(rule) {
|
|
|
1173
1516
|
case "cron": return `cron ${rule.expression} (${rule.timezone})`;
|
|
1174
1517
|
}
|
|
1175
1518
|
}
|
|
1176
|
-
function answer(outcome, next, changedFields) {
|
|
1519
|
+
function answer(outcome, next, changedFields, action) {
|
|
1177
1520
|
switch (outcome.kind) {
|
|
1178
1521
|
case "ask": return outcome.result;
|
|
1179
|
-
case "refused": return {
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1522
|
+
case "refused": return scheduleResult({
|
|
1523
|
+
ok: false,
|
|
1524
|
+
error: {
|
|
1525
|
+
code: "schedule_refused",
|
|
1526
|
+
message: [...outcome.message].slice(0, 512).join(""),
|
|
1527
|
+
retryable: false
|
|
1528
|
+
},
|
|
1529
|
+
next: null
|
|
1530
|
+
}, action, "not-started");
|
|
1531
|
+
case "done": {
|
|
1532
|
+
let nextRunAt = null, nextRunKnown = true;
|
|
1533
|
+
try {
|
|
1534
|
+
const at = next()[outcome.trigger.id];
|
|
1535
|
+
nextRunAt = at == null ? null : new Date(at).toISOString();
|
|
1536
|
+
} catch {
|
|
1537
|
+
nextRunKnown = false;
|
|
1538
|
+
}
|
|
1539
|
+
const config = storedConfig(outcome.trigger.config);
|
|
1540
|
+
return scheduleResult({
|
|
1541
|
+
ok: true,
|
|
1542
|
+
committed: true,
|
|
1543
|
+
id: outcome.trigger.id,
|
|
1544
|
+
name: outcome.trigger.name,
|
|
1545
|
+
rule: config?.rule ?? null,
|
|
1546
|
+
catchUp: config?.catchUp ?? null,
|
|
1547
|
+
updatedAt: outcome.trigger.updatedAt,
|
|
1548
|
+
enabled: outcome.trigger.enabled,
|
|
1549
|
+
nextRunAt,
|
|
1550
|
+
nextRunKnown,
|
|
1551
|
+
changedFields
|
|
1552
|
+
}, action);
|
|
1553
|
+
}
|
|
1191
1554
|
}
|
|
1192
1555
|
}
|
|
1193
|
-
function failure(error) {
|
|
1556
|
+
function failure(error, action, state = "unknown") {
|
|
1194
1557
|
const text = (error instanceof Error ? error.message : String(error)).slice(0, 512);
|
|
1195
1558
|
const last = text.charCodeAt(text.length - 1);
|
|
1196
|
-
return {
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1559
|
+
return scheduleResult({
|
|
1560
|
+
ok: false,
|
|
1561
|
+
error: {
|
|
1562
|
+
code: "schedule_failed",
|
|
1563
|
+
message: last >= 55296 && last <= 56319 ? text.slice(0, -1) : text,
|
|
1564
|
+
retryable: false
|
|
1565
|
+
},
|
|
1566
|
+
next: null
|
|
1567
|
+
}, action, state);
|
|
1200
1568
|
}
|
|
1201
1569
|
function createScheduleTool(triggers, agentLimit, next = () => ({})) {
|
|
1570
|
+
const documents = createTextDocuments(scheduleDocument);
|
|
1202
1571
|
return {
|
|
1203
1572
|
name: "schedule_create",
|
|
1204
1573
|
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
|
|
1574
|
+
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\u2019s runs and is always shown to the user.",
|
|
1206
1575
|
inputSchema: CreateInput,
|
|
1207
|
-
outputSchema: toolOutputSchema(
|
|
1576
|
+
outputSchema: toolOutputSchema(ScheduleReceiptSchema, CreateInput, "schedule_create"),
|
|
1208
1577
|
deliveryKind: "receipt",
|
|
1578
|
+
formatModel: documents.formatModel,
|
|
1209
1579
|
async execute(input, ctx) {
|
|
1580
|
+
let submitted = false;
|
|
1210
1581
|
try {
|
|
1211
1582
|
const limit = agentLimit();
|
|
1212
1583
|
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`));
|
|
1584
|
+
if (triggers.countCreated(ctx) >= limit) return failure(/* @__PURE__ */ new Error(`this agent already has ${limit} scheduled tasks in this workspace; delete one first`), "create", "not-started");
|
|
1214
1585
|
}
|
|
1215
1586
|
const rule = toRule(input.rule, Date.now());
|
|
1587
|
+
submitted = true;
|
|
1216
1588
|
return answer(triggers.create(ctx, {
|
|
1217
1589
|
kind: SOURCE_KIND,
|
|
1218
1590
|
name: input.name,
|
|
@@ -1224,22 +1596,25 @@ function createScheduleTool(triggers, agentLimit, next = () => ({})) {
|
|
|
1224
1596
|
instruction: input.instruction,
|
|
1225
1597
|
target: input.target,
|
|
1226
1598
|
...input.scope === void 0 ? {} : { scope: input.scope }
|
|
1227
|
-
}), next, Object.keys(input));
|
|
1599
|
+
}), next, Object.keys(input), "create");
|
|
1228
1600
|
} catch (error) {
|
|
1229
|
-
return failure(error);
|
|
1601
|
+
return failure(error, "create", submitted ? "unknown" : "not-started");
|
|
1230
1602
|
}
|
|
1231
1603
|
}
|
|
1232
1604
|
};
|
|
1233
1605
|
}
|
|
1234
1606
|
function updateScheduleTool(triggers, next = () => ({})) {
|
|
1607
|
+
const documents = createTextDocuments(scheduleDocument);
|
|
1235
1608
|
return {
|
|
1236
1609
|
name: "schedule_update",
|
|
1237
1610
|
preload: false,
|
|
1238
1611
|
description: "Change a scheduled task you created. Changing what it does, when, where, or widening its scope may ask the user.",
|
|
1239
1612
|
inputSchema: UpdateInput,
|
|
1240
|
-
outputSchema: toolOutputSchema(
|
|
1613
|
+
outputSchema: toolOutputSchema(ScheduleReceiptSchema, UpdateInput, "schedule_update"),
|
|
1241
1614
|
deliveryKind: "receipt",
|
|
1615
|
+
formatModel: documents.formatModel,
|
|
1242
1616
|
async execute(input, ctx) {
|
|
1617
|
+
let submitted = false;
|
|
1243
1618
|
try {
|
|
1244
1619
|
const { id, rule, catchUp, ...rest } = input;
|
|
1245
1620
|
const patch = Object.fromEntries(Object.entries(rest).filter(([, value]) => value !== void 0));
|
|
@@ -1248,50 +1623,47 @@ function updateScheduleTool(triggers, next = () => ({})) {
|
|
|
1248
1623
|
rule: rule === void 0 ? current.rule : toRule(rule, Date.now()),
|
|
1249
1624
|
catchUp: catchUp ?? current.catchUp
|
|
1250
1625
|
};
|
|
1626
|
+
submitted = true;
|
|
1251
1627
|
return answer(triggers.update(ctx, id, {
|
|
1252
1628
|
...patch,
|
|
1253
1629
|
...config === void 0 ? {} : { config },
|
|
1254
1630
|
...current === void 0 ? {} : { summary: describeRule((config ?? current).rule) }
|
|
1255
|
-
}), next, Object.keys(input).filter((key) => key !== "id"));
|
|
1631
|
+
}), next, Object.keys(input).filter((key) => key !== "id"), "update");
|
|
1256
1632
|
} catch (error) {
|
|
1257
|
-
return failure(error);
|
|
1633
|
+
return failure(error, "update", submitted ? "unknown" : "not-started");
|
|
1258
1634
|
}
|
|
1259
1635
|
}
|
|
1260
1636
|
};
|
|
1261
1637
|
}
|
|
1262
|
-
/** Deletes an owned schedule collection atomically and returns its durable operation receipt. */
|
|
1263
1638
|
function deleteScheduleTool(triggers) {
|
|
1639
|
+
const documents = createTextDocuments(scheduleDocument);
|
|
1264
1640
|
return {
|
|
1265
1641
|
name: "schedule_delete",
|
|
1266
1642
|
preload: false,
|
|
1267
|
-
description: "Delete 1
|
|
1643
|
+
description: "Delete 1\u201364 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
1644
|
inputSchema: DeleteInput,
|
|
1269
|
-
outputSchema: toolOutputSchema(
|
|
1270
|
-
operationState: z.literal("committed"),
|
|
1271
|
-
operationId: z.uuid(),
|
|
1272
|
-
value: z.strictObject({ removed: z.array(z.string()) })
|
|
1273
|
-
}), DeleteInput, "schedule_delete"),
|
|
1645
|
+
outputSchema: toolOutputSchema(ScheduleDeleteSchema, DeleteInput, "schedule_delete"),
|
|
1274
1646
|
deliveryKind: "receipt",
|
|
1647
|
+
formatModel: documents.formatModel,
|
|
1275
1648
|
async execute(input, ctx) {
|
|
1276
1649
|
try {
|
|
1277
|
-
return
|
|
1650
|
+
return scheduleResult(structuredClone(triggers.removeMany(ctx, input.ids, input.operationId)), "delete");
|
|
1278
1651
|
} catch (error) {
|
|
1279
|
-
return failure(error);
|
|
1652
|
+
return failure(error, "delete");
|
|
1280
1653
|
}
|
|
1281
1654
|
}
|
|
1282
1655
|
};
|
|
1283
1656
|
}
|
|
1284
|
-
function registerScheduleTools(ctx, register, agentLimit = () => DEFAULT_SCHEDULE_SETTINGS.agentLimit, next = () => ({})) {
|
|
1657
|
+
function registerScheduleTools(ctx, register, agentLimit = () => DEFAULT_SCHEDULE_SETTINGS.agentLimit, next = () => ({}), paused = () => ({})) {
|
|
1285
1658
|
const triggers = ctx.services.get(TRIGGERS_SERVICE);
|
|
1286
1659
|
register(createScheduleTool(triggers, agentLimit, next));
|
|
1287
|
-
register(listSchedulesTool(triggers, next, ctx.services.get("query-resources")));
|
|
1660
|
+
register(listSchedulesTool(triggers, next, ctx.services.get("query-resources"), paused));
|
|
1288
1661
|
register(readScheduleTool(triggers, ctx.services.get("query-resources")));
|
|
1289
1662
|
register(updateScheduleTool(triggers, next));
|
|
1290
1663
|
register(deleteScheduleTool(triggers));
|
|
1291
1664
|
}
|
|
1292
1665
|
//#endregion
|
|
1293
1666
|
//#region src/tool-names.ts
|
|
1294
|
-
/** Canonical names shared by tool registration and browser presentation. */
|
|
1295
1667
|
const TOOL_NAMES = [
|
|
1296
1668
|
"schedule_create",
|
|
1297
1669
|
"schedule_list",
|
|
@@ -1301,46 +1673,26 @@ const TOOL_NAMES = [
|
|
|
1301
1673
|
];
|
|
1302
1674
|
//#endregion
|
|
1303
1675
|
//#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
1676
|
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
1677
|
function browserModule() {
|
|
1331
1678
|
const path = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
1332
1679
|
return existsSync(path) ? path : void 0;
|
|
1333
1680
|
}
|
|
1334
1681
|
const schedulePlugin = {
|
|
1335
1682
|
name: "@eum-agent/automation-schedule",
|
|
1336
|
-
requires: [
|
|
1683
|
+
requires: [
|
|
1684
|
+
"query-resources",
|
|
1685
|
+
"triggers",
|
|
1686
|
+
"session-lifecycle"
|
|
1687
|
+
],
|
|
1337
1688
|
configSchema: ScheduleConfig,
|
|
1338
1689
|
apply(ctx, config) {
|
|
1339
1690
|
const disabled = new Set(config.disabled);
|
|
1340
1691
|
const register = (tool) => disabled.has(tool.name) ? void 0 : ctx.tools.register(tool);
|
|
1341
1692
|
const settings = openScheduleSettings(ctx);
|
|
1342
1693
|
let current = settings.read();
|
|
1343
|
-
|
|
1694
|
+
const source = registerScheduleSource(ctx);
|
|
1695
|
+
registerScheduleTools(ctx, register, () => current.agentLimit, source.next, source.paused);
|
|
1344
1696
|
ctx.client.registerMethod({
|
|
1345
1697
|
name: "getScheduleSettings",
|
|
1346
1698
|
description: "The scheduled-task settings: tasks one agent may create per workspace (0 is no limit).",
|
|
@@ -1360,7 +1712,10 @@ const schedulePlugin = {
|
|
|
1360
1712
|
});
|
|
1361
1713
|
ctx.tools.guide(GUIDANCE);
|
|
1362
1714
|
const uiModule = browserModule();
|
|
1363
|
-
if (uiModule !== void 0) ctx.client.
|
|
1715
|
+
if (uiModule !== void 0) ctx.client.registerPackageFiles({
|
|
1716
|
+
root: dirname(uiModule),
|
|
1717
|
+
entry: "ui.js"
|
|
1718
|
+
});
|
|
1364
1719
|
}
|
|
1365
1720
|
};
|
|
1366
1721
|
//#endregion
|