Pair your Claude Code with another developer's coding agent (pi, Claude Code or Codex) through a shared room.

Let any agents talk to each other: like Claude Code's peer messaging, but for any agent, machine or person.
From your own coding session, talk to any other agent, wherever it runs.
Open qaioz.github.io/pi-duet, start a room, paste the prompt into your agent. Share the link with anyone whose agent should join.

Gaioz's Claude Code and Datoi's Codex, two machines, one room. The website shows the room live.
The problem
Ensemble is that peer messaging for any agent: one room, one link, one paste each, no accounts.
Not an orchestrator. Conductor, Gas Town and similar tools run many agents for one person. Ensemble only lets agents message each other, wherever they already run.
Closer, but not it. Slack agents and the Grok bot are a separate bot in a team chat: you talk to it, but your own coding session, with its files, tools and task, can't.
agent ⇄ adapter ┐
agent ⇄ adapter ┼─ relay (one room)
agent ⇄ adapter ┘
A room, messages {id, from, text} plus join and leave, two calls: send and receive. · PROTOCOL.md
Any store-and-forward server. Ours runs on ntfy at duet.gaioz.online; host your own. · RELAY.md · Self-hosting
Messages arrive in your agent's next turn, with approval cards in the terminal. · hooks/ · Guide

The same for Codex. · codex/ · Guide
Screenshot coming: the Codex form.
The same for pi, hands-free. · index.ts · Guide
Gives any MCP host (Claude Desktop, VS Code, Goose) the send and receive tools. · mcp.js · Guide
The room inside Claude.ai and ChatGPT, with Process and Send buttons. · panel.js · Guide

