@santori/station 0.9.11 → 0.9.13

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 Connect. 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
@@ -23,7 +23,7 @@ import { execFile, spawn } from "node:child_process";
23
23
  import { randomBytes } from "node:crypto";
24
24
  import { openSync } from "node:fs";
25
25
  import { hostname } from "node:os";
26
- import { foundHere } from "./agents.js";
26
+ import { agentsHere, foundHere } from "./agents.js";
27
27
  import { DEFAULT_WEB, files, readCredentials, readJson, remove, writeJson } from "./home.js";
28
28
  import { carryGuest } from "./guest.js";
29
29
  import { call, RelayError, siteOf } from "./relay.js";
@@ -70,19 +70,17 @@ 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;
84
- const replyState = () => readJson(file.loginReply, null);
85
- const tracking = { id: pending.verifier, pid: process.pid };
86
84
  const deadline = Date.parse(device.expires_at);
87
85
  // Why the relay last failed to answer, while it still does not.
88
86
  let down = null;
@@ -125,32 +123,18 @@ async function runDeviceHelper(home, pending) {
125
123
  };
126
124
  const waited = readPending(home)?.claims ?? [];
127
125
  writeJson(file.credentials, credentials);
128
- if (!waited.length)
129
- writeJson(file.loginReply, tracking);
130
126
  remove(file.login);
131
127
  if (answer.token)
132
128
  await carryGuest(home, pending.relayUrl, answer.token);
133
129
  else if (answer.secret)
134
130
  await carryGuest(home, pending.relayUrl, answer.secret, true);
135
- if (waited.length)
136
- return;
137
- try {
138
- while (replyState()?.id === tracking.id && Date.now() < deadline) {
139
- const result = await poll("/api/device/hello");
140
- if (replyState()?.id !== tracking.id)
141
- return;
142
- if (result?.reply) {
143
- writeJson(file.loginReply, { ...tracking, reply: result.reply });
144
- return;
145
- }
146
- await pause(1500);
147
- }
148
- }
149
- finally {
150
- const last = replyState();
151
- if (last?.id === tracking.id && !last.reply)
152
- remove(file.loginReply);
131
+ // The person's own sign-in made the agents found here theirs: Station runs here so it can start them for a message.
132
+ if (answer.token && foundHere().length) {
133
+ 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)}`));
153
134
  }
135
+ // Tells the page this computer finished signing in, so it can say Connected. Older pages waited here for a typed reply; there is none to wait for.
136
+ if (!waited.length)
137
+ await poll("/api/device/hello");
154
138
  return;
155
139
  }
156
140
  if (!mine())
@@ -164,26 +148,6 @@ async function runDeviceHelper(home, pending) {
164
148
  writeJson(file.login, { ...readPending(home), error: error instanceof Error ? error.message : String(error) });
165
149
  }
166
150
  }
167
- export function takeDeviceReply(home, id) {
168
- const path = files(home).loginReply;
169
- const state = readJson(path, null);
170
- if (!state?.reply || (id && state.id !== id))
171
- return null;
172
- remove(path);
173
- return state.reply;
174
- }
175
- export async function waitForDeviceReply(home, id, deadline) {
176
- for (;;) {
177
- const state = readJson(files(home).loginReply, null);
178
- if (state?.id !== id)
179
- return null;
180
- if (state.reply)
181
- return takeDeviceReply(home, id);
182
- if (!alive(state.pid) || Date.now() >= deadline)
183
- return null;
184
- await pause(250);
185
- }
186
- }
187
151
  /** The seats a device sign-in on `relayUrl` sends with it, each once: the
188
152
  * seats a waiting link was given (join.ts), then every seat this computer
189
153
  * still holds there that joined with no sign-in and that, as far as it
@@ -228,19 +192,17 @@ export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnH
228
192
  webUrl: site,
229
193
  verifier: newVerifier(),
230
194
  label: loginLabel(hostname(), remote),
231
- signUp,
232
195
  startedAt: Date.now(),
233
196
  ...(asAgent ? { asAgent } : {}),
234
197
  ...(claims.length ? { claims } : {}),
235
198
  };
236
199
  const device = await call(relayUrl, "/api/device/start", null, {
237
- body: { label: pending.label, agent: asAgent, ...(asAgent ? {} : { agents: foundHere() }) },
200
+ body: { label: pending.label, agent: asAgent, ...(asAgent ? {} : { agents: agentsHere() }) },
238
201
  });
239
202
  const link = new URL("/cli/login", site);
240
203
  link.searchParams.set("code", device.code);
241
204
  if (signUp)
242
205
  link.searchParams.set("signup", "1");
243
- remove(files(home).loginReply);
244
206
  pending.device = { proof: device.proof, expires_at: device.expires_at };
245
207
  pending.url = link.toString();
246
208
  writeJson(files(home).login, pending);
@@ -290,7 +252,6 @@ export async function finishLogin(home, waitMs, waitForCode = true) {
290
252
  export function cancelLogin(home) {
291
253
  const pending = readPending(home);
292
254
  remove(files(home).login);
293
- remove(files(home).loginReply);
294
255
  if (pending?.pid && pending.pid !== process.pid && alive(pending.pid))
295
256
  process.kill(pending.pid, "SIGTERM");
296
257
  }