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,386 @@
1
+ // `ay cron` / `ay schedules` CLI shell: store files, ay ls/send, the daemon loop and
2
+ // its autostart, over the pure core in schedules.ts.
3
+ import { spawn, spawnSync } from "child_process";
4
+ import {
5
+ appendFileSync,
6
+ existsSync,
7
+ mkdirSync,
8
+ openSync,
9
+ readFileSync,
10
+ renameSync,
11
+ watch,
12
+ writeFileSync,
13
+ } from "fs";
14
+ import { homedir } from "os";
15
+ import path from "path";
16
+ import {
17
+ CRON_HELP,
18
+ DAEMON_NAME,
19
+ SCHEDULES_HELP,
20
+ type LogEntry,
21
+ type RunState,
22
+ type Store,
23
+ type StoreEntry,
24
+ fmtTime,
25
+ launchdDaemonPlist,
26
+ legacyRows,
27
+ logFile,
28
+ nextCronId,
29
+ nextRuns,
30
+ parseCronAdd,
31
+ parseState,
32
+ parseStore,
33
+ pickAutostart,
34
+ renderMessage,
35
+ resolveTarget,
36
+ stateFile,
37
+ storeFile,
38
+ systemdDaemonUnit,
39
+ tick,
40
+ wakeDelay,
41
+ windowsTaskArgs,
42
+ } from "./schedules.ts";
43
+
44
+ function selfCmd(): string[] {
45
+ const argv1 = process.argv[1];
46
+ return argv1 && /\.(c|m)?[jt]s$/.test(argv1) ? [process.execPath, argv1] : [argv1 || "ay"];
47
+ }
48
+
49
+ function runSelf(args: string[]) {
50
+ const [cmd, ...pre] = selfCmd();
51
+ return spawnSync(cmd!, [...pre, ...args], {
52
+ encoding: "utf8",
53
+ stdio: ["ignore", "pipe", "pipe"],
54
+ maxBuffer: 64 * 1024 * 1024,
55
+ });
56
+ }
57
+
58
+ function readText(f: string): string | null {
59
+ return existsSync(f) ? readFileSync(f, "utf8") : null;
60
+ }
61
+
62
+ function writeAtomic(f: string, text: string) {
63
+ mkdirSync(path.dirname(f), { recursive: true });
64
+ const tmp = `${f}.${process.pid}.tmp`;
65
+ writeFileSync(tmp, text);
66
+ renameSync(tmp, f);
67
+ }
68
+
69
+ const loadStore = (): Store => parseStore(readText(storeFile()));
70
+ const saveStore = (s: Store) => writeAtomic(storeFile(), JSON.stringify(s, null, 2) + "\n");
71
+ const loadState = (): RunState => parseState(readText(stateFile()));
72
+ const saveState = (s: RunState) => writeAtomic(stateFile(), JSON.stringify(s) + "\n");
73
+
74
+ function log(e: LogEntry) {
75
+ const f = logFile();
76
+ mkdirSync(path.dirname(f), { recursive: true });
77
+ appendFileSync(f, JSON.stringify(e) + "\n");
78
+ }
79
+
80
+ /** Resolve the target and `ay send --force`. Returns the exit code (3 = target not live). */
81
+ export function fire(e: StoreEntry, now: number, manual = false): number {
82
+ let live: { pid: number; agent_id: string; cwd: string }[] = [];
83
+ try {
84
+ live = JSON.parse(runSelf(["ls", "--json"]).stdout || "[]");
85
+ } catch {
86
+ /* none */
87
+ }
88
+ const r = resolveTarget(e.target, live, (lane) => {
89
+ const x = runSelf(["lanes", "id", lane]);
90
+ return {
91
+ ok: x.status === 0,
92
+ out: x.status === 0 ? x.stdout : (x.stderr || "").trim().split("\n")[0] || "",
93
+ };
94
+ });
95
+ const base = {
96
+ ts: new Date(now).toISOString(),
97
+ name: e.name,
98
+ target: e.target,
99
+ ...(manual ? { manual } : {}),
100
+ };
101
+ if (!r.ok) {
102
+ log({ ...base, ok: false, code: 3, error: r.error });
103
+ console.error(`ay cron ${e.name}: ${r.error}; nothing sent`);
104
+ return 3;
105
+ }
106
+ const s = runSelf(["send", r.agentId, renderMessage(e, now), "--force"]);
107
+ const code = s.status ?? 1;
108
+ log({
109
+ ...base,
110
+ agent_id: r.agentId,
111
+ ok: code === 0,
112
+ code,
113
+ ...(code ? { error: (s.stderr || "").trim().slice(0, 500) } : {}),
114
+ });
115
+ return code;
116
+ }
117
+
118
+ function lastStr(st: RunState, name: string, tz: string): string {
119
+ const l = st.last[name];
120
+ return l ? `${fmtTime(l.at, tz)} ${l.ok ? "ok" : `exit ${l.code}`}` : "-";
121
+ }
122
+
123
+ function printEntries(entries: StoreEntry[], st: RunState, withSource: boolean) {
124
+ const now = Date.now();
125
+ for (const e of entries) {
126
+ const next = e.enabled ? nextRuns(e.cron, e.tz, now, 1)[0] : undefined;
127
+ console.log(
128
+ [
129
+ e.name.padEnd(6),
130
+ ...(withSource ? [`source=${e.source}`] : []),
131
+ `"${e.cron}" ${e.tz}`,
132
+ e.target,
133
+ e.enabled ? "" : "(disabled)",
134
+ `next ${next ? fmtTime(next, e.tz) : "-"}`,
135
+ `last ${lastStr(st, e.name, e.tz)}`,
136
+ `: ${e.message.length > 60 ? e.message.slice(0, 59) + "…" : e.message}`,
137
+ ]
138
+ .filter(Boolean)
139
+ .join(" "),
140
+ );
141
+ }
142
+ }
143
+
144
+ // ---------------------------------------------------------------------------
145
+ // ay cron
146
+ // ---------------------------------------------------------------------------
147
+
148
+ export async function cmdCron(argv: string[]): Promise<number> {
149
+ const [sub, ...rest] = argv;
150
+ if (!sub || sub === "help" || sub === "--help" || sub === "-h") {
151
+ process.stdout.write(CRON_HELP);
152
+ return sub ? 0 : 1;
153
+ }
154
+ if (sub === "ls" || sub === "list") {
155
+ const st = loadState();
156
+ const entries = loadStore().entries.filter((e) => e.source === "cron");
157
+ if (!entries.length) console.log("no reminders (ay cron help)");
158
+ printEntries(entries, st, false);
159
+ if (entries.length && !daemonPid())
160
+ console.log(`\nwarning: the scheduler daemon is not running (ay schedules daemon install)`);
161
+ return 0;
162
+ }
163
+ if (sub === "rm" || sub === "remove") {
164
+ const id = rest[0];
165
+ const store = loadStore();
166
+ const hit = store.entries.find((e) => e.name === id && e.source === "cron");
167
+ if (!id || !hit) {
168
+ console.error(`ay cron rm: no reminder "${id ?? ""}" (see ay cron ls)`);
169
+ return 2;
170
+ }
171
+ saveStore({ ...store, entries: store.entries.filter((e) => e !== hit) });
172
+ console.log(`removed ${id}`);
173
+ return 0;
174
+ }
175
+ const p = parseCronAdd(argv);
176
+ if (!p.ok) {
177
+ console.error(`ay cron: ${p.error}`);
178
+ return 1;
179
+ }
180
+ const store = loadStore();
181
+ const name = nextCronId(store);
182
+ const entry: StoreEntry = {
183
+ name,
184
+ cron: p.cron,
185
+ tz: p.tz,
186
+ target: p.target,
187
+ message: p.message,
188
+ enabled: true,
189
+ missed: "skip",
190
+ source: "cron",
191
+ since: Date.now(),
192
+ };
193
+ saveStore({ ...store, entries: [...store.entries, entry] });
194
+ const next = nextRuns(p.cron, p.tz, Date.now(), 1)[0];
195
+ console.log(
196
+ `added ${name}: "${p.cron}" ${p.tz} -> ${p.target}; next ${next ? fmtTime(next, p.tz) : "-"}`,
197
+ );
198
+ const started = await ensureDaemon(false);
199
+ if (!started)
200
+ console.log(`warning: could not start the scheduler daemon (ay schedules daemon install)`);
201
+ return 0;
202
+ }
203
+
204
+ // ---------------------------------------------------------------------------
205
+ // daemon
206
+ // ---------------------------------------------------------------------------
207
+
208
+ const pidFile = () => path.join(path.dirname(stateFile()), "schedulerd.pid");
209
+
210
+ function alive(pid: number): boolean {
211
+ try {
212
+ process.kill(pid, 0);
213
+ return true;
214
+ } catch (e) {
215
+ return (e as NodeJS.ErrnoException).code === "EPERM";
216
+ }
217
+ }
218
+
219
+ export function daemonPid(): number | null {
220
+ const pid = Number(readText(pidFile())?.trim());
221
+ return pid && alive(pid) ? pid : null;
222
+ }
223
+
224
+ /**
225
+ * Foreground loop, one per machine (pid file). Sleeps until the earliest next fire
226
+ * (capped at MAX_SLEEP_MS), re-arms after each fire, and wakes at once when the
227
+ * store file changes (fs.watch on its directory: writes are atomic renames).
228
+ */
229
+ export async function daemonRun(): Promise<number> {
230
+ const other = daemonPid();
231
+ if (other && other !== process.pid) {
232
+ console.error(`${DAEMON_NAME}: already running (pid ${other})`);
233
+ return 0;
234
+ }
235
+ writeAtomic(pidFile(), `${process.pid}\n`);
236
+ const sf = storeFile();
237
+ mkdirSync(path.dirname(sf), { recursive: true });
238
+ console.error(`${DAEMON_NAME}: started pid ${process.pid}, store ${sf}`);
239
+ let wake: (() => void) | null = null;
240
+ watch(path.dirname(sf), (_ev, file) => {
241
+ if (!file || file.toString() === path.basename(sf)) wake?.();
242
+ });
243
+ for (;;) {
244
+ const now = Date.now();
245
+ const entries = loadStore().entries;
246
+ const t = tick(entries, loadState(), now);
247
+ if (t.clockBack)
248
+ console.error(
249
+ `${DAEMON_NAME}: clock went backwards; resuming from ${new Date(now).toISOString()}`,
250
+ );
251
+ for (const e of t.fire) {
252
+ const code = fire(e, now);
253
+ t.state.last[e.name] = { at: now, ok: code === 0, code };
254
+ }
255
+ saveState(t.state);
256
+ const ms = wakeDelay(entries, Date.now());
257
+ await new Promise<void>((r) => {
258
+ const timer = setTimeout(done, ms);
259
+ function done() {
260
+ clearTimeout(timer);
261
+ wake = null;
262
+ r();
263
+ }
264
+ wake = done;
265
+ });
266
+ }
267
+ }
268
+
269
+ function has(cmd: string, args: string[]): boolean {
270
+ const r = spawnSync(cmd, args, { stdio: "ignore" });
271
+ return r.status === 0;
272
+ }
273
+
274
+ function which(cmd: string): string | null {
275
+ const r = spawnSync(process.platform === "win32" ? "where" : "which", [cmd], {
276
+ encoding: "utf8",
277
+ });
278
+ return r.status === 0 ? r.stdout.split(/\r?\n/)[0]!.trim() || null : null;
279
+ }
280
+
281
+ function autostartKind() {
282
+ return pickAutostart({
283
+ platform: process.platform,
284
+ hasOxmgr: !!which("oxmgr"),
285
+ systemdUser: process.platform === "linux" && has("systemctl", ["--user", "show-environment"]),
286
+ });
287
+ }
288
+
289
+ /** Start the daemon and register it to stay alive. Returns whether it is running. */
290
+ export async function ensureDaemon(verbose: boolean): Promise<boolean> {
291
+ if (daemonPid()) {
292
+ if (verbose) console.log(`${DAEMON_NAME}: already running (pid ${daemonPid()})`);
293
+ return true;
294
+ }
295
+ const argv = [...selfCmd(), "schedules", "daemon", "run"];
296
+ const pathEnv = process.env.PATH || "";
297
+ const kind = autostartKind();
298
+ const home = homedir();
299
+ const say = (m: string) => verbose && console.log(m);
300
+ let ok = false;
301
+ if (kind === "oxmgr") {
302
+ const q = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`;
303
+ ok = has("oxmgr", [
304
+ "start",
305
+ argv.map(q).join(" "),
306
+ "--name",
307
+ DAEMON_NAME,
308
+ "--restart",
309
+ "always",
310
+ ]);
311
+ if (ok) {
312
+ const { ensureBootAutostart } = await import("./oxmgrService.ts");
313
+ await ensureBootAutostart(which("oxmgr")!).catch(() => false);
314
+ }
315
+ } else if (kind === "systemd") {
316
+ const f = path.join(home, ".config", "systemd", "user", `${DAEMON_NAME}.service`);
317
+ writeAtomic(f, systemdDaemonUnit(argv, pathEnv));
318
+ ok =
319
+ has("systemctl", ["--user", "daemon-reload"]) &&
320
+ has("systemctl", ["--user", "enable", "--now", `${DAEMON_NAME}.service`]);
321
+ } else if (kind === "launchd") {
322
+ const f = path.join(home, "Library", "LaunchAgents", "com.agent-yes.schedulerd.plist");
323
+ writeAtomic(
324
+ f,
325
+ launchdDaemonPlist(argv, pathEnv, path.join(path.dirname(stateFile()), "schedulerd.log")),
326
+ );
327
+ ok = has("launchctl", ["load", "-w", f]);
328
+ } else if (kind === "schtasks") {
329
+ ok = has("schtasks", windowsTaskArgs(argv)) && has("schtasks", ["/Run", "/TN", DAEMON_NAME]);
330
+ }
331
+ if (!ok) {
332
+ // nohup fallback (containers without an init system): detached child; not restarted on reboot.
333
+ const f = path.join(path.dirname(stateFile()), "schedulerd.log");
334
+ mkdirSync(path.dirname(f), { recursive: true });
335
+ const out = openSync(f, "a");
336
+ const child = spawn(argv[0]!, argv.slice(1), { detached: true, stdio: ["ignore", out, out] });
337
+ child.unref();
338
+ say(
339
+ `${DAEMON_NAME}: ${kind === "nohup" ? "" : `${kind} failed; `}started detached (pid ${child.pid}); not restarted on reboot`,
340
+ );
341
+ } else say(`${DAEMON_NAME}: installed via ${kind}`);
342
+ for (let i = 0; i < 20 && !daemonPid(); i++) await new Promise((r) => setTimeout(r, 250));
343
+ return !!daemonPid();
344
+ }
345
+
346
+ // ---------------------------------------------------------------------------
347
+ // ay schedules
348
+ // ---------------------------------------------------------------------------
349
+
350
+ export async function cmdSchedules(argv: string[]): Promise<number> {
351
+ const [sub, ...rest] = argv;
352
+ if (!sub || sub === "help" || sub === "--help" || sub === "-h") {
353
+ process.stdout.write(SCHEDULES_HELP);
354
+ return sub ? 0 : 1;
355
+ }
356
+ if (sub === "ls" || sub === "list") {
357
+ printEntries(loadStore().entries, loadState(), true);
358
+ const ox = which("oxmgr");
359
+ if (ox) {
360
+ const r = spawnSync(ox, ["list"], { encoding: "utf8" });
361
+ for (const row of legacyRows(r.stdout || "")) console.log(`source=schedule ${row.trim()}`);
362
+ }
363
+ const pid = daemonPid();
364
+ console.log(
365
+ `\ndaemon: ${pid ? `running (pid ${pid})` : "not running (ay schedules daemon install)"}`,
366
+ );
367
+ return 0;
368
+ }
369
+ if (sub === "daemon") {
370
+ const what = rest[0] ?? "status";
371
+ if (what === "run") return daemonRun();
372
+ if (what === "install" || what === "start") return (await ensureDaemon(true)) ? 0 : 1;
373
+ if (what === "status") {
374
+ const pid = daemonPid();
375
+ console.log(
376
+ pid
377
+ ? `running (pid ${pid}); autostart: ${autostartKind()}`
378
+ : `not running; autostart would use ${autostartKind()}`,
379
+ );
380
+ return pid ? 0 : 3;
381
+ }
382
+ }
383
+ console.error(`ay schedules: unknown command "${argv.join(" ")}"\n`);
384
+ process.stdout.write(SCHEDULES_HELP);
385
+ return 1;
386
+ }
@@ -0,0 +1,12 @@
1
+ import { expect, test } from "bun:test";
2
+ import { controlCodeFromName, isSubmitCode } from "./subcommands.ts";
3
+
4
+ test("native queued send stays Enter; immediate Alt+M requires an explicit code", () => {
5
+ expect(controlCodeFromName("enter")).toBe("\r");
6
+ for (const alias of ["alt-m", "alt+m"]) {
7
+ expect(controlCodeFromName(alias)).toBe("\x1bm");
8
+ expect(isSubmitCode(controlCodeFromName(alias))).toBe(true);
9
+ }
10
+ for (const code of ["esc", "ctrl-c", "tab", "none"])
11
+ expect(isSubmitCode(controlCodeFromName(code))).toBe(false);
12
+ });
@@ -230,9 +230,7 @@ export function pidOwnershipVerdict(
230
230
  toleranceSecs = 60,
231
231
  ): PidOwnership {
232
232
  if (ageSecs === undefined || startedAt === undefined) return "unknown";
233
- return ageMatchesRegistration(ageSecs, startedAt, now, toleranceSecs)
234
- ? "ours"
235
- : "reused";
233
+ return ageMatchesRegistration(ageSecs, startedAt, now, toleranceSecs) ? "ours" : "reused";
236
234
  }
237
235
 
238
236
  export async function readAncestryTable(
package/ts/serve.ts CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  import { existsSync, realpathSync, renameSync, watch, writeFileSync } from "node:fs";
14
14
  import { execFileSync } from "node:child_process";
15
15
  import { fileURLToPath } from "node:url";
16
- import { createHash, randomBytes, timingSafeEqual } from "crypto";
16
+ import { randomBytes, timingSafeEqual } from "crypto";
17
17
  import {
18
18
  arch,
19
19
  cpus,
@@ -72,7 +72,6 @@ import { updateGlobalPidStatus } from "./globalPidIndex.ts";
72
72
  import { spawnRejectionReason } from "./spawnGate.ts";
73
73
  import { findSpawnHiddenLauncher } from "./rustBinary.ts";
74
74
  import { launchTray } from "./trayApp.ts";
75
- import { pgidForWrapper } from "./reaper.ts";
76
75
  import { SUPPORTED_CLIS } from "./SUPPORTED_CLIS.ts";
77
76
  import { getInstalledPackage } from "./versionChecker.ts";
78
77
  import { negotiateSize, sanitizeCap, type SizeCap } from "./sizeNego.ts";
@@ -1914,7 +1913,7 @@ export async function cmdServe(rest: string[]): Promise<number> {
1914
1913
  // the Rust daemon; the rest stays here. See ts/serveRust.ts for the split.
1915
1914
  // `--no-rust` is stripped for the parsers below either way.
1916
1915
  {
1917
- const { planRustServe } = await import("./serveRust.ts");
1916
+ const { planRustServe, SERVE_SUBCOMMANDS } = await import("./serveRust.ts");
1918
1917
  const plan = planRustServe(rest);
1919
1918
  if (plan.kind === "rust-only") {
1920
1919
  const { ensureAyrsBinary } = await import("./rustBinary.ts");
@@ -1941,6 +1940,13 @@ export async function cmdServe(rest: string[]): Promise<number> {
1941
1940
  process.stderr.write(`ay serve: ${plan.reason}: joining rooms needs the Rust daemon\n`);
1942
1941
  return 1;
1943
1942
  }
1943
+ // Say which server runs and why, so a daemon log (and `ay share`'s
1944
+ // choice of room file) never leaves the operator guessing. Subcommands
1945
+ // and the explicit opt-outs are not "fallbacks", so stay quiet there.
1946
+ const optedOut = plan.reason === "--no-rust" || plan.reason === "AGENT_YES_NO_RUST=1";
1947
+ if (!optedOut && !SERVE_SUBCOMMANDS.has(rest[0] ?? "")) {
1948
+ process.stderr.write(`ay serve: running the TypeScript server (${plan.reason})\n`);
1949
+ }
1944
1950
  }
1945
1951
  }
1946
1952
 
@@ -2160,7 +2166,7 @@ export async function cmdServe(rest: string[]): Promise<number> {
2160
2166
  // eslint-disable-next-line no-control-regex
2161
2167
  const oscTitleRe = /\x1b\][02];([^\x07\x1b]*)(?:\x07|\x1b\\)/g;
2162
2168
  let title: string | null = null;
2163
- for (let m; (m = oscTitleRe.exec(text)); ) if (m[1]!.trim()) title = m[1]!.trim();
2169
+ for (let m; (m = oscTitleRe.exec(text));) if (m[1]!.trim()) title = m[1]!.trim();
2164
2170
  // Defense-in-depth: this title is remote-controlled text (an agent sets its
2165
2171
  // own terminal title) that the web console renders. The console escapes it,
2166
2172
  // but strip C0/C1 control bytes and cap the length at the SOURCE too, so a
@@ -2615,12 +2621,16 @@ export async function cmdServe(rest: string[]): Promise<number> {
2615
2621
  await unlink(capFile(pid, `${daemonTag}:${viewer}`)).catch(() => {});
2616
2622
  };
2617
2623
  // Read every live cap for a pid across ALL daemons; prune expired files.
2618
- const readSharedCaps = async (pid: number): Promise<SizeCap[]> => {
2624
+ // `local` = the operator terminal's cap (role "local"), which bounds the nego floor.
2625
+ const readSharedCaps = async (
2626
+ pid: number,
2627
+ ): Promise<{ caps: SizeCap[]; local: SizeCap | null }> => {
2628
+ let local: SizeCap | null = null;
2619
2629
  let files: string[];
2620
2630
  try {
2621
2631
  files = await readdir(capsDir(pid));
2622
2632
  } catch {
2623
- return [];
2633
+ return { caps: [], local };
2624
2634
  }
2625
2635
  const now = Date.now();
2626
2636
  const caps: SizeCap[] = [];
@@ -2635,11 +2645,12 @@ export async function cmdServe(rest: string[]): Promise<number> {
2635
2645
  }
2636
2646
  const cap = sanitizeCap({ cols: Number(parts[0]), rows: Number(parts[1]) });
2637
2647
  if (cap) caps.push(cap);
2648
+ if (cap && parts[3] === "local") local = cap;
2638
2649
  } catch {
2639
2650
  /* unreadable/racing — skip */
2640
2651
  }
2641
2652
  }
2642
- return caps;
2653
+ return { caps, local };
2643
2654
  };
2644
2655
 
2645
2656
  // ── PTY size negotiation — tmux's "smallest client wins" ──────────────────
@@ -2691,8 +2702,8 @@ export async function cmdServe(rest: string[]): Promise<number> {
2691
2702
  negoTimers.delete(pid);
2692
2703
  // Negotiate over the SHARED cap store — every daemon's viewers (+ the local
2693
2704
  // tty cap, 3b) — so all daemons compute the same min and converge.
2694
- const caps = await readSharedCaps(pid);
2695
- const eff = negotiateSize(caps);
2705
+ const { caps, local } = await readSharedCaps(pid);
2706
+ const eff = negotiateSize(caps, local);
2696
2707
  const file = winsizePathFor(pid);
2697
2708
  const prev = negoApplied.get(pid);
2698
2709
  try {
@@ -4191,30 +4202,8 @@ export async function cmdServe(rest: string[]): Promise<number> {
4191
4202
  return new Response("force-kill unsupported on a Windows serve", { status: 501 });
4192
4203
  try {
4193
4204
  const record = await resolveOne(keyword, defaultOpts({ all: true }));
4194
- const killed: string[] = [];
4195
- const sig = (target: number, label: string) => {
4196
- if (!target || target <= 1) return;
4197
- try {
4198
- process.kill(target, "SIGKILL");
4199
- killed.push(label);
4200
- } catch {
4201
- /* ESRCH: already gone */
4202
- }
4203
- };
4204
- // Whole process group first (kills children too), then the pids directly in
4205
- // case they aren't group leaders.
4206
- const pgid = await pgidForWrapper(record.wrapper_pid ?? 0);
4207
- if (pgid && pgid > 1) {
4208
- try {
4209
- process.kill(-pgid, "SIGKILL");
4210
- killed.push(`group ${pgid}`);
4211
- } catch {
4212
- /* group already gone */
4213
- }
4214
- }
4215
- sig(record.pid, `pid ${record.pid}`);
4216
- if (record.wrapper_pid && record.wrapper_pid !== record.pid)
4217
- sig(record.wrapper_pid, `wrapper ${record.wrapper_pid}`);
4205
+ const { forceKill, forceKillTargets } = await import("./forceKill.ts");
4206
+ const { killed } = forceKill(await forceKillTargets(record));
4218
4207
  await updateGlobalPidStatus(record.pid, {
4219
4208
  status: "exited",
4220
4209
  exit_reason: "force-killed via console",
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import { daemonShareRuntime, planRustServe } from "./serveRust.ts";
3
+ import { planDaemonArgs } from "./shareCore.ts";
3
4
 
4
5
  // `ay serve` runs the Rust daemon (`ayrs serve`) by default, like `ay <cli>`
5
6
  // runs the Rust agent runtime — but only for invocations ayrs can express.
@@ -54,17 +55,38 @@ describe("planRustServe", () => {
54
55
  }
55
56
  });
56
57
 
58
+ it("drops --http and a loopback --host next to --port: ayrs's port IS that console", () => {
59
+ // What `ay share webrtc` registers over an HTTP daemon.
60
+ expect(planRustServe(["--port", "7432", "--http", "--webrtc"], env)).toEqual({
61
+ kind: "rust",
62
+ argv: ["serve", "--port", "7432", "--webrtc"],
63
+ });
64
+ expect(
65
+ planRustServe(["--webrtc", "--http", "--host", "127.0.0.1", "--port=7432"], env),
66
+ ).toEqual({ kind: "rust", argv: ["serve", "--webrtc", "--port", "7432"] });
67
+ expect(planRustServe(["--host=localhost", "--port", "1"], env)).toEqual({
68
+ kind: "rust",
69
+ argv: ["serve", "--port", "1"],
70
+ });
71
+ });
72
+
57
73
  it("falls back, naming the flag, on anything ayrs cannot express", () => {
58
74
  expect(planRustServe(["--share"], env)).toMatchObject({ kind: "ts", reason: "--share" });
75
+ // --http without a port is the Portless console, which ayrs lacks.
59
76
  expect(planRustServe(["--webrtc", "--http"], env)).toMatchObject({
60
77
  kind: "ts",
61
- reason: "--http",
78
+ reason: "--http without --port (Portless HTTPS console)",
62
79
  });
63
80
  expect(planRustServe(["-d", "--webrtc"], env)).toMatchObject({ kind: "ts", reason: "-d" });
81
+ // ayrs listens on loopback only.
64
82
  expect(planRustServe(["--port", "0", "--host", "0.0.0.0"], env)).toMatchObject({
65
83
  kind: "ts",
66
- reason: "--host",
84
+ reason: "--host 0.0.0.0 (ayrs listens on loopback only)",
67
85
  });
86
+ expect(
87
+ planRustServe(["--webrtc", "--http", "--host", "100.64.0.1", "--port", "7432"], env),
88
+ ).toMatchObject({ kind: "ts", reason: "--host 100.64.0.1 (ayrs listens on loopback only)" });
89
+ expect(planRustServe(["--host", "127.0.0.1"], env)).toMatchObject({ kind: "ts" });
68
90
  // Any room link spelling reaches ayrs as webrtc://; a non-link stays on TS.
69
91
  expect(planRustServe(["--webrtc", "https://agent-yes.com/room/#room=r1&s=e1.ab"], env)).toEqual(
70
92
  { kind: "rust", argv: ["serve", "--webrtc", "webrtc://r1:e1.ab@s.agent-yes.com"] },
@@ -113,6 +135,11 @@ describe("daemonShareRuntime", () => {
113
135
  expect(daemonShareRuntime(["--webrtc"], ayrs, env)).toBe("rust");
114
136
  expect(daemonShareRuntime(["--webrtc", "--sighost", "s.example"], ayrs, env)).toBe("rust");
115
137
  expect(daemonShareRuntime(["--webrtc", "--port", "0"], ayrs, env)).toBe("rust");
138
+ // `ay share webrtc` over an HTTP daemon keeps HTTP with --http; that must
139
+ // not pin the room to the TypeScript host.
140
+ expect(daemonShareRuntime(planDaemonArgs(["--port", "9000"], "webrtc"), ayrs, env)).toBe(
141
+ "rust",
142
+ );
116
143
  });
117
144
 
118
145
  it("is ts whenever cmdServe would fall back to the TypeScript host", () => {
package/ts/serveRust.ts CHANGED
@@ -16,6 +16,10 @@
16
16
  * join-secret (print the link + join secret members need; ayrs only)
17
17
  * --port <n> / --port=<n> (loopback HTTP console; 0 = free port)
18
18
  * --sighost <host> / --sighost=<host>
19
+ * --http (with --port: ayrs's --port listener IS the HTTP
20
+ * console, so the flag is implied and dropped)
21
+ * --host <loopback> (with --port: 127.0.0.1 / localhost / ::1 — ayrs
22
+ * binds loopback anyway, so the flag is dropped)
19
23
  *
20
24
  * What stays on TypeScript, with the reason printed:
21
25
  * - `--no-rust` / AGENT_YES_NO_RUST=1 (explicit opt-out)
@@ -24,14 +28,15 @@
24
28
  * - the daemon subcommands (install/uninstall/status/logs/start/stop/
25
29
  * healthcheck) and -d/--daemon: ayrs has its own OS-supervisor install and
26
30
  * the two must not manage each other's registration
27
- * - --share (http+webrtc over Portless), --http, --host, --token, --tls-*,
31
+ * - --share (http+webrtc over Portless), --http without --port (Portless),
32
+ * a non-loopback --host (ayrs listens on loopback only), --token, --tls-*,
28
33
  * --local
29
34
  */
30
35
 
31
36
  /** Subcommands `ay serve` dispatches before flag parsing — never delegated. */
32
37
  import { toWebrtcUrl } from "./webrtcLink.ts";
33
38
 
34
- const SERVE_SUBCOMMANDS = new Set([
39
+ export const SERVE_SUBCOMMANDS = new Set([
35
40
  "install",
36
41
  "uninstall",
37
42
  "status",
@@ -41,6 +46,8 @@ const SERVE_SUBCOMMANDS = new Set([
41
46
  "healthcheck",
42
47
  ]);
43
48
 
49
+ const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "::1"]);
50
+
44
51
  export type RustServePlan =
45
52
  | { kind: "rust"; argv: string[] }
46
53
  | { kind: "ts"; reason: string; rest: string[] }
@@ -80,6 +87,9 @@ export function planRustServe(
80
87
  return { kind: "ts", reason: `\`ay serve ${first}\``, rest };
81
88
  }
