agent-yes 1.299.1 → 1.300.2

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-BAeTuI-p.js} +3 -3
  4. package/dist/{SUPPORTED_CLIS-YZvIGQvw.js → SUPPORTED_CLIS-BZlaxyEH.js} +2 -2
  5. package/dist/{agentShare-dKQQSOD7.js → agentShare-DGQM24wU.js} +3 -3
  6. package/dist/{callback-BEbbWLKe.js → callback-3RsdcuV0.js} +3 -3
  7. package/dist/{callback-DWxTSlly.js → callback-CQadU_zP.js} +3 -3
  8. package/dist/cli.js +5 -5
  9. package/dist/{cmdPs-D7HWttUU.js → cmdPs-CQxFAs9M.js} +3 -3
  10. package/dist/index.js +2 -2
  11. package/dist/{notifyDaemon-B0aU7koS.js → notifyDaemon-CxkiJvOo.js} +3 -3
  12. package/dist/{parentPingLoop-DSiOXQeU.js → parentPingLoop-vZ8I9k5K.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-CKuufNRn.js → rustBinary-B1buVId2.js} +2 -2
  16. package/dist/{rustBinary-DgRg5H6V.js → rustBinary-etb0Jsga.js} +2 -2
  17. package/dist/{schedule-BStFx0_s.js → schedule-CMBHLSlz.js} +4 -4
  18. package/dist/{serve-Cis4oJM-.js → serve-D5ijYGTv.js} +42 -28
  19. package/dist/{setup-B0sg4AV1.js → setup-DMJYufvD.js} +2 -2
  20. package/dist/{shareCmd-DKIvwe0I.js → shareCmd-CNhCKuOK.js} +3 -3
  21. package/dist/{subcommands-CvL_1Nt9.js → subcommands-BncoxUN6.js} +775 -78
  22. package/dist/subcommands-ZEjbTV_7.js +13 -0
  23. package/dist/{terminal-DqsAuqhw.js → terminal-DzbPI4n0.js} +2 -2
  24. package/dist/{trayApp-Dayj9Frx.js → trayApp-BvtgbxMB.js} +2 -2
  25. package/dist/trayApp-CpPsP3_a.js +5 -0
  26. package/dist/{ts-C2osm4MO.js → ts-Gr1eJOUk.js} +3 -3
  27. package/dist/{versionChecker-BmXwOe40.js → versionChecker-BrjeGNf1.js} +2 -2
  28. package/dist/{widget-D5tsB-oi.js → widget-p4Db_OXd.js} +3 -3
  29. package/dist/{ws-B4jdOeB2.js → ws-D_QClddd.js} +3 -3
  30. package/dist/{ws-mz7VJJwO.js → ws-DnKPi3TS.js} +2 -2
  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 +564 -42
  45. package/ts/subcommands.ts +650 -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
package/ts/subcommands.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  import { randomBytes } from "crypto";
15
15
  import { closeSync, constants as fsConstants, openSync, realpathSync } from "fs";
16
16
  import { execFileSync } from "node:child_process";
17
- import { appendFile, mkdir, open, readFile, stat, writeFile } from "fs/promises";
17
+ import { appendFile, mkdir, open, readFile, rm, stat, writeFile } from "fs/promises";
18
18
  import ms from "ms";
19
19
  import { homedir } from "os";
20
20
  import path from "path";
@@ -99,6 +99,27 @@ import {
99
99
  } from "./remoteHealth.ts";
100
100
  import { isWebrtcSpec } from "./webrtcLink.ts";
101
101
  import { withIpcLock } from "./ipcLock.ts";
102
+ import { isWithin, resolveWorkDir } from "./workDir.ts";
103
+ import {
104
+ bodyHash,
105
+ classifyComposer,
106
+ composerPromptRow,
107
+ DUPLICATE_WINDOW_MS,
108
+ findRecentDuplicate,
109
+ noteRecentSend,
110
+ queuedReceipt,
111
+ senderKey,
112
+ type RecentSend,
113
+ isComposerChrome,
114
+ claimPending,
115
+ type ComposerState,
116
+ enqueuePending,
117
+ listPending,
118
+ PENDING_MAX_AGE_MS,
119
+ readPending,
120
+ retirePending,
121
+ rowsFromXterm,
122
+ } from "./composerGuard.ts";
102
123
 
103
124
  // ---------------------------------------------------------------------------
104
125
  // notes store (~/.agent-yes/notes.jsonl)
