@santori/station 0.9.11 → 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/dist/hooks.js CHANGED
@@ -10,12 +10,13 @@
10
10
  // The person allows them once per computer, on the page where they approve
11
11
  // its sign-in (login keeps that as `allowHooks` in credentials.json), and
12
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.
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
15
  import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
16
16
  import { dirname, join } from "node:path";
17
17
  import { fileURLToPath } from "node:url";
18
18
  import { claudeHome } from "./claude.js";
19
+ import { codexHome } from "./codex.js";
19
20
  import { files, readJson } from "./home.js";
20
21
  import { Usage } from "./usage.js";
21
22
  /** The protocol the hook script and the daemon speak (hook.mjs PROTOCOL). */
@@ -27,6 +28,11 @@ export const HOOK_EVENTS = [
27
28
  { event: "Stop", timeout: 86_400, asyncRewake: true },
28
29
  { event: "SessionEnd", timeout: 5 },
29
30
  ];
31
+ const CODEX_EVENTS = [
32
+ { event: "UserPromptSubmit", timeout: 5 },
33
+ { event: "PostToolUse", timeout: 5 },
34
+ { event: "Stop", timeout: 5 },
35
+ ];
30
36
  /** The script this package ships, copied into Station's home on install. */
31
37
  export const HOOK_SOURCE = fileURLToPath(new URL("../hook/hook.mjs", import.meta.url));
32
38
  export const hookScript = (home) => join(home, "hook.mjs");
@@ -38,16 +44,18 @@ export function hooksAllowed(home) {
38
44
  export const hooksOffHere = (env = process.env) => (env.STATION_HOOKS ?? "").toLowerCase() === "off";
39
45
  /** Where Claude Code reads a person's own hooks from. */
40
46
  export const hooksFile = (env = process.env) => join(claudeHome(env), "settings.json");
47
+ export const codexHooksFile = (home = codexHome()) => join(home, "hooks.json");
41
48
  const quote = (part) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(part) ? part : `'${part.replace(/'/g, `'\\''`)}'`);
42
49
  /** What Claude Code runs: Node by its absolute path, so no npx, PATH or nvm in between. */
43
50
  export const hookCommand = (home, node = process.execPath) => [node, hookScript(home), files(home).socket].map(quote).join(" ");
44
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>`. */
45
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()));
46
53
  /** The config without Station's entries. Everything else stays as it was. */
