@santori/station 0.9.10 → 0.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -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";
19
+ import { answers, runDaemon } from "./daemon.js";
20
20
  import { DEFAULT_RELAY, ensureHome, files, readCredentials, readJson, remove, stationHome } from "./home.js";
21
- import { taskHint, ensureDaemon, inSession, joinedLines, saidLines, seatForReply, mySeat, seatsOf, nameRoom, ownerLines, parseRuns, readHeldIn, readIn, readRunsIn, sayIn, takeSeat, waitIn } from "./join.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";
22
23
  import { LISTEN_MS, cancelLogin, elsewhere, finishLogin, openBrowser, readPending, runHelper, startLogin, takeDeviceReply, waitingAt, waitForDeviceReply } from "./login.js";
23
- import { answerText, asideText, cachedTools, cliOf, commandFrom, commandHelp, commandLines, groupOf, inputsFrom } from "./commands.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
30
  import { authFor, loadSeats, roomLabel, seatDelivers, seatFor } from "./seats.js";
27
31
  import { listRooms, openRoom, openedLines, roomLines, signedIn } from "./rooms.js";
28
- import { callingAgent, 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";
@@ -66,26 +70,18 @@ const HELP = `station: an agent's way into Station rooms
66
70
  station say <text> say something in the room
67
71
  [--reply <thread>] answer in the thread of a message marked [thread N]
68
72
  (every answer should; leave it out for something new)
69
- [--to <name>[,<name>]] address them: seats here, or your person's agents by name (Codex),
70
- seated here or not. Repeat --to for more. Wakes each agent and
71
- says if it reached it; the room can still read it.
72
- @ and an agent's name in the text does the same
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.
73
77
  [--to everyone] in a thread to someone, reach the whole room
74
78
  station wait [--seconds N] wait for new messages and print them (until one comes, or N seconds)
75
79
  (outside Claude Code and Codex, which get them on their own)
76
80
  station read <n> | <n>-<m> print message n, or messages n to m (several: 12,15-17)
77
81
  station read [--after N] print the room's messages after message N (0 for the oldest), 100 at a time
78
82
  station name "<a few words>" name the room once you know its work
79
- station cp <file>... <to> put files from this computer on the room's board: to is a
80
- board path for one file, or a folder ending with /.
81
- A file already there is replaced. [--if-rev N]
82
83
  station status working|thinking|here ["<a few words on what>"]
83
84
  show what you are working on, on the room's page
84
- station tool [<name> [--<input> <value> ...]]
85
- run a Station tool from the shell, each input as a flag.
86
- station tool lists them; station tool <name> --help shows its flags.
87
- To say what you are working on:
88
- station tool room_status --status working --doing "writing the copy"
89
85
  station ask "<what>" [--command "<cmd>"] [--for "<who asked>"]
90
86
  ask the person you work for on a card in the room
91
87
  station ask --answered approved|declined
@@ -95,6 +91,10 @@ const HELP = `station: an agent's way into Station rooms
95
91
  Give it to them in your own chat, never in the room.
96
92
  station trace put this session's log on the board
97
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.
98
98
  station seats | doctor | daemon | --version
99
99
  station mcp serve these actions as tools (Model Context Protocol, stdio)
100
100
  station webhook add --agent "<name>" --url <https url> [--header-name Authorization]
@@ -109,6 +109,8 @@ const HELP = `station: an agent's way into Station rooms
109
109
  Run these from any agent's own shell. Claude Code and Codex receive room
110
110
  messages after the current turn: Claude Code gets a short note with the
111
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.
112
114
  Other agents read with station wait.
113
115
  For several agents in one folder or Claude Code/Codex session (subagents),
114
116
  give each its own STATION_SESSION=<name> on every command. Each name has
@@ -120,15 +122,12 @@ As tools in Claude Code: claude mcp add station -- npx -y ${PACKAGE}@latest mcp`
120
122
  /** Commands of Station's (the relay's tool list) that HELP lists itself,
121
123
  * so the list from Station does not repeat them. */
122
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)`;
123
127
  /** One seat, as `station seats`, `whoami` and `doctor` list it. */
124
128
  const seatLine = (seat) => `${seat.relayUrl}/${seat.roomId} ${roomLabel(seat)} as "${seat.name}" (${seat.via === "cli" ? "signed in" : "room token"}${seat.left ? ", left" : ""})`;
125
129
  /** For a second agent in a Claude Code or Codex session, such as a subagent. */
126
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.";
127
- /** The commands the help lists, for an unknown one. */
128
- const VISIBLE = ["login", "signup", "logout", "whoami", "rooms", "new", "add", "watch", "join", "say", "wait", "read", "name", "cp", "status", "tool", "ask", "admit", "claim", "trace", "leave", "seats", "doctor", "mcp", "webhook"];
129
- /** The commands this CLI has of its own. Any other word is looked up in
130
- * the commands Station defines (commands.ts). */
131
- const OWN = ["login", "login-helper", "signup", "logout", "whoami", "rooms", "webhook", "webhooks", "new", "add", "watch", "join", "wait", "read", "say", "name", "cp", "file", "ask", "admit", "claim", "status", "trace", "leave", "seats", "tool", "daemon", "mcp", "doctor", "poke", "help", "--help", "--version", "-v", "version"];
132
131
  /** The help, with the commands Station defines as it last listed them
133
132
  * (asked for now when this computer has never had the list). */
134
133
  async function help(home, me) {
@@ -136,6 +135,12 @@ async function help(home, me) {
136
135
  const tools = kept.length ? kept : await stationTools(home).list().catch(() => []);
137
136
  return [HELP, ...commandLines(me, tools.filter((tool) => !IN_HELP.has(cliOf(tool)?.command ?? "")))].join("\n");
138
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
+ }
139
144
  /** The agent of this session's seat, or null outside a session with one. */
140
145
  function seatAgentOf(home) {
141
146
  try {
@@ -152,10 +157,24 @@ function signedInLine(credentials, me) {
152
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.`;
153
158
  }
