Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .changeset/trigger-notices.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@ The notice a receiver sends for a trigger, defined

- The protocol defines a notice (`control-notice.json`): a receiver's unsigned word that something changed on a topic the machine listed, as a closed set of short typed fields with no session, words, folder, level or tool. It travels in a new `notices` list beside `messages` in a poll answer, at most 50 at a time, and is acked at `POST {control}/notices/ack` (`control-notice-ack.json`) with its outcome alone: what ran is never said.
- A machine's hello can carry `triggers`: whether triggers are on and the topics a receiver may send notices on. A receiver's well-known file can say `control.notices`.
- `sessionpipe-core` exports `parseNotice`, `noticesIn` and `noticeAck`, which read a notice against the generated definition and build its ack. Nothing runs on a notice yet.
- `sessionpipe-core` exports `parseNotice`, `noticesIn` and `noticeAck`, which read a notice against the generated definition and build its ack.
18 changes: 18 additions & 0 deletions .changeset/triggers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
"sessionpipe": minor
"sessionpipe-core": minor
"sessionpipe-receiver": minor
---

The background service takes a receiver's notices and runs the rules they fit

- Every hello says `triggers`: on, with the topics each receiver may send notices on, or off. A hello goes at once when that changes: a rule added, paused, resumed or removed, `sessionpipe triggers on|off`, a pause the machine made, or a second pairing on a rule's receiver. Hellos go one at a time, so the last one a receiver hears is what is so now.
- Each notice of a poll answer, at most 50, is checked in the order CONTROL.md §14.7 gives: its id, the switch, its shape and times, whether it expired, whether this receiver sent it in the last 25 hours, and the first rule it fits. Its id is recorded on disk before anything runs, so a notice runs at most once, across a restart too. One that can't be recorded is not acked and runs nothing; the receiver sends it again.
- A notice sent again while its run is still getting ready (a sign-in check, say) is not acked until the run says `taken` or `ran`: the receiver never hears `duplicate` first.
- Each notice is acked at `POST {control}/notices/ack`, 50 at a time, and its ack is kept on disk until the receiver accepts it. One ack waits per notice: the final one replaces `taken`, and `duplicate` never goes out ahead of it. At most 2 000 wait for one receiver; past that the oldest that is neither `ran` nor `taken` is dropped. An ack goes back to the pairing its notice came from, even when another pairing on the same host was added meanwhile.
- `sessionpipe triggers off` holds for the next notice at once, before the file watcher notices the change.
- A run that waits is saved before its notice is told `taken`, so a crash between the two can't leave a `taken` that never gets a final ack.
- A receiver that sends notices on every answer is polled at most once a second, and this computer remembers at most 20 000 of one receiver's notice ids at a time; past that a new notice waits.
- Two pairings on one host: neither can trigger a rule, and both are told triggers are off. A second service that doesn't run the rules says off, acks nothing and writes none of their files.
- `sessionpipe-core` exports `receiverName`, the name a rule gives its receiver, so `trigger add` and the service read it the same way. An address with no host names no receiver.
- `sessionpipe-receiver` exports the notices half of a receiver as plain functions over one machine's state: `onHello`, `offer`, `forPoll` and `onAcks`, and a file to keep it in. A receiver built on them sends only topics the last hello listed, keeps one notice per subject, and never lets `duplicate` or a later final replace a `ran` it already has.
3 changes: 2 additions & 1 deletion packages/cli/src/control/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import { ControlDaemon, DaemonRunning, type Status } from "./daemon.js";
import { ask, socketPath } from "./local.js";
import { installService, off, pair, removeKey, uninstallService, withoutInherit } from "./pair.js";
import { CLAUDE_NOT_FOUND } from "./route.js";
import { readRules, rulesOf, triggersFile } from "./rules-file.js";
import { readRules, rulesOf, rulesStamp, triggersFile } from "./rules-file.js";
import { loadSdk } from "./sdk.js";
import {
askOn,
Expand Down Expand Up @@ -473,6 +473,7 @@ async function runDaemon(out: (s?: string) => void, distDir: string): Promise<vo
onLostSocket: () => process.exit(0),
pool,
rules: () => rulesOf(readRules()),
rulesStamp: () => rulesStamp(),
});
try {
await d.start();
Expand Down
246 changes: 232 additions & 14 deletions packages/cli/src/control/daemon.ts

Large diffs are not rendered by default.

338 changes: 338 additions & 0 deletions packages/cli/src/control/notices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,338 @@
// SPDX-License-Identifier: Apache-2.0
// The notices step (spec/CONTROL.md §14.7 steps 1 to 6): what the daemon does with each notice
// of a poll answer before the engine (control/triggers.ts) is asked to run anything. The id read,
// the switch, the shape and the times, the 25-hour dedup and the match, in that order, in one
// function (`takeNotice`), with the two stores it needs: the ids seen from each receiver, and the
// acks not yet accepted. Both files are the claim holder's only (`triggers-state.lock`): a daemon
// without the claim reads no notice and writes neither.
//
// <state>/control/notices-seen.jsonl {"r":"<control url><machine id>","i":"01KB…","t":1764000000000}
// <state>/control/notice-acks.jsonl {"receiver":"<control url><machine id>","id":"01KB…","outcome":"ran","at":"…Z","session":"…"}

import {
appendFileSync,
closeSync,
existsSync,
fsyncSync,
mkdirSync,
openSync,
readFileSync,
renameSync,
unlinkSync,
writeSync,
} from "node:fs";
import path from "node:path";
import {
type ControlNotice,
NOTICE_SEEN_MS,
type NoticeAck,
type NoticeResult,
noticeId,
parseNotice,
type TriggerRule,
writeWhole,
} from "@sessionpipe/core";

/** Live ids a machine keeps per receiver. Notices are unsigned, so a paired receiver could send
* fresh ids without end: past this many, a notice is held (not acked, nothing runs) until the
* oldest age out. A day of an honest board is far below it. */
export const NOTICE_SEEN_MAX = 20_000;
/** Acks a machine keeps waiting for one receiver. A receiver that answers every ack with an error
* while it sends fresh ids that are refused at once could otherwise grow the outbox without end:
* past this many, the oldest that is neither `ran` nor `taken` gives way. */
export const NOTICE_ACK_MAX = 2_000;
/** The pause before polling again after an answer that carried notices. */
export const NOTICE_POLL_GAP_MS = 1_000;
/** How long a poll that produced acks waits for them to land before it polls again (§14.4: a
* machine SHOULD ack every notice of an answer before it polls that receiver again). */
export const NOTICE_ACK_WAIT_MS = 3_000;
/** How soon a send of the acks that failed on this machine's own disk is tried again. */
export const NOTICE_ACK_RETRY_MS = 5_000;
/** Acks per `POST {control}/notices/ack` (control-notice-ack.json). */
export const NOTICE_ACKS_PER_POST = 50;
const DAY_MS = 24 * 3600_000;

/** The ids each receiver sent in the last 25 hours, as NonceStore keeps nonces: in memory,
* appended and synced before `record` returns, the file rewritten with only the live window at
* start and once a day. A line a crash cut short is skipped. */
export class NoticeSeen {
private readonly ids = new Map<string, Map<string, number>>();
private compacted = 0;

constructor(
private readonly file: string,
private readonly now: () => number = Date.now,
) {
let raw = "";
try {
raw = readFileSync(file, "utf8");
} catch {}
const cut = this.now() - NOTICE_SEEN_MS;
for (const line of raw.split("\n")) {
if (!line) continue;
try {
const { r, i, t } = JSON.parse(line) as { r: unknown; i: unknown; t: unknown };
if (typeof r === "string" && typeof i === "string" && typeof t === "number" && t > cut) this.mine(r).set(i, t);
} catch {}
}
this.compact();
}

private mine(r: string): Map<string, number> {
let m = this.ids.get(r);
if (!m) {
m = new Map();
this.ids.set(r, m);
}
return m;
}

/** `id` came from `r` within the last 25 hours. */
has(r: string, id: string): boolean {
const t = this.ids.get(r)?.get(id);
return t !== undefined && t > this.now() - NOTICE_SEEN_MS;
}

/** Record `id` from `r`, on disk before this returns. Throws when it can't: the write failed,
* or `r` already has NOTICE_SEEN_MAX live ids. Either way nothing may run for it. */
record(r: string, id: string): void {
const at = this.now();
if (at - this.compacted >= DAY_MS) this.compact();
const m = this.mine(r);
if (m.size >= NOTICE_SEEN_MAX) {
for (const [i, t] of m) if (t <= at - NOTICE_SEEN_MS) m.delete(i);
if (m.size >= NOTICE_SEEN_MAX) throw new Error(`${NOTICE_SEEN_MAX} notices in 25 hours from one receiver`);
}
mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
const fd = openSync(this.file, "a", 0o600);
try {
appendFileSync(fd, `${JSON.stringify({ r, i: id, t: at })}\n`);
fsyncSync(fd);
} finally {
closeSync(fd);
}
m.set(id, at);
}

/** Rewrite the file with only the live window. */
compact(): void {
const at = this.now();
this.compacted = at;
const lines: string[] = [];
for (const [r, m] of this.ids) {
for (const [i, t] of m)
if (t <= at - NOTICE_SEEN_MS) m.delete(i);
else lines.push(JSON.stringify({ r, i, t }));
if (!m.size) this.ids.delete(r);
}
if (!existsSync(this.file) && !lines.length) return;
// Only a smaller file: one that can't be rewritten is still read whole, and `record` says
// whether the disk takes anything.
try {
writeSynced(this.file, lines.length ? `${lines.join("\n")}\n` : "");
} catch {}
}
}

/** Write a file whole and on disk before it takes the old one's place, so a crash or a power cut
* leaves the old file or the new one, never an empty one. The file beside it goes if anything
* fails. */
function writeSynced(file: string, text: string): void {
mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
const beside = `${file}.${process.pid}.tmp`;
try {
const fd = openSync(beside, "w", 0o600);
try {
writeSync(fd, text);
fsyncSync(fd);
} finally {
closeSync(fd);
}
renameSync(beside, file);
} catch (e) {
try {
unlinkSync(beside);
} catch {}
throw e;
}
}

/** A notice's ack waiting for its receiver to accept it, and which pairing it is for. */
export interface StoredNoticeAck extends NoticeAck {
receiver: string;
}

const isFinal = (o: NoticeAck["outcome"]): boolean => o !== "taken" && o !== "duplicate";
const keyOf = (a: StoredNoticeAck): string => `${a.receiver}\0${a.id}`;
/** What waits for a notice once `a` is added to `was`: only a final replaces what waits, and only
* what is not final itself. */
const merged = (was: StoredNoticeAck | undefined, a: StoredNoticeAck): StoredNoticeAck =>
!was || (isFinal(a.outcome) && !isFinal(was.outcome)) ? a : was;
/** Worth more than the rest when one must give way: the session a run went to, a run that waits. */
const precious = (a: StoredNoticeAck): boolean => a.outcome === "ran" || a.outcome === "taken";

/** Notice acks not yet accepted, as AckOutbox keeps a command's: on disk before they are sent,
* so a restart sends rather than forgets. At most one waits per notice: a `taken` gives way to
* the final that follows it, a `duplicate` is not added while anything waits for that notice
* (the receiver would learn it before the session), and nothing ever goes back to `taken`. One
* older than 25 hours is no use to anyone (its notice expired) and is dropped, and a receiver has
* at most NOTICE_ACK_MAX waiting. Every change is on disk before it is made here: a write that
* fails throws and changes nothing. */
export class NoticeAckOutbox {
/** By receiver and id, oldest first. */
private pending = new Map<string, StoredNoticeAck>();
/** How many wait for each receiver. */
private counts = new Map<string, number>();

constructor(
private readonly file: string,
private readonly now: () => number = Date.now,
) {
let raw = "";
try {
raw = readFileSync(file, "utf8");
} catch {}
const lines = raw.split("\n").filter(Boolean);
let next = new Map<string, StoredNoticeAck>();
for (const line of lines) {
try {
const a = JSON.parse(line) as StoredNoticeAck;
if (typeof a?.receiver === "string" && typeof a.id === "string" && typeof a.outcome === "string")
next = this.with(next, a);
} catch {}
}
next = this.live(next);
this.keep(next);
// Written back only when reading changed it: a line cut short, one past its time, two for one
// notice. Not written, it is read the same way next time.
if (next.size !== lines.length)
try {
this.write(next);
} catch {}
}

/** `list` with `a` added under the outbox's rules, the receiver's cap kept. */
private with(list: Map<string, StoredNoticeAck>, a: StoredNoticeAck): Map<string, StoredNoticeAck> {
const k = keyOf(a);
const next = new Map(list);
next.set(k, merged(list.get(k), a));
const theirs = [...next.values()].filter((x) => x.receiver === a.receiver);
if (theirs.length > NOTICE_ACK_MAX) {
const out = theirs.find((x) => !precious(x)) ?? theirs.find((x) => x.outcome !== "ran") ?? theirs[0];
next.delete(keyOf(out as StoredNoticeAck));
}
return next;
}

private live(list: Map<string, StoredNoticeAck>): Map<string, StoredNoticeAck> {
const cut = this.now() - NOTICE_SEEN_MS;
return new Map([...list].filter(([, a]) => Date.parse(a.at) > cut));
}

private write(list: Map<string, StoredNoticeAck>): void {
mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
const body = [...list.values()].map((a) => JSON.stringify(a)).join("\n");
writeWhole(this.file, body ? `${body}\n` : "");
}

private keep(next: Map<string, StoredNoticeAck>): void {
this.pending = next;
this.counts = new Map();
for (const a of next.values()) this.counts.set(a.receiver, (this.counts.get(a.receiver) ?? 0) + 1);
}

/** Make `next` the outbox: on disk first. */
private commit(next: Map<string, StoredNoticeAck>): void {
this.write(next);
this.keep(next);
}

/** Every ack that waits, oldest first. */
all(): StoredNoticeAck[] {
const next = this.live(this.pending);
if (next.size !== this.pending.size) this.commit(next);
return [...this.pending.values()];
}

add(a: StoredNoticeAck): void {
const k = keyOf(a);
const was = this.pending.get(k);
if (merged(was, a) === was) return;
// A new ack under the receiver's cap: one line appended, then one entry. A final in place of
// `taken`, or one that makes room: the file rewritten.
const n = this.counts.get(a.receiver) ?? 0;
if (!was && n < NOTICE_ACK_MAX) {
mkdirSync(path.dirname(this.file), { recursive: true, mode: 0o700 });
appendFileSync(this.file, `${JSON.stringify(a)}\n`, { mode: 0o600 });
this.pending.set(k, a);
this.counts.set(a.receiver, n + 1);
} else this.commit(this.with(this.pending, a));
}

/** Accepted by their receiver: gone, unless something replaced them meanwhile. */
sent(acks: readonly StoredNoticeAck[]): void {
const next = new Map(this.pending);
for (const a of acks) if (next.get(keyOf(a)) === a) next.delete(keyOf(a));
if (next.size !== this.pending.size) this.commit(next);
}

/** Only these pairings' acks are kept: one no longer paired has nobody to tell. */
only(receivers: ReadonlySet<string>): void {
const next = new Map([...this.pending].filter(([, a]) => receivers.has(a.receiver)));
if (next.size !== this.pending.size) this.commit(next);
}
}

/** What to do with one notice of a poll answer. `drop`: nothing to ack, its id can't be read.
* `hold`: no ack and nothing runs, so the receiver sends it again (it could not be recorded, or
* its first ack has not gone out yet).
* `ack`: answered here, nothing runs. `fire`: the engine runs `rule` for it, and says its
* outcome. */
export type NoticeStep =
| { do: "drop" }
| { do: "hold"; id: string; why: "unrecorded" | "in_hand" }
| { do: "ack"; id: string; result: NoticeResult }
| { do: "fire"; id: string; rule: string; notice: ControlNotice };

export interface NoticeCtx {
now: number;
/** Triggers are on, the rules file read whole, and this receiver's name is its own. */
on: boolean;
seen: NoticeSeen;
/** The pairing the notice came from (`control + machine`): what `seen` keys it by. */
receiver: string;
/** The first rule that takes it (§14.7 step 6), the machine's pauses counted. */
match(n: ControlNotice): TriggerRule | null;
/** The engine has this notice in hand and has said nothing of it yet (a run that is still
* looking before it begins or waits). */
inHand(id: string): boolean;
}

/** One notice, §14.7 steps 1 to 6 in order, stopping at the first that fails. The id is recorded
* before anything runs: a crash after it means the notice comes again as `duplicate` and runs
* nothing, at most once as the spec chooses. */
export function takeNotice(raw: unknown, ctx: NoticeCtx): NoticeStep {
const id = noticeId(raw);
if (id === null) return { do: "drop" };
if (!ctx.on) return { do: "ack", id, result: { outcome: "refused", code: "triggers_off" } };
const r = parseNotice(raw, ctx.now);
if (!r.ok)
return {
do: "ack",
id,
result: r.code === "expired" ? { outcome: "expired" } : { outcome: "refused", code: "bad_notice" },
};
// Sent again before its first ack went out: held, so `duplicate` never reaches the receiver
// ahead of the `taken` or `ran` that is coming.
if (ctx.seen.has(ctx.receiver, id))
return ctx.inHand(id) ? { do: "hold", id, why: "in_hand" } : { do: "ack", id, result: { outcome: "duplicate" } };
try {
ctx.seen.record(ctx.receiver, id);
} catch {
return { do: "hold", id, why: "unrecorded" };
}
const rule = ctx.match(r.notice);
return rule
? { do: "fire", id, rule: rule.name, notice: r.notice }
: { do: "ack", id, result: { outcome: "no_match" } };
}
11 changes: 11 additions & 0 deletions packages/cli/src/control/rules-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,17 @@ export const triggersFile = (env: NodeJS.ProcessEnv = process.env): string =>
export const triggerStateFile = (env: NodeJS.ProcessEnv = process.env): string =>
path.join(controlState(env), "triggers-state.json");

/** What tells the rules file changed without reading it: its inode, size and time ("none" when
* it is not there). The daemon looks before it takes a poll's notices. */
export function rulesStamp(env: NodeJS.ProcessEnv = process.env): string {
try {
const s = statSync(triggersFile(env));
return `${s.ino}:${s.size}:${s.mtimeMs}`;
} catch {
return "none";
}
}

/** The rules file as a machine reads it: not there, read whole, or refused whole with every
* problem (CONTROL.md §14.1: "a file that does not fit this, or is not there, is read as no
* rules with triggers off"). */
Expand Down
Loading
Loading