agent-yes 1.299.0 → 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.
- package/README.md +13 -2
- package/default.config.yaml +12 -0
- package/dist/{SUPPORTED_CLIS-BIlQQJa6.js → SUPPORTED_CLIS-BUn4zN_B.js} +3 -3
- package/dist/{SUPPORTED_CLIS-Ct9reIJH.js → SUPPORTED_CLIS-DWZDaH9f.js} +2 -2
- package/dist/{agentShare-uzFuaLUH.js → agentShare-DpJmCvJ2.js} +3 -3
- package/dist/{callback-DRrURxmb.js → callback-BW73zdcS.js} +3 -3
- package/dist/{callback-BxTZx3xJ.js → callback-DQrYImyf.js} +3 -3
- package/dist/cli.js +5 -5
- package/dist/{cmdPs-BGIWbeBM.js → cmdPs-DBt-LD-H.js} +3 -3
- package/dist/index.js +2 -2
- package/dist/{notifyDaemon-EEbnpoYp.js → notifyDaemon-BkuOBb_g.js} +3 -3
- package/dist/{parentPingLoop-C1XXpKK7.js → parentPingLoop-d0GZjqY9.js} +2 -2
- package/dist/{remotes-DrYe_nfw.js → remotes-B4v0Nowo.js} +64 -7
- package/dist/remotes-DnMQWaqQ.js +5 -0
- package/dist/{rustBinary-B7rq3nuz.js → rustBinary-CVjRaDmT.js} +2 -2
- package/dist/{rustBinary--pof-MTj.js → rustBinary-DdWIf051.js} +2 -2
- package/dist/{schedule-BFUe9-Mf.js → schedule-C0HWIN7Z.js} +4 -4
- package/dist/{serve-Q4dnZc5l.js → serve-DTQomE4j.js} +42 -28
- package/dist/{setup-aEuGSFjB.js → setup-BwZ3UlCM.js} +2 -2
- package/dist/{shareCmd-DkITELaM.js → shareCmd-Cx2kxthJ.js} +3 -3
- package/dist/subcommands-R1eJF51D.js +13 -0
- package/dist/{subcommands-CUWPMI_r.js → subcommands-sr1CIEeP.js} +766 -81
- package/dist/{terminal-CUn1_oPd.js → terminal-CHPcyJuv.js} +2 -2
- package/dist/{trayApp-BHwAJFzl.js → trayApp-CjUWDytD.js} +2 -2
- package/dist/trayApp-K6-U3syh.js +5 -0
- package/dist/{ts-oIxnyQbE.js → ts-tta7Z887.js} +3 -3
- package/dist/{versionChecker-DOgDaagD.js → versionChecker-qFzGUoUo.js} +2 -2
- package/dist/{widget-CuagzQwz.js → widget-BOUSiXVj.js} +3 -3
- package/dist/{ws-DcJBGzQP.js → ws-BV2o8Zce.js} +2 -2
- package/dist/{ws-ID7-zDiJ.js → ws-xxrH3pXD.js} +3 -3
- package/package.json +1 -1
- package/ts/composerGuard.spec.ts +279 -0
- package/ts/composerGuard.ts +366 -0
- package/ts/globalPidIndex.ts +7 -0
- package/ts/messageLog.ts +2 -0
- package/ts/needsInput.bun.spec.ts +36 -0
- package/ts/needsInput.spec.ts +36 -0
- package/ts/remotes.bun.spec.ts +125 -0
- package/ts/remotes.spec.ts +125 -0
- package/ts/remotes.ts +95 -5
- package/ts/serve.bun.spec.ts +50 -0
- package/ts/serve.spec.ts +57 -1
- package/ts/serve.ts +50 -9
- package/ts/subcommands.spec.ts +530 -50
- package/ts/subcommands.ts +657 -94
- package/ts/workDir.bun.spec.ts +90 -0
- package/ts/workDir.spec.ts +90 -0
- package/ts/workDir.ts +75 -0
- package/dist/remotes-BDMnvGI6.js +0 -5
- package/dist/subcommands-CuRZt3X6.js +0 -13
- package/dist/trayApp-ucuB_j5l.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)
|
|
@@ -627,13 +648,13 @@ const SUBCOMMANDS = new Set([
|
|
|
627
648
|
"result",
|
|
628
649
|
"notify",
|
|
629
650
|
"notifyd",
|
|
630
|
-
"read",
|
|
631
651
|
"cat",
|
|
632
652
|
"tail",
|
|
633
653
|
"head",
|
|
634
654
|
"hist",
|
|
635
655
|
"history",
|
|
636
656
|
"send",
|
|
657
|
+
"send-drain",
|
|
637
658
|
"msgs",
|
|
638
659
|
"key",
|
|
639
660
|
"select",
|
|
@@ -666,15 +687,21 @@ const SUBCOMMANDS = new Set([
|
|
|
666
687
|
// Subcommands recognised ONLY on the GENERIC manager entry (`ay` / `agent-yes`).
|
|
667
688
|
// A cli-bound alias like `cy` (= claude-yes = "agent-yes claude") must NOT treat
|
|
668
689
|
// these as subcommands — it falls straight through to running the agent with that
|
|
669
|
-
// text. Two reasons a name lands here:
|
|
670
|
-
//
|
|
671
|
-
//
|
|
672
|
-
//
|
|
690
|
+
// text. Two reasons a name lands here:
|
|
691
|
+
// - host management: `cy setup …` / `cy ws …` should prompt claude, not share
|
|
692
|
+
// the machine over WebRTC (#67).
|
|
693
|
+
// - it is an ordinary English verb people start prompts with: `cy read ts/cli.ts
|
|
694
|
+
// and explain it` / `cy connect the frontend to the API` must reach claude.
|
|
695
|
+
// The commands stay reachable on the manager entry (`ay read`, `ay share`,
|
|
696
|
+
// `ay connect`); `cy cat` / `cy tail` / `cy head` / `cy ls` are unchanged —
|
|
697
|
+
// nobody opens a prompt with those.
|
|
698
|
+
// Kept one name per line so both runtimes' copies stay easy to keep in sync.
|
|
673
699
|
const MANAGER_SUBCOMMANDS = new Set([
|
|
674
700
|
// manage this host
|
|
675
701
|
"setup",
|
|
676
702
|
"ws",
|
|
677
|
-
// prompt-word verbs
|
|
703
|
+
// prompt-word verbs
|
|
704
|
+
"read",
|
|
678
705
|
"share",
|
|
679
706
|
"connect",
|
|
680
707
|
]);
|
|
@@ -696,12 +723,11 @@ const STUCK_THRESHOLD_MS = (() => {
|
|
|
696
723
|
// trailing Enter before that settles gets swallowed by the CLI's paste handling
|
|
697
724
|
// (it lands mid-paste instead of submitting). So instead of a blind fixed sleep,
|
|
698
725
|
// we poll the log for actual quiet, then confirm the Enter landed by watching for
|
|
699
|
-
//
|
|
726
|
+
// our message identity in the transcript; retry only while it remains in input.
|
|
700
727
|
const SEND_SETTLE_QUIET_MS = 150; // no log growth for this long → paste finished rendering
|
|
701
728
|
const SEND_SETTLE_MAX_MS = 1500; // cap: don't wait forever on a screen that's busy for other reasons
|
|
702
729
|
const SEND_CONFIRM_QUIET_MS = 400; // after Enter, no growth for this long → response has settled
|
|
703
730
|
const SEND_CONFIRM_MAX_MS = 1200; // cap per confirm attempt
|
|
704
|
-
const SEND_CONFIRM_MIN_GROWTH_BYTES = 8; // filters out pure cursor-blink/frame noise
|
|
705
731
|
const SEND_SUBMIT_MAX_RETRIES = 2; // total attempts = 1 + this
|
|
706
732
|
// `ay send` typing-backoff: if the user is actively typing at the target's
|
|
707
733
|
// terminal, injecting our body mid-line would fuse into their text and submit a
|
|
@@ -906,8 +932,9 @@ export function isUnreachableWriteErrno(code: string | undefined): boolean {
|
|
|
906
932
|
/**
|
|
907
933
|
* Whether `name` is a subcommand. `managerCommands` (default true, for the
|
|
908
934
|
* generic `ay`/`agent-yes` entry) additionally admits manager-only commands
|
|
909
|
-
*
|
|
910
|
-
* names fall through to running the agent instead
|
|
935
|
+
* (`setup`, `ws`, `read`); pass false for a cli-bound alias (cy/claude-yes/…) so
|
|
936
|
+
* those names fall through to running the agent instead — `cy read <file>` is a
|
|
937
|
+
* prompt, `ay read <keyword>` is the log pager.
|
|
911
938
|
*/
|
|
912
939
|
export function isSubcommand(name: string | undefined, managerCommands = true): boolean {
|
|
913
940
|
if (!name) return false;
|
|
@@ -991,9 +1018,10 @@ async function writeStdoutFlushed(text: string): Promise<void> {
|
|
|
991
1018
|
*/
|
|
992
1019
|
export async function runSubcommand(argv: string[]): Promise<number | null> {
|
|
993
1020
|
const sub = argv[2];
|
|
994
|
-
// Manager-only subcommands (setup) aren't subcommands for a
|
|
995
|
-
// like `cy` — they fall through to running the agent
|
|
996
|
-
//
|
|
1021
|
+
// Manager-only subcommands (setup / ws / read) aren't subcommands for a
|
|
1022
|
+
// cli-bound alias like `cy` — they fall through to running the agent with that
|
|
1023
|
+
// word as prompt text. Computed once from argv so it holds regardless of
|
|
1024
|
+
// caller, and reused to hide manager-only help.
|
|
997
1025
|
const managerCommands = !invokedCliName(argv);
|
|
998
1026
|
if (!isSubcommand(sub, managerCommands)) return null;
|
|
999
1027
|
|
|
@@ -1030,6 +1058,8 @@ export async function runSubcommand(argv: string[]): Promise<number | null> {
|
|
|
1030
1058
|
return await (await import("./hist.ts")).cmdHist(rest);
|
|
1031
1059
|
case "send":
|
|
1032
1060
|
return await cmdSend(rest);
|
|
1061
|
+
case "send-drain":
|
|
1062
|
+
return await cmdSendDrain(rest);
|
|
1033
1063
|
case "msgs":
|
|
1034
1064
|
return await cmdMsgs(rest);
|
|
1035
1065
|
case "key":
|
|
@@ -1270,10 +1300,15 @@ export async function cmdHelp(managerCommands = true): Promise<number> {
|
|
|
1270
1300
|
? ` ay ws ls [--status] list <owner>/<repo>/tree/<branch> workspaces\n` +
|
|
1271
1301
|
` ay ws new <owner>/<repo>[@branch] clone/refresh a workspace (ay ws help for more)\n`
|
|
1272
1302
|
: ``;
|
|
1273
|
-
// `
|
|
1274
|
-
//
|
|
1275
|
-
//
|
|
1276
|
-
//
|
|
1303
|
+
// `read` is manager-entry-only too, but for the opposite reason: it's a word
|
|
1304
|
+
// people open prompts with, so `cy read …` runs the agent. Unlike setup/ws the
|
|
1305
|
+
// line stays visible (pagination is worth knowing about) — just labelled, so
|
|
1306
|
+
// nobody types `cy read <pid>` and gets a claude session instead of a log.
|
|
1307
|
+
const readAliasNote = managerCommands
|
|
1308
|
+
? ``
|
|
1309
|
+
: ` (\`ay read\` only — \`cy read …\` is a prompt)\n`;
|
|
1310
|
+
// Same for `share` / `connect`: prompt words, but `ay share` is how the web
|
|
1311
|
+
// console is reached at all, so label the lines rather than hide the feature.
|
|
1277
1312
|
const shareAliasNote = managerCommands
|
|
1278
1313
|
? ``
|
|
1279
1314
|
: ` (\`ay\` only — \`cy share\`/\`cy connect\` are prompts)\n`;
|
|
@@ -1295,6 +1330,7 @@ export async function cmdHelp(managerCommands = true): Promise<number> {
|
|
|
1295
1330
|
` [--fail-on TEXT] [--count N] 3 = --fail-on hit first)\n` +
|
|
1296
1331
|
` ay read <keyword> [page opts] paginate: --last/--head N, --range A:B,\n` +
|
|
1297
1332
|
` --before-line L [--limit N]\n` +
|
|
1333
|
+
readAliasNote +
|
|
1298
1334
|
` ay cat <keyword> full log\n` +
|
|
1299
1335
|
` ay head <keyword> first N lines\n` +
|
|
1300
1336
|
` ay hist [-n 6] [--all] [--json] past agent conversations (claude/codex\n` +
|
|
@@ -1382,10 +1418,16 @@ export function matchKeyword(record: GlobalPidRecord, keyword: string): boolean
|
|
|
1382
1418
|
// fragment. Repurposed from the (near-useless) substring behavior — a lone `.`
|
|
1383
1419
|
// was in almost every path, so it never selected anything meaningful.
|
|
1384
1420
|
if (kw === "." || kw === "./") {
|
|
1385
|
-
|
|
1421
|
+
const here = path.resolve(process.cwd());
|
|
1422
|
+
return (
|
|
1423
|
+
path.resolve(record.cwd) === here ||
|
|
1424
|
+
(!!record.workdir && path.resolve(record.workdir) === here)
|
|
1425
|
+
);
|
|
1386
1426
|
}
|
|
1387
|
-
// 2. cwd contains keyword
|
|
1427
|
+
// 2. cwd (spawn dir or effective work dir) contains keyword
|
|
1388
1428
|
if (record.cwd.toLowerCase().includes(kw)) return true;
|
|
1429
|
+
if (record.workdir && record.workdir.toLowerCase().includes(kw)) return true;
|
|
1430
|
+
|
|
1389
1431
|
// 3. cli exact (lowercase)
|
|
1390
1432
|
if (record.cli.toLowerCase() === kw) return true;
|
|
1391
1433
|
// 4. prompt substring
|
|
@@ -1414,16 +1456,45 @@ export async function listRecords(
|
|
|
1414
1456
|
if (opts.active) {
|
|
1415
1457
|
records = records.filter((r) => isPidAlive(r.pid));
|
|
1416
1458
|
}
|
|
1459
|
+
records = await withWorkDirs(records);
|
|
1417
1460
|
if (opts.cwdScope) {
|
|
1418
1461
|
const scope = opts.cwdScope;
|
|
1419
|
-
records = records.filter(
|
|
1462
|
+
records = records.filter(
|
|
1463
|
+
(r) => isWithin(r.cwd, scope) || (!!r.workdir && isWithin(r.workdir, scope)),
|
|
1464
|
+
);
|
|
1420
1465
|
}
|
|
1466
|
+
|
|
1421
1467
|
if (keyword) records = records.filter((r) => matchKeyword(r, keyword));
|
|
1422
1468
|
// newest first
|
|
1423
1469
|
records.sort((a, b) => b.started_at - a.started_at);
|
|
1424
1470
|
return records;
|
|
1425
1471
|
}
|
|
1426
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
|
+
|
|
1427
1498
|
export function isPidAlive(pid: number): boolean {
|
|
1428
1499
|
try {
|
|
1429
1500
|
process.kill(pid, 0);
|
|
@@ -2203,7 +2274,7 @@ async function runAllRemotesLs(opts: {
|
|
|
2203
2274
|
? await Promise.all([
|
|
2204
2275
|
r.log_file ? extractTaskCounts(r.log_file) : Promise.resolve(null),
|
|
2205
2276
|
r.log_file ? extractBadges(r.log_file) : Promise.resolve([]),
|
|
2206
|
-
gitStatusOnce(r.cwd, gitRootCache, gitInfoCache),
|
|
2277
|
+
gitStatusOnce(r.workdir ?? r.cwd, gitRootCache, gitInfoCache),
|
|
2207
2278
|
isUserTyping(r.pid),
|
|
2208
2279
|
])
|
|
2209
2280
|
: [null, [], null, false];
|
|
@@ -2272,7 +2343,7 @@ async function runAllRemotesLs(opts: {
|
|
|
2272
2343
|
const cliW = Math.max(3, ...rows.map((r) => String(r.rec.cli).length));
|
|
2273
2344
|
const statusW = Math.max(6, ...rows.map((r) => String(r.rec.status).length));
|
|
2274
2345
|
const ageW = Math.max(3, ...rows.map((r) => ageOf(r.rec).length));
|
|
2275
|
-
const cwdW = Math.max(3, ...rows.map((r) =>
|
|
2346
|
+
const cwdW = Math.max(3, ...rows.map((r) => cwdLabel(r.rec).length));
|
|
2276
2347
|
const promptBudget = Math.max(
|
|
2277
2348
|
20,
|
|
2278
2349
|
termWidth - hostW - pidW - cliW - statusW - ageW - cwdW - 6 * 2 - 1,
|
|
@@ -2311,7 +2382,7 @@ async function runAllRemotesLs(opts: {
|
|
|
2311
2382
|
String(rec.cli).padEnd(cliW),
|
|
2312
2383
|
String(rec.status).padEnd(statusW),
|
|
2313
2384
|
ageOf(rec).padEnd(ageW),
|
|
2314
|
-
|
|
2385
|
+
cwdLabel(rec).padEnd(cwdW),
|
|
2315
2386
|
label,
|
|
2316
2387
|
].join(" ") + "\n",
|
|
2317
2388
|
);
|
|
@@ -2839,7 +2910,7 @@ async function cmdLs(rest: string[]): Promise<number> {
|
|
|
2839
2910
|
);
|
|
2840
2911
|
const ageOf = (r: GlobalPidRecord) => humanizeAge(now - (lastActive.get(r.pid) ?? r.started_at));
|
|
2841
2912
|
|
|
2842
|
-
const rawCwds = records.map((r) =>
|
|
2913
|
+
const rawCwds = records.map((r) => cwdLabel(r));
|
|
2843
2914
|
const widths = {
|
|
2844
2915
|
pid: Math.max(3, ...records.map((r) => String(r.pid).length)),
|
|
2845
2916
|
cli: Math.max(3, ...records.map((r) => r.cli.length)),
|
|
@@ -2875,7 +2946,7 @@ async function cmdLs(rest: string[]): Promise<number> {
|
|
|
2875
2946
|
? await Promise.all([
|
|
2876
2947
|
r.log_file ? extractTaskCounts(r.log_file) : Promise.resolve(null),
|
|
2877
2948
|
r.log_file ? extractBadges(r.log_file) : Promise.resolve([]),
|
|
2878
|
-
gitStatusOnce(r.cwd, gitRootCache, gitInfoCache),
|
|
2949
|
+
gitStatusOnce(r.workdir ?? r.cwd, gitRootCache, gitInfoCache),
|
|
2879
2950
|
isUserTyping(r.pid),
|
|
2880
2951
|
])
|
|
2881
2952
|
: [null, [], null, false];
|
|
@@ -2911,7 +2982,7 @@ async function cmdLs(rest: string[]): Promise<number> {
|
|
|
2911
2982
|
cli: r.cli,
|
|
2912
2983
|
status: displayStatus,
|
|
2913
2984
|
age: ageOf(r),
|
|
2914
|
-
cwd:
|
|
2985
|
+
cwd: cwdLabel(r),
|
|
2915
2986
|
label,
|
|
2916
2987
|
hasNote,
|
|
2917
2988
|
_alive: displayStatus !== "stopped",
|
|
@@ -4195,6 +4266,47 @@ export async function renderLogTailLines(
|
|
|
4195
4266
|
n = 40,
|
|
4196
4267
|
geom?: RenderGeom,
|
|
4197
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> {
|
|
4198
4310
|
const TAIL_BYTES = 32 * 1024;
|
|
4199
4311
|
let buf: Uint8Array;
|
|
4200
4312
|
try {
|
|
@@ -4216,17 +4328,7 @@ export async function renderLogTailLines(
|
|
|
4216
4328
|
} catch {
|
|
4217
4329
|
return null;
|
|
4218
4330
|
}
|
|
4219
|
-
|
|
4220
|
-
// Render at the agent's REAL PTY geometry when provided — the raw log is full
|
|
4221
|
-
// of absolute cursor-positioning, so replaying at the wrong width reflows the
|
|
4222
|
-
// TUI into garbage (chars land in the wrong columns). Callers with a pid pass
|
|
4223
|
-
// readPtysize(pid); without it we fall back to the default width.
|
|
4224
|
-
return (await renderRawLog(buf, { mode: "tail", n, cols: geom?.cols, rows: geom?.rows })).split(
|
|
4225
|
-
"\n",
|
|
4226
|
-
);
|
|
4227
|
-
} catch {
|
|
4228
|
-
return null;
|
|
4229
|
-
}
|
|
4331
|
+
return buf;
|
|
4230
4332
|
}
|
|
4231
4333
|
|
|
4232
4334
|
export async function extractNeedsInput(logPath: string, cli: string): Promise<NeedsInput | null> {
|
|
@@ -4591,43 +4693,170 @@ export async function backoffWhileTyping(
|
|
|
4591
4693
|
return { clear: false, waitedMs: Date.now() - start };
|
|
4592
4694
|
}
|
|
4593
4695
|
|
|
4594
|
-
|
|
4595
|
-
|
|
4596
|
-
|
|
4597
|
-
|
|
4598
|
-
|
|
4599
|
-
|
|
4600
|
-
|
|
4601
|
-
|
|
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. */
|
|
4602
4805
|
export async function submitAndConfirm(
|
|
4603
4806
|
record: GlobalPidRecord,
|
|
4604
4807
|
fifoPath: string,
|
|
4605
4808
|
trailing: string,
|
|
4606
|
-
|
|
4809
|
+
identity: string,
|
|
4810
|
+
beforePaste?: string[] | null,
|
|
4811
|
+
): Promise<{ confirmed: boolean; screen: string[]; submission: SubmissionState }> {
|
|
4607
4812
|
const logFile = record.log_file!;
|
|
4813
|
+
const geometry = (await readAgentPtysize(record)) ?? undefined;
|
|
4608
4814
|
const cfg = (await cliDefaults())[record.cli];
|
|
4609
|
-
let screen
|
|
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);
|
|
4610
4838
|
for (let attempt = 0; attempt <= SEND_SUBMIT_MAX_RETRIES; attempt++) {
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
4614
|
-
|
|
4615
|
-
|
|
4616
|
-
|
|
4617
|
-
|
|
4618
|
-
|
|
4619
|
-
|
|
4620
|
-
|
|
4621
|
-
|
|
4622
|
-
|
|
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
|
+
}
|
|
4623
4852
|
await writeToIpc(fifoPath, trailing);
|
|
4624
|
-
|
|
4625
|
-
screen = (await renderLogTailLines(logFile, 40)) ?? [];
|
|
4626
|
-
const
|
|
4627
|
-
|
|
4628
|
-
if ((
|
|
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;
|
|
4629
4858
|
}
|
|
4630
|
-
return { confirmed: false, screen };
|
|
4859
|
+
return { confirmed: false, screen, submission: "not-submitted" };
|
|
4631
4860
|
}
|
|
4632
4861
|
|
|
4633
4862
|
/** Poll until the agent is no longer parked on a menu (selection accepted → it
|
|
@@ -4645,6 +4874,236 @@ async function waitForNeedsInputClear(
|
|
|
4645
4874
|
return false;
|
|
4646
4875
|
}
|
|
4647
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
|
+
|
|
4648
5107
|
async function cmdSend(rest: string[]): Promise<number> {
|
|
4649
5108
|
const y = yargs(rest)
|
|
4650
5109
|
// Disable yargs' `--no-<flag>` negation: without this, `--no-wait` is parsed
|
|
@@ -4656,7 +5115,11 @@ async function cmdSend(rest: string[]): Promise<number> {
|
|
|
4656
5115
|
.usage(
|
|
4657
5116
|
"Usage: ay send <keyword> <msg|-> [options]\n\n" +
|
|
4658
5117
|
"Exit: 0 sent, 3 target unreachable (nothing sent; ay ls shows it as\n" +
|
|
4659
|
-
"'unreachable' — ay restart <pid> revives it),
|
|
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.",
|
|
4660
5123
|
)
|
|
4661
5124
|
.option("code", {
|
|
4662
5125
|
type: "string",
|
|
@@ -4927,15 +5390,13 @@ async function cmdSend(rest: string[]): Promise<number> {
|
|
|
4927
5390
|
// body mid-line fuses into their text and submits a mangled line. Only for a
|
|
4928
5391
|
// real text body; skipped for --force (caller means it), --no-wait
|
|
4929
5392
|
// (fire-and-forget), and empty bodies (a bare esc/ctrl-c interrupt is usually
|
|
4930
|
-
// intentional and time-sensitive).
|
|
4931
|
-
// message is
|
|
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;
|
|
4932
5396
|
if (fullBody && !noWait && !force) {
|
|
4933
5397
|
const { clear, waitedMs } = await backoffWhileTyping(record.pid, SEND_TYPING_MAX_WAIT_MS);
|
|
4934
5398
|
if (!clear) {
|
|
4935
|
-
|
|
4936
|
-
`warning: user still typing at pid ${record.pid} after ${Math.round(waitedMs / 1000)}s — ` +
|
|
4937
|
-
`sending anyway (may interleave with their line). Use --force to skip this wait.\n`,
|
|
4938
|
-
);
|
|
5399
|
+
parkReason = `user still typing after ${Math.round(waitedMs / 1000)}s`;
|
|
4939
5400
|
} else if (waitedMs > 0) {
|
|
4940
5401
|
process.stderr.write(
|
|
4941
5402
|
`waited ${Math.round(waitedMs / 1000)}s for the user to pause typing before sending.\n`,
|
|
@@ -4948,8 +5409,34 @@ async function cmdSend(rest: string[]): Promise<number> {
|
|
|
4948
5409
|
// double-interrupt. Checked against the resolved byte, not the code NAME, so
|
|
4949
5410
|
// every alias that resolves to Enter (--code=enter or --code=cr) is covered.
|
|
4950
5411
|
const canConfirm = trailing === "\r" && Boolean(fullBody) && !noWait;
|
|
4951
|
-
|
|
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
|
+
};
|
|
4952
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
|
+
};
|
|
4953
5440
|
// The body and its Enter are ONE transaction: every gap between them (the
|
|
4954
5441
|
// paste-settle wait, the submit-confirm retries) is a window where another
|
|
4955
5442
|
// writer's bytes would land mid-message. See ts/ipcLock.ts.
|
|
@@ -4957,25 +5444,52 @@ async function cmdSend(rest: string[]): Promise<number> {
|
|
|
4957
5444
|
await withIpcLock(
|
|
4958
5445
|
record.pid,
|
|
4959
5446
|
async () => {
|
|
4960
|
-
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
|
|
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,
|
|
4969
5478
|
fifoPath,
|
|
5479
|
+
fullBody,
|
|
4970
5480
|
trailing,
|
|
4971
|
-
|
|
4972
|
-
|
|
4973
|
-
|
|
4974
|
-
|
|
5481
|
+
identity,
|
|
5482
|
+
record: mailBase,
|
|
5483
|
+
});
|
|
5484
|
+
parked = true;
|
|
5485
|
+
return;
|
|
4975
5486
|
}
|
|
4976
|
-
} else {
|
|
4977
|
-
await writeToIpc(fifoPath, fullBody + trailing);
|
|
4978
5487
|
}
|
|
5488
|
+
({
|
|
5489
|
+
confirmed,
|
|
5490
|
+
screen: lastScreen,
|
|
5491
|
+
submission: receipt.submission,
|
|
5492
|
+
} = await deliverBody(record, fifoPath, fullBody, trailing, identity, canConfirm));
|
|
4979
5493
|
},
|
|
4980
5494
|
(why) =>
|
|
4981
5495
|
process.stderr.write(
|
|
@@ -4997,11 +5511,53 @@ async function cmdSend(rest: string[]): Promise<number> {
|
|
|
4997
5511
|
);
|
|
4998
5512
|
return SEND_EXIT_UNREACHABLE;
|
|
4999
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;
|
|
5000
5549
|
const payload = body + trailing;
|
|
5001
|
-
const status =
|
|
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)";
|
|
5002
5556
|
process.stdout.write(
|
|
5003
5557
|
`${status} to pid ${record.pid} (${record.cli}): ${truncate(payload, 80)}\n`,
|
|
5004
5558
|
);
|
|
5559
|
+
if (submission === "queued")
|
|
5560
|
+
process.stderr.write(queuedReceipt("cli-queued", `${record.cli} is busy`) + "\n");
|
|
5005
5561
|
|
|
5006
5562
|
// Persist a durable record of the exchange from both ends' point of view (the
|
|
5007
5563
|
// sender's outbox + the recipient's inbox). Only real message bodies are
|
|
@@ -5036,12 +5592,13 @@ async function cmdSend(rest: string[]): Promise<number> {
|
|
|
5036
5592
|
body,
|
|
5037
5593
|
code: trailing === "\r" ? undefined : codeName,
|
|
5038
5594
|
confirmed,
|
|
5595
|
+
submission,
|
|
5039
5596
|
wrapped: Boolean(nonce),
|
|
5040
5597
|
});
|
|
5041
5598
|
}
|
|
5042
|
-
if (!confirmed) {
|
|
5599
|
+
if (!confirmed && submission !== "queued") {
|
|
5043
5600
|
process.stderr.write(
|
|
5044
|
-
`\nwarning: couldn't confirm the CLI acted on
|
|
5601
|
+
`\nwarning: couldn't confirm the CLI acted on this message — ` +
|
|
5045
5602
|
`it may still be sitting unsubmitted in the prompt. Last screen:\n` +
|
|
5046
5603
|
lastScreen
|
|
5047
5604
|
.slice(-8)
|
|
@@ -5083,7 +5640,7 @@ async function cmdSend(rest: string[]): Promise<number> {
|
|
|
5083
5640
|
const tip = stopTipForCli(record.cli, record.pid);
|
|
5084
5641
|
if (tip) process.stderr.write(tip);
|
|
5085
5642
|
}
|
|
5086
|
-
return confirmed ? 0 : 1;
|
|
5643
|
+
return submission === "queued" ? SEND_EXIT_QUEUED : confirmed ? 0 : 1;
|
|
5087
5644
|
}
|
|
5088
5645
|
|
|
5089
5646
|
// ---------------------------------------------------------------------------
|
|
@@ -5192,7 +5749,8 @@ async function cmdMsgs(rest: string[]): Promise<number> {
|
|
|
5192
5749
|
const fromLabel = senderLabel(rec);
|
|
5193
5750
|
const peer = dir === "out" ? `→ ${rec.to.cli} #${rec.to.pid}` : `← ${fromLabel}`;
|
|
5194
5751
|
const via = rec.remote ? ` (via ${rec.remote})` : "";
|
|
5195
|
-
const flag =
|
|
5752
|
+
const flag =
|
|
5753
|
+
rec.submission === "queued" ? " (QUEUED)" : rec.confirmed === false ? " (unconfirmed)" : "";
|
|
5196
5754
|
const tag = rec.kind ? `[${rec.kind}] ` : "";
|
|
5197
5755
|
const line = tag + truncate(rec.body.replace(/\s+/g, " "), 100);
|
|
5198
5756
|
process.stdout.write(`${when} ${peer.padEnd(20)}${via}${flag} ${line}\n`);
|
|
@@ -6388,6 +6946,9 @@ export interface StatusSnapshot {
|
|
|
6388
6946
|
pid: number;
|
|
6389
6947
|
cli: string;
|
|
6390
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";
|
|
6391
6952
|
// needs_input: alive but blocked on an interactive menu (distinct from idle =
|
|
6392
6953
|
// alive+quiet/done, and stopped = exited). stuck: alive + busy marker on screen
|
|
6393
6954
|
// but long-silent (wedged mid-stream). unreachable: alive but its stdin FIFO
|
|
@@ -6463,6 +7024,8 @@ export async function snapshotStatus(record: GlobalPidRecord): Promise<StatusSna
|
|
|
6463
7024
|
pid: record.pid,
|
|
6464
7025
|
cli: record.cli,
|
|
6465
7026
|
cwd: record.cwd,
|
|
7027
|
+
workdir: record.workdir ?? record.cwd,
|
|
7028
|
+
workdir_source: record.workdir_source ?? "spawn",
|
|
6466
7029
|
state,
|
|
6467
7030
|
activity,
|
|
6468
7031
|
question,
|