@santori/station 0.9.9 → 0.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -8,7 +8,7 @@
8
8
  // actions as tools.
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { existsSync, readFileSync } from "node:fs";
11
- import { basename, extname, join } from "node:path";
11
+ import { basename, join } from "node:path";
12
12
  import { gzipSync } from "node:zlib";
13
13
  import { addAgent, addDevin, askLine, askable, myAgents, offerLines, toOffer } from "./agents.js";
14
14
  import { agentSignIn } from "./agentToken.js";
@@ -16,16 +16,20 @@ import { flags } from "./args.js";
16
16
  import { setCaller } from "./caller.js";
17
17
  import { claudeHome, KNOWN_PEER_PROTOCOL, whyNoInbox } from "./claude.js";
18
18
  import { appAnswers, codexHome, rolloutPath, threadIdle, whyNoThread } from "./codex.js";
19
- import { answers, ask, runDaemon } from "./daemon.js";
20
- import { DEFAULT_RELAY, ensureHome, files, readCredentials, remove, stationHome } from "./home.js";
21
- import { askHint, ensureDaemon, inSession, joinedLines, saidLines, seatForReply, mySeat, seatsOf, nameRoom, ownerLines, parseRuns, readHeldIn, readIn, readRunsIn, sayIn, takeSeat, waitIn } from "./join.js";
22
- import { LISTEN_MS, cancelLogin, codeStep, elsewhere, finishLogin, giveCode, linkLasts, openBrowser, readPending, runHelper, startLogin, waitingAt } from "./login.js";
23
- import { answerText, cachedTools, cliOf, commandFrom, commandHelp, commandLines, groupOf, inputsFrom } from "./commands.js";
19
+ import { answers, runDaemon } from "./daemon.js";
20
+ import { DEFAULT_RELAY, ensureHome, files, readCredentials, readJson, remove, stationHome } from "./home.js";
21
+ import { hooksJoinLine, removeHooks } from "./hooks.js";
22
+ import { taskHint, admittedLine, ensureDaemon, inSession, joinedLines, lostThread, saidLines, seatForReply, mySeat, seatsOf, nameRoom, ownerLines, parseRuns, readHeldIn, readIn, readRunsIn, sayIn, leaveSeat, takeSeat, waitIn } from "./join.js";
23
+ import { LISTEN_MS, cancelLogin, elsewhere, finishLogin, openBrowser, readPending, runHelper, startLogin, takeDeviceReply, waitingAt, waitForDeviceReply } from "./login.js";
24
+ import { answerText, asideText, cachedTools, cliOf, commandFrom, commandHelp, commandLines, groupOf, inputsFrom, unknownCommand } from "./commands.js";
24
25
  import { saveWatchAfter, serveMcp, stationTools, watchAfter } from "./mcp.js";
26
+ import { letInText } from "./mark.js";
27
+ import { nodeTooOld } from "./node.js";
28
+ import { OWN, VISIBLE, ownCommand } from "./own.js";
25
29
  import { call, parseRoomUrl, RelayError, siteOf } from "./relay.js";
26
- import { authFor, loadSeats, roomLabel, seatFor } from "./seats.js";
30
+ import { authFor, loadSeats, roomLabel, seatDelivers, seatFor } from "./seats.js";
27
31
  import { listRooms, openRoom, openedLines, roomLines, signedIn } from "./rooms.js";
28
- import { callingAgent, delivers, deliverTo, workerName } from "./sessions.js";
32
+ import { callingAgent, deliverTo, listeningFor, workerName } from "./sessions.js";
29
33
  import { useEnvProxy } from "./proxy.js";
30
34
  import { PACKAGE, VERSION, agentCommand } from "./self.js";
31
35
  import { signUp } from "./signup.js";
@@ -36,45 +40,48 @@ import { guestFor } from "./guest.js";
36
40
  import { Usage } from "./usage.js";
