agent-yes 1.303.1 → 1.304.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.
Files changed (184) hide show
  1. package/README.md +54 -0
  2. package/default.config.yaml +5 -5
  3. package/dist/{JsonlStore-BpYZZTap.js → JsonlStore-CB_0sfdT.js} +5 -4
  4. package/dist/{SUPPORTED_CLIS-Dq9Lq9WJ.js → SUPPORTED_CLIS-C_1IiOj3.js} +2 -2
  5. package/dist/SUPPORTED_CLIS-Do3GHAY1.js +12 -0
  6. package/dist/{agentShare-suB6yPgO.js → agentShare-BvpEm-Fr.js} +10 -9
  7. package/dist/{askCli-BU3CNCLU.js → askCli-KmMf-3wA.js} +6 -6
  8. package/dist/{browser-BmxN1Ur9.js → browser-BAFPmEvN.js} +2 -2
  9. package/dist/{callback-Ctj3_Wxp.js → callback-BiSUhjw7.js} +6 -6
  10. package/dist/callback-SqLD2mMX.js +17 -0
  11. package/dist/{callbackCore-DSJWhqAe.js → callbackCore-BZ_10zyc.js} +1 -1
  12. package/dist/{callbackCore-BesbQ6-Z.js → callbackCore-Deve5pv3.js} +1 -1
  13. package/dist/{channels-j5nWuzlQ.js → channels-Y36S0ccW.js} +2 -2
  14. package/dist/cli.js +118 -13
  15. package/dist/{cmdDsh-2LP0grim.js → cmdDsh-DZ8bLsH7.js} +1 -1
  16. package/dist/cmdKill-CzSBfWmx.js +116 -0
  17. package/dist/{cmdPs-wc1j85fi.js → cmdPs-DBt23Qz0.js} +11 -10
  18. package/dist/{cwdConflictWarn-skQSMwEh.js → cwdConflictWarn-y-epQyOj.js} +21 -5
  19. package/dist/{cwdPassthroughHint-BUbWMoz0.js → cwdPassthroughHint-CzWh0hrw.js} +1 -1
  20. package/dist/{expose-Dawq1LxC.js → expose-Bhsn5yUz.js} +2 -2
  21. package/dist/forceKill-BDqxx4uQ.js +44 -0
  22. package/dist/{forkNested-CavHyWzA.js → forkNested-3heLs5XC.js} +45 -5
  23. package/dist/{globalPidIndex-CRB5KtyL.js → globalPidIndex-BsjlId-h.js} +6 -5
  24. package/dist/{globalPidIndex-BftWlg2V.js → globalPidIndex-uoz8Esqz.js} +2 -2
  25. package/dist/{hist-Cs0KFSUW.js → hist-DY16wm7g.js} +1 -1
  26. package/dist/{identity-DA7YI9km.js → identity-C0MxfwI2.js} +1 -1
  27. package/dist/{identity-Bk-aG_xl.js → identity-Ckav3-Up.js} +1 -1
  28. package/dist/index.js +7 -7
  29. package/dist/{initMsg-CcTqFtsp.js → initMsg-BEVDWYnv.js} +1 -1
  30. package/dist/{initMsg-D9KJnfgC.js → initMsg-GPU52N-j.js} +1 -1
  31. package/dist/liagent/box-BSIrRRc_.js +2320 -0
  32. package/dist/liagent/box-DloywR57.d.ts +409 -0
  33. package/dist/liagent/box.d.ts +3 -0
  34. package/dist/liagent/box.js +3 -0
  35. package/dist/liagent/cli.d.ts +1 -0
  36. package/dist/liagent/cli.js +908 -0
  37. package/dist/liagent/client.d.ts +28 -0
  38. package/dist/liagent/client.js +240 -0
  39. package/dist/liagent/echo-BvzPSI0x.js +86 -0
  40. package/dist/liagent/echo-W2RcMEny.d.ts +38 -0
  41. package/dist/liagent/hub.d.ts +405 -0
  42. package/dist/liagent/hub.js +1831 -0
  43. package/dist/liagent/index.d.ts +14 -0
  44. package/dist/liagent/index.js +10 -0
  45. package/dist/liagent/liagent.js +339 -0
  46. package/dist/liagent/mic-audio-C3Shud_F.js +754 -0
  47. package/dist/liagent/mic-audio-DMCWtEI-.d.ts +317 -0
  48. package/dist/liagent/mic-button-CtZHFBSG.js +651 -0
  49. package/dist/liagent/mic-button-Y0ioPetQ.d.ts +248 -0
  50. package/dist/liagent/mic.d.ts +3 -0
  51. package/dist/liagent/mic.js +4 -0
  52. package/dist/liagent/progress-CJs08bXb.js +473 -0
  53. package/dist/liagent/progress-CfE-meHr.d.ts +205 -0
  54. package/dist/liagent/progress.d.ts +2 -0
  55. package/dist/liagent/progress.js +3 -0
  56. package/dist/liagent/protocol.d.ts +324 -0
  57. package/dist/liagent/protocol.js +504 -0
  58. package/dist/liagent/speech-rate-DXeJjRTc.js +42 -0
  59. package/dist/liagent/state-tree-BZCmAknI.js +353 -0
  60. package/dist/liagent/tree-BrR7NwMf.js +710 -0
  61. package/dist/liagent/tree-HB9RhX_H.d.ts +295 -0
  62. package/dist/liagent/tree.d.ts +2 -0
  63. package/dist/liagent/tree.js +4 -0
  64. package/dist/liagent/ui-strings-B03le3fh.d.ts +27 -0
  65. package/dist/liagent/ui-strings-CJIwW5Gf.js +794 -0
  66. package/dist/liagent/ui.d.ts +394 -0
  67. package/dist/liagent/ui.js +5 -0
  68. package/dist/liagent/voice-D7yeS9VM.js +802 -0
  69. package/dist/liagent/voice-Qo7SCgi8.d.ts +308 -0
  70. package/dist/liagent/voice.d.ts +3 -0
  71. package/dist/liagent/voice.js +4 -0
  72. package/dist/{notifyDaemon-C7GlfJ1E.js → notifyDaemon-DkUB7GV2.js} +10 -9
  73. package/dist/{openBrowser-1cIo4dJL.js → openBrowser-CQAOIrD6.js} +1 -1
  74. package/dist/oxmgrService-DlYHmqyI.js +37 -0
  75. package/dist/oxmgrService-o9L3I6FX.js +3 -0
  76. package/dist/{parentLink-DoEWVGld.js → parentLink-BcAYcO9L.js} +2 -2
  77. package/dist/{parentLink-B58V1RVd.js → parentLink-MBUD3oY2.js} +2 -2
  78. package/dist/{parentPingLoop-C73bbmCE.js → parentPingLoop-DDO592Wh.js} +5 -5
  79. package/dist/{pidStore-433kvh9D.js → pidStore-C50VPk3E.js} +3 -3
  80. package/dist/pidStore-COkPjpW8.js +6 -0
  81. package/dist/{procStats-BvmrBrOs.js → procStats-DwTxj3rs.js} +1 -1
  82. package/dist/{remotes-MfdV9M8u.js → remotes-BqLoB5GR.js} +2 -2
  83. package/dist/{remotes-DevcBeLl.js → remotes-BsMGvAay.js} +3 -3
  84. package/dist/{roomReplyAlias-DFqg_6IU.js → roomReplyAlias-B-v76TA8.js} +3 -3
  85. package/dist/roomReplyAlias-BzWUBkQy.js +6 -0
  86. package/dist/{rustBinary-7VK7oLlW.js → rustBinary-BrJ2p8wy.js} +2 -2
  87. package/dist/{rustBinary-BV4LxMMn.js → rustBinary-vpfpWj1q.js} +2 -2
  88. package/dist/{schedule-Dp0qkNO1.js → schedule-Bzjhl6-h.js} +15 -44
  89. package/dist/schedulesCli-CLqieyQZ.js +784 -0
  90. package/dist/senderAncestry-CVHeKk1Y.js +173 -0
  91. package/dist/senderAncestry-KhAUPCQs.js +3 -0
  92. package/dist/{serve-BpOIIOVc.js → serve-XwFYE0cE.js} +67 -69
  93. package/dist/{serveRust-CbBrcUrg.js → serveRust-BfWkeL6T.js} +31 -4
  94. package/dist/{setup-DdIBk6Iv.js → setup-D4-s2VZw.js} +5 -5
  95. package/dist/{share-w5oRbvlj.js → share-CbFetL5H.js} +1 -1
  96. package/dist/{share-DrS3LYqf.js → share-_TPYAGWC.js} +1 -1
  97. package/dist/{shareCmd-DDENkBW2.js → shareCmd-DUBsVI3e.js} +10 -10
  98. package/dist/spawnGate-Dfj9V76w.js +5 -0
  99. package/dist/{spawnGate-lr3tvA6U.js → spawnGate-Dj_WaS29.js} +3 -3
  100. package/dist/{subcommands-DxgvDmZX.js → subcommands-B7YZJL8n.js} +471 -307
  101. package/dist/subcommands-BZPxFgkT.js +15 -0
  102. package/dist/{systemPathLink-SjUzgSiq.js → systemPathLink-Y3iC7bYV.js} +1 -1
  103. package/dist/{terminal-C2h7tpe0.js → terminal-13cGj3h6.js} +2 -2
  104. package/dist/terminal.js +1 -1
  105. package/dist/{todoAutomation-TTp_Qz9G.js → todoAutomation-CKlrxuZv.js} +2 -2
  106. package/dist/{todoCli-BWm5nZE0.js → todoCli-CU9vSJSJ.js} +6 -6
  107. package/dist/{todoIdentity-BvXZKWJI.js → todoIdentity-CzS1e7VL.js} +2 -2
  108. package/dist/{todoStore-C9RTz0Vs.js → todoStore-msRCEUi1.js} +2 -2
  109. package/dist/{tray-BeRSozJz.js → tray-CLktEN3G.js} +1 -1
  110. package/dist/{trayApp-QQjqhDv1.js → trayApp-5_OlvQcz.js} +2 -2
  111. package/dist/trayApp-DkAPo0m6.js +5 -0
  112. package/dist/{ts-6LF7f4fx.js → ts-njuddXQz.js} +126 -57
  113. package/dist/{versionChecker-Bc62HNf6.js → versionChecker-BJycAanp.js} +2 -2
  114. package/dist/{webrtcLink-va_gAR77.js → webrtcLink-DcvacEci.js} +1 -1
  115. package/dist/{webrtcLink-SsInrVHU.js → webrtcLink-WxS1nTIs.js} +1 -1
  116. package/dist/{webrtcRemote-BlGyNZDC.js → webrtcRemote-C3xQyf3u.js} +2 -2
  117. package/dist/{widget-Crb5zeHL.js → widget-DmRwOlco.js} +3 -3
  118. package/dist/widgets.js +1 -1
  119. package/dist/{workspaceConfig-BLWB5Wu9.js → workspaceConfig-DBgsu81B.js} +1 -1
  120. package/dist/{ws-DIbwNz8Z.js → ws-ByO6JO6m.js} +3 -3
  121. package/dist/{ws-BRhPG1Vy.js → ws-D0-Jg88z.js} +9 -8
  122. package/lab/ui/index.html +1 -1
  123. package/lab/ui/lab/posts/2026-08-11-slack-term-safe-writes.md +1 -1
  124. package/package.json +73 -8
  125. package/ts/JsonlStore.ts +10 -3
  126. package/ts/cli-idle.bun.spec.ts +1 -1
  127. package/ts/cli-idle.spec.ts +1 -1
  128. package/ts/cli.ts +35 -0
  129. package/ts/cmdKill.bun.spec.ts +155 -0
  130. package/ts/cmdKill.spec.ts +155 -0
  131. package/ts/cmdKill.ts +183 -0
  132. package/ts/composerGuard.edges.spec.ts +91 -0
  133. package/ts/composerGuard.spec.ts +53 -6
  134. package/ts/composerGuard.ts +42 -13
  135. package/ts/conptyModeFilter.spec.ts +30 -0
  136. package/ts/conptyModeFilter.ts +53 -0
  137. package/ts/copyLiagent.ts +42 -0
  138. package/ts/cwdConflictWarn.io.spec.ts +50 -0
  139. package/ts/cwdConflictWarn.spec.ts +34 -1
  140. package/ts/cwdConflictWarn.ts +43 -5
  141. package/ts/cwdGuard.spec.ts +110 -0
  142. package/ts/cwdGuard.ts +118 -0
  143. package/ts/forceKill.ts +52 -0
  144. package/ts/forkNested.bun.spec.ts +41 -0
  145. package/ts/forkNested.spec.ts +41 -0
  146. package/ts/forkNested.ts +48 -1
  147. package/ts/globalPidIndex.edges.spec.ts +125 -0
  148. package/ts/globalPidIndex.ts +6 -2
  149. package/ts/index.ts +13 -1
  150. package/ts/interruptSend.bun.spec.ts +99 -0
  151. package/ts/interruptSend.spec.ts +99 -0
  152. package/ts/interruptSend.ts +51 -0
  153. package/ts/lockRegistry.spec.ts +49 -0
  154. package/ts/lsRenderCache.spec.ts +58 -0
  155. package/ts/needsInput.edges.spec.ts +23 -0
  156. package/ts/parseCliArgs.ts +7 -0
  157. package/ts/pushGatePlan.spec.ts +147 -0
  158. package/ts/roomReplyAlias.io.spec.ts +81 -0
  159. package/ts/schedule.ts +5 -1
  160. package/ts/schedules.bun.spec.ts +397 -0
  161. package/ts/schedules.spec.ts +397 -0
  162. package/ts/schedules.ts +517 -0
  163. package/ts/schedulesCli.ts +386 -0
  164. package/ts/sendControl.bun.spec.ts +12 -0
  165. package/ts/senderAncestry.ts +1 -3
  166. package/ts/serve.ts +22 -33
  167. package/ts/serveRust.spec.ts +29 -2
  168. package/ts/serveRust.ts +27 -2
  169. package/ts/sizeNego.bun.spec.ts +9 -2
  170. package/ts/sizeNego.spec.ts +9 -2
  171. package/ts/sizeNego.ts +10 -5
  172. package/ts/subcommands.spec.ts +348 -9
  173. package/ts/subcommands.ts +513 -93
  174. package/ts/suggestAgents.spec.ts +33 -0
  175. package/ts/terminal/browser.ts +1 -1
  176. package/ts/todoParse.spec.ts +22 -1
  177. package/ts/todoParse.ts +19 -0
  178. package/dist/SUPPORTED_CLIS-ByO5twge.js +0 -12
  179. package/dist/callback-D7qfh_7p.js +0 -16
  180. package/dist/pidStore-BRlKRHXY.js +0 -6
  181. package/dist/roomReplyAlias-DuEkSSDI.js +0 -6
  182. package/dist/spawnGate-DeQBTX-o.js +0 -5
  183. package/dist/subcommands-DmiswRy4.js +0 -14
  184. package/dist/trayApp-C4TAvRvU.js +0 -5
