agent-yes 1.299.1 → 1.300.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +9 -0
  2. package/default.config.yaml +12 -0
  3. package/dist/{SUPPORTED_CLIS-MftynU62.js → SUPPORTED_CLIS-BAeTuI-p.js} +3 -3
  4. package/dist/{SUPPORTED_CLIS-YZvIGQvw.js → SUPPORTED_CLIS-BZlaxyEH.js} +2 -2
  5. package/dist/{agentShare-dKQQSOD7.js → agentShare-DGQM24wU.js} +3 -3
  6. package/dist/{callback-BEbbWLKe.js → callback-3RsdcuV0.js} +3 -3
  7. package/dist/{callback-DWxTSlly.js → callback-CQadU_zP.js} +3 -3
  8. package/dist/cli.js +5 -5
  9. package/dist/{cmdPs-D7HWttUU.js → cmdPs-CQxFAs9M.js} +3 -3
  10. package/dist/index.js +2 -2
  11. package/dist/{notifyDaemon-B0aU7koS.js → notifyDaemon-CxkiJvOo.js} +3 -3
  12. package/dist/{parentPingLoop-DSiOXQeU.js → parentPingLoop-vZ8I9k5K.js} +2 -2
  13. package/dist/{remotes-DrYe_nfw.js → remotes-B4v0Nowo.js} +64 -7
  14. package/dist/remotes-DnMQWaqQ.js +5 -0
  15. package/dist/{rustBinary-CKuufNRn.js → rustBinary-B1buVId2.js} +2 -2
  16. package/dist/{rustBinary-DgRg5H6V.js → rustBinary-etb0Jsga.js} +2 -2
  17. package/dist/{schedule-BStFx0_s.js → schedule-CMBHLSlz.js} +4 -4
  18. package/dist/{serve-Cis4oJM-.js → serve-D5ijYGTv.js} +42 -28
  19. package/dist/{setup-B0sg4AV1.js → setup-DMJYufvD.js} +2 -2
  20. package/dist/{shareCmd-DKIvwe0I.js → shareCmd-CNhCKuOK.js} +3 -3
  21. package/dist/{subcommands-CvL_1Nt9.js → subcommands-BncoxUN6.js} +775 -78
  22. package/dist/subcommands-ZEjbTV_7.js +13 -0
  23. package/dist/{terminal-DqsAuqhw.js → terminal-DzbPI4n0.js} +2 -2
  24. package/dist/{trayApp-Dayj9Frx.js → trayApp-BvtgbxMB.js} +2 -2
  25. package/dist/trayApp-CpPsP3_a.js +5 -0
  26. package/dist/{ts-C2osm4MO.js → ts-Gr1eJOUk.js} +3 -3
  27. package/dist/{versionChecker-BmXwOe40.js → versionChecker-BrjeGNf1.js} +2 -2
  28. package/dist/{widget-D5tsB-oi.js → widget-p4Db_OXd.js} +3 -3
  29. package/dist/{ws-B4jdOeB2.js → ws-D_QClddd.js} +3 -3
  30. package/dist/{ws-mz7VJJwO.js → ws-DnKPi3TS.js} +2 -2
  31. package/package.json +1 -1
  32. package/ts/composerGuard.spec.ts +279 -0
  33. package/ts/composerGuard.ts +366 -0
  34. package/ts/globalPidIndex.ts +7 -0
  35. package/ts/messageLog.ts +2 -0
  36. package/ts/needsInput.bun.spec.ts +36 -0
  37. package/ts/needsInput.spec.ts +36 -0
  38. package/ts/remotes.bun.spec.ts +125 -0
  39. package/ts/remotes.spec.ts +125 -0
  40. package/ts/remotes.ts +95 -5
  41. package/ts/serve.bun.spec.ts +50 -0
  42. package/ts/serve.spec.ts +57 -1
  43. package/ts/serve.ts +50 -9
  44. package/ts/subcommands.spec.ts +564 -42
  45. package/ts/subcommands.ts +650 -79
  46. package/ts/workDir.bun.spec.ts +90 -0
  47. package/ts/workDir.spec.ts +90 -0
  48. package/ts/workDir.ts +75 -0
  49. package/dist/remotes-BDMnvGI6.js +0 -5
  50. package/dist/subcommands-DioyG80q.js +0 -13
  51. package/dist/trayApp-C6C7-TSh.js +0 -5
