@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.cjs
CHANGED
|
@@ -30,6 +30,7 @@ __export(src_exports, {
|
|
|
30
30
|
MCPError: () => MCPError,
|
|
31
31
|
PartialReadError: () => PartialReadError,
|
|
32
32
|
ProviderError: () => ProviderError,
|
|
33
|
+
Scheduler: () => Scheduler,
|
|
33
34
|
UNTITLED: () => UNTITLED,
|
|
34
35
|
WEB_TOOL_NAMES: () => WEB_TOOL_NAMES,
|
|
35
36
|
Workspace: () => Workspace,
|
|
@@ -37,12 +38,15 @@ __export(src_exports, {
|
|
|
37
38
|
askUserTool: () => askUserTool,
|
|
38
39
|
buildSystemPrompt: () => buildSystemPrompt,
|
|
39
40
|
buildZip: () => buildZip,
|
|
41
|
+
changeTask: () => changeTask,
|
|
42
|
+
checkSchedule: () => checkSchedule,
|
|
40
43
|
collectCompletion: () => collectCompletion,
|
|
41
44
|
configurePdf: () => configurePdf,
|
|
42
45
|
connectMCP: () => connectMCP,
|
|
43
46
|
createAgent: () => createAgent,
|
|
44
47
|
decodeText: () => decodeText,
|
|
45
48
|
defineTool: () => defineTool,
|
|
49
|
+
describeSchedule: () => describeSchedule,
|
|
46
50
|
domUI: () => domUI,
|
|
47
51
|
estimateTokens: () => estimateTokens,
|
|
48
52
|
expandSlash: () => expandSlash,
|
|
@@ -50,6 +54,7 @@ __export(src_exports, {
|
|
|
50
54
|
fileGuard: () => fileGuard,
|
|
51
55
|
fileTools: () => fileTools,
|
|
52
56
|
fitBudget: () => fitBudget,
|
|
57
|
+
formatLocalTime: () => formatLocalTime,
|
|
53
58
|
formatPdfText: () => formatPdfText,
|
|
54
59
|
groupTurns: () => groupTurns,
|
|
55
60
|
guessType: () => guessType,
|
|
@@ -57,8 +62,12 @@ __export(src_exports, {
|
|
|
57
62
|
isPdf: () => isPdf,
|
|
58
63
|
listTemplates: () => listTemplates,
|
|
59
64
|
listZip: () => listZip,
|
|
65
|
+
localSchedules: () => localSchedules,
|
|
66
|
+
makeTask: () => makeTask,
|
|
60
67
|
memoryFS: () => memoryFS,
|
|
68
|
+
memorySchedules: () => memorySchedules,
|
|
61
69
|
modelAccepts: () => modelAccepts,
|
|
70
|
+
nextRun: () => nextRun,
|
|
62
71
|
normalizeForFuzzyMatch: () => normalizeForFuzzyMatch,
|
|
63
72
|
normalizePath: () => normalizePath,
|
|
64
73
|
normalizeResult: () => normalizeResult,
|
|
@@ -66,13 +75,16 @@ __export(src_exports, {
|
|
|
66
75
|
openAIProvider: () => openAIProvider,
|
|
67
76
|
openWorkspace: () => openWorkspace,
|
|
68
77
|
parseCommandArgs: () => parseCommandArgs,
|
|
78
|
+
parseCron: () => parseCron,
|
|
69
79
|
parseFrontmatter: () => parseFrontmatter,
|
|
80
|
+
parseLocalTime: () => parseLocalTime,
|
|
70
81
|
parseSkill: () => parseSkill,
|
|
71
82
|
planCut: () => planCut,
|
|
72
83
|
readZipEntry: () => readZipEntry,
|
|
73
84
|
runInSandbox: () => runInSandbox,
|
|
74
85
|
runappsProvider: () => runappsProvider,
|
|
75
86
|
sandboxTool: () => sandboxTool,
|
|
87
|
+
scheduleTools: () => scheduleTools,
|
|
76
88
|
serializeConversation: () => serializeConversation,
|
|
77
89
|
skillFoldersOf: () => skillFoldersOf,
|
|
78
90
|
skillZipFS: () => skillZipFS,
|
|
@@ -518,14 +530,14 @@ function summaryOf(m) {
|
|
|
518
530
|
function summaryMessage(summary) {
|
|
519
531
|
return { role: "user", content: COMPACTION_SUMMARY_PREFIX + summary + COMPACTION_SUMMARY_SUFFIX };
|
|
520
532
|
}
|
|
521
|
-
function resolveSettings(
|
|
533
|
+
function resolveSettings(window2, s = {}) {
|
|
522
534
|
return {
|
|
523
|
-
reserveTokens: Math.min(s.reserveTokens ?? DEFAULT_COMPACTION.reserveTokens, Math.floor(
|
|
524
|
-
keepRecentTokens: Math.min(s.keepRecentTokens ?? DEFAULT_COMPACTION.keepRecentTokens, Math.floor(
|
|
535
|
+
reserveTokens: Math.min(s.reserveTokens ?? DEFAULT_COMPACTION.reserveTokens, Math.floor(window2 * 0.2)),
|
|
536
|
+
keepRecentTokens: Math.min(s.keepRecentTokens ?? DEFAULT_COMPACTION.keepRecentTokens, Math.floor(window2 * 0.4))
|
|
525
537
|
};
|
|
526
538
|
}
|
|
527
|
-
function shouldCompact(contextTokens,
|
|
528
|
-
return contextTokens >
|
|
539
|
+
function shouldCompact(contextTokens, window2, s) {
|
|
540
|
+
return contextTokens > window2 - s.reserveTokens;
|
|
529
541
|
}
|
|
530
542
|
function planCut(messages, keepRecentTokens) {
|
|
531
543
|
if (messages.length < 2) return null;
|
|
@@ -2466,8 +2478,8 @@ function isMachineTitle(title) {
|
|
|
2466
2478
|
return /^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(title);
|
|
2467
2479
|
}
|
|
2468
2480
|
function withLock(name, fn) {
|
|
2469
|
-
const
|
|
2470
|
-
return
|
|
2481
|
+
const locks2 = typeof navigator !== "undefined" ? navigator.locks : void 0;
|
|
2482
|
+
return locks2 && typeof locks2.request === "function" ? locks2.request(name, fn) : fn();
|
|
2471
2483
|
}
|
|
2472
2484
|
function memoryFS(initial = {}, opts = {}) {
|
|
2473
2485
|
const files = /* @__PURE__ */ new Map();
|
|
@@ -3699,7 +3711,7 @@ var Agent = class {
|
|
|
3699
3711
|
__publicField(this, "loaded");
|
|
3700
3712
|
__publicField(this, "createdAt", Date.now());
|
|
3701
3713
|
/** The session's title, fixed once known (a later compaction must not turn it into the summary's first words). */
|
|
3702
|
-
__publicField(this, "
|
|
3714
|
+
__publicField(this, "fixedTitle");
|
|
3703
3715
|
__publicField(this, "_ended", null);
|
|
3704
3716
|
__publicField(this, "persist");
|
|
3705
3717
|
this.provider = toProvider(provider);
|
|
@@ -3747,6 +3759,14 @@ var Agent = class {
|
|
|
3747
3759
|
this.loaded = Promise.resolve();
|
|
3748
3760
|
}
|
|
3749
3761
|
}
|
|
3762
|
+
/** The conversation's title as the session list shows it (the first thing the user wrote, unless `setTitle` fixed another); undefined before there is one. */
|
|
3763
|
+
get title() {
|
|
3764
|
+
return this.fixedTitle;
|
|
3765
|
+
}
|
|
3766
|
+
/** Fixes the conversation's title (a scheduled task's name, say); saved with the session. */
|
|
3767
|
+
setTitle(title) {
|
|
3768
|
+
this.fixedTitle = title.trim() || void 0;
|
|
3769
|
+
}
|
|
3750
3770
|
applySession(data) {
|
|
3751
3771
|
if (data.v !== 1 && data.v !== 2) throw new Error("unknown session format");
|
|
3752
3772
|
this.history = data.messages.slice();
|
|
@@ -3755,7 +3775,7 @@ var Agent = class {
|
|
|
3755
3775
|
this._usage = { ...data.usage };
|
|
3756
3776
|
this.createdAt = data.createdAt ?? data.savedAt ?? Date.now();
|
|
3757
3777
|
this._ended = data.ended ?? null;
|
|
3758
|
-
this.
|
|
3778
|
+
this.fixedTitle = data.title && !isMachineTitle(data.title) ? data.title : void 0;
|
|
3759
3779
|
if (data.model && !this.opts.model) {
|
|
3760
3780
|
this.opts.model = data.model;
|
|
3761
3781
|
this.catalogue = null;
|
|
@@ -3865,8 +3885,8 @@ var Agent = class {
|
|
|
3865
3885
|
* starts (`reserveTokens`) and how much of the newest it keeps verbatim
|
|
3866
3886
|
* (`keepRecentTokens`), each capped by the window (20 % / 40 %).
|
|
3867
3887
|
*/
|
|
3868
|
-
compactionFor(
|
|
3869
|
-
return { summarize: this.compactSummaries, ...resolveSettings(
|
|
3888
|
+
compactionFor(window2) {
|
|
3889
|
+
return { summarize: this.compactSummaries, ...resolveSettings(window2, this.compactThresholds) };
|
|
3870
3890
|
}
|
|
3871
3891
|
/** A snapshot to save (`restore` continues it). Taken at the last complete turn. */
|
|
3872
3892
|
export() {
|
|
@@ -3882,18 +3902,18 @@ var Agent = class {
|
|
|
3882
3902
|
savedAt: Date.now(),
|
|
3883
3903
|
...this._ended ? { ended: this._ended } : {}
|
|
3884
3904
|
};
|
|
3885
|
-
if (!this.
|
|
3905
|
+
if (!this.fixedTitle) {
|
|
3886
3906
|
const tt = titleOf(data);
|
|
3887
|
-
if (tt !== UNTITLED) this.
|
|
3907
|
+
if (tt !== UNTITLED) this.fixedTitle = tt;
|
|
3888
3908
|
}
|
|
3889
|
-
data.title = this.
|
|
3909
|
+
data.title = this.fixedTitle ?? UNTITLED;
|
|
3890
3910
|
return data;
|
|
3891
3911
|
}
|
|
3892
3912
|
/** Forgets the conversation (the workspace stays). */
|
|
3893
3913
|
reset() {
|
|
3894
3914
|
if (this.current) throw new Error("cannot reset while a run is active; abort() first");
|
|
3895
3915
|
this.history = [];
|
|
3896
|
-
this.
|
|
3916
|
+
this.fixedTitle = void 0;
|
|
3897
3917
|
this._ended = null;
|
|
3898
3918
|
this.committed = 0;
|
|
3899
3919
|
this.droppedTurns = 0;
|
|
@@ -4074,8 +4094,8 @@ var Agent = class {
|
|
|
4074
4094
|
this.emit("run_start", { runId, message: prefaced });
|
|
4075
4095
|
const maxTurns = this.opts.maxTurns ?? DEFAULT_MAX_TURNS;
|
|
4076
4096
|
const { output: maxTokens, input: catalogueWindow } = await this.limits();
|
|
4077
|
-
let
|
|
4078
|
-
let compaction = resolveSettings(
|
|
4097
|
+
let window2 = catalogueWindow;
|
|
4098
|
+
let compaction = resolveSettings(window2, this.compactThresholds);
|
|
4079
4099
|
let overflowRetries = 0;
|
|
4080
4100
|
try {
|
|
4081
4101
|
if (prefaceError) throw prefaceError;
|
|
@@ -4094,13 +4114,13 @@ var Agent = class {
|
|
|
4094
4114
|
const system = await this.systemPrompt();
|
|
4095
4115
|
const fixed = this.fixedText(system);
|
|
4096
4116
|
const tokensBefore = estimateTokens(this.history, fixed);
|
|
4097
|
-
if (shouldCompact(tokensBefore,
|
|
4117
|
+
if (shouldCompact(tokensBefore, window2, compaction)) {
|
|
4098
4118
|
const summarized = !this.compactSummaries ? false : await this.compactWith(compaction, runId, signal);
|
|
4099
4119
|
const after = estimateTokens(this.history, fixed);
|
|
4100
|
-
if (!summarized || shouldCompact(after,
|
|
4120
|
+
if (!summarized || shouldCompact(after, window2, compaction)) {
|
|
4101
4121
|
const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
|
|
4102
4122
|
const rest = this.history.slice(pinned.length);
|
|
4103
|
-
const fit = fitBudget(rest, { budget:
|
|
4123
|
+
const fit = fitBudget(rest, { budget: window2 - compaction.reserveTokens - estimateTokens(pinned), keepTurns: this.opts.keepTurns ?? 4, system: fixed });
|
|
4104
4124
|
if (fit.droppedTurns || fit.elidedResults) {
|
|
4105
4125
|
this.history = [...pinned, ...fit.messages];
|
|
4106
4126
|
this.droppedTurns += fit.droppedTurns;
|
|
@@ -4126,7 +4146,7 @@ var Agent = class {
|
|
|
4126
4146
|
const asked = Date.now();
|
|
4127
4147
|
let completion;
|
|
4128
4148
|
try {
|
|
4129
|
-
if (estimateTokens(this.history, fixed) >
|
|
4149
|
+
if (estimateTokens(this.history, fixed) > window2 * 2 && (typeof this.opts.maxInputTokens === "number" || typeof (await this.modelInfo())?.max_input_tokens === "number")) {
|
|
4130
4150
|
throw new ProviderError(413, "the request is far larger than the model's context");
|
|
4131
4151
|
}
|
|
4132
4152
|
completion = await this.callModel(params, runId, signal);
|
|
@@ -4134,17 +4154,17 @@ var Agent = class {
|
|
|
4134
4154
|
this.emit("response", { runId, turn, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
|
|
4135
4155
|
if (signal.aborted || !isContextOverflow(err)) throw err;
|
|
4136
4156
|
const limit = overflowLimit(err);
|
|
4137
|
-
if (limit !== void 0 && limit <
|
|
4138
|
-
|
|
4139
|
-
compaction = resolveSettings(
|
|
4157
|
+
if (limit !== void 0 && limit < window2) {
|
|
4158
|
+
window2 = limit;
|
|
4159
|
+
compaction = resolveSettings(window2, this.compactThresholds);
|
|
4140
4160
|
}
|
|
4141
4161
|
let smaller = false;
|
|
4142
|
-
while (!smaller && overflowRetries < 2) smaller = await this.squeeze(
|
|
4162
|
+
while (!smaller && overflowRetries < 2) smaller = await this.squeeze(window2, overflowRetries++, compaction, fixed, runId, signal);
|
|
4143
4163
|
if (smaller) {
|
|
4144
4164
|
turn--;
|
|
4145
4165
|
continue;
|
|
4146
4166
|
}
|
|
4147
|
-
throw new ContextOverflowError({ cause: this.overflowCause(
|
|
4167
|
+
throw new ContextOverflowError({ cause: this.overflowCause(window2, fixed), used: estimateTokens(this.history, fixed), window: window2 }, err instanceof Error ? err.message : String(err), errorStatus(err) ?? 400);
|
|
4148
4168
|
}
|
|
4149
4169
|
this.emit("response", { runId, turn, durationMs: Date.now() - asked, finishReason: completion.finishReason, usage: completion.usage, message: completion.message });
|
|
4150
4170
|
if (completion.usage) this.addUsage(completion.usage);
|
|
@@ -4325,8 +4345,8 @@ var Agent = class {
|
|
|
4325
4345
|
*/
|
|
4326
4346
|
compact(focus) {
|
|
4327
4347
|
return this.exclusive("compact", async (signal) => {
|
|
4328
|
-
const
|
|
4329
|
-
const settings = this.squeezed(resolveSettings(
|
|
4348
|
+
const window2 = await this.contextTokens();
|
|
4349
|
+
const settings = this.squeezed(resolveSettings(window2, this.compactThresholds));
|
|
4330
4350
|
const done = await this.compactWith(settings, void 0, signal, focus);
|
|
4331
4351
|
if (done) await this.saveSession();
|
|
4332
4352
|
return done;
|
|
@@ -4343,8 +4363,8 @@ var Agent = class {
|
|
|
4343
4363
|
const first = rest[0] ? summaryOf(rest[0]) : null;
|
|
4344
4364
|
const toSummarize = first === null ? rest : rest.slice(1);
|
|
4345
4365
|
if (!toSummarize.length) return first;
|
|
4346
|
-
const
|
|
4347
|
-
const settings = resolveSettings(
|
|
4366
|
+
const window2 = await this.contextTokens();
|
|
4367
|
+
const settings = resolveSettings(window2, this.compactThresholds);
|
|
4348
4368
|
this.emit("compaction_start", {});
|
|
4349
4369
|
try {
|
|
4350
4370
|
return await this.writeSummary({ toSummarize, previousSummary: first ?? void 0, kept: [] }, settings, void 0, signal);
|
|
@@ -4396,12 +4416,12 @@ var Agent = class {
|
|
|
4396
4416
|
* window (the estimate may run low); round 1 trims to 40%, big results of the
|
|
4397
4417
|
* latest turn included. True when the request did get smaller.
|
|
4398
4418
|
*/
|
|
4399
|
-
async squeeze(
|
|
4419
|
+
async squeeze(window2, round2, settings, fixed, runId, signal) {
|
|
4400
4420
|
const before = estimateTokens(this.history, fixed);
|
|
4401
4421
|
if (round2 === 0 && this.compactSummaries) await this.compactWith(this.squeezed(settings), runId, signal);
|
|
4402
4422
|
const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
|
|
4403
4423
|
const rest = this.history.slice(pinned.length);
|
|
4404
|
-
const budget = Math.floor(
|
|
4424
|
+
const budget = Math.floor(window2 * (round2 === 0 ? 0.7 : 0.4)) - estimateTokens(pinned);
|
|
4405
4425
|
const fit = fitBudget(rest, { budget, keepTurns: 1, system: fixed, keepResults: round2 === 0 ? 3 : 0 });
|
|
4406
4426
|
if (fit.droppedTurns || fit.elidedResults) {
|
|
4407
4427
|
this.history = [...pinned, ...fit.messages];
|
|
@@ -4412,13 +4432,13 @@ var Agent = class {
|
|
|
4412
4432
|
return estimateTokens(this.history, fixed) < before;
|
|
4413
4433
|
}
|
|
4414
4434
|
/** What takes up the room in a request that cannot be made smaller. */
|
|
4415
|
-
overflowCause(
|
|
4435
|
+
overflowCause(window2, fixed) {
|
|
4416
4436
|
const tools = this.tools.length ? estimateTokens([], JSON.stringify(this.tools.map((t) => toChatTool(t)))) : 0;
|
|
4417
4437
|
const latest = [...this.history].reverse().find((m) => m.role === "user" && summaryOf(m) === null);
|
|
4418
4438
|
const asked = latest ? estimateTokens([latest]) : 0;
|
|
4419
4439
|
const others = estimateTokens(this.history) - asked;
|
|
4420
4440
|
const biggest = Math.max(tools, asked, others);
|
|
4421
|
-
if (biggest * 2 <
|
|
4441
|
+
if (biggest * 2 < window2) return "model";
|
|
4422
4442
|
if (biggest === asked) {
|
|
4423
4443
|
const files = Array.isArray(latest.content) ? latest.content.length > 1 : /(^|\n)\[attachments\]/.test(String(latest.content ?? ""));
|
|
4424
4444
|
return files ? "attachments" : "message";
|
|
@@ -4662,7 +4682,7 @@ Fix the call and try again.`);
|
|
|
4662
4682
|
else if (tool.destructive) question = `Allow ${tool.name}?`;
|
|
4663
4683
|
if (question === false) return true;
|
|
4664
4684
|
const { title, message, always, ok, body } = typeof question === "string" ? { title: question, message: void 0, always: void 0, ok: void 0, body: void 0 } : question;
|
|
4665
|
-
return this.ui.confirm(title, message, { danger: !!tool.destructive, signal, always, ...ok ? { ok } : {}, ...body ? { body } : {} });
|
|
4685
|
+
return this.ui.confirm(title, message, { danger: !!tool.destructive, signal, always, permission: true, ...ok ? { ok } : {}, ...body ? { body } : {} });
|
|
4666
4686
|
}
|
|
4667
4687
|
/** After an abort, every open tool call gets a result so the transcript stays valid. */
|
|
4668
4688
|
closeOpenToolCalls() {
|
|
@@ -4746,8 +4766,8 @@ Fix the call and try again.`);
|
|
|
4746
4766
|
}
|
|
4747
4767
|
/** How full the model's context is: tokens the next call would send (estimated) against the window. */
|
|
4748
4768
|
async context() {
|
|
4749
|
-
const [
|
|
4750
|
-
return { used: estimateTokens(this.history, this.fixedText(system)), window };
|
|
4769
|
+
const [window2, system] = await Promise.all([this.contextTokens(), this.systemPrompt().catch(() => "")]);
|
|
4770
|
+
return { used: estimateTokens(this.history, this.fixedText(system)), window: window2 };
|
|
4751
4771
|
}
|
|
4752
4772
|
/**
|
|
4753
4773
|
* The files whose contents are still in the conversation: read (with the
|
|
@@ -4885,6 +4905,463 @@ function round(n) {
|
|
|
4885
4905
|
return Math.round(n * 1e6) / 1e6;
|
|
4886
4906
|
}
|
|
4887
4907
|
|
|
4908
|
+
// src/schedule.ts
|
|
4909
|
+
function localSchedules(key) {
|
|
4910
|
+
const read = () => {
|
|
4911
|
+
try {
|
|
4912
|
+
const v = JSON.parse(localStorage.getItem(key) || "[]");
|
|
4913
|
+
return Array.isArray(v) ? v : [];
|
|
4914
|
+
} catch {
|
|
4915
|
+
return [];
|
|
4916
|
+
}
|
|
4917
|
+
};
|
|
4918
|
+
const write = (list) => {
|
|
4919
|
+
try {
|
|
4920
|
+
if (list.length) localStorage.setItem(key, JSON.stringify(list));
|
|
4921
|
+
else localStorage.removeItem(key);
|
|
4922
|
+
} catch {
|
|
4923
|
+
}
|
|
4924
|
+
};
|
|
4925
|
+
const change = (fn) => lock(`${key}:write`, async () => {
|
|
4926
|
+
write(fn(read()));
|
|
4927
|
+
});
|
|
4928
|
+
return {
|
|
4929
|
+
list: async () => read(),
|
|
4930
|
+
get: async (id) => read().find((t) => t.id === id),
|
|
4931
|
+
put: (task) => change((list) => {
|
|
4932
|
+
const i = list.findIndex((t) => t.id === task.id);
|
|
4933
|
+
if (i >= 0) list[i] = task;
|
|
4934
|
+
else list.push(task);
|
|
4935
|
+
return list;
|
|
4936
|
+
}),
|
|
4937
|
+
delete: (id) => change((list) => list.filter((t) => t.id !== id)),
|
|
4938
|
+
subscribe(fn) {
|
|
4939
|
+
if (typeof window === "undefined") return () => {
|
|
4940
|
+
};
|
|
4941
|
+
const on = (e) => {
|
|
4942
|
+
if (e.key === key) fn();
|
|
4943
|
+
};
|
|
4944
|
+
window.addEventListener("storage", on);
|
|
4945
|
+
return () => window.removeEventListener("storage", on);
|
|
4946
|
+
}
|
|
4947
|
+
};
|
|
4948
|
+
}
|
|
4949
|
+
function memorySchedules(initial = []) {
|
|
4950
|
+
const map = new Map(initial.map((t) => [t.id, structuredClone(t)]));
|
|
4951
|
+
return {
|
|
4952
|
+
list: async () => [...map.values()].map((t) => structuredClone(t)),
|
|
4953
|
+
get: async (id) => {
|
|
4954
|
+
const t = map.get(id);
|
|
4955
|
+
return t && structuredClone(t);
|
|
4956
|
+
},
|
|
4957
|
+
put: async (task) => {
|
|
4958
|
+
map.set(task.id, structuredClone(task));
|
|
4959
|
+
},
|
|
4960
|
+
delete: async (id) => {
|
|
4961
|
+
map.delete(id);
|
|
4962
|
+
}
|
|
4963
|
+
};
|
|
4964
|
+
}
|
|
4965
|
+
var locks = () => typeof navigator !== "undefined" ? navigator.locks : void 0;
|
|
4966
|
+
function lock(name, fn) {
|
|
4967
|
+
const l = locks();
|
|
4968
|
+
return l ? l.request(name, {}, fn) : fn();
|
|
4969
|
+
}
|
|
4970
|
+
async function tryLock(name, fn) {
|
|
4971
|
+
const l = locks();
|
|
4972
|
+
if (!l) {
|
|
4973
|
+
await fn();
|
|
4974
|
+
return true;
|
|
4975
|
+
}
|
|
4976
|
+
let got = false;
|
|
4977
|
+
await l.request(name, { ifAvailable: true }, async (held) => {
|
|
4978
|
+
if (!held) return;
|
|
4979
|
+
got = true;
|
|
4980
|
+
await fn();
|
|
4981
|
+
});
|
|
4982
|
+
return got;
|
|
4983
|
+
}
|
|
4984
|
+
var HHMM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
|
|
4985
|
+
function parseLocalTime(s) {
|
|
4986
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(s.trim());
|
|
4987
|
+
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] ?? 0)).getTime();
|
|
4988
|
+
return /[zZ]|[+-]\d{2}:?\d{2}$/.test(s) ? Date.parse(s) : NaN;
|
|
4989
|
+
}
|
|
4990
|
+
function formatLocalTime(ms) {
|
|
4991
|
+
const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
|
|
4992
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
4993
|
+
}
|
|
4994
|
+
var 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 };
|
|
4995
|
+
function parseCron(expr) {
|
|
4996
|
+
const f = expr.trim().split(/\s+/);
|
|
4997
|
+
if (f.length !== 5) throw new Error(`cron needs five fields (minute hour day month weekday), got "${expr}"`);
|
|
4998
|
+
const field = (s, lo, hi, what) => {
|
|
4999
|
+
const out = /* @__PURE__ */ new Set();
|
|
5000
|
+
for (const part of s.toLowerCase().split(",")) {
|
|
5001
|
+
const [range, stepS] = part.split("/");
|
|
5002
|
+
const step = stepS === void 0 ? 1 : Number(stepS);
|
|
5003
|
+
if (!Number.isInteger(step) || step < 1) throw new Error(`cron ${what}: bad step in "${part}"`);
|
|
5004
|
+
const num = (x) => {
|
|
5005
|
+
const n = CRON_NAMES[x] ?? Number(x);
|
|
5006
|
+
if (!Number.isInteger(n)) throw new Error(`cron ${what}: "${x}" is not a number`);
|
|
5007
|
+
return n;
|
|
5008
|
+
};
|
|
5009
|
+
let a, b;
|
|
5010
|
+
if (range === "*") {
|
|
5011
|
+
a = lo;
|
|
5012
|
+
b = hi;
|
|
5013
|
+
} else if (range.includes("-")) {
|
|
5014
|
+
const [x, y] = range.split("-");
|
|
5015
|
+
a = num(x);
|
|
5016
|
+
b = num(y);
|
|
5017
|
+
} else {
|
|
5018
|
+
a = num(range);
|
|
5019
|
+
b = stepS === void 0 ? a : hi;
|
|
5020
|
+
}
|
|
5021
|
+
if (what === "weekday") {
|
|
5022
|
+
if (a === 7) a = 0;
|
|
5023
|
+
if (b === 7 && a !== 0) b = 6, out.add(0);
|
|
5024
|
+
}
|
|
5025
|
+
if (a < lo || b > hi || a > b) throw new Error(`cron ${what}: "${part}" is outside ${lo}-${hi}`);
|
|
5026
|
+
for (let n = a; n <= b; n += step) out.add(n);
|
|
5027
|
+
}
|
|
5028
|
+
return out;
|
|
5029
|
+
};
|
|
5030
|
+
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] === "*" };
|
|
5031
|
+
}
|
|
5032
|
+
function cronNext(c, after) {
|
|
5033
|
+
const start = new Date(after);
|
|
5034
|
+
start.setSeconds(0, 0);
|
|
5035
|
+
start.setMinutes(start.getMinutes() + 1);
|
|
5036
|
+
const hours = [...c.hour].sort((a, b) => a - b), mins = [...c.min].sort((a, b) => a - b);
|
|
5037
|
+
for (let day = 0; day < 366 * 5; day++) {
|
|
5038
|
+
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + day);
|
|
5039
|
+
if (!c.mon.has(d.getMonth() + 1)) continue;
|
|
5040
|
+
const domOk = c.dom.has(d.getDate()), dowOk = c.dow.has(d.getDay());
|
|
5041
|
+
if (!(c.domAny && c.dowAny ? true : c.domAny ? dowOk : c.dowAny ? domOk : domOk || dowOk)) continue;
|
|
5042
|
+
for (const h of hours) for (const m of mins) {
|
|
5043
|
+
const t = new Date(d.getFullYear(), d.getMonth(), d.getDate(), h, m).getTime();
|
|
5044
|
+
if (t >= start.getTime()) return t;
|
|
5045
|
+
}
|
|
5046
|
+
}
|
|
5047
|
+
return null;
|
|
5048
|
+
}
|
|
5049
|
+
function checkSchedule(s, minMinutes = 1) {
|
|
5050
|
+
switch (s?.type) {
|
|
5051
|
+
case "once":
|
|
5052
|
+
return Number.isFinite(parseLocalTime(s.at)) ? void 0 : `"at" must be a local time like 2026-11-28 09:00, got "${s.at}"`;
|
|
5053
|
+
case "every":
|
|
5054
|
+
return Number.isFinite(s.minutes) && s.minutes >= minMinutes ? void 0 : `"minutes" must be at least ${minMinutes}`;
|
|
5055
|
+
case "daily":
|
|
5056
|
+
if (!HHMM.test(s.time ?? "")) return `"time" must be HH:mm, got "${s.time}"`;
|
|
5057
|
+
if (s.days && (!s.days.length || s.days.some((d) => !Number.isInteger(d) || d < 0 || d > 6))) return `"days" must be weekday numbers 0 (Sunday) to 6`;
|
|
5058
|
+
return void 0;
|
|
5059
|
+
case "cron": {
|
|
5060
|
+
try {
|
|
5061
|
+
const c = parseCron(s.cron);
|
|
5062
|
+
if (cronNext(c, Date.now()) === null) return "this cron never runs";
|
|
5063
|
+
} catch (err) {
|
|
5064
|
+
return err.message;
|
|
5065
|
+
}
|
|
5066
|
+
if (minMinutes > 1) {
|
|
5067
|
+
const c = parseCron(s.cron);
|
|
5068
|
+
const a = cronNext(c, Date.now()), b = cronNext(c, a);
|
|
5069
|
+
if (b !== null && b - a < minMinutes * 6e4) return `runs more often than every ${minMinutes} minutes`;
|
|
5070
|
+
}
|
|
5071
|
+
return void 0;
|
|
5072
|
+
}
|
|
5073
|
+
default:
|
|
5074
|
+
return `"type" must be once, every, daily or cron`;
|
|
5075
|
+
}
|
|
5076
|
+
}
|
|
5077
|
+
function nextRun(s, after, from = after) {
|
|
5078
|
+
switch (s.type) {
|
|
5079
|
+
case "once": {
|
|
5080
|
+
const t = parseLocalTime(s.at);
|
|
5081
|
+
return Number.isFinite(t) && t > after ? t : null;
|
|
5082
|
+
}
|
|
5083
|
+
case "every": {
|
|
5084
|
+
const p = s.minutes * 6e4;
|
|
5085
|
+
let t = from + p;
|
|
5086
|
+
if (t <= after) t = after + p;
|
|
5087
|
+
return t;
|
|
5088
|
+
}
|
|
5089
|
+
case "daily": {
|
|
5090
|
+
const m = HHMM.exec(s.time);
|
|
5091
|
+
if (!m) return null;
|
|
5092
|
+
const base = new Date(after);
|
|
5093
|
+
for (let day = 0; day < 8; day++) {
|
|
5094
|
+
const d = new Date(base.getFullYear(), base.getMonth(), base.getDate() + day, +m[1], +m[2]);
|
|
5095
|
+
if (d.getTime() > after && (!s.days?.length || s.days.includes(d.getDay()))) return d.getTime();
|
|
5096
|
+
}
|
|
5097
|
+
return null;
|
|
5098
|
+
}
|
|
5099
|
+
case "cron":
|
|
5100
|
+
try {
|
|
5101
|
+
return cronNext(parseCron(s.cron), after);
|
|
5102
|
+
} catch {
|
|
5103
|
+
return null;
|
|
5104
|
+
}
|
|
5105
|
+
}
|
|
5106
|
+
}
|
|
5107
|
+
var DAY_EN = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
5108
|
+
var DAY_ZH = ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"];
|
|
5109
|
+
function describeSchedule(s, locale = "en") {
|
|
5110
|
+
const zh = locale === "zh";
|
|
5111
|
+
switch (s.type) {
|
|
5112
|
+
case "once": {
|
|
5113
|
+
const t = parseLocalTime(s.at);
|
|
5114
|
+
return (zh ? "\u4E00\u6B21 \xB7 " : "Once \xB7 ") + (Number.isFinite(t) ? formatLocalTime(t) : s.at);
|
|
5115
|
+
}
|
|
5116
|
+
case "every": {
|
|
5117
|
+
const m = s.minutes;
|
|
5118
|
+
const v = m % 1440 === 0 ? zh ? `${m / 1440} \u5929` : `${m / 1440} d` : m % 60 === 0 ? zh ? `${m / 60} \u5C0F\u65F6` : `${m / 60} h` : zh ? `${m} \u5206\u949F` : `${m} min`;
|
|
5119
|
+
return zh ? `\u6BCF ${v}` : `Every ${v}`;
|
|
5120
|
+
}
|
|
5121
|
+
case "daily": {
|
|
5122
|
+
const days = [...new Set(s.days ?? [])].sort((a, b) => a - b);
|
|
5123
|
+
if (!days.length || days.length === 7) return (zh ? "\u6BCF\u5929 " : "Daily ") + s.time;
|
|
5124
|
+
if (days.join() === "1,2,3,4,5") return (zh ? "\u5DE5\u4F5C\u65E5 " : "Weekdays ") + s.time;
|
|
5125
|
+
if (days.join() === "0,6") return (zh ? "\u5468\u672B " : "Weekends ") + s.time;
|
|
5126
|
+
return (zh ? "\u6BCF\u5468" + days.map((d) => DAY_ZH[d]).join("\u3001") + " " : days.map((d) => DAY_EN[d]).join(", ") + " ") + s.time;
|
|
5127
|
+
}
|
|
5128
|
+
case "cron":
|
|
5129
|
+
return `cron ${s.cron}`;
|
|
5130
|
+
}
|
|
5131
|
+
}
|
|
5132
|
+
var newTaskId = () => `t_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
5133
|
+
function makeTask(fields, limits = {}, now = Date.now()) {
|
|
5134
|
+
const name = fields.name?.trim(), prompt = fields.prompt?.trim();
|
|
5135
|
+
if (!name) throw new Error("a task needs a name");
|
|
5136
|
+
if (!prompt) throw new Error("a task needs a prompt");
|
|
5137
|
+
const problem = checkSchedule(fields.schedule, limits.minMinutes ?? 5);
|
|
5138
|
+
if (problem) throw new Error(problem);
|
|
5139
|
+
const enabled = fields.enabled ?? true;
|
|
5140
|
+
const next = enabled ? nextRun(fields.schedule, now) : null;
|
|
5141
|
+
if (enabled && next === null) throw new Error("that time has already passed");
|
|
5142
|
+
return { id: newTaskId(), name, prompt, schedule: fields.schedule, enabled, next, by: fields.by, created: now, updated: now, runs: 0 };
|
|
5143
|
+
}
|
|
5144
|
+
function changeTask(task, patch, limits = {}, now = Date.now()) {
|
|
5145
|
+
const out = { ...task, updated: now };
|
|
5146
|
+
if (patch.name !== void 0) {
|
|
5147
|
+
if (!patch.name.trim()) throw new Error("a task needs a name");
|
|
5148
|
+
out.name = patch.name.trim();
|
|
5149
|
+
}
|
|
5150
|
+
if (patch.prompt !== void 0) {
|
|
5151
|
+
if (!patch.prompt.trim()) throw new Error("a task needs a prompt");
|
|
5152
|
+
out.prompt = patch.prompt.trim();
|
|
5153
|
+
}
|
|
5154
|
+
if (patch.schedule) {
|
|
5155
|
+
const problem = checkSchedule(patch.schedule, limits.minMinutes ?? 5);
|
|
5156
|
+
if (problem) throw new Error(problem);
|
|
5157
|
+
out.schedule = patch.schedule;
|
|
5158
|
+
}
|
|
5159
|
+
if (patch.enabled !== void 0) out.enabled = patch.enabled;
|
|
5160
|
+
if (patch.schedule || patch.enabled !== void 0) {
|
|
5161
|
+
out.next = out.enabled ? nextRun(out.schedule, now) : null;
|
|
5162
|
+
if (out.enabled && out.next === null) throw new Error("that time has already passed");
|
|
5163
|
+
}
|
|
5164
|
+
return out;
|
|
5165
|
+
}
|
|
5166
|
+
var SCHEDULE_SCHEMA = {
|
|
5167
|
+
type: "object",
|
|
5168
|
+
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 \u2026 6 = Saturday; [1,2,3,4,5] for weekdays). type "cron": cron (five fields, local time).`,
|
|
5169
|
+
properties: {
|
|
5170
|
+
type: { type: "string", enum: ["once", "every", "daily", "cron"] },
|
|
5171
|
+
at: { type: "string" },
|
|
5172
|
+
in_minutes: { type: "number" },
|
|
5173
|
+
minutes: { type: "number" },
|
|
5174
|
+
time: { type: "string" },
|
|
5175
|
+
days: { type: "array", items: { type: "integer", minimum: 0, maximum: 6 } },
|
|
5176
|
+
cron: { type: "string" }
|
|
5177
|
+
},
|
|
5178
|
+
required: ["type"],
|
|
5179
|
+
additionalProperties: false
|
|
5180
|
+
};
|
|
5181
|
+
function toSchedule(a, now) {
|
|
5182
|
+
switch (a.type) {
|
|
5183
|
+
case "once":
|
|
5184
|
+
return { type: "once", at: a.at ?? (a.in_minutes !== void 0 ? formatLocalTime(now + Math.max(1, Math.round(a.in_minutes)) * 6e4) : "") };
|
|
5185
|
+
case "every":
|
|
5186
|
+
return { type: "every", minutes: Math.round(a.minutes ?? 0) };
|
|
5187
|
+
case "daily":
|
|
5188
|
+
return { type: "daily", time: a.time ?? "", ...a.days?.length ? { days: a.days } : {} };
|
|
5189
|
+
case "cron":
|
|
5190
|
+
return { type: "cron", cron: a.cron ?? "" };
|
|
5191
|
+
}
|
|
5192
|
+
}
|
|
5193
|
+
function taskLine(t, now = Date.now()) {
|
|
5194
|
+
return {
|
|
5195
|
+
id: t.id,
|
|
5196
|
+
name: t.name,
|
|
5197
|
+
prompt: t.prompt,
|
|
5198
|
+
schedule: describeSchedule(t.schedule),
|
|
5199
|
+
enabled: t.enabled,
|
|
5200
|
+
next: t.next ? formatLocalTime(t.next) : null,
|
|
5201
|
+
runs: t.runs,
|
|
5202
|
+
...t.last ? { last_run: `${formatLocalTime(t.last.at)} ${t.last.status}${t.last.note ? ": " + t.last.note : ""}` } : {},
|
|
5203
|
+
...t.next && t.next < now ? { overdue: true } : {}
|
|
5204
|
+
};
|
|
5205
|
+
}
|
|
5206
|
+
function scheduleTools(store, opts = {}) {
|
|
5207
|
+
const now = opts.now ?? Date.now;
|
|
5208
|
+
const tz = (() => {
|
|
5209
|
+
try {
|
|
5210
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
5211
|
+
} catch {
|
|
5212
|
+
return "local";
|
|
5213
|
+
}
|
|
5214
|
+
})();
|
|
5215
|
+
const changed = () => {
|
|
5216
|
+
try {
|
|
5217
|
+
opts.onChange?.();
|
|
5218
|
+
} catch {
|
|
5219
|
+
}
|
|
5220
|
+
};
|
|
5221
|
+
const header = () => `Now: ${formatLocalTime(now())} (${tz}).`;
|
|
5222
|
+
return [
|
|
5223
|
+
defineTool({
|
|
5224
|
+
name: "schedule_list",
|
|
5225
|
+
description: "Lists the scheduled tasks: prompts this app's agent runs on its own at set times (while the app is open).",
|
|
5226
|
+
readOnly: true,
|
|
5227
|
+
display: { label: () => "Scheduled tasks" },
|
|
5228
|
+
execute: async () => {
|
|
5229
|
+
const list = await store.list();
|
|
5230
|
+
return `${header()}
|
|
5231
|
+
${list.length ? JSON.stringify(list.map((t) => taskLine(t, now())), null, 1) : "No scheduled tasks."}`;
|
|
5232
|
+
}
|
|
5233
|
+
}),
|
|
5234
|
+
defineTool({
|
|
5235
|
+
name: "schedule_add",
|
|
5236
|
+
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.`,
|
|
5237
|
+
parameters: {
|
|
5238
|
+
type: "object",
|
|
5239
|
+
properties: {
|
|
5240
|
+
name: { type: "string", description: 'Short name the user sees, e.g. "Morning news digest".' },
|
|
5241
|
+
prompt: { type: "string", description: "The instruction for each run, complete on its own." },
|
|
5242
|
+
schedule: SCHEDULE_SCHEMA,
|
|
5243
|
+
enabled: { type: "boolean", description: "Default true." }
|
|
5244
|
+
},
|
|
5245
|
+
required: ["name", "prompt", "schedule"],
|
|
5246
|
+
additionalProperties: false
|
|
5247
|
+
},
|
|
5248
|
+
display: { label: (a) => `Schedule \u201C${a.name ?? ""}\u201D` },
|
|
5249
|
+
execute: async (a) => {
|
|
5250
|
+
const list = await store.list();
|
|
5251
|
+
if (list.length >= (opts.maxTasks ?? 20)) throw new Error(`there are already ${list.length} tasks, the most allowed; remove one first`);
|
|
5252
|
+
const task = makeTask({ name: a.name, prompt: a.prompt, schedule: toSchedule(a.schedule, now()), enabled: a.enabled, by: "agent" }, opts, now());
|
|
5253
|
+
await store.put(task);
|
|
5254
|
+
changed();
|
|
5255
|
+
return `${header()}
|
|
5256
|
+
Added: ${JSON.stringify(taskLine(task, now()))}`;
|
|
5257
|
+
}
|
|
5258
|
+
}),
|
|
5259
|
+
defineTool({
|
|
5260
|
+
name: "schedule_update",
|
|
5261
|
+
description: "Changes a scheduled task (by id, from schedule_list): its name, prompt, schedule, or enabled (false pauses it).",
|
|
5262
|
+
parameters: {
|
|
5263
|
+
type: "object",
|
|
5264
|
+
properties: { id: { type: "string" }, name: { type: "string" }, prompt: { type: "string" }, schedule: SCHEDULE_SCHEMA, enabled: { type: "boolean" } },
|
|
5265
|
+
required: ["id"],
|
|
5266
|
+
additionalProperties: false
|
|
5267
|
+
},
|
|
5268
|
+
display: { label: (a) => `Update scheduled task ${a.id ?? ""}` },
|
|
5269
|
+
execute: async (a) => {
|
|
5270
|
+
const task = await store.get(a.id);
|
|
5271
|
+
if (!task) throw new Error(`no task with id ${a.id}; schedule_list shows them`);
|
|
5272
|
+
const next = changeTask(task, { name: a.name, prompt: a.prompt, schedule: a.schedule ? toSchedule(a.schedule, now()) : void 0, enabled: a.enabled }, opts, now());
|
|
5273
|
+
await store.put(next);
|
|
5274
|
+
changed();
|
|
5275
|
+
return `${header()}
|
|
5276
|
+
Updated: ${JSON.stringify(taskLine(next, now()))}`;
|
|
5277
|
+
}
|
|
5278
|
+
}),
|
|
5279
|
+
defineTool({
|
|
5280
|
+
name: "schedule_remove",
|
|
5281
|
+
description: "Removes a scheduled task (by id). Its conversation stays.",
|
|
5282
|
+
parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"], additionalProperties: false },
|
|
5283
|
+
display: { label: (a) => `Remove scheduled task ${a.id ?? ""}` },
|
|
5284
|
+
execute: async (a) => {
|
|
5285
|
+
const task = await store.get(a.id);
|
|
5286
|
+
if (!task) throw new Error(`no task with id ${a.id}`);
|
|
5287
|
+
await store.delete(a.id);
|
|
5288
|
+
changed();
|
|
5289
|
+
return `Removed \u201C${task.name}\u201D.`;
|
|
5290
|
+
}
|
|
5291
|
+
})
|
|
5292
|
+
];
|
|
5293
|
+
}
|
|
5294
|
+
var Scheduler = class {
|
|
5295
|
+
constructor(opts) {
|
|
5296
|
+
__publicField(this, "opts", opts);
|
|
5297
|
+
__publicField(this, "timer", null);
|
|
5298
|
+
__publicField(this, "busy", false);
|
|
5299
|
+
__publicField(this, "unsub", null);
|
|
5300
|
+
/** Ids of tasks this tab is running now. */
|
|
5301
|
+
__publicField(this, "running", /* @__PURE__ */ new Set());
|
|
5302
|
+
__publicField(this, "poke", () => void this.tick());
|
|
5303
|
+
}
|
|
5304
|
+
start() {
|
|
5305
|
+
if (this.timer) return;
|
|
5306
|
+
this.timer = setInterval(() => void this.tick(), this.opts.interval ?? 2e4);
|
|
5307
|
+
this.unsub = this.opts.store.subscribe?.(() => this.opts.onChange?.()) ?? null;
|
|
5308
|
+
if (typeof window !== "undefined") window.addEventListener("focus", this.poke);
|
|
5309
|
+
void this.tick();
|
|
5310
|
+
}
|
|
5311
|
+
stop() {
|
|
5312
|
+
if (this.timer) clearInterval(this.timer);
|
|
5313
|
+
this.timer = null;
|
|
5314
|
+
this.unsub?.();
|
|
5315
|
+
this.unsub = null;
|
|
5316
|
+
if (typeof window !== "undefined") window.removeEventListener("focus", this.poke);
|
|
5317
|
+
}
|
|
5318
|
+
/** Looks for a due task and runs it when idle. Resolves once that run is over. */
|
|
5319
|
+
async tick() {
|
|
5320
|
+
if (this.busy || !this.opts.idle()) return;
|
|
5321
|
+
const now = (this.opts.now ?? Date.now)();
|
|
5322
|
+
const due = (await this.opts.store.list()).filter((t) => t.enabled && t.next !== null && t.next <= now).sort((a, b) => a.next - b.next);
|
|
5323
|
+
for (const t of due) {
|
|
5324
|
+
if (this.busy || !this.opts.idle()) return;
|
|
5325
|
+
if (await this.fire(t.id, false)) return;
|
|
5326
|
+
}
|
|
5327
|
+
}
|
|
5328
|
+
/** Runs a task now (the user's "Run now"), whatever its time; false when it is already running somewhere. */
|
|
5329
|
+
runNow(id) {
|
|
5330
|
+
return this.fire(id, true);
|
|
5331
|
+
}
|
|
5332
|
+
async fire(id, force) {
|
|
5333
|
+
if (this.busy) return false;
|
|
5334
|
+
this.busy = true;
|
|
5335
|
+
let ran = false;
|
|
5336
|
+
try {
|
|
5337
|
+
await tryLock(`${this.opts.lockPrefix}:task:${id}`, async () => {
|
|
5338
|
+
const store = this.opts.store, clock = this.opts.now ?? Date.now;
|
|
5339
|
+
const task = await store.get(id);
|
|
5340
|
+
const now = clock();
|
|
5341
|
+
if (!task || !force && (!task.enabled || task.next === null || task.next > now)) return;
|
|
5342
|
+
const next = task.enabled ? nextRun(task.schedule, now, now) : task.next;
|
|
5343
|
+
await store.put({ ...task, next: task.schedule.type === "once" && !force ? null : next, ...task.schedule.type === "once" && !force ? { enabled: false } : {} });
|
|
5344
|
+
ran = true;
|
|
5345
|
+
this.running.add(id);
|
|
5346
|
+
this.opts.onChange?.();
|
|
5347
|
+
let out;
|
|
5348
|
+
try {
|
|
5349
|
+
out = await this.opts.run(task);
|
|
5350
|
+
} catch (err) {
|
|
5351
|
+
out = { status: "error", note: err.message };
|
|
5352
|
+
}
|
|
5353
|
+
this.running.delete(id);
|
|
5354
|
+
const after = await store.get(id);
|
|
5355
|
+
if (after) await store.put({ ...after, runs: after.runs + 1, last: { at: now, ...out } });
|
|
5356
|
+
this.opts.onChange?.();
|
|
5357
|
+
});
|
|
5358
|
+
return ran;
|
|
5359
|
+
} finally {
|
|
5360
|
+
this.busy = false;
|
|
5361
|
+
}
|
|
5362
|
+
}
|
|
5363
|
+
};
|
|
5364
|
+
|
|
4888
5365
|
// src/mcp.ts
|
|
4889
5366
|
var PROTOCOL_VERSION = "2025-06-18";
|
|
4890
5367
|
var MCPError = class extends Error {
|