154
159
  async function main(argv) {
155
- const [command, ...rawArgs] = argv;
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]}`;
156
175
  // A flag the command does not have stops it before it does anything:
157
176
  // `say --reply-to 280` used to post with no thread.
158
- const { rest: args, flag, all } = flags(rawArgs, command, agentCommand());
177
+ const { rest: args, flag, all } = flags(rawArgs, command, agentCommand(), shown);
159
178
  const own = command === undefined || OWN.includes(command);
160
179
  // A cloud agent with its install's secret signs in as itself (agentToken.ts).
161
180
  // A secret that stopped working (its agent cut off, the relay out of
@@ -180,7 +199,7 @@ async function main(argv) {
180
199
  return 0;
181
200
  }
182
201
  const mode = command === "mcp" || command === "daemon" ? command : "cli";
183
- setCaller({ mode, command: mode === "cli" ? (command ?? null) : null });
202
+ setCaller({ mode, command: mode === "cli" ? (argv[0] ?? null) : null });
184
203
  const home = stationHome();
185
204
  ensureHome(home);
186
205
  const out = (line) => console.log(line);
@@ -230,9 +249,9 @@ async function main(argv) {
230
249
  const signedAs = saved;
231
250
  if (asAgent && signedAs && !signedAs.agent && !signedAs.secret)
232
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.`);
233
- const login = await startLogin(home, relayUrl, webUrl, signUp, undefined, remote, [], undefined, asAgent?.trim() ?? null);
252
+ const login = await startLogin(home, relayUrl, webUrl, signUp, undefined, remote, [], asAgent?.trim() ?? null);
234
253
  const { url } = login;
235
- if (!remote && flag("no-browser") !== "true")
254
+ if (!remote && process.stdout.isTTY && flag("no-browser") !== "true")
236
255
  openBrowser(url);
237
256
  out(`${signUp ? "Sign up for Station" : "Sign in to Station"}, then click Approve:\n${url}`);
