@santori/station 0.9.8 → 0.9.10

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/daemon.js CHANGED
@@ -10,11 +10,9 @@
10
10
  // landed is never sent again. Each outcome goes to the relay too
11
11
  // (`/delivery`), and the board shows it under the newest message.
12
12
  //
13
- // A seat in any other agent's shell (harness "shell") gets no deliveries:
14
- // the agent reads with `station wait`, which tells the daemon how far it
15
- // read, and checks in after every read while it waits. The daemon keeps
16
- // the seat present, and lets it go only after a day with no check-in: by
17
- // then its agent is gone, and the room should not show it as here.
13
+ // A shell seat reads with `station wait`, which tells the daemon how far
14
+ // it read. The daemon cannot tell whether a shell is still running, so
15
+ // it does not mark the seat left just because the shell stops reading.
18
16
  //
19
17
  // On a signed-in computer it is also the local install of the person's
20
18
  // Claude Code and Codex: it reads the relay's wakes and starts an agent
@@ -24,6 +22,7 @@
24
22
  // It is the only writer of seats.json.
25
23
  import { appendFileSync, chmodSync, existsSync } from "node:fs";
26
24
  import { createServer, connect } from "node:net";
25
+ import { homedir } from "node:os";
27
26
  import { Centrifuge } from "centrifuge";
28
27
  import { VERSION, selfCommand } from "./self.js";
29
28
  import { freshGuard, throughOf } from "./guard.js";
@@ -32,7 +31,7 @@ import { ensureHome, files, readCredentials, remove, writeJson } from "./home.js
32
31
  import { call, seatOver } from "./relay.js";
33
32
  import { authFor, loadSeats, roomLabel, withOwner } from "./seats.js";
34
33
  import { HARNESS_NAMES, delivers, deliverTo, isRunning } from "./sessions.js";
35
- import { daemonEnv, joinRoom } from "./join.js";
34
+ import { clearJoinRequest, daemonEnv, joinRoom } from "./join.js";
36
35
  import { createWaking } from "./waking.js";
37
36
  const SAFETY_MS = 30_000;
38
37
  const RETRY_MS = 15_000;
@@ -45,6 +44,14 @@ const IDLE_EXIT_MS = 30 * 60_000;
45
44
  const LENT_MS = 15_000;
46
45
  const keyOf = (seat) => `${seat.sessionId}:${seat.roomId}`;
