Skip to content

abso-core

Public

abso is version control for agents: the client, the engine and a server you can run on your own Cloudflare account.

Check passed
MCP
code on this site's /mcp
CLI
none: the JSON below is the answer
JSON
/christopher/abso-core/files/client/src/news-stream.ts?format=json
204 linesbox-grants 100%Last change box-grants in version 299, 6 versions changed it
1// abso news --stream and --follow (abso 690): news the moment it arrives, with no polling.
2//
3// The server holds a WebSocket per seat on the project's object. Opening one takes a ticket, minted with the seat's
4// key: it opens that seat's stream once, within a minute, and rides as a subprotocol, never in the URL. A Claude Code
5// Monitor can't send headers, and whatever its call names is written into the chat, so the key never goes there.
6//
7// --stream prints the Monitor's arguments with a fresh ticket. --follow holds the socket itself and prints a line per
8// item, opening a new one (with a new ticket) whenever it closes; the ticket is never printed. On connect the server
9// sends what arrived since the seat last heard its news, so nothing is lost between sockets.
11/** The subprotocol a news stream speaks; the ticket rides beside it as `abso-ticket.<ticket>`. */
12export const NEWS_PROTOCOL = "abso-news.1";
14/** What the server answers a ticket request with. */
15export interface NewsTicket {
16 readonly url: string;
17 readonly protocols: readonly string[];
18 /** When the ticket stops working: the server sends an ISO time; milliseconds are taken too. */
19 readonly expiresAt: number | string;
22/** A ticket's expiry in milliseconds, whichever form the server sent; now when it can't be read. */
23export function expiresAtMs(ticket: NewsTicket, now: number): number {
24 const at = typeof ticket.expiresAt === "number" ? ticket.expiresAt : Date.parse(ticket.expiresAt);
25 return Number.isFinite(at) ? at : now;
28/** A Monitor lasts at most 30 minutes; the skill re-arms it when it ends. */
29export const MONITOR_TIMEOUT_MS = 30 * 60_000;
31/** The Monitor call that holds a seat's stream: `Monitor({ ws, description, timeout_ms })`. */
32export function monitorArgs(
33 ticket: NewsTicket,
34 project: string,
35 agent: string,
36): { ws: { url: string; protocols: string[] }; description: string; timeout_ms: number } {
37 return {
38 ws: { url: ticket.url, protocols: [...ticket.protocols] },
39 description: `abso news for ${agent} in ${project}`,
40 timeout_ms: MONITOR_TIMEOUT_MS,
41 };
44/** The text --stream prints: the call to make, then the arguments as one line of JSON. */
45export function streamText(ticket: NewsTicket, project: string, agent: string, now = Date.now()): string {
46 const seconds = Math.max(0, Math.round((expiresAtMs(ticket, now) - now) / 1000));
47 return [
48 `Open this with Monitor within ${seconds} seconds (the ticket opens ${agent}'s news stream once). When the Monitor ends or the socket closes, run abso news --stream again; the new socket sends what arrived in between.`,
49 JSON.stringify(monitorArgs(ticket, project, agent)),
50 ].join("\n");
53/** The file that says this folder's seat holds its stream, until when: the abso-hooks mod's news poll skips meanwhile. */
54export const STREAM_MARK = "news-stream.json";
56/** How long --stream's mark holds: the Monitor's 30 minutes, and the minute the ticket waits to be used. */
57export function streamMarkUntil(ticket: NewsTicket, now: number): number {
58 return Math.max(now, expiresAtMs(ticket, now)) + MONITOR_TIMEOUT_MS;
61/** The part of a WebSocket --follow uses: the platform's own, or a test's. */
62export interface Socket {
63 onopen: (() => void) | null;
64 onmessage: ((e: { data: unknown }) => void) | null;
65 onclose: ((e: { code: number; reason: string }) => void) | null;
66 onerror: ((e: unknown) => void) | null;
67 send(text: string): void;
68 close(code?: number): void;
71/** A close the server sends for a revoked key or a fifth socket (1008): --follow stops instead of trying again. */
72export function isRefusal(code: number): boolean {
73 return code === 1008;
76/** How long --follow waits before opening a socket again: 1 s doubling to a minute; a socket that lived a minute resets it. */
77export function nextWait(previous: number, livedMs: number): number {
78 if (livedMs >= 60_000) return 1_000;
79 return Math.min(60_000, Math.max(1_000, previous * 2));
82/** The client sends this every PING_MS so an idle socket stays open; the object answers it without waking. */
83export const PING = "ping";
84export const PONG = "pong";
85export const PING_MS = 45_000;
87export interface FollowDeps {
88 mint(): Promise<NewsTicket>;
89 connect(url: string, protocols: readonly string[]): Socket;
90 /** One news item, as the server sent it. */
91 write(line: string): void;
92 /** A line about the stream itself, not news. */
93 note(line: string): void;
94 sleep(ms: number): Promise<void>;
95 now(): number;
96 every(ms: number, fn: () => void): () => void;
97 /** Reads the seat's news, marking it heard (POST news); a frame calls it. Without it, frames are printed as they come. */
98 take?(): Promise<readonly string[]>;
99 /** Called when a socket opens and at each ping: the stream is held until the next ping is due, and a little more. */
100 held?(until: number): void;
101 /** Set when --follow should stop (Ctrl-C, or a test). */
102 readonly stopped: () => boolean;
105/** Why a mint failed: a refused key, or a server with no news stream (404), stops --follow; anything else is tried again. */
106function refusedMint(err: unknown): boolean {
107 const status = (err as { status?: number }).status;
108 return status === 401 || status === 403 || status === 404;
111/**
112 * A frame is a wake (abso 690): on one, read the seat's news (which marks it heard) and print what that answers, one
113 * read at a time, with frames that arrive meanwhile folded into one more read. When the read answers nothing (a server
114 * that counts a frame as heard already, or another chat on the seat took it first), the frames themselves are printed.
115 */
116function frameReads(deps: FollowDeps): { frame(text: string): void; idle(): Promise<void> } {
117 let frames: string[] = [];
118 /** The lines printed lately, so a frame a read already printed isn't printed again. */
119 const shown: string[] = [];
120 const show = (line: string) => {
121 deps.write(line);
122 shown.push(line);
123 if (shown.length > 200) shown.shift();
124 };
125 let running: Promise<void> | undefined;
126 let again = false;
127 const pass = async () => {
128 do {
129 again = false;
130 const these = frames;
131 frames = [];
132 let items: readonly string[] = [];
133 try {
134 items = await deps.take!();
135 } catch (err) {
136 deps.note(`(abso news --follow: couldn't read the news: ${(err as Error).message}; showing the frames)`);
137 }
138 for (const line of items) show(line);
139 // A frame the read didn't cover still shows: on a server that counts a frame as heard, its item never comes back
140 // from the read. A catch-up frame names several items, so a frame holding a shown item counts as covered.
141 for (const frame of these) if (!shown.some((line) => frame.includes(line) || line.includes(frame))) show(frame);
142 } while (again);
143 running = undefined;
144 };
145 return {
146 frame(text) {
147 frames.push(text);
148 if (running !== undefined) again = true;
149 else running = pass();
150 },
151 idle: () => running ?? Promise.resolve(),
152 };
155/**
156 * Holds the seat's stream, printing one line per item, until the key is refused or `stopped()`.
157 * Returns why it ended.
158 */
159export async function follow(deps: FollowDeps): Promise<{ ended: "refused" | "stopped"; reason: string }> {
160 const reads = frameReads(deps);
161 let wait = 1_000;
162 while (!deps.stopped()) {
163 let ticket: NewsTicket;
164 try {
165 ticket = await deps.mint();
166 } catch (err) {
167 if (refusedMint(err)) return { ended: "refused", reason: (err as Error).message };
168 deps.note(`(abso news --follow: no ticket: ${(err as Error).message}; trying again in ${wait / 1000} s)`);
169 await deps.sleep(wait);
170 wait = nextWait(wait, 0);
171 continue;
172 }
173 const opened = deps.now();
174 const closed = await new Promise<{ code: number; reason: string }>((done) => {
175 const socket = deps.connect(ticket.url, ticket.protocols);
176 let stopPing = () => {};
177 socket.onopen = () => {
178 deps.held?.(deps.now() + 2 * PING_MS);
179 stopPing = deps.every(PING_MS, () => {
180 if (deps.stopped()) socket.close(1000);
181 else {
182 socket.send(PING);
183 deps.held?.(deps.now() + 2 * PING_MS);
184 }
185 });
186 };
187 socket.onmessage = (e) => {
188 if (typeof e.data !== "string" || e.data === PONG) return;
189 if (deps.take === undefined) deps.write(e.data);
190 else reads.frame(e.data);
191 };
192 socket.onerror = () => {};
193 socket.onclose = (e) => {
194 stopPing();
195 void reads.idle().then(() => done({ code: e.code, reason: e.reason }));
196 };
197 });
198 if (isRefusal(closed.code)) return { ended: "refused", reason: closed.reason || `closed ${closed.code}` };
199 if (deps.stopped()) break;
200 wait = nextWait(wait, deps.now() - opened);
201 await deps.sleep(wait);
202 }
203 return { ended: "stopped", reason: "stopped" };