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
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { formatCwdConflictWarning, shQuote } from "./cwdConflictWarn.ts";
2
+ import { formatCwdConflictWarning, launchingCli, shQuote, vendorOf } from "./cwdConflictWarn.ts";
3
3
 
4
4
  describe("cwdConflictWarn.formatCwdConflictWarning", () => {
5
5
  const cwd = "/code/proj/tree/main";
@@ -18,6 +18,9 @@ describe("cwdConflictWarn.formatCwdConflictWarning", () => {
18
18
  // original command is appended so the suggestion is copy-pasteable
19
19
  expect(msg).toContain("&& ay claude -- fix");
20
20
  expect(msg).toContain("AGENT_YES_NO_CWD_WARN=1");
21
+ expect(msg).toContain("STRONGLY NOT RECOMMENDED");
22
+ expect(msg).toContain("in-harness subagents");
23
+ expect(msg).toContain("harvest that work by git");
21
24
  });
22
25
 
23
26
  it("pluralizes and lists at most 3 peers with an overflow count", () => {
@@ -37,6 +40,36 @@ describe("cwdConflictWarn.formatCwdConflictWarning", () => {
37
40
  });
38
41
  });
39
42
 
43
+ describe("vendor-aware warning", () => {
44
+ const cwd = "/code/proj/tree/main";
45
+ it("fires the strong warning for a same-vendor duplicate only", () => {
46
+ const msg = formatCwdConflictWarning(
47
+ [
48
+ { pid: 1, cli: "claude" },
49
+ { pid: 2, cli: "codex" },
50
+ ],
51
+ cwd,
52
+ "ay claude",
53
+ "claude",
54
+ )!;
55
+ expect(msg).toContain("STRONGLY NOT RECOMMENDED");
56
+ expect(msg).toContain("1 agent is already running");
57
+ expect(msg).not.toContain("codex");
58
+ });
59
+ it("is a soft note with an awareness hint across vendors", () => {
60
+ const msg = formatCwdConflictWarning([{ pid: 2, cli: "codex" }], cwd, "ay claude", "claude")!;
61
+ expect(msg).not.toContain("STRONGLY");
62
+ expect(msg).toContain("Are they?");
63
+ });
64
+ it("maps cli names to vendors and finds the launching cli", () => {
65
+ expect(vendorOf("cy")).toBe("claude");
66
+ expect(vendorOf("claude-yes")).toBe("claude");
67
+ expect(vendorOf("codex-yes")).toBe("codex");
68
+ expect(launchingCli(["bun", "/x/ay", "--robust", "claude", "--", "hi"])).toBe("claude");
69
+ expect(launchingCli(["bun", "/x/codex-yes.js"])).toBe("codex");
70
+ });
71
+ });
72
+
40
73
  describe("cwdConflictWarn.shQuote", () => {
41
74
  it("passes safe tokens through unquoted", () => {
42
75
  expect(shQuote("ay")).toBe("ay");
@@ -18,6 +18,21 @@ export interface CwdOccupant {
18
18
  cli: string;
19
19
  }
20
20
 
21
+ /** The vendor behind a cli name: claude/cy/claude-yes -> claude, codex-* -> codex. */
22
+ export function vendorOf(cli: string): string {
23
+ const c = cli.toLowerCase().replace(/-yes$/, "");
24
+ if (c === "cy" || c.startsWith("claude")) return "claude";
25
+ if (c.startsWith("codex")) return "codex";
26
+ return c;
27
+ }
28
+
29
+ /** The cli this launch starts: a `<cli>-yes` entry name, else the first non-flag argument. */
30
+ export function launchingCli(rawArgv: string[]): string | null {
31
+ const bin = path.basename(rawArgv[1] ?? "").replace(/\.(c?js|ts)$/, "");
32
+ if (bin.endsWith("-yes") && bin !== "agent-yes") return bin.replace(/-yes$/, "");
33
+ return rawArgv.slice(2).find((a) => !a.startsWith("-")) ?? null;
34
+ }
35
+
21
36
  /**
22
37
  * POSIX single-quote a shell token so a copy-pasted recovery command survives
23
38
  * spaces, quotes, `$`, `;`, `&`, etc. Safe-charset tokens pass through unquoted
@@ -38,8 +53,26 @@ export function formatCwdConflictWarning(
38
53
  occupants: CwdOccupant[],
39
54
  cwd: string,
40
55
  origCmd: string,
56
+ launching: string | null = null,
41
57
  ): string | null {
42
58
  if (occupants.length === 0) return null;
59
+ // Different vendors in one cwd (say claude + codex) that know about each other
60
+ // are fine, even good: only same-vendor duplicates get the strong warning.
61
+ const same = launching
62
+ ? occupants.filter((r) => vendorOf(r.cli) === vendorOf(launching))
63
+ : occupants;
64
+ if (launching && same.length === 0) {
65
+ const names = occupants
66
+ .slice(0, 3)
67
+ .map((r) => `${r.cli} ${r.pid}`)
68
+ .join(", ");
69
+ return (
70
+ `\nℹ ${names} ${occupants.length > 1 ? "are" : "is"} already running in this directory (${cwd}), from a different vendor than ${launching}.\n` +
71
+ ` That is fine if they are aware of each other (\`ay ls --cwd .\`, \`ay send <pid> "…"\`). Are they? Otherwise\n` +
72
+ ` they share one checkout, builds and ports without knowing it. (AGENT_YES_NO_CWD_WARN=1 silences this)\n\n`
73
+ );
74
+ }
75
+ occupants = same;
43
76
  // Worktree name doubles as the new dir AND the new branch. `git worktree add`
44
77
  // (not `git clone .`) is the correct primitive: it resolves the repo root even
45
78
  // from a subdir, shares the object store, and creates the branch in one step.
@@ -53,11 +86,16 @@ export function formatCwdConflictWarning(
53
86
  const branch = shQuote(wt);
54
87
  const dir = shQuote(`../${wt}`);
55
88
  return (
56
- `\n⚠ ${occupants.length} agent${occupants.length > 1 ? "s are" : " is"} already running in this directory (${cwd}):\n` +
89
+ `\n⚠⚠⚠ STRONGLY NOT RECOMMENDED: ${occupants.length} agent${occupants.length > 1 ? "s are" : " is"} already running in this directory (${cwd}):\n` +
57
90
  `${list}${more}\n` +
58
- ` Parallel agents in one working tree clobber each other's files, builds, and ports.\n` +
59
- ` To isolate this run in its own git worktree, cancel (Ctrl-C) and instead:\n` +
60
- ` git worktree add -b ${branch} ${dir} && cd ${dir} && ${cmd}\n` +
91
+ ` Two top-level agents in one working tree share one checkout, one set of builds and\n` +
92
+ ` one set of live services and ports, and neither knows what the other is doing.\n` +
93
+ ` Do one of these instead (cancel with Ctrl-C):\n` +
94
+ ` 1. Parallel work in THIS directory: use in-harness subagents inside the existing\n` +
95
+ ` agent (e.g. Claude's Agent tool), not a second \`ay\`. Subagents are not counted here.\n` +
96
+ ` 2. Parallel work on another branch: start it in its OWN directory (a git worktree)\n` +
97
+ ` and let the main branch harvest that work by git (merge or PR):\n` +
98
+ ` git worktree add -b ${branch} ${dir} && cd ${dir} && ${cmd}\n` +
61
99
  ` (set AGENT_YES_NO_CWD_WARN=1 to silence)\n\n`
62
100
  );
63
101
  }
@@ -79,7 +117,7 @@ export async function warnIfCwdOccupied(rawArgv: string[]): Promise<void> {
79
117
  // `-- "fix the bug"`). We can't recover the user's exact original quoting
80
118
  // from argv, but per-token quoting is copy-paste-correct.
81
119
  const origCmd = ["ay", ...rawArgv.slice(2)].map(shQuote).join(" ");
82
- const msg = formatCwdConflictWarning(occupants, here, origCmd);
120
+ const msg = formatCwdConflictWarning(occupants, here, origCmd, launchingCli(rawArgv));
83
121
  if (msg) {
84
122
  process.stderr.write(msg);
85
123
  // Interactive CLIs (claude/codex) switch to the alternate screen
@@ -0,0 +1,110 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { applyCwdGuard, checkCwd } from "./cwdGuard.ts";
4
+
5
+ // Every case injects its deps: the real guard chdir()s the process, and a spec
6
+ // that actually parked vitest in a deleted directory would break module
7
+ // resolution for the rest of the run. The end-to-end behaviour is covered by
8
+ // running the built CLI from a deleted cwd (see the PR).
9
+ const gone = () => {
10
+ throw Object.assign(new Error("ENOENT: uv_cwd"), { code: "ENOENT", syscall: "uv_cwd" });
11
+ };
12
+
13
+ describe("checkCwd", () => {
14
+ it("passes through when the cwd is fine", () => {
15
+ const chdir = vi.fn();
16
+ expect(checkCwd({ cwd: () => "/repo/alpha", chdir, pwd: "/repo/alpha" })).toEqual({
17
+ state: "ok",
18
+ });
19
+ expect(chdir).not.toHaveBeenCalled();
20
+ });
21
+
22
+ it("recovers into $PWD when the directory was recreated", () => {
23
+ // The `ay ws new` case: the shell's inode is gone but the path exists again,
24
+ // and it is exactly where the user typed the command.
25
+ const chdir = vi.fn();
26
+ expect(
27
+ checkCwd({ cwd: gone, chdir, pwd: "/x/acme/acme/tree/main", isDir: () => true }),
28
+ ).toEqual({ state: "recovered", dir: "/x/acme/acme/tree/main" });
29
+ expect(chdir).toHaveBeenCalledWith("/x/acme/acme/tree/main");
30
+ });
31
+
32
+ it("reports when $PWD is gone too, naming the path and the way out", () => {
33
+ const v = checkCwd({
34
+ cwd: gone,
35
+ chdir: vi.fn(),
36
+ pwd: "/x/acme/acme/tree/main",
37
+ isDir: () => false,
38
+ });
39
+ expect(v.state).toBe("stale");
40
+ const msg = v.state === "stale" ? v.message : "";
41
+ expect(msg).toContain("/x/acme/acme/tree/main");
42
+ expect(msg).toContain("no longer exists");
43
+ expect(msg).toContain('cd "$PWD"');
44
+ // One readable block, not a stack trace: no ` at <frame>` lines.
45
+ expect(msg).not.toMatch(/\n\s+at /);
46
+ });
47
+
48
+ it("does not trust a relative or missing $PWD", () => {
49
+ const chdir = vi.fn();
50
+ // A relative $PWD cannot be resolved without the cwd we just lost.
51
+ expect(checkCwd({ cwd: gone, chdir, pwd: "tree/main", isDir: () => true }).state).toBe("stale");
52
+ expect(checkCwd({ cwd: gone, chdir, pwd: undefined, isDir: () => true }).state).toBe("stale");
53
+ expect(chdir).not.toHaveBeenCalled();
54
+ });
55
+
56
+ it("reports when chdir itself fails (a race with another delete)", () => {
57
+ const v = checkCwd({
58
+ cwd: gone,
59
+ chdir: () => {
60
+ throw new Error("ENOENT");
61
+ },
62
+ pwd: "/repo/alpha",
63
+ isDir: () => true,
64
+ });
65
+ expect(v.state).toBe("stale");
66
+ });
67
+ });
68
+
69
+ describe("applyCwdGuard", () => {
70
+ it("warns once on recovery and does not fail", () => {
71
+ const warn = vi.fn();
72
+ const fail = vi.fn(() => {
73
+ throw new Error("should not fail");
74
+ }) as unknown as (s: string) => never;
75
+ const v = applyCwdGuard(
76
+ { cwd: gone, chdir: vi.fn(), pwd: "/repo/alpha", isDir: () => true },
77
+ { warn, fail },
78
+ );
79
+ expect(v.state).toBe("recovered");
80
+ expect(warn).toHaveBeenCalledTimes(1);
81
+ expect(warn.mock.calls[0]![0]).toContain("/repo/alpha");
82
+ });
83
+
84
+ it("fails with the message when there is nothing to recover to", () => {
85
+ const warn = vi.fn();
86
+ const fail = vi.fn() as unknown as (s: string) => never;
87
+ applyCwdGuard({ cwd: gone, chdir: vi.fn(), pwd: undefined }, { warn, fail });
88
+ expect(warn).not.toHaveBeenCalled();
89
+ expect(fail).toHaveBeenCalledTimes(1);
90
+ });
91
+
92
+ it("stays silent when the cwd is healthy", () => {
93
+ const warn = vi.fn();
94
+ const fail = vi.fn() as unknown as (s: string) => never;
95
+ applyCwdGuard({ cwd: () => "/repo/alpha", chdir: vi.fn() }, { warn, fail });
96
+ expect(warn).not.toHaveBeenCalled();
97
+ expect(fail).not.toHaveBeenCalled();
98
+ });
99
+ });
100
+
101
+ describe("cli.ts import order", () => {
102
+ // The guard only works if it is evaluated before any import that touches the
103
+ // cwd. Reordering the imports would silently restore the raw-stack-trace
104
+ // crash, with nothing failing to show it — so pin the position here.
105
+ it("imports ./cwdGuard.ts before anything else", async () => {
106
+ const src = await readFile(new URL("./cli.ts", import.meta.url), "utf8");
107
+ const firstImport = src.split("\n").find((l) => l.trimStart().startsWith("import "));
108
+ expect(firstImport).toContain("./cwdGuard.ts");
109
+ });
110
+ });
package/ts/cwdGuard.ts ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Startup guard for a working directory that no longer exists.
3
+ *
4
+ * A shell can sit in a directory that gets deleted and recreated under it —
5
+ * routine here, since `ay ws new` re-clones `<ws>/tree/<branch>` and worktrees
6
+ * get removed and re-added while a terminal is parked inside one. The path
7
+ * still resolves, but the inode the shell holds is gone, so `process.cwd()`
8
+ * throws ENOENT/uv_cwd.
9
+ *
10
+ * Nothing used to catch that. The first thing to call `process.cwd()` was the
11
+ * eager config load (ts/index.ts top-level-awaits agent-yes.config.ts, whose
12
+ * body awaits loadCascadingConfig → process.cwd()), and later execa and
13
+ * bun-pty, so `cy` died with a raw Bun stack trace — three of them — before any
14
+ * of our own error handling existed. No pid record, no log, nothing to read
15
+ * back; see the no-trace symptom in the report that prompted this.
16
+ *
17
+ * So this runs FIRST, before anything else can touch the cwd: recover when the
18
+ * shell's `$PWD` still names a real directory (the recreated workspace — which
19
+ * is where the user meant to be), and otherwise fail with one actionable line
20
+ * instead of a stack trace.
21
+ *
22
+ * Imported for its side effect as the first import of ts/cli.ts: an ES module's
23
+ * imports are evaluated before the importing module's body, so an inline check
24
+ * in cli.ts would already be too late if any import touched the cwd.
25
+ * cwdGuard.spec.ts pins that import position.
26
+ */
27
+
28
+ import { statSync } from "node:fs";
29
+ import { isAbsolute } from "node:path";
30
+
31
+ export type CwdCheck =
32
+ | { state: "ok" }
33
+ | { state: "recovered"; dir: string }
34
+ | { state: "stale"; message: string };
35
+
36
+ /** Injectable for tests — the real thing mutates the process and must not run in-suite. */
37
+ export interface CwdDeps {
38
+ cwd?: () => string;
39
+ chdir?: (dir: string) => void;
40
+ pwd?: string | undefined;
41
+ isDir?: (dir: string) => boolean;
42
+ }
43
+
44
+ function staleMessage(pwd: string | undefined): string {
45
+ const where = pwd ? ` ('${pwd}')` : "";
46
+ return (
47
+ `agent-yes: this shell's working directory${where} no longer exists.\n` +
48
+ ` It was deleted or replaced while the shell stayed in it, so process.cwd()\n` +
49
+ ` fails (ENOENT/uv_cwd) and no agent can be started here.\n` +
50
+ ` Re-enter it, then retry:\n` +
51
+ ` cd "$PWD" # if the path was recreated\n` +
52
+ ` cd <some-dir> # otherwise, go somewhere that exists\n`
53
+ );
54
+ }
55
+
56
+ /**
57
+ * Is the cwd usable, and can it be recovered when not? Pure given `deps`; the
58
+ * process-mutating `chdir` only runs on the recovery path.
59
+ */
60
+ export function checkCwd(deps: CwdDeps = {}): CwdCheck {
61
+ const cwd = deps.cwd ?? (() => process.cwd());
62
+ const chdir = deps.chdir ?? ((dir: string) => process.chdir(dir));
63
+ const pwd = "pwd" in deps ? deps.pwd : process.env.PWD;
64
+ const isDir =
65
+ deps.isDir ??
66
+ ((dir: string) => {
67
+ try {
68
+ return statSync(dir).isDirectory();
69
+ } catch {
70
+ return false;
71
+ }
72
+ });
73
+
74
+ try {
75
+ cwd();
76
+ return { state: "ok" };
77
+ } catch {
78
+ // cwd is gone — fall through to recovery.
79
+ }
80
+
81
+ // `$PWD` is the shell's idea of where the user is. When the path was recreated
82
+ // (the `ay ws new` case) that directory exists again and is exactly where they
83
+ // typed the command, so moving there beats refusing to run. Absolute only: a
84
+ // relative `$PWD` can't be resolved without the cwd we just lost.
85
+ if (pwd && isAbsolute(pwd) && isDir(pwd)) {
86
+ try {
87
+ chdir(pwd);
88
+ return { state: "recovered", dir: pwd };
89
+ } catch {
90
+ // chdir can still fail (permissions, a race with another delete) — report.
91
+ }
92
+ }
93
+ return { state: "stale", message: staleMessage(pwd) };
94
+ }
95
+
96
+ /** Apply the verdict: notify on recovery, exit 1 with one readable line otherwise. */
97
+ export function applyCwdGuard(
98
+ deps: CwdDeps = {},
99
+ io: { warn?: (s: string) => void; fail?: (s: string) => never } = {},
100
+ ): CwdCheck {
101
+ const warn = io.warn ?? ((s: string) => void process.stderr.write(s));
102
+ const fail =
103
+ io.fail ??
104
+ ((s: string) => {
105
+ process.stderr.write(s);
106
+ process.exit(1);
107
+ });
108
+ const verdict = checkCwd(deps);
109
+ if (verdict.state === "recovered")
110
+ warn(
111
+ `agent-yes: the working directory was replaced while this shell sat in it; ` +
112
+ `continuing in ${verdict.dir}\n`,
113
+ );
114
+ else if (verdict.state === "stale") fail(verdict.message);
115
+ return verdict;
116
+ }
117
+
118
+ applyCwdGuard();
@@ -0,0 +1,52 @@
1
+ // The force-kill shared by the console's POST /api/kill and `ay kill <pid>`.
2
+ //
3
+ // SIGKILL the agent's process GROUP (wrapper + CLI + children), via the pgid
4
+ // the reaper recorded, then the pids directly in case they aren't group
5
+ // leaders. The >1 guards are critical — process.kill(-1)/kill(0) would signal
6
+ // far too much. Unix only; callers refuse win32.
7
+
8
+ import { pgidForWrapper } from "./reaper.ts";
9
+
10
+ export interface ForceKillTarget {
11
+ pid: number;
12
+ wrapper_pid?: number | null;
13
+ }
14
+
15
+ /** What forceKill would signal, without signalling it. */
16
+ export async function forceKillTargets(record: ForceKillTarget): Promise<{
17
+ pgid: number | null;
18
+ pids: number[];
19
+ }> {
20
+ const g = await pgidForWrapper(record.wrapper_pid ?? 0);
21
+ const pids = [record.pid];
22
+ if (record.wrapper_pid && record.wrapper_pid !== record.pid) pids.push(record.wrapper_pid);
23
+ return { pgid: g && g > 1 ? g : null, pids: pids.filter((p) => p > 1) };
24
+ }
25
+
26
+ /**
27
+ * SIGKILL the targets. Returns labels of what was signalled, and of what could
28
+ * NOT be signalled for a reason other than "already gone" (ESRCH) — e.g. EPERM,
29
+ * a process owned by another user.
30
+ */
31
+ export function forceKill(targets: { pgid: number | null; pids: number[] }): {
32
+ killed: string[];
33
+ failed: string[];
34
+ } {
35
+ const killed: string[] = [];
36
+ const failed: string[] = [];
37
+ const sig = (target: number, label: string) => {
38
+ try {
39
+ process.kill(target, "SIGKILL");
40
+ killed.push(label);
41
+ } catch (e) {
42
+ const code = (e as NodeJS.ErrnoException).code;
43
+ if (code !== "ESRCH") failed.push(`${label} (${code ?? "error"})`);
44
+ }
45
+ };
46
+ if (targets.pgid && targets.pgid > 1) sig(-targets.pgid, `group ${targets.pgid}`);
47
+ for (const pid of targets.pids) {
48
+ if (pid <= 1) continue;
49
+ sig(pid, pid === targets.pids[0] ? `pid ${pid}` : `wrapper ${pid}`);
50
+ }
51
+ return { killed, failed };
52
+ }
@@ -7,6 +7,7 @@ import {
7
7
  confirmAgentStarted,
8
8
  predictedLogPath,
9
9
  shouldForkNested,
10
+ stripDetachFlag,
10
11
  waitForRegistration,
11
12
  } from "./forkNested";
12
13
 
@@ -28,6 +29,46 @@ describe("shouldForkNested", () => {
28
29
  it("does NOT fork when attach opts out, regardless of context", () => {
29
30
  expect(shouldForkNested({ isTTY: false, ayPid: "1234", attach: true })).toBe(false);
30
31
  });
32
+
33
+ it("--detach forks in any context — a TTY, not nested (e.g. a human over ssh)", () => {
34
+ for (const isTTY of [true, false])
35
+ for (const ayPid of [undefined, "1234"])
36
+ expect(shouldForkNested({ isTTY, ayPid, attach: false, detach: true })).toBe(true);
37
+ });
38
+ });
39
+
40
+ describe("stripDetachFlag", () => {
41
+ it("strips a leading bare --detach", () => {
42
+ expect(stripDetachFlag(["--detach", "claude", "--", "hi"], true)).toEqual({
43
+ ok: true,
44
+ args: ["claude", "--", "hi"],
45
+ });
46
+ });
47
+ it("leaves args alone without any detach token, and never touches prompt text", () => {
48
+ const args = ["claude", "--verbose", "--", "--detach"];
49
+ expect(stripDetachFlag(args, false)).toEqual({ ok: true, args });
50
+ expect(stripDetachFlag(["--detach", "claude", "--", "--detach"], true)).toEqual({
51
+ ok: true,
52
+ args: ["claude", "--", "--detach"],
53
+ });
54
+ });
55
+ it("refuses every other spelling or position yargs could read as detach", () => {
56
+ for (const [args, parsed] of [
57
+ [["--detach=true", "claude"], true],
58
+ [["--detach", "true", "claude"], true],
59
+ [["--detach", "false", "claude"], false],
60
+ [["--no-detach", "claude"], false],
61
+ [["--cli", "claude", "--detach", "--", "hi"], true],
62
+ [["--verbose", "--detach", "claude"], true],
63
+ [["--detach", "--detach", "claude"], true],
64
+ [["--verbose", "--detach=false", "claude"], false],
65
+ [["claude", "--detach"], false], // even after the CLI name: refused, not forwarded
66
+ ] as const) {
67
+ const r = stripDetachFlag([...args], parsed);
68
+ expect(r.ok).toBe(false);
69
+ if (!r.ok) expect(r.error).toMatch(/ay --detach <cli>/);
70
+ }
71
+ });
31
72
  });
32
73
 
33
74
  describe("waitForRegistration", () => {
@@ -7,6 +7,7 @@ import {
7
7
  confirmAgentStarted,
8
8
  predictedLogPath,
9
9
  shouldForkNested,
10
+ stripDetachFlag,
10
11
  waitForRegistration,
11
12
  } from "./forkNested";
12
13
 
@@ -28,6 +29,46 @@ describe("shouldForkNested", () => {
28
29
  it("does NOT fork when attach opts out, regardless of context", () => {
29
30
  expect(shouldForkNested({ isTTY: false, ayPid: "1234", attach: true })).toBe(false);
30
31
  });
32
+
33
+ it("--detach forks in any context — a TTY, not nested (e.g. a human over ssh)", () => {
34
+ for (const isTTY of [true, false])
35
+ for (const ayPid of [undefined, "1234"])
36
+ expect(shouldForkNested({ isTTY, ayPid, attach: false, detach: true })).toBe(true);
37
+ });
38
+ });
39
+
40
+ describe("stripDetachFlag", () => {
41
+ it("strips a leading bare --detach", () => {
42
+ expect(stripDetachFlag(["--detach", "claude", "--", "hi"], true)).toEqual({
43
+ ok: true,
44
+ args: ["claude", "--", "hi"],
45
+ });
46
+ });
47
+ it("leaves args alone without any detach token, and never touches prompt text", () => {
48
+ const args = ["claude", "--verbose", "--", "--detach"];
49
+ expect(stripDetachFlag(args, false)).toEqual({ ok: true, args });
50
+ expect(stripDetachFlag(["--detach", "claude", "--", "--detach"], true)).toEqual({
51
+ ok: true,
52
+ args: ["claude", "--", "--detach"],
53
+ });
54
+ });
55
+ it("refuses every other spelling or position yargs could read as detach", () => {
56
+ for (const [args, parsed] of [
57
+ [["--detach=true", "claude"], true],
58
+ [["--detach", "true", "claude"], true],
59
+ [["--detach", "false", "claude"], false],
60
+ [["--no-detach", "claude"], false],
61
+ [["--cli", "claude", "--detach", "--", "hi"], true],
62
+ [["--verbose", "--detach", "claude"], true],
63
+ [["--detach", "--detach", "claude"], true],
64
+ [["--verbose", "--detach=false", "claude"], false],
65
+ [["claude", "--detach"], false], // even after the CLI name: refused, not forwarded
66
+ ] as const) {
67
+ const r = stripDetachFlag([...args], parsed);
68
+ expect(r.ok).toBe(false);
69
+ if (!r.ok) expect(r.error).toMatch(/ay --detach <cli>/);
70
+ }
71
+ });
31
72
  });
32
73
 
33
74
  describe("waitForRegistration", () => {
package/ts/forkNested.ts CHANGED
@@ -12,18 +12,65 @@ import path from "path";
12
12
  * into an agent's environment by its wrapper — a human shell never has it) AND
13
13
  * stdout is not a TTY (captured/piped, e.g. a tool's Bash). A human piping output
14
14
  * (`ay claude | cat`) has no `AGENT_YES_PID`, so they still block as before.
15
- * `attach` (the `--attach` flag or `AGENT_YES_ATTACH=1`) forces foreground.
15
+ * `attach` (the `--attach` flag or `AGENT_YES_ATTACH=1`) forces foreground;
16
+ * `detach` (the `--detach` flag) forces the fork in any context — e.g. a human
17
+ * spawning an agent over `ssh host ay --detach claude -- …`, where the session
18
+ * would otherwise stay open for the agent's whole life.
16
19
  */
17
20
  export function shouldForkNested(opts: {
18
21
  isTTY: boolean;
19
22
  ayPid: string | undefined;
20
23
  attach: boolean;
24
+ detach?: boolean;
21
25
  }): boolean {
26
+ if (opts.detach) return true;
22
27
  if (opts.attach) return false;
23
28
  if (opts.isTTY) return false;
24
29
  return Boolean(opts.ayPid && opts.ayPid.trim());
25
30
  }
26
31
 
32
+ /**
33
+ * Validate where `--detach` was written and return the args with it removed.
34
+ *
35
+ * Accepted in exactly one spelling and place: the bare token `--detach` as the
36
+ * FIRST argument (`ay --detach <cli> …`), once. That keeps the strip
37
+ * parse-free — the Rust runner would otherwise forward the unknown flag to the
38
+ * target CLI. Any OTHER detach-like token before `--` (`--detach=…`,
39
+ * `--detach true`, `--no-detach`, a repeat, or `--detach` after other flags —
40
+ * even after the CLI name) is refused with the one form that works, rather
41
+ * than half-working. After `--` the words are prompt text and are untouched.
42
+ *
43
+ * `rawArgs` is argv without the runtime + script; `parsedDetach` is what yargs
44
+ * concluded.
45
+ */
46
+ export function stripDetachFlag(
47
+ rawArgs: string[],
48
+ parsedDetach: boolean,
49
+ ): { ok: true; args: string[] } | { ok: false; error: string } {
50
+ const form = "use exactly: ay --detach <cli> [options] -- <prompt>";
51
+ const dash = rawArgs.indexOf("--");
52
+ const end = dash === -1 ? rawArgs.length : dash;
53
+ const hits: number[] = [];
54
+ for (let i = 0; i < end; i++) if (/^--(no-)?detach(=|$)/.test(rawArgs[i]!)) hits.push(i);
55
+ if (hits.length === 0) {
56
+ return parsedDetach
57
+ ? { ok: false, error: `unsupported --detach form — ${form}` }
58
+ : { ok: true, args: rawArgs };
59
+ }
60
+ const leadingBare =
61
+ hits.length === 1 &&
62
+ hits[0] === 0 &&
63
+ rawArgs[0] === "--detach" &&
64
+ !/^(true|false)$/.test(rawArgs[1] ?? "");
65
+ if (!leadingBare) {
66
+ return {
67
+ ok: false,
68
+ error: `unsupported --detach form '${hits.map((i) => rawArgs[i]).join(" ")}' — ${form}`,
69
+ };
70
+ }
71
+ return { ok: true, args: rawArgs.slice(1) };
72
+ }
73
+
27
74
  /** The tutorial printed to the parent agent after a detached spawn, telling it
28
75
  * exactly how to drive the agent it just started. */
29
76
  export function buildSpawnTutorial(cli: string, pid: number): string {