@santori/station 0.9.10 → 0.9.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/commands.js CHANGED
@@ -7,7 +7,9 @@
7
7
  // A tool is offered as a command when its listing carries
8
8
  // _meta "station/cli": { command, args, stdin?, usage }. `command` is the
9
9
  // word after `station`, or two words ("board ls") for one of a group, and
10
- // `station board` alone lists the group; `args` are the inputs given in order without a
10
+ // `station board` alone lists the group; `aliases` are other words for it
11
+ // ({ "take": "task take" }: `station take 12` runs `station task take 12`);
12
+ // `args` are the inputs given in order without a
11
13
  // flag; every other input is --its-name (an input named if_rev is
12
14
  // --if-rev; a list of objects takes each as JSON); `stdin` names the input read from stdin when it is not given,
13
15
  // and that input also takes @<path> for a file's text. What the flags are,
@@ -15,13 +17,15 @@
15
17
  // schema and answer, so a new command or a new flag needs only a relay
16
18
  // deploy.
17
19
  import { readFileSync } from "node:fs";
20
+ import { distance } from "./args.js";
18
21
  import { files, readJson } from "./home.js";
19
22
  import { Usage } from "./usage.js";
20
23
  export function cliOf(tool) {
21
24
  const meta = tool._meta?.["station/cli"];
22
25
  if (!meta || typeof meta.command !== "string" || !/^[a-z][a-z0-9-]*( [a-z][a-z0-9-]*)?$/.test(meta.command))
23
26
  return null;
24
- return { command: meta.command, args: Array.isArray(meta.args) ? meta.args.filter((arg) => typeof arg === "string") : [], stdin: typeof meta.stdin === "string" ? meta.stdin : undefined, usage: typeof meta.usage === "string" ? meta.usage : undefined };
27
+ const aliases = Object.fromEntries(Object.entries(meta.aliases ?? {}).filter(([word, means]) => /^[a-z][a-z0-9-]*$/.test(word) && typeof means === "string"));
28
+ return { command: meta.command, args: Array.isArray(meta.args) ? meta.args.filter((arg) => typeof arg === "string") : [], stdin: typeof meta.stdin === "string" ? meta.stdin : undefined, usage: typeof meta.usage === "string" ? meta.usage : undefined, aliases };
25
29
  }
26
30
  /** The tools Station listed last, without asking it. */
