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
package/ts/subcommands.ts CHANGED
@@ -12,7 +12,17 @@
12
12
  */
13
13
 
14
14
  import { randomBytes } from "crypto";
15
- import { closeSync, constants as fsConstants, openSync, realpathSync } from "fs";
15
+ import { interruptBeforeSend, interruptScreenState } from "./interruptSend.ts";
16
+ import {
17
+ closeSync,
18
+ constants as fsConstants,
19
+ mkdirSync,
20
+ openSync,
21
+ readFileSync,
22
+ realpathSync,
23
+ renameSync,
24
+ writeFileSync,
25
+ } from "fs";
16
26
  import { execFileSync, spawn as spawnChild } from "node:child_process";
17
27
  import { appendFile, mkdir, open, readFile, rm, stat, writeFile } from "fs/promises";
18
28
  import ms from "ms";
@@ -22,7 +32,7 @@ import { type GlobalPidRecord, readGlobalPids, updateGlobalPidStatus } from "./g
22
32
  import { formatIdentity, localHost, localUser } from "./identity.ts";
23
33
  import { hostedRoomMember, roomAliasPlaceholder } from "./roomReplyAlias.ts";
24
34
  import { buildAgentForest, flattenForest } from "./agentTree.ts";
25
- import { parseTaskCounts, type TaskCounts } from "./todoParse.ts";
35
+ import { mayHoldTaskBlock, parseTaskCounts, type TaskCounts } from "./todoParse.ts";
26
36
  import { agentYesHome } from "./agentYesHome.ts";
27
37
  import { PidStore } from "./pidStore.ts";
