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
show on this site's /mcp
CLI
abso show 269 --json
JSON
/christopher/abso-core/versions/269?format=json

abso news --stream and --follow (abso 690, news wakes agents): --stream mints a ticket and prints the Monitor call (ws URL plus subprotocols, 30-minute timeout) so a Claude Code chat wakes the moment news arrives, with no polling. --follow holds the seat's stream itself, a line per item, a new ticket per socket, a ping every 45 s, waits 1 s doubling to a minute between sockets, and stops on a refused key or a server without the stream (404). The key never goes in a URL or a Monitor call. Needs the server's news/ticket and news/stream routes (Read Speed, next). Tests: client/test/news-stream.test.ts.

of shared·box-grants··Not checked

Version 268 · Files at version 269

5 files, 350 lines added, 5 removed.

--- a/client/src/announce.ts
+++ b/client/src/announce.ts
@@ -6,6 +6,7 @@
66import { bool, type Parsed, str, UsageError } from "./args.ts";
77import { type Env, type Output, open, plural } from "./commands.ts";
88import { logNews } from "./folder.ts";
9+import { follow, monitorArgs, type Socket, streamText } from "./news-stream.ts";
910import { newsWithTime } from "./times.ts";
1011
1112export async function runAnnounce(args: Parsed, env: Env): Promise<Output> {
@@ -73,8 +74,49 @@
7374 return { text: lines.join("\n"), json: { ...answer } };
7475}
7576
76−export async function runNews(_args: Parsed, env: Env): Promise<Output> {
77− const { root, api } = open(env);
77+export async function runNews(args: Parsed, env: Env): Promise<Output> {
78+ const { root, config, api } = open(env);
79+ if (bool(args, "stream") && bool(args, "follow"))
80+ throw new UsageError("abso news takes --stream or --follow, not both");
81+ if (bool(args, "stream")) {
82+ const ticket = await api.newsTicket();
83+ return {
84+ text: streamText(ticket, config.project, config.agent),
85+ json: { monitor: monitorArgs(ticket, config.project, config.agent), expiresAt: ticket.expiresAt },
86+ };
87+ }
88+ if (bool(args, "follow")) {
89+ let stop = false;
90+ const onInt = () => {
91+ stop = true;
92+ };
93+ process.once("SIGINT", onInt);
94+ try {
95+ const ended = await follow({
96+ mint: () => api.newsTicket(),
97+ connect: (url, protocols) => new WebSocket(url, [...protocols]) as unknown as Socket,
98+ write: (line) => {
99+ logNews(root, [line]);
100+ env.write(`${line.replace(/\r?\n/g, " ")}\n`);
101+ },
102+ note: (line) =>
103+ env.write(`${line}
104+`),
105+ sleep: (ms) => new Promise((ok) => setTimeout(ok, ms)),
106+ now: () => Date.now(),
107+ every: (ms, fn) => {
108+ const t = setInterval(fn, ms);
109+ return () => clearInterval(t);
110+ },
111+ stopped: () => stop,
112+ });
113+ return ended.ended === "refused"
114+ ? { text: `The news stream refused this seat: ${ended.reason}`, json: ended, exit: 2 }
115+ : { text: "", json: ended };
116+ } finally {
117+ process.off("SIGINT", onInt);
118+ }
119+ }
78120 const answer = await api.news();
79121 const news = newsLines(answer.news);
80122 logNews(root, news);
--- a/client/src/api.ts
+++ b/client/src/api.ts
@@ -977,6 +977,11 @@
977977 return this.json("POST", this.agentPath("news"), {});
978978 }
979979
980+ /** A ticket that opens this agent's news stream once, within a minute (abso 690; news-stream.ts). */
981+ newsTicket(): Promise<{ url: string; protocols: string[]; expiresAt: number }> {
982+ return this.json("POST", this.agentPath("news/ticket"), {});
983+ }
980985 /** This agent's unpublished changes, file by file. */
981986 diff(): Promise<DiffAnswer> {
982987 return this.json("POST", this.agentPath("diff"), {});
--- a/client/src/main.ts
+++ b/client/src/main.ts
@@ -762,10 +762,10 @@
762762 run: runStart,
763763 },
764764 news: {
765− flags: {},
766− usage: "abso news",
765+ flags: { stream: "boolean", follow: "boolean" },
766+ usage: "abso news [--stream | --follow]",
767767 about:
768− "The news waiting for you: collisions, changed definitions, moved lines and announcements. Each item comes once.",
768+ "The news waiting for you: collisions, changed definitions, moved lines and announcements. Each item comes once. --stream prints a Monitor call that wakes a Claude Code chat the moment news arrives (a ticket that opens the stream once, within a minute); --follow holds the stream itself and prints a line per item until stopped.",
769769 run: runNews,
770770 },
771771 "fix-eol": {
--- /dev/null
+++ b/client/src/news-stream.ts
@@ -0,0 +1,135 @@
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>`. */
12+export const NEWS_PROTOCOL = "abso-news.1";
14+/** What the server answers a ticket request with. */
15+export interface NewsTicket {
16+ readonly url: string;
17+ readonly protocols: readonly string[];
18+ readonly expiresAt: number;
19+}
21+/** A Monitor lasts at most 30 minutes; the skill re-arms it when it ends. */
22+export const MONITOR_TIMEOUT_MS = 30 * 60_000;
24+/** The Monitor call that holds a seat's stream: `Monitor({ ws, description, timeout_ms })`. */
25+export function monitorArgs(
26+ ticket: NewsTicket,
27+ project: string,
28+ agent: string,
29+): { ws: { url: string; protocols: string[] }; description: string; timeout_ms: number } {
30+ return {
31+ ws: { url: ticket.url, protocols: [...ticket.protocols] },
32+ description: `abso news for ${agent} in ${project}`,
33+ timeout_ms: MONITOR_TIMEOUT_MS,
34+ };
35+}
37+/** The text --stream prints: the call to make, then the arguments as one line of JSON. */
38+export function streamText(ticket: NewsTicket, project: string, agent: string, now = Date.now()): string {
39+ const seconds = Math.max(0, Math.round((ticket.expiresAt - now) / 1000));
40+ return [
41+ `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.`,
42+ JSON.stringify(monitorArgs(ticket, project, agent)),
43+ ].join("\n");
44+}
46+/** The part of a WebSocket --follow uses: the platform's own, or a test's. */
47+export interface Socket {
48+ onopen: (() => void) | null;
49+ onmessage: ((e: { data: unknown }) => void) | null;
50+ onclose: ((e: { code: number; reason: string }) => void) | null;
51+ onerror: ((e: unknown) => void) | null;
52+ send(text: string): void;
53+ close(code?: number): void;
54+}
56+/** A close the server sends when the ticket or key is refused: --follow stops instead of trying again. */
57+export function isRefusal(code: number): boolean {
58+ return code === 4401 || code === 4403;
59+}
61+/** How long --follow waits before opening a socket again: 1 s doubling to a minute; a socket that lived a minute resets it. */
62+export function nextWait(previous: number, livedMs: number): number {
63+ if (livedMs >= 60_000) return 1_000;
64+ return Math.min(60_000, Math.max(1_000, previous * 2));
65+}
67+/** The client sends this every PING_MS so an idle socket stays open; the object answers it without waking. */
68+export const PING = "ping";
69+export const PONG = "pong";
70+export const PING_MS = 45_000;
72+export interface FollowDeps {
73+ mint(): Promise<NewsTicket>;
74+ connect(url: string, protocols: readonly string[]): Socket;
75+ /** One news item, as the server sent it. */
76+ write(line: string): void;
77+ /** A line about the stream itself, not news. */
78+ note(line: string): void;
79+ sleep(ms: number): Promise<void>;
80+ now(): number;
81+ every(ms: number, fn: () => void): () => void;
82+ /** Set when --follow should stop (Ctrl-C, or a test). */
83+ readonly stopped: () => boolean;
84+}
86+/** Why a mint failed: a refused key, or a server with no news stream (404), stops --follow; anything else is tried again. */
87+function refusedMint(err: unknown): boolean {
88+ const status = (err as { status?: number }).status;
89+ return status === 401 || status === 403 || status === 404;
90+}
92+/**
93+ * Holds the seat's stream, printing one line per item, until the key is refused or `stopped()`.
94+ * Returns why it ended.
95+ */
96+export async function follow(deps: FollowDeps): Promise<{ ended: "refused" | "stopped"; reason: string }> {
97+ let wait = 1_000;
98+ while (!deps.stopped()) {
99+ let ticket: NewsTicket;
100+ try {
101+ ticket = await deps.mint();
102+ } catch (err) {
103+ if (refusedMint(err)) return { ended: "refused", reason: (err as Error).message };
104+ deps.note(`(abso news --follow: no ticket: ${(err as Error).message}; trying again in ${wait / 1000} s)`);
105+ await deps.sleep(wait);
106+ wait = nextWait(wait, 0);
107+ continue;
108+ }
109+ const opened = deps.now();
110+ const closed = await new Promise<{ code: number; reason: string }>((done) => {
111+ const socket = deps.connect(ticket.url, ticket.protocols);
112+ let stopPing = () => {};
113+ socket.onopen = () => {
114+ stopPing = deps.every(PING_MS, () => {
115+ if (deps.stopped()) socket.close(1000);
116+ else socket.send(PING);
117+ });
118+ };
119+ socket.onmessage = (e) => {
120+ if (typeof e.data !== "string" || e.data === PONG) return;
121+ deps.write(e.data);
122+ };
123+ socket.onerror = () => {};
124+ socket.onclose = (e) => {
125+ stopPing();
126+ done({ code: e.code, reason: e.reason });
127+ };
128+ });
129+ if (isRefusal(closed.code)) return { ended: "refused", reason: closed.reason || `closed ${closed.code}` };
130+ if (deps.stopped()) break;
131+ wait = nextWait(wait, deps.now() - opened);
132+ await deps.sleep(wait);
133+ }
134+ return { ended: "stopped", reason: "stopped" };
135+}
--- /dev/null
+++ b/client/test/news-stream.test.ts
@@ -0,0 +1,163 @@
1+// abso news --stream and --follow (abso 690): the Monitor call, and holding the stream through closes and refusals.
2+
3+import assert from "node:assert/strict";
4+import { test } from "node:test";
5+import {
6+ type FollowDeps,
7+ follow,
8+ isRefusal,
9+ MONITOR_TIMEOUT_MS,
10+ monitorArgs,
11+ NEWS_PROTOCOL,
12+ type NewsTicket,
13+ nextWait,
14+ PING,
15+ PING_MS,
16+ PONG,
17+ type Socket,
18+ streamText,
19+} from "../src/news-stream.ts";
21+const NOW = 1_800_000_000_000;
22+const ticket = (n: number): NewsTicket => ({
23+ url: "wss://api.abso.dev/p/abso/a/fe/news/stream",
24+ protocols: [NEWS_PROTOCOL, `abso-ticket.t${n}`],
25+ expiresAt: NOW + 60_000,
26+});
28+test("--stream prints the Monitor call: the URL and protocols as the server gave them, 30 minutes, named for the seat", () => {
29+ const args = monitorArgs(ticket(1), "abso", "fe");
30+ assert.deepEqual(args, {
31+ ws: { url: "wss://api.abso.dev/p/abso/a/fe/news/stream", protocols: ["abso-news.1", "abso-ticket.t1"] },
32+ description: "abso news for fe in abso",
33+ timeout_ms: MONITOR_TIMEOUT_MS,
34+ });
35+ assert.equal(MONITOR_TIMEOUT_MS, 30 * 60_000);
36+ // The ticket never goes in the URL.
37+ assert.doesNotMatch(args.ws.url, /t1/);
38+ const text = streamText(ticket(1), "abso", "fe", NOW + 15_000).split("\n");
39+ assert.match(text[0]!, /within 45 seconds/);
40+ assert.match(text[0]!, /run abso news --stream again/);
41+ assert.deepEqual(JSON.parse(text[1]!), args);
42+});
44+test("a refusal close stops --follow; any other close opens again, waiting 1 s doubling to a minute", () => {
45+ assert.equal(isRefusal(4401), true);
46+ assert.equal(isRefusal(4403), true);
47+ assert.equal(isRefusal(1006), false);
48+ assert.equal(isRefusal(1001), false);
49+ assert.equal(nextWait(1_000, 0), 2_000);
50+ assert.equal(nextWait(32_000, 5_000), 60_000);
51+ assert.equal(nextWait(60_000, 5_000), 60_000);
52+ // A socket that lived a minute starts the wait over.
53+ assert.equal(nextWait(60_000, 60_000), 1_000);
54+});
56+/** A world for follow(): each connect gets the next script of frames and a close. */
57+function world(scripts: { frames: string[]; close: { code: number; reason?: string }; livedMs?: number }[]) {
58+ let now = NOW;
59+ let n = 0;
60+ const lines: string[] = [];
61+ const notes: string[] = [];
62+ const sent: string[] = [];
63+ const slept: number[] = [];
64+ const opened: { url: string; protocols: readonly string[] }[] = [];
65+ const pings: (() => void)[] = [];
66+ let stop = false;
67+ const deps: FollowDeps = {
68+ mint: async () => ticket(++n),
69+ connect: (url, protocols) => {
70+ opened.push({ url, protocols });
71+ const script = scripts[opened.length - 1];
72+ const socket: Socket = {
73+ onopen: null,
74+ onmessage: null,
75+ onclose: null,
76+ onerror: null,
77+ send: (text) => sent.push(text),
78+ close: () => {},
79+ };
80+ queueMicrotask(() => {
81+ socket.onopen?.();
82+ if (script === undefined) {
83+ stop = true;
84+ socket.onclose?.({ code: 1000, reason: "" });
85+ return;
86+ }
87+ for (const pinged of pings.splice(0)) pinged();
88+ for (const data of script.frames) socket.onmessage?.({ data });
89+ now += script.livedMs ?? 1_000;
90+ socket.onclose?.({ code: script.close.code, reason: script.close.reason ?? "" });
91+ });
92+ return socket;
93+ },
94+ write: (line) => lines.push(line),
95+ note: (line) => notes.push(line),
96+ sleep: async (ms) => {
97+ slept.push(ms);
98+ },
99+ now: () => now,
100+ every: (ms, fn) => {
101+ assert.equal(ms, PING_MS);
102+ pings.push(fn);
103+ return () => {};
104+ },
105+ stopped: () => stop,
106+ };
107+ return { deps, lines, notes, sent, slept, opened };
108+}
110+test("--follow prints each item once, skips the server's pongs, and opens a new socket with a new ticket after a close", async () => {
111+ const w = world([
112+ { frames: ["fe told you: hello", PONG, "an ask from cloud: ship it?"], close: { code: 1006 } },
113+ { frames: ["second socket's item"], close: { code: 1001 }, livedMs: 120_000 },
114+ ]);
115+ const ended = await follow(w.deps);
116+ assert.deepEqual(ended, { ended: "stopped", reason: "stopped" });
117+ assert.deepEqual(w.lines, ["fe told you: hello", "an ask from cloud: ship it?", "second socket's item"]);
118+ // Each socket used its own ticket; each ticket was used once.
119+ assert.deepEqual(
120+ w.opened.map((o) => o.protocols[1]),
121+ ["abso-ticket.t1", "abso-ticket.t2", "abso-ticket.t3"],
122+ );
123+ // The first socket lived a second: wait 2 s. The second lived two minutes: start over at 1 s.
124+ assert.deepEqual(w.slept, [2_000, 1_000]);
125+ assert.equal(w.notes.length, 0);
126+});
128+test("--follow keeps an idle socket open with a ping the object answers without waking", async () => {
129+ const w = world([{ frames: [], close: { code: 1006 } }]);
130+ await follow(w.deps);
131+ assert.deepEqual(w.sent, [PING]);
132+});
134+test("a refused ticket or a refusal close ends --follow; a ticket that can't be had is tried again", async () => {
135+ const refusedClose = world([{ frames: ["one item"], close: { code: 4401, reason: "the key was revoked" } }]);
136+ assert.deepEqual(await follow(refusedClose.deps), { ended: "refused", reason: "the key was revoked" });
137+ assert.deepEqual(refusedClose.lines, ["one item"]);
139+ const w = world([{ frames: [], close: { code: 1000 } }]);
140+ let tries = 0;
141+ const mint = w.deps.mint;
142+ w.deps.mint = async () => {
143+ tries++;
144+ if (tries === 1) throw Object.assign(new Error("could not reach the server"), { status: undefined });
145+ if (tries === 3)
146+ throw Object.assign(new Error("POST /a/fe/news/ticket answered 401: no such key"), { status: 401 });
147+ return mint();
148+ };
149+ const ended = await follow(w.deps);
150+ assert.equal(ended.ended, "refused");
151+ assert.match(ended.reason, /401/);
152+ assert.equal(w.notes.length, 1);
153+ assert.match(w.notes[0]!, /no ticket: could not reach the server; trying again in 1 s/);
154+ assert.deepEqual(w.lines, []);
156+ // A server without the stream (before abso 690) answers the ticket 404: stop, don't retry.
157+ const old = world([]);
158+ old.deps.mint = async () => {
159+ throw Object.assign(new Error("POST /a/fe/news/ticket answered 404: not found"), { status: 404 });
160+ };
161+ assert.equal((await follow(old.deps)).ended, "refused");
162+ assert.deepEqual(old.slept, []);
163+});