@@ -633,6 +654,7 @@ const SUBCOMMANDS = new Set([
633
654
  "hist",
634
655
  "history",
635
656
  "send",
657
+ "send-drain",
636
658
  "msgs",
637
659
  "key",
638
660
  "select",
@@ -701,12 +723,11 @@ const STUCK_THRESHOLD_MS = (() => {
701
723
  // trailing Enter before that settles gets swallowed by the CLI's paste handling
702
724
  // (it lands mid-paste instead of submitting). So instead of a blind fixed sleep,
703
725
  // we poll the log for actual quiet, then confirm the Enter landed by watching for
704
- // either a `working` busy marker or a meaningful size bump, retrying if not.
726
+ // our message identity in the transcript; retry only while it remains in input.
705
727
  const SEND_SETTLE_QUIET_MS = 150; // no log growth for this long → paste finished rendering
706
728
  const SEND_SETTLE_MAX_MS = 1500; // cap: don't wait forever on a screen that's busy for other reasons
707
729
  const SEND_CONFIRM_QUIET_MS = 400; // after Enter, no growth for this long → response has settled
708
730
  const SEND_CONFIRM_MAX_MS = 1200; // cap per confirm attempt
709
- const SEND_CONFIRM_MIN_GROWTH_BYTES = 8; // filters out pure cursor-blink/frame noise
710
731
  const SEND_SUBMIT_MAX_RETRIES = 2; // total attempts = 1 + this
711
732
  // `ay send` typing-backoff: if the user is actively typing at the target's
712
733
  // terminal, injecting our body mid-line would fuse into their text and submit a
@@ -1037,6 +1058,8 @@ export async function runSubcommand(argv: string[]): Promise<number | null> {
1037
1058
  return await (await import("./hist.ts")).cmdHist(rest);
1038
1059
  case "send":
1039
1060
  return await cmdSend(rest);
1061
+ case "send-drain":
1062
+ return await cmdSendDrain(rest);
1040
1063
  case "msgs":
1041
1064
  return await cmdMsgs(rest);
1042
1065
  case "key":
@@ -1376,6 +1399,11 @@ export interface CommonOpts {
1376
1399
  json: boolean;
1377
1400
  }
1378
1401
 
1402
+ /** Looks like an agent_id (12 hex, or a longer injected one) rather than a word. */
1403
+ export function isAgentIdShaped(keyword: string): boolean {
1404
+ return /^[0-9a-f]{12,32}$/i.test(keyword);
1405
+ }
1406
+
1379
1407
  export function matchKeyword(record: GlobalPidRecord, keyword: string): boolean {
1380
1408
  if (!keyword) return true;
1381
1409
  const kw = keyword.toLowerCase();
@@ -1389,16 +1417,30 @@ export function matchKeyword(record: GlobalPidRecord, keyword: string): boolean
1389
1417
  if (record.pid === Number(keyword)) return true;
1390
1418
  return !!(record.agent_id && record.agent_id.toLowerCase().startsWith(kw));
1391
1419
  }
1420
+ // 1a. An id-shaped keyword (12+ hex, the agent_id format) is an identity
1421
+ // selector too. When that agent is gone (its wrapper exited or restarted
1422
+ // under a new id), the id still sits in every sublane's prompt ("reply: ay
1423
+ // send <id>"), so falling through to the prompt rule would resolve it to
1424
+ // whichever lane quoted it — one such lane and `ay send` misdelivers.
1425
+ if (isAgentIdShaped(keyword)) {
1426
+ return !!(record.agent_id && record.agent_id.toLowerCase().startsWith(kw));
1427
+ }
1392
1428
  // 1b. `.` / `./` — shell convention for "the current directory": target the
1393
1429
  // agent whose cwd IS process.cwd() (exact match). Lets `ay send .` reach the
1394
1430
  // sibling agent running in this same dir without typing its pid or a path
1395
1431
  // fragment. Repurposed from the (near-useless) substring behavior — a lone `.`
1396
1432
  // was in almost every path, so it never selected anything meaningful.
1397
1433
  if (kw === "." || kw === "./") {
1398
- return path.resolve(record.cwd) === path.resolve(process.cwd());
1434
+ const here = path.resolve(process.cwd());
1435
+ return (
1436
+ path.resolve(record.cwd) === here ||
1437
+ (!!record.workdir && path.resolve(record.workdir) === here)
1438
+ );
1399
1439
  }
1400
- // 2. cwd contains keyword
1440
+ // 2. cwd (spawn dir or effective work dir) contains keyword
1401
1441
  if (record.cwd.toLowerCase().includes(kw)) return true;
1442
+ if (record.workdir && record.workdir.toLowerCase().includes(kw)) return true;
1443
+
1402
1444
  // 3. cli exact (lowercase)
1403
1445
  if (record.cli.toLowerCase() === kw) return true;
1404
1446
  // 4. prompt substring
@@ -1427,16 +1469,45 @@ export async function listRecords(
1427
1469
  if (opts.active) {
1428
1470
  records = records.filter((r) => isPidAlive(r.pid));
1429
1471
  }
1472
+ records = await withWorkDirs(records);
1430
1473
  if (opts.cwdScope) {
1431
1474
  const scope = opts.cwdScope;
1432
- records = records.filter((r) => r.cwd === scope || r.cwd.startsWith(scope + path.sep));
1475
+ records = records.filter(
1476
+ (r) => isWithin(r.cwd, scope) || (!!r.workdir && isWithin(r.workdir, scope)),
1477
+ );
1433
1478
  }
1479
+
1434
1480
  if (keyword) records = records.filter((r) => matchKeyword(r, keyword));
1435
1481
  // newest first
1436
1482
  records.sort((a, b) => b.started_at - a.started_at);
1437
1483
  return records;
1438
1484
  }
1439
1485
 
1486
+ /**
1487
+ * Stamp each live record with its effective work dir (ts/workDir.ts). Exited
1488
+ * agents keep their spawn cwd: their transcript is history, not a location.
1489
+ */
1490
+ async function withWorkDirs(records: GlobalPidRecord[]): Promise<GlobalPidRecord[]> {
1491
+ return Promise.all(
1492
+ records.map(async (r) =>
1493
+ r.status === "exited"
1494
+ ? { ...r, workdir: r.cwd, workdir_source: "spawn" as const, workdir_at: null }
1495
+ : { ...r, ...(await resolveWorkDir(r)) },
1496
+ ),
1497
+ );
1498
+ }
1499
+
1500
+ /**
1501
+ * The CWD column: the effective work dir, with a leading `↪` when it is not the
1502
+ * spawn dir (sampled from its shells) so a reader knows the registry's `cwd`
1503
+ * says otherwise. `ay ls --json` carries both (`cwd` + `workdir`).
1504
+ */
1505
+ export function cwdLabel(r: { cwd: string; workdir?: string; workdir_source?: string }): string {
1506
+ if (r.workdir && r.workdir_source && r.workdir_source !== "spawn")
1507
+ return `↪ ${shortenPath(r.workdir)}`;
1508
+ return shortenPath(r.cwd);
1509
+ }
1510
+
1440
1511
  export function isPidAlive(pid: number): boolean {
1441
1512
  try {
1442
1513
  process.kill(pid, 0);
@@ -1546,6 +1617,14 @@ export async function resolveOne(
1546
1617
  }
1547
1618
  const matches = await listRecords(keyword, opts);
1548
1619
  if (matches.length === 0) {
1620
+ if (isAgentIdShaped(keyword)) {
1621
+ const gone = opts.all ? [] : await listRecords(keyword, { ...opts, all: true });
1622
+ throw new Error(
1623
+ `no live agent has id "${keyword}"${gone.length ? ` (pid ${gone[0]!.pid} exited)` : ""} — ` +
1624
+ `it is unknown or stale: an agent whose wrapper restarted gets a new id. ` +
1625
+ `Find the current one with \`ay ls\`; nothing was sent.`,
1626
+ );
1627
+ }
1549
1628
  throw new Error(`no agent matched "${keyword}"`);
1550
1629
  }
1551
1630
  // Exact identity beats fuzzy. A numeric pid or a full agent_id names exactly
@@ -2216,7 +2295,7 @@ async function runAllRemotesLs(opts: {
2216
2295
  ? await Promise.all([
2217
2296
  r.log_file ? extractTaskCounts(r.log_file) : Promise.resolve(null),
2218
2297
  r.log_file ? extractBadges(r.log_file) : Promise.resolve([]),
2219
- gitStatusOnce(r.cwd, gitRootCache, gitInfoCache),
2298
+ gitStatusOnce(r.workdir ?? r.cwd, gitRootCache, gitInfoCache),
2220
2299
  isUserTyping(r.pid),
2221
2300
  ])
2222
2301
  : [null, [], null, false];
@@ -2285,7 +2364,7 @@ async function runAllRemotesLs(opts: {
2285
2364
  const cliW = Math.max(3, ...rows.map((r) => String(r.rec.cli).length));
2286
2365
  const statusW = Math.max(6, ...rows.map((r) => String(r.rec.status).length));
2287
2366
  const ageW = Math.max(3, ...rows.map((r) => ageOf(r.rec).length));
2288
- const cwdW = Math.max(3, ...rows.map((r) => shortenPath(String(r.rec.cwd)).length));
2367
+ const cwdW = Math.max(3, ...rows.map((r) => cwdLabel(r.rec).length));
2289
2368
  const promptBudget = Math.max(
2290
2369
  20,
2291
2370
  termWidth - hostW - pidW - cliW - statusW - ageW - cwdW - 6 * 2 - 1,
@@ -2324,7 +2403,7 @@ async function runAllRemotesLs(opts: {
2324
2403
  String(rec.cli).padEnd(cliW),
2325
2404
  String(rec.status).padEnd(statusW),
2326
2405
  ageOf(rec).padEnd(ageW),
2327
- shortenPath(String(rec.cwd)).padEnd(cwdW),
2406
+ cwdLabel(rec).padEnd(cwdW),
2328
2407
  label,
2329
2408
  ].join(" ") + "\n",
2330
2409
  );
@@ -2852,7 +2931,7 @@ async function cmdLs(rest: string[]): Promise<number> {
2852
2931
  );
2853
2932
  const ageOf = (r: GlobalPidRecord) => humanizeAge(now - (lastActive.get(r.pid) ?? r.started_at));
2854
2933
 
2855
- const rawCwds = records.map((r) => shortenPath(r.cwd));
2934
+ const rawCwds = records.map((r) => cwdLabel(r));
2856
2935
  const widths = {
2857
2936
  pid: Math.max(3, ...records.map((r) => String(r.pid).length)),
2858
2937
  cli: Math.max(3, ...records.map((r) => r.cli.length)),
@@ -2888,7 +2967,7 @@ async function cmdLs(rest: string[]): Promise<number> {
2888
2967
  ? await Promise.all([
2889
2968
  r.log_file ? extractTaskCounts(r.log_file) : Promise.resolve(null),
2890
2969
  r.log_file ? extractBadges(r.log_file) : Promise.resolve([]),
2891
- gitStatusOnce(r.cwd, gitRootCache, gitInfoCache),
2970
+ gitStatusOnce(r.workdir ?? r.cwd, gitRootCache, gitInfoCache),
2892
2971
  isUserTyping(r.pid),
2893
2972
  ])
2894
2973
  : [null, [], null, false];
@@ -2924,7 +3003,7 @@ async function cmdLs(rest: string[]): Promise<number> {
2924
3003
  cli: r.cli,
2925
3004
  status: displayStatus,
2926
3005
  age: ageOf(r),
2927
- cwd: shortenPath(r.cwd),
3006
+ cwd: cwdLabel(r),
2928
3007
  label,
2929
3008
  hasNote,
2930
3009
  _alive: displayStatus !== "stopped",
@@ -4208,6 +4287,47 @@ export async function renderLogTailLines(
4208
4287
  n = 40,
4209
4288
  geom?: RenderGeom,
4210
4289
  ): Promise<string[] | null> {
4290
+ const buf = await readLogTailBytes(logPath);
4291
+ if (!buf) return null;
4292
+ try {
4293
+ // Render at the agent's REAL PTY geometry when provided — the raw log is full
4294
+ // of absolute cursor-positioning, so replaying at the wrong width reflows the
4295
+ // TUI into garbage (chars land in the wrong columns). Callers with a pid pass
4296
+ // readPtysize(pid); without it we fall back to the default width.
4297
+ return (await renderRawLog(buf, { mode: "tail", n, cols: geom?.cols, rows: geom?.rows })).split(
4298
+ "\n",
4299
+ );
4300
+ } catch {
4301
+ return null;
4302
+ }
4303
+ }
4304
+
4305
+ /**
4306
+ * What the target's composer holds right now, read from the same 32 KB tail
4307
+ * `renderLogTailLines` renders, but keeping per-cell attributes (dim/inverse) so
4308
+ * ghost text can be told from a real draft. See ts/composerGuard.ts.
4309
+ */
4310
+ export async function readComposerState(record: GlobalPidRecord): Promise<ComposerState> {
4311
+ if (!record.log_file) return { kind: "unknown", reason: "no log file recorded" };
4312
+ const buf = await readLogTailBytes(record.log_file);
4313
+ if (!buf) return { kind: "unknown", reason: "log unreadable or empty" };
4314
+ const geom = (await readAgentPtysize(record)) ?? undefined;
4315
+ try {
4316
+ const Terminal = await loadXtermTerminal();
4317
+ const term = new Terminal({
4318
+ cols: geom?.cols && geom.cols > 0 ? geom.cols : 200,
4319
+ rows: geom?.rows && geom.rows > 0 ? geom.rows : 50,
4320
+ scrollback: 5000,
4321
+ allowProposedApi: true,
4322
+ });
4323
+ await new Promise<void>((resolve) => term.write(buf, resolve));
4324
+ return classifyComposer(rowsFromXterm(term as never, 40));
4325
+ } catch (e) {
4326
+ return { kind: "unknown", reason: `render failed: ${(e as Error)?.message ?? e}` };
4327
+ }
4328
+ }
4329
+
4330
+ async function readLogTailBytes(logPath: string): Promise<Uint8Array | null> {
4211
4331
  const TAIL_BYTES = 32 * 1024;
4212
4332
  let buf: Uint8Array;
4213
4333
  try {
@@ -4229,17 +4349,7 @@ export async function renderLogTailLines(
4229
4349
  } catch {
4230
4350
  return null;
4231
4351
  }
4232
- try {
4233
- // Render at the agent's REAL PTY geometry when provided — the raw log is full
4234
- // of absolute cursor-positioning, so replaying at the wrong width reflows the
4235
- // TUI into garbage (chars land in the wrong columns). Callers with a pid pass
4236
- // readPtysize(pid); without it we fall back to the default width.
4237
- return (await renderRawLog(buf, { mode: "tail", n, cols: geom?.cols, rows: geom?.rows })).split(
4238
- "\n",
4239
- );
4240
- } catch {
4241
- return null;
4242
- }
4352
+ return buf;
4243
4353
  }
4244
4354
 
4245
4355
  export async function extractNeedsInput(logPath: string, cli: string): Promise<NeedsInput | null> {
@@ -4604,43 +4714,170 @@ export async function backoffWhileTyping(
4604
4714
  return { clear: false, waitedMs: Date.now() - start };
4605
4715
  }
4606
4716
 
4607
- /**
4608
- * Send the trailing submit code and confirm the CLI actually acted on it —
4609
- * either a `working` busy marker appears, or the log grows meaningfully. Retries
4610
- * (re-sending just the trailing code) up to SEND_SUBMIT_MAX_RETRIES times when
4611
- * neither shows, since a swallowed Enter looks identical to a slow one until we
4612
- * check. Returns whether submission was confirmed, plus the final rendered tail
4613
- * (for a caller to show the user when it wasn't).
4614
- */
4717
+ type SubmissionState = "submitted" | "queued" | "not-submitted";
4718
+
4719
+ /** Attribute the evidence to THIS message, never to redraws or another turn. */
4720
+ export function inspectSubmission(
4721
+ screen: string[],
4722
+ identity: string,
4723
+ ): {
4724
+ submission: SubmissionState;
4725
+ retry: boolean;
4726
+ transcriptMatches: number;
4727
+ /** A composer is on screen (so `inComposer` means something). */
4728
+ composerVisible: boolean;
4729
+ /** Our message is sitting in that composer, unsent. */
4730
+ inComposer: boolean;
4731
+ } {
4732
+ const unknown = {
4733
+ submission: "not-submitted" as const,
4734
+ retry: false,
4735
+ transcriptMatches: 0,
4736
+ composerVisible: false,
4737
+ inComposer: false,
4738
+ };
4739
+ // The same boundary the draft check uses: a quoted `› line` inside our own
4740
+ // unsent message must not be taken for the prompt (that would count the
4741
+ // message's nonce as transcript evidence — codex review).
4742
+ const prompt = composerPromptRow(screen);
4743
+ if (prompt < 0 || !identity.trim()) return unknown;
4744
+ // Strip whitespace to tolerate terminal wrapping of the nonce/header or body.
4745
+ const compact = (text: string) => text.replace(/\s+/gu, "");
4746
+ const needle = compact(identity);
4747
+ const wrapped = identity.startsWith("<ay-msg ");
4748
+ const transcriptLines = screen.slice(0, prompt);
4749
+ const transcript = compact(transcriptLines.join("\n"));
4750
+ // For raw sends, a short body such as "x" must not match "Codex" or a
4751
+ // suggestion containing that character. Match whole rendered message lines.
4752
+ let transcriptMatches = wrapped ? transcript.split(needle).length - 1 : 0;
4753
+ if (!wrapped) {
4754
+ const lines = transcriptLines.map((line) => compact(line.replace(/^\s*[❯›]\s*/u, "")));
4755
+ for (let start = 0; start < lines.length; start++) {
4756
+ let candidate = "";
4757
+ for (let end = start; end < lines.length && candidate.length < needle.length; end++) {
4758
+ candidate += lines[end];
4759
+ if (candidate === needle) {
4760
+ transcriptMatches++;
4761
+ break;
4762
+ }
4763
+ }
4764
+ }
4765
+ }
4766
+ const input: string[] = [screen[prompt]!.replace(/^\s*[❯›]\s*/u, "")];
4767
+ for (const line of screen.slice(prompt + 1)) {
4768
+ // A rule or the Claude/Codex footer chrome (incl. the model/cwd status row).
4769
+ if (isComposerChrome(line)) break;
4770
+ input.push(line);
4771
+ }
4772
+ const composer = compact(input.join("\n"));
4773
+ if (wrapped ? composer.includes(needle) : composer === needle) {
4774
+ return {
4775
+ submission: "not-submitted",
4776
+ retry: true,
4777
+ transcriptMatches,
4778
+ composerVisible: true,
4779
+ inComposer: true,
4780
+ };
4781
+ }
4782
+ const queued = screen.some((line) =>
4783
+ /^\s*(?:[❯›]\s*)?Press up to edit queued messages\s*$/iu.test(line),
4784
+ );
4785
+ if (transcriptMatches) {
4786
+ // Empty prompts, Codex placeholders and Claude suggestions all mean that
4787
+ // our message has left the composer when its identity is in the transcript.
4788
+ return {
4789
+ submission: queued ? "queued" : "submitted",
4790
+ retry: false,
4791
+ transcriptMatches,
4792
+ composerVisible: true,
4793
+ inComposer: false,
4794
+ };
4795
+ }
4796
+ return { ...unknown, composerVisible: true };
4797
+ }
4798
+
4799
+ export function submissionState(screen: string[], identity = ""): SubmissionState {
4800
+ return inspectSubmission(screen, identity).submission;
4801
+ }
4802
+
4803
+ /** A collapsed paste is not delivery evidence; it can only authorize a retry. */
4804
+ function collapsedPasteToken(screen: string[]): string | null {
4805
+ const prompt = screen.findLastIndex((line) => /^\s*❯($|\s)/u.test(line));
4806
+ if (prompt < 0) return null;
4807
+ const input = screen[prompt]!.replace(/^\s*❯\s*/u, "").trim();
4808
+ return /^\[Pasted text #\d+ \+\d+ lines\]$/.test(input) ? input : null;
4809
+ }
4810
+
4811
+ export function ownedCollapsedPaste(
4812
+ cli: string,
4813
+ beforePaste: string[] | null | undefined,
4814
+ afterPaste: string[],
4815
+ ): string | null {
4816
+ if (cli !== "claude" || !beforePaste) return null;
4817
+ const token = collapsedPasteToken(afterPaste);
4818
+ // Snapshot under the input lock BEFORE writing the body. A pre-existing
4819
+ // placeholder (even in history), missing snapshot, or another CLI is unknown.
4820
+ return token && !beforePaste.join("\n").includes(token) ? token : null;
4821
+ }
4822
+
4823
+ export const SEND_EXIT_QUEUED = 4;
4824
+
4825
+ /** Retry only Enter, never the body. Three attempts, phi delay capped at 400ms. */
4615
4826
  export async function submitAndConfirm(
4616
4827
  record: GlobalPidRecord,
4617
4828
  fifoPath: string,
4618
4829
  trailing: string,
4619
- ): Promise<{ confirmed: boolean; screen: string[] }> {
4830
+ identity: string,
4831
+ beforePaste?: string[] | null,
4832
+ ): Promise<{ confirmed: boolean; screen: string[]; submission: SubmissionState }> {
4620
4833
  const logFile = record.log_file!;
4834
+ const geometry = (await readAgentPtysize(record)) ?? undefined;
4621
4835
  const cfg = (await cliDefaults())[record.cli];
4622
- let screen: string[] = [];
4836
+ let screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
4837
+ const before = inspectSubmission(screen, identity);
4838
+ const baseline = before.transcriptMatches;
4839
+ // Delivered = a NEW copy in the transcript, or — what a count in a rolling
4840
+ // 40-line window cannot show for a repeated raw message like "continue" —
4841
+ // our text was in the visible composer before Enter and has left it while
4842
+ // the composer is still on screen (codex review).
4843
+ const delivered = (e: ReturnType<typeof inspectSubmission>): boolean =>
4844
+ (e.submission !== "not-submitted" && e.transcriptMatches > baseline) ||
4845
+ (before.inComposer && e.composerVisible && !e.inComposer);
4846
+ const outcome = (e: ReturnType<typeof inspectSubmission>, current: string[]) => {
4847
+ const queued =
4848
+ e.submission === "queued" ||
4849
+ current.some((line) => /^\s*(?:[❯›]\s*)?Press up to edit queued messages\s*$/iu.test(line));
4850
+ return {
4851
+ confirmed: !queued,
4852
+ screen: current,
4853
+ submission: (queued ? "queued" : "submitted") as SubmissionState,
4854
+ };
4855
+ };
4856
+ const ownPaste = ownedCollapsedPaste(record.cli, beforePaste, screen);
4857
+ const canRetry = (evidence: ReturnType<typeof inspectSubmission>, current: string[]) =>
4858
+ evidence.retry || (ownPaste !== null && collapsedPasteToken(current) === ownPaste);
4623
4859
  for (let attempt = 0; attempt <= SEND_SUBMIT_MAX_RETRIES; attempt++) {
4624
- const sizeBefore =
4625
- (await stat(logFile)
4626
- .then((s) => s.size)
4627
- .catch(() => null)) ?? 0;
4628
- // A working marker already on screen BEFORE this attempt (e.g. a busy agent
4629
- // that queues typed input) proves nothing about whether THIS Enter landed —
4630
- // it could just be leftover from whatever the agent was already doing. Only
4631
- // a working marker that WASN'T there before, or actual log growth, counts.
4632
- const wasAlreadyWorking = isWorkingScreen(
4633
- (await renderLogTailLines(logFile, 40)) ?? [],
4634
- cfg?.working,
4635
- );
4860
+ if (attempt) {
4861
+ await new Promise((r) => setTimeout(r, Math.min(400, 150 * 1.618 ** (attempt - 1))));
4862
+ // Recheck after the delay: the target could have accepted the earlier Enter.
4863
+ screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
4864
+ const settled = inspectSubmission(screen, identity);
4865
+ if (delivered(settled)) return outcome(settled, screen);
4866
+ if (
4867
+ !canRetry(settled, screen) ||
4868
+ (cfg?.needsInput?.length &&
4869
+ parseMenu(screen, { needsInput: cfg.needsInput, working: cfg.working }))
4870
+ )
4871
+ break;
4872
+ }
4636
4873
  await writeToIpc(fifoPath, trailing);
4637
- const sizeAfter = await waitForLogQuiet(logFile, SEND_CONFIRM_QUIET_MS, SEND_CONFIRM_MAX_MS);
4638
- screen = (await renderLogTailLines(logFile, 40)) ?? [];
4639
- const grew = sizeAfter !== null && sizeAfter >= sizeBefore + SEND_CONFIRM_MIN_GROWTH_BYTES;
4640
- const nowWorking = isWorkingScreen(screen, cfg?.working);
4641
- if ((nowWorking && !wasAlreadyWorking) || grew) return { confirmed: true, screen };
4874
+ await waitForLogQuiet(logFile, SEND_CONFIRM_QUIET_MS, SEND_CONFIRM_MAX_MS);
4875
+ screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
4876
+ const evidence = inspectSubmission(screen, identity);
4877
+ if (delivered(evidence)) return outcome(evidence, screen);
4878
+ if (!canRetry(evidence, screen)) break;
4642
4879
  }
4643
- return { confirmed: false, screen };
4880
+ return { confirmed: false, screen, submission: "not-submitted" };
4644
4881
  }
4645
4882
 
4646
4883
  /** Poll until the agent is no longer parked on a menu (selection accepted → it
@@ -4658,6 +4895,236 @@ async function waitForNeedsInputClear(
4658
4895
  return false;
4659
4896
  }
4660
4897
 
4898
+ /**
4899
+ * Write one message and its trailing code to the target, then (when `canConfirm`)
4900
+ * confirm the submit. The caller holds the input lock. The body is written
4901
+ * exactly once; only Enter is ever retried (see submitAndConfirm).
4902
+ */
4903
+ async function deliverBody(
4904
+ record: GlobalPidRecord,
4905
+ fifoPath: string,
4906
+ fullBody: string,
4907
+ trailing: string,
4908
+ identity: string,
4909
+ canConfirm: boolean,
4910
+ ): Promise<{
4911
+ confirmed: boolean;
4912
+ screen: string[];
4913
+ submission: "submitted" | "queued" | "not-submitted" | "unchecked";
4914
+ }> {
4915
+ if (fullBody && trailing) {
4916
+ const beforePaste =
4917
+ canConfirm && record.log_file
4918
+ ? await renderLogTailLines(
4919
+ record.log_file,
4920
+ 40,
4921
+ (await readAgentPtysize(record)) ?? undefined,
4922
+ )
4923
+ : null;
4924
+ await writeToIpc(fifoPath, fullBody);
4925
+ if (canConfirm && record.log_file) {
4926
+ // Wait for the paste to actually finish rendering — a long/multi-line body
4927
+ // can take longer than any fixed guess, and sending Enter mid-paste gets
4928
+ // swallowed by the CLI's bracketed-paste handling instead of submitting.
4929
+ await waitForLogQuiet(record.log_file, SEND_SETTLE_QUIET_MS, SEND_SETTLE_MAX_MS);
4930
+ return submitAndConfirm(record, fifoPath, trailing, identity, beforePaste);
4931
+ }
4932
+ await new Promise((r) => setTimeout(r, 200));
4933
+ await writeToIpc(fifoPath, trailing);
4934
+ } else {
4935
+ await writeToIpc(fifoPath, fullBody + trailing);
4936
+ }
4937
+ return {
4938
+ confirmed: !canConfirm,
4939
+ screen: [],
4940
+ submission: canConfirm ? "not-submitted" : "unchecked",
4941
+ };
4942
+ }
4943
+
4944
+ // Drainer pacing: poll the parked target with a φ backoff from 500 ms up to 5 s,
4945
+ // reset after every delivery. Worst case a message waits PENDING_MAX_AGE_MS.
4946
+ const DRAIN_POLL_BASE_MS = 500;
4947
+ const DRAIN_POLL_CAP_MS = 5000;
4948
+
4949
+ function drainerLockPath(pid: number): string {
4950
+ return path.join(agentYesHome(), "pending", `${pid}.drainer`);
4951
+ }
4952
+
4953
+ /** The pid of a live drainer for `pid`'s queue, or null. */
4954
+ async function liveDrainer(pid: number): Promise<number | null> {
4955
+ const raw = await readFile(drainerLockPath(pid), "utf-8").catch(() => null);
4956
+ const owner = Number(raw?.trim());
4957
+ if (!Number.isInteger(owner) || owner <= 0) return null;
4958
+ try {
4959
+ process.kill(owner, 0);
4960
+ return owner;
4961
+ } catch {
4962
+ return null;
4963
+ }
4964
+ }
4965
+
4966
+ /**
4967
+ * The argv that re-launches THIS build as the drainer. The drainer must be the
4968
+ * same build that parked the message (an older `ay` on PATH has no
4969
+ * send-drain), so prefer the running script over PATH lookup. Under the bun
4970
+ * runtime that is `bun <script>` on every platform: argv[1] is a .js/.ts file,
4971
+ * never an executable, so spawning it bare (as the first cut did on win32)
4972
+ * ENOENTs and the parked message waits for a manual `ay send-drain`. A
4973
+ * compiled single-file binary has no script to hand over: re-run the binary.
4974
+ */
4975
+ export function drainerLauncher(
4976
+ execPath: string,
4977
+ script: string | undefined,
4978
+ onPath: string | null | undefined,
4979
+ ): string[] | null {
4980
+ const bunRuntime = /(^|[\\/])bun(\.exe)?$/i.test(execPath);
4981
+ if (!bunRuntime) return [execPath];
4982
+ if (script) return [execPath, script];
4983
+ return onPath ? [execPath, onPath] : null;
4984
+ }
4985
+
4986
+ /** Start the per-target drainer unless one is already running. */
4987
+ async function ensureSendDrainer(pid: number): Promise<number | null> {
4988
+ const existing = await liveDrainer(pid);
4989
+ if (existing) return existing;
4990
+ const { spawn } = await import("node:child_process");
4991
+ const launcher = drainerLauncher(process.execPath, process.argv[1], Bun.which("ay"));
4992
+ if (!launcher) return null;
4993
+ const [cmd, ...pre] = launcher;
4994
+ const child = spawn(cmd!, [...pre, "send-drain", String(pid)], {
4995
+ detached: true,
4996
+ stdio: "ignore",
4997
+ });
4998
+ child.on("error", () => {});
4999
+ child.unref();
5000
+ return child.pid ?? null;
5001
+ }
5002
+
5003
+ function pidAlive(pid: number): boolean {
5004
+ try {
5005
+ process.kill(pid, 0);
5006
+ return true;
5007
+ } catch (e) {
5008
+ return (e as NodeJS.ErrnoException)?.code === "EPERM";
5009
+ }
5010
+ }
5011
+
5012
+ /**
5013
+ * `ay send-drain <pid>` — deliver the messages `ay send` parked for <pid>
5014
+ * because its composer held a draft. Runs until the queue is empty, the target
5015
+ * exits, or every message expired. One drainer per target (a pid file under
5016
+ * pending/); a second one exits at once. Normally started by `ay send` itself.
5017
+ */
5018
+ async function cmdSendDrain(rest: string[]): Promise<number> {
5019
+ const pid = Number(rest[0]);
5020
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error("usage: ay send-drain <pid>");
5021
+ const lockFile = drainerLockPath(pid);
5022
+ await mkdir(path.dirname(lockFile), { recursive: true });
5023
+ const other = await liveDrainer(pid);
5024
+ if (other && other !== process.pid) return 0;
5025
+ await writeFile(lockFile, `${process.pid}\n`);
5026
+ // Two drainers can both pass the check above; the last writer owns the queue
5027
+ // and the other one leaves. claimPending keeps a message from going out twice
5028
+ // even inside that window.
5029
+ await new Promise((r) => setTimeout(r, 50));
5030
+ if ((await liveDrainer(pid)) !== process.pid) return 0;
5031
+ try {
5032
+ let attempt = 0;
5033
+ // sender + body hash → when this drainer delivered it: a second parked copy
5034
+ // of the same message from the same agent within the window is dropped.
5035
+ const delivered = new Map<string, number>();
5036
+ for (;;) {
5037
+ const names = await listPending(pid);
5038
+ if (!names.length) {
5039
+ // Give up ownership only under the input lock, which every enqueue also
5040
+ // holds: a sender that parks a message after this re-check finds no
5041
+ // drainer pid file and starts a new drainer; one that parked before it
5042
+ // is seen here and keeps this drainer running.
5043
+ const done = await withIpcLock(pid, async () => {
5044
+ if ((await listPending(pid)).length) return false;
5045
+ await rm(lockFile, { force: true });
5046
+ return true;
5047
+ });
5048
+ if (done) return 0;
5049
+ continue;
5050
+ }
5051
+ const name = names[0]!;
5052
+ const msg = await readPending(pid, name);
5053
+ if (!msg) {
5054
+ await retirePending(pid, name, "unparseable pending file");
5055
+ continue;
5056
+ }
5057
+ const gone = !pidAlive(pid);
5058
+ const expired = Date.now() - msg.queuedAt > PENDING_MAX_AGE_MS;
5059
+ if (gone || expired) {
5060
+ const why = gone ? "target exited before its input box was free" : "expired after 24h";
5061
+ for (const n of gone ? names : [name]) await retirePending(pid, n, why);
5062
+ await recordMessage({
5063
+ at: Date.now(),
5064
+ ...(msg.record as Omit<MessageRecord, "at">),
5065
+ confirmed: false,
5066
+ submission: "not-submitted",
5067
+ } as MessageRecord);
5068
+ if (gone) return 1;
5069
+ continue;
5070
+ }
5071
+ const from = senderKey(
5072
+ (msg.record as { from?: { agent_id?: string; pid?: number } | null }).from,
5073
+ );
5074
+ const msgBody = (msg.record as { body?: string }).body ?? "";
5075
+ const dupKey = from && msgBody ? `${from}|${bodyHash(msgBody)}` : null;
5076
+ const prev = dupKey ? delivered.get(dupKey) : undefined;
5077
+ if (prev !== undefined && msg.queuedAt - prev <= DUPLICATE_WINDOW_MS) {
5078
+ await retirePending(
5079
+ pid,
5080
+ name,
5081
+ `duplicate of the same sender's identical message delivered ${Math.round((Date.now() - prev) / 1000)}s ago`,
5082
+ );
5083
+ continue;
5084
+ }
5085
+ const record = (await readGlobalPids()).find((r) => r.pid === pid);
5086
+ let result: Awaited<ReturnType<typeof deliverBody>> | null = null;
5087
+ if (record && !(await isUserTyping(pid))) {
5088
+ await withIpcLock(pid, async () => {
5089
+ // Re-check under the lock, right before the write.
5090
+ if (await isUserTyping(pid)) return;
5091
+ // Only a positive reading releases a parked message: an unreadable
5092
+ // screen or one without a composer (a menu) waits for the next poll.
5093
+ const composer = await readComposerState(record);
5094
+ if (composer.kind !== "empty") return;
5095
+ if (!(await claimPending(pid, name))) return;
5096
+ result = await deliverBody(
5097
+ record,
5098
+ msg.fifoPath,
5099
+ msg.fullBody,
5100
+ msg.trailing,
5101
+ msg.identity,
5102
+ msg.trailing === "\r" && Boolean(record.log_file),
5103
+ );
5104
+ });
5105
+ }
5106
+ if (result) {
5107
+ const d = result as Awaited<ReturnType<typeof deliverBody>>;
5108
+ if (dupKey) delivered.set(dupKey, Date.now());
5109
+ await recordMessage({
5110
+ at: Date.now(),
5111
+ ...(msg.record as Omit<MessageRecord, "at">),
5112
+ confirmed: d.confirmed,
5113
+ submission: d.submission,
5114
+ } as MessageRecord);
5115
+ attempt = 0;
5116
+ continue;
5117
+ }
5118
+ attempt++;
5119
+ await new Promise((r) =>
5120
+ setTimeout(r, Math.min(DRAIN_POLL_CAP_MS, DRAIN_POLL_BASE_MS * 1.618 ** (attempt - 1))),
5121
+ );
5122
+ }
5123
+ } finally {
5124
+ if ((await liveDrainer(pid)) === process.pid) await rm(lockFile, { force: true });
5125
+ }
5126
+ }
5127
+
4661
5128
  async function cmdSend(rest: string[]): Promise<number> {
4662
5129
  const y = yargs(rest)
4663
5130
  // Disable yargs' `--no-<flag>` negation: without this, `--no-wait` is parsed
@@ -4669,7 +5136,11 @@ async function cmdSend(rest: string[]): Promise<number> {
4669
5136
  .usage(
4670
5137
  "Usage: ay send <keyword> <msg|-> [options]\n\n" +
4671
5138
  "Exit: 0 sent, 3 target unreachable (nothing sent; ay ls shows it as\n" +
4672
- "'unreachable' — ay restart <pid> revives it), 1 everything else.",
5139
+ "'unreachable' — ay restart <pid> revives it), 4 QUEUED (accepted, not yet\n" +
5140
+ "submitted: either the CLI queued it, or its input box held someone's draft and\n" +
5141
+ "the message was parked for delivery once the box is empty — do not resend;\n" +
5142
+ "an identical resend from the same agent within 60s is dropped as a DUPLICATE),\n" +
5143
+ "1 everything else.",
4673
5144
  )
4674
5145
  .option("code", {
4675
5146
  type: "string",
@@ -4940,15 +5411,13 @@ async function cmdSend(rest: string[]): Promise<number> {
4940
5411
  // body mid-line fuses into their text and submits a mangled line. Only for a
4941
5412
  // real text body; skipped for --force (caller means it), --no-wait
4942
5413
  // (fire-and-forget), and empty bodies (a bare esc/ctrl-c interrupt is usually
4943
- // intentional and time-sensitive). Sends anyway after the deadline so a
4944
- // message is never silently dropped.
5414
+ // intentional and time-sensitive). If they are still typing at the deadline
5415
+ // the message is parked (see the composer guard below) instead of interleaved.
5416
+ let parkReason: string | null = null;
4945
5417
  if (fullBody && !noWait && !force) {
4946
5418
  const { clear, waitedMs } = await backoffWhileTyping(record.pid, SEND_TYPING_MAX_WAIT_MS);
4947
5419
  if (!clear) {
4948
- process.stderr.write(
4949
- `warning: user still typing at pid ${record.pid} after ${Math.round(waitedMs / 1000)}s — ` +
4950
- `sending anyway (may interleave with their line). Use --force to skip this wait.\n`,
4951
- );
5420
+ parkReason = `user still typing after ${Math.round(waitedMs / 1000)}s`;
4952
5421
  } else if (waitedMs > 0) {
4953
5422
  process.stderr.write(
4954
5423
  `waited ${Math.round(waitedMs / 1000)}s for the user to pause typing before sending.\n`,
@@ -4961,8 +5430,34 @@ async function cmdSend(rest: string[]): Promise<number> {
4961
5430
  // double-interrupt. Checked against the resolved byte, not the code NAME, so
4962
5431
  // every alias that resolves to Enter (--code=enter or --code=cr) is covered.
4963
5432
  const canConfirm = trailing === "\r" && Boolean(fullBody) && !noWait;
4964
- let confirmed = true;
5433
+ const identity = nonce ? `<ay-msg ${nonce}` : body;
5434
+ let confirmed = !canConfirm;
5435
+ const receipt: { submission: "submitted" | "queued" | "not-submitted" | "unchecked" } = {
5436
+ submission: canConfirm ? "not-submitted" : "unchecked",
5437
+ };
4965
5438
  let lastScreen: string[] = [];
5439
+ let parked = false;
5440
+ let duplicateOf: RecentSend | null = null;
5441
+ // The mailbox fields known before delivery; a parked message carries them to
5442
+ // the drainer so its eventual record names the real sender, not the drainer.
5443
+ const mailBase = {
5444
+ nonce,
5445
+ origin: sender.agent ? undefined : ("shell" as const),
5446
+ from_via: sender.via,
5447
+ sender_observed: observedSender(),
5448
+ from: sender.agent
5449
+ ? {
5450
+ pid: sender.agent.pid,
5451
+ cli: sender.agent.cli,
5452
+ cwd: sender.agent.cwd,
5453
+ agent_id: sender.agent.agent_id,
5454
+ }
5455
+ : null,
5456
+ to: { pid: record.pid, cli: record.cli, cwd: record.cwd, agent_id: record.agent_id },
5457
+ body,
5458
+ code: trailing === "\r" ? undefined : codeName,
5459
+ wrapped: Boolean(nonce),
5460
+ };
4966
5461
  // The body and its Enter are ONE transaction: every gap between them (the
4967
5462
  // paste-settle wait, the submit-confirm retries) is a window where another
4968
5463
  // writer's bytes would land mid-message. See ts/ipcLock.ts.
@@ -4970,25 +5465,52 @@ async function cmdSend(rest: string[]): Promise<number> {
4970
5465
  await withIpcLock(
4971
5466
  record.pid,
4972
5467
  async () => {
4973
- if (fullBody && trailing) {
4974
- await writeToIpc(fifoPath, fullBody);
4975
- if (canConfirm && record.log_file) {
4976
- // Wait for the paste to actually finish rendering — a long/multi-line body
4977
- // can take longer than any fixed guess, and sending Enter mid-paste gets
4978
- // swallowed by the CLI's bracketed-paste handling instead of submitting.
4979
- await waitForLogQuiet(record.log_file, SEND_SETTLE_QUIET_MS, SEND_SETTLE_MAX_MS);
4980
- ({ confirmed, screen: lastScreen } = await submitAndConfirm(
4981
- record,
5468
+ // Composer guard (ts/composerGuard.ts): never type into someone else's
5469
+ // draft. Checked under the input lock, right before the write, so no
5470
+ // other `ay send` can change the composer between the check and the
5471
+ // paste. A message already parked for this pid also parks this one, so
5472
+ // delivery keeps send order.
5473
+ // Dedupe at the sink: the same agent re-sending the same body within a
5474
+ // minute (it read rc=4 QUEUED as a failure) is dropped, not typed or
5475
+ // parked twice. --force and human (shell) senders are exempt.
5476
+ const dedupeKey = force || !body ? null : senderKey(mailBase.from);
5477
+ if (dedupeKey) {
5478
+ duplicateOf = await findRecentDuplicate(record.pid, dedupeKey, body);
5479
+ if (duplicateOf) return;
5480
+ }
5481
+ if (fullBody) {
5482
+ if (!parkReason && (await listPending(record.pid)).length)
5483
+ parkReason = "earlier messages to this agent are still queued";
5484
+ if (!parkReason) {
5485
+ const composer = await readComposerState(record);
5486
+ if (composer.kind === "draft")
5487
+ parkReason = `its input box holds a draft (${composer.chars} chars)`;
5488
+ else if (composer.kind === "unknown")
5489
+ process.stderr.write(
5490
+ `warning: ay send could not see pid ${record.pid}'s input box (${composer.reason}) — sending without the draft check.\n`,
5491
+ );
5492
+ }
5493
+ if (dedupeKey)
5494
+ await noteRecentSend(record.pid, dedupeKey, body, parkReason ? "queued" : "sent");
5495
+ if (parkReason) {
5496
+ await enqueuePending({
5497
+ queuedAt: Date.now(),
5498
+ pid: record.pid,
4982
5499
  fifoPath,
5500
+ fullBody,
4983
5501
  trailing,
4984
- ));
4985
- } else {
4986
- await new Promise((r) => setTimeout(r, 200));
4987
- await writeToIpc(fifoPath, trailing);
5502
+ identity,
5503
+ record: mailBase,
5504
+ });
5505
+ parked = true;
5506
+ return;
4988
5507
  }
4989
- } else {
4990
- await writeToIpc(fifoPath, fullBody + trailing);
4991
5508
  }
5509
+ ({
5510
+ confirmed,
5511
+ screen: lastScreen,
5512
+ submission: receipt.submission,
5513
+ } = await deliverBody(record, fifoPath, fullBody, trailing, identity, canConfirm));
4992
5514
  },
4993
5515
  (why) =>
4994
5516
  process.stderr.write(
@@ -5010,11 +5532,53 @@ async function cmdSend(rest: string[]): Promise<number> {
5010
5532
  );
5011
5533
  return SEND_EXIT_UNREACHABLE;
5012
5534
  }
5535
+ if (duplicateOf) {
5536
+ const dup = duplicateOf as RecentSend;
5537
+ const ago = Math.max(0, Math.round((Date.now() - dup.at) / 1000));
5538
+ process.stdout.write(
5539
+ `DUPLICATE (not resent) to pid ${record.pid} (${record.cli}): ${truncate(body + trailing, 80)}\n`,
5540
+ );
5541
+ process.stderr.write(
5542
+ queuedReceipt(
5543
+ "duplicate",
5544
+ `you sent this exact message to pid ${record.pid} ${ago}s ago and it was ${dup.outcome}`,
5545
+ ) + "\n",
5546
+ );
5547
+ return dup.outcome === "queued" ? SEND_EXIT_QUEUED : 0;
5548
+ }
5549
+ if (parked) {
5550
+ const drainer = await ensureSendDrainer(record.pid);
5551
+ process.stdout.write(
5552
+ `QUEUED to pid ${record.pid} (${record.cli}): ${truncate(body + trailing, 80)}\n`,
5553
+ );
5554
+ process.stderr.write(
5555
+ queuedReceipt("parked", parkReason!) +
5556
+ (drainer
5557
+ ? ` (drainer pid ${drainer})\n`
5558
+ : `\nay send: the drainer did not start; run: ay send-drain ${record.pid}\n`),
5559
+ );
5560
+ if (body)
5561
+ await recordMessage({
5562
+ at: Date.now(),
5563
+ ...mailBase,
5564
+ confirmed: false,
5565
+ submission: "queued",
5566
+ } as MessageRecord);
5567
+ return SEND_EXIT_QUEUED;
5568
+ }
5569
+ const { submission } = receipt;
5013
5570
  const payload = body + trailing;
5014
- const status = confirmed ? "sent" : "sent but NOT confirmed submitted";
5571
+ const status =
5572
+ submission === "queued"
5573
+ ? "QUEUED"
5574
+ : confirmed
5575
+ ? "sent"
5576
+ : "NOT SUBMITTED (NOT confirmed: our message remains in input or destination evidence is unavailable)";
5015
5577
  process.stdout.write(
5016
5578
  `${status} to pid ${record.pid} (${record.cli}): ${truncate(payload, 80)}\n`,
5017
5579
  );
5580
+ if (submission === "queued")
5581
+ process.stderr.write(queuedReceipt("cli-queued", `${record.cli} is busy`) + "\n");
5018
5582
 
5019
5583
  // Persist a durable record of the exchange from both ends' point of view (the
5020
5584
  // sender's outbox + the recipient's inbox). Only real message bodies are
@@ -5049,12 +5613,13 @@ async function cmdSend(rest: string[]): Promise<number> {
5049
5613
  body,
5050
5614
  code: trailing === "\r" ? undefined : codeName,
5051
5615
  confirmed,
5616
+ submission,
5052
5617
  wrapped: Boolean(nonce),
5053
5618
  });
5054
5619
  }
5055
- if (!confirmed) {
5620
+ if (!confirmed && submission !== "queued") {
5056
5621
  process.stderr.write(
5057
- `\nwarning: couldn't confirm the CLI acted on it after ${SEND_SUBMIT_MAX_RETRIES + 1} attempt(s) — ` +
5622
+ `\nwarning: couldn't confirm the CLI acted on this message — ` +
5058
5623
  `it may still be sitting unsubmitted in the prompt. Last screen:\n` +
5059
5624
  lastScreen
5060
5625
  .slice(-8)
@@ -5096,7 +5661,7 @@ async function cmdSend(rest: string[]): Promise<number> {
5096
5661
  const tip = stopTipForCli(record.cli, record.pid);
5097
5662
  if (tip) process.stderr.write(tip);
5098
5663
  }
5099
- return confirmed ? 0 : 1;
5664
+ return submission === "queued" ? SEND_EXIT_QUEUED : confirmed ? 0 : 1;
5100
5665
  }
5101
5666
 
5102
5667
  // ---------------------------------------------------------------------------
@@ -5205,7 +5770,8 @@ async function cmdMsgs(rest: string[]): Promise<number> {
5205
5770
  const fromLabel = senderLabel(rec);
5206
5771
  const peer = dir === "out" ? `→ ${rec.to.cli} #${rec.to.pid}` : `← ${fromLabel}`;
5207
5772
  const via = rec.remote ? ` (via ${rec.remote})` : "";
5208
- const flag = rec.confirmed === false ? " (unconfirmed)" : "";
5773
+ const flag =
5774
+ rec.submission === "queued" ? " (QUEUED)" : rec.confirmed === false ? " (unconfirmed)" : "";
5209
5775
  const tag = rec.kind ? `[${rec.kind}] ` : "";
5210
5776
  const line = tag + truncate(rec.body.replace(/\s+/g, " "), 100);
5211
5777
  process.stdout.write(`${when} ${peer.padEnd(20)}${via}${flag} ${line}\n`);
@@ -6401,6 +6967,9 @@ export interface StatusSnapshot {
6401
6967
  pid: number;
6402
6968
  cli: string;
6403
6969
  cwd: string;
6970
+ /** Effective work dir (see ts/workDir.ts); equals `cwd` when source is spawn. */
6971
+ workdir: string;
6972
+ workdir_source: "observed" | "spawn";
6404
6973
  // needs_input: alive but blocked on an interactive menu (distinct from idle =
6405
6974
  // alive+quiet/done, and stopped = exited). stuck: alive + busy marker on screen
6406
6975
  // but long-silent (wedged mid-stream). unreachable: alive but its stdin FIFO
@@ -6476,6 +7045,8 @@ export async function snapshotStatus(record: GlobalPidRecord): Promise<StatusSna
6476
7045
  pid: record.pid,
6477
7046
  cli: record.cli,
6478
7047
  cwd: record.cwd,
7048
+ workdir: record.workdir ?? record.cwd,
7049
+ workdir_source: record.workdir_source ?? "spawn",
6479
7050
  state,
6480
7051
  activity,
6481
7052
  question,