82
89
 
90
+ // `--http`/`--host` only map onto ayrs next to an explicit port: without
91
+ // one, TypeScript's HTTP console runs behind Portless, which ayrs lacks.
92
+ const hasPort = rest.some((a) => a === "--port" || a.startsWith("--port="));
83
93
  const argv = ["serve"];
84
94
  for (let i = 0; i < rest.length; i++) {
85
95
  const a = rest[i]!;
@@ -122,6 +132,21 @@ export function planRustServe(
122
132
  argv.push("--port", v);
123
133
  break;
124
134
  }
135
+ case "--http": {
136
+ if (inline !== undefined || !hasPort)
137
+ return { kind: "ts", reason: `${a} without --port (Portless HTTPS console)`, rest };
138
+ break; // ayrs's --port listener is the HTTP console
139
+ }
140
+ case "--host": {
141
+ const v = takeNext();
142
+ if (v === undefined || !LOOPBACK_HOSTS.has(v) || !hasPort)
143
+ return {
144
+ kind: "ts",
145
+ reason: `--host ${v ?? "(missing)"} (ayrs listens on loopback only)`,
146
+ rest,
147
+ };
148
+ break; // ayrs binds 127.0.0.1 already
149
+ }
125
150
  case "--sighost": {
126
151
  const v = takeNext();
127
152
  if (v === undefined) return { kind: "ts", reason: "--sighost (missing value)", rest };