238
257
  // A terminal waits and says who signed in; an agent's shell moves on.
@@ -275,7 +294,11 @@ async function main(argv) {
275
294
  await call(credentials.relayUrl, "/me/cli-token", { token: credentials.token }, { method: "DELETE" }).catch(() => { });
276
295
  remove(files(home).credentials);
277
296
  cancelLogin(home);
297
+ // Signed out, room messages stop reaching Claude Code through its hooks too.
298
+ const hooks = removeHooks();
278
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}.`);
279
302
  return 0;
280
303
  }
281
304
  case "whoami": {
@@ -338,14 +361,14 @@ async function main(argv) {
338
361
  out(line);
339
362
  if (opened.note)
340
363
  out(opened.note);
341
- 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}`);
342
365
  return 0;
343
366
  }
344
367
  const credentials = signedIn(home);
345
368
  const opened = await openRoom(credentials, { title: title || null, isPublic: flag("public") === "true", team: flag("team") });
346
369
  for (const line of openedLines(opened))
347
370
  out(line);
348
- 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}`);
349
372
  return 0;
350
373
  }
351
374
  case "add": {
@@ -401,15 +424,35 @@ async function main(argv) {
401
424
  const held = seatFor(loadSeats(files(home).seats), session.id, parseRoomUrl(url, readCredentials(home)).roomId);
402
425
  if (held && session.harness !== "shell")
403
426
  out(`This session already has a seat in ${roomLabel(held)}, as ${held.name}; this join is the same seat. ${ANOTHER_AGENT}`);
404
- 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));
405
441
  // A signed-in seat can ask its person's agents by name, seated here or not.
406
442
  const mine = joined.seat.via === "cli" ? await myAgents(readCredentials(home)) : null;
407
- for (const line of joinedLines(me, joined, session.harness === "shell" ? session.why : null, { ask: askLine(askable(mine, joined.seat.agentId), me) }))
408
- out(line);
409
- for (const line of await ownerLines(home, joined.seat, joined.room, me))
410
- out(line);
411
- 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)
412
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
+ }
413
456
  return 0;
414
457
  }
415
458
  case "wait": {
@@ -469,7 +512,7 @@ async function main(argv) {
469
512
  }
470
513
  case "say": {
471
514
  const text = args.join(" ").trim();
472
- 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]`;
473
516
  if (!text)
474
517
  throw new Usage(usage);
475
518
  const reply = flag("reply") === undefined ? undefined : Number(flag("reply"));
@@ -489,7 +532,7 @@ async function main(argv) {
489
532
  return 0;
490
533
  }
