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,125 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import * as fs from "fs/promises";
3
+ import path from "path";
4
+ import { tmpdir } from "os";
5
+ import {
6
+ appendGlobalPid,
7
+ gcLogs,
8
+ getGlobalPidIndexPath,
9
+ maybeCompactGlobalPids,
10
+ pruneOldLogs,
11
+ readGlobalPids,
12
+ sweepOrphanLogs,
13
+ updateGlobalPidStatus,
14
+ type GlobalPidRecord,
15
+ } from "./globalPidIndex.ts";
16
+
17
+ describe("registry recovery and orphan log retention", () => {
18
+ let root: string;
19
+ let cwd: string;
20
+ const record = (over: Partial<GlobalPidRecord> = {}): GlobalPidRecord => ({
21
+ pid: 1111,
22
+ cli: "claude",
23
+ prompt: null,
24
+ cwd: "",
25
+ log_file: null,
26
+ status: "exited",
27
+ started_at: 1,
28
+ exit_code: 0,
29
+ exit_reason: null,
30
+ ...over,
31
+ });
32
+ beforeEach(async () => {
33
+ cwd = process.cwd();
34
+ root = await fs.realpath(await fs.mkdtemp(path.join(tmpdir(), "ay-index-edges-")));
35
+ process.chdir(root);
36
+ vi.stubEnv("AGENT_YES_HOME", path.join(root, "state"));
37
+ vi.spyOn(process, "kill").mockImplementation((pid) => {
38
+ if (pid === 2222) return true;
39
+ throw Object.assign(new Error("gone"), { code: "ESRCH" });
40
+ });
41
+ });
42
+ afterEach(async () => {
43
+ vi.restoreAllMocks();
44
+ vi.unstubAllEnvs();
45
+ process.chdir(cwd);
46
+ await fs.rm(root, { recursive: true, force: true });
47
+ });
48
+ async function index(rows: GlobalPidRecord[]) {
49
+ const file = getGlobalPidIndexPath();
50
+ await fs.mkdir(path.dirname(file), { recursive: true });
51
+ await fs.writeFile(file, rows.map((r) => JSON.stringify(r)).join("\n"));
52
+ }
53
+ async function oldLog(name: string) {
54
+ const file = path.join(root, ".agent-yes", name);
55
+ await fs.mkdir(path.dirname(file), { recursive: true });
56
+ await fs.writeFile(file, "old log");
57
+ await fs.utimes(file, new Date(0), new Date(0));
58
+ return file;
59
+ }
60
+ it("does not compact missing or unreadable registries", async () => {
61
+ await expect(maybeCompactGlobalPids()).resolves.toBeUndefined();
62
+ await fs.mkdir(getGlobalPidIndexPath(), { recursive: true });
63
+ await expect(maybeCompactGlobalPids()).resolves.toBeUndefined();
64
+ expect(await pruneOldLogs(1)).toBe(0);
65
+ await expect(readGlobalPids()).rejects.toThrow();
66
+ await expect(updateGlobalPidStatus(1111, { status: "idle" })).resolves.toBeUndefined();
67
+ await expect(appendGlobalPid(record())).resolves.toBeUndefined();
68
+ });
69
+ it("ignores malformed records and updates for unknown processes", async () => {
70
+ await index([]);
71
+ await fs.writeFile(getGlobalPidIndexPath(), 'not-json\n{"cli":"claude"}\n');
72
+ expect(await readGlobalPids()).toEqual([]);
73
+ await updateGlobalPidStatus(1111, { status: "idle" });
74
+ expect(await readGlobalPids()).toEqual([]);
75
+ });
76
+ it("compacts an all-exited registry to an empty file", async () => {
77
+ await index(Array.from({ length: 500 }, () => record()));
78
+ await maybeCompactGlobalPids();
79
+ expect(await fs.readFile(getGlobalPidIndexPath(), "utf8")).toBe("");
80
+ });
81
+ it("retains live sessions, null logs and sessions with no timestamp", async () => {
82
+ const file = await oldLog("1111.raw.log");
83
+ const rows = [
84
+ record({ started_at: undefined as unknown as number, log_file: file }),
85
+ record({ pid: 2222, status: "active", log_file: file }),
86
+ record({ pid: 3333 }),
87
+ ];
88
+ await index(rows);
89
+ expect(await pruneOldLogs(1000)).toBe(0);
90
+ expect(await fs.readFile(file, "utf8")).toBe("old log");
91
+ });
92
+ it("sweeps only old orphan pid logs while retaining live, recent and unrelated files", async () => {
93
+ const old = await oldLog("1111.raw.log");
94
+ const live = await oldLog("2222.log");
95
+ const zero = await oldLog("0.log");
96
+ const unrelated = await oldLog("inbox.jsonl");
97
+ const recent = await oldLog("3333.debug.log");
98
+ await fs.utimes(recent, new Date(), new Date());
99
+ await fs.mkdir(path.join(root, ".agent-yes", "4444.log"));
100
+ await index([record({ cwd: path.join(root, "missing") })]);
101
+ const result = await sweepOrphanLogs(1000);
102
+ expect(result.removed).toEqual([old]);
103
+ expect(result.freedBytes).toBe(7);
104
+ for (const file of [live, zero, unrelated, recent])
105
+ expect(await fs.readFile(file, "utf8")).toBe("old log");
106
+ });
107
+ it("collects orphan logs even when the registry is unreadable", async () => {
108
+ const old = await oldLog("1111.lines.log");
109
+ await fs.mkdir(getGlobalPidIndexPath(), { recursive: true });
110
+ expect((await sweepOrphanLogs(1)).removed).toEqual([old]);
111
+ });
112
+ it("combines index retention with orphan discovery without counting a file twice", async () => {
113
+ const indexed = await oldLog("1111.raw.log");
114
+ const orphan = await oldLog("3333.log");
115
+ await index([record({ cwd: root, log_file: indexed })]);
116
+ const result = await gcLogs(1);
117
+ expect(new Set(result.removed)).toEqual(new Set([indexed, orphan]));
118
+ expect(result.freedBytes).toBe(14);
119
+ });
120
+ it("uses the configured retention period for the default sweep", async () => {
121
+ vi.stubEnv("AGENT_YES_LOG_RETENTION_DAYS", "1");
122
+ const file = await oldLog("1111.log");
123
+ expect((await gcLogs()).removed).toContain(file);
124
+ });
125
+ });
@@ -107,8 +107,12 @@ async function withLock<R>(file: string, fn: () => Promise<R>): Promise<R> {
107
107
  await mkdir(dir, { recursive: true });
108
108
  let release: (() => Promise<void>) | undefined;
109
109
  try {
110
- release = await lock(dir, {
111
- lockfilePath: file + ".lock",
110
+ // The registry is keyed by the first argument, so key it by the lockfile's
111
+ // own path: a shared directory made unrelated locks collide (#516).
112
+ const lockfilePath = file + ".lock";
113
+ release = await lock(lockfilePath, {
114
+ realpath: false,
115
+ lockfilePath,
112
116
  retries: { retries: 5, minTimeout: 50, maxTimeout: 500 },
113
117
  });
114
118
  return await fn();
package/ts/index.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { ConptyModeFilter } from "./conptyModeFilter.ts";
1
2
  import { randomBytes } from "node:crypto";
2
3
  import { execaCommandSync, parseCommandString } from "execa";
3
4
  import { fromWritable } from "from-node-stream";
@@ -574,7 +575,16 @@ export default async function agentYes({
574
575
 
575
576
  // Attach data handler IMMEDIATELY after spawn to avoid losing early PTY output.
576
577
  // node-pty emits 'data' events eagerly — if no listener is attached, events are lost.
577
- function onData(data: string) {
578
+ let modeFilter = new ConptyModeFilter();
579
+ let modeFilterPid = shell.pid;
580
+ function onData(data: string, final = false) {
581
+ if (modeFilterPid !== shell.pid) {
582
+ modeFilter = new ConptyModeFilter();
583
+ modeFilterPid = shell.pid;
584
+ }
585
+ if (process.platform === "win32")
586
+ data = modeFilter.feed(data) + (final ? modeFilter.finish() : "");
587
+ if (!data) return;
578
588
  const currentPid = shell.pid;
579
589
  xtermProxy.write(data);
580
590
  globalAgentRegistry.appendStdout(currentPid, data);
@@ -642,6 +652,7 @@ export default async function agentYes({
642
652
  robust,
643
653
  autoYes,
644
654
  });
655
+ ctx.screen = () => xtermProxy.tail(24);
645
656
 
646
657
  // Register agent in global registry (non-blocking)
647
658
  try {
@@ -679,6 +690,7 @@ export default async function agentYes({
679
690
  const pendingExitCode = Promise.withResolvers<number | null>();
680
691
 
681
692
  shell.onExit(async function onExit({ exitCode }) {
693
+ onData("", true); // Flush an incomplete final control sequence before a restart.
682
694
  const exitedPid = shell.pid; // Capture PID immediately before any shell reassignment
683
695
  // Reap the exited agent's process group. The PTY child is a session/group
684
696
  // leader, so a `yes | cmd` (or any descendant) it leaked shares its pgid even
@@ -0,0 +1,99 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { interruptBeforeSend, interruptScreenState, type InterruptState } from "./interruptSend.ts";
3
+
4
+ describe("interrupt screen classification", () => {
5
+ const cfg = { working: [/esc to (interrupt|cancel)/g], needsInput: [/❯ 1\. Allow/g] };
6
+ it("prioritizes confirmation prompts over lingering busy chrome", () => {
7
+ for (const menu of [
8
+ "❯ 1. Allow",
9
+ "› 2. Deny",
10
+ "> 1. Yes",
11
+ "┃ ctrl+k approve · alt+j manage",
12
+ "┃ task needs approval",
13
+ ])
14
+ expect(interruptScreenState("claude", ["esc to interrupt", menu], cfg)).toBe("permission");
15
+ });
16
+ it("recognizes busy, idle and unknown screens without stateful regexp matches", () => {
17
+ for (let i = 0; i < 2; i++)
18
+ expect(interruptScreenState("codex", ["esc to interrupt", "›"], cfg)).toBe("busy");
19
+ expect(interruptScreenState("agy", [">"], {})).toBe("idle");
20
+ expect(interruptScreenState("claude", ["❯ draft"], {})).toBe("idle");
21
+ expect(interruptScreenState("codex", ["›"], {})).toBe("idle");
22
+ expect(interruptScreenState("codex", ["> quoted transcript"], {})).toBe("unknown");
23
+ expect(interruptScreenState("agy", [], {})).toBe("unknown");
24
+ expect(
25
+ interruptScreenState("claude", ["confirm operation"], { needsInput: [/confirm operation/] }),
26
+ ).toBe("permission");
27
+ });
28
+ });
29
+
30
+ describe("interrupt before delivery", () => {
31
+ function fixture(states: InterruptState[]) {
32
+ const events: string[] = [];
33
+ return {
34
+ events,
35
+ deps: {
36
+ readState: async () => {
37
+ const state = states.length > 1 ? states.shift()! : states[0]!;
38
+ events.push(state);
39
+ return state;
40
+ },
41
+ write: async (code: string) => {
42
+ events.push(code);
43
+ },
44
+ sleep: async (ms: number) => {
45
+ events.push(`wait ${ms}`);
46
+ },
47
+ },
48
+ };
49
+ }
50
+ it.each(["claude", "codex", "agy"])(
51
+ "cancels %s once and waits for the idle prompt before delivery",
52
+ async (cli) => {
53
+ const { events, deps } = fixture(["busy", "busy", "unknown", "idle"]);
54
+ expect(await interruptBeforeSend(cli, deps)).toBe("interrupted");
55
+ events.push("paste message");
56
+ expect(events).toEqual([
57
+ "busy",
58
+ "\x1b",
59
+ "wait 100",
60
+ "busy",
61
+ "wait 100",
62
+ "unknown",
63
+ "wait 100",
64
+ "idle",
65
+ "paste message",
66
+ ]);
67
+ },
68
+ );
69
+ it.each(["idle", "permission", "unknown"] as const)(
70
+ "does not inject a cancellation key at %s",
71
+ async (state) => {
72
+ const { events, deps } = fixture([state]);
73
+ expect(await interruptBeforeSend("claude", deps)).toBe(state);
74
+ expect(events).toEqual([state]);
75
+ },
76
+ );
77
+ it("stops waiting when a permission prompt appears during cancellation", async () => {
78
+ const { events, deps } = fixture(["busy", "permission"]);
79
+ expect(await interruptBeforeSend("agy", deps)).toBe("permission");
80
+ expect(events.filter((event) => event === "\x1b")).toHaveLength(1);
81
+ });
82
+ it("does not guess an unsupported CLI's key", async () => {
83
+ const { events, deps } = fixture(["busy"]);
84
+ expect(await interruptBeforeSend("other", deps)).toBe("unsupported");
85
+ expect(events).toEqual([]);
86
+ });
87
+ it("times out without delivering or repeatedly cancelling", async () => {
88
+ const { events, deps } = fixture(["busy"]);
89
+ await expect(interruptBeforeSend("codex", deps, 200)).rejects.toThrow("message was not sent");
90
+ expect(events).toEqual(["busy", "\x1b", "wait 100", "busy", "wait 100", "busy"]);
91
+ });
92
+ it("propagates an IPC failure before delivery", async () => {
93
+ const { deps } = fixture(["busy"]);
94
+ deps.write = async () => {
95
+ throw new Error("broken FIFO");
96
+ };
97
+ await expect(interruptBeforeSend("agy", deps)).rejects.toThrow("broken FIFO");
98
+ });
99
+ });
@@ -0,0 +1,99 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { interruptBeforeSend, interruptScreenState, type InterruptState } from "./interruptSend.ts";
3
+
4
+ describe("interrupt screen classification", () => {
5
+ const cfg = { working: [/esc to (interrupt|cancel)/g], needsInput: [/❯ 1\. Allow/g] };
6
+ it("prioritizes confirmation prompts over lingering busy chrome", () => {
7
+ for (const menu of [
8
+ "❯ 1. Allow",
9
+ "› 2. Deny",
10
+ "> 1. Yes",
11
+ "┃ ctrl+k approve · alt+j manage",
12
+ "┃ task needs approval",
13
+ ])
14
+ expect(interruptScreenState("claude", ["esc to interrupt", menu], cfg)).toBe("permission");
15
+ });
16
+ it("recognizes busy, idle and unknown screens without stateful regexp matches", () => {
17
+ for (let i = 0; i < 2; i++)
18
+ expect(interruptScreenState("codex", ["esc to interrupt", "›"], cfg)).toBe("busy");
19
+ expect(interruptScreenState("agy", [">"], {})).toBe("idle");
20
+ expect(interruptScreenState("claude", ["❯ draft"], {})).toBe("idle");
21
+ expect(interruptScreenState("codex", ["›"], {})).toBe("idle");
22
+ expect(interruptScreenState("codex", ["> quoted transcript"], {})).toBe("unknown");
23
+ expect(interruptScreenState("agy", [], {})).toBe("unknown");
24
+ expect(
25
+ interruptScreenState("claude", ["confirm operation"], { needsInput: [/confirm operation/] }),
26
+ ).toBe("permission");
27
+ });
28
+ });
29
+
30
+ describe("interrupt before delivery", () => {
31
+ function fixture(states: InterruptState[]) {
32
+ const events: string[] = [];
33
+ return {
34
+ events,
35
+ deps: {
36
+ readState: async () => {
37
+ const state = states.length > 1 ? states.shift()! : states[0]!;
38
+ events.push(state);
39
+ return state;
40
+ },
41
+ write: async (code: string) => {
42
+ events.push(code);
43
+ },
44
+ sleep: async (ms: number) => {
45
+ events.push(`wait ${ms}`);
46
+ },
47
+ },
48
+ };
49
+ }
50
+ it.each(["claude", "codex", "agy"])(
51
+ "cancels %s once and waits for the idle prompt before delivery",
52
+ async (cli) => {
53
+ const { events, deps } = fixture(["busy", "busy", "unknown", "idle"]);
54
+ expect(await interruptBeforeSend(cli, deps)).toBe("interrupted");
55
+ events.push("paste message");
56
+ expect(events).toEqual([
57
+ "busy",
58
+ "\x1b",
59
+ "wait 100",
60
+ "busy",
61
+ "wait 100",
62
+ "unknown",
63
+ "wait 100",
64
+ "idle",
65
+ "paste message",
66
+ ]);
67
+ },
68
+ );
69
+ it.each(["idle", "permission", "unknown"] as const)(
70
+ "does not inject a cancellation key at %s",
71
+ async (state) => {
72
+ const { events, deps } = fixture([state]);
73
+ expect(await interruptBeforeSend("claude", deps)).toBe(state);
74
+ expect(events).toEqual([state]);
75
+ },
76
+ );
77
+ it("stops waiting when a permission prompt appears during cancellation", async () => {
78
+ const { events, deps } = fixture(["busy", "permission"]);
79
+ expect(await interruptBeforeSend("agy", deps)).toBe("permission");
80
+ expect(events.filter((event) => event === "\x1b")).toHaveLength(1);
81
+ });
82
+ it("does not guess an unsupported CLI's key", async () => {
83
+ const { events, deps } = fixture(["busy"]);
84
+ expect(await interruptBeforeSend("other", deps)).toBe("unsupported");
85
+ expect(events).toEqual([]);
86
+ });
87
+ it("times out without delivering or repeatedly cancelling", async () => {
88
+ const { events, deps } = fixture(["busy"]);
89
+ await expect(interruptBeforeSend("codex", deps, 200)).rejects.toThrow("message was not sent");
90
+ expect(events).toEqual(["busy", "\x1b", "wait 100", "busy", "wait 100", "busy"]);
91
+ });
92
+ it("propagates an IPC failure before delivery", async () => {
93
+ const { deps } = fixture(["busy"]);
94
+ deps.write = async () => {
95
+ throw new Error("broken FIFO");
96
+ };
97
+ await expect(interruptBeforeSend("agy", deps)).rejects.toThrow("broken FIFO");
98
+ });
99
+ });
@@ -0,0 +1,51 @@
1
+ export type InterruptState = "busy" | "idle" | "permission" | "unknown";
2
+
3
+ /** Permission prompts take precedence over lingering busy chrome. */
4
+ export function interruptScreenState(
5
+ cli: string,
6
+ lines: string[],
7
+ cfg: { working?: RegExp[]; needsInput?: RegExp[] },
8
+ ): InterruptState {
9
+ const text = lines.join("\n");
10
+ const matches = (patterns: RegExp[] = []) =>
11
+ patterns.some((re) => new RegExp(re.source, re.flags.replace(/[gy]/g, "")).test(text));
12
+ if (
13
+ matches(cfg.needsInput) ||
14
+ lines.some((line) =>
15
+ /^\s*[│┃]?\s*(?:[❯›>]\s*\d+\.\s|.*\bctrl\+k\s+approve\b|.*\bneeds approval\b)/i.test(line),
16
+ )
17
+ )
18
+ return "permission";
19
+ if (matches(cfg.working)) return "busy";
20
+ const prompt = cli === "agy" ? /^\s*>($|\s)/u : /^\s*[❯›]($|\s)/u;
21
+ return lines.some((line) => prompt.test(line)) ? "idle" : "unknown";
22
+ }
23
+
24
+ export type InterruptResult = "interrupted" | "idle" | "permission" | "unsupported" | "unknown";
25
+
26
+ /** Caller holds the input lock through cancellation, idle detection and delivery. */
27
+ export async function interruptBeforeSend(
28
+ cli: string,
29
+ deps: {
30
+ readState: () => Promise<InterruptState>;
31
+ write: (code: string) => Promise<void>;
32
+ sleep: (ms: number) => Promise<void>;
33
+ },
34
+ timeoutMs = 8000,
35
+ ): Promise<InterruptResult> {
36
+ if (!["claude", "codex", "agy"].includes(cli)) return "unsupported";
37
+ const before = await deps.readState();
38
+ if (before !== "busy") return before;
39
+ // One Escape cancels the turn. Never send Ctrl+C (which can quit a CLI),
40
+ // Alt+M (which submits existing input), or a second Escape at an idle draft.
41
+ await deps.write("\x1b");
42
+ for (let elapsed = 0; elapsed < timeoutMs; elapsed += 100) {
43
+ await deps.sleep(100);
44
+ const state = await deps.readState();
45
+ if (state === "idle") return "interrupted";
46
+ if (state === "permission") return "permission";
47
+ }
48
+ throw new Error(
49
+ "ay send: --interrupt timed out waiting for the idle prompt; message was not sent",
50
+ );
51
+ }
@@ -0,0 +1,49 @@
1
+ // #516: proper-lockfile keys its in-process registry by the first argument to
2
+ // lock(). Locking a shared directory (with a per-file lockfilePath) made two
3
+ // stores in one directory overwrite each other's entry, and the orphaned
4
+ // refresh timer of the first then threw from a timer callback. Each store must
5
+ // lock its own file instead.
6
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
7
+ import { mkdir, rm } from "fs/promises";
8
+ import os from "os";
9
+ import path from "path";
10
+ import { JsonlStore } from "./JsonlStore";
11
+
12
+ const DIR = path.join(os.tmpdir(), `lock-registry-test-${process.pid}`);
13
+
14
+ describe("lock registry (#516)", () => {
15
+ beforeEach(async () => {
16
+ await rm(DIR, { recursive: true, force: true });
17
+ await mkdir(DIR, { recursive: true });
18
+ });
19
+ afterEach(async () => {
20
+ vi.useRealTimers();
21
+ await rm(DIR, { recursive: true, force: true }).catch(() => {});
22
+ });
23
+
24
+ it("two stores sharing a directory do not break each other's lock refresh", async () => {
25
+ const uncaught: unknown[] = [];
26
+ const onUncaught = (e: unknown) => void uncaught.push(e);
27
+ process.on("uncaughtException", onUncaught);
28
+ try {
29
+ const a = new JsonlStore<{ n: number }>(path.join(DIR, "a.jsonl"));
30
+ const b = new JsonlStore<{ n: number }>(path.join(DIR, "b.jsonl"));
31
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
32
+ // Hold A's lock while B takes and releases its own in the same directory.
33
+ let finishA!: () => void;
34
+ const holdA = new Promise<void>((r) => (finishA = r));
35
+ const aBusy = (a as unknown as { withLock(f: () => Promise<void>): Promise<void> }).withLock(
36
+ () => holdA,
37
+ );
38
+ await vi.advanceTimersByTimeAsync(10);
39
+ await b.append({ n: 1 });
40
+ // Let A's mtime-refresh timer fire (stale/2 = 5 s) after B released.
41
+ await vi.advanceTimersByTimeAsync(6_000);
42
+ finishA();
43
+ await aBusy;
44
+ expect(uncaught).toEqual([]);
45
+ } finally {
46
+ process.off("uncaughtException", onUncaught);
47
+ }
48
+ });
49
+ });
@@ -0,0 +1,58 @@
1
+ import { appendFileSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "fs";
2
+ import { tmpdir } from "os";
3
+ import path from "path";
4
+ import { afterAll, describe, expect, it } from "vitest";
5
+ import {
6
+ enableRenderDiskCache,
7
+ extractTaskCounts,
8
+ renderLogTailLines,
9
+ resetRenderDiskCache,
10
+ saveRenderDisk,
11
+ } from "./subcommands.ts";
12
+
13
+ // `ay ls`'s cross-run render cache: persisted under AGENT_YES_HOME, keyed by the log's state, never stale.
14
+ const home = mkdtempSync(path.join(tmpdir(), "ay-ls-cache-"));
15
+ const prevHome = process.env.AGENT_YES_HOME;
16
+ process.env.AGENT_YES_HOME = home;
17
+ enableRenderDiskCache(); // the destination is fixed here, inside the temp home
18
+ afterAll(() => {
19
+ resetRenderDiskCache(); // forget it without writing; the exit handler goes too
20
+ if (prevHome === undefined) delete process.env.AGENT_YES_HOME;
21
+ else process.env.AGENT_YES_HOME = prevHome;
22
+ });
23
+
24
+ const file = path.join(home, "cache", "ls-render.json");
25
+ const plant = (pick: (key: string) => boolean, value: unknown) => {
26
+ const saved = JSON.parse(readFileSync(file, "utf8")) as Record<string, unknown>;
27
+ for (const k of Object.keys(saved)) if (pick(k)) saved[k] = value;
28
+ writeFileSync(file, JSON.stringify(saved));
29
+ };
30
+ const freshRun = () => {
31
+ // a new `ay ls` process: nothing in memory, the file read again
32
+ resetRenderDiskCache();
33
+ enableRenderDiskCache();
34
+ };
35
+
36
+ describe("ls render disk cache", () => {
37
+ it("is read by the next run for an unchanged log, and never used for a changed one", async () => {
38
+ const log = path.join(home, "agent.log");
39
+ writeFileSync(log, "first line\r\nsecond line\r\n");
40
+ expect(await renderLogTailLines(log, 40)).toEqual(["first line", "second line"]);
41
+ expect(await extractTaskCounts(log)).toBeNull();
42
+ saveRenderDisk();
43
+ // Windows reports 0o666 for any writable file (no owner/group/other bits), so the mode is checked elsewhere
44
+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);
45
+
46
+ // a marker planted in the saved file comes back: the next run read the disk, it did not re-render
47
+ plant((k) => !k.startsWith("tasks"), ["from disk"]);
48
+ plant((k) => k.startsWith("tasks"), { done: 1, total: 2 });
49
+ freshRun();
50
+ expect(await renderLogTailLines(log, 40)).toEqual(["from disk"]);
51
+ expect(await extractTaskCounts(log)).toEqual({ done: 1, total: 2 });
52
+
53
+ // the log changes: new keys, so the real screen is rendered again
54
+ appendFileSync(log, "third line\r\n");
55
+ expect(await renderLogTailLines(log, 40)).toEqual(["first line", "second line", "third line"]);
56
+ expect(await extractTaskCounts(log)).toBeNull();
57
+ });
58
+ });
@@ -0,0 +1,23 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { classifyNeedsInput, parseMenu } from "./needsInput.ts";
3
+
4
+ describe("permission menu parsing edges", () => {
5
+ it("does not leak state from global or sticky configuration expressions", () => {
6
+ const pattern = /❯ 2\./gy;
7
+ pattern.lastIndex = 20;
8
+ for (let i = 0; i < 2; i++)
9
+ expect(classifyNeedsInput(["❯ 2. Deny"], { needsInput: [pattern] })).not.toBeNull();
10
+ });
11
+ it("does not treat a multiline-only match or non-numbered confirmation as a navigable menu", () => {
12
+ expect(parseMenu(["Confirm", "operation"], { needsInput: [/Confirm\noperation/] })).toBeNull();
13
+ expect(parseMenu(["Confirm operation"], { needsInput: [/Confirm operation/] })).toBeNull();
14
+ expect(classifyNeedsInput(["idle"], {})).toBeNull();
15
+ });
16
+ it("collects each option once and retains a cursor number from a custom menu layout", () => {
17
+ const result = parseMenu(["1. Allow", "1. Allow", "selection: 3. Deny"], {
18
+ needsInput: [/selection: 3\./],
19
+ });
20
+ expect(result?.cursor).toBe(3);
21
+ expect(result?.options).toEqual([1, 3]);
22
+ });
23
+ });
@@ -40,6 +40,12 @@ export function parseCliArgs(argv: string[], supportedClis?: readonly string[])
40
40
  "Run the agent in the foreground even when nested inside another agent (disables fork-by-default; also AGENT_YES_ATTACH=1).",
41
41
  alias: "foreground",
42
42
  })
43
+ .option("detach", {
44
+ type: "boolean",
45
+ default: false,
46
+ description:
47
+ "Start the agent in the background and return immediately (prints its pid and how to drive it) — e.g. when spawning over ssh. Rust runtime only.",
48
+ })
43
49
  .option("logFile", {
44
50
  type: "string",
45
51
  description: "Rendered log file to write to.",
@@ -349,6 +355,7 @@ export function parseCliArgs(argv: string[], supportedClis?: readonly string[])
349
355
  queue: parsedArgv.queue,
350
356
  robust: parsedArgv.robust,
351
357
  attach: parsedArgv.attach,
358
+ detach: parsedArgv.detach,
352
359
  logFile: parsedArgv.logFile,
353
360
  verbose: parsedArgv.verbose,
354
361
  resume: parsedArgv.continue, // Note: intentional use resume here to avoid preserved keyword (continue)