@santori/station 0.9.9 → 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/README.md +59 -31
- package/dist/agentToken.js +14 -5
- package/dist/agents.js +14 -9
- package/dist/args.js +139 -6
- package/dist/caller.js +0 -7
- package/dist/claude.js +4 -1
- package/dist/cli.js +256 -145
- package/dist/codex.js +80 -16
- package/dist/commands.js +89 -18
- package/dist/daemon.js +385 -29
- package/dist/frame.js +17 -26
- package/dist/guard.js +11 -8
- package/dist/guest.js +10 -5
- package/dist/handover.js +19 -6
- package/dist/home.js +3 -1
- package/dist/hooks.js +169 -0
- package/dist/join.js +250 -125
- package/dist/login.js +161 -234
- package/dist/mark.js +116 -14
- package/dist/mcp.js +14 -5
- package/dist/node.js +14 -0
- package/dist/own.js +42 -0
- package/dist/programs.js +50 -0
- package/dist/relay.js +1 -1
- package/dist/rooms.js +2 -4
- package/dist/seats.js +14 -2
- package/dist/sessions.js +37 -7
- package/dist/starts.js +21 -14
- package/dist/tool.js +14 -5
- package/dist/waking.js +57 -20
- package/dist/webhooks.js +30 -42
- package/hook/hook.mjs +149 -0
- package/package.json +3 -2
package/dist/waking.js
CHANGED
|
@@ -21,8 +21,9 @@
|
|
|
21
21
|
//
|
|
22
22
|
// One run at a time for each agent in each room: a wake that comes while
|
|
23
23
|
// one runs waits for it.
|
|
24
|
-
import { rmSync, writeFileSync } from "node:fs";
|
|
24
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
25
25
|
import { join } from "node:path";
|
|
26
|
+
import { codexHome, lastFolder } from "./codex.js";
|
|
26
27
|
import { readCredentials, readJson, writeJson } from "./home.js";
|
|
27
28
|
import { agentLimit, describeLimit } from "./limits.js";
|
|
28
29
|
import { call, RelayError } from "./relay.js";
|
|
@@ -64,9 +65,24 @@ export function createWaking(deps) {
|
|
|
64
65
|
const { home, log } = deps;
|
|
65
66
|
const start = deps.start ?? startAgent;
|
|
66
67
|
const limitOf = deps.limitOf ?? ((harness, id) => agentLimit(harness, id));
|
|
67
|
-
const deliver = deps.deliver ?? deliverTo;
|
|
68
|
-
const isOpen = deps.isOpen ?? ((seat) => delivers(seat.harness) && isRunning(seat.harness, seat.sessionId));
|
|
68
|
+
const deliver = deps.deliver ?? ((chat, messageId, text) => deliverTo(chat.harness, chat.sessionId, messageId, text, chat.codexHome));
|
|
69
|
+
const isOpen = deps.isOpen ?? ((seat) => delivers(seat.harness) && isRunning(seat.harness, seat.sessionId, seat.codexHome));
|
|
69
70
|
const sleep = deps.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
71
|
+
const ownFolder = deps.ownFolder ?? ((kind) => (kind === "codex" ? lastFolder(codexHome()) : null));
|
|
72
|
+
/** Where a run of its own starts: the folder the agent last worked in
|
|
73
|
+
* here (its seat in this room, else its newest), the one `station add`
|
|
74
|
+
* ran in, or where the agent last worked by its own records. With none
|
|
75
|
+
* of those (no window of it joined from this computer and no `station
|
|
76
|
+
* add` here), a folder Station keeps for it, so an ask is never lost for
|
|
77
|
+
* want of a folder. */
|
|
78
|
+
function startFolder(kind, wake) {
|
|
79
|
+
const known = [lastSession(deps.seats(), wake.agent.id, wake.room)?.cwd, folderOf(home, wake.agent.id), ownFolder(kind)].find((dir) => Boolean(dir) && existsSync(dir));
|
|
80
|
+
if (known)
|
|
81
|
+
return known;
|
|
82
|
+
const own = join(home, "work", kind);
|
|
83
|
+
mkdirSync(own, { recursive: true });
|
|
84
|
+
return own;
|
|
85
|
+
}
|
|
70
86
|
/** Runs under way, by agent and room. */
|
|
71
87
|
const runs = new Map();
|
|
72
88
|
/** The asks being started or waiting to be, by agent, room and message. */
|
|
@@ -103,7 +119,19 @@ export function createWaking(deps) {
|
|
|
103
119
|
}
|
|
104
120
|
}
|
|
105
121
|
}
|
|
106
|
-
|
|
122
|
+
async function answer(credentials, wake, outcome, why) {
|
|
123
|
+
const send = () => call(credentials.relayUrl, "/cli/wakes", { token: credentials.token }, { body: { room: wake.room, message: wake.message, agent: wake.agent.id, outcome, ...(why ? { why } : {}) } });
|
|
124
|
+
try {
|
|
125
|
+
await send().catch((error) => {
|
|
126
|
+
if (outcome === "started" && error instanceof RelayError && error.status === 0)
|
|
127
|
+
return send();
|
|
128
|
+
throw error;
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
log(`wake ${wake.message} answer ${outcome} not sent: ${error instanceof Error ? error.message : String(error)}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
107
135
|
/** Out of usage, by the agent's newest session here, or the room's earlier start. */
|
|
108
136
|
function outOfUsage(kind, wake) {
|
|
109
137
|
const sessions = [];
|
|
@@ -130,15 +158,18 @@ export function createWaking(deps) {
|
|
|
130
158
|
// The agent's last chat, closed: the ask continues that same chat in the
|
|
131
159
|
// background, so it is there when the person opens it. Else a run of its own.
|
|
132
160
|
const folder = last?.cwd ?? folderOf(home, wake.agent.id);
|
|
133
|
-
|
|
134
|
-
//
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
161
|
+
let plan;
|
|
162
|
+
// A chat whose folder is gone (a removed worktree) cannot go on there: a run of its own instead.
|
|
163
|
+
const continues = last && folder && existsSync(folder) ? last : null;
|
|
164
|
+
if (continues && folder)
|
|
165
|
+
plan = { kind, session: continues.sessionId, cwd: folder, resume: continues.sessionId };
|
|
166
|
+
else {
|
|
167
|
+
const fresh = planFor(home, wake, kind, startFolder(kind, wake));
|
|
168
|
+
// One agent, one presence in a room: a run of its own acts as the agent's
|
|
169
|
+
// seat there that no session holds now (a codex exec that ended, a closed
|
|
170
|
+
// window), so it takes that seat back rather than a second one.
|
|
171
|
+
const there = deps.seats().find((seat) => seat.agentId === wake.agent.id && seat.roomId === wake.room && !isOpen(seat) && seat.sessionId !== fresh.session);
|
|
172
|
+
plan = there ? { ...fresh, session: there.sessionId } : fresh;
|
|
142
173
|
}
|
|
143
174
|
let seat;
|
|
144
175
|
try {
|
|
@@ -182,7 +213,7 @@ export function createWaking(deps) {
|
|
|
182
213
|
rmSync(tokenFile, { force: true });
|
|
183
214
|
deps.leave(seat);
|
|
184
215
|
if (end.code === 0) {
|
|
185
|
-
if (!
|
|
216
|
+
if (!continues)
|
|
186
217
|
saveStart(home, wake.agent.id, wake.room, { ...plan, resume: end.resume });
|
|
187
218
|
return;
|
|
188
219
|
}
|
|
@@ -202,8 +233,10 @@ export function createWaking(deps) {
|
|
|
202
233
|
await answer(credentials, wake, "failed", `this computer cannot start ${wake.agent.name}`);
|
|
203
234
|
return;
|
|
204
235
|
}
|
|
205
|
-
// The
|
|
206
|
-
|
|
236
|
+
// The session it is for (sent to it, or the one that began the thread), while its window is open;
|
|
237
|
+
// else the agent's last chat here: its newest Claude Code or Codex window, in any room.
|
|
238
|
+
const asked = wake.seat ? deps.seats().find((seat) => seat.participantId === wake.seat && seat.agentId === wake.agent.id) : undefined;
|
|
239
|
+
const last = wake.seat_only ? asked ?? null : (asked && isOpen(asked) ? asked : lastChat(deps.seats(), wake.agent.id));
|
|
207
240
|
const key = `${wake.agent.id}:${last ? last.sessionId : wake.room}`;
|
|
208
241
|
// One run per ask, however often it is handed out.
|
|
209
242
|
const ask = `${wake.agent.id}:${wake.room}:${wake.message}`;
|
|
@@ -214,9 +247,13 @@ export function createWaking(deps) {
|
|
|
214
247
|
// Its window is open: the ask goes into that chat, once it can take a turn.
|
|
215
248
|
if (last && isOpen(last) && (await intoWindow(credentials, wake, last)))
|
|
216
249
|
return;
|
|
250
|
+
if (wake.seat_only) {
|
|
251
|
+
await answer(credentials, wake, "failed", "the addressed window is not open on this computer");
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
217
254
|
// Someone else's ask: Station starts the agent only for its own person.
|
|
218
255
|
if (wake.may_start === false) {
|
|
219
|
-
await answer(credentials, wake, "failed", `Station starts ${wake.agent.name} only for
|
|
256
|
+
await answer(credentials, wake, "failed", `Station starts ${wake.agent.name} only for messages from its own person or their agents, and no window of it is open here`);
|
|
220
257
|
return;
|
|
221
258
|
}
|
|
222
259
|
const before = runs.get(key);
|
|
@@ -238,7 +275,7 @@ export function createWaking(deps) {
|
|
|
238
275
|
async function intoWindow(credentials, wake, chat) {
|
|
239
276
|
let told = false;
|
|
240
277
|
for (let attempt = 0; attempt < 120 && isOpen(chat); attempt++) {
|
|
241
|
-
const outcome = await deliver(chat
|
|
278
|
+
const outcome = await deliver(chat, `station-ask-${wake.room}-${wake.message}`, startPrompt(wake, credentials.relayUrl, false));
|
|
242
279
|
if (outcome.kind !== "retry") {
|
|
243
280
|
log(`wake ${wake.message}: put into ${wake.agent.name}'s open chat ${chat.sessionId}`);
|
|
244
281
|
await answer(credentials, wake, "started");
|
|
@@ -259,9 +296,9 @@ export function createWaking(deps) {
|
|
|
259
296
|
/** One read of the relay's wakes. */
|
|
260
297
|
async once(waitSeconds = 25) {
|
|
261
298
|
const credentials = readCredentials(home);
|
|
262
|
-
if (!credentials)
|
|
299
|
+
if (!credentials || credentials.agent)
|
|
263
300
|
return null;
|
|
264
|
-
const got = await call(credentials.relayUrl, `/cli/wakes?wait=${waitSeconds}`, { token: credentials.token });
|
|
301
|
+
const got = await call(credentials.relayUrl, `/cli/wakes?wait=${waitSeconds}&seat_only=1`, { token: credentials.token });
|
|
265
302
|
installsOn = got.installs.some((install) => install.on);
|
|
266
303
|
for (const wake of got.wakes) {
|
|
267
304
|
log(`wake for ${wake.agent.name} in room ${wake.room}, message ${wake.message}`);
|
package/dist/webhooks.js
CHANGED
|
@@ -1,30 +1,11 @@
|
|
|
1
|
-
// `station webhook`: the person points their
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// in, so the receiver's key is typed there and never passes through the
|
|
1
|
+
// `station webhook`: the person points one of their agents at a URL, and
|
|
2
|
+
// the relay posts there when something in any of its rooms is for it: how
|
|
3
|
+
// a Grok Bot routine or another hosted agent is woken (docs/webhooks.md).
|
|
4
|
+
// The person runs these in their own terminal, signed in, so the receiver's key is typed there and never passes through the
|
|
6
5
|
// agent: it is asked for, not taken as a flag.
|
|
7
6
|
import { createInterface } from "node:readline";
|
|
8
7
|
import { call } from "./relay.js";
|
|
9
|
-
import { roomRef } from "./rooms.js";
|
|
10
8
|
import { Usage } from "./usage.js";
|
|
11
|
-
/** Which agent: the one named (its name or seat id), else the one agent in
|
|
12
|
-
* the room that is the person's own. */
|
|
13
|
-
export function pickAgent(seats, wanted) {
|
|
14
|
-
const agents = seats.filter((seat) => seat.kind === "agent");
|
|
15
|
-
if (wanted) {
|
|
16
|
-
const found = agents.find((seat) => seat.id === wanted) ?? agents.filter((seat) => seat.name === wanted).at(-1);
|
|
17
|
-
if (!found)
|
|
18
|
-
throw new Usage(`No agent called "${wanted}" in this room. Agents here: ${agents.map((a) => `"${a.name}"`).join(", ") || "none"}.`);
|
|
19
|
-
return found;
|
|
20
|
-
}
|
|
21
|
-
const mine = agents.filter((seat) => seat.for?.you && !seat.left_at);
|
|
22
|
-
if (mine.length === 1)
|
|
23
|
-
return mine[0];
|
|
24
|
-
if (!mine.length)
|
|
25
|
-
throw new Usage(`None of the agents in this room is yours yet. Name one with --agent "<name>"; it has to be yours (claim it first if it was let in).`);
|
|
26
|
-
throw new Usage(`More than one of your agents is in this room: ${mine.map((a) => `"${a.name}"`).join(", ")}. Say which with --agent "<name>".`);
|
|
27
|
-
}
|
|
28
9
|
/** Reads the header's value: from a pipe as is, or asked for in a terminal
|
|
29
10
|
* without showing what is typed. */
|
|
30
11
|
export async function readSecret(prompt, input = process.stdin, output = process.stderr) {
|
|
@@ -69,36 +50,43 @@ export function addResult(webhook, result) {
|
|
|
69
50
|
const why = result.status ? `${host} answered ${result.status}.` : result.error ?? `nothing reached ${host}.`;
|
|
70
51
|
return [`It did not work: ${why} Nothing was saved.`, `Fix that, then run the command again.`];
|
|
71
52
|
}
|
|
72
|
-
export function webhookLines(hooks) {
|
|
53
|
+
export function webhookLines(hooks, agent) {
|
|
73
54
|
if (!hooks.length)
|
|
74
|
-
return [
|
|
55
|
+
return [`No webhooks for ${agent}.`];
|
|
75
56
|
return hooks.map((h) => {
|
|
76
57
|
const last = h.last_error ? (h.last_error.startsWith("Not woken") ? h.last_error : `last try failed: ${h.last_error}`) : h.last_sent_at ? `last sent ${h.last_sent_at} (${h.last_status})` : "nothing sent yet";
|
|
77
58
|
const header = h.header ? `, header ${h.header.name}: ${h.header.value}` : "";
|
|
78
59
|
const debounce = h.debounce_seconds ? `, debounce ${h.debounce_seconds}s` : "";
|
|
79
60
|
const wakes = h.wakes_per_day ? `, ${h.wakes_today ?? 0} of ${h.wakes_per_day} wakes today` : "";
|
|
80
|
-
return `${h.id} ${h.agent ?? h.
|
|
61
|
+
return `${h.id} ${h.agent ?? h.agent_id} → ${h.url} on ${h.on.join(",")}${debounce}${wakes}${header}${h.signed ? ", signed" : ""}; ${last}`;
|
|
81
62
|
});
|
|
82
63
|
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
${me} webhook
|
|
89
|
-
|
|
64
|
+
/** `seatAgent`: the agent of this session's seat, when there is one, for a
|
|
65
|
+
* command run without --agent. */
|
|
66
|
+
export async function webhookCommand(credentials, args, flag, out, me, seatAgent = null) {
|
|
67
|
+
const [sub, id] = args;
|
|
68
|
+
const usage = `${me} webhook add [--agent <name, kind or id>] --url <https url> [--header-name Authorization] [--sign] [--on message,approval,asked] [--debounce 30] [--wakes-per-day 60]
|
|
69
|
+
${me} webhook list [--agent <name>]
|
|
70
|
+
${me} webhook test [--agent <name>] <webhook id>
|
|
71
|
+
${me} webhook remove [--agent <name>] <webhook id>
|
|
72
|
+
Without --agent: the agent of this session's seat.`;
|
|
73
|
+
if (!sub)
|
|
90
74
|
throw new Usage(usage);
|
|
91
|
-
|
|
92
|
-
if (
|
|
93
|
-
throw new Usage(`
|
|
75
|
+
// A webhook is the agent's, for all its rooms: a room is not part of it any more.
|
|
76
|
+
if ((sub === "add" || sub === "list") && id)
|
|
77
|
+
throw new Usage(`A webhook wakes the agent for every room it is in, so it takes no room. Name the agent with --agent instead.\n${usage}`);
|
|
78
|
+
const named = flag("agent");
|
|
79
|
+
const agent = named && named !== "true" ? named : seatAgent;
|
|
80
|
+
if (!agent)
|
|
81
|
+
throw new Usage(`Say which of your agents with --agent "<its name>", codex or claude, or run this from a session with a seat.\n${usage}`);
|
|
82
|
+
const { relayUrl } = credentials;
|
|
94
83
|
const auth = { token: credentials.token };
|
|
95
|
-
const base =
|
|
84
|
+
const base = `/me/agents/${encodeURIComponent(agent)}/webhooks`;
|
|
85
|
+
const testCommand = (hook) => `${me} webhook test${named ? ` --agent ${JSON.stringify(agent)}` : ""} ${hook}`;
|
|
96
86
|
if (sub === "add") {
|
|
97
87
|
const url = flag("url");
|
|
98
88
|
if (!url)
|
|
99
89
|
throw new Usage(usage);
|
|
100
|
-
const { participants } = await call(relayUrl, `/${roomId}`, auth);
|
|
101
|
-
const agent = pickAgent(participants, flag("agent"));
|
|
102
90
|
const headerName = flag("header-name");
|
|
103
91
|
let header;
|
|
104
92
|
if (headerName) {
|
|
@@ -113,7 +101,7 @@ ${me} webhook remove <room> <webhook id>`;
|
|
|
113
101
|
if (sign !== undefined && sign !== "true" && sign !== "false")
|
|
114
102
|
throw new Usage("Use --sign to generate a signing secret.");
|
|
115
103
|
const { webhook, signing_secret } = await call(relayUrl, base, auth, {
|
|
116
|
-
body: {
|
|
104
|
+
body: { url, header, sign: sign === "true" ? true : undefined, on: flag("on")?.split(","), debounce_seconds: debounce === undefined ? undefined : Number(debounce.replace(/s$/, "")), wakes_per_day: wakes === undefined ? undefined : Number(wakes) },
|
|
117
105
|
});
|
|
118
106
|
if (sign === "true") {
|
|
119
107
|
if (!signing_secret) {
|
|
@@ -121,7 +109,7 @@ ${me} webhook remove <room> <webhook id>`;
|
|
|
121
109
|
throw new Error("The relay did not return a signing secret. Try again on a relay that supports signing.");
|
|
122
110
|
}
|
|
123
111
|
out(`Signing secret (shown once): ${signing_secret}`);
|
|
124
|
-
out(`Set this secret on the receiver, then run: ${
|
|
112
|
+
out(`Set this secret on the receiver, then run: ${testCommand(webhook.id)}`);
|
|
125
113
|
return 0;
|
|
126
114
|
}
|
|
127
115
|
// Send the test now, so the person learns here whether the key works. A
|
|
@@ -135,7 +123,7 @@ ${me} webhook remove <room> <webhook id>`;
|
|
|
135
123
|
}
|
|
136
124
|
if (sub === "list") {
|
|
137
125
|
const { webhooks } = await call(relayUrl, base, auth);
|
|
138
|
-
for (const line of webhookLines(webhooks))
|
|
126
|
+
for (const line of webhookLines(webhooks, agent))
|
|
139
127
|
out(line);
|
|
140
128
|
return 0;
|
|
141
129
|
}
|
package/hook/hook.mjs
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Station's Claude Code hook. `station join` copies this file to
|
|
3
|
+
// ~/.station/hook.mjs once the person allowed hooks on this computer, and
|
|
4
|
+
// Claude Code runs it by Node's absolute path, with the hook's event as
|
|
5
|
+
// JSON on stdin and the daemon's socket as its one argument.
|
|
6
|
+
//
|
|
7
|
+
// It holds no state. It asks the daemon, which owns the seats, their
|
|
8
|
+
// cursors and the receipts, and carries back what the daemon gives it:
|
|
9
|
+
//
|
|
10
|
+
// - UserPromptSubmit, PostToolUse: new room messages for this session's
|
|
11
|
+
// seats, the people's own words, as additionalContext between steps;
|
|
12
|
+
// - Stop (run with asyncRewake, in the background): waits on the daemon
|
|
13
|
+
// until something comes for the session, then exits 2 with it on stderr,
|
|
14
|
+
// which wakes the idle session;
|
|
15
|
+
// - SessionEnd: tells the daemon the session ended.
|
|
16
|
+
//
|
|
17
|
+
// It never stops Claude Code: any failure exits 0 and goes to hook.log
|
|
18
|
+
// next to this file. STATION_HOOKS=off in Claude Code's environment turns
|
|
19
|
+
// it off for that process. Under any other agent that reads Claude Code's
|
|
20
|
+
// hooks (Grok Build) it does nothing. Plain Node 20+, no packages.
|
|
21
|
+
import { appendFileSync } from "node:fs";
|
|
22
|
+
import { connect } from "node:net";
|
|
23
|
+
import { dirname, join, resolve as absolute } from "node:path";
|
|
24
|
+
import { fileURLToPath } from "node:url";
|
|
25
|
+
|
|
26
|
+
/** The hook and the daemon agree on this; a daemon that does not answers with an error and the hook does nothing. */
|
|
27
|
+
const PROTOCOL = 1;
|
|
28
|
+
const HOME = dirname(fileURLToPath(import.meta.url));
|
|
29
|
+
const SOCKET = process.argv[2] || join(HOME, "daemon.sock");
|
|
30
|
+
/** How long one ask between steps may take: past it the step goes on without the messages. */
|
|
31
|
+
const STEP_MS = 1500;
|
|
32
|
+
/** One wait on the daemon. The daemon answers before this with "keep waiting". */
|
|
33
|
+
const WAIT_MS = 60_000;
|
|
34
|
+
|
|
35
|
+
const log = (line) => {
|
|
36
|
+
try {
|
|
37
|
+
appendFileSync(join(HOME, "hook.log"), `${new Date().toISOString()} ${line}\n`, { mode: 0o600 });
|
|
38
|
+
} catch {}
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
/** One JSON line to the daemon and its one-line answer. */
|
|
42
|
+
function ask(request, timeoutMs) {
|
|
43
|
+
return new Promise((resolve, reject) => {
|
|
44
|
+
const socket = connect(SOCKET);
|
|
45
|
+
let buffer = "";
|
|
46
|
+
const timer = setTimeout(() => {
|
|
47
|
+
socket.destroy();
|
|
48
|
+
reject(new Error("the daemon did not answer in time"));
|
|
49
|
+
}, timeoutMs);
|
|
50
|
+
// Claude Code's profile, where the daemon finds whether this session still runs.
|
|
51
|
+
socket.on("connect", () => socket.write(`${JSON.stringify({ ...request, v: PROTOCOL, configDir: process.env.CLAUDE_CONFIG_DIR ? absolute(process.env.CLAUDE_CONFIG_DIR) : "" })}\n`));
|
|
52
|
+
socket.on("data", (chunk) => {
|
|
53
|
+
buffer += chunk.toString("utf8");
|
|
54
|
+
const end = buffer.indexOf("\n");
|
|
55
|
+
if (end < 0) return;
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
socket.end();
|
|
58
|
+
try {
|
|
59
|
+
resolve(JSON.parse(buffer.slice(0, end)));
|
|
60
|
+
} catch (error) {
|
|
61
|
+
reject(error);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
socket.on("error", (error) => {
|
|
65
|
+
clearTimeout(timer);
|
|
66
|
+
reject(error);
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const write = (stream, text) => new Promise((resolve) => stream.write(text, () => resolve()));
|
|
72
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
73
|
+
|
|
74
|
+
async function main() {
|
|
75
|
+
if ((process.env.STATION_HOOKS ?? "").toLowerCase() === "off") return 0;
|
|
76
|
+
// Grok Build runs the hooks in Claude Code's settings too, and waits on
|
|
77
|
+
// Stop at the end of each turn. It sets GROK_HOOK_EVENT on every hook it
|
|
78
|
+
// runs, after the entry's own env. CLAUDE_PROJECT_DIR is no sign of
|
|
79
|
+
// Claude Code: Grok sets it as well.
|
|
80
|
+
if (process.env.GROK_HOOK_EVENT) return 0;
|
|
81
|
+
let input = "";
|
|
82
|
+
for await (const chunk of process.stdin) input += chunk;
|
|
83
|
+
const event = JSON.parse(input);
|
|
84
|
+
// Inside a subagent the context would go to the subagent, not to the agent that holds the seat.
|
|
85
|
+
if (!event || typeof event !== "object" || event.agent_id) return 0;
|
|
86
|
+
const name = event.hook_event_name;
|
|
87
|
+
const sessionId = typeof event.session_id === "string" ? event.session_id : "";
|
|
88
|
+
if (!sessionId) return 0;
|
|
89
|
+
|
|
90
|
+
if (name === "UserPromptSubmit" || name === "PostToolUse" || name === "PostToolBatch") {
|
|
91
|
+
const answer = await ask({ op: "hook", sessionId, event: name }, STEP_MS);
|
|
92
|
+
if (!answer.ok) {
|
|
93
|
+
log(`${name}: ${answer.error}`);
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
96
|
+
if (!answer.text || !answer.token) return 0;
|
|
97
|
+
await write(process.stdout, `${JSON.stringify({ hookSpecificOutput: { hookEventName: name, additionalContext: answer.text } })}\n`);
|
|
98
|
+
await ask({ op: "hookRead", sessionId, token: answer.token }, STEP_MS).catch((error) => log(`${name} receipt: ${error.message}`));
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if (name === "SessionEnd") {
|
|
103
|
+
await ask({ op: "hook", sessionId, event: name }, STEP_MS).catch(() => {});
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (name !== "Stop") return 0;
|
|
108
|
+
// Waits in the background until something comes for this session. A
|
|
109
|
+
// daemon that restarts is waited for a little; one that is gone ends it.
|
|
110
|
+
let failures = 0;
|
|
111
|
+
// Asked again, it says nothing of the turn: the person may have typed since.
|
|
112
|
+
let again = false;
|
|
113
|
+
for (;;) {
|
|
114
|
+
let answer;
|
|
115
|
+
try {
|
|
116
|
+
answer = await ask({ op: "hookWait", sessionId, ...(again ? { again } : {}) }, WAIT_MS + 5_000);
|
|
117
|
+
again = true;
|
|
118
|
+
failures = 0;
|
|
119
|
+
} catch (error) {
|
|
120
|
+
// No daemon has answered this hook yet: there is none to wait for, and
|
|
121
|
+
// `claude -p` waits on this hook before it exits.
|
|
122
|
+
if (!again || ++failures > 6) {
|
|
123
|
+
log(`Stop: stopped waiting: ${error.message}`);
|
|
124
|
+
return 0;
|
|
125
|
+
}
|
|
126
|
+
await sleep(5_000);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (!answer.ok) {
|
|
130
|
+
log(`Stop: ${answer.error}`);
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
if (answer.wait) continue;
|
|
134
|
+
if (!answer.text || !answer.token) return 0;
|
|
135
|
+
await write(process.stderr, `${answer.text}\n`);
|
|
136
|
+
await ask({ op: "hookRead", sessionId, token: answer.token }, STEP_MS).catch((error) => log(`Stop receipt: ${error.message}`));
|
|
137
|
+
// Exit 2 from an asyncRewake Stop hook wakes the session with stderr.
|
|
138
|
+
return 2;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
process.on("SIGTERM", () => process.exit(0));
|
|
143
|
+
main().then(
|
|
144
|
+
(code) => process.exit(code),
|
|
145
|
+
(error) => {
|
|
146
|
+
log(`failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
147
|
+
process.exit(0);
|
|
148
|
+
},
|
|
149
|
+
);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@santori/station",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.11",
|
|
4
4
|
"description": "Meeting rooms for your agents. They can share context with each other and work together. This CLI brings any agent into a Station room. In Claude Code and Codex, messages from the room arrive in the session on their own.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"station",
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
},
|
|
24
24
|
"files": [
|
|
25
25
|
"dist",
|
|
26
|
+
"hook",
|
|
26
27
|
"README.md"
|
|
27
28
|
],
|
|
28
29
|
"engines": {
|
|
@@ -44,7 +45,7 @@
|
|
|
44
45
|
},
|
|
45
46
|
"devDependencies": {
|
|
46
47
|
"@types/node": "^22.20.5",
|
|
47
|
-
"typescript": "^
|
|
48
|
+
"typescript": "^7.0.2",
|
|
48
49
|
"vitest": "^2.1.9"
|
|
49
50
|
}
|
|
50
51
|
}
|