491
534
  case "name": {
492
- const title = args.join(" ").trim();
535
+ const title = (flag("name") ?? args.join(" ")).trim();
493
536
  if (!title)
494
537
  throw new Usage(`${me} name "<a few words>"`);
495
538
  const seat = mySeat(home, inSession(), flag("room"));
@@ -497,19 +540,29 @@ async function main(argv) {
497
540
  out(`The room is now named ${named.title}.`);
498
541
  return 0;
499
542
  }
500
- // station file <path> [--name <name>] is the cp from before cp: one
501
- // file, to the top of the board. Like cp, it replaces a file already at
502
- // that path; before cp it took the next free name. Kept for the agents
503
- // whose instructions and installed CLIs still say station file.
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":
504
549
  case "cp":
505
550
  case "file": {
506
- const from = command === "file" ? args.slice(0, 1) : args.slice(0, -1);
507
- const to = command === "file" ? (flag("name") ?? "/") : args[args.length - 1];
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];
508
559
  if (!from.length)
509
- throw new Usage(command === "file" ? `${me} file <path>` : `${me} cp <file>... <to> (to: a board path for one file, or a folder ending with /)`);
560
+ throw new Usage(BOARD_CP(me));
510
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>".` : "";
511
564
  if (missing)
512
- throw new Usage(`The file does not exist: ${missing}. Check the path, then run ${me} ${command} again.`);
565
+ throw new Usage(`The file does not exist: ${missing}. Check the path, then run ${me} board cp again.${write}`);
513
566
  const seat = mySeat(home, inSession(), flag("room"));
514
567
  const ifRev = flag("if-rev");
515
568
  // One upload link per file (the relay's board.cp), then each file's bytes to its link.
@@ -523,26 +576,33 @@ async function main(argv) {
523
576
  return 0;
524
577
  }
525
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`);
526
592
  const seat = mySeat(home, inSession(), flag("room"));
527
593
  const auth = authFor(seat, readCredentials(home));
528
- const answered = flag("answered");
529
594
  if (answered !== undefined) {
530
- // They answered in this session: close the newest waiting card.
531
- if (answered !== "approved" && answered !== "declined")
532
- throw new Usage(`${me} ask --answered approved|declined`);
533
595
  const room = await call(seat.relayUrl, `/${seat.roomId}`, auth);
534
596
  const card = room.messages
535
- .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))
536
598
  .sort((a, b) => b.id - a.id)[0];
537
599
  if (!card)
538
- throw new Usage("This seat has no card waiting.");
539
- await call(seat.relayUrl, `/${seat.roomId}/approvals/${card.id}`, auth, {
540
- body: { decision: answered === "approved" ? "approve" : "decline" },
541
- });
542
- 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.`);
543
603
  return 0;
544
604
  }
545
- const request = args.join(" ").trim();
605
+ const request = (flag("request") ?? args.join(" ")).trim();
546
606
  if (!request)
547
607
  throw new Usage(`${me} ask "<what you would do>" [--command "<exact command>"] [--for "<who asked>"]`);
