@celljs/ta-cron 4.18.0 → 4.20.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.en.md CHANGED
@@ -30,10 +30,11 @@ When a task runs is said in a line of words (`when`), the same for a person and
30
30
  - **Interval**: `30m`, `2h`, `1d`, `1h30m`; at least 1 minute.
31
31
  - **cron**: five fields (minute hour day month weekday) with `*`, ranges, lists, steps and names such as `jan` and `mon`, and `@hourly`, `@daily`, `@weekly`, `@monthly`, `@yearly`; when both days are restricted, either one matches (as in cron). Quote an expression with spaces.
32
32
 
33
+ - **Random delay**: a task that runs at a time may have a `jitter` (`30m`, `1h`, from 1 minute to 12 hours): each run starts at random within it after the time of its rule, so `daily 08:30` with `jitter: 30m` runs between 08:30 and 09:00, at another time each day: daily chores such as a check-in done at about a time, as a person would, and tasks of the same time spread out rather than load the Ta service at once. Set it under Random delay in the editor, with `/schedule set <task> --jitter 30m` (`-` back to on time), or `jitter` of the tool `schedule_task` and of `ta call`; the next run shows the time drawn, the next three show as windows. Not for tasks run by files or a webhook.
33
34
  - **When files change**: `{ "kind": "watch", "path": "src" }`, a folder or a file of the task's directory (`.` for all of it) or an absolute path; not of a remote directory. A run starts once the files rest for 5 seconds, its prompt followed by the files that changed (`<ta-cron-event>`, at most 30); changes in `.git`, `node_modules` and build folders do not count. Changes while a run works make one more run after it.
34
35
  - **When its webhook is called**: `{ "kind": "webhook" }`. The task has an address of its own, `http://<the Ta service>/api/hooks/ta-cron/<secret>` (copied from the task, also given by `/schedule show` and the show of the tool); a POST to it on this computer runs the task, what it sends (at most 256 KB; at most 4000 characters told to the run) following the prompt. For git hooks, a CI of this computer and scripts. The address needs no token of the Ta service: whoever has it can run the task; another rule ends it.
35
36
 
36
- Times are local to the machine of the Ta service. A command may end with `--name`, `--notify always|error|never`, `--model <provider>/<model>`, `--thinking <level>`, `--cwd <directory>` and `--timeout <duration>`.
37
+ Times are local to the machine of the Ta service. A command may end with `--name`, `--notify always|error|never`, `--model <provider>/<model>`, `--thinking <level>`, `--cwd <directory>`, `--timeout <duration>` and `--jitter <duration>`.
37
38
 
38
39
  ## For agents and scripts
39
40
 
package/README.md CHANGED
@@ -30,10 +30,11 @@ Ta 自带的 pi 包(默认开启,可在 Web 客户端的 设置 → 扩展
30
30
  - **间隔**:`30m`、`2h`、`1d`、`1h30m`,最短 1 分钟。
31
31
  - **cron**:五个字段(分 时 日 月 周),支持 `*`、范围、列表、步长和 `jan`、`mon` 这类名字,以及 `@hourly`、`@daily`、`@weekly`、`@monthly`、`@yearly`;日和周都限定时,任一个匹配即可(与 cron 相同)。表达式里有空格时要加引号。
32
32
 
33
+ - **随机延后**:按时间运行的任务可以设 `jitter`(`30m`、`1h`,1 分钟到 12 小时),每次在规则的时间之后这段时间内随机开始,例如 `daily 08:30` 加 `jitter: 30m` 在 08:30–09:00 之间随机运行、每次不同:像人一样在大致的时间做签到、打卡这类日常事,也让同一时刻的任务错开,不一起挤占 Ta 服务。编辑器"时间"下的"随机延后"、`/schedule set <任务> --jitter 30m`(`-` 恢复准时)、工具 `schedule_task` 和 `ta call` 的 `jitter` 都能设;下次运行显示抽到的时间,接下来三次显示成时间段。文件变化和 Webhook 触发的任务不能设。
33
34
  - **文件变化时**:`{ "kind": "watch", "path": "src" }`,监听任务目录下的文件夹或文件(`.` 是整个目录,也可以写绝对路径;远程目录不支持)。文件停下 5 秒后运行,这次运行的提示词后面附上改了哪些文件(`<ta-cron-event>`,最多 30 个);`.git`、`node_modules`、构建目录里的变化不算。运行还没结束时又有变化,结束后再运行一次。
34
35
  - **收到 Webhook 时**:`{ "kind": "webhook" }`。任务有一个随机地址 `http://<Ta 服务>/api/hooks/ta-cron/<密钥>`(任务详情里复制,`/schedule show` 和工具的 show 也会给出),在这台电脑上向它发 POST 就运行,发送的内容(最多 256 KB,附给运行的最多 4000 字)附在提示词后面。适合 git hooks、本机 CI、脚本。这个地址不需要 Ta 服务的令牌,拿到它的人都能触发;改成别的规则后地址作废。
35
36
 
36
- 时间都按 Ta 服务所在机器的本地时间。命令末尾可以带 `--name`、`--notify always|error|never`、`--model <provider>/<model>`、`--thinking <级别>`、`--cwd <目录>`、`--timeout <时长>`。
37
+ 时间都按 Ta 服务所在机器的本地时间。命令末尾可以带 `--name`、`--notify always|error|never`、`--model <provider>/<model>`、`--thinking <级别>`、`--cwd <目录>`、`--timeout <时长>`、`--jitter <时长>`。
37
38
 
38
39
  ## 给 Agent 和脚本
39
40
 
@@ -50,6 +50,22 @@ var TaHostUtil;
50
50
  }
51
51
  TaHostUtil2.role = role;
52
52
  })(TaHostUtil || (TaHostUtil = {}));
