@runappsai/agent 0.1.11 → 0.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.
@@ -0,0 +1,505 @@
1
+ // Scheduled tasks: a prompt the agent runs on its own at set times — once,
2
+ // every N minutes, daily at a time (on chosen weekdays), or by a cron
3
+ // expression — kept per app, added and changed by the agent (its tools) or
4
+ // the user (the chat's Scheduled panel). They run in the page: while the
5
+ // app is open, a task that is due waits until the chat is idle and then
6
+ // runs; one that came due while the page was closed runs once when it is
7
+ // next opened. One tab runs a task (a Web Lock per task), the others see
8
+ // its next time move.
9
+ import { defineTool } from "./tool.js";
10
+ /** Tasks in localStorage under `key` (one JSON list); other tabs' changes arrive through the `storage` event. */
11
+ export function localSchedules(key) {
12
+ const read = () => {
13
+ try {
14
+ const v = JSON.parse(localStorage.getItem(key) || "[]");
15
+ return Array.isArray(v) ? v : [];
16
+ }
17
+ catch {
18
+ return [];
19
+ }
20
+ };
21
+ const write = (list) => {
22
+ try {
23
+ if (list.length)
24
+ localStorage.setItem(key, JSON.stringify(list));
25
+ else
26
+ localStorage.removeItem(key);
27
+ }
28
+ catch { /* private mode */ }
29
+ };
30
+ // Every write re-reads under one lock, so two tabs saving at once do not drop each other's change.
31
+ const change = (fn) => lock(`${key}:write`, async () => { write(fn(read())); });
32
+ return {
33
+ list: async () => read(),
34
+ get: async (id) => read().find((t) => t.id === id),
35
+ put: (task) => change((list) => { const i = list.findIndex((t) => t.id === task.id); if (i >= 0)
36
+ list[i] = task;
37
+ else
38
+ list.push(task); return list; }),
39
+ delete: (id) => change((list) => list.filter((t) => t.id !== id)),
40
+ subscribe(fn) {
41
+ if (typeof window === "undefined")
42
+ return () => { };
43
+ const on = (e) => { if (e.key === key)
44
+ fn(); };
45
+ window.addEventListener("storage", on);
46
+ return () => window.removeEventListener("storage", on);
47
+ },
48
+ };
49
+ }
50
+ /** Tasks in memory (tests, or an app that keeps them itself). */
51
+ export function memorySchedules(initial = []) {
52
+ const map = new Map(initial.map((t) => [t.id, structuredClone(t)]));
53
+ return {
54
+ list: async () => [...map.values()].map((t) => structuredClone(t)),
55
+ get: async (id) => { const t = map.get(id); return t && structuredClone(t); },
56
+ put: async (task) => { map.set(task.id, structuredClone(task)); },
57
+ delete: async (id) => { map.delete(id); },
58
+ };
59
+ }
60
+ const locks = () => (typeof navigator !== "undefined" ? navigator.locks : undefined);
61
+ function lock(name, fn) {
62
+ const l = locks();
63
+ return l ? l.request(name, {}, fn) : fn();
64
+ }
65
+ /** Runs `fn` holding `name` when no other tab holds it; false (fn not run) when one does. */
66
+ async function tryLock(name, fn) {
67
+ const l = locks();
68
+ if (!l) {
69
+ await fn();
70
+ return true;
71
+ }
72
+ let got = false;
73
+ await l.request(name, { ifAvailable: true }, async (held) => { if (!held)
74
+ return; got = true; await fn(); });
75
+ return got;
76
+ }
77
+ /* ------------------------------------------------------------------ */
78
+ /* Times */
79
+ /* ------------------------------------------------------------------ */
80
+ const HHMM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
81
+ /** A local "YYYY-MM-DD HH:mm" / "YYYY-MM-DDTHH:mm[:ss]" (or an ISO time with a zone) → ms; NaN when it is not one. */
82
+ export function parseLocalTime(s) {
83
+ const m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(s.trim());
84
+ if (m)
85
+ return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] ?? 0)).getTime();
86
+ return /[zZ]|[+-]\d{2}:?\d{2}$/.test(s) ? Date.parse(s) : NaN;
87
+ }
88
+ /** "2026-11-28 09:00" in local time. */
89
+ export function formatLocalTime(ms) {
90
+ const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
91
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
92
+ }
93
+ const CRON_NAMES = { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6, jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 };
94
+ /** Parses a five-field cron expression; throws a readable error. */
95
+ export function parseCron(expr) {
96
+ const f = expr.trim().split(/\s+/);
97
+ if (f.length !== 5)
98
+ throw new Error(`cron needs five fields (minute hour day month weekday), got "${expr}"`);
99
+ const field = (s, lo, hi, what) => {
100
+ const out = new Set();
101
+ for (const part of s.toLowerCase().split(",")) {
102
+ const [range, stepS] = part.split("/");
103
+ const step = stepS === undefined ? 1 : Number(stepS);
104
+ if (!Number.isInteger(step) || step < 1)
105
+ throw new Error(`cron ${what}: bad step in "${part}"`);
106
+ const num = (x) => { const n = CRON_NAMES[x] ?? Number(x); if (!Number.isInteger(n))
107
+ throw new Error(`cron ${what}: "${x}" is not a number`); return n; };
108
+ let a, b;
109
+ if (range === "*") {
110
+ a = lo;
111
+ b = hi;
112
+ }
113
+ else if (range.includes("-")) {
114
+ const [x, y] = range.split("-");
115
+ a = num(x);
116
+ b = num(y);
117
+ }
118
+ else {
119
+ a = num(range);
120
+ b = stepS === undefined ? a : hi;
121
+ }
122
+ if (what === "weekday") {
123
+ if (a === 7)
124
+ a = 0;
125
+ if (b === 7 && a !== 0)
126
+ b = 6, out.add(0);
127
+ }
128
+ if (a < lo || b > hi || a > b)
129
+ throw new Error(`cron ${what}: "${part}" is outside ${lo}-${hi}`);
130
+ for (let n = a; n <= b; n += step)
131
+ out.add(n);
132
+ }
133
+ return out;
134
+ };
135
+ return { min: field(f[0], 0, 59, "minute"), hour: field(f[1], 0, 23, "hour"), dom: field(f[2], 1, 31, "day"), mon: field(f[3], 1, 12, "month"), dow: field(f[4], 0, 7, "weekday"), domAny: f[2] === "*", dowAny: f[4] === "*" };
136
+ }
137
+ function cronNext(c, after) {
138
+ const start = new Date(after);
139
+ start.setSeconds(0, 0);
140
+ start.setMinutes(start.getMinutes() + 1);
141
+ const hours = [...c.hour].sort((a, b) => a - b), mins = [...c.min].sort((a, b) => a - b);
142
+ for (let day = 0; day < 366 * 5; day++) {
143
+ const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + day);
144
+ if (!c.mon.has(d.getMonth() + 1))
145
+ continue;
146
+ // Standard cron: with both day fields restricted, either may match.
147
+ const domOk = c.dom.has(d.getDate()), dowOk = c.dow.has(d.getDay());
148
+ if (!(c.domAny && c.dowAny ? true : c.domAny ? dowOk : c.dowAny ? domOk : domOk || dowOk))
149
+ continue;
150
+ for (const h of hours)
151
+ for (const m of mins) {
152
+ const t = new Date(d.getFullYear(), d.getMonth(), d.getDate(), h, m).getTime();
153
+ if (t >= start.getTime())
154
+ return t;
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+ /** Checks a schedule; returns a readable problem, or undefined when it is fine. `minMinutes` is the shortest repeat allowed. */
160
+ export function checkSchedule(s, minMinutes = 1) {
161
+ switch (s?.type) {
162
+ case "once": return Number.isFinite(parseLocalTime(s.at)) ? undefined : `"at" must be a local time like 2026-11-28 09:00, got "${s.at}"`;
163
+ case "every": return Number.isFinite(s.minutes) && s.minutes >= minMinutes ? undefined : `"minutes" must be at least ${minMinutes}`;
164
+ case "daily":
165
+ if (!HHMM.test(s.time ?? ""))
166
+ return `"time" must be HH:mm, got "${s.time}"`;
167
+ if (s.days && (!s.days.length || s.days.some((d) => !Number.isInteger(d) || d < 0 || d > 6)))
168
+ return `"days" must be weekday numbers 0 (Sunday) to 6`;
169
+ return undefined;
170
+ case "cron": {
171
+ try {
172
+ const c = parseCron(s.cron);
173
+ if (cronNext(c, Date.now()) === null)
174
+ return "this cron never runs";
175
+ }
176
+ catch (err) {
177
+ return err.message;
178
+ }
179
+ // Every minute is allowed only when the app allows it.
180
+ if (minMinutes > 1) {
181
+ const c = parseCron(s.cron);
182
+ const a = cronNext(c, Date.now()), b = cronNext(c, a);
183
+ if (b !== null && b - a < minMinutes * 60_000)
184
+ return `runs more often than every ${minMinutes} minutes`;
185
+ }
186
+ return undefined;
187
+ }
188
+ default: return `"type" must be once, every, daily or cron`;
189
+ }
190
+ }
191
+ /** The first run of `s` after `after` (ms); null when there is none (a one-off already past). `from` is when an "every" schedule last ran or was set. */
192
+ export function nextRun(s, after, from = after) {
193
+ switch (s.type) {
194
+ case "once": {
195
+ const t = parseLocalTime(s.at);
196
+ return Number.isFinite(t) && t > after ? t : null;
197
+ }
198
+ case "every": {
199
+ const p = s.minutes * 60_000;
200
+ let t = from + p;
201
+ if (t <= after)
202
+ t = after + p;
203
+ return t;
204
+ }
205
+ case "daily": {
206
+ const m = HHMM.exec(s.time);
207
+ if (!m)
208
+ return null;
209
+ const base = new Date(after);
210
+ for (let day = 0; day < 8; day++) {
211
+ const d = new Date(base.getFullYear(), base.getMonth(), base.getDate() + day, +m[1], +m[2]);
212
+ if (d.getTime() > after && (!s.days?.length || s.days.includes(d.getDay())))
213
+ return d.getTime();
214
+ }
215
+ return null;
216
+ }
217
+ case "cron": try {
218
+ return cronNext(parseCron(s.cron), after);
219
+ }
220
+ catch {
221
+ return null;
222
+ }
223
+ }
224
+ }
225
+ const DAY_EN = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], DAY_ZH = ["日", "一", "二", "三", "四", "五", "六"];
226
+ /** The schedule in words: "Every 30 min", "Daily 09:00", "Mon–Fri 09:00", "Once 2026-11-28 09:00", "cron 0 9 * * 1". */
227
+ export function describeSchedule(s, locale = "en") {
228
+ const zh = locale === "zh";
229
+ switch (s.type) {
230
+ case "once": {
231
+ const t = parseLocalTime(s.at);
232
+ return (zh ? "一次 · " : "Once · ") + (Number.isFinite(t) ? formatLocalTime(t) : s.at);
233
+ }
234
+ case "every": {
235
+ const m = s.minutes;
236
+ const v = m % 1440 === 0 ? (zh ? `${m / 1440} 天` : `${m / 1440} d`) : m % 60 === 0 ? (zh ? `${m / 60} 小时` : `${m / 60} h`) : (zh ? `${m} 分钟` : `${m} min`);
237
+ return zh ? `每 ${v}` : `Every ${v}`;
238
+ }
239
+ case "daily": {
240
+ const days = [...new Set(s.days ?? [])].sort((a, b) => a - b);
241
+ if (!days.length || days.length === 7)
242
+ return (zh ? "每天 " : "Daily ") + s.time;
243
+ if (days.join() === "1,2,3,4,5")
244
+ return (zh ? "工作日 " : "Weekdays ") + s.time;
245
+ if (days.join() === "0,6")
246
+ return (zh ? "周末 " : "Weekends ") + s.time;
247
+ return (zh ? "每周" + days.map((d) => DAY_ZH[d]).join("、") + " " : days.map((d) => DAY_EN[d]).join(", ") + " ") + s.time;
248
+ }
249
+ case "cron": return `cron ${s.cron}`;
250
+ }
251
+ }
252
+ const newTaskId = () => `t_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
253
+ /** Builds a task from a schedule and fields, checking them; throws a readable error. */
254
+ export function makeTask(fields, limits = {}, now = Date.now()) {
255
+ const name = fields.name?.trim(), prompt = fields.prompt?.trim();
256
+ if (!name)
257
+ throw new Error("a task needs a name");
258
+ if (!prompt)
259
+ throw new Error("a task needs a prompt");
260
+ const problem = checkSchedule(fields.schedule, limits.minMinutes ?? 5);
261
+ if (problem)
262
+ throw new Error(problem);
263
+ const enabled = fields.enabled ?? true;
264
+ const next = enabled ? nextRun(fields.schedule, now) : null;
265
+ if (enabled && next === null)
266
+ throw new Error("that time has already passed");
267
+ return { id: newTaskId(), name, prompt, schedule: fields.schedule, enabled, next, by: fields.by, created: now, updated: now, runs: 0 };
268
+ }
269
+ /** Applies a change to a task, checking it; throws a readable error. */
270
+ export function changeTask(task, patch, limits = {}, now = Date.now()) {
271
+ const out = { ...task, updated: now };
272
+ if (patch.name !== undefined) {
273
+ if (!patch.name.trim())
274
+ throw new Error("a task needs a name");
275
+ out.name = patch.name.trim();
276
+ }
277
+ if (patch.prompt !== undefined) {
278
+ if (!patch.prompt.trim())
279
+ throw new Error("a task needs a prompt");
280
+ out.prompt = patch.prompt.trim();
281
+ }
282
+ if (patch.schedule) {
283
+ const problem = checkSchedule(patch.schedule, limits.minMinutes ?? 5);
284
+ if (problem)
285
+ throw new Error(problem);
286
+ out.schedule = patch.schedule;
287
+ }
288
+ if (patch.enabled !== undefined)
289
+ out.enabled = patch.enabled;
290
+ if (patch.schedule || patch.enabled !== undefined) {
291
+ out.next = out.enabled ? nextRun(out.schedule, now) : null;
292
+ if (out.enabled && out.next === null)
293
+ throw new Error("that time has already passed");
294
+ }
295
+ return out;
296
+ }
297
+ /** The schedule argument as the model sends it: one flat object, read by `type`. */
298
+ const SCHEDULE_SCHEMA = {
299
+ type: "object",
300
+ description: "When it runs, in the user's local time. type \"once\": at (\"YYYY-MM-DD HH:mm\") or in_minutes (from now). type \"every\": minutes. type \"daily\": time (\"HH:mm\") and optional days (0 = Sunday … 6 = Saturday; [1,2,3,4,5] for weekdays). type \"cron\": cron (five fields, local time).",
301
+ properties: {
302
+ type: { type: "string", enum: ["once", "every", "daily", "cron"] },
303
+ at: { type: "string" },
304
+ in_minutes: { type: "number" },
305
+ minutes: { type: "number" },
306
+ time: { type: "string" },
307
+ days: { type: "array", items: { type: "integer", minimum: 0, maximum: 6 } },
308
+ cron: { type: "string" },
309
+ },
310
+ required: ["type"],
311
+ additionalProperties: false,
312
+ };
313
+ function toSchedule(a, now) {
314
+ switch (a.type) {
315
+ case "once": return { type: "once", at: a.at ?? (a.in_minutes !== undefined ? formatLocalTime(now + Math.max(1, Math.round(a.in_minutes)) * 60_000) : "") };
316
+ case "every": return { type: "every", minutes: Math.round(a.minutes ?? 0) };
317
+ case "daily": return { type: "daily", time: a.time ?? "", ...(a.days?.length ? { days: a.days } : {}) };
318
+ case "cron": return { type: "cron", cron: a.cron ?? "" };
319
+ }
320
+ }
321
+ /** What the model reads about a task. */
322
+ export function taskLine(t, now = Date.now()) {
323
+ return {
324
+ id: t.id, name: t.name, prompt: t.prompt, schedule: describeSchedule(t.schedule), enabled: t.enabled,
325
+ next: t.next ? formatLocalTime(t.next) : null, runs: t.runs,
326
+ ...(t.last ? { last_run: `${formatLocalTime(t.last.at)} ${t.last.status}${t.last.note ? ": " + t.last.note : ""}` } : {}),
327
+ ...(t.next && t.next < now ? { overdue: true } : {}),
328
+ };
329
+ }
330
+ /**
331
+ * The agent's tools over the tasks: `schedule_list`, `schedule_add`,
332
+ * `schedule_update`, `schedule_remove`. None asks first — the user set the
333
+ * agent free to manage them, and sees them in the Scheduled panel.
334
+ * `onChange` runs after each change (the chat redraws its panel).
335
+ */
336
+ export function scheduleTools(store, opts = {}) {
337
+ const now = opts.now ?? Date.now;
338
+ const tz = (() => { try {
339
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
340
+ }
341
+ catch {
342
+ return "local";
343
+ } })();
344
+ const changed = () => { try {
345
+ opts.onChange?.();
346
+ }
347
+ catch { /* the host's */ } };
348
+ const header = () => `Now: ${formatLocalTime(now())} (${tz}).`;
349
+ return [
350
+ defineTool({
351
+ name: "schedule_list",
352
+ description: "Lists the scheduled tasks: prompts this app's agent runs on its own at set times (while the app is open).",
353
+ readOnly: true,
354
+ display: { label: () => "Scheduled tasks" },
355
+ execute: async () => {
356
+ const list = await store.list();
357
+ return `${header()}\n${list.length ? JSON.stringify(list.map((t) => taskLine(t, now())), null, 1) : "No scheduled tasks."}`;
358
+ },
359
+ }),
360
+ defineTool({
361
+ name: "schedule_add",
362
+ description: `Adds a scheduled task: at the set times the agent is given \`prompt\` in a conversation of the task's own and works on it unattended (the user may not be watching; questions wait for them). Runs only while the app is open in a browser; a run missed while it was closed happens once when it is next opened. Repeats at most every ${opts.minMinutes ?? 5} minutes. Write the prompt so it stands alone: the run does not see this conversation.`,
363
+ parameters: {
364
+ type: "object",
365
+ properties: {
366
+ name: { type: "string", description: "Short name the user sees, e.g. \"Morning news digest\"." },
367
+ prompt: { type: "string", description: "The instruction for each run, complete on its own." },
368
+ schedule: SCHEDULE_SCHEMA,
369
+ enabled: { type: "boolean", description: "Default true." },
370
+ },
371
+ required: ["name", "prompt", "schedule"],
372
+ additionalProperties: false,
373
+ },
374
+ display: { label: (a) => `Schedule “${a.name ?? ""}”` },
375
+ execute: async (a) => {
376
+ const list = await store.list();
377
+ if (list.length >= (opts.maxTasks ?? 20))
378
+ throw new Error(`there are already ${list.length} tasks, the most allowed; remove one first`);
379
+ const task = makeTask({ name: a.name, prompt: a.prompt, schedule: toSchedule(a.schedule, now()), enabled: a.enabled, by: "agent" }, opts, now());
380
+ await store.put(task);
381
+ changed();
382
+ return `${header()}\nAdded: ${JSON.stringify(taskLine(task, now()))}`;
383
+ },
384
+ }),
385
+ defineTool({
386
+ name: "schedule_update",
387
+ description: "Changes a scheduled task (by id, from schedule_list): its name, prompt, schedule, or enabled (false pauses it).",
388
+ parameters: {
389
+ type: "object",
390
+ properties: { id: { type: "string" }, name: { type: "string" }, prompt: { type: "string" }, schedule: SCHEDULE_SCHEMA, enabled: { type: "boolean" } },
391
+ required: ["id"],
392
+ additionalProperties: false,
393
+ },
394
+ display: { label: (a) => `Update scheduled task ${a.id ?? ""}` },
395
+ execute: async (a) => {
396
+ const task = await store.get(a.id);
397
+ if (!task)
398
+ throw new Error(`no task with id ${a.id}; schedule_list shows them`);
399
+ const next = changeTask(task, { name: a.name, prompt: a.prompt, schedule: a.schedule ? toSchedule(a.schedule, now()) : undefined, enabled: a.enabled }, opts, now());
400
+ await store.put(next);
401
+ changed();
402
+ return `${header()}\nUpdated: ${JSON.stringify(taskLine(next, now()))}`;
403
+ },
404
+ }),
405
+ defineTool({
406
+ name: "schedule_remove",
407
+ description: "Removes a scheduled task (by id). Its conversation stays.",
408
+ parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"], additionalProperties: false },
409
+ display: { label: (a) => `Remove scheduled task ${a.id ?? ""}` },
410
+ execute: async (a) => {
411
+ const task = await store.get(a.id);
412
+ if (!task)
413
+ throw new Error(`no task with id ${a.id}`);
414
+ await store.delete(a.id);
415
+ changed();
416
+ return `Removed “${task.name}”.`;
417
+ },
418
+ }),
419
+ ];
420
+ }
421
+ /** Fires due tasks while `idle()`: one at a time, each in one tab only. */
422
+ export class Scheduler {
423
+ opts;
424
+ timer = null;
425
+ busy = false;
426
+ unsub = null;
427
+ /** Ids of tasks this tab is running now. */
428
+ running = new Set();
429
+ constructor(opts) {
430
+ this.opts = opts;
431
+ }
432
+ start() {
433
+ if (this.timer)
434
+ return;
435
+ this.timer = setInterval(() => void this.tick(), this.opts.interval ?? 20_000);
436
+ this.unsub = this.opts.store.subscribe?.(() => this.opts.onChange?.()) ?? null;
437
+ if (typeof window !== "undefined")
438
+ window.addEventListener("focus", this.poke);
439
+ void this.tick();
440
+ }
441
+ stop() {
442
+ if (this.timer)
443
+ clearInterval(this.timer);
444
+ this.timer = null;
445
+ this.unsub?.();
446
+ this.unsub = null;
447
+ if (typeof window !== "undefined")
448
+ window.removeEventListener("focus", this.poke);
449
+ }
450
+ poke = () => void this.tick();
451
+ /** Looks for a due task and runs it when idle. Resolves once that run is over. */
452
+ async tick() {
453
+ if (this.busy || !this.opts.idle())
454
+ return;
455
+ const now = (this.opts.now ?? Date.now)();
456
+ const due = (await this.opts.store.list()).filter((t) => t.enabled && t.next !== null && t.next <= now).sort((a, b) => a.next - b.next);
457
+ for (const t of due) {
458
+ if (this.busy || !this.opts.idle())
459
+ return;
460
+ if (await this.fire(t.id, false))
461
+ return;
462
+ }
463
+ }
464
+ /** Runs a task now (the user's "Run now"), whatever its time; false when it is already running somewhere. */
465
+ runNow(id) { return this.fire(id, true); }
466
+ async fire(id, force) {
467
+ if (this.busy)
468
+ return false;
469
+ this.busy = true;
470
+ let ran = false;
471
+ try {
472
+ await tryLock(`${this.opts.lockPrefix}:task:${id}`, async () => {
473
+ const store = this.opts.store, clock = this.opts.now ?? Date.now;
474
+ // Read again under the lock: another tab may have just run it.
475
+ const task = await store.get(id);
476
+ const now = clock();
477
+ if (!task || (!force && (!task.enabled || task.next === null || task.next > now)))
478
+ return;
479
+ // Its next time moves first, so other tabs see it is taken (a crash mid-run then skips this one, not repeats it).
480
+ const next = task.enabled ? nextRun(task.schedule, now, now) : task.next;
481
+ await store.put({ ...task, next: task.schedule.type === "once" && !force ? null : next, ...(task.schedule.type === "once" && !force ? { enabled: false } : {}) });
482
+ ran = true;
483
+ this.running.add(id);
484
+ this.opts.onChange?.();
485
+ let out;
486
+ try {
487
+ out = await this.opts.run(task);
488
+ }
489
+ catch (err) {
490
+ out = { status: "error", note: err.message };
491
+ }
492
+ this.running.delete(id);
493
+ // The task may have been changed or removed while it ran: keep that, add the run.
494
+ const after = await store.get(id);
495
+ if (after)
496
+ await store.put({ ...after, runs: after.runs + 1, last: { at: now, ...out } });
497
+ this.opts.onChange?.();
498
+ });
499
+ return ran;
500
+ }
501
+ finally {
502
+ this.busy = false;
503
+ }
504
+ }
505
+ }
package/dist/types.d.ts CHANGED
@@ -161,6 +161,8 @@ export interface ToolDisplay<A = any> {
161
161
  label?: (args: A) => string;
162
162
  /** The card's icon (SVG markup, about 14px). */
163
163
  icon?: string;
164
+ /** Marks the card's icon for a call the reader should notice: `warning` (it spends or acts for the user), `danger` (it deletes or publishes). */
165
+ tone?: "warning" | "danger";
164
166
  /**
165
167
  * Content of the app's own on the card, under its title and visible while
166
168
  * it is folded (a card's arguments and raw result stay behind it): called
@@ -199,6 +201,8 @@ export interface AgentUI {
199
201
  * Yes/no question; resolves false when dismissed. With `always`, a UI may
200
202
  * offer a third answer under its label ("Always allow"): it calls
201
203
  * `onChoose` and resolves true. A UI that does not just answers yes or no.
204
+ * `permission` is set when the question is the agent asking whether a
205
+ * tool may run (`permissions: "ask"`), not a tool's own question.
202
206
  */
203
207
  confirm(title: string, message?: string, opts?: {
204
208
  ok?: string;
@@ -210,6 +214,7 @@ export interface AgentUI {
210
214
  onChoose: () => void;
211
215
  };
212
216
  body?: () => HTMLElement;
217
+ permission?: boolean;
213
218
  }): Promise<boolean>;
214
219
  /**
215
220
  * Pick one (or several with `multi`) of `options`; `allowOther` adds a
@@ -218,7 +223,9 @@ export interface AgentUI {
218
223
  select(title: string, options: SelectOption[], opts?: {
219
224
  message?: string;
220
225
  multi?: boolean;
221
- allowOther?: boolean;
226
+ allowOther?: boolean; /** With `multi`: how many may be picked (default at least 1); OK waits until the count fits. */
227
+ min?: number;
228
+ max?: number;
222
229
  signal?: AbortSignal;
223
230
  }): Promise<string[] | null>;
