@santori/station 0.9.7 → 0.9.9

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/limits.js ADDED
@@ -0,0 +1,210 @@
1
+ // Whether a local agent has run out of usage, so its work can move to
2
+ // another agent. Each harness says so in its own files:
3
+ //
4
+ // - Claude Code writes a turn that a limit stopped into the session's
5
+ // transcript (`<claude home>/projects/<folder>/<session>.jsonl`) as an
6
+ // assistant record with `error: "rate_limit"`, `isApiErrorMessage`, and
7
+ // `quotaLimits` (or `apiErrorParams.rate_limit_info`) holding
8
+ // `rateLimitType` and `resetsAt` in Unix seconds. Successful turns carry
9
+ // no usage, so the transcript shows a limit only after it is hit.
10
+ // - Codex ends a turn that a limit stopped with a `task_complete` event in
11
+ // the thread's rollout: `error.codex_error_info: "usage_limit_exceeded"`,
12
+ // and `error.message` ending "try again at Sep 26th, 2026 4:38 PM", the
13
+ // reset as wall-clock time on the computer Codex runs on. That is the
14
+ // signal: at all 26 run-outs in this computer's rollouts (Sep 2026) the
15
+ // newest `token_count` had no windows and no `rate_limit_reached_type`.
16
+ // (The app's `thread_history_1.sqlite` has the same failure as a
17
+ // `thread_turns` row with status failed and `error_json.codexErrorInfo:
18
+ // "usageLimitExceeded"`; Station reads the rollout.)
19
+ // - Codex also writes a `token_count` event with `rate_limits` after each
20
+ // model response: `primary` and `secondary` windows with `used_percent`,
21
+ // `window_minutes` and `resets_at`. A window at 100%, or a
22
+ // `rate_limit_reached_type`, is a run-out. A snapshot with no windows
23
+ // says nothing. The app-server's `account/rateLimits/read` answers it in
24
+ // camelCase.
25
+ // - `claude -p` and `codex exec` print the limit message and exit 1.
26
+ // `fromMessage` knows those messages, and reads Codex's reset time.
27
+ import { claudeHome, transcriptPath } from "./claude.js";
28
+ import { codexHome, rolloutPath, tailLines } from "./codex.js";
29
+ import { HARNESS_NAMES } from "./sessions.js";
30
+ const record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
31
+ const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : null);
32
+ const str = (value) => (typeof value === "string" ? value : null);
33
+ const parse = (line) => {
34
+ try {
35
+ return record(JSON.parse(line));
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ };
41
+ const passed = (resetsAt, now) => resetsAt !== null && resetsAt * 1000 <= now;
42
+ // Claude Code's message for a limit on one model family, and Codex's.
43
+ const MODEL_LIMIT = /hit your (Opus|Sonnet) limit|hit your usage limit for .+Switch to another model|\/model to switch models/i;
44
+ const LIMIT_MESSAGE = /You[’']ve hit your .*limit|You[’']re out of usage credits/i;
45
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
46
+ const CODEX_RESET = /try again at (?:([A-Z][a-z]{2})[a-z]* (\d{1,2})(?:st|nd|rd|th)?,? (\d{4}),? )?(\d{1,2}):(\d{2}) ?([AP]M)/i;
47
+ /** The reset in Codex's "try again at Sep 26th, 2026 4:38 PM": wall-clock
48
+ * time on this computer, the one Codex ran on. A bare "try again at 3:42
49
+ * PM" is the next 3:42 PM after `after` (when the turn ended). Null for
50
+ * any other text, or a bare time with nothing to count from. */
51
+ export function codexResetAt(text, after = null) {
52
+ const m = CODEX_RESET.exec(text);
53
+ if (!m)
54
+ return null;
55
+ const hour = (Number(m[4]) % 12) + (m[6].toUpperCase() === "PM" ? 12 : 0);
56
+ if (m[1]) {
57
+ const month = MONTHS.indexOf(m[1].toLowerCase());
58
+ if (month < 0)
59
+ return null;
60
+ return Math.floor(new Date(Number(m[3]), month, Number(m[2]), hour, Number(m[5])).getTime() / 1000);
61
+ }
62
+ if (after === null || !Number.isFinite(after))
63
+ return null;
64
+ const reset = new Date(after);
65
+ reset.setHours(hour, Number(m[5]), 0, 0);
66
+ if (reset.getTime() <= after)
67
+ reset.setDate(reset.getDate() + 1);
68
+ return Math.floor(reset.getTime() / 1000);
69
+ }
70
+ /** A limit from the text a headless run printed (`claude -p` result,
71
+ * `codex exec` stderr or its `turn.failed` message). Null when the text is
72
+ * not a usage limit. `now`: when the run printed it. */
73
+ export function fromMessage(text, now = Date.now()) {
74
+ if (!LIMIT_MESSAGE.test(text))
75
+ return null;
76
+ return { state: "out", window: null, resetsAt: codexResetAt(text, now), switchModel: MODEL_LIMIT.test(text), seenAt: null, text };
77
+ }
78
+ /** The limit a Claude Code transcript ends on: its newest limit error,
79
+ * unless the session replied again after it or the reset time passed. */
80
+ export function fromClaudeTranscript(lines, now = Date.now()) {
81
+ let found = null;
82
+ for (const line of lines) {
83
+ if (!line.includes('"assistant"'))
84
+ continue;
85
+ const entry = parse(line);
86
+ if (entry?.type !== "assistant")
87
+ continue;
88
+ if (entry.error !== "rate_limit" || entry.isApiErrorMessage !== true) {
89
+ // A real reply means the session got going again. Claude Code also
90
+ // writes `<synthetic>` records of its own ("No response requested."),
91
+ // which are not a reply.
92
+ if (!entry.isApiErrorMessage && record(entry.message)?.model !== "<synthetic>")
93
+ found = null;
94
+ continue;
95
+ }
96
+ const info = record(entry.quotaLimits) ?? record(record(entry.apiErrorParams)?.rate_limit_info);
97
+ const content = record(entry.message)?.content;
98
+ const text = Array.isArray(content) ? (content.map((part) => str(record(part)?.text)).find((t) => t) ?? null) : null;
99
+ found = {
100
+ state: "out",
101
+ window: str(info?.rateLimitType),
102
+ resetsAt: num(info?.resetsAt),
103
+ switchModel: entry.apiError === "model_requires_usage_credits" || (text !== null && MODEL_LIMIT.test(text)),
104
+ seenAt: str(entry.timestamp),
105
+ text,
106
+ };
107
+ }
108
+ return found && !passed(found.resetsAt, now) ? found : null;
109
+ }
110
+ /** The fullest window in a set of `{ used, resetsAt }`, skipping any whose
111
+ * reset passed; out at 100%. `reached`: the harness says a limit was hit,
112
+ * which counts only while the window it was hit in (the one at 100%, else
113
+ * the fullest) has not reset. */
114
+ function fullest(windows, now, reached) {
115
+ const sorted = [...windows].sort((a, b) => b.used - a.used);
116
+ if (reached && sorted[0] && passed(sorted[0].resetsAt, now))
117
+ reached = false;
118
+ const top = sorted.filter((w) => !passed(w.resetsAt, now))[0];
119
+ if (!top)
120
+ return null;
121
+ if (reached || top.used >= 100)
122
+ return { state: "out", window: top.window, resetsAt: top.resetsAt, switchModel: false, seenAt: null, text: null };
123
+ return null;
124
+ }
125
+ const WINDOW_NAMES = { 300: "5-hour", 10080: "weekly" };
126
+ /** The limit in a Codex rate limit snapshot: a rollout's `rate_limits`
127
+ * (snake_case) or the app-server's `rateLimits` (camelCase). */
128
+ export function fromCodexSnapshot(snapshot, now = Date.now()) {
129
+ const s = record(snapshot);
130
+ if (!s)
131
+ return null;
132
+ const windows = ["primary", "secondary"].flatMap((key) => {
133
+ const w = record(s[key]);
134
+ const used = num(w?.used_percent ?? w?.usedPercent);
135
+ if (!w || used === null)
136
+ return [];
137
+ const minutes = num(w.window_minutes ?? w.windowDurationMins);
138
+ return [{ window: (minutes !== null && WINDOW_NAMES[minutes]) || key, used, resetsAt: num(w.resets_at ?? w.resetsAt) }];
139
+ });
140
+ return fullest(windows, now, (s.rate_limit_reached_type ?? s.rateLimitReachedType ?? null) !== null);
141
+ }
142
+ const CODEX_RUN_OUT = new Set(["usage_limit_exceeded", "usageLimitExceeded"]);
143
+ /** The limit in a Codex rollout, newest record first. A turn that ended on
144
+ * `usage_limit_exceeded` is out until the reset its message names; a turn
145
+ * that ended without it means Codex got going again. Otherwise the newest
146
+ * `token_count` snapshot that has windows says whether it is out. */
147
+ export function fromCodexRollout(lines, now = Date.now()) {
148
+ let turnEnded = false;
149
+ for (let i = lines.length - 1; i >= 0; i--) {
150
+ const line = lines[i];
151
+ if (!line.includes('"task_complete"') && !line.includes('"rate_limits"'))
152
+ continue;
153
+ const entry = parse(line);
154
+ const payload = record(entry?.payload);
155
+ if (entry?.type !== "event_msg" || !payload)
156
+ continue;
157
+ if (payload.type === "task_complete") {
158
+ // Only the newest turn counts: an earlier one's snapshots are from before it.
159
+ if (turnEnded)
160
+ return null;
161
+ turnEnded = true;
162
+ const error = record(payload.error);
163
+ if (!CODEX_RUN_OUT.has(str(error?.codex_error_info) ?? ""))
164
+ continue;
165
+ const text = str(error?.message);
166
+ const resetsAt = text ? codexResetAt(text, Date.parse(str(entry.timestamp) ?? "")) : null;
167
+ if (passed(resetsAt, now))
168
+ return null;
169
+ return { state: "out", window: null, resetsAt, switchModel: text !== null && MODEL_LIMIT.test(text), seenAt: str(entry.timestamp), text };
170
+ }
171
+ if (payload.type !== "token_count")
172
+ continue;
173
+ const snapshot = record(payload.rate_limits);
174
+ if (!snapshot || (!record(snapshot.primary) && !record(snapshot.secondary)))
175
+ continue;
176
+ const limit = fromCodexSnapshot(snapshot, now);
177
+ return limit && { ...limit, seenAt: str(entry.timestamp) };
178
+ }
179
+ return null;
180
+ }
181
+ /** Whether the agent session with this id ran out of usage, from the
182
+ * files its harness writes. Null when it did not, or when Station
183
+ * cannot tell (any other agent, or no file yet). */
184
+ export function agentLimit(harness, id, now = Date.now(), env = process.env) {
185
+ try {
186
+ if (harness === "claude-code") {
187
+ const path = transcriptPath(claudeHome(env), id);
188
+ return path ? fromClaudeTranscript(tailLines(path), now) : null;
189
+ }
190
+ if (harness === "codex") {
191
+ const path = rolloutPath(codexHome(env), id);
192
+ return path ? fromCodexRollout(tailLines(path), now) : null;
193
+ }
194
+ }
195
+ catch {
196
+ // a file that went away or cannot be read says nothing
197
+ }
198
+ return null;
199
+ }
200
+ const CLAUDE_WINDOWS = { five_hour: "session", seven_day: "weekly" };
201
+ const utc = (seconds) => `${new Date(seconds * 1000).toISOString().slice(0, 16).replace("T", " ")} UTC`;
202
+ /** One or two plain sentences for a person or an agent. */
203
+ export function describeLimit(harness, limit) {
204
+ const who = HARNESS_NAMES[harness];
205
+ const window = limit.window ? (CLAUDE_WINDOWS[limit.window] ?? limit.window.replace(/_/g, " ")) : null;
206
+ const resets = limit.resetsAt !== null ? ` It resets at ${utc(limit.resetsAt)}.` : "";
207
+ if (limit.switchModel)
208
+ return `${who} ran out of its limit for this model. Another model may still work.${resets}`;
209
+ return `${who} ran out of its ${window ? `${window} ` : ""}limit.${resets}`;
210
+ }
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
  });
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,6 +3,7 @@
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
9
  code;