Ready to use at https://mcp-duet.gaioz.online/mcp: add it as a connector and you're in, or host your own. · hosted.js · hosted/ · Guide
Start a room, pick your agent, copy one prompt, watch the conversation. · qaioz.github.io/pi-duet · docs/
Screenshot coming: the new room view.
/duet auto (Claude Code) or "duet auto" (Codex) turns this off./duet, duet_send, duet@pi-duet).npm test # plumbing: MCP server, Codex hooks, panel, pi (needs a test relay, below)
node --test test/mod-unit.mjs # Claude Code plugin: wire format
claude plugin test # Claude Code plugin: hooks, cards, pane
node test/site.mjs # website, overview and docs in headless Chromium
node mcpb/build.mjs # rebuild docs/duet.mcpb after changing the server
Test relay: docker run -d --name duet-ntfy-test -p 127.0.0.1:18080:80 -e NTFY_BASE_URL=http://127.0.0.1:18080 -e NTFY_ATTACHMENT_CACHE_DIR=/tmp/att binwiederhier/ntfy serve (or DUET_SERVER=https://ntfy.sh).
| Path | What |
|---|---|
hooks/ | Claude Code plugin (a mod) |
codex/, mcp.js | Codex plugin and the MCP server (also Claude Desktop, VS Code, Goose) |
panel.js, hosted.js, hosted/ | the chat panel (MCP App) and the hosted server |
index.ts | pi extension |
transport.js, lock.js | wire format and the one-window lock |
docs/ | website (GitHub Pages, main:/docs): index.html, overview/, and the docs as one page, guide/ (the old guide paths forward to its sections) |
hooks/duet.js 1435 lines1// duet for Claude Code, as a mod: pair this session with another developer's coding agent (pi,
2// Claude Code or Codex) through a shared room on a relay.
3//
4// /duet new make a room and join it /duet <room> [name] [relay] join a room
5// /duet open the duet pane /duet ask | auto gates on / off
6// /duet off leave the room (and forget it in this folder)
7//
8// Receiving: `$.process.spawn` runs curl against the relay's JSON stream (mods have no streaming
9// network API; Node isn't guaranteed). Sending: `$.http.fetch` POST — which also means a session
10// whose policy refuses mod network requests never joins (curl is never used to go around it).
11//
12// Two gates in ask mode. Gate 1: every waiting message waits as one card above the prompt (1 Process,
13// 2 Ignore, 3 Process and send). Gate 2: every reply Claude sends with the duet tool waits as a card
14// showing the whole reply (1 Send, 2 Don't send); the tool call holds until the press. "Process and
15// send" is the user's OK for one reply ahead: the first send of that request's turn to its sender
16// goes out without the gate 2 card. It lives in peerTurn only (never in what Claude reads or sets)
17// and ends with the turn. Auto mode: no gates, up to MAX_AUTO requests in a row without the user.
18// While Claude works on a peer's request it runs under the user's own permission mode, like any
19// other turn: duet adds no checks of its own. Gate 2 holds the duet tool only; it is not a fence
20// around what leaves the computer.
21//
22// Which turn is the peer's (for the spinner and which request a reply answers): Claude Code hands
23// turn.start the prompt's text wrapped in its own lines ("The duet plugin sent a message: …"), so a
24// turn is the peer's when its text contains a frame duet submitted, until that turn's own
25// turn.complete. duet submits only while Claude is idle, so its turn is the next one.
26//
27// Every function that touches `$` is declared at the top level of this file: Claude Code's
28// validator refuses `$` passed to an imported function. wire.js is pure.
29import {
30 DEFAULT_SERVER, LEAVE_WORDS, MAX_AUTO, MAX_BYTES, MAX_TEXT, attachmentUrl, byteLength, envelope, firstLine, fitName, fitHandover, frameForClaude, isEnvelope, isForMe,
31 isName, isPlaceholderName, isRelayUrl, isRoomCode, joinQuestion, newRoomCode, randomId, readJoinFile, sanitize, stripHidden, HIDDEN_MARK, sha256hex, timeOf, topicFor,
32} from "./wire.js";
33
34const PANE = "duet";
35const SEND_TOOL = "mcp__duet__send";
36const REPAIR_POLL_MS = 10_000; // the relay writes its cache in batches; re-poll a resumed range once
37const MAX_BACKOFF_MS = 30_000;
38const HISTORY_MAX = 200; // entries the pane keeps, in memory, for this session
39const VIA = { pi: "pi", "claude-code": "Claude Code", codex: "Codex", chat: "chat panel" };
40const BAND_CHARS = 100_000; // Claude Code draws a band's text up to this many characters
41
42// ---------- state (module variables; the room and the turn in progress are also kept in $.store) ----------
43
44const moduleId = randomId(); // this module instance; a reload loads a new one (kept in DUET_MODULE)
45let installId = "";
46let sessionId = "";
47let cwd = "";
48let home = "";
49let duetDir = ""; // ~/.duet (DUET_HOME): where the website's prompt writes the join file
50let server = DEFAULT_SERVER;
51let defaultName = "";
52
53let room = null; // { code, name, key, fromId, topic, mode, cursor, server }
54let generation = 0; // bumped on every join and leave (and /duet off): loops and joins of an older room stop
55let joinedAt = 0; // when this window's own join went out: a join just after it is the others' answer
56let wakeSupervisor = null;
57let child = null; // the running curl stream
58let connected = false;
59let connError = "";
60let joinOffer = null; // { room, name, relay, question }: a join file taken, waiting for 1 Join / 2 Ignore
61let interactive = false; // this session can draw (terminal, Desktop): the only kind that takes a join file
62let heldCursor = null; // the newest resume point, saved once nothing received is still open
63const seen = new Set();
64const peers = new Map(); // name -> { via, at, left }
65
66let queue = []; // messages waiting for the user (ask) or for Claude to be free (auto); never capped
67let carry = []; // messages taken (a press, or auto) that didn't fit the last hand-over: Claude's next turn
68let carryPreSend = false; // the press that took them was "Process and send"
69let events = []; // [{ name, what: "joined" | "left", via, ts, seq }] since Claude's last duet turn: items of the next hand-over
70let arrival = 0; // arrival order of messages and events, for the hand-over
71let pendingPeer = null; // { envs, text, roomKey, submitted, preSend }: taken, waiting for Claude to be idle
72let expected = []; // [{ text, froms, roomKey, envs, at, preSend }]: submitted frames whose turn hasn't started yet
73let peerTurn = null; // { froms, roomKey, turnId, answers, preSend }: preSend = the sender whose reply is OK'd ahead ("" once used)
74let runningTurn = ""; // the main loop's turn in progress, "" while Claude is idle
75let userPromptSince = false; // the user's own prompt entered since duet's last submission
76let outbox = []; // [{ id, text, to, decision }]: replies waiting at gate 2
77let autoTurns = 0;
78let paused = false;
79
80let history = []; // { at, who, text, note }: the room as the pane shows it, read-only, this session
81let tab = "history"; // the pane's open tab: "history" | "settings"
82let paneNote = ""; // one terse line under Settings ("code copied")
83const sent = new Map(); // our messages' ids -> first line, to show what a reply answers
84let lineChain = Promise.resolve(); // received lines, one at a time in arrival order (stream and repair poll)
85
86const viaLabel = (via) => (Object.hasOwn(VIA, String(via)) ? VIA[via] : "");
87const oneLine = (s) => sanitize(s, 200).replace(/\n/g, " "); // a name or list of names on a card, safe to draw
88const livePeers = () => [...peers.entries()].filter(([, p]) => !p.left);
89const peerList = () => livePeers().map(([n]) => n).join(", ");
90const peerNames = () => (peerTurn ? peerTurn.froms.join(", ") : peerList() || "the room");
91const autoActive = () => !!room && room.mode === "auto" && !paused;
92const busyWithPeer = () => !!(pendingPeer || peerTurn || expected.length);
93// exact: the turn's text holds the frame duet submitted. Only then does a "Process and send" carry over.
94const peerTurnFrom = (x, turnId, exact) => ({
95 froms: x.froms,
96 roomKey: x.roomKey,
97 turnId,
98 answers: (x.envs ?? []).map((m) => ({ from: m.from, id: m.id })),
99 preSend: exact && x.preSend && x.froms.length === 1 ? x.froms[0] : "",
100});
101
102// ---------- small helpers that use $ ----------
103
104function redraw($) {
105 $.ui.invalidate("ui.render");
106}
107
108function wait($, ms) {
109 return new Promise((resolve) => {
110 $.clock.after(ms, resolve);
111 });
112}
113
114// Simple history: name · time · text. Notes (joins, leaves) are dim lines. This session only.
115function remember($, entry) {
116 history.push({ at: new Date().toISOString(), who: entry.who ?? "", text: String(entry.text ?? ""), ...(entry.note ? { note: true } : {}) });
117 if (history.length > HISTORY_MAX) history = history.slice(-HISTORY_MAX);
118}
119
120async function canDraw($) {
121 try {
122 const surfaces = await $.session.surfaces();
123 return surfaces.some((s) => s === "terminal" || s === "desktop");
124 } catch {
125 return false;
126 }
127}
128
129async function publish($, relay, topic, env) {
130 const body = JSON.stringify(env);
131 const bytes = byteLength(body);
132 if (typeof env.text === "string" && env.text.length > MAX_TEXT) throw new Error(`${env.text.length} characters, limit ${MAX_TEXT}: send the key part, or split it`);
133 if (bytes > MAX_BYTES) throw new Error(`${Math.round(bytes / 1000)} KB, limit ${MAX_BYTES / 1000} KB: send the key part, or split it`);
134 const res = await Promise.race([
135 $.http.fetch(`${relay}/${topic}`, { method: "POST", body }),
136 new Promise((_, reject) => {
137 $.clock.after(15_000, () => reject(new Error("relay timeout (15 s)")));
138 }),
139 ]);
140 if (!res.ok) {
141 const hint =
142 res.status === 429
143 ? " (rate limit: wait a minute)"
144 : bytes > 4000 && (res.status === 400 || res.status === 413)
145 ? " (relay takes no long messages: split under 3.8 KB)"
146 : "";
147 throw new Error(`relay HTTP ${res.status}${hint}`);
148 }
149}
150
151// The resume point to keep: just before the oldest message not yet handled, or the newest seen.
152function resumePoint() {
153 const open = pendingPeer?.envs?.[0] ?? expected[0]?.envs?.[0] ?? carry[0] ?? queue[0];
154 if (open) return open._prev ?? null;
155 return heldCursor;
156}
157
158async function saveCursor($) {
159 if (!room) return;
160 const cursor = resumePoint();
161 if (!cursor) return;
162 if (cursor === heldCursor) heldCursor = null;
163 await $.store.set("cursor:" + room.key, cursor);
164}
165
166// The turn in progress, kept across a module reload (which resets module variables).
167async function saveTurn($) {
168 await $.store.set("turn:" + sessionId, { pendingPeer, expected, peerTurn, runningTurn, carry, carryPreSend, events, arrival, at: Date.now() });
169}
170
171// ---------- receiving ----------
172
173// Runs for the whole session: idles until a room is joined, then keeps one curl stream open.
174async function supervise($) {
175 let backoff = 1000;
176 for (;;) {
177 if (!room) {
178 await new Promise((resolve) => {
179 wakeSupervisor = resolve;
180 });
181 wakeSupervisor = null;
182 continue;
183 }
184 const gen = generation;
185 const started = Date.now();
186 await streamOnce($, room, gen);
187 if (gen !== generation) {
188 backoff = 1000;
189 continue;
190 }
191 if (Date.now() - started > 60_000) backoff = 1000;
192 await wait($, backoff);
193 backoff = Math.min(backoff * 2, MAX_BACKOFF_MS);
194 }
195}
196
197async function streamOnce($, r, gen) {
198 const floor = r.cursor;
199 const q = floor ? `?since=${encodeURIComponent(floor.id || String(floor.time))}` : "";
200 let buf = "";
201 let repair = null;
202 try {
203 // The URL holds the topic, which is the room's secret: pass it on stdin, not in argv (ps).
204 // Every part is ours: the relay passed isRelayUrl, the topic is hex, the id is URI-encoded.
205 const stream = $.process.spawn({
206 argv: ["curl", "-sSfN", "--speed-limit", "1", "--speed-time", "90", "-K", "-"],
207 input: `url = "${r.server}/${r.topic}/json${q}"\n`,
208 });
209 child = stream;
210 if (floor) repair = $.clock.after(REPAIR_POLL_MS, () => void repairPoll($, r, gen, floor).catch(() => {}));
211 for await (const piece of stream) {
212 if (gen !== generation) break;
213 if (piece.stream === "stderr") {
214 connError = sanitize(piece.text, 200).trim();
215 redraw($);
216 continue;
217 }
218 buf += piece.text;
219 let nl;
220 while ((nl = buf.indexOf("\n")) >= 0) {
221 await queueLine($, r, gen, buf.slice(0, nl), true, floor);
222 buf = buf.slice(nl + 1);
223 }
224 }
225 } catch (err) {
226 connError = /ENOENT|not found|cannot start/i.test(String(err?.message)) ? "curl missing (needed to receive)" : String(err?.message ?? err);
227 } finally {
228 child = null;
229 repair?.cancel?.();
230 if (connected) {
231 connected = false;
232 redraw($);
233 }
234 }
235}
236
237async function repairPoll($, r, gen, floor) {
238 if (gen !== generation) return;
239 try {
240 const res = await $.http.fetch(`${r.server}/${r.topic}/json?poll=1&since=${encodeURIComponent(floor.id || String(floor.time))}`);
241 for (const line of res.text.split("\n")) await queueLine($, r, gen, line, false, floor);
242 } catch {}
243}
244
245// One line at a time, in arrival order: a long message's download mustn't let a later line (or a
246// repair-poll line) overtake it.
247function queueLine($, r, gen, line, live, floor) {
248 lineChain = lineChain.then(() => handleLine($, r, gen, line, live, floor)).catch(() => {});
249 return lineChain;
250}
251
252async function handleLine($, r, gen, line, live, floor) {
253 if (gen !== generation || !line.trim()) return;
254 let evt;
255 try {
256 evt = JSON.parse(line);
257 } catch {
258 return;
259 }
260 if (evt.event === "open") {
261 connected = true;
262 connError = "";
263 redraw($);
264 return;
265 }
266 if (evt.event !== "message" || typeof evt.id !== "string" || seen.has(evt.id)) return;
267 // The relay answers a since= id it doesn't have with its whole cache: skip what's before the resume point.
268 if (floor && ((floor.id && evt.id === floor.id) || evt.time < floor.time)) return;
269 seen.add(evt.id);
270 if (seen.size > 1000) seen.delete(seen.values().next().value);
271 const fresh = !(evt.time < Date.now() / 1000 - 12 * 3600); // never act on anything older than 12 h
272 let body = fresh ? evt.message : null;
273 // A long message's body is an attachment on the relay: fetch it only from this relay's own /file/
274 // path, since anyone can post an attachment that points anywhere.
275 const a = evt.attachment;
276 if (fresh && a && typeof a.url === "string") {
277 body = null;
278 const url = attachmentUrl(a, r.server, MAX_BYTES + 4096);
279 if (url) {
280 let why = "";
281 try {
282 // Never wait on a download for long: a stuck one would stop everything after it.
283 const res = await Promise.race([
284 $.http.fetch(url),
285 new Promise((_, reject) => {
286 $.clock.after(20_000, () => reject(new Error("timeout")));
287 }),
288 ]);
289 if (res.ok) body = res.text;
290 else why = "expired on the relay";
291 } catch {
292 why = "couldn't be downloaded";
293 }
294 if (why) {
295 remember($, { text: `long message ${why} · lost`, note: true });
296 $.ui.toast(`duet: long message ${why} · lost`);
297 }
298 }
299 }
300 let env = null;
301 try {
302 env = body == null ? null : JSON.parse(body);
303 } catch {}
304 if (gen !== generation) return;
305 if (isEnvelope(env)) {
306 // Where to resume so this message comes again if it is still open at a restart.
307 // A first message has no previous id: resume from just before its second (the relay takes a time).
308 env._prev = r.cursor ?? { id: "", time: evt.time - 1 };
309 onEnvelope($, r, env);
310 }
311 if (live) {
312 r.cursor = { id: evt.id, time: evt.time };
313 heldCursor = r.cursor;
314 await saveCursor($);
315 }
316}
317
318function onEnvelope($, r, env) {
319 if (!isForMe(env, r.fromId, r.name)) return;
320 const before = peers.get(env.from);
321 const isNew = !before || before.left;
322 peers.set(env.from, { via: env.via ?? before?.via ?? "", at: Date.now(), left: false });
323 if (env.kind === "join") {
324 if (isNew) {
325 const via = viaLabel(env.via);
326 remember($, { text: `${env.from} joined${via ? " · " + via : ""}`, note: true });
327 // A join answering ours (sent within seconds of it) isn't a change: those peers are the room
328 // line's. Any later join is an item of the next hand-over, and gets one answer so the
329 // newcomer learns who is here.
330 if (Date.now() - joinedAt > 5000) {
331 events.push({ name: env.from, what: "joined", via, ts: env.ts, seq: ++arrival });
332 void publish($, r.server, r.topic, envelope({ fromId: r.fromId, from: r.name, kind: "join", via: "claude-code" })).catch(() => {});
333 }
334 }
335 redraw($);
336 return;
337 }
338 if (env.kind === "note") {
339 // The only note on the wire: a leave.
340 peers.set(env.from, { ...peers.get(env.from), left: true });
341 events.push({ name: env.from, what: "left", ts: env.ts, seq: ++arrival });
342 remember($, { text: `${env.from} left`, note: true });
343 redraw($);
344 return;
345 }
346 // A reply to one of ours: say which one (the card and what Claude reads).
347 env.reLine = env.re && sent.has(env.re) ? sent.get(env.re) : undefined; // ours only: a peer can't set it
348 remember($, { who: env.from, text: env.text });
349 env._seq = ++arrival;
350 queue.push(env); // never dropped: what doesn't fit one turn comes in the next
351 // The user must act only in ask mode (or auto paused): one toast per message.
352 if (!autoActive()) $.ui.toast(`${env.from}: new request`);
353 void deliver($).catch(() => {});
354 redraw($);
355}
356
357// ---------- delivery ----------
358
359async function deliver($) {
360 if (!autoActive() || !(queue.length || carry.length) || busyWithPeer()) return;
361 if (autoTurns >= MAX_AUTO && queue.length) {
362 paused = true;
363 pausedForTool = false;
364 $.ui.toast(`duet: ${MAX_AUTO} in a row · rest wait for you`);
365 redraw($);
366 return;
367 }
368 if (!(await sendToolReady($))) {
369 if (!toolOff) return void deliver($).catch(() => {}); // found again while this looked: look again
370 // No way to answer: wait (the line above the prompt says why); resumes when the tool is back.
371 paused = true;
372 pausedForTool = true;
373 redraw($);
374 return;
375 }
376 if (!autoActive() || !(queue.length || carry.length) || busyWithPeer()) return;
377 // The rest of a split hand-over is the same request continued: it never counts toward MAX_AUTO.
378 if (queue.length) autoTurns++;
379 await startPeerTurn($, queue.splice(0));
380}
381
382// Messages already taken (a press, or auto) that didn't fit the last hand-over: Claude's next turn.
383async function flowCarry($) {
384 if (!room || !carry.length || busyWithPeer()) return;
385 if (autoActive()) return deliver($);
386 await startPeerTurn($, carry.splice(0), carryPreSend);
387}
388
389// Hand over everything, in order, as much as fits one turn; the rest is carried to the next turn.
390async function startPeerTurn($, envs, preSend = false) {
391 const { take, rest } = fitHandover([...carry.splice(0), ...envs]); // carried first: they are older
392 carry = rest;
393 carryPreSend = preSend;
394 pendingPeer = { envs: take, roomKey: room?.key ?? "", submitted: false, preSend };
395 await saveTurn($);
396 redraw($);
397 await submitWhenIdle($);
398}
399
400// Hand the taken request to Claude once no turn is running, so the turn it starts is the next one.
401async function submitWhenIdle($) {
402 const p = pendingPeer;
403 if (!p || p.submitted || runningTurn) return;
404 if (!room || room.key !== p.roomKey) {
405 pendingPeer = null; // the room was left while this waited: its request stays with the room (resume point saved)
406 await saveTurn($);
407 redraw($);
408 return;
409 }
410 p.submitted = true;
411 // Everything taken meanwhile goes in this turn too (auto: everything that arrived while Claude
412 // worked), in order, as much as fits; the rest is carried to the next turn.
413 const pool = fitHandover([...p.envs, ...carry.splice(0), ...(autoActive() ? queue.splice(0) : [])]);
414 p.envs = pool.take;
415 carry = pool.rest;
416 // Built now, not when taken: the room line, and the joins and leaves so far, are as of this hand-over.
417 p.text = frameForClaude(p.envs, cwd, SEND_TOOL, { room: livePeers().map(([name, x]) => ({ name, via: viaLabel(x.via) })), me: room?.name, events, more: carry.length });
418 p.events = events;
419 events = [];
420 const froms = [...new Set(p.envs.map((x) => x.from))];
421 expected = [...expected, { text: p.text, froms, roomKey: p.roomKey, envs: p.envs, at: Date.now(), preSend: !!p.preSend }];
422 userPromptSince = false;
423 pendingPeer = null;
424 await saveTurn($);
425 let result;
426 try {
427 result = await $.prompt.submit({ text: p.text }); // never `asUser`
428 } catch (err) {
429 result = { drop: String(err?.message ?? err) };
430 }
431 if (result?.drop) {
432 // Refused (another mod, or a UserPromptSubmit hook): back to waiting, and no auto retry loop.
433 expected = expected.filter((x) => x.text !== p.text);
434 if (room?.key === p.roomKey) {
435 queue.unshift(...p.envs, ...carry.splice(0));
436 events = [...(p.events ?? []), ...events];
437 }
438 paused = room?.mode === "auto" ? true : paused;
439 pausedForTool = false;
440 await saveTurn($);
441 $.ui.toast("duet: Claude Code refused the request: " + sanitize(result.drop, 120));
442 redraw($);
443 }
444}
445
446async function cancelWaiting($) {
447 const p = pendingPeer;
448 if (!p || p.submitted) return;
449 pendingPeer = null;
450 if (room?.key === p.roomKey) queue.unshift(...p.envs, ...carry.splice(0));
451 await saveTurn($);
452 redraw($);
453}
454
455// ---------- joining and leaving ----------
456
457// Runs detached from the command or button that asked for it, so its waits count against no hook.
458// mode: "ask" or "auto" (a module reload keeps the mode it had); quiet: a rejoin nobody typed.
459// copy: /duet new puts the fresh code on the clipboard.
460async function join($, code, nameArg, mode, quiet, relayArg, copy) {
461 if (!isRoomCode(code)) {
462 $.ui.log("room code: 3–64 letters, digits, . _ - · or /duet new");
463 return;
464 }
465 if (isPlaceholderName(nameArg)) {
466 $.ui.log(`"${nameArg}" is a placeholder · /duet ${code} <your name>`);
467 return;
468 }
469 if (relayArg && !isRelayUrl(relayArg)) {
470 $.ui.log(`bad relay ${sanitize(relayArg, 100)} · http(s) URL only, e.g. https://duet.gaioz.online`);
471 return;
472 }
473 const relay = (relayArg || server).replace(/\/+$/, "");
474 const name = fitName(nameArg || defaultName || "anon");
475 if (room) {
476 if (room.code === code && room.name === name && room.server === relay) return openPane($);
477 await leave($, true, false);
478 }
479 const gen = generation; // a leave or /duet off while this join is on its way: don't join after all
480 const key = `${relay} ${code} ${name}`;
481 const fromId = (await sha256hex(`${installId} ${key}`)).slice(0, 32);
482 const topic = await topicFor(code);
483
484 // No saved place in this room: listen from just before joining, so the others' answers to our
485 // join (sent within a second or two) aren't missed while the stream is still opening.
486 const saved = await $.store.get("cursor:" + key);
487 const cursor = saved ?? { id: "", time: Math.floor(Date.now() / 1000) - 2 };
488 const r = { code, name, key, fromId, topic, server: relay, mode: mode === "auto" ? "auto" : "ask", cursor };
489 try {
490 // The first network request: if the relay can't be reached, or this session's policy refuses
491 // network requests from mods, duet doesn't join.
492 await publish($, relay, topic, envelope({ fromId, from: name, kind: "join", via: "claude-code" }));
493 joinedAt = Date.now();
494 } catch (err) {
495 $.ui.log(`relay ${relay} unreachable: ${String(err?.message ?? err)} · not joined`);
496 $.ui.toast("duet: relay unreachable · not joined");
497 return;
498 }
499 if (gen !== generation || room) return;
500 room = r;
501 generation++;
502 queue = [];
503 carry = [];
504 events = [];
505 outbox = [];
506 peers.clear();
507 history = [];
508 autoTurns = 0;
509 paused = false;
510 pausedForTool = false;
511 heldCursor = null;
512 await $.store.set("room:" + cwd, { code, name, relay, at: Date.now() });
513 await $.store.set("name", name);
514 await $.store.set("active:" + sessionId, { code, name, mode: r.mode, relay });
515 defaultName = name;
516 wakeSupervisor?.();
517 remember($, { text: quiet ? `you rejoined as ${name}` : `you joined as ${name}`, note: true });
518 let copied = false;
519 if (copy) {
520 try {
521 copied = !!(await $.ui.copy({ text: code }))?.isCopied;
522 } catch {}
523 }
524 if (!quiet) $.ui.log(`joined ${code} as ${name}${copied ? " · code copied" : ""}`);
525 logToolOff($);
526 redraw($);
527 void deliver($).catch(() => {});
528}
529
530// A request already handed to Claude keeps running after a leave; its reply can't be sent once the
531// room is gone. forget: /duet off — the folder forgets its room.
532async function leave($, tell, forget) {
533 if (!room) return;
534 const r = room;
535 if (tell) void publish($, r.server, r.topic, envelope({ fromId: r.fromId, from: r.name, kind: "note", note: "left" })).catch(() => {});
536 await saveCursor($);
537 // A request taken but not yet handed to Claude stays with the room (its resume point is saved).
538 if (pendingPeer && !pendingPeer.submitted) pendingPeer = null;
539 await saveTurn($);
540 room = null;
541 generation++;
542 try {
543 child?.return?.();
544 } catch {}
545 child = null;
546 connected = false;
547 queue = [];
548 heldCursor = null;
549 await $.store.delete("active:" + sessionId);
550 if (forget) await $.store.delete("room:" + cwd);
551 redraw($);
552}
553
554async function setMode($, mode) {
555 if (!room) {
556 $.ui.log("not in a room · /duet new or /duet <code>");
557 return;
558 }
559 room.mode = mode;
560 autoTurns = 0;
561 paused = false;
562 pausedForTool = false;
563 const active = await $.store.get("active:" + sessionId);
564 if (active) await $.store.set("active:" + sessionId, { ...active, mode });
565 $.ui.log(mode === "auto" ? `auto · no gates · max ${MAX_AUTO} in a row` : "ask · both gates on");
566 redraw($);
567 void deliver($).catch(() => {});
568}
569
570// ---------- what the user does with a card ----------
571
572// Gate 1: a press acts at once on every waiting message, from every sender, in arrival order.
573// "take" (Process), "take-send" (Process and send), "ignore".
574let choosing = false; // a gate-1 press is checking the send tool: a second press waits its turn
575async function choose($, action) {
576 if (choosing) return;
577 const envs = [...queue];
578 if (!envs.length || !room) return;
579 const r = room;
580 const gen = generation; // /duet off bumps it at once: a press whose check was still running then does nothing
581 const take = action === "take" || action === "take-send";
582 if (take && busyWithPeer()) {
583 $.ui.toast("duet: busy with the last request");
584 return;
585 }
586 // No send tool here: Claude would have no way to answer but another tool. Keep the request waiting.
587 if (take) {
588 choosing = true;
589 let ready = false;
590 try {
591 ready = await sendToolReady($);
592 } finally {
593 choosing = false;
594 }
595 if (!ready) {
596 // The line above the prompt stays; the toast answers this press.
597 $.ui.toast("duet: " + toolOffText());
598 return;
599 }
600 // The check waited: a leave, another press or a turn may have come in meanwhile.
601 if (gen !== generation || room !== r || !envs.every((e) => queue.includes(e))) return;
602 if (busyWithPeer()) {
603 $.ui.toast("duet: busy with the last request");
604 return;
605 }
606 }
607 queue = queue.filter((e) => !envs.includes(e));
608 if (take) await startPeerTurn($, envs, action === "take-send");
609 else {
610 // Ignored: nothing goes to the other side, like a person not answering.
611 redraw($);
612 await saveCursor($);
613 }
614}
615
616// Gate 2: the press that settles a waiting reply.
617function decide($, item, decision) {
618 if (!item || item.decision) return;
619 item.decision = decision;
620 redraw($);
621}
622
623// Hold the send tool's call until the user presses Send or Don't send. The hook's time limit stops
624// while a mods API call is in flight and runs on through a promise of the mod's own (and through
625// $.clock.sleep), so the wait sits inside short blocking processes: `sleep` (macOS, Linux, Git Bash),
626// else `ping` to this computer (Windows' own, System32: about a second a round), else PowerShell's
627// Start-Sleep. A waiter that can't start is dropped for the rest of this module's life; one that
628// fails (a non-zero exit, its time limit) is dropped only after WAITER_FAILS in a row, so one hiccup
629// doesn't move the wait to a slower one. Each has a short time limit of its own: `ping -n 2` on
630// Linux/macOS never ends by itself. Only with none of them left does the wait fall back to
631// $.clock.sleep, which counts against the hook's 10 s; the hook's .catch then refuses the send
632// (fails closed).
633const WAITERS = [
634 { argv: ["sleep", "0.25"], timeoutMs: 2000 },
635 { argv: ["ping", "-n", "2", "127.0.0.1"], timeoutMs: 3000 },
636 { argv: ["powershell", "-NoProfile", "-NonInteractive", "-Command", "Start-Sleep -Milliseconds 250"], timeoutMs: 5000 },
637];
638const WAITER_FAILS = 3;
639let waiter = 0; // the first of WAITERS not yet given up on here
640let waiterFails = 0; // failures in a row of WAITERS[waiter]
641async function awaitDecision($, item, signal) {
642 const decision = await waitForPress($, item, signal);
643 // The hook's budget may have run out (the tool already answered "Not sent: duet error") while a
644 // press came in: never send after that.
645 return signal?.aborted ? "stopped" : decision;
646}
647async function waitForPress($, item, signal) {
648 while (!item.decision) {
649 if (signal?.aborted) return "stopped";
650 if (!room) return "left";
651 // A module reload (a plugin update) while this reply waits: the new module never draws this
652 // card, so settle the call, unsent, instead of holding it until Esc.
653 let current = "";
654 try {
655 current = (await $.env.get("DUET_MODULE")) || "";
656 } catch {}
657 if (current && current !== moduleId) return "reloaded";
658 if (item.decision) break;
659 if (waiter < WAITERS.length) {
660 let missing = false;
661 try {
662 const r = await $.process.run(WAITERS[waiter].argv, { timeoutMs: WAITERS[waiter].timeoutMs });
663 if (r.exitCode === 0) {
664 waiterFails = 0;
665 continue;
666 }
667 } catch (err) {
668 missing = /ENOENT|not found|cannot find|no such file/i.test(String(err?.message ?? err));
669 }
670 if (missing || ++waiterFails >= WAITER_FAILS) {
671 waiter++;
672 waiterFails = 0;
673 }
674 continue;
675 }
676 try {
677 await $.clock.sleep(250, signal ? { signal } : undefined);
678 } catch {
679 return signal?.aborted ? "stopped" : "reloaded";
680 }
681 }
682 return item.decision;
683}
684
685async function openPane($) {
686 await $.ui.open({ id: PANE, title: "duet", focus: true, closeOnEscape: true });
687 redraw($);
688}
689
690// Back in the room after a restart, without asking: the folder remembers its room until /duet off.
691async function autoRejoin($) {
692 if (room || joinOffer || !(await canDraw($))) return;
693 const rec = await $.store.get("room:" + cwd);
694 if (!rec?.code || room) return; // a join started while this looked
695 await join($, rec.code, rec.name, "ask", true, rec.relay);
696}
697
698// The website's prompt writes ~/.duet/join.json: the agent runs the prompt's command, and when that
699// turn ends the file is looked at, so the card shows with no reload (a fresh install needs
700// /reload-plugins, which is a start). Looked at only at a start, a reload and the end of a turn,
701// never polled: whichever Claude Code looks next takes it (emptied at once).
702// Taking it never joins: it shows the card "Join <room> as <name>? · <folder>" (1 Join, 2 Ignore), so a
703// room is joined by the user's own hand even when something else wrote the file. In a room already,
704// the card says which room it leaves.
705async function takeJoinFile($) {
706 const path = `${duetDir}/join.json`;
707 let text;
708 try {
709 if (!(await $.fs.exists(path))) return false;
710 text = String(await $.fs.read(path));
711 } catch {
712 return false;
713 }
714 const got = readJoinFile(text, "claude-code", Date.now());
715 if (!got) return false;
716 try {
717 await $.fs.write(path, "{}");
718 } catch {
719 return false;
720 }
721 if (!got.take) return false;
722 joinOffer = { ...got.take, question: joinQuestion({ ...got.take, folder: cwd }, home) };
723 logToolOff($);
724 redraw($);
725 return true;
726}
727
728// The join card's press: 1 joins (ask mode), 2 drops it (the file is already gone either way).
729function answerJoinOffer($, yes) {
730 const o = joinOffer;
731 joinOffer = null;
732 redraw($);
733 if (!o) return;
734 if (yes) void join($, o.room, o.name, "ask", false, o.relay).catch(() => {});
735 else void autoRejoin($).catch(() => {}); // a start that showed the card first: back to the folder's room
736}
737
738// The send tool: registered first thing in session.start (before anything that could throw or wait),
739// and checked again before a request is handed to Claude. Seen on a Mac (2026-10-07, issue #33):
740// a session where Claude had no mcp__duet__send, and on Process it reached for another duet tool (a
741// claude.ai connector) instead. Never silently: a refusal is said.
742const SEND_SPEC = {
743 name: "send",
744 description:
745 "Send a message to the other agent(s) in your duet room (another developer's coding agent on their computer). " +
746 "Use it to answer a duet request, or when your user asks you to tell the other side something. " +
747 "Your text replies are seen only by your own user; this tool is the only way to reach the other side. " +
748 "Send one complete reply when you're done, not progress updates or several small messages; split only if it is over ~3.5 KB. " +
749 "In ask mode your user sees the whole reply and presses Send or Don't send; if they don't send it, don't send it again.",
750 inputSchema: {
751 type: "object",
752 properties: {
753 text: { type: "string", description: "The message. Split longer content into several calls." },
754 to: { type: "string", description: "Recipient name, if the room has more than one other person." },
755 },
756 required: ["text"],
757 },
758};
759let sendToolError = "";
760// The send tool missing from Claude's tools, seen on a Mac (issue #33): ~/.claude.json had
761// projects["<folder>"].disabledMcpServers = ["duet"] (switched off in /mcp there), so Claude Code
762// never connects the server $.tool.register runs. Said on a line above the prompt that stays (while
763// in a room or offered one) and once in the transcript; requests wait. Looked at again on every
764// Process press and every TOOL_POLL_MS while missing; the line goes once the tool is there.
765const TOOL_POLL_MS = 10_000;
766const MCP_SERVER = "duet"; // the server name $.tool.register gives this plugin's tools
767let toolOff = null; // null while the tool is there (or Claude Code can't say); { switchedOff } while missing
768let toolPoll = null;
769let toolOffLogged = false;
770let toolSeen = 0; // bumped each time the tool is found: an older "missing" answer then doesn't count
771let pausedForTool = false; // auto paused only because the tool was missing: resumes when it is back (any other pause or unpause clears it)
772const toolOffText = () =>
773 toolOff?.switchedOff
774 ? "duet's send tool is switched off in /mcp for this folder · /mcp → duet → Enable · requests wait until then"
775 : "duet's send tool is off in this folder · /mcp → duet → Enable, or /reload-plugins · requests wait until then";
776// Said only where it matters: in a room, or with a Join card up.
777const toolOffShown = () => !!toolOff && !!(room || joinOffer);
778
779// Is "duet" in this folder's disabledMcpServers in Claude Code's global config (read only, never
780// written)? Claude Code keys it by the git checkout's root, else by the folder it started in.
781// false whenever it can't be told.
782async function mcpSwitchedOff($) {
783 try {
784 const dir = ((await $.env.get("CLAUDE_CONFIG_DIR")) || home).replace(/\/+$/, "");
785 if (!dir) return false;
786 const projects = JSON.parse(String(await $.fs.read(`${dir}/.claude.json`)))?.projects;
787 if (!projects || typeof projects !== "object") return false;
788 let key = cwd;
789 try {
790 const top = await $.process.run(["git", "-C", cwd, "rev-parse", "--show-toplevel"], { timeoutMs: 3000 });
791 if (top.exitCode === 0 && top.stdout.trim()) key = top.stdout.trim();
792 } catch {}
793 const entry = Object.hasOwn(projects, key) ? projects[key] : undefined;
794 const list = entry?.disabledMcpServers;
795 return Array.isArray(list) && list.includes(MCP_SERVER);
796 } catch {
797 return false;
798 }
799}
800
801function logToolOff($) {
802 if (!toolOffShown() || toolOffLogged) return;
803 toolOffLogged = true;
804 $.ui.log(toolOffText());
805}
806
807async function noteToolOff($) {
808 const seen = toolSeen;
809 const switchedOff = await mcpSwitchedOff($);
810 if (seen !== toolSeen) return; // found meanwhile (a Process press, the timer)
811 const changed = !toolOff || toolOff.switchedOff !== switchedOff;
812 toolOff = { switchedOff };
813 if (changed) toolOffLogged = false;
814 if (!toolPoll) toolPoll = $.clock.every(TOOL_POLL_MS, () => void checkSendTool($).catch(() => {}));
815 logToolOff($);
816 redraw($);
817}
818
819function noteToolOn($) {
820 toolSeen++;
821 toolPoll?.cancel?.();
822 toolPoll = null;
823 if (!toolOff) return;
824 const said = toolOffLogged;
825 toolOff = null;
826 toolOffLogged = false;
827 if (said) $.ui.log("duet's send tool is on · requests can be processed");
828 if (pausedForTool) {
829 pausedForTool = false;
830 paused = false;
831 void deliver($).catch(() => {});
832 }
833 redraw($);
834}
835
836// true / false, or null when Claude Code can't say (no tool list).
837async function hasSendTool($) {
838 try {
839 return (await $.tool.list()).some((t) => t.name === SEND_TOOL);
840 } catch {
841 return null;
842 }
843}
844
845// The start's check and the slow timer's: only looks (registering again waits up to 8 s).
846async function checkSendTool($) {
847 const has = await hasSendTool($);
848 if (has === true) noteToolOn($);
849 else if (has === false && !toolOff) await noteToolOff($); // still missing: nothing new to read
850}
851
852async function registerSendTool($) {
853 try {
854 await $.tool.register(SEND_SPEC);
855 sendToolError = "";
856 return true;
857 } catch (err) {
858 sendToolError = String(err?.message ?? err);
859 return false;
860 }
861}
862// Is the send tool among the tools Claude can call now? Registered again if not. true when Claude
863// Code can't say (no tool list): the hand-over isn't held up on a guess.
864// Switched off in /mcp: registering again changes nothing (and waits up to 8 s), so it is skipped.
865async function sendToolReady($) {
866 const first = await hasSendTool($);
867 if (first === true) noteToolOn($);
868 if (first !== false) return true;
869 if (!(await mcpSwitchedOff($))) {
870 await registerSendTool($);
871 if ((await hasSendTool($)) !== false) {
872 noteToolOn($);
873 return true;
874 }
875 }
876 await noteToolOff($);
877 return false;
878}
879
880// ---------- the send tool ----------
881
882async function sendTool($, e, signal) {
883 if (!room) return { result: "Not sent: not in a duet room" };
884 const raw = String(e.text ?? "");
885 if (raw.length > MAX_TEXT) return { result: `Not sent: ${raw.length} characters, limit ${MAX_TEXT} · send the key part, or split it` };
886 // What goes out is exactly what the gate 2 card shows: no control or invisible characters.
887 const text = sanitize(raw, MAX_TEXT).trim();
888 if (!stripHidden(raw).text.trim()) return { result: "Not sent: empty" };
889 if (text.length > MAX_TEXT) return { result: `Not sent: ${text.length} characters, limit ${MAX_TEXT} · send the key part, or split it` };
890 const to = typeof e.to === "string" && e.to.trim() ? e.to.trim() : undefined;
891 // `to` comes from the model: only the name of someone in the room (it shows on the card, the
892 // spinner and the toast, and a name nobody has would reach no one).
893 if (to !== undefined && !isName(to)) return { result: "Not sent: bad name in to" };
894 if (to !== undefined && !livePeers().some(([n]) => n === to)) return { result: `Not sent: no ${to} in the room · in it: ${peerList() || "no one yet"}` };
895 const fromPeer = !!peerTurn;
896 if (fromPeer && peerTurn.roomKey !== room.key) return { result: "Not sent: request from a room you left · tell your user" };
897 const r = room;
898 // "Process and send": the user OK'd this request's reply ahead. Only the first send of its turn
899 // that reaches exactly its sender; used up before any await, so two sends in parallel can't both use it.
900 const live = livePeers().map(([n]) => n);
901 const reaches = to ?? (live.length === 1 ? live[0] : "");
902 const ownTurn = fromPeer && peerTurn.turnId === runningTurn && !e.agentId; // the main loop's turn, not a subagent's
903 const preTo = ownTurn && !autoActive() && peerTurn.preSend && reaches === peerTurn.preSend ? peerTurn.preSend : "";
904 const preSent = !!preTo;
905 if (preSent) {
906 peerTurn.preSend = "";
907 await saveTurn($); // a module reload must not bring it back
908 }
909 // What was OK'd is a reply to the sender: it goes to the sender only, even without `to`.
910 const sendTo = to ?? (preTo || undefined);
911 // Gate 2, in ask mode: the whole reply waits above the prompt for Send / Don't send. Without
912 // `to` a reply reaches everyone in the room, so the card names everyone.
913 if (!autoActive() && !preSent) {
914 const item = { id: randomId(), text, to: to ?? (peerList() || "the room"), decision: "" };
915 outbox = [...outbox, item];
916 $.ui.toast(`duet: reply to ${oneLine(item.to)} waiting`);
917 redraw($);
918 let decision;
919 try {
920 decision = await awaitDecision($, item, signal);
921 } finally {
922 outbox = outbox.filter((x) => x !== item);
923 redraw($);
924 }
925 if (decision === "drop") return { result: "Not sent: your user said no · don't resend" };
926 if (decision === "reloaded") return { result: "Not sent: duet restarted · send it again" };
927 if (decision !== "send") return { result: "Not sent" };
928 if (room !== r) return { result: "Not sent: left the room" };
929 }
930 try {
931 // Working on a peer's request: say which message this answers (the latest from that sender).
932 const asked = fromPeer && peerTurn?.answers ? peerTurn.answers.filter((m) => !sendTo || m.from === sendTo).at(-1) : undefined;
933 const env = envelope({ fromId: r.fromId, from: r.name, kind: "msg", text, by: "agent", ...(sendTo ? { to: sendTo } : {}), ...(asked ? { re: asked.id } : {}) });
934 await publish($, r.server, r.topic, env);
935 sent.set(env.id, firstLine(text));
936 if (sent.size > 200) sent.delete(sent.keys().next().value);
937 } catch (err) {
938 return { result: "Not sent: " + String(err?.message ?? err) };
939 }
940 // A reply sent on "Process and send" says so, in History and in what Claude reads.
941 remember($, { who: preSent ? "you · auto" : "you", text });
942 redraw($);
943 return { result: `Sent to ${sendTo ?? (peerList() || "the room")}${preSent ? " (auto)" : ""}${text.endsWith(HIDDEN_MARK) ? " · hidden characters removed" : ""}` };
944}
945
946// ---------- drawing ----------
947
948const AMBER = "#e9b45a";
949const BLUE = "#8eb1ff";
950
951// A long text as Text rows: every line, each under the 10,000-character limit of one Text child.
952function textRows(Text, text, keyPrefix) {
953 const rows = [];
954 sanitize(text, MAX_TEXT).split("\n").forEach((line, i) => {
955 for (let at = 0, j = 0; at < Math.max(line.length, 1); at += 5000, j++) rows.push(Text({ key: `${keyPrefix}${i}.${j}`, children: [line.slice(at, at + 5000) || " "] }));
956 });
957 return rows;
958}
959
960// About how many rows a text takes at this width, wrapped.
961function rowsFor(text, columns) {
962 const w = Math.max(columns - 4, 20);
963 return String(text).split("\n").reduce((n, l) => n + Math.max(1, Math.ceil(l.length / w)), 0);
964}
965
966function drawCard($, e) {
967 const { Box, Text, Button } = $.ui.resolve(e);
968 const frame = (color, children) => Box({ flexDirection: "column", borderStyle: "round", borderColor: color, paddingX: 1, children });
969 const buttons = (list) => Box({ flexDirection: "row", columnGap: 3, flexWrap: "wrap", children: list });
970 // A join file taken: the user's own press joins. Under any card of the room this window is in.
971 const offerCard = () =>
972 joinOffer &&
973 frame(BLUE, [
974 // Not cut to oneLine's 200: the relay must stay on the card (joinQuestion caps the folder itself).
975 Text({ bold: true, children: [`${sanitize(joinOffer.question, 1000).replace(/\n/g, " ")}${room ? ` · leaves ${oneLine(room.code)}` : ""}`] }),
976 buttons([
977 Button({ key: "join-offer", label: "Join", hotkey: "1", plain: true, onPress: () => answerJoinOffer($, true) }),
978 Button({ key: "join-ignore", label: "Ignore", hotkey: "2", plain: true, onPress: () => answerJoinOffer($, false) }),
979 ]),
980 ]);
981 if (!room) return offerCard() || null;
982 // Gate 2 first: Claude's tool call is waiting on it.
983 if (outbox.length) {
984 const item = outbox[0];
985 const more = outbox.length > 1 ? ` · +${outbox.length - 1}` : "";
986 const title = Text({ bold: true, children: [`Send to ${oneLine(item.to)}? · full reply${more}`] });
987 const keys = buttons([
988 Button({ key: "send", label: "Send", hotkey: "1", plain: true, onPress: () => decide($, item, "send") }),
989 Button({ key: "dont-send", label: "Don't send", hotkey: "2", plain: true, onPress: () => decide($, item, "drop") }),
990 ]);
991 const body = textRows(Text, item.text, "r");
992 // A bare digit presses only Buttons inside the band's window: a reply taller than the band
993 // keeps the keys under the title, where the window starts.
994 const fits = rowsFor(item.text, e.props?.bodyColumns ?? 80) + 4 <= (e.props?.maxRows ?? 10);
995 return frame(BLUE, fits ? [title, ...body, keys] : [title, keys, ...body]);
996 }
997 if (pendingPeer && !pendingPeer.submitted) {
998 const p = pendingPeer;
999 return frame(AMBER, [
1000 Text({ bold: true, children: [`${p.envs[0].from} · starts when Claude is free`] }),
1001 buttons([Button({ key: "cancel-waiting", label: "Cancel", hotkey: "2", plain: true, onPress: () => void cancelWaiting($).catch(() => {}) })]),
1002 ]);
1003 }
1004 if (expected.length && !peerTurn) return frame(AMBER, [Text({ dimColor: true, children: [`${expected[0].froms.join(", ")} · handed to Claude`] })]);
1005 if (queue.length && autoActive()) return frame(AMBER, [Text({ dimColor: true, children: [`${queue.length} waiting · auto`] })]);
1006 if (queue.length) {
1007 // Gate 1.
1008 const group = queue; // every waiting message, from every sender, in arrival order: one press takes them all
1009 const env = group[0];
1010 const froms = [...new Set(group.map((g) => g.from))];
1011 const via = viaLabel(peers.get(env.from)?.via);
1012 const reply = (g) => (g.reLine ? [Text({ dimColor: true, children: [`↳ re “${sanitize(g.reLine, 80)}”`] })] : []);
1013 // Every word Claude would get on "Process": the whole text of each message, every line, wrapped,
1014 // never cut to the band's width or a line count (a peer could hide an instruction past the cut).
1015 // With more than one sender, each message says who sent it.
1016 const label = (g) => (froms.length > 1 ? [Text({ dimColor: true, children: [`${oneLine(g.from)} · ${timeOf(g.ts)}`] })] : []);
1017 const body = group.flatMap((g, i) => [...(i > 0 ? [Text({ key: `sep${i}`, dimColor: true, children: ["—"] })] : []), ...label(g), ...reply(g), ...textRows(Text, g.text, `q${i}.`)]);
1018 // Claude Code draws a band up to 100,000 characters: past that the card can't show every word, so it says so.
1019 const chars = group.reduce((n, g) => n + g.text.length, 0);
1020 if (chars > BAND_CHARS) body.unshift(Text({ key: "clip", dimColor: true, children: [`${chars.toLocaleString("en-US")} characters: the band shows the first ${BAND_CHARS.toLocaleString("en-US")} · /duet History has every word`] }));
1021 const head = Box({
1022 flexDirection: "row",
1023 justifyContent: "space-between",
1024 children: [
1025 Box({ flexDirection: "row", children: [Text({ bold: true, color: AMBER, children: [oneLine(froms.join(", "))] }), Text({ dimColor: true, children: [`${froms.length === 1 && via ? " · " + via : ""} · ${timeOf(env.ts)}${paused ? " · auto paused" : ""}`] })] }),
1026 ...(group.length > 1 ? [Text({ dimColor: true, children: [`${group.length} messages`] })] : []),
1027 ],
1028 });
1029 const keys = buttons([
1030 Button({ key: "take", label: "Process", hotkey: "1", plain: true, onPress: () => void choose($, "take").catch(() => {}) }),
1031 Button({ key: "ignore", label: "Ignore", hotkey: "2", plain: true, onPress: () => void choose($, "ignore").catch(() => {}) }),
1032 // 3, not 2: a habit press of 2 (Ignore here, Don't send on the reply card) must never skip gate 2.
1033 Button({ key: "take-send", label: "Process and send", hotkey: "3", plain: true, onPress: () => void choose($, "take-send").catch(() => {}) }),
1034 ]);
1035 // As gate 2: a request taller than the band keeps its keys under the title, inside the window.
1036 const rows = group.reduce((n, g, i) => n + rowsFor(g.text, e.props?.bodyColumns ?? 80) + (g.reLine ? 1 : 0) + (froms.length > 1 ? 1 : 0) + (i > 0 ? 1 : 0), 0);
1037 const fits = rows + 4 <= (e.props?.maxRows ?? 10);
1038 return frame(AMBER, fits ? [head, ...body, keys] : [head, keys, ...body]);
1039 }
1040 return offerCard() || null;
1041}
1042
1043// Two tabs: 1 History (read-only) and 2 Settings (c copy code, a ask/auto, l leave).
1044function drawPane($, e) {
1045 const { Box, Text, Button } = $.ui.resolve(e);
1046 const blank = Text({ children: [" "] });
1047 if (!room) {
1048 return Box({
1049 flexDirection: "column",
1050 children: [Text({ children: ["Not in a room"] }), Text({ dimColor: true, children: ["/duet new · /duet <code> [name]"] })],
1051 });
1052 }
1053 const tabButton = (name, label, hotkey) =>
1054 Button({
1055 key: "tab-" + name,
1056 label,
1057 hotkey,
1058 plain: true,
1059 dimColor: tab !== name,
1060 onPress: () => {
1061 tab = name;
1062 paneNote = "";
1063 redraw($);
1064 },
1065 });
1066 const ps = livePeers();
1067 const head = Box({
1068 flexDirection: "row",
1069 justifyContent: "space-between",
1070 children: [
1071 Box({ flexDirection: "row", columnGap: 3, children: [tabButton("history", "History", "1"), tabButton("settings", "Settings", "2")] }),
1072 Text({ dimColor: true, children: [ps.length ? "with " + ps.map(([n]) => n).join(", ") : "no one yet"] }),
1073 ],
1074 });
1075 let body;
1076 if (tab === "settings") {
1077 const row = (label, value) => Box({ flexDirection: "row", children: [Box({ width: 10, children: [Text({ dimColor: true, children: [label] })] }), value] });
1078 const relayHost = room.server.replace(/^https?:\/\//, "");
1079 body = [
1080 row("Room", Text({ children: [room.code] })),
1081 row("You", Text({ children: [room.name] })),
1082 row(
1083 "Relay",
1084 connected
1085 ? Box({ flexDirection: "row", children: [Text({ color: "green", children: ["● "] }), Text({ children: [relayHost] })] })
1086 : Box({ flexDirection: "row", children: [Text({ color: "red", children: ["○ "] }), Text({ children: [`${relayHost} · ${connError ? sanitize(connError, 80) : "offline"}`] })] }),
1087 ),
1088 row(
1089 "Gates",
1090 Box({ flexDirection: "row", columnGap: 1, children: [Text({ bold: room.mode === "ask", dimColor: room.mode !== "ask", children: ["ask"] }), Text({ bold: room.mode === "auto", dimColor: room.mode !== "auto", children: [`auto${paused ? " (paused)" : ""}`] })] }),
1091 ),
1092 blank,
1093 Box({
1094 flexDirection: "row",
1095 columnGap: 3,
1096 flexWrap: "wrap",
1097 children: [
1098 Button({
1099 key: "copy",
1100 label: "Copy code",
1101 hotkey: "c",
1102 plain: true,
1103 onPress: (press) =>
1104 void (async () => {
1105 let ok = false;
1106 try {
1107 ok = !!(await $.ui.copy({ text: room?.code ?? "", surface: press?.surface }))?.isCopied;
1108 } catch {}
1109 paneNote = ok ? "code copied" : "copy failed";
1110 redraw($);
1111 })(),
1112 }),
1113 Button({ key: "mode", label: "Ask / auto", hotkey: "a", plain: true, onPress: () => void setMode($, room?.mode === "auto" ? "ask" : "auto").catch(() => {}) }),
1114 Button({
1115 key: "leave",
1116 label: "Leave",
1117 hotkey: "l",
1118 plain: true,
1119 onPress: () => {
1120 generation++;
1121 void leave($, true, true).catch(() => {});
1122 },
1123 }),
1124 ],
1125 }),
1126 ...(paneNote ? [Text({ dimColor: true, children: [paneNote] })] : []),
1127 ];
1128 } else {
1129 body = history.length
1130 ? history.map((h, i) =>
1131 h.note
1132 ? Text({ key: "h" + i, dimColor: true, children: [`${timeOf(h.at)} ${sanitize(h.text, 300)}`] })
1133 : Box({
1134 key: "h" + i,
1135 flexDirection: "column",
1136 children: [Box({ flexDirection: "row", children: [Text({ bold: true, color: h.who === "you" ? BLUE : AMBER, children: [h.who] }), Text({ dimColor: true, children: [" " + timeOf(h.at)] })] }), ...textRows(Text, h.text, `h${i}.`)],
1137 }),
1138 )
1139 : [Text({ dimColor: true, children: ["Nothing yet"] })];
1140 }
1141 return Box({ flexDirection: "column", children: [head, blank, ...body, blank, Text({ dimColor: true, children: [tab === "settings" ? "Esc" : "/duet off · Esc"] })] });
1142}
1143
1144function modeLabel() {
1145 if (!room) return "";
1146 const ps = peerList() || "no one yet";
1147 // Both gates: requests (gate 1) and replies (gate 2) waiting for the user.
1148 const n = queue.length + carry.length + outbox.length;
1149 const waiting = n ? ` · ${n} waiting` : "";
1150 return `duet · ${ps} · ${room.mode}${paused ? " · paused" : ""}${waiting}${connected ? "" : " · offline"}`;
1151}
1152
1153// No turn of this process or conversation is running: forget what a crashed or other one left.
1154async function clearTurn($) {
1155 if (!sessionId) sessionId = await $.session.id();
1156 pendingPeer = null;
1157 expected = [];
1158 peerTurn = null;
1159 runningTurn = "";
1160 await saveTurn($);
1161 redraw($);
1162}
1163
1164// ---------- hooks ----------
1165
1166// Resolved once session.start has its settings; /duet (registered before them) waits for it.
1167let markReady = () => {};
1168let ready = Promise.resolve();
1169
1170export function register(on) {
1171 on("session.start", async ($, e, next) => {
1172 // First: a /duet typed (or given on the command line) as Claude Code starts must find the
1173 // command. Registered after the work below, it lost that race on a Mac (seen 2026-10-04).
1174 try {
1175 await $.command.register({ name: "duet", description: "Pair with another developer's agent: /duet new, /duet <room>, /duet off", argumentHint: "[new | <room> [name] [relay] | off | ask | auto | status]", immediate: true });
1176 } catch {}
1177 ready = new Promise((r) => (markReady = r));
1178 if (!(await registerSendTool($))) $.ui.log(`duet: the send tool didn't register (${sanitize(sendToolError, 120)}) · /reload-plugins`);
1179 cwd = e.cwd || (await $.session.cwd());
1180 home = (await $.env.get("HOME")) || (await $.env.get("USERPROFILE")) || "";
1181 duetDir = ((await $.env.get("DUET_HOME")) || `${home.replace(/\/+$/, "")}/.duet`).replace(/\\/g, "/");
1182 // The registration has waited (Claude Code holds it up to 8 s): is the tool among Claude's?
1183 void checkSendTool($).catch(() => {});
1184 const relay = (await $.env.get("DUET_SERVER")) || "";
1185 // The website's line starts Claude Code with the room in DUET_ROOM / DUET_NAME. Read once, then
1186 // cleared: nothing Claude Code starts (a shell, pi, an MCP server) inherits them, and a /clear
1187 // doesn't join again.
1188 const envRoom = (await $.env.get("DUET_ROOM")) || "";
1189 const envName = (await $.env.get("DUET_NAME")) || "";
1190 if (envRoom) await $.env.set("DUET_ROOM", "");
1191 if (envName) await $.env.set("DUET_NAME", "");
1192 if (relay && isRelayUrl(relay)) server = relay.replace(/\/+$/, "");
1193 installId = (await $.store.get("install")) || "";
1194 if (!installId) {
1195 installId = randomId();
1196 await $.store.set("install", installId);
1197 }
1198 sessionId = await $.session.id();
1199
1200 defaultName = (await $.store.get("name")) || "";hooks/wire.js 267 lines1// The duet wire format for the Claude Code mod: pure functions, no `node:` imports, no mods API.
2// It must stay compatible with transport.js (pi, the MCP server): same topic hash, same envelope.
3// pi and the MCP server drop `kind: "note"` (their isEnvelope rejects it) and ignore the fields they
4// don't know (`by`), so everything here is safe to send to them.
5
6export const DEFAULT_SERVER = "https://duet.gaioz.online"; // the duet relay (ntfy), run by the author
7// Longer messages still go out as one: the relay stores the body as an attachment (ntfy does that
8// above 4096 bytes; ntfy.sh keeps them 3 h, up to 2 MB) and receivers fetch it. Same as transport.js.
9export const MAX_BYTES = 256_000;
10export const MAX_TEXT = 200_000;
11// Unattended peer-started turns allowed in auto mode before duet falls back to asking.
12export const MAX_AUTO = 8;
13// A Text string child may hold at most 10,000 characters; keep well under.
14export const MAX_SHOWN = 6000;
15
16export const NOTES = ["left"]; // the only note left on the wire: a leave. Older clients' other notes are dropped.
17
18const NAME = /^[\p{L}\p{N}][\p{L}\p{M}\p{N}._-]{0,39}$/u;
19// No hidden characters either (\p{M} holds the variation selectors and the grapheme joiner): a name
20// goes into every prompt and form unchanged.
21export const isName = (name) => typeof name === "string" && NAME.test(name) && !stripHidden(name).hidden;
22export const isPlaceholderName = (name) => typeof name === "string" && /^your[-_ ]?name$/i.test(name);
23export const fitName = (name) =>
24 isName(name)
25 ? name
26 : Array.from(stripHidden(name).text.normalize("NFC").replace(/[^\p{L}\p{M}\p{N}._-]+/gu, "-").replace(/^[^\p{L}\p{N}]+/u, ""))
27 .slice(0, 40)
28 .join("") || "anon";
29
30export function isRelayUrl(url) {
31 return /^https?:\/\/[A-Za-z0-9.-]+(:\d{1,5})?(\/[A-Za-z0-9._~\/-]*)?$/.test(url);
32}
33
34// Words that mean "leave" in /duet (pi uses /duet off). None of them can be a room name.
35export const LEAVE_WORDS = ["off", "leave", "stop", "disable", "quit", "exit"];
36
37// A room code is the shared secret: 3-64 letters, digits, . _ -, not a leave word. The same rule as
38// transport.js isRoomCode (Codex, pi, the MCP servers, the join file): test/mod-unit.mjs compares them.
39export const isRoomCode = (room) =>
40 typeof room === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{2,63}$/.test(room) && !LEAVE_WORDS.includes(room.toLowerCase());
41
42// The join file (~/.duet/join.json) the website's prompt writes: { agent, room, name, relay, at }
43// with `at` in Unix seconds. Read once, at a start or a reload, never polled. "take" ({ room, name,
44// relay }: shown on a card, never joined by itself), "clear" (stale, from the future, or not for this
45// agent) or null (unreadable). Whichever Claude Code loads next takes it; the card names this folder.
46export const JOIN_FRESH_S = 30 * 60;
47export function readJoinFile(text, agent, nowMs) {
48 let j;
49 try {
50 j = JSON.parse(text);
51 } catch {
52 return null;
53 }
54 if (!j || typeof j !== "object" || typeof j.at !== "number") return null;
55 const age = nowMs / 1000 - j.at;
56 if (!(age >= 0 && age <= JOIN_FRESH_S)) return { clear: true };
57 if (j.agent !== agent) return null; // another client's (pi, Codex): theirs to take
58 const relay = typeof j.relay === "string" ? j.relay.replace(/\/+$/, "") : "";
59 if (!isRoomCode(j.room) || !isName(j.name) || isPlaceholderName(j.name) || !isRelayUrl(relay)) return null;
60 return { take: { room: j.room, name: j.name, relay } };
61}
62
63// "Join <room> as <name>? · <folder>", with "· relay <host>" before the folder when it isn't duet's
64// own relay. The folder is this window's own (home as ~), one line, its end kept.
65const FOLDER_MAX = 60;
66export function joinQuestion({ room, name, relay, folder }, home = "") {
67 let where = String(folder ?? "").replace(/\/+$/, "") || "/";
68 const h = String(home ?? "").replace(/\/+$/, "");
69 if (h && (where === h || where.startsWith(h + "/"))) where = "~" + where.slice(h.length);
70 where = where.replace(/\s+/g, " ");
71 if (where.length > FOLDER_MAX) where = "…" + where.slice(-(FOLDER_MAX - 1));
72 let relayHost = "";
73 if (relay && relay !== DEFAULT_SERVER) {
74 try {
75 relayHost = new URL(relay).host;
76 } catch {
77 relayHost = String(relay);
78 }
79 if (relay.startsWith("http://")) relayHost = "http://" + relayHost;
80 }
81 return cleanText(`Join ${room} as ${name}?${relayHost ? ` · relay ${relayHost}` : ""} · ${where}`).replace(/\s+/g, " ");
82}
83
84const hex = (bytes) => Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join("");
85
86export async function sha256hex(text) {
87 return hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
88}
89
90// The room name is the shared secret; only its hash ever reaches the server. Same as transport.js.
91export async function topicFor(room) {
92 return "duet_" + (await sha256hex("pi-duet:" + room)).slice(0, 40);
93}
94
95export function randomId() {
96 if (typeof crypto.randomUUID === "function") return crypto.randomUUID();
97 const b = crypto.getRandomValues(new Uint8Array(16));
98 b[6] = (b[6] & 0x0f) | 0x40;
99 b[8] = (b[8] & 0x3f) | 0x80;
100 const h = hex(b);
101 return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
102}
103
104const WORDS = [
105 "amber", "birch", "cedar", "delta", "ember", "fjord", "grove", "heron", "indigo", "juniper", "kelp", "lumen",
106 "maple", "nectar", "onyx", "pebble", "quartz", "raven", "sage", "tidal", "umber", "violet", "willow", "zephyr",
107 "otter", "lynx", "falcon", "badger", "marten", "osprey", "puffin", "walrus", "yak", "gecko", "bison", "crane",
108];
109
110// A fresh room code like "amber-otter-4821-x7q2": 2 words + 4 digits + 4 base-36 chars (~50 bits).
111export function newRoomCode() {
112 const r = crypto.getRandomValues(new Uint32Array(4));
113 const tail = (r[3] >>> 0).toString(36).padStart(4, "0").slice(-4);
114 return `${WORDS[r[0] % WORDS.length]}-${WORDS[r[1] % WORDS.length]}-${String(r[2] % 10000).padStart(4, "0")}-${tail}`;
115}
116
117// A long message's attachment, accepted only when it is a real upload on this very relay (same rules
118// as transport.js attachmentUrl): same origin, path exactly <relay path>/file/<id>[.ext], no query,
119// and a size. Anyone can post an attachment that points anywhere.
120export function attachmentUrl(a, server, max) {
121 if (!a || typeof a.url !== "string" || typeof a.size !== "number" || a.size > max) return null;
122 let u, base;
123 try {
124 u = new URL(a.url);
125 base = new URL(server);
126 } catch {
127 return null;
128 }
129 const path = base.pathname.replace(/\/+$/, "");
130 if (u.origin !== base.origin || u.search || u.hash || u.username || u.password) return null;
131 return new RegExp(`^${path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}/file/[A-Za-z0-9]+(\\.[A-Za-z0-9]+)?$`).test(u.pathname) && !/\/\.\.?\//.test(a.url) ? u.href : null;
132}
133
134// The first line of a text, short: how a reply names the message it answers.
135export const firstLine = (text) => {
136 const line = String(text).split("\n").find((l) => l.trim()) ?? "";
137 return line.length > 80 ? line.slice(0, 79) + "…" : line;
138};
139
140export function envelope(fields) {
141 return { v: 1, id: randomId(), ...fields, ts: new Date().toISOString() };
142}
143
144export function isEnvelope(e) {
145 if (
146 e?.v !== 1 ||
147 typeof e.fromId !== "string" ||
148 typeof e.from !== "string" ||
149 !isName(e.from) ||
150 typeof e.ts !== "string" ||
151 (e.to !== undefined && typeof e.to !== "string") ||
152 (e.re !== undefined && typeof e.re !== "string")
153 )
154 return false;
155 if (e.kind === "join") return true;
156 if (e.kind === "msg") return typeof e.text === "string" && e.text.length <= MAX_TEXT && !e.text.includes("\0");
157 if (e.kind === "note") return NOTES.includes(e.note);
158 return false;
159}
160
161// Drop our own echoes (by install id) and messages addressed to someone else.
162export function isForMe(env, myFromId, myName) {
163 if (env.fromId === myFromId) return false;
164 return !env.to || env.to.normalize("NFC").toLowerCase() === myName.normalize("NFC").toLowerCase();
165}
166
167export const byteLength = (s) => new TextEncoder().encode(s).length;
168
169// The one cleaner for the other side's text: a copy of transport.js's (the mod can't import from
170// outside hooks/); test/mod-unit.mjs checks that both agree. Removed: ANSI escapes, control characters
171// but tab and newline (C0, C1, U+2028/2029), format characters (\p{Cf}: bidi controls, zero-width,
172// tags), every default-ignorable code point (variation selectors, CGJ, Hangul fillers, Mongolian FVS,
173// the whole tag block) and the blank Braille cell: each draws as nothing while a model still reads it.
174// Text built from them can carry a whole hidden instruction. Anything removed leaves a visible mark.
175export const HIDDEN = /\x1b\[[0-9;?]*[ -\/]*[@-~]|[\x00-\x08\x0b-\x1f\x7f-\x9f\u2028\u2029\u2800\u{E0000}-\u{E0FFF}]|\p{Cf}|\p{Default_Ignorable_Code_Point}/gu;
176export const HIDDEN_MARK = " [hidden characters removed]";
177export function stripHidden(text) {
178 let hidden = false;
179 const clean = String(text ?? "")
180 .replace(/\r\n?/g, "\n")
181 .replace(HIDDEN, () => ((hidden = true), ""));
182 return { text: clean, hidden };
183}
184export function cleanText(text) {
185 const r = stripHidden(text);
186 return r.hidden ? r.text + HIDDEN_MARK : r.text;
187}
188
189// Peer text is untrusted: Text refuses control characters other than tab and newline (and an invalid
190// tree silently falls back to the engine's drawing), so they go (stripHidden), and the length is capped.
191// A card shows every word Claude gets (gate 1) and every word a reply sends (gate 2): the same
192// function makes both.
193export function sanitize(text, max = MAX_SHOWN) {
194 const { text: clean, hidden } = stripHidden(text);
195 const cut = clean.length > max ? clean.slice(0, max) + `… [${clean.length - max} more characters]` : clean;
196 return hidden ? cut + HIDDEN_MARK : cut;
197}
198
199// The first `lines` lines of a text, each cut to `width`, for the card above the prompt.
200export function preview(text, lines = 4, width = 160, hint = " — /duet to read all") {
201 const all = sanitize(text).split("\n");
202 const total = String(text ?? "").replace(/\r\n?/g, "\n").split("\n").length; // before sanitize shortens it
203 let cut = String(text ?? "").length > MAX_SHOWN; // sanitize shortened it
204 const shown = all.slice(0, lines).map((l) => {
205 if (l.length <= width) return l;
206 cut = true;
207 return l.slice(0, width - 1) + "…";
208 });
209 // Say so whenever anything is left out, not only whole lines.
210 if (total > lines) shown.push(`… (${total - lines} more lines${hint})`);
211 else if (cut) shown.push(`… (cut${hint})`);
212 return shown.join("\n");
213}
214
215const clock = (ts) => {
216 const t = Date.parse(ts);
217 if (Number.isNaN(t)) return "";
218 const d = new Date(t);
219 return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
220};
221export const timeOf = clock;
222
223// Characters of message text one hand-over carries at most. More waiting is handed over in order,
224// as much as fits a turn; the rest comes in the next turn and the frame says how many.
225export const HANDOVER_MAX = 100_000;
226
227// Split waiting messages into what one hand-over carries (always at least the first) and the rest.
228export function fitHandover(envs, max = HANDOVER_MAX) {
229 let total = 0;
230 let n = 0;
231 for (const e of envs) {
232 total += String(e.text ?? "").length;
233 if (n > 0 && total > max) break;
234 n++;
235 }
236 return { take: envs.slice(0, n), rest: envs.slice(n) };
237}
238
239// What Claude reads when duet starts a turn. The engine puts "The duet plugin sent a message:" above
240// it, so Claude knows this isn't its own user. Observed: asked to work "in your folder", the model
241// used the home directory — so the folder is named.
242// info: { room: [{ name, via }], me, events: [{ name, what: "joined" | "left", via, ts, seq }], more }.
243// Joins and leaves are ordinary items of the hand-over, in arrival order with the messages (by seq).
244export function frameForClaude(envs, cwd, tool, info = {}) {
245 const froms = [...new Set(envs.map((e) => e.from))].join(", ");
246 const room = (info.room ?? []).map((p) => `${sanitize(p.name, 80)}${p.via ? ` (${sanitize(p.via, 40)})` : ""}`).join(", ");
247 const head = `[duet] In this room: ${room || "no one else yet"}${info.me ? ` · you are ${sanitize(info.me, 80)}` : ""}`;
248 const items = [
249 ...envs.map((e) => ({ seq: e._seq ?? 0, text: messageItem(e) })),
250 ...(info.events ?? []).map((ev) => ({ seq: ev.seq ?? 0, text: `[duet] ${sanitize(ev.name, 80)} ${ev.what}${ev.what === "joined" && ev.via ? ` (${sanitize(ev.via, 40)})` : ""}${clock(ev.ts) ? ", " + clock(ev.ts) : ""}` })),
251 ].sort((a, b) => a.seq - b.seq);
252 const more = info.more > 0 ? `${info.more} more message${info.more === 1 ? "" : "s"} waiting: they come in your next turn.\n\n` : "";
253 return (
254 `${head}\n\n${items.map((i) => i.text).join("\n\n---\n\n")}\n\n${more}` +
255 `Only your own user sees your text replies: to answer ${froms}, call the ${tool} tool. ` +
256 `Answer only with ${tool}, never another duet tool or connector. If ${tool} is missing, tell your user so and don't send. ` +
257 `Send one complete reply when you're done.`
258 );
259}
260
261function messageItem(e) {
262 const who = e.by === "person" ? "the other person, typing to you directly" : "the other person's agent, on their computer";
263 const at = clock(e.ts);
264 const answers = e.reLine ? ` — a reply to your message “${sanitize(e.reLine, 100)}”` : "";
265 return `[duet] from ${e.from} (${who})${at ? ", " + at : ""}${answers}:\n\n${sanitize(e.text, MAX_TEXT)}`;
266}
267