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,784 @@
1
+ import { spawn, spawnSync } from "child_process";
2
+ import { appendFileSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, watch, writeFileSync } from "fs";
3
+ import { homedir } from "os";
4
+ import path from "path";
5
+
6
+ //#region ts/schedules.ts
7
+ const DEFAULT_TZ = "Asia/Tokyo";
8
+ const CRON_HELP = `Usage:
9
+ ay cron "<cron>" <lane:<name>|agent> <message...> add a reminder (5-field cron, tz $AY_CRON_TZ or ${DEFAULT_TZ})
10
+ ay cron ls list reminders with next run and last result
11
+ ay cron rm <id> remove one
12
+
13
+ A target is lane:<name> (resolved with ay lanes id), a lane name tagged in a live
14
+ agent's prompt, or an agent id / pid / keyword. The message is sent with
15
+ ay send --force; {now} and {name} are substituted. Reminders are fired by the
16
+ per-machine scheduler daemon (ay schedules daemon status|install). A missed tick
17
+ (daemon down) is skipped. Each fire is logged as JSONL to
18
+ ~/.local/share/agent-yes/schedules.log ($AY_SCHEDULES_LOG).
19
+
20
+ Example:
21
+ ay cron "*/30 9-18 * * 1-5" lane:alpha "progress report please ({now})"
22
+ `;
23
+ const SCHEDULES_HELP = `Usage: ay schedules <command> (alias: ay sched)
24
+
25
+ ay schedules ls every schedule on this machine: ay cron reminders
26
+ (source=cron) and legacy ay schedule jobs (source=schedule)
27
+ ay schedules daemon status is the scheduler daemon running, and how it is kept alive
28
+ ay schedules daemon install start it and keep it alive (oxmgr / systemd --user /
29
+ launchd / Task Scheduler / nohup)
30
+ ay schedules daemon run the daemon loop itself (foreground)
31
+
32
+ Declarative schedules.yaml, apply and missed-run policies are pending a design decision.
33
+ `;
34
+ function logFile(env = process.env, home = homedir()) {
35
+ return env.AY_SCHEDULES_LOG || path.join(home, ".local", "share", "agent-yes", "schedules.log");
36
+ }
37
+ function validTz(tz) {
38
+ try {
39
+ new Intl.DateTimeFormat("en-US", { timeZone: tz });
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+ const FIELDS = [
46
+ {
47
+ min: 0,
48
+ max: 59
49
+ },
50
+ {
51
+ min: 0,
52
+ max: 23
53
+ },
54
+ {
55
+ min: 1,
56
+ max: 31
57
+ },
58
+ {
59
+ min: 1,
60
+ max: 12,
61
+ names: [
62
+ "jan",
63
+ "feb",
64
+ "mar",
65
+ "apr",
66
+ "may",
67
+ "jun",
68
+ "jul",
69
+ "aug",
70
+ "sep",
71
+ "oct",
72
+ "nov",
73
+ "dec"
74
+ ]
75
+ },
76
+ {
77
+ min: 0,
78
+ max: 7,
79
+ names: [
80
+ "sun",
81
+ "mon",
82
+ "tue",
83
+ "wed",
84
+ "thu",
85
+ "fri",
86
+ "sat"
87
+ ]
88
+ }
89
+ ];
90
+ const FIELD_NAMES = [
91
+ "minute",
92
+ "hour",
93
+ "day-of-month",
94
+ "month",
95
+ "day-of-week"
96
+ ];
97
+ function parseNum(s, spec) {
98
+ const lower = s.toLowerCase();
99
+ const idx = spec.names?.indexOf(lower) ?? -1;
100
+ if (idx >= 0) return idx + (spec.names.length === 12 ? 1 : 0);
101
+ if (!/^\d+$/.test(s)) throw new Error(`"${s}" is not a number`);
102
+ const n = Number(s);
103
+ if (n < spec.min || n > spec.max) throw new Error(`${n} out of range ${spec.min}-${spec.max}`);
104
+ return n;
105
+ }
106
+ function parseField(text, spec, isDow) {
107
+ const set = /* @__PURE__ */ new Set();
108
+ let star = false;
109
+ for (const part of text.split(",")) {
110
+ const [range, stepS, extra] = part.split("/");
111
+ if (extra !== void 0 || range === "") throw new Error(`bad term "${part}"`);
112
+ const step = stepS === void 0 ? 1 : Number(stepS);
113
+ if (!Number.isInteger(step) || step < 1 || stepS !== void 0 && !/^\d+$/.test(stepS)) throw new Error(`bad step in "${part}"`);
114
+ let lo, hi;
115
+ if (range === "*") {
116
+ lo = spec.min;
117
+ hi = isDow ? 6 : spec.max;
118
+ if (step === 1) star = true;
119
+ } else if (range.includes("-")) {
120
+ const [a, b] = range.split("-");
121
+ lo = parseNum(a, spec);
122
+ hi = parseNum(b, spec);
123
+ if (lo > hi) throw new Error(`range ${range} goes backwards`);
124
+ } else {
125
+ lo = parseNum(range, spec);
126
+ hi = stepS === void 0 ? lo : isDow ? 6 : spec.max;
127
+ }
128
+ for (let v = lo; v <= hi; v += step) set.add(isDow && v === 7 ? 0 : v);
129
+ }
130
+ return {
131
+ values: [...set].sort((a, b) => a - b),
132
+ star
133
+ };
134
+ }
135
+ function parseCron(cron) {
136
+ const parts = cron.trim().split(/\s+/);
137
+ if (parts.length !== 5) throw new Error(`expected 5 fields, got ${parts.length}`);
138
+ const f = parts.map((p, i) => {
139
+ try {
140
+ return parseField(p, FIELDS[i], i === 4);
141
+ } catch (e) {
142
+ throw new Error(`${FIELD_NAMES[i]}: ${e.message}`);
143
+ }
144
+ });
145
+ return {
146
+ minute: f[0],
147
+ hour: f[1],
148
+ dom: f[2],
149
+ month: f[3],
150
+ dow: f[4]
151
+ };
152
+ }
153
+ function cronError(cron) {
154
+ try {
155
+ parseCron(cron);
156
+ return null;
157
+ } catch (e) {
158
+ return e.message;
159
+ }
160
+ }
161
+ const DOW_NAMES = [
162
+ "Sun",
163
+ "Mon",
164
+ "Tue",
165
+ "Wed",
166
+ "Thu",
167
+ "Fri",
168
+ "Sat"
169
+ ];
170
+ const fmtCache = /* @__PURE__ */ new Map();
171
+ function tzParts(ms, tz) {
172
+ let f = fmtCache.get(tz);
173
+ if (!f) {
174
+ f = new Intl.DateTimeFormat("en-US", {
175
+ timeZone: tz,
176
+ hourCycle: "h23",
177
+ year: "numeric",
178
+ month: "numeric",
179
+ day: "numeric",
180
+ hour: "numeric",
181
+ minute: "numeric",
182
+ weekday: "short"
183
+ });
184
+ fmtCache.set(tz, f);
185
+ }
186
+ const p = {};
187
+ for (const x of f.formatToParts(ms)) p[x.type] = x.value;
188
+ return {
189
+ y: Number(p.year),
190
+ mo: Number(p.month),
191
+ d: Number(p.day),
192
+ h: Number(p.hour) % 24,
193
+ mi: Number(p.minute),
194
+ dow: DOW_NAMES.indexOf(p.weekday)
195
+ };
196
+ }
197
+ /** Next fire times (epoch ms) strictly after `from`, in `tz`. */
198
+ function nextRuns(cron, tz, from, n = 1) {
199
+ const c = parseCron(cron);
200
+ const has = (f, v) => f.star || f.values.includes(v);
201
+ const dayOk = (p) => {
202
+ if (!c.dom.star && !c.dow.star) return has(c.dom, p.d) || has(c.dow, p.dow);
203
+ return has(c.dom, p.d) && has(c.dow, p.dow);
204
+ };
205
+ const out = [];
206
+ let t = Math.floor(from / 6e4) * 6e4 + 6e4;
207
+ const end = from + 400 * 864e5;
208
+ while (out.length < n && t < end) {
209
+ const p = tzParts(t, tz);
210
+ if (!has(c.month, p.mo) || !dayOk(p)) t += (1440 - p.h * 60 - p.mi) * 6e4;
211
+ else if (!has(c.hour, p.h)) t += (60 - p.mi) * 6e4;
212
+ else if (!has(c.minute, p.mi)) t += 6e4;
213
+ else {
214
+ out.push(t);
215
+ t += 6e4;
216
+ }
217
+ }
218
+ return out;
219
+ }
220
+ /** `2026-01-02 03:04 Asia/Tokyo` */
221
+ function fmtTime(ms, tz) {
222
+ const p = tzParts(ms, tz);
223
+ const z = (n) => String(n).padStart(2, "0");
224
+ return `${p.y}-${z(p.mo)}-${z(p.d)} ${z(p.h)}:${z(p.mi)} ${tz}`;
225
+ }
226
+ function renderMessage(s, now) {
227
+ return s.message.replaceAll("{now}", fmtTime(now, s.tz)).replaceAll("{name}", s.name);
228
+ }
229
+ function storeFile(env = process.env, home = homedir()) {
230
+ return env.AY_SCHEDULES_STORE || path.join(home, ".config", "agent-yes", "schedules.json");
231
+ }
232
+ function stateFile(env = process.env, home = homedir()) {
233
+ return env.AY_SCHEDULES_STATE || path.join(home, ".local", "share", "agent-yes", "schedules.state.json");
234
+ }
235
+ function parseStore(text) {
236
+ if (!text) return {
237
+ version: 1,
238
+ entries: []
239
+ };
240
+ const j = JSON.parse(text);
241
+ return {
242
+ version: 1,
243
+ entries: Array.isArray(j?.entries) ? j.entries : []
244
+ };
245
+ }
246
+ function parseState(text) {
247
+ try {
248
+ const j = text ? JSON.parse(text) : {};
249
+ return {
250
+ lastTick: Number(j.lastTick) || 0,
251
+ last: j.last && typeof j.last === "object" ? j.last : {}
252
+ };
253
+ } catch {
254
+ return {
255
+ lastTick: 0,
256
+ last: {}
257
+ };
258
+ }
259
+ }
260
+ /** Next free cron-entry id: c1, c2, … */
261
+ function nextCronId(store) {
262
+ let n = 1;
263
+ while (store.entries.some((e) => e.name === `c${n}`)) n++;
264
+ return `c${n}`;
265
+ }
266
+ /** Window in which a due fire still counts as on time (not missed). */
267
+ const ON_TIME_MS = 9e4;
268
+ /**
269
+ * One scheduler tick: which entries fire now. For each enabled entry, a fire is
270
+ * due if a cron time falls in (max(lastTick, since, last run), now]. If the most
271
+ * recent due time is within ON_TIME_MS it is on time and fires; otherwise it was
272
+ * missed (daemon down / machine asleep) and fires once only when missed=run-once.
273
+ */
274
+ function dueNow(entries, state, now) {
275
+ const out = [];
276
+ for (const e of entries) {
277
+ if (!e.enabled) continue;
278
+ const from = Math.max(state.lastTick, e.since, state.last[e.name]?.at ?? 0);
279
+ const first = nextRuns(e.cron, e.tz, from, 1)[0];
280
+ if (first == null || first > now) continue;
281
+ const recent = nextRuns(e.cron, e.tz, now - ON_TIME_MS, 3).filter((t) => t <= now).at(-1);
282
+ if (recent != null && recent <= now && recent > from || e.missed === "run-once") out.push(e);
283
+ }
284
+ return out;
285
+ }
286
+ /**
287
+ * Longest single sleep. The daemon sleeps until the earliest next fire (no polling),
288
+ * but never longer than this, so a wall-clock jump or a suspend is noticed within a day.
289
+ */
290
+ const MAX_SLEEP_MS = 24 * 36e5;
291
+ /** How long to sleep from `now` until the earliest next fire of any enabled entry. */
292
+ function wakeDelay(entries, now) {
293
+ let best = Infinity;
294
+ for (const e of entries) {
295
+ if (!e.enabled) continue;
296
+ const t = nextRuns(e.cron, e.tz, now, 1)[0];
297
+ if (t != null && t < best) best = t;
298
+ }
299
+ return best === Infinity ? MAX_SLEEP_MS : Math.min(MAX_SLEEP_MS, Math.max(0, best - now + 50));
300
+ }
301
+ /**
302
+ * One wake-up, judged by the wall clock: what fires, and the new state. A clock
303
+ * that jumped backwards (lastTick in the future) resets lastTick to now, so
304
+ * nothing replays and the schedule resumes from the new time. A jump forwards
305
+ * or a suspend is a plain "slept past the slot": skip, or run-once.
306
+ */
307
+ function tick(entries, state, now) {
308
+ const clockBack = state.lastTick > now;
309
+ const last = Object.fromEntries(Object.entries(state.last).map(([k, v]) => [k, v.at > now ? {
310
+ ...v,
311
+ at: now
312
+ } : v]));
313
+ const st = {
314
+ lastTick: clockBack ? now : state.lastTick || now - 6e4,
315
+ last
316
+ };
317
+ return {
318
+ fire: dueNow(entries, st, now),
319
+ state: {
320
+ ...st,
321
+ lastTick: now
322
+ },
323
+ clockBack
324
+ };
325
+ }
326
+ const DAEMON_NAME = "agent-yes-schedulerd";
327
+ function systemdDaemonUnit(argv, pathEnv) {
328
+ const q = (s) => /^[\w@%+=:,./-]+$/.test(s) ? s : `"${s.replace(/(["\\])/g, "\\$1").replace(/%/g, "%%")}"`;
329
+ return `[Unit]\nDescription=agent-yes scheduler (ay schedules / ay cron)\n\n[Service]\nExecStart=${argv.map(q).join(" ")}\nEnvironment=${q(`PATH=${pathEnv}`)}\nRestart=always\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n`;
330
+ }
331
+ function launchdDaemonPlist(argv, pathEnv, logPath) {
332
+ const x = (v) => v.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
333
+ return `<?xml version="1.0" encoding="UTF-8"?>
334
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
335
+ <plist version="1.0">
336
+ <dict>
337
+ <key>Label</key><string>com.agent-yes.schedulerd</string>
338
+ <key>ProgramArguments</key>\n <array>\n${argv.map((a) => ` <string>${x(a)}</string>\n`).join("")} </array>\n <key>EnvironmentVariables</key>\n <dict><key>PATH</key><string>${x(pathEnv)}</string></dict>\n <key>RunAtLoad</key><true/>\n <key>KeepAlive</key><true/>\n <key>StandardErrorPath</key><string>${x(logPath)}</string>\n</dict>\n</plist>\n`;
339
+ }
340
+ /** Windows Task Scheduler: start at logon, restart is handled by the daemon's own lock. */
341
+ function windowsTaskArgs(argv) {
342
+ const q = (s) => /[\s"]/.test(s) ? `"${s.replace(/"/g, "\\\"")}"` : s;
343
+ return [
344
+ "/Create",
345
+ "/F",
346
+ "/SC",
347
+ "ONLOGON",
348
+ "/TN",
349
+ DAEMON_NAME,
350
+ "/TR",
351
+ argv.map(q).join(" ")
352
+ ];
353
+ }
354
+ /** Pick how to keep the daemon alive: the existing oxmgr runner first, then per-OS. */
355
+ function pickAutostart(o) {
356
+ if (o.hasOxmgr) return "oxmgr";
357
+ if (o.platform === "darwin") return "launchd";
358
+ if (o.platform === "win32") return "schtasks";
359
+ if (o.platform === "linux" && o.systemdUser) return "systemd";
360
+ return "nohup";
361
+ }
362
+ function parseTarget(t) {
363
+ const s = t.trim();
364
+ return s.startsWith("lane:") ? {
365
+ kind: "lane",
366
+ lane: s.slice(5).trim()
367
+ } : {
368
+ kind: "agent",
369
+ ref: s
370
+ };
371
+ }
372
+ /**
373
+ * Resolve a target to a live agent id. `laneId` answers `ay lanes id <name>`.
374
+ * An agent ref matches an exact agent_id or pid, else a unique agent_id prefix,
375
+ * else a unique cwd containing it (a keyword).
376
+ */
377
+ function resolveTarget(target, live, laneId) {
378
+ const t = parseTarget(target);
379
+ if (t.kind === "lane") {
380
+ const r = laneId(t.lane);
381
+ const id = r.out.trim();
382
+ return r.ok && id ? {
383
+ ok: true,
384
+ agentId: id
385
+ } : {
386
+ ok: false,
387
+ error: `lane "${t.lane}" has no live agent${id ? `: ${id}` : ""}`
388
+ };
389
+ }
390
+ const ref = t.ref;
391
+ const tiers = [
392
+ live.filter((a) => a.agent_id === ref || String(a.pid) === ref),
393
+ live.filter((a) => a.agent_id.startsWith(ref)),
394
+ live.filter((a) => a.cwd.includes(ref))
395
+ ];
396
+ for (const hits of tiers) {
397
+ if (hits.length === 1) return {
398
+ ok: true,
399
+ agentId: hits[0].agent_id
400
+ };
401
+ if (hits.length > 1) return {
402
+ ok: false,
403
+ error: `"${ref}" matches ${hits.length} live agents (${hits.map((a) => a.pid).join(", ")}); be more specific`
404
+ };
405
+ }
406
+ return {
407
+ ok: false,
408
+ error: `no live agent matches "${ref}"`
409
+ };
410
+ }
411
+ /** `ay cron "<cron>" <target> <message...>` → a new entry (name filled by the caller). */
412
+ function parseCronAdd(argv, env = process.env) {
413
+ let args = argv;
414
+ if (args.length >= 7 && !/\s/.test(args[0]) && cronError(args.slice(0, 5).join(" ")) == null) args = [args.slice(0, 5).join(" "), ...args.slice(5)];
415
+ const [cron, target, ...msg] = args;
416
+ if (!cron || !target || !msg.length) return {
417
+ ok: false,
418
+ error: `usage: ay cron "<cron>" <target> <message...>`
419
+ };
420
+ const e = cronError(cron);
421
+ if (e) return {
422
+ ok: false,
423
+ error: `bad cron "${cron}": ${e}`
424
+ };
425
+ const tz = env.AY_CRON_TZ || DEFAULT_TZ;
426
+ if (!validTz(tz)) return {
427
+ ok: false,
428
+ error: `unknown tz "${tz}" (AY_CRON_TZ)`
429
+ };
430
+ if (target.startsWith("lane:") && !target.slice(5).trim()) return {
431
+ ok: false,
432
+ error: `target "lane:" needs a lane name`
433
+ };
434
+ return {
435
+ ok: true,
436
+ cron: cron.trim().replace(/\s+/g, " "),
437
+ tz,
438
+ target,
439
+ message: msg.join(" ")
440
+ };
441
+ }
442
+ /** Rows of `oxmgr list` output that are legacy `ay schedule` jobs. */
443
+ function legacyRows(oxmgrList) {
444
+ return oxmgrList.split("\n").filter((l) => l.includes("agent-yes-cron-"));
445
+ }
446
+
447
+ //#endregion
448
+ //#region ts/schedulesCli.ts
449
+ function selfCmd() {
450
+ const argv1 = process.argv[1];
451
+ return argv1 && /\.(c|m)?[jt]s$/.test(argv1) ? [process.execPath, argv1] : [argv1 || "ay"];
452
+ }
453
+ function runSelf(args) {
454
+ const [cmd, ...pre] = selfCmd();
455
+ return spawnSync(cmd, [...pre, ...args], {
456
+ encoding: "utf8",
457
+ stdio: [
458
+ "ignore",
459
+ "pipe",
460
+ "pipe"
461
+ ],
462
+ maxBuffer: 64 * 1024 * 1024
463
+ });
464
+ }
465
+ function readText(f) {
466
+ return existsSync(f) ? readFileSync(f, "utf8") : null;
467
+ }
468
+ function writeAtomic(f, text) {
469
+ mkdirSync(path.dirname(f), { recursive: true });
470
+ const tmp = `${f}.${process.pid}.tmp`;
471
+ writeFileSync(tmp, text);
472
+ renameSync(tmp, f);
473
+ }
474
+ const loadStore = () => parseStore(readText(storeFile()));
475
+ const saveStore = (s) => writeAtomic(storeFile(), JSON.stringify(s, null, 2) + "\n");
476
+ const loadState = () => parseState(readText(stateFile()));
477
+ const saveState = (s) => writeAtomic(stateFile(), JSON.stringify(s) + "\n");
478
+ function log(e) {
479
+ const f = logFile();
480
+ mkdirSync(path.dirname(f), { recursive: true });
481
+ appendFileSync(f, JSON.stringify(e) + "\n");
482
+ }
483
+ /** Resolve the target and `ay send --force`. Returns the exit code (3 = target not live). */
484
+ function fire(e, now, manual = false) {
485
+ let live = [];
486
+ try {
487
+ live = JSON.parse(runSelf(["ls", "--json"]).stdout || "[]");
488
+ } catch {}
489
+ const r = resolveTarget(e.target, live, (lane) => {
490
+ const x = runSelf([
491
+ "lanes",
492
+ "id",
493
+ lane
494
+ ]);
495
+ return {
496
+ ok: x.status === 0,
497
+ out: x.status === 0 ? x.stdout : (x.stderr || "").trim().split("\n")[0] || ""
498
+ };
499
+ });
500
+ const base = {
501
+ ts: new Date(now).toISOString(),
502
+ name: e.name,
503
+ target: e.target,
504
+ ...manual ? { manual } : {}
505
+ };
506
+ if (!r.ok) {
507
+ log({
508
+ ...base,
509
+ ok: false,
510
+ code: 3,
511
+ error: r.error
512
+ });
513
+ console.error(`ay cron ${e.name}: ${r.error}; nothing sent`);
514
+ return 3;
515
+ }
516
+ const s = runSelf([
517
+ "send",
518
+ r.agentId,
519
+ renderMessage(e, now),
520
+ "--force"
521
+ ]);
522
+ const code = s.status ?? 1;
523
+ log({
524
+ ...base,
525
+ agent_id: r.agentId,
526
+ ok: code === 0,
527
+ code,
528
+ ...code ? { error: (s.stderr || "").trim().slice(0, 500) } : {}
529
+ });
530
+ return code;
531
+ }
532
+ function lastStr(st, name, tz) {
533
+ const l = st.last[name];
534
+ return l ? `${fmtTime(l.at, tz)} ${l.ok ? "ok" : `exit ${l.code}`}` : "-";
535
+ }
536
+ function printEntries(entries, st, withSource) {
537
+ const now = Date.now();
538
+ for (const e of entries) {
539
+ const next = e.enabled ? nextRuns(e.cron, e.tz, now, 1)[0] : void 0;
540
+ console.log([
541
+ e.name.padEnd(6),
542
+ ...withSource ? [`source=${e.source}`] : [],
543
+ `"${e.cron}" ${e.tz}`,
544
+ e.target,
545
+ e.enabled ? "" : "(disabled)",
546
+ `next ${next ? fmtTime(next, e.tz) : "-"}`,
547
+ `last ${lastStr(st, e.name, e.tz)}`,
548
+ `: ${e.message.length > 60 ? e.message.slice(0, 59) + "…" : e.message}`
549
+ ].filter(Boolean).join(" "));
550
+ }
551
+ }
552
+ async function cmdCron(argv) {
553
+ const [sub, ...rest] = argv;
554
+ if (!sub || sub === "help" || sub === "--help" || sub === "-h") {
555
+ process.stdout.write(CRON_HELP);
556
+ return sub ? 0 : 1;
557
+ }
558
+ if (sub === "ls" || sub === "list") {
559
+ const st = loadState();
560
+ const entries = loadStore().entries.filter((e) => e.source === "cron");
561
+ if (!entries.length) console.log("no reminders (ay cron help)");
562
+ printEntries(entries, st, false);
563
+ if (entries.length && !daemonPid()) console.log(`\nwarning: the scheduler daemon is not running (ay schedules daemon install)`);
564
+ return 0;
565
+ }
566
+ if (sub === "rm" || sub === "remove") {
567
+ const id = rest[0];
568
+ const store = loadStore();
569
+ const hit = store.entries.find((e) => e.name === id && e.source === "cron");
570
+ if (!id || !hit) {
571
+ console.error(`ay cron rm: no reminder "${id ?? ""}" (see ay cron ls)`);
572
+ return 2;
573
+ }
574
+ saveStore({
575
+ ...store,
576
+ entries: store.entries.filter((e) => e !== hit)
577
+ });
578
+ console.log(`removed ${id}`);
579
+ return 0;
580
+ }
581
+ const p = parseCronAdd(argv);
582
+ if (!p.ok) {
583
+ console.error(`ay cron: ${p.error}`);
584
+ return 1;
585
+ }
586
+ const store = loadStore();
587
+ const name = nextCronId(store);
588
+ const entry = {
589
+ name,
590
+ cron: p.cron,
591
+ tz: p.tz,
592
+ target: p.target,
593
+ message: p.message,
594
+ enabled: true,
595
+ missed: "skip",
596
+ source: "cron",
597
+ since: Date.now()
598
+ };
599
+ saveStore({
600
+ ...store,
601
+ entries: [...store.entries, entry]
602
+ });
603
+ const next = nextRuns(p.cron, p.tz, Date.now(), 1)[0];
604
+ console.log(`added ${name}: "${p.cron}" ${p.tz} -> ${p.target}; next ${next ? fmtTime(next, p.tz) : "-"}`);
605
+ if (!await ensureDaemon(false)) console.log(`warning: could not start the scheduler daemon (ay schedules daemon install)`);
606
+ return 0;
607
+ }
608
+ const pidFile = () => path.join(path.dirname(stateFile()), "schedulerd.pid");
609
+ function alive(pid) {
610
+ try {
611
+ process.kill(pid, 0);
612
+ return true;
613
+ } catch (e) {
614
+ return e.code === "EPERM";
615
+ }
616
+ }
617
+ function daemonPid() {
618
+ const pid = Number(readText(pidFile())?.trim());
619
+ return pid && alive(pid) ? pid : null;
620
+ }
621
+ /**
622
+ * Foreground loop, one per machine (pid file). Sleeps until the earliest next fire
623
+ * (capped at MAX_SLEEP_MS), re-arms after each fire, and wakes at once when the
624
+ * store file changes (fs.watch on its directory: writes are atomic renames).
625
+ */
626
+ async function daemonRun() {
627
+ const other = daemonPid();
628
+ if (other && other !== process.pid) {
629
+ console.error(`${DAEMON_NAME}: already running (pid ${other})`);
630
+ return 0;
631
+ }
632
+ writeAtomic(pidFile(), `${process.pid}\n`);
633
+ const sf = storeFile();
634
+ mkdirSync(path.dirname(sf), { recursive: true });
635
+ console.error(`${DAEMON_NAME}: started pid ${process.pid}, store ${sf}`);
636
+ let wake = null;
637
+ watch(path.dirname(sf), (_ev, file) => {
638
+ if (!file || file.toString() === path.basename(sf)) wake?.();
639
+ });
640
+ for (;;) {
641
+ const now = Date.now();
642
+ const entries = loadStore().entries;
643
+ const t = tick(entries, loadState(), now);
644
+ if (t.clockBack) console.error(`${DAEMON_NAME}: clock went backwards; resuming from ${new Date(now).toISOString()}`);
645
+ for (const e of t.fire) {
646
+ const code = fire(e, now);
647
+ t.state.last[e.name] = {
648
+ at: now,
649
+ ok: code === 0,
650
+ code
651
+ };
652
+ }
653
+ saveState(t.state);
654
+ const ms = wakeDelay(entries, Date.now());
655
+ await new Promise((r) => {
656
+ const timer = setTimeout(done, ms);
657
+ function done() {
658
+ clearTimeout(timer);
659
+ wake = null;
660
+ r();
661
+ }
662
+ wake = done;
663
+ });
664
+ }
665
+ }
666
+ function has(cmd, args) {
667
+ return spawnSync(cmd, args, { stdio: "ignore" }).status === 0;
668
+ }
669
+ function which(cmd) {
670
+ const r = spawnSync(process.platform === "win32" ? "where" : "which", [cmd], { encoding: "utf8" });
671
+ return r.status === 0 ? r.stdout.split(/\r?\n/)[0].trim() || null : null;
672
+ }
673
+ function autostartKind() {
674
+ return pickAutostart({
675
+ platform: process.platform,
676
+ hasOxmgr: !!which("oxmgr"),
677
+ systemdUser: process.platform === "linux" && has("systemctl", ["--user", "show-environment"])
678
+ });
679
+ }
680
+ /** Start the daemon and register it to stay alive. Returns whether it is running. */
681
+ async function ensureDaemon(verbose) {
682
+ if (daemonPid()) {
683
+ if (verbose) console.log(`${DAEMON_NAME}: already running (pid ${daemonPid()})`);
684
+ return true;
685
+ }
686
+ const argv = [
687
+ ...selfCmd(),
688
+ "schedules",
689
+ "daemon",
690
+ "run"
691
+ ];
692
+ const pathEnv = process.env.PATH || "";
693
+ const kind = autostartKind();
694
+ const home = homedir();
695
+ const say = (m) => verbose && console.log(m);
696
+ let ok = false;
697
+ if (kind === "oxmgr") {
698
+ const q = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
699
+ ok = has("oxmgr", [
700
+ "start",
701
+ argv.map(q).join(" "),
702
+ "--name",
703
+ DAEMON_NAME,
704
+ "--restart",
705
+ "always"
706
+ ]);
707
+ if (ok) {
708
+ const { ensureBootAutostart } = await import("./oxmgrService-o9L3I6FX.js");
709
+ await ensureBootAutostart(which("oxmgr")).catch(() => false);
710
+ }
711
+ } else if (kind === "systemd") {
712
+ writeAtomic(path.join(home, ".config", "systemd", "user", `${DAEMON_NAME}.service`), systemdDaemonUnit(argv, pathEnv));
713
+ ok = has("systemctl", ["--user", "daemon-reload"]) && has("systemctl", [
714
+ "--user",
715
+ "enable",
716
+ "--now",
717
+ `${DAEMON_NAME}.service`
718
+ ]);
719
+ } else if (kind === "launchd") {
720
+ const f = path.join(home, "Library", "LaunchAgents", "com.agent-yes.schedulerd.plist");
721
+ writeAtomic(f, launchdDaemonPlist(argv, pathEnv, path.join(path.dirname(stateFile()), "schedulerd.log")));
722
+ ok = has("launchctl", [
723
+ "load",
724
+ "-w",
725
+ f
726
+ ]);
727
+ } else if (kind === "schtasks") ok = has("schtasks", windowsTaskArgs(argv)) && has("schtasks", [
728
+ "/Run",
729
+ "/TN",
730
+ DAEMON_NAME
731
+ ]);
732
+ if (!ok) {
733
+ const f = path.join(path.dirname(stateFile()), "schedulerd.log");
734
+ mkdirSync(path.dirname(f), { recursive: true });
735
+ const out = openSync(f, "a");
736
+ const child = spawn(argv[0], argv.slice(1), {
737
+ detached: true,
738
+ stdio: [
739
+ "ignore",
740
+ out,
741
+ out
742
+ ]
743
+ });
744
+ child.unref();
745
+ say(`${DAEMON_NAME}: ${kind === "nohup" ? "" : `${kind} failed; `}started detached (pid ${child.pid}); not restarted on reboot`);
746
+ } else say(`${DAEMON_NAME}: installed via ${kind}`);
747
+ for (let i = 0; i < 20 && !daemonPid(); i++) await new Promise((r) => setTimeout(r, 250));
748
+ return !!daemonPid();
749
+ }
750
+ async function cmdSchedules(argv) {
751
+ const [sub, ...rest] = argv;
752
+ if (!sub || sub === "help" || sub === "--help" || sub === "-h") {
753
+ process.stdout.write(SCHEDULES_HELP);
754
+ return sub ? 0 : 1;
755
+ }
756
+ if (sub === "ls" || sub === "list") {
757
+ printEntries(loadStore().entries, loadState(), true);
758
+ const ox = which("oxmgr");
759
+ if (ox) {
760
+ const r = spawnSync(ox, ["list"], { encoding: "utf8" });
761
+ for (const row of legacyRows(r.stdout || "")) console.log(`source=schedule ${row.trim()}`);
762
+ }
763
+ const pid = daemonPid();
764
+ console.log(`\ndaemon: ${pid ? `running (pid ${pid})` : "not running (ay schedules daemon install)"}`);
765
+ return 0;
766
+ }
767
+ if (sub === "daemon") {
768
+ const what = rest[0] ?? "status";
769
+ if (what === "run") return daemonRun();
770
+ if (what === "install" || what === "start") return await ensureDaemon(true) ? 0 : 1;
771
+ if (what === "status") {
772
+ const pid = daemonPid();
773
+ console.log(pid ? `running (pid ${pid}); autostart: ${autostartKind()}` : `not running; autostart would use ${autostartKind()}`);
774
+ return pid ? 0 : 3;
775
+ }
776
+ }
777
+ console.error(`ay schedules: unknown command "${argv.join(" ")}"\n`);
778
+ process.stdout.write(SCHEDULES_HELP);
779
+ return 1;
780
+ }
781
+
782
+ //#endregion
783
+ export { cmdCron, cmdSchedules };
784
+ //# sourceMappingURL=schedulesCli-CLqieyQZ.js.map