@@ -14,6 +15,12 @@ export class RelayError extends Error {
14
15
  this.code = code;
15
16
  }
16
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
+ }
17
24
  export async function call(base, path, auth, init = {}) {
18
25
  const headers = { ...(init.headers ?? {}) };
19
26
  if (auth)
@@ -32,7 +39,12 @@ export async function call(base, path, auth, init = {}) {
32
39
  response = await fetchAsCaller(`${base}${path}`, { method: init.method ?? (body ? "POST" : "GET"), headers, body });
33
40
  }
34
41
  catch (error) {
35
- throw new RelayError(0, `Could not reach ${base}: ${error instanceof Error ? error.message : String(error)}. Check the address and connection, then try again.`);
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}`);
36
48
  }
37
49
  if (!response.ok) {
38
50
  let detail = response.statusText;
@@ -51,6 +63,31 @@ export async function call(base, path, auth, init = {}) {
51
63
  }
52
64
  return (response.status === 204 ? undefined : await response.json());
53
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})?\/?$/;
54
91
  /** A relay room URL, or a room page on Station's website. */
55
92
  export function parseRoomUrl(url, credentials = null) {
56
93
  // The paste is a sentence ("Come join my Station room. To get started, run
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,41 @@
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
+ }
11
41
  /** The command a seat types to run Station again as itself. A worker named
12
42
  * with STATION_SESSION keeps the name in front: without it the command acts
13
43
  * for another seat, or for none. */
package/dist/sessions.js CHANGED
@@ -25,6 +25,17 @@ export function shellSession(install, env = process.env, cwd = process.cwd(), wh
25
25
  const id = `shell-${createHash("sha256").update(`${install}\n${key}`).digest("hex").slice(0, 32)}`;
26
26
  return { harness: "shell", id, cwd, name: named, why, ...(host ? { host } : {}) };
27
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 };
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 });
30
41
  /** The pids from `from` up to the first process, nearest first. */
@@ -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.