agent-yes 1.299.1 → 1.300.1

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 (51) hide show
  1. package/README.md +9 -0
  2. package/default.config.yaml +12 -0
  3. package/dist/{SUPPORTED_CLIS-MftynU62.js → SUPPORTED_CLIS-BUn4zN_B.js} +3 -3
  4. package/dist/{SUPPORTED_CLIS-YZvIGQvw.js → SUPPORTED_CLIS-DWZDaH9f.js} +2 -2
  5. package/dist/{agentShare-dKQQSOD7.js → agentShare-DpJmCvJ2.js} +3 -3
  6. package/dist/{callback-BEbbWLKe.js → callback-BW73zdcS.js} +3 -3
  7. package/dist/{callback-DWxTSlly.js → callback-DQrYImyf.js} +3 -3
  8. package/dist/cli.js +5 -5
  9. package/dist/{cmdPs-D7HWttUU.js → cmdPs-DBt-LD-H.js} +3 -3
  10. package/dist/index.js +2 -2
  11. package/dist/{notifyDaemon-B0aU7koS.js → notifyDaemon-BkuOBb_g.js} +3 -3
  12. package/dist/{parentPingLoop-DSiOXQeU.js → parentPingLoop-d0GZjqY9.js} +2 -2
  13. package/dist/{remotes-DrYe_nfw.js → remotes-B4v0Nowo.js} +64 -7
  14. package/dist/remotes-DnMQWaqQ.js +5 -0
  15. package/dist/{rustBinary-DgRg5H6V.js → rustBinary-CVjRaDmT.js} +2 -2
  16. package/dist/{rustBinary-CKuufNRn.js → rustBinary-DdWIf051.js} +2 -2
  17. package/dist/{schedule-BStFx0_s.js → schedule-C0HWIN7Z.js} +4 -4
  18. package/dist/{serve-Cis4oJM-.js → serve-DTQomE4j.js} +42 -28
  19. package/dist/{setup-B0sg4AV1.js → setup-BwZ3UlCM.js} +2 -2
  20. package/dist/{shareCmd-DKIvwe0I.js → shareCmd-Cx2kxthJ.js} +3 -3
  21. package/dist/subcommands-R1eJF51D.js +13 -0
  22. package/dist/{subcommands-CvL_1Nt9.js → subcommands-sr1CIEeP.js} +760 -77
  23. package/dist/{terminal-DqsAuqhw.js → terminal-CHPcyJuv.js} +2 -2
  24. package/dist/{trayApp-Dayj9Frx.js → trayApp-CjUWDytD.js} +2 -2
  25. package/dist/trayApp-K6-U3syh.js +5 -0
  26. package/dist/{ts-C2osm4MO.js → ts-tta7Z887.js} +3 -3
  27. package/dist/{versionChecker-BmXwOe40.js → versionChecker-qFzGUoUo.js} +2 -2
  28. package/dist/{widget-D5tsB-oi.js → widget-BOUSiXVj.js} +3 -3
  29. package/dist/{ws-mz7VJJwO.js → ws-BV2o8Zce.js} +2 -2
  30. package/dist/{ws-B4jdOeB2.js → ws-xxrH3pXD.js} +3 -3
  31. package/package.json +1 -1
  32. package/ts/composerGuard.spec.ts +279 -0
  33. package/ts/composerGuard.ts +366 -0
  34. package/ts/globalPidIndex.ts +7 -0
  35. package/ts/messageLog.ts +2 -0
  36. package/ts/needsInput.bun.spec.ts +36 -0
  37. package/ts/needsInput.spec.ts +36 -0
  38. package/ts/remotes.bun.spec.ts +125 -0
  39. package/ts/remotes.spec.ts +125 -0
  40. package/ts/remotes.ts +95 -5
  41. package/ts/serve.bun.spec.ts +50 -0
  42. package/ts/serve.spec.ts +57 -1
  43. package/ts/serve.ts +50 -9
  44. package/ts/subcommands.spec.ts +512 -42
  45. package/ts/subcommands.ts +629 -79
  46. package/ts/workDir.bun.spec.ts +90 -0
  47. package/ts/workDir.spec.ts +90 -0
  48. package/ts/workDir.ts +75 -0
  49. package/dist/remotes-BDMnvGI6.js +0 -5
  50. package/dist/subcommands-DioyG80q.js +0 -13
  51. package/dist/trayApp-C6C7-TSh.js +0 -5
@@ -8,17 +8,17 @@ import { n as localHost, r as localUser, t as formatIdentity } from "./identity-
8
8
  import { n as isWorkingScreen, r as parseMenu, t as classifyNeedsInput } from "./needsInput-BHopZGM8.js";
9
9
  import { S as postmortemStartedAt, _ as filterSinceSeq, a as getCursor, b as maxSeq, f as readInbox, o as heartbeatWatcher, p as setCursor, r as clearWatcher, s as hostId, v as filterSinceTs, y as filterUnread } from "./notifyStore-2SWKGwZI.js";
10
10
  import { n as isWebrtcSpec } from "./webrtcLink-DFRyWNMs.js";
11
- import { c as resolveRemoteSpec, s as readRemotes } from "./remotes-DrYe_nfw.js";
11
+ import { l as readRemotes, u as resolveRemoteSpec } from "./remotes-B4v0Nowo.js";
12
12
  import { execFile } from "child_process";
13
13
  import ms from "ms";
14
14
  import yargs from "yargs";
15
15
  import { closeSync, constants, openSync, realpathSync } from "fs";
16
- import { appendFile, mkdir, open, readFile, rename, stat, writeFile } from "fs/promises";
16
+ import { appendFile, mkdir, open, readFile, readdir, rename, rm, stat, writeFile } from "fs/promises";
17
17
  import { homedir } from "os";
18
18
  import path from "path";
19
19
  import { lock } from "proper-lockfile";
20
20
  import { execFileSync as execFileSync$1 } from "node:child_process";
21
- import { randomBytes } from "crypto";
21
+ import { createHash, randomBytes } from "crypto";
22
22
  import { promisify } from "util";
23
23
 
24
24
  //#region ts/agentTree.ts
@@ -991,6 +991,306 @@ async function withIpcLock(pid, fn, onFallback) {
991
991
  }
992
992
  }
993
993
 