53
+ var TA_DOUBLE_LOOK = {
54
+ name: "@celljs/ta-web",
55
+ key: "assistant.species",
56
+ given: ["trex", "triceratops", "stegosaurus", "brachiosaurus", "velociraptor", "ankylosaurus", "pteranodon", "parasaurolophus"]
57
+ };
58
+ var TaDoubleLookUtil;
59
+ (function(TaDoubleLookUtil2) {
60
+ function given(id) {
61
+ let hash = 2166136261;
62
+ for (let i = 0;i < id.length; i++) {
63
+ hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
64
+ }
65
+ return TA_DOUBLE_LOOK.given[(hash >>> 0) % TA_DOUBLE_LOOK.given.length];
66
+ }
67
+ TaDoubleLookUtil2.given = given;
68
+ })(TaDoubleLookUtil || (TaDoubleLookUtil = {}));
53
69
  var TA_KEEP_MARK = "[ta:keep]";
54
70
  var TA_ASK_ENTRY = "ta-ask";
55
71
  var TaAskUtil;
@@ -119,6 +135,8 @@ var Limits;
119
135
  Limits.WRAP_UP_MS = 10 * 60000;
120
136
  Limits.RUN_TIMEOUT_MIN_MS = 5 * 60000;
121
137
  Limits.RUN_TIMEOUT_MAX_MS = 4 * 60 * 60000;
138
+ Limits.JITTER_MIN_MS = 60000;
139
+ Limits.JITTER_MAX_MS = 12 * 60 * 60000;
122
140
  Limits.GRACE_MS = 5 * 60000;
123
141
  Limits.RESUME_WAIT_MS = 2 * 60000;
124
142
  Limits.RAN_SAVE_MS = 60000;
@@ -808,7 +826,7 @@ class Words {
808
826
  }
809
827
 
810
828
  // web-src/commands.ts
811
- var FLAG_NAMES = ["name", "notify", "model", "thinking", "cwd", "timeout"];
829
+ var FLAG_NAMES = ["name", "notify", "model", "thinking", "cwd", "timeout", "jitter"];
812
830
  var TRAILING_FLAG = new RegExp(`(?:^|\\s)--(${FLAG_NAMES.join("|")})(?:=|\\s+)("[^"]*"|'[^']*'|\\S*)\\s*$`);
813
831
  var ACTIONS = ["add", "list", "show", "runs", "run", "enable", "disable", "set", "remove", "clear", "help"];
814
832
  var HELP = `Scheduled tasks: each run is a conversation of its own in the Ta service, which runs them while it runs.
@@ -827,7 +845,8 @@ var HELP = `Scheduled tasks: each run is a conversation of its own in the Ta ser
827
845
 
828
846
  A task is its id, the start of it, or its name. Flags at the end of a prompt:
829
847
  --name <name> --notify always|error|never --model <provider/model> --thinking <level> --cwd <directory>
830
- --timeout <duration> how long a run may take before it is stopped, 5m to 4h; default 30m`;
848
+ --timeout <duration> how long a run may take before it is stopped, 5m to 4h; default 30m
849
+ --jitter <duration> start each run at random up to this much later than its time, 1m to 12h; default on time`;
831
850
  var CommandParser;
832
851
  ((CommandParser) => {
833
852
  function splitFlags(text) {
@@ -905,8 +924,11 @@ var CommandParser;
905
924
  if (flags.timeout !== undefined) {
906
925
  patch2.timeout = value(flags.timeout);
907
926
  }
927
+ if (flags.jitter !== undefined) {
928
+ patch2.jitter = value(flags.jitter);
929
+ }
908
930
  if (Object.keys(patch2).length === 0) {
909
- throw new Error("Say what changes: --name, --notify, --model, --thinking, --cwd or --timeout.");
931
+ throw new Error("Say what changes: --name, --notify, --model, --thinking, --cwd, --timeout or --jitter.");
910
932
  }
911
933
  return { ref: rest, patch: patch2 };
912
934
  }
@@ -933,7 +955,8 @@ var CommandParser;
933
955
  ...flags.model ? { model: flags.model } : {},
934
956
  ...flags.thinking ? { thinking: flags.thinking } : {},
935
957
  ...flags.notify ? { notify: flags.notify } : {},
936
- ...flags.timeout ? { timeout: flags.timeout } : {}
958
+ ...flags.timeout ? { timeout: flags.timeout } : {},
959
+ ...flags.jitter ? { jitter: flags.jitter } : {}
937
960
  };
938
961
  }
939
962
  function unquote(value) {
@@ -965,7 +988,8 @@ var CronText;
965
988
  const state = !task2.enabled ? "off" : task2.lastStatus === "running" ? "running" : task2.nextRunAt ? `next ${ScheduleUtil.clock(new Date(task2.nextRunAt), now)}` : ScheduleUtil.isEvent(task2.schedule) ? "waiting for its event" : "done";
966
989
  const last = task2.lastStatus && task2.lastStatus !== "running" ? `, last ${task2.lastStatus}` : "";
967
990
  const timeout = task2.timeout ? `, stops after ${task2.timeout}` : "";
968
- return `${task2.id} ${task2.name} (when: ${When.format(task2.schedule)}; ${state}${last}${timeout}) in ${task2.cwd}`;
991
+ const jitter = task2.jitter ? `, starts up to ${task2.jitter} late at random` : "";
992
+ return `${task2.id} ${task2.name} (when: ${When.format(task2.schedule)}; ${state}${last}${timeout}${jitter}) in ${task2.cwd}`;
969
993
  }
970
994
  CronText.task = task;
