@runappsai/agent 0.1.10 → 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/dist/index.cjs CHANGED
@@ -24,11 +24,13 @@ var src_exports = {};
24
24
  __export(src_exports, {
25
25
  Agent: () => Agent,
26
26
  ContextOverflowError: () => ContextOverflowError,
27
+ DEFAULT_COMPACTION: () => DEFAULT_COMPACTION,
27
28
  DEFAULT_SKILLS_DIR: () => DEFAULT_SKILLS_DIR,
28
29
  DEFAULT_USER_SKILLS_DIR: () => DEFAULT_USER_SKILLS_DIR,
29
30
  MCPError: () => MCPError,
30
31
  PartialReadError: () => PartialReadError,
31
32
  ProviderError: () => ProviderError,
33
+ Scheduler: () => Scheduler,
32
34
  UNTITLED: () => UNTITLED,
33
35
  WEB_TOOL_NAMES: () => WEB_TOOL_NAMES,
34
36
  Workspace: () => Workspace,
@@ -36,12 +38,15 @@ __export(src_exports, {
36
38
  askUserTool: () => askUserTool,
37
39
  buildSystemPrompt: () => buildSystemPrompt,
38
40
  buildZip: () => buildZip,
41
+ changeTask: () => changeTask,
42
+ checkSchedule: () => checkSchedule,
39
43
  collectCompletion: () => collectCompletion,
40
44
  configurePdf: () => configurePdf,
41
45
  connectMCP: () => connectMCP,
42
46
  createAgent: () => createAgent,
43
47
  decodeText: () => decodeText,
44
48
  defineTool: () => defineTool,
49
+ describeSchedule: () => describeSchedule,
45
50
  domUI: () => domUI,
46
51
  estimateTokens: () => estimateTokens,
47
52
  expandSlash: () => expandSlash,
@@ -49,6 +54,7 @@ __export(src_exports, {
49
54
  fileGuard: () => fileGuard,
50
55
  fileTools: () => fileTools,
51
56
  fitBudget: () => fitBudget,
57
+ formatLocalTime: () => formatLocalTime,
52
58
  formatPdfText: () => formatPdfText,
53
59
  groupTurns: () => groupTurns,
54
60
  guessType: () => guessType,
@@ -56,8 +62,12 @@ __export(src_exports, {
56
62
  isPdf: () => isPdf,
57
63
  listTemplates: () => listTemplates,
58
64
  listZip: () => listZip,
65
+ localSchedules: () => localSchedules,
66
+ makeTask: () => makeTask,
59
67
  memoryFS: () => memoryFS,
68
+ memorySchedules: () => memorySchedules,
60
69
  modelAccepts: () => modelAccepts,
70
+ nextRun: () => nextRun,
61
71
  normalizeForFuzzyMatch: () => normalizeForFuzzyMatch,
62
72
  normalizePath: () => normalizePath,
63
73
  normalizeResult: () => normalizeResult,
@@ -65,13 +75,16 @@ __export(src_exports, {
65
75
  openAIProvider: () => openAIProvider,
66
76
  openWorkspace: () => openWorkspace,
67
77
  parseCommandArgs: () => parseCommandArgs,
78
+ parseCron: () => parseCron,
68
79
  parseFrontmatter: () => parseFrontmatter,
80
+ parseLocalTime: () => parseLocalTime,
69
81
  parseSkill: () => parseSkill,
70
82
  planCut: () => planCut,
71
83
  readZipEntry: () => readZipEntry,
72
84
  runInSandbox: () => runInSandbox,
73
85
  runappsProvider: () => runappsProvider,
74
86
  sandboxTool: () => sandboxTool,
87
+ scheduleTools: () => scheduleTools,
75
88
  serializeConversation: () => serializeConversation,
76
89
  skillFoldersOf: () => skillFoldersOf,
77
90
  skillZipFS: () => skillZipFS,
@@ -517,14 +530,14 @@ function summaryOf(m) {
517
530
  function summaryMessage(summary) {
518
531
  return { role: "user", content: COMPACTION_SUMMARY_PREFIX + summary + COMPACTION_SUMMARY_SUFFIX };
519
532
  }
520
- function resolveSettings(window, s = {}) {
533
+ function resolveSettings(window2, s = {}) {
521
534
  return {
522
- reserveTokens: Math.min(s.reserveTokens ?? DEFAULT_COMPACTION.reserveTokens, Math.floor(window * 0.2)),
523
- keepRecentTokens: Math.min(s.keepRecentTokens ?? DEFAULT_COMPACTION.keepRecentTokens, Math.floor(window * 0.4))
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))
524
537
  };
525
538
  }
526
- function shouldCompact(contextTokens, window, s) {
527
- return contextTokens > window - s.reserveTokens;
539
+ function shouldCompact(contextTokens, window2, s) {
540
+ return contextTokens > window2 - s.reserveTokens;
528
541
  }
529
542
  function planCut(messages, keepRecentTokens) {
530
543
  if (messages.length < 2) return null;
@@ -2465,8 +2478,8 @@ function isMachineTitle(title) {
2465
2478
  return /^(The conversation history before this point|<skill[\s>]|\[environment\]|\[attachments\]|\[context\] )|\[attachments\]/.test(title);
2466
2479
  }
2467
2480
  function withLock(name, fn) {
2468
- const locks = typeof navigator !== "undefined" ? navigator.locks : void 0;
2469
- return locks && typeof locks.request === "function" ? locks.request(name, fn) : fn();
2481
+ const locks2 = typeof navigator !== "undefined" ? navigator.locks : void 0;
2482
+ return locks2 && typeof locks2.request === "function" ? locks2.request(name, fn) : fn();
2470
2483
  }
2471
2484
  function memoryFS(initial = {}, opts = {}) {
2472
2485
  const files = /* @__PURE__ */ new Map();
@@ -3673,6 +3686,10 @@ var Agent = class {
3673
3686
  __publicField(this, "opts");
3674
3687
  /** `webTools` as configured (a function is read every turn). */
3675
3688
  __publicField(this, "web");
3689
+ /** Whether the loop summarises older turns (else it only trims them): `compaction !== false`, or `configure({ compaction })`. */
3690
+ __publicField(this, "compactSummaries");
3691
+ /** The compaction thresholds set (an unset one is the default): the `compaction` object, or `configure({ compaction })`. */
3692
+ __publicField(this, "compactThresholds");
3676
3693
  /** The platform's web tools, loaded the first time they are offered. */
3677
3694
  __publicField(this, "webCache", null);
3678
3695
  __publicField(this, "history", []);
@@ -3694,11 +3711,13 @@ var Agent = class {
3694
3711
  __publicField(this, "loaded");
3695
3712
  __publicField(this, "createdAt", Date.now());
3696
3713
  /** The session's title, fixed once known (a later compaction must not turn it into the summary's first words). */
3697
- __publicField(this, "title");
3714
+ __publicField(this, "fixedTitle");
3698
3715
  __publicField(this, "_ended", null);
3699
3716
  __publicField(this, "persist");
3700
3717
  this.provider = toProvider(provider);
3701
3718
  this.opts = opts;
3719
+ this.compactSummaries = opts.compaction !== false;
3720
+ this.compactThresholds = typeof opts.compaction === "object" ? { ...opts.compaction } : {};
3702
3721
  this.id = opts.id || `agent_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
3703
3722
  this.ui = opts.ui ?? domUI();
3704
3723
  this.workspace = opts.workspace ?? null;
@@ -3740,6 +3759,14 @@ var Agent = class {
3740
3759
  this.loaded = Promise.resolve();
3741
3760
  }
3742
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
+ }
3743
3770
  applySession(data) {
3744
3771
  if (data.v !== 1 && data.v !== 2) throw new Error("unknown session format");
3745
3772
  this.history = data.messages.slice();
@@ -3748,7 +3775,7 @@ var Agent = class {
3748
3775
  this._usage = { ...data.usage };
3749
3776
  this.createdAt = data.createdAt ?? data.savedAt ?? Date.now();
3750
3777
  this._ended = data.ended ?? null;
3751
- this.title = data.title && !isMachineTitle(data.title) ? data.title : void 0;
3778
+ this.fixedTitle = data.title && !isMachineTitle(data.title) ? data.title : void 0;
3752
3779
  if (data.model && !this.opts.model) {
3753
3780
  this.opts.model = data.model;
3754
3781
  this.catalogue = null;
@@ -3826,10 +3853,20 @@ var Agent = class {
3826
3853
  get settings() {
3827
3854
  const p = this.opts.permissions ?? "ask";
3828
3855
  const re = this.opts.extra?.reasoning_effort;
3829
- return { model: this.opts.model, maxTurns: this.opts.maxTurns ?? DEFAULT_MAX_TURNS, maxTokens: typeof this.opts.maxTokens === "number" ? this.opts.maxTokens : "auto", permissions: typeof p === "function" ? "custom" : p, reasoningEffort: typeof re === "string" ? re : void 0 };
3856
+ return { model: this.opts.model, maxTurns: this.opts.maxTurns ?? DEFAULT_MAX_TURNS, maxTokens: typeof this.opts.maxTokens === "number" ? this.opts.maxTokens : "auto", permissions: typeof p === "function" ? "custom" : p, reasoningEffort: typeof re === "string" ? re : void 0, compaction: { summarize: this.compactSummaries, ...this.compactThresholds } };
3830
3857
  }
3831
3858
  /** Changes settings for the runs that follow (a run in progress keeps its own). `undefined` leaves a field alone; `reasoningEffort: null` takes the model's default. */
3832
3859
  configure(patch) {
3860
+ if (patch.compaction) {
3861
+ const c = patch.compaction;
3862
+ if (typeof c.summarize === "boolean") this.compactSummaries = c.summarize;
3863
+ for (const k of ["reserveTokens", "keepRecentTokens"]) {
3864
+ if (!(k in c)) continue;
3865
+ const v = c[k];
3866
+ if (typeof v === "number" && Number.isFinite(v) && v > 0) this.compactThresholds[k] = Math.floor(v);
3867
+ else delete this.compactThresholds[k];
3868
+ }
3869
+ }
3833
3870
  if ("model" in patch) this.model = patch.model || void 0;
3834
3871
  if (typeof patch.webTools === "boolean") this.web = patch.webTools;
3835
3872
  if ("reasoningEffort" in patch) {
@@ -3842,6 +3879,15 @@ var Agent = class {
3842
3879
  if (patch.maxTokens !== void 0) this.opts.maxTokens = patch.maxTokens;
3843
3880
  if (patch.permissions !== void 0) this.opts.permissions = patch.permissions;
3844
3881
  }
3882
+ /**
3883
+ * Compaction as it applies to a window of `window` tokens: whether older
3884
+ * turns are summarised (else only trimmed), at how many tokens left it
3885
+ * starts (`reserveTokens`) and how much of the newest it keeps verbatim
3886
+ * (`keepRecentTokens`), each capped by the window (20 % / 40 %).
3887
+ */
3888
+ compactionFor(window2) {
3889
+ return { summarize: this.compactSummaries, ...resolveSettings(window2, this.compactThresholds) };
3890
+ }
3845
3891
  /** A snapshot to save (`restore` continues it). Taken at the last complete turn. */
3846
3892
  export() {
3847
3893
  const messages = this.history.slice(0, this.committed);
@@ -3856,18 +3902,18 @@ var Agent = class {
3856
3902
  savedAt: Date.now(),
3857
3903
  ...this._ended ? { ended: this._ended } : {}
3858
3904
  };
3859
- if (!this.title) {
3905
+ if (!this.fixedTitle) {
3860
3906
  const tt = titleOf(data);
3861
- if (tt !== UNTITLED) this.title = tt;
3907
+ if (tt !== UNTITLED) this.fixedTitle = tt;
3862
3908
  }
3863
- data.title = this.title ?? UNTITLED;
3909
+ data.title = this.fixedTitle ?? UNTITLED;
3864
3910
  return data;
3865
3911
  }
3866
3912
  /** Forgets the conversation (the workspace stays). */
3867
3913
  reset() {
3868
3914
  if (this.current) throw new Error("cannot reset while a run is active; abort() first");
3869
3915
  this.history = [];
3870
- this.title = void 0;
3916
+ this.fixedTitle = void 0;
3871
3917
  this._ended = null;
3872
3918
  this.committed = 0;
3873
3919
  this.droppedTurns = 0;
@@ -4048,8 +4094,8 @@ var Agent = class {
4048
4094
  this.emit("run_start", { runId, message: prefaced });
4049
4095
  const maxTurns = this.opts.maxTurns ?? DEFAULT_MAX_TURNS;
4050
4096
  const { output: maxTokens, input: catalogueWindow } = await this.limits();
4051
- let window = catalogueWindow;
4052
- let compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4097
+ let window2 = catalogueWindow;
4098
+ let compaction = resolveSettings(window2, this.compactThresholds);
4053
4099
  let overflowRetries = 0;
4054
4100
  try {
4055
4101
  if (prefaceError) throw prefaceError;
@@ -4068,13 +4114,13 @@ var Agent = class {
4068
4114
  const system = await this.systemPrompt();
4069
4115
  const fixed = this.fixedText(system);
4070
4116
  const tokensBefore = estimateTokens(this.history, fixed);
4071
- if (shouldCompact(tokensBefore, window, compaction)) {
4072
- const summarized = this.opts.compaction === false ? false : await this.compactWith(compaction, runId, signal);
4117
+ if (shouldCompact(tokensBefore, window2, compaction)) {
4118
+ const summarized = !this.compactSummaries ? false : await this.compactWith(compaction, runId, signal);
4073
4119
  const after = estimateTokens(this.history, fixed);
4074
- if (!summarized || shouldCompact(after, window, compaction)) {
4120
+ if (!summarized || shouldCompact(after, window2, compaction)) {
4075
4121
  const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
4076
4122
  const rest = this.history.slice(pinned.length);
4077
- const fit = fitBudget(rest, { budget: window - compaction.reserveTokens - estimateTokens(pinned), keepTurns: this.opts.keepTurns ?? 4, system: fixed });
4123
+ const fit = fitBudget(rest, { budget: window2 - compaction.reserveTokens - estimateTokens(pinned), keepTurns: this.opts.keepTurns ?? 4, system: fixed });
4078
4124
  if (fit.droppedTurns || fit.elidedResults) {
4079
4125
  this.history = [...pinned, ...fit.messages];
4080
4126
  this.droppedTurns += fit.droppedTurns;
@@ -4100,7 +4146,7 @@ var Agent = class {
4100
4146
  const asked = Date.now();
4101
4147
  let completion;
4102
4148
  try {
4103
- if (estimateTokens(this.history, fixed) > window * 2 && (typeof this.opts.maxInputTokens === "number" || typeof (await this.modelInfo())?.max_input_tokens === "number")) {
4149
+ if (estimateTokens(this.history, fixed) > window2 * 2 && (typeof this.opts.maxInputTokens === "number" || typeof (await this.modelInfo())?.max_input_tokens === "number")) {
4104
4150
  throw new ProviderError(413, "the request is far larger than the model's context");
4105
4151
  }
4106
4152
  completion = await this.callModel(params, runId, signal);
@@ -4108,17 +4154,17 @@ var Agent = class {
4108
4154
  this.emit("response", { runId, turn, durationMs: Date.now() - asked, error: err instanceof Error ? err.message : String(err) });
4109
4155
  if (signal.aborted || !isContextOverflow(err)) throw err;
4110
4156
  const limit = overflowLimit(err);
4111
- if (limit !== void 0 && limit < window) {
4112
- window = limit;
4113
- compaction = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4157
+ if (limit !== void 0 && limit < window2) {
4158
+ window2 = limit;
4159
+ compaction = resolveSettings(window2, this.compactThresholds);
4114
4160
  }
4115
4161
  let smaller = false;
4116
- while (!smaller && overflowRetries < 2) smaller = await this.squeeze(window, overflowRetries++, compaction, fixed, runId, signal);
4162
+ while (!smaller && overflowRetries < 2) smaller = await this.squeeze(window2, overflowRetries++, compaction, fixed, runId, signal);
4117
4163
  if (smaller) {
4118
4164
  turn--;
4119
4165
  continue;
4120
4166
  }
4121
- throw new ContextOverflowError({ cause: this.overflowCause(window, fixed), used: estimateTokens(this.history, fixed), window }, err instanceof Error ? err.message : String(err), errorStatus(err) ?? 400);
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);
4122
4168
  }
4123
4169
  this.emit("response", { runId, turn, durationMs: Date.now() - asked, finishReason: completion.finishReason, usage: completion.usage, message: completion.message });
4124
4170
  if (completion.usage) this.addUsage(completion.usage);
@@ -4299,8 +4345,8 @@ var Agent = class {
4299
4345
  */
4300
4346
  compact(focus) {
4301
4347
  return this.exclusive("compact", async (signal) => {
4302
- const window = await this.contextTokens();
4303
- const settings = this.squeezed(resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {}));
4348
+ const window2 = await this.contextTokens();
4349
+ const settings = this.squeezed(resolveSettings(window2, this.compactThresholds));
4304
4350
  const done = await this.compactWith(settings, void 0, signal, focus);
4305
4351
  if (done) await this.saveSession();
4306
4352
  return done;
@@ -4317,8 +4363,8 @@ var Agent = class {
4317
4363
  const first = rest[0] ? summaryOf(rest[0]) : null;
4318
4364
  const toSummarize = first === null ? rest : rest.slice(1);
4319
4365
  if (!toSummarize.length) return first;
4320
- const window = await this.contextTokens();
4321
- const settings = resolveSettings(window, typeof this.opts.compaction === "object" ? this.opts.compaction : {});
4366
+ const window2 = await this.contextTokens();
4367
+ const settings = resolveSettings(window2, this.compactThresholds);
4322
4368
  this.emit("compaction_start", {});
4323
4369
  try {
4324
4370
  return await this.writeSummary({ toSummarize, previousSummary: first ?? void 0, kept: [] }, settings, void 0, signal);
@@ -4370,12 +4416,12 @@ var Agent = class {
4370
4416
  * window (the estimate may run low); round 1 trims to 40%, big results of the
4371
4417
  * latest turn included. True when the request did get smaller.
4372
4418
  */
4373
- async squeeze(window, round2, settings, fixed, runId, signal) {
4419
+ async squeeze(window2, round2, settings, fixed, runId, signal) {
4374
4420
  const before = estimateTokens(this.history, fixed);
4375
- if (round2 === 0 && this.opts.compaction !== false) await this.compactWith(this.squeezed(settings), runId, signal);
4421
+ if (round2 === 0 && this.compactSummaries) await this.compactWith(this.squeezed(settings), runId, signal);
4376
4422
  const pinned = this.history.length && summaryOf(this.history[0]) !== null ? [this.history[0]] : [];
4377
4423
  const rest = this.history.slice(pinned.length);
4378
- const budget = Math.floor(window * (round2 === 0 ? 0.7 : 0.4)) - estimateTokens(pinned);
4424
+ const budget = Math.floor(window2 * (round2 === 0 ? 0.7 : 0.4)) - estimateTokens(pinned);
4379
4425
  const fit = fitBudget(rest, { budget, keepTurns: 1, system: fixed, keepResults: round2 === 0 ? 3 : 0 });
4380
4426
  if (fit.droppedTurns || fit.elidedResults) {
4381
4427
  this.history = [...pinned, ...fit.messages];
@@ -4386,13 +4432,13 @@ var Agent = class {
4386
4432
  return estimateTokens(this.history, fixed) < before;
4387
4433
  }
4388
4434
  /** What takes up the room in a request that cannot be made smaller. */
4389
- overflowCause(window, fixed) {
4435
+ overflowCause(window2, fixed) {
4390
4436
  const tools = this.tools.length ? estimateTokens([], JSON.stringify(this.tools.map((t) => toChatTool(t)))) : 0;
4391
4437
  const latest = [...this.history].reverse().find((m) => m.role === "user" && summaryOf(m) === null);
4392
4438
  const asked = latest ? estimateTokens([latest]) : 0;
4393
4439
  const others = estimateTokens(this.history) - asked;
4394
4440
  const biggest = Math.max(tools, asked, others);
4395
- if (biggest * 2 < window) return "model";
4441
+ if (biggest * 2 < window2) return "model";
4396
4442
  if (biggest === asked) {
4397
4443
  const files = Array.isArray(latest.content) ? latest.content.length > 1 : /(^|\n)\[attachments\]/.test(String(latest.content ?? ""));
4398
4444
  return files ? "attachments" : "message";
@@ -4636,7 +4682,7 @@ Fix the call and try again.`);
4636
4682
  else if (tool.destructive) question = `Allow ${tool.name}?`;
4637
4683
  if (question === false) return true;
4638
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;
4639
- 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 } : {} });
4640
4686
  }
4641
4687
  /** After an abort, every open tool call gets a result so the transcript stays valid. */
4642
4688
  closeOpenToolCalls() {
@@ -4720,8 +4766,8 @@ Fix the call and try again.`);
4720
4766
  }
4721
4767
  /** How full the model's context is: tokens the next call would send (estimated) against the window. */
4722
4768
  async context() {
4723
- const [window, system] = await Promise.all([this.contextTokens(), this.systemPrompt().catch(() => "")]);
4724
- 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 };
4725
4771
  }
4726
4772
  /**
4727
4773
  * The files whose contents are still in the conversation: read (with the
@@ -4859,6 +4905,463 @@ function round(n) {
4859
4905
  return Math.round(n * 1e6) / 1e6;
4860
4906
  }
4861
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
+
4862
5365
  // src/mcp.ts
4863
5366
  var PROTOCOL_VERSION = "2025-06-18";
4864
5367
  var MCPError = class extends Error {