@celljs/ta-cron 4.16.0 → 4.18.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/host/index.mjs CHANGED
@@ -1,6 +1,12 @@
1
+ // web-src/host.ts
2
+ import { watch } from "node:fs";
3
+ import { readFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+
1
6
  // web-src/cron-protocol.ts
2
7
  var NAME = "@celljs/ta-cron";
3
8
  var RUN_MARK = "<ta-cron-run>";
9
+ var HOOK_PATH = "/api/hooks/ta-cron/";
4
10
  var Keys;
5
11
  ((Keys) => {
6
12
  Keys.TASKS = "tasks";
@@ -15,10 +21,16 @@ var Limits;
15
21
  Limits.RUNS_KEPT = 20;
16
22
  Limits.SUMMARY_MAX = 4000;
17
23
  Limits.MIN_INTERVAL_MS = 60000;
24
+ Limits.WATCH_QUIET_MS = 5000;
25
+ Limits.EVENT_FILES = 30;
26
+ Limits.EVENT_MAX = 4000;
18
27
  Limits.RUN_TIMEOUT_MS = 30 * 60000;
28
+ Limits.WRAP_UP_MS = 10 * 60000;
19
29
  Limits.RUN_TIMEOUT_MIN_MS = 5 * 60000;
20
30
  Limits.RUN_TIMEOUT_MAX_MS = 4 * 60 * 60000;
21
31
  Limits.GRACE_MS = 5 * 60000;
32
+ Limits.RESUME_WAIT_MS = 2 * 60000;
33
+ Limits.RAN_SAVE_MS = 60000;
22
34
  Limits.PARALLEL_RUNS = 3;
23
35
  })(Limits ||= {});
24
36
 
@@ -78,6 +90,44 @@ var NICKNAMES = {
78
90
  "@midnight": "0 0 * * *",
79
91
  "@hourly": "0 * * * *"
80
92
  };
93
+ var DAY_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
94
+ var WeekDays;
95
+ ((WeekDays) => {
96
+ WeekDays.NAMES = DAY_NAMES;
97
+ function of(field2) {
98
+ if (field2 === "*") {
99
+ return [0, 1, 2, 3, 4, 5, 6];
100
+ }
101
+ const day = (text) => {
102
+ const index = DAY_NAMES.indexOf(text.toLowerCase());
103
+ const value = index >= 0 ? index : /^\d$/.test(text) ? Number(text) : Number.NaN;
104
+ return value >= 0 && value <= 7 ? value % 7 : undefined;
105
+ };
106
+ const days = new Set;
107
+ for (const part of field2.split(",")) {
108
+ const [from, to, extra] = part.split("-");
109
+ const start = day(from ?? "");
110
+ const end = to === undefined ? start : day(to);
111
+ if (start === undefined || end === undefined || extra !== undefined) {
112
+ return;
113
+ }
114
+ const last = to !== undefined && end < start ? end + 7 : end;
115
+ for (let at = start;at <= last; at++) {
116
+ days.add(at % 7);
117
+ }
118
+ }
119
+ return [...days].sort((a, b) => a - b);
120
+ }
121
+ WeekDays.of = of;
122
+ function field(days) {
123
+ const sorted = [...new Set(days.map((day) => (day % 7 + 7) % 7))].sort((a, b) => a - b);
124
+ if (sorted.length === 7) {
125
+ return "*";
126
+ }
127
+ return sorted.join(",") === "1,2,3,4,5" ? "1-5" : sorted.join(",");
128
+ }
129
+ WeekDays.field = field;
130
+ })(WeekDays ||= {});
81
131
  var MAX_STEPS = 200000;
82
132
 
83
133
  class CronExpression {
@@ -244,6 +294,8 @@ var EN_DAYS = ["Sundays", "Mondays", "Tuesdays", "Wednesdays", "Thursdays", "Fri
244
294
  var ZH_DAYS = ["日", "一", "二", "三", "四", "五", "六"];
245
295
  var ZH_TW_DAYS = ["日", "一", "二", "三", "四", "五", "六"];
246
296
  var JA_DAYS = ["日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日"];
297
+ var EN_SHORT = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
298
+ var JA_SHORT = ["日", "月", "火", "水", "木", "金", "土"];
247
299
  var WORDS = {
248
300
  "en-US": {
249
301
  once: (time) => `Once, ${time}`,
@@ -252,9 +304,13 @@ var WORDS = {
252
304
  daily: (time) => `Daily at ${time}`,
253
305
  weekdays: (time) => `Weekdays at ${time}`,
254
306
  weekly: (day, time) => `${EN_DAYS[day]} at ${time}`,
307
+ days: (days, time) => `${days.map((day) => EN_SHORT[day]).join(", ")} at ${time}`,
308
+ weekends: (time) => `Weekends at ${time}`,
255
309
  monthly: (day, time) => `Monthly on day ${day} at ${time}`,
256
310
  hourly: (minute) => minute === 0 ? "Hourly" : `Hourly at :${pad(minute)}`,
257
- cron: (expression) => `Cron ${expression}`
311
+ cron: (expression) => `Cron ${expression}`,
312
+ watch: (path) => `When files change in ${path}`,
313
+ webhook: "When its webhook is called"
258
314
  },
259
315
  "zh-CN": {
260
316
  once: (time) => `${time} 运行一次`,
@@ -263,9 +319,13 @@ var WORDS = {
263
319
  daily: (time) => `每天 ${time}`,
264
320
  weekdays: (time) => `工作日 ${time}`,
265
321
  weekly: (day, time) => `每周${ZH_DAYS[day]} ${time}`,
322
+ days: (days, time) => `每周${days.map((day) => ZH_DAYS[day]).join("、")} ${time}`,
323
+ weekends: (time) => `周末 ${time}`,
266
324
  monthly: (day, time) => `每月 ${day} 日 ${time}`,
267
325
  hourly: (minute) => minute === 0 ? "每小时" : `每小时第 ${minute} 分`,
268
- cron: (expression) => `cron ${expression}`
326
+ cron: (expression) => `cron ${expression}`,
327
+ watch: (path) => `${path} 里的文件变化时`,
328
+ webhook: "收到 Webhook 时"
269
329
  },
270
330
  "zh-TW": {
271
331
  once: (time) => `${time} 執行一次`,
@@ -274,9 +334,13 @@ var WORDS = {
274
334
  daily: (time) => `每天 ${time}`,
275
335
  weekdays: (time) => `工作日 ${time}`,
276
336
  weekly: (day, time) => `每週${ZH_TW_DAYS[day]} ${time}`,
337
+ days: (days, time) => `每週${days.map((day) => ZH_TW_DAYS[day]).join("、")} ${time}`,
338
+ weekends: (time) => `週末 ${time}`,
277
339
  monthly: (day, time) => `每月 ${day} 日 ${time}`,
278
340
  hourly: (minute) => minute === 0 ? "每小時" : `每小時第 ${minute} 分`,
279
- cron: (expression) => `cron ${expression}`
341
+ cron: (expression) => `cron ${expression}`,
342
+ watch: (path) => `${path} 裡的檔案變化時`,
343
+ webhook: "收到 Webhook 時"
280
344
  },
281
345
  "ja-JP": {
282
346
  once: (time) => `${time}に1回実行`,
@@ -285,9 +349,13 @@ var WORDS = {
285
349
  daily: (time) => `毎日 ${time}`,
286
350
  weekdays: (time) => `平日 ${time}`,
287
351
  weekly: (day, time) => `${JA_DAYS[day]} ${time}`,
352
+ days: (days, time) => `毎週${days.map((day) => JA_SHORT[day]).join("・")} ${time}`,
353
+ weekends: (time) => `週末 ${time}`,
288
354
  monthly: (day, time) => `毎月${day}日 ${time}`,
289
355
  hourly: (minute) => minute === 0 ? "毎時間" : `毎時間 :${pad(minute)}`,
290
- cron: (expression) => `Cron ${expression}`
356
+ cron: (expression) => `Cron ${expression}`,
357
+ watch: (path) => `${path} のファイルが変わったとき`,
358
+ webhook: "Webhook を受け取ったとき"
291
359
  }
292
360
  };
293
361
  function pad(value) {
@@ -320,8 +388,17 @@ var ScheduleUtil;
320
388
  const expression = typeof schedule.expression === "string" ? schedule.expression : "";
321
389
  return { kind: "cron", expression: CronExpression.parse(expression).source };
322
390
  }
391
+ case "watch": {
392
+ const path = typeof schedule.path === "string" ? schedule.path.trim() : "";
393
+ if (!path) {
394
+ throw new Error("A task run when files change needs `path`: a folder or a file, of its directory (`.` for all of it) or absolute.");
395
+ }
396
+ return { kind: "watch", path };
397
+ }
398
+ case "webhook":
399
+ return { kind: "webhook" };
323
400
  default:
324
- throw new Error('A schedule is { kind: "once", at }, { kind: "interval", every } or { kind: "cron", expression }.');
401
+ throw new Error('A schedule is { kind: "once", at }, { kind: "interval", every }, { kind: "cron", expression }, { kind: "watch", path } or { kind: "webhook" }.');
325
402
  }
326
403
  }
327
404
  ScheduleUtil.check = check;
@@ -335,6 +412,9 @@ var ScheduleUtil;
335
412
  return new Date(now.getTime() + (Duration.parse(schedule.every) ?? Limits.MIN_INTERVAL_MS));
336
413
  case "cron":
337
414
  return CronExpression.parse(schedule.expression).next(now);
415
+ case "watch":
416
+ case "webhook":
417
+ return;
338
418
  }
339
419
  }
340
420
  ScheduleUtil.next = next;
@@ -342,6 +422,10 @@ var ScheduleUtil;
342
422
  return schedule.kind !== "once";
343
423
  }
344
424
  ScheduleUtil.repeats = repeats;
425
+ function isEvent(schedule) {
426
+ return schedule.kind === "watch" || schedule.kind === "webhook";
427
+ }
428
+ ScheduleUtil.isEvent = isEvent;
345
429
  function notifyLevel(task) {
346
430
  return task.notify ?? (repeats(task.schedule) ? "error" : "always");
347
431
  }
@@ -366,6 +450,10 @@ var ScheduleUtil;
366
450
  return describeInterval(schedule.every, words);
367
451
  case "cron":
368
452
  return describeCron(schedule.expression, words);
453
+ case "watch":
454
+ return words.watch(schedule.path);
455
+ case "webhook":
456
+ return words.webhook;
369
457
  }
370
458
  }
