@santori/station 0.9.9 → 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/daemon.js CHANGED
@@ -10,29 +10,39 @@
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
21
19
  // with no window open for an ask to it (waking.ts, starts.ts).
22
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
+ //
23
29
  // Commands talk to it over ~/.station/daemon.sock, one JSON line each way.
24
30
  // It is the only writer of seats.json.
31
+ import { randomUUID } from "node:crypto";
25
32
  import { appendFileSync, chmodSync, existsSync } from "node:fs";
26
33
  import { createServer, connect } from "node:net";
34
+ import { homedir } from "node:os";
27
35
  import { Centrifuge } from "centrifuge";
28
36
  import { VERSION, selfCommand } from "./self.js";
29
37
  import { freshGuard, throughOf } from "./guard.js";
30
38
  import { handOver, heldRead, heldWaiting, messagesById, readHeld } from "./handover.js";
31
39
  import { ensureHome, files, readCredentials, remove, writeJson } from "./home.js";
40
+ import { HOOK_PROTOCOL, hooksAllowed } from "./hooks.js";
32
41
  import { call, seatOver } from "./relay.js";
33
42
  import { authFor, loadSeats, roomLabel, withOwner } from "./seats.js";
34
43
  import { HARNESS_NAMES, delivers, deliverTo, isRunning } from "./sessions.js";
35
- import { daemonEnv, joinRoom } from "./join.js";
44
+ import { claudeHome } from "./claude.js";
45
+ import { clearJoinRequest, daemonEnv, joinRoom } from "./join.js";
36
46
  import { createWaking } from "./waking.js";
37
47
  const SAFETY_MS = 30_000;
38
48
  const RETRY_MS = 15_000;
@@ -43,8 +53,25 @@ const IDLE_EXIT_MS = 30 * 60_000;
43
53
  /** How long `station wait` has to write out held messages before the
44
54
  * daemon may deliver them itself. */
45
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;
46
65
  const keyOf = (seat) => `${seat.sessionId}:${seat.roomId}`;
47
66
  export async function runDaemon(home) {
67
+ // It inherits the folder of whichever session started it, which may be
68
+ // deleted later. Nothing here needs that folder, so work from home.
69
+ try {
70
+ process.chdir(homedir());
71
+ }
72
+ catch {
73
+ // No home folder: stay where it started.
74
+ }
48
75
  // The computer's daemon acts with the computer's sign-in only (daemonEnv in join.ts).
49
76
  for (const name of Object.keys(process.env))
50
77
  if (!(name in daemonEnv()))
@@ -75,6 +102,37 @@ export async function runDaemon(home) {
75
102
  const waitingSent = new Map();
76
103
  /** Seats whose held messages `station wait` is writing out, and until when. */
77
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();
131
+ async function seatCall(seat, path, init) {
132
+ const credentials = readCredentials(home);
133
+ const secret = credentials?.allowHooks !== undefined ? credentials.secret : undefined;
134
+ return call(seat.relayUrl, `/${seat.roomId}${path}`, authFor(seat, credentials && secret ? { ...credentials, token: secret } : credentials), init);
135
+ }
78
136
  /** Tells the room what happened to its messages, for the board. Best
79
137
  * effort: a relay without the route must not cost the seat. A wait is
80
138
  * sent once per reason, not on every retry. */
@@ -83,7 +141,7 @@ export async function runDaemon(home) {
83
141
  if (receipt.through === undefined && waitingSent.get(key) === receipt.waiting)
84
142
  return;
85
143
  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)}`));
144
+ void seatCall(seat, "/delivery", { body: receipt }).catch((error) => log(`${key} receipt not sent: ${error instanceof Error ? error.message : String(error)}`));
87
145
  };
88
146
  let emptySince = seats.some((s) => !s.left) ? null : Date.now();
89
147
  const save = () => writeJson(paths.seats, seats);
@@ -93,7 +151,7 @@ export async function runDaemon(home) {
93
151
  const known = people.get(key) ?? [];
94
152
  if (authors.every((id) => known.some((p) => p.id === id)))
95
153
  return known;
96
- const room = await call(seat.relayUrl, `/${seat.roomId}`, authFor(seat, readCredentials(home)));
154
+ const room = await seatCall(seat, "");
97
155
  people.set(key, room.participants);
98
156
  // Someone new spoke: maybe the person this seat works for, come in late.
99
157
  const learned = withOwner(seat, room.owner);
@@ -104,22 +162,35 @@ export async function runDaemon(home) {
104
162
  }
105
163
  return room.participants;
106
164
  };
107
- /** Reads a seat's room for the hand-over: its people, and held messages again by id. */
108
- const roomOf = (key) => ({
109
- participants: (authors) => participantsFor(find(key), authors),
110
- messages: (ids) => {
111
- const seat = find(key);
112
- return messagesById(ids, (after) => call(seat.relayUrl, `/${seat.roomId}/messages?after=${after}&all=1`, authFor(seat, readCredentials(home))));
113
- },
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`)),
114
171
  });
