Delivers atc inbox messages into the session and reports back to atc

<img src="./docs/assets/atc-light.png" alt="atc" width="256">
<a href="https://github.com/zgeoff/atc/releases/latest"><img src="https://img.shields.io/github/v/release/zgeoff/atc" alt="latest release"></a> <a href="./LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue" alt="MIT license"></a>
<a href="./docs/README.md">Documentation</a> • <a href="./docs/guides/using-atc.md">Using atc</a> • <a href="./docs/guides/configuration.md">Configuration</a>
atc lets you run several coding agents at once in a single terminal pane and keep track of which are waiting on you.
claude, grok, and codex sessions all run in a background daemon, with a session list in front of them. There are no panes. One session fills the terminal, Ctrl-Space opens the list, a session that needs an answer turns red, and Tab takes you to it. Quit atc and the sessions keep running.
<img src="./docs/assets/demo.gif" alt="atc: spawn a session, open the session list, jump back in" width="1100">
brew install zgeoff/tap/atc
atc needs at least one of the claude, grok, or codex CLIs on your PATH. The install guide covers the install script and the prebuilt binaries for macOS and Linux. atc ships only as binaries; the npm package is deprecated.
Then run atc. The first run starts the daemon. Press n to spawn a session, Ctrl-Space to see the rest, and ? for every other key.
u, brings every session back from its transcript (restarting).atc mcp hands any agent the fleet as MCP tools, so it can spawn, read, and message other sessions (agents that drive agents).atc mcp --http serves the same tools to ChatGPT or Claude.ai behind OAuth, with the scopes you approve (remote MCP).atc events prints every fleet event, and config.json hooks run your own commands on them (events).atc creates ~/.config/atc/config.json on first run. The configuration guide covers every field: the agents and their arguments, the leader key, targets, gateways, principals, and hooks.
docs/ covers how atc works, the guides, and the runbooks.
hooks/register.ts 877 lines1import type { EngineInterface, Register, TurnStepResult } from 'claude-code';
2import { ATC_CLI } from './atc-cli.ts';
3
4const SENDER_KINDS = ['connector', 'session', 'local', 'owner'] as const;
5
6// Who sent a message, as atc built it from the caller: its kind, and the atc
7// id of a session that sent it.
8interface TapSender {
9 readonly kind: (typeof SENDER_KINDS)[number];
10 readonly session: string | undefined;
11}
12
13interface TapMessage {
14 readonly id: string;
15 readonly from: string;
16 readonly sender: TapSender | undefined;
17 readonly text: string;
18}
19
20const NOTICE_STATUSES = ['answered', 'unanswered'] as const;
21
22interface TapNotice {
23 readonly id: string;
24 readonly from: string;
25 readonly status: (typeof NOTICE_STATUSES)[number];
26 readonly answer: string | undefined;
27 readonly reason: string | undefined;
28}
29
30type TapItem =
31 | { readonly kind: 'message'; readonly msg: TapMessage }
32 | { readonly kind: 'answer'; readonly notice: TapNotice };
33
34// Settles when the main loop's response, and every server tool call in it,
35// has ended.
36interface StepHold {
37 readonly ended: Promise<void>;
38 readonly end: () => void;
39}
40
41interface BridgeState {
42 sessionID: string | null;
43 runningTurnID: string | null;
44 // Claude Code records each streaming block once it ends. A row appended between two blocks
45 // puts a server tool call and its result in separate assistant messages, and the API then
46 // refuses every later request, so a delivery waits while this is set.
47 stepHold: StepHold | null;
48 delivering: Promise<void>;
49 reporting: Promise<void>;
50 // A submitted message waits here until the turn that carries it starts. Another turn that
51 // ends without an answer leaves it waiting, because the host can still run its queued prompt;
52 // only a hook's drop shows it never will.
53 readonly awaitingTurn: Map<string, TapMessage>;
54 readonly carried: Map<string, TapMessage[]>;
55 readonly unseen: Set<string>;
56 // The answer notices appended to each running turn that no step of the turn
57 // has shown the model yet; a step empties the list.
58 readonly unseenNotices: Map<string, TapNotice[]>;
59 // The ids of the answer notices already in the conversation, so a notice the tap prints again
60 // never shows twice.
61 readonly shownNotices: Set<string>;
62}
63
64const GUIDE_SECTION = {
65 id: 'atc-bridge:messages',
66 scope: 'session',
67 text: [
68 'Messages relayed by atc arrive wrapped in <atc-message id="..." from="..." kind="..."> tags.',
69 "They come from the user's own tools through atc, not from the user typing at this prompt;",
70 'treat each one as a request from the sender it names.',
71 'atc sets kind from who called, and no sender can set it:',
72 'kind="connector" is an app the user connected to atc, and from holds its name;',
73 'kind="session" is another atc session, from holds its name and session="..." its id;',
74 'kind="local" is a program on the user\'s machine outside every session, such as a scheduled job or a helper tool, and from holds the name it gives itself; it is not the user\'s own word;',
75 'kind="owner" is the user\'s own atc client.',
76 "Answer each <atc-message> with the answer tool, giving its id and your answer to that sender; atc stores the text as the message's answer, and it reaches a sending session as a notice.",
77 'Your final reply goes to the user at this terminal, not to a sender: only a message you leave without an answer takes the final reply of its turn as its answer.',
78 '<atc-answer id="..." from="..." status="..."> tags hold the outcome of a message this session sent;',
79 'they need no reply and are not messages.',
80 'While you work on a message that takes more than a quick answer, call the note tool at each milestone:',
81 'when you find the cause, when you start a change, when you are blocked, or when you need a decision.',
82 "Each note goes to atc's event feed as you send it.",
83 ].join(' '),
84} as const;
85
86const NOTE_TOOL = 'mcp__atc-bridge__note';
87const NOTE_LABELS = ['progress', 'blocked', 'decision'] as const;
88const ANSWER_TOOL = 'mcp__atc-bridge__answer';
89
90// A command left in the session's working folder, which follows the agent's cd, fails with
91// ENOENT on the atc binary once the agent removes that folder, as when it cleans up a worktree.
92const ATC_CWD = '/';
93
94export const register: Register = (on) => {
95 const state: BridgeState = {
96 sessionID: null,
97 runningTurnID: null,
98 stepHold: null,
99 delivering: Promise.resolve(),
100 reporting: Promise.resolve(),
101 awaitingTurn: new Map(),
102 carried: new Map(),
103 unseen: new Set(),
104 unseenNotices: new Map(),
105 shownNotices: new Set(),
106 };
107
108 on('session.start', async ($, e, next) => {
109 const sessionID = await $.env.get('ATC_SESSION_ID');
110
111 if (sessionID === undefined || sessionID === '') {
112 return next(e);
113 }
114
115 try {
116 await $.tool.register({
117 name: 'note',
118 description:
119 "Add a short note to atc's event feed while you keep working, so a reader of the feed sees progress before your final reply. Use it at milestones: when you find the cause, start a change, get blocked or need a decision. It does not answer a message or reach its sender: the answer tool does that. Do not repeat an answer or your final reply here. The result shows only that the note was handed to atc, not that it reached the event feed or a reader.",
120 inputSchema: {
121 type: 'object',
122 properties: {
123 text: {
124 type: 'string',
125 description: "The note's text; atc refuses empty text and cuts text over 64 KiB.",
126 },
127 label: {
128 type: 'string',
129 enum: [...NOTE_LABELS],
130 description:
131 'progress (the default) for a milestone, blocked when you cannot go on, or decision when you need a choice made',
132 },
133 },
134 required: ['text'],
135 },
136 });
137
138 await $.tool.register({
139 name: 'answer',
140 description:
141 "Answer one <atc-message> with your own text before your turn ends: atc stores the text as that message's answer, and a sending session gets it as an <atc-answer> notice. Call it once for each message the turn carries; your final reply then goes to the user at this terminal, and only a message you leave without an answer takes the final reply as its answer. Use note instead for progress that answers nothing. The result shows only that the answer was handed to atc, not that atc stored it or that the sender read it. It refuses an id that the running turn does not carry, a message that already has an answer, and empty text; a refused call changes nothing, so one message takes one answer.",
142 inputSchema: {
143 type: 'object',
144 properties: {
145 message: {
146 type: 'string',
147 description: 'The id attribute of the <atc-message> tag to answer.',
148 },
149 text: {
150 type: 'string',
151 description:
152 "The answer's text, for the sender; atc refuses empty text and cuts text over 64 KiB.",
153 },
154 },
155 required: ['message', 'text'],
156 },
157 });
158 } catch (error) {
159 $.ui.log(
160 `atc-bridge: off for this session, the Claude Code build refused it (${String(error)})`,
161 {
162 to: 'debug',
163 },
164 );
165
166 return next(e);
167 }
168
169 state.sessionID = sessionID;
170
171 const started = await next(e);
172
173 void runTap($, state, sessionID);
174
175 return started;
176 });
177
178 on('prompt.compose', async ($, e, next) => {
179 const composed = await next(e);
180
181 return state.sessionID === null
182 ? composed
183 : { sections: [...composed.sections, GUIDE_SECTION] };
184 });
185
186 on('turn.start', async ($, e, next) => {
187 const started = await next(e);
188
189 if (state.sessionID !== null) {
190 updateTurnStarted(state, e.turnId, e.text);
191 }
192
193 return started;
194 });
195
196 on('turn.step', async function* updateStepState($, e, next) {
197 if (e.agentId !== undefined) {
198 return yield* next(e);
199 }
200
201 if (e.turnId === state.runningTurnID) {
202 for (const msg of state.carried.get(e.turnId) ?? []) {
203 state.unseen.delete(msg.id);
204 }
205
206 state.unseenNotices.get(e.turnId)?.splice(0);
207 }
208
209 updateStepStarted(state);
210
211 let isServerToolRunning = false;
212
213 try {
214 const stepped = yield* next(e);
215
216 isServerToolRunning = isServerToolUnfinished(stepped);
217
218 return stepped;
219 } finally {
220 // A paused response's server tool call goes on in the next step, so the
221 // hold stays until that step ends.
222 if (!isServerToolRunning) {
223 updateStepEnded(state);
224 }
225 }
226 });
227
228 on('turn.complete', async ($, e, next) => {
229 const completed = await next(e);
230
231 if (e.agentId === undefined) {
232 updateStepEnded(state);
233 }
234
235 if (state.sessionID !== null && e.agentId === undefined) {
236 updateTurnCompleted($, state, e.turnId, e.answer, e.reason);
237 }
238
239 return completed;
240 });
241
242 on('tool.call', { tool: NOTE_TOOL }, async ($, e) => {
243 const text = typeof e['text'] === 'string' ? e['text'].trim() : '';
244 const label = typeof e['label'] === 'string' ? e['label'].trim() : 'progress';
245
246 if (text === '') {
247 return { deny: 'note needs non-empty text' };
248 }
249
250 if (!isNoteLabel(label)) {
251 return {
252 deny: `note label must be ${NOTE_LABELS.slice(0, -1).join(', ')} or ${NOTE_LABELS.at(-1)}`,
253 };
254 }
255
256 try {
257 await $.process.run([...ATC_CLI, 'note', '--label', label], {
258 cwd: ATC_CWD,
259 stdin: text,
260 timeoutMs: 5000,
261 });
262 } catch (error) {
263 return { deny: `atc did not take the note: ${String(error)}` };
264 }
265
266 return { result: 'Handed to atc for its event feed.' };
267 });
268
269 on('tool.call', { tool: ANSWER_TOOL }, async ($, e) => {
270 const messageID = typeof e['message'] === 'string' ? e['message'].trim() : '';
271 const text = typeof e['text'] === 'string' ? e['text'] : '';
272
273 if (text.trim() === '') {
274 return { deny: 'answer needs non-empty text' };
275 }
276
277 const turnID = state.runningTurnID;
278 const carried = turnID === null ? undefined : state.carried.get(turnID);
279 const msg = carried?.find((x) => x.id === messageID);
280
281 if (carried === undefined || msg === undefined) {
282 return {
283 deny: `answer takes the id of an <atc-message> the running turn carries that has no answer yet, not "${messageID}"`,
284 };
285 }
286
287 // The message leaves the turn before the call, so a second answer for it
288 // is refused and the turn's final reply never answers it.
289 removeCarriedMessage(carried, msg);
290
291 state.unseen.delete(msg.id);
292
293 const failure = await tryRunAnswer($, msg.id, text);
294
295 if (failure !== null) {
296 // A turn that ended during the call no longer reports the message, so
297 // the failed answer settles it instead of leaving it delivered.
298 if (state.carried.get(turnID ?? '') === carried) {
299 carried.push(msg);
300 } else {
301 scheduleUnansweredReport($, state, [msg.id], 'error', turnID);
302 }
303
304 return { deny: `atc did not take the answer: ${failure}` };
305 }
306
307 return { result: `Handed to atc as the answer to ${msg.id}.` };
308 });
309};
310
311// A step that continues a paused response keeps the hold the paused step left.
312function updateStepStarted(state: BridgeState): void {
313 if (state.stepHold !== null) {
314 return;
315 }
316
317 const { promise, resolve } = Promise.withResolvers<void>();
318
319 state.stepHold = { ended: promise, end: resolve };
320}
321
322function updateStepEnded(state: BridgeState): void {
323 state.stepHold?.end();
324 state.stepHold = null;
325}
326
327// The API pauses a long response before a server tool call's result, and the
328// engine sends the response back to go on: the call has no end yet.
329function isServerToolUnfinished(stepped: TurnStepResult): boolean {
330 return (
331 stepped.stopReason === 'pause_turn' ||
332 (stepped.serverToolUses ?? []).some((use) => use.endedAt === undefined)
333 );
334}
335
336function removeCarriedMessage(carried: TapMessage[], msg: TapMessage): void {
337 carried.splice(carried.indexOf(msg), 1);
338}
339
340// Why atc did not take the answer, or null once it did. The reporter always
341// exits 0, so its printed delivery result shows whether atc took the answer.
342async function tryRunAnswer(
343 $: EngineInterface,
344 messageID: string,
345 text: string,
346): Promise<string | null> {
347 try {
348 const ran = await $.process.run([...ATC_CLI, 'answer', '--message', messageID], {
349 cwd: ATC_CWD,
350 stdin: text,
351 timeoutMs: 5000,
352 });
353
354 if (ran.exitCode !== 0) {
355 return `atc exited with ${String(ran.exitCode)}`;
356 }
357
358 return ran.stdout.trim() === 'delivered' ? null : 'the answer did not reach atc';
359 } catch (error) {
360 return String(error);
361 }
362}
363
364function isNoteLabel(value: string): value is (typeof NOTE_LABELS)[number] {
365 return NOTE_LABELS.some((label) => label === value);
366}
367
368const FIRST_TAP_RETRY_MS = 1000;
369const LONGEST_TAP_RETRY_MS = 30_000;
370
371// atc refuses every message to a session whose tap never attached, and atc tap exits 0 only
372// once atc closed the inbox for good, so any other end starts the tap again.
373async function runTap($: EngineInterface, state: BridgeState, sessionID: string): Promise<void> {
374 let wait = FIRST_TAP_RETRY_MS;
375
376 for (;;) {
377 const failure = await runTapOnce($, state, sessionID);
378
379 if (failure === null) {
380 $.ui.log('atc-bridge: atc tap ended; this session takes no more atc messages', {
381 to: 'debug',
382 });
383
384 return;
385 }
386
387 $.ui.log(`atc-bridge: atc tap failed (${failure}); starting it again in ${wait}ms`, {
388 to: 'debug',
389 });
390
391 // An unload of the mod rejects the wait, and the next load starts its own tap.
392 try {
393 await $.clock.sleep(wait);
394 } catch {
395 return;
396 }
397
398 wait = Math.min(wait * 2, LONGEST_TAP_RETRY_MS);
399 }
400}
401
402async function runTapOnce(
403 $: EngineInterface,
404 state: BridgeState,
405 sessionID: string,
406): Promise<string | null> {
407 const tap = $.process.spawn({
408 argv: [...ATC_CLI, 'tap', '--session', sessionID, '--notices'],
409 cwd: ATC_CWD,
410 });
411
412 let pending = '';
413 let stderr = '';
414
415 try {
416 for await (const chunk of tap) {
417 if (chunk.stream !== 'stdout') {
418 stderr = `${stderr}${chunk.text}`.slice(-1000);
419 continue;
420 }
421
422 const lines = `${pending}${chunk.text}`.split('\n');
423
424 pending = lines.pop() ?? '';
425
426 for (const line of lines) {
427 const item = parseTapLine(line);
428
429 if (item?.kind === 'message') {
430 scheduleDelivery($, state, item.msg);
431 } else if (item?.kind === 'answer') {
432 scheduleNoticeDelivery($, state, item.notice);
433 }
434 }
435 }
436
437 const exit = await tap.result;
438
439 if (exit.code === 0) {
440 return null;
441 }
442
443 const reason = exit.signal ?? `exit ${String(exit.code)}`;
444 const said = stderr.trim();
445
446 return said === '' ? reason : `${reason}: ${said}`;
447 } catch (error) {
448 return String(error);
449 }
450}
451
452function parseTapLine(line: string): TapItem | null {
453 let parsed: unknown;
454
455 try {
456 parsed = JSON.parse(line);
457 } catch {
458 return null;
459 }
460
461 if (typeof parsed !== 'object' || parsed === null) {
462 return null;
463 }
464
465 // A line that declares a kind is never a message, whatever else it holds.
466 if ('kind' in parsed) {
467 const notice = parsed.kind === 'answer' ? parseTapNotice(parsed) : null;
468
469 return notice === null ? null : { kind: 'answer', notice };
470 }
471
472 if (!('id' in parsed) || !('from' in parsed) || !('text' in parsed)) {
473 return null;
474 }
475
476 if (
477 typeof parsed.id !== 'string' ||
478 typeof parsed.from !== 'string' ||
479 typeof parsed.text !== 'string'
480 ) {
481 return null;
482 }
483
484 const sender = 'sender' in parsed ? parseTapSender(parsed.sender) : undefined;
485
486 return { kind: 'message', msg: { id: parsed.id, from: parsed.from, sender, text: parsed.text } };
487}
488
489// A sender this mod cannot read is left out, and the message still goes out
490// with its sender's name.
491function parseTapSender(value: unknown): TapSender | undefined {
492 if (typeof value !== 'object' || value === null) {
493 return undefined;
494 }
495
496 const fields: Record<string, unknown> = { ...value };
497 const { kind, session } = fields;
498
499 if (typeof kind !== 'string' || !isSenderKind(kind)) {
500 return undefined;
501 }
502
503 if (kind !== 'session') {
504 return { kind, session: undefined };
505 }
506
507 return typeof session === 'string' ? { kind, session } : undefined;
508}
509
510function isSenderKind(value: string): value is TapSender['kind'] {
511 return SENDER_KINDS.some((kind) => kind === value);
512}
513
514function parseTapNotice(parsed: object): TapNotice | null {
515 const fields: Record<string, unknown> = { ...parsed };
516 const { id, from, status, answer, reason } = fields;
517
518 if (
519 typeof id !== 'string' ||
520 typeof from !== 'string' ||
521 typeof status !== 'string' ||
522 !isNoticeStatus(status) ||
523 (answer !== undefined && typeof answer !== 'string') ||
524 (reason !== undefined && typeof reason !== 'string')
525 ) {
526 return null;
527 }
528
529 return { id, from, status, answer, reason };
530}
531
532function isNoticeStatus(value: string): value is TapNotice['status'] {
533 return NOTICE_STATUSES.some((status) => status === value);
534}
535
536function scheduleDelivery($: EngineInterface, state: BridgeState, msg: TapMessage): void {
537 state.delivering = state.delivering
538 .then(() => sendMessage($, state, msg))
539 .catch((error: unknown) => {
540 $.ui.log(`atc-bridge: delivering ${msg.id} failed (${String(error)})`, { to: 'debug' });
541 });
542}
543
544async function sendMessage($: EngineInterface, state: BridgeState, msg: TapMessage): Promise<void> {
545 await waitForStepEnd(state);
546
547 const turnID = state.runningTurnID;
548
549 if (turnID !== null && (await tryUpdateConversation($, msg.id, renderEnvelope(msg)))) {
550 const carried = state.carried.get(turnID);
551
552 // The append can resolve after the turn completed; the turn then no
553 // longer reports or redelivers anything, so the message goes out as a
554 // fresh submit instead.
555 if (carried !== undefined && state.runningTurnID === turnID) {
556 carried.push(msg);
557 state.unseen.add(msg.id);
558
559 return;
560 }
561 }
562
563 state.awaitingTurn.set(msg.id, msg);
564
565 const submitted = await $.prompt.submit({ text: renderEnvelope(msg) });
566
567 if ('drop' in submitted && submitted.drop !== undefined) {
568 state.awaitingTurn.delete(msg.id);
569 $.ui.log(`atc-bridge: a hook dropped ${msg.id} (${submitted.drop})`, { to: 'debug' });
570
571 scheduleUnansweredReport($, state, [msg.id], 'not_started', null);
572 }
573}
574
575// A hold that ends lets the next delivery go, which a step that starts at once
576// can hold again.
577async function waitForStepEnd(state: BridgeState): Promise<void> {
578 while (state.stepHold !== null) {
579 await state.stepHold.ended;
580 }
581}
582
583async function tryUpdateConversation(
584 $: EngineInterface,
585 id: string,
586 text: string,
587): Promise<boolean> {
588 try {
589 const appended = await $.session.append({
590 message: { type: 'user', content: [{ type: 'text', text }] },
591 });
592
593 return appended.deny === undefined;
594 } catch (error) {
595 $.ui.log(`atc-bridge: appending ${id} failed (${String(error)}); submitting it instead`, {
596 to: 'debug',
597 });
598
599 return false;
600 }
601}
602
603function renderEnvelope(msg: TapMessage): string {
604 const body = msg.text.replaceAll('</atc-message>', '</atc-message>');
605
606 return `<atc-message id="${encodeAttribute(msg.id)}" from="${encodeAttribute(msg.from)}"${renderSenderAttributes(msg.sender)}>\n${body}\n</atc-message>`;
607}
608
609function renderSenderAttributes(sender: TapSender | undefined): string {
610 if (sender === undefined) {
611 return '';
612 }
613
614 const session =
615 sender.session === undefined ? '' : ` session="${encodeAttribute(sender.session)}"`;
616
617 return ` kind="${sender.kind}"${session}`;
618}
619
620function encodeAttribute(value: string): string {
621 return value
622 .replaceAll('&', '&')
623 .replaceAll('"', '"')
624 .replaceAll('<', '<')
625 .replaceAll('>', '>');
626}
627
628function scheduleNoticeDelivery($: EngineInterface, state: BridgeState, notice: TapNotice): void {
629 state.delivering = state.delivering
630 .then(() => sendNotice($, state, notice))
631 .catch((error: unknown) => {
632 $.ui.log(
633 `atc-bridge: delivering the answer notice for ${notice.id} failed (${String(error)})`,
634 {
635 to: 'debug',
636 },
637 );
638 });
639}
640
641// A notice never waits for a turn to start and never joins one's carried
642// messages, so no turn reports an answer for it. An appended notice stays in
643// the conversation, so it is never sent again; a turn that ends before a step
644// shows it leaves a reminder that names it instead.
645async function sendNotice(
646 $: EngineInterface,
647 state: BridgeState,
648 notice: TapNotice,
649): Promise<void> {
650 if (state.shownNotices.has(notice.id)) {
651 return;
652 }
653
654 await waitForStepEnd(state);
655
656 const turnID = state.runningTurnID;
657 const text = renderAnswerNotice(notice);
658
659 if (turnID !== null && (await tryUpdateConversation($, notice.id, text))) {
660 state.shownNotices.add(notice.id);
661
662 const unseen = state.unseenNotices.get(turnID);
663
664 if (unseen !== undefined && state.runningTurnID === turnID) {
665 unseen.push(notice);
666 } else {
667 scheduleNoticeReminder($, state, [notice.id]);
668 }
669
670 return;
671 }
672
673 const submitted = await $.prompt.submit({ text });
674
675 if ('drop' in submitted && submitted.drop !== undefined) {
676 $.ui.log(`atc-bridge: a hook dropped the answer notice for ${notice.id} (${submitted.drop})`, {
677 to: 'debug',
678 });
679
680 return;
681 }
682
683 state.shownNotices.add(notice.id);
684}
685
686// A prompt that wakes the model for notices already in its conversation,
687// which names them without repeating them.
688function scheduleNoticeReminder(
689 $: EngineInterface,
690 state: BridgeState,
691 messageIDs: readonly string[],
692): void {
693 const text = renderNoticeReminder(messageIDs);
694
695 state.delivering = state.delivering
696 .then(async () => {
697 const submitted = await $.prompt.submit({ text });
698
699 if ('drop' in submitted && submitted.drop !== undefined) {
700 $.ui.log(`atc-bridge: a hook dropped the reminder for ${messageIDs.join(', ')}`, {
701 to: 'debug',
702 });
703 }
704 })
705 .catch((error: unknown) => {
706 $.ui.log(
707 `atc-bridge: reminding of the answer notices for ${messageIDs.join(', ')} failed (${String(error)})`,
708 { to: 'debug' },
709 );
710 });
711}
712
713function renderNoticeReminder(messageIDs: readonly string[]): string {
714 const subject =
715 messageIDs.length === 1
716 ? `the answer notice for ${messageIDs.join('')}`
717 : `the answer notices for ${messageIDs.join(', ')}`;
718
719 return `atc added ${subject} to this conversation after your last reply. Read ${messageIDs.length === 1 ? 'it' : 'them'} above; atc does not send ${messageIDs.length === 1 ? 'it' : 'them'} again.`;
720}
721
722function renderAnswerNotice(notice: TapNotice): string {
723 const reason =
724 notice.status === 'unanswered' && notice.reason !== undefined
725 ? ` reason="${encodeAttribute(notice.reason)}"`
726 : '';
727
728 const body = (notice.answer ?? renderNoticeAdvice(notice)).replaceAll(
729 '</atc-answer>',
730 '</atc-answer>',
731 );
732
733 return `<atc-answer id="${encodeAttribute(notice.id)}" from="${encodeAttribute(notice.from)}" status="${encodeAttribute(notice.status)}"${reason}>\n${body}\n</atc-answer>`;
734}
735
736// A message whose session ended before it answered reaches no one unless
737// its sender sends it again, so the notice says so.
738function renderNoticeAdvice(notice: TapNotice): string {
739 return notice.status === 'unanswered' && notice.reason === 'session_ended'
740 ? 'This message has no answer, because its session ended before it answered. Send it again if you still need the answer.'
741 : '';
742}
743
744const ENVELOPE_ID = /<atc-message id="(?<id>[^"]+)"/gu;
745
746function updateTurnStarted(state: BridgeState, turnID: string, text: string): void {
747 const carried: TapMessage[] = [];
748
749 state.runningTurnID = turnID;
750
751 state.carried.set(turnID, carried);
752 state.unseenNotices.set(turnID, []);
753
754 for (const match of text.matchAll(ENVELOPE_ID)) {
755 const msg = state.awaitingTurn.get(match.groups?.['id'] ?? '');
756
757 if (msg !== undefined) {
758 state.awaitingTurn.delete(msg.id);
759 carried.push(msg);
760 }
761 }
762}
763
764function updateTurnCompleted(
765 $: EngineInterface,
766 state: BridgeState,
767 turnID: string,
768 answer: string,
769 reason: string,
770): void {
771 const carried = state.carried.get(turnID) ?? [];
772
773 state.carried.delete(turnID);
774
775 const unseenNotices = state.unseenNotices.get(turnID) ?? [];
776
777 if (unseenNotices.length > 0) {
778 scheduleNoticeReminder(
779 $,
780 state,
781 unseenNotices.map((notice) => notice.id),
782 );
783 }
784
785 state.unseenNotices.delete(turnID);
786
787 if (state.runningTurnID === turnID) {
788 state.runningTurnID = null;
789 }
790
791 const isAnswered = reason === 'answer';
792 const answered: string[] = [];
793 const unanswered: string[] = [];
794
795 for (const msg of carried) {
796 if (state.unseen.delete(msg.id)) {
797 scheduleDelivery($, state, msg);
798 } else if (isAnswered) {
799 answered.push(msg.id);
800 } else {
801 unanswered.push(msg.id);
802 }
803 }
804
805 // One answer carries every message the turn answered, so atc records the
806 // whole group at once and no member reads as answered before the rest.
807 if (answered.length > 0) {
808 scheduleAnsweredReport($, state, answered, turnID, answer);
809 }
810
811 if (unanswered.length > 0) {
812 scheduleUnansweredReport($, state, unanswered, toUnansweredReason(reason), turnID);
813 }
814}
815
816function toUnansweredReason(reason: string): string {
817 if (reason === 'aborted') {
818 return 'interrupted';
819 }
820
821 return reason === 'refusal' ? 'refusal' : 'error';
822}
823
824function scheduleAnsweredReport(
825 $: EngineInterface,
826 state: BridgeState,
827 messageIDs: readonly string[],
828 turnID: string,
829 answer: string,
830): void {
831 state.reporting = state.reporting
832 .then(async () => {
833 await $.process.run(
834 [...ATC_CLI, 'answer', '--messages', messageIDs.join(','), '--turn', turnID],
835 {
836 cwd: ATC_CWD,
837 stdin: answer,
838 timeoutMs: 5000,
839 },
840 );
841 })
842 .catch((error: unknown) => {
843 $.ui.log(`atc-bridge: reporting ${messageIDs.join(', ')} failed (${String(error)})`, {
844 to: 'debug',
845 });
846 });
847}
848
849function scheduleUnansweredReport(
850 $: EngineInterface,
851 state: BridgeState,
852 messageIDs: readonly string[],
853 reason: string,
854 turnID: string | null,
855): void {
856 state.reporting = state.reporting
857 .then(async () => {
858 await $.process.run(
859 [
860 ...ATC_CLI,
861 'unanswered',
862 '--messages',
863 messageIDs.join(','),
864 ...(turnID === null ? [] : ['--turn', turnID]),
865 '--reason',
866 reason,
867 ],
868 { cwd: ATC_CWD, timeoutMs: 5000 },
869 );
870 })
871 .catch((error: unknown) => {
872 $.ui.log(`atc-bridge: reporting ${messageIDs.join(', ')} failed (${String(error)})`, {
873 to: 'debug',
874 });
875 });
876}
877hooks/atc-cli.ts 2 lines1export const ATC_CLI: readonly string[] = ['atc'];
2