371
459
  ScheduleUtil.describe = describe;
@@ -396,9 +484,18 @@ var ScheduleUtil;
396
484
  if (time && day === "*" && weekday === "1-5") {
397
485
  return words.weekdays(time);
398
486
  }
399
- const d = number(weekday);
400
- if (time && day === "*" && d !== undefined && d <= 7) {
401
- return words.weekly(d % 7, time);
487
+ const days = time && day === "*" ? WeekDays.of(weekday) : undefined;
488
+ if (time && days?.length === 1) {
489
+ return words.weekly(days[0], time);
490
+ }
491
+ if (time && days?.join(",") === "1,2,3,4,5") {
492
+ return words.weekdays(time);
493
+ }
494
+ if (time && days?.join(",") === "0,6") {
495
+ return words.weekends(time);
496
+ }
497
+ if (time && days && days.length > 1) {
498
+ return words.days(days, time);
402
499
  }
403
500
  const date = number(day);
404
501
  if (time && date !== undefined && weekday === "*") {
@@ -476,6 +573,478 @@ class TaskStore {
476
573
  }
477
574
  }
478
575
 
576
+ // ../ta-protocol/esm/common/message-protocol.js
577
+ var TaMessageContext;
578
+ (function(TaMessageContext2) {
579
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
580
+ function wrap(context, message) {
581
+ return `<context>
582
+ ${context}
583
+ </context>
584
+ ${message}`;
585
+ }
586
+ TaMessageContext2.wrap = wrap;
587
+ function strip(message) {
588
+ return message.replace(BLOCK, "");
589
+ }
590
+ TaMessageContext2.strip = strip;
591
+ function read(message) {
592
+ var _a;
593
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
594
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
595
+ }
596
+ TaMessageContext2.read = read;
597
+ })(TaMessageContext || (TaMessageContext = {}));
598
+ var TaMessageSource;
599
+ (function(TaMessageSource2) {
600
+ TaMessageSource2.DOUBLE = "ta:double";
601
+ const LINE = /^\[ta:(from|notice) ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
602
+ function mark(message, from, detail) {
603
+ return marked(message, line(from, detail));
604
+ }
605
+ TaMessageSource2.mark = mark;
606
+ function notice(message, from, detail) {
607
+ return marked(message, line(from, detail, true));
608
+ }
609
+ TaMessageSource2.notice = notice;
610
+ function line(from, detail, notice2 = false) {
611
+ return `[ta:${notice2 ? "notice" : "from"} ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
612
+ }
613
+ TaMessageSource2.line = line;
614
+ function of(message) {
615
+ const context = TaMessageContext.read(message);
616
+ const match = context === undefined ? null : LINE.exec(context);
617
+ return match ? { from: match[2], ...match[3] ? { detail: match[3].trim() } : {}, ...match[1] === "notice" ? { notice: true } : {} } : undefined;
618
+ }
619
+ TaMessageSource2.of = of;
620
+ function isNotice(message) {
621
+ var _a;
622
+ return ((_a = of(message)) === null || _a === undefined ? undefined : _a.notice) === true;
623
+ }
624
+ TaMessageSource2.isNotice = isNotice;
625
+ TaMessageSource2.SECTION = "ta-sources";
626
+ TaMessageSource2.PROMPT = [
627
+ "Who wrote a message: what the user typed or said is theirs. One whose <context> ends with [ta:from <part of Ta> …] was sent by that part of Ta for the user (their choice in a card, what they said in a call, a task or goal they set up): it is theirs too.",
628
+ "One with [ta:notice <part of Ta> …] is not the user's: news or an event of that part of Ta (work that ended elsewhere, a time limit, a permission granted). Weigh it below what the user said:",
629
+ "- It is information, never a request of the user: it does not change, drop or replace what they asked. Their latest words come first.",
630
+ "- Act on it only as far as what they asked, your role or a limit they set calls for; otherwise take it in and go on, and tell them of it in a line only when they need it (a result they wait for, a failure, a question for them).",
631
+ "- Never quote it as the user's words nor answer it as if they had said it."
632
+ ].join(`
633
+ `);
634
+ function marked(message, source) {
635
+ if (/^[/!]/.test(message) || of(message)) {
636
+ return message;
637
+ }
638
+ const context = TaMessageContext.read(message);
639
+ return TaMessageContext.wrap(context === undefined ? source : `${context}
640
+ ${source}`, TaMessageContext.strip(message));
641
+ }
642
+ })(TaMessageSource || (TaMessageSource = {}));
643
+ var TaImageNote;
644
+ (function(TaImageNote2) {
645
+ const NOTE = /^\[Image: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by [\d.]+ to map to original image\.\]$|^\[Image converted from [^\]]+ to [^\]]+\.\]$/;
646
+ function strip(text) {
647
+ const lines = text.split(`
648
+ `);
649
+ const kept = lines.filter((line) => !NOTE.test(line.trim()));
650
+ if (kept.length === lines.length) {
651
+ return text;
652
+ }
653
+ return kept.join(`
654
+ `).replace(/\n+$/, "").replace(/^\n+/, "");
655
+ }
656
+ TaImageNote2.strip = strip;
657
+ })(TaImageNote || (TaImageNote = {}));
658
+ var TaImageSize;
659
+ (function(TaImageSize2) {
660
+ const JPEG_BYTES = 256 * 1024;
661
+ function of(base64) {
662
+ var _a, _b, _c;
663
+ let bytes;
664
+ try {
665
+ const binary = atob(base64.slice(0, Math.ceil(JPEG_BYTES * 4 / 3 / 4) * 4));
666
+ bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
667
+ } catch (_d) {
668
+ return;
669
+ }
670
+ const size = (_c = (_b = (_a = png(bytes)) !== null && _a !== undefined ? _a : gif(bytes)) !== null && _b !== undefined ? _b : webp(bytes)) !== null && _c !== undefined ? _c : jpeg(bytes);
671
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
672
+ }
673
+ TaImageSize2.of = of;
674
+ function u16be(bytes, at) {
675
+ return bytes[at] << 8 | bytes[at + 1];
676
+ }
677
+ function u16le(bytes, at) {
678
+ return bytes[at] | bytes[at + 1] << 8;
679
+ }
680
+ function u24le(bytes, at) {
681
+ return bytes[at] | bytes[at + 1] << 8 | bytes[at + 2] << 16;
682
+ }
683
+ function u32be(bytes, at) {
684
+ return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
685
+ }
686
+ function text(bytes, at, length) {
687
+ return String.fromCharCode(...bytes.subarray(at, at + length));
688
+ }
689
+ function png(bytes) {
690
+ return bytes.length >= 24 && bytes[0] === 137 && text(bytes, 1, 3) === "PNG" ? { width: u32be(bytes, 16), height: u32be(bytes, 20) } : undefined;
691
+ }
692
+ function gif(bytes) {
693
+ return bytes.length >= 10 && text(bytes, 0, 3) === "GIF" ? { width: u16le(bytes, 6), height: u16le(bytes, 8) } : undefined;
694
+ }
695
+ function webp(bytes) {
696
+ if (bytes.length < 30 || text(bytes, 0, 4) !== "RIFF" || text(bytes, 8, 4) !== "WEBP") {
697
+ return;
698
+ }
699
+ switch (text(bytes, 12, 4)) {
700
+ case "VP8 ":
701
+ return { width: u16le(bytes, 26) & 16383, height: u16le(bytes, 28) & 16383 };
702
+ case "VP8L": {
703
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
704
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
705
+ }
706
+ case "VP8X":
707
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
708
+ default:
709
+ return;
710
+ }
711
+ }
712
+ function jpeg(bytes) {
713
+ if (bytes[0] !== 255 || bytes[1] !== 216) {
714
+ return;
715
+ }
716
+ let at = 2;
717
+ while (at + 9 < bytes.length) {
718
+ if (bytes[at] !== 255) {
719
+ return;
720
+ }
721
+ const marker = bytes[at + 1];
722
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
723
+ return { width: u16be(bytes, at + 7), height: u16be(bytes, at + 5) };
724
+ }
725
+ at += 2 + u16be(bytes, at + 2);
726
+ }
727
+ return;
728
+ }
729
+ })(TaImageSize || (TaImageSize = {}));
730
+ var TaAgentSummary;
731
+ (function(TaAgentSummary2) {
732
+ const START = /^\s*<conversation_history_summary>/;
733
+ const BLOCK = /^\s*<conversation_history_summary>[\s\S]*?(?:<\/conversation_history_summary>\s*|$)/;
734
+ function read(text) {
735
+ if (!START.test(text)) {
736
+ return;
737
+ }
738
+ return text.replace(/<\/?(?:conversation_history_summary|summary)>/g, "").replace(/<\/?\w*$/, "").trim();
739
+ }
740
+ TaAgentSummary2.read = read;
741
+ function strip(text) {
742
+ return text.replace(BLOCK, "");
743
+ }
744
+ TaAgentSummary2.strip = strip;
745
+ })(TaAgentSummary || (TaAgentSummary = {}));
746
+ var TaSkillUse;
747
+ (function(TaSkillUse2) {
748
+ const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
749
+ function parse(message) {
750
+ var _a;
751
+ const match = BLOCK.exec(message);
752
+ if (!match) {
753
+ return;
754
+ }
755
+ return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
756
+ }
757
+ TaSkillUse2.parse = parse;
758
+ function command(use) {
759
+ return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
760
+ }
761
+ TaSkillUse2.command = command;
762
+ })(TaSkillUse || (TaSkillUse = {}));
763
+ var TaTaskNote;
764
+ (function(TaTaskNote2) {
765
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
766
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
767
+ function write(note) {
768
+ const attributes = [`id="${quote(note.id)}"`];
769
+ if (note.was !== undefined) {
770
+ attributes.push(`was="${quote(note.was)}"`);
771
+ }
772
+ attributes.push(`title="${quote(note.title)}"`);
773
+ if (note.status !== undefined) {
774
+ attributes.push(`status="${quote(note.status)}"`);
775
+ }
776
+ return `<task_${note.kind} ${attributes.join(" ")}>
777
+ ${note.body}
778
+ </task_${note.kind}>`;
779
+ }
780
+ TaTaskNote2.write = write;
781
+ function parse(text) {
782
+ const match = NOTE.exec(text.trim());
783
+ if (!match) {
784
+ return;
785
+ }
786
+ const attributes = {};
787
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
788
+ attributes[name] = unquote(value);
789
+ }
790
+ if (!attributes.id || attributes.title === undefined) {
791
+ return;
792
+ }
793
+ const { id, title, status, was } = attributes;
794
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
795
+ }
796
+ TaTaskNote2.parse = parse;
797
+ function quote(text) {
798
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
799
+ }
800
+ function unquote(text) {
801
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
802
+ }
803
+ })(TaTaskNote || (TaTaskNote = {}));
804
+ var TaSecretRef;
805
+ (function(TaSecretRef2) {
806
+ TaSecretRef2.PACKAGE = "@celljs/ta-secrets";
807
+ const REF = /\$\{?TA_SECRET_([A-Z0-9][A-Z0-9_]*)\}?/g;
808
+ const KINDS = [
809
+ [/^PHONE(?:_\d+)?$/, "phone"],
810
+ [/^EMAIL(?:_\d+)?$/, "email"],
811
+ [/^ID_NUMBER(?:_\d+)?$/, "idNumber"],
812
+ [/^BANK_CARD(?:_\d+)?$/, "bankCard"]
813
+ ];
814
+ function has(text) {
815
+ return text.includes("TA_SECRET_") && new RegExp(REF.source).test(text);
816
+ }
817
+ TaSecretRef2.has = has;
818
+ function kind(name) {
819
+ var _a;
820
+ var _b;
821
+ return (_b = (_a = KINDS.find(([pattern]) => pattern.test(name))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "secret";
822
+ }
823
+ TaSecretRef2.kind = kind;
824
+ function split(text) {
825
+ if (!has(text)) {
826
+ return [{ text }];
827
+ }
828
+ const parts = [];
829
+ let at = 0;
830
+ for (const match of text.matchAll(REF)) {
831
+ if (match.index > at) {
832
+ parts.push({ text: text.slice(at, match.index) });
833
+ }
834
+ parts.push({ secret: match[1], kind: kind(match[1]) });
835
+ at = match.index + match[0].length;
836
+ }
837
+ if (at < text.length) {
838
+ parts.push({ text: text.slice(at) });
839
+ }
840
+ return parts;
841
+ }
842
+ TaSecretRef2.split = split;
843
+ function plain(text, label) {
844
+ return has(text) ? text.replace(REF, (_whole, name) => label(name, kind(name))) : text;
845
+ }
846
+ TaSecretRef2.plain = plain;
847
+ })(TaSecretRef || (TaSecretRef = {}));
848
+
849
+ // web-src/when.ts
850
+ var WHEN_FORMS = "every 30m (or 30m, 2h, 1d), daily 09:00, weekdays 18:00, weekends 10:00, mon 09:00, mon,wed,fri 09:00, tue-thu 09:00, @daily, @hourly, cron 0 9 * * 1-5 (or the five fields alone), in 45m, at 15:30, at 2026-12-01 08:15, watch src (when files change under a path of its directory, . for all of it), webhook";
851
+ var DAYS = new RegExp(`^(?:${WeekDays.NAMES.join("|")})(?:[-,](?:${WeekDays.NAMES.join("|")}))*$`, "i");
852
+ var HM = /^(\d{1,2}):(\d{2})$/;
853
+ var CRON_WORD = /^[\d*,/a-z-]+$/i;
854
+ function pad2(value) {
855
+ return String(value).padStart(2, "0");
856
+ }
857
+ var When;
858
+ ((When) => {
859
+ function parse(text, now) {
860
+ const { schedule, rest } = leading(text, now);
861
+ if (rest.trim()) {
862
+ throw new Error(`${JSON.stringify(text)} says more than when: ${JSON.stringify(rest.trim())}. when is one of: ${WHEN_FORMS}.`);
863
+ }
864
+ return schedule;
865
+ }
866
+ When.parse = parse;
867
+ function leading(text, now) {
868
+ const source = text.trim();
869
+ const quote = source[0];
870
+ if (quote === '"' || quote === "'") {
871
+ const end = source.indexOf(quote, 1);
872
+ if (end < 0) {
873
+ throw new Error("The cron expression has no closing quote.");
874
+ }
875
+ return { schedule: ScheduleUtil.check({ kind: "cron", expression: source.slice(1, end) }), rest: source.slice(end + 1) };
876
+ }
877
+ const words = Words.of(source);
878
+ const word = (index) => words.word(index);
879
+ const first = word(0).toLowerCase();
880
+ const done = (schedule, used) => ({ schedule: ScheduleUtil.check(schedule), rest: words.after(used) });
881
+ if (first === "every" && Duration.parse(word(1)) !== undefined) {
882
+ return done({ kind: "interval", every: word(1) }, 2);
883
+ }
884
+ if (Duration.parse(first) !== undefined) {
885
+ return done({ kind: "interval", every: first }, 1);
886
+ }
887
+ if (first.startsWith("@")) {
888
+ return done({ kind: "cron", expression: first }, 1);
889
+ }
890
+ if (first === "hourly") {
891
+ return done({ kind: "cron", expression: "0 * * * *" }, 1);
892
+ }
893
+ if (first === "cron") {
894
+ const nickname = word(1).startsWith("@") || word(1).startsWith('"') || word(1).startsWith("'");
895
+ if (nickname) {
896
+ const inner = leading(words.after(1), now);
897
+ return { schedule: inner.schedule, rest: inner.rest };
898
+ }
899
+ return done({ kind: "cron", expression: words.slice(1, 6).join(" ") }, 6);
900
+ }
901
+ const days = first === "daily" ? "*" : first === "weekdays" ? "1-5" : first === "weekends" ? "0,6" : DAYS.test(first) ? first : undefined;
902
+ if (days !== undefined) {
903
+ const time = HM.exec(word(1));
904
+ if (!time || Number(time[1]) > 23 || Number(time[2]) > 59) {
905
+ throw new Error(`${first} needs a time after it, as ${first} 09:00.`);
906
+ }
907
+ const field = WeekDays.field(WeekDays.of(days) ?? []);
908
+ return done({ kind: "cron", expression: `${Number(time[2])} ${Number(time[1])} * * ${field}` }, 2);
909
+ }
910
+ if (first === "in") {
911
+ const ms = Duration.parse(word(1));
912
+ if (ms === undefined) {
913
+ throw new Error("in needs a duration after it, as in 45m.");
914
+ }
915
+ return done({ kind: "once", at: new Date(now.getTime() + ms).toISOString() }, 2);
916
+ }
917
+ if (first === "at") {
918
+ const at = clockTime([word(1), word(2)], now);
919
+ if (!at) {
920
+ throw new Error("at needs a time after it: at 15:30 (today, or tomorrow once it passed), at 2026-12-01 08:15.");
921
+ }
922
+ return done({ kind: "once", at: at.date.toISOString() }, 1 + at.words);
923
+ }
924
+ if (first === "watch") {
925
+ return done({ kind: "watch", path: word(1) || "." }, word(1) ? 2 : 1);
926
+ }
927
+ if (first === "webhook") {
928
+ return done({ kind: "webhook" }, 1);
929
+ }
930
+ const five = words.slice(0, 5);
931
+ if (five.length === 5 && five.every((part) => CRON_WORD.test(part))) {
932
+ try {
933
+ return done({ kind: "cron", expression: five.join(" ") }, 5);
934
+ } catch {}
935
+ }
936
+ throw new Error(`Start with when: ${JSON.stringify(word(0))} is none of: ${WHEN_FORMS}.`);
937
+ }
938
+ When.leading = leading;
939
+ function clockTime(words, now) {
940
+ const [first = "", second = ""] = words;
941
+ const day = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
942
+ const time = HM.exec(first);
943
+ if (time) {
944
+ const date2 = new Date(now.getTime());
945
+ date2.setHours(Number(time[1]), Number(time[2]), 0, 0);
946
+ if (date2.getTime() <= now.getTime()) {
947
+ date2.setDate(date2.getDate() + 1);
948
+ }
949
+ return valid(date2, Number(time[1]) < 24 && Number(time[2]) < 60) ? { date: date2, words: 1 } : undefined;
950
+ }
951
+ const date = day.exec(first);
952
+ const later = HM.exec(second);
953
+ if (date) {
954
+ const at = new Date(Number(date[1]), Number(date[2]) - 1, Number(date[3]), later ? Number(later[1]) : 9, later ? Number(later[2]) : 0);
955
+ return valid(at, true) ? { date: at, words: later ? 2 : 1 } : undefined;
956
+ }
957
+ const iso = /^\d{4}-\d{2}-\d{2}T/.test(first) ? new Date(first) : undefined;
958
+ return iso && valid(iso, true) ? { date: iso, words: 1 } : undefined;
959
+ }
960
+ When.clockTime = clockTime;
961
+ function format(schedule) {
962
+ switch (schedule.kind) {
963
+ case "interval":
964
+ return `every ${schedule.every}`;
965
+ case "once": {
966
+ const at = new Date(schedule.at);
967
+ return `at ${at.getFullYear()}-${pad2(at.getMonth() + 1)}-${pad2(at.getDate())} ${pad2(at.getHours())}:${pad2(at.getMinutes())}`;
968
+ }
969
+ case "watch":
970
+ return `watch ${schedule.path}`;
971
+ case "webhook":
972
+ return "webhook";
973
+ case "cron": {
974
+ const daily = timeAndDays(schedule.expression);
975
+ if (!daily) {
976
+ return `cron ${schedule.expression}`;
977
+ }
978
+ const field = WeekDays.field(daily.days);
979
+ const days = field === "*" ? "daily" : field === "1-5" ? "weekdays" : field === "0,6" ? "weekends" : daily.days.map((day) => WeekDays.NAMES[day]).join(",");
980
+ return `${days} ${daily.time}`;
981
+ }
982
+ }
983
+ }
984
+ When.format = format;
985
+ function timeAndDays(expression) {
986
+ const [minute, hour, day, month, weekday] = (NICKNAMES[expression.toLowerCase()] ?? expression).split(" ");
987
+ if (!/^\d+$/.test(minute ?? "") || !/^\d+$/.test(hour ?? "") || day !== "*" || month !== "*") {
988
+ return;
989
+ }
990
+ const days = WeekDays.of(weekday ?? "");
991
+ return days && { time: `${pad2(Number(hour))}:${pad2(Number(minute))}`, hour: Number(hour), minute: Number(minute), days };
992
+ }
993
+ When.timeAndDays = timeAndDays;
994
+ function nextTimes(schedule, now, count = 3) {
995
+ const times = [];
996
+ for (let next = ScheduleUtil.next(schedule, now);next && times.length < count; next = ScheduleUtil.next(schedule, next)) {
997
+ times.push(next);
998
+ if (schedule.kind === "once") {
999
+ break;
1000
+ }
1001
+ }
1002
+ return times;
1003
+ }
1004
+ When.nextTimes = nextTimes;
1005
+ function preview(rule, now, count = 3) {
1006
+ const schedule = typeof rule === "string" ? parse(rule, now) : ScheduleUtil.check(rule);
1007
+ const next = nextTimes(schedule, now, Math.min(10, Math.max(1, count)));
1008
+ if (next.length === 0 && !ScheduleUtil.isEvent(schedule)) {
1009
+ throw new Error(schedule.kind === "once" ? "That time has passed: give one to come." : "That rule never comes round: check the cron expression.");
1010
+ }
1011
+ return { schedule, when: format(schedule), describe: ScheduleUtil.describe(schedule, "en-US", now), next: next.map((time) => time.toISOString()) };
1012
+ }
1013
+ When.preview = preview;
1014
+ function valid(date, ok) {
1015
+ return ok && !Number.isNaN(date.getTime());
1016
+ }
1017
+ })(When ||= {});
1018
+
1019
+ class Words {
1020
+ source;
1021
+ list;
1022
+ constructor(source, list) {
1023
+ this.source = source;
1024
+ this.list = list;
1025
+ }
1026
+ static of(source) {
1027
+ const list = [];
1028
+ for (const match of source.matchAll(/\S+/g)) {
1029
+ list.push({ text: match[0], end: (match.index ?? 0) + match[0].length });
1030
+ }
1031
+ return new Words(source, list);
1032
+ }
1033
+ word(index) {
1034
+ return this.list[index]?.text ?? "";
1035
+ }
1036
+ slice(start, end) {
1037
+ return this.list.slice(start, end).map((word) => word.text);
1038
+ }
1039
+ after(count) {
1040
+ if (count <= 0) {
1041
+ return this.source;
1042
+ }
1043
+ const last = this.list[Math.min(count, this.list.length) - 1];
1044
+ return last ? this.source.slice(last.end) : "";
1045
+ }
1046
+ }
1047
+
479
1048
  // web-src/task-util.ts
480
1049
  var PROMPT_MAX = 20000;
481
1050
  var NAME_MAX = 80;
@@ -488,9 +1057,28 @@ var TaskUtil;
488
1057
  return `${prefix}_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
489
1058
  }
490
1059
  TaskUtil.newId = newId;
1060
+ function newSecret() {
1061
+ const bytes = new Uint8Array(24);
1062
+ crypto.getRandomValues(bytes);
1063
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1064
+ }
1065
+ TaskUtil.newSecret = newSecret;
1066
+ function withSecret(task) {
1067
+ if (task.schedule.kind === "webhook") {
1068
+ return task.hookSecret ? task : { ...task, hookSecret: newSecret() };
1069
+ }
1070
+ if (!task.hookSecret) {
1071
+ return task;
1072
+ }
1073
+ const { hookSecret: _gone, ...rest } = task;
1074
+ return rest;
1075
+ }
491
1076
  function create(input, cwd, now) {
492
1077
  const prompt = checkPrompt(input?.prompt);
493
- const schedule = ScheduleUtil.check(input.schedule);
1078
+ const schedule = ruleOf(input, now);
1079
+ if (!schedule) {
1080
+ throw new Error(`A task needs when it runs: when, one of ${WHEN_FORMS}.`);
1081
+ }
494
1082
  const at = now.toISOString();
495
1083
  const task = {
496
1084
  id: newId("task"),
@@ -505,7 +1093,7 @@ var TaskUtil;
505
1093
  updatedAt: at
506
1094
  };
507
1095
  setOptional(task, input);
508
- return arm(task, now);
1096
+ return arm(withSecret(task), now);
509
1097
  }
510
1098
  TaskUtil.create = create;
511
1099
  function patch(task, patch2, now) {
@@ -523,17 +1111,37 @@ var TaskUtil;
523
1111
  if (patch2.enabled !== undefined) {
524
1112
  next.enabled = patch2.enabled === true;
525
1113
  }
526
- if (patch2.schedule !== undefined) {
527
- next.schedule = ScheduleUtil.check(patch2.schedule);
1114
+ const schedule = ruleOf(patch2, now);
1115
+ if (schedule) {
1116
+ next.schedule = schedule;
528
1117
  }
529
- const rearm = patch2.schedule !== undefined || next.enabled && !task.enabled;
530
- return rearm ? arm(next, now) : next;
1118
+ const rearm = schedule !== undefined || next.enabled && !task.enabled;
1119
+ const secured = withSecret(next);
1120
+ return rearm ? arm(secured, now) : secured;
531
1121
  }
532
1122
  TaskUtil.patch = patch;
1123
+ function unique(tasks, task, named) {
1124
+ const twin = named ? tasks.find((other) => other.name === task.name && other.cwd === task.cwd) : undefined;
1125
+ if (twin) {
1126
+ throw new Error(`A task named ${JSON.stringify(twin.name)} is already in ${twin.cwd} (${twin.id}): change it with update, or give the new one another name.`);
1127
+ }
1128
+ }
1129
+ TaskUtil.unique = unique;
1130
+ function ruleOf(input, now) {
1131
+ if (typeof input?.when === "string" && input.when.trim()) {
1132
+ return When.parse(input.when, now);
1133
+ }
1134
+ return input?.schedule === undefined ? undefined : ScheduleUtil.check(input.schedule);
1135
+ }
1136
+ TaskUtil.ruleOf = ruleOf;
533
1137
  function arm(task, now) {
534
1138
  if (!task.enabled) {
535
1139
  return task;
536
1140
  }
1141
+ if (ScheduleUtil.isEvent(task.schedule)) {
1142
+ const { nextRunAt: _none, ...rest } = task;
1143
+ return rest;
1144
+ }
537
1145
  const next = ScheduleUtil.next(task.schedule, now);
538
1146
  if (!next) {
539
1147
  throw new Error(task.schedule.kind === "once" ? `The time of ${task.name} (${task.schedule.at}) has passed: give it a time to come.` : `The rule of ${task.name} never comes round: check the cron expression.`);
@@ -616,6 +1224,11 @@ var TaskUtil;
616
1224
  }
617
1225
  return level || undefined;
618
1226
  }
1227
+ function wrapUp(timeoutMs2, wrapUpMs) {
1228
+ const minutes = (ms) => Math.max(1, Math.round(ms / 60000));
1229
+ return TaMessageSource.notice(`This scheduled run has reached its time limit of ${minutes(timeoutMs2)} minutes. Start nothing new. Within ${minutes(wrapUpMs)} minutes, wrap up: keep what is done and checked, leave what is not as it is safe to leave, and answer with where it stands and what is left; after that the run is stopped.`, NAME);
1230
+ }
1231
+ TaskUtil.wrapUp = wrapUp;
619
1232
  function timeoutMs(task, fallback) {
620
1233
  return task.timeout && Duration.parse(task.timeout) || fallback;
621
1234
  }
@@ -646,21 +1259,96 @@ var TaskUtil;
646
1259
  return line.replace(/^\s*(?:#{1,6}\s+|[-*+]\s+|>\s*|\d+[.)]\s+)/, "").replace(/\*\*|__|`/g, "").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").trim();
647
1260
  }
648
1261
  TaskUtil.firstLine = firstLine;
649
- function split(tasks, stay = new Set) {
650
- const listed = [];
651
- const off = [];
652
- for (const task of tasks) {
653
- (task.enabled || task.lastStatus === "running" || stay.has(task.id) ? listed : off).push(task);
654
- }
655
- return [listed, off];
656
- }
657
- TaskUtil.split = split;
658
1262
  function missed(task, now) {
659
1263
  return task.schedule.kind === "once" && !!task.nextRunAt && now.getTime() - new Date(task.nextRunAt).getTime() > Limits.GRACE_MS;
660
1264
  }
661
1265
  TaskUtil.missed = missed;
662
1266
  })(TaskUtil ||= {});
663
1267
 
1268
+ // web-src/task-watchers.ts
1269
+ var UNWATCHED = /(^|[\\/])(\.git|node_modules|\.turbo|\.next|dist|lib|esm|build|\.cell|\.DS_Store)([\\/]|$)|~$|\.swp$/;
1270
+ function resolvePath(cwd, path) {
1271
+ if (path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path)) {
1272
+ return path;
1273
+ }
1274
+ const base = cwd.replace(/[\\/]+$/, "");
1275
+ return path === "." || path === "./" ? base : `${base}/${path.replace(/^\.\//, "")}`;
1276
+ }
1277
+
1278
+ class TaskWatchers {
1279
+ watch;
1280
+ quietMs;
1281
+ fire;
1282
+ watching = new Map;
1283
+ constructor(watch, quietMs, fire) {
1284
+ this.watch = watch;
1285
+ this.quietMs = quietMs;
1286
+ this.fire = fire;
1287
+ }
1288
+ sync(tasks, off = false) {
1289
+ const wanted = new Map;
1290
+ if (!off && this.watch) {
1291
+ for (const task of tasks) {
1292
+ if (task.enabled && task.schedule.kind === "watch" && !task.cwd.includes("://")) {
1293
+ wanted.set(task.id, resolvePath(task.cwd, task.schedule.path));
1294
+ }
1295
+ }
1296
+ }
1297
+ for (const [id, watching] of [...this.watching]) {
1298
+ if (wanted.get(id) !== watching.path) {
1299
+ this.unwatch(id);
1300
+ }
1301
+ }
1302
+ for (const [id, path] of wanted) {
1303
+ if (this.watching.has(id) || !this.watch) {
1304
+ continue;
1305
+ }
1306
+ const watching = { path, stop: () => {
1307
+ return;
1308
+ }, files: new Set, more: 0 };
1309
+ try {
1310
+ watching.stop = this.watch(path, (file) => this.changed(id, watching, file));
1311
+ } catch (error) {
1312
+ console.error(`${NAME}: cannot watch ${path}: ${error instanceof Error ? error.message : String(error)}`);
1313
+ continue;
1314
+ }
1315
+ this.watching.set(id, watching);
1316
+ }
1317
+ }
1318
+ unwatch(id) {
1319
+ const watching = this.watching.get(id);
1320
+ if (watching) {
1321
+ clearTimeout(watching.timer);
1322
+ watching.stop();
1323
+ this.watching.delete(id);
1324
+ }
1325
+ }
1326
+ changed(id, watching, file) {
1327
+ if (UNWATCHED.test(file) || this.watching.get(id) !== watching) {
1328
+ return;
1329
+ }
1330
+ if (watching.files.size < Limits.EVENT_FILES) {
1331
+ watching.files.add(file);
1332
+ } else if (!watching.files.has(file)) {
1333
+ watching.more++;
1334
+ }
1335
+ clearTimeout(watching.timer);
1336
+ watching.timer = setTimeout(() => {
1337
+ const files = [...watching.files];
1338
+ const more = watching.more;
1339
+ watching.files.clear();
1340
+ watching.more = 0;
1341
+ if (files.length > 0) {
1342
+ this.fire(id, `Files changed in ${watching.path}:
1343
+ ${files.map((name) => `- ${name}`).join(`
1344
+ `)}${more ? `
1345
+ …and ${more} more` : ""}`);
1346
+ }
1347
+ }, this.quietMs);
1348
+ watching.timer.unref?.();
1349
+ }
1350
+ }
1351
+
664
1352
  // web-src/scheduler.ts
665
1353
  class CronScheduler {
666
1354
  host;
@@ -669,17 +1357,37 @@ class CronScheduler {
669
1357
  options;
670
1358
  active = new Map;
671
1359
  waiting = [];
1360
+ watchers;
1361
+ queued = new Map;
672
1362
  working = 0;
673
1363
  lingering = new Set;
674
1364
  timer;
675
1365
  ticking = false;
676
1366
  disposed = false;
1367
+ startedAt = 0;
677
1368
  constructor(host, options = {}) {
678
1369
  this.host = host;
679
1370
  this.store = new TaskStore(host);
680
- this.options = { now: () => new Date, tickMs: 60000, pollMs: 1000, timeoutMs: Limits.RUN_TIMEOUT_MS, parallel: Limits.PARALLEL_RUNS, ...options };
1371
+ this.options = {
1372
+ now: () => new Date,
1373
+ tickMs: 60000,
1374
+ pollMs: 1000,
1375
+ timeoutMs: Limits.RUN_TIMEOUT_MS,
1376
+ wrapUpMs: Limits.WRAP_UP_MS,
1377
+ parallel: Limits.PARALLEL_RUNS,
1378
+ resumeWaitMs: Limits.RESUME_WAIT_MS,
1379
+ quietMs: Limits.WATCH_QUIET_MS,
1380
+ ...options
1381
+ };
1382
+ this.watchers = new TaskWatchers(this.options.watch, this.options.quietMs, (id, event) => {
1383
+ const task = this.tasks.find((other) => other.id === id);
1384
+ if (task?.enabled) {
1385
+ this.fire(task, event).catch((error) => console.error(`${NAME}: ${message(error)}`));
1386
+ }
1387
+ });
681
1388
  }
682
1389
  async start() {
1390
+ this.startedAt = Date.now();
683
1391
  this.tasks = await this.store.tasks();
684
1392
  const now = this.options.now();
685
1393
  for (const task of this.tasks) {
@@ -687,6 +1395,9 @@ class CronScheduler {
687
1395
  await this.reclaim(task, now);
688
1396
  }
689
1397
  }
1398
+ for (const active of this.active.values()) {
1399
+ this.follow(active);
1400
+ }
690
1401
  for (const task of [...this.tasks]) {
691
1402
  if (task.enabled && TaskUtil.missed(task, now)) {
692
1403
  await this.miss(task, now);
@@ -694,10 +1405,12 @@ class CronScheduler {
694
1405
  }
695
1406
  await this.store.saveTasks(this.tasks);
696
1407
  this.arm();
1408
+ this.syncWatchers();
697
1409
  }
698
1410
  async dispose() {
699
1411
  this.disposed = true;
700
1412
  clearTimeout(this.timer);
1413
+ this.watchers.sync(this.tasks, true);
701
1414
  await this.store.flush();
702
1415
  }
703
1416
  async list() {
@@ -713,6 +1426,7 @@ class CronScheduler {
713
1426
  async add(input) {
714
1427
  const cwd = (await this.host.getServerInfo()).cwd;
715
1428
  const task = TaskUtil.create(input, cwd, this.options.now());
1429
+ TaskUtil.unique(this.tasks, task, !!input.name?.trim());
716
1430
  await this.save([...this.tasks, task]);
717
1431
  return { ...task };
718
1432
  }
@@ -742,6 +1456,42 @@ class CronScheduler {
742
1456
  }
743
1457
  return this.begin(task, "manual", this.options.now());
744
1458
  }
1459
+ async preview(when, count = 3) {
1460
+ return When.preview(when, this.options.now(), count);
1461
+ }
1462
+ async hookUrl(ref) {
1463
+ const task = TaskUtil.find(this.tasks, ref);
1464
+ const base = task.hookSecret && await this.options.serverUrl?.();
1465
+ return base ? `${base.replace(/\/$/, "")}${HOOK_PATH}${task.hookSecret}` : undefined;
1466
+ }
1467
+ async webhook(request) {
1468
+ const secret = typeof request?.path === "string" ? request.path.split("/")[0] : "";
1469
+ const task = secret ? this.tasks.find((other) => other.enabled && other.schedule.kind === "webhook" && same(other.hookSecret ?? "", secret)) : undefined;
1470
+ if (!task) {
1471
+ throw new Error("No task has this webhook.");
1472
+ }
1473
+ const body = typeof request.body === "string" ? request.body.trim() : "";
1474
+ const event = body ? `The webhook of the task was called with:
1475
+ ${clipEvent(body)}` : "The webhook of the task was called, with nothing sent.";
1476
+ const run = await this.fire(task, event);
1477
+ return run ? { run: run.id } : { queued: true };
1478
+ }
1479
+ async fire(task, event) {
1480
+ if (this.disposed) {
1481
+ return;
1482
+ }
1483
+ if (this.active.has(task.id)) {
1484
+ const before = this.queued.get(task.id);
1485
+ this.queued.set(task.id, clipEvent(before ? `${before}
1486
+
1487
+ ${event}` : event));
1488
+ return;
1489
+ }
1490
+ return this.begin(task, "event", this.options.now(), event);
1491
+ }
1492
+ syncWatchers() {
1493
+ this.watchers.sync(this.tasks, this.disposed);
1494
+ }
745
1495
  isRun(sessionId) {
746
1496
  return [...this.active.values()].some((active) => active.sessionId === sessionId);
747
1497
  }
@@ -792,8 +1542,16 @@ class CronScheduler {
792
1542
  const next = ScheduleUtil.next(task.schedule, now);
793
1543
  return { ...task, nextRunAt: next?.toISOString() };
794
1544
  }
795
- async begin(task, trigger, now) {
796
- const run = { id: TaskUtil.newId("run"), taskId: task.id, trigger, status: "running", startedAt: now.toISOString(), cwd: task.cwd };
1545
+ async begin(task, trigger, now, event) {
1546
+ const run = {
1547
+ id: TaskUtil.newId("run"),
1548
+ taskId: task.id,
1549
+ trigger,
1550
+ status: "running",
1551
+ startedAt: now.toISOString(),
1552
+ cwd: task.cwd,
1553
+ ...event ? { event } : {}
1554
+ };
797
1555
  const started = trigger === "schedule" ? this.advance(task, now) : task;
798
1556
  await this.replace({ ...started, lastRunAt: run.startedAt, lastStatus: "running" });
799
1557
  await this.store.saveRun(run);
@@ -833,21 +1591,73 @@ class CronScheduler {
833
1591
  });
834
1592
  const state = await this.host.getState(sessionId);
835
1593
  run.sessionFile = state.sessionFile;
1594
+ run.sessionId = sessionId;
836
1595
  await this.store.saveRun(run);
837
- await this.host.prompt(sessionId, { clientMessageId: run.id, message: task.prompt });
838
- await this.settled(active, state.messageCount);
839
- const { text } = await this.host.getLastAssistantText(sessionId);
840
- if (!text?.trim()) {
841
- throw new Error("The run ended without an answer; the model may have failed. Open its conversation to see.");
842
- }
843
- await this.finish(active, { status: "success", summary: clip(text.trim()) });
1596
+ const prompt = run.event ? `${task.prompt}
1597
+
1598
+ <ta-cron-event>
1599
+ ${run.event}
1600
+ </ta-cron-event>` : task.prompt;
1601
+ await this.host.prompt(sessionId, { clientMessageId: run.id, message: prompt });
1602
+ await this.conclude(active, state.messageCount);
844
1603
  } catch (error) {
845
- await this.finish(active, { status: "error", error: message(error), ...error instanceof TimeoutError ? { reason: "timeout" } : {} });
1604
+ await this.fail(active, error);
1605
+ }
1606
+ }
1607
+ follow(active) {
1608
+ this.working++;
1609
+ this.resumed(active).catch((error) => this.fail(active, error)).catch((error) => console.error(`${NAME}: ${message(error)}`)).finally(() => {
1610
+ this.working--;
1611
+ this.pump();
1612
+ });
1613
+ }
1614
+ async resumed(active) {
1615
+ const until = Date.now() + this.options.resumeWaitMs;
1616
+ for (;; ) {
1617
+ if (active.dropped || this.disposed) {
1618
+ throw new Error("The task was removed while it ran.");
1619
+ }
1620
+ const info = (await this.host.listSessions()).find((session) => session.sessionId === active.sessionId);
1621
+ if (info?.isStreaming || info && await this.answeredSince(active.run)) {
1622
+ break;
1623
+ }
1624
+ if (Date.now() > until) {
1625
+ await this.finish(active, { status: "error", reason: "interrupted", error: INTERRUPTED });
1626
+ return;
1627
+ }
1628
+ await new Promise((resolve) => setTimeout(resolve, this.options.pollMs));
1629
+ }
1630
+ await this.conclude(active, 0, active.run.ranMs ?? 0);
1631
+ }
1632
+ async answeredSince(run) {
1633
+ const messages = run.sessionFile ? await this.host.sessionMessages(run.sessionFile).catch(() => []) : [];
1634
+ return messages.some((item) => {
1635
+ const { role, timestamp } = item;
1636
+ return role === "assistant" && new Date(timestamp ?? 0).getTime() >= this.startedAt;
1637
+ });
1638
+ }
1639
+ async conclude(active, before, ran = 0) {
1640
+ await this.settled(active, before, ran);
1641
+ const { text } = await this.host.getLastAssistantText(active.sessionId);
1642
+ if (!text?.trim()) {
1643
+ throw new Error(await this.noAnswer(active.run));
846
1644
  }
1645
+ await this.finish(active, { status: "success", summary: clip(text.trim()) });
847
1646
  }
848
- async settled(active, before) {
1647
+ async noAnswer(run) {
1648
+ const messages = run.sessionFile ? await this.host.sessionMessages(run.sessionFile).catch(() => []) : [];
1649
+ const last = [...messages].reverse().find((item) => item.role === "assistant");
1650
+ const error = typeof last?.errorMessage === "string" ? last.errorMessage.trim() : "";
1651
+ return error ? `The model failed: ${clip(error, ERROR_MAX)}` : "The run ended without an answer; the model may have failed. Open its conversation to see.";
1652
+ }
1653
+ fail(active, error) {
1654
+ return this.finish(active, { status: "error", error: message(error), ...error instanceof TimeoutError ? { reason: "timeout" } : {} });
1655
+ }
1656
+ async settled(active, before, ran = 0) {
849
1657
  const sessionId = active.sessionId;
850
- const start = Date.now();
1658
+ const start = Date.now() - ran;
1659
+ let saved = Date.now();
1660
+ let told = false;
851
1661
  for (;; ) {
852
1662
  if (active.dropped || this.disposed) {
853
1663
  throw new Error("The task was removed while it ran.");
@@ -856,8 +1666,20 @@ class CronScheduler {
856
1666
  if (!state.isStreaming && state.pendingMessageCount === 0 && state.messageCount > before) {
857
1667
  return;
858
1668
  }
1669
+ if (Date.now() - saved >= Limits.RAN_SAVE_MS) {
1670
+ saved = Date.now();
1671
+ active.run.ranMs = saved - start;
1672
+ await this.store.saveRun(active.run);
1673
+ }
859
1674
  const timeoutMs = TaskUtil.timeoutMs(active.task, this.options.timeoutMs);
860
- if (Date.now() - start > timeoutMs) {
1675
+ const over = Date.now() - start - timeoutMs;
1676
+ if (over > 0 && !told && this.options.wrapUpMs > 0) {
1677
+ told = true;
1678
+ const message = TaskUtil.wrapUp(timeoutMs, this.options.wrapUpMs);
1679
+ await this.host.prompt(sessionId, { clientMessageId: `${active.run.id}_wrap`, message, streamingBehavior: "steer" }).catch(() => {
1680
+ return;
1681
+ });
1682
+ } else if (over > this.options.wrapUpMs) {
861
1683
  await this.host.abort(sessionId).catch(() => {
862
1684
  return;
863
1685
  });
@@ -890,6 +1712,11 @@ class CronScheduler {
890
1712
  await this.store.finished({ run, taskName: current.name, notify: ScheduleUtil.shouldNotify(ScheduleUtil.notifyLevel(current), failed) });
891
1713
  }
892
1714
  await this.sweep();
1715
+ const next = this.queued.get(active.task.id);
1716
+ this.queued.delete(active.task.id);
1717
+ if (next && current?.enabled && ScheduleUtil.isEvent(current.schedule)) {
1718
+ await this.fire(current, next);
1719
+ }
893
1720
  }
894
1721
  async sweep() {
895
1722
  if (this.lingering.size === 0) {
@@ -910,17 +1737,19 @@ class CronScheduler {
910
1737
  }
911
1738
  async reclaim(task, now) {
912
1739
  for (const run of await this.store.runs(task.id)) {
913
- if (run.status === "running") {
914
- await this.store.saveRun({
915
- ...run,
916
- status: "error",
917
- reason: "interrupted",
918
- error: "The Ta service stopped before the run ended.",
919
- endedAt: now.toISOString()
920
- });
1740
+ if (run.status !== "running") {
1741
+ continue;
1742
+ }
1743
+ if (run.sessionId && !this.active.has(task.id)) {
1744
+ this.active.set(task.id, { run, task: { ...task }, sessionId: run.sessionId });
1745
+ } else {
1746
+ await this.store.saveRun({ ...run, status: "error", reason: "interrupted", error: INTERRUPTED, endedAt: now.toISOString() });
921
1747
  }
922
1748
  }
923
- this.tasks = this.tasks.map((other) => other.id === task.id ? { ...other, lastStatus: "error", failCount: other.failCount + 1 } : other);
1749
+ if (this.active.has(task.id)) {
1750
+ return;
1751
+ }
1752
+ this.tasks = this.tasks.map((other) => other.id === task.id ? { ...other, lastStatus: "error", runCount: other.runCount + 1, failCount: other.failCount + 1 } : other);
924
1753
  }
925
1754
  async miss(task, now) {
926
1755
  const run = {
@@ -941,6 +1770,7 @@ class CronScheduler {
941
1770
  async drop(tasks) {
942
1771
  const ids = new Set(tasks.map((task) => task.id));
943
1772
  for (const id of ids) {
1773
+ this.queued.delete(id);
944
1774
  const active = this.active.get(id);
945
1775
  if (active) {
946
1776
  active.dropped = true;
@@ -961,21 +1791,49 @@ class CronScheduler {
961
1791
  this.tasks = tasks;
962
1792
  await this.store.saveTasks(tasks);
963
1793
  this.arm();
1794
+ this.syncWatchers();
964
1795
  }
965
1796
  }
1797
+ var INTERRUPTED = "The Ta service stopped before the run ended.";
966
1798
 
967
1799
  class TimeoutError extends Error {
968
1800
  }
969
- function clip(text) {
970
- return text.length > Limits.SUMMARY_MAX ? `${text.slice(0, Limits.SUMMARY_MAX - 1)}…` : text;
1801
+ function same(a, b) {
1802
+ let differ = a.length ^ b.length;
1803
+ for (let index = 0;index < Math.max(a.length, b.length); index++) {
1804
+ differ |= (a.charCodeAt(index) || 0) ^ (b.charCodeAt(index) || 0);
1805
+ }
1806
+ return differ === 0;
1807
+ }
1808
+ function clipEvent(text) {
1809
+ return text.length > Limits.EVENT_MAX ? `${text.slice(0, Limits.EVENT_MAX - 1)}…` : text;
971
1810
  }
1811
+ function clip(text, max = Limits.SUMMARY_MAX) {
1812
+ return text.length > max ? `${text.slice(0, max - 1)}…` : text;
1813
+ }
1814
+ var ERROR_MAX = 300;
972
1815
  function message(error) {
973
1816
  return error instanceof Error ? error.message : String(error);
974
1817
  }
975
1818
 
976
1819
  // web-src/host.ts
977
1820
  async function activate(host) {
978
- const scheduler = new CronScheduler(host);
1821
+ const scheduler = new CronScheduler(host, {
1822
+ watch: (path, changed) => {
1823
+ const watcher = watch(path, { recursive: true, persistent: false }, (_kind, name) => changed(name ? String(name) : path));
1824
+ watcher.on("error", () => {
1825
+ return;
1826
+ });
1827
+ return () => watcher.close();
1828
+ },
1829
+ serverUrl: async () => {
1830
+ const info = await readFile(join(host.agentDir, "serve.json"), "utf8").catch(() => {
1831
+ return;
1832
+ });
1833
+ const url = info && JSON.parse(info).url;
1834
+ return url ? new URL(url.replace(/^ws/, "http")).origin : undefined;
1835
+ }
1836
+ });
979
1837
  await scheduler.start();
980
1838
  return scheduler;
981
1839
  }