@@ -0,0 +1,517 @@
1
+ // Shared schedule store + cross-platform scheduler core for `ay cron` and `ay schedules`.
2
+ //
3
+ // ONE store ($AY_SCHEDULES_STORE, else ~/.config/agent-yes/schedules.json) holds every
4
+ // reminder. `ay cron` adds/lists/removes entries (source "cron"); `ay schedules ls`
5
+ // lists them together with the legacy oxmgr-backed `ay schedule` jobs. A single
6
+ // per-machine daemon (`ay schedules daemon run`) sleeps until the next fire, sends due
7
+ // entries with `ay send --force`, and keeps last-run state on disk
8
+ // ($AY_SCHEDULES_STATE) so a restart neither double-fires nor storms missed runs.
9
+ // It is kept alive by oxmgr when present (the runner `ay schedule` already uses),
10
+ // else systemd --user, launchd, Windows Task Scheduler, or a detached nohup process.
11
+ //
12
+ // This file is the pure core; I/O lives in schedulesCli.ts.
13
+ import { homedir } from "os";
14
+ import path from "path";
15
+
16
+ export const DEFAULT_TZ = "Asia/Tokyo";
17
+
18
+ export interface Schedule {
19
+ /** unique id/name (cron entries: c1, c2, …) */
20
+ name: string;
21
+ /** 5-field cron */
22
+ cron: string;
23
+ tz: string;
24
+ /** lane:<name>, or an agent id / pid / keyword */
25
+ target: string;
26
+ message: string;
27
+ enabled: boolean;
28
+ /** missed fires (daemon down): skip, or fire once on restart */
29
+ missed: "skip" | "run-once";
30
+ }
31
+
32
+ export const CRON_HELP = `Usage:
33
+ ay cron "<cron>" <lane:<name>|agent> <message...> add a reminder (5-field cron, tz $AY_CRON_TZ or ${DEFAULT_TZ})
34
+ ay cron ls list reminders with next run and last result
35
+ ay cron rm <id> remove one
36
+
37
+ A target is lane:<name> (resolved with ay lanes id), a lane name tagged in a live
38
+ agent's prompt, or an agent id / pid / keyword. The message is sent with
39
+ ay send --force; {now} and {name} are substituted. Reminders are fired by the
40
+ per-machine scheduler daemon (ay schedules daemon status|install). A missed tick
41
+ (daemon down) is skipped. Each fire is logged as JSONL to
42
+ ~/.local/share/agent-yes/schedules.log ($AY_SCHEDULES_LOG).
43
+
44
+ Example:
45
+ ay cron "*/30 9-18 * * 1-5" lane:alpha "progress report please ({now})"
46
+ `;
47
+
48
+ export const SCHEDULES_HELP = `Usage: ay schedules <command> (alias: ay sched)
49
+
50
+ ay schedules ls every schedule on this machine: ay cron reminders
51
+ (source=cron) and legacy ay schedule jobs (source=schedule)
52
+ ay schedules daemon status is the scheduler daemon running, and how it is kept alive
53
+ ay schedules daemon install start it and keep it alive (oxmgr / systemd --user /
54
+ launchd / Task Scheduler / nohup)
55
+ ay schedules daemon run the daemon loop itself (foreground)
56
+
57
+ Declarative schedules.yaml, apply and missed-run policies are pending a design decision.
58
+ `;
59
+
60
+ export function logFile(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
61
+ return env.AY_SCHEDULES_LOG || path.join(home, ".local", "share", "agent-yes", "schedules.log");
62
+ }
63
+
64
+ export function validTz(tz: string): boolean {
65
+ try {
66
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
67
+ return true;
68
+ } catch {
69
+ return false;
70
+ }
71
+ }
72
+
73
+ // ---------------------------------------------------------------------------
74
+ // Cron
75
+ // ---------------------------------------------------------------------------
76
+
77
+ interface FieldSpec {
78
+ min: number;
79
+ max: number;
80
+ names?: string[];
81
+ }
82
+ const FIELDS: FieldSpec[] = [
83
+ { min: 0, max: 59 },
84
+ { min: 0, max: 23 },
85
+ { min: 1, max: 31 },
86
+ {
87
+ min: 1,
88
+ max: 12,
89
+ names: ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"],
90
+ },
91
+ { min: 0, max: 7, names: ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] },
92
+ ];
93
+ const FIELD_NAMES = ["minute", "hour", "day-of-month", "month", "day-of-week"];
94
+
95
+ export interface CronField {
96
+ /** sorted distinct values */
97
+ values: number[];
98
+ /** the field was `*` or `*\/n` with n=1 (unrestricted) */
99
+ star: boolean;
100
+ }
101
+ export interface ParsedCron {
102
+ minute: CronField;
103
+ hour: CronField;
104
+ dom: CronField;
105
+ month: CronField;
106
+ dow: CronField;
107
+ }
108
+
109
+ function parseNum(s: string, spec: FieldSpec): number {
110
+ const lower = s.toLowerCase();
111
+ const idx = spec.names?.indexOf(lower) ?? -1;
112
+ if (idx >= 0) return idx + (spec.names!.length === 12 ? 1 : 0);
113
+ if (!/^\d+$/.test(s)) throw new Error(`"${s}" is not a number`);
114
+ const n = Number(s);
115
+ if (n < spec.min || n > spec.max) throw new Error(`${n} out of range ${spec.min}-${spec.max}`);
116
+ return n;
117
+ }
118
+
119
+ function parseField(text: string, spec: FieldSpec, isDow: boolean): CronField {
120
+ const set = new Set<number>();
121
+ let star = false;
122
+ for (const part of text.split(",")) {
123
+ const [range, stepS, extra] = part.split("/");
124
+ if (extra !== undefined || range === "") throw new Error(`bad term "${part}"`);
125
+ const step = stepS === undefined ? 1 : Number(stepS);
126
+ if (!Number.isInteger(step) || step < 1 || (stepS !== undefined && !/^\d+$/.test(stepS)))
127
+ throw new Error(`bad step in "${part}"`);
128
+ let lo: number, hi: number;
129
+ if (range === "*") {
130
+ lo = spec.min;
131
+ hi = isDow ? 6 : spec.max;
132
+ if (step === 1) star = true;
133
+ } else if (range!.includes("-")) {
134
+ const [a, b] = range!.split("-");
135
+ lo = parseNum(a!, spec);
136
+ hi = parseNum(b!, spec);
137
+ if (lo > hi) throw new Error(`range ${range} goes backwards`);
138
+ } else {
139
+ lo = parseNum(range!, spec);
140
+ hi = stepS === undefined ? lo : isDow ? 6 : spec.max;
141
+ }
142
+ for (let v = lo; v <= hi; v += step) set.add(isDow && v === 7 ? 0 : v);
143
+ }
144
+ return { values: [...set].sort((a, b) => a - b), star };
145
+ }
146
+
147
+ export function parseCron(cron: string): ParsedCron {
148
+ const parts = cron.trim().split(/\s+/);
149
+ if (parts.length !== 5) throw new Error(`expected 5 fields, got ${parts.length}`);
150
+ const f = parts.map((p, i) => {
151
+ try {
152
+ return parseField(p, FIELDS[i]!, i === 4);
153
+ } catch (e) {
154
+ throw new Error(`${FIELD_NAMES[i]}: ${(e as Error).message}`);
155
+ }
156
+ });
157
+ return { minute: f[0]!, hour: f[1]!, dom: f[2]!, month: f[3]!, dow: f[4]! };
158
+ }
159
+
160
+ export function cronError(cron: string): string | null {
161
+ try {
162
+ parseCron(cron);
163
+ return null;
164
+ } catch (e) {
165
+ return (e as Error).message;
166
+ }
167
+ }
168
+
169
+ const DOW_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
170
+
171
+ interface Parts {
172
+ y: number;
173
+ mo: number;
174
+ d: number;
175
+ h: number;
176
+ mi: number;
177
+ dow: number;
178
+ }
179
+ const fmtCache = new Map<string, Intl.DateTimeFormat>();
180
+ export function tzParts(ms: number, tz: string): Parts {
181
+ let f = fmtCache.get(tz);
182
+ if (!f) {
183
+ f = new Intl.DateTimeFormat("en-US", {
184
+ timeZone: tz,
185
+ hourCycle: "h23",
186
+ year: "numeric",
187
+ month: "numeric",
188
+ day: "numeric",
189
+ hour: "numeric",
190
+ minute: "numeric",
191
+ weekday: "short",
192
+ });
193
+ fmtCache.set(tz, f);
194
+ }
195
+ const p: Record<string, string> = {};
196
+ for (const x of f.formatToParts(ms)) p[x.type] = x.value;
197
+ return {
198
+ y: Number(p.year),
199
+ mo: Number(p.month),
200
+ d: Number(p.day),
201
+ h: Number(p.hour) % 24,
202
+ mi: Number(p.minute),
203
+ dow: DOW_NAMES.indexOf(p.weekday!),
204
+ };
205
+ }
206
+
207
+ /** Next fire times (epoch ms) strictly after `from`, in `tz`. */
208
+ export function nextRuns(cron: string, tz: string, from: number, n = 1): number[] {
209
+ const c = parseCron(cron);
210
+ const has = (f: CronField, v: number) => f.star || f.values.includes(v);
211
+ const dayOk = (p: Parts) => {
212
+ if (!c.dom.star && !c.dow.star) return has(c.dom, p.d) || has(c.dow, p.dow);
213
+ return has(c.dom, p.d) && has(c.dow, p.dow);
214
+ };
215
+ const out: number[] = [];
216
+ let t = Math.floor(from / 60000) * 60000 + 60000;
217
+ const end = from + 400 * 86400000;
218
+ while (out.length < n && t < end) {
219
+ const p = tzParts(t, tz);
220
+ if (!has(c.month, p.mo) || !dayOk(p)) t += (1440 - p.h * 60 - p.mi) * 60000;
221
+ else if (!has(c.hour, p.h)) t += (60 - p.mi) * 60000;
222
+ else if (!has(c.minute, p.mi)) t += 60000;
223
+ else {
224
+ out.push(t);
225
+ t += 60000;
226
+ }
227
+ }
228
+ return out;
229
+ }
230
+
231
+ /** `2026-01-02 03:04 Asia/Tokyo` */
232
+ export function fmtTime(ms: number, tz: string): string {
233
+ const p = tzParts(ms, tz);
234
+ const z = (n: number) => String(n).padStart(2, "0");
235
+ return `${p.y}-${z(p.mo)}-${z(p.d)} ${z(p.h)}:${z(p.mi)} ${tz}`;
236
+ }
237
+
238
+ export function renderMessage(s: Schedule, now: number): string {
239
+ return s.message.replaceAll("{now}", fmtTime(now, s.tz)).replaceAll("{name}", s.name);
240
+ }
241
+
242
+ // ---------------------------------------------------------------------------
243
+ // Store: entries + run state (separate files: the CLI writes the store, the daemon the state).
244
+ // ---------------------------------------------------------------------------
245
+
246
+ export type Source = "cron";
247
+
248
+ export interface StoreEntry extends Schedule {
249
+ source: Source;
250
+ /** epoch ms the entry was added: nothing before it is due */
251
+ since: number;
252
+ }
253
+
254
+ export interface Store {
255
+ version: 1;
256
+ entries: StoreEntry[];
257
+ }
258
+
259
+ export interface RunState {
260
+ /** last time the daemon finished a tick (epoch ms) */
261
+ lastTick: number;
262
+ /** per name: last fire */
263
+ last: Record<string, { at: number; ok: boolean; code: number }>;
264
+ }
265
+
266
+ export function storeFile(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
267
+ return env.AY_SCHEDULES_STORE || path.join(home, ".config", "agent-yes", "schedules.json");
268
+ }
269
+
270
+ export function stateFile(env: NodeJS.ProcessEnv = process.env, home = homedir()): string {
271
+ return (
272
+ env.AY_SCHEDULES_STATE ||
273
+ path.join(home, ".local", "share", "agent-yes", "schedules.state.json")
274
+ );
275
+ }
276
+
277
+ export function parseStore(text: string | null): Store {
278
+ if (!text) return { version: 1, entries: [] };
279
+ const j = JSON.parse(text);
280
+ return { version: 1, entries: Array.isArray(j?.entries) ? j.entries : [] };
281
+ }
282
+
283
+ export function parseState(text: string | null): RunState {
284
+ try {
285
+ const j = text ? JSON.parse(text) : {};
286
+ return {
287
+ lastTick: Number(j.lastTick) || 0,
288
+ last: j.last && typeof j.last === "object" ? j.last : {},
289
+ };
290
+ } catch {
291
+ return { lastTick: 0, last: {} };
292
+ }
293
+ }
294
+
295
+ /** Next free cron-entry id: c1, c2, … */
296
+ export function nextCronId(store: Store): string {
297
+ let n = 1;
298
+ while (store.entries.some((e) => e.name === `c${n}`)) n++;
299
+ return `c${n}`;
300
+ }
301
+
302
+ /** Window in which a due fire still counts as on time (not missed). */
303
+ export const ON_TIME_MS = 90_000;
304
+
305
+ /**
306
+ * One scheduler tick: which entries fire now. For each enabled entry, a fire is
307
+ * due if a cron time falls in (max(lastTick, since, last run), now]. If the most
308
+ * recent due time is within ON_TIME_MS it is on time and fires; otherwise it was
309
+ * missed (daemon down / machine asleep) and fires once only when missed=run-once.
310
+ */
311
+ export function dueNow(entries: StoreEntry[], state: RunState, now: number): StoreEntry[] {
312
+ const out: StoreEntry[] = [];
313
+ for (const e of entries) {
314
+ if (!e.enabled) continue;
315
+ const from = Math.max(state.lastTick, e.since, state.last[e.name]?.at ?? 0);
316
+ const first = nextRuns(e.cron, e.tz, from, 1)[0];
317
+ if (first == null || first > now) continue;
318
+ // the latest slot at or before now (a */1 cron has two in the window)
319
+ const recent = nextRuns(e.cron, e.tz, now - ON_TIME_MS, 3)
320
+ .filter((t) => t <= now)
321
+ .at(-1);
322
+ const onTime = recent != null && recent <= now && recent > from;
323
+ if (onTime || e.missed === "run-once") out.push(e);
324
+ }
325
+ return out;
326
+ }
327
+
328
+ /**
329
+ * Longest single sleep. The daemon sleeps until the earliest next fire (no polling),
330
+ * but never longer than this, so a wall-clock jump or a suspend is noticed within a day.
331
+ */
332
+ export const MAX_SLEEP_MS = 24 * 3600e3;
333
+
334
+ /** How long to sleep from `now` until the earliest next fire of any enabled entry. */
335
+ export function wakeDelay(entries: StoreEntry[], now: number): number {
336
+ let best = Infinity;
337
+ for (const e of entries) {
338
+ if (!e.enabled) continue;
339
+ const t = nextRuns(e.cron, e.tz, now, 1)[0];
340
+ if (t != null && t < best) best = t;
341
+ }
342
+ return best === Infinity ? MAX_SLEEP_MS : Math.min(MAX_SLEEP_MS, Math.max(0, best - now + 50));
343
+ }
344
+
345
+ /**
346
+ * One wake-up, judged by the wall clock: what fires, and the new state. A clock
347
+ * that jumped backwards (lastTick in the future) resets lastTick to now, so
348
+ * nothing replays and the schedule resumes from the new time. A jump forwards
349
+ * or a suspend is a plain "slept past the slot": skip, or run-once.
350
+ */
351
+ export function tick(
352
+ entries: StoreEntry[],
353
+ state: RunState,
354
+ now: number,
355
+ ): { fire: StoreEntry[]; state: RunState; clockBack: boolean } {
356
+ const clockBack = state.lastTick > now;
357
+ const last = Object.fromEntries(
358
+ Object.entries(state.last).map(([k, v]) => [k, v.at > now ? { ...v, at: now } : v]),
359
+ );
360
+ const st: RunState = { lastTick: clockBack ? now : state.lastTick || now - 60000, last };
361
+ return { fire: dueNow(entries, st, now), state: { ...st, lastTick: now }, clockBack };
362
+ }
363
+
364
+ // ---------------------------------------------------------------------------
365
+ // Daemon autostart (one `ay schedules daemon run` per machine)
366
+ // ---------------------------------------------------------------------------
367
+
368
+ export const DAEMON_NAME = "agent-yes-schedulerd";
369
+
370
+ export function systemdDaemonUnit(argv: string[], pathEnv: string): string {
371
+ const q = (s: string) =>
372
+ /^[\w@%+=:,./-]+$/.test(s) ? s : `"${s.replace(/(["\\])/g, "\\$1").replace(/%/g, "%%")}"`;
373
+ return (
374
+ `[Unit]\nDescription=agent-yes scheduler (ay schedules / ay cron)\n\n` +
375
+ `[Service]\nExecStart=${argv.map(q).join(" ")}\nEnvironment=${q(`PATH=${pathEnv}`)}\n` +
376
+ `Restart=always\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n`
377
+ );
378
+ }
379
+
380
+ export function launchdDaemonPlist(argv: string[], pathEnv: string, logPath: string): string {
381
+ const x = (v: string) => v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
382
+ return (
383
+ `<?xml version="1.0" encoding="UTF-8"?>\n` +
384
+ `<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n` +
385
+ `<plist version="1.0">\n<dict>\n <key>Label</key><string>com.agent-yes.schedulerd</string>\n` +
386
+ ` <key>ProgramArguments</key>\n <array>\n${argv.map((a) => ` <string>${x(a)}</string>\n`).join("")} </array>\n` +
387
+ ` <key>EnvironmentVariables</key>\n <dict><key>PATH</key><string>${x(pathEnv)}</string></dict>\n` +
388
+ ` <key>RunAtLoad</key><true/>\n <key>KeepAlive</key><true/>\n` +
389
+ ` <key>StandardErrorPath</key><string>${x(logPath)}</string>\n` +
390
+ `</dict>\n</plist>\n`
391
+ );
392
+ }
393
+
394
+ /** Windows Task Scheduler: start at logon, restart is handled by the daemon's own lock. */
395
+ export function windowsTaskArgs(argv: string[]): string[] {
396
+ const q = (s: string) => (/[\s"]/.test(s) ? `"${s.replace(/"/g, '\\"')}"` : s);
397
+ return ["/Create", "/F", "/SC", "ONLOGON", "/TN", DAEMON_NAME, "/TR", argv.map(q).join(" ")];
398
+ }
399
+
400
+ export type AutostartKind = "oxmgr" | "systemd" | "launchd" | "schtasks" | "nohup";
401
+
402
+ /** Pick how to keep the daemon alive: the existing oxmgr runner first, then per-OS. */
403
+ export function pickAutostart(o: {
404
+ platform: string;
405
+ hasOxmgr: boolean;
406
+ systemdUser: boolean;
407
+ }): AutostartKind {
408
+ if (o.hasOxmgr) return "oxmgr";
409
+ if (o.platform === "darwin") return "launchd";
410
+ if (o.platform === "win32") return "schtasks";
411
+ if (o.platform === "linux" && o.systemdUser) return "systemd";
412
+ return "nohup";
413
+ }
414
+ // ---------------------------------------------------------------------------
415
+ // Targets
416
+ // ---------------------------------------------------------------------------
417
+
418
+ export type Target = { kind: "lane"; lane: string } | { kind: "agent"; ref: string };
419
+
420
+ export function parseTarget(t: string): Target {
421
+ const s = t.trim();
422
+ return s.startsWith("lane:")
423
+ ? { kind: "lane", lane: s.slice(5).trim() }
424
+ : { kind: "agent", ref: s };
425
+ }
426
+
427
+ export interface LiveRef {
428
+ pid: number;
429
+ agent_id: string;
430
+ cwd: string;
431
+ }
432
+
433
+ export type TargetResolution = { ok: true; agentId: string } | { ok: false; error: string };
434
+
435
+ /**
436
+ * Resolve a target to a live agent id. `laneId` answers `ay lanes id <name>`.
437
+ * An agent ref matches an exact agent_id or pid, else a unique agent_id prefix,
438
+ * else a unique cwd containing it (a keyword).
439
+ */
440
+ export function resolveTarget(
441
+ target: string,
442
+ live: LiveRef[],
443
+ laneId: (lane: string) => { ok: boolean; out: string },
444
+ ): TargetResolution {
445
+ const t = parseTarget(target);
446
+ if (t.kind === "lane") {
447
+ const r = laneId(t.lane);
448
+ const id = r.out.trim();
449
+ return r.ok && id
450
+ ? { ok: true, agentId: id }
451
+ : { ok: false, error: `lane "${t.lane}" has no live agent${id ? `: ${id}` : ""}` };
452
+ }
453
+ const ref = t.ref;
454
+ const exact = live.filter((a) => a.agent_id === ref || String(a.pid) === ref);
455
+ const tiers = [
456
+ exact,
457
+ live.filter((a) => a.agent_id.startsWith(ref)),
458
+ live.filter((a) => a.cwd.includes(ref)),
459
+ ];
460
+ for (const hits of tiers) {
461
+ if (hits.length === 1) return { ok: true, agentId: hits[0]!.agent_id };
462
+ if (hits.length > 1)
463
+ return {
464
+ ok: false,
465
+ error: `"${ref}" matches ${hits.length} live agents (${hits.map((a) => a.pid).join(", ")}); be more specific`,
466
+ };
467
+ }
468
+ return { ok: false, error: `no live agent matches "${ref}"` };
469
+ }
470
+
471
+ // ---------------------------------------------------------------------------
472
+ // Log
473
+ // ---------------------------------------------------------------------------
474
+
475
+ export interface LogEntry {
476
+ ts: string;
477
+ name: string;
478
+ target: string;
479
+ agent_id?: string;
480
+ ok: boolean;
481
+ code: number;
482
+ error?: string;
483
+ manual?: boolean;
484
+ host?: string;
485
+ }
486
+
487
+ // ---------------------------------------------------------------------------
488
+ // `ay cron` argument parsing
489
+ // ---------------------------------------------------------------------------
490
+
491
+ /** `ay cron "<cron>" <target> <message...>` → a new entry (name filled by the caller). */
492
+ export function parseCronAdd(
493
+ argv: string[],
494
+ env: NodeJS.ProcessEnv = process.env,
495
+ ):
496
+ | { ok: true; cron: string; tz: string; target: string; message: string }
497
+ | { ok: false; error: string } {
498
+ let args = argv;
499
+ // also accept the cron unquoted: five fields then target then message
500
+ if (args.length >= 7 && !/\s/.test(args[0]!) && cronError(args.slice(0, 5).join(" ")) == null)
501
+ args = [args.slice(0, 5).join(" "), ...args.slice(5)];
502
+ const [cron, target, ...msg] = args;
503
+ if (!cron || !target || !msg.length)
504
+ return { ok: false, error: `usage: ay cron "<cron>" <target> <message...>` };
505
+ const e = cronError(cron);
506
+ if (e) return { ok: false, error: `bad cron "${cron}": ${e}` };
507
+ const tz = env.AY_CRON_TZ || DEFAULT_TZ;
508
+ if (!validTz(tz)) return { ok: false, error: `unknown tz "${tz}" (AY_CRON_TZ)` };
509
+ if (target.startsWith("lane:") && !target.slice(5).trim())
510
+ return { ok: false, error: `target "lane:" needs a lane name` };
511
+ return { ok: true, cron: cron.trim().replace(/\s+/g, " "), tz, target, message: msg.join(" ") };
512
+ }
513
+
514
+ /** Rows of `oxmgr list` output that are legacy `ay schedule` jobs. */
515
+ export function legacyRows(oxmgrList: string): string[] {
516
+ return oxmgrList.split("\n").filter((l) => l.includes("agent-yes-cron-"));
517
+ }