@@ -0,0 +1,366 @@
1
+ /**
2
+ * Composer guard for `ay send`: never type into, append to, or submit a draft
3
+ * someone else left in the target's input box.
4
+ *
5
+ * Why: a terminal shared by a human and by other agents' `ay send` has ONE
6
+ * composer. Observed 2026-10-08: a human had typed "btw how" and paused; a lane's
7
+ * report was pasted after it and Enter submitted both as one turn, so the human's
8
+ * half-written message went out early, fused with the report, and the rest of it
9
+ * was lost. The stdin-activity backoff (isUserTyping) cannot see this: it only
10
+ * knows when the last key was pressed, not whether text is still sitting there.
11
+ *
12
+ * So the send path reads the composer off the rendered screen first. When it
13
+ * holds real input, the message is parked in a per-target file queue and a
14
+ * single detached drainer delivers it once the composer is empty again.
15
+ *
16
+ * Telling a draft from ghost text: Claude Code renders its prompt suggestion
17
+ * (and the "Press up to edit queued messages" hint) with SGR 2 (dim/faint) in the
18
+ * default colour; typed or pasted input is drawn without SGR 2. Measured on the
19
+ * raw PTY log of a live lane: the suggestion frame is `ESC[2mwater the plants
20
+ * ESC[22m` on the prompt row, while typed text on the same row is plain. Colour
21
+ * is not used: typed input is drawn in the default colour, exactly like the
22
+ * ghost, and the user's theme changes the palette but not the SGR 2 attribute.
23
+ * Inverse cells are ignored too: a TUI that paints its own cursor as an inverse
24
+ * block over the first ghost character must not turn a suggestion into a draft.
25
+ */
26
+ import { createHash, randomBytes } from "crypto";
27
+ import { mkdir, readdir, readFile, rename, rm, writeFile } from "fs/promises";
28
+ import path from "path";
29
+ import { agentYesHome } from "./agentYesHome.ts";
30
+
31
+ /** One rendered terminal cell, reduced to what the guard needs. */
32
+ export interface ComposerCell {
33
+ ch: string;
34
+ dim: boolean;
35
+ inverse: boolean;
36
+ /** Drawn in a non-default foreground colour (Claude's footer is; typed text is not). */
37
+ colored: boolean;
38
+ }
39
+
40
+ /** A rendered row: its plain text plus per-cell attributes. */
41
+ export interface ComposerRow {
42
+ text: string;
43
+ cells: ComposerCell[];
44
+ }
45
+
46
+ export type ComposerState =
47
+ /** Nothing typed: an empty prompt, possibly showing dim ghost text. */
48
+ | { kind: "empty"; ghost: boolean }
49
+ /** Real input is sitting in the composer. `chars` counts the real cells. */
50
+ | { kind: "draft"; chars: number }
51
+ /** No composer is visible (menu, trust dialog, unknown CLI screen). */
52
+ | { kind: "unknown"; reason: string };
53
+
54
+ const PROMPT_RE = /^\s*[❯›]($|\s)/u;
55
+ // Same chrome inspectSubmission stops at: the separator rule under the box and
56
+ // the Claude/Codex footer rows.
57
+ const SEPARATOR_RE = /^\s*[─━]{3,}/u;
58
+ const FOOTER_RE =
59
+ /^\s*(?:·\s*)?(?:[←→] .*agents|\? for shortcuts|esc to interrupt|ctrl\+t to|GPT-[^·]*·|gpt-[^·]*·|⏵⏵|⏸|⏎ send|\d+% context left)/iu;
60
+ // Claude Code's status footer often LEADS with other `·`-separated segments
61
+ // ("1 shell · esc to interrupt · ← 2 agents · ↓ to manage", "PR #12 · 2 shells ·
62
+ // ← for agents · …", "shell, 1 monitor · …"), and ink's partial redraws can leave
63
+ // it garbled ("1 · esc to …", "↓ t…"). Unmatched, the whole row was
64
+ // counted as a 20-40 char draft and every send to an idle lane was parked. So a
65
+ // row is also the footer when any later segment is one of its fixed hints, or
66
+ // when only the mode label's "(shift+tab to cycle)" tail survived the redraw.
67
+ // Unanchored, that could also match a draft line that happens to contain
68
+ // "· esc to interrupt", so the draft check only accepts it on a row drawn
69
+ // entirely in colour, as the footer is — typed input is in the default colour.
70
+ const FOOTER_SEGMENT_RE = /·\s*(?:[←→] .*agents?|↓ |esc to interrupt)|\(shift\+tab to /u;
71
+
72
+ /**
73
+ * The composer's prompt row among plain-text rows (oldest first), or -1.
74
+ * Claude Code boxes its composer, so the prompt is the row directly under the
75
+ * LAST rule that has a prompt row under it — a `›`/`❯` that merely starts a
76
+ * line of a multi-line draft is inside the box, not a second prompt. Without
77
+ * any box (Codex) it is the last prompt-looking row. Shared by the draft check
78
+ * and by submission confirmation, so both agree on where history ends.
79
+ */
80
+ export function composerPromptRow(texts: string[]): number {
81
+ for (let i = texts.length - 2; i >= 0; i--) {
82
+ if (SEPARATOR_RE.test(texts[i]!) && PROMPT_RE.test(texts[i + 1]!)) return i + 1;
83
+ }
84
+ return texts.findLastIndex((t) => PROMPT_RE.test(t));
85
+ }
86
+
87
+ /**
88
+ * Is this row composer chrome (a rule or a Claude/Codex footer) — the end of the
89
+ * input? Pass the row's `cells` when known: the loose footer match then also
90
+ * requires every visible cell to be coloured, so a typed line is never cut off.
91
+ */
92
+ export function isComposerChrome(text: string, cells?: ComposerCell[]): boolean {
93
+ if (SEPARATOR_RE.test(text) || FOOTER_RE.test(text)) return true;
94
+ if (!FOOTER_SEGMENT_RE.test(text)) return false;
95
+ return !cells || cells.every((c) => !c.ch.trim() || c.ch === "\u00a0" || c.colored);
96
+ }
97
+
98
+ /**
99
+ * Classify the composer from rendered rows (oldest first, screen bottom last).
100
+ *
101
+ * Claude Code draws the composer as a box: a rule, the prompt row, any further
102
+ * draft rows, a rule. The box is found by its TOP rule (the last rule directly
103
+ * followed by a prompt row) and runs to the next rule, so a draft line that
104
+ * itself starts with `›`/`❯`, or a blank line inside a multi-line draft, stays
105
+ * inside it. When the bottom rule is not on screen (a partial redraw in the
106
+ * replayed tail) the box ends at the footer instead.
107
+ *
108
+ * Without a top rule (Codex) the composer is the last prompt row plus every row
109
+ * under it up to a rule or the footer (Codex's `⏎ send` hints / `% context
110
+ * left` row) — blank rows included, so a multi-line draft with a blank line in
111
+ * it is not cut short and read as empty (codex review). Any other non-dim text
112
+ * down there counts as a draft: parking a message is recoverable, typing into a
113
+ * draft is not. A draft whose own line starts with a prompt glyph can still be
114
+ * misread there.
115
+ */
116
+ export function classifyComposer(rows: ComposerRow[]): ComposerState {
117
+ const prompt = composerPromptRow(rows.map((r) => r.text));
118
+ if (prompt < 0) return { kind: "unknown", reason: "no prompt row on screen" };
119
+ let real = 0;
120
+ let ghost = false;
121
+ for (let i = prompt; i < rows.length; i++) {
122
+ const row = rows[i]!;
123
+ if (i > prompt) {
124
+ if (isComposerChrome(row.text, row.cells)) break;
125
+ if (!row.text.trim()) continue;
126
+ }
127
+ let cells = row.cells;
128
+ if (i === prompt) {
129
+ // Skip the indentation and the prompt glyph itself.
130
+ const glyph = cells.findIndex((c) => c.ch === "❯" || c.ch === "›");
131
+ cells = glyph >= 0 ? cells.slice(glyph + 1) : cells;
132
+ }
133
+ for (const c of cells) {
134
+ if (!c.ch.trim() || c.ch === "\u00a0") continue;
135
+ if (c.inverse) continue;
136
+ if (c.dim) ghost = true;
137
+ else real++;
138
+ }
139
+ }
140
+ return real > 0 ? { kind: "draft", chars: real } : { kind: "empty", ghost };
141
+ }
142
+
143
+ type XtermLike = {
144
+ buffer: {
145
+ active: {
146
+ length: number;
147
+ getLine(i: number):
148
+ | {
149
+ length: number;
150
+ translateToString(trim: boolean): string;
151
+ getCell(x: number):
152
+ | {
153
+ getChars(): string;
154
+ isDim(): number;
155
+ isInverse(): number;
156
+ isFgDefault(): boolean;
157
+ getWidth(): number;
158
+ }
159
+ | undefined;
160
+ }
161
+ | undefined;
162
+ };
163
+ };
164
+ };
165
+
166
+ /** Read the bottom `n` rows of an xterm buffer as ComposerRows. */
167
+ export function rowsFromXterm(term: XtermLike, n: number): ComposerRow[] {
168
+ const active = term.buffer.active;
169
+ const rows: ComposerRow[] = [];
170
+ for (let i = Math.max(0, active.length - n); i < active.length; i++) {
171
+ const line = active.getLine(i);
172
+ if (!line) {
173
+ rows.push({ text: "", cells: [] });
174
+ continue;
175
+ }
176
+ const cells: ComposerCell[] = [];
177
+ for (let x = 0; x < line.length; x++) {
178
+ const c = line.getCell(x);
179
+ if (!c || c.getWidth() === 0) continue; // trailing half of a wide char
180
+ cells.push({
181
+ ch: c.getChars() || " ",
182
+ dim: c.isDim() !== 0,
183
+ inverse: c.isInverse() !== 0,
184
+ colored: !c.isFgDefault(),
185
+ });
186
+ }
187
+ rows.push({ text: line.translateToString(true), cells });
188
+ }
189
+ while (rows.length && rows[rows.length - 1]!.text.trim() === "") rows.pop();
190
+ return rows;
191
+ }
192
+
193
+ // ---------------------------------------------------------------------------
194
+ // Pending queue: one JSON file per parked message, under
195
+ // <AGENT_YES_HOME>/pending/<pid>/, delivered oldest first by one drainer.
196
+ // ---------------------------------------------------------------------------
197
+
198
+ /** Everything the drainer needs to deliver and to record a parked message. */
199
+ export interface PendingSend {
200
+ id: string;
201
+ queuedAt: number;
202
+ pid: number;
203
+ fifoPath: string;
204
+ /** Exactly what cmdSend would have written (envelope + paste framing). */
205
+ fullBody: string;
206
+ trailing: string;
207
+ /** Submit-confirm identity (`<ay-msg nonce` or the raw body). */
208
+ identity: string;
209
+ /** The mailbox record to append once the outcome is known. */
210
+ record: Record<string, unknown>;
211
+ }
212
+
213
+ /** How long a parked message waits for the composer before it is given up. */
214
+ export const PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1000;
215
+
216
+ export function pendingDir(pid: number): string {
217
+ return path.join(agentYesHome(), "pending", String(pid));
218
+ }
219
+
220
+ export async function listPending(pid: number): Promise<string[]> {
221
+ const names = await readdir(pendingDir(pid)).catch(() => [] as string[]);
222
+ return names.filter((n) => n.endsWith(".json")).sort();
223
+ }
224
+
225
+ export async function enqueuePending(p: Omit<PendingSend, "id">): Promise<PendingSend> {
226
+ const dir = pendingDir(p.pid);
227
+ await mkdir(dir, { recursive: true, mode: 0o700 });
228
+ // Sortable name keeps delivery in send order: zero-padded ms, then random.
229
+ const id = `${String(p.queuedAt).padStart(15, "0")}-${randomBytes(4).toString("hex")}`;
230
+ const full: PendingSend = { ...p, id };
231
+ const tmp = path.join(dir, `.${id}.tmp`);
232
+ await writeFile(tmp, JSON.stringify(full), { mode: 0o600 });
233
+ await rename(tmp, path.join(dir, `${id}.json`));
234
+ return full;
235
+ }
236
+
237
+ export async function readPending(pid: number, name: string): Promise<PendingSend | null> {
238
+ const raw = await readFile(path.join(pendingDir(pid), name), "utf-8").catch(() => null);
239
+ if (raw === null) return null;
240
+ try {
241
+ return JSON.parse(raw) as PendingSend;
242
+ } catch {
243
+ return null;
244
+ }
245
+ }
246
+
247
+ /**
248
+ * Take a parked message off the queue BEFORE writing it. Delivery is therefore
249
+ * at most once: a drainer that dies mid-write loses the message (it is still in
250
+ * the sender's outbox as queued) rather than pasting it a second time into
251
+ * whatever the composer holds next. Returns false when another process took it.
252
+ */
253
+ export async function claimPending(pid: number, name: string): Promise<boolean> {
254
+ try {
255
+ await rm(path.join(pendingDir(pid), name));
256
+ return true;
257
+ } catch {
258
+ return false;
259
+ }
260
+ }
261
+
262
+ /** Move a message the drainer gave up on out of the queue, keeping it on disk. */
263
+ export async function retirePending(pid: number, name: string, why: string): Promise<void> {
264
+ const dir = path.join(pendingDir(pid), "undelivered");
265
+ await mkdir(dir, { recursive: true, mode: 0o700 }).catch(() => {});
266
+ await rename(path.join(pendingDir(pid), name), path.join(dir, name)).catch(() => {});
267
+ await writeFile(path.join(dir, `${name}.why`), `${why}\n`, { mode: 0o600 }).catch(() => {});
268
+ }
269
+
270
+ // ---------------------------------------------------------------------------
271
+ // Duplicate suppression at the sink. With the guard, rc=4 QUEUED is common, and
272
+ // a lane that reads it as "failed" resends the same report (observed
273
+ // live: one lane → another twice, 6 s apart). The target keeps a tiny
274
+ // ledger of what agents recently sent it — sender, body HASH, time, outcome;
275
+ // never the body — read and written under the same input lock as the paste,
276
+ // so a resend racing the original still sees it.
277
+ // ---------------------------------------------------------------------------
278
+
279
+ /** An identical body from the same sender within this window is a resend. */
280
+ export const DUPLICATE_WINDOW_MS = 60_000;
281
+
282
+ export interface RecentSend {
283
+ at: number;
284
+ sender: string;
285
+ hash: string;
286
+ outcome: "sent" | "queued";
287
+ }
288
+
289
+ export function recentSendsPath(pid: number): string {
290
+ return path.join(agentYesHome(), "pending", `${pid}.recent.jsonl`);
291
+ }
292
+
293
+ /** Who sent it, for dedupe purposes: an agent's stable id (or pid). A person at
294
+ * a shell (no agent) is never deduped — typing "continue" twice is deliberate. */
295
+ export function senderKey(
296
+ from: { agent_id?: string | null; pid?: number | null } | null | undefined,
297
+ ): string | null {
298
+ if (!from) return null;
299
+ if (from.agent_id) return `a:${from.agent_id}`;
300
+ return typeof from.pid === "number" ? `p:${from.pid}` : null;
301
+ }
302
+
303
+ export function bodyHash(body: string): string {
304
+ return createHash("sha256").update(body).digest("hex");
305
+ }
306
+
307
+ async function readRecent(pid: number): Promise<RecentSend[]> {
308
+ const raw = await readFile(recentSendsPath(pid), "utf-8").catch(() => "");
309
+ const out: RecentSend[] = [];
310
+ for (const line of raw.split("\n")) {
311
+ if (!line.trim()) continue;
312
+ try {
313
+ out.push(JSON.parse(line) as RecentSend);
314
+ } catch {
315
+ /* torn line */
316
+ }
317
+ }
318
+ return out;
319
+ }
320
+
321
+ /** The earlier identical send this one repeats, or null. Call under the input lock. */
322
+ export async function findRecentDuplicate(
323
+ pid: number,
324
+ sender: string,
325
+ body: string,
326
+ now = Date.now(),
327
+ ): Promise<RecentSend | null> {
328
+ const hash = bodyHash(body);
329
+ const hits = (await readRecent(pid)).filter(
330
+ (r) =>
331
+ r.sender === sender &&
332
+ r.hash === hash &&
333
+ now - r.at >= 0 &&
334
+ now - r.at <= DUPLICATE_WINDOW_MS,
335
+ );
336
+ return hits.at(-1) ?? null;
337
+ }
338
+
339
+ /** Note a send (before it is typed or parked) and drop entries past the window. */
340
+ export async function noteRecentSend(
341
+ pid: number,
342
+ sender: string,
343
+ body: string,
344
+ outcome: RecentSend["outcome"],
345
+ now = Date.now(),
346
+ ): Promise<void> {
347
+ const kept = (await readRecent(pid)).filter((r) => now - r.at <= DUPLICATE_WINDOW_MS);
348
+ kept.push({ at: now, sender, hash: bodyHash(body), outcome });
349
+ const file = recentSendsPath(pid);
350
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
351
+ const tmp = `${file}.${randomBytes(4).toString("hex")}.tmp`;
352
+ await writeFile(tmp, kept.map((r) => JSON.stringify(r)).join("\n") + "\n", { mode: 0o600 });
353
+ await rename(tmp, file);
354
+ }
355
+
356
+ /** What `ay send` prints when a send exits 4, so no caller reads it as a failure. */
357
+ export function queuedReceipt(kind: "parked" | "cli-queued" | "duplicate", detail: string): string {
358
+ switch (kind) {
359
+ case "parked":
360
+ return `ay send: nothing was typed — ${detail}. The message is parked and will be delivered once the input box is empty and nobody is typing. Queued, do not resend.`;
361
+ case "cli-queued":
362
+ return `ay send: the target accepted it into its own queue (${detail}); it runs after the current turn. Queued, do not resend.`;
363
+ case "duplicate":
364
+ return `ay send: not resent — ${detail}. Do not resend.`;
365
+ }
366
+ }
@@ -72,6 +72,13 @@ export interface GlobalPidRecord {
72
72
  // "what is this agent doing" without reading its screen. Mirrors Rust's
73
73
  // `title`.
74
74
  title?: string | null;
75
+ // Derived at read time by listRecords (ts/workDir.ts), never persisted: the
76
+ // repo this agent's shells actually run in, sampled from the kernel by the
77
+ // Rust wrapper — differs from `cwd` when a lane spawned in one dir works in
78
+ // another.
79
+ workdir?: string;
80
+ workdir_source?: "observed" | "spawn";
81
+ workdir_at?: number | null;
75
82
  }
76
83
 
77
84
  /**
package/ts/messageLog.ts CHANGED
@@ -107,6 +107,8 @@ export interface MessageRecord {
107
107
  code?: string;
108
108
  /** Whether `ay send` confirmed the CLI acted on it. */
109
109
  confirmed?: boolean;
110
+ /** Destination submission evidence; queued is accepted but not yet submitted. */
111
+ submission?: "submitted" | "queued" | "not-submitted" | "unchecked";
110
112
  /** Whether the body was wrapped in an `[ay-msg …]` attribution block. */
111
113
  wrapped: boolean;
112
114
  /** The remote url/alias when this message crossed the wire (`ay send <remote>:<kw>`);
@@ -155,3 +155,39 @@ test("parseMenu: a boxed 'N.M' version still isn't mistaken for an option", () =
155
155
  const menu = parseMenu(screen, claude);
156
156
  expect(menu!.options).toEqual([1, 2]);
157
157
  });
158
+
159
+ test("detects claude parked on the folder-trust dialog (current un-numbered layout)", () => {
160
+ // The auto Down+Enter normally answers this; when it loses the race the lane
161
+ // sits here, and before this pattern `ay ls` reported it as plain idle.
162
+ const screen = [
163
+ "Do you trust the files in this folder?",
164
+ "",
165
+ "/repo/alpha/tree/feat-x",
166
+ "",
167
+ "❯ No, exit",
168
+ " Yes, I trust this folder",
169
+ "",
170
+ "Enter to confirm · Esc to cancel",
171
+ ];
172
+ const r = classifyNeedsInput(screen, claude);
173
+ expect(r).not.toBeNull();
174
+ expect(r!.question).toContain("trust");
175
+ });
176
+
177
+ test("detects the legacy numbered folder-trust dialog", () => {
178
+ const screen = [
179
+ "Do you trust the files in this folder?",
180
+ " > 1. Yes, I trust this folder",
181
+ " 2. No, exit",
182
+ ];
183
+ expect(classifyNeedsInput(screen, claude)).not.toBeNull();
184
+ });
185
+
186
+ test("prose mentioning the trust dialog is not a trust prompt", () => {
187
+ const screen = [
188
+ "⏺ The trust dialog says Yes, I trust this folder when accepted.",
189
+ "",
190
+ "? for shortcuts",
191
+ ];
192
+ expect(classifyNeedsInput(screen, claude)).toBeNull();
193
+ });
@@ -155,3 +155,39 @@ test("parseMenu: a boxed 'N.M' version still isn't mistaken for an option", () =
155
155
  const menu = parseMenu(screen, claude);
156
156
  expect(menu!.options).toEqual([1, 2]);
157
157
  });
158
+
159
+ test("detects claude parked on the folder-trust dialog (current un-numbered layout)", () => {
160
+ // The auto Down+Enter normally answers this; when it loses the race the lane
161
+ // sits here, and before this pattern `ay ls` reported it as plain idle.
162
+ const screen = [
163
+ "Do you trust the files in this folder?",
164
+ "",
165
+ "/repo/alpha/tree/feat-x",
166
+ "",
167
+ "❯ No, exit",
168
+ " Yes, I trust this folder",
169
+ "",
170
+ "Enter to confirm · Esc to cancel",
171
+ ];
172
+ const r = classifyNeedsInput(screen, claude);
173
+ expect(r).not.toBeNull();
174
+ expect(r!.question).toContain("trust");
175
+ });
176
+
177
+ test("detects the legacy numbered folder-trust dialog", () => {
178
+ const screen = [
179
+ "Do you trust the files in this folder?",
180
+ " > 1. Yes, I trust this folder",
181
+ " 2. No, exit",
182
+ ];
183
+ expect(classifyNeedsInput(screen, claude)).not.toBeNull();
184
+ });
185
+
186
+ test("prose mentioning the trust dialog is not a trust prompt", () => {
187
+ const screen = [
188
+ "⏺ The trust dialog says Yes, I trust this folder when accepted.",
189
+ "",
190
+ "? for shortcuts",
191
+ ];
192
+ expect(classifyNeedsInput(screen, claude)).toBeNull();
193
+ });
@@ -0,0 +1,125 @@
1
+ import { mkdtemp, rm } from "fs/promises";
2
+ import { tmpdir } from "os";
3
+ import path from "path";
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from "bun:test";
5
+ import { cmdRemote, MASK, maskRemoteUrl, writeRemoteAlias } from "./remotes.ts";
6
+ import { parseWebrtcLink } from "./webrtcLink.ts";
7
+
8
+ // Synthetic secrets only — a v2 share secret shape (e1.<64 hex>) and a plain token.
9
+ const SECRET = "e1.0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
10
+ const TOKEN = "tok-aaaaaaaabbbbbbbbcccccccc";
11
+
12
+ describe("maskRemoteUrl", () => {
13
+ it("masks the token of a webrtc:// link, keeping room and host", () => {
14
+ expect(maskRemoteUrl(`webrtc://room1:${SECRET}@s.example.com`)).toBe(
15
+ `webrtc://room1:${MASK}@s.example.com`,
16
+ );
17
+ });
18
+ it("masks a positional /w/ share link, with and without a sighost", () => {
19
+ expect(maskRemoteUrl(`https://agent-yes.com/w/#room1:${SECRET}`)).toBe(
20
+ `https://agent-yes.com/w/#room1:${MASK}`,
21
+ );
22
+ expect(maskRemoteUrl(`https://agent-yes.com/w/#room1:${SECRET}@s.example.com`)).toBe(
23
+ `https://agent-yes.com/w/#room1:${MASK}@s.example.com`,
24
+ );
25
+ });
26
+ it("masks s= and k= in a key=value fragment, keeping the other keys", () => {
27
+ expect(maskRemoteUrl(`https://agent-yes.com/room/#room=room1&s=${SECRET}&sig=s.x`)).toBe(
28
+ `https://agent-yes.com/room/#room=room1&s=${MASK}&sig=s.x`,
29
+ );
30
+ expect(maskRemoteUrl(`https://box.example.ts.net/ay/#k=${TOKEN}`)).toBe(
31
+ `https://box.example.ts.net/ay/#k=${MASK}`,
32
+ );
33
+ });
34
+ it("masks percent-encoded secret keys, which URLSearchParams decodes on use", () => {
35
+ expect(maskRemoteUrl(`https://agent-yes.com/room/#room=room1&%73=${SECRET}`)).toBe(
36
+ `https://agent-yes.com/room/#room=room1&%73=${MASK}`,
37
+ );
38
+ expect(maskRemoteUrl(`https://agent-yes.com/room/#%73=${SECRET}&room=room1`)).toBe(
39
+ `https://agent-yes.com/room/#%73=${MASK}&room=room1`,
40
+ );
41
+ expect(maskRemoteUrl(`https://box.example.ts.net/ay/#?%6B=${TOKEN}`)).toBe(
42
+ `https://box.example.ts.net/ay/#?%6B=${MASK}`,
43
+ );
44
+ });
45
+ it("treats a room id containing `=` as positional, like the parser does", () => {
46
+ expect(maskRemoteUrl(`https://agent-yes.com/w/#room1=demo:${SECRET}`)).toBe(
47
+ `https://agent-yes.com/w/#room1=demo:${MASK}`,
48
+ );
49
+ });
50
+ it("masks a malformed webrtc:// link that has no @host", () => {
51
+ expect(maskRemoteUrl(`webrtc://room1:${SECRET}`)).toBe(`webrtc://room1:${MASK}`);
52
+ });
53
+ it("masks userinfo credentials", () => {
54
+ expect(maskRemoteUrl(`http://${TOKEN}@192.0.2.5:7432`)).toBe(`http://${MASK}@192.0.2.5:7432`);
55
+ });
56
+ it("leaves a URL without secrets untouched", () => {
57
+ expect(maskRemoteUrl("http://192.0.2.5:7432")).toBe("http://192.0.2.5:7432");
58
+ expect(maskRemoteUrl("https://box.example.ts.net/ay")).toBe("https://box.example.ts.net/ay");
59
+ });
60
+ });
61
+
62
+ // Cross-check against the real parser: whatever it accepts as a working share
63
+ // link, the masked form must not contain the secret it would connect with.
64
+ describe("maskRemoteUrl vs parseWebrtcLink", () => {
65
+ const HEX = SECRET.slice(3);
66
+ const links = [
67
+ `webrtc://room1:${SECRET}@s.example.com`,
68
+ `https://agent-yes.com/w/#room1:${SECRET}`,
69
+ `https://agent-yes.com/w/#room1:${SECRET}@s.example.com`,
70
+ `https://agent-yes.com/w/#room1=demo:${SECRET}`,
71
+ `https://agent-yes.com/room/#room=room1&s=${SECRET}`,
72
+ `https://agent-yes.com/room/#?room=room1&s=${SECRET}&sig=s.example.com`,
73
+ `https://agent-yes.com/room/#room=room1&%73=${SECRET}`,
74
+ `https://agent-yes.com/room/#s=${SECRET}&room=room1`,
75
+ ];
76
+ for (const link of links) {
77
+ it(`hides the secret of ${link.replace(SECRET, "<secret>")}`, () => {
78
+ expect(parseWebrtcLink(link)?.s).toBe(HEX); // the parser accepts it
79
+ expect(maskRemoteUrl(link)).not.toContain(HEX.slice(0, 16));
80
+ });
81
+ }
82
+ });
83
+
84
+ describe("ay remote ls", () => {
85
+ let home: string;
86
+ let out: string;
87
+ let prevHome: string | undefined;
88
+ beforeEach(async () => {
89
+ home = await mkdtemp(path.join(tmpdir(), "ay-remotes-"));
90
+ prevHome = process.env.AGENT_YES_HOME;
91
+ process.env.AGENT_YES_HOME = home;
92
+ out = "";
93
+ vi.spyOn(process.stdout, "write").mockImplementation((c: any) => ((out += String(c)), true));
94
+ vi.spyOn(process.stderr, "write").mockImplementation(() => true);
95
+ await writeRemoteAlias("rtc", { url: `https://agent-yes.com/w/#room1:${SECRET}`, token: "" });
96
+ await writeRemoteAlias("lan", { url: "http://192.0.2.5:7432", token: TOKEN });
97
+ });
98
+ afterEach(async () => {
99
+ vi.restoreAllMocks();
100
+ if (prevHome === undefined) delete process.env.AGENT_YES_HOME;
101
+ else process.env.AGENT_YES_HOME = prevHome;
102
+ await rm(home, { recursive: true, force: true });
103
+ });
104
+
105
+ it("masks every secret by default", async () => {
106
+ expect(await cmdRemote(["ls"])).toBe(0);
107
+ expect(out).not.toContain(SECRET);
108
+ expect(out).not.toContain(TOKEN.slice(0, 8));
109
+ expect(out).toContain(`rtc\thttps://agent-yes.com/w/#room1:${MASK}\n`);
110
+ expect(out).toContain(`lan\thttp://192.0.2.5:7432\ttoken:${MASK}\n`);
111
+ });
112
+ it("reveals secrets with --show-secrets", async () => {
113
+ expect(await cmdRemote(["ls", "--show-secrets"])).toBe(0);
114
+ expect(out).toContain(SECRET);
115
+ expect(out).toContain(`token:${TOKEN}`);
116
+ });
117
+ it("accepts the flag without the ls verb", async () => {
118
+ expect(await cmdRemote(["--show-secrets"])).toBe(0);
119
+ expect(out).toContain(SECRET);
120
+ });
121
+ it("rejects an unknown flag instead of ignoring it", async () => {
122
+ expect(await cmdRemote(["ls", "--show-secret"])).toBe(1);
123
+ expect(out).toBe("");
124
+ });
125
+ });