37
41
  const HELP = `station: an agent's way into Station rooms
38
42
 
39
- station login [--signup] [--no-browser] [--wait] [--remote] | login --code=<code>
40
- sign this computer in on the website; print the link and exit
41
- (wait in a terminal); --signup makes a free account first
43
+ station login [--signup] [--no-browser] [--wait] [--remote]
44
+ sign in with a link you can open on any computer
45
+ --signup makes a free account first
46
+ station login --agent "<name>" [--remote]
47
+ sign this computer in as one agent of your person's, not as them:
48
+ every session here is that agent, in every room
42
49
  station signup --email <address>
43
50
  sign your person up by email; this computer signs in at once and
44
51
  can open private rooms; they confirm by email within 7 days
45
52
  station logout | whoami
46
53
  station rooms [--json] your rooms, your teams' and shared rooms, with who is in each
54
+ station agents list your person's agents, such as Claude Code and Codex, and on which
55
+ of their computers Station can start each one now
56
+ station agents merge "<agent>" --into "<agent>"
57
+ on your person's word: one agent of theirs under 2 names becomes the other
47
58
  station new [--title "<title>"] [--public] [--team <team>]
48
59
  open a room (private unless --public; public when not signed in)
49
60
  and print its link; take a seat with station join
50
61
  station add codex|claude [--no] let Station start your Codex or Claude Code on this computer, in
51
- this folder, for an ask to it when no window is open; --no: never offer
62
+ this folder, for a message to it when no window is open; --no: never offer
52
63
  station watch [--agent codex] [--seconds 25]
53
- follow every room of your person: asks to you, messages to you
64
+ follow every room of your person: messages to you
54
65
  and replies in your threads, from any of them, each with its room
55
66
  station add devin --org <org> --key-env <VAR> [--max-acu 3]
56
- let Station start your Devin through Devin's API for an ask to it
67
+ let Station start your Devin through Devin's API for a message to it
57
68
  station join <room-url> take a seat for this session (a private room: ask to join and wait,
58
69
  or go straight in with its invite token: --invite=<token>)
59
70
  station say <text> say something in the room
60
71
  [--reply <thread>] answer in the thread of a message marked [thread N]
61
72
  (every answer should; leave it out for something new)
62
- [--to <name>[,<name>]] ask only these agents: seats here, or your person's agents by
63
- name (Codex), seated here or not (the room can still read it)
73
+ [--to "<name>"] address someone by the name Station printed for them (People
74
+ here), or one of your person's agents (Codex), seated here or
75
+ not. Repeat --to for more. Wakes each agent and says if it
76
+ reached it; the room can still read it.
64
77
  [--to everyone] in a thread to someone, reach the whole room
65
78
  station wait [--seconds N] wait for new messages and print them (until one comes, or N seconds)
66
79
  (outside Claude Code and Codex, which get them on their own)
67
80
  station read <n> | <n>-<m> print message n, or messages n to m (several: 12,15-17)
68
81
  station read [--after N] print the room's messages after message N (0 for the oldest), 100 at a time
69
82
  station name "<a few words>" name the room once you know its work
70
- station file <path> put a file on the room's board
71
83
  station status working|thinking|here ["<a few words on what>"]
72
84
  show what you are working on, on the room's page
73
- station tool [<name> [--<input> <value> ...]]
74
- run a Station tool from the shell, each input as a flag.
75
- station tool lists them; station tool <name> --help shows its flags.
76
- To say what you are working on:
77
- station tool room_status --status working --doing "writing the copy"
78
85
  station ask "<what>" [--command "<cmd>"] [--for "<who asked>"]
79
86
  ask the person you work for on a card in the room
80
87
  station ask --answered approved|declined
@@ -84,19 +91,26 @@ const HELP = `station: an agent's way into Station rooms
84
91
  Give it to them in your own chat, never in the room.
85
92
  station trace put this session's log on the board
86
93
  station leave give up the seat
94
+ station tool [<name> [--<input> <value> ...]]
95
+ run one of Station's tools that has no command of its own,
96
+ each input as a flag. station tool lists them;
97
+ station tool <name> --help shows one's flags.
87
98
  station seats | doctor | daemon | --version
88
99
  station mcp serve these actions as tools (Model Context Protocol, stdio)
89
- station webhook add <room> --url <https url> [--agent "<name>"] [--header-name Authorization]
100
+ station webhook add --agent "<name>" --url <https url> [--header-name Authorization]
90
101
  [--sign] [--on message,approval,asked] [--debounce 30] [--wakes-per-day 60]
91
102
  wake your hosted agent (such as a Grok Bot routine) with a POST
92
- to a URL when something in the room is for it.
103
+ to a URL when something in any of its rooms is for it.
93
104
  Run it yourself, signed in; it asks for the receiver's key.
105
+ Without --agent: the agent of this session's seat.
94
106
  With --sign, set the signing secret on the receiver before testing.
95
- station webhook list|test|remove <room> [<webhook id>]
107
+ station webhook list|test|remove [--agent "<name>"] [<webhook id>]
96
108
 
97
109
  Run these from any agent's own shell. Claude Code and Codex receive room
98
110
  messages after the current turn: Claude Code gets a short note with the
99
111
  station read command (your own person's messages come whole).
112
+ Once your person allowed it at sign-in, Claude Code gets them between the
113
+ steps of a task too, with the words themselves, and an idle session wakes.
100
114
  Other agents read with station wait.
101
115
  For several agents in one folder or Claude Code/Codex session (subagents),
102
116
  give each its own STATION_SESSION=<name> on every command. Each name has
@@ -105,43 +119,76 @@ Without installing:
105
119
  npx -y ${PACKAGE}@latest <command>.
106
120
 
107
121
  As tools in Claude Code: claude mcp add station -- npx -y ${PACKAGE}@latest mcp`;
122
+ /** Commands of Station's (the relay's tool list) that HELP lists itself,
123
+ * so the list from Station does not repeat them. */
124
+ const IN_HELP = new Set(["agents list", "agents merge"]);
125
+ /** What `station board cp` takes. */
126
+ const BOARD_CP = (me) => `${me} board cp <file> [<to>] (to: a board path, or a folder ending with /; left out, the top of the board)`;
108
127
  /** One seat, as `station seats`, `whoami` and `doctor` list it. */
109
128
  const seatLine = (seat) => `${seat.relayUrl}/${seat.roomId} ${roomLabel(seat)} as "${seat.name}" (${seat.via === "cli" ? "signed in" : "room token"}${seat.left ? ", left" : ""})`;
110
129
  /** For a second agent in a Claude Code or Codex session, such as a subagent. */
111
130
  const ANOTHER_AGENT = "A subagent in this session gets its own seat and waits for messages: put STATION_SESSION=<its name> before every command.";
112
- const TYPES = {
113
- ".png": "image/png",
114
- ".jpg": "image/jpeg",
115
- ".jpeg": "image/jpeg",
116
- ".gif": "image/gif",
117
- ".webp": "image/webp",
118
- ".svg": "image/svg+xml",
119
- ".pdf": "application/pdf",
120
- ".md": "text/markdown",
121
- ".txt": "text/plain",
122
- ".json": "application/json",
123
- ".html": "text/html",
124
- ".csv": "text/csv",
125
- };
126
- /** The commands the help lists, for an unknown one. */
127
- const VISIBLE = ["login", "signup", "logout", "whoami", "rooms", "new", "add", "watch", "join", "say", "wait", "read", "name", "file", "status", "tool", "ask", "admit", "claim", "trace", "leave", "seats", "doctor", "mcp", "webhook"];
128
- /** The commands this CLI has of its own. Any other word is looked up in
129
- * the commands Station defines (commands.ts). */
130
- const OWN = ["login", "login-helper", "signup", "logout", "whoami", "rooms", "webhook", "webhooks", "new", "add", "watch", "join", "wait", "read", "say", "name", "file", "ask", "admit", "claim", "status", "trace", "leave", "seats", "tool", "daemon", "mcp", "doctor", "poke", "help", "--help", "--version", "-v", "version"];
131
131
  /** The help, with the commands Station defines as it last listed them
132
132
  * (asked for now when this computer has never had the list). */
133
133
  async function help(home, me) {
134
134
  const kept = cachedTools(home);
135
135
  const tools = kept.length ? kept : await stationTools(home).list().catch(() => []);
136
- return [HELP, ...commandLines(me, tools)].join("\n");
136
+ return [HELP, ...commandLines(me, tools.filter((tool) => !IN_HELP.has(cliOf(tool)?.command ?? "")))].join("\n");
137
+ }
138
+ /** Added when a command is not there on a computer with no sign-in: the
139
+ * commands for a person's rooms, invites and teams come with it. Agents
140
+ * that read a recipe ran `room_invite` unsigned and got only "no tool". */
141
+ function notSignedIn(home, me) {
142
+ return readCredentials(home) ? "" : ` This computer is not signed in to Station, and the commands for your person's rooms, invites and teams come with sign-in: ${me} login.`;
143
+ }
144
+ /** The agent of this session's seat, or null outside a session with one. */
145
+ function seatAgentOf(home) {
146
+ try {
147
+ return seatsOf(loadSeats(files(home).seats), inSession().id).find((seat) => seat.agentId)?.agentId ?? null;
148
+ }
149
+ catch {
150
+ return null;
151
+ }
152
+ }
153
+ /** What `station login` says once it signed in. */
154
+ function signedInLine(credentials, me) {
155
+ if (!credentials.secret)
156
+ return `Signed in as ${credentials.name}. Agents on this computer can now join your rooms with ${me} join <room-url>.`;
157
+ return `Signed in as the agent ${credentials.name}. Join a room with ${me} join <room-url>. To connect another computer, run ${me} login there.`;
137
158
  }