27
31
  export function cachedTools(home) {
@@ -32,13 +36,44 @@ export function commandNamed(tools, command) {
32
36
  return tools.find((tool) => cliOf(tool)?.command === command) ?? null;
33
37
  }
34
38
  /** The command the words after `station` start with, two words before
35
- * one, and the words left for it. */
36
- export function commandFrom(tools, argv) {
37
- const two = argv.length > 1 ? commandNamed(tools, `${argv[0]} ${argv[1]}`) : null;
39
+ * one, and the words left for it. A first word that is another word for a
40
+ * command (`take` for "task take") is read as the words it stands for. */
41
+ export function commandFrom(tools, argv, aliased = false) {
42
+ // An action's second word as mutate spells it: `room claim_link` is "room claim-link".
43
+ const two = argv.length > 1 ? commandNamed(tools, `${argv[0]} ${argv[1].replace(/_/g, "-")}`) : null;
38
44
  if (two)
39
45
  return { tool: two, rest: argv.slice(2) };
40
46
  const one = argv.length ? commandNamed(tools, argv[0]) : null;
41
- return one ? { tool: one, rest: argv.slice(1) } : null;
47
+ if (one)
48
+ return { tool: one, rest: argv.slice(1) };
49
+ const means = aliased || !argv.length ? undefined : tools.map((tool) => cliOf(tool)?.aliases[argv[0]]).find(Boolean);
50
+ return means ? commandFrom(tools, [...means.split(" "), ...argv.slice(1)], true) : null;
51
+ }
52
+ /** The command a mistyped word most likely is, or null. Stricter than for
53
+ * a flag, since following a wrong guess runs another command (`log` must
54
+ * not suggest `logout`): the word with letters after it (`tasks`), the
55
+ * first 4 letters or more of one, or 1 letter off (2 in a word of 7 or more). */
56
+ function closestCommand(word, known) {
57
+ const starts = known.filter((one) => (one.length >= 3 && word.startsWith(one)) || (word.length >= 4 && one.startsWith(word))).sort((a, b) => b.length - a.length)[0];
58
+ if (starts)
59
+ return starts;
60
+ const near = known.map((one) => ({ one, far: distance(word, one) })).sort((a, b) => a.far - b.far)[0];
61
+ return near && near.far <= (word.length >= 7 ? 2 : 1) ? near.one : null;
62
+ }
63
+ /** The MCP tool whose shell command has another word: agents that read
64
+ * Station's MCP tools typed `station send`. */
65
+ const MCP_WORDS = { send: "say" };
66
+ /** What a word that is no command gets back: the closest real command,
67
+ * then the names only. The whole help is over 5 KB, and an agent asked
68
+ * for none of it. `own`: the CLI's own commands, as the help lists them. */
69
+ export function unknownCommand(me, word, own, tools) {
70
+ const offered = tools.flatMap((tool) => cliOf(tool)?.command ?? []);
71
+ const groups = [...new Set(offered.map((command) => command.split(" ")[0]))];
72
+ const aliases = tools.flatMap((tool) => Object.keys(cliOf(tool)?.aliases ?? {}));
73
+ const typed = word.toLowerCase().replace(/_/g, "-");
74
+ // What Station's MCP tools call it, then the second word of a command typed alone (`done` is "task done").
75
+ const near = MCP_WORDS[typed] ?? offered.find((command) => command.split(" ")[1] === typed) ?? closestCommand(typed, [...own, ...groups, ...aliases]);
76
+ return `Unknown command: ${word}.${near ? ` Did you mean ${me} ${near}?` : ""} The commands: ${[...new Set([...own, ...groups])].join(", ")}. ${me} help says what each does.`;
42
77
  }
43
78
  /** The tools whose command is one of this group: `board` for "board ls". */
44
79
  export function groupOf(tools, group) {
@@ -117,14 +152,29 @@ export function commandHelp(me, tool) {
117
152
  }
118
153
  return lines.join("\n");
119
154
  }
120
- /** The lines `station help` adds for the commands Station defines. */
121
- export function commandLines(me, tools) {
155
+ /** The lines `station help` adds for the commands Station defines. A
156
+ * command with no usage line of its own is named under its first word
157
+ * only, on one line for all of that word's: there are 30 of them for a
158
+ * person's rooms, teams and agents, and `station team` lists a word's in
159
+ * full. `full`: every command on its own line, as that listing has them. */
160
+ export function commandLines(me, tools, full = false) {
122
161
  const offered = tools.filter((tool) => cliOf(tool));
123
162
  if (!offered.length)
124
163
  return [];
125
- const starts = offered.map((tool) => ` ${me} ${cliOf(tool).command} ${cliOf(tool).args.map((arg) => (required(tool).includes(arg) ? `<${arg}>` : `[${arg}]`)).join(" ")}`.trimEnd());
126
- const width = Math.max(...starts.map((start) => start.length)) + 2;
127
- return ["", `From Station itself (${me} <command> --help for each one's flags):`, ...offered.map((tool, index) => `${starts[index].padEnd(width)}${cliOf(tool).usage ?? tool.title ?? ""}`)];
164
+ const own = offered.filter((tool) => full || cliOf(tool).usage);
165
+ const starts = own.map((tool) => ` ${me} ${cliOf(tool).command} ${cliOf(tool).args.map((arg) => (required(tool).includes(arg) ? `<${arg}>` : `[${arg}]`)).join(" ")}`.trimEnd());
166
+ const width = Math.max(0, ...starts.map((start) => start.length)) + 2;
167
+ const rest = new Map();
168
+ for (const tool of offered.filter((one) => !own.includes(one))) {
169
+ const [first, second] = cliOf(tool).command.split(" ");
170
+ rest.set(first, [...(rest.get(first) ?? []), second ?? ""]);
171
+ }
172
+ return [
173
+ "",
174
+ `From Station itself (${me} <command> --help for each one's flags):`,
175
+ ...own.map((tool, index) => `${starts[index].padEnd(width)}${cliOf(tool).usage ?? tool.title ?? ""}`),
176
+ ...(rest.size ? [`For your person's rooms, teams and agents, when they ask (${me} <first word> lists what each does):`, ...[...rest].map(([first, seconds]) => ` ${me} ${first} ${seconds.filter(Boolean).join("|")}`.trimEnd())] : []),
177
+ ];
128
178
  }
129
179
  export const reads = {
130
180
  file: (path) => readFileSync(path, "utf8"),
@@ -158,9 +208,13 @@ export async function inputsFrom(me, tool, argv, io = reads) {
158
208
  const prop = known[name];
159
209
  let given = match[2];
160
210
  if (given === undefined) {
161
- // A yes-or-no flag stands alone; any other takes the next word.
211
+ // A yes-or-no flag stands alone; any other takes the next word. In a
212
+ // command with nothing left to give without a flag, the true or false
213
+ // after it is its value (`room invite --on false`, as agents type an
214
+ // action's input). Elsewhere that word is the next thing given
215
+ // (`board grep --ignore-case true` searches for "true").
162
216
  if (allows(prop, "boolean") && !allows(prop, "string") && !allows(prop, "number"))
163
- given = "true";
217
+ given = positional.length >= cli.args.length && (argv[i + 1] === "true" || argv[i + 1] === "false") ? argv[++i] : "true";
164
218
  else if (i + 1 < argv.length)
165
219
  given = argv[++i];
166
220
  else
package/dist/daemon.js CHANGED
@@ -18,8 +18,17 @@
18
18
  // Claude Code and Codex: it reads the relay's wakes and starts an agent
19
19
  // with no window open for an ask to it (waking.ts, starts.ts).
20
20
  //
21
+ // A Claude Code session with Station's hooks (hooks.ts, hook/hook.mjs) gets
22
+ // its messages from them instead, one path at a time: between the steps of
23
+ // a turn the hook asks for what is new, and when the turn ends its Stop hook
24
+ // waits here in the background and wakes the session with what comes. A
25
+ // message is held by one path only: the hook's, or the old one above for a
26
+ // session with no hook running (no hooks, or a turn that ended without a
27
+ // Stop), never both.
28
+ //
21
29
  // Commands talk to it over ~/.station/daemon.sock, one JSON line each way.
22
30
  // It is the only writer of seats.json.
31
+ import { randomUUID } from "node:crypto";
23
32
  import { appendFileSync, chmodSync, existsSync } from "node:fs";
24
33
  import { createServer, connect } from "node:net";
25
34
  import { homedir } from "node:os";
@@ -28,9 +37,11 @@ import { VERSION, selfCommand } from "./self.js";
28
37
  import { freshGuard, throughOf } from "./guard.js";
29
38
  import { handOver, heldRead, heldWaiting, messagesById, readHeld } from "./handover.js";
30
39
  import { ensureHome, files, readCredentials, remove, writeJson } from "./home.js";
40
+ import { HOOK_PROTOCOL, hooksAllowed } from "./hooks.js";
31
41
  import { call, seatOver } from "./relay.js";
32
42
  import { authFor, loadSeats, roomLabel, withOwner } from "./seats.js";
33
43
  import { HARNESS_NAMES, delivers, deliverTo, isRunning } from "./sessions.js";
44
+ import { claudeHome } from "./claude.js";
34
45
  import { clearJoinRequest, daemonEnv, joinRoom } from "./join.js";
35
46
  import { createWaking } from "./waking.js";
36
47
  const SAFETY_MS = 30_000;
@@ -42,6 +53,15 @@ const IDLE_EXIT_MS = 30 * 60_000;
42
53
  /** How long `station wait` has to write out held messages before the
43
54
  * daemon may deliver them itself. */
44
55
  const LENT_MS = 15_000;
56
+ /** A session in a turn whose hooks have said nothing for this long (a turn
57
+ * interrupted at the keyboard ends with no Stop) gets its messages the old
58
+ * way again, which waits for the turn to end by itself. */
59
+ const BUSY_MS = 10 * 60_000;
60
+ /** How long one wait of a Stop hook lasts before the daemon says "keep waiting". */
61
+ const HOOK_WAIT_MS = 25_000;
62
+ /** What the board says while its person keeps messages from reaching the session. */
63
+ /** About as much text as one hook hands over: a batch longer than this goes in whole messages over several steps. */
64
+ const HOOK_TEXT_CHARS = 9_000;
45
65
  const keyOf = (seat) => `${seat.sessionId}:${seat.roomId}`;
46
66
  export async function runDaemon(home) {
47
67
  // It inherits the folder of whichever session started it, which may be
@@ -82,6 +102,32 @@ export async function runDaemon(home) {
82
102
  const waitingSent = new Map();
83
103
  /** Seats whose held messages `station wait` is writing out, and until when. */
84
104
  const lent = new Map();
105
+ /** Sessions in a turn, by their hook's word, and until when that word holds. */
106
+ const busy = new Map();
107
+ /** The Claude Code profile each session's hook runs under, by its own
108
+ * CLAUDE_CONFIG_DIR: the session's registry entry is there, not always
109
+ * in the daemon's. */
110
+ const claudeHomes = new Map();
111
+ const running = (seat) => isRunning(seat.harness, seat.sessionId, seat.codexHome, claudeHomes.get(seat.sessionId));
112
+ /** Sessions whose Stop hook waits here, and how to tell it something came. */
113
+ const waiters = new Map();
114
+ /** What each device-linked seat last told the relay about its window. */
115
+ const openSaid = new Map();
116
+ const tellOpen = (seat, open) => {
117
+ const key = keyOf(seat);
118
+ const body = windowOpenReport(openSaid, key, seat, readCredentials(home), open);
119
+ if (!body)
120
+ return;
121
+ void seatCall(seat, "/delivery", { body }).catch((error) => {
122
+ // Said again on the next tick.
123
+ openSaid.delete(key);
124
+ log(`${key} window ${open ? "open" : "closed"} not told: ${error instanceof Error ? error.message : String(error)}`);
125
+ });
126
+ };
127
+ /** Seats with something that may be new, kept for the session's hook. */
128
+ const forHook = new Set();
129
+ /** What a hook was given and has not yet said it wrote out. */
130
+ const hookLent = new Map();
85
131
  async function seatCall(seat, path, init) {
86
132
  const credentials = readCredentials(home);
87
133
  const secret = credentials?.allowHooks !== undefined ? credentials.secret : undefined;
@@ -116,22 +162,35 @@ export async function runDaemon(home) {
116
162
  }
117
163
  return room.participants;
118
164
  };
119
- /** Reads a seat's room for the hand-over: its people, and held messages again by id. */
120
- const roomOf = (key) => ({
121
- participants: (authors) => participantsFor(find(key), authors),
122
- messages: (ids) => {
123
- const seat = find(key);
124
- return messagesById(ids, (after) => seatCall(seat, `/messages?after=${after}&all=1`));
125
- },
165
+ /** Reads a seat's room for the hand-over: its people, and held messages
166
+ * again by id. As that seat, even when it left meanwhile: its caller then
167
+ * hands nothing over. */
168
+ const roomOf = (seat) => ({
169
+ participants: (authors) => participantsFor(seat, authors),
170
+ messages: (ids) => messagesById(ids, (after) => seatCall(seat, `/messages?after=${after}&all=1`)),
126
171
  });
127
172
  async function pump(key) {
128
173
  // A shell's agent reads for itself with station wait.
129
174
  const target = find(key);
130
175
  if (target && !delivers(target.harness))
131
176
  return;
132
- // `station wait` is writing the held messages out: do not deliver them too.
177
+ // `station wait` or the hook is writing messages out: do not deliver them too.
133
178
  if ((lent.get(key) ?? 0) > Date.now())
134
179
  return;
180
+ if (target) {
181
+ // In a turn, by its hook's word: the hook hands them over between steps.
182
+ if ((busy.get(target.sessionId) ?? 0) > Date.now()) {
183
+ forHook.add(key);
184
+ return;
185
+ }
186
+ // Its Stop hook waits: it takes them and wakes the session.
187
+ const poke = waiters.get(target.sessionId);
188
+ if (poke) {
189
+ forHook.add(key);
190
+ poke();
191
+ return;
192
+ }
193
+ }
135
194
  if (pumping.has(key)) {
136
195
  again.add(key);
137
196
  return;
@@ -145,19 +204,19 @@ export async function runDaemon(home) {
145
204
  break;
146
205
  const before = seat.guard ?? freshGuard();
147
206
  const otherRooms = seats.some((s) => s.sessionId === seat.sessionId && s.roomId !== seat.roomId);
148
- const result = await handOver(() => find(key) ?? seat, before, answer, roomOf(key), Date.now(), selfCommand(), otherRooms);
207
+ const result = await handOver(() => find(key) ?? seat, before, answer, roomOf(seat), Date.now(), selfCommand(), otherRooms);
149
208
  const { text, handed, guard } = result;
150
209
  seat = find(key);
151
210
  if (!seat)
152
211
  break;
153
212
  if (text) {
154
- if (!delivers(seat.harness) || !isRunning(seat.harness, seat.sessionId)) {
213
+ if (!delivers(seat.harness) || !running(seat)) {
155
214
  // The tick decides whether it ended.
156
215
  if (handed)
157
216
  report(seat, { waiting: `The ${HARNESS_NAMES[seat.harness]} session is not open.` });
158
217
  break;
159
218
  }
160
- const outcome = await deliverTo(seat.harness, seat.sessionId, `station-${seat.roomId}-${answer.next_after}-${result.lastId}`, text);
219
+ const outcome = await deliverTo(seat.harness, seat.sessionId, `station-${seat.roomId}-${answer.next_after}-${result.lastId}`, text, seat.codexHome);
161
220
  if (outcome.kind === "retry") {
162
221
  log(`${key} not delivered, will retry: ${outcome.reason}`);
163
222
  if (handed)
@@ -245,6 +304,7 @@ export async function runDaemon(home) {
245
304
  function add(joined) {
246
305
  const key = keyOf(joined);
247
306
  closers.get(key)?.();
307
+ openSaid.delete(key);
248
308
  // Joining again keeps what the loop guard holds: those messages are not lost.
249
309
  const held = find(key)?.guard;
250
310
  const seat = held ? { ...joined, guard: held } : joined;
@@ -260,8 +320,12 @@ export async function runDaemon(home) {
260
320
  closers.get(key)?.();
261
321
  closers.delete(key);
262
322
  waitingSent.delete(key);
323
+ openSaid.delete(key);
263
324
  lent.delete(key);
325
+ forHook.delete(key);
326
+ hookLent.delete(key);
264
327
  people.delete(key);
328
+ // Its Stop hook stops waiting when it asks again and finds no seat.
265
329
  seats = seats.map((s) => keyOf(s) === key ? { ...s, left: true } : s);
266
330
  save();
267
331
  if (!seats.some((s) => !s.left))
@@ -283,7 +347,7 @@ export async function runDaemon(home) {
283
347
  return { text: null, ids: [] };
284
348
  pumping.add(key);
285
349
  try {
286
- const read = await readHeld(seat, seat.guard, roomOf(key), selfCommand());
350
+ const read = await readHeld(seat, seat.guard, roomOf(seat), selfCommand());
287
351
  // Nothing left of them in the room: there is nothing to write out.
288
352
  if (!read.text)
289
353
  tookHeld(key, read.ids);
@@ -297,6 +361,84 @@ export async function runDaemon(home) {
297
361
  void pump(key);
298
362
  }
299
363
  }
364
+ /** What is new for one seat, for its session's hook. Like one round of
365
+ * the pump, but the text goes back to the hook, and the seat's position
366
+ * moves only when the hook says it wrote the text out (`hookTook`). No
367
+ * word within LENT_MS and the pump has the messages again. */
368
+ async function hookPull(key, token, how) {
369
+ // Nothing changed in the room since the last look: no call to the relay.
370
+ if (!forHook.delete(key))
371
+ return null;
372
+ while (pumping.has(key))
373
+ await new Promise((resolve) => setTimeout(resolve, 50));
374
+ const seat = find(key);
375
+ if (!seat || (lent.get(key) ?? 0) > Date.now())
376
+ return null;
377
+ pumping.add(key);
378
+ try {
379
+ let answer = await seatCall(seat, `/messages?after=${seat.after}`);
380
+ const before = seat.guard ?? freshGuard();
381
+ const otherRooms = seats.some((s) => s.sessionId === seat.sessionId && s.roomId !== seat.roomId);
382
+ const handOut = () => handOver(() => find(key) ?? seat, before, answer, roomOf(seat), Date.now(), selfCommand(), otherRooms, true);
383
+ let result = await handOut();
384
+ // A full page, or more than one hook's text: there is more to read on the hook's next run.
385
+ if (answer.messages.length >= 100)
386
+ forHook.add(key);
387
+ // Whole messages only: the first half of the batch, until it fits or one message is left.
388
+ while (result.text && result.text.length > HOOK_TEXT_CHARS && answer.messages.length > 1) {
389
+ const messages = answer.messages.slice(0, Math.floor(answer.messages.length / 2));
390
+ answer = { ...answer, messages, next_after: messages[messages.length - 1].id };
391
+ result = await handOut();
392
+ forHook.add(key);
393
+ }
394
+ const current = find(key);
395
+ if (!current)
396
+ return null;
397
+ const moved = { ...current, after: answer.next_after, guard: result.guard };
398
+ if (!result.text) {
399
+ if (answer.next_after !== current.after || JSON.stringify(result.guard) !== JSON.stringify(before)) {
400
+ seats = seats.map((s) => (keyOf(s) === key ? moved : s));
401
+ save();
402
+ log(`${key} hook: ${answer.messages.length} new, nothing for the session`);
403
+ }
404
+ if (result.guard.held.length)
405
+ report(current, { waiting: result.waiting });
406
+ return null;
407
+ }
408
+ hookLent.set(key, { token, from: current.after, moved, receipt: { through: result.through, waiting: result.waiting, messages: result.messages }, handed: result.handed, how });
409
+ lent.set(key, Date.now() + LENT_MS);
410
+ return result.text;
411
+ }
412
+ catch (error) {
413
+ // Still there for the next run, or for the pump when the turn ends.
414
+ forHook.add(key);
415
+ log(`${key} hook read failed: ${error instanceof Error ? error.message : String(error)}`);
416
+ return null;
417
+ }
418
+ finally {
419
+ pumping.delete(key);
420
+ again.delete(key);
421
+ }
422
+ }
423
+ /** The hook wrote out what it was given: the seat moves past it. */
424
+ function hookTook(key, token) {
425
+ const given = hookLent.get(key);
426
+ if (!given || given.token !== token)
427
+ return;
428
+ hookLent.delete(key);
429
+ const seat = find(key);
430
+ // Too late: the pump took the messages back and may have delivered them.
431
+ if (!seat || seat.after !== given.from || (lent.get(key) ?? 0) <= Date.now())
432
+ return;
433
+ lent.delete(key);
434
+ seats = seats.map((s) => (keyOf(s) === key ? given.moved : s));
435
+ save();
436
+ if (given.handed)
437
+ report(given.moved, { through: given.receipt.through, state: "delivered", waiting: given.receipt.waiting, messages: given.receipt.messages, how: given.how });
438
+ else
439
+ report(given.moved, { waiting: given.receipt.waiting });
440
+ log(`${key} handed ${given.handed} message(s) and answer(s) to the session's hook (${given.how === "woke" ? "woke it" : "mid-task"})`);
441
+ }
300
442
  function tookHeld(key, ids) {
301
443
  lent.delete(key);
302
444
  const seat = find(key);
@@ -313,6 +455,7 @@ export async function runDaemon(home) {
313
455
  const waking = createWaking({
314
456
  home,
315
457
  log,
458
+ deliver: deliverAsk,
316
459
  seats: () => seats,
317
460
  join: async (session, url) => {
318
461
  const { seat } = await joinRoom(home, session, url, {
@@ -326,7 +469,191 @@ export async function runDaemon(home) {
326
469
  },
327
470
  leave: (seat) => drop(keyOf(seat), true),
328
471
  });
329
- const respond = async (request) => {
472
+ /** What is new for each of the session's seats, under one token. */
473
+ async function pullAll(keys, token, how, sessionId) {
474
+ const room = [];
475
+ const waiting = [...((sessionId ? asksFor.get(sessionId) : undefined)?.values() ?? [])];
476
+ // The rooms first: each read hears its seat's switch, and a seat with an ask waiting reads it now.
477
+ for (const ask of waiting)
478
+ forHook.add(keyOf(ask.chat));
479
+ for (const key of keys) {
480
+ const text = await hookPull(key, token, how);
481
+ if (text)
482
+ room.push(text);
483
+ }
484
+ const texts = [];
485
+ // Asks to the agent go in by the same path, first: they are what it was sent (deliverAsk).
486
+ for (const ask of waiting) {
487
+ if (ask.done || (ask.lent && ask.lent.until > Date.now()))
488
+ continue;
489
+ ask.lent = { token, until: Date.now() + LENT_MS };
490
+ texts.push(ask.text);
491
+ }
492
+ texts.push(...room);
493
+ return texts.length ? texts.join("\n\n") : null;
494
+ }
495
+ /** Asks to the agent waiting for a session's hook, by message id. */
496
+ const asksFor = new Map();
497
+ /** How an ask to the agent goes into its open window (waking.ts): through
498
+ * the session's hooks while they run or wait, as its room messages do, so
499
+ * a window has one way in; else into its inbox as before. Delivered once
500
+ * a hook wrote it out; a retry until then, which asks again with the same
501
+ * message id and so waits for the same hand-over. */
502
+ async function deliverAsk(chat, messageId, text) {
503
+ const { harness, sessionId } = chat;
504
+ const hooked = harness === "claude-code" && hooksAllowed(home) && (waiters.has(sessionId) || (busy.get(sessionId) ?? 0) > Date.now());
505
+ const waiting = asksFor.get(sessionId)?.get(messageId);
506
+ // A hook wrote it out between two tries: it is in.
507
+ if (waiting?.done) {
508
+ asksFor.get(sessionId)?.delete(messageId);
509
+ return { kind: "delivered" };
510
+ }
511
+ // No hook runs or waits (none ever did, or an interrupted turn's hold ran
512
+ // out): the inbox. Not while a hook holds the ask lent: it may still be
513
+ // writing it out. A queued ask is held for the inbox during the try and
514
+ // leaves the queue only when the inbox took it; with no inbox it stays
515
+ // for the session's next hook.
516
+ if (!hooked && !(waiting?.lent && waiting.lent.until > Date.now())) {
517
+ const held = { token: `inbox-${randomUUID()}`, until: Date.now() + LENT_MS };
518
+ if (waiting)
519
+ waiting.lent = held;
520
+ const outcome = await deliverTo(harness, sessionId, messageId, text, chat.codexHome);
521
+ if (outcome.kind === "retry") {
522
+ if (waiting?.lent === held)
523
+ waiting.lent = undefined;
524
+ return outcome;
525
+ }
526
+ if (waiting) {
527
+ asksFor.get(sessionId)?.delete(messageId);
528
+ waiting.took();
529
+ }
530
+ return outcome;
531
+ }
532
+ let ask = waiting;
533
+ if (!ask) {
534
+ let took = () => { };
535
+ const taken = new Promise((resolve) => (took = resolve));
536
+ ask = { chat, text, took: () => took(), taken };
537
+ asksFor.set(sessionId, (asksFor.get(sessionId) ?? new Map()).set(messageId, ask));
538
+ }
539
+ waiters.get(sessionId)?.();
540
+ const done = await Promise.race([ask.taken.then(() => true), new Promise((resolve) => setTimeout(() => resolve(false), HOOK_WAIT_MS).unref())]);
541
+ if (!done)
542
+ return { kind: "retry", reason: "The session's hook has not taken it yet." };
543
+ if (asksFor.get(sessionId)?.get(messageId) === ask)
544
+ asksFor.get(sessionId)?.delete(messageId);
545
+ return { kind: "delivered" };
546
+ }
547
+ /** The hook's three asks. Every answer is quick except a Stop hook's wait,
548
+ * which lasts until something comes or HOOK_WAIT_MS passes. */
549
+ async function hookAnswer(request, closed) {
550
+ if (request.v !== HOOK_PROTOCOL) {
551
+ log(`${request.sessionId} hook speaks protocol ${request.v ?? "none"}, this daemon ${HOOK_PROTOCOL}: its messages go the old way`);
552
+ return { ok: false, error: `This hook speaks protocol ${request.v ?? "none"}; Station ${VERSION} speaks ${HOOK_PROTOCOL}. Join again to update it.` };
553
+ }
554
+ const sessionId = request.sessionId;
555
+ if (typeof request.configDir === "string")
556
+ claudeHomes.set(sessionId, claudeHome({ CLAUDE_CONFIG_DIR: request.configDir }));
557
+ // A hook runs in every Claude Code session on the computer: one with no
558
+ // seat, or a computer whose person took hooks back, gets nothing, and fast.
559
+ const mine = seats.filter((s) => !s.left && s.sessionId === sessionId && delivers(s.harness)).map(keyOf);
560
+ if (!mine.length || !hooksAllowed(home))
561
+ return { ok: true, text: null };
562
+ if (request.op === "hookRead") {
563
+ for (const key of mine)
564
+ hookTook(key, request.token);
565
+ for (const [id, ask] of asksFor.get(sessionId) ?? []) {
566
+ if (ask.done || ask.lent?.token !== request.token)
567
+ continue;
568
+ // Kept, marked done, until the wake's try hears it: a try between two
569
+ // waits must not queue it again.
570
+ ask.done = true;
571
+ ask.took();
572
+ log(`${sessionId} took ask ${id} through its hook`);
573
+ }
574
+ return { ok: true };
575
+ }
576
+ const token = randomUUID();
577
+ if (request.op === "hook") {
578
+ if (request.event === "SessionEnd") {
579
+ busy.delete(sessionId);
580
+ // Its asks go the other way now (waking.ts tries again, or continues the chat).
581
+ asksFor.delete(sessionId);
582
+ return { ok: true, text: null };
583
+ }
584
+ if (!((busy.get(sessionId) ?? 0) > Date.now()))
585
+ log(`${sessionId} in a turn, by its hook`);
586
+ busy.set(sessionId, Date.now() + BUSY_MS);
587
+ const text = await pullAll(mine, token, "mid_task", sessionId);
588
+ return text ? { ok: true, text, token } : { ok: true, text: null };
589
+ }
590
+ // The turn ended and the Stop hook waits in the background. Its later
591
+ // asks say nothing of the turn: the person may have typed since.
592
+ if (!request.again && busy.delete(sessionId))
593
+ log(`${sessionId} turn ended, its Stop hook waits`);
594
+ const inTurn = () => (busy.get(sessionId) ?? 0) > Date.now();
595
+ for (const key of mine)
596
+ forHook.add(key);
597
+ const now = inTurn() ? null : await pullAll(mine, token, "woke", sessionId);
598
+ if (now) {
599
+ busy.set(sessionId, Date.now() + BUSY_MS);
600
+ return { ok: true, text: now, token };
601
+ }
602
+ return new Promise((resolve) => {
603
+ let done = false;
604
+ const finish = (response) => {
605
+ if (done)
606
+ return;
607
+ done = true;
608
+ clearTimeout(timer);
609
+ if (waiters.get(sessionId) === poke)
610
+ waiters.delete(sessionId);
611
+ closed.removeEventListener("abort", gone);
612
+ resolve(response);
613
+ };
614
+ // One pull at a time under this hook's token: two at once would each
615
+ // lend messages under it, and the hook's receipt would mark the batch
616
+ // it never got delivered. A poke during a pull pulls again after it.
617
+ let pulling = false;
618
+ let pokedAgain = false;
619
+ const poke = () => {
620
+ // Taken back meanwhile (station logout): the hook stops waiting, and wakes nothing.
621
+ if (!hooksAllowed(home))
622
+ return finish({ ok: true, text: null });
623
+ // A turn is under way: its step hooks hand messages over.
624
+ if (done || inTurn())
625
+ return;
626
+ if (pulling) {
627
+ pokedAgain = true;
628
+ return;
629
+ }
630
+ pulling = true;
631
+ void pullAll(mine, token, "woke", sessionId).then((text) => {
632
+ pulling = false;
633
+ if (done)
634
+ return;
635
+ if (text) {
636
+ // The session wakes into a turn: what comes next waits for its hooks.
637
+ busy.set(sessionId, Date.now() + BUSY_MS);
638
+ return finish({ ok: true, text, token });
639
+ }
640
+ if (pokedAgain) {
641
+ pokedAgain = false;
642
+ poke();
643
+ }
644
+ }, () => {
645
+ pulling = false;
646
+ });
647
+ };
648
+ // Claude Code stopped the hook (the session closed, or the person typed):
649
+ // what comes goes the old way until a hook runs again.
650
+ const gone = () => finish({ ok: true, text: null });
651
+ const timer = setTimeout(() => finish({ ok: true, wait: true }), HOOK_WAIT_MS);
652
+ waiters.set(sessionId, poke);
653
+ closed.addEventListener("abort", gone);
654
+ });
655
+ }
656
+ const respond = async (request, closed = new AbortController().signal) => {
330
657
  if (request.op === "ping" || request.op === "list")
331
658
  return { ok: true, seats, version: VERSION };
332
659
  if (request.op === "stop") {
@@ -348,6 +675,8 @@ export async function runDaemon(home) {
348
675
  save();
349
676
  return { ok: true };
350
677
  }
678
+ if (request.op === "hook" || request.op === "hookWait" || request.op === "hookRead")
679
+ return hookAnswer(request, closed);
351
680
  if (request.op !== "read" && request.op !== "held" && request.op !== "heldRead")
352
681
  return { ok: false, error: "unknown request" };
353
682
  const key = keyOf(request);
@@ -366,13 +695,15 @@ export async function runDaemon(home) {
366
695
  const server = createServer((socket) => {
367
696
  let buffer = "";
368
697
  let answered = false;
698
+ const closed = new AbortController();
699
+ socket.on("close", () => closed.abort());
369
700
  socket.on("data", (chunk) => {
370
701
  buffer += chunk.toString("utf8");
371
702
  const end = buffer.indexOf("\n");
372
703
  if (end < 0 || answered)
373
704
  return;
374
705
  answered = true;
375
- new Promise((resolve) => resolve(respond(JSON.parse(buffer.slice(0, end)))))
706
+ new Promise((resolve) => resolve(respond(JSON.parse(buffer.slice(0, end)), closed.signal)))
376
707
  .catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error) }))
377
708
  .then((response) => socket.end(`${JSON.stringify(response)}\n`));
378
709
  });
@@ -395,11 +726,13 @@ export async function runDaemon(home) {
395
726
  // A shell's agent reads for itself: the daemon has nothing to do for it.
396
727
  if (!delivers(seat.harness))
397
728
  continue;
398
- if (isRunning(seat.harness, seat.sessionId)) {
729
+ if (running(seat)) {
399
730
  missingSince.delete(seat.sessionId);
731
+ tellOpen(seat, true);
400
732
  void pump(key);
401
733
  }
402
734
  else {
735
+ tellOpen(seat, false);
403
736
  const since = missingSince.get(seat.sessionId) ?? Date.now();
404
737
  missingSince.set(seat.sessionId, since);
405
738
  if (Date.now() - since > GONE_MS)
@@ -419,7 +752,7 @@ export async function runDaemon(home) {
419
752
  waking.stop();
420
753
  // Station starts nothing on this computer from now: it hears so at once.
421
754
  const credentials = readCredentials(home);
422
- if (credentials)
755
+ if (credentials?.token)
423
756
  void call(credentials.relayUrl, "/cli/wakes", { token: credentials.token }, { method: "DELETE" }).catch(() => { });
424
757
  for (const close of closers.values())
425
758
  close();
@@ -431,6 +764,16 @@ export async function runDaemon(home) {
431
764
  process.on("SIGTERM", () => stop("SIGTERM"));
432
765
  process.on("SIGINT", () => stop("SIGINT"));
433
766
  }
767
+ /** What to tell the relay about a device-linked seat's window, once per
768
+ * change: `session_open: false` while it is closed and the daemon still
769
+ * reads the room for its return, so an ask to the agent as a whole goes to
770
+ * another computer meanwhile (the relay's wake.ts). Null: nothing new. */
771
+ export function windowOpenReport(said, key, seat, credentials, open) {
772
+ if (seat.via !== "cli" || credentials?.allowHooks === undefined || said.get(key) === open)
773
+ return null;
774
+ said.set(key, open);
775
+ return { session_open: open };
776
+ }
434
777
  /** Whether a daemon answers on the socket. */
435
778
  export function answers(socketPath) {
436
779
  return ask(socketPath, { op: "ping" }).then((response) => response.ok, () => false);