47
- export function withoutStationHooks(config) {
54
+ export function withoutStationHooks(config, owns = isStationHook) {
48
55
  if (!config.hooks || typeof config.hooks !== "object")
49
56
  return config;
50
57
  const events = {};
58
+ let removed = false;
51
59
  for (const [event, groups] of Object.entries(config.hooks)) {
52
60
  if (!Array.isArray(groups)) {
53
61
  events[event] = groups;
@@ -56,22 +64,25 @@ export function withoutStationHooks(config) {
56
64
  const kept = groups.flatMap((group) => {
57
65
  if (!Array.isArray(group?.hooks))
58
66
  return [group];
59
- const handlers = group.hooks.filter((handler) => !isStationHook(handler?.command));
67
+ const handlers = group.hooks.filter((handler) => !owns(handler?.command));
60
68
  if (handlers.length === group.hooks.length)
61
69
  return [group];
70
+ removed = true;
62
71
  return handlers.length ? [{ ...group, hooks: handlers }] : [];
63
72
  });
64
- if (kept.length)
73
+ if (kept.length || !groups.length)
65
74
  events[event] = kept;
66
75
  }
76
+ if (!removed)
77
+ return config;
67
78
  const { hooks: _, ...rest } = config;
68
79
  return Object.keys(events).length ? { ...rest, hooks: events } : rest;
69
80
  }
70
81
  /** The config with Station's entries, once each. */
71
- export function withStationHooks(config, command) {
72
- const clean = withoutStationHooks(config);
82
+ export function withStationHooks(config, command, definitions = HOOK_EVENTS, owns = isStationHook) {
83
+ const clean = withoutStationHooks(config, owns);
73
84
  const events = { ...(clean.hooks ?? {}) };
74
- for (const { event, ...rest } of HOOK_EVENTS)
85
+ for (const { event, ...rest } of definitions)
75
86
  events[event] = [...(events[event] ?? []), { hooks: [{ type: "command", command, ...rest }] }];
76
87
  return { ...clean, hooks: events };
77
88
  }
@@ -105,13 +116,41 @@ function writeSettings(path, value) {
105
116
  }
106
117
  /** Copies the script into Station's home and writes Station's entries into Claude Code's settings, backing the file up first. */
107
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);
108
150
  mkdirSync(home, { recursive: true });
109
151
  // The script is copied only when it changed (a new Station), so a call with nothing to do writes nothing.
110
152
  if (!existsSync(hookScript(home)) || !readFileSync(source).equals(readFileSync(hookScript(home))))
111
153
  copyFileSync(source, hookScript(home));
112
- const path = hooksFile(env);
113
- const before = readConfig(path);
114
- const after = withStationHooks(before, hookCommand(home, node));
115
154
  if (JSON.stringify(before) === JSON.stringify(after))
116
155
  return { path, changed: false, backup: null };
117
156
  mkdirSync(dirname(path), { recursive: true });
@@ -123,7 +162,12 @@ export function installHooks(home, env = process.env, source = HOOK_SOURCE, node
123
162
  }
124
163
  /** Takes Station's entries out of Claude Code's settings. */
125
164
  export function removeHooks(env = process.env) {
126
- const path = hooksFile(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) {
127
171
  if (!existsSync(path))
128
172
  return { path, changed: false, backup: null };
129
173
  let before;
@@ -133,33 +177,26 @@ export function removeHooks(env = process.env) {
133
177
  catch {
134
178
  return { path, changed: false, backup: null };
135
179
  }
136
- const after = withoutStationHooks(before);
137
- const changed = JSON.stringify(before) !== JSON.stringify(after);
180
+ const after = withoutStationHooks(before, owns);
181
+ const changed = after !== before;
138
182
  if (changed)
139
183
  writeSettings(path, after);
140
184
  return { path, changed, backup: null };
141
185
  }
142
- export function hooksOn(env = process.env) {
143
- try {
144
- return hasStationHooks(readConfig(hooksFile(env)));
145
- }
146
- catch {
147
- return false;
148
- }
149
- }
150
186
  /** Station's hooks for Claude Code, written when the person allowed them
151
187
  * and nothing turned them off. `change` is null when they are not in place:
152
188
  * not allowed, or `failed` says why they could not be written. */
153
- export function hooksReady(home, env = process.env) {
189
+ export function hooksReady(home, env = process.env, codexProfile) {
154
190
  if (!hooksAllowed(home) || hooksOffHere(env))
155
191
  return { change: null, failed: null };
156
192
  try {
157
- return { change: installHooks(home, env), failed: null };
193
+ return { change: codexProfile ? installCodexHooks(home, codexProfile) : installHooks(home, env), failed: null };
158
194
  }
159
195
  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)}.` };
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)}.` };
161
197
  }
162
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}.` : ""}`;
163
200
  /** What `station join` says about Station's hooks in a Claude Code
164
201
  * session, on every join: how messages come in, and that its person chose
165
202
  * it. Where the file is only when this join wrote it. */
package/dist/join.js CHANGED
@@ -10,13 +10,13 @@ import { KNOWN_PEER_PROTOCOL, claudeHome, systemPs, whyNoInbox } from "./claude.
10
10
  import { codexHome, whyNoThread } from "./codex.js";
11
11
  import { answers, ask } from "./daemon.js";
12
12
  import { askNewsFor, askNewsFrame, askedFrame, askedIn, decisionFrame, decisionsFor, frame, hearerFor } from "./frame.js";
13
- import { heldLine, lineOf, noteFor, seatLabels, severalOwners, threadHint, whereOf } from "./mark.js";
13
+ import { heldLine, lineOf, mention, noteFor, firstOfEach, seatLabels, severalOwners, threadHint, whereOf } from "./mark.js";
14
14
  import { files, installId, readCredentials, readJson, remove, stationHome, writeJson } from "./home.js";
15
15
  import { call, parseRoomUrl, RelayError } from "./relay.js";
16
16
  import { authFor, forgetAgentSeat, keepAgentSeat, loadSeats, roomLabel, seatDelivers, seatFor } from "./seats.js";
17
17
  import { addClaim, elsewhere, startLogin } from "./login.js";
18
18
  import { hooksReady } from "./hooks.js";
19
- import { HARNESS_NAMES, callingAgent, delivers, shellSession, startedSession, workerName } from "./sessions.js";
19
+ import { HARNESS_NAMES, PROGRAMS, agentOf, agentProgram, callingAgent, delivers, shellProgram, shellSession, startedSession, workerName } from "./sessions.js";
20
20
  import { VERSION, agentCommand, newer } from "./self.js";
21
21
  import { Usage } from "./usage.js";
22
22
  /** The session this process runs inside. Every command works in any
@@ -25,6 +25,11 @@ import { Usage } from "./usage.js";
25
25
  * wait`, and `why` says what kept a Claude Code or Codex session from
26
26
  * taking them, when one was there. */
27
27
  export function inSession(worker = workerName(process.env.STATION_SESSION), env = process.env, ps = systemPs) {
28
+ const session = sessionIn(worker, env, ps);
29
+ // A shell of a known program (Cursor, Devin, Grok) is that program's agent, in any folder.
30
+ return session.harness === "shell" && !session.host ? { ...session, program: shellProgram(env, agentProgram(undefined, ps)) } : session;
31
+ }
32
+ function sessionIn(worker, env, ps) {
28
33
  // Station started this agent to answer an ask: its session is the one the daemon named.
29
34
  const started = startedSession(env);
30
35
  if (started)
@@ -151,17 +156,18 @@ export function seatsOf(seats, sessionId) {
151
156
  /** The join body for the session. client tells the relay a daemon holds
152
157
  * the seat, so it is not put on the curl path's listening window. */
153
158
  export function joinBody(name, session, client = "station-cli") {
154
- // The program the session runs in, which says whose agent it is: a
155
- // worker or a started session in Codex is Codex, a shell's is its own.
156
- const kind = session.harness === "shell" ? session.host : session.harness;
157
- return { name, cwd: session.cwd, git_branch: gitBranch(session.cwd), session_id: session.id, harness: session.harness, ...(kind ? { agent_kind: kind } : {}), client: `${client}/${VERSION}` };
159
+ // The program the session runs in, which says which of the person's agents it is (agentOf).
160
+ return { ...(name ? { name } : {}), cwd: session.cwd, git_branch: gitBranch(session.cwd), session_id: session.id, harness: session.harness, ...agentOf(session), client: `${client}/${VERSION}` };
158
161
  }
162
+ const ID_LIKE = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
159
163
  /** What the CLI says when a private room has it ask to join. */
160
164
  export const ASKED_TO_JOIN = "This room is private, so this session asked to join. Someone in the room has to let it in; waiting here until they do.";
161
165
  const STILL_ASKING = "Nobody has let this session in yet. Ask someone in the room to let it in, then join again.";
162
166
  const CHECKING_REQUEST = "Checking the join request this session already made.";
163
167
  /** Ten minutes. */
164
168
  const ASK_FOR_MS = 600_000;
169
+ /** How long a read waits before it tells the room a second time what it showed. */
170
+ const RECEIPT_RETRY_MS = 1_000;
165
171
  function joinRequestPath(home, { relayUrl, roomId, sessionId }) {
166
172
  const id = createHash("sha256").update(JSON.stringify([relayUrl, roomId, sessionId])).digest("hex");
167
173
  return join(home, `join-${id}.json`);
@@ -210,12 +216,10 @@ export async function takeSeat(home, session, url, options = {}) {
210
216
  throw new Usage("Inside Codex's sandbox, Station cannot start what puts room messages into this thread. Run the same command again with full access.");
211
217
  }
212
218
  const joined = await joinRoom(home, session, url, options);
213
- // Claude Code gets Station's hooks however it took its seat (station join,
214
- // the MCP's wait, a rejoin). When they cannot be written, it gets messages
215
- // as when its person did not allow them, and the join says why.
219
+ // Hooks are installed however the session took its seat.
216
220
  const claudeCode = session.harness === "claude-code" || (session.harness === "shell" && session.host === "claude-code");
217
- const ready = claudeCode ? hooksReady(home) : { change: null, failed: null };
218
- const hooks = ready.failed ? { failed: `${ready.failed} ${session.harness === "claude-code" ? "Room messages still come in after each turn." : "Read room messages with wait."}` } : ready.change;
221
+ const ready = claudeCode || session.harness === "codex" ? hooksReady(home, process.env, joined.seat.codexHome) : { change: null, failed: null };
222
+ const hooks = ready.failed ? { failed: `${ready.failed} ${session.harness === "shell" ? "Read room messages with wait." : "Room messages still come in after each turn."}` } : ready.change;
219
223
  if (ownSeat) {
220
224
  keepAgentSeat(files(home).seats, joined.seat);
221
225
  clearJoinRequest(home, joined.seat);
@@ -267,8 +271,16 @@ export async function joinRoom(home, session, url, options = {}) {
267
271
  // A named worker in a Claude Code or Codex session is called after it, so the room shows which agent it is.
268
272
  const harness = session.harness === "shell" && session.host ? session.host : session.harness;
269
273
  // An agent's own sign-in knows which agent it is (STATION_AGENT_NAME).
270
- const who = credentials?.agent && credentials.name ? credentials.name : HARNESS_NAMES[harness];
271
- const name = (options.name ?? kept?.name ?? `${who} · ${session.name || basename(session.cwd)}`).slice(0, 80);
274
+ const who = credentials?.agent && credentials.name ? credentials.name : session.harness === "shell" && session.program ? PROGRAMS[session.program].name : HARNESS_NAMES[harness];
275
+ // The seat is called by the name given, else Station calls it by its agent's own name ("Claude Code").
276
+ // A named worker goes by its name in its agent ("Claude Code · reviewer"). An agent Station does not
277
+ // recognise is 1 agent per folder, so the folder is its name, unless the folder is named after an id
278
+ // (a room's, a task's), which says nothing about the agent.
279
+ const place = session.name || basename(session.cwd);
280
+ const unknown = session.harness === "shell" && !session.host && !session.program && !credentials?.agent;
281
+ // A name the seat kept is resent, unless it is only the folder name older CLIs added by default.
282
+ const keptName = kept?.name && kept.name !== `${who} · ${place}` ? kept.name : null;
283
+ const name = (options.name ?? keptName ?? (session.name ? `${who} · ${session.name}` : unknown && !ID_LIKE.test(place) ? `${who} · ${place}` : null))?.slice(0, 80) ?? null;
272
284
  const body = joinBody(name, session, options.client);
273
285
  if (invite && !token)
274
286
  body.invite_token = invite;
@@ -360,7 +372,8 @@ export function chatLines(seat, room, last, me) {
360
372
  const chat = room.messages.filter((m) => m.kind === "chat");
361
373
  const recent = chat.slice(-last);
362
374
  const authors = recent.map((m) => byId.get(m.participant_id ?? ""));
363
- const lines = recent.map((m, i) => lineOf(hearer, authors[i], m.body, whereOf(hearer, m, room.participants)));
375
+ const first = firstOfEach(authors);
376
+ const lines = recent.map((m, i) => lineOf(hearer, authors[i], m.body, whereOf(hearer, m, room.participants), first[i]));
364
377
  const older = chat.length - recent.length;
365
378
  if (older > 0)
366
379
  lines.unshift(`(${older} older message${older === 1 ? "" : "s"} not shown here. Read them with: ${me} read --after 0)`);
@@ -376,9 +389,9 @@ export function admittedLine(name, me, room = "") {
376
389
  }
377
390
  /** What `station join` says once seated. `me` is the command to type again.
378
391
  * `ask`: the person's agents the seat can ask, which need no seat here. */
379
- export function joinedLines(me, { seat, room }, why = null, { ask = null, listening = null } = {}) {
392
+ export function joinedLines(me, { seat, room }, why = null, { ask = null, listening = null, hello = [] } = {}) {
380
393
  const here = room.participants.filter((p) => !p.left_at);
381
- // Each other seat as --to takes it. Whose each is counts the reader's own seat too.
394
+ // Each other seat with its mention to copy. Whose each is counts the reader's own seat too.
382
395
  const others = here.filter((p) => p.id !== seat.participantId);
383
396
  const labels = seatLabels(others, severalOwners(here));
384
397
  const lines = [`Joined ${roomLabel(seat)} as "${seat.name}".`, `People here: ${here.map((p) => (others.includes(p) ? labels[others.indexOf(p)] : p.name)).join(", ")}`];
@@ -405,7 +418,13 @@ export function joinedLines(me, { seat, room }, why = null, { ask = null, listen
405
418
  if (room.open_tasks?.length)
406
419
  lines.push(["Open tasks:", ...room.open_tasks.map((task) => heldLine(hearerFor(seat, room.participants, me), room.participants, task))].join("\n"));
407
420
  const opener = room.board.opener?.instruction ?? "Say hello in one short message: what you are working on and which files, or what you can work on if you are free.";
408
- lines.push(`First, as the room asks: ${opener} With: ${me} say "<one short line>"`);
421
+ // A new room on a signed-in computer with the person's other agents here: the first thing is a hello to them.
422
+ // Agents read the CLI whole; told only on a web page, some stopped to ask before it.
423
+ if (hello.length && !room.messages.some((m) => m.kind === "chat")) {
424
+ lines.push(`First, say hello to your person's own other agents on this computer (${hello.map((agent) => agent.name).join(", ")}). Your person asked for this hello when they pasted the setup line. With: ${me} say "${hello.map((agent) => mention(agent.id)).join(" ")} <1 plain line on what you are working on, and ask each to answer the same way>". Leave out folder, branch and file names. Station starts each one here, in its own folder, and it answers in this room.`);
425
+ }
426
+ else
427
+ lines.push(`First, as the room asks: ${opener} With: ${me} say "<one short line>"`);
409
428
  if (room.board.next)
410
429
  lines.push(room.board.next);
411
430
  lines.push(`Put anything longer than a line or two on the board as a .md file: ${me} board write <name>.md --text "<the text>". For a file you already have: ${me} board cp <file>.`);
@@ -425,9 +444,16 @@ export function joinedLines(me, { seat, room }, why = null, { ask = null, listen
425
444
  // Tasks, once: 1 family of commands, each a task action of its own. No flag on `say` is one.
426
445
  // A seat that is nobody's agent yet cannot start its own (the relay refuses it).
427
446
  // "Any other work": work its person asks for in its own chat is not asked for in the room, and "work nobody asked for" read as leaving it out.
428
- const start = seat.agentId || seat.via === "cli" ? ` Before any other work you start, your person's included: ${me} task start "<what, and which files>", which lists what the others hold.` : "";
429
- lines.push(`Tasks. Before work that message n in this room asks for: ${me} task take <n>.${start} After your reply in its thread: ${me} task done <n>. To give one up: ${me} task release <n>. Asked to hand this session off to another agent: ${me} recipe handoff.`);
430
- lines.push(afterThisSession(me, seat.agentId ?? seat.name, seatDelivers(seat) ? null : `running \`${me} wait\``));
447
+ // Said as facts about the room: "Before any other work you start, your person's included" read as an order to log all
448
+ // its work, and a real Claude Code run told its person so (Nov 28).
449
+ const start = seat.agentId || seat.via === "cli" ? ` Work of your own in this room: ${me} task start "<what, and which files>", which lists what the others hold.` : "";
450
+ lines.push(`Tasks show the others here what each agent is on. Work that message n in this room asks for: ${me} task take <n>.${start} After your reply in its thread: ${me} task done <n>. To give one up: ${me} task release <n>. Asked to hand this session off to another agent: ${me} recipe handoff.`);
451
+ // Claude Code or Codex on a signed-in computer is already reached after this session: Station starts it here
452
+ // for a message to it (signup and sign-in bring it in). Listing ways to set that up made agents offer a step for it.
453
+ if (seat.via === "cli" && (seat.harness === "claude-code" || seat.harness === "codex"))
454
+ lines.push("When this session ends, Station starts you on this computer for a message to you.");
455
+ else
456
+ lines.push(afterThisSession(me, seat.agentId ?? seat.name, seatDelivers(seat) ? null : `running \`${me} wait\``));
431
457
  return lines;
432
458
  }
433
459
  /** How an agent keeps hearing its asks once this session ends, said once
@@ -441,7 +467,7 @@ export function afterThisSession(me, agent, wait) {
441
467
  `- A check on a schedule (cron, an automation): needs this computer signed in to Station. Run \`${me} watch --agent <which agent you are, such as codex>\` every few minutes. It reads all your person's rooms. Messages reach you late this way, and until then the sender may hear that Station could not reach you.`,
442
468
  `- Claude Code or Codex on a computer: needs this computer signed in to Station. \`${me} add claude\` (or codex) lets Station start it for a message to it.`,
443
469
  ...(wait ? [`- A session that stays open: keep ${wait}.`] : []),
444
- `If this computer is not signed in, run \`${me} login\` and give your person the link privately. After they click Approve, run the step. If this session ends first, nothing is set up: tell your person so, and give them the step's command, starting with \`cd\` to this folder's full path.`,
470
+ `If this computer is not signed in, run \`${me} signup --email <their email>\`. If it prints a link, give it to your person privately, and run the step after they click Approve. If this session ends first, nothing is set up: tell your person so, and give them the step's command, starting with \`cd\` to this folder's full path.`,
445
471
  ].join("\n");
446
472
  }
447
473
  /** The session's seat in the room, taken now when it has none. */
@@ -455,8 +481,6 @@ export async function seatOrJoin(home, session, relayUrl, roomId, client) {
455
481
  /** The longest the relay holds one read, in seconds. `station wait`
456
482
  * chains reads, so it can wait far longer than this. */
457
483
  export const WAIT_SECONDS = 25;
458
- /** The longest `room_wait` waits: MCP clients give up on a tool call after about a minute. */
459
- export const TOOL_WAIT_SECONDS = 50;
460
484
  /** What `station wait` hands a shell's agent: the room's new messages, in
461
485
  * the words a Claude Code or Codex session gets them, or null when nothing
462
486
  * came within `seconds`. With `seconds` null it waits until something
@@ -490,6 +514,7 @@ hand) {
490
514
  let after = seat.after;
491
515
  let text = null;
492
516
  let messages = [];
517
+ let notes = [];
493
518
  const tell = async () => {
494
519
  // A seat an agent's own sign-in took: no daemon to tell.
495
520
  if (seat.own)
@@ -500,18 +525,22 @@ hand) {
500
525
  };
501
526
  for (;;) {
502
527
  const left = Math.max(0, Math.min(WAIT_SECONDS, Math.ceil((until - Date.now()) / 1000)));
503
- const answer = await call(seat.relayUrl, `/${seat.roomId}/messages?after=${after}&wait=${left}`, auth);
528
+ // station=report: the Station team's notes come until the delivery below says they were handed over.
529
+ const answer = await call(seat.relayUrl, `/${seat.roomId}/messages?after=${after}&wait=${left}&station=report`, auth);
530
+ // The Station team's notes about reports this agent sent: they are in no room.
531
+ const station = (answer.station ?? []).map((note) => note.text);
532
+ notes = answer.station ?? [];
504
533
  const chat = answer.messages.filter((m) => m.kind === "chat" && m.participant_id !== seat.participantId);
505
534
  const decisions = decisionsFor(seat, answer.messages);
506
535
  const asked = askedIn(answer.messages);
507
536
  const news = askNewsFor(seat, answer.messages);
508
537
  after = Math.max(after, answer.next_after);
509
- if (chat.length || decisions.length || asked.length || news.length) {
538
+ if (chat.length || decisions.length || asked.length || news.length || station.length) {
510
539
  if (exactReceipt)
511
540
  messages = [...chat, ...decisions, ...asked, ...news].map((message) => message.id);
512
541
  const { participants } = await call(seat.relayUrl, `/${seat.roomId}`, auth);
513
542
  const otherRooms = loadSeats(files(home).seats).some((other) => other.sessionId === seat.sessionId && other.roomId !== seat.roomId && !other.left);
514
- text = [news.length ? askNewsFrame(seat, news) : null, decisions.length ? decisionFrame(seat, decisions, participants) : null, chat.length ? frame(seat, chat, participants, me, [], otherRooms) : null, asked.length ? askedFrame(seat, asked, me) : null]
543
+ text = [...station, news.length ? askNewsFrame(seat, news) : null, decisions.length ? decisionFrame(seat, decisions, participants) : null, chat.length ? frame(seat, chat, participants, me, [], otherRooms) : null, asked.length ? askedFrame(seat, asked, me) : null]
515
544
  .filter(Boolean)
516
545
  .join("\n\n");
517
546
  break;
@@ -531,7 +560,7 @@ hand) {
531
560
  keepAgentSeat(files(home).seats, { ...seat, after });
532
561
  if (text) {
533
562
  // The board shows these as read under the newest message, as it does for a delivery.
534
- await call(seat.relayUrl, `/${seat.roomId}/delivery`, auth, { body: { through: after, state: "delivered", waiting: null, ...(exactReceipt ? { messages } : {}) } }).catch(() => { });
563
+ await sendReceipt(seat, auth, { through: after, state: "delivered", waiting: null, ...(exactReceipt ? { messages } : {}), ...(notes.length ? { station: notes.map((note) => note.id) } : {}) });
535
564
  }
536
565
  return text;
537
566
  }
@@ -541,7 +570,7 @@ hand) {
541
570
  export async function readIn(home, seat, after, me) {
542
571
  const auth = authFor(seat, readCredentials(home));
543
572
  const [answer, room] = await Promise.all([
544
- call(seat.relayUrl, `/${seat.roomId}/messages?after=${after}&all=1`, auth),
573
+ call(seat.relayUrl, `/${seat.roomId}/messages?after=${after}&all=1&receipt=1`, auth),
545
574
  call(seat.relayUrl, `/${seat.roomId}`, auth),
546
575
  ]);
547
576
  const hearer = hearerFor(seat, room.participants, me);
@@ -549,7 +578,9 @@ export async function readIn(home, seat, after, me) {
549
578
  const chat = answer.messages.filter((m) => m.kind === "chat");
550
579
  const authors = chat.map((m) => byId.get(m.participant_id ?? ""));
551
580
  const note = noteFor(hearer, authors);
552
- const lines = [`[Station · ${roomLabel(seat)}] Messages after ${after}:`, "", ...(note ? [note, ""] : []), ...(chat.length ? chat.map((m, i) => lineOf(hearer, authors[i], m.body, whereOf(hearer, m, room.participants) + taskHint(m))) : ["(none)"]), ""];
581
+ const first = firstOfEach(authors);
582
+ const lines = [`[Station · ${roomLabel(seat)}] Messages after ${after}:`, "", ...(note ? [note, ""] : []), ...(chat.length ? chat.map((m, i) => lineOf(hearer, authors[i], m.body, whereOf(hearer, m, room.participants) + taskHint(m), first[i])) : ["(none)"]), ""];
583
+ await readReceipt(home, seat, chat.map((m) => m.id));
553
584
  lines.push(answer.messages.length === 100 ? `There are more. Read on with: ${me} read --after ${answer.next_after}` : "That is everything up to now.");
554
585
  // Who holds what now, whatever page of messages this is.
555
586
  if (room.open_tasks?.length)
@@ -623,9 +654,10 @@ export function numberedText(seat, runs, read, participants, me, otherRooms = fa
623
654
  const byId = new Map(participants.map((p) => [p.id, p]));
624
655
  const authors = read.messages.map((m) => byId.get(m.participant_id ?? ""));
625
656
  const note = noteFor(hearer, authors);
657
+ const first = firstOfEach(authors);
626
658
  const asked = runs.map((run) => (run.from === run.to ? String(run.from) : `${run.from}-${run.to}`)).join(", ");
627
659
  const lines = [`[Station · ${roomLabel(seat)}] ${runs.length === 1 && runs[0].from === runs[0].to ? "Message" : "Messages"} ${asked}:`, "", ...(note ? [note, ""] : [])];
628
- lines.push(...(read.messages.length ? read.messages.map((m, i) => lineOf(hearer, authors[i], m.body, whereOf(hearer, m, participants) + taskHint(m))) : ["(no chat message with that number in this room)"]), "");
660
+ lines.push(...(read.messages.length ? read.messages.map((m, i) => lineOf(hearer, authors[i], m.body, whereOf(hearer, m, participants) + taskHint(m), first[i])) : ["(no chat message with that number in this room)"]), "");
629
661
  if (read.more !== null) {
630
662
  const rest = runs.flatMap((run) => (run.to < read.more ? [] : [{ from: Math.max(run.from, read.more), to: run.to }]));
631
663
  lines.push(`There are more. Read on with: ${me} read ${rest.map((run) => (run.from === run.to ? String(run.from) : `${run.from}-${run.to}`)).join(",")}${room}`);
@@ -638,11 +670,39 @@ export function numberedText(seat, runs, read, participants, me, otherRooms = fa
638
670
  export async function readRunsIn(home, seat, runs, me) {
639
671
  const auth = authFor(seat, readCredentials(home));
640
672
  const [read, room] = await Promise.all([
641
- messagesIn(runs, (after) => call(seat.relayUrl, `/${seat.roomId}/messages?after=${after}&all=1`, auth)),
673
+ messagesIn(runs, (after) => call(seat.relayUrl, `/${seat.roomId}/messages?after=${after}&all=1&receipt=1`, auth)),
642
674
  call(seat.relayUrl, `/${seat.roomId}`, auth),
643
675
  ]);
644
676
  const otherRooms = loadSeats(files(home).seats).some((other) => other.sessionId === seat.sessionId && other.roomId !== seat.roomId);
645
- return numberedText(seat, runs, read, room.participants, me, otherRooms);
677
+ const text = numberedText(seat, runs, read, room.participants, me, otherRooms);
678
+ await readReceipt(home, seat, read.messages.map((m) => m.id));
679
+ return text;
680
+ }
681
+ /** The messages a read showed reached the agent: only those, not the rest
682
+ * of the page, and the seat's place does not move (through 0). */
683
+ async function readReceipt(home, seat, messages) {
684
+ if (!messages.length)
685
+ return;
686
+ await sendReceipt(seat, authFor(seat, readCredentials(home)), { through: 0, state: "delivered", messages });
687
+ }
688
+ /** Tells the room what reached the agent. A lost receipt leaves the
689
+ * messages "sent", and their senders later hear the agent could not be
690
+ * reached, so it is tried twice and a second failure is said on stderr. */
691
+ async function sendReceipt(seat, auth, body) {
692
+ const post = () => call(seat.relayUrl, `/${seat.roomId}/delivery`, auth, { body });
693
+ try {
694
+ await post();
695
+ }
696
+ catch {
697
+ await new Promise((resolve) => setTimeout(resolve, RECEIPT_RETRY_MS));
698
+ try {
699
+ await post();
700
+ }
701
+ catch (error) {
702
+ const which = body.messages?.length ? `messages ${body.messages.join(", ")}` : `messages up to ${body.through}`;
703
+ console.error(`Station could not record that you read ${which}: ${error instanceof Error ? error.message : String(error)} Their senders may be told you could not be reached, so answer them in the room.`);
704
+ }
705
+ }
646
706
  }
647
707
  /** The session's seat for a reply: in the room of the message it answers,
648
708
  * never the room it joined last, taking a seat there when it has none. */
@@ -685,22 +745,6 @@ export function saidLines(seat, said) {
685
745
  export async function nameRoom(home, seat, title) {
686
746
  return call(seat.relayUrl, `/${seat.roomId}`, authFor(seat, readCredentials(home)), { method: "PATCH", body: { title } });
687
747
  }
688
- /** The name a title gives a .md file. */
689
- export function markdownName(title) {
690
- return /\.(md|markdown)$/i.test(title) ? title : `${title}.md`;
691
- }
692
- export async function putItem(home, seat, item) {
693
- const auth = authFor(seat, readCredentials(home));
694
- const { items } = item.kind === "link"
695
- ? await call(seat.relayUrl, `/${seat.roomId}/items`, auth, { body: { kind: "link", title: item.title, href: item.href } })
696
- : await call(seat.relayUrl, `/${seat.roomId}/files`, auth, {
697
- method: "PUT",
698
- raw: new TextEncoder().encode(item.text),
699
- headers: { "Content-Type": "text/markdown; charset=utf-8", "X-File-Name": encodeURIComponent(markdownName(item.title)) },
700
- });
701
- const { id, kind, title, href } = items[0];
702
- return { id, kind, title, href };
703
- }
704
748
  /** What `station join` says when the room records nobody as this agent's
705
749
  * person: a sign-in link for them. Whoever opens it, with an account or
706
750
  * only their browser, signs this computer in, and the seat becomes theirs;
package/dist/login.js CHANGED
@@ -70,14 +70,14 @@ export function openBrowser(url) {
70
70
  /** The helper: polls the relay until the person answers the link, then
71
71
  * saves the sign-in. `station login-helper` runs it in its own process;
72
72
  * tests call it here. */
73
- export async function runHelper(home) {
73
+ export async function runHelper(home, startStation = async () => { }) {
74
74
  const pending = readPending(home);
75
75
  // A login.json with no device link is an older CLI's: its own helper finishes it.
76
76
  if (pending?.device)
77
- await runDeviceHelper(home, pending);
77
+ await runDeviceHelper(home, pending, startStation);
78
78
  }
79
79
  const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
80
- async function runDeviceHelper(home, pending) {
80
+ async function runDeviceHelper(home, pending, startStation) {
81
81
  const device = pending.device;
82
82
  const file = files(home);
83
83
  const mine = () => readPending(home)?.verifier === pending.verifier;
@@ -132,6 +132,10 @@ async function runDeviceHelper(home, pending) {
132
132
  await carryGuest(home, pending.relayUrl, answer.token);
133
133
  else if (answer.secret)
134
134
  await carryGuest(home, pending.relayUrl, answer.secret, true);
135
+ // The person's own sign-in made the agents found here theirs: Station runs here so it can start them for a message.
136
+ if (answer.token && foundHere().length) {
137
+ await startStation(home).catch((error) => console.error(`station login: Station did not start on this computer, so it cannot start your agents yet: ${error instanceof Error ? error.message : String(error)}`));
138
+ }
135
139
  if (waited.length)
136
140
  return;
137
141
  try {
@@ -228,7 +232,6 @@ export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnH
228
232
  webUrl: site,
229
233
  verifier: newVerifier(),
230
234
  label: loginLabel(hostname(), remote),
231
- signUp,
232
235
  startedAt: Date.now(),
233
236
  ...(asAgent ? { asAgent } : {}),
234
237
  ...(claims.length ? { claims } : {}),
package/dist/mark.js CHANGED
@@ -29,22 +29,39 @@ export function severalOwners(seats) {
29
29
  const owners = seats.filter((seat) => seat.kind === "agent").map((seat) => (seat.for?.you ? "you" : (seat.for?.name ?? `seat ${seat.id}`)));
30
30
  return new Set(owners).size > 1;
31
31
  }
32
- /** A seat or an agent by its id, as a message's text can name it. Printed only to tell 2 with the same name apart (seatLabels). */
32
+ /** A seat or an agent by its id, as a message's text tags it. */
33
33
  export const mention = (id) => `<@${id}>`;
34
- /** A seat as an agent reads it in a list of names, and as `to` takes it
35
- * back (the relay's tags.ts named): its name, and whose agent it is when
34
+ /** For a run of message lines, whether each is its author's first: the
35
+ * author's mention goes on that line only, where the agent copies it. */
36
+ export function firstOfEach(authors) {
37
+ const seen = new Set();
38
+ return authors.map((author) => {
39
+ if (!author || seen.has(author.id))
40
+ return false;
41
+ seen.add(author.id);
42
+ return true;
43
+ });
44
+ }
45
+ /** For lines that print an author's seat id themselves (an inbox across
46
+ * rooms): " <@id>" on each author's first line, "" on the rest. */
47
+ export function tagsOnce(seats) {
48
+ const first = firstOfEach(seats.map((id) => (id ? { id } : undefined)));
49
+ return seats.map((id, i) => (id && first[i] ? ` ${mention(id)}` : ""));
50
+ }
51
+ /** A seat as an agent reads it in a list: its name, whose agent it is when
36
52
  * the list's agents are more than 1 person's (`owners`, severalOwners),
37
- * such as "Claude Code · cadmate (Albert's)". `twin`: another in the list
38
- * reads the same, so its mention follows. */
39
- export function seatLabel(seat, owners, twin = false) {
53
+ * then the mention to copy, built from its id: "Claude Code · cadmate
54
+ * (Albert's) <@id>". A seat's id is its seat's, so the tag reaches that
55
+ * session; an agent with no seat in the room goes by its agent id. A name
56
+ * printed this way also still works in `to` (the relay's tags.ts named);
57
+ * no text teaches that. */
58
+ export function seatLabel(seat, owners) {
40
59
  const owner = owners && seat.kind === "agent" ? whose(seat.for) : null;
41
- return `${seat.name}${owner ? ` (${owner})` : ""}${twin ? ` ${mention(seat.id)}` : ""}`;
60
+ return `${seat.name}${owner ? ` (${owner})` : ""} ${mention(seat.id)}`;
42
61
  }
43
- /** These seats as one list of names. Each is what `to` takes to reach
44
- * that one: 2 that would read the same get their mention as well. */
62
+ /** These seats as one list of labels (seatLabel). */
45
63
  export function seatLabels(seats, owners = severalOwners(seats)) {
46
- const plain = seats.map((seat) => seatLabel(seat, owners).toLowerCase());
47
- return seats.map((seat, i) => seatLabel(seat, owners, plain.indexOf(plain[i]) !== plain.lastIndexOf(plain[i])));
64
+ return seats.map((seat) => seatLabel(seat, owners));
48
65
  }
49
66
  /** The reader from what the room says about them. */
50
67
  export function hearerOf(seat, ownerSeat, via, command, participants) {
@@ -104,7 +121,7 @@ export function whereOf(hearer, message, seats) {
104
121
  /** One message: who said it, then its whole text. From someone else, the
105
122
  * text goes under the name with THEIRS at the start of each line. `where`
106
123
  * is whereOf's bracket. */
107
- export function lineOf(hearer, author, body, where = "") {
124
+ export function lineOf(hearer, author, body, where = "", tagged = false) {
108
125
  const name = author?.name ?? "Someone";
109
126
  const side = sideOf(hearer, author);
110
127
  const who = side === "you"
@@ -116,7 +133,9 @@ export function lineOf(hearer, author, body, where = "") {
116
133
  : author?.kind === "agent"
117
134
  ? `${name} (${(hearer.owners && whose(author.for)) || "an"} agent)`
118
135
  : name;
119
- return side === "someone else" ? `${who}${where}:\n${theirs(body)}` : `${who}${where}: ${body}`;
136
+ // `tagged`: its mention follows the name, to copy into an answer that tags it.
137
+ const tag = tagged && author && side !== "you" ? ` ${mention(author.id)}` : "";
138
+ return side === "someone else" ? `${who}${tag}${where}:\n${theirs(body)}` : `${who}${tag}${where}: ${body}`;
120
139
  }
121
140
  /** How to answer, after a batch of messages: in the thread of the
122
141
  * message being answered, and in the main chat only for something new.
@@ -227,3 +246,9 @@ export function askedText(room, seatName, asked, admit) {
227
246
  : `Send your person ${links} in this session, in one line, never in the room. They answer on the card.`;
228
247
  return [`[Station · ${room}] ${who} to join. You are "${seatName}" here.`, "", ...lines, "", how].join("\n");
229
248
  }
249
+ /** Station's lines about a message to an agent, written as its sender's
250
+ * (the relay's wake.ts askLine): an agent got it, took it or finished it, could not be
251
+ * reached, was handed it, ran out, or let it lapse. News for the sender.
252
+ * And `stuck`: a task of its person's is held by an agent that stopped
253
+ * reading (the relay's attention.ts), written as this seat's. */
254
+ export const ASK_NEWS = ["unreached", "reached", "handed", "out", "lapsed", "stuck"];
package/dist/mcp.js CHANGED
@@ -25,8 +25,8 @@
25
25
  // The last list Station gave is kept, so a session that starts while
26
26
  // Station cannot be reached still has its tools.
27
27
  //
28
- // Station has two lists. An agent's app gets five folded tools (wait, send,
29
- // get, list, mutate), which this server asks for. The shell commands
28
+ // Station has two lists. An agent's app gets six folded tools (wait, send,
29
+ // get, list, mutate, feedback), which this server asks for. The shell commands
30
30
  // (`station tool`, `station board ls`) get the tools one by one, each with
31
31
  // its own flags, by not asking.
32
32
  import { randomUUID } from "node:crypto";
@@ -41,6 +41,7 @@ import { ask } from "./daemon.js";
41
41
  import { guestFor, readGuest } from "./guest.js";
42
42
  import { DEFAULT_RELAY, files, readCredentials, readJson, writeJson } from "./home.js";
43
43
  import { ensureDaemon, inSession, takeSeat } from "./join.js";
44
+ import { codexHooksJoinLine } from "./hooks.js";
44
45
  import { finishLogin, readPending } from "./login.js";
45
46
  import { roomRef } from "./rooms.js";
46
47
  import { authFor, keepAgentSeat, loadSeats, seatDelivers, seatFor } from "./seats.js";
@@ -98,7 +99,9 @@ export const thisComputer = {
98
99
  session: (worker, thread) => inSession(worker, thread ? { ...process.env, CODEX_THREAD_ID: thread } : process.env),
99
100
  takeSeat: async (home, session, url, name) => {
100
101
  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
+ if (hooks && "failed" in hooks)
103
+ return { ...seat, note: hooks.failed };
104
+ return hooks && seat.harness === "codex" ? { ...seat, note: codexHooksJoinLine(hooks) } : seat;
102
105
  },
103
106
  read: async (home, seat, after) => {
104
107
  // A seat of an agent's own sign-in keeps its own place.