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
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":
@@ -1395,10 +1418,16 @@ export function matchKeyword(record: GlobalPidRecord, keyword: string): boolean
1395
1418
  // fragment. Repurposed from the (near-useless) substring behavior — a lone `.`
1396
1419
  // was in almost every path, so it never selected anything meaningful.
1397
1420
  if (kw === "." || kw === "./") {
1398
- return path.resolve(record.cwd) === path.resolve(process.cwd());
1421
+ const here = path.resolve(process.cwd());
1422
+ return (
1423
+ path.resolve(record.cwd) === here ||
1424
+ (!!record.workdir && path.resolve(record.workdir) === here)
1425
+ );
1399
1426
  }
1400
- // 2. cwd contains keyword
1427
+ // 2. cwd (spawn dir or effective work dir) contains keyword
1401
1428
  if (record.cwd.toLowerCase().includes(kw)) return true;
1429
+ if (record.workdir && record.workdir.toLowerCase().includes(kw)) return true;
1430
+
1402
1431
  // 3. cli exact (lowercase)
1403
1432
  if (record.cli.toLowerCase() === kw) return true;
1404
1433
  // 4. prompt substring
@@ -1427,16 +1456,45 @@ export async function listRecords(
1427
1456
  if (opts.active) {
1428
1457
  records = records.filter((r) => isPidAlive(r.pid));
1429
1458
  }
1459
+ records = await withWorkDirs(records);
1430
1460
  if (opts.cwdScope) {
1431
1461
  const scope = opts.cwdScope;
1432
- records = records.filter((r) => r.cwd === scope || r.cwd.startsWith(scope + path.sep));
1462
+ records = records.filter(
1463
+ (r) => isWithin(r.cwd, scope) || (!!r.workdir && isWithin(r.workdir, scope)),
1464
+ );
1433
1465
  }
1466
+
1434
1467
  if (keyword) records = records.filter((r) => matchKeyword(r, keyword));
1435
1468
  // newest first
1436
1469
  records.sort((a, b) => b.started_at - a.started_at);
1437
1470
  return records;
1438
1471
  }
1439
1472
 