971
995
  function nextTimes(task2, now = new Date) {
@@ -1068,7 +1092,7 @@ var CronTool;
1068
1092
  CronTool.DEFINITION = {
1069
1093
  name: CronTool.NAME,
1070
1094
  label: "Schedule task",
1071
- description: `Schedules a prompt for Ta to run later, once or again and again (reminders, checks, reports), and manages those tasks. Each run is a new conversation of its own in the Ta service, in the task's directory, with no user watching; its last answer is the summary the user sees. Actions: add (prompt and when; name, cwd, model, thinking, notify, timeout optional; a name already used in the directory is refused, so change that task with update), update (id and the fields to change; "" clears model, thinking, notify or timeout), preview (when: checks it and gives its next times, making nothing), list, show (with its last runs), enable, disable, delete, run (now, by hand), runs, clear (the tasks of this directory). Deleting and clearing ask the user first. Times are the local time of the Ta service.`,
1095
+ description: `Schedules a prompt for Ta to run later, once or again and again (reminders, checks, reports), and manages those tasks. Each run is a new conversation of its own in the Ta service, in the task's directory, with no user watching; its last answer is the summary the user sees. Actions: add (prompt and when; name, cwd, model, thinking, notify, timeout, jitter optional; a name already used in the directory is refused, so change that task with update), update (id and the fields to change; "" clears model, thinking, notify, timeout or jitter), preview (when: checks it and gives its next times, making nothing), list, show (with its last runs), enable, disable, delete, run (now, by hand), runs, clear (the tasks of this directory). Deleting and clearing ask the user first. Times are the local time of the Ta service.`,
1072
1096
  parameters: {
1073
1097
  type: "object",
1074
1098
  properties: {
@@ -1087,6 +1111,10 @@ var CronTool;
1087
1111
  description: "When the pages of Ta tell the user a run ended; default always for once, error for repeating."
1088
1112
  },
1089
1113
  timeout: { type: "string", description: "How long a run may take before it is stopped, as 90m or 2h (5m to 4h); default 30m." },
1114
+ jitter: {
1115
+ type: "string",
1116
+ description: "At most how much later than its time each run starts, at random, as 15m or 1h (1m to 12h): for work a person would do at about that time (a daily check-in), and to spread tasks of the same time. Default: on time."
1117
+ },
1090
1118
  enabled: { type: "boolean" },
1091
1119
  limit: { type: "number", description: "How many runs to list; default 10." }
1092
1120
  },
@@ -1108,13 +1136,14 @@ var CronTool;
1108
1136
  thinking: optional(params.thinking),
1109
1137
  notify: optional(params.notify),
1110
1138
  timeout: optional(params.timeout),
1139
+ jitter: optional(params.jitter),
1111
1140
  enabled: params.enabled === false ? false : undefined
1112
1141
  });
1113
1142
  return `Scheduled: ${CronText.task(task)}${CronText.nextTimes(task)}`;
1114
1143
  }
