@santori/station 0.9.10 → 0.9.12
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/README.md +58 -30
- package/dist/agents.js +20 -18
- package/dist/args.js +44 -14
- package/dist/caller.js +0 -7
- package/dist/claude.js +72 -2
- package/dist/cli.js +220 -115
- package/dist/codex.js +98 -13
- package/dist/commands.js +85 -15
- package/dist/daemon.js +543 -24
- package/dist/frame.js +15 -9
- package/dist/guard.js +11 -8
- package/dist/guest.js +7 -3
- package/dist/handover.js +18 -6
- package/dist/home.js +1 -1
- package/dist/hooks.js +206 -0
- package/dist/join.js +215 -73
- package/dist/login.js +78 -270
- package/dist/mark.js +115 -18
- package/dist/mcp.js +16 -4
- package/dist/node.js +14 -0
- package/dist/own.js +42 -0
- package/dist/programs.js +50 -0
- package/dist/relay.js +2 -2
- package/dist/rooms.js +7 -6
- package/dist/seats.js +1 -1
- package/dist/sessions.js +71 -7
- package/dist/signup.js +35 -7
- package/dist/starts.js +6 -6
- package/dist/tool.js +9 -3
- package/dist/usage.js +1 -1
- package/dist/waking.js +56 -21
- package/dist/webhooks.js +7 -0
- package/hook/hook.mjs +169 -0
- package/package.json +2 -1
package/dist/frame.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// What a session reads when room messages arrive: who in the room said
|
|
2
2
|
// what, and whether that is the person the session works for. Claude Code
|
|
3
3
|
// also marks it as from another session; Codex shows it as a user message.
|
|
4
|
-
import { askedText, askNewsText, chatHeader, decisionText, hearerOf, lineOf, noteFor, threadHint, whereOf } from "./mark.js";
|
|
4
|
+
import { ASK_NEWS, askedText, askNewsText, chatHeader, decisionText, hearerOf, lineOf, noteFor, firstOfEach, threadHint, whereOf } from "./mark.js";
|
|
5
5
|
import { roomLabel } from "./seats.js";
|
|
6
6
|
/** The seat as a reader of its room: who it works for, from what the
|
|
7
7
|
* room says (mark.ts owns the rule and the words). */
|
|
@@ -22,16 +22,15 @@ export function decisionFrame(seat, decisions, participants) {
|
|
|
22
22
|
const person = participants.find((p) => p.id === decisions[0]?.participant_id)?.name ?? "The person you work for";
|
|
23
23
|
return decisionText(roomLabel(seat), person, decisions.map((m) => ({ approved: m.event?.type === "approved", request: m.event?.request ?? "your request" })));
|
|
24
24
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
*
|
|
28
|
-
* or let its lease lapse.
|
|
25
|
+
/** What became of this seat's own asks: an agent got it, took it or finished it,
|
|
26
|
+
* Station could not reach an agent, or handed the ask to another, or the
|
|
27
|
+
* agent holding it ran out of usage or let its lease lapse.
|
|
29
28
|
* The event is about the sender's seat. */
|
|
30
29
|
export function askNewsFor(seat, messages) {
|
|
31
30
|
return messages.filter((m) => m.kind === "event" && ASK_NEWS.includes(String(m.event?.type)) && m.participant_id === seat.participantId);
|
|
32
31
|
}
|
|
33
32
|
export function askNewsFrame(seat, news) {
|
|
34
|
-
return askNewsText(roomLabel(seat), news.map((m) => m.body));
|
|
33
|
+
return askNewsText(roomLabel(seat), news.map((m) => ({ body: m.body, message: m.event?.message })));
|
|
35
34
|
}
|
|
36
35
|
/** Someone asking to join the room: an asked event in the stream. */
|
|
37
36
|
export function askedIn(messages) {
|
|
@@ -51,18 +50,25 @@ export function askedFrame(seat, asked, command = "station") {
|
|
|
51
50
|
* what agents said earlier that Station was holding: it goes after the
|
|
52
51
|
* new messages, under its own line, so a person's message is read first
|
|
53
52
|
* and is not the part Codex cuts from a long delivery. */
|
|
54
|
-
export function frame(seat, messages, participants, command = "station", before = []) {
|
|
53
|
+
export function frame(seat, messages, participants, command = "station", before = [], otherRooms = false) {
|
|
54
|
+
// In more than one room, a reply names this one: without a sign-in,
|
|
55
|
+
// station say goes to the room the session joined last.
|
|
56
|
+
const room = otherRooms ? ` --room ${seat.roomId}` : "";
|
|
55
57
|
const hearer = hearerFor(seat, participants, command);
|
|
56
58
|
const byId = new Map(participants.map((p) => [p.id, p]));
|
|
57
59
|
const authorOf = (message) => byId.get(message.participant_id ?? "");
|
|
58
|
-
|
|
60
|
+
// Each author's mention on its first line only, across both lists.
|
|
61
|
+
const all = [...messages, ...before];
|
|
62
|
+
const firsts = firstOfEach(all.map(authorOf));
|
|
63
|
+
const first = new Map(all.map((message, i) => [message, firsts[i]]));
|
|
64
|
+
const line = (message) => lineOf(hearer, authorOf(message), message.body, whereOf(hearer, message, participants), first.get(message));
|
|
59
65
|
const note = noteFor(hearer, [...messages, ...before].map(authorOf));
|
|
60
66
|
// Codex shows this as an ordinary user message, so the header says where it came from.
|
|
61
67
|
// The mark goes before the messages: Codex cuts a long delivery at its end.
|
|
62
68
|
const parts = [chatHeader(roomLabel(seat), seat.name), "", ...(note ? [note, ""] : []), ...messages.map(line), ""];
|
|
63
69
|
if (before.length)
|
|
64
70
|
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>"
|
|
71
|
+
const hint = threadHint(messages.length ? messages : before, `${command} say${room} --reply {thread} "<your reply>"`, `${command} say${room} "<your message>"`, hearer);
|
|
66
72
|
if (hint)
|
|
67
73
|
parts.push(hint);
|
|
68
74
|
return parts.join("\n");
|
package/dist/guard.js
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
|
-
// Two agents can talk each other into an endless exchange.
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
// the room
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
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 =
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
32
|
-
`
|
|
33
|
-
|
|
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
|
-
|
|
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/home.js
CHANGED
|
@@ -24,7 +24,7 @@ export const files = (home) => ({
|
|
|
24
24
|
log: join(home, "daemon.log"),
|
|
25
25
|
/** The tools Station listed last, for a session that starts while it cannot be reached (mcp.ts). */
|
|
26
26
|
tools: join(home, "tools.json"),
|
|
27
|
-
/** The
|
|
27
|
+
/** The folded tools Station listed last for `station mcp`, kept apart from the commands' list. */
|
|
28
28
|
mcpTools: join(home, "tools-mcp.json"),
|
|
29
29
|
/** A `station login` under way (login.ts). */
|
|
30
30
|
login: join(home, "login.json"),
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
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.
|
|
14
|
+
// Codex uses a synchronous Stop and keeps its queue or router for idle turns.
|
|
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 { codexHome } from "./codex.js";
|
|
20
|
+
import { files, readJson } from "./home.js";
|
|
21
|
+
import { Usage } from "./usage.js";
|
|
22
|
+
/** The protocol the hook script and the daemon speak (hook.mjs PROTOCOL). */
|
|
23
|
+
export const HOOK_PROTOCOL = 1;
|
|
24
|
+
/** The events Station hooks. Stop waits in the background for a day, the longest a session sits idle and still gets woken. */
|
|
25
|
+
export const HOOK_EVENTS = [
|
|
26
|
+
{ event: "UserPromptSubmit", timeout: 5 },
|
|
27
|
+
{ event: "PostToolUse", timeout: 5 },
|
|
28
|
+
{ event: "Stop", timeout: 86_400, asyncRewake: true },
|
|
29
|
+
{ event: "SessionEnd", timeout: 5 },
|
|
30
|
+
];
|
|
31
|
+
const CODEX_EVENTS = [
|
|
32
|
+
{ event: "UserPromptSubmit", timeout: 5 },
|
|
33
|
+
{ event: "PostToolUse", timeout: 5 },
|
|
34
|
+
{ event: "Stop", timeout: 5 },
|
|
35
|
+
];
|
|
36
|
+
/** The script this package ships, copied into Station's home on install. */
|
|
37
|
+
export const HOOK_SOURCE = fileURLToPath(new URL("../hook/hook.mjs", import.meta.url));
|
|
38
|
+
export const hookScript = (home) => join(home, "hook.mjs");
|
|
39
|
+
/** The person allowed hooks on this computer when they approved its sign-in. */
|
|
40
|
+
export function hooksAllowed(home) {
|
|
41
|
+
return readJson(files(home).credentials, null)?.allowHooks === true;
|
|
42
|
+
}
|
|
43
|
+
/** STATION_HOOKS=off: none for this process. */
|
|
44
|
+
export const hooksOffHere = (env = process.env) => (env.STATION_HOOKS ?? "").toLowerCase() === "off";
|
|
45
|
+
/** Where Claude Code reads a person's own hooks from. */
|
|
46
|
+
export const hooksFile = (env = process.env) => join(claudeHome(env), "settings.json");
|
|
47
|
+
export const codexHooksFile = (home = codexHome()) => join(home, "hooks.json");
|
|
48
|
+
const quote = (part) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(part) ? part : `'${part.replace(/'/g, `'\\''`)}'`);
|
|
49
|
+
/** What Claude Code runs: Node by its absolute path, so no npx, PATH or nvm in between. */
|
|
50
|
+
export const hookCommand = (home, node = process.execPath) => [node, hookScript(home), files(home).socket].map(quote).join(" ");
|
|
51
|
+
/** 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>`. */
|
|
52
|
+
export const isStationHook = (command) => typeof command === "string" && (/[/\\]hook\.mjs'? +(?:'(?:[^']|'\\'')*\.sock'|[^ ']*\.sock)$/.test(command.trim()) || /(^|[/\\ '"])(station|cli\.js)'?"? hook (claude-code|codex)$/.test(command.trim()));
|
|
53
|
+
/** The config without Station's entries. Everything else stays as it was. */
|
|
54
|
+
export function withoutStationHooks(config, owns = isStationHook) {
|
|
55
|
+
if (!config.hooks || typeof config.hooks !== "object")
|
|
56
|
+
return config;
|
|
57
|
+
const events = {};
|
|
58
|
+
let removed = false;
|
|
59
|
+
for (const [event, groups] of Object.entries(config.hooks)) {
|
|
60
|
+
if (!Array.isArray(groups)) {
|
|
61
|
+
events[event] = groups;
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
const kept = groups.flatMap((group) => {
|
|
65
|
+
if (!Array.isArray(group?.hooks))
|
|
66
|
+
return [group];
|
|
67
|
+
const handlers = group.hooks.filter((handler) => !owns(handler?.command));
|
|
68
|
+
if (handlers.length === group.hooks.length)
|
|
69
|
+
return [group];
|
|
70
|
+
removed = true;
|
|
71
|
+
return handlers.length ? [{ ...group, hooks: handlers }] : [];
|
|
72
|
+
});
|
|
73
|
+
if (kept.length || !groups.length)
|
|
74
|
+
events[event] = kept;
|
|
75
|
+
}
|
|
76
|
+
if (!removed)
|
|
77
|
+
return config;
|
|
78
|
+
const { hooks: _, ...rest } = config;
|
|
79
|
+
return Object.keys(events).length ? { ...rest, hooks: events } : rest;
|
|
80
|
+
}
|
|
81
|
+
/** The config with Station's entries, once each. */
|
|
82
|
+
export function withStationHooks(config, command, definitions = HOOK_EVENTS, owns = isStationHook) {
|
|
83
|
+
const clean = withoutStationHooks(config, owns);
|
|
84
|
+
const events = { ...(clean.hooks ?? {}) };
|
|
85
|
+
for (const { event, ...rest } of definitions)
|
|
86
|
+
events[event] = [...(events[event] ?? []), { hooks: [{ type: "command", command, ...rest }] }];
|
|
87
|
+
return { ...clean, hooks: events };
|
|
88
|
+
}
|
|
89
|
+
/** Whether the file holds Station's entry for every event. */
|
|
90
|
+
export function hasStationHooks(config) {
|
|
91
|
+
return HOOK_EVENTS.every(({ event }) => (config.hooks?.[event] ?? []).some((group) => (group?.hooks ?? []).some((handler) => isStationHook(handler?.command))));
|
|
92
|
+
}
|
|
93
|
+
function readConfig(path) {
|
|
94
|
+
if (!existsSync(path))
|
|
95
|
+
return {};
|
|
96
|
+
try {
|
|
97
|
+
const value = JSON.parse(readFileSync(path, "utf8"));
|
|
98
|
+
if (value && typeof value === "object" && !Array.isArray(value))
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
// falls through
|
|
103
|
+
}
|
|
104
|
+
// Never write over a file Station cannot read: it is the person's.
|
|
105
|
+
throw new Usage(`${path} is not JSON Station can read, so Station left it alone. Fix or remove it, then join again.`);
|
|
106
|
+
}
|
|
107
|
+
/** Writes the settings where they really live: a settings.json linked to
|
|
108
|
+
* a dotfiles copy stays a link, and the file keeps its mode. */
|
|
109
|
+
function writeSettings(path, value) {
|
|
110
|
+
const target = existsSync(path) ? realpathSync(path) : path;
|
|
111
|
+
const mode = existsSync(target) ? statSync(target).mode & 0o777 : 0o600;
|
|
112
|
+
const temp = `${target}.${process.pid}.tmp`;
|
|
113
|
+
writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`, { mode });
|
|
114
|
+
chmodSync(temp, mode);
|
|
115
|
+
renameSync(temp, target);
|
|
116
|
+
}
|
|
117
|
+
/** Copies the script into Station's home and writes Station's entries into Claude Code's settings, backing the file up first. */
|
|
118
|
+
export function installHooks(home, env = process.env, source = HOOK_SOURCE, node = process.execPath) {
|
|
119
|
+
const path = hooksFile(env);
|
|
120
|
+
return install(home, path, source, (before) => withStationHooks(before, hookCommand(home, node)));
|
|
121
|
+
}
|
|
122
|
+
const codexHookArgs = (home) => [hookScript(home), files(home).socket, "codex"].map(quote).join(" ");
|
|
123
|
+
const ownsCodexHook = (home) => (command) => typeof command === "string" && command.trim().endsWith(` ${codexHookArgs(home)}`);
|
|
124
|
+
export function installCodexHooks(home, profile, source = HOOK_SOURCE, node = process.execPath) {
|
|
125
|
+
const path = codexHooksFile(profile);
|
|
126
|
+
const command = `${quote(node)} ${codexHookArgs(home)}`;
|
|
127
|
+
const owns = ownsCodexHook(home);
|
|
128
|
+
return install(home, path, source, (before) => {
|
|
129
|
+
if (before.hooks !== undefined && (!before.hooks || typeof before.hooks !== "object" || Array.isArray(before.hooks) ||
|
|
130
|
+
CODEX_EVENTS.some(({ event }) => event in before.hooks && !Array.isArray(before.hooks[event])))) {
|
|
131
|
+
throw new Usage(`${path} does not contain a Codex hook configuration Station can update, so Station left it alone.`);
|
|
132
|
+
}
|
|
133
|
+
const hooks = { ...before.hooks };
|
|
134
|
+
for (const definition of CODEX_EVENTS) {
|
|
135
|
+
const { event, timeout } = definition;
|
|
136
|
+
const groups = hooks[event] ?? [];
|
|
137
|
+
const owned = groups.flatMap((group) => Array.isArray(group?.hooks) ? group.hooks.filter((handler) => owns(handler?.command)).map((handler) => ({ group, handler })) : []);
|
|
138
|
+
const existing = owned.length === 1 ? owned[0] : undefined;
|
|
139
|
+
if (existing && !existing.group.matcher && existing.handler.command === command && existing.handler.type === "command" &&
|
|
140
|
+
existing.handler.timeout === timeout && (existing.handler.async === undefined || existing.handler.async === false))
|
|
141
|
+
continue;
|
|
142
|
+
hooks[event] = withStationHooks({ hooks: { [event]: groups } }, command, [definition], owns).hooks[event];
|
|
143
|
+
}
|
|
144
|
+
return { ...before, hooks };
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
function install(home, path, source, update) {
|
|
148
|
+
const before = readConfig(path);
|
|
149
|
+
const after = update(before);
|
|
150
|
+
mkdirSync(home, { recursive: true });
|
|
151
|
+
// The script is copied only when it changed (a new Station), so a call with nothing to do writes nothing.
|
|
152
|
+
if (!existsSync(hookScript(home)) || !readFileSync(source).equals(readFileSync(hookScript(home))))
|
|
153
|
+
copyFileSync(source, hookScript(home));
|
|
154
|
+
if (JSON.stringify(before) === JSON.stringify(after))
|
|
155
|
+
return { path, changed: false, backup: null };
|
|
156
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
157
|
+
const backup = existsSync(path) ? `${path}.before-station` : null;
|
|
158
|
+
if (backup)
|
|
159
|
+
copyFileSync(path, backup);
|
|
160
|
+
writeSettings(path, after);
|
|
161
|
+
return { path, changed: true, backup };
|
|
162
|
+
}
|
|
163
|
+
/** Takes Station's entries out of Claude Code's settings. */
|
|
164
|
+
export function removeHooks(env = process.env) {
|
|
165
|
+
return removeFrom(hooksFile(env), isStationHook);
|
|
166
|
+
}
|
|
167
|
+
export function removeCodexHooks(home, profile) {
|
|
168
|
+
return removeFrom(codexHooksFile(profile), ownsCodexHook(home));
|
|
169
|
+
}
|
|
170
|
+
function removeFrom(path, owns) {
|
|
171
|
+
if (!existsSync(path))
|
|
172
|
+
return { path, changed: false, backup: null };
|
|
173
|
+
let before;
|
|
174
|
+
try {
|
|
175
|
+
before = readConfig(path);
|
|
176
|
+
}
|
|
177
|
+
catch {
|
|
178
|
+
return { path, changed: false, backup: null };
|
|
179
|
+
}
|
|
180
|
+
const after = withoutStationHooks(before, owns);
|
|
181
|
+
const changed = after !== before;
|
|
182
|
+
if (changed)
|
|
183
|
+
writeSettings(path, after);
|
|
184
|
+
return { path, changed, backup: null };
|
|
185
|
+
}
|
|
186
|
+
/** Station's hooks for Claude Code, written when the person allowed them
|
|
187
|
+
* and nothing turned them off. `change` is null when they are not in place:
|
|
188
|
+
* not allowed, or `failed` says why they could not be written. */
|
|
189
|
+
export function hooksReady(home, env = process.env, codexProfile) {
|
|
190
|
+
if (!hooksAllowed(home) || hooksOffHere(env))
|
|
191
|
+
return { change: null, failed: null };
|
|
192
|
+
try {
|
|
193
|
+
return { change: codexProfile ? installCodexHooks(home, codexProfile) : installHooks(home, env), failed: null };
|
|
194
|
+
}
|
|
195
|
+
catch (error) {
|
|
196
|
+
return { change: null, failed: error instanceof Usage ? error.message : `Station could not write its hooks to ${codexProfile ? codexHooksFile(codexProfile) : hooksFile(env)}: ${error instanceof Error ? error.message : String(error)}.` };
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
export const codexHooksJoinLine = (hooks) => `Review and trust Station's hooks in Codex with /hooks to get room messages during a turn.${hooks.changed ? ` Station wrote them to ${hooks.path}.` : ""}`;
|
|
200
|
+
/** What `station join` says about Station's hooks in a Claude Code
|
|
201
|
+
* session, on every join: how messages come in, and that its person chose
|
|
202
|
+
* it. Where the file is only when this join wrote it. */
|
|
203
|
+
export function hooksJoinLine(hooks) {
|
|
204
|
+
const where = hooks.changed ? ` Station's hooks are in ${hooks.path}${hooks.backup ? ` (your old file: ${hooks.backup})` : ""}.` : "";
|
|
205
|
+
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}`;
|
|
206
|
+
}
|