548
608
  const { message, page } = await call(seat.relayUrl, `/${seat.roomId}/approvals`, auth, {
@@ -565,16 +625,20 @@ async function main(argv) {
565
625
  case "admit": {
566
626
  // Someone asked to join; the room told this session (frame.ts,
567
627
  // askedFrame). Only on the word of the person the agent works for.
568
- const [request] = args;
628
+ const request = flag("request") ?? args[0];
569
629
  if (!request)
570
630
  throw new Usage(`${me} admit <request> [--no]`);
571
631
  const seat = mySeat(home, inSession(), flag("room"));
572
632
  if (seat.via !== "cli")
573
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.");
574
- 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";
575
636
  // room_admit, as the person, the same as an agent through station mcp.
576
637
  const answered = await useTool(signedIn(home), "room_admit", { room: seat.roomId, request, approve });
577
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}` : ""));
578
642
  return 0;
579
643
  }
580
644
  case "claim": {
@@ -590,11 +654,11 @@ async function main(argv) {
590
654
  return 0;
591
655
  }
592
656
  case "tool":
593
- return toolCommand({ home, args: rawArgs, out, me });
657
+ return toolCommand({ home, args: rawArgs, out, me, signedIn: Boolean(readCredentials(home)) });
594
658
  case "status": {
595
- const [status, ...words] = args;
659
+ const [status, ...words] = flag("status") === undefined ? args : [flag("status"), ...args];
596
660
  if (!["working", "thinking", "here"].includes(status ?? ""))
597
- 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>"]`);
598
662
  // What on, in a few words: after the status, or as --doing. Agents type
599
663
  // `station status working "reading the cookie code"` unprompted, and
600
664
  // the words used to be dropped without a word.
@@ -629,11 +693,7 @@ async function main(argv) {
629
693
  case "leave": {
630
694
  const session = inSession();
631
695
  const seat = mySeat(home, session, flag("room"));
632
- await ensureDaemon(home);
633
- await call(seat.relayUrl, `/${seat.roomId}/presence`, authFor(seat, readCredentials(home)), { body: { leaving: true } });
634
- const dropped = await ask(files(home).socket, { op: "drop", sessionId: seat.sessionId, roomId: seat.roomId });
635
- if (!dropped.ok)
636
- throw new Error(dropped.error);
696
+ await leaveSeat(home, seat);
637
697
  out(`Left ${roomLabel(seat)}.`);
638
698
  return 0;
639
699
  }
@@ -719,8 +779,10 @@ async function main(argv) {
719
779
  // A command Station defines: its tool list says which tools are
720
780
  // commands, and with which flags (commands.ts).
721
781
  let seat = null;
782
+ let session = null;
722
783
  try {
723
- seat = seatFor(loadSeats(files(home).seats), inSession().id);
784
+ session = inSession();
785
+ seat = seatFor(loadSeats(files(home).seats), session.id);
724
786
  }
725
787
  catch {
726
788
  // Not an agent's session: the call goes as the person.
@@ -731,15 +793,19 @@ async function main(argv) {
731
793
  if (!found) {
732
794
  // `station board`: the commands of that group, and nothing done.
733
795
  const group = groupOf(tools, command);
734
- if (!group.length) {
735
- // The names only: the whole help is over 5 KB, and an agent asked for none of it.
736
- const groups = [...new Set(tools.flatMap((tool) => cliOf(tool)?.command.split(" ")[0] ?? []))];
737
- throw new Usage(`Unknown command: ${command}. The commands: ${[...VISIBLE, ...groups].join(", ")}. ${me} help says what each does.`);
738
- }
739
- 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");
740
803
  const asked = rawArgs.filter((word) => word !== "--help" && word !== "help");
741
- if (asked.length)
742
- 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
+ }
743
809
  out(lines);
744
810
  return 0;
745
811
  }
@@ -750,9 +816,9 @@ async function main(argv) {
750
816
  }
751
817
  const inputs = await inputsFrom(me, tool, rest);
752
818
  // With no --room, the room this session has a seat in.
753
- 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"))) {
754
820
  if (!seat)
755
- 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) : ""}`);
756
822
  inputs.room = `${seat.relayUrl}/${seat.roomId}`;
757
823
  }
758
824
  const result = await station.call(tool.name, inputs);
package/dist/codex.js CHANGED
@@ -137,8 +137,9 @@ function firstLine(path) {
137
137
  * that folder is there. */
138
138
  export function threadFolder(home, thread) {
139
139
  const rollout = rolloutPath(home, thread);
140
- if (!rollout)
141
- return null;
140
+ return rollout ? rolloutFolder(rollout) : null;
141
+ }
142
+ function rolloutFolder(rollout) {
142
143
  try {
143
144
  const cwd = JSON.parse(firstLine(rollout)).payload?.cwd;
144
145
  return typeof cwd === "string" && existsSync(cwd) ? cwd : null;
@@ -147,6 +148,27 @@ export function threadFolder(home, thread) {
147
148
  return null;
148
149
  }
149
150
  }
151
+ /** The folder Codex worked in last on this computer: the thread written to
152
+ * last (a resumed older chat writes to its old rollout), while its folder
153
+ * is there. Null when Codex has no thread here. */
154
+ export function lastFolder(home) {
155
+ const written = (path) => {
156
+ try {
157
+ return statSync(path).mtimeMs;
158
+ }
159
+ catch {
160
+ return 0;
161
+ }
162
+ };
163
+ const newest = [...rollouts(home)].map((path) => ({ path, at: written(path) })).sort((a, b) => b.at - a.at);
164
+ // Past these, a person with many deleted folders gets none.
165
+ for (const { path } of newest.slice(0, 50)) {
166
+ const cwd = rolloutFolder(path);
167
+ if (cwd)
168
+ return cwd;
169
+ }
170
+ return null;
171
+ }
150
172
  /** The Codex thread this process runs inside: `CODEX_THREAD_ID`, vouched for
151
173
  * by the nearest `codex` above it holding the thread's lock. */
152
174
  export function callingThread(home, env = process.env, from = process.ppid, ps = systemPs, holders = systemHolders) {
@@ -156,19 +178,31 @@ export function callingThread(home, env = process.env, from = process.ppid, ps =
156
178
  let pid = from;
157
179
  for (let hops = 0; hops < 64 && pid > 1; hops++) {
158
180
  const executable = ps(pid, "comm");
159
- // Codex's own sandbox hides the processes above a command it runs (ps
160
- // and lsof are refused there). The thread is then vouched for by its own
161
- // files instead: its rollout, and its writer lock while it is loaded.
162
181
  if (!executable)
163
- return env.CODEX_SANDBOX ? sandboxedThread(home, thread, env) : null;
182
+ break;
164
183
  if (basename(executable) === "codex")
165
184
  return describe(home, thread, pid, ps, holders);
166
185
  const parent = Number(ps(pid, "ppid"));
167
186
  if (!Number.isInteger(parent) || parent <= 1 || parent === pid)
168
- return null;
187
+ break;
169
188
  pid = parent;
170
189
  }
171
- return null;
190
+ // Codex's own sandbox hides the Codex above a command it runs: on macOS
191
+ // ps and lsof are refused, and on Linux the command runs in a process
192
+ // namespace of its own, whose first process is the sandbox's and not the
193
+ // thread's Codex. The thread is then vouched for by its own files: its
194
+ // rollout, and its writer lock while it is loaded.
195
+ return inCodexSandbox(env, ps) ? sandboxedThread(home, thread, env) : null;
196
+ }
197
+ /** Whether this process runs in Codex's sandbox. Codex sets CODEX_SANDBOX
198
+ * on macOS, and CODEX_SANDBOX_NETWORK_DISABLED wherever the sandbox has no
199
+ * network (Linux sets only this one). A Linux sandbox with network sets
200
+ * neither, but its first process is Codex's. */
201
+ function inCodexSandbox(env = process.env, ps = systemPs) {
202
+ if (env.CODEX_SANDBOX || env.CODEX_SANDBOX_NETWORK_DISABLED)
203
+ return true;
204
+ const first = ps(1, "comm");
205
+ return !!first && basename(first) === "codex";
172
206
  }
173
207
  /** Why `callingThread` found nothing, step by step, for a process Codex
174
208
  * started (it has `CODEX_THREAD_ID`); null when it is not one. */
@@ -217,18 +251,27 @@ export function liveThread(home, thread, ps = systemPs, holders = systemHolders)
217
251
  * newest day first. Codex compresses older rollouts in place to
218
252
  * `.jsonl.zst`; the plain file wins when both are there. */
219
253
  export function rolloutPath(home, thread) {
254
+ for (const names of rolloutDays(home)) {
255
+ const found = names.find((file) => file.endsWith(`-${thread}.jsonl`)) ?? names.find((file) => file.endsWith(`-${thread}.jsonl.zst`));
256
+ if (found)
257
+ return found;
258
+ }
259
+ return null;
260
+ }
261
+ /** Each day's rollouts, newest day first and newest first within it. */
262
+ function* rolloutDays(home) {
220
263
  const root = join(home, "sessions");
221
264
  const down = (dir) => (existsSync(dir) ? readdirSync(dir).sort().reverse() : []);
222
265
  for (const year of down(root))
223
266
  for (const month of down(join(root, year)))
224
267
  for (const day of down(join(root, year, month))) {
225
268
  const dir = join(root, year, month, day);
226
- const names = down(dir).filter((file) => file.startsWith("rollout-"));
227
- const name = names.find((file) => file.endsWith(`-${thread}.jsonl`)) ?? names.find((file) => file.endsWith(`-${thread}.jsonl.zst`));
228
- if (name)
229
- return join(dir, name);
269
+ yield down(dir).filter((file) => file.startsWith("rollout-")).map((file) => join(dir, file));
230
270
  }
231
- return null;
271
+ }
272
+ function* rollouts(home) {
273
+ for (const names of rolloutDays(home))
274
+ yield* names;
232
275
  }
233
276
  const TAIL_BYTES = 4 * 1024 * 1024;
234
277
  /** Whether the rollout's last turn is still open: a `task_started` with no