1115
1144
  case "update": {
1116
1145
  const patch = {};
1117
- for (const key of ["name", "prompt", "when", "cwd", "model", "thinking", "notify", "timeout"]) {
1146
+ for (const key of ["name", "prompt", "when", "cwd", "model", "thinking", "notify", "timeout", "jitter"]) {
1118
1147
  if (typeof params[key] === "string") {
1119
1148
  patch[key] = params[key];
1120
1149
  }
package/host/index.mjs CHANGED
@@ -28,6 +28,8 @@ var Limits;
28
28
  Limits.WRAP_UP_MS = 10 * 60000;
29
29
  Limits.RUN_TIMEOUT_MIN_MS = 5 * 60000;
30
30
  Limits.RUN_TIMEOUT_MAX_MS = 4 * 60 * 60000;
31
+ Limits.JITTER_MIN_MS = 60000;
32
+ Limits.JITTER_MAX_MS = 12 * 60 * 60000;
31
33
  Limits.GRACE_MS = 5 * 60000;
32
34
  Limits.RESUME_WAIT_MS = 2 * 60000;
33
35
  Limits.RAN_SAVE_MS = 60000;
@@ -1073,7 +1075,7 @@ var TaskUtil;
1073
1075
  const { hookSecret: _gone, ...rest } = task;
1074
1076
  return rest;
1075
1077
  }
1076
- function create(input, cwd, now) {
1078
+ function create(input, cwd, now, random = Math.random) {
1077
1079
  const prompt = checkPrompt(input?.prompt);
1078
1080
  const schedule = ruleOf(input, now);
1079
1081
  if (!schedule) {
@@ -1093,10 +1095,11 @@ var TaskUtil;
1093
1095
  updatedAt: at
1094
1096
  };
1095
1097
  setOptional(task, input);
1096
- return arm(withSecret(task), now);
1098
+ fitJitter(task, input);
1099
+ return arm(withSecret(task), now, random);
1097
1100
  }
1098
1101
  TaskUtil.create = create;
1099
- function patch(task, patch2, now) {
1102
+ function patch(task, patch2, now, random = Math.random) {
1100
1103
  const next = { ...task, updatedAt: now.toISOString() };
1101
1104
  if (patch2.prompt !== undefined) {
1102
1105
  next.prompt = checkPrompt(patch2.prompt);
@@ -1115,9 +1118,10 @@ var TaskUtil;
1115
1118
  if (schedule) {
1116
1119
  next.schedule = schedule;
1117
1120
  }
1118
- const rearm = schedule !== undefined || next.enabled && !task.enabled;
1121
+ fitJitter(next, patch2);
1122
+ const rearm = schedule !== undefined || patch2.jitter !== undefined || next.enabled && !task.enabled;
1119
1123
  const secured = withSecret(next);
1120
- return rearm ? arm(secured, now) : secured;
1124
+ return rearm ? arm(secured, now, random) : secured;
1121
1125
  }
1122
1126
  TaskUtil.patch = patch;
1123
1127
  function unique(tasks, task, named) {
@@ -1134,7 +1138,7 @@ var TaskUtil;
1134
1138
  return input?.schedule === undefined ? undefined : ScheduleUtil.check(input.schedule);
1135
1139
  }
1136
1140
  TaskUtil.ruleOf = ruleOf;
1137
- function arm(task, now) {
1141
+ function arm(task, now, random = Math.random) {
1138
1142
  if (!task.enabled) {
1139
1143
  return task;
1140
1144
  }
@@ -1142,13 +1146,23 @@ var TaskUtil;
1142
1146
  const { nextRunAt: _none, ...rest } = task;
1143
1147
  return rest;
1144
1148
  }
1145
- const next = ScheduleUtil.next(task.schedule, now);
1149
+ const next = nextRun(task, now, random);
1146
1150
  if (!next) {
1147
1151
  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.`);
1148
1152
  }
1149
1153
  return { ...task, nextRunAt: next.toISOString() };
1150
1154
  }
1151
1155
  TaskUtil.arm = arm;
1156
+ function nextRun(task, now, random = Math.random) {
1157
+ const next = ScheduleUtil.next(task.schedule, now);
1158
+ const jitter = jitterMs(task);
1159
+ return next && jitter ? new Date(next.getTime() + Math.floor(Math.min(Math.max(random(), 0), 1) * jitter)) : next;
1160
+ }
1161
+ TaskUtil.nextRun = nextRun;
1162
+ function jitterMs(task) {
1163
+ return task.jitter && Duration.parse(task.jitter) || 0;
1164
+ }
1165
+ TaskUtil.jitterMs = jitterMs;
1152
1166
  function find(tasks, ref) {
1153
1167
  const text = typeof ref === "string" ? ref.trim() : "";
1154
1168
  const found = tasks.find((task) => task.id === text) ?? tasks.find((task) => task.name === text) ?? (text.length >= PREFIX_MIN ? only(tasks.filter((task) => task.id.startsWith(text))) : undefined);
@@ -1185,7 +1199,10 @@ var TaskUtil;
1185
1199
  if (input.timeout !== undefined) {
1186
1200
  task.timeout = checkTimeout(input.timeout);
1187
1201
  }
1188
- for (const key of ["model", "thinking", "notify", "timeout"]) {
1202
+ if (input.jitter !== undefined) {
1203
+ task.jitter = checkJitter(input.jitter);
1204
+ }
1205
+ for (const key of ["model", "thinking", "notify", "timeout", "jitter"]) {
1189
1206
  if (task[key] === undefined) {
1190
1207
  delete task[key];
1191
1208
  }
@@ -1244,6 +1261,25 @@ var TaskUtil;
1244
1261
  }
1245
1262
  return Duration.format(ms);
1246
1263
  }
1264
+ function checkJitter(value) {
1265
+ const text = typeof value === "string" ? value.trim() : "";
1266
+ if (!text) {
1267
+ return;
1268
+ }
1269
+ const ms = Duration.parse(text);
1270
+ if (ms === undefined || ms < Limits.JITTER_MIN_MS || ms > Limits.JITTER_MAX_MS) {
1271
+ throw new Error(`A jitter is a duration from 1m to 12h, as 15m or 1h; not ${JSON.stringify(text)}.`);
1272
+ }
1273
+ return Duration.format(ms);
1274
+ }
1275
+ function fitJitter(task, input) {
1276
+ if (task.jitter && ScheduleUtil.isEvent(task.schedule)) {
1277
+ if (input.jitter) {
1278
+ throw new Error("A jitter is for a task that runs at a time; a task run by files or its webhook starts when they come.");
1279
+ }
1280
+ delete task.jitter;
1281
+ }
1282
+ }
1247
1283
  function checkNotify(value) {
1248
1284
  if (value === "" || value === null) {
1249
1285
  return;
@@ -1377,6 +1413,7 @@ class CronScheduler {
1377
1413
  parallel: Limits.PARALLEL_RUNS,
1378
1414
  resumeWaitMs: Limits.RESUME_WAIT_MS,
1379
1415
  quietMs: Limits.WATCH_QUIET_MS,
1416
+ random: Math.random,
1380
1417
  ...options
1381
1418
  };
1382
1419
  this.watchers = new TaskWatchers(this.options.watch, this.options.quietMs, (id, event) => {
@@ -1425,14 +1462,14 @@ class CronScheduler {
1425
1462
  }
1426
1463
  async add(input) {
1427
1464
  const cwd = (await this.host.getServerInfo()).cwd;
1428
- const task = TaskUtil.create(input, cwd, this.options.now());
1465
+ const task = TaskUtil.create(input, cwd, this.options.now(), this.options.random);
1429
1466
  TaskUtil.unique(this.tasks, task, !!input.name?.trim());
1430
1467
  await this.save([...this.tasks, task]);
1431
1468
  return { ...task };
1432
1469
  }
1433
1470
  async update(ref, patch) {
1434
1471
  const task = TaskUtil.find(this.tasks, ref);
1435
- const next = TaskUtil.patch(task, patch ?? {}, this.options.now());
1472
+ const next = TaskUtil.patch(task, patch ?? {}, this.options.now(), this.options.random);
1436
1473
  await this.replace(next);
1437
1474
  return { ...next };
1438
1475
  }
@@ -1539,7 +1576,7 @@ ${event}` : event));
1539
1576
  const { nextRunAt: _done, ...rest } = task;
1540
1577
  return { ...rest, enabled: false };
1541
1578
  }
1542
- const next = ScheduleUtil.next(task.schedule, now);
1579
+ const next = TaskUtil.nextRun(task, now, this.options.random);
1543
1580
  return { ...task, nextRunAt: next?.toISOString() };
1544
1581
  }
1545
1582
  async begin(task, trigger, now, event) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@celljs/ta-cron",
3
- "version": "4.18.0",
3
+ "version": "4.20.0",
4
4
  "description": "A pi package for Ta: prompts that run on a schedule, once, every so often or by a cron expression, each run in a conversation of its own in the Ta service",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -27,8 +27,8 @@
27
27
  "watch": "tsc -b -w --preserveWatchOutput"
28
28
  },
29
29
  "devDependencies": {
30
- "@celljs/ta-protocol": "4.18.0",
31
- "@celljs/ta-web": "4.18.0",
30
+ "@celljs/ta-protocol": "4.20.0",
31
+ "@celljs/ta-web": "4.20.0",
32
32
  "@types/react": "^19.3.0"
33
33
  },
34
34
  "publishConfig": {
package/web/index.js CHANGED
@@ -24,6 +24,8 @@ var Limits;
24
24
  Limits.WRAP_UP_MS = 10 * 60000;
25
25
  Limits.RUN_TIMEOUT_MIN_MS = 5 * 60000;
26
26
  Limits.RUN_TIMEOUT_MAX_MS = 4 * 60 * 60000;
27
+ Limits.JITTER_MIN_MS = 60000;
28
+ Limits.JITTER_MAX_MS = 12 * 60 * 60000;
27
29
  Limits.GRACE_MS = 5 * 60000;
28
30
  Limits.RESUME_WAIT_MS = 2 * 60000;
29
31
  Limits.RAN_SAVE_MS = 60000;
@@ -196,6 +198,10 @@ var EN = {
196
198
  timeoutLabel: "A run takes at most",
197
199
  timeoutDefault: "Default (30 minutes)",
198
200
  timeoutIs: "up to {time}",
201
+ jitterLabel: "Random delay",
202
+ jitterNone: "None, on time",
203
+ jitterUpTo: "up to {time}",
204
+ factJitter: "Random delay",
199
205
  pickDays: "Pick a day at least",
200
206
  toolAdd: "Schedule",
201
207
  toolUpdate: "Change scheduled task",
@@ -336,6 +342,10 @@ var ZH = {
336
342
  timeoutLabel: "每次最长运行",
337
343
  timeoutDefault: "默认(30 分钟)",
338
344
  timeoutIs: "最长 {time}",
345
+ jitterLabel: "随机延后",
346
+ jitterNone: "不延后,准时运行",
347
+ jitterUpTo: "最多 {time}",
348
+ factJitter: "随机延后",
339
349
  pickDays: "至少选一天",
340
350
  toolAdd: "新建定时任务",
341
351
  toolUpdate: "修改定时任务",
@@ -476,6 +486,10 @@ var ZH_TW = {
476
486
  timeoutLabel: "每次最長執行",
477
487
  timeoutDefault: "預設(30 分鐘)",
478
488
  timeoutIs: "最長 {time}",
489
+ jitterLabel: "隨機延後",
490
+ jitterNone: "不延後,準時執行",
491
+ jitterUpTo: "最多 {time}",
492
+ factJitter: "隨機延後",
479
493
  pickDays: "至少選一天",
480
494
  toolAdd: "新建定時任務",
481
495
  toolUpdate: "修改定時任務",
@@ -616,6 +630,10 @@ var JA = {
616
630
  timeoutLabel: "1 回の最長実行時間",
617
631
  timeoutDefault: "デフォルト(30 分)",
618
632
  timeoutIs: "最長 {time}",
633
+ jitterLabel: "ランダムな遅延",
634
+ jitterNone: "なし(定刻に実行)",
635
+ jitterUpTo: "最大 {time}",
636
+ factJitter: "ランダムな遅延",
619
637
  pickDays: "1 日以上選んでください",
620
638
  toolAdd: "スケジュール",
621
639
  toolUpdate: "スケジュールされたタスクを変更",
@@ -1421,7 +1439,7 @@ var TaskChange;
1421
1439
  `The user wants the scheduled task "${task.name}" changed as they say below. Change it with schedule_task (action "update", id ${task.id}), only the fields their words touch; a new prompt stays complete in itself, since a run does not see this conversation. Do not run the task unless they ask. When their words leave the change unclear, ask before changing it. Then say in a line or two what changed and when it runs next. Without that tool, give the user the new values to put in the Edit dialog of the task.`,
1422
1440
  "",
1423
1441
  `Task: ${task.id}, ${ScheduleUtil.describe(task.schedule, "en-US")} (schedule ${JSON.stringify(task.schedule)}), in ${task.cwd}, ${task.enabled ? "on" : "off"}, ran ${task.runCount} times (${task.failCount} failed).`,
1424
- `Settings: model ${task.model || "default"}, thinking ${task.thinking || "default"}, notify ${task.notify || "default"}, timeout ${task.timeout || "default 30m"}.`,
1442
+ `Settings: model ${task.model || "default"}, thinking ${task.thinking || "default"}, notify ${task.notify || "default"}, timeout ${task.timeout || "default 30m"}, jitter ${task.jitter || "none"}.`,
1425
1443
  "Its prompt:",
1426
1444
  TaskExtension.fence(TaskExtension.clip(task.prompt, PROMPT_MAX2))
1427
1445
  ];
@@ -1962,7 +1980,7 @@ class Words {
1962
1980
  }
1963
1981
 
1964
1982
  // web-src/commands.ts
1965
- var FLAG_NAMES = ["name", "notify", "model", "thinking", "cwd", "timeout"];
1983
+ var FLAG_NAMES = ["name", "notify", "model", "thinking", "cwd", "timeout", "jitter"];
1966
1984
  var TRAILING_FLAG = new RegExp(`(?:^|\\s)--(${FLAG_NAMES.join("|")})(?:=|\\s+)("[^"]*"|'[^']*'|\\S*)\\s*$`);
1967
1985
  var ACTIONS = ["add", "list", "show", "runs", "run", "enable", "disable", "set", "remove", "clear", "help"];
1968
1986
  var HELP = `Scheduled tasks: each run is a conversation of its own in the Ta service, which runs them while it runs.
@@ -1981,7 +1999,8 @@ var HELP = `Scheduled tasks: each run is a conversation of its own in the Ta ser
1981
1999
 
1982
2000
  A task is its id, the start of it, or its name. Flags at the end of a prompt:
1983
2001
  --name <name> --notify always|error|never --model <provider/model> --thinking <level> --cwd <directory>
1984
- --timeout <duration> how long a run may take before it is stopped, 5m to 4h; default 30m`;
2002
+ --timeout <duration> how long a run may take before it is stopped, 5m to 4h; default 30m
2003
+ --jitter <duration> start each run at random up to this much later than its time, 1m to 12h; default on time`;
1985
2004
  var CommandParser;
1986
2005
  ((CommandParser) => {
1987
2006
  function splitFlags(text) {
@@ -2059,8 +2078,11 @@ var CommandParser;
2059
2078
  if (flags.timeout !== undefined) {
2060
2079
  patch2.timeout = value(flags.timeout);
2061
2080
  }
2081
+ if (flags.jitter !== undefined) {
2082
+ patch2.jitter = value(flags.jitter);
2083
+ }
2062
2084
  if (Object.keys(patch2).length === 0) {
2063
- throw new Error("Say what changes: --name, --notify, --model, --thinking, --cwd or --timeout.");
2085
+ throw new Error("Say what changes: --name, --notify, --model, --thinking, --cwd, --timeout or --jitter.");
2064
2086
  }
2065
2087
  return { ref: rest, patch: patch2 };
2066
2088
  }
@@ -2087,7 +2109,8 @@ var CommandParser;
2087
2109
  ...flags.model ? { model: flags.model } : {},
2088
2110
  ...flags.thinking ? { thinking: flags.thinking } : {},
2089
2111
  ...flags.notify ? { notify: flags.notify } : {},
2090
- ...flags.timeout ? { timeout: flags.timeout } : {}
2112
+ ...flags.timeout ? { timeout: flags.timeout } : {},
2113
+ ...flags.jitter ? { jitter: flags.jitter } : {}
2091
2114
  };
2092
2115
  }
2093
2116
  function unquote(value) {
@@ -2119,7 +2142,8 @@ var CronText;
2119
2142
  const state = !task2.enabled ? "off" : task2.lastStatus === "running" ? "running" : task2.nextRunAt ? `next ${ScheduleUtil.clock(new Date(task2.nextRunAt), now)}` : ScheduleUtil.isEvent(task2.schedule) ? "waiting for its event" : "done";
2120
2143
  const last = task2.lastStatus && task2.lastStatus !== "running" ? `, last ${task2.lastStatus}` : "";
2121
2144
  const timeout = task2.timeout ? `, stops after ${task2.timeout}` : "";
2122
- return `${task2.id} ${task2.name} (when: ${When.format(task2.schedule)}; ${state}${last}${timeout}) in ${task2.cwd}`;
2145
+ const jitter = task2.jitter ? `, starts up to ${task2.jitter} late at random` : "";
2146
+ return `${task2.id} ${task2.name} (when: ${When.format(task2.schedule)}; ${state}${last}${timeout}${jitter}) in ${task2.cwd}`;
2123
2147
  }
2124
2148
  CronText.task = task;
2125
2149
  function nextTimes(task2, now = new Date) {
@@ -2422,6 +2446,9 @@ var STYLE = `
2422
2446
  .tcr-time-row { align-items: center; justify-content: space-between; }
2423
2447
  .tcr-time { width: 140px; flex: none; }
2424
2448
  .tcr-time-row .tcr-link { align-self: center; }
2449
+ .tcr-jitter { align-items: center; }
2450
+ .tcr-jitter-label { flex: none; color: var(--ta-muted); font-size: calc(12.5px * var(--ta-font-scale)); }
2451
+ .tcr-jitter .tcr-input { width: auto; flex: none; min-width: 140px; }
2425
2452
  .tcr-more-summary { margin-left: 6px; color: var(--ta-muted); }
2426
2453
  .tcr-hook { display: flex; align-items: center; gap: 6px; padding: 8px 6px 8px 12px; border-radius: 10px; background: var(--ta-raised); min-width: 0; }
2427
2454
  .tcr-hook code { flex: 1; min-width: 0; overflow-x: auto; white-space: nowrap; scrollbar-width: none; font-size: calc(12px * var(--ta-font-scale)); color: var(--ta-text); }
@@ -2560,7 +2587,8 @@ var FormUtil;
2560
2587
  notify: "",
2561
2588
  model: "",
2562
2589
  thinking: "",
2563
- timeout: ""
2590
+ timeout: "",
2591
+ jitter: ""
2564
2592
  };
2565
2593
  }
2566
2594
  FormUtil.empty = empty;
@@ -2573,7 +2601,8 @@ var FormUtil;
2573
2601
  notify: task.notify ?? "",
2574
2602
  model: task.model ?? "",
2575
2603
  thinking: task.thinking ?? "",
2576
- timeout: task.timeout ?? ""
2604
+ timeout: task.timeout ?? "",
2605
+ jitter: task.jitter ?? ""
2577
2606
  };
2578
2607
  return { ...form, ...ruleOf(task.schedule) };
2579
2608
  }
@@ -2641,7 +2670,8 @@ var FormUtil;
2641
2670
  model: form.model || undefined,
2642
2671
  thinking: form.thinking || undefined,
2643
2672
  notify: form.notify || undefined,
2644
- timeout: form.timeout || undefined
2673
+ timeout: form.timeout || undefined,
2674
+ jitter: form.mode !== "event" && form.jitter || undefined
2645
2675
  };
2646
2676
  }
2647
2677
  FormUtil.input = input;
@@ -2660,6 +2690,7 @@ var NOTIFY = [
2660
2690
  ["never", "notifyNever"]
2661
2691
  ];
2662
2692
  var TIMEOUTS = ["15m", "1h", "2h", "4h"];
2693
+ var JITTERS = ["5m", "10m", "15m", "30m", "1h", "2h"];
2663
2694
  var WEEK = [1, 2, 3, 4, 5, 6, 0];
2664
2695
  var DAY_NAMES2 = new Map;
2665
2696
  function weekdayNames() {
@@ -2789,6 +2820,31 @@ function moreSummary(form) {
2789
2820
  form.notify && t(NOTIFY.find(([level]) => level === form.notify)?.[1] ?? "notifyDefault")
2790
2821
  ].filter(Boolean).join(" · ");
2791
2822
  }
2823
+ function JitterField({ form, set }) {
2824
+ const jitters = form.jitter && !JITTERS.includes(form.jitter) ? [...JITTERS, form.jitter] : JITTERS;
2825
+ return /* @__PURE__ */ React.createElement("label", {
2826
+ className: "tcr-row tcr-jitter"
2827
+ }, /* @__PURE__ */ React.createElement("span", {
2828
+ className: "tcr-jitter-label"
2829
+ }, t("jitterLabel")), /* @__PURE__ */ React.createElement("select", {
2830
+ className: "tcr-input",
2831
+ name: "jitter",
2832
+ value: form.jitter,
2833
+ onChange: (event) => set({ jitter: event.target.value })
2834
+ }, /* @__PURE__ */ React.createElement("option", {
2835
+ value: ""
2836
+ }, t("jitterNone")), jitters.map((jitter) => /* @__PURE__ */ React.createElement("option", {
2837
+ key: jitter,
2838
+ value: jitter
2839
+ }, t("jitterUpTo", { time: length(jitter) })))));
2840
+ }
2841
+ function timeWindow(time, jitter, now) {
2842
+ if (!jitter) {
2843
+ return ScheduleUtil.clock(time, now);
2844
+ }
2845
+ const end = new Date(time.getTime() + jitter);
2846
+ return `${ScheduleUtil.clock(time, now)}–${String(end.getHours()).padStart(2, "0")}:${String(end.getMinutes()).padStart(2, "0")}`;
2847
+ }
2792
2848
  function When2({ form, set }) {
2793
2849
  const preview = usePreview(form);
2794
2850
  let rule = null;
@@ -2866,6 +2922,7 @@ function When2({ form, set }) {
2866
2922
  const Clock = icon(preview.event ? "Zap" : "Clock");
2867
2923
  const bad = !preview.next && !preview.event;
2868
2924
  const now = new Date;
2925
+ const jitter = form.mode === "event" ? 0 : Duration.parse(form.jitter) ?? 0;
2869
2926
  return /* @__PURE__ */ React.createElement("div", {
2870
2927
  className: "tcr-field"
2871
2928
  }, /* @__PURE__ */ React.createElement("div", {
@@ -2874,12 +2931,15 @@ function When2({ form, set }) {
2874
2931
  value: kind,
2875
2932
  options: kinds,
2876
2933
  onChange: pick
2877
- }), rule, /* @__PURE__ */ React.createElement("div", {
2934
+ }), rule, form.mode !== "event" && /* @__PURE__ */ React.createElement(JitterField, {
2935
+ form,
2936
+ set
2937
+ }), /* @__PURE__ */ React.createElement("div", {
2878
2938
  className: `tcr-preview${bad ? " tcr-bad" : ""}`,
2879
2939
  role: "status"
2880
2940
  }, /* @__PURE__ */ React.createElement(Clock, {
2881
2941
  size: 13
2882
- }), preview.event ? t(form.event === "webhook" ? "webhookHint" : "watchHint") : preview.next ? t("preview", { time: preview.next.map((time) => ScheduleUtil.clock(time, now)).join(" · ") }) : preview.error || t(form.mode === "repeat" && form.repeat === "days" && form.days.length === 0 ? "pickDays" : "noNext")));
2942
+ }), preview.event ? t(form.event === "webhook" ? "webhookHint" : "watchHint") : preview.next ? t("preview", { time: preview.next.map((time) => timeWindow(time, jitter, now)).join(" · ") }) : preview.error || t(form.mode === "repeat" && form.repeat === "days" && form.days.length === 0 ? "pickDays" : "noNext")));
2883
2943
  }
2884
2944
  function TaskEditor({ client, editing, onClose }) {
2885
2945
  const Dialog = pi.ui.Dialog;
@@ -2920,7 +2980,8 @@ function TaskEditor({ client, editing, onClose }) {
2920
2980
  model: form.model,
2921
2981
  thinking: form.thinking,
2922
2982
  notify: form.notify,
2923
- timeout: form.timeout
2983
+ timeout: form.timeout,
2984
+ jitter: form.mode === "event" ? "" : form.jitter
2924
2985
  });
2925
2986
  } else {
2926
2987
  await client.add(input);
@@ -3214,7 +3275,7 @@ var TaskUtil;
3214
3275
  const { hookSecret: _gone, ...rest } = task;
3215
3276
  return rest;
3216
3277
  }
3217
- function create(input, cwd, now) {
3278
+ function create(input, cwd, now, random = Math.random) {
3218
3279
  const prompt = checkPrompt(input?.prompt);
3219
3280
  const schedule = ruleOf(input, now);
3220
3281
  if (!schedule) {
@@ -3234,10 +3295,11 @@ var TaskUtil;
3234
3295
  updatedAt: at
3235
3296
  };
3236
3297
  setOptional(task, input);
3237
- return arm(withSecret(task), now);
3298
+ fitJitter(task, input);
3299
+ return arm(withSecret(task), now, random);
3238
3300
  }
3239
3301
  TaskUtil.create = create;
3240
- function patch(task, patch2, now) {
3302
+ function patch(task, patch2, now, random = Math.random) {
3241
3303
  const next = { ...task, updatedAt: now.toISOString() };
3242
3304
  if (patch2.prompt !== undefined) {
3243
3305
  next.prompt = checkPrompt(patch2.prompt);
@@ -3256,9 +3318,10 @@ var TaskUtil;
3256
3318
  if (schedule) {
3257
3319
  next.schedule = schedule;
3258
3320
  }
3259
- const rearm = schedule !== undefined || next.enabled && !task.enabled;
3321
+ fitJitter(next, patch2);
3322
+ const rearm = schedule !== undefined || patch2.jitter !== undefined || next.enabled && !task.enabled;
3260
3323
  const secured = withSecret(next);
3261
- return rearm ? arm(secured, now) : secured;
3324
+ return rearm ? arm(secured, now, random) : secured;
3262
3325
  }
3263
3326
  TaskUtil.patch = patch;
3264
3327
  function unique(tasks, task, named) {
@@ -3275,7 +3338,7 @@ var TaskUtil;
3275
3338
  return input?.schedule === undefined ? undefined : ScheduleUtil.check(input.schedule);
3276
3339
  }
3277
3340
  TaskUtil.ruleOf = ruleOf;
3278
- function arm(task, now) {
3341
+ function arm(task, now, random = Math.random) {
3279
3342
  if (!task.enabled) {
3280
3343
  return task;
3281
3344
  }
@@ -3283,13 +3346,23 @@ var TaskUtil;
3283
3346
  const { nextRunAt: _none, ...rest } = task;
3284
3347
  return rest;
3285
3348
  }
3286
- const next = ScheduleUtil.next(task.schedule, now);
3349
+ const next = nextRun(task, now, random);
3287
3350
  if (!next) {
3288
3351
  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.`);
3289
3352
  }
3290
3353
  return { ...task, nextRunAt: next.toISOString() };
3291
3354
  }
3292
3355
  TaskUtil.arm = arm;
3356
+ function nextRun(task, now, random = Math.random) {
3357
+ const next = ScheduleUtil.next(task.schedule, now);
3358
+ const jitter = jitterMs(task);
3359
+ return next && jitter ? new Date(next.getTime() + Math.floor(Math.min(Math.max(random(), 0), 1) * jitter)) : next;
3360
+ }
3361
+ TaskUtil.nextRun = nextRun;
3362
+ function jitterMs(task) {
3363
+ return task.jitter && Duration.parse(task.jitter) || 0;
3364
+ }
3365
+ TaskUtil.jitterMs = jitterMs;
3293
3366
  function find(tasks, ref) {
3294
3367
  const text = typeof ref === "string" ? ref.trim() : "";
3295
3368
  const found = tasks.find((task) => task.id === text) ?? tasks.find((task) => task.name === text) ?? (text.length >= PREFIX_MIN ? only(tasks.filter((task) => task.id.startsWith(text))) : undefined);
@@ -3326,7 +3399,10 @@ var TaskUtil;
3326
3399
  if (input.timeout !== undefined) {
3327
3400
  task.timeout = checkTimeout(input.timeout);
3328
3401
  }
3329
- for (const key of ["model", "thinking", "notify", "timeout"]) {
3402
+ if (input.jitter !== undefined) {
3403
+ task.jitter = checkJitter(input.jitter);
3404
+ }
3405
+ for (const key of ["model", "thinking", "notify", "timeout", "jitter"]) {
3330
3406
  if (task[key] === undefined) {
3331
3407
  delete task[key];
3332
3408
  }
@@ -3385,6 +3461,25 @@ var TaskUtil;
3385
3461
  }
3386
3462
  return Duration.format(ms);
3387
3463
  }
3464
+ function checkJitter(value) {
3465
+ const text = typeof value === "string" ? value.trim() : "";
3466
+ if (!text) {
3467
+ return;
3468
+ }
3469
+ const ms = Duration.parse(text);
3470
+ if (ms === undefined || ms < Limits.JITTER_MIN_MS || ms > Limits.JITTER_MAX_MS) {
3471
+ throw new Error(`A jitter is a duration from 1m to 12h, as 15m or 1h; not ${JSON.stringify(text)}.`);
3472
+ }
3473
+ return Duration.format(ms);
3474
+ }
3475
+ function fitJitter(task, input) {
3476
+ if (task.jitter && ScheduleUtil.isEvent(task.schedule)) {
3477
+ if (input.jitter) {
3478
+ throw new Error("A jitter is for a task that runs at a time; a task run by files or its webhook starts when they come.");
3479
+ }
3480
+ delete task.jitter;
3481
+ }
3482
+ }
3388
3483
  function checkNotify(value) {
3389
3484
  if (value === "" || value === null) {
3390
3485
  return;
@@ -3571,6 +3666,9 @@ function Facts({ task, now }) {
3571
3666
  }
3572
3667
  facts.push(["factDir", basename(task.cwd), task.cwd]);
3573
3668
  facts.push(["factTimeout", length(task.timeout ?? "30m")]);
3669
+ if (task.jitter) {
3670
+ facts.push(["factJitter", t("jitterUpTo", { time: length(task.jitter) })]);
3671
+ }
3574
3672
  if (task.model) {
3575
3673
  facts.push(["model", task.model.split("/").pop() ?? task.model, task.model]);
3576
3674
  }