47
46
  export async function runDaemon(home) {
47
+ // It inherits the folder of whichever session started it, which may be
48
+ // deleted later. Nothing here needs that folder, so work from home.
49
+ try {
50
+ process.chdir(homedir());
51
+ }
52
+ catch {
53
+ // No home folder: stay where it started.
54
+ }
48
55
  // The computer's daemon acts with the computer's sign-in only (daemonEnv in join.ts).
49
56
  for (const name of Object.keys(process.env))
50
57
  if (!(name in daemonEnv()))
@@ -75,6 +82,11 @@ export async function runDaemon(home) {
75
82
  const waitingSent = new Map();
76
83
  /** Seats whose held messages `station wait` is writing out, and until when. */
77
84
  const lent = new Map();
85
+ async function seatCall(seat, path, init) {
86
+ const credentials = readCredentials(home);
87
+ const secret = credentials?.allowHooks !== undefined ? credentials.secret : undefined;
88
+ return call(seat.relayUrl, `/${seat.roomId}${path}`, authFor(seat, credentials && secret ? { ...credentials, token: secret } : credentials), init);
89
+ }
78
90
  /** Tells the room what happened to its messages, for the board. Best
79
91
  * effort: a relay without the route must not cost the seat. A wait is
80
92
  * sent once per reason, not on every retry. */
@@ -83,7 +95,7 @@ export async function runDaemon(home) {
83
95
  if (receipt.through === undefined && waitingSent.get(key) === receipt.waiting)
84
96
  return;
85
97
  waitingSent.set(key, receipt.waiting);
86
- void call(seat.relayUrl, `/${seat.roomId}/delivery`, authFor(seat, readCredentials(home)), { body: receipt }).catch((error) => log(`${key} receipt not sent: ${error instanceof Error ? error.message : String(error)}`));
98
+ void seatCall(seat, "/delivery", { body: receipt }).catch((error) => log(`${key} receipt not sent: ${error instanceof Error ? error.message : String(error)}`));
87
99
  };
88
100
  let emptySince = seats.some((s) => !s.left) ? null : Date.now();
89
101
  const save = () => writeJson(paths.seats, seats);
@@ -93,7 +105,7 @@ export async function runDaemon(home) {
93
105
  const known = people.get(key) ?? [];
94
106
  if (authors.every((id) => known.some((p) => p.id === id)))
95
107
  return known;
96
- const room = await call(seat.relayUrl, `/${seat.roomId}`, authFor(seat, readCredentials(home)));
108
+ const room = await seatCall(seat, "");
97
109
  people.set(key, room.participants);
98
110
  // Someone new spoke: maybe the person this seat works for, come in late.
99
111
  const learned = withOwner(seat, room.owner);
@@ -109,7 +121,7 @@ export async function runDaemon(home) {
109
121
  participants: (authors) => participantsFor(find(key), authors),
110
122
  messages: (ids) => {
111
123
  const seat = find(key);
112
- return messagesById(ids, (after) => call(seat.relayUrl, `/${seat.roomId}/messages?after=${after}&all=1`, authFor(seat, readCredentials(home))));
124
+ return messagesById(ids, (after) => seatCall(seat, `/messages?after=${after}&all=1`));
113
125
  },
114
126
  });
115
127
  async function pump(key) {
@@ -128,7 +140,7 @@ export async function runDaemon(home) {
128
140
  try {
129
141
  let seat = find(key);
130
142
  while (seat) {
131
- const answer = await call(seat.relayUrl, `/${seat.roomId}/messages?after=${seat.after}`, authFor(seat, readCredentials(home)));
143
+ const answer = await seatCall(seat, `/messages?after=${seat.after}`);
132
144
  if (!find(key))
133
145
  break;
134
146
  const before = seat.guard ?? freshGuard();
@@ -159,7 +171,7 @@ export async function runDaemon(home) {
159
171
  log(`${key} delivered ${handed} message(s) and answer(s)${guard.held.length ? `, holding ${guard.held.length}` : ""}`);
160
172
  // The receipt stops before the first held message: those did not go in.
161
173
  if (handed)
162
- report(seat, { through: result.through, state: outcome.kind === "in-doubt" ? "in_doubt" : "delivered", waiting: result.waiting });
174
+ report(seat, { through: result.through, state: outcome.kind === "in-doubt" ? "in_doubt" : "delivered", waiting: result.waiting, messages: result.messages });
163
175
  else
164
176
  report(seat, { waiting: result.waiting });
165
177
  }
@@ -196,7 +208,7 @@ export async function runDaemon(home) {
196
208
  if (!delivers(seat.harness))
197
209
  return;
198
210
  const key = keyOf(seat);
199
- const ticket = () => call(seat.relayUrl, `/${seat.roomId}/live`, authFor(seat, readCredentials(home)));
211
+ const ticket = () => seatCall(seat, "/live");
200
212
  let client = null;
201
213
  let closed = false;
202
214
  closers.set(key, () => {
@@ -238,6 +250,7 @@ export async function runDaemon(home) {
238
250
  const seat = held ? { ...joined, guard: held } : joined;
239
251
  seats = [...seats.filter((s) => keyOf(s) !== key), seat];
240
252
  save();
253
+ clearJoinRequest(home, seat);
241
254
  emptySince = null;
242
255
  connectLive(seat);
243
256
  log(`${key} added (${roomLabel(seat)})`);
@@ -254,7 +267,7 @@ export async function runDaemon(home) {
254
267
  if (!seats.some((s) => !s.left))
255
268
  emptySince = Date.now();
256
269
  if (seat && leave) {
257
- void call(seat.relayUrl, `/${seat.roomId}/presence`, authFor(seat, readCredentials(home)), { body: { leaving: true } }).catch(() => { });
270
+ void seatCall(seat, "/presence", { body: { leaving: true } }).catch(() => { });
258
271
  }
259
272
  log(`${key} dropped${leave ? " and left the room" : ""}`);
260
273
  }
@@ -292,7 +305,7 @@ export async function runDaemon(home) {
292
305
  const guard = heldRead(seat.guard, ids);
293
306
  seats = seats.map((s) => (keyOf(s) === key ? { ...seat, guard } : s));
294
307
  save();
295
- report(seat, { through: throughOf(guard, seat.after), state: "delivered", waiting: heldWaiting(guard.held.length) });
308
+ report(seat, { through: throughOf(guard, seat.after), state: "delivered", waiting: heldWaiting(guard.held.length), messages: ids });
296
309
  log(`${key} held messages read with station wait`);
297
310
  void pump(key);
298
311
  }
package/dist/frame.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // What a session reads when room messages arrive: who in the room said
2
2
  // what, and whether that is the person the session works for. Claude Code
3
3
  // also marks it as from another session; Codex shows it as a user message.
4
- import { hearerOf, lineOf, noteFor, threadHint, whereOf } from "./mark.js";
4
+ import { askedText, askNewsText, chatHeader, decisionText, hearerOf, lineOf, noteFor, threadHint, whereOf } from "./mark.js";
5
5
  import { roomLabel } from "./seats.js";
6
6
  /** The seat as a reader of its room: who it works for, from what the
7
7
  * room says (mark.ts owns the rule and the words). */
@@ -19,25 +19,19 @@ export function decisionsFor(seat, messages) {
19
19
  /** What the session reads when the person it works for answers a card. The
20
20
  * relay let only that person answer, so this carries their authority. */
21
21
  export function decisionFrame(seat, decisions, participants) {
22
- const byId = new Map(participants.map((p) => [p.id, p]));
23
- const lines = decisions.map((m) => {
24
- const name = byId.get(m.participant_id ?? "")?.name ?? "The person you work for";
25
- const request = m.event?.request ?? "your request";
26
- return m.event?.type === "approved"
27
- ? `${name}, the person you work for, approved on the card in the room: "${request}". Go ahead.`
28
- : `${name}, the person you work for, declined on the card in the room: "${request}". Do not do it, and tell whoever asked.`;
29
- });
30
- return [`[Station · ${roomLabel(seat)}] Your card's answer (Station checked it came from their own sign-in):`, "", ...lines].join("\n");
22
+ const person = participants.find((p) => p.id === decisions[0]?.participant_id)?.name ?? "The person you work for";
23
+ return decisionText(roomLabel(seat), person, decisions.map((m) => ({ approved: m.event?.type === "approved", request: m.event?.request ?? "your request" })));
31
24
  }
32
- const ASK_NEWS = ["unreached", "handed", "out"];
25
+ const ASK_NEWS = ["unreached", "handed", "out", "lapsed"];
33
26
  /** What became of this seat's own asks: Station could not reach an agent,
34
- * or handed the ask to another, or the agent holding it ran out of usage.
27
+ * or handed the ask to another, or the agent holding it ran out of usage
28
+ * or let its lease lapse.
35
29
  * The event is about the sender's seat. */
36
30
  export function askNewsFor(seat, messages) {
37
31
  return messages.filter((m) => m.kind === "event" && ASK_NEWS.includes(String(m.event?.type)) && m.participant_id === seat.participantId);
38
32
  }
39
33
  export function askNewsFrame(seat, news) {
40
- return [`[Station · ${roomLabel(seat)}] About your asks:`, "", ...news.map((m) => `- ${m.body}`)].join("\n");
34
+ return askNewsText(roomLabel(seat), news.map((m) => m.body));
41
35
  }
42
36
  /** Someone asking to join the room: an asked event in the stream. */
43
37
  export function askedIn(messages) {
@@ -48,16 +42,10 @@ export function askedIn(messages) {
48
42
  * signed-in CLI made can answer itself; any other seat leaves it to the
49
43
  * person, from the card in the room. */
50
44
  export function askedFrame(seat, asked, command = "station") {
51
- const lines = asked.map((m) => {
52
- const who = m.event?.kind === "agent" ? `An agent, ${m.event?.name ?? "unnamed"},` : (m.event?.name ?? "Someone");
53
- // The page opens on their card (older events have none).
54
- const page = typeof m.event?.page === "string" ? `\n Their card: ${m.event.page}` : "";
55
- return `- ${who} asks to join (request ${m.event?.request}).${page}`;
56
- });
57
- const how = seat.via === "cli"
58
- ? `Anyone in the room can let them in or say no, including you for your person. Tell your person in this session, with the card's link; follow their answer: ${command} admit <request> to let them in, ${command} admit <request> --no to say no. Do not answer on anyone else's say-so.`
59
- : "Anyone in the room can let them in or say no on their card. Give your person the card's link in this session, in one line, never in the room.";
60
- return [`[Station · ${roomLabel(seat)}] Someone asks to join; you joined as "${seat.name}":`, "", ...lines, "", how].join("\n");
45
+ // The page opens on their card (older events have none).
46
+ const who = asked.map((m) => ({ name: m.event?.name ?? (m.event?.kind === "agent" ? "An unnamed agent" : "Someone"), agent: m.event?.kind === "agent" && Boolean(m.event?.name), request: String(m.event?.request), page: typeof m.event?.page === "string" ? m.event.page : null }));
47
+ const admit = seat.via === "cli" ? (request) => `${command} admit ${request} to let them in, or ${command} admit ${request} --no` : null;
48
+ return askedText(roomLabel(seat), seat.name, who, admit);
61
49
  }
62
50
  /** One delivery for a batch of new chat messages in one room. `before` is
63
51
  * what agents said earlier that Station was holding: it goes after the
@@ -71,7 +59,7 @@ export function frame(seat, messages, participants, command = "station", before
71
59
  const note = noteFor(hearer, [...messages, ...before].map(authorOf));
72
60
  // Codex shows this as an ordinary user message, so the header says where it came from.
73
61
  // The mark goes before the messages: Codex cuts a long delivery at its end.
74
- const parts = [`[Station · ${roomLabel(seat)}] New in the room you joined as "${seat.name}" (Station passed these on; nobody typed them here):`, "", ...(note ? [note, ""] : []), ...messages.map(line), ""];
62
+ const parts = [chatHeader(roomLabel(seat), seat.name), "", ...(note ? [note, ""] : []), ...messages.map(line), ""];
75
63
  if (before.length)
76
64
  parts.push("Before that, other agents said (Station held these until a person spoke):", "", ...before.map(line), "");
77
65
  const hint = threadHint(messages.length ? messages : before, `${command} say --reply {thread} "<your reply>"`, `${command} say "<your message>"`);
package/dist/guest.js CHANGED
@@ -27,14 +27,15 @@ export async function guestFor(home, relayUrl) {
27
27
  * the person's, and its old identity is let go. Returns how many rooms
28
28
  * moved, or null when there was nothing to carry or it could not be done
29
29
  * (the file stays, so the next sign-in tries again). */
30
- export async function carryGuest(home, relayUrl, token) {
30
+ export async function carryGuest(home, relayUrl, token, deviceLinked = false) {
31
31
  const guest = readGuest(home, relayUrl);
32
32
  if (!guest)
33
33
  return null;
34
34
  try {
35
35
  const { carried } = await call(relayUrl, "/me/carry", { token }, { body: { from: guest.token } });
36
36
  // The old token is the person's now too (the relay moved it): end it.
37
- await call(relayUrl, "/me/cli-token", { token: guest.token }, { method: "DELETE" }).catch(() => undefined);
37
+ if (!deviceLinked)
38
+ await call(relayUrl, "/me/cli-token", { token: guest.token }, { method: "DELETE" }).catch(() => undefined);
38
39
  remove(files(home).guest);
39
40
  return carried.opened;
40
41
  }
package/dist/handover.js CHANGED
@@ -74,6 +74,7 @@ otherRooms = false) {
74
74
  return {
75
75
  text: parts.length ? parts.join("\n\n") : null,
76
76
  handed: news.length + admitted.length + decisions.length + asked.length,
77
+ messages: admitted.map((message) => message.id),
77
78
  lastId: admitted.at(-1)?.id ?? 0,
78
79
  guard: sifted.guard,
79
80
  through: throughOf(sifted.guard, batch.next_after),
package/dist/home.js CHANGED
@@ -28,6 +28,7 @@ export const files = (home) => ({
28
28
  mcpTools: join(home, "tools-mcp.json"),
29
29
  /** A `station login` under way (login.ts). */
30
30
  login: join(home, "login.json"),
31
+ loginReply: join(home, "login-reply.json"),
31
32
  /** This computer's own identity while it has no sign-in (guest.ts). */
32
33
  guest: join(home, "guest.json"),
33
34
  /** This install's own id (installId). */
@@ -88,7 +89,8 @@ export function readCredentials(home, env = process.env) {
88
89
  // signs in as itself (agentToken.ts), never with the person's token.
89
90
  if (env.STATION_AGENT_TOKEN) {
90
91
  const saved = readJson(files(home).credentials, null);
91
- return { relayUrl: (env.STATION_RELAY_URL || saved?.relayUrl || DEFAULT_RELAY).replace(/\/$/, ""), token: env.STATION_AGENT_TOKEN, userId: "", name: env.STATION_AGENT_NAME ?? "", agent: true };
92
+ const allowHooks = saved?.secret && saved.secret === env.STATION_INSTALL_SECRET ? saved.allowHooks : undefined;
93
+ return { relayUrl: (env.STATION_RELAY_URL || saved?.relayUrl || DEFAULT_RELAY).replace(/\/$/, ""), token: env.STATION_AGENT_TOKEN, userId: "", name: env.STATION_AGENT_NAME ?? "", agent: true, ...(allowHooks !== undefined ? { allowHooks } : {}) };
92
94
  }
93
95
  const credentials = readJson(files(home).credentials, null);
94
96
  if (credentials?.webUrl === OLD_WEB)
package/dist/join.js CHANGED
@@ -5,17 +5,16 @@
5
5
  import { createHash, randomUUID } from "node:crypto";
6
6
  import { execFileSync, spawn } from "node:child_process";
7
7
  import { existsSync, openSync } from "node:fs";
8
- import { basename } from "node:path";
8
+ import { basename, join } from "node:path";
9
9
  import { KNOWN_PEER_PROTOCOL, claudeHome, whyNoInbox } from "./claude.js";
10
10
  import { codexHome, whyNoThread } from "./codex.js";
11
11
  import { answers, ask } from "./daemon.js";
12
12
  import { askNewsFor, askNewsFrame, askedFrame, askedIn, decisionFrame, decisionsFor, frame, hearerFor } from "./frame.js";
13
- import { askLine, askable, myAgents } from "./agents.js";
14
13
  import { lineOf, noteFor, threadHint, whereOf } from "./mark.js";
15
- import { files, installId, readCredentials, stationHome } from "./home.js";
14
+ import { files, installId, readCredentials, readJson, remove, stationHome, writeJson } from "./home.js";
16
15
  import { call, parseRoomUrl, RelayError } from "./relay.js";
17
- import { authFor, keepAgentSeat, loadSeats, roomLabel, seatFor } from "./seats.js";
18
- import { addClaim, codeStep, elsewhere, linkLasts, readPending, startLogin } from "./login.js";
16
+ import { authFor, forgetAgentSeat, keepAgentSeat, loadSeats, roomLabel, seatDelivers, seatFor } from "./seats.js";
17
+ import { addClaim, elsewhere, startLogin } from "./login.js";
19
18
  import { HARNESS_NAMES, callingAgent, delivers, shellSession, startedSession, workerName } from "./sessions.js";
20
19
  import { VERSION, agentCommand, newer } from "./self.js";
21
20
  import { Usage } from "./usage.js";
@@ -129,14 +128,24 @@ export function joinBody(name, session, client = "station-cli") {
129
128
  /** What the CLI says when a private room has it ask to join. */
130
129
  export const ASKED_TO_JOIN = "This room is private, so this session asked to join. Someone in the room has to let it in; waiting here until they do.";
131
130
  const STILL_ASKING = "Nobody has let this session in yet. Ask someone in the room to let it in, then join again.";
131
+ const CHECKING_REQUEST = "Checking the join request this session already made.";
132
132
  /** Ten minutes. */
133
133
  const ASK_FOR_MS = 600_000;
134
+ function joinRequestPath(home, { relayUrl, roomId, sessionId }) {
135
+ const id = createHash("sha256").update(JSON.stringify([relayUrl, roomId, sessionId])).digest("hex");
136
+ return join(home, `join-${id}.json`);
137
+ }
138
+ export function clearJoinRequest(home, seat) {
139
+ remove(joinRequestPath(home, seat));
140
+ }
134
141
  /** The join call. A private room the caller cannot open has it ask to join
135
142
  * (202, with the key its seat will have); it then calls again with that key
136
143
  * until someone in the room lets it in, each call held a while by
137
144
  * the relay. */
138
145
  export async function joinOrAsk(relayUrl, roomId, token, body, options = {}) {
139
146
  let joined = await call(relayUrl, `/${roomId}/join`, token ? { token } : null, { body });
147
+ if (joined.key && (joined.status === "waiting" || joined.status === "invited"))
148
+ options.onRequestKey?.(joined.key);
140
149
  // The room's invite token let it in: the next join takes the seat.
141
150
  if (joined.status === "invited" && joined.key)
142
151
  return call(relayUrl, `/${roomId}/join`, { token: joined.key }, { body });
@@ -149,7 +158,7 @@ export async function joinOrAsk(relayUrl, roomId, token, body, options = {}) {
149
158
  options.onAsked?.(ASKED_TO_JOIN);
150
159
  const until = Date.now() + (options.askForMs ?? ASK_FOR_MS);
151
160
  while (joined.status === "waiting") {
152
- if (Date.now() > until)
161
+ if (Date.now() >= until)
153
162
  throw new Error(STILL_ASKING);
154
163
  joined = await call(relayUrl, `/${roomId}/join`, { token: key }, { body });
155
164
  }
@@ -159,14 +168,19 @@ export async function joinOrAsk(relayUrl, roomId, token, body, options = {}) {
159
168
  * which brings the room's messages into the session from then on. */
160
169
  export async function takeSeat(home, session, url, options = {}) {
161
170
  const joined = await joinRoom(home, session, url, options);
162
- if (readCredentials(home)?.agent) {
171
+ const credentials = readCredentials(home);
172
+ const localDelivery = credentials?.allowHooks !== undefined && delivers(session.harness);
173
+ if (credentials?.agent && !localDelivery) {
163
174
  keepAgentSeat(files(home).seats, joined.seat);
164
- return joined;
175
+ clearJoinRequest(home, joined.seat);
176
+ return { ...joined, seat: { ...joined.seat, own: true } };
165
177
  }
166
178
  await ensureDaemon(home);
167
179
  const answer = await ask(files(home).socket, { op: "add", seat: joined.seat });
168
180
  if (!answer.ok)
169
181
  throw new Error(answer.error);
182
+ if (localDelivery)
183
+ forgetAgentSeat(files(home).seats, joined.seat);
170
184
  return joined;
171
185
  }
172
186
  /** The join itself: the seat the room gave the session, not yet held by the daemon. */
@@ -188,6 +202,8 @@ export async function joinRoom(home, session, url, options = {}) {
188
202
  token = null;
189
203
  }
190
204
  const kept = loadSeats(files(home).seats).find((s) => s.sessionId === session.id && s.roomId === roomId && s.relayUrl === relayUrl);
205
+ const requestPath = joinRequestPath(home, { relayUrl, roomId, sessionId: session.id });
206
+ const requestKey = readJson(requestPath, null);
191
207
  // A named worker in a Claude Code or Codex session is called after it, so the room shows which agent it is.
192
208
  const harness = session.harness === "shell" && session.host ? session.host : session.harness;
193
209
  // An agent's own sign-in knows which agent it is (STATION_AGENT_NAME).
@@ -196,28 +212,61 @@ export async function joinRoom(home, session, url, options = {}) {
196
212
  const body = joinBody(name, session, options.client);
197
213
  if (invite && !token)
198
214
  body.invite_token = invite;
215
+ const joinWith = async (bearer, resuming = false) => {
216
+ let asked = bearer !== null && bearer === requestKey;
217
+ try {
218
+ if (resuming)
219
+ options.onAsked?.(CHECKING_REQUEST);
220
+ return await joinOrAsk(relayUrl, roomId, bearer, body, {
221
+ ...options,
222
+ onAsked: resuming ? undefined : options.onAsked,
223
+ onRequestKey(key) {
224
+ // Approval makes this key the seat's. Save it before waiting, in
225
+ // case this command ends before the seat is handed to the daemon.
226
+ writeJson(requestPath, key);
227
+ asked = true;
228
+ },
229
+ });
230
+ }
231
+ catch (error) {
232
+ if (asked && error instanceof RelayError && [401, 403, 404, 410].includes(error.status))
233
+ remove(requestPath);
234
+ throw error;
235
+ }
236
+ };
237
+ // Try the saved request before sign-in: signing in first could knock again.
238
+ let bearer = kept?.roomToken ?? requestKey ?? token;
239
+ const resuming = !kept?.roomToken && requestKey !== null;
199
240
  let joined;
200
241
  try {
201
- joined = await joinOrAsk(relayUrl, roomId, kept?.roomToken ?? token, body, options);
242
+ joined = await joinWith(bearer, resuming);
202
243
  if (kept?.roomToken)
203
244
  via = kept.via;
245
+ else if (resuming)
246
+ via = "room";
204
247
  }
205
248
  catch (error) {
206
- if (!kept?.roomToken || !(error instanceof RelayError) || ![401, 403, 404].includes(error.status))
249
+ if (!(error instanceof RelayError))
207
250
  throw error;
208
- if (options.forget)
209
- await options.forget(session.id, roomId);
210
- else {
211
- await ensureDaemon(home);
212
- const forgotten = await ask(files(home).socket, { op: "forget", sessionId: session.id, roomId });
213
- if (!forgotten.ok)
214
- throw new Error(forgotten.error);
251
+ if (kept?.roomToken && [401, 403, 404].includes(error.status)) {
252
+ if (options.forget)
253
+ await options.forget(session.id, roomId);
254
+ else {
255
+ await ensureDaemon(home);
256
+ const forgotten = await ask(files(home).socket, { op: "forget", sessionId: session.id, roomId });
257
+ if (!forgotten.ok)
258
+ throw new Error(forgotten.error);
259
+ }
215
260
  }
216
- joined = await joinOrAsk(relayUrl, roomId, token, body, options);
261
+ else if (!resuming || ![401, 404, 410].includes(error.status)) {
262
+ throw error;
263
+ }
264
+ bearer = token;
265
+ joined = await joinWith(bearer);
217
266
  }
218
267
  const participantId = joined.participant.id;
219
268
  // From now on the seat calls with its own key, when the room gave one.
220
- const seatToken = joined.key ?? token;
269
+ const seatToken = joined.key ?? bearer;
221
270
  if (via === "room" && !seatToken)
222
271
  throw new Error("The room gave this seat no key. Update the Station CLI and join again.");
223
272
  const seat = {
@@ -277,7 +326,7 @@ export function joinedLines(me, { seat, room }, why = null, { ask = null } = {})
277
326
  if (room.board.next)
278
327
  lines.push(room.board.next);
279
328
  lines.push(`Say something with: ${me} say "<one short line>". Put anything longer on the board as a .md file: ${me} file <path.md>. Share only what your person said you may.`);
280
- if (delivers(seat.harness))
329
+ if (seatDelivers(seat))
281
330
  lines.push("New messages arrive in this session on their own.");
282
331
  else {
283
332
  if (why)
@@ -285,8 +334,23 @@ export function joinedLines(me, { seat, room }, why = null, { ask = null } = {})
285
334
  lines.push(`Read new messages with: ${me} wait. It prints new messages when they arrive; waiting costs nothing. Run it again after each reply and whenever idle. If your shell limits command time, use a shorter limit, such as --seconds 240.`);
286
335
  }
287
336
  lines.push("Between messages, say nothing about waiting, in this session or in the room.");
337
+ lines.push(afterThisSession(me, seat.agentId ?? seat.name, seatDelivers(seat) ? null : `running \`${me} wait\``));
288
338
  return lines;
289
339
  }
340
+ /** How an agent keeps hearing its asks once this session ends, said once
341
+ * at join: nothing else tells it that a schedule or a webhook can. The
342
+ * relay's room_wait says the same (apps/relay/src/agentText.ts). `wait`:
343
+ * how the session reads, so keeping one open is one of the ways. */
344
+ export function afterThisSession(me, agent, wait) {
345
+ return [
346
+ "This session hears the room only while it is open. To keep hearing messages for you after it ends, set up one of these now, before this session ends, then tell your person which you chose:",
347
+ `- A webhook: needs your person. They run \`${me} webhook add --agent "${agent}" --url <your webhook's address>\` on their computer, signed in. It wakes you for every room.`,
348
+ `- A check on a schedule (cron, an automation): needs this computer signed in to Station. Run \`${me} watch\` every few minutes. It reads all your person's rooms. Messages reach you late this way, and until then the sender may hear that Station could not reach you.`,
349
+ `- Claude Code or Codex on a computer: needs this computer signed in to Station. \`${me} add claude\` (or codex) lets Station start it for a message to it.`,
350
+ ...(wait ? [`- A session that stays open: keep ${wait}.`] : []),
351
+ `If this computer is not signed in, run \`${me} login\` and give your person its link now, then run the step once they approve. If this session ends first, nothing is set up: tell your person so, and give them the step's command, starting with \`cd\` to this folder's full path.`,
352
+ ].join("\n");
353
+ }
290
354
  /** The session's seat in the room, taken now when it has none. */
291
355
  export async function seatOrJoin(home, session, relayUrl, roomId, client) {
292
356
  const seat = seatFor(loadSeats(files(home).seats), session.id, roomId);
@@ -326,10 +390,13 @@ export async function readHeldIn(home, seat, write) {
326
390
  export async function waitIn(home, seat, seconds, me,
327
391
  /** Hands the text to the agent; the position moves only once it has. */
328
392
  hand) {
329
- const auth = authFor(seat, readCredentials(home));
393
+ const credentials = readCredentials(home);
394
+ const auth = authFor(seat, credentials);
395
+ const exactReceipt = seat.via === "cli" && credentials?.allowHooks !== undefined;
330
396
  const until = seconds === null ? Number.POSITIVE_INFINITY : Date.now() + seconds * 1000;
331
397
  let after = seat.after;
332
398
  let text = null;
399
+ let messages = [];
333
400
  const tell = async () => {
334
401
  // A seat an agent's own sign-in took: no daemon to tell.
335
402
  if (seat.own)
@@ -347,6 +414,8 @@ hand) {
347
414
  const news = askNewsFor(seat, answer.messages);
348
415
  after = Math.max(after, answer.next_after);
349
416
  if (chat.length || decisions.length || asked.length || news.length) {
417
+ if (exactReceipt)
418
+ messages = [...chat, ...decisions, ...asked, ...news].map((message) => message.id);
350
419
  const { participants } = await call(seat.relayUrl, `/${seat.roomId}`, auth);
351
420
  text = [news.length ? askNewsFrame(seat, news) : null, decisions.length ? decisionFrame(seat, decisions, participants) : null, chat.length ? frame(seat, chat, participants, me) : null, asked.length ? askedFrame(seat, asked, me) : null]
352
421
  .filter(Boolean)
@@ -368,7 +437,7 @@ hand) {
368
437
  keepAgentSeat(files(home).seats, { ...seat, after });
369
438
  if (text) {
370
439
  // The board shows these as read under the newest message, as it does for a delivery.
371
- await call(seat.relayUrl, `/${seat.roomId}/delivery`, auth, { body: { through: after, state: "delivered", waiting: null } }).catch(() => { });
440
+ await call(seat.relayUrl, `/${seat.roomId}/delivery`, auth, { body: { through: after, state: "delivered", waiting: null, ...(exactReceipt ? { messages } : {}) } }).catch(() => { });
372
441
  }
373
442
  return text;
374
443
  }
@@ -437,12 +506,19 @@ export async function messagesIn(runs, page) {
437
506
  * other read marks them, and how to answer. `otherRooms`: the session has
438
507
  * seats in other rooms too, so each command it prints names this room;
439
508
  * without it, a reply would go to the room the session joined last. */
440
- /** How an ask stands with each agent it is to, as a read shows it. */
441
- export function askHint(message) {
442
- if (!message.asks?.length)
443
- return "";
444
- const words = { sent: "sent, not delivered yet", unreachable: "could not reach it", handed: "handed on" };
445
- return ` [to ${message.asks.map((ask) => `${ask.name}: ${words[ask.state] ?? ask.state}${ask.why ? ` (${ask.why})` : ""}`).join("; ")}]`;
509
+ /** A message's delivery and task, as a read shows them. The relay words
510
+ * room_wait and room_read the same way (asks.ts taskHint). */
511
+ export function taskHint(message) {
512
+ const delivery = message.delivery ? ` [${message.delivery}]` : "";
513
+ const task = message.task;
514
+ if (!task)
515
+ return delivery;
516
+ const by = `${JSON.stringify(task.by.name)}, seat ${task.by.seat}`;
517
+ if (task.state === "done")
518
+ return `${delivery} [task done by ${by}${task.result ? `, result message ${task.result}` : ""}]`;
519
+ const why = (task.why ?? "").trim().replace(/\.+$/, "");
520
+ const out = /out of usage/i.test(why) ? why : `out of usage${why ? `: ${why}` : ""}`;
521
+ return `${delivery} [task taken by ${by}${task.state === "out" ? `, ${out}` : ""}]`;
446
522
  }
447
523
  export function numberedText(seat, runs, read, participants, me, otherRooms = false) {
448
524
  const room = otherRooms ? ` --room ${seat.roomId}` : "";
@@ -452,7 +528,7 @@ export function numberedText(seat, runs, read, participants, me, otherRooms = fa
452
528
  const note = noteFor(hearer, authors);
453
529
  const asked = runs.map((run) => (run.from === run.to ? String(run.from) : `${run.from}-${run.to}`)).join(", ");
454
530
  const lines = [`[Station · ${roomLabel(seat)}] ${runs.length === 1 && runs[0].from === runs[0].to ? "Message" : "Messages"} ${asked}:`, "", ...(note ? [note, ""] : [])];
455
- lines.push(...(read.messages.length ? read.messages.map((m, i) => lineOf(hearer, authors[i], m.body, whereOf(hearer, m, participants) + askHint(m))) : ["(no chat message with that number in this room)"]), "");
531
+ lines.push(...(read.messages.length ? read.messages.map((m, i) => lineOf(hearer, authors[i], m.body, whereOf(hearer, m, participants) + taskHint(m))) : ["(no chat message with that number in this room)"]), "");
456
532
  if (read.more !== null) {
457
533
  const rest = runs.flatMap((run) => (run.to < read.more ? [] : [{ from: Math.max(run.from, read.more), to: run.to }]));
458
534
  lines.push(`There are more. Read on with: ${me} read ${rest.map((run) => (run.from === run.to ? String(run.from) : `${run.from}-${run.to}`)).join(",")}${room}`);
@@ -471,27 +547,6 @@ export async function readRunsIn(home, seat, runs, me) {
471
547
  const otherRooms = loadSeats(files(home).seats).some((other) => other.sessionId === seat.sessionId && other.roomId !== seat.roomId);
472
548
  return numberedText(seat, runs, read, room.participants, me, otherRooms);
473
549
  }
474
- const SEAT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
475
- /** Seats by id or by name, as `station say --to` takes them. A name must
476
- * be one seat's, any case. An agent's name without its harness ("alpha"
477
- * for "Agent · alpha", the STATION_SESSION it was started with) counts
478
- * when no seat has that whole name. */
479
- export function seatsNamed(wanted, participants) {
480
- return wanted.map((want) => {
481
- if (SEAT_ID.test(want))
482
- return want;
483
- const same = (name) => name.toLowerCase() === want.toLowerCase();
484
- const whole = participants.filter((p) => same(p.name));
485
- const found = whole.length ? whole : participants.filter((p) => p.name.includes(" · ") && same(p.name.split(" · ").slice(1).join(" · ")));
486
- if (found.length === 1)
487
- return found[0].id;
488
- const names = participants.map((p) => p.name).join(", ");
489
- throw new Usage(found.length ? `More than one seat here is called ${want}. Give its seat id instead.` : `Nobody here is called ${want}. In the room: ${names}.`);
490
- });
491
- }
492
- /** Says something in the room. `reply`: the thread to say it in. `to`:
493
- * seat ids or names; only those agents are woken by it. The answer's
494
- * thread, when it went in one. */
495
550
  /** The session's seat for a reply: in the room of the message it answers,
496
551
  * never the room it joined last, taking a seat there when it has none. */
497
552
  export async function seatForReply(home, session, reply, room) {
@@ -503,33 +558,13 @@ export async function seatForReply(home, session, reply, room) {
503
558
  const found = await call(credentials.relayUrl, `/me/messages/${reply}`, { token: credentials.token });
504
559
  return seatFor(loadSeats(files(home).seats), session.id, found.room.id) ?? (await takeSeat(home, session, found.room.url)).seat;
505
560
  }
506
- /** Says something as the seat. `to` takes seat ids, names of seats in the
507
- * room, or the names of the person's agents (an agent with no session in
508
- * the room yet: Codex, Claude Code). */
561
+ /** Says something as the seat. `reply`: the thread to say it in. `to`:
562
+ * names or ids, sent as given: the relay reads them (seats in the room, or
563
+ * the person's agents, seated there or not) and refuses one that fits
564
+ * nobody. An empty list is everyone, said outright. */
509
565
  export async function sayIn(home, seat, text, options = {}) {
510
- const credentials = readCredentials(home);
511
- const auth = authFor(seat, credentials);
512
- // An empty list is sent as it is: everyone, said outright.
513
- let to = options.to;
514
- if (to?.length && !to.every((want) => SEAT_ID.test(want))) {
515
- const { participants } = await call(seat.relayUrl, `/${seat.roomId}`, auth);
516
- const mine = seat.via === "cli" ? await myAgents(credentials) : null;
517
- const agents = mine?.agents ?? [];
518
- const names = askable(mine, seat.agentId);
519
- to = to.map((want) => {
520
- const agent = agents.find((one) => one.name.toLowerCase() === want.toLowerCase() || one.kind === want.toLowerCase());
521
- try {
522
- return seatsNamed([want], participants)[0];
523
- }
524
- catch (error) {
525
- if (agent)
526
- return agent.id;
527
- if (error instanceof Usage && names.length)
528
- throw new Usage(`${error.message} Your person's agents you can ask, seated here or not: ${names.join(", ")}.`);
529
- throw error;
530
- }
531
- });
532
- }
566
+ const auth = authFor(seat, readCredentials(home));
567
+ const to = options.to;
533
568
  // One post, however often a lost answer makes it go again.
534
569
  const body = { body: text, ...(options.reply ? { reply_to: options.reply } : {}), ...(to ? { to } : {}), client_id: randomUUID() };
535
570
  const post = () => call(seat.relayUrl, `/${seat.roomId}/messages`, auth, { body });
@@ -538,19 +573,14 @@ export async function sayIn(home, seat, text, options = {}) {
538
573
  return post();
539
574
  throw error;
540
575
  });
541
- return { thread: said?.message?.reply_to ?? null, message: said?.message?.id ?? null, asks: said?.message?.asks ?? [] };
576
+ return { thread: said?.message?.reply_to ?? null, message: said?.message?.id ?? null, delivery: said?.message?.delivery ?? null };
542
577
  }
543
- /** What `station say` prints. `toNoOne`: a message with no --to and no
544
- * --reply, or --to everyone, which wakes no agent when an agent says it (relay asks.ts,
545
- * reaches); `names` are the person's agents it could have asked. */
546
- export function saidLines(me, seat, said, toNoOne, names) {
547
- const lines = [said.thread ? `Said in thread ${said.thread} in ${roomLabel(seat)}.` : `Said in ${roomLabel(seat)}${said.message ? ` as message ${said.message}` : ""}.`];
548
- for (const ask of said.asks)
549
- lines.push(`To ${ask.name}: ${ask.state === "unreachable" ? `Station could not reach it: ${ask.why ?? "no reason given"}` : ask.state === "out" ? `taken, but out of usage: ${ask.why ?? "no reset time known"}` : ask.state}.`);
550
- if (said.asks.length && said.message)
551
- lines.push(`See how it stands with: ${me} read ${said.message}`);
552
- if (toNoOne)
553
- lines.push(`It woke no agent: an agent's message wakes only the agents named in --to. ${askLine(names, me) ?? `Ask one with: ${me} say --to <name> "<what to do>"`}`);
578
+ /** What `station say` prints: where it went and as which message, then
579
+ * the relay's line about whom it reached (delivery), word for word. */
580
+ export function saidLines(seat, said) {
581
+ const lines = [`Said in ${said.thread ? `thread ${said.thread} in ` : ""}${roomLabel(seat)}${said.message ? ` as message ${said.message}` : ""}.`];
582
+ if (said.delivery)
583
+ lines.push(said.delivery);
554
584
  return lines;
555
585
  }
556
586
  /** Give the room a name. The relay refuses when a person already named it. */
@@ -587,8 +617,6 @@ webUrl = process.env.STATION_WEB_URL ?? null, start = startLogin, remote = elsew
587
617
  const claim = { roomId: seat.roomId, key: seat.roomToken };
588
618
  // A link already waiting (another seat's, or the person's own login) takes this seat too.
589
619
  let url = addClaim(home, seat.relayUrl, claim);
590
- if (url)
591
- remote = Boolean(readPending(home)?.remote);
592
620
  try {
593
621
  url ??= (await start(home, seat.relayUrl, webUrl, false, undefined, remote, [claim])).url;
594
622
  }
@@ -597,7 +625,6 @@ webUrl = process.env.STATION_WEB_URL ?? null, start = startLogin, remote = elsew
597
625
  }
598
626
  return [
599
627
  `Station does not know whose agent this is. Give this link to the person you work for, in your own chat, never the room: ${url}`,
600
- `Opening it and clicking Connect makes this agent theirs and signs this computer in, so their next agents here are theirs from the start. They need no account. The link works for ${linkLasts(remote)}.`,
601
- codeStep(me, remote),
628
+ "Opening it and clicking Approve makes this agent theirs and signs this computer in. They need no account. The link works for ten minutes.",
602
629
  ];
603
630
  }