@santori/station 0.9.6 → 0.9.8

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/login.js CHANGED
@@ -32,7 +32,7 @@ import { hostname } from "node:os";
32
32
  import { DEFAULT_WEB, files, readCredentials, readJson, remove, writeJson } from "./home.js";
33
33
  import { callingAgentName } from "./caller.js";
34
34
  import { carryGuest } from "./guest.js";
35
- import { call } from "./relay.js";
35
+ import { call, siteOf } from "./relay.js";
36
36
  /** How long the helper listens for the website's answer. */
37
37
  export const LISTEN_MS = 10 * 60_000;
38
38
  /** A person on another computer brings the code back by hand, often long
@@ -238,8 +238,10 @@ export async function claimSeat(relayUrl, claim, token) {
238
238
  return false;
239
239
  }
240
240
  }
241
- /** Starts a sign-in: the helper listens, and this returns its link. */
241
+ /** Starts a sign-in: the helper listens, and this returns its link. The
242
+ * link is on `webUrl` when one is given, else on the relay's own site. */
242
243
  export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnHelper, remote = false, claims = [], agent = callingAgentName()) {
244
+ const site = await siteOf(relayUrl, webUrl);
243
245
  // A newer login replaces one still listening.
244
246
  const before = readPending(home);
245
247
  if (before?.pid && before.pid !== process.pid && alive(before.pid))
@@ -249,7 +251,7 @@ export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnH
249
251
  claims = [...(before.claims ?? []).filter((one) => !claims.some((it) => it.key === one.key)), ...claims];
250
252
  const pending = {
251
253
  relayUrl,
252
- webUrl,
254
+ webUrl: site,
253
255
  verifier: newVerifier(),
254
256
  state: randomBytes(16).toString("base64url"),
255
257
  label: loginLabel(hostname(), remote),
@@ -324,11 +326,22 @@ export function codeIn(given) {
324
326
  * back from the website. The helper trades it, as if the browser had come. */
325
327
  export async function giveCode(home, given, command = "station") {
326
328
  const pending = readPending(home);
327
- if (!pending || pending.error || !pending.port || !alive(pending.pid))
329
+ if (!pending || pending.error || !pending.port || !alive(pending.pid)) {
330
+ // Often the browser reached this computer after all, and that code signed it in.
331
+ const saved = pending ? null : readCredentials(home);
332
+ if (saved)
333
+ throw new Error(`No sign-in is waiting for a code: this computer is already signed in as ${saved.name}. Nothing more to do.`);
328
334
  throw new Error(`No sign-in is waiting for a code here: its link ran out or a newer one replaced it. Run ${command} login again.`);
335
+ }
329
336
  const code = codeIn(given);
330
337
  if (!code)
331
338
  throw new Error("That is not a Station sign-in code. Give the code from the page, or the whole address the browser ended on.");
339
+ // An address carries its link's state. One from a link a newer login
340
+ // replaced cannot sign in: its secret is gone, so it is not sent at all.
341
+ const state = /[?&]state=([^&#\s]+)/.exec(given)?.[1];
342
+ if (state && decodeURIComponent(state) !== pending.state) {
343
+ throw new Error("That address is from an older sign-in link. A newer station login replaced it. Give the person the newest link, and after they click Connect, ask for the address it ends on.");
344
+ }
332
345
  const response = await fetch(`http://127.0.0.1:${pending.port}/callback?${new URLSearchParams({ code, state: pending.state })}`, {
333
346
  headers: { Accept: "application/json" },
334
347
  });
@@ -339,8 +352,8 @@ export async function giveCode(home, given, command = "station") {
339
352
  /** What the agent does with the code, while a login waits for it. */
340
353
  export function codeStep(command, remote) {
341
354
  return remote
342
- ? `After Connect the page shows them a code. Ask them to send it to you. It works for five minutes, so run this as soon as it arrives: ${command} login --code=<the code>`
343
- : `If their browser ends on a page at 127.0.0.1 that cannot be reached, their browser is on another computer. Ask them for that page's whole address. It works for five minutes, so run this as soon as it arrives: ${command} login --code='<that address>'`;
355
+ ? `After Connect, ask them for the code on the page. It works for five minutes; run this as soon as it arrives: ${command} login --code=<the code>`
356
+ : `If their browser cannot reach the final 127.0.0.1 page, it is on another computer. Ask for that page's whole address. It works for five minutes; run this as soon as it arrives: ${command} login --code='<that address>'`;
344
357
  }
345
358
  /** Whether the login under way is one where the person brings a code back. */
346
359
  export function waitingForCode(home) {
package/dist/mcp.js CHANGED
@@ -29,18 +29,21 @@
29
29
  // get, list, mutate), which this server asks for. The shell commands
30
30
  // (`station tool`, `station board ls`) get the tools one by one, each with
31
31
  // its own flags, by not asking.
32
+ import { randomUUID } from "node:crypto";
32
33
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
34
+ import { join } from "node:path";
33
35
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
34
36
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
35
37
  import { CallToolRequestSchema, LATEST_PROTOCOL_VERSION, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
38
+ import { agentSignIn } from "./agentToken.js";
36
39
  import { fetchAsCaller, setCaller } from "./caller.js";
37
40
  import { ask } from "./daemon.js";
38
41
  import { guestFor, readGuest } from "./guest.js";
39
- import { DEFAULT_RELAY, files, readCredentials } from "./home.js";
42
+ import { DEFAULT_RELAY, files, readCredentials, readJson, writeJson } from "./home.js";
40
43
  import { ensureDaemon, inSession, takeSeat } from "./join.js";
41
44
  import { finishLogin, readPending } from "./login.js";
42
45
  import { roomRef } from "./rooms.js";
43
- import { authFor, loadSeats, seatFor } from "./seats.js";
46
+ import { authFor, keepAgentSeat, loadSeats, seatFor } from "./seats.js";
44
47
  import { delivers, workerName } from "./sessions.js";
45
48
  import { VERSION, selfCommand } from "./self.js";
46
49
  /** What the agent is told when Station gave no rules of its own: it could
@@ -64,6 +67,15 @@ export const postToAgent = async (relayUrl, headers, method, params) => {
64
67
  * this computer, and that it gives a worker named with `as` its own seat
65
68
  * (the relay offers `as` only then; 0.7.0 and before ignored it). */
66
69
  const ours = (folded = false) => ({ "X-Station-Command": selfCommand(), "X-Station-Workers": "1", ...(folded ? { "X-Station-Tools": "2" } : {}) });
70
+ /** How far each of the person's agents on this computer read what it follows (a wait with no room). */
71
+ const watchFile = (home) => join(home, "watch.json");
72
+ export function watchAfter(home, agent) {
73
+ const value = readJson(watchFile(home), {})[agent];
74
+ return typeof value === "number" ? value : null;
75
+ }
76
+ export function saveWatchAfter(home, agent, after) {
77
+ writeJson(watchFile(home), { ...readJson(watchFile(home), {}), [agent]: after });
78
+ }
67
79
  function failed(error) {
68
80
  return { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true };
69
81
  }
@@ -83,9 +95,12 @@ async function settled(home) {
83
95
  return readPending(home) ? null : readCredentials(home);
84
96
  }
85
97
  export const thisComputer = {
86
- session: inSession,
98
+ session: (worker, thread) => inSession(worker, thread ? { ...process.env, CODEX_THREAD_ID: thread } : process.env),
87
99
  takeSeat: async (home, session, url, name) => (await takeSeat(home, session, url, { client: "station-mcp", name: name ?? undefined })).seat,
88
100
  read: async (home, seat, after) => {
101
+ // A seat of an agent's own sign-in keeps its own place.
102
+ if (seat.own)
103
+ return keepAgentSeat(files(home).seats, { ...seat, after: Math.max(seat.after, after) });
89
104
  await ensureDaemon(home);
90
105
  await ask(files(home).socket, { op: "read", sessionId: seat.sessionId, roomId: seat.roomId, after });
91
106
  },
@@ -124,6 +139,14 @@ export async function instructionsFrom(home, post = postToAgent) {
124
139
  return null;
125
140
  }
126
141
  }
142
+ /** The Codex thread a call comes from. One Codex runs many threads over one
143
+ * Station server, so the server has no CODEX_THREAD_ID of its own; Codex
144
+ * names the calling thread in each call's _meta instead. */
145
+ export function callerThread(meta) {
146
+ const turn = meta?.["x-codex-turn-metadata"];
147
+ const thread = meta?.threadId ?? turn?.thread_id;
148
+ return typeof thread === "string" ? thread : null;
149
+ }
127
150
  export function stationTools(home, post = postToAgent, computer = thisComputer, folded = false) {
128
151
  let known = new Map();
129
152
  const kept = folded ? files(home).mcpTools : files(home).tools;
@@ -142,8 +165,11 @@ export function stationTools(home, post = postToAgent, computer = thisComputer,
142
165
  known = new Map(tools.map((tool) => [tool.name, tool]));
143
166
  return tools;
144
167
  };
145
- const call = async (name, args) => {
168
+ const call = async (name, given, sent) => {
169
+ let args = given;
146
170
  try {
171
+ // An hour's agent sign-in, bought again from the install's secret when it runs out.
172
+ await agentSignIn();
147
173
  if (!known.has(name))
148
174
  await list();
149
175
  const credentials = await settled(home);
@@ -162,25 +188,40 @@ export function stationTools(home, post = postToAgent, computer = thisComputer,
162
188
  const worker = workerName(args.as) ?? workerName(process.env.STATION_SESSION);
163
189
  let caller = null;
164
190
  try {
165
- caller = computer.session(worker);
191
+ caller = computer.session(worker, callerThread(sent));
166
192
  }
167
193
  catch {
168
194
  // Not a session that can hold a seat: the call goes as the person.
169
195
  }
170
196
  let seat = roomId && caller ? seatFor(loadSeats(files(home).seats), caller.id, roomId) : null;
171
197
  let joined = false;
172
- if (!seat && roomId && known.get(name)?._meta?.["station/seat"] === "take") {
198
+ // A tool that acts as the session's seat takes one first; so does an action of mutate that does (ask.take).
199
+ const meta = known.get(name)?._meta;
200
+ const seatActions = meta?.["station/seat-for"];
201
+ if (!seat && roomId && (meta?.["station/seat"] === "take" || (Array.isArray(seatActions) && seatActions.includes(args.action)))) {
173
202
  // Says why when this is not an agent's session that can hold a seat.
174
203
  // The seat's name, when the call gives one (room_wait's `name`), as station join --name.
175
204
  const name = typeof args.name === "string" && args.name.trim() ? args.name.trim() : null;
176
205
  const invite = inviteToken ? `?${new URLSearchParams({ invite_token: inviteToken })}` : "";
177
- seat = await computer.takeSeat(home, caller ?? computer.session(worker), `${relayUrl}/${roomId}${invite}`, name);
206
+ seat = await computer.takeSeat(home, caller ?? computer.session(worker, callerThread(sent)), `${relayUrl}/${roomId}${invite}`, name);
178
207
  joined = true;
179
208
  }
180
209
  if (!seat && roomId && caller) {
181
210
  seat = loadSeats(files(home).seats).find((s) => s.left && s.sessionId === caller.id && s.roomId === roomId && s.relayUrl === relayUrl) ?? null;
182
211
  }
183
212
  const headers = ours(folded);
213
+ // Which of the person's agents this session is: what a wait with no room follows.
214
+ const kind = caller ? (caller.harness === "shell" ? caller.host : caller.harness) : undefined;
215
+ if (kind)
216
+ headers["X-Station-Agent"] = kind;
217
+ // A wait with no room follows every room of the person: how far this agent read.
218
+ const watching = (name === "wait" || name === "room_watch") && roomId === null && !seat;
219
+ const watchedTo = watching ? watchAfter(home, kind ?? "agent") : null;
220
+ if (watchedTo !== null)
221
+ headers["X-Station-After"] = String(watchedTo);
222
+ // A post is made once, however often a lost answer makes this call again.
223
+ if ((name === "send" || name === "room_say") && typeof args.client_id !== "string")
224
+ args = { ...args, client_id: randomUUID() };
184
225
  if (seat) {
185
226
  const auth = authFor(seat, credentials);
186
227
  relayUrl = seat.relayUrl;
@@ -201,13 +242,21 @@ export function stationTools(home, post = postToAgent, computer = thisComputer,
201
242
  const guest = unsigned ? readGuest(home, relayUrl) : null;
202
243
  if (guest)
203
244
  headers.Authorization = `Bearer ${guest.token}`;
204
- let result = (await post(relayUrl, headers, "tools/call", { name, arguments: args }));
245
+ const send = () => post(relayUrl, headers, "tools/call", { name, arguments: args });
246
+ // Once more on a lost answer: a post carries its client_id, so it is not written twice.
247
+ let result = await send().catch((error) => {
248
+ if (!(error instanceof TypeError || (error instanceof Error && /fetch failed|aborted|socket|ECONNRESET/i.test(error.message))))
249
+ throw error;
250
+ return send();
251
+ });
205
252
  // Station says the call needs that identity (opening a room): get one and call again.
206
253
  if (unsigned && !guest && result._meta?.["station/identity"] === "guest") {
207
254
  headers.Authorization = `Bearer ${await computer.guest(home, relayUrl)}`;
208
255
  result = (await post(relayUrl, headers, "tools/call", { name, arguments: args }));
209
256
  }
210
257
  const after = result._meta?.["station/after"];
258
+ if (watching && typeof after === "number")
259
+ saveWatchAfter(home, kind ?? "agent", after);
211
260
  if (seat && !seat.left && typeof after === "number" && after > seat.after) {
212
261
  // The seat's place moves, so the next read starts after these.
213
262
  await computer.read(home, seat, after).catch(() => undefined);
@@ -230,9 +279,11 @@ export function createStationServer(home, post = postToAgent, instructions = nul
230
279
  server.oninitialized = () => setCaller({ host: server.getClientVersion()?.name ?? null });
231
280
  const tools = stationTools(home, post, computer, true);
232
281
  server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: await tools.list() }));
233
- server.setRequestHandler(CallToolRequestSchema, async (request) => tools.call(request.params.name, request.params.arguments ?? {}));
282
+ server.setRequestHandler(CallToolRequestSchema, async (request) => tools.call(request.params.name, request.params.arguments ?? {}, request.params._meta));
234
283
  return server;
235
284
  }
236
285
  export async function serveMcp(home) {
286
+ // A started agent's sign-in is in a file: read it before anything asks the relay.
287
+ await agentSignIn();
237
288
  await createStationServer(home, postToAgent, await instructionsFrom(home)).connect(new StdioServerTransport());
238
289
  }
package/dist/proxy.js CHANGED
@@ -12,6 +12,11 @@ export function wantsProxy(env = process.env, node = process.versions.node) {
12
12
  const [major, minor] = node.split(".").map(Number);
13
13
  return major >= 24 || (major === 22 && minor >= 21);
14
14
  }
15
+ /** Whether a proxy is set that this process's fetch does not use: Node
16
+ * before 22.21, or a start again that could not happen (Windows). */
17
+ export function proxyIgnored(env = process.env) {
18
+ return !env.NODE_USE_ENV_PROXY && PROXY_VARS.some((name) => env[name]?.trim());
19
+ }
15
20
  /** Starts this CLI again in place with NODE_USE_ENV_PROXY=1, when a proxy is
16
21
  * set and Node can do that (not on Windows); otherwise does nothing. */
17
22
  export function useEnvProxy() {
package/dist/relay.js CHANGED
@@ -3,13 +3,24 @@
3
3
  // pasted room, or this computer's sign-in.
4
4
  import { fetchAsCaller } from "./caller.js";
5
5
  import { DEFAULT_RELAY, DEFAULT_WEB } from "./home.js";
6
+ import { proxyIgnored } from "./proxy.js";
6
7
  export class RelayError extends Error {
7
8
  status;
8
- constructor(status, message) {
9
+ code;
10
+ constructor(status, message,
11
+ /** The relay's name for the case, on refusals it names (its `code`). */
12
+ code = null) {
9
13
  super(message);
10
14
  this.status = status;
15
+ this.code = code;
11
16
  }
12
17
  }
18
+ /** The relay says the seat is over: gone (404, 410), its sign-in refused
19
+ * (401), or its agent cut off by its person (code cut_off). The daemon
20
+ * stops using it. */
21
+ export function seatOver(error) {
22
+ return error instanceof RelayError && (error.status === 404 || error.status === 410 || error.status === 401 || error.code === "cut_off");
23
+ }
13
24
  export async function call(base, path, auth, init = {}) {
14
25
  const headers = { ...(init.headers ?? {}) };
15
26
  if (auth)
@@ -28,22 +39,55 @@ export async function call(base, path, auth, init = {}) {
28
39
  response = await fetchAsCaller(`${base}${path}`, { method: init.method ?? (body ? "POST" : "GET"), headers, body });
29
40
  }
30
41
  catch (error) {
31
- throw new RelayError(0, `Could not reach ${base}: ${error instanceof Error ? error.message : String(error)}`);
42
+ const why = error instanceof Error ? error.message : String(error);
43
+ // Node 20 has no way to use a proxy from the environment.
44
+ const next = proxyIgnored()
45
+ ? `A proxy is set (HTTPS_PROXY), and Node ${process.versions.node} does not send requests through it. Node 22.21 or later does: run the CLI with that Node, or join with the curl steps the room link gives.`
46
+ : "Check the address and connection, then try again.";
47
+ throw new RelayError(0, `Could not reach ${base}: ${why}. ${next}`);
32
48
  }
33
49
  if (!response.ok) {
34
50
  let detail = response.statusText;
51
+ let code = null;
35
52
  try {
36
53
  const payload = (await response.json());
37
54
  if (payload.error)
38
55
  detail = payload.error;
56
+ if (typeof payload.code === "string")
57
+ code = payload.code;
39
58
  }
40
59
  catch {
41
60
  // not JSON
42
61
  }
43
- throw new RelayError(response.status, detail);
62
+ throw new RelayError(response.status, detail, code);
44
63
  }
45
64
  return (response.status === 204 ? undefined : await response.json());
46
65
  }
66
+ /** The website that goes with a relay: the one given (--web,
67
+ * STATION_WEB_URL), else the one the relay names as its own, so a link
68
+ * never puts one relay's sign-in on another Station's site. A relay from
69
+ * before it named its site (404) is Station's own. */
70
+ export async function siteOf(relayUrl, given = null) {
71
+ if (given)
72
+ return given.replace(/\/$/, "");
73
+ let site;
74
+ try {
75
+ site = (await call(relayUrl, "/.well-known/mcp.json", null)).site;
76
+ }
77
+ catch (error) {
78
+ if (error instanceof RelayError && error.status === 404)
79
+ return DEFAULT_WEB;
80
+ throw error;
81
+ }
82
+ if (site === undefined)
83
+ return DEFAULT_WEB;
84
+ // Only a plain address: the link goes to a browser, through cmd on Windows.
85
+ if (!SITE.test(site))
86
+ throw new Error(`The relay at ${relayUrl} names a website Station cannot use. Give one with --web.`);
87
+ return site.replace(/\/$/, "");
88
+ }
89
+ /** An http(s) origin and nothing else: no path, query or shell characters. */
90
+ const SITE = /^https?:\/\/([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:\d{1,5})?\/?$/;
47
91
  /** A relay room URL, or a room page on Station's website. */
48
92
  export function parseRoomUrl(url, credentials = null) {
49
93
  // The paste is a sentence ("Come join my Station room. To get started, run
@@ -55,7 +99,7 @@ export function parseRoomUrl(url, credentials = null) {
55
99
  parsed = new URL(trimmed);
56
100
  }
57
101
  catch {
58
- throw new Error(`Not a room URL: ${url}`);
102
+ throw new Error(`Not a room URL: ${url}. Copy the room's link and try again.`);
59
103
  }
60
104
  const webRelay = parsed.origin === new URL(credentials?.webUrl ?? DEFAULT_WEB).origin
61
105
  ? credentials?.relayUrl ?? DEFAULT_RELAY
@@ -63,7 +107,7 @@ export function parseRoomUrl(url, credentials = null) {
63
107
  const page = webRelay ? parsed.pathname.match(/^\/b\/([0-9a-f-]{36})(?:\/.*)?$/i) : null;
64
108
  const roomId = page?.[1] ?? parsed.pathname.replace(/^\/+|\/+$/g, "");
65
109
  if (!/^[0-9a-f-]{36}$/i.test(roomId))
66
- throw new Error(`Not a room URL: ${url}`);
110
+ throw new Error(`Not a room URL: ${url}. Copy the room's link and try again.`);
67
111
  // The room's invite token, when the link carries it (?invite_token=).
68
112
  return { relayUrl: page && webRelay ? webRelay : parsed.origin, roomId, inviteToken: parsed.searchParams.get("invite_token") || null };
69
113
  }
package/dist/rooms.js CHANGED
@@ -5,18 +5,19 @@
5
5
  // never disagree.
6
6
  import { DEFAULT_RELAY, DEFAULT_WEB, readCredentials } from "./home.js";
7
7
  import { codeStep, waitingAt, waitingForCode } from "./login.js";
8
+ import { agentCommand } from "./self.js";
8
9
  import { call, parseRoomUrl } from "./relay.js";
9
10
  import { connectTo, useTool } from "./station.js";
10
11
  import { NOT_SIGNED_IN, Usage } from "./usage.js";
11
12
  /** This computer's sign-in, or the error every signed-in action gives. */
12
- export function signedIn(home) {
13
+ export function signedIn(home, me = agentCommand()) {
13
14
  const credentials = readCredentials(home);
14
15
  // A login under way may be switching accounts: no acting as the old one meanwhile.
15
16
  const url = waitingAt(home);
16
17
  if (url && waitingForCode(home))
17
- throw new Usage(`Not signed in yet: the person has not finished at ${url}. ${codeStep("station", true)}`);
18
+ throw new Usage(`Not signed in yet: the person has not finished at ${url}. ${codeStep(me, true)}`);
18
19
  if (url)
19
- throw new Usage(`Not signed in yet: the person has not finished at ${url}. Run this again once they have clicked Connect. ${codeStep("station", false)}`);
20
+ throw new Usage(`Not signed in yet: the person has not finished at ${url}. Run this again once they have clicked Connect. ${codeStep(me, false)}`);
20
21
  if (!credentials)
21
22
  throw new Usage(NOT_SIGNED_IN);
22
23
  return credentials;
@@ -67,7 +68,7 @@ export function roomPage(credentials, roomId) {
67
68
  export function openedLines(opened) {
68
69
  const lines = [`Opened a ${opened.is_public ? "public" : "private"} room: ${opened.url}`, `Its page: ${opened.page}`, `Paste for an agent: ${opened.paste}`];
69
70
  if (!opened.is_public)
70
- lines.push("An agent that isn't signed in to Station as you asks to join with that line; let it in from the room's page.");
71
+ lines.push("Agents not signed in to Station as you ask to join with that line; let them in from the room's page.");
71
72
  return lines;
72
73
  }
73
74
  /** A room named by its URL or its id. An id alone is on this computer's
@@ -80,7 +81,7 @@ export function roomRef(credentials, room) {
80
81
  }
81
82
  const id = trimmed.replace(/^[<("'`]+|[>)"'`.,;:!?]+$/g, "");
82
83
  if (!/^[0-9a-f-]{36}$/i.test(id))
83
- throw new Usage(`Not a room URL or id: ${room}`);
84
+ throw new Usage(`Not a room URL or id: ${room}. Use the room's URL or its id from ${agentCommand()} rooms --json.`);
84
85
  return { relayUrl: credentials?.relayUrl ?? DEFAULT_RELAY, roomId: id };
85
86
  }
86
87
  export async function readRoom(relayUrl, roomId, auth) {
package/dist/seats.js CHANGED
@@ -1,9 +1,21 @@
1
1
  // A seat: one agent session (Claude Code, Codex, or any agent's shell) in one room. The daemon keeps the list in
2
2
  // ~/.station/seats.json and is its only writer; commands read it to find
3
3
  // the calling session's seat.
4
- import { readJson } from "./home.js";
4
+ import { readJson, writeJson } from "./home.js";
5
+ import { Usage } from "./usage.js";
5
6
  export function loadSeats(path) {
6
- return readJson(path, []).map((seat) => ({ ...seat, harness: seat.harness ?? "claude-code" }));
7
+ // Seats an agent's own sign-in took are kept beside the daemon's (agentSeatsFile): no daemon holds them.
8
+ const own = readJson(agentSeatsFile(path), []);
9
+ return [...readJson(path, []), ...own].map((seat) => ({ ...seat, harness: seat.harness ?? "claude-code" }));
10
+ }
11
+ /** Where a session signed in as an agent itself (STATION_AGENT_TOKEN) keeps
12
+ * its seats. The daemon acts with the computer's sign-in only, so it does
13
+ * not hold them; the agent reads its rooms with wait. */
14
+ export const agentSeatsFile = (seatsPath) => seatsPath.replace(/seats\.json$/, "agent-seats.json");
15
+ export function keepAgentSeat(seatsPath, seat) {
16
+ const path = agentSeatsFile(seatsPath);
17
+ const kept = readJson(path, []).filter((one) => !(one.sessionId === seat.sessionId && one.roomId === seat.roomId));
18
+ writeJson(path, [...kept, { ...seat, own: true }]);
7
19
  }
8
20
  export function authFor(seat, credentials) {
9
21
  const token = seat.via === "room" ? seat.roomToken : credentials?.token;
@@ -15,8 +27,16 @@ export function authFor(seat, credentials) {
15
27
  * an id, or the start of one), else the one it joined last. */
16
28
  export function seatFor(seats, sessionId, room) {
17
29
  const mine = seats.filter((seat) => seat.sessionId === sessionId && !seat.left);
18
- if (room)
19
- return mine.find((seat) => room.includes(seat.roomId) || seat.roomId.startsWith(room)) ?? null;
30
+ if (room) {
31
+ const byId = mine.find((seat) => room.includes(seat.roomId) || seat.roomId.startsWith(room));
32
+ if (byId)
33
+ return byId;
34
+ // A room's name: only when one room of the session's has it.
35
+ const named = mine.filter((seat) => seat.roomTitle?.trim().toLowerCase() === room.trim().toLowerCase());
36
+ if (named.length > 1)
37
+ throw new Usage(`More than one of your rooms is called "${room}": ${named.map((seat) => `${seat.roomId} (${seat.relayUrl}/${seat.roomId})`).join(" and ")}. Say which with --room and its id.`);
38
+ return named[0] ?? null;
39
+ }
20
40
  return mine.sort((a, b) => b.joinedAt.localeCompare(a.joinedAt))[0] ?? null;
21
41
  }
22
42
  /** The seat with its owner learned from the room, when it did not know
package/dist/self.js CHANGED
@@ -3,11 +3,51 @@
3
3
  // agent's PATH, so the hints Station prints must say
4
4
  // `npx -y @santori/station@latest`. Without @latest, npx reuses whatever
5
5
  // copy it cached first and never picks up a new release.
6
- import { readFileSync } from "node:fs";
6
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
7
+ import { basename, delimiter, join } from "node:path";
7
8
  export const PACKAGE = "@santori/station";
8
9
  export function selfCommand(script = process.argv[1] ?? "") {
9
10
  return script.includes("/_npx/") ? `npx -y ${PACKAGE}@latest` : "station";
10
11
  }
12
+ /** How another agent's app starts this same CLI's `station mcp`: the npx
13
+ * line through npx, an installed `station` by its path, and a build run
14
+ * with node (a checkout) with that node. */
15
+ export function mcpCommand(script = process.argv[1] ?? "", node = process.execPath, path = process.env.PATH ?? "") {
16
+ if (script.includes("/_npx/"))
17
+ return ["npx", "-y", `${PACKAGE}@latest`, "mcp"];
18
+ if (basename(script) === "station")
19
+ return [script, "mcp"];
20
+ // A `station` on PATH that is this same script outlives a node upgrade.
21
+ const real = (file) => {
22
+ try {
23
+ return realpathSync(file);
24
+ }
25
+ catch {
26
+ return null;
27
+ }
28
+ };
29
+ const bin = path.split(delimiter).filter(Boolean).map((dir) => join(dir, "station")).find((file) => real(file) !== null && real(file) === real(script));
30
+ return bin ? [bin, "mcp"] : [node, script, "mcp"];
31
+ }
32
+ /** A program on PATH, by its full path; null when it is not there. */
33
+ export function onPath(program, env = process.env) {
34
+ for (const dir of (env.PATH ?? "").split(delimiter).filter(Boolean)) {
35
+ const file = join(dir, program);
36
+ if (existsSync(file))
37
+ return file;
38
+ }
39
+ return null;
40
+ }
41
+ /** The command a seat types to run Station again as itself. A worker named
42
+ * with STATION_SESSION keeps the name in front: without it the command acts
43
+ * for another seat, or for none. */
44
+ export function agentCommand(script = process.argv[1] ?? "", env = process.env) {
45
+ const name = env.STATION_SESSION?.trim().slice(0, 80);
46
+ if (!name)
47
+ return selfCommand(script);
48
+ const quoted = /^[A-Za-z0-9._@:+-]+$/.test(name) ? name : `'${name.replace(/'/g, `'\\''`)}'`;
49
+ return `STATION_SESSION=${quoted} ${selfCommand(script)}`;
50
+ }
11
51
  /** This CLI's version, from its package.json (npm always ships it). */
12
52
  export const VERSION = (() => {
13
53
  try {
package/dist/sessions.js CHANGED
@@ -15,7 +15,7 @@ export function workerName(given) {
15
15
  return typeof given === "string" && given.trim() ? given.trim().slice(0, 80) : null;
16
16
  }
17
17
  /** The session for an agent Station cannot put messages into. */
18
- export function shellSession(install, env = process.env, cwd = process.cwd(), why = null, within = null) {
18
+ export function shellSession(install, env = process.env, cwd = process.cwd(), why = null, within = null, host) {
19
19
  const named = workerName(env.STATION_SESSION);
20
20
  // Hashed: the join sends the session id to the room, which may be public,
21
21
  // and the folder's whole path is not the room's business. A worker in a
@@ -23,7 +23,18 @@ export function shellSession(install, env = process.env, cwd = process.cwd(), wh
23
23
  // two sessions' workers of one name are two seats.
24
24
  const key = named && within ? `${within}\n${named}` : named || cwd;
25
25
  const id = `shell-${createHash("sha256").update(`${install}\n${key}`).digest("hex").slice(0, 32)}`;
26
- return { harness: "shell", id, cwd, name: named, why };
26
+ return { harness: "shell", id, cwd, name: named, why, ...(host ? { host } : {}) };
27
+ }
28
+ export const isLocalKind = (kind) => kind === "claude-code" || kind === "codex";
29
+ /** A session Station started itself to answer an ask, with no window
30
+ * open: the daemon sets STATION_STARTED to "<kind>:<session id>" for it
31
+ * (starts.ts). It reads the room with Station's tools, like any agent's
32
+ * shell, and its seat is a session of its person's agent of that kind. */
33
+ export function startedSession(env = process.env, cwd = process.cwd()) {
34
+ const [kind, id] = (env.STATION_STARTED ?? "").split(/:(.*)/s);
35
+ if (!isLocalKind(kind) || !id)
36
+ return null;
37
+ return { harness: "shell", id, cwd, name: null, why: null, host: kind };
27
38
  }
28
39
  const fromClaude = (claude) => ({ harness: "claude-code", id: claude.sessionId, cwd: claude.cwd, name: claude.name, claude });
29
40
  const fromCodex = (codex, cwd) => ({ harness: "codex", id: codex.thread, cwd, name: null, codex });
@@ -71,10 +82,8 @@ export function agentProgram(from = process.ppid, ps = systemPs) {
71
82
  }
72
83
  /** Whether the session with this id is still running. */
73
84
  export function isRunning(harness, id) {
74
- // A shell's agent cannot be seen from here; the daemon goes by when it
75
- // last ran `station wait` instead.
76
85
  if (harness === "shell")
77
- return true;
86
+ return false;
78
87
  return harness === "codex" ? liveThread(codexHome(), id) !== null : sessionById(claudeHome(), id) !== null;
79
88
  }
80
89
  /** Puts `text` into the session as a new user message. */
package/dist/signup.js CHANGED
@@ -10,7 +10,7 @@ import { hostname } from "node:os";
10
10
  import { readGuest } from "./guest.js";
11
11
  import { DEFAULT_WEB, files, readCredentials, remove, writeJson } from "./home.js";
12
12
  import { cancelLogin, claimSeat, elsewhere, loginLabel, readPending } from "./login.js";
13
- import { call } from "./relay.js";
13
+ import { call, siteOf } from "./relay.js";
14
14
  /** "November 26": the day the rooms lock, as the email says it. */
15
15
  export function lockDay(locksAt) {
16
16
  return new Date(locksAt).toLocaleDateString("en-US", { month: "long", day: "numeric", timeZone: "UTC" });
@@ -24,6 +24,8 @@ export async function signUp(home, relayUrl, webUrl, email, me = "station", labe
24
24
  // A computer that opened rooms with no sign-in signs up as the identity
25
25
  // that holds them (guest.ts), so the rooms are the person's with no carry.
26
26
  const guest = saved ? null : readGuest(home, relayUrl);
27
+ // Before the sign-up: its answer holds a new token, which a failed lookup after it would lose.
28
+ const web = await siteOf(relayUrl, webUrl);
27
29
  const answer = await call(relayUrl, "/signup", auth ?? (guest ? { token: guest.token } : null), { body: { email, label } });
28
30
  const day = lockDay(answer.locks_at);
29
31
  const confirm = `Tell the person you work for, in your own chat: Station emailed ${answer.email} a link. They open it and press Confirm by ${day}. Until they do, they cannot open these rooms in a browser, and after ${day} the rooms lock.`;
@@ -35,7 +37,7 @@ export async function signUp(home, relayUrl, webUrl, email, me = "station", labe
35
37
  // Seats this computer took with no sign-in were waiting on a login link to become the person's.
36
38
  const claims = readPending(home)?.relayUrl === relayUrl ? (readPending(home)?.claims ?? []) : [];
37
39
  cancelLogin(home);
38
- const site = webUrl === DEFAULT_WEB ? {} : { webUrl };
40
+ const site = web === DEFAULT_WEB ? {} : { webUrl: web };
39
41
  const credentials = { relayUrl, ...site, token, userId: answer.user_id, name: answer.name ?? answer.email.split("@")[0] };
40
42
  writeJson(files(home).credentials, credentials);
41
43
  // The computer's own identity is the sign-in now.