115
172
  async function pump(key) {
116
173
  // A shell's agent reads for itself with station wait.
117
174
  const target = find(key);
118
175
  if (target && !delivers(target.harness))
119
176
  return;
120
- // `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.
121
178
  if ((lent.get(key) ?? 0) > Date.now())
122
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
+ }
123
194
  if (pumping.has(key)) {
124
195
  again.add(key);
125
196
  return;
@@ -128,24 +199,24 @@ export async function runDaemon(home) {
128
199
  try {
129
200
  let seat = find(key);
130
201
  while (seat) {
131
- const answer = await call(seat.relayUrl, `/${seat.roomId}/messages?after=${seat.after}`, authFor(seat, readCredentials(home)));
202
+ const answer = await seatCall(seat, `/messages?after=${seat.after}`);
132
203
  if (!find(key))
133
204
  break;
134
205
  const before = seat.guard ?? freshGuard();
135
206
  const otherRooms = seats.some((s) => s.sessionId === seat.sessionId && s.roomId !== seat.roomId);
136
- 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);
137
208
  const { text, handed, guard } = result;
138
209
  seat = find(key);
139
210
  if (!seat)
140
211
  break;
141
212
  if (text) {
142
- if (!delivers(seat.harness) || !isRunning(seat.harness, seat.sessionId)) {
213
+ if (!delivers(seat.harness) || !running(seat)) {
143
214
  // The tick decides whether it ended.
144
215
  if (handed)
145
216
  report(seat, { waiting: `The ${HARNESS_NAMES[seat.harness]} session is not open.` });
146
217
  break;
147
218
  }
148
- 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);
149
220
  if (outcome.kind === "retry") {
150
221
  log(`${key} not delivered, will retry: ${outcome.reason}`);
151
222
  if (handed)
@@ -159,7 +230,7 @@ export async function runDaemon(home) {
159
230
  log(`${key} delivered ${handed} message(s) and answer(s)${guard.held.length ? `, holding ${guard.held.length}` : ""}`);
160
231
  // The receipt stops before the first held message: those did not go in.
161
232
  if (handed)
162
- report(seat, { through: result.through, state: outcome.kind === "in-doubt" ? "in_doubt" : "delivered", waiting: result.waiting });
233
+ report(seat, { through: result.through, state: outcome.kind === "in-doubt" ? "in_doubt" : "delivered", waiting: result.waiting, messages: result.messages });
163
234
  else
164
235
  report(seat, { waiting: result.waiting });
165
236
  }
@@ -196,7 +267,7 @@ export async function runDaemon(home) {
196
267
  if (!delivers(seat.harness))
197
268
  return;
198
269
  const key = keyOf(seat);
199
- const ticket = () => call(seat.relayUrl, `/${seat.roomId}/live`, authFor(seat, readCredentials(home)));
270
+ const ticket = () => seatCall(seat, "/live");
200
271
  let client = null;
201
272
  let closed = false;
202
273
  closers.set(key, () => {
@@ -233,11 +304,13 @@ export async function runDaemon(home) {
233
304
  function add(joined) {
234
305
  const key = keyOf(joined);
235
306
  closers.get(key)?.();
307
+ openSaid.delete(key);
236
308
  // Joining again keeps what the loop guard holds: those messages are not lost.
237
309
  const held = find(key)?.guard;
238
310
  const seat = held ? { ...joined, guard: held } : joined;
239
311
  seats = [...seats.filter((s) => keyOf(s) !== key), seat];
240
312
  save();
313
+ clearJoinRequest(home, seat);
241
314
  emptySince = null;
242
315
  connectLive(seat);
243
316
  log(`${key} added (${roomLabel(seat)})`);
@@ -247,14 +320,18 @@ export async function runDaemon(home) {
247
320
  closers.get(key)?.();
248
321
  closers.delete(key);
249
322
  waitingSent.delete(key);
323
+ openSaid.delete(key);
250
324
  lent.delete(key);
325
+ forHook.delete(key);
326
+ hookLent.delete(key);
251
327
  people.delete(key);
328
+ // Its Stop hook stops waiting when it asks again and finds no seat.
252
329
  seats = seats.map((s) => keyOf(s) === key ? { ...s, left: true } : s);
253
330
  save();
254
331
  if (!seats.some((s) => !s.left))
255
332
  emptySince = Date.now();
256
333
  if (seat && leave) {
257
- void call(seat.relayUrl, `/${seat.roomId}/presence`, authFor(seat, readCredentials(home)), { body: { leaving: true } }).catch(() => { });
334
+ void seatCall(seat, "/presence", { body: { leaving: true } }).catch(() => { });
258
335
  }
259
336
  log(`${key} dropped${leave ? " and left the room" : ""}`);
260
337
  }
@@ -270,7 +347,7 @@ export async function runDaemon(home) {
270
347
  return { text: null, ids: [] };
271
348
  pumping.add(key);
272
349
  try {
273
- const read = await readHeld(seat, seat.guard, roomOf(key), selfCommand());
350
+ const read = await readHeld(seat, seat.guard, roomOf(seat), selfCommand());
274
351
  // Nothing left of them in the room: there is nothing to write out.
275
352
  if (!read.text)
276
353
  tookHeld(key, read.ids);
@@ -284,6 +361,84 @@ export async function runDaemon(home) {
284
361
  void pump(key);
285
362
  }
286
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
+ }
287
442
  function tookHeld(key, ids) {
288
443
  lent.delete(key);
289
444
  const seat = find(key);
@@ -292,7 +447,7 @@ export async function runDaemon(home) {
292
447
  const guard = heldRead(seat.guard, ids);
293
448
  seats = seats.map((s) => (keyOf(s) === key ? { ...seat, guard } : s));
294
449
  save();
295
- report(seat, { through: throughOf(guard, seat.after), state: "delivered", waiting: heldWaiting(guard.held.length) });
450
+ report(seat, { through: throughOf(guard, seat.after), state: "delivered", waiting: heldWaiting(guard.held.length), messages: ids });
296
451
  log(`${key} held messages read with station wait`);
297
452
  void pump(key);
298
453
  }
@@ -300,6 +455,7 @@ export async function runDaemon(home) {
300
455
  const waking = createWaking({
301
456
  home,
302
457
  log,
458
+ deliver: deliverAsk,
303
459
  seats: () => seats,
304
460
  join: async (session, url) => {
305
461
  const { seat } = await joinRoom(home, session, url, {
@@ -313,7 +469,191 @@ export async function runDaemon(home) {
313
469
  },
314
470
  leave: (seat) => drop(keyOf(seat), true),
315
471
  });
316
- 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) => {
317
657
  if (request.op === "ping" || request.op === "list")
318
658
  return { ok: true, seats, version: VERSION };
319
659
  if (request.op === "stop") {
@@ -335,6 +675,8 @@ export async function runDaemon(home) {
335
675
  save();
336
676
  return { ok: true };
337
677
  }
678
+ if (request.op === "hook" || request.op === "hookWait" || request.op === "hookRead")
679
+ return hookAnswer(request, closed);
338
680
  if (request.op !== "read" && request.op !== "held" && request.op !== "heldRead")
339
681
  return { ok: false, error: "unknown request" };
340
682
  const key = keyOf(request);
@@ -353,13 +695,15 @@ export async function runDaemon(home) {
353
695
  const server = createServer((socket) => {
354
696
  let buffer = "";
355
697
  let answered = false;
698
+ const closed = new AbortController();
699
+ socket.on("close", () => closed.abort());
356
700
  socket.on("data", (chunk) => {
357
701
  buffer += chunk.toString("utf8");
358
702
  const end = buffer.indexOf("\n");
359
703
  if (end < 0 || answered)
360
704
  return;
361
705
  answered = true;
362
- 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)))
363
707
  .catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error) }))
364
708
  .then((response) => socket.end(`${JSON.stringify(response)}\n`));
365
709
  });
@@ -382,11 +726,13 @@ export async function runDaemon(home) {
382
726
  // A shell's agent reads for itself: the daemon has nothing to do for it.
383
727
  if (!delivers(seat.harness))
384
728
  continue;
385
- if (isRunning(seat.harness, seat.sessionId)) {
729
+ if (running(seat)) {
386
730
  missingSince.delete(seat.sessionId);
731
+ tellOpen(seat, true);
387
732
  void pump(key);
388
733
  }
389
734
  else {
735
+ tellOpen(seat, false);
390
736
  const since = missingSince.get(seat.sessionId) ?? Date.now();
391
737
  missingSince.set(seat.sessionId, since);
392
738
  if (Date.now() - since > GONE_MS)
@@ -406,7 +752,7 @@ export async function runDaemon(home) {
406
752
  waking.stop();
407
753
  // Station starts nothing on this computer from now: it hears so at once.
408
754
  const credentials = readCredentials(home);
409
- if (credentials)
755
+ if (credentials?.token)
410
756
  void call(credentials.relayUrl, "/cli/wakes", { token: credentials.token }, { method: "DELETE" }).catch(() => { });
411
757
  for (const close of closers.values())
412
758
  close();
@@ -418,6 +764,16 @@ export async function runDaemon(home) {
418
764
  process.on("SIGTERM", () => stop("SIGTERM"));
419
765
  process.on("SIGINT", () => stop("SIGINT"));
420
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
+ }
421
777
  /** Whether a daemon answers on the socket. */
422
778
  export function answers(socketPath) {
423
779
  return ask(socketPath, { op: "ping" }).then((response) => response.ok, () => false);