28
38
  import {
@@ -123,6 +133,7 @@ import {
123
133
  classifyComposer,
124
134
  composerBoxed,
125
135
  composerPromptRow,
136
+ stripPromptGlyph,
126
137
  DUPLICATE_WINDOW_MS,
127
138
  findRecentDuplicate,
128
139
  noteRecentSend,
@@ -712,18 +723,23 @@ const SUBCOMMANDS = new Set([
712
723
  // the machine over WebRTC (#67).
713
724
  // - it is an ordinary English verb people start prompts with: `cy read ts/cli.ts
714
725
  // and explain it` / `cy connect the frontend to the API` must reach claude.
715
- // The commands stay reachable on the manager entry (`ay read`, `ay share`,
716
- // `ay connect`); `cy cat` / `cy tail` / `cy head` / `cy ls` are unchanged —
717
- // nobody opens a prompt with those.
726
+ // Same for `cy kill the stale dev server`. The commands stay reachable on
727
+ // the manager entry (`ay read`, `ay share`, `ay connect`, `ay kill`);
728
+ // `cy cat` / `cy tail` / `cy head` / `cy ls` are unchanged — nobody opens a
729
+ // prompt with those.
718
730
  // Kept one name per line so both runtimes' copies stay easy to keep in sync.
719
731
  const MANAGER_SUBCOMMANDS = new Set([
720
732
  // manage this host
721
733
  "setup",
722
734
  "ws",
735
+ "schedules",
736
+ "sched",
737
+ "cron",
723
738
  // prompt-word verbs
724
739
  "read",
725
740
  "share",
726
741
  "connect",
742
+ "kill",
727
743
  ]);
728
744
 
729
745
  const IDLE_THRESHOLD_MS = 60 * 1000;
@@ -1103,6 +1119,8 @@ export async function runSubcommand(argv: string[]): Promise<number | null> {
1103
1119
  return await cmdExit(rest);
1104
1120
  case "restart":
1105
1121
  return await cmdRestart(rest);
1122
+ case "kill":
1123
+ return await (await import("./cmdKill.ts")).cmdKill(rest);
1106
1124
  case "note":
1107
1125
  return await cmdNote(rest);
1108
1126
  case "ask":
@@ -1167,6 +1185,15 @@ export async function runSubcommand(argv: string[]): Promise<number | null> {
1167
1185
  const { cmdWs } = await import("./ws.ts");
1168
1186
  return cmdWs(rest);
1169
1187
  }
1188
+ case "schedules":
1189
+ case "sched": {
1190
+ const { cmdSchedules } = await import("./schedulesCli.ts");
1191
+ return cmdSchedules(rest);
1192
+ }
1193
+ case "cron": {
1194
+ const { cmdCron } = await import("./schedulesCli.ts");
1195
+ return cmdCron(rest);
1196
+ }
1170
1197
  case "schedule": {
1171
1198
  const { cmdSchedule } = await import("./schedule.ts");
1172
1199
  return cmdSchedule(rest);
@@ -1291,7 +1318,11 @@ async function buildAgentContextSection(self: GlobalPidRecord): Promise<string>
1291
1318
  dutyLine +
1292
1319
  `\n` +
1293
1320
  `As an agent, you can:\n` +
1294
- ` Spawn a sub-agent:\n` +
1321
+ ` Parallel work: in the SAME cwd use your harness's own subagents (e.g. the Agent\n` +
1322
+ ` tool), NOT a second \`ay\` there (two top-level agents in one checkout is strongly\n` +
1323
+ ` not recommended). For another branch, spawn \`ay\` in a SEPARATE cwd (git worktree)\n` +
1324
+ ` and harvest it by git (merge/PR).\n` +
1325
+ ` Spawn a sub-agent (in its own cwd):\n` +
1295
1326
  ` ay <cli> -- "<prompt>" auto-links as your child\n` +
1296
1327
  ` ay claude --model sonnet --advisor opus -- "<prompt>" routine task\n` +
1297
1328
  ` ay claude --model opus --advisor fable -- "<prompt>" complex task\n` +
@@ -1325,7 +1356,9 @@ export async function cmdHelp(managerCommands = true): Promise<number> {
1325
1356
  // `ws` is manager-only for the same reason as `setup`.
1326
1357
  const wsLines = managerCommands
1327
1358
  ? ` ay ws ls [--status] list <owner>/<repo>/tree/<branch> workspaces\n` +
1328
- ` ay ws new <owner>/<repo>[@branch] clone/refresh a workspace (ay ws help for more)\n`
1359
+ ` ay ws new <owner>/<repo>[@branch] clone/refresh a workspace (ay ws help for more)\n` +
1360
+ ` ay cron "<cron>" <target> <msg> recurring reminder sent to an agent (ay cron help)\n` +
1361
+ ` ay schedules ls|daemon all schedules on this machine + the scheduler daemon\n`
1329
1362
  : ``;
1330
1363
  // `read` is manager-entry-only too, but for the opposite reason: it's a word
1331
1364
  // people open prompts with, so `cy read …` runs the agent. Unlike setup/ws the
@@ -1339,6 +1372,9 @@ export async function cmdHelp(managerCommands = true): Promise<number> {
1339
1372
  const shareAliasNote = managerCommands
1340
1373
  ? ``
1341
1374
  : ` (\`ay\` only — \`cy share\`/\`cy connect\` are prompts)\n`;
1375
+ const killAliasNote = managerCommands
1376
+ ? ``
1377
+ : ` (\`ay kill\` only — \`cy kill …\` is a prompt)\n`;
1342
1378
  // Only agents carry AGENT_YES_PID — a human shell never sets it — so this
1343
1379
  // section is skipped entirely (no async work at all) for interactive use.
1344
1380
  const self = process.env.AGENT_YES_PID ? await resolveSender() : null;
@@ -1376,6 +1412,9 @@ export async function cmdHelp(managerCommands = true): Promise<number> {
1376
1412
  ` ay stop <keyword> graceful shutdown (/exit for claude/codex)\n` +
1377
1413
  ` ay exit <keyword> [reason] graceful shutdown, recording who/why (= 'ay send <kw> exit')\n` +
1378
1414
  ` ay restart <keyword> [--fresh] stop (if live) + relaunch resuming the session; --fresh replays the prompt\n` +
1415
+ ` ay kill <pid> [--dry-run] SIGKILL an agent + its process group, like the console's\n` +
1416
+ ` Kill (exact pid from ay ls; never the calling shell)\n` +
1417
+ killAliasNote +
1379
1418
  ` ay status <keyword> agent status snapshot\n` +
1380
1419
  ` ay notify watch --unread get notified when sub-agents finish/stuck/crash (writes to inbox)\n` +
1381
1420
  ` ay whoami [--json] (inside an agent) your own registry identity + reply address\n` +
@@ -1404,6 +1443,8 @@ export async function cmdHelp(managerCommands = true): Promise<number> {
1404
1443
  `Run an agent (naming a CLI is what launches one — bare 'ay' shows this help):\n` +
1405
1444
  ` ay <claude|codex|...> [options] -- [prompt]\n` +
1406
1445
  ` ay claude -- "fix the bug in auth.ts"\n` +
1446
+ ` ay --detach claude -- "…" start it in the background and return at once\n` +
1447
+ ` (e.g. over ssh); prints its pid + how to drive it\n` +
1407
1448
  ` cy [options] -- [prompt] shortcut for 'ay claude' (bare 'cy' starts claude)\n` +
1408
1449
  ` ay claude --help full agent-runner options\n` +
1409
1450
  `\n` +
@@ -1636,6 +1677,53 @@ async function pickInteractive(matches: GlobalPidRecord[]): Promise<GlobalPidRec
1636
1677
  });
1637
1678
  }
1638
1679
 
1680
+ /** Edit distance (Levenshtein), small strings only. */
1681
+ function editDistance(a: string, b: string): number {
1682
+ const d = Array.from({ length: b.length + 1 }, (_, j) => j);
1683
+ for (let i = 1; i <= a.length; i++) {
1684
+ let prev = d[0]!;
1685
+ d[0] = i;
1686
+ for (let j = 1; j <= b.length; j++) {
1687
+ const tmp = d[j]!;
1688
+ d[j] = Math.min(d[j]! + 1, d[j - 1]! + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
1689
+ prev = tmp;
1690
+ }
1691
+ }
1692
+ return d[b.length]!;
1693
+ }
1694
+
1695
+ /**
1696
+ * The live agents closest to a keyword that matched nothing, best first (at
1697
+ * most `max`): each agent is scored by its cwd path segments and title words,
1698
+ * so a typo ("lumne" for "lumen") or a stale name still points at the right lane.
1699
+ */
1700
+ export function suggestAgents(
1701
+ records: GlobalPidRecord[],
1702
+ keyword: string,
1703
+ max = 3,
1704
+ ): GlobalPidRecord[] {
1705
+ const kw = keyword.toLowerCase();
1706
+ if (!kw || /^\d+$/.test(kw)) return [];
1707
+ const scored = records
1708
+ .filter((r) => r.status !== "exited")
1709
+ .map((r) => {
1710
+ const tokens = `${r.cwd ?? ""} ${(r as { title?: string }).title ?? ""}`
1711
+ .toLowerCase()
1712
+ .split(/[\s/\\._:@[\]-]+/)
1713
+ .filter((t) => t.length >= 2);
1714
+ const best = Math.min(
1715
+ Infinity,
1716
+ ...tokens.map((t) =>
1717
+ t.includes(kw) ? 0 : editDistance(kw, t) / Math.max(kw.length, t.length),
1718
+ ),
1719
+ );
1720
+ return { r, best };
1721
+ })
1722
+ .filter((x) => x.best < 0.5)
1723
+ .sort((a, b) => a.best - b.best || b.r.started_at - a.r.started_at);
1724
+ return scored.slice(0, max).map((x) => x.r);
1725
+ }
1726
+
1639
1727
  export async function resolveOne(
1640
1728
  keyword: string | undefined,
1641
1729
  opts: CommonOpts,
@@ -1653,7 +1741,14 @@ export async function resolveOne(
1653
1741
  `Find the current one with \`ay ls\`; nothing was sent.`,
1654
1742
  );
1655
1743
  }
1656
- throw new Error(`no agent matched "${keyword}"`);
1744
+ const near = suggestAgents(await listRecords(undefined, opts), keyword);
1745
+ throw new Error(
1746
+ `no agent matched "${keyword}"` +
1747
+ (near.length
1748
+ ? ` — closest live agents:\n` +
1749
+ near.map((r) => ` ${r.pid} ${r.agent_id ?? ""} ${shortenPath(r.cwd)}`).join("\n")
1750
+ : ""),
1751
+ );
1657
1752
  }
1658
1753
  // Exact identity beats fuzzy. A numeric pid or a full agent_id names exactly
1659
1754
  // one agent; without this, that agent gets pooled with prompt-substring
@@ -3046,6 +3141,10 @@ async function cmdLs(rest: string[]): Promise<number> {
3046
3141
  return 0;
3047
3142
  }
3048
3143
 
3144
+ // one-shot `ay ls` only: reuse renders of logs that did not change since the last run (not --watch, which
3145
+ // polls changing logs for as long as it runs and would keep every version)
3146
+ if (!argv.watch) enableRenderDiskCache();
3147
+
3049
3148
  const keyword = argv._[0] !== undefined ? String(argv._[0]) : undefined;
3050
3149
  // A keyword naming a specific remote (alias or token@host:port) → just that
3051
3150
  // remote, regardless of the local/all-remotes default below.
@@ -4397,34 +4496,9 @@ export function resolveReadWindow(opts: {
4397
4496
  * Reads only the last 32 KB for speed, renders via xterm for clean output.
4398
4497
  */
4399
4498
  async function extractActivity(logPath: string): Promise<string | null> {
4400
- const TAIL_BYTES = 32 * 1024;
4401
- let buf: Uint8Array;
4402
- try {
4403
- const fh = await open(logPath, "r");
4404
- try {
4405
- const { size } = await fh.stat();
4406
- if (size === 0) return null;
4407
- if (size <= TAIL_BYTES) {
4408
- const data = await fh.readFile();
4409
- buf = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
4410
- } else {
4411
- const tmp = Buffer.alloc(TAIL_BYTES);
4412
- const { bytesRead } = await fh.read(tmp, 0, TAIL_BYTES, size - TAIL_BYTES);
4413
- buf = new Uint8Array(tmp.buffer, 0, bytesRead);
4414
- }
4415
- } finally {
4416
- await fh.close();
4417
- }
4418
- } catch {
4419
- return null;
4420
- }
4421
-
4422
- try {
4423
- const rendered = await renderRawLog(buf, { mode: "tail", n: 40 });
4424
- return extractActivityFromLines(rendered.split("\n"));
4425
- } catch {
4426
- return null;
4427
- }
4499
+ // the same 32 KB tail, 40 lines and default geometry as the needs_input / stuck checks: rendered once (cached)
4500
+ const lines = await renderLogTailLines(logPath, 40);
4501
+ return lines ? extractActivityFromLines(lines) : null;
4428
4502
  }
4429
4503
 
4430
4504
  /**
@@ -4439,11 +4513,20 @@ export async function extractTaskCounts(logPath: string): Promise<TaskCounts | n
4439
4513
  // Larger window than activity: a todo block is often pushed up by later output.
4440
4514
  const TAIL_BYTES = 256 * 1024;
4441
4515
  let buf: Uint8Array;
4516
+ let key: string;
4442
4517
  try {
4443
4518
  const fh = await open(logPath, "r");
4444
4519
  try {
4445
- const { size } = await fh.stat();
4520
+ const st = await fh.stat();
4521
+ const { size } = st;
4446
4522
  if (size === 0) return null;
4523
+ // the same log state gives the same counts: reuse the last `ay ls` run's answer (none included)
4524
+ key = `tasks\0${logPath}\0${size}\0${st.mtimeMs}`;
4525
+ const kept = renderDiskGet(key);
4526
+ if (kept !== undefined && (kept === "none" || isTaskCounts(kept))) {
4527
+ renderDiskPut(key, kept);
4528
+ return kept === "none" ? null : kept;
4529
+ }
4447
4530
  if (size <= TAIL_BYTES) {
4448
4531
  const data = await fh.readFile();
4449
4532
  buf = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
@@ -4459,16 +4542,29 @@ export async function extractTaskCounts(logPath: string): Promise<TaskCounts | n
4459
4542
  return null;
4460
4543
  }
4461
4544
 
4545
+ // No ⎿ or too few markers in the bytes: no render of them holds a block, so skip the xterm replay
4546
+ // (most logs have no todo block; this replay was the biggest cost of `ay ls`).
4547
+ if (!mayHoldTaskBlock(new TextDecoder().decode(buf))) {
4548
+ renderDiskPut(key, "none");
4549
+ return null;
4550
+ }
4462
4551
  try {
4463
4552
  // mode "cat" renders the full window so parseTaskCounts can find the most
4464
4553
  // recent block anywhere in it (not just the last n lines).
4465
4554
  const rendered = await renderRawLog(buf, { mode: "cat", n: 0 });
4466
- return parseTaskCounts(rendered.split("\n"));
4555
+ const counts = parseTaskCounts(rendered.split("\n"));
4556
+ renderDiskPut(key, counts ?? "none");
4557
+ return counts;
4467
4558
  } catch {
4468
4559
  return null;
4469
4560
  }
4470
4561
  }
4471
4562
 
4563
+ function isTaskCounts(v: unknown): v is TaskCounts {
4564
+ const c = v as TaskCounts;
4565
+ return !!c && typeof c === "object" && Number.isInteger(c.done) && Number.isInteger(c.total);
4566
+ }
4567
+
4472
4568
  // Shared CLI defaults (ready/working/needsInput patterns), loaded once per
4473
4569
  // process from default.config.yaml. Type-only import of AgentCliConfig keeps the
4474
4570
  // heavy ts/index.ts module out of the `ay ls`/`ay status` startup path.
@@ -4504,6 +4600,106 @@ export async function renderLogTailLines(
4504
4600
  logPath: string,
4505
4601
  n = 40,
4506
4602
  geom?: RenderGeom,
4603
+ ): Promise<string[] | null> {
4604
+ // One render per log state per process: an `ay ls` row asks for the same tail up to four times (needs_input
4605
+ // twice, stuck, activity), each a fresh xterm replay — that was most of `ay ls`'s time. Keyed by the file's
4606
+ // size + mtime, so a long-running caller (serve) never gets a stale screen; the size cap bounds the memory.
4607
+ let key: string;
4608
+ try {
4609
+ const s = await stat(logPath);
4610
+ key = `${logPath}\0${s.size}\0${s.mtimeMs}\0${n}\0${geom?.cols ?? ""}x${geom?.rows ?? ""}`;
4611
+ } catch {
4612
+ return null;
4613
+ }
4614
+ const kept = renderDiskGet(key);
4615
+ if (Array.isArray(kept) && kept.every((l) => typeof l === "string")) {
4616
+ renderDiskPut(key, kept);
4617
+ return (kept as string[]).slice();
4618
+ }
4619
+ let hit = tailRenderCache.get(key);
4620
+ if (!hit) {
4621
+ const p = renderLogTailLinesUncached(logPath, n, geom);
4622
+ hit = p;
4623
+ if (tailRenderCache.size >= TAIL_RENDER_CACHE_MAX) {
4624
+ tailRenderCache.delete(tailRenderCache.keys().next().value as string);
4625
+ }
4626
+ tailRenderCache.set(key, p);
4627
+ // a failed read/render is not remembered: the next call retries (concurrent callers still share this one)
4628
+ void p.then((r) => {
4629
+ if (r === null && tailRenderCache.get(key) === p) tailRenderCache.delete(key);
4630
+ });
4631
+ }
4632
+ const lines = await hit;
4633
+ if (lines) renderDiskPut(key, lines);
4634
+ return lines ? lines.slice() : null; // a copy: callers may change their array
4635
+ }
4636
+
4637
+ const tailRenderCache = new Map<string, Promise<string[] | null>>();
4638
+ const TAIL_RENDER_CACHE_MAX = 256;
4639
+
4640
+ // Cross-run cache, `ay ls` only (enableRenderDiskCache): most agents are idle between two `ay ls` runs, so
4641
+ // their logs are unchanged and the rendered tails / task counts can be reused instead of replayed. Same keys
4642
+ // as above (path + size + mtime + …). Only the entries this run used are written back, so the file stays
4643
+ // small and entries of changed or gone logs drop out. Not for serve (long-running: nothing would be flushed).
4644
+ let renderDiskEnabled = false;
4645
+ let renderDiskPath = ""; // fixed when enabled, so a later AGENT_YES_HOME change cannot redirect the write
4646
+ let renderDisk: Record<string, unknown> | null = null;
4647
+ const renderDiskUsed = new Map<string, unknown>();
4648
+ const RENDER_DISK_MAX = 1024; // a safety bound: one `ay ls` run uses about 2 entries per agent
4649
+
4650
+ export function enableRenderDiskCache(): void {
4651
+ renderDiskEnabled = true;
4652
+ renderDiskPath = path.join(agentYesHome(), "cache", "ls-render.json");
4653
+ }
4654
+
4655
+ /** Turn the cross-run cache off and forget it in this process, without writing (tests). */
4656
+ export function resetRenderDiskCache(): void {
4657
+ if (renderDiskUsed.size > 0) process.removeListener("exit", saveRenderDisk);
4658
+ renderDiskEnabled = false;
4659
+ renderDiskPath = "";
4660
+ renderDisk = null;
4661
+ renderDiskUsed.clear();
4662
+ tailRenderCache.clear();
4663
+ }
4664
+
4665
+ function renderDiskGet(key: string): unknown {
4666
+ if (!renderDiskEnabled) return undefined;
4667
+ if (renderDisk === null) {
4668
+ try {
4669
+ const v: unknown = JSON.parse(readFileSync(renderDiskPath, "utf8"));
4670
+ renderDisk = v && typeof v === "object" ? (v as Record<string, unknown>) : {};
4671
+ } catch {
4672
+ renderDisk = {};
4673
+ }
4674
+ }
4675
+ return Object.prototype.hasOwnProperty.call(renderDisk, key) ? renderDisk[key] : undefined;
4676
+ }
4677
+
4678
+ function renderDiskPut(key: string, value: unknown): void {
4679
+ if (!renderDiskEnabled) return;
4680
+ if (renderDiskUsed.size >= RENDER_DISK_MAX && !renderDiskUsed.has(key)) return;
4681
+ if (renderDiskUsed.size === 0) process.once("exit", saveRenderDisk);
4682
+ renderDiskUsed.set(key, value);
4683
+ }
4684
+
4685
+ /** Write the entries this run used (runs at exit; exported for tests). */
4686
+ export function saveRenderDisk(): void {
4687
+ if (!renderDiskPath) return;
4688
+ try {
4689
+ const file = renderDiskPath;
4690
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
4691
+ const tmp = `${file}.${process.pid}.tmp`;
4692
+ writeFileSync(tmp, JSON.stringify(Object.fromEntries(renderDiskUsed)), { mode: 0o600 });
4693
+ renameSync(tmp, file);
4694
+ } catch {
4695
+ // a cache: losing it only costs the next run a replay
4696
+ }
4697
+ }
4698
+
4699
+ async function renderLogTailLinesUncached(
4700
+ logPath: string,
4701
+ n: number,
4702
+ geom?: RenderGeom,
4507
4703
  ): Promise<string[] | null> {
4508
4704
  const buf = await readLogTailBytes(logPath);
4509
4705
  if (!buf) return null;
@@ -4556,23 +4752,23 @@ function dropComposerTerm(logPath: string) {
4556
4752
  }
4557
4753
 
4558
4754
  /**
4559
- * What the target's composer holds right now, read from the same 32 KB tail
4560
- * `renderLogTailLines` renders (further back when a Claude screen shows no
4561
- * composer box), keeping per-cell attributes (dim/inverse) so ghost text can be
4562
- * told from a real draft. See ts/composerGuard.ts.
4755
+ * The bottom 40 rows of a log as the composer check sees them: rendered from
4756
+ * the 32 KB tail and, for Claude, from further back until its composer box is
4757
+ * on screen (see COMPOSER_WINDOWS). Keeps per-cell attributes. Null for an
4758
+ * empty log; throws when the log cannot be read or rendered.
4563
4759
  */
4564
- export async function readComposerState(
4565
- record: GlobalPidRecord,
4760
+ async function renderComposerRows(
4761
+ record: GlobalPidRecord & { log_file: string },
4566
4762
  windows = COMPOSER_WINDOWS,
4567
- ): Promise<ComposerState> {
4763
+ fromContent = false,
4764
+ ): Promise<ReturnType<typeof rowsFromXterm> | null> {
4568
4765
  const logPath = record.log_file;
4569
- if (!logPath) return { kind: "unknown", reason: "no log file recorded" };
4570
4766
  const geom = (await readAgentPtysize(record)) ?? undefined;
4571
4767
  const key = `${geom?.cols}x${geom?.rows}:${record.cli}:${windows.join()}`;
4572
4768
  const claude = record.cli === "claude";
4573
4769
  try {
4574
4770
  const { size } = await stat(logPath);
4575
- if (size === 0) return { kind: "unknown", reason: "log unreadable or empty" };
4771
+ if (size === 0) return null;
4576
4772
  let ct = composerTerms.get(logPath);
4577
4773
  if (ct && (ct.key !== key || size < ct.offset)) {
4578
4774
  dropComposerTerm(logPath); // resized, or the log was truncated
@@ -4586,9 +4782,16 @@ export async function readComposerState(
4586
4782
  await new Promise<void>((resolve) => ct!.term.write(delta, resolve));
4587
4783
  ct.offset += delta.length;
4588
4784
  }
4589
- rows = rowsFromXterm(ct.term as never, 40);
4785
+ rows = rowsFromXterm(ct.term as never, 40, fromContent);
4590
4786
  next = ct.whole ? windows.length : ct.window + 1;
4591
- if (!claude || composerBoxed(rows.map((r) => r.text))) next = windows.length;
4787
+ if (
4788
+ composerBoxed(
4789
+ rows.map((r) => r.text),
4790
+ record.cli,
4791
+ claude,
4792
+ )
4793
+ )
4794
+ next = windows.length;
4592
4795
  }
4593
4796
  for (let w = next; w < windows.length; w++) {
4594
4797
  const from = Math.max(0, size - windows[w]!);
@@ -4611,17 +4814,54 @@ export async function readComposerState(
4611
4814
  });
4612
4815
  if (composerTerms.size > COMPOSER_TERMS_MAX)
4613
4816
  dropComposerTerm(composerTerms.keys().next().value!); // oldest first
4614
- rows = rowsFromXterm(term as never, 40);
4615
- if (!claude || from === 0 || composerBoxed(rows.map((r) => r.text))) break;
4817
+ rows = rowsFromXterm(term as never, 40, fromContent);
4818
+ if (
4819
+ from === 0 ||
4820
+ composerBoxed(
4821
+ rows.map((r) => r.text),
4822
+ record.cli,
4823
+ claude,
4824
+ )
4825
+ )
4826
+ break;
4616
4827
  }
4617
- const state = classifyComposer(rows ?? []);
4828
+ return rows ?? [];
4829
+ } catch (e) {
4830
+ dropComposerTerm(logPath);
4831
+ throw e;
4832
+ }
4833
+ }
4834
+
4835
+ /**
4836
+ * What the target's composer holds right now, read from the same 32 KB tail
4837
+ * `renderLogTailLines` renders (further back when a Claude screen shows no
4838
+ * composer box), keeping per-cell attributes (dim/inverse) so ghost text can be
4839
+ * told from a real draft. See ts/composerGuard.ts.
4840
+ */
4841
+ export async function readComposerState(
4842
+ record: GlobalPidRecord,
4843
+ windows = COMPOSER_WINDOWS,
4844
+ ): Promise<ComposerState> {
4845
+ const logPath = record.log_file;
4846
+ if (!logPath) return { kind: "unknown", reason: "no log file recorded" };
4847
+ const claude = record.cli === "claude";
4848
+ try {
4849
+ const rows = await renderComposerRows({ ...record, log_file: logPath }, windows);
4850
+ if (!rows) return { kind: "unknown", reason: "log unreadable or empty" };
4851
+ const state = classifyComposer(rows, record.cli);
4618
4852
  // No window showed the box, so a "draft" was read under some other prompt
4619
4853
  // row, possibly an old turn: say so instead of reporting it as a draft.
4620
- if (claude && state.kind === "draft" && !composerBoxed((rows ?? []).map((r) => r.text)))
4854
+ if (
4855
+ state.kind === "draft" &&
4856
+ !composerBoxed(
4857
+ rows.map((r) => r.text),
4858
+ record.cli,
4859
+ claude,
4860
+ )
4861
+ )
4621
4862
  return { kind: "hidden", reason: "its input box is not on screen" };
4622
4863
  return state;
4623
4864
  } catch (e) {
4624
- dropComposerTerm(logPath);
4625
4865
  return {
4626
4866
  kind: "unknown",
4627
4867
  reason: `log unreadable or render failed: ${(e as Error)?.message ?? e}`,
@@ -4629,6 +4869,53 @@ export async function readComposerState(
4629
4869
  }
4630
4870
  }
4631
4871
 
4872
+ /** Waits between re-reads of a draft before it counts as abandoned (~15 s in all). */
4873
+ export const DRAFT_STABLE_WAITS_MS = [1000, 2000, 4000, 8000];
4874
+
4875
+ /** The bottom of the screen as plain text, to tell "unchanged" from "changed". */
4876
+ async function composerFingerprint(record: GlobalPidRecord): Promise<string | null> {
4877
+ if (!record.log_file) return null;
4878
+ try {
4879
+ const rows = await renderComposerRows({ ...record, log_file: record.log_file });
4880
+ return rows
4881
+ ? rows
4882
+ .slice(-8)
4883
+ .map((r) => r.text)
4884
+ .join("\n")
4885
+ : null;
4886
+ } catch {
4887
+ return null;
4888
+ }
4889
+ }
4890
+
4891
+ /**
4892
+ * The target's input box holds text and has not changed for DRAFT_STABLE_WAITS_MS
4893
+ * (1, 2, 4, 8 s): nobody is typing, so submit it with Enter and report true once
4894
+ * the box reads empty again. Only a draft: a menu or yes/no prompt is a question
4895
+ * agent-yes deliberately does not answer. Any change, or a box that never clears,
4896
+ * returns false and the caller parks the message as before.
4897
+ */
4898
+ export async function submitStableDraft(
4899
+ record: GlobalPidRecord,
4900
+ waits: number[] = DRAFT_STABLE_WAITS_MS,
4901
+ sleep: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
4902
+ ): Promise<boolean> {
4903
+ if ((await readComposerState(record)).kind !== "draft") return false;
4904
+ const base = await composerFingerprint(record);
4905
+ if (base === null) return false;
4906
+ for (const ms of waits) {
4907
+ await sleep(ms);
4908
+ if ((await composerFingerprint(record)) !== base) return false;
4909
+ }
4910
+ if (!record.fifo_file) return false;
4911
+ await withIpcLock(record.pid, () => writeToIpc(record.fifo_file!, "\r"));
4912
+ for (let i = 0; i < 5; i++) {
4913
+ await sleep(500);
4914
+ if ((await readComposerState(record)).kind === "empty") return true;
4915
+ }
4916
+ return false;
4917
+ }
4918
+
4632
4919
  /** Bytes `[from, to)` of a log file. */
4633
4920
  async function readLogRange(logPath: string, from: number, to: number): Promise<Uint8Array> {
4634
4921
  const fh = await open(logPath, "r");
@@ -4776,9 +5063,7 @@ function extractActivityFromLines(lines: string[]): string | null {
4776
5063
 
4777
5064
  // ❯ appears after (or without) any spinner → agent is idle/waiting for input
4778
5065
  if (lastPromptIdx > lastSpinnerIdx) {
4779
- const text = clean[lastPromptIdx]!.trim()
4780
- .replace(/^❯\s*/, "")
4781
- .trim();
5066
+ const text = clean[lastPromptIdx]!.trim().replace(/^❯\s*/, "").trim();
4782
5067
  return text ? `» ${text}` : null;
4783
5068
  }
4784
5069
 
@@ -5034,6 +5319,7 @@ type SubmissionState = "submitted" | "queued" | "not-submitted";
5034
5319
  export function inspectSubmission(
5035
5320
  screen: string[],
5036
5321
  identity: string,
5322
+ cli?: string,
5037
5323
  ): {
5038
5324
  submission: SubmissionState;
5039
5325
  retry: boolean;
@@ -5055,10 +5341,17 @@ export function inspectSubmission(
5055
5341
  const compact = (text: string) => text.replace(/\s+/gu, "");
5056
5342
  const needle = compact(identity);
5057
5343
  const wrapped = identity.startsWith("<ay-msg ");
5344
+ // A wrapped message also ends with `</ay-msg NONCE>`. A long body pushes its
5345
+ // header out of the rendered window (Claude echoes a queued message in full
5346
+ // above the composer), so the closing tag, which sits right above the
5347
+ // composer, is often the only copy of the nonce left on screen.
5348
+ const closer = wrapped ? compact(`</ay-msg ${identity.slice("<ay-msg ".length)}>`) : null;
5349
+ const occurrences = (text: string) =>
5350
+ Math.max(text.split(needle).length - 1, closer ? text.split(closer).length - 1 : 0);
5058
5351
  // The same boundary the draft check uses: a quoted `› line` inside our own
5059
5352
  // unsent message must not be taken for the prompt (that would count the
5060
5353
  // message's nonce as transcript evidence — codex review).
5061
- const prompt = composerPromptRow(screen);
5354
+ const prompt = composerPromptRow(screen, cli);
5062
5355
  if (prompt < 0) {
5063
5356
  // No composer on screen: a plain shell (cmd, bash, an ssh session) has no
5064
5357
  // `❯` row to inspect. It echoes the submitted line after its prompt and
@@ -5089,9 +5382,9 @@ export function inspectSubmission(
5089
5382
  const transcript = compact(transcriptLines.join("\n"));
5090
5383
  // For raw sends, a short body such as "x" must not match "Codex" or a
5091
5384
  // suggestion containing that character. Match whole rendered message lines.
5092
- let transcriptMatches = wrapped ? transcript.split(needle).length - 1 : 0;
5385
+ let transcriptMatches = wrapped ? occurrences(transcript) : 0;
5093
5386
  if (!wrapped) {
5094
- const lines = transcriptLines.map((line) => compact(line.replace(/^\s*[❯›]\s*/u, "")));
5387
+ const lines = transcriptLines.map((line) => compact(stripPromptGlyph(line, cli)));
5095
5388
  for (let start = 0; start < lines.length; start++) {
5096
5389
  let candidate = "";
5097
5390
  for (let end = start; end < lines.length && candidate.length < needle.length; end++) {
@@ -5103,14 +5396,14 @@ export function inspectSubmission(
5103
5396
  }
5104
5397
  }
5105
5398
  }
5106
- const input: string[] = [screen[prompt]!.replace(/^\s*[❯›]\s*/u, "")];
5399
+ const input: string[] = [stripPromptGlyph(screen[prompt]!, cli)];
5107
5400
  for (const line of screen.slice(prompt + 1)) {
5108
5401
  // A rule or the Claude/Codex footer chrome (incl. the model/cwd status row).
5109
5402
  if (isComposerChrome(line)) break;
5110
5403
  input.push(line);
5111
5404
  }
5112
5405
  const composer = compact(input.join("\n"));
5113
- if (wrapped ? composer.includes(needle) : composer === needle) {
5406
+ if (wrapped ? occurrences(composer) > 0 : composer === needle) {
5114
5407
  return {
5115
5408
  submission: "not-submitted",
5116
5409
  retry: true,
@@ -5136,8 +5429,8 @@ export function inspectSubmission(
5136
5429
  return { ...unknown, composerVisible: true };
5137
5430
  }
5138
5431
 
5139
- export function submissionState(screen: string[], identity = ""): SubmissionState {
5140
- return inspectSubmission(screen, identity).submission;
5432
+ export function submissionState(screen: string[], identity = "", cli?: string): SubmissionState {
5433
+ return inspectSubmission(screen, identity, cli).submission;
5141
5434
  }
5142
5435
 
5143
5436
  /** A collapsed paste is not delivery evidence; it can only authorize a retry. */
@@ -5160,6 +5453,24 @@ export function ownedCollapsedPaste(
5160
5453
  return token && !beforePaste.join("\n").includes(token) ? token : null;
5161
5454
  }
5162
5455
 
5456
+ /**
5457
+ * The target's screen as submit-confirm reads it. For Claude this is the
5458
+ * composer check's render, which goes further back than the 32 KB tail when the
5459
+ * tail lacks the composer box: Claude redraws only changed rows, so while it is
5460
+ * busy the tail can hold spinner redraws but neither the box nor a message
5461
+ * queued above it, and nothing on such a screen can be attributed to our send.
5462
+ */
5463
+ async function renderSendScreen(
5464
+ record: GlobalPidRecord & { log_file: string },
5465
+ geometry?: RenderGeom,
5466
+ ): Promise<string[]> {
5467
+ if (record.cli === "claude") {
5468
+ const rows = await renderComposerRows(record, COMPOSER_WINDOWS, true).catch(() => undefined);
5469
+ if (rows !== undefined) return (rows ?? []).map((r) => r.text);
5470
+ }
5471
+ return (await renderLogTailLines(record.log_file, 40, geometry)) ?? [];
5472
+ }
5473
+
5163
5474
  export const SEND_EXIT_QUEUED = 4;
5164
5475
 
5165
5476
  /** Retry only Enter, never the body. Three attempts, phi delay capped at 400ms. */
@@ -5171,10 +5482,11 @@ export async function submitAndConfirm(
5171
5482
  beforePaste?: string[] | null,
5172
5483
  ): Promise<{ confirmed: boolean; screen: string[]; submission: SubmissionState }> {
5173
5484
  const logFile = record.log_file!;
5485
+ const target = { ...record, log_file: logFile };
5174
5486
  const geometry = (await readAgentPtysize(record)) ?? undefined;
5175
5487
  const cfg = (await cliDefaults())[record.cli];
5176
- let screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
5177
- const before = inspectSubmission(screen, identity);
5488
+ let screen = await renderSendScreen(target, geometry);
5489
+ const before = inspectSubmission(screen, identity, record.cli);
5178
5490
  const baseline = before.transcriptMatches;
5179
5491
  // Delivered = a NEW copy in the transcript, or — what a count in a rolling
5180
5492
  // 40-line window cannot show for a repeated raw message like "continue" —
@@ -5194,14 +5506,17 @@ export async function submitAndConfirm(
5194
5506
  };
5195
5507
  };
5196
5508
  const ownPaste = ownedCollapsedPaste(record.cli, beforePaste, screen);
5509
+ // Immediate-send shortcuts may cancel work. A requested shortcut is sent
5510
+ // once; only native Enter is safe to retry against an owned composer.
5197
5511
  const canRetry = (evidence: ReturnType<typeof inspectSubmission>, current: string[]) =>
5198
- evidence.retry || (ownPaste !== null && collapsedPasteToken(current) === ownPaste);
5512
+ trailing === "\r" &&
5513
+ (evidence.retry || (ownPaste !== null && collapsedPasteToken(current) === ownPaste));
5199
5514
  for (let attempt = 0; attempt <= SEND_SUBMIT_MAX_RETRIES; attempt++) {
5200
5515
  if (attempt) {
5201
5516
  await new Promise((r) => setTimeout(r, Math.min(400, 150 * 1.618 ** (attempt - 1))));
5202
5517
  // Recheck after the delay: the target could have accepted the earlier Enter.
5203
- screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
5204
- const settled = inspectSubmission(screen, identity);
5518
+ screen = await renderSendScreen(target, geometry);
5519
+ const settled = inspectSubmission(screen, identity, record.cli);
5205
5520
  if (delivered(settled)) return outcome(settled, screen);
5206
5521
  if (
5207
5522
  !canRetry(settled, screen) ||
@@ -5212,8 +5527,8 @@ export async function submitAndConfirm(
5212
5527
  }
5213
5528
  await writeToIpc(fifoPath, trailing);
5214
5529
  await waitForLogQuiet(logFile, SEND_CONFIRM_QUIET_MS, SEND_CONFIRM_MAX_MS);
5215
- screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
5216
- const evidence = inspectSubmission(screen, identity);
5530
+ screen = await renderSendScreen(target, geometry);
5531
+ const evidence = inspectSubmission(screen, identity, record.cli);
5217
5532
  if (delivered(evidence)) return outcome(evidence, screen);
5218
5533
  if (!canRetry(evidence, screen)) break;
5219
5534
  }
@@ -5255,9 +5570,8 @@ async function deliverBody(
5255
5570
  if (fullBody && trailing) {
5256
5571
  const beforePaste =
5257
5572
  canConfirm && record.log_file
5258
- ? await renderLogTailLines(
5259
- record.log_file,
5260
- 40,
5573
+ ? await renderSendScreen(
5574
+ { ...record, log_file: record.log_file },
5261
5575
  (await readAgentPtysize(record)) ?? undefined,
5262
5576
  )
5263
5577
  : null;
@@ -5281,6 +5595,43 @@ async function deliverBody(
5281
5595
  };
5282
5596
  }
5283
5597
 
5598
+ /** Called under the same input lock as the subsequent paste and submit. */
5599
+ export async function interruptSendTarget(
5600
+ record: GlobalPidRecord,
5601
+ fifoPath: string,
5602
+ ): Promise<string> {
5603
+ const cfg = (await cliDefaults())[record.cli] ?? {};
5604
+ const result = await interruptBeforeSend(record.cli, {
5605
+ readState: async () => {
5606
+ if (!record.log_file) return "unknown";
5607
+ const screen = await renderSendScreen({ ...record, log_file: record.log_file });
5608
+ return interruptScreenState(record.cli, screen, cfg);
5609
+ },
5610
+ write: (code) => writeToIpc(fifoPath, code),
5611
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
5612
+ });
5613
+ const notice =
5614
+ result === "permission"
5615
+ ? "ay send: --interrupt skipped: target is at a permission/confirmation prompt; sending as usual"
5616
+ : result === "unknown" || result === "unsupported"
5617
+ ? `ay send: --interrupt skipped: ${result === "unknown" ? "could not verify the target's screen" : `unsupported CLI ${record.cli}`}; sending as usual`
5618
+ : `ay send: ${result === "interrupted" ? "current turn interrupted; idle prompt confirmed" : "target is already idle"}`;
5619
+ process.stderr.write(notice + "\n");
5620
+ return notice;
5621
+ }
5622
+
5623
+ async function interruptPermissionPrompt(record: GlobalPidRecord): Promise<boolean> {
5624
+ if (!record.log_file) return false;
5625
+ const cfg = (await cliDefaults())[record.cli] ?? {};
5626
+ return (
5627
+ interruptScreenState(
5628
+ record.cli,
5629
+ await renderSendScreen({ ...record, log_file: record.log_file }),
5630
+ cfg,
5631
+ ) === "permission"
5632
+ );
5633
+ }
5634
+
5284
5635
  // Drainer pacing: poll the parked target with a φ backoff from 500 ms up to 5 s,
5285
5636
  // reset after every delivery. Worst case a message waits PENDING_MAX_AGE_MS.
5286
5637
  const DRAIN_POLL_BASE_MS = 500;
@@ -5424,6 +5775,9 @@ async function cmdSendDrain(rest: string[]): Promise<number> {
5424
5775
  }
5425
5776
  const record = (await readGlobalPids()).find((r) => r.pid === pid);
5426
5777
  let result: Awaited<ReturnType<typeof deliverBody>> | null = null;
5778
+ // A draft nobody touches (unchanged at 1/2/4/8 s) is submitted for its
5779
+ // owner here too, so a message parked behind it is not stuck forever.
5780
+ if (record && !msg.interrupt && !(await isUserTyping(pid))) await submitStableDraft(record);
5427
5781
  if (record && !(await isUserTyping(pid))) {
5428
5782
  await withIpcLock(pid, async () => {
5429
5783
  // Re-check under the lock, right before the write.
@@ -5432,6 +5786,10 @@ async function cmdSendDrain(rest: string[]): Promise<number> {
5432
5786
  // screen or one without a composer (a menu) waits for the next poll.
5433
5787
  const composer = await readComposerState(record);
5434
5788
  if (composer.kind !== "empty") return;
5789
+ if (msg.interrupt) {
5790
+ await interruptSendTarget(record, msg.fifoPath);
5791
+ if ((await readComposerState(record)).kind !== "empty") return;
5792
+ }
5435
5793
  if (!(await claimPending(pid, name))) return;
5436
5794
  result = await deliverBody(
5437
5795
  record,
@@ -5439,7 +5797,7 @@ async function cmdSendDrain(rest: string[]): Promise<number> {
5439
5797
  msg.fullBody,
5440
5798
  msg.trailing,
5441
5799
  msg.identity,
5442
- msg.trailing === "\r" && Boolean(record.log_file),
5800
+ isSubmitCode(msg.trailing) && Boolean(record.log_file),
5443
5801
  );
5444
5802
  });
5445
5803
  }
@@ -5467,6 +5825,7 @@ async function cmdSendDrain(rest: string[]): Promise<number> {
5467
5825
 
5468
5826
  async function cmdSend(rest: string[]): Promise<number> {
5469
5827
  const y = yargs(rest)
5828
+ .help(false)
5470
5829
  // Disable yargs' `--no-<flag>` negation: without this, `--no-wait` is parsed
5471
5830
  // as negating a phantom `wait` option (argv.wait=false) instead of setting our
5472
5831
  // explicitly-defined `no-wait`/`noWait` flag — so `--no-wait` silently did
@@ -5475,6 +5834,9 @@ async function cmdSend(rest: string[]): Promise<number> {
5475
5834
  .parserConfiguration({ "boolean-negation": false })
5476
5835
  .usage(
5477
5836
  "Usage: ay send <keyword> <msg|-> [options]\n\n" +
5837
+ "Busy targets receive input without waiting for idle using native Enter input.\n" +
5838
+ "Explicit --code=alt-m requests immediate send and may interrupt work.\n" +
5839
+ "Existing drafts are protected and may defer delivery.\n\n" +
5478
5840
  "Exit: 0 sent, 3 target unreachable (nothing sent; ay ls shows it as\n" +
5479
5841
  "'unreachable' — ay restart <pid> revives it), 4 QUEUED (accepted, not yet\n" +
5480
5842
  "submitted: either the CLI queued it, or its input box held someone's draft and\n" +
@@ -5485,8 +5847,17 @@ async function cmdSend(rest: string[]): Promise<number> {
5485
5847
  .option("code", {
5486
5848
  type: "string",
5487
5849
  default: "enter",
5488
- description: "Trailing control code (enter|esc|ctrl-c|ctrl-y|tab|none)",
5850
+ description:
5851
+ "Trailing control code (enter|alt-m|esc|ctrl-c|ctrl-y|tab|none); alt-m may interrupt work",
5852
+ })
5853
+ .option("interrupt", {
5854
+ alias: "i",
5855
+ type: "boolean",
5856
+ default: false,
5857
+ description:
5858
+ "Stop a local target's current turn, wait for idle, then deliver; never cancel a permission/confirmation prompt",
5489
5859
  })
5860
+ .option("help", { alias: "h", type: "boolean", description: "Show send options" })
5490
5861
  .option("all", { type: "boolean", default: false, description: "Include exited agents" })
5491
5862
  .option("latest", { type: "boolean", default: false, description: "Use most recent match" })
5492
5863
  .option("cwd", { type: "string", description: "Restrict to agents under this dir" })
@@ -5510,7 +5881,6 @@ async function cmdSend(rest: string[]): Promise<number> {
5510
5881
  description:
5511
5882
  "Send the body verbatim: omit the <ay-msg …> attribution wrapper that agent senders add by default (also: AGENT_YES_SEND_RAW=1)",
5512
5883
  })
5513
- .help(false)
5514
5884
  .version(false)
5515
5885
  // An UNKNOWN flag must be an error, never a silent reinterpretation of the
5516
5886
  // message. yargs otherwise swallows `--body-file /tmp/x` as an ad-hoc option
@@ -5524,6 +5894,10 @@ async function cmdSend(rest: string[]): Promise<number> {
5524
5894
  .exitProcess(false);
5525
5895
 
5526
5896
  const argv = await y.parseAsync();
5897
+ if (argv.help) {
5898
+ process.stdout.write((await y.getHelp()) + "\n");
5899
+ return 0;
5900
+ }
5527
5901
  const opts: CommonOpts = {
5528
5902
  all: argv.all,
5529
5903
  active: false,
@@ -5535,7 +5909,9 @@ async function cmdSend(rest: string[]): Promise<number> {
5535
5909
  const rawMessage = argv._.slice(1).map(String).join(" ");
5536
5910
 
5537
5911
  if (!keyword)
5538
- throw new Error("usage: ay send <keyword> <msg|-> [--code=enter|esc|ctrl-c|ctrl-y|tab|none]");
5912
+ throw new Error(
5913
+ "usage: ay send <keyword> <msg|-> [--code=enter|alt-m|esc|ctrl-c|ctrl-y|tab|none]",
5914
+ );
5539
5915
 
5540
5916
  // Second line of defence, independent of how the message went missing: never
5541
5917
  // deliver nothing. Sending an empty body is never what anyone meant, and its
@@ -5553,6 +5929,10 @@ async function cmdSend(rest: string[]): Promise<number> {
5553
5929
  const remote = await resolveRemoteSpec(keyword);
5554
5930
  // --raw / AGENT_YES_SEND_RAW means "deliver verbatim"; it has to be honoured
5555
5931
  // on this path too, now that the remote path wraps at all.
5932
+ if (remote && argv.interrupt)
5933
+ throw new Error(
5934
+ "ay send: --interrupt requires a local target; run ay send --interrupt on the target host",
5935
+ );
5556
5936
  if (remote)
5557
5937
  return runRemoteSend(
5558
5938
  remote,
@@ -5746,6 +6126,7 @@ async function cmdSend(rest: string[]): Promise<number> {
5746
6126
  }
5747
6127
  const fullBody = framePaste ? frameAsPaste(prefix + body + suffix) : prefix + body + suffix;
5748
6128
  const noWait = Boolean(argv.noWait) || process.env.AGENT_YES_SEND_NO_WAIT === "1";
6129
+ let interrupt = argv.interrupt;
5749
6130
 
5750
6131
  // Back off while the user is typing at the target's terminal — injecting our
5751
6132
  // body mid-line fuses into their text and submits a mangled line. Only for a
@@ -5764,12 +6145,12 @@ async function cmdSend(rest: string[]): Promise<number> {
5764
6145
  );
5765
6146
  }
5766
6147
  }
5767
- // Submit-confirm only applies to an actual submit (Enter/CR) with a body and a
6148
+ // Submit-confirm only applies to an actual submit (Enter/CR or explicit Alt+M) with a body and a
5768
6149
  // log to watch — other trailing codes (esc/ctrl-c/tab/none) don't have a "did
5769
6150
  // it land" signal in the same sense, and retrying e.g. ctrl-c could
5770
6151
  // double-interrupt. Checked against the resolved byte, not the code NAME, so
5771
- // every alias that resolves to Enter (--code=enter or --code=cr) is covered.
5772
- const canConfirm = trailing === "\r" && Boolean(fullBody) && !noWait;
6152
+ // every submit alias is covered. Alt+M is never automatically retried.
6153
+ const canConfirm = isSubmitCode(trailing) && Boolean(fullBody) && !noWait;
5773
6154
  const identity = nonce ? `<ay-msg ${nonce}` : body;
5774
6155
  let confirmed = !canConfirm;
5775
6156
  const receipt: { submission: "submitted" | "queued" | "not-submitted" | "unchecked" } = {
@@ -5798,6 +6179,17 @@ async function cmdSend(rest: string[]): Promise<number> {
5798
6179
  code: trailing === "\r" ? undefined : codeName,
5799
6180
  wrapped: Boolean(nonce),
5800
6181
  };
6182
+ // A draft nobody is touching (unchanged at 1, 2, 4, 8 s) is submitted for its
6183
+ // owner, so it does not hold this message until someone clears the box.
6184
+ if (
6185
+ fullBody &&
6186
+ !interrupt &&
6187
+ !noWait &&
6188
+ !parkReason &&
6189
+ (await listPending(record.pid)).length === 0
6190
+ ) {
6191
+ await submitStableDraft(record);
6192
+ }
5801
6193
  // The body and its Enter are ONE transaction: every gap between them (the
5802
6194
  // paste-settle wait, the submit-confirm retries) is a window where another
5803
6195
  // writer's bytes would land mid-message. See ts/ipcLock.ts.
@@ -5818,6 +6210,26 @@ async function cmdSend(rest: string[]): Promise<number> {
5818
6210
  duplicateOf = await findRecentDuplicate(record.pid, dedupeKey, body);
5819
6211
  if (duplicateOf) return;
5820
6212
  }
6213
+ const park = async () => {
6214
+ if (dedupeKey) await noteRecentSend(record.pid, dedupeKey, body, "queued");
6215
+ await enqueuePending({
6216
+ queuedAt: Date.now(),
6217
+ pid: record.pid,
6218
+ fifoPath,
6219
+ fullBody,
6220
+ trailing,
6221
+ interrupt,
6222
+ identity,
6223
+ record: mailBase,
6224
+ });
6225
+ parked = true;
6226
+ };
6227
+ if (interrupt && (await interruptPermissionPrompt(record))) {
6228
+ process.stderr.write(
6229
+ "ay send: --interrupt skipped: target is at a permission/confirmation prompt; sending as usual\n",
6230
+ );
6231
+ interrupt = false;
6232
+ }
5821
6233
  if (fullBody) {
5822
6234
  if (!parkReason && (await listPending(record.pid)).length)
5823
6235
  parkReason = "earlier messages to this agent are still queued";
@@ -5831,19 +6243,19 @@ async function cmdSend(rest: string[]): Promise<number> {
5831
6243
  `warning: ay send could not see pid ${record.pid}'s input box (${composer.reason}) — sending without the draft check.\n`,
5832
6244
  );
5833
6245
  }
5834
- if (dedupeKey)
5835
- await noteRecentSend(record.pid, dedupeKey, body, parkReason ? "queued" : "sent");
5836
6246
  if (parkReason) {
5837
- await enqueuePending({
5838
- queuedAt: Date.now(),
5839
- pid: record.pid,
5840
- fifoPath,
5841
- fullBody,
5842
- trailing,
5843
- identity,
5844
- record: mailBase,
5845
- });
5846
- parked = true;
6247
+ await park();
6248
+ return;
6249
+ }
6250
+ }
6251
+ if (interrupt) {
6252
+ await interruptSendTarget(record, fifoPath);
6253
+ // Cancellation can restore a prior draft. Recheck before pasting so
6254
+ // stopping the turn never submits or overwrites that restored input.
6255
+ const composer = await readComposerState(record);
6256
+ if (composer.kind === "draft" || composer.kind === "hidden") {
6257
+ parkReason = "input box was occupied after cancelling the current turn";
6258
+ await park();
5847
6259
  return;
5848
6260
  }
5849
6261
  }
@@ -5852,6 +6264,7 @@ async function cmdSend(rest: string[]): Promise<number> {
5852
6264
  screen: lastScreen,
5853
6265
  submission: receipt.submission,
5854
6266
  } = await deliverBody(record, fifoPath, fullBody, trailing, identity, canConfirm));
6267
+ if (dedupeKey) await noteRecentSend(record.pid, dedupeKey, body, "sent");
5855
6268
  },
5856
6269
  (why) =>
5857
6270
  process.stderr.write(
@@ -6353,12 +6766,19 @@ export const GRACEFUL_EXIT_COMMANDS: Record<string, string> = {
6353
6766
  powershell: "exit",
6354
6767
  };
6355
6768
 
6769
+ export function isSubmitCode(code: string): boolean {
6770
+ return code === "\r" || code === "\x1bm";
6771
+ }
6772
+
6356
6773
  export function controlCodeFromName(name: string): string {
6357
6774
  switch (name) {
6358
6775
  case "enter":
6359
6776
  case "cr":
6360
6777
  case "return":
6361
6778
  return "\r";
6779
+ case "alt-m":
6780
+ case "alt+m":
6781
+ return "\x1bm";
6362
6782
  case "esc":
6363
6783
  case "escape":
6364
6784
  return "\x1b";