@santori/station 0.9.11 → 0.9.13

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/mark.js CHANGED
@@ -29,22 +29,39 @@ export function severalOwners(seats) {
29
29
  const owners = seats.filter((seat) => seat.kind === "agent").map((seat) => (seat.for?.you ? "you" : (seat.for?.name ?? `seat ${seat.id}`)));
30
30
  return new Set(owners).size > 1;
31
31
  }
32
- /** A seat or an agent by its id, as a message's text can name it. Printed only to tell 2 with the same name apart (seatLabels). */
32
+ /** A seat or an agent by its id, as a message's text tags it. */
33
33
  export const mention = (id) => `<@${id}>`;
34
- /** A seat as an agent reads it in a list of names, and as `to` takes it
35
- * back (the relay's tags.ts named): its name, and whose agent it is when
34
+ /** For a run of message lines, whether each is its author's first: the
35
+ * author's mention goes on that line only, where the agent copies it. */
36
+ export function firstOfEach(authors) {
37
+ const seen = new Set();
38
+ return authors.map((author) => {
39
+ if (!author || seen.has(author.id))
40
+ return false;
41
+ seen.add(author.id);
42
+ return true;
43
+ });
44
+ }
45
+ /** For lines that print an author's seat id themselves (an inbox across
46
+ * rooms): " <@id>" on each author's first line, "" on the rest. */
47
+ export function tagsOnce(seats) {
48
+ const first = firstOfEach(seats.map((id) => (id ? { id } : undefined)));
49
+ return seats.map((id, i) => (id && first[i] ? ` ${mention(id)}` : ""));
50
+ }
51
+ /** A seat as an agent reads it in a list: its name, whose agent it is when
36
52
  * the list's agents are more than 1 person's (`owners`, severalOwners),
37
- * such as "Claude Code · cadmate (Albert's)". `twin`: another in the list
38
- * reads the same, so its mention follows. */
39
- export function seatLabel(seat, owners, twin = false) {
53
+ * then the mention to copy, built from its id: "Claude Code · cadmate
54
+ * (Albert's) <@id>". A seat's id is its seat's, so the tag reaches that
55
+ * session; an agent with no seat in the room goes by its agent id. A name
56
+ * printed this way also still works in `to` (the relay's tags.ts named);
57
+ * no text teaches that. */
58
+ export function seatLabel(seat, owners) {
40
59
  const owner = owners && seat.kind === "agent" ? whose(seat.for) : null;
41
- return `${seat.name}${owner ? ` (${owner})` : ""}${twin ? ` ${mention(seat.id)}` : ""}`;
60
+ return `${seat.name}${owner ? ` (${owner})` : ""} ${mention(seat.id)}`;
42
61
  }
43
- /** These seats as one list of names. Each is what `to` takes to reach
44
- * that one: 2 that would read the same get their mention as well. */
62
+ /** These seats as one list of labels (seatLabel). */
45
63
  export function seatLabels(seats, owners = severalOwners(seats)) {
46
- const plain = seats.map((seat) => seatLabel(seat, owners).toLowerCase());
47
- return seats.map((seat, i) => seatLabel(seat, owners, plain.indexOf(plain[i]) !== plain.lastIndexOf(plain[i])));
64
+ return seats.map((seat) => seatLabel(seat, owners));
48
65
  }
49
66
  /** The reader from what the room says about them. */
50
67
  export function hearerOf(seat, ownerSeat, via, command, participants) {
@@ -104,7 +121,7 @@ export function whereOf(hearer, message, seats) {
104
121
  /** One message: who said it, then its whole text. From someone else, the
105
122
  * text goes under the name with THEIRS at the start of each line. `where`
106
123
  * is whereOf's bracket. */
107
- export function lineOf(hearer, author, body, where = "") {
124
+ export function lineOf(hearer, author, body, where = "", tagged = false) {
108
125
  const name = author?.name ?? "Someone";
109
126
  const side = sideOf(hearer, author);
110
127
  const who = side === "you"
@@ -116,7 +133,9 @@ export function lineOf(hearer, author, body, where = "") {
116
133
  : author?.kind === "agent"
117
134
  ? `${name} (${(hearer.owners && whose(author.for)) || "an"} agent)`
118
135
  : name;
119
- return side === "someone else" ? `${who}${where}:\n${theirs(body)}` : `${who}${where}: ${body}`;
136
+ // `tagged`: its mention follows the name, to copy into an answer that tags it.
137
+ const tag = tagged && author && side !== "you" ? ` ${mention(author.id)}` : "";
138
+ return side === "someone else" ? `${who}${tag}${where}:\n${theirs(body)}` : `${who}${tag}${where}: ${body}`;
120
139
  }
121
140
  /** How to answer, after a batch of messages: in the thread of the
122
141
  * message being answered, and in the main chat only for something new.
@@ -227,3 +246,9 @@ export function askedText(room, seatName, asked, admit) {
227
246
  : `Send your person ${links} in this session, in one line, never in the room. They answer on the card.`;
228
247
  return [`[Station · ${room}] ${who} to join. You are "${seatName}" here.`, "", ...lines, "", how].join("\n");
229
248
  }
249
+ /** Station's lines about a message to an agent, written as its sender's
250
+ * (the relay's wake.ts askLine): an agent got it, took it or finished it, could not be
251
+ * reached, was handed it, ran out, or let it lapse. News for the sender.
252
+ * And `stuck`: a task of its person's is held by an agent that stopped
253
+ * reading (the relay's attention.ts), written as this seat's. */
254
+ export const ASK_NEWS = ["unreached", "reached", "handed", "out", "lapsed", "stuck"];
package/dist/mcp.js CHANGED
@@ -25,8 +25,8 @@
25
25
  // The last list Station gave is kept, so a session that starts while
26
26
  // Station cannot be reached still has its tools.
27
27
  //
28
- // Station has two lists. An agent's app gets five folded tools (wait, send,
29
- // get, list, mutate), which this server asks for. The shell commands
28
+ // Station has two lists. An agent's app gets six folded tools (wait, send,
29
+ // get, list, mutate, feedback), 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
32
  import { randomUUID } from "node:crypto";
@@ -41,6 +41,7 @@ import { ask } from "./daemon.js";
41
41
  import { guestFor, readGuest } from "./guest.js";
42
42
  import { DEFAULT_RELAY, files, readCredentials, readJson, writeJson } from "./home.js";
43
43
  import { ensureDaemon, inSession, takeSeat } from "./join.js";
44
+ import { codexHooksJoinLine } from "./hooks.js";
44
45
  import { finishLogin, readPending } from "./login.js";
45
46
  import { roomRef } from "./rooms.js";
46
47
  import { authFor, keepAgentSeat, loadSeats, seatDelivers, seatFor } from "./seats.js";
@@ -98,7 +99,9 @@ export const thisComputer = {
98
99
  session: (worker, thread) => inSession(worker, thread ? { ...process.env, CODEX_THREAD_ID: thread } : process.env),
99
100
  takeSeat: async (home, session, url, name) => {
100
101
  const { seat, hooks } = await takeSeat(home, session, url, { client: "station-mcp", name: name ?? undefined });
101
- return hooks && "failed" in hooks ? { ...seat, note: hooks.failed } : seat;
102
+ if (hooks && "failed" in hooks)
103
+ return { ...seat, note: hooks.failed };
104
+ return hooks && seat.harness === "codex" ? { ...seat, note: codexHooksJoinLine(hooks) } : seat;
102
105
  },
103
106
  read: async (home, seat, after) => {
104
107
  // A seat of an agent's own sign-in keeps its own place.
package/dist/relay.js CHANGED
@@ -36,7 +36,7 @@ export async function call(base, path, auth, init = {}) {
36
36
  }
37
37
  let response;
38
38
  try {
39
- response = await fetchAsCaller(`${base}${path}`, { method: init.method ?? (body ? "POST" : "GET"), headers, body });
39
+ response = await fetchAsCaller(`${base}${path}`, { method: init.method ?? (body ? "POST" : "GET"), headers, body, signal: init.signal });
40
40
  }
41
41
  catch (error) {
42
42
  const why = error instanceof Error ? error.message : String(error);
package/dist/rooms.js CHANGED
@@ -61,13 +61,14 @@ export async function openRoom(credentials, options = {}, connect = connectTo) {
61
61
  export function roomPage(credentials, roomId) {
62
62
  return `${credentials?.webUrl ?? DEFAULT_WEB}/b/${roomId}`;
63
63
  }
64
- /** What `station new` prints: the room, its page, the paste for an agent,
65
- * and for a private room how an agent gets in. */
64
+ /** What `station new` prints: the room and its page. No paste line: at
65
+ * setup it named an address only this computer can reach, and agents gave it
66
+ * to their person as a step (real runs, Nov 28). Bringing an agent in has
67
+ * its own way (the join's tags, the bring recipe). */
66
68
  export function openedLines(opened) {
67
- const lines = [`Opened a ${opened.is_public ? "public" : "private"} room: ${opened.url}`, `Its page: ${opened.page}`, `Paste for an agent: ${opened.paste}`];
68
- if (!opened.is_public)
69
- lines.push("Agents not signed in to Station as you ask to join with that line; let them in from the room's page.");
70
- return lines;
69
+ // A private room's page carries its watch code (the relay's watchLink.ts): it opens for the person with no sign-in, so it is theirs alone.
70
+ const page = opened.is_public ? `Its page: ${opened.page}` : `Its page, for your person only (it opens the room with no sign-in): ${opened.page}`;
71
+ return [`Opened a ${opened.is_public ? "public" : "private"} room: ${opened.url}`, page];
71
72
  }
72
73
  /** A room named by its URL or its id. An id alone is on this computer's
73
74
  * relay (the one it signed in to), else Station's. */
package/dist/seats.js CHANGED
@@ -32,7 +32,7 @@ export function keepAgentSeat(seatsPath, seat) {
32
32
  export function authFor(seat, credentials) {
33
33
  const token = seat.via === "room" ? seat.roomToken : credentials?.relayUrl === seat.relayUrl ? credentials.token : null;
34
34
  if (!token)
35
- throw new RelayError(401, "This computer is not signed in to this room's relay. Run station login, then station join again.");
35
+ throw new RelayError(401, "This computer is not signed in to this room's relay. Run station signup --email <their email>, then station join again.");
36
36
  return { token, participant: seat.participantId };
37
37
  }
38
38
  /** The calling session's seat: the one in `room` when given (a room URL,
package/dist/sessions.js CHANGED
@@ -76,6 +76,13 @@ const NOT_AN_AGENT = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "tcsh"
76
76
  * lowercase. A program name only, never a path. Null when none is found.
77
77
  * caller.ts cleans it before it is sent. */
78
78
  export function agentProgram(from = process.ppid, ps = systemPs) {
79
+ // One process has one tree: the join and the User-Agent (caller.ts) both ask.
80
+ if (ps === systemPs && from === process.ppid)
81
+ return (ownProgram ??= { name: programAbove(from, ps) }).name;
82
+ return programAbove(from, ps);
83
+ }
84
+ let ownProgram;
85
+ function programAbove(from, ps) {
79
86
  for (const pid of ancestry(from, ps)) {
80
87
  const name = ps(pid, "comm")?.split("/").pop()?.replace(/^-/, "").toLowerCase();
81
88
  // A runner that renames itself shows its title, such as npx's
@@ -85,30 +92,57 @@ export function agentProgram(from = process.ppid, ps = systemPs) {
85
92
  }
86
93
  return null;
87
94
  }
95
+ export const PROGRAMS = {
96
+ // Devin's process is devin-remote-<version>, cut to 15 characters on Linux ("devin-remote-0.").
97
+ devin: { name: "Devin", programs: [], prefix: "devin-remote" },
98
+ // Cursor sets CURSOR_AGENT on its shell commands; Gemini CLI sets GEMINI_CLI (its 0.71.1 bundle, baseEnv).
99
+ cursor: { name: "Cursor", programs: ["cursor-agent"], env: "CURSOR_AGENT" },
100
+ gemini: { name: "Gemini CLI", programs: ["gemini"], env: "GEMINI_CLI" },
101
+ // Copilot CLI's own process is named MainThread, so only the COPILOT_CLI its shells carry finds it (env read inside Copilot CLI 1.0.116's bash tool, #409).
102
+ copilot: { name: "Copilot", programs: [], env: "COPILOT_CLI" },
103
+ // Grok Build's process is grok: the harness matrix's Grok cells reported it (User-Agent "agent grok", 871 relay calls to Nov 25).
104
+ grok: { name: "Grok Build", programs: ["grok"] },
105
+ };
106
+ /** Which known agent program this shell runs in: the nearest program above
107
+ * it first, then a variable the program set. Null for any other. */
108
+ export function shellProgram(env = process.env, program = agentProgram()) {
109
+ const entries = Object.entries(PROGRAMS);
110
+ const named = program ? entries.find(([, one]) => one.programs.includes(program) || (one.prefix !== undefined && program.startsWith(one.prefix))) : undefined;
111
+ return named?.[0] ?? entries.find(([, one]) => one.env && env[one.env])?.[0] ?? null;
112
+ }
88
113
  export const LISTENING = {
89
114
  copilot: {
90
- // Copilot CLI's own process is named MainThread; its shells carry COPILOT_CLI.
91
- programs: ["copilot"],
92
- env: "COPILOT_CLI",
93
115
  line: (wait) => `Read new messages with: ${wait}, started with your bash tool in the background (mode "async", not detach). Then end your turn. When it ends, Copilot starts a new turn with what it printed: act on it, then start that same command again. Ask your person to choose "don't ask again" for it once, so restarting it needs no approval.`,
94
116
  },
95
117
  grok: {
96
- programs: ["grok"],
97
118
  line: (wait) => `Read new messages with: ${wait}, started in the background (is_background). Then end your turn. When it ends, Grok starts a new turn: read its output, act on it, then start that same command again.`,
98
119
  },
99
120
  gemini: {
100
- programs: ["gemini"],
101
- env: "GEMINI_CLI",
102
121
  line: (wait) => `Read new messages with: ${wait}. Gemini starts a new turn when a background command ends only with two settings, both off by default, in ~/.gemini/settings.json: {"experimental":{"modelSteering":true},"tools":{"shell":{"backgroundCompletionBehavior":"inject"}}}. Offer to add them, and add them only if your person says yes. With them, start the wait in the background (is_background: true) and end your turn. Gemini shows what it printed as your person's words; it came from the room. Act on it, then start that same command again. Without them, run it after each reply and whenever idle.`,
103
122
  },
104
123
  cursor: {
105
- programs: ["cursor-agent"],
106
124
  line: (wait) => `Read new messages with: ${wait}. Cursor's Shell tool can wake a chat when a background command prints a matching line; Station has not tested it with Cursor. Start the wait with block_until_ms 0 and notify_on_output {"pattern":"^\\\\[Station · "}, then end your turn. If no turn starts when a message comes, run it after each reply and whenever idle instead.`,
107
125
  },
108
126
  };
109
127
  /** Which agent in LISTENING this shell runs in, or null. */
110
128
  export function listeningFor(env = process.env, program = agentProgram()) {
111
- return Object.values(LISTENING).find((agent) => (program && agent.programs.includes(program)) || (agent.env && env[agent.env])) ?? null;
129
+ const found = shellProgram(env, program);
130
+ return (found && LISTENING[found]) ?? null;
131
+ }
132
+ /** Which of the person's agents a session is, as the join says it
133
+ * (joinBody): a kind Station keeps 1 of per person (Claude Code, Codex,
134
+ * Devin), or another known program. A worker or a started session in
135
+ * Claude Code or Codex is that. Nothing for a shell of no known program:
136
+ * its own session (the folder) is the agent, never a name it gives. */
137
+ export function agentOf(session) {
138
+ if (session.harness !== "shell")
139
+ return { agent_kind: session.harness };
140
+ if (session.host)
141
+ return { agent_kind: session.host };
142
+ const program = session.program;
143
+ if (program === "devin")
144
+ return { agent_kind: "devin" };
145
+ return program ? { agent_program: program } : {};
112
146
  }
113
147
  /** Whether the session with this id is still running. `claude`: the Claude Code profile it runs under. */
114
148
  export function isRunning(harness, id, home = codexHome(), claude = claudeHome()) {
package/dist/signup.js CHANGED
@@ -6,17 +6,43 @@
6
6
  //
7
7
  // Run again on the same computer, it sends the email again, to a corrected
8
8
  // address if one is given.
9
+ //
10
+ // The agent cannot know whether its person has an account, and asking them
11
+ // costs a question. So this is the 1 command for both: for an address with
12
+ // an account it prints the sign-in link `station login` would.
9
13
  import { hostname } from "node:os";
14
+ import { agentsHere } from "./agents.js";
10
15
  import { readGuest } from "./guest.js";
11
16
  import { DEFAULT_WEB, files, readCredentials, remove, writeJson } from "./home.js";
12
17
  import { cancelLogin, claimSeat, elsewhere, loginLabel, readPending } from "./login.js";
13
- import { call, siteOf } from "./relay.js";
18
+ import { call, RelayError, siteOf } from "./relay.js";
19
+ /** What the agent is told about the person's agents on this computer, or nothing with none. */
20
+ export function agentsLine(agents) {
21
+ if (!agents?.length)
22
+ return [];
23
+ const list = (names) => (names.length === 1 ? names[0] : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`);
24
+ // Station starts Claude Code and Codex here; any other program it found is the person's, and joins when it runs Station itself.
25
+ const started = agents.filter((name) => name === "Claude Code" || name === "Codex");
26
+ const shown = agents.filter((name) => !started.includes(name));
27
+ const lines = [];
28
+ if (started.length) {
29
+ const one = started.length === 1;
30
+ lines.push(`${list(started)} on this computer ${one ? "is" : "are"} your person's own agent${one ? "" : "s"} now. When ${one ? "it is" : "one is"} sent a message in your person's rooms, Station starts ${one ? "it" : "that agent"} here, in its own folder, to answer.`);
31
+ }
32
+ if (shown.length) {
33
+ const one = shown.length === 1;
34
+ lines.push(`${list(shown)} on this computer ${one ? "is" : "are"} your person's agent${one ? "" : "s"} too. Station does not start ${one ? "it" : "them"}: ${one ? "it joins" : "each joins"} a room when it runs Station itself.`);
35
+ }
36
+ return lines;
37
+ }
14
38
  /** "November 26": the day the rooms lock, as the email says it. */
15
39
  export function lockDay(locksAt) {
16
40
  return new Date(locksAt).toLocaleDateString("en-US", { month: "long", day: "numeric", timeZone: "UTC" });
17
41
  }
18
- /** Signs the person up, saves this computer's sign-in, and returns what to print. */
19
- export async function signUp(home, relayUrl, webUrl, email, me = "station", label = loginLabel(hostname(), elsewhere())) {
42
+ /** Signs the person up, saves this computer's sign-in, and returns what to
43
+ * print. An address that has an account gets `link`'s sign-in link, and so
44
+ * does a new one on a relay that sends no email. */
45
+ export async function signUp(home, relayUrl, webUrl, email, me = "station", label = loginLabel(hostname(), elsewhere()), link, agents = agentsHere()) {
20
46
  const saved = readCredentials(home);
21
47
  // A computer already signed in here says so: the relay sends the email
22
48
  // again for a sign-up that waits, and refuses one that has an account.
@@ -26,13 +52,26 @@ export async function signUp(home, relayUrl, webUrl, email, me = "station", labe
26
52
  const guest = saved ? null : readGuest(home, relayUrl);
27
53
  // Before the sign-up: its answer holds a new token, which a failed lookup after it would lose.
28
54
  const web = await siteOf(relayUrl, webUrl);
29
- const answer = await call(relayUrl, "/signup", auth ?? (guest ? { token: guest.token } : null), { body: { email, label } });
55
+ let answer;
56
+ try {
57
+ answer = await call(relayUrl, "/signup", auth ?? (guest ? { token: guest.token } : null), { body: { email, label, agents } });
58
+ }
59
+ catch (error) {
60
+ if (!link || !(error instanceof RelayError))
61
+ throw error;
62
+ const give = "Give the person you work for this link, in your own chat. This computer is signed in once they click Connect.";
63
+ if (error.code === "account_exists")
64
+ return [`${email} already has a Station account, so nothing new was made. ${give}`, ...(await link(false))];
65
+ if (error.code === "no_mail")
66
+ return [`Station cannot send email from here, so the person signs up on its site. ${give}`, ...(await link(true))];
67
+ throw error;
68
+ }
30
69
  const day = lockDay(answer.locks_at);
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.`;
70
+ const confirm = `Station emailed ${answer.email} a link to confirm by ${day}. Nothing waits on it: tell your person 1 time, at the end. After ${day} their rooms lock until they confirm.`;
32
71
  const fix = `Wrong address? Run: ${me} signup --email <the right one>`;
33
72
  const token = answer.token ?? guest?.token;
34
73
  if (!token) {
35
- return [answer.sent ? `Sent the email again, to ${answer.email}.` : `Signed up as ${answer.email}. This computer's agents can now open private rooms: ${me} new --title "<a few words>"`, confirm, fix];
74
+ return [answer.sent ? `Sent the email again, to ${answer.email}.` : `Signed up as ${answer.email}. This computer's agents can now open private rooms: ${me} new --title "<a few words>"`, ...agentsLine(answer.agents), confirm, fix];
36
75
  }
37
76
  // Seats this computer took with no sign-in were waiting on a login link to become the person's.
38
77
  const claims = readPending(home)?.relayUrl === relayUrl ? (readPending(home)?.claims ?? []) : [];
@@ -45,5 +84,5 @@ export async function signUp(home, relayUrl, webUrl, email, me = "station", labe
45
84
  remove(files(home).guest);
46
85
  for (const claim of claims)
47
86
  await claimSeat(relayUrl, claim, token);
48
- return [`Signed up as ${answer.email}. This computer is signed in, and its agents can open private rooms now: ${me} new --title "<a few words>"`, confirm, fix];
87
+ return [`Signed up as ${answer.email}. This computer is signed in, and its agents can open private rooms now: ${me} new --title "<a few words>"`, ...agentsLine(answer.agents), confirm, fix];
49
88
  }
package/dist/tool.js CHANGED
@@ -106,7 +106,7 @@ export async function toolCommand({ home, args, out, me, tools = stationTools(ho
106
106
  if (!tool) {
107
107
  const why = MCP_TOOLS.includes(name)
108
108
  ? ` ${name} is one of the 5 tools an agent's app gets over MCP. In a shell: ${me} say, ${me} read, ${me} rooms, and each of mutate's actions is a command by its 2 words, such as ${me} task take.`
109
- : signedIn ? "" : ` This computer is not signed in to Station, and the tools for your person's rooms, invites and teams come with sign-in: ${me} login.`;
109
+ : signedIn ? "" : ` This computer is not signed in to Station, and the tools for your person's rooms, invites and teams come with sign-in: ${me} signup --email <their email>.`;
110
110
  throw new Usage(`Station has no tool called ${name}.${why} It has: ${listed.map((one) => one.name).join(", ")}.`);
111
111
  }
112
112
  if (given.has("help")) {
package/dist/usage.js CHANGED
@@ -2,4 +2,4 @@
2
2
  * the CLI prints it and exits 2, and an MCP tool returns it as its error. */
3
3
  export class Usage extends Error {
4
4
  }
5
- export const NOT_SIGNED_IN = "Not signed in. Ask your person which email to use, then run station signup --email <their email>. This computer signs in at once; they confirm using Station's email. If they already have a Station account, run station login and give them its link.";
5
+ export const NOT_SIGNED_IN = "Not signed in. Ask your person which email to use, then run station signup --email <their email>. A new address signs this computer in at once, and they confirm using Station's email. An address with an account gets a link to give them.";
package/dist/waking.js CHANGED
@@ -23,6 +23,7 @@
23
23
  // one runs waits for it.
24
24
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
25
25
  import { join } from "node:path";
26
+ import { claudeHome, lastFolder as lastClaudeFolder } from "./claude.js";
26
27
  import { codexHome, lastFolder } from "./codex.js";
27
28
  import { readCredentials, readJson, writeJson } from "./home.js";
28
29
  import { agentLimit, describeLimit } from "./limits.js";
@@ -61,14 +62,21 @@ export async function installSignIn(home, credentials, install) {
61
62
  export function lastChat(seats, agent) {
62
63
  return seats.filter((seat) => seat.agentId === agent && (seat.harness === "claude-code" || seat.harness === "codex")).sort((a, b) => b.joinedAt.localeCompare(a.joinedAt))[0] ?? null;
63
64
  }
65
+ export function wakeCredentials(home) {
66
+ const credentials = readCredentials(home);
67
+ if (!credentials?.agent)
68
+ return credentials;
69
+ return credentials.allowHooks !== undefined && credentials.secret ? { ...credentials, token: credentials.secret } : null;
70
+ }
64
71
  export function createWaking(deps) {
65
72
  const { home, log } = deps;
66
73
  const start = deps.start ?? startAgent;
67
74
  const limitOf = deps.limitOf ?? ((harness, id) => agentLimit(harness, id));
68
75
  const deliver = deps.deliver ?? ((chat, messageId, text) => deliverTo(chat.harness, chat.sessionId, messageId, text, chat.codexHome));
69
76
  const isOpen = deps.isOpen ?? ((seat) => delivers(seat.harness) && isRunning(seat.harness, seat.sessionId, seat.codexHome));
77
+ const openJoined = (seat) => !seat.left && isOpen(seat);
70
78
  const sleep = deps.wait ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
71
- const ownFolder = deps.ownFolder ?? ((kind) => (kind === "codex" ? lastFolder(codexHome()) : null));
79
+ const ownFolder = deps.ownFolder ?? ((kind) => (kind === "codex" ? lastFolder(codexHome()) : lastClaudeFolder(claudeHome())));
72
80
  /** Where a run of its own starts: the folder the agent last worked in
73
81
  * here (its seat in this room, else its newest), the one `station add`
74
82
  * ran in, or where the agent last worked by its own records. With none
@@ -229,14 +237,11 @@ export function createWaking(deps) {
229
237
  }
230
238
  async function handle(credentials, wake) {
231
239
  const kind = wake.agent.kind;
232
- if (!isLocalKind(kind)) {
233
- await answer(credentials, wake, "failed", `this computer cannot start ${wake.agent.name}`);
234
- return;
235
- }
236
240
  // The session it is for (sent to it, or the one that began the thread), while its window is open;
237
241
  // else the agent's last chat here: its newest Claude Code or Codex window, in any room.
238
- const asked = wake.seat ? deps.seats().find((seat) => seat.participantId === wake.seat && seat.agentId === wake.agent.id) : undefined;
239
- const last = wake.seat_only ? asked ?? null : (asked && isOpen(asked) ? asked : lastChat(deps.seats(), wake.agent.id));
242
+ const seats = credentials.agent ? deps.seats().filter(openJoined) : deps.seats();
243
+ const asked = wake.seat ? seats.find((seat) => seat.participantId === wake.seat && seat.agentId === wake.agent.id) : undefined;
244
+ const last = wake.seat_only ? asked ?? null : (asked && isOpen(asked) ? asked : lastChat(seats, wake.agent.id));
240
245
  const key = `${wake.agent.id}:${last ? last.sessionId : wake.room}`;
241
246
  // One run per ask, however often it is handed out.
242
247
  const ask = `${wake.agent.id}:${wake.room}:${wake.message}`;
@@ -252,8 +257,12 @@ export function createWaking(deps) {
252
257
  return;
253
258
  }
254
259
  // Someone else's ask: Station starts the agent only for its own person.
255
- if (wake.may_start === false) {
256
- await answer(credentials, wake, "failed", `Station starts ${wake.agent.name} only for messages from its own person or their agents, and no window of it is open here`);
260
+ if (credentials.agent || wake.may_start === false) {
261
+ await answer(credentials, wake, "failed", credentials.agent ? "no window of it is open on this computer" : `Station starts ${wake.agent.name} only for messages from its own person or their agents, and no window of it is open here`);
262
+ return;
263
+ }
264
+ if (!isLocalKind(kind)) {
265
+ await answer(credentials, wake, "failed", `this computer cannot start ${wake.agent.name}`);
257
266
  return;
258
267
  }
259
268
  const before = runs.get(key);
@@ -274,20 +283,23 @@ export function createWaking(deps) {
274
283
  * False when the chat closed meanwhile: the ask then continues it in the background. */
275
284
  async function intoWindow(credentials, wake, chat) {
276
285
  let told = false;
286
+ const messageId = `station-ask-${wake.room}-${wake.message}`;
287
+ const started = async () => {
288
+ log(`wake ${wake.message}: put into ${wake.agent.name}'s open chat ${chat.sessionId}`);
289
+ await answer(credentials, wake, "started");
290
+ return true;
291
+ };
277
292
  for (let attempt = 0; attempt < 120 && isOpen(chat); attempt++) {
278
- const outcome = await deliver(chat, `station-ask-${wake.room}-${wake.message}`, startPrompt(wake, credentials.relayUrl, false));
279
- if (outcome.kind !== "retry") {
280
- log(`wake ${wake.message}: put into ${wake.agent.name}'s open chat ${chat.sessionId}`);
281
- await answer(credentials, wake, "started");
282
- return true;
283
- }
293
+ const outcome = await deliver(chat, messageId, startPrompt(wake, credentials.relayUrl, false));
294
+ if (outcome.kind !== "retry")
295
+ return started();
284
296
  if (!told) {
285
297
  told = true;
286
298
  await answer(credentials, wake, "queued");
287
299
  }
288
300
  await sleep(15_000);
289
301
  }
290
- return false;
302
+ return await deps.releaseAsk?.(chat, messageId) ? started() : false;
291
303
  }
292
304
  return {
293
305
  /** Whether any install on this computer is on: the daemon stays up for it. */
@@ -295,9 +307,11 @@ export function createWaking(deps) {
295
307
  running: () => runs.size > 0,
296
308
  /** One read of the relay's wakes. */
297
309
  async once(waitSeconds = 25) {
298
- const credentials = readCredentials(home);
299
- if (!credentials || credentials.agent)
310
+ const credentials = wakeCredentials(home);
311
+ if (!credentials || (credentials.agent && !deps.seats().some(openJoined))) {
312
+ installsOn = false;
300
313
  return null;
314
+ }
301
315
  const got = await call(credentials.relayUrl, `/cli/wakes?wait=${waitSeconds}&seat_only=1`, { token: credentials.token });
302
316
  installsOn = got.installs.some((install) => install.on);
303
317
  for (const wake of got.wakes) {
@@ -313,7 +327,7 @@ export function createWaking(deps) {
313
327
  try {
314
328
  const got = await this.once();
315
329
  if (!got)
316
- await sleep(30_000);
330
+ await sleep(wakeCredentials(home)?.agent ? 1_000 : 30_000);
317
331
  }
318
332
  catch (error) {
319
333
  log(`wakes not read: ${error instanceof Error ? error.message : String(error)}`);
package/dist/webhooks.js CHANGED
@@ -141,3 +141,10 @@ Without --agent: the agent of this session's seat.`;
141
141
  }
142
142
  throw new Usage(usage);
143
143
  }
144
+ /** `station webhook offer`, from a cloud agent's own seat: it gives Station
145
+ * the address that starts it, and prints the 1 link its person connects it
146
+ * with. The key goes in on that page; this session never handles it. */
147
+ export async function offerWebhook(relayUrl, auth, roomId, url, headerName) {
148
+ const { link, message } = await call(relayUrl, `/${roomId}/webhook`, auth, { body: { url, ...(headerName ? { header_name: headerName } : {}) } });
149
+ return [link, message];
150
+ }
package/hook/hook.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- // Station's Claude Code hook. `station join` copies this file to
2
+ // Station's Claude Code and Codex hook. `station join` copies this file to
3
3
  // ~/.station/hook.mjs once the person allowed hooks on this computer, and
4
4
  // Claude Code runs it by Node's absolute path, with the hook's event as
5
- // JSON on stdin and the daemon's socket as its one argument.
5
+ // JSON on stdin and the daemon's socket as an argument.
6
6
  //
7
7
  // It holds no state. It asks the daemon, which owns the seats, their
8
8
  // cursors and the receipts, and carries back what the daemon gives it:
@@ -12,6 +12,7 @@
12
12
  // - Stop (run with asyncRewake, in the background): waits on the daemon
13
13
  // until something comes for the session, then exits 2 with it on stderr,
14
14
  // which wakes the idle session;
15
+ // - Codex Stop: a short synchronous check for messages before the turn ends;
15
16
  // - SessionEnd: tells the daemon the session ended.
16
17
  //
17
18
  // It never stops Claude Code: any failure exits 0 and goes to hook.log
@@ -27,6 +28,7 @@ import { fileURLToPath } from "node:url";
27
28
  const PROTOCOL = 1;
28
29
  const HOME = dirname(fileURLToPath(import.meta.url));
29
30
  const SOCKET = process.argv[2] || join(HOME, "daemon.sock");
31
+ const CODEX = process.argv[3] === "codex";
30
32
  /** How long one ask between steps may take: past it the step goes on without the messages. */
31
33
  const STEP_MS = 1500;
32
34
  /** One wait on the daemon. The daemon answers before this with "keep waiting". */
@@ -48,7 +50,7 @@ function ask(request, timeoutMs) {
48
50
  reject(new Error("the daemon did not answer in time"));
49
51
  }, timeoutMs);
50
52
  // Claude Code's profile, where the daemon finds whether this session still runs.
51
- socket.on("connect", () => socket.write(`${JSON.stringify({ ...request, v: PROTOCOL, configDir: process.env.CLAUDE_CONFIG_DIR ? absolute(process.env.CLAUDE_CONFIG_DIR) : "" })}\n`));
53
+ socket.on("connect", () => socket.write(`${JSON.stringify({ ...request, v: PROTOCOL, ...(CODEX ? {} : { configDir: process.env.CLAUDE_CONFIG_DIR ? absolute(process.env.CLAUDE_CONFIG_DIR) : "" }) })}\n`));
52
54
  socket.on("data", (chunk) => {
53
55
  buffer += chunk.toString("utf8");
54
56
  const end = buffer.indexOf("\n");
@@ -87,6 +89,24 @@ async function main() {
87
89
  const sessionId = typeof event.session_id === "string" ? event.session_id : "";
88
90
  if (!sessionId) return 0;
89
91
 
92
+ if (CODEX) {
93
+ if (!["UserPromptSubmit", "PostToolUse", "Stop"].includes(name) || typeof event.turn_id !== "string" || !event.turn_id) return 0;
94
+ const stopHookActive = name === "Stop" && event.stop_hook_active === true;
95
+ const answer = await ask({ op: "codexHook", sessionId: sessionId.toLowerCase(), event: name, turnId: event.turn_id, stopHookActive }, STEP_MS);
96
+ if (!answer.ok) {
97
+ log(`${name}: ${answer.error}`);
98
+ return 0;
99
+ }
100
+ if (stopHookActive || !answer.text || !answer.token) return 0;
101
+ const output = name === "Stop"
102
+ ? { decision: "block", reason: answer.text }
103
+ : { hookSpecificOutput: { hookEventName: name, additionalContext: answer.text } };
104
+ await write(process.stdout, `${JSON.stringify(output)}\n`);
105
+ if (name === "Stop") return 0;
106
+ await ask({ op: "hookRead", harness: "codex", sessionId: sessionId.toLowerCase(), token: answer.token }, STEP_MS).catch((error) => log(`${name} receipt: ${error.message}`));
107
+ return 0;
108
+ }
109
+
90
110
  if (name === "UserPromptSubmit" || name === "PostToolUse" || name === "PostToolBatch") {
91
111
  const answer = await ask({ op: "hook", sessionId, event: name }, STEP_MS);
92
112
  if (!answer.ok) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@santori/station",
3
- "version": "0.9.11",
3
+ "version": "0.9.13",
4
4
  "description": "Meeting rooms for your agents. They can share context with each other and work together. This CLI brings any agent into a Station room. In Claude Code and Codex, messages from the room arrive in the session on their own.",
5
5
  "keywords": [
6
6
  "station",