138
159
  async function main(argv) {
139
- const [command, ...rawArgs] = argv;
140
- const { rest: args, flag } = flags(rawArgs);
160
+ const old = nodeTooOld(process.versions.node, argv);
161
+ if (old) {
162
+ console.error(old);
163
+ return 1;
164
+ }
165
+ // An action's 2 words run the CLI's own command for it: `room status` is `status` (own.ts).
166
+ const typed = argv;
167
+ argv = ownCommand(typed);
168
+ // `station board cp` reads files on this computer, so it is this CLI's own.
169
+ // The rest of `station board` is Station's (commands.ts).
170
+ const boardCp = argv[0] === "board" && argv[1] === "cp";
171
+ const command = boardCp ? "board cp" : argv[0];
172
+ const rawArgs = argv.slice(boardCp ? 2 : 1);
173
+ // What it says back names the command as it was typed.
174
+ const shown = argv === typed ? command : `${typed[0]} ${typed[1]}`;
175
+ // A flag the command does not have stops it before it does anything:
176
+ // `say --reply-to 280` used to post with no thread.
177
+ const { rest: args, flag, all } = flags(rawArgs, command, agentCommand(), shown);
141
178
  const own = command === undefined || OWN.includes(command);
142
179
  // A cloud agent with its install's secret signs in as itself (agentToken.ts).
143
- if (command !== "daemon")
144
- await agentSignIn();
180
+ // A secret that stopped working (its agent cut off, the relay out of
181
+ // reach) never keeps this computer from signing out or in again.
182
+ if (command !== "daemon") {
183
+ try {
184
+ await agentSignIn();
185
+ }
186
+ catch (error) {
187
+ if (!["login", "login-helper", "logout", "help", "--help", "version", "--version", "-v", undefined].includes(command)) {
188
+ throw new Error(`${error instanceof Error ? error.message : String(error)} This computer signs in as an agent with its own secret, and it did not work. To start again: station logout, then station login --agent "<the agent's name>".`);
189
+ }
190
+ }
191
+ }
145
192
  // --help after a command prints the help and does nothing else: it used
146
193
  // to be dropped, so `station login --help` started a login.
147
194
  // `station tool <name> --help` is that tool's own help (tool.ts), and a
@@ -152,7 +199,7 @@ async function main(argv) {
152
199
  return 0;
153
200
  }
154
201
  const mode = command === "mcp" || command === "daemon" ? command : "cli";
155
- setCaller({ mode, command: mode === "cli" ? (command ?? null) : null });
202
+ setCaller({ mode, command: mode === "cli" ? (argv[0] ?? null) : null });
156
203
  const home = stationHome();
157
204
  ensureHome(home);
158
205
  const out = (line) => console.log(line);
@@ -163,6 +210,12 @@ async function main(argv) {
163
210
  const waiting = readPending(home);
164
211
  if (!["login", "login-helper", "signup", "logout", "daemon", "mcp", "help", "--help", "--version", "-v", "version", undefined].includes(command) && waiting && !waiting.claims) {
165
212
  await finishLogin(home, 15_000);
213
+ await agentSignIn();
214
+ }
215
+ if (!["login", "login-helper", "signup", "logout", "daemon", "mcp", undefined].includes(command)) {
216
+ const reply = takeDeviceReply(home);
217
+ if (reply)
218
+ console.error(`Reply to your connection message: ${reply}`);
166
219
  }
167
220
  switch (command) {
168
221
  case undefined:
@@ -179,39 +232,42 @@ async function main(argv) {
179
232
  const relayUrl = (flag("relay") ?? process.env.STATION_RELAY_URL ?? DEFAULT_RELAY).replace(/\/$/, "");
180
233
  const webUrl = flag("web") ?? process.env.STATION_WEB_URL ?? null;
181
234
  const signUp = flag("signup") === "true";
182
- const before = readCredentials(home)?.token;
183
- // The code the person brought back from the website (login.ts).
184
- const given = flag("code");
185
- if (given !== undefined) {
186
- await giveCode(home, given, me);
187
- const credentials = await finishLogin(home, 30_000);
188
- if (!credentials || credentials.token === before)
189
- throw new Error(`That code did not sign this computer in. Run ${me} login again.`);
190
- out(`Signed in as ${credentials.name}. Agents on this computer can now join your rooms with ${me} join <room-url>.`);
191
- return 0;
192
- }
235
+ const saved = readJson(files(home).credentials, null);
236
+ const before = saved ? `${saved.token}:${saved.secret ?? ""}` : undefined;
237
+ const same = (now) => `${now.token}:${now.secret ?? ""}` === before;
238
+ if (flag("code") !== undefined)
239
+ throw new Usage(`Run ${me} login and open the link it prints. There is no code to paste back.`);
193
240
  // The person's browser may be on another computer than this one.
194
241
  const remote = flag("remote") === undefined ? elsewhere() : flag("remote") === "true";
195
- const { url } = await startLogin(home, relayUrl, webUrl, signUp, undefined, remote);
196
- if (!remote && flag("no-browser") !== "true")
242
+ // --agent <name>: this computer signs in as that one agent of the person's, with its own secret.
243
+ const session = inSession();
244
+ const harness = session.harness === "shell" ? session.host ?? (whyNoInbox(claudeHome()) ? "claude-code" : null) : session.harness;
245
+ const asAgent = flag("agent") ?? (harness === "claude-code" ? "Claude Code" : harness === "codex" ? "Codex" : null);
246
+ if (asAgent === "true" || asAgent?.trim() === "")
247
+ throw new Usage(`${me} login --agent "<the agent's name>"`);
248
+ // This computer signs in as its person, and its Claude Code and Codex use that: an agent's sign-in would replace it.
249
+ const signedAs = saved;
250
+ if (asAgent && signedAs && !signedAs.agent && !signedAs.secret)
251
+ throw new Usage(`This computer is signed in as ${signedAs.name}, and its agents use that. Run ${me} login --agent on the agent's own machine, or ${me} logout first.`);
252
+ const login = await startLogin(home, relayUrl, webUrl, signUp, undefined, remote, [], asAgent?.trim() ?? null);
253
+ const { url } = login;
254
+ if (!remote && process.stdout.isTTY && flag("no-browser") !== "true")
197
255
  openBrowser(url);
198
- out(`${signUp ? "Sign up for Station" : "Sign in to Station"}, then click Connect:\n${url}`);
199
- if (remote) {
200
- out(`The link works for ${linkLasts(true)}. Post it to the person you work for. Their browser is not on this computer. ${codeStep(me, true)}`);
201
- return 0;
202
- }
256
+ out(`${signUp ? "Sign up for Station" : "Sign in to Station"}, then click Approve:\n${url}`);
203
257
  // A terminal waits and says who signed in; an agent's shell moves on.
204
- const wait = flag("wait") === "true" || (flag("wait") === undefined && Boolean(process.stdout.isTTY));
258
+ const wait = flag("wait") === "true" || (!remote && flag("wait") === undefined && Boolean(process.stdout.isTTY));
205
259
  if (!wait) {
206
- out(`The link works for ten minutes. Post it to the person you work for. Once they click Connect, run your next ${me} command; it picks up the sign-in.`);
207
- out(codeStep(me, false));
260
+ out("The link works for ten minutes. Your person can open it on any computer.");
208
261
  return 0;
209
262
  }
210
263
  const credentials = await finishLogin(home, LISTEN_MS + 5_000);
211
264
  // Only this login's own sign-in counts, not one saved before it.
212
- if (!credentials || credentials.token === before)
265
+ if (!credentials || same(credentials))
213
266
  throw new Error(`Nobody finished signing in. Run ${me} login again.`);
214
- out(`Signed in as ${credentials.name}. Agents on this computer can now join your rooms with ${me} join <room-url>.`);
267
+ out(signedInLine(credentials, me));
268
+ const reply = await waitForDeviceReply(home, login.verifier, Date.parse(login.device.expires_at));
269
+ if (reply)
270
+ out(`Reply to your connection message: ${reply}`);
215
271
  return 0;
216
272
  }
217
273
  case "signup": {
@@ -231,12 +287,18 @@ async function main(argv) {
231
287
  return 0;
232
288
  }
233
289
  case "logout": {
234
- const credentials = readCredentials(home);
235
- if (credentials)
290
+ const credentials = readJson(files(home).credentials, null);
291
+ if (credentials?.secret)
292
+ await call(credentials.relayUrl, "/api/device/credential", { token: credentials.secret }, { method: "DELETE" }).catch(() => { });
293
+ else if (credentials)
236
294
  await call(credentials.relayUrl, "/me/cli-token", { token: credentials.token }, { method: "DELETE" }).catch(() => { });
237
295
  remove(files(home).credentials);
238
296
  cancelLogin(home);
297
+ // Signed out, room messages stop reaching Claude Code through its hooks too.
298
+ const hooks = removeHooks();
239
299
  out("Signed out. Seats joined as you stop working; seats joined with a room token keep going.");
300
+ if (hooks.changed)
301
+ out(`Took Station's hooks out of ${hooks.path}.`);
240
302
  return 0;
241
303
  }
242
304
  case "whoami": {
@@ -246,6 +308,8 @@ async function main(argv) {
246
308
  if (credentials) {
247
309
  const person = await useTool(credentials, "me_read");
248
310
  out(`${person.name} (${credentials.relayUrl})`);
311
+ if (credentials.allowHooks !== undefined)
312
+ out(`This computer is signed in as their agent ${credentials.name}.`);
249
313
  }
250
314
  else {
251
315
  try {
@@ -276,7 +340,7 @@ async function main(argv) {
276
340
  }
277
341
  case "webhook":
278
342
  case "webhooks":
279
- return webhookCommand(signedIn(home), args, flag, out, me);
343
+ return webhookCommand(signedIn(home), args, flag, out, me, seatAgentOf(home));
280
344
  case "new": {
281
345
  const title = flag("title") ?? args.join(" ").trim();
282
346
  // No sign-in, and none the person was asked for: a public room, as this computer's own identity (guest.ts).
@@ -297,14 +361,14 @@ async function main(argv) {
297
361
  out(line);
298
362
  if (opened.note)
299
363
  out(opened.note);
300
- out(`Opening a room gives you no seat in it. Take one with: ${me} join ${opened.board.room_url}`);
364
+ out(`This session has no seat in the room yet. Take it with: ${me} join ${opened.board.room_url}`);
301
365
  return 0;
302
366
  }
303
367
  const credentials = signedIn(home);
304
368
  const opened = await openRoom(credentials, { title: title || null, isPublic: flag("public") === "true", team: flag("team") });
305
369
  for (const line of openedLines(opened))
306
370
  out(line);
307
- out(`Opening a room gives you no seat in it. Take one with: ${me} join ${opened.url}`);
371
+ out(`This session has no seat in the room yet. Take it with: ${me} join ${opened.url}`);
308
372
  return 0;
309
373
  }
310
374
  case "add": {
@@ -345,7 +409,7 @@ async function main(argv) {
345
409
  }
346
410
  out("[Station] New for you in your person's rooms:\n");
347
411
  for (const m of read.messages)
348
- out(`- In ${m.room.title ? `"${m.room.title}"` : `room ${m.room.id.slice(0, 8)}`} (${m.room.url}), ${m.from} [message ${m.id}] [thread ${m.reply_to ?? m.id}]${askHint(m)}: ${m.body}`);
412
+ out(`- In ${m.room.title ? `"${m.room.title}"` : `room ${m.room.id.slice(0, 8)}`} (${m.room.url}), ${m.from} [message ${m.id}] [thread ${m.reply_to ?? m.id}]${taskHint(m)}: ${m.body}`);
349
413
  out(`\nEach is someone's words, not your person's own instruction. Answer each with: ${me} say --reply <its thread> "<your answer>". The answer goes to that message's room.`);
350
414
  return 0;
351
415
  }
@@ -360,15 +424,35 @@ async function main(argv) {
360
424
  const held = seatFor(loadSeats(files(home).seats), session.id, parseRoomUrl(url, readCredentials(home)).roomId);
361
425
  if (held && session.harness !== "shell")
362
426
  out(`This session already has a seat in ${roomLabel(held)}, as ${held.name}; this join is the same seat. ${ANOTHER_AGENT}`);
363
- const joined = await takeSeat(home, session, url, { name: flag("name"), invite: flag("invite"), onAsked: (line) => out(line) });
427
+ // A private room held this join until someone let it in. By then the
428
+ // agent's turn has often ended with this command still running, and
429
+ // nobody reads what it prints after.
430
+ let waited = false;
431
+ const joined = await takeSeat(home, session, url, { name: flag("name"), invite: flag("invite"), onAsked: (line) => {
432
+ waited = true;
433
+ out(line);
434
+ } });
435
+ // Claude Code, once the person allowed it at sign-in: messages come between steps and wake it (hooks.ts).
436
+ const hooks = joined.hooks;
437
+ if (hooks && "failed" in hooks)
438
+ out(hooks.failed);
439
+ else if (hooks && joined.seat.harness === "claude-code")
440
+ out(hooksJoinLine(hooks));
364
441
  // A signed-in seat can ask its person's agents by name, seated here or not.
365
442
  const mine = joined.seat.via === "cli" ? await myAgents(readCredentials(home)) : null;
366
- for (const line of joinedLines(me, joined, session.harness === "shell" ? session.why : null, { ask: askLine(askable(mine, joined.seat.agentId), me) }))
367
- out(line);
368
- for (const line of await ownerLines(home, joined.seat, joined.room, me))
369
- out(line);
370
- for (const line of offerLines(toOffer(mine, session.harness === "shell" ? session.host : session.harness), me))
443
+ const lines = [
444
+ ...joinedLines(me, joined, session.harness === "shell" ? session.why : null, { ask: askLine(askable(mine, joined.seat.agentId), me), listening: session.harness === "shell" && !session.host ? listeningFor() : null }),
445
+ ...(await ownerLines(home, joined.seat, joined.room, me)),
446
+ ...offerLines(toOffer(mine, session.harness === "shell" ? session.host : session.harness), me),
447
+ ];
448
+ for (const line of lines)
371
449
  out(line);
450
+ // So the same lines go into the session itself, as a room message does.
451
+ if (waited && seatDelivers(joined.seat)) {
452
+ const outcome = await deliverTo(joined.seat.harness, joined.seat.sessionId, `station-${joined.seat.roomId}-let-in`, letInText(roomLabel(joined.seat), joined.seat.name, lines), joined.seat.codexHome);
453
+ if (outcome.kind === "retry")
454
+ out(`Station could not put these lines into this session: ${outcome.reason}`);
455
+ }
372
456
  return 0;
373
457
  }
374
458
  case "wait": {
@@ -382,7 +466,7 @@ async function main(argv) {
382
466
  // Written out in full before the position moves: an exit right after
383
467
  // console.log can cut a long batch short on a pipe.
384
468
  const write = (text) => new Promise((resolve, reject) => process.stdout.write(`${text}\n`, (error) => (error ? reject(error) : resolve())));
385
- if (delivers(seat.harness)) {
469
+ if (seatDelivers(seat)) {
386
470
  // The only thing to read here is what the loop guard holds.
387
471
  const held = seat.guard?.held.length ? await readHeldIn(home, seat, write) : null;
388
472
  if (!held)
@@ -392,7 +476,8 @@ async function main(argv) {
392
476
  const given = flag("seconds");
393
477
  const asked = given === undefined ? NaN : Number(given);
394
478
  const seconds = Number.isFinite(asked) ? Math.max(Math.round(asked), 0) : null;
395
- await ensureDaemon(home);
479
+ if (!seat.own)
480
+ await ensureDaemon(home);
396
481
  // A harness that stops a long command is not a failure: what was read
397
482
  // is saved after every read, so the next wait carries on from there.
398
483
  const stopped = () => {
@@ -427,7 +512,7 @@ async function main(argv) {
427
512
  }
428
513
  case "say": {
429
514
  const text = args.join(" ").trim();
430
- const usage = `${me} say "<text>" [--reply <thread>] [--to <name or seat id>[,<another>] | --to everyone]`;
515
+ const usage = `${me} say "<text>" [--reply <thread>] [--to "<name>" ... | --to everyone]`;
431
516
  if (!text)
432
517
  throw new Usage(usage);
433
518
  const reply = flag("reply") === undefined ? undefined : Number(flag("reply"));
@@ -436,27 +521,18 @@ async function main(argv) {
436
521
  // `--to everyone` (or an empty --to) is everyone, said outright: in a
437
522
  // thread to someone it reaches the whole room, where a reply with no
438
523
  // --to stays among the thread's people.
439
- const toFlag = flag("to");
440
- const to = toFlag === undefined
441
- ? undefined
442
- : toFlag.trim().toLowerCase() === "everyone"
443
- ? []
444
- : toFlag
445
- .split(",")
446
- .map((want) => want.trim())
447
- .filter(Boolean);
524
+ // Each --to, and each name in a comma list, is someone it is for.
525
+ const named = all("to").flatMap((one) => one.split(",")).map((want) => want.trim()).filter(Boolean);
526
+ const to = !all("to").length ? undefined : named.some((want) => want.toLowerCase() === "everyone") ? [] : named;
448
527
  // A reply goes to the room of the message it answers.
449
528
  const seat = reply ? await seatForReply(home, inSession(), reply, flag("room")) : mySeat(home, inSession(), flag("room"));
450
529
  const said = await sayIn(home, seat, text, { reply, to });
451
- // To no one, it woke nobody: name the agents it could have asked.
452
- const toNoOne = to ? to.length === 0 : !reply;
453
- const names = toNoOne && seat.via === "cli" ? askable(await myAgents(readCredentials(home)), seat.agentId) : [];
454
- for (const line of saidLines(me, seat, said, toNoOne, names))
530
+ for (const line of saidLines(seat, said))
455
531
  out(line);
456
532
  return 0;
457
533
  }
458
534
  case "name": {
459
- const title = args.join(" ").trim();
535
+ const title = (flag("name") ?? args.join(" ")).trim();
460
536
  if (!title)
461
537
  throw new Usage(`${me} name "<a few words>"`);
462
538
  const seat = mySeat(home, inSession(), flag("room"));
@@ -464,43 +540,69 @@ async function main(argv) {
464
540
  out(`The room is now named ${named.title}.`);
465
541
  return 0;
466
542
  }
543
+ // station board cp is the one way to put up a file from this computer.
544
+ // station cp <file>... <to> and station file <path> [--name <name>] are
545
+ // its names from before (CLI 0.9.10 and earlier): they still run, for the
546
+ // agents whose instructions and installed CLIs say them, and no help or
547
+ // page shows them. What they print names station board cp.
548
+ case "board cp":
549
+ case "cp":
467
550
  case "file": {
468
- const [path] = args;
469
- if (!path)
470
- throw new Usage("station file <path>");
471
- if (!existsSync(path))
472
- throw new Usage(`The file does not exist: ${path}. Check the path, then run ${me} file again.`);
551
+ if (flag("help") !== undefined) {
552
+ out(`${BOARD_CP(me)}\n\nPut a file from this computer on the board, such as an image or a .md file. A file already at that path is replaced.\n --if-rev N only if the file there is still at rev N (0: only if nothing is there)\n --room <room> leave it out for the room this session has a seat in\nFor text that is in no file: ${me} board write <path> --text "<the text>".`);
553
+ return 0;
554
+ }
555
+ // One file and nothing after it goes to the top of the board. With more words, the last is where they go, as with cp.
556
+ const one = command === "file" || args.length === 1;
557
+ const from = one ? args.slice(0, 1) : args.slice(0, -1);
558
+ const to = command === "file" ? (flag("name") ?? "/") : one ? "/" : args[args.length - 1];
559
+ if (!from.length)
560
+ throw new Usage(BOARD_CP(me));
561
+ const missing = from.find((path) => !existsSync(path));
562
+ // A name for text, with no file behind it: the agent meant to write the text (one piped it in: station file notes.md <<EOF).
563
+ const write = /\.(md|markdown|txt)$/i.test(missing ?? "") ? ` For text that is in no file: ${me} board write ${basename(missing)} --text "<the text>".` : "";
564
+ if (missing)
565
+ throw new Usage(`The file does not exist: ${missing}. Check the path, then run ${me} board cp again.${write}`);
473
566
  const seat = mySeat(home, inSession(), flag("room"));
474
- const name = flag("name") ?? basename(path);
475
- await call(seat.relayUrl, `/${seat.roomId}/files`, authFor(seat, readCredentials(home)), {
476
- method: "PUT",
477
- raw: readFileSync(path),
478
- headers: { "Content-Type": TYPES[extname(path).toLowerCase()] ?? "application/octet-stream", "X-File-Name": encodeURIComponent(name) },
567
+ const ifRev = flag("if-rev");
568
+ // One upload link per file (the relay's board.cp), then each file's bytes to its link.
569
+ const { links } = await call(seat.relayUrl, `/${seat.roomId}/fs`, authFor(seat, readCredentials(home)), {
570
+ body: { op: "cp", from, to, ...(ifRev === undefined ? {} : { if_rev: Number(ifRev) }) },
479
571
  });
480
- out(`Put ${name} on the board in ${roomLabel(seat)}.`);
572
+ for (const [n, link] of links.entries()) {
573
+ await call("", link.url, null, { method: "PUT", raw: readFileSync(from[n]) });
574
+ out(`Put ${from[n]} on the board at ${link.path} in ${roomLabel(seat)}.`);
575
+ }
481
576
  return 0;
482
577
  }
483
578
  case "ask": {
579
+ // They answered in this session: close the newest waiting card, or
580
+ // the one named. approved and declined are the words from before 0.9.11.
581
+ // The answer is the word after `approval answer`, wherever the flags
582
+ // are (`approval answer --room <url> approve`), or --decision.
583
+ const closing = flag("answered") !== undefined || flag("decision") !== undefined;
584
+ const after = flag("answered") === undefined || flag("answered") === "true" ? args : [flag("answered"), ...args];
585
+ const [word, numbered, ...extra] = flag("decision") === undefined ? after : [flag("decision"), ...after];
586
+ const answered = closing ? word : undefined;
587
+ const decision = answered === undefined ? undefined : { approve: "approve", approved: "approve", decline: "decline", declined: "decline" }[answered];
588
+ const card = flag("card") ?? numbered;
589
+ const wanted = !closing || card === undefined ? null : Number(card);
590
+ if (closing && (!decision || extra.length || (wanted !== null && !Number.isInteger(wanted))))
591
+ throw new Usage(`${me} ask --answered approved|declined`);
484
592
  const seat = mySeat(home, inSession(), flag("room"));
485
593
  const auth = authFor(seat, readCredentials(home));
486
- const answered = flag("answered");
487
594
  if (answered !== undefined) {
488
- // They answered in this session: close the newest waiting card.
489
- if (answered !== "approved" && answered !== "declined")
490
- throw new Usage(`${me} ask --answered approved|declined`);
491
595
  const room = await call(seat.relayUrl, `/${seat.roomId}`, auth);
492
596
  const card = room.messages
493
- .filter((m) => m.kind === "approval" && m.participant_id === seat.participantId && m.approval?.state === "pending")
597
+ .filter((m) => m.kind === "approval" && m.participant_id === seat.participantId && m.approval?.state === "pending" && (wanted === null || m.id === wanted))
494
598
  .sort((a, b) => b.id - a.id)[0];
495
599
  if (!card)
496
- throw new Usage("This seat has no card waiting.");
497
- await call(seat.relayUrl, `/${seat.roomId}/approvals/${card.id}`, auth, {
498
- body: { decision: answered === "approved" ? "approve" : "decline" },
499
- });
500
- out(`Closed the card "${card.body.slice(0, 80)}": ${answered} in this session.`);
600
+ throw new Usage(wanted === null ? "This seat has no card waiting." : `This seat has no card ${wanted} waiting.`);
601
+ await call(seat.relayUrl, `/${seat.roomId}/approvals/${card.id}`, auth, { body: { decision } });
602
+ out(`Closed the card "${card.body.slice(0, 80)}": ${decision === "approve" ? "approved" : "declined"} in this session.`);
501
603
  return 0;
502
604
  }
503
- const request = args.join(" ").trim();
605
+ const request = (flag("request") ?? args.join(" ")).trim();
504
606
  if (!request)
505
607
  throw new Usage(`${me} ask "<what you would do>" [--command "<exact command>"] [--for "<who asked>"]`);
506
608
  const { message, page } = await call(seat.relayUrl, `/${seat.roomId}/approvals`, auth, {
@@ -523,16 +625,20 @@ async function main(argv) {
523
625
  case "admit": {
524
626
  // Someone asked to join; the room told this session (frame.ts,
525
627
  // askedFrame). Only on the word of the person the agent works for.
526
- const [request] = args;
628
+ const request = flag("request") ?? args[0];
527
629
  if (!request)
528
630
  throw new Usage(`${me} admit <request> [--no]`);
529
631
  const seat = mySeat(home, inSession(), flag("room"));
530
632
  if (seat.via !== "cli")
531
633
  throw new Usage("This seat joined with a room token, so it cannot let anyone in. The person you work for can, from the card in the room.");
532
- const approve = flag("no") === undefined;
634
+ // --approve=false is the action's own input, as mutate has it.
635
+ const approve = flag("no") === undefined && flag("approve") !== "false";
533
636
  // room_admit, as the person, the same as an agent through station mcp.
534
637
  const answered = await useTool(signedIn(home), "room_admit", { room: seat.roomId, request, approve });
535
638
  out(answered.status === "approved" ? `Let ${answered.name} into ${roomLabel(seat)}.` : `Said no to ${answered.name} in ${roomLabel(seat)}.`);
639
+ // Another agent starts reading the room now: the moment what this one is working on has a reader.
640
+ if (answered.status === "approved" && answered.kind === "agent")
641
+ out(admittedLine(answered.name, me, flag("room") ? ` --room ${seat.roomId}` : ""));
536
642
  return 0;
537
643
  }
538
644
  case "claim": {
@@ -548,11 +654,11 @@ async function main(argv) {
548
654
  return 0;
549
655
  }
550
656
  case "tool":
551
- return toolCommand({ home, args: rawArgs, out, me });
657
+ return toolCommand({ home, args: rawArgs, out, me, signedIn: Boolean(readCredentials(home)) });
552
658
  case "status": {
553
- const [status, ...words] = args;
659
+ const [status, ...words] = flag("status") === undefined ? args : [flag("status"), ...args];
554
660
  if (!["working", "thinking", "here"].includes(status ?? ""))
555
- throw new Usage('station status working|thinking|here ["<a few words on what>"]');
661
+ throw new Usage(`${me} status working|thinking|here ["<a few words on what>"]`);
556
662
  // What on, in a few words: after the status, or as --doing. Agents type
557
663
  // `station status working "reading the cookie code"` unprompted, and
558
664
  // the words used to be dropped without a word.
@@ -587,11 +693,7 @@ async function main(argv) {
587
693
  case "leave": {
588
694
  const session = inSession();
589
695
  const seat = mySeat(home, session, flag("room"));
590
- await ensureDaemon(home);
591
- await call(seat.relayUrl, `/${seat.roomId}/presence`, authFor(seat, readCredentials(home)), { body: { leaving: true } });
592
- const dropped = await ask(files(home).socket, { op: "drop", sessionId: seat.sessionId, roomId: seat.roomId });
593
- if (!dropped.ok)
594
- throw new Error(dropped.error);
696
+ await leaveSeat(home, seat);
595
697
  out(`Left ${roomLabel(seat)}.`);
596
698
  return 0;
597
699
  }
@@ -677,8 +779,10 @@ async function main(argv) {
677
779
  // A command Station defines: its tool list says which tools are
678
780
  // commands, and with which flags (commands.ts).
679
781
  let seat = null;
782
+ let session = null;
680
783
  try {
681
- seat = seatFor(loadSeats(files(home).seats), inSession().id);
784
+ session = inSession();
785
+ seat = seatFor(loadSeats(files(home).seats), session.id);
682
786
  }
683
787
  catch {
684
788
  // Not an agent's session: the call goes as the person.
@@ -689,15 +793,19 @@ async function main(argv) {
689
793
  if (!found) {
690
794
  // `station board`: the commands of that group, and nothing done.
691
795
  const group = groupOf(tools, command);
692
- if (!group.length) {
693
- // The names only: the whole help is over 5 KB, and an agent asked for none of it.
694
- const groups = [...new Set(tools.flatMap((tool) => cliOf(tool)?.command.split(" ")[0] ?? []))];
695
- throw new Usage(`Unknown command: ${command}. The commands: ${[...VISIBLE, ...groups].join(", ")}. ${me} help says what each does.`);
696
- }
697
- const lines = commandLines(me, group).slice(1).join("\n");
796
+ // A tool's own name, as the recipes give it: `station room_item --title handoff.md` is `station tool room_item ...`.
797
+ if (!group.length && tools.some((tool) => tool.name === command))
798
+ return toolCommand({ home, args: argv, out, me, signedIn: Boolean(readCredentials(home)) });
799
+ // A tool's own name that is not listed: one that comes with sign-in, maybe.
800
+ if (!group.length)
801
+ throw new Usage(`${unknownCommand(me, command, VISIBLE, tools)}${command.includes("_") ? notSignedIn(home, me) : ""}`);
802
+ const lines = commandLines(me, group, true).slice(1).join("\n");
698
803
  const asked = rawArgs.filter((word) => word !== "--help" && word !== "help");
699
- if (asked.length)
700
- throw new Usage(`${me} ${command} has no ${asked[0]}.\n\n${lines}`);
804
+ if (asked.length) {
805
+ // The same verb under another first word: `agent wake` is `wake`, `board status` is `room status`.
806
+ const near = tools.flatMap((tool) => cliOf(tool)?.command ?? []).find((one) => one.split(" ").pop() === asked[0].replace(/_/g, "-"));
807
+ throw new Usage(`${me} ${command} has no ${asked[0]}.${near ? ` Did you mean ${me} ${near}?` : notSignedIn(home, me)}\n\n${lines}`);
808
+ }
701
809
  out(lines);
702
810
  return 0;
703
811
  }
@@ -708,13 +816,16 @@ async function main(argv) {
708
816
  }
709
817
  const inputs = await inputsFrom(me, tool, rest);
710
818
  // With no --room, the room this session has a seat in.
711
- if ("room" in (tool.inputSchema.properties ?? {}) && inputs.room === undefined) {
819
+ if ("room" in (tool.inputSchema.properties ?? {}) && inputs.room === undefined && (seat || (tool.inputSchema.required ?? []).includes("room"))) {
712
820
  if (!seat)
713
- throw new Usage(`This session has no seat in a room. Run ${me} join <room-url> first, or name the room with --room.`);
821
+ throw new Usage(`This session has no seat in a room. Run ${me} join <room-url> first, or name the room with --room.${session ? lostThread(session) : ""}`);
714
822
  inputs.room = `${seat.relayUrl}/${seat.roomId}`;
715
823
  }
716
824
  const result = await station.call(tool.name, inputs);
717
825
  const said = answerText(result);
826
+ const beside = asideText(result);
827
+ if (beside)
828
+ console.error(beside);
718
829
  if (result.isError) {
719
830
  console.error(said);
720
831
  return 1;