1473
+ /**
1474
+ * Stamp each live record with its effective work dir (ts/workDir.ts). Exited
1475
+ * agents keep their spawn cwd: their transcript is history, not a location.
1476
+ */
1477
+ async function withWorkDirs(records: GlobalPidRecord[]): Promise<GlobalPidRecord[]> {
1478
+ return Promise.all(
1479
+ records.map(async (r) =>
1480
+ r.status === "exited"
1481
+ ? { ...r, workdir: r.cwd, workdir_source: "spawn" as const, workdir_at: null }
1482
+ : { ...r, ...(await resolveWorkDir(r)) },
1483
+ ),
1484
+ );
1485
+ }
1486
+
1487
+ /**
1488
+ * The CWD column: the effective work dir, with a leading `↪` when it is not the
1489
+ * spawn dir (sampled from its shells) so a reader knows the registry's `cwd`
1490
+ * says otherwise. `ay ls --json` carries both (`cwd` + `workdir`).
1491
+ */
1492
+ export function cwdLabel(r: { cwd: string; workdir?: string; workdir_source?: string }): string {
1493
+ if (r.workdir && r.workdir_source && r.workdir_source !== "spawn")
1494
+ return `↪ ${shortenPath(r.workdir)}`;
1495
+ return shortenPath(r.cwd);
1496
+ }
1497
+
1440
1498
  export function isPidAlive(pid: number): boolean {
1441
1499
  try {
1442
1500
  process.kill(pid, 0);
@@ -2216,7 +2274,7 @@ async function runAllRemotesLs(opts: {
2216
2274
  ? await Promise.all([
2217
2275
  r.log_file ? extractTaskCounts(r.log_file) : Promise.resolve(null),
2218
2276
  r.log_file ? extractBadges(r.log_file) : Promise.resolve([]),
2219
- gitStatusOnce(r.cwd, gitRootCache, gitInfoCache),
2277
+ gitStatusOnce(r.workdir ?? r.cwd, gitRootCache, gitInfoCache),
2220
2278
  isUserTyping(r.pid),
2221
2279
  ])
2222
2280
  : [null, [], null, false];
@@ -2285,7 +2343,7 @@ async function runAllRemotesLs(opts: {
2285
2343
  const cliW = Math.max(3, ...rows.map((r) => String(r.rec.cli).length));
2286
2344
  const statusW = Math.max(6, ...rows.map((r) => String(r.rec.status).length));
2287
2345
  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));
2346
+ const cwdW = Math.max(3, ...rows.map((r) => cwdLabel(r.rec).length));
2289
2347
  const promptBudget = Math.max(
2290
2348
  20,
2291
2349
  termWidth - hostW - pidW - cliW - statusW - ageW - cwdW - 6 * 2 - 1,
@@ -2324,7 +2382,7 @@ async function runAllRemotesLs(opts: {
2324
2382
  String(rec.cli).padEnd(cliW),
2325
2383
  String(rec.status).padEnd(statusW),
2326
2384
  ageOf(rec).padEnd(ageW),
2327
- shortenPath(String(rec.cwd)).padEnd(cwdW),
2385
+ cwdLabel(rec).padEnd(cwdW),
2328
2386
  label,
2329
2387
  ].join(" ") + "\n",
2330
2388
  );
@@ -2852,7 +2910,7 @@ async function cmdLs(rest: string[]): Promise<number> {
2852
2910
  );
2853
2911
  const ageOf = (r: GlobalPidRecord) => humanizeAge(now - (lastActive.get(r.pid) ?? r.started_at));
2854
2912
 
2855
- const rawCwds = records.map((r) => shortenPath(r.cwd));
2913
+ const rawCwds = records.map((r) => cwdLabel(r));
2856
2914
  const widths = {
2857
2915
  pid: Math.max(3, ...records.map((r) => String(r.pid).length)),
2858
2916
  cli: Math.max(3, ...records.map((r) => r.cli.length)),
@@ -2888,7 +2946,7 @@ async function cmdLs(rest: string[]): Promise<number> {
2888
2946
  ? await Promise.all([
2889
2947
  r.log_file ? extractTaskCounts(r.log_file) : Promise.resolve(null),
2890
2948
  r.log_file ? extractBadges(r.log_file) : Promise.resolve([]),
2891
- gitStatusOnce(r.cwd, gitRootCache, gitInfoCache),
2949
+ gitStatusOnce(r.workdir ?? r.cwd, gitRootCache, gitInfoCache),
2892
2950
  isUserTyping(r.pid),
2893
2951
  ])
2894
2952
  : [null, [], null, false];
@@ -2924,7 +2982,7 @@ async function cmdLs(rest: string[]): Promise<number> {
2924
2982
  cli: r.cli,
2925
2983
  status: displayStatus,
2926
2984
  age: ageOf(r),
2927
- cwd: shortenPath(r.cwd),
2985
+ cwd: cwdLabel(r),
2928
2986
  label,
2929
2987
  hasNote,
2930
2988
  _alive: displayStatus !== "stopped",
@@ -4208,6 +4266,47 @@ export async function renderLogTailLines(
4208
4266
  n = 40,
4209
4267
  geom?: RenderGeom,
4210
4268
  ): Promise<string[] | null> {
4269
+ const buf = await readLogTailBytes(logPath);
4270
+ if (!buf) return null;
4271
+ try {
4272
+ // Render at the agent's REAL PTY geometry when provided — the raw log is full
4273
+ // of absolute cursor-positioning, so replaying at the wrong width reflows the
4274
+ // TUI into garbage (chars land in the wrong columns). Callers with a pid pass
4275
+ // readPtysize(pid); without it we fall back to the default width.
4276
+ return (await renderRawLog(buf, { mode: "tail", n, cols: geom?.cols, rows: geom?.rows })).split(
4277
+ "\n",
4278
+ );
4279
+ } catch {
4280
+ return null;
4281
+ }
4282
+ }
4283
+
4284
+ /**
4285
+ * What the target's composer holds right now, read from the same 32 KB tail
4286
+ * `renderLogTailLines` renders, but keeping per-cell attributes (dim/inverse) so
4287
+ * ghost text can be told from a real draft. See ts/composerGuard.ts.
4288
+ */
4289
+ export async function readComposerState(record: GlobalPidRecord): Promise<ComposerState> {
4290
+ if (!record.log_file) return { kind: "unknown", reason: "no log file recorded" };
4291
+ const buf = await readLogTailBytes(record.log_file);
4292
+ if (!buf) return { kind: "unknown", reason: "log unreadable or empty" };
4293
+ const geom = (await readAgentPtysize(record)) ?? undefined;
4294
+ try {
4295
+ const Terminal = await loadXtermTerminal();
4296
+ const term = new Terminal({
4297
+ cols: geom?.cols && geom.cols > 0 ? geom.cols : 200,
4298
+ rows: geom?.rows && geom.rows > 0 ? geom.rows : 50,
4299
+ scrollback: 5000,
4300
+ allowProposedApi: true,
4301
+ });
4302
+ await new Promise<void>((resolve) => term.write(buf, resolve));
4303
+ return classifyComposer(rowsFromXterm(term as never, 40));
4304
+ } catch (e) {
4305
+ return { kind: "unknown", reason: `render failed: ${(e as Error)?.message ?? e}` };
4306
+ }
4307
+ }
4308
+
4309
+ async function readLogTailBytes(logPath: string): Promise<Uint8Array | null> {
4211
4310
  const TAIL_BYTES = 32 * 1024;
4212
4311
  let buf: Uint8Array;
4213
4312
  try {
@@ -4229,17 +4328,7 @@ export async function renderLogTailLines(
4229
4328
  } catch {
4230
4329
  return null;
4231
4330
  }
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
- }
4331
+ return buf;
4243
4332
  }
4244
4333
 
4245
4334
  export async function extractNeedsInput(logPath: string, cli: string): Promise<NeedsInput | null> {
@@ -4604,43 +4693,170 @@ export async function backoffWhileTyping(
4604
4693
  return { clear: false, waitedMs: Date.now() - start };
4605
4694
  }
4606
4695
 
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
- */
4696
+ type SubmissionState = "submitted" | "queued" | "not-submitted";
4697
+
4698
+ /** Attribute the evidence to THIS message, never to redraws or another turn. */
4699
+ export function inspectSubmission(
4700
+ screen: string[],
4701
+ identity: string,
4702
+ ): {
4703
+ submission: SubmissionState;
4704
+ retry: boolean;
4705
+ transcriptMatches: number;
4706
+ /** A composer is on screen (so `inComposer` means something). */
4707
+ composerVisible: boolean;
4708
+ /** Our message is sitting in that composer, unsent. */
4709
+ inComposer: boolean;
4710
+ } {
4711
+ const unknown = {
4712
+ submission: "not-submitted" as const,
4713
+ retry: false,
4714
+ transcriptMatches: 0,
4715
+ composerVisible: false,
4716
+ inComposer: false,
4717
+ };
4718
+ // The same boundary the draft check uses: a quoted `› line` inside our own
4719
+ // unsent message must not be taken for the prompt (that would count the
4720
+ // message's nonce as transcript evidence — codex review).
4721
+ const prompt = composerPromptRow(screen);
4722
+ if (prompt < 0 || !identity.trim()) return unknown;
4723
+ // Strip whitespace to tolerate terminal wrapping of the nonce/header or body.
4724
+ const compact = (text: string) => text.replace(/\s+/gu, "");
4725
+ const needle = compact(identity);
4726
+ const wrapped = identity.startsWith("<ay-msg ");
4727
+ const transcriptLines = screen.slice(0, prompt);
4728
+ const transcript = compact(transcriptLines.join("\n"));
4729
+ // For raw sends, a short body such as "x" must not match "Codex" or a
4730
+ // suggestion containing that character. Match whole rendered message lines.
4731
+ let transcriptMatches = wrapped ? transcript.split(needle).length - 1 : 0;
4732
+ if (!wrapped) {
4733
+ const lines = transcriptLines.map((line) => compact(line.replace(/^\s*[❯›]\s*/u, "")));
4734
+ for (let start = 0; start < lines.length; start++) {
4735
+ let candidate = "";
4736
+ for (let end = start; end < lines.length && candidate.length < needle.length; end++) {
4737
+ candidate += lines[end];
4738
+ if (candidate === needle) {
4739
+ transcriptMatches++;
4740
+ break;
4741
+ }
4742
+ }
4743
+ }
4744
+ }
4745
+ const input: string[] = [screen[prompt]!.replace(/^\s*[❯›]\s*/u, "")];
4746
+ for (const line of screen.slice(prompt + 1)) {
4747
+ // A rule or the Claude/Codex footer chrome (incl. the model/cwd status row).
4748
+ if (isComposerChrome(line)) break;
4749
+ input.push(line);
4750
+ }
4751
+ const composer = compact(input.join("\n"));
4752
+ if (wrapped ? composer.includes(needle) : composer === needle) {
4753
+ return {
4754
+ submission: "not-submitted",
4755
+ retry: true,
4756
+ transcriptMatches,
4757
+ composerVisible: true,
4758
+ inComposer: true,
4759
+ };
4760
+ }
4761
+ const queued = screen.some((line) =>
4762
+ /^\s*(?:[❯›]\s*)?Press up to edit queued messages\s*$/iu.test(line),
4763
+ );
4764
+ if (transcriptMatches) {
4765
+ // Empty prompts, Codex placeholders and Claude suggestions all mean that
4766
+ // our message has left the composer when its identity is in the transcript.
4767
+ return {
4768
+ submission: queued ? "queued" : "submitted",
4769
+ retry: false,
4770
+ transcriptMatches,
4771
+ composerVisible: true,
4772
+ inComposer: false,
4773
+ };
4774
+ }
4775
+ return { ...unknown, composerVisible: true };
4776
+ }
4777
+
4778
+ export function submissionState(screen: string[], identity = ""): SubmissionState {
4779
+ return inspectSubmission(screen, identity).submission;
4780
+ }
4781
+
4782
+ /** A collapsed paste is not delivery evidence; it can only authorize a retry. */
4783
+ function collapsedPasteToken(screen: string[]): string | null {
4784
+ const prompt = screen.findLastIndex((line) => /^\s*❯($|\s)/u.test(line));
4785
+ if (prompt < 0) return null;
4786
+ const input = screen[prompt]!.replace(/^\s*❯\s*/u, "").trim();
4787
+ return /^\[Pasted text #\d+ \+\d+ lines\]$/.test(input) ? input : null;
4788
+ }
4789
+
4790
+ export function ownedCollapsedPaste(
4791
+ cli: string,
4792
+ beforePaste: string[] | null | undefined,
4793
+ afterPaste: string[],
4794
+ ): string | null {
4795
+ if (cli !== "claude" || !beforePaste) return null;
4796
+ const token = collapsedPasteToken(afterPaste);
4797
+ // Snapshot under the input lock BEFORE writing the body. A pre-existing
4798
+ // placeholder (even in history), missing snapshot, or another CLI is unknown.
4799
+ return token && !beforePaste.join("\n").includes(token) ? token : null;
4800
+ }
4801
+
4802
+ export const SEND_EXIT_QUEUED = 4;
4803
+
4804
+ /** Retry only Enter, never the body. Three attempts, phi delay capped at 400ms. */
4615
4805
  export async function submitAndConfirm(
4616
4806
  record: GlobalPidRecord,
4617
4807
  fifoPath: string,
4618
4808
  trailing: string,
4619
- ): Promise<{ confirmed: boolean; screen: string[] }> {
4809
+ identity: string,
4810
+ beforePaste?: string[] | null,
4811
+ ): Promise<{ confirmed: boolean; screen: string[]; submission: SubmissionState }> {
4620
4812
  const logFile = record.log_file!;
4813
+ const geometry = (await readAgentPtysize(record)) ?? undefined;
4621
4814
  const cfg = (await cliDefaults())[record.cli];
4622
- let screen: string[] = [];
4815
+ let screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
4816
+ const before = inspectSubmission(screen, identity);
4817
+ const baseline = before.transcriptMatches;
4818
+ // Delivered = a NEW copy in the transcript, or — what a count in a rolling
4819
+ // 40-line window cannot show for a repeated raw message like "continue" —
4820
+ // our text was in the visible composer before Enter and has left it while
4821
+ // the composer is still on screen (codex review).
4822
+ const delivered = (e: ReturnType<typeof inspectSubmission>): boolean =>
4823
+ (e.submission !== "not-submitted" && e.transcriptMatches > baseline) ||
4824
+ (before.inComposer && e.composerVisible && !e.inComposer);
4825
+ const outcome = (e: ReturnType<typeof inspectSubmission>, current: string[]) => {
4826
+ const queued =
4827
+ e.submission === "queued" ||
4828
+ current.some((line) => /^\s*(?:[❯›]\s*)?Press up to edit queued messages\s*$/iu.test(line));
4829
+ return {
4830
+ confirmed: !queued,
4831
+ screen: current,
4832
+ submission: (queued ? "queued" : "submitted") as SubmissionState,
4833
+ };
4834
+ };
4835
+ const ownPaste = ownedCollapsedPaste(record.cli, beforePaste, screen);
4836
+ const canRetry = (evidence: ReturnType<typeof inspectSubmission>, current: string[]) =>
4837
+ evidence.retry || (ownPaste !== null && collapsedPasteToken(current) === ownPaste);
4623
4838
  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
- );
4839
+ if (attempt) {
4840
+ await new Promise((r) => setTimeout(r, Math.min(400, 150 * 1.618 ** (attempt - 1))));
4841
+ // Recheck after the delay: the target could have accepted the earlier Enter.
4842
+ screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
4843
+ const settled = inspectSubmission(screen, identity);
4844
+ if (delivered(settled)) return outcome(settled, screen);
4845
+ if (
4846
+ !canRetry(settled, screen) ||
4847
+ (cfg?.needsInput?.length &&
4848
+ parseMenu(screen, { needsInput: cfg.needsInput, working: cfg.working }))
4849
+ )
4850
+ break;
4851
+ }
4636
4852
  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 };
4853
+ await waitForLogQuiet(logFile, SEND_CONFIRM_QUIET_MS, SEND_CONFIRM_MAX_MS);
4854
+ screen = (await renderLogTailLines(logFile, 40, geometry)) ?? [];
4855
+ const evidence = inspectSubmission(screen, identity);
4856
+ if (delivered(evidence)) return outcome(evidence, screen);
4857
+ if (!canRetry(evidence, screen)) break;
4642
4858
  }
4643
- return { confirmed: false, screen };
4859
+ return { confirmed: false, screen, submission: "not-submitted" };
4644
4860
  }
4645
4861
 
4646
4862
  /** Poll until the agent is no longer parked on a menu (selection accepted → it
@@ -4658,6 +4874,236 @@ async function waitForNeedsInputClear(
4658
4874
  return false;
4659
4875
  }
4660
4876
 
4877
+ /**
4878
+ * Write one message and its trailing code to the target, then (when `canConfirm`)
4879
+ * confirm the submit. The caller holds the input lock. The body is written
4880
+ * exactly once; only Enter is ever retried (see submitAndConfirm).
4881
+ */
4882
+ async function deliverBody(
4883
+ record: GlobalPidRecord,
4884
+ fifoPath: string,
4885
+ fullBody: string,
4886
+ trailing: string,
4887
+ identity: string,
4888
+ canConfirm: boolean,
4889
+ ): Promise<{
4890
+ confirmed: boolean;
4891
+ screen: string[];
4892
+ submission: "submitted" | "queued" | "not-submitted" | "unchecked";
4893
+ }> {
4894
+ if (fullBody && trailing) {
4895
+ const beforePaste =
4896
+ canConfirm && record.log_file
4897
+ ? await renderLogTailLines(
4898
+ record.log_file,
4899
+ 40,
4900
+ (await readAgentPtysize(record)) ?? undefined,
4901
+ )
4902
+ : null;
4903
+ await writeToIpc(fifoPath, fullBody);
4904
+ if (canConfirm && record.log_file) {
4905
+ // Wait for the paste to actually finish rendering — a long/multi-line body
4906
+ // can take longer than any fixed guess, and sending Enter mid-paste gets
4907
+ // swallowed by the CLI's bracketed-paste handling instead of submitting.
4908
+ await waitForLogQuiet(record.log_file, SEND_SETTLE_QUIET_MS, SEND_SETTLE_MAX_MS);
4909
+ return submitAndConfirm(record, fifoPath, trailing, identity, beforePaste);
4910
+ }
4911
+ await new Promise((r) => setTimeout(r, 200));
4912
+ await writeToIpc(fifoPath, trailing);
4913
+ } else {
4914
+ await writeToIpc(fifoPath, fullBody + trailing);
4915
+ }
4916
+ return {
4917
+ confirmed: !canConfirm,
4918
+ screen: [],
4919
+ submission: canConfirm ? "not-submitted" : "unchecked",
4920
+ };
4921
+ }
4922
+
4923
+ // Drainer pacing: poll the parked target with a φ backoff from 500 ms up to 5 s,
4924
+ // reset after every delivery. Worst case a message waits PENDING_MAX_AGE_MS.
4925
+ const DRAIN_POLL_BASE_MS = 500;
4926
+ const DRAIN_POLL_CAP_MS = 5000;
4927
+
4928
+ function drainerLockPath(pid: number): string {
4929
+ return path.join(agentYesHome(), "pending", `${pid}.drainer`);
4930
+ }
4931
+
4932
+ /** The pid of a live drainer for `pid`'s queue, or null. */
4933
+ async function liveDrainer(pid: number): Promise<number | null> {
4934
+ const raw = await readFile(drainerLockPath(pid), "utf-8").catch(() => null);
4935
+ const owner = Number(raw?.trim());
4936
+ if (!Number.isInteger(owner) || owner <= 0) return null;
4937
+ try {
4938
+ process.kill(owner, 0);
4939
+ return owner;
4940
+ } catch {
4941
+ return null;
4942
+ }
4943
+ }
4944
+
4945
+ /**
4946
+ * The argv that re-launches THIS build as the drainer. The drainer must be the
4947
+ * same build that parked the message (an older `ay` on PATH has no
4948
+ * send-drain), so prefer the running script over PATH lookup. Under the bun
4949
+ * runtime that is `bun <script>` on every platform: argv[1] is a .js/.ts file,
4950
+ * never an executable, so spawning it bare (as the first cut did on win32)
4951
+ * ENOENTs and the parked message waits for a manual `ay send-drain`. A
4952
+ * compiled single-file binary has no script to hand over: re-run the binary.
4953
+ */
4954
+ export function drainerLauncher(
4955
+ execPath: string,
4956
+ script: string | undefined,
4957
+ onPath: string | null | undefined,
4958
+ ): string[] | null {
4959
+ const bunRuntime = /(^|[\\/])bun(\.exe)?$/i.test(execPath);
4960
+ if (!bunRuntime) return [execPath];
4961
+ if (script) return [execPath, script];
4962
+ return onPath ? [execPath, onPath] : null;
4963
+ }
4964
+
4965
+ /** Start the per-target drainer unless one is already running. */
4966
+ async function ensureSendDrainer(pid: number): Promise<number | null> {
4967
+ const existing = await liveDrainer(pid);
4968
+ if (existing) return existing;
4969
+ const { spawn } = await import("node:child_process");
4970
+ const launcher = drainerLauncher(process.execPath, process.argv[1], Bun.which("ay"));
4971
+ if (!launcher) return null;
4972
+ const [cmd, ...pre] = launcher;
4973
+ const child = spawn(cmd!, [...pre, "send-drain", String(pid)], {
4974
+ detached: true,
4975
+ stdio: "ignore",
4976
+ });
4977
+ child.on("error", () => {});
4978
+ child.unref();
4979
+ return child.pid ?? null;
4980
+ }
4981
+
4982
+ function pidAlive(pid: number): boolean {
4983
+ try {
4984
+ process.kill(pid, 0);
4985
+ return true;
4986
+ } catch (e) {
4987
+ return (e as NodeJS.ErrnoException)?.code === "EPERM";
4988
+ }
4989
+ }
4990
+
4991
+ /**
4992
+ * `ay send-drain <pid>` — deliver the messages `ay send` parked for <pid>
4993
+ * because its composer held a draft. Runs until the queue is empty, the target
4994
+ * exits, or every message expired. One drainer per target (a pid file under
4995
+ * pending/); a second one exits at once. Normally started by `ay send` itself.
4996
+ */
4997
+ async function cmdSendDrain(rest: string[]): Promise<number> {
4998
+ const pid = Number(rest[0]);
4999
+ if (!Number.isInteger(pid) || pid <= 0) throw new Error("usage: ay send-drain <pid>");
5000
+ const lockFile = drainerLockPath(pid);
5001
+ await mkdir(path.dirname(lockFile), { recursive: true });
5002
+ const other = await liveDrainer(pid);
5003
+ if (other && other !== process.pid) return 0;
5004
+ await writeFile(lockFile, `${process.pid}\n`);
5005
+ // Two drainers can both pass the check above; the last writer owns the queue
5006
+ // and the other one leaves. claimPending keeps a message from going out twice
5007
+ // even inside that window.
5008
+ await new Promise((r) => setTimeout(r, 50));
5009
+ if ((await liveDrainer(pid)) !== process.pid) return 0;
5010
+ try {
5011
+ let attempt = 0;
5012
+ // sender + body hash → when this drainer delivered it: a second parked copy
5013
+ // of the same message from the same agent within the window is dropped.
5014
+ const delivered = new Map<string, number>();
5015
+ for (;;) {
5016
+ const names = await listPending(pid);
5017
+ if (!names.length) {
5018
+ // Give up ownership only under the input lock, which every enqueue also
5019
+ // holds: a sender that parks a message after this re-check finds no
5020
+ // drainer pid file and starts a new drainer; one that parked before it
5021
+ // is seen here and keeps this drainer running.
5022
+ const done = await withIpcLock(pid, async () => {
5023
+ if ((await listPending(pid)).length) return false;
5024
+ await rm(lockFile, { force: true });
5025
+ return true;
5026
+ });
5027
+ if (done) return 0;
5028
+ continue;
5029
+ }
5030
+ const name = names[0]!;
5031
+ const msg = await readPending(pid, name);
5032
+ if (!msg) {
5033
+ await retirePending(pid, name, "unparseable pending file");
5034
+ continue;
5035
+ }
5036
+ const gone = !pidAlive(pid);
5037
+ const expired = Date.now() - msg.queuedAt > PENDING_MAX_AGE_MS;
5038
+ if (gone || expired) {
5039
+ const why = gone ? "target exited before its input box was free" : "expired after 24h";
5040
+ for (const n of gone ? names : [name]) await retirePending(pid, n, why);
5041
+ await recordMessage({
5042
+ at: Date.now(),
5043
+ ...(msg.record as Omit<MessageRecord, "at">),
5044
+ confirmed: false,
5045
+ submission: "not-submitted",
5046
+ } as MessageRecord);
5047
+ if (gone) return 1;
5048
+ continue;
5049
+ }
5050
+ const from = senderKey(
5051
+ (msg.record as { from?: { agent_id?: string; pid?: number } | null }).from,
5052
+ );
5053
+ const msgBody = (msg.record as { body?: string }).body ?? "";
5054
+ const dupKey = from && msgBody ? `${from}|${bodyHash(msgBody)}` : null;
5055
+ const prev = dupKey ? delivered.get(dupKey) : undefined;
5056
+ if (prev !== undefined && msg.queuedAt - prev <= DUPLICATE_WINDOW_MS) {
5057
+ await retirePending(
5058
+ pid,
5059
+ name,
5060
+ `duplicate of the same sender's identical message delivered ${Math.round((Date.now() - prev) / 1000)}s ago`,
5061
+ );
5062
+ continue;
5063
+ }
5064
+ const record = (await readGlobalPids()).find((r) => r.pid === pid);
5065
+ let result: Awaited<ReturnType<typeof deliverBody>> | null = null;
5066
+ if (record && !(await isUserTyping(pid))) {
5067
+ await withIpcLock(pid, async () => {
5068
+ // Re-check under the lock, right before the write.
5069
+ if (await isUserTyping(pid)) return;
5070
+ // Only a positive reading releases a parked message: an unreadable
5071
+ // screen or one without a composer (a menu) waits for the next poll.
5072
+ const composer = await readComposerState(record);
5073
+ if (composer.kind !== "empty") return;
5074
+ if (!(await claimPending(pid, name))) return;
5075
+ result = await deliverBody(
5076
+ record,
5077
+ msg.fifoPath,
5078
+ msg.fullBody,
5079
+ msg.trailing,
5080
+ msg.identity,
5081
+ msg.trailing === "\r" && Boolean(record.log_file),
5082
+ );
5083
+ });
5084
+ }
5085
+ if (result) {
5086
+ const d = result as Awaited<ReturnType<typeof deliverBody>>;
5087
+ if (dupKey) delivered.set(dupKey, Date.now());
5088
+ await recordMessage({
5089
+ at: Date.now(),
5090
+ ...(msg.record as Omit<MessageRecord, "at">),
5091
+ confirmed: d.confirmed,
5092
+ submission: d.submission,
5093
+ } as MessageRecord);
5094
+ attempt = 0;
5095
+ continue;
5096
+ }
5097
+ attempt++;
5098
+ await new Promise((r) =>
5099
+ setTimeout(r, Math.min(DRAIN_POLL_CAP_MS, DRAIN_POLL_BASE_MS * 1.618 ** (attempt - 1))),
5100
+ );
5101
+ }
5102
+ } finally {
5103
+ if ((await liveDrainer(pid)) === process.pid) await rm(lockFile, { force: true });
5104
+ }
5105
+ }
5106
+
4661
5107
  async function cmdSend(rest: string[]): Promise<number> {
4662
5108
  const y = yargs(rest)
4663
5109
  // Disable yargs' `--no-<flag>` negation: without this, `--no-wait` is parsed
@@ -4669,7 +5115,11 @@ async function cmdSend(rest: string[]): Promise<number> {
4669
5115
  .usage(
4670
5116
  "Usage: ay send <keyword> <msg|-> [options]\n\n" +
4671
5117
  "Exit: 0 sent, 3 target unreachable (nothing sent; ay ls shows it as\n" +
4672
- "'unreachable' — ay restart <pid> revives it), 1 everything else.",
5118
+ "'unreachable' — ay restart <pid> revives it), 4 QUEUED (accepted, not yet\n" +
5119
+ "submitted: either the CLI queued it, or its input box held someone's draft and\n" +
5120
+ "the message was parked for delivery once the box is empty — do not resend;\n" +
5121
+ "an identical resend from the same agent within 60s is dropped as a DUPLICATE),\n" +
5122
+ "1 everything else.",
4673
5123
  )
4674
5124
  .option("code", {
4675
5125
  type: "string",
@@ -4940,15 +5390,13 @@ async function cmdSend(rest: string[]): Promise<number> {
4940
5390
  // body mid-line fuses into their text and submits a mangled line. Only for a
4941
5391
  // real text body; skipped for --force (caller means it), --no-wait
4942
5392
  // (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.
5393
+ // intentional and time-sensitive). If they are still typing at the deadline
5394
+ // the message is parked (see the composer guard below) instead of interleaved.
5395
+ let parkReason: string | null = null;
4945
5396
  if (fullBody && !noWait && !force) {
4946
5397
  const { clear, waitedMs } = await backoffWhileTyping(record.pid, SEND_TYPING_MAX_WAIT_MS);
4947
5398
  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
- );
5399
+ parkReason = `user still typing after ${Math.round(waitedMs / 1000)}s`;
4952
5400
  } else if (waitedMs > 0) {
4953
5401
  process.stderr.write(
4954
5402
  `waited ${Math.round(waitedMs / 1000)}s for the user to pause typing before sending.\n`,
@@ -4961,8 +5409,34 @@ async function cmdSend(rest: string[]): Promise<number> {
4961
5409
  // double-interrupt. Checked against the resolved byte, not the code NAME, so
4962
5410
  // every alias that resolves to Enter (--code=enter or --code=cr) is covered.
4963
5411
  const canConfirm = trailing === "\r" && Boolean(fullBody) && !noWait;
4964
- let confirmed = true;
5412
+ const identity = nonce ? `<ay-msg ${nonce}` : body;
5413
+ let confirmed = !canConfirm;
5414
+ const receipt: { submission: "submitted" | "queued" | "not-submitted" | "unchecked" } = {
5415
+ submission: canConfirm ? "not-submitted" : "unchecked",
5416
+ };
4965
5417
  let lastScreen: string[] = [];
5418
+ let parked = false;
5419
+ let duplicateOf: RecentSend | null = null;
5420
+ // The mailbox fields known before delivery; a parked message carries them to
5421
+ // the drainer so its eventual record names the real sender, not the drainer.
5422
+ const mailBase = {
5423
+ nonce,
5424
+ origin: sender.agent ? undefined : ("shell" as const),
5425
+ from_via: sender.via,
5426
+ sender_observed: observedSender(),
5427
+ from: sender.agent
5428
+ ? {
5429
+ pid: sender.agent.pid,
5430
+ cli: sender.agent.cli,
5431
+ cwd: sender.agent.cwd,
5432
+ agent_id: sender.agent.agent_id,
5433
+ }
5434
+ : null,
5435
+ to: { pid: record.pid, cli: record.cli, cwd: record.cwd, agent_id: record.agent_id },
5436
+ body,
5437
+ code: trailing === "\r" ? undefined : codeName,
5438
+ wrapped: Boolean(nonce),
5439
+ };
4966
5440
  // The body and its Enter are ONE transaction: every gap between them (the
4967
5441
  // paste-settle wait, the submit-confirm retries) is a window where another
4968
5442
  // writer's bytes would land mid-message. See ts/ipcLock.ts.
@@ -4970,25 +5444,52 @@ async function cmdSend(rest: string[]): Promise<number> {
4970
5444
  await withIpcLock(
4971
5445
  record.pid,
4972
5446
  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,
5447
+ // Composer guard (ts/composerGuard.ts): never type into someone else's
5448
+ // draft. Checked under the input lock, right before the write, so no
5449
+ // other `ay send` can change the composer between the check and the
5450
+ // paste. A message already parked for this pid also parks this one, so
5451
+ // delivery keeps send order.
5452
+ // Dedupe at the sink: the same agent re-sending the same body within a
5453
+ // minute (it read rc=4 QUEUED as a failure) is dropped, not typed or
5454
+ // parked twice. --force and human (shell) senders are exempt.
5455
+ const dedupeKey = force || !body ? null : senderKey(mailBase.from);
5456
+ if (dedupeKey) {
5457
+ duplicateOf = await findRecentDuplicate(record.pid, dedupeKey, body);
5458
+ if (duplicateOf) return;
5459
+ }
5460
+ if (fullBody) {
5461
+ if (!parkReason && (await listPending(record.pid)).length)
5462
+ parkReason = "earlier messages to this agent are still queued";
5463
+ if (!parkReason) {
5464
+ const composer = await readComposerState(record);
5465
+ if (composer.kind === "draft")
5466
+ parkReason = `its input box holds a draft (${composer.chars} chars)`;
5467
+ else if (composer.kind === "unknown")
5468
+ process.stderr.write(
5469
+ `warning: ay send could not see pid ${record.pid}'s input box (${composer.reason}) — sending without the draft check.\n`,
5470
+ );
5471
+ }
5472
+ if (dedupeKey)
5473
+ await noteRecentSend(record.pid, dedupeKey, body, parkReason ? "queued" : "sent");
5474
+ if (parkReason) {
5475
+ await enqueuePending({
5476
+ queuedAt: Date.now(),
5477
+ pid: record.pid,
4982
5478
  fifoPath,
5479
+ fullBody,
4983
5480
  trailing,
4984
- ));
4985
- } else {
4986
- await new Promise((r) => setTimeout(r, 200));
4987
- await writeToIpc(fifoPath, trailing);
5481
+ identity,
5482
+ record: mailBase,
5483
+ });
5484
+ parked = true;
5485
+ return;
4988
5486
  }
4989
- } else {
4990
- await writeToIpc(fifoPath, fullBody + trailing);
4991
5487
  }
5488
+ ({
5489
+ confirmed,
5490
+ screen: lastScreen,
5491
+ submission: receipt.submission,
5492
+ } = await deliverBody(record, fifoPath, fullBody, trailing, identity, canConfirm));
4992
5493
  },
4993
5494
  (why) =>
4994
5495
  process.stderr.write(
@@ -5010,11 +5511,53 @@ async function cmdSend(rest: string[]): Promise<number> {
5010
5511
  );
5011
5512
  return SEND_EXIT_UNREACHABLE;
5012
5513
  }
5514
+ if (duplicateOf) {
5515
+ const dup = duplicateOf as RecentSend;
5516
+ const ago = Math.max(0, Math.round((Date.now() - dup.at) / 1000));
5517
+ process.stdout.write(
5518
+ `DUPLICATE (not resent) to pid ${record.pid} (${record.cli}): ${truncate(body + trailing, 80)}\n`,
5519
+ );
5520
+ process.stderr.write(
5521
+ queuedReceipt(
5522
+ "duplicate",
5523
+ `you sent this exact message to pid ${record.pid} ${ago}s ago and it was ${dup.outcome}`,
5524
+ ) + "\n",
5525
+ );
5526
+ return dup.outcome === "queued" ? SEND_EXIT_QUEUED : 0;
5527
+ }
5528
+ if (parked) {
5529
+ const drainer = await ensureSendDrainer(record.pid);
5530
+ process.stdout.write(
5531
+ `QUEUED to pid ${record.pid} (${record.cli}): ${truncate(body + trailing, 80)}\n`,
5532
+ );
5533
+ process.stderr.write(
5534
+ queuedReceipt("parked", parkReason!) +
5535
+ (drainer
5536
+ ? ` (drainer pid ${drainer})\n`
5537
+ : `\nay send: the drainer did not start; run: ay send-drain ${record.pid}\n`),
5538
+ );
5539
+ if (body)
5540
+ await recordMessage({
5541
+ at: Date.now(),
5542
+ ...mailBase,
5543
+ confirmed: false,
5544
+ submission: "queued",
5545
+ } as MessageRecord);
5546
+ return SEND_EXIT_QUEUED;
5547
+ }
5548
+ const { submission } = receipt;
5013
5549
  const payload = body + trailing;
5014
- const status = confirmed ? "sent" : "sent but NOT confirmed submitted";
5550
+ const status =
5551
+ submission === "queued"
5552
+ ? "QUEUED"
5553
+ : confirmed
5554
+ ? "sent"
5555
+ : "NOT SUBMITTED (NOT confirmed: our message remains in input or destination evidence is unavailable)";
5015
5556
  process.stdout.write(
5016
5557
  `${status} to pid ${record.pid} (${record.cli}): ${truncate(payload, 80)}\n`,
5017
5558
  );
5559
+ if (submission === "queued")
5560
+ process.stderr.write(queuedReceipt("cli-queued", `${record.cli} is busy`) + "\n");
5018
5561
 
5019
5562
  // Persist a durable record of the exchange from both ends' point of view (the
5020
5563
  // sender's outbox + the recipient's inbox). Only real message bodies are
@@ -5049,12 +5592,13 @@ async function cmdSend(rest: string[]): Promise<number> {
5049
5592
  body,
5050
5593
  code: trailing === "\r" ? undefined : codeName,
5051
5594
  confirmed,
5595
+ submission,
5052
5596
  wrapped: Boolean(nonce),
5053
5597
  });
5054
5598
  }
5055
- if (!confirmed) {
5599
+ if (!confirmed && submission !== "queued") {
5056
5600
  process.stderr.write(
5057
- `\nwarning: couldn't confirm the CLI acted on it after ${SEND_SUBMIT_MAX_RETRIES + 1} attempt(s) — ` +
5601
+ `\nwarning: couldn't confirm the CLI acted on this message — ` +
5058
5602
  `it may still be sitting unsubmitted in the prompt. Last screen:\n` +
5059
5603
  lastScreen
5060
5604
  .slice(-8)
@@ -5096,7 +5640,7 @@ async function cmdSend(rest: string[]): Promise<number> {
5096
5640
  const tip = stopTipForCli(record.cli, record.pid);
5097
5641
  if (tip) process.stderr.write(tip);
5098
5642
  }
5099
- return confirmed ? 0 : 1;
5643
+ return submission === "queued" ? SEND_EXIT_QUEUED : confirmed ? 0 : 1;
5100
5644
  }
5101
5645
 
5102
5646
  // ---------------------------------------------------------------------------
@@ -5205,7 +5749,8 @@ async function cmdMsgs(rest: string[]): Promise<number> {
5205
5749
  const fromLabel = senderLabel(rec);
5206
5750
  const peer = dir === "out" ? `→ ${rec.to.cli} #${rec.to.pid}` : `← ${fromLabel}`;
5207
5751
  const via = rec.remote ? ` (via ${rec.remote})` : "";
5208
- const flag = rec.confirmed === false ? " (unconfirmed)" : "";
5752
+ const flag =
5753
+ rec.submission === "queued" ? " (QUEUED)" : rec.confirmed === false ? " (unconfirmed)" : "";
5209
5754
  const tag = rec.kind ? `[${rec.kind}] ` : "";
5210
5755
  const line = tag + truncate(rec.body.replace(/\s+/g, " "), 100);
5211
5756
  process.stdout.write(`${when} ${peer.padEnd(20)}${via}${flag} ${line}\n`);
@@ -6401,6 +6946,9 @@ export interface StatusSnapshot {
6401
6946
  pid: number;
6402
6947
  cli: string;
6403
6948
  cwd: string;
6949
+ /** Effective work dir (see ts/workDir.ts); equals `cwd` when source is spawn. */
6950
+ workdir: string;
6951
+ workdir_source: "observed" | "spawn";
6404
6952
  // needs_input: alive but blocked on an interactive menu (distinct from idle =
6405
6953
  // alive+quiet/done, and stopped = exited). stuck: alive + busy marker on screen
6406
6954
  // but long-silent (wedged mid-stream). unreachable: alive but its stdin FIFO
@@ -6476,6 +7024,8 @@ export async function snapshotStatus(record: GlobalPidRecord): Promise<StatusSna
6476
7024
  pid: record.pid,
6477
7025
  cli: record.cli,
6478
7026
  cwd: record.cwd,
7027
+ workdir: record.workdir ?? record.cwd,
7028
+ workdir_source: record.workdir_source ?? "spawn",
6479
7029
  state,
6480
7030
  activity,
6481
7031
  question,