@runappsai/agent 0.1.11 → 0.1.15
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/README.md +1 -1
- package/dist/agent-core.umd.js +90 -87
- package/dist/agent.d.ts +5 -1
- package/dist/agent.js +11 -7
- package/dist/agent.umd.js +130 -104
- package/dist/chat.d.ts +40 -1
- package/dist/chat.js +375 -16
- package/dist/dom.d.ts +28 -1
- package/dist/dom.js +38 -1
- package/dist/files-panel.js +2 -2
- package/dist/index.cjs +514 -37
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/schedule.d.ts +152 -0
- package/dist/schedule.js +505 -0
- package/dist/types.d.ts +3 -0
- package/dist/ui.cjs +932 -13
- package/dist/ui.d.ts +1 -0
- package/docs/chat-ui.md +23 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ export { planCut, serializeConversation, splitForSummary, summaryOf, summaryMess
|
|
|
23
23
|
export { parseCommandArgs, substituteArgs, listTemplates, expandSlash, type PromptTemplate } from "./templates.js";
|
|
24
24
|
export { applyEdits, normalizeForFuzzyMatch, type TextEdit } from "./edit.js";
|
|
25
25
|
export { defineTool, normalizeResult } from "./tool.js";
|
|
26
|
+
export { Scheduler, scheduleTools, localSchedules, memorySchedules, makeTask, changeTask, nextRun, checkSchedule, describeSchedule, parseCron, parseLocalTime, formatLocalTime, type Schedule, type ScheduledTask, type ScheduleStore, type ScheduleLimits, type ScheduleRunStatus, type SchedulerOptions } from "./schedule.js";
|
|
26
27
|
export { domUI, nullUI, askUserTool } from "./dialogs.js";
|
|
27
28
|
export { configurePdf, extractPdfText, formatPdfText, isPdf, type PdfLib } from "./pdf.js";
|
|
28
29
|
export { fileTools, type FileToolsOptions } from "./file-tools.js";
|
package/dist/index.js
CHANGED
|
@@ -31,6 +31,7 @@ export { planCut, serializeConversation, splitForSummary, summaryOf, summaryMess
|
|
|
31
31
|
export { parseCommandArgs, substituteArgs, listTemplates, expandSlash } from "./templates.js";
|
|
32
32
|
export { applyEdits, normalizeForFuzzyMatch } from "./edit.js";
|
|
33
33
|
export { defineTool, normalizeResult } from "./tool.js";
|
|
34
|
+
export { Scheduler, scheduleTools, localSchedules, memorySchedules, makeTask, changeTask, nextRun, checkSchedule, describeSchedule, parseCron, parseLocalTime, formatLocalTime } from "./schedule.js";
|
|
34
35
|
export { domUI, nullUI, askUserTool } from "./dialogs.js";
|
|
35
36
|
export { configurePdf, extractPdfText, formatPdfText, isPdf } from "./pdf.js";
|
|
36
37
|
export { fileTools } from "./file-tools.js";
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import type { Tool } from "./types.js";
|
|
2
|
+
/** When a task runs. Times are the user's local time. */
|
|
3
|
+
export type Schedule =
|
|
4
|
+
/** Once, at `at` (local "YYYY-MM-DDTHH:mm", or an ISO time with a zone). */
|
|
5
|
+
{
|
|
6
|
+
type: "once";
|
|
7
|
+
at: string;
|
|
8
|
+
}
|
|
9
|
+
/** Every `minutes` minutes, the first `minutes` after it is set. */
|
|
10
|
+
| {
|
|
11
|
+
type: "every";
|
|
12
|
+
minutes: number;
|
|
13
|
+
}
|
|
14
|
+
/** Daily at `time` ("HH:mm"), only on `days` (0 = Sunday … 6 = Saturday) when given. */
|
|
15
|
+
| {
|
|
16
|
+
type: "daily";
|
|
17
|
+
time: string;
|
|
18
|
+
days?: number[];
|
|
19
|
+
}
|
|
20
|
+
/** A five-field cron expression (minute hour day-of-month month day-of-week), local time. */
|
|
21
|
+
| {
|
|
22
|
+
type: "cron";
|
|
23
|
+
cron: string;
|
|
24
|
+
};
|
|
25
|
+
export type ScheduleRunStatus = "ok" | "error" | "stopped";
|
|
26
|
+
export interface ScheduledTask {
|
|
27
|
+
id: string;
|
|
28
|
+
name: string;
|
|
29
|
+
/** What the agent is told each time it runs. */
|
|
30
|
+
prompt: string;
|
|
31
|
+
schedule: Schedule;
|
|
32
|
+
enabled: boolean;
|
|
33
|
+
/** Next run (ms since epoch); null when it will not run again (a past one-off, or off). */
|
|
34
|
+
next: number | null;
|
|
35
|
+
/** Who set it up. */
|
|
36
|
+
by: "agent" | "user";
|
|
37
|
+
created: number;
|
|
38
|
+
updated: number;
|
|
39
|
+
runs: number;
|
|
40
|
+
last?: {
|
|
41
|
+
at: number;
|
|
42
|
+
status: ScheduleRunStatus;
|
|
43
|
+
note?: string;
|
|
44
|
+
cost?: number;
|
|
45
|
+
};
|
|
46
|
+
/** The conversation its runs go to (the chat's choice; one per task). */
|
|
47
|
+
session?: string;
|
|
48
|
+
}
|
|
49
|
+
/** Where tasks are kept. `localSchedules` (the default) keeps them in localStorage. */
|
|
50
|
+
export interface ScheduleStore {
|
|
51
|
+
list(): Promise<ScheduledTask[]>;
|
|
52
|
+
get(id: string): Promise<ScheduledTask | undefined>;
|
|
53
|
+
put(task: ScheduledTask): Promise<void>;
|
|
54
|
+
delete(id: string): Promise<void>;
|
|
55
|
+
/** Called when another tab changed the tasks. */
|
|
56
|
+
subscribe?(fn: () => void): () => void;
|
|
57
|
+
}
|
|
58
|
+
/** Tasks in localStorage under `key` (one JSON list); other tabs' changes arrive through the `storage` event. */
|
|
59
|
+
export declare function localSchedules(key: string): ScheduleStore;
|
|
60
|
+
/** Tasks in memory (tests, or an app that keeps them itself). */
|
|
61
|
+
export declare function memorySchedules(initial?: ScheduledTask[]): ScheduleStore;
|
|
62
|
+
/** 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. */
|
|
63
|
+
export declare function parseLocalTime(s: string): number;
|
|
64
|
+
/** "2026-11-28 09:00" in local time. */
|
|
65
|
+
export declare function formatLocalTime(ms: number): string;
|
|
66
|
+
interface Cron {
|
|
67
|
+
min: Set<number>;
|
|
68
|
+
hour: Set<number>;
|
|
69
|
+
dom: Set<number>;
|
|
70
|
+
mon: Set<number>;
|
|
71
|
+
dow: Set<number>;
|
|
72
|
+
domAny: boolean;
|
|
73
|
+
dowAny: boolean;
|
|
74
|
+
}
|
|
75
|
+
/** Parses a five-field cron expression; throws a readable error. */
|
|
76
|
+
export declare function parseCron(expr: string): Cron;
|
|
77
|
+
/** Checks a schedule; returns a readable problem, or undefined when it is fine. `minMinutes` is the shortest repeat allowed. */
|
|
78
|
+
export declare function checkSchedule(s: Schedule, minMinutes?: number): string | undefined;
|
|
79
|
+
/** 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. */
|
|
80
|
+
export declare function nextRun(s: Schedule, after: number, from?: number): number | null;
|
|
81
|
+
/** The schedule in words: "Every 30 min", "Daily 09:00", "Mon–Fri 09:00", "Once 2026-11-28 09:00", "cron 0 9 * * 1". */
|
|
82
|
+
export declare function describeSchedule(s: Schedule, locale?: "en" | "zh"): string;
|
|
83
|
+
export interface ScheduleLimits {
|
|
84
|
+
/** Shortest repeat, in minutes (default 5): a task that runs every minute would spend the user's money fast. */
|
|
85
|
+
minMinutes?: number;
|
|
86
|
+
/** Most tasks at once (default 20). */
|
|
87
|
+
maxTasks?: number;
|
|
88
|
+
}
|
|
89
|
+
/** Builds a task from a schedule and fields, checking them; throws a readable error. */
|
|
90
|
+
export declare function makeTask(fields: {
|
|
91
|
+
name: string;
|
|
92
|
+
prompt: string;
|
|
93
|
+
schedule: Schedule;
|
|
94
|
+
enabled?: boolean;
|
|
95
|
+
by: "agent" | "user";
|
|
96
|
+
}, limits?: ScheduleLimits, now?: number): ScheduledTask;
|
|
97
|
+
/** Applies a change to a task, checking it; throws a readable error. */
|
|
98
|
+
export declare function changeTask(task: ScheduledTask, patch: {
|
|
99
|
+
name?: string;
|
|
100
|
+
prompt?: string;
|
|
101
|
+
schedule?: Schedule;
|
|
102
|
+
enabled?: boolean;
|
|
103
|
+
}, limits?: ScheduleLimits, now?: number): ScheduledTask;
|
|
104
|
+
/** What the model reads about a task. */
|
|
105
|
+
export declare function taskLine(t: ScheduledTask, now?: number): Record<string, unknown>;
|
|
106
|
+
/**
|
|
107
|
+
* The agent's tools over the tasks: `schedule_list`, `schedule_add`,
|
|
108
|
+
* `schedule_update`, `schedule_remove`. None asks first — the user set the
|
|
109
|
+
* agent free to manage them, and sees them in the Scheduled panel.
|
|
110
|
+
* `onChange` runs after each change (the chat redraws its panel).
|
|
111
|
+
*/
|
|
112
|
+
export declare function scheduleTools(store: ScheduleStore, opts?: ScheduleLimits & {
|
|
113
|
+
onChange?: () => void;
|
|
114
|
+
now?: () => number;
|
|
115
|
+
}): Tool[];
|
|
116
|
+
export interface SchedulerOptions {
|
|
117
|
+
store: ScheduleStore;
|
|
118
|
+
/** Runs one task; resolves how it went. The scheduler runs one task at a time. */
|
|
119
|
+
run: (task: ScheduledTask) => Promise<{
|
|
120
|
+
status: ScheduleRunStatus;
|
|
121
|
+
note?: string;
|
|
122
|
+
cost?: number;
|
|
123
|
+
}>;
|
|
124
|
+
/** Whether a task may start now (the chat: nothing running, no question open). */
|
|
125
|
+
idle: () => boolean;
|
|
126
|
+
/** Names the per-task locks, so tabs of the same app agree (e.g. the app's project). */
|
|
127
|
+
lockPrefix: string;
|
|
128
|
+
/** How often to look, ms (default 20 s; also on focus and when told). */
|
|
129
|
+
interval?: number;
|
|
130
|
+
now?: () => number;
|
|
131
|
+
/** After a task changed (ran, or was claimed). */
|
|
132
|
+
onChange?: () => void;
|
|
133
|
+
}
|
|
134
|
+
/** Fires due tasks while `idle()`: one at a time, each in one tab only. */
|
|
135
|
+
export declare class Scheduler {
|
|
136
|
+
private readonly opts;
|
|
137
|
+
private timer;
|
|
138
|
+
private busy;
|
|
139
|
+
private unsub;
|
|
140
|
+
/** Ids of tasks this tab is running now. */
|
|
141
|
+
readonly running: Set<string>;
|
|
142
|
+
constructor(opts: SchedulerOptions);
|
|
143
|
+
start(): void;
|
|
144
|
+
stop(): void;
|
|
145
|
+
private poke;
|
|
146
|
+
/** Looks for a due task and runs it when idle. Resolves once that run is over. */
|
|
147
|
+
tick(): Promise<void>;
|
|
148
|
+
/** Runs a task now (the user's "Run now"), whatever its time; false when it is already running somewhere. */
|
|
149
|
+
runNow(id: string): Promise<boolean>;
|
|
150
|
+
private fire;
|
|
151
|
+
}
|
|
152
|
+
export {};
|
package/dist/schedule.js
ADDED
|
@@ -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
|
+
}
|