994
+ //#endregion
995
+ //#region ts/workDir.ts
996
+ function isWithin(child, parent) {
997
+ const rel = path.relative(parent, child);
998
+ return rel === "" || !rel.startsWith("..") && !path.isAbsolute(rel);
999
+ }
1000
+ function workdirSamplePath(pid) {
1001
+ return path.join(agentYesHome(), "workdir", `${pid}.json`);
1002
+ }
1003
+ /**
1004
+ * The wrapper's latest sample for this agent, or null. A sample whose
1005
+ * `agent_id` doesn't match belongs to an earlier agent that had the same pid.
1006
+ */
1007
+ async function readWorkdirSample(r) {
1008
+ try {
1009
+ const j = JSON.parse(await readFile(workdirSamplePath(r.pid), "utf-8"));
1010
+ if (typeof j?.workdir !== "string" || typeof j?.at !== "number") return null;
1011
+ if (!r.agent_id || j.agent_id !== r.agent_id) return null;
1012
+ return {
1013
+ workdir: j.workdir,
1014
+ at: j.at
1015
+ };
1016
+ } catch {
1017
+ return null;
1018
+ }
1019
+ }
1020
+ /**
1021
+ * The effective work dir for a record. The sampled repo wins unless it merely
1022
+ * contains the spawn dir (a lane working in the repo it was spawned in — the
1023
+ * spawn cwd is the more precise answer) or it no longer exists.
1024
+ */
1025
+ async function resolveWorkDir(r) {
1026
+ const spawn = {
1027
+ workdir: r.cwd,
1028
+ workdir_source: "spawn",
1029
+ workdir_at: null
1030
+ };
1031
+ const sample = await readWorkdirSample(r);
1032
+ const w = sample?.workdir;
1033
+ if (!w || isWithin(r.cwd, w)) return spawn;
1034
+ if (!await stat(w).then((s) => s.isDirectory(), () => false)) return spawn;
1035
+ return {
1036
+ workdir: w,
1037
+ workdir_source: "observed",
1038
+ workdir_at: sample.at
1039
+ };
1040
+ }
1041
+
1042
+ //#endregion
1043
+ //#region ts/composerGuard.ts
1044
+ /**
1045
+ * Composer guard for `ay send`: never type into, append to, or submit a draft
1046
+ * someone else left in the target's input box.
1047
+ *
1048
+ * Why: a terminal shared by a human and by other agents' `ay send` has ONE
1049
+ * composer. Observed 2026-10-08: a human had typed "btw how" and paused; a lane's
1050
+ * report was pasted after it and Enter submitted both as one turn, so the human's
1051
+ * half-written message went out early, fused with the report, and the rest of it
1052
+ * was lost. The stdin-activity backoff (isUserTyping) cannot see this: it only
1053
+ * knows when the last key was pressed, not whether text is still sitting there.
1054
+ *
1055
+ * So the send path reads the composer off the rendered screen first. When it
1056
+ * holds real input, the message is parked in a per-target file queue and a
1057
+ * single detached drainer delivers it once the composer is empty again.
1058
+ *
1059
+ * Telling a draft from ghost text: Claude Code renders its prompt suggestion
1060
+ * (and the "Press up to edit queued messages" hint) with SGR 2 (dim/faint) in the
1061
+ * default colour; typed or pasted input is drawn without SGR 2. Measured on the
1062
+ * raw PTY log of a live lane: the suggestion frame is `ESC[2mwater the plants
1063
+ * ESC[22m` on the prompt row, while typed text on the same row is plain. Colour
1064
+ * is not used: typed input is drawn in the default colour, exactly like the
1065
+ * ghost, and the user's theme changes the palette but not the SGR 2 attribute.
1066
+ * Inverse cells are ignored too: a TUI that paints its own cursor as an inverse
1067
+ * block over the first ghost character must not turn a suggestion into a draft.
1068
+ */
1069
+ const PROMPT_RE = /^\s*[❯›]($|\s)/u;
1070
+ const SEPARATOR_RE = /^\s*[─━]{3,}/u;
1071
+ const FOOTER_RE = /^\s*(?:·\s*)?(?:[←→] .*agents|\? for shortcuts|esc to interrupt|ctrl\+t to|GPT-[^·]*·|gpt-[^·]*·|⏵⏵|⏸|⏎ send|\d+% context left)/iu;
1072
+ const FOOTER_SEGMENT_RE = /·\s*(?:[←→] .*agents?|↓ |esc to interrupt)|\(shift\+tab to /u;
1073
+ /**
1074
+ * The composer's prompt row among plain-text rows (oldest first), or -1.
1075
+ * Claude Code boxes its composer, so the prompt is the row directly under the
1076
+ * LAST rule that has a prompt row under it — a `›`/`❯` that merely starts a
1077
+ * line of a multi-line draft is inside the box, not a second prompt. Without
1078
+ * any box (Codex) it is the last prompt-looking row. Shared by the draft check
1079
+ * and by submission confirmation, so both agree on where history ends.
1080
+ */
1081
+ function composerPromptRow(texts) {
1082
+ for (let i = texts.length - 2; i >= 0; i--) if (SEPARATOR_RE.test(texts[i]) && PROMPT_RE.test(texts[i + 1])) return i + 1;
1083
+ return texts.findLastIndex((t) => PROMPT_RE.test(t));
1084
+ }
1085
+ /**
1086
+ * Is this row composer chrome (a rule or a Claude/Codex footer) — the end of the
1087
+ * input? Pass the row's `cells` when known: the loose footer match then also
1088
+ * requires every visible cell to be coloured, so a typed line is never cut off.
1089
+ */
1090
+ function isComposerChrome(text, cells) {
1091
+ if (SEPARATOR_RE.test(text) || FOOTER_RE.test(text)) return true;
1092
+ if (!FOOTER_SEGMENT_RE.test(text)) return false;
1093
+ return !cells || cells.every((c) => !c.ch.trim() || c.ch === "\xA0" || c.colored);
1094
+ }
1095
+ /**
1096
+ * Classify the composer from rendered rows (oldest first, screen bottom last).
1097
+ *
1098
+ * Claude Code draws the composer as a box: a rule, the prompt row, any further
1099
+ * draft rows, a rule. The box is found by its TOP rule (the last rule directly
1100
+ * followed by a prompt row) and runs to the next rule, so a draft line that
1101
+ * itself starts with `›`/`❯`, or a blank line inside a multi-line draft, stays
1102
+ * inside it. When the bottom rule is not on screen (a partial redraw in the
1103
+ * replayed tail) the box ends at the footer instead.
1104
+ *
1105
+ * Without a top rule (Codex) the composer is the last prompt row plus every row
1106
+ * under it up to a rule or the footer (Codex's `⏎ send` hints / `% context
1107
+ * left` row) — blank rows included, so a multi-line draft with a blank line in
1108
+ * it is not cut short and read as empty (codex review). Any other non-dim text
1109
+ * down there counts as a draft: parking a message is recoverable, typing into a
1110
+ * draft is not. A draft whose own line starts with a prompt glyph can still be
1111
+ * misread there.
1112
+ */
1113
+ function classifyComposer(rows) {
1114
+ const prompt = composerPromptRow(rows.map((r) => r.text));
1115
+ if (prompt < 0) return {
1116
+ kind: "unknown",
1117
+ reason: "no prompt row on screen"
1118
+ };
1119
+ let real = 0;
1120
+ let ghost = false;
1121
+ for (let i = prompt; i < rows.length; i++) {
1122
+ const row = rows[i];
1123
+ if (i > prompt) {
1124
+ if (isComposerChrome(row.text, row.cells)) break;
1125
+ if (!row.text.trim()) continue;
1126
+ }
1127
+ let cells = row.cells;
1128
+ if (i === prompt) {
1129
+ const glyph = cells.findIndex((c) => c.ch === "❯" || c.ch === "›");
1130
+ cells = glyph >= 0 ? cells.slice(glyph + 1) : cells;
1131
+ }
1132
+ for (const c of cells) {
1133
+ if (!c.ch.trim() || c.ch === "\xA0") continue;
1134
+ if (c.inverse) continue;
1135
+ if (c.dim) ghost = true;
1136
+ else real++;
1137
+ }
1138
+ }
1139
+ return real > 0 ? {
1140
+ kind: "draft",
1141
+ chars: real
1142
+ } : {
1143
+ kind: "empty",
1144
+ ghost
1145
+ };
1146
+ }
1147
+ /** Read the bottom `n` rows of an xterm buffer as ComposerRows. */
1148
+ function rowsFromXterm(term, n) {
1149
+ const active = term.buffer.active;
1150
+ const rows = [];
1151
+ for (let i = Math.max(0, active.length - n); i < active.length; i++) {
1152
+ const line = active.getLine(i);
1153
+ if (!line) {
1154
+ rows.push({
1155
+ text: "",
1156
+ cells: []
1157
+ });
1158
+ continue;
1159
+ }
1160
+ const cells = [];
1161
+ for (let x = 0; x < line.length; x++) {
1162
+ const c = line.getCell(x);
1163
+ if (!c || c.getWidth() === 0) continue;
1164
+ cells.push({
1165
+ ch: c.getChars() || " ",
1166
+ dim: c.isDim() !== 0,
1167
+ inverse: c.isInverse() !== 0,
1168
+ colored: !c.isFgDefault()
1169
+ });
1170
+ }
1171
+ rows.push({
1172
+ text: line.translateToString(true),
1173
+ cells
1174
+ });
1175
+ }
1176
+ while (rows.length && rows[rows.length - 1].text.trim() === "") rows.pop();
1177
+ return rows;
1178
+ }
1179
+ /** How long a parked message waits for the composer before it is given up. */
1180
+ const PENDING_MAX_AGE_MS = 1440 * 60 * 1e3;
1181
+ function pendingDir(pid) {
1182
+ return path.join(agentYesHome(), "pending", String(pid));
1183
+ }
1184
+ async function listPending(pid) {
1185
+ return (await readdir(pendingDir(pid)).catch(() => [])).filter((n) => n.endsWith(".json")).sort();
1186
+ }
1187
+ async function enqueuePending(p) {
1188
+ const dir = pendingDir(p.pid);
1189
+ await mkdir(dir, {
1190
+ recursive: true,
1191
+ mode: 448
1192
+ });
1193
+ const id = `${String(p.queuedAt).padStart(15, "0")}-${randomBytes(4).toString("hex")}`;
1194
+ const full = {
1195
+ ...p,
1196
+ id
1197
+ };
1198
+ const tmp = path.join(dir, `.${id}.tmp`);
1199
+ await writeFile(tmp, JSON.stringify(full), { mode: 384 });
1200
+ await rename(tmp, path.join(dir, `${id}.json`));
1201
+ return full;
1202
+ }
1203
+ async function readPending(pid, name) {
1204
+ const raw = await readFile(path.join(pendingDir(pid), name), "utf-8").catch(() => null);
1205
+ if (raw === null) return null;
1206
+ try {
1207
+ return JSON.parse(raw);
1208
+ } catch {
1209
+ return null;
1210
+ }
1211
+ }
1212
+ /**
1213
+ * Take a parked message off the queue BEFORE writing it. Delivery is therefore
1214
+ * at most once: a drainer that dies mid-write loses the message (it is still in
1215
+ * the sender's outbox as queued) rather than pasting it a second time into
1216
+ * whatever the composer holds next. Returns false when another process took it.
1217
+ */
1218
+ async function claimPending(pid, name) {
1219
+ try {
1220
+ await rm(path.join(pendingDir(pid), name));
1221
+ return true;
1222
+ } catch {
1223
+ return false;
1224
+ }
1225
+ }
1226
+ /** Move a message the drainer gave up on out of the queue, keeping it on disk. */
1227
+ async function retirePending(pid, name, why) {
1228
+ const dir = path.join(pendingDir(pid), "undelivered");
1229
+ await mkdir(dir, {
1230
+ recursive: true,
1231
+ mode: 448
1232
+ }).catch(() => {});
1233
+ await rename(path.join(pendingDir(pid), name), path.join(dir, name)).catch(() => {});
1234
+ await writeFile(path.join(dir, `${name}.why`), `${why}\n`, { mode: 384 }).catch(() => {});
1235
+ }
1236
+ /** An identical body from the same sender within this window is a resend. */
1237
+ const DUPLICATE_WINDOW_MS = 6e4;
1238
+ function recentSendsPath(pid) {
1239
+ return path.join(agentYesHome(), "pending", `${pid}.recent.jsonl`);
1240
+ }
1241
+ /** Who sent it, for dedupe purposes: an agent's stable id (or pid). A person at
1242
+ * a shell (no agent) is never deduped — typing "continue" twice is deliberate. */
1243
+ function senderKey(from) {
1244
+ if (!from) return null;
1245
+ if (from.agent_id) return `a:${from.agent_id}`;
1246
+ return typeof from.pid === "number" ? `p:${from.pid}` : null;
1247
+ }
1248
+ function bodyHash(body) {
1249
+ return createHash("sha256").update(body).digest("hex");
1250
+ }
1251
+ async function readRecent(pid) {
1252
+ const raw = await readFile(recentSendsPath(pid), "utf-8").catch(() => "");
1253
+ const out = [];
1254
+ for (const line of raw.split("\n")) {
1255
+ if (!line.trim()) continue;
1256
+ try {
1257
+ out.push(JSON.parse(line));
1258
+ } catch {}
1259
+ }
1260
+ return out;
1261
+ }
1262
+ /** The earlier identical send this one repeats, or null. Call under the input lock. */
1263
+ async function findRecentDuplicate(pid, sender, body, now = Date.now()) {
1264
+ const hash = bodyHash(body);
1265
+ return (await readRecent(pid)).filter((r) => r.sender === sender && r.hash === hash && now - r.at >= 0 && now - r.at <= DUPLICATE_WINDOW_MS).at(-1) ?? null;
1266
+ }
1267
+ /** Note a send (before it is typed or parked) and drop entries past the window. */
1268
+ async function noteRecentSend(pid, sender, body, outcome, now = Date.now()) {
1269
+ const kept = (await readRecent(pid)).filter((r) => now - r.at <= DUPLICATE_WINDOW_MS);
1270
+ kept.push({
1271
+ at: now,
1272
+ sender,
1273
+ hash: bodyHash(body),
1274
+ outcome
1275
+ });
1276
+ const file = recentSendsPath(pid);
1277
+ await mkdir(path.dirname(file), {
1278
+ recursive: true,
1279
+ mode: 448
1280
+ });
1281
+ const tmp = `${file}.${randomBytes(4).toString("hex")}.tmp`;
1282
+ await writeFile(tmp, kept.map((r) => JSON.stringify(r)).join("\n") + "\n", { mode: 384 });
1283
+ await rename(tmp, file);
1284
+ }
1285
+ /** What `ay send` prints when a send exits 4, so no caller reads it as a failure. */
1286
+ function queuedReceipt(kind, detail) {
1287
+ switch (kind) {
1288
+ case "parked": return `ay send: nothing was typed — ${detail}. The message is parked and will be delivered once the input box is empty and nobody is typing. Queued, do not resend.`;
1289
+ case "cli-queued": return `ay send: the target accepted it into its own queue (${detail}); it runs after the current turn. Queued, do not resend.`;
1290
+ case "duplicate": return `ay send: not resent — ${detail}. Do not resend.`;
1291
+ }
1292
+ }
1293
+
994
1294
  //#endregion
995
1295
  //#region ts/subcommands.ts
996
1296
  /**
@@ -1425,6 +1725,7 @@ const SUBCOMMANDS = new Set([
1425
1725
  "hist",
1426
1726
  "history",
1427
1727
  "send",
1728
+ "send-drain",
1428
1729
  "msgs",
1429
1730
  "key",
1430
1731
  "select",
@@ -1469,7 +1770,6 @@ const SEND_SETTLE_QUIET_MS = 150;
1469
1770
  const SEND_SETTLE_MAX_MS = 1500;
1470
1771
  const SEND_CONFIRM_QUIET_MS = 400;
1471
1772
  const SEND_CONFIRM_MAX_MS = 1200;
1472
- const SEND_CONFIRM_MIN_GROWTH_BYTES = 8;
1473
1773
  const SEND_SUBMIT_MAX_RETRIES = 2;
1474
1774
  const SEND_TYPING_POLL_MS = 200;
1475
1775
  const SEND_TYPING_MAX_WAIT_MS = 1e4;
@@ -1686,7 +1986,7 @@ async function runSubcommand(argv) {
1686
1986
  switch (sub) {
1687
1987
  case "ls":
1688
1988
  case "list": return await cmdLs(rest);
1689
- case "ps": return await (await import("./cmdPs-D7HWttUU.js")).cmdPs(rest);
1989
+ case "ps": return await (await import("./cmdPs-DBt-LD-H.js")).cmdPs(rest);
1690
1990
  case "status": return await cmdStatus(rest);
1691
1991
  case "whoami": return await cmdWhoami(rest);
1692
1992
  case "result": return await cmdResult(rest);
@@ -1699,6 +1999,7 @@ async function runSubcommand(argv) {
1699
1999
  case "hist":
1700
2000
  case "history": return await (await import("./hist-DZxq7NMA.js")).cmdHist(rest);
1701
2001
  case "send": return await cmdSend(rest);
2002
+ case "send-drain": return await cmdSendDrain(rest);
1702
2003
  case "msgs": return await cmdMsgs(rest);
1703
2004
  case "key": return await cmdKey(rest);
1704
2005
  case "select": return await cmdSelect(rest);
@@ -1733,47 +2034,47 @@ async function runSubcommand(argv) {
1733
2034
  return cmdCh(rest);
1734
2035
  }
1735
2036
  case "term": {
1736
- const { cmdTerm } = await import("./terminal-DqsAuqhw.js");
2037
+ const { cmdTerm } = await import("./terminal-CHPcyJuv.js");
1737
2038
  return cmdTerm(rest);
1738
2039
  }
1739
2040
  case "widget": {
1740
- const { cmdWidget } = await import("./widget-D5tsB-oi.js");
2041
+ const { cmdWidget } = await import("./widget-BOUSiXVj.js");
1741
2042
  return cmdWidget(rest);
1742
2043
  }
1743
2044
  case "mint": {
1744
- const { cmdMint } = await import("./widget-D5tsB-oi.js");
2045
+ const { cmdMint } = await import("./widget-BOUSiXVj.js");
1745
2046
  return cmdMint(rest);
1746
2047
  }
1747
2048
  case "serve": {
1748
- const { cmdServe } = await import("./serve-Cis4oJM-.js");
2049
+ const { cmdServe } = await import("./serve-DTQomE4j.js");
1749
2050
  return cmdServe(rest);
1750
2051
  }
1751
2052
  case "tray": {
1752
- const { cmdTray } = await import("./trayApp-C6C7-TSh.js");
2053
+ const { cmdTray } = await import("./trayApp-K6-U3syh.js");
1753
2054
  return cmdTray(rest);
1754
2055
  }
1755
2056
  case "setup": {
1756
- const { cmdSetup } = await import("./setup-B0sg4AV1.js");
2057
+ const { cmdSetup } = await import("./setup-BwZ3UlCM.js");
1757
2058
  return cmdSetup(rest);
1758
2059
  }
1759
2060
  case "ws": {
1760
- const { cmdWs } = await import("./ws-B4jdOeB2.js");
2061
+ const { cmdWs } = await import("./ws-xxrH3pXD.js");
1761
2062
  return cmdWs(rest);
1762
2063
  }
1763
2064
  case "schedule": {
1764
- const { cmdSchedule } = await import("./schedule-BStFx0_s.js");
2065
+ const { cmdSchedule } = await import("./schedule-C0HWIN7Z.js");
1765
2066
  return cmdSchedule(rest);
1766
2067
  }
1767
2068
  case "remote": {
1768
- const { cmdRemote } = await import("./remotes-BDMnvGI6.js");
2069
+ const { cmdRemote } = await import("./remotes-DnMQWaqQ.js");
1769
2070
  return cmdRemote(rest);
1770
2071
  }
1771
2072
  case "share": {
1772
- const { cmdShare } = await import("./shareCmd-DKIvwe0I.js");
2073
+ const { cmdShare } = await import("./shareCmd-Cx2kxthJ.js");
1773
2074
  return cmdShare(rest);
1774
2075
  }
1775
2076
  case "connect": {
1776
- const { cmdConnect } = await import("./remotes-BDMnvGI6.js");
2077
+ const { cmdConnect } = await import("./remotes-DnMQWaqQ.js");
1777
2078
  return cmdConnect(rest);
1778
2079
  }
1779
2080
  case "expose": {
@@ -1781,7 +2082,7 @@ async function runSubcommand(argv) {
1781
2082
  return cmdExpose(rest);
1782
2083
  }
1783
2084
  case "callback": {
1784
- const { cmdCallback } = await import("./callback-BEbbWLKe.js");
2085
+ const { cmdCallback } = await import("./callback-BW73zdcS.js");
1785
2086
  return cmdCallback(rest);
1786
2087
  }
1787
2088
  case "reap":
@@ -1792,7 +2093,7 @@ async function runSubcommand(argv) {
1792
2093
  return await cmdDsh(rest);
1793
2094
  }
1794
2095
  case "gc": {
1795
- const { gcOldBinaryDirs } = await import("./rustBinary-DgRg5H6V.js");
2096
+ const { gcOldBinaryDirs } = await import("./rustBinary-CVjRaDmT.js");
1796
2097
  const { gcLogs } = await import("./globalPidIndex-DC93JhHQ.js");
1797
2098
  const bins = gcOldBinaryDirs();
1798
2099
  const logs = await gcLogs();
@@ -1865,8 +2166,12 @@ function matchKeyword(record, keyword) {
1865
2166
  if (record.pid === Number(keyword)) return true;
1866
2167
  return !!(record.agent_id && record.agent_id.toLowerCase().startsWith(kw));
1867
2168
  }
1868
- if (kw === "." || kw === "./") return path.resolve(record.cwd) === path.resolve(process.cwd());
2169
+ if (kw === "." || kw === "./") {
2170
+ const here = path.resolve(process.cwd());
2171
+ return path.resolve(record.cwd) === here || !!record.workdir && path.resolve(record.workdir) === here;
2172
+ }
1869
2173
  if (record.cwd.toLowerCase().includes(kw)) return true;
2174
+ if (record.workdir && record.workdir.toLowerCase().includes(kw)) return true;
1870
2175
  if (record.cli.toLowerCase() === kw) return true;
1871
2176
  if (record.prompt && record.prompt.toLowerCase().includes(kw)) return true;
1872
2177
  if (record.agent_id && record.agent_id.toLowerCase().startsWith(kw)) return true;
@@ -1876,14 +2181,39 @@ async function listRecords(keyword, opts) {
1876
2181
  let records = mergeRecords(await readLocalTsPids(process.cwd()), opts.cwdScope ? await readLocalTsPids(opts.cwdScope) : [], await readGlobalPids());
1877
2182
  if (!opts.all) records = records.filter((r) => r.status !== "exited");
1878
2183
  if (opts.active) records = records.filter((r) => isPidAlive(r.pid));
2184
+ records = await withWorkDirs(records);
1879
2185
  if (opts.cwdScope) {
1880
2186
  const scope = opts.cwdScope;
1881
- records = records.filter((r) => r.cwd === scope || r.cwd.startsWith(scope + path.sep));
2187
+ records = records.filter((r) => isWithin(r.cwd, scope) || !!r.workdir && isWithin(r.workdir, scope));
1882
2188
  }
1883
2189
  if (keyword) records = records.filter((r) => matchKeyword(r, keyword));
1884
2190
  records.sort((a, b) => b.started_at - a.started_at);
1885
2191
  return records;
1886
2192
  }
2193
+ /**
2194
+ * Stamp each live record with its effective work dir (ts/workDir.ts). Exited
2195
+ * agents keep their spawn cwd: their transcript is history, not a location.
2196
+ */
2197
+ async function withWorkDirs(records) {
2198
+ return Promise.all(records.map(async (r) => r.status === "exited" ? {
2199
+ ...r,
2200
+ workdir: r.cwd,
2201
+ workdir_source: "spawn",
2202
+ workdir_at: null
2203
+ } : {
2204
+ ...r,
2205
+ ...await resolveWorkDir(r)
2206
+ }));
2207
+ }
2208
+ /**
2209
+ * The CWD column: the effective work dir, with a leading `↪` when it is not the
2210
+ * spawn dir (sampled from its shells) so a reader knows the registry's `cwd`
2211
+ * says otherwise. `ay ls --json` carries both (`cwd` + `workdir`).
2212
+ */
2213
+ function cwdLabel(r) {
2214
+ if (r.workdir && r.workdir_source && r.workdir_source !== "spawn") return `↪ ${shortenPath(r.workdir)}`;
2215
+ return shortenPath(r.cwd);
2216
+ }
1887
2217
  function isPidAlive(pid) {
1888
2218
  try {
1889
2219
  process.kill(pid, 0);
@@ -2411,7 +2741,7 @@ async function runAllRemotesLs(opts) {
2411
2741
  const [tasks, badges, git, typing] = state !== "stopped" ? await Promise.all([
2412
2742
  r.log_file ? extractTaskCounts(r.log_file) : Promise.resolve(null),
2413
2743
  r.log_file ? extractBadges(r.log_file) : Promise.resolve([]),
2414
- gitStatusOnce(r.cwd, gitRootCache, gitInfoCache),
2744
+ gitStatusOnce(r.workdir ?? r.cwd, gitRootCache, gitInfoCache),
2415
2745
  isUserTyping(r.pid)
2416
2746
  ]) : [
2417
2747
  null,
@@ -2463,7 +2793,7 @@ async function runAllRemotesLs(opts) {
2463
2793
  const cliW = Math.max(3, ...rows.map((r) => String(r.rec.cli).length));
2464
2794
  const statusW = Math.max(6, ...rows.map((r) => String(r.rec.status).length));
2465
2795
  const ageW = Math.max(3, ...rows.map((r) => ageOf(r.rec).length));
2466
- const cwdW = Math.max(3, ...rows.map((r) => shortenPath(String(r.rec.cwd)).length));
2796
+ const cwdW = Math.max(3, ...rows.map((r) => cwdLabel(r.rec).length));
2467
2797
  const promptBudget = Math.max(20, termWidth - hostW - pidW - cliW - statusW - ageW - cwdW - 12 - 1);
2468
2798
  process.stdout.write([
2469
2799
  "HOST".padEnd(hostW),
@@ -2487,7 +2817,7 @@ async function runAllRemotesLs(opts) {
2487
2817
  String(rec.cli).padEnd(cliW),
2488
2818
  String(rec.status).padEnd(statusW),
2489
2819
  ageOf(rec).padEnd(ageW),
2490
- shortenPath(String(rec.cwd)).padEnd(cwdW),
2820
+ cwdLabel(rec).padEnd(cwdW),
2491
2821
  label
2492
2822
  ].join(" ") + "\n");
2493
2823
  }
@@ -2910,7 +3240,7 @@ async function cmdLs(rest) {
2910
3240
  const now = Date.now();
2911
3241
  const lastActive = new Map(await Promise.all(records.map(async (r) => [r.pid, await deriveLastActiveAt(r)])));
2912
3242
  const ageOf = (r) => humanizeAge(now - (lastActive.get(r.pid) ?? r.started_at));
2913
- const rawCwds = records.map((r) => shortenPath(r.cwd));
3243
+ const rawCwds = records.map((r) => cwdLabel(r));
2914
3244
  const widths = {
2915
3245
  pid: Math.max(3, ...records.map((r) => String(r.pid).length)),
2916
3246
  cli: Math.max(3, ...records.map((r) => r.cli.length)),
@@ -2931,7 +3261,7 @@ async function cmdLs(rest) {
2931
3261
  const [tasks, flags, git, typing] = alive ? await Promise.all([
2932
3262
  r.log_file ? extractTaskCounts(r.log_file) : Promise.resolve(null),
2933
3263
  r.log_file ? extractBadges(r.log_file) : Promise.resolve([]),
2934
- gitStatusOnce(r.cwd, gitRootCache, gitInfoCache),
3264
+ gitStatusOnce(r.workdir ?? r.cwd, gitRootCache, gitInfoCache),
2935
3265
  isUserTyping(r.pid)
2936
3266
  ]) : [
2937
3267
  null,
@@ -2958,7 +3288,7 @@ async function cmdLs(rest) {
2958
3288
  cli: r.cli,
2959
3289
  status: displayStatus,
2960
3290
  age: ageOf(r),
2961
- cwd: shortenPath(r.cwd),
3291
+ cwd: cwdLabel(r),
2962
3292
  label,
2963
3293
  hasNote,
2964
3294
  _alive: displayStatus !== "stopped"
@@ -3871,6 +4201,52 @@ function cliDefaults() {
3871
4201
  * stuck classifiers so they don't each re-implement the tail read.
3872
4202
  */
3873
4203
  async function renderLogTailLines(logPath, n = 40, geom) {
4204
+ const buf = await readLogTailBytes(logPath);
4205
+ if (!buf) return null;
4206
+ try {
4207
+ return (await renderRawLog(buf, {
4208
+ mode: "tail",
4209
+ n,
4210
+ cols: geom?.cols,
4211
+ rows: geom?.rows
4212
+ })).split("\n");
4213
+ } catch {
4214
+ return null;
4215
+ }
4216
+ }
4217
+ /**
4218
+ * What the target's composer holds right now, read from the same 32 KB tail
4219
+ * `renderLogTailLines` renders, but keeping per-cell attributes (dim/inverse) so
4220
+ * ghost text can be told from a real draft. See ts/composerGuard.ts.
4221
+ */
4222
+ async function readComposerState(record) {
4223
+ if (!record.log_file) return {
4224
+ kind: "unknown",
4225
+ reason: "no log file recorded"
4226
+ };
4227
+ const buf = await readLogTailBytes(record.log_file);
4228
+ if (!buf) return {
4229
+ kind: "unknown",
4230
+ reason: "log unreadable or empty"
4231
+ };
4232
+ const geom = await readAgentPtysize(record) ?? void 0;
4233
+ try {
4234
+ const term = new (await (loadXtermTerminal()))({
4235
+ cols: geom?.cols && geom.cols > 0 ? geom.cols : 200,
4236
+ rows: geom?.rows && geom.rows > 0 ? geom.rows : 50,
4237
+ scrollback: 5e3,
4238
+ allowProposedApi: true
4239
+ });
4240
+ await new Promise((resolve) => term.write(buf, resolve));
4241
+ return classifyComposer(rowsFromXterm(term, 40));
4242
+ } catch (e) {
4243
+ return {
4244
+ kind: "unknown",
4245
+ reason: `render failed: ${e?.message ?? e}`
4246
+ };
4247
+ }
4248
+ }
4249
+ async function readLogTailBytes(logPath) {
3874
4250
  const TAIL_BYTES = 32 * 1024;
3875
4251
  let buf;
3876
4252
  try {
@@ -3892,16 +4268,7 @@ async function renderLogTailLines(logPath, n = 40, geom) {
3892
4268
  } catch {
3893
4269
  return null;
3894
4270
  }
3895
- try {
3896
- return (await renderRawLog(buf, {
3897
- mode: "tail",
3898
- n,
3899
- cols: geom?.cols,
3900
- rows: geom?.rows
3901
- })).split("\n");
3902
- } catch {
3903
- return null;
3904
- }
4271
+ return buf;
3905
4272
  }
3906
4273
  async function extractNeedsInput(logPath, cli) {
3907
4274
  const cfg = (await cliDefaults())[cli];
@@ -4128,33 +4495,116 @@ async function backoffWhileTyping(pid, maxWaitMs) {
4128
4495
  waitedMs: Date.now() - start
4129
4496
  };
4130
4497
  }
4131
- /**
4132
- * Send the trailing submit code and confirm the CLI actually acted on it —
4133
- * either a `working` busy marker appears, or the log grows meaningfully. Retries
4134
- * (re-sending just the trailing code) up to SEND_SUBMIT_MAX_RETRIES times when
4135
- * neither shows, since a swallowed Enter looks identical to a slow one until we
4136
- * check. Returns whether submission was confirmed, plus the final rendered tail
4137
- * (for a caller to show the user when it wasn't).
4138
- */
4139
- async function submitAndConfirm(record, fifoPath, trailing) {
4498
+ /** Attribute the evidence to THIS message, never to redraws or another turn. */
4499
+ function inspectSubmission(screen, identity) {
4500
+ const unknown = {
4501
+ submission: "not-submitted",
4502
+ retry: false,
4503
+ transcriptMatches: 0,
4504
+ composerVisible: false,
4505
+ inComposer: false
4506
+ };
4507
+ const prompt = composerPromptRow(screen);
4508
+ if (prompt < 0 || !identity.trim()) return unknown;
4509
+ const compact = (text) => text.replace(/\s+/gu, "");
4510
+ const needle = compact(identity);
4511
+ const wrapped = identity.startsWith("<ay-msg ");
4512
+ const transcriptLines = screen.slice(0, prompt);
4513
+ const transcript = compact(transcriptLines.join("\n"));
4514
+ let transcriptMatches = wrapped ? transcript.split(needle).length - 1 : 0;
4515
+ if (!wrapped) {
4516
+ const lines = transcriptLines.map((line) => compact(line.replace(/^\s*[❯›]\s*/u, "")));
4517
+ for (let start = 0; start < lines.length; start++) {
4518
+ let candidate = "";
4519
+ for (let end = start; end < lines.length && candidate.length < needle.length; end++) {
4520
+ candidate += lines[end];
4521
+ if (candidate === needle) {
4522
+ transcriptMatches++;
4523
+ break;
4524
+ }
4525
+ }
4526
+ }
4527
+ }
4528
+ const input = [screen[prompt].replace(/^\s*[❯›]\s*/u, "")];
4529
+ for (const line of screen.slice(prompt + 1)) {
4530
+ if (isComposerChrome(line)) break;
4531
+ input.push(line);
4532
+ }
4533
+ const composer = compact(input.join("\n"));
4534
+ if (wrapped ? composer.includes(needle) : composer === needle) return {
4535
+ submission: "not-submitted",
4536
+ retry: true,
4537
+ transcriptMatches,
4538
+ composerVisible: true,
4539
+ inComposer: true
4540
+ };
4541
+ const queued = screen.some((line) => /^\s*(?:[❯›]\s*)?Press up to edit queued messages\s*$/iu.test(line));
4542
+ if (transcriptMatches) return {
4543
+ submission: queued ? "queued" : "submitted",
4544
+ retry: false,
4545
+ transcriptMatches,
4546
+ composerVisible: true,
4547
+ inComposer: false
4548
+ };
4549
+ return {
4550
+ ...unknown,
4551
+ composerVisible: true
4552
+ };
4553
+ }
4554
+ /** A collapsed paste is not delivery evidence; it can only authorize a retry. */
4555
+ function collapsedPasteToken(screen) {
4556
+ const prompt = screen.findLastIndex((line) => /^\s*❯($|\s)/u.test(line));
4557
+ if (prompt < 0) return null;
4558
+ const input = screen[prompt].replace(/^\s*❯\s*/u, "").trim();
4559
+ return /^\[Pasted text #\d+ \+\d+ lines\]$/.test(input) ? input : null;
4560
+ }
4561
+ function ownedCollapsedPaste(cli, beforePaste, afterPaste) {
4562
+ if (cli !== "claude" || !beforePaste) return null;
4563
+ const token = collapsedPasteToken(afterPaste);
4564
+ return token && !beforePaste.join("\n").includes(token) ? token : null;
4565
+ }
4566
+ const SEND_EXIT_QUEUED = 4;
4567
+ /** Retry only Enter, never the body. Three attempts, phi delay capped at 400ms. */
4568
+ async function submitAndConfirm(record, fifoPath, trailing, identity, beforePaste) {
4140
4569
  const logFile = record.log_file;
4570
+ const geometry = await readAgentPtysize(record) ?? void 0;
4141
4571
  const cfg = (await cliDefaults())[record.cli];
4142
- let screen = [];
4572
+ let screen = await renderLogTailLines(logFile, 40, geometry) ?? [];
4573
+ const before = inspectSubmission(screen, identity);
4574
+ const baseline = before.transcriptMatches;
4575
+ const delivered = (e) => e.submission !== "not-submitted" && e.transcriptMatches > baseline || before.inComposer && e.composerVisible && !e.inComposer;
4576
+ const outcome = (e, current) => {
4577
+ const queued = e.submission === "queued" || current.some((line) => /^\s*(?:[❯›]\s*)?Press up to edit queued messages\s*$/iu.test(line));
4578
+ return {
4579
+ confirmed: !queued,
4580
+ screen: current,
4581
+ submission: queued ? "queued" : "submitted"
4582
+ };
4583
+ };
4584
+ const ownPaste = ownedCollapsedPaste(record.cli, beforePaste, screen);
4585
+ const canRetry = (evidence, current) => evidence.retry || ownPaste !== null && collapsedPasteToken(current) === ownPaste;
4143
4586
  for (let attempt = 0; attempt <= SEND_SUBMIT_MAX_RETRIES; attempt++) {
4144
- const sizeBefore = await stat(logFile).then((s) => s.size).catch(() => null) ?? 0;
4145
- const wasAlreadyWorking = isWorkingScreen(await renderLogTailLines(logFile, 40) ?? [], cfg?.working);
4587
+ if (attempt) {
4588
+ await new Promise((r) => setTimeout(r, Math.min(400, 150 * 1.618 ** (attempt - 1))));
4589
+ screen = await renderLogTailLines(logFile, 40, geometry) ?? [];
4590
+ const settled = inspectSubmission(screen, identity);
4591
+ if (delivered(settled)) return outcome(settled, screen);
4592
+ if (!canRetry(settled, screen) || cfg?.needsInput?.length && parseMenu(screen, {
4593
+ needsInput: cfg.needsInput,
4594
+ working: cfg.working
4595
+ })) break;
4596
+ }
4146
4597
  await writeToIpc(fifoPath, trailing);
4147
- const sizeAfter = await waitForLogQuiet(logFile, SEND_CONFIRM_QUIET_MS, SEND_CONFIRM_MAX_MS);
4148
- screen = await renderLogTailLines(logFile, 40) ?? [];
4149
- const grew = sizeAfter !== null && sizeAfter >= sizeBefore + SEND_CONFIRM_MIN_GROWTH_BYTES;
4150
- if (isWorkingScreen(screen, cfg?.working) && !wasAlreadyWorking || grew) return {
4151
- confirmed: true,
4152
- screen
4153
- };
4598
+ await waitForLogQuiet(logFile, SEND_CONFIRM_QUIET_MS, SEND_CONFIRM_MAX_MS);
4599
+ screen = await renderLogTailLines(logFile, 40, geometry) ?? [];
4600
+ const evidence = inspectSubmission(screen, identity);
4601
+ if (delivered(evidence)) return outcome(evidence, screen);
4602
+ if (!canRetry(evidence, screen)) break;
4154
4603
  }
4155
4604
  return {
4156
4605
  confirmed: false,
4157
- screen
4606
+ screen,
4607
+ submission: "not-submitted"
4158
4608
  };
4159
4609
  }
4160
4610
  /** Poll until the agent is no longer parked on a menu (selection accepted → it
@@ -4167,8 +4617,173 @@ async function waitForNeedsInputClear(record, timeoutMs) {
4167
4617
  }
4168
4618
  return false;
4169
4619
  }
4620
+ /**
4621
+ * Write one message and its trailing code to the target, then (when `canConfirm`)
4622
+ * confirm the submit. The caller holds the input lock. The body is written
4623
+ * exactly once; only Enter is ever retried (see submitAndConfirm).
4624
+ */
4625
+ async function deliverBody(record, fifoPath, fullBody, trailing, identity, canConfirm) {
4626
+ if (fullBody && trailing) {
4627
+ const beforePaste = canConfirm && record.log_file ? await renderLogTailLines(record.log_file, 40, await readAgentPtysize(record) ?? void 0) : null;
4628
+ await writeToIpc(fifoPath, fullBody);
4629
+ if (canConfirm && record.log_file) {
4630
+ await waitForLogQuiet(record.log_file, SEND_SETTLE_QUIET_MS, SEND_SETTLE_MAX_MS);
4631
+ return submitAndConfirm(record, fifoPath, trailing, identity, beforePaste);
4632
+ }
4633
+ await new Promise((r) => setTimeout(r, 200));
4634
+ await writeToIpc(fifoPath, trailing);
4635
+ } else await writeToIpc(fifoPath, fullBody + trailing);
4636
+ return {
4637
+ confirmed: !canConfirm,
4638
+ screen: [],
4639
+ submission: canConfirm ? "not-submitted" : "unchecked"
4640
+ };
4641
+ }
4642
+ const DRAIN_POLL_BASE_MS = 500;
4643
+ const DRAIN_POLL_CAP_MS = 5e3;
4644
+ function drainerLockPath(pid) {
4645
+ return path.join(agentYesHome(), "pending", `${pid}.drainer`);
4646
+ }
4647
+ /** The pid of a live drainer for `pid`'s queue, or null. */
4648
+ async function liveDrainer(pid) {
4649
+ const raw = await readFile(drainerLockPath(pid), "utf-8").catch(() => null);
4650
+ const owner = Number(raw?.trim());
4651
+ if (!Number.isInteger(owner) || owner <= 0) return null;
4652
+ try {
4653
+ process.kill(owner, 0);
4654
+ return owner;
4655
+ } catch {
4656
+ return null;
4657
+ }
4658
+ }
4659
+ /**
4660
+ * The argv that re-launches THIS build as the drainer. The drainer must be the
4661
+ * same build that parked the message (an older `ay` on PATH has no
4662
+ * send-drain), so prefer the running script over PATH lookup. Under the bun
4663
+ * runtime that is `bun <script>` on every platform: argv[1] is a .js/.ts file,
4664
+ * never an executable, so spawning it bare (as the first cut did on win32)
4665
+ * ENOENTs and the parked message waits for a manual `ay send-drain`. A
4666
+ * compiled single-file binary has no script to hand over: re-run the binary.
4667
+ */
4668
+ function drainerLauncher(execPath, script, onPath) {
4669
+ if (!/(^|[\\/])bun(\.exe)?$/i.test(execPath)) return [execPath];
4670
+ if (script) return [execPath, script];
4671
+ return onPath ? [execPath, onPath] : null;
4672
+ }
4673
+ /** Start the per-target drainer unless one is already running. */
4674
+ async function ensureSendDrainer(pid) {
4675
+ const existing = await liveDrainer(pid);
4676
+ if (existing) return existing;
4677
+ const { spawn } = await import("node:child_process");
4678
+ const launcher = drainerLauncher(process.execPath, process.argv[1], Bun.which("ay"));
4679
+ if (!launcher) return null;
4680
+ const [cmd, ...pre] = launcher;
4681
+ const child = spawn(cmd, [
4682
+ ...pre,
4683
+ "send-drain",
4684
+ String(pid)
4685
+ ], {
4686
+ detached: true,
4687
+ stdio: "ignore"
4688
+ });
4689
+ child.on("error", () => {});
4690
+ child.unref();
4691
+ return child.pid ?? null;
4692
+ }
4693
+ function pidAlive(pid) {
4694
+ try {
4695
+ process.kill(pid, 0);
4696
+ return true;
4697
+ } catch (e) {
4698
+ return e?.code === "EPERM";
4699
+ }
4700
+ }
4701
+ /**
4702
+ * `ay send-drain <pid>` — deliver the messages `ay send` parked for <pid>
4703
+ * because its composer held a draft. Runs until the queue is empty, the target
4704
+ * exits, or every message expired. One drainer per target (a pid file under
4705
+ * pending/); a second one exits at once. Normally started by `ay send` itself.
4706
+ */
4707
+ async function cmdSendDrain(rest) {
4708
+ const pid = Number(rest[0]);
4709
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error("usage: ay send-drain <pid>");
4710
+ const lockFile = drainerLockPath(pid);
4711
+ await mkdir(path.dirname(lockFile), { recursive: true });
4712
+ const other = await liveDrainer(pid);
4713
+ if (other && other !== process.pid) return 0;
4714
+ await writeFile(lockFile, `${process.pid}\n`);
4715
+ await new Promise((r) => setTimeout(r, 50));
4716
+ if (await liveDrainer(pid) !== process.pid) return 0;
4717
+ try {
4718
+ let attempt = 0;
4719
+ const delivered = /* @__PURE__ */ new Map();
4720
+ for (;;) {
4721
+ const names = await listPending(pid);
4722
+ if (!names.length) {
4723
+ if (await withIpcLock(pid, async () => {
4724
+ if ((await listPending(pid)).length) return false;
4725
+ await rm(lockFile, { force: true });
4726
+ return true;
4727
+ })) return 0;
4728
+ continue;
4729
+ }
4730
+ const name = names[0];
4731
+ const msg = await readPending(pid, name);
4732
+ if (!msg) {
4733
+ await retirePending(pid, name, "unparseable pending file");
4734
+ continue;
4735
+ }
4736
+ const gone = !pidAlive(pid);
4737
+ const expired = Date.now() - msg.queuedAt > PENDING_MAX_AGE_MS;
4738
+ if (gone || expired) {
4739
+ const why = gone ? "target exited before its input box was free" : "expired after 24h";
4740
+ for (const n of gone ? names : [name]) await retirePending(pid, n, why);
4741
+ await recordMessage({
4742
+ at: Date.now(),
4743
+ ...msg.record,
4744
+ confirmed: false,
4745
+ submission: "not-submitted"
4746
+ });
4747
+ if (gone) return 1;
4748
+ continue;
4749
+ }
4750
+ const from = senderKey(msg.record.from);
4751
+ const msgBody = msg.record.body ?? "";
4752
+ const dupKey = from && msgBody ? `${from}|${bodyHash(msgBody)}` : null;
4753
+ const prev = dupKey ? delivered.get(dupKey) : void 0;
4754
+ if (prev !== void 0 && msg.queuedAt - prev <= DUPLICATE_WINDOW_MS) {
4755
+ await retirePending(pid, name, `duplicate of the same sender's identical message delivered ${Math.round((Date.now() - prev) / 1e3)}s ago`);
4756
+ continue;
4757
+ }
4758
+ const record = (await readGlobalPids()).find((r) => r.pid === pid);
4759
+ let result = null;
4760
+ if (record && !await isUserTyping(pid)) await withIpcLock(pid, async () => {
4761
+ if (await isUserTyping(pid)) return;
4762
+ if ((await readComposerState(record)).kind !== "empty") return;
4763
+ if (!await claimPending(pid, name)) return;
4764
+ result = await deliverBody(record, msg.fifoPath, msg.fullBody, msg.trailing, msg.identity, msg.trailing === "\r" && Boolean(record.log_file));
4765
+ });
4766
+ if (result) {
4767
+ const d = result;
4768
+ if (dupKey) delivered.set(dupKey, Date.now());
4769
+ await recordMessage({
4770
+ at: Date.now(),
4771
+ ...msg.record,
4772
+ confirmed: d.confirmed,
4773
+ submission: d.submission
4774
+ });
4775
+ attempt = 0;
4776
+ continue;
4777
+ }
4778
+ attempt++;
4779
+ await new Promise((r) => setTimeout(r, Math.min(DRAIN_POLL_CAP_MS, DRAIN_POLL_BASE_MS * 1.618 ** (attempt - 1))));
4780
+ }
4781
+ } finally {
4782
+ if (await liveDrainer(pid) === process.pid) await rm(lockFile, { force: true });
4783
+ }
4784
+ }
4170
4785
  async function cmdSend(rest) {
4171
- const argv = await yargs(rest).parserConfiguration({ "boolean-negation": false }).usage("Usage: ay send <keyword> <msg|-> [options]\n\nExit: 0 sent, 3 target unreachable (nothing sent; ay ls shows it as\n'unreachable' — ay restart <pid> revives it), 1 everything else.").option("code", {
4786
+ const argv = await yargs(rest).parserConfiguration({ "boolean-negation": false }).usage("Usage: ay send <keyword> <msg|-> [options]\n\nExit: 0 sent, 3 target unreachable (nothing sent; ay ls shows it as\n'unreachable' — ay restart <pid> revives it), 4 QUEUED (accepted, not yet\nsubmitted: either the CLI queued it, or its input box held someone's draft and\nthe message was parked for delivery once the box is empty — do not resend;\nan identical resend from the same agent within 60s is dropped as a DUPLICATE),\n1 everything else.").option("code", {
4172
4787
  type: "string",
4173
4788
  default: "enter",
4174
4789
  description: "Trailing control code (enter|esc|ctrl-c|ctrl-y|tab|none)"
@@ -4281,26 +4896,70 @@ async function cmdSend(rest) {
4281
4896
  }
4282
4897
  const fullBody = framePaste$1 ? framePaste(prefix + body + suffix) : prefix + body + suffix;
4283
4898
  const noWait = Boolean(argv.noWait) || process.env.AGENT_YES_SEND_NO_WAIT === "1";
4899
+ let parkReason = null;
4284
4900
  if (fullBody && !noWait && !force) {
4285
4901
  const { clear, waitedMs } = await backoffWhileTyping(record.pid, SEND_TYPING_MAX_WAIT_MS);
4286
- if (!clear) process.stderr.write(`warning: user still typing at pid ${record.pid} after ${Math.round(waitedMs / 1e3)}s — sending anyway (may interleave with their line). Use --force to skip this wait.\n`);
4902
+ if (!clear) parkReason = `user still typing after ${Math.round(waitedMs / 1e3)}s`;
4287
4903
  else if (waitedMs > 0) process.stderr.write(`waited ${Math.round(waitedMs / 1e3)}s for the user to pause typing before sending.\n`);
4288
4904
  }
4289
4905
  const canConfirm = trailing === "\r" && Boolean(fullBody) && !noWait;
4290
- let confirmed = true;
4906
+ const identity = nonce ? `<ay-msg ${nonce}` : body;
4907
+ let confirmed = !canConfirm;
4908
+ const receipt = { submission: canConfirm ? "not-submitted" : "unchecked" };
4291
4909
  let lastScreen = [];
4910
+ let parked = false;
4911
+ let duplicateOf = null;
4912
+ const mailBase = {
4913
+ nonce,
4914
+ origin: sender.agent ? void 0 : "shell",
4915
+ from_via: sender.via,
4916
+ sender_observed: observedSender(),
4917
+ from: sender.agent ? {
4918
+ pid: sender.agent.pid,
4919
+ cli: sender.agent.cli,
4920
+ cwd: sender.agent.cwd,
4921
+ agent_id: sender.agent.agent_id
4922
+ } : null,
4923
+ to: {
4924
+ pid: record.pid,
4925
+ cli: record.cli,
4926
+ cwd: record.cwd,
4927
+ agent_id: record.agent_id
4928
+ },
4929
+ body,
4930
+ code: trailing === "\r" ? void 0 : codeName,
4931
+ wrapped: Boolean(nonce)
4932
+ };
4292
4933
  try {
4293
4934
  await withIpcLock(record.pid, async () => {
4294
- if (fullBody && trailing) {
4295
- await writeToIpc(fifoPath, fullBody);
4296
- if (canConfirm && record.log_file) {
4297
- await waitForLogQuiet(record.log_file, SEND_SETTLE_QUIET_MS, SEND_SETTLE_MAX_MS);
4298
- ({confirmed, screen: lastScreen} = await submitAndConfirm(record, fifoPath, trailing));
4299
- } else {
4300
- await new Promise((r) => setTimeout(r, 200));
4301
- await writeToIpc(fifoPath, trailing);
4935
+ const dedupeKey = force || !body ? null : senderKey(mailBase.from);
4936
+ if (dedupeKey) {
4937
+ duplicateOf = await findRecentDuplicate(record.pid, dedupeKey, body);
4938
+ if (duplicateOf) return;
4939
+ }
4940
+ if (fullBody) {
4941
+ if (!parkReason && (await listPending(record.pid)).length) parkReason = "earlier messages to this agent are still queued";
4942
+ if (!parkReason) {
4943
+ const composer = await readComposerState(record);
4944
+ if (composer.kind === "draft") parkReason = `its input box holds a draft (${composer.chars} chars)`;
4945
+ else if (composer.kind === "unknown") process.stderr.write(`warning: ay send could not see pid ${record.pid}'s input box (${composer.reason}) — sending without the draft check.\n`);
4946
+ }
4947
+ if (dedupeKey) await noteRecentSend(record.pid, dedupeKey, body, parkReason ? "queued" : "sent");
4948
+ if (parkReason) {
4949
+ await enqueuePending({
4950
+ queuedAt: Date.now(),
4951
+ pid: record.pid,
4952
+ fifoPath,
4953
+ fullBody,
4954
+ trailing,
4955
+ identity,
4956
+ record: mailBase
4957
+ });
4958
+ parked = true;
4959
+ return;
4302
4960
  }
4303
- } else await writeToIpc(fifoPath, fullBody + trailing);
4961
+ }
4962
+ ({confirmed, screen: lastScreen, submission: receipt.submission} = await deliverBody(record, fifoPath, fullBody, trailing, identity, canConfirm));
4304
4963
  }, (why) => process.stderr.write(`warning: ay send writing pid ${record.pid} without the input lock (${why})\n`));
4305
4964
  } catch (e) {
4306
4965
  const code = e?.code;
@@ -4308,9 +4967,30 @@ async function cmdSend(rest) {
4308
4967
  process.stderr.write(`ay send: pid ${record.pid} (${record.cli}) became UNREACHABLE mid-send — its stdin FIFO ${fifoPath} stopped taking a writer (${code}). The message may be partly delivered. Retire the row with: ay stop ${record.pid} (registry only, sends no signal); ay restart writes to this same FIFO and would fail the same way.\n`);
4309
4968
  return SEND_EXIT_UNREACHABLE;
4310
4969
  }
4970
+ if (duplicateOf) {
4971
+ const dup = duplicateOf;
4972
+ const ago = Math.max(0, Math.round((Date.now() - dup.at) / 1e3));
4973
+ process.stdout.write(`DUPLICATE (not resent) to pid ${record.pid} (${record.cli}): ${truncate(body + trailing, 80)}\n`);
4974
+ process.stderr.write(queuedReceipt("duplicate", `you sent this exact message to pid ${record.pid} ${ago}s ago and it was ${dup.outcome}`) + "\n");
4975
+ return dup.outcome === "queued" ? SEND_EXIT_QUEUED : 0;
4976
+ }
4977
+ if (parked) {
4978
+ const drainer = await ensureSendDrainer(record.pid);
4979
+ process.stdout.write(`QUEUED to pid ${record.pid} (${record.cli}): ${truncate(body + trailing, 80)}\n`);
4980
+ process.stderr.write(queuedReceipt("parked", parkReason) + (drainer ? ` (drainer pid ${drainer})\n` : `\nay send: the drainer did not start; run: ay send-drain ${record.pid}\n`));
4981
+ if (body) await recordMessage({
4982
+ at: Date.now(),
4983
+ ...mailBase,
4984
+ confirmed: false,
4985
+ submission: "queued"
4986
+ });
4987
+ return SEND_EXIT_QUEUED;
4988
+ }
4989
+ const { submission } = receipt;
4311
4990
  const payload = body + trailing;
4312
- const status = confirmed ? "sent" : "sent but NOT confirmed submitted";
4991
+ const status = submission === "queued" ? "QUEUED" : confirmed ? "sent" : "NOT SUBMITTED (NOT confirmed: our message remains in input or destination evidence is unavailable)";
4313
4992
  process.stdout.write(`${status} to pid ${record.pid} (${record.cli}): ${truncate(payload, 80)}\n`);
4993
+ if (submission === "queued") process.stderr.write(queuedReceipt("cli-queued", `${record.cli} is busy`) + "\n");
4314
4994
  if (body) await recordMessage({
4315
4995
  at: Date.now(),
4316
4996
  nonce,
@@ -4332,9 +5012,10 @@ async function cmdSend(rest) {
4332
5012
  body,
4333
5013
  code: trailing === "\r" ? void 0 : codeName,
4334
5014
  confirmed,
5015
+ submission,
4335
5016
  wrapped: Boolean(nonce)
4336
5017
  });
4337
- if (!confirmed) process.stderr.write(`\nwarning: couldn't confirm the CLI acted on it after ${SEND_SUBMIT_MAX_RETRIES + 1} attempt(s) — it may still be sitting unsubmitted in the prompt. Last screen:\n` + lastScreen.slice(-8).map((l) => ` ${l}`).join("\n") + "\n");
5018
+ if (!confirmed && submission !== "queued") process.stderr.write("\nwarning: couldn't confirm the CLI acted on this message — it may still be sitting unsubmitted in the prompt. Last screen:\n" + lastScreen.slice(-8).map((l) => ` ${l}`).join("\n") + "\n");
4338
5019
  if (record.log_file) {
4339
5020
  const geom = await readAgentPtysize(record) ?? void 0;
4340
5021
  const tail = await renderLogTailLines(record.log_file, 10, geom) ?? [];
@@ -4349,7 +5030,7 @@ async function cmdSend(rest) {
4349
5030
  const tip = stopTipForCli(record.cli, record.pid);
4350
5031
  if (tip) process.stderr.write(tip);
4351
5032
  }
4352
- return confirmed ? 0 : 1;
5033
+ return submission === "queued" ? SEND_EXIT_QUEUED : confirmed ? 0 : 1;
4353
5034
  }
4354
5035
  /**
4355
5036
  * `ay msgs [keyword]` — show the inter-agent messages an agent sent and
@@ -4442,7 +5123,7 @@ async function cmdMsgs(rest) {
4442
5123
  const fromLabel = senderLabel(rec);
4443
5124
  const peer = dir === "out" ? `→ ${rec.to.cli} #${rec.to.pid}` : `← ${fromLabel}`;
4444
5125
  const via = rec.remote ? ` (via ${rec.remote})` : "";
4445
- const flag = rec.confirmed === false ? " (unconfirmed)" : "";
5126
+ const flag = rec.submission === "queued" ? " (QUEUED)" : rec.confirmed === false ? " (unconfirmed)" : "";
4446
5127
  const line = (rec.kind ? `[${rec.kind}] ` : "") + truncate(rec.body.replace(/\s+/g, " "), 100);
4447
5128
  process.stdout.write(`${when} ${peer.padEnd(20)}${via}${flag} ${line}\n`);
4448
5129
  }
@@ -4895,7 +5576,7 @@ async function cmdAttach(rest) {
4895
5576
  const winsizeDir = path.join(ayHome, "winsize");
4896
5577
  await mkdir(winsizeDir, { recursive: true });
4897
5578
  const winsizePath = path.join(winsizeDir, String(record.pid));
4898
- const { resolveDaemonHttpBase, loadTokenReadOnly } = await import("./serve-Cis4oJM-.js");
5579
+ const { resolveDaemonHttpBase, loadTokenReadOnly } = await import("./serve-DTQomE4j.js");
4899
5580
  const daemonBase = await resolveDaemonHttpBase().catch(() => null);
4900
5581
  const daemonToken = daemonBase ? await loadTokenReadOnly().catch(() => null) ?? "" : "";
4901
5582
  const capViewer = `attach:${process.pid}`;
@@ -5251,6 +5932,8 @@ async function snapshotStatus(record) {
5251
5932
  pid: record.pid,
5252
5933
  cli: record.cli,
5253
5934
  cwd: record.cwd,
5935
+ workdir: record.workdir ?? record.cwd,
5936
+ workdir_source: record.workdir_source ?? "spawn",
5254
5937
  state,
5255
5938
  activity,
5256
5939
  question,
@@ -5622,7 +6305,7 @@ async function cmdNotify(rest) {
5622
6305
  }
5623
6306
  const ensure = async () => {
5624
6307
  if (!argv["ensure-daemon"]) return;
5625
- const { ensureDaemon } = await import("./notifyDaemon-B0aU7koS.js");
6308
+ const { ensureDaemon } = await import("./notifyDaemon-BkuOBb_g.js");
5626
6309
  await ensureDaemon().catch(() => null);
5627
6310
  };
5628
6311
  await heartbeatWatcher(parent, selfStartedAt);
@@ -5696,7 +6379,7 @@ async function cmdNotifyCursor(args) {
5696
6379
  }
5697
6380
  async function cmdNotifyd(rest) {
5698
6381
  const sub = rest[0] ?? "status";
5699
- const daemon = await import("./notifyDaemon-B0aU7koS.js");
6382
+ const daemon = await import("./notifyDaemon-BkuOBb_g.js");
5700
6383
  switch (sub) {
5701
6384
  case "run": return daemon.runDaemon();
5702
6385
  case "once": return daemon.runDaemon({ once: true });
@@ -5722,5 +6405,5 @@ async function cmdNotifyd(rest) {
5722
6405
  }
5723
6406
 
5724
6407
  //#endregion
5725
- export { sendPayloadCapError as $, isUnknownManagerToken as A, readLogForRender as B, finalizedLines as C, isPidAlive as D, isExitRequest as E, listRecords as F, renderLogTailLines as G, readPtysize as H, matchKeyword as I, resolveOne as J, renderRawLog as K, menuSelectKeys as L, isUserTyping as M, lastReadAt as N, isSlashCommand as O, lastStdinAt as P, runSubcommand as Q, probeStdinReachable as R, extractTaskCounts as S, isBareManagerInvocation as T, recentMessageEdges as U, readNotes as V, recentReadEdges as W, resolveResumeArgs as X, resolveReadWindow as Y, restartHintLines as Z, envelopeAttribution as _, SEND_BODY_MAX_CHARS as a, writeKeysPaced as at, extractMenu as b, backoffWhileTyping as c, framePaste as ct, cmdHelp as d, buildAgentForest as dt, snapshotStatus as et, confirmStdinUnreachable as f, flattenForest as ft, deriveLiveStatus as g, deriveLiveState as h, READ_WINDOW_MS as i, waitForLogQuiet as it, isUnreachableWriteErrno as j, isSubcommand as k, buildEnvelope as l, shouldFramePaste as lt, cursorAbs as m, MAX_RENDER_BYTES as n, stopTipForCli as nt, SEND_EXIT_UNREACHABLE as o, writeToIpc as ot, controlCodeFromName as p, renderRawLogLines as q, READ_PAGE_DEFAULT as r, submitAndConfirm as rt, TYPING_WINDOW_MS as s, withIpcLock as st, GRACEFUL_EXIT_COMMANDS as t, stdinActivityPath as tt, cliDefaults as u, TYPING_BADGE as ut, envelopeCostFor as v, isAgentStuck as w, extractNeedsInput as x, extractBadges as y, readAgentPtysize as z };
5726
- //# sourceMappingURL=subcommands-CvL_1Nt9.js.map
6408
+ export { renderRawLogLines as $, isExitRequest as A, matchKeyword as B, extractMenu as C, inspectSubmission as D, finalizedLines as E, isUnreachableWriteErrno as F, readComposerState as G, ownedCollapsedPaste as H, isUserTyping as I, readPtysize as J, readLogForRender as K, lastReadAt as L, isSlashCommand as M, isSubcommand as N, isAgentStuck as O, isUnknownManagerToken as P, renderRawLog as Q, lastStdinAt as R, extractBadges as S, extractTaskCounts as T, probeStdinReachable as U, menuSelectKeys as V, readAgentPtysize as W, recentReadEdges as X, recentMessageEdges as Y, renderLogTailLines as Z, deriveLiveState as _, buildAgentForest as _t, SEND_BODY_MAX_CHARS as a, sendPayloadCapError as at, envelopeAttribution as b, TYPING_WINDOW_MS as c, stopTipForCli as ct, cliDefaults as d, writeKeysPaced as dt, resolveOne as et, cmdHelp as f, writeToIpc as ft, cwdLabel as g, TYPING_BADGE as gt, cursorAbs as h, shouldFramePaste as ht, READ_WINDOW_MS as i, runSubcommand as it, isPidAlive as j, isBareManagerInvocation as k, backoffWhileTyping as l, submitAndConfirm as lt, controlCodeFromName as m, framePaste as mt, MAX_RENDER_BYTES as n, resolveResumeArgs as nt, SEND_EXIT_QUEUED as o, snapshotStatus as ot, confirmStdinUnreachable as p, withIpcLock as pt, readNotes as q, READ_PAGE_DEFAULT as r, restartHintLines as rt, SEND_EXIT_UNREACHABLE as s, stdinActivityPath as st, GRACEFUL_EXIT_COMMANDS as t, resolveReadWindow as tt, buildEnvelope as u, waitForLogQuiet as ut, deriveLiveStatus as v, flattenForest as vt, extractNeedsInput as w, envelopeCostFor as x, drainerLauncher as y, listRecords as z };
6409
+ //# sourceMappingURL=subcommands-sr1CIEeP.js.map