224
231
  /** Free text; null when dismissed. */
@@ -229,8 +236,27 @@ export interface AgentUI {
229
236
  initial?: string;
230
237
  signal?: AbortSignal;
231
238
  }): Promise<string | null>;
239
+ /**
240
+ * Several fields in one question; resolves the values by field name (a
241
+ * `number` field gives a number, an empty optional field is left out), or
242
+ * null when dismissed. Optional: a UI without it cannot be asked for a form.
243
+ */
244
+ form?(title: string, fields: FormField[], opts?: {
245
+ message?: string;
246
+ ok?: string;
247
+ signal?: AbortSignal;
248
+ }): Promise<Record<string, string | number> | null>;
232
249
  notify(message: string, level?: "info" | "warning" | "error"): void;
233
250
  }
251
+ /** One field of `AgentUI.form`. */
252
+ export interface FormField {
253
+ name: string;
254
+ label?: string;
255
+ type?: "text" | "number";
256
+ required?: boolean;
257
+ placeholder?: string;
258
+ initial?: string | number;
259
+ }
234
260
  export interface FileStat {
235
261
  /** Absolute POSIX path inside the workspace. */
236
262
  path: string;
@@ -393,7 +419,8 @@ export interface AgentEventMap {
393
419
  tokensBefore: number;
394
420
  tokensAfter: number;
395
421
  droppedTurns: number;
396
- elidedResults: number;
422
+ elidedResults: number; /** The summary's text, from an agent that does not keep it as its first message. */
423
+ summaryText?: string;
397
424
  };
398
425
  /** The session was written to the workspace. */
399
426
  session_saved: {
@@ -430,6 +457,16 @@ export interface AgentEventMap {
430
457
  rewind: {
431
458
  index: number;
432
459
  };
460
+ /**
461
+ * The messages changed from outside a run of this agent (an agent whose
462
+ * conversation lives elsewhere: see ChatAgent): the transcript is drawn
463
+ * again. `older`: messages were put before the first one, the view stays
464
+ * on what it showed; `newer`: messages were added at the end, the view
465
+ * follows them when it was at the end; `replace`: another set, shown from its end.
466
+ */
467
+ history: {
468
+ reason: "older" | "newer" | "replace";
469
+ };
433
470
  queued: {
434
471
  kind: "steer" | "followUp";
435
472
  message: ChatMessage;