@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.
- package/README.md +1 -1
- package/dist/agent-core.umd.js +90 -87
- package/dist/agent.d.ts +25 -1
- package/dist/agent.js +11 -7
- package/dist/agent.umd.js +140 -107
- package/dist/chat.d.ts +77 -8
- package/dist/chat.js +526 -49
- package/dist/debug-panel.d.ts +1 -1
- package/dist/debug-panel.js +1 -1
- package/dist/dialogs.js +43 -1
- package/dist/dom.d.ts +28 -1
- package/dist/dom.js +38 -1
- package/dist/files-panel.js +2 -2
- package/dist/index.cjs +555 -38
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -0
- package/dist/schedule.d.ts +152 -0
- package/dist/schedule.js +505 -0
- package/dist/types.d.ts +39 -2
- package/dist/ui.cjs +1094 -43
- package/dist/ui.d.ts +2 -0
- package/dist/vlist.d.ts +6 -0
- package/dist/vlist.js +16 -0
- package/docs/chat-ui.md +72 -1
- package/docs/tools.md +1 -0
- 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();
|
|
@@ -3433,7 +3445,8 @@ function domUI() {
|
|
|
3433
3445
|
button(zh ? "\u53D6\u6D88" : "Cancel", false, false, () => done(null)),
|
|
3434
3446
|
button(zh ? "\u786E\u5B9A" : "OK", true, false, () => {
|
|
3435
3447
|
const picked = inputs.filter((i) => i.checked).map((i) => i.value === "__other__" ? other?.value.trim() || "" : i.value).filter(Boolean);
|
|
3436
|
-
|
|
3448
|
+
const min = opts.multi ? opts.min ?? 1 : 1, max = opts.multi ? opts.max : void 0;
|
|
3449
|
+
if (picked.length < min || max !== void 0 && picked.length > max) return;
|
|
3437
3450
|
done(picked);
|
|
3438
3451
|
})
|
|
3439
3452
|
);
|
|
@@ -3465,6 +3478,45 @@ function domUI() {
|
|
|
3465
3478
|
}, opts.signal, null);
|
|
3466
3479
|
return typeof v === "string" ? v : null;
|
|
3467
3480
|
},
|
|
3481
|
+
async form(title, fields, opts = {}) {
|
|
3482
|
+
const zh = isZh();
|
|
3483
|
+
const v = await openDialog((d, done) => {
|
|
3484
|
+
d.append(el("div", "font-weight:600;font-size:15px;margin-bottom:6px", title));
|
|
3485
|
+
if (opts.message) d.append(el("div", "white-space:pre-wrap;opacity:.8;font-size:13px;margin-bottom:10px", opts.message));
|
|
3486
|
+
const inputs = fields.map((f) => {
|
|
3487
|
+
const label = el("label", "display:block;font-size:13px;margin:8px 0");
|
|
3488
|
+
label.append(el("div", "opacity:.8;margin-bottom:4px", (f.label ?? f.name) + (f.required ? " *" : "")));
|
|
3489
|
+
const input = el("input", "font:inherit;padding:8px 10px;border:1px solid rgba(127,127,127,.35);border-radius:8px;background:transparent;color:inherit;width:100%;box-sizing:border-box");
|
|
3490
|
+
input.type = f.type === "number" ? "number" : "text";
|
|
3491
|
+
if (f.type === "number") input.step = "any";
|
|
3492
|
+
if (f.placeholder) input.placeholder = f.placeholder;
|
|
3493
|
+
if (f.initial !== void 0) input.value = String(f.initial);
|
|
3494
|
+
label.append(input);
|
|
3495
|
+
d.append(label);
|
|
3496
|
+
return { f, input };
|
|
3497
|
+
});
|
|
3498
|
+
const submit = () => {
|
|
3499
|
+
const out = {};
|
|
3500
|
+
for (const { f, input } of inputs) {
|
|
3501
|
+
const raw = input.value.trim();
|
|
3502
|
+
if (!raw && f.required || raw && f.type === "number" && !Number.isFinite(Number(raw))) {
|
|
3503
|
+
input.focus();
|
|
3504
|
+
return;
|
|
3505
|
+
}
|
|
3506
|
+
if (raw) out[f.name] = f.type === "number" ? Number(raw) : raw;
|
|
3507
|
+
}
|
|
3508
|
+
done(out);
|
|
3509
|
+
};
|
|
3510
|
+
const row = el("div", "display:flex;justify-content:flex-end;gap:8px;margin-top:12px");
|
|
3511
|
+
row.append(
|
|
3512
|
+
button(zh ? "\u53D6\u6D88" : "Cancel", false, false, () => done(null)),
|
|
3513
|
+
button(opts.ok ?? (zh ? "\u786E\u5B9A" : "OK"), true, false, submit)
|
|
3514
|
+
);
|
|
3515
|
+
d.append(row);
|
|
3516
|
+
queueMicrotask(() => inputs[0]?.input.focus());
|
|
3517
|
+
}, opts.signal, null);
|
|
3518
|
+
return v && typeof v === "object" && !Array.isArray(v) ? v : null;
|
|
3519
|
+
},
|
|
3468
3520
|
notify(message, level = "info") {
|
|
3469
3521
|
const host = el("div", [
|
|
3470
3522
|
"position:fixed",
|
|
@@ -3699,7 +3751,7 @@ var Agent = class {
|
|
|
3699
3751
|
__publicField(this, "loaded");
|
|
3700
3752
|
__publicField(this, "createdAt", Date.now());
|
|
3701
3753
|
/** The session's title, fixed once known (a later compaction must not turn it into the summary's first words). */
|
|
3702
|
-
__publicField(this, "
|
|
3754
|
+
__publicField(this, "fixedTitle");
|
|
3703
3755
|
__publicField(this, "_ended", null);
|
|
3704
3756
|
__publicField(this, "persist");
|
|
3705
3757
|
this.provider = toProvider(provider);
|
|
@@ -3747,6 +3799,14 @@ var Agent = class {
|
|
|
3747
3799
|
this.loaded = Promise.resolve();
|
|
3748
3800
|
}
|
|
3749
3801
|
}
|
|
3802
|
+
/** 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. */
|
|
3803
|
+
get title() {
|
|
3804
|
+
return this.fixedTitle;
|
|
3805
|
+
}
|
|
3806
|
+
/** Fixes the conversation's title (a scheduled task's name, say); saved with the session. */
|
|
3807
|
+
setTitle(title) {
|
|
3808
|
+
this.fixedTitle = title.trim() || void 0;
|
|
3809
|
+
}
|
|
3750
3810
|
applySession(data) {
|
|
3751
3811
|
if (data.v !== 1 && data.v !== 2) throw new Error("unknown session format");
|
|
3752
3812
|
this.history = data.messages.slice();
|
|
@@ -3755,7 +3815,7 @@ var Agent = class {
|
|
|
3755
3815
|
this._usage = { ...data.usage };
|
|
3756
3816
|
this.createdAt = data.createdAt ?? data.savedAt ?? Date.now();
|
|
3757
3817
|
this._ended = data.ended ?? null;
|
|
3758
|
-
this.
|
|
3818
|
+
this.fixedTitle = data.title && !isMachineTitle(data.title) ? data.title : void 0;
|
|
3759
3819
|
if (data.model && !this.opts.model) {
|
|
3760
3820
|
this.opts.model = data.model;
|
|
3761
3821
|
this.catalogue = null;
|
|
@@ -3865,8 +3925,8 @@ var Agent = class {
|
|
|
3865
3925
|
* starts (`reserveTokens`) and how much of the newest it keeps verbatim
|
|
3866
3926
|
* (`keepRecentTokens`), each capped by the window (20 % / 40 %).
|
|
3867
3927
|
*/
|
|
3868
|
-
compactionFor(
|
|
3869
|
-
return { summarize: this.compactSummaries, ...resolveSettings(
|
|
3928
|
+
compactionFor(window2) {
|
|
3929
|
+
return { summarize: this.compactSummaries, ...resolveSettings(window2, this.compactThresholds) };
|
|
3870
3930
|
}
|
|
3871
3931
|
/** A snapshot to save (`restore` continues it). Taken at the last complete turn. */
|
|
3872
3932
|
export() {
|
|
@@ -3882,18 +3942,18 @@ var Agent = class {
|
|
|
3882
3942
|
savedAt: Date.now(),
|
|
3883
3943
|
...this._ended ? { ended: this._ended } : {}
|
|
3884
3944
|
};
|
|
3885
|
-
if (!this.
|
|
3945
|
+
if (!this.fixedTitle) {
|
|
3886
3946
|
const tt = titleOf(data);
|
|
3887
|
-
if (tt !== UNTITLED) this.
|
|
3947
|
+
if (tt !== UNTITLED) this.fixedTitle = tt;
|
|
3888
3948
|
}
|
|
3889
|
-
data.title = this.
|
|
3949
|
+
data.title = this.fixedTitle ?? UNTITLED;
|
|
3890
3950
|
return data;
|
|
3891
3951
|
}
|
|
3892
3952
|
/** Forgets the conversation (the workspace stays). */
|
|
3893
3953
|
reset() {
|
|
3894
3954
|
if (this.current) throw new Error("cannot reset while a run is active; abort() first");
|
|
3895
3955
|
this.history = [];
|
|
3896
|
-
this.
|
|
3956
|
+
this.fixedTitle = void 0;
|
|
3897
3957
|
this._ended = null;
|
|
3898
3958
|
this.committed = 0;
|
|
3899
3959
|
this.droppedTurns = 0;
|
|
@@ -4074,8 +4134,8 @@ var Agent = class {
|
|
|
4074
4134
|
this.emit("run_start", { runId, message: prefaced });
|
|
4075
4135
|
const maxTurns = this.opts.maxTurns ?? DEFAULT_MAX_TURNS;
|
|
4076
4136
|
const { output: maxTokens, input: catalogueWindow } = await this.limits();
|
|
4077
|
-
let
|
|
4078
|
-
let compaction = resolveSettings(
|
|
4137
|
+
let window2 = catalogueWindow;
|
|
4138
|
+
let compaction = resolveSettings(window2, this.compactThresholds);
|
|
4079
4139
|
let overflowRetries = 0;
|
|
4080
4140
|
try {
|
|
4081
4141
|
if (prefaceError) throw prefaceError;
|
|
@@ -4094,13 +4154,13 @@ var Agent = class {
|
|
|
4094
4154
|
const system = await this.systemPrompt();
|
|
4095
4155
|
const fixed = this.fixedText(system);
|
|
4096
4156
|
const tokensBefore = estimateTokens(this.history, fixed);
|
|
4097
|
-
if (shouldCompact(tokensBefore,
|
|
4157
|
+
if (shouldCompact(tokensBefore, window2, compaction)) {
|
|
4098
4158
|
const summarized = !this.compactSummaries ? false : await this.compactWith(compaction, runId, signal);
|
|
4099
4159
|
const after = estimateTokens(this.history, fixed);
|
|
4100
|
-
if (!summarized || shouldCompact(after,
|
|
4160
|
+
if (!summarized || shouldCompact(after, window2, compaction)) {
|
|
4101
4161
|
const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
|
|
4102
4162
|
const rest = this.history.slice(pinned.length);
|
|
4103
|
-
const fit = fitBudget(rest, { budget:
|
|
4163
|
+
const fit = fitBudget(rest, { budget: window2 - compaction.reserveTokens - estimateTokens(pinned), keepTurns: this.opts.keepTurns ?? 4, system: fixed });
|
|
4104
4164
|
if (fit.droppedTurns || fit.elidedResults) {
|
|
4105
4165
|
this.history = [...pinned, ...fit.messages];
|
|
4106
4166
|
this.droppedTurns += fit.droppedTurns;
|
|
@@ -4126,7 +4186,7 @@ var Agent = class {
|
|
|
4126
4186
|
const asked = Date.now();
|
|
4127
4187
|
let completion;
|
|
4128
4188
|
try {
|
|
4129
|
-
if (estimateTokens(this.history, fixed) >
|
|
4189
|
+
if (estimateTokens(this.history, fixed) > window2 * 2 && (typeof this.opts.maxInputTokens === "number" || typeof (await this.modelInfo())?.max_input_tokens === "number")) {
|
|
4130
4190
|
throw new ProviderError(413, "the request is far larger than the model's context");
|
|
4131
4191
|
}
|
|
4132
4192
|
completion = await this.callModel(params, runId, signal);
|
|
@@ -4134,17 +4194,17 @@ var Agent = class {
|
|
|
4134
4194
|
this.emit("response", { runId, turn, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
|
|
4135
4195
|
if (signal.aborted || !isContextOverflow(err)) throw err;
|
|
4136
4196
|
const limit = overflowLimit(err);
|
|
4137
|
-
if (limit !== void 0 && limit <
|
|
4138
|
-
|
|
4139
|
-
compaction = resolveSettings(
|
|
4197
|
+
if (limit !== void 0 && limit < window2) {
|
|
4198
|
+
window2 = limit;
|
|
4199
|
+
compaction = resolveSettings(window2, this.compactThresholds);
|
|
4140
4200
|
}
|
|
4141
4201
|
let smaller = false;
|
|
4142
|
-
while (!smaller && overflowRetries < 2) smaller = await this.squeeze(
|
|
4202
|
+
while (!smaller && overflowRetries < 2) smaller = await this.squeeze(window2, overflowRetries++, compaction, fixed, runId, signal);
|
|
4143
4203
|
if (smaller) {
|
|
4144
4204
|
turn--;
|
|
4145
4205
|
continue;
|
|
4146
4206
|
}
|
|
4147
|
-
throw new ContextOverflowError({ cause: this.overflowCause(
|
|
4207
|
+
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
4208
|
}
|
|
4149
4209
|
this.emit("response", { runId, turn, durationMs: Date.now() - asked, finishReason: completion.finishReason, usage: completion.usage, message: completion.message });
|
|
4150
4210
|
if (completion.usage) this.addUsage(completion.usage);
|
|
@@ -4325,8 +4385,8 @@ var Agent = class {
|
|
|
4325
4385
|
*/
|
|
4326
4386
|
compact(focus) {
|
|
4327
4387
|
return this.exclusive("compact", async (signal) => {
|
|
4328
|
-
const
|
|
4329
|
-
const settings = this.squeezed(resolveSettings(
|
|
4388
|
+
const window2 = await this.contextTokens();
|
|
4389
|
+
const settings = this.squeezed(resolveSettings(window2, this.compactThresholds));
|
|
4330
4390
|
const done = await this.compactWith(settings, void 0, signal, focus);
|
|
4331
4391
|
if (done) await this.saveSession();
|
|
4332
4392
|
return done;
|
|
@@ -4343,8 +4403,8 @@ var Agent = class {
|
|
|
4343
4403
|
const first = rest[0] ? summaryOf(rest[0]) : null;
|
|
4344
4404
|
const toSummarize = first === null ? rest : rest.slice(1);
|
|
4345
4405
|
if (!toSummarize.length) return first;
|
|
4346
|
-
const
|
|
4347
|
-
const settings = resolveSettings(
|
|
4406
|
+
const window2 = await this.contextTokens();
|
|
4407
|
+
const settings = resolveSettings(window2, this.compactThresholds);
|
|
4348
4408
|
this.emit("compaction_start", {});
|
|
4349
4409
|
try {
|
|
4350
4410
|
return await this.writeSummary({ toSummarize, previousSummary: first ?? void 0, kept: [] }, settings, void 0, signal);
|
|
@@ -4396,12 +4456,12 @@ var Agent = class {
|
|
|
4396
4456
|
* window (the estimate may run low); round 1 trims to 40%, big results of the
|
|
4397
4457
|
* latest turn included. True when the request did get smaller.
|
|
4398
4458
|
*/
|
|
4399
|
-
async squeeze(
|
|
4459
|
+
async squeeze(window2, round2, settings, fixed, runId, signal) {
|
|
4400
4460
|
const before = estimateTokens(this.history, fixed);
|
|
4401
4461
|
if (round2 === 0 && this.compactSummaries) await this.compactWith(this.squeezed(settings), runId, signal);
|
|
4402
4462
|
const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
|
|
4403
4463
|
const rest = this.history.slice(pinned.length);
|
|
4404
|
-
const budget = Math.floor(
|
|
4464
|
+
const budget = Math.floor(window2 * (round2 === 0 ? 0.7 : 0.4)) - estimateTokens(pinned);
|
|
4405
4465
|
const fit = fitBudget(rest, { budget, keepTurns: 1, system: fixed, keepResults: round2 === 0 ? 3 : 0 });
|
|
4406
4466
|
if (fit.droppedTurns || fit.elidedResults) {
|
|
4407
4467
|
this.history = [...pinned, ...fit.messages];
|
|
@@ -4412,13 +4472,13 @@ var Agent = class {
|
|
|
4412
4472
|
return estimateTokens(this.history, fixed) < before;
|
|
4413
4473
|
}
|
|
4414
4474
|
/** What takes up the room in a request that cannot be made smaller. */
|
|
4415
|
-
overflowCause(
|
|
4475
|
+
overflowCause(window2, fixed) {
|
|
4416
4476
|
const tools = this.tools.length ? estimateTokens([], JSON.stringify(this.tools.map((t) => toChatTool(t)))) : 0;
|
|
4417
4477
|
const latest = [...this.history].reverse().find((m) => m.role === "user" && summaryOf(m) === null);
|
|
4418
4478
|
const asked = latest ? estimateTokens([latest]) : 0;
|
|
4419
4479
|
const others = estimateTokens(this.history) - asked;
|
|
4420
4480
|
const biggest = Math.max(tools, asked, others);
|
|
4421
|
-
if (biggest * 2 <
|
|
4481
|
+
if (biggest * 2 < window2) return "model";
|
|
4422
4482
|
if (biggest === asked) {
|
|
4423
4483
|
const files = Array.isArray(latest.content) ? latest.content.length > 1 : /(^|\n)\[attachments\]/.test(String(latest.content ?? ""));
|
|
4424
4484
|
return files ? "attachments" : "message";
|
|
@@ -4662,7 +4722,7 @@ Fix the call and try again.`);
|
|
|
4662
4722
|
else if (tool.destructive) question = `Allow ${tool.name}?`;
|
|
4663
4723
|
if (question === false) return true;
|
|
4664
4724
|
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 } : {} });
|
|
4725
|
+
return this.ui.confirm(title, message, { danger: !!tool.destructive, signal, always, permission: true, ...ok ? { ok } : {}, ...body ? { body } : {} });
|
|
4666
4726
|
}
|
|
4667
4727
|
/** After an abort, every open tool call gets a result so the transcript stays valid. */
|
|
4668
4728
|
closeOpenToolCalls() {
|
|
@@ -4746,8 +4806,8 @@ Fix the call and try again.`);
|
|
|
4746
4806
|
}
|
|
4747
4807
|
/** How full the model's context is: tokens the next call would send (estimated) against the window. */
|
|
4748
4808
|
async context() {
|
|
4749
|
-
const [
|
|
4750
|
-
return { used: estimateTokens(this.history, this.fixedText(system)), window };
|
|
4809
|
+
const [window2, system] = await Promise.all([this.contextTokens(), this.systemPrompt().catch(() => "")]);
|
|
4810
|
+
return { used: estimateTokens(this.history, this.fixedText(system)), window: window2 };
|
|
4751
4811
|
}
|
|
4752
4812
|
/**
|
|
4753
4813
|
* The files whose contents are still in the conversation: read (with the
|
|
@@ -4885,6 +4945,463 @@ function round(n) {
|
|
|
4885
4945
|
return Math.round(n * 1e6) / 1e6;
|
|
4886
4946
|
}
|
|
4887
4947
|
|
|
4948
|
+
// src/schedule.ts
|
|
4949
|
+
function localSchedules(key) {
|
|
4950
|
+
const read = () => {
|
|
4951
|
+
try {
|
|
4952
|
+
const v = JSON.parse(localStorage.getItem(key) || "[]");
|
|
4953
|
+
return Array.isArray(v) ? v : [];
|
|
4954
|
+
} catch {
|
|
4955
|
+
return [];
|
|
4956
|
+
}
|
|
4957
|
+
};
|
|
4958
|
+
const write = (list) => {
|
|
4959
|
+
try {
|
|
4960
|
+
if (list.length) localStorage.setItem(key, JSON.stringify(list));
|
|
4961
|
+
else localStorage.removeItem(key);
|
|
4962
|
+
} catch {
|
|
4963
|
+
}
|
|
4964
|
+
};
|
|
4965
|
+
const change = (fn) => lock(`${key}:write`, async () => {
|
|
4966
|
+
write(fn(read()));
|
|
4967
|
+
});
|
|
4968
|
+
return {
|
|
4969
|
+
list: async () => read(),
|
|
4970
|
+
get: async (id) => read().find((t) => t.id === id),
|
|
4971
|
+
put: (task) => change((list) => {
|
|
4972
|
+
const i = list.findIndex((t) => t.id === task.id);
|
|
4973
|
+
if (i >= 0) list[i] = task;
|
|
4974
|
+
else list.push(task);
|
|
4975
|
+
return list;
|
|
4976
|
+
}),
|
|
4977
|
+
delete: (id) => change((list) => list.filter((t) => t.id !== id)),
|
|
4978
|
+
subscribe(fn) {
|
|
4979
|
+
if (typeof window === "undefined") return () => {
|
|
4980
|
+
};
|
|
4981
|
+
const on = (e) => {
|
|
4982
|
+
if (e.key === key) fn();
|
|
4983
|
+
};
|
|
4984
|
+
window.addEventListener("storage", on);
|
|
4985
|
+
return () => window.removeEventListener("storage", on);
|
|
4986
|
+
}
|
|
4987
|
+
};
|
|
4988
|
+
}
|
|
4989
|
+
function memorySchedules(initial = []) {
|
|
4990
|
+
const map = new Map(initial.map((t) => [t.id, structuredClone(t)]));
|
|
4991
|
+
return {
|
|
4992
|
+
list: async () => [...map.values()].map((t) => structuredClone(t)),
|
|
4993
|
+
get: async (id) => {
|
|
4994
|
+
const t = map.get(id);
|
|
4995
|
+
return t && structuredClone(t);
|
|
4996
|
+
},
|
|
4997
|
+
put: async (task) => {
|
|
4998
|
+
map.set(task.id, structuredClone(task));
|
|
4999
|
+
},
|
|
5000
|
+
delete: async (id) => {
|
|
5001
|
+
map.delete(id);
|
|
5002
|
+
}
|
|
5003
|
+
};
|
|
5004
|
+
}
|
|
5005
|
+
var locks = () => typeof navigator !== "undefined" ? navigator.locks : void 0;
|
|
5006
|
+
function lock(name, fn) {
|
|
5007
|
+
const l = locks();
|
|
5008
|
+
return l ? l.request(name, {}, fn) : fn();
|
|
5009
|
+
}
|
|
5010
|
+
async function tryLock(name, fn) {
|
|
5011
|
+
const l = locks();
|
|
5012
|
+
if (!l) {
|
|
5013
|
+
await fn();
|
|
5014
|
+
return true;
|
|
5015
|
+
}
|
|
5016
|
+
let got = false;
|
|
5017
|
+
await l.request(name, { ifAvailable: true }, async (held) => {
|
|
5018
|
+
if (!held) return;
|
|
5019
|
+
got = true;
|
|
5020
|
+
await fn();
|
|
5021
|
+
});
|
|
5022
|
+
return got;
|
|
5023
|
+
}
|
|
5024
|
+
var HHMM = /^([01]?\d|2[0-3]):([0-5]\d)$/;
|
|
5025
|
+
function parseLocalTime(s) {
|
|
5026
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(s.trim());
|
|
5027
|
+
if (m) return new Date(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +(m[6] ?? 0)).getTime();
|
|
5028
|
+
return /[zZ]|[+-]\d{2}:?\d{2}$/.test(s) ? Date.parse(s) : NaN;
|
|
5029
|
+
}
|
|
5030
|
+
function formatLocalTime(ms) {
|
|
5031
|
+
const d = new Date(ms), p = (n) => String(n).padStart(2, "0");
|
|
5032
|
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}`;
|
|
5033
|
+
}
|
|
5034
|
+
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 };
|
|
5035
|
+
function parseCron(expr) {
|
|
5036
|
+
const f = expr.trim().split(/\s+/);
|
|
5037
|
+
if (f.length !== 5) throw new Error(`cron needs five fields (minute hour day month weekday), got "${expr}"`);
|
|
5038
|
+
const field = (s, lo, hi, what) => {
|
|
5039
|
+
const out = /* @__PURE__ */ new Set();
|
|
5040
|
+
for (const part of s.toLowerCase().split(",")) {
|
|
5041
|
+
const [range, stepS] = part.split("/");
|
|
5042
|
+
const step = stepS === void 0 ? 1 : Number(stepS);
|
|
5043
|
+
if (!Number.isInteger(step) || step < 1) throw new Error(`cron ${what}: bad step in "${part}"`);
|
|
5044
|
+
const num = (x) => {
|
|
5045
|
+
const n = CRON_NAMES[x] ?? Number(x);
|
|
5046
|
+
if (!Number.isInteger(n)) throw new Error(`cron ${what}: "${x}" is not a number`);
|
|
5047
|
+
return n;
|
|
5048
|
+
};
|
|
5049
|
+
let a, b;
|
|
5050
|
+
if (range === "*") {
|
|
5051
|
+
a = lo;
|
|
5052
|
+
b = hi;
|
|
5053
|
+
} else if (range.includes("-")) {
|
|
5054
|
+
const [x, y] = range.split("-");
|
|
5055
|
+
a = num(x);
|
|
5056
|
+
b = num(y);
|
|
5057
|
+
} else {
|
|
5058
|
+
a = num(range);
|
|
5059
|
+
b = stepS === void 0 ? a : hi;
|
|
5060
|
+
}
|
|
5061
|
+
if (what === "weekday") {
|
|
5062
|
+
if (a === 7) a = 0;
|
|
5063
|
+
if (b === 7 && a !== 0) b = 6, out.add(0);
|
|
5064
|
+
}
|
|
5065
|
+
if (a < lo || b > hi || a > b) throw new Error(`cron ${what}: "${part}" is outside ${lo}-${hi}`);
|
|
5066
|
+
for (let n = a; n <= b; n += step) out.add(n);
|
|
5067
|
+
}
|
|
5068
|
+
return out;
|
|
5069
|
+
};
|
|
5070
|
+
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] === "*" };
|
|
5071
|
+
}
|
|
5072
|
+
function cronNext(c, after) {
|
|
5073
|
+
const start = new Date(after);
|
|
5074
|
+
start.setSeconds(0, 0);
|
|
5075
|
+
start.setMinutes(start.getMinutes() + 1);
|
|
5076
|
+
const hours = [...c.hour].sort((a, b) => a - b), mins = [...c.min].sort((a, b) => a - b);
|
|
5077
|
+
for (let day = 0; day < 366 * 5; day++) {
|
|
5078
|
+
const d = new Date(start.getFullYear(), start.getMonth(), start.getDate() + day);
|
|
5079
|
+
if (!c.mon.has(d.getMonth() + 1)) continue;
|
|
5080
|
+
const domOk = c.dom.has(d.getDate()), dowOk = c.dow.has(d.getDay());
|
|
5081
|
+
if (!(c.domAny && c.dowAny ? true : c.domAny ? dowOk : c.dowAny ? domOk : domOk || dowOk)) continue;
|
|
5082
|
+
for (const h of hours) for (const m of mins) {
|
|
5083
|
+
const t = new Date(d.getFullYear(), d.getMonth(), d.getDate(), h, m).getTime();
|
|
5084
|
+
if (t >= start.getTime()) return t;
|
|
5085
|
+
}
|
|
5086
|
+
}
|
|
5087
|
+
return null;
|
|
5088
|
+
}
|
|
5089
|
+
function checkSchedule(s, minMinutes = 1) {
|
|
5090
|
+
switch (s?.type) {
|
|
5091
|
+
case "once":
|
|
5092
|
+
return Number.isFinite(parseLocalTime(s.at)) ? void 0 : `"at" must be a local time like 2026-11-28 09:00, got "${s.at}"`;
|
|
5093
|
+
case "every":
|
|
5094
|
+
return Number.isFinite(s.minutes) && s.minutes >= minMinutes ? void 0 : `"minutes" must be at least ${minMinutes}`;
|
|
5095
|
+
case "daily":
|
|
5096
|
+
if (!HHMM.test(s.time ?? "")) return `"time" must be HH:mm, got "${s.time}"`;
|
|
5097
|
+
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`;
|
|
5098
|
+
return void 0;
|
|
5099
|
+
case "cron": {
|
|
5100
|
+
try {
|
|
5101
|
+
const c = parseCron(s.cron);
|
|
5102
|
+
if (cronNext(c, Date.now()) === null) return "this cron never runs";
|
|
5103
|
+
} catch (err) {
|
|
5104
|
+
return err.message;
|
|
5105
|
+
}
|
|
5106
|
+
if (minMinutes > 1) {
|
|
5107
|
+
const c = parseCron(s.cron);
|
|
5108
|
+
const a = cronNext(c, Date.now()), b = cronNext(c, a);
|
|
5109
|
+
if (b !== null && b - a < minMinutes * 6e4) return `runs more often than every ${minMinutes} minutes`;
|
|
5110
|
+
}
|
|
5111
|
+
return void 0;
|
|
5112
|
+
}
|
|
5113
|
+
default:
|
|
5114
|
+
return `"type" must be once, every, daily or cron`;
|
|
5115
|
+
}
|
|
5116
|
+
}
|
|
5117
|
+
function nextRun(s, after, from = after) {
|
|
5118
|
+
switch (s.type) {
|
|
5119
|
+
case "once": {
|
|
5120
|
+
const t = parseLocalTime(s.at);
|
|
5121
|
+
return Number.isFinite(t) && t > after ? t : null;
|
|
5122
|
+
}
|
|
5123
|
+
case "every": {
|
|
5124
|
+
const p = s.minutes * 6e4;
|
|
5125
|
+
let t = from + p;
|
|
5126
|
+
if (t <= after) t = after + p;
|
|
5127
|
+
return t;
|
|
5128
|
+
}
|
|
5129
|
+
case "daily": {
|
|
5130
|
+
const m = HHMM.exec(s.time);
|
|
5131
|
+
if (!m) return null;
|
|
5132
|
+
const base = new Date(after);
|
|
5133
|
+
for (let day = 0; day < 8; day++) {
|
|
5134
|
+
const d = new Date(base.getFullYear(), base.getMonth(), base.getDate() + day, +m[1], +m[2]);
|
|
5135
|
+
if (d.getTime() > after && (!s.days?.length || s.days.includes(d.getDay()))) return d.getTime();
|
|
5136
|
+
}
|
|
5137
|
+
return null;
|
|
5138
|
+
}
|
|
5139
|
+
case "cron":
|
|
5140
|
+
try {
|
|
5141
|
+
return cronNext(parseCron(s.cron), after);
|
|
5142
|
+
} catch {
|
|
5143
|
+
return null;
|
|
5144
|
+
}
|
|
5145
|
+
}
|
|
5146
|
+
}
|
|
5147
|
+
var DAY_EN = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
|
5148
|
+
var DAY_ZH = ["\u65E5", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D"];
|
|
5149
|
+
function describeSchedule(s, locale = "en") {
|
|
5150
|
+
const zh = locale === "zh";
|
|
5151
|
+
switch (s.type) {
|
|
5152
|
+
case "once": {
|
|
5153
|
+
const t = parseLocalTime(s.at);
|
|
5154
|
+
return (zh ? "\u4E00\u6B21 \xB7 " : "Once \xB7 ") + (Number.isFinite(t) ? formatLocalTime(t) : s.at);
|
|
5155
|
+
}
|
|
5156
|
+
case "every": {
|
|
5157
|
+
const m = s.minutes;
|
|
5158
|
+
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`;
|
|
5159
|
+
return zh ? `\u6BCF ${v}` : `Every ${v}`;
|
|
5160
|
+
}
|
|
5161
|
+
case "daily": {
|
|
5162
|
+
const days = [...new Set(s.days ?? [])].sort((a, b) => a - b);
|
|
5163
|
+
if (!days.length || days.length === 7) return (zh ? "\u6BCF\u5929 " : "Daily ") + s.time;
|
|
5164
|
+
if (days.join() === "1,2,3,4,5") return (zh ? "\u5DE5\u4F5C\u65E5 " : "Weekdays ") + s.time;
|
|
5165
|
+
if (days.join() === "0,6") return (zh ? "\u5468\u672B " : "Weekends ") + s.time;
|
|
5166
|
+
return (zh ? "\u6BCF\u5468" + days.map((d) => DAY_ZH[d]).join("\u3001") + " " : days.map((d) => DAY_EN[d]).join(", ") + " ") + s.time;
|
|
5167
|
+
}
|
|
5168
|
+
case "cron":
|
|
5169
|
+
return `cron ${s.cron}`;
|
|
5170
|
+
}
|
|
5171
|
+
}
|
|
5172
|
+
var newTaskId = () => `t_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
5173
|
+
function makeTask(fields, limits = {}, now = Date.now()) {
|
|
5174
|
+
const name = fields.name?.trim(), prompt = fields.prompt?.trim();
|
|
5175
|
+
if (!name) throw new Error("a task needs a name");
|
|
5176
|
+
if (!prompt) throw new Error("a task needs a prompt");
|
|
5177
|
+
const problem = checkSchedule(fields.schedule, limits.minMinutes ?? 5);
|
|
5178
|
+
if (problem) throw new Error(problem);
|
|
5179
|
+
const enabled = fields.enabled ?? true;
|
|
5180
|
+
const next = enabled ? nextRun(fields.schedule, now) : null;
|
|
5181
|
+
if (enabled && next === null) throw new Error("that time has already passed");
|
|
5182
|
+
return { id: newTaskId(), name, prompt, schedule: fields.schedule, enabled, next, by: fields.by, created: now, updated: now, runs: 0 };
|
|
5183
|
+
}
|
|
5184
|
+
function changeTask(task, patch, limits = {}, now = Date.now()) {
|
|
5185
|
+
const out = { ...task, updated: now };
|
|
5186
|
+
if (patch.name !== void 0) {
|
|
5187
|
+
if (!patch.name.trim()) throw new Error("a task needs a name");
|
|
5188
|
+
out.name = patch.name.trim();
|
|
5189
|
+
}
|
|
5190
|
+
if (patch.prompt !== void 0) {
|
|
5191
|
+
if (!patch.prompt.trim()) throw new Error("a task needs a prompt");
|
|
5192
|
+
out.prompt = patch.prompt.trim();
|
|
5193
|
+
}
|
|
5194
|
+
if (patch.schedule) {
|
|
5195
|
+
const problem = checkSchedule(patch.schedule, limits.minMinutes ?? 5);
|
|
5196
|
+
if (problem) throw new Error(problem);
|
|
5197
|
+
out.schedule = patch.schedule;
|
|
5198
|
+
}
|
|
5199
|
+
if (patch.enabled !== void 0) out.enabled = patch.enabled;
|
|
5200
|
+
if (patch.schedule || patch.enabled !== void 0) {
|
|
5201
|
+
out.next = out.enabled ? nextRun(out.schedule, now) : null;
|
|
5202
|
+
if (out.enabled && out.next === null) throw new Error("that time has already passed");
|
|
5203
|
+
}
|
|
5204
|
+
return out;
|
|
5205
|
+
}
|
|
5206
|
+
var SCHEDULE_SCHEMA = {
|
|
5207
|
+
type: "object",
|
|
5208
|
+
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).`,
|
|
5209
|
+
properties: {
|
|
5210
|
+
type: { type: "string", enum: ["once", "every", "daily", "cron"] },
|
|
5211
|
+
at: { type: "string" },
|
|
5212
|
+
in_minutes: { type: "number" },
|
|
5213
|
+
minutes: { type: "number" },
|
|
5214
|
+
time: { type: "string" },
|
|
5215
|
+
days: { type: "array", items: { type: "integer", minimum: 0, maximum: 6 } },
|
|
5216
|
+
cron: { type: "string" }
|
|
5217
|
+
},
|
|
5218
|
+
required: ["type"],
|
|
5219
|
+
additionalProperties: false
|
|
5220
|
+
};
|
|
5221
|
+
function toSchedule(a, now) {
|
|
5222
|
+
switch (a.type) {
|
|
5223
|
+
case "once":
|
|
5224
|
+
return { type: "once", at: a.at ?? (a.in_minutes !== void 0 ? formatLocalTime(now + Math.max(1, Math.round(a.in_minutes)) * 6e4) : "") };
|
|
5225
|
+
case "every":
|
|
5226
|
+
return { type: "every", minutes: Math.round(a.minutes ?? 0) };
|
|
5227
|
+
case "daily":
|
|
5228
|
+
return { type: "daily", time: a.time ?? "", ...a.days?.length ? { days: a.days } : {} };
|
|
5229
|
+
case "cron":
|
|
5230
|
+
return { type: "cron", cron: a.cron ?? "" };
|
|
5231
|
+
}
|
|
5232
|
+
}
|
|
5233
|
+
function taskLine(t, now = Date.now()) {
|
|
5234
|
+
return {
|
|
5235
|
+
id: t.id,
|
|
5236
|
+
name: t.name,
|
|
5237
|
+
prompt: t.prompt,
|
|
5238
|
+
schedule: describeSchedule(t.schedule),
|
|
5239
|
+
enabled: t.enabled,
|
|
5240
|
+
next: t.next ? formatLocalTime(t.next) : null,
|
|
5241
|
+
runs: t.runs,
|
|
5242
|
+
...t.last ? { last_run: `${formatLocalTime(t.last.at)} ${t.last.status}${t.last.note ? ": " + t.last.note : ""}` } : {},
|
|
5243
|
+
...t.next && t.next < now ? { overdue: true } : {}
|
|
5244
|
+
};
|
|
5245
|
+
}
|
|
5246
|
+
function scheduleTools(store, opts = {}) {
|
|
5247
|
+
const now = opts.now ?? Date.now;
|
|
5248
|
+
const tz = (() => {
|
|
5249
|
+
try {
|
|
5250
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
|
5251
|
+
} catch {
|
|
5252
|
+
return "local";
|
|
5253
|
+
}
|
|
5254
|
+
})();
|
|
5255
|
+
const changed = () => {
|
|
5256
|
+
try {
|
|
5257
|
+
opts.onChange?.();
|
|
5258
|
+
} catch {
|
|
5259
|
+
}
|
|
5260
|
+
};
|
|
5261
|
+
const header = () => `Now: ${formatLocalTime(now())} (${tz}).`;
|
|
5262
|
+
return [
|
|
5263
|
+
defineTool({
|
|
5264
|
+
name: "schedule_list",
|
|
5265
|
+
description: "Lists the scheduled tasks: prompts this app's agent runs on its own at set times (while the app is open).",
|
|
5266
|
+
readOnly: true,
|
|
5267
|
+
display: { label: () => "Scheduled tasks" },
|
|
5268
|
+
execute: async () => {
|
|
5269
|
+
const list = await store.list();
|
|
5270
|
+
return `${header()}
|
|
5271
|
+
${list.length ? JSON.stringify(list.map((t) => taskLine(t, now())), null, 1) : "No scheduled tasks."}`;
|
|
5272
|
+
}
|
|
5273
|
+
}),
|
|
5274
|
+
defineTool({
|
|
5275
|
+
name: "schedule_add",
|
|
5276
|
+
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.`,
|
|
5277
|
+
parameters: {
|
|
5278
|
+
type: "object",
|
|
5279
|
+
properties: {
|
|
5280
|
+
name: { type: "string", description: 'Short name the user sees, e.g. "Morning news digest".' },
|
|
5281
|
+
prompt: { type: "string", description: "The instruction for each run, complete on its own." },
|
|
5282
|
+
schedule: SCHEDULE_SCHEMA,
|
|
5283
|
+
enabled: { type: "boolean", description: "Default true." }
|
|
5284
|
+
},
|
|
5285
|
+
required: ["name", "prompt", "schedule"],
|
|
5286
|
+
additionalProperties: false
|
|
5287
|
+
},
|
|
5288
|
+
display: { label: (a) => `Schedule \u201C${a.name ?? ""}\u201D` },
|
|
5289
|
+
execute: async (a) => {
|
|
5290
|
+
const list = await store.list();
|
|
5291
|
+
if (list.length >= (opts.maxTasks ?? 20)) throw new Error(`there are already ${list.length} tasks, the most allowed; remove one first`);
|
|
5292
|
+
const task = makeTask({ name: a.name, prompt: a.prompt, schedule: toSchedule(a.schedule, now()), enabled: a.enabled, by: "agent" }, opts, now());
|
|
5293
|
+
await store.put(task);
|
|
5294
|
+
changed();
|
|
5295
|
+
return `${header()}
|
|
5296
|
+
Added: ${JSON.stringify(taskLine(task, now()))}`;
|
|
5297
|
+
}
|
|
5298
|
+
}),
|
|
5299
|
+
defineTool({
|
|
5300
|
+
name: "schedule_update",
|
|
5301
|
+
description: "Changes a scheduled task (by id, from schedule_list): its name, prompt, schedule, or enabled (false pauses it).",
|
|
5302
|
+
parameters: {
|
|
5303
|
+
type: "object",
|
|
5304
|
+
properties: { id: { type: "string" }, name: { type: "string" }, prompt: { type: "string" }, schedule: SCHEDULE_SCHEMA, enabled: { type: "boolean" } },
|
|
5305
|
+
required: ["id"],
|
|
5306
|
+
additionalProperties: false
|
|
5307
|
+
},
|
|
5308
|
+
display: { label: (a) => `Update scheduled task ${a.id ?? ""}` },
|
|
5309
|
+
execute: async (a) => {
|
|
5310
|
+
const task = await store.get(a.id);
|
|
5311
|
+
if (!task) throw new Error(`no task with id ${a.id}; schedule_list shows them`);
|
|
5312
|
+
const next = changeTask(task, { name: a.name, prompt: a.prompt, schedule: a.schedule ? toSchedule(a.schedule, now()) : void 0, enabled: a.enabled }, opts, now());
|
|
5313
|
+
await store.put(next);
|
|
5314
|
+
changed();
|
|
5315
|
+
return `${header()}
|
|
5316
|
+
Updated: ${JSON.stringify(taskLine(next, now()))}`;
|
|
5317
|
+
}
|
|
5318
|
+
}),
|
|
5319
|
+
defineTool({
|
|
5320
|
+
name: "schedule_remove",
|
|
5321
|
+
description: "Removes a scheduled task (by id). Its conversation stays.",
|
|
5322
|
+
parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"], additionalProperties: false },
|
|
5323
|
+
display: { label: (a) => `Remove scheduled task ${a.id ?? ""}` },
|
|
5324
|
+
execute: async (a) => {
|
|
5325
|
+
const task = await store.get(a.id);
|
|
5326
|
+
if (!task) throw new Error(`no task with id ${a.id}`);
|
|
5327
|
+
await store.delete(a.id);
|
|
5328
|
+
changed();
|
|
5329
|
+
return `Removed \u201C${task.name}\u201D.`;
|
|
5330
|
+
}
|
|
5331
|
+
})
|
|
5332
|
+
];
|
|
5333
|
+
}
|
|
5334
|
+
var Scheduler = class {
|
|
5335
|
+
constructor(opts) {
|
|
5336
|
+
__publicField(this, "opts", opts);
|
|
5337
|
+
__publicField(this, "timer", null);
|
|
5338
|
+
__publicField(this, "busy", false);
|
|
5339
|
+
__publicField(this, "unsub", null);
|
|
5340
|
+
/** Ids of tasks this tab is running now. */
|
|
5341
|
+
__publicField(this, "running", /* @__PURE__ */ new Set());
|
|
5342
|
+
__publicField(this, "poke", () => void this.tick());
|
|
5343
|
+
}
|
|
5344
|
+
start() {
|
|
5345
|
+
if (this.timer) return;
|
|
5346
|
+
this.timer = setInterval(() => void this.tick(), this.opts.interval ?? 2e4);
|
|
5347
|
+
this.unsub = this.opts.store.subscribe?.(() => this.opts.onChange?.()) ?? null;
|
|
5348
|
+
if (typeof window !== "undefined") window.addEventListener("focus", this.poke);
|
|
5349
|
+
void this.tick();
|
|
5350
|
+
}
|
|
5351
|
+
stop() {
|
|
5352
|
+
if (this.timer) clearInterval(this.timer);
|
|
5353
|
+
this.timer = null;
|
|
5354
|
+
this.unsub?.();
|
|
5355
|
+
this.unsub = null;
|
|
5356
|
+
if (typeof window !== "undefined") window.removeEventListener("focus", this.poke);
|
|
5357
|
+
}
|
|
5358
|
+
/** Looks for a due task and runs it when idle. Resolves once that run is over. */
|
|
5359
|
+
async tick() {
|
|
5360
|
+
if (this.busy || !this.opts.idle()) return;
|
|
5361
|
+
const now = (this.opts.now ?? Date.now)();
|
|
5362
|
+
const due = (await this.opts.store.list()).filter((t) => t.enabled && t.next !== null && t.next <= now).sort((a, b) => a.next - b.next);
|
|
5363
|
+
for (const t of due) {
|
|
5364
|
+
if (this.busy || !this.opts.idle()) return;
|
|
5365
|
+
if (await this.fire(t.id, false)) return;
|
|
5366
|
+
}
|
|
5367
|
+
}
|
|
5368
|
+
/** Runs a task now (the user's "Run now"), whatever its time; false when it is already running somewhere. */
|
|
5369
|
+
runNow(id) {
|
|
5370
|
+
return this.fire(id, true);
|
|
5371
|
+
}
|
|
5372
|
+
async fire(id, force) {
|
|
5373
|
+
if (this.busy) return false;
|
|
5374
|
+
this.busy = true;
|
|
5375
|
+
let ran = false;
|
|
5376
|
+
try {
|
|
5377
|
+
await tryLock(`${this.opts.lockPrefix}:task:${id}`, async () => {
|
|
5378
|
+
const store = this.opts.store, clock = this.opts.now ?? Date.now;
|
|
5379
|
+
const task = await store.get(id);
|
|
5380
|
+
const now = clock();
|
|
5381
|
+
if (!task || !force && (!task.enabled || task.next === null || task.next > now)) return;
|
|
5382
|
+
const next = task.enabled ? nextRun(task.schedule, now, now) : task.next;
|
|
5383
|
+
await store.put({ ...task, next: task.schedule.type === "once" && !force ? null : next, ...task.schedule.type === "once" && !force ? { enabled: false } : {} });
|
|
5384
|
+
ran = true;
|
|
5385
|
+
this.running.add(id);
|
|
5386
|
+
this.opts.onChange?.();
|
|
5387
|
+
let out;
|
|
5388
|
+
try {
|
|
5389
|
+
out = await this.opts.run(task);
|
|
5390
|
+
} catch (err) {
|
|
5391
|
+
out = { status: "error", note: err.message };
|
|
5392
|
+
}
|
|
5393
|
+
this.running.delete(id);
|
|
5394
|
+
const after = await store.get(id);
|
|
5395
|
+
if (after) await store.put({ ...after, runs: after.runs + 1, last: { at: now, ...out } });
|
|
5396
|
+
this.opts.onChange?.();
|
|
5397
|
+
});
|
|
5398
|
+
return ran;
|
|
5399
|
+
} finally {
|
|
5400
|
+
this.busy = false;
|
|
5401
|
+
}
|
|
5402
|
+
}
|
|
5403
|
+
};
|
|
5404
|
+
|
|
4888
5405
|
// src/mcp.ts
|
|
4889
5406
|
var PROTOCOL_VERSION = "2025-06-18";
|
|
4890
5407
|
var MCPError = class extends Error {
|