@santori/station 0.9.10 → 0.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/frame.js CHANGED
@@ -31,7 +31,7 @@ export function askNewsFor(seat, messages) {
31
31
  return messages.filter((m) => m.kind === "event" && ASK_NEWS.includes(String(m.event?.type)) && m.participant_id === seat.participantId);
32
32
  }
33
33
  export function askNewsFrame(seat, news) {
34
- return askNewsText(roomLabel(seat), news.map((m) => m.body));
34
+ return askNewsText(roomLabel(seat), news.map((m) => ({ body: m.body, message: m.event?.message })));
35
35
  }
36
36
  /** Someone asking to join the room: an asked event in the stream. */
37
37
  export function askedIn(messages) {
@@ -51,7 +51,10 @@ export function askedFrame(seat, asked, command = "station") {
51
51
  * what agents said earlier that Station was holding: it goes after the
52
52
  * new messages, under its own line, so a person's message is read first
53
53
  * and is not the part Codex cuts from a long delivery. */
54
- export function frame(seat, messages, participants, command = "station", before = []) {
54
+ export function frame(seat, messages, participants, command = "station", before = [], otherRooms = false) {
55
+ // In more than one room, a reply names this one: without a sign-in,
56
+ // station say goes to the room the session joined last.
57
+ const room = otherRooms ? ` --room ${seat.roomId}` : "";
55
58
  const hearer = hearerFor(seat, participants, command);
56
59
  const byId = new Map(participants.map((p) => [p.id, p]));
57
60
  const authorOf = (message) => byId.get(message.participant_id ?? "");
@@ -62,7 +65,7 @@ export function frame(seat, messages, participants, command = "station", before
62
65
  const parts = [chatHeader(roomLabel(seat), seat.name), "", ...(note ? [note, ""] : []), ...messages.map(line), ""];
63
66
  if (before.length)
64
67
  parts.push("Before that, other agents said (Station held these until a person spoke):", "", ...before.map(line), "");
65
- const hint = threadHint(messages.length ? messages : before, `${command} say --reply {thread} "<your reply>"`, `${command} say "<your message>"`);
68
+ const hint = threadHint(messages.length ? messages : before, `${command} say${room} --reply {thread} "<your reply>"`, `${command} say${room} "<your message>"`, hearer);
66
69
  if (hint)
67
70
  parts.push(hint);
68
71
  return parts.join("\n");
package/dist/guard.js CHANGED
@@ -1,14 +1,17 @@
1
- // Two agents can talk each other into an endless exchange. A seat takes at
2
- // most AGENT_LIMIT messages from other agents in WINDOW_MS with no person's
3
- // message in between. Past that, agents' messages are held: they stay in
4
- // the room, the session is told once how many wait and how to read them,
5
- // and they come through when a person speaks or the window passes. Nothing
6
- // is dropped. acm (agent-chat-room) keeps them in the room the same way;
7
- // Agent Relay and bot2bot refuse the sender instead.
1
+ // Two agents can talk each other into an endless exchange. Whether an
2
+ // exchange is a loop is the agents' call: each delivery says how many
3
+ // messages from other agents came in the window since a person last wrote
4
+ // in the room (handover.ts). What is left here is a cost ceiling: a seat
5
+ // takes at most AGENT_LIMIT messages from other agents in WINDOW_MS with no
6
+ // person's message in between. Past that, agents' messages are held: they
7
+ // stay in the room, the session is told once how many wait, and they come
8
+ // through when a person speaks or the window passes. Nothing is dropped.
9
+ // acm (agent-chat-room) keeps them in the room the same way; Agent Relay and
10
+ // bot2bot refuse the sender instead.
8
11
  //
9
12
  // The guard goes by the sender's seat id and its kind from the relay,
10
13
  // never by what a message says.
11
- export const AGENT_LIMIT = 6;
14
+ export const AGENT_LIMIT = 60;
12
15
  export const WINDOW_MS = 10 * 60_000;
13
16
  export const freshGuard = () => ({ agentTimes: [], held: [], told: false });
14
17
  /** Which of a batch of new chat messages go into the session now. A
package/dist/guest.js CHANGED
@@ -13,12 +13,16 @@ export function readGuest(home, relayUrl) {
13
13
  const guest = readJson(files(home).guest, null);
14
14
  return guest && guest.relayUrl === relayUrl && typeof guest.token === "string" ? guest : null;
15
15
  }
16
- /** This computer's identity on that relay, asked for the first time it is needed. */
17
- export async function guestFor(home, relayUrl) {
16
+ /** This computer's identity on that relay, asked for the first time it is needed.
17
+ * A test run sets STATION_TEST=1, so the identity is marked test and its
18
+ * rooms stay out of Station's analytics. */
19
+ export async function guestFor(home, relayUrl, env = process.env) {
18
20
  const known = readGuest(home, relayUrl);
19
21
  if (known)
20
22
  return known;
21
- const answer = await call(relayUrl, "/cli/guest", null, { body: { label: hostname().replace(/\.local$/, "").slice(0, 80) } });
23
+ const label = hostname().replace(/\.local$/, "").slice(0, 80);
24
+ const body = env.STATION_TEST === "1" ? { label, test: true } : { label };
25
+ const answer = await call(relayUrl, "/cli/guest", null, { body });
22
26
  const guest = { relayUrl, token: answer.token, userId: answer.user_id };
23
27
  writeJson(files(home).guest, guest);
24
28
  return guest;
package/dist/handover.js CHANGED
@@ -25,17 +25,25 @@ export async function messagesById(ids, page) {
25
25
  const plural = (n) => `${n} message${n === 1 ? "" : "s"}`;
26
26
  export const heldWaiting = (count) => count ? `Holding ${plural(count)} from other agents until a person in the room says something.` : null;
27
27
  export const readHeldCommand = (seat, command) => `${command} wait --room ${seat.roomId}`;
28
- /** Told once, when the guard starts holding. */
28
+ const MINUTES = WINDOW_MS / 60_000;
29
+ /** The facts for the agent to judge an exchange by: how many messages from
30
+ * other agents came in the window since a person last wrote here. */
31
+ export const agentCount = (count) => `Since a person last wrote in this room: ${plural(count)} from other agents in the last ${MINUTES} minutes.`;
32
+ /** Told once, when the guard starts holding. Codex gets no command: each
33
+ * Station command in Codex's sandbox can cost its person an approval, and
34
+ * the held messages come here on their own. */
29
35
  export function heldNote(seat, count, command) {
30
36
  return [
31
- `[Station · ${roomLabel(seat)}] Station is holding ${plural(count)} from other agents. More than ${AGENT_LIMIT} came within ${WINDOW_MS / 60_000} minutes with no person in between, so Station stopped putting them here to keep agents from talking in a loop. Nothing is lost.`,
32
- `To read them now, run: ${readHeldCommand(seat, command)}`,
33
- `They also come through here on their own when a person in the room says something, or as the ${WINDOW_MS / 60_000} minutes pass.`,
37
+ `[Station · ${roomLabel(seat)}] Station is holding ${plural(count)} from other agents: more than ${AGENT_LIMIT} came within ${MINUTES} minutes with no person in between. Nothing is lost.`,
38
+ `They come through here when a person writes in the room, or as the ${MINUTES} minutes pass.`,
39
+ ...(seat.harness === "codex" ? [] : [`To read them now: ${readHeldCommand(seat, command)}`]),
34
40
  ].join("\n");
35
41
  }
36
42
  export async function handOver(seat, guard, batch, room, now, command,
37
43
  /** The session has seats in other rooms too: the note's read command names this room. */
38
- otherRooms = false) {
44
+ otherRooms = false,
45
+ /** For Claude Code's hooks: every message whole, as for Codex, not a note to read them. */
46
+ whole = false) {
39
47
  const chat = batch.messages.filter((m) => m.kind === "chat" && m.participant_id !== seat().participantId);
40
48
  const decisions = decisionsFor(seat(), batch.messages);
41
49
  const asked = askedIn(batch.messages);
@@ -59,13 +67,17 @@ otherRooms = false) {
59
67
  // Claude Code gets a one-line note and reads the messages with station read. Codex still gets every message
60
68
  // whole: a station command in Codex's sandbox needs its person to allow
61
69
  // network access, so reading after a note could cost an approval each time.
62
- const chatFrame = seat().harness === "claude-code" ? noteFrame(seat(), said, participants, command, before, otherRooms) : frame(seat(), said, participants, command, before);
70
+ // Its hooks give the words themselves (hook/hook.mjs): added context
71
+ // between steps, or what wakes it, the way Claude Code documents.
72
+ const chatFrame = seat().harness === "claude-code" && !whole ? noteFrame(seat(), said, participants, command, before, otherRooms) : frame(seat(), said, participants, command, before, otherRooms);
63
73
  const parts = [
64
74
  // What became of its own asks: could not reach, handed on, out of usage.
65
75
  news.length ? askNewsFrame(seat(), news) : null,
66
76
  // Answers on its cards: they are what the agent is waiting for.
67
77
  decisions.length ? decisionFrame(seat(), decisions, participants) : null,
68
78
  admitted.length ? chatFrame : null,
79
+ // More than one from agents with no person since: the count, for the agent to judge.
80
+ admitted.some((m) => kinds.get(m.participant_id ?? "") === "agent") && sifted.guard.agentTimes.length > 1 ? agentCount(sifted.guard.agentTimes.length) : null,
69
81
  // Someone asking to join: the people who can answer may not be looking
70
82
  // at the room, so the agents seated there say so.
71
83
  asked.length ? askedFrame(seat(), asked, command) : null,
package/dist/hooks.js ADDED
@@ -0,0 +1,169 @@
1
+ // Hooks: the documented way for room messages to reach Claude Code. Claude
2
+ // Code runs a configured command at points in a session and gives its
3
+ // output to the model (hooks/hook.mjs is that command):
4
+ //
5
+ // - between the steps of a task (UserPromptSubmit, PostToolUse): the
6
+ // people's own words, as added context;
7
+ // - when a turn ends (Stop, run in the background with asyncRewake): the
8
+ // hook waits on the daemon and wakes the idle session with what comes.
9
+ //
10
+ // The person allows them once per computer, on the page where they approve
11
+ // its sign-in (login keeps that as `allowHooks` in credentials.json), and
12
+ // `station join` in a Claude Code session then writes them. `station logout`
13
+ // takes them out, and the daemon stops serving them once the sign-in is gone. Codex is unchanged: its
14
+ // messages go the way codex.ts has them.
15
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
16
+ import { dirname, join } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { claudeHome } from "./claude.js";
19
+ import { files, readJson } from "./home.js";
20
+ import { Usage } from "./usage.js";
21
+ /** The protocol the hook script and the daemon speak (hook.mjs PROTOCOL). */
22
+ export const HOOK_PROTOCOL = 1;
23
+ /** The events Station hooks. Stop waits in the background for a day, the longest a session sits idle and still gets woken. */
24
+ export const HOOK_EVENTS = [
25
+ { event: "UserPromptSubmit", timeout: 5 },
26
+ { event: "PostToolUse", timeout: 5 },
27
+ { event: "Stop", timeout: 86_400, asyncRewake: true },
28
+ { event: "SessionEnd", timeout: 5 },
29
+ ];
30
+ /** The script this package ships, copied into Station's home on install. */
31
+ export const HOOK_SOURCE = fileURLToPath(new URL("../hook/hook.mjs", import.meta.url));
32
+ export const hookScript = (home) => join(home, "hook.mjs");
33
+ /** The person allowed hooks on this computer when they approved its sign-in. */
34
+ export function hooksAllowed(home) {
35
+ return readJson(files(home).credentials, null)?.allowHooks === true;
36
+ }
37
+ /** STATION_HOOKS=off: none for this process. */
38
+ export const hooksOffHere = (env = process.env) => (env.STATION_HOOKS ?? "").toLowerCase() === "off";
39
+ /** Where Claude Code reads a person's own hooks from. */
40
+ export const hooksFile = (env = process.env) => join(claudeHome(env), "settings.json");
41
+ const quote = (part) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(part) ? part : `'${part.replace(/'/g, `'\\''`)}'`);
42
+ /** What Claude Code runs: Node by its absolute path, so no npx, PATH or nvm in between. */
43
+ export const hookCommand = (home, node = process.execPath) => [node, hookScript(home), files(home).socket].map(quote).join(" ");
44
+ /** Whether a hook command is one Station wrote: this script with its socket, quoted or not (a home with a space in its path), or the pilot's `station hook <harness>`. */
45
+ export const isStationHook = (command) => typeof command === "string" && (/[/\\]hook\.mjs'? +(?:'(?:[^']|'\\'')*\.sock'|[^ ']*\.sock)$/.test(command.trim()) || /(^|[/\\ '"])(station|cli\.js)'?"? hook (claude-code|codex)$/.test(command.trim()));
46
+ /** The config without Station's entries. Everything else stays as it was. */
47
+ export function withoutStationHooks(config) {
48
+ if (!config.hooks || typeof config.hooks !== "object")
49
+ return config;
50
+ const events = {};
51
+ for (const [event, groups] of Object.entries(config.hooks)) {
52
+ if (!Array.isArray(groups)) {
53
+ events[event] = groups;
54
+ continue;
55
+ }
56
+ const kept = groups.flatMap((group) => {
57
+ if (!Array.isArray(group?.hooks))
58
+ return [group];
59
+ const handlers = group.hooks.filter((handler) => !isStationHook(handler?.command));
60
+ if (handlers.length === group.hooks.length)
61
+ return [group];
62
+ return handlers.length ? [{ ...group, hooks: handlers }] : [];
63
+ });
64
+ if (kept.length)
65
+ events[event] = kept;
66
+ }
67
+ const { hooks: _, ...rest } = config;
68
+ return Object.keys(events).length ? { ...rest, hooks: events } : rest;
69
+ }
70
+ /** The config with Station's entries, once each. */
71
+ export function withStationHooks(config, command) {
72
+ const clean = withoutStationHooks(config);
73
+ const events = { ...(clean.hooks ?? {}) };
74
+ for (const { event, ...rest } of HOOK_EVENTS)
75
+ events[event] = [...(events[event] ?? []), { hooks: [{ type: "command", command, ...rest }] }];
76
+ return { ...clean, hooks: events };
77
+ }
78
+ /** Whether the file holds Station's entry for every event. */
79
+ export function hasStationHooks(config) {
80
+ return HOOK_EVENTS.every(({ event }) => (config.hooks?.[event] ?? []).some((group) => (group?.hooks ?? []).some((handler) => isStationHook(handler?.command))));
81
+ }
82
+ function readConfig(path) {
83
+ if (!existsSync(path))
84
+ return {};
85
+ try {
86
+ const value = JSON.parse(readFileSync(path, "utf8"));
87
+ if (value && typeof value === "object" && !Array.isArray(value))
88
+ return value;
89
+ }
90
+ catch {
91
+ // falls through
92
+ }
93
+ // Never write over a file Station cannot read: it is the person's.
94
+ throw new Usage(`${path} is not JSON Station can read, so Station left it alone. Fix or remove it, then join again.`);
95
+ }
96
+ /** Writes the settings where they really live: a settings.json linked to
97
+ * a dotfiles copy stays a link, and the file keeps its mode. */
98
+ function writeSettings(path, value) {
99
+ const target = existsSync(path) ? realpathSync(path) : path;
100
+ const mode = existsSync(target) ? statSync(target).mode & 0o777 : 0o600;
101
+ const temp = `${target}.${process.pid}.tmp`;
102
+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode });
103
+ chmodSync(temp, mode);
104
+ renameSync(temp, target);
105
+ }
106
+ /** Copies the script into Station's home and writes Station's entries into Claude Code's settings, backing the file up first. */
107
+ export function installHooks(home, env = process.env, source = HOOK_SOURCE, node = process.execPath) {
108
+ mkdirSync(home, { recursive: true });
109
+ // The script is copied only when it changed (a new Station), so a call with nothing to do writes nothing.
110
+ if (!existsSync(hookScript(home)) || !readFileSync(source).equals(readFileSync(hookScript(home))))
111
+ copyFileSync(source, hookScript(home));
112
+ const path = hooksFile(env);
113
+ const before = readConfig(path);
114
+ const after = withStationHooks(before, hookCommand(home, node));
115
+ if (JSON.stringify(before) === JSON.stringify(after))
116
+ return { path, changed: false, backup: null };
117
+ mkdirSync(dirname(path), { recursive: true });
118
+ const backup = existsSync(path) ? `${path}.before-station` : null;
119
+ if (backup)
120
+ copyFileSync(path, backup);
121
+ writeSettings(path, after);
122
+ return { path, changed: true, backup };
123
+ }
124
+ /** Takes Station's entries out of Claude Code's settings. */
125
+ export function removeHooks(env = process.env) {
126
+ const path = hooksFile(env);
127
+ if (!existsSync(path))
128
+ return { path, changed: false, backup: null };
129
+ let before;
130
+ try {
131
+ before = readConfig(path);
132
+ }
133
+ catch {
134
+ return { path, changed: false, backup: null };
135
+ }
136
+ const after = withoutStationHooks(before);
137
+ const changed = JSON.stringify(before) !== JSON.stringify(after);
138
+ if (changed)
139
+ writeSettings(path, after);
140
+ return { path, changed, backup: null };
141
+ }
142
+ export function hooksOn(env = process.env) {
143
+ try {
144
+ return hasStationHooks(readConfig(hooksFile(env)));
145
+ }
146
+ catch {
147
+ return false;
148
+ }
149
+ }
150
+ /** Station's hooks for Claude Code, written when the person allowed them
151
+ * and nothing turned them off. `change` is null when they are not in place:
152
+ * not allowed, or `failed` says why they could not be written. */
153
+ export function hooksReady(home, env = process.env) {
154
+ if (!hooksAllowed(home) || hooksOffHere(env))
155
+ return { change: null, failed: null };
156
+ try {
157
+ return { change: installHooks(home, env), failed: null };
158
+ }
159
+ catch (error) {
160
+ return { change: null, failed: error instanceof Usage ? error.message : `Station could not write its hooks to ${hooksFile(env)}: ${error instanceof Error ? error.message : String(error)}.` };
161
+ }
162
+ }
163
+ /** What `station join` says about Station's hooks in a Claude Code
164
+ * session, on every join: how messages come in, and that its person chose
165
+ * it. Where the file is only when this join wrote it. */
166
+ export function hooksJoinLine(hooks) {
167
+ const where = hooks.changed ? ` Station's hooks are in ${hooks.path}${hooks.backup ? ` (your old file: ${hooks.backup})` : ""}.` : "";
168
+ return `Messages from this room come into this Claude Code between the steps of a task, and wake it when idle. Your person allowed that when they signed this computer in to Station.${where}`;
169
+ }