@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/mcp.js CHANGED
@@ -96,7 +96,10 @@ async function settled(home) {
96
96
  }
97
97
  export const thisComputer = {
98
98
  session: (worker, thread) => inSession(worker, thread ? { ...process.env, CODEX_THREAD_ID: thread } : process.env),
99
- takeSeat: async (home, session, url, name) => (await takeSeat(home, session, url, { client: "station-mcp", name: name ?? undefined })).seat,
99
+ takeSeat: async (home, session, url, name) => {
100
+ const { seat, hooks } = await takeSeat(home, session, url, { client: "station-mcp", name: name ?? undefined });
101
+ return hooks && "failed" in hooks ? { ...seat, note: hooks.failed } : seat;
102
+ },
100
103
  read: async (home, seat, after) => {
101
104
  // A seat of an agent's own sign-in keeps its own place.
102
105
  if (seat.own)
@@ -195,6 +198,8 @@ export function stationTools(home, post = postToAgent, computer = thisComputer,
195
198
  }
196
199
  let seat = roomId && caller ? seatFor(loadSeats(files(home).seats), caller.id, roomId) : null;
197
200
  let joined = false;
201
+ /** What the agent should know about the seat just taken, before Station's answer. */
202
+ let note = null;
198
203
  // A tool that acts as the session's seat takes one first; so does an action of mutate that does (ask.take).
199
204
  const meta = known.get(name)?._meta;
200
205
  const seatActions = meta?.["station/seat-for"];
@@ -203,7 +208,9 @@ export function stationTools(home, post = postToAgent, computer = thisComputer,
203
208
  // The seat's name, when the call gives one (room_wait's `name`), as station join --name.
204
209
  const name = typeof args.name === "string" && args.name.trim() ? args.name.trim() : null;
205
210
  const invite = inviteToken ? `?${new URLSearchParams({ invite_token: inviteToken })}` : "";
206
- seat = await computer.takeSeat(home, caller ?? computer.session(worker, callerThread(sent)), `${relayUrl}/${roomId}${invite}`, name);
211
+ const { note: said, ...taken } = await computer.takeSeat(home, caller ?? computer.session(worker, callerThread(sent)), `${relayUrl}/${roomId}${invite}`, name);
212
+ seat = taken;
213
+ note = said ?? null;
207
214
  joined = true;
208
215
  }
209
216
  if (!seat && roomId && caller) {
@@ -264,6 +271,8 @@ export function stationTools(home, post = postToAgent, computer = thisComputer,
264
271
  // The seat left the room: nothing here holds it any longer.
265
272
  if (seat && result._meta?.["station/seat"] === "drop")
266
273
  await computer.drop(home, seat).catch(() => undefined);
274
+ if (note)
275
+ return { ...result, content: [{ type: "text", text: note }, ...(result.content ?? [])] };
267
276
  return result;
268
277
  }
269
278
  catch (error) {
package/dist/node.js ADDED
@@ -0,0 +1,14 @@
1
+ // The oldest Node the CLI runs on (package.json's engines, and CI tests it
2
+ // there). On an older one a command fails somewhere odd, so the CLI says so
3
+ // first, with the way to join a room that needs no Node.
4
+ export const OLDEST_NODE = 20;
5
+ /** What to print on a Node too old to run the CLI, or null when it is new
6
+ * enough. `argv` is the command's own arguments: a join names its room. */
7
+ export function nodeTooOld(version, argv) {
8
+ const major = Number(version.split(".")[0]);
9
+ if (!Number.isFinite(major) || major >= OLDEST_NODE)
10
+ return null;
11
+ const room = argv[0] === "join" && /^https?:\/\//.test(argv[1] ?? "") ? argv[1].split("?")[0].replace(/\/+$/, "") : null;
12
+ const steps = room ? `curl -s "${room}/how/curl"` : "curl -s <the room's address>/how/curl";
13
+ return `Station's CLI needs Node ${OLDEST_NODE} or later, and this is Node ${version}. To join a room without it, run ${steps} and follow the steps there.`;
14
+ }
package/dist/own.js ADDED
@@ -0,0 +1,42 @@
1
+ // Names for the commands this CLI runs itself.
2
+ //
3
+ // The taught name of a command is the short one it shipped with: `station
4
+ // status`, `station leave`. Over MCP the same action is one of mutate's
5
+ // (`room.status`), so an agent that knows that name may type its 2 words in
6
+ // a shell (`station room status`). ACTION_COMMANDS is that table: the
7
+ // action's 2 words, and the short command whose code runs them. The 2 words
8
+ // run so a guess works. No help and no page shows them.
9
+ /** The action's 2 words, and the words of the CLI's own command it runs. */
10
+ export const ACTION_COMMANDS = {
11
+ "room new": ["new"],
12
+ "room status": ["status"],
13
+ "room name": ["name"],
14
+ "room leave": ["leave"],
15
+ "room admit": ["admit"],
16
+ "room claim-link": ["claim"],
17
+ "approval ask": ["ask"],
18
+ "approval answer": ["ask", "--answered"],
19
+ };
20
+ /** The command line with an action's 2 words read as the CLI's own command:
21
+ * `room status working` is `status working`. */
22
+ export function ownCommand(argv) {
23
+ // The second word as mutate spells it runs too: `room claim_link`.
24
+ const own = argv.length > 1 ? ACTION_COMMANDS[`${argv[0]} ${argv[1].replace(/_/g, "-")}`] : undefined;
25
+ return own ? [...own, ...argv.slice(2)] : argv;
26
+ }
27
+ /** The commands this CLI has of its own. Any other word is looked up in
28
+ * the commands Station defines (commands.ts). */
29
+ export const OWN = ["login", "login-helper", "signup", "logout", "whoami", "rooms", "webhook", "webhooks", "new", "add", "watch", "join", "wait", "read", "say", "name", "cp", "file", "ask", "admit", "claim", "status", "trace", "leave", "seats", "tool", "daemon", "mcp", "doctor", "poke", "help", "--help", "--version", "-v", "version"];
30
+ /** The commands the help lists, for an unknown one. */
31
+ export const VISIBLE = ["login", "signup", "logout", "whoami", "rooms", "new", "add", "watch", "join", "say", "wait", "read", "name", "status", "tool", "ask", "admit", "claim", "trace", "leave", "seats", "doctor", "mcp", "webhook"];
32
+ /** The words that still run and that nothing teaches, each with the name
33
+ * that is taught. An action's 2 words are in ACTION_COMMANDS; `handoff` and
34
+ * `take` are Station's own (its tool list says what each stands for); `cp`
35
+ * and `file` put a file on the board before `board cp` did. */
36
+ export const UNTAUGHT = {
37
+ ...Object.fromEntries(Object.entries(ACTION_COMMANDS).map(([words, own]) => [words, own.join(" ")])),
38
+ handoff: "recipe handoff",
39
+ take: "task take",
40
+ cp: "board cp",
41
+ file: "board cp",
42
+ };
@@ -0,0 +1,50 @@
1
+ // Where an agent's own program is on this computer. One lookup for both
2
+ // questions Station asks: is the agent here (`station add`, and the offer
3
+ // a join makes), and what to run to start it for an ask (starts.ts). So
4
+ // Station never says an agent is here and then cannot start it.
5
+ //
6
+ // PATH first. Then the places an install puts the program where PATH often
7
+ // does not reach: the daemon has the PATH of whichever session started
8
+ // it, and an agent that came as a desktop app has no program on PATH.
9
+ // - Codex: the Codex app keeps its own `codex` inside the app, as
10
+ // ChatGPT's app did before it.
11
+ // - Claude Code: the native installer's ~/.local/bin (it asks the person
12
+ // to add that to PATH), the older ~/.claude/local (reached through a
13
+ // shell alias, never PATH), and the copy the Claude desktop app
14
+ // downloads for its Code tab, newest version first.
15
+ import { accessSync, constants, readdirSync, statSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { join } from "node:path";
18
+ import { newer, onPath } from "./self.js";
19
+ export const programName = (kind) => (kind === "codex" ? "codex" : "claude");
20
+ /** The places outside PATH, in the order Station looks. */
21
+ export function programPlaces(kind, home) {
22
+ if (kind === "codex") {
23
+ return [join(home, "Applications"), "/Applications"].flatMap((apps) => [
24
+ join(apps, "Codex.app/Contents/Resources/codex"),
25
+ join(apps, "ChatGPT.app/Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex"),
26
+ ]);
27
+ }
28
+ const desktop = join(home, "Library/Application Support/Claude/claude-code");
29
+ let versions = [];
30
+ try {
31
+ versions = readdirSync(desktop).sort((a, b) => (newer(a, b) ? -1 : newer(b, a) ? 1 : 0));
32
+ }
33
+ catch {
34
+ // No Claude desktop app, or it never downloaded Claude Code.
35
+ }
36
+ return [join(home, ".local/bin/claude"), join(home, ".claude/local/claude"), ...versions.map((version) => join(desktop, version, "claude.app/Contents/MacOS/claude"))];
37
+ }
38
+ function runnable(file) {
39
+ try {
40
+ accessSync(file, constants.X_OK);
41
+ return statSync(file).isFile();
42
+ }
43
+ catch {
44
+ return false;
45
+ }
46
+ }
47
+ /** The agent's program by its full path; null when it is not on this computer. */
48
+ export function findProgram(kind, env = process.env, places = programPlaces(kind, env.HOME || homedir())) {
49
+ return onPath(programName(kind), env) ?? places.find(runnable) ?? null;
50
+ }
package/dist/relay.js CHANGED
@@ -43,7 +43,7 @@ export async function call(base, path, auth, init = {}) {
43
43
  // Node 20 has no way to use a proxy from the environment.
44
44
  const next = proxyIgnored()
45
45
  ? `A proxy is set (HTTPS_PROXY), and Node ${process.versions.node} does not send requests through it. Node 22.21 or later does: run the CLI with that Node, or join with the curl steps the room link gives.`
46
- : "Check the address and connection, then try again.";
46
+ : "Check the address and connection, then try again. In a sandbox with no network, such as Codex's, run it with network access.";
47
47
  throw new RelayError(0, `Could not reach ${base}: ${why}. ${next}`);
48
48
  }
49
49
  if (!response.ok) {
package/dist/sessions.js CHANGED
@@ -56,8 +56,11 @@ export function callingAgent(env = process.env, from = process.ppid, cwd = proce
56
56
  const claude = callingSession(claudeHome(env), from, ps);
57
57
  const codex = callingThread(codexHome(env), env, from, ps, holders);
58
58
  if (claude && codex) {
59
+ // A thread found only by its files (Codex's sandbox, pid 0) is not in
60
+ // the chain: the Claude Code seen above this process wins.
59
61
  const chain = ancestry(from, ps);
60
- return chain.indexOf(codex.pid) < chain.indexOf(claude.pid) ? fromCodex(codex, cwd) : fromClaude(claude);
62
+ const at = chain.indexOf(codex.pid);
63
+ return at >= 0 && at < chain.indexOf(claude.pid) ? fromCodex(codex, cwd) : fromClaude(claude);
61
64
  }
62
65
  if (claude)
63
66
  return fromClaude(claude);
@@ -75,23 +78,50 @@ const NOT_AN_AGENT = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "tcsh"
75
78
  export function agentProgram(from = process.ppid, ps = systemPs) {
76
79
  for (const pid of ancestry(from, ps)) {
77
80
  const name = ps(pid, "comm")?.split("/").pop()?.replace(/^-/, "").toLowerCase();
78
- if (name && !NOT_AN_AGENT.has(name))
81
+ // A runner that renames itself shows its title, such as npx's
82
+ // "npm exec @santori/station@latest", cut to "npm exec @santo" on Linux.
83
+ if (name && !NOT_AN_AGENT.has(name) && !NOT_AN_AGENT.has(name.split(" ")[0]))
79
84
  return name;
80
85
  }
81
86
  return null;
82
87
  }
83
- /** Whether the session with this id is still running. */
84
- export function isRunning(harness, id) {
88
+ export const LISTENING = {
89
+ copilot: {
90
+ // Copilot CLI's own process is named MainThread; its shells carry COPILOT_CLI.
91
+ programs: ["copilot"],
92
+ env: "COPILOT_CLI",
93
+ line: (wait) => `Read new messages with: ${wait}, started with your bash tool in the background (mode "async", not detach). Then end your turn. When it ends, Copilot starts a new turn with what it printed: act on it, then start that same command again. Ask your person to choose "don't ask again" for it once, so restarting it needs no approval.`,
94
+ },
95
+ grok: {
96
+ programs: ["grok"],
97
+ line: (wait) => `Read new messages with: ${wait}, started in the background (is_background). Then end your turn. When it ends, Grok starts a new turn: read its output, act on it, then start that same command again.`,
98
+ },
99
+ gemini: {
100
+ programs: ["gemini"],
101
+ env: "GEMINI_CLI",
102
+ line: (wait) => `Read new messages with: ${wait}. Gemini starts a new turn when a background command ends only with two settings, both off by default, in ~/.gemini/settings.json: {"experimental":{"modelSteering":true},"tools":{"shell":{"backgroundCompletionBehavior":"inject"}}}. Offer to add them, and add them only if your person says yes. With them, start the wait in the background (is_background: true) and end your turn. Gemini shows what it printed as your person's words; it came from the room. Act on it, then start that same command again. Without them, run it after each reply and whenever idle.`,
103
+ },
104
+ cursor: {
105
+ programs: ["cursor-agent"],
106
+ line: (wait) => `Read new messages with: ${wait}. Cursor's Shell tool can wake a chat when a background command prints a matching line; Station has not tested it with Cursor. Start the wait with block_until_ms 0 and notify_on_output {"pattern":"^\\\\[Station · "}, then end your turn. If no turn starts when a message comes, run it after each reply and whenever idle instead.`,
107
+ },
108
+ };
109
+ /** Which agent in LISTENING this shell runs in, or null. */
110
+ export function listeningFor(env = process.env, program = agentProgram()) {
111
+ return Object.values(LISTENING).find((agent) => (program && agent.programs.includes(program)) || (agent.env && env[agent.env])) ?? null;
112
+ }
113
+ /** Whether the session with this id is still running. `claude`: the Claude Code profile it runs under. */
114
+ export function isRunning(harness, id, home = codexHome(), claude = claudeHome()) {
85
115
  if (harness === "shell")
86
116
  return false;
87
- return harness === "codex" ? liveThread(codexHome(), id) !== null : sessionById(claudeHome(), id) !== null;
117
+ return harness === "codex" ? liveThread(home, id) !== null : sessionById(claude, id) !== null;
88
118
  }
89
119
  /** Puts `text` into the session as a new user message. */
90
- export async function deliverTo(harness, id, messageId, text) {
120
+ export async function deliverTo(harness, id, messageId, text, home = codexHome()) {
91
121
  if (harness === "shell")
92
122
  return { kind: "retry", reason: "Station cannot put messages into this agent; it reads them with station wait." };
93
123
  if (harness === "codex")
94
- return deliverCodex(codexHome(), id, messageId, text);
124
+ return deliverCodex(home, id, messageId, text);
95
125
  const session = sessionById(claudeHome(), id);
96
126
  if (!session)
97
127
  return { kind: "retry", reason: "That Claude Code session is not running." };
package/dist/starts.js CHANGED
@@ -16,7 +16,7 @@ import { createHash, randomUUID } from "node:crypto";
16
16
  import { existsSync } from "node:fs";
17
17
  import { files, readJson, writeJson } from "./home.js";
18
18
  import { fromMessage } from "./limits.js";
19
- import { onPath } from "./self.js";
19
+ import { findProgram, programName } from "./programs.js";
20
20
  export const startsFile = (home) => `${files(home).seats.replace(/seats\.json$/, "")}starts.json`;
21
21
  const keyOf = (agent, room) => `${agent}:${room}`;
22
22
  export function loadStarts(home) {
@@ -43,8 +43,6 @@ export function planFor(home, wake, kind, cwd) {
43
43
  const known = loadStarts(home)[keyOf(wake.agent.id, wake.room)];
44
44
  if (known && existsSync(known.cwd))
45
45
  return known;
46
- if (!cwd || !existsSync(cwd))
47
- return null;
48
46
  return { kind, session: startedSessionId(wake.agent.id, wake.room), cwd, resume: null };
49
47
  }
50
48
  /** What the started agent is told: the ask, then how to answer it with
@@ -111,6 +109,8 @@ export function claudeArgs(plan, server, prompt, sessionId) {
111
109
  "acceptEdits",
112
110
  "--allowedTools",
113
111
  "mcp__station",
112
+ // --allowedTools takes many values: without --, claude reads the prompt as one of them and starts with none.
113
+ "--",
114
114
  prompt,
115
115
  ];
116
116
  }
@@ -119,10 +119,10 @@ export function claudeArgs(plan, server, prompt, sessionId) {
119
119
  export function startAgent(plan, wake, relayUrl, server, options = {}) {
120
120
  const env = options.env ?? process.env;
121
121
  const log = options.log ?? (() => { });
122
- const program = plan.kind === "codex" ? "codex" : "claude";
123
- const executable = onPath(program, env);
122
+ const program = programName(plan.kind);
123
+ const executable = findProgram(plan.kind, env);
124
124
  if (!executable)
125
- return Promise.resolve({ code: null, why: `${program} is not on this computer's PATH`, limit: null, resume: plan.resume });
125
+ return Promise.resolve({ code: null, why: `${program} is not on this computer: not on PATH or in its app`, limit: null, resume: plan.resume });
126
126
  const prompt = startPrompt(wake, relayUrl);
127
127
  const claudeSession = plan.resume ?? randomUUID();
128
128
  const args = plan.kind === "codex" ? codexArgs(plan, server, prompt) : claudeArgs(plan, server, prompt, claudeSession);
package/dist/tool.js CHANGED
@@ -82,10 +82,12 @@ function sessionSeat(home) {
82
82
  function textOf(result) {
83
83
  return (result.content ?? []).map((part) => (part.type === "text" ? part.text : "")).join("\n");
84
84
  }
85
+ /** The 5 tools `station mcp` gives an agent's app. A shell has commands instead. */
86
+ const MCP_TOOLS = ["wait", "send", "get", "list", "mutate"];
85
87
  /** Old tool names, still run as the new ones (the relay's OLD_TOOLS in mcp.ts). */
86
88
  const OLD_TOOLS = { ask_take: "task_take", ask_release: "task_release", ask_done: "task_done" };
87
89
  /** Runs `station tool ...`: 0 when the tool answered, 1 when it refused. */
88
- export async function toolCommand({ home, args, out, me, tools = stationTools(home), seat = () => sessionSeat(home) }) {
90
+ export async function toolCommand({ home, args, out, me, tools = stationTools(home), seat = () => sessionSeat(home), signedIn = true }) {
89
91
  const { given, rest } = toolFlags(args);
90
92
  const [name, ...extra] = rest;
91
93
  const mine = seat();
@@ -101,8 +103,12 @@ export async function toolCommand({ home, args, out, me, tools = stationTools(ho
101
103
  }
102
104
  // Names from before a taken message was called a task, as older wake prompts give them.
103
105
  const tool = listed.find((one) => one.name === (OLD_TOOLS[name] ?? name));
104
- if (!tool)
105
- throw new Usage(`Station has no tool called ${name}. It has: ${listed.map((one) => one.name).join(", ")}.`);
106
+ if (!tool) {
107
+ const why = MCP_TOOLS.includes(name)
108
+ ? ` ${name} is one of the 5 tools an agent's app gets over MCP. In a shell: ${me} say, ${me} read, ${me} rooms, and each of mutate's actions is a command by its 2 words, such as ${me} task take.`
109
+ : signedIn ? "" : ` This computer is not signed in to Station, and the tools for your person's rooms, invites and teams come with sign-in: ${me} login.`;
110
+ throw new Usage(`Station has no tool called ${name}.${why} It has: ${listed.map((one) => one.name).join(", ")}.`);
111
+ }
106
112
  if (given.has("help")) {
107
113
  for (const line of toolHelp(me, tool))
108
114
  out(line);
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
- const answer = (credentials, wake, outcome, why) => call(credentials.relayUrl, "/cli/wakes", { token: credentials.token }, { body: { room: wake.room, message: wake.message, agent: wake.agent.id, outcome, ...(why ? { why } : {}) } }).catch((error) => log(`wake ${wake.message} answer ${outcome} not sent: ${error instanceof Error ? error.message : String(error)}`));
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
- const fresh = last && folder ? null : planFor(home, wake, kind, lastSession(deps.seats(), wake.agent.id, wake.room)?.cwd ?? folderOf(home, wake.agent.id));
134
- // One agent, one presence in a room: a run of its own acts as the agent's
135
- // seat there that no session holds now (a codex exec that ended, a closed
136
- // window), so it takes that seat back rather than a second one.
137
- const there = fresh ? deps.seats().find((seat) => seat.agentId === wake.agent.id && seat.roomId === wake.room && !isOpen(seat) && seat.sessionId !== fresh.session) : undefined;
138
- const plan = last && folder ? { kind, session: last.sessionId, cwd: folder, resume: last.sessionId } : fresh && there ? { ...fresh, session: there.sessionId } : fresh;
139
- if (!plan) {
140
- await answer(credentials, wake, "failed", `Station knows no folder on this computer to start ${wake.agent.name} in. Run station add ${kind === "codex" ? "codex" : "claude"} in the folder it should work in`);
141
- return;
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 (!last)
216
+ if (!continues)
186
217
  saveStart(home, wake.agent.id, wake.room, { ...plan, resume: end.resume });
187
218
  return;
188
219
  }
@@ -244,7 +275,7 @@ export function createWaking(deps) {
244
275
  async function intoWindow(credentials, wake, chat) {
245
276
  let told = false;
246
277
  for (let attempt = 0; attempt < 120 && isOpen(chat); attempt++) {
247
- const outcome = await deliver(chat.harness, chat.sessionId, `station-ask-${wake.room}-${wake.message}`, startPrompt(wake, credentials.relayUrl, false));
278
+ const outcome = await deliver(chat, `station-ask-${wake.room}-${wake.message}`, startPrompt(wake, credentials.relayUrl, false));
248
279
  if (outcome.kind !== "retry") {
249
280
  log(`wake ${wake.message}: put into ${wake.agent.name}'s open chat ${chat.sessionId}`);
250
281
  await answer(credentials, wake, "started");
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.10",
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": {