@santori/station 0.9.10 → 0.9.12

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
@@ -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,12 @@ 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";
45
+ import { codexHome, rolloutPath, STOP_OUTPUT_BYTES, stopDeliveryMarker, stopDeliveryStatus, threadIdle } from "./codex.js";
34
46
  import { clearJoinRequest, daemonEnv, joinRoom } from "./join.js";
35
47
  import { createWaking } from "./waking.js";
36
48
  const SAFETY_MS = 30_000;
@@ -42,6 +54,15 @@ const IDLE_EXIT_MS = 30 * 60_000;
42
54
  /** How long `station wait` has to write out held messages before the
43
55
  * daemon may deliver them itself. */
44
56
  const LENT_MS = 15_000;
57
+ /** A session in a turn whose hooks have said nothing for this long (a turn
58
+ * interrupted at the keyboard ends with no Stop) gets its messages the old
59
+ * way again, which waits for the turn to end by itself. */
60
+ const BUSY_MS = 10 * 60_000;
61
+ /** How long one wait of a Stop hook lasts before the daemon says "keep waiting". */
62
+ const HOOK_WAIT_MS = 25_000;
63
+ /** What the board says while its person keeps messages from reaching the session. */
64
+ /** About as much text as one hook hands over: a batch longer than this goes in whole messages over several steps. */
65
+ const HOOK_TEXT_CHARS = 9_000;
45
66
  const keyOf = (seat) => `${seat.sessionId}:${seat.roomId}`;
46
67
  export async function runDaemon(home) {
47
68
  // It inherits the folder of whichever session started it, which may be
@@ -82,6 +103,34 @@ export async function runDaemon(home) {
82
103
  const waitingSent = new Map();
83
104
  /** Seats whose held messages `station wait` is writing out, and until when. */
84
105
  const lent = new Map();
106
+ /** Sessions in a turn, by their hook's word, until when that word holds,
107
+ * and for Codex the turn's id. */
108
+ const busy = new Map();
109
+ const codexStops = new Map();
110
+ /** The Claude Code profile each session's hook runs under, by its own
111
+ * CLAUDE_CONFIG_DIR: the session's registry entry is there, not always
112
+ * in the daemon's. */
113
+ const claudeHomes = new Map();
114
+ const running = (seat) => isRunning(seat.harness, seat.sessionId, seat.codexHome, claudeHomes.get(seat.sessionId));
115
+ /** Sessions whose Stop hook waits here, and how to tell it something came. */
116
+ const waiters = new Map();
117
+ /** What each device-linked seat last told the relay about its window. */
118
+ const openSaid = new Map();
119
+ const tellOpen = (seat, open) => {
120
+ const key = keyOf(seat);
121
+ const body = windowOpenReport(openSaid, key, seat, readCredentials(home), open);
122
+ if (!body)
123
+ return;
124
+ void seatCall(seat, "/delivery", { body }).catch((error) => {
125
+ // Said again on the next tick.
126
+ openSaid.delete(key);
127
+ log(`${key} window ${open ? "open" : "closed"} not told: ${error instanceof Error ? error.message : String(error)}`);
128
+ });
129
+ };
130
+ /** Seats with something that may be new, kept for the session's hook. */
131
+ const forHook = new Set();
132
+ /** What a hook was given and has not yet said it wrote out. */
133
+ const hookLent = new Map();
85
134
  async function seatCall(seat, path, init) {
86
135
  const credentials = readCredentials(home);
87
136
  const secret = credentials?.allowHooks !== undefined ? credentials.secret : undefined;
@@ -92,7 +141,7 @@ export async function runDaemon(home) {
92
141
  * sent once per reason, not on every retry. */
93
142
  const report = (seat, receipt) => {
94
143
  const key = keyOf(seat);
95
- if (receipt.through === undefined && waitingSent.get(key) === receipt.waiting)
144
+ if (receipt.through === undefined && !receipt.station?.length && waitingSent.get(key) === receipt.waiting)
96
145
  return;
97
146
  waitingSent.set(key, receipt.waiting);
98
147
  void seatCall(seat, "/delivery", { body: receipt }).catch((error) => log(`${key} receipt not sent: ${error instanceof Error ? error.message : String(error)}`));
@@ -100,12 +149,12 @@ export async function runDaemon(home) {
100
149
  let emptySince = seats.some((s) => !s.left) ? null : Date.now();
101
150
  const save = () => writeJson(paths.seats, seats);
102
151
  const find = (key) => seats.find((seat) => keyOf(seat) === key && !seat.left) ?? null;
103
- const participantsFor = async (seat, authors) => {
152
+ const participantsFor = async (seat, authors, signal) => {
104
153
  const key = keyOf(seat);
105
154
  const known = people.get(key) ?? [];
106
155
  if (authors.every((id) => known.some((p) => p.id === id)))
107
156
  return known;
108
- const room = await seatCall(seat, "");
157
+ const room = await seatCall(seat, "", { signal });
109
158
  people.set(key, room.participants);
110
159
  // Someone new spoke: maybe the person this seat works for, come in late.
111
160
  const learned = withOwner(seat, room.owner);
@@ -116,22 +165,51 @@ export async function runDaemon(home) {
116
165
  }
117
166
  return room.participants;
118
167
  };
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
- },
168
+ /** Reads a seat's room for the hand-over: its people, and held messages
169
+ * again by id. As that seat, even when it left meanwhile: its caller then
170
+ * hands nothing over. */
171
+ const roomOf = (seat, signal) => ({
172
+ participants: (authors) => participantsFor(seat, authors, signal),
173
+ messages: (ids) => messagesById(ids, (after) => seatCall(seat, `/messages?after=${after}&all=1&receipt=1`, { signal })),
126
174
  });
175
+ /** Whether the session is in a turn, by its hook's word. A Codex turn
176
+ * that was interrupted runs no Stop hook, so its thread going idle ends it. */
177
+ function inTurn(seat) {
178
+ const turn = busy.get(seat.sessionId);
179
+ if (!turn || turn.until <= Date.now())
180
+ return false;
181
+ if (seat.harness !== "codex" || !threadIdle(seat.codexHome ?? codexHome(), seat.sessionId))
182
+ return true;
183
+ busy.delete(seat.sessionId);
184
+ return false;
185
+ }
186
+ /** Whether the session's hook takes its messages now, the one place the
187
+ * daemon picks the path: it is in a turn by its hook's word, or (Claude
188
+ * Code) its Stop hook waits. Hooks turned off take nothing, so nothing
189
+ * waits for them. */
190
+ function hookTakes(seat) {
191
+ if (!hooksAllowed(home))
192
+ return false;
193
+ if (seat.harness === "codex")
194
+ return inTurn(seat);
195
+ if (seat.harness !== "claude-code")
196
+ return false;
197
+ return waiters.has(seat.sessionId) || inTurn(seat);
198
+ }
127
199
  async function pump(key) {
128
200
  // A shell's agent reads for itself with station wait.
129
201
  const target = find(key);
130
202
  if (target && !delivers(target.harness))
131
203
  return;
132
- // `station wait` is writing the held messages out: do not deliver them too.
204
+ // `station wait` or the hook is writing messages out: do not deliver them too.
133
205
  if ((lent.get(key) ?? 0) > Date.now())
134
206
  return;
207
+ if (target && hookTakes(target)) {
208
+ forHook.add(key);
209
+ // In a turn, its hook hands them over between steps. Else its Stop hook waits: it takes them and wakes the session.
210
+ waiters.get(target.sessionId)?.();
211
+ return;
212
+ }
135
213
  if (pumping.has(key)) {
136
214
  again.add(key);
137
215
  return;
@@ -140,24 +218,33 @@ export async function runDaemon(home) {
140
218
  try {
141
219
  let seat = find(key);
142
220
  while (seat) {
143
- const answer = await seatCall(seat, `/messages?after=${seat.after}`);
221
+ // station=report: the Station team's notes come until this daemon says it put them in.
222
+ const answer = await seatCall(seat, `/messages?after=${seat.after}&station=report`);
144
223
  if (!find(key))
145
224
  break;
146
225
  const before = seat.guard ?? freshGuard();
147
226
  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);
149
- const { text, handed, guard } = result;
227
+ const result = await handOver(() => find(key) ?? seat, before, answer, roomOf(seat), Date.now(), selfCommand(), otherRooms);
228
+ const { handed, guard } = result;
229
+ // The Station team's notes about reports this agent sent go in first: they are in no room.
230
+ const notes = answer.station ?? [];
231
+ const text = [...notes.map((note) => note.text), result.text].filter(Boolean).join("\n\n") || null;
232
+ const station = notes.length ? { station: notes.map((note) => note.id) } : {};
150
233
  seat = find(key);
151
234
  if (!seat)
152
235
  break;
153
236
  if (text) {
154
- if (!delivers(seat.harness) || !isRunning(seat.harness, seat.sessionId)) {
237
+ if (seat.harness === "codex" && hookTakes(seat)) {
238
+ forHook.add(key);
239
+ break;
240
+ }
241
+ if (!delivers(seat.harness) || !running(seat)) {
155
242
  // The tick decides whether it ended.
156
243
  if (handed)
157
244
  report(seat, { waiting: `The ${HARNESS_NAMES[seat.harness]} session is not open.` });
158
245
  break;
159
246
  }
160
- const outcome = await deliverTo(seat.harness, seat.sessionId, `station-${seat.roomId}-${answer.next_after}-${result.lastId}`, text);
247
+ const outcome = await deliverTo(seat.harness, seat.sessionId, `station-${seat.roomId}-${answer.next_after}-${result.lastId}`, text, seat.codexHome);
161
248
  if (outcome.kind === "retry") {
162
249
  log(`${key} not delivered, will retry: ${outcome.reason}`);
163
250
  if (handed)
@@ -171,9 +258,9 @@ export async function runDaemon(home) {
171
258
  log(`${key} delivered ${handed} message(s) and answer(s)${guard.held.length ? `, holding ${guard.held.length}` : ""}`);
172
259
  // The receipt stops before the first held message: those did not go in.
173
260
  if (handed)
174
- report(seat, { through: result.through, state: outcome.kind === "in-doubt" ? "in_doubt" : "delivered", waiting: result.waiting, messages: result.messages });
261
+ report(seat, { through: result.through, state: outcome.kind === "in-doubt" ? "in_doubt" : "delivered", waiting: result.waiting, messages: result.messages, ...station });
175
262
  else
176
- report(seat, { waiting: result.waiting });
263
+ report(seat, { waiting: result.waiting, ...station });
177
264
  }
178
265
  else if (guard.held.length)
179
266
  report(seat, { waiting: result.waiting });
@@ -245,6 +332,7 @@ export async function runDaemon(home) {
245
332
  function add(joined) {
246
333
  const key = keyOf(joined);
247
334
  closers.get(key)?.();
335
+ openSaid.delete(key);
248
336
  // Joining again keeps what the loop guard holds: those messages are not lost.
249
337
  const held = find(key)?.guard;
250
338
  const seat = held ? { ...joined, guard: held } : joined;
@@ -260,8 +348,12 @@ export async function runDaemon(home) {
260
348
  closers.get(key)?.();
261
349
  closers.delete(key);
262
350
  waitingSent.delete(key);
351
+ openSaid.delete(key);
263
352
  lent.delete(key);
353
+ forHook.delete(key);
354
+ hookLent.delete(key);
264
355
  people.delete(key);
356
+ // Its Stop hook stops waiting when it asks again and finds no seat.
265
357
  seats = seats.map((s) => keyOf(s) === key ? { ...s, left: true } : s);
266
358
  save();
267
359
  if (!seats.some((s) => !s.left))
@@ -279,11 +371,11 @@ export async function runDaemon(home) {
279
371
  while (pumping.has(key))
280
372
  await new Promise((resolve) => setTimeout(resolve, 50));
281
373
  const seat = find(key);
282
- if (!seat?.guard?.held.length)
374
+ if (!seat?.guard?.held.length || lent.get(key) === Infinity)
283
375
  return { text: null, ids: [] };
284
376
  pumping.add(key);
285
377
  try {
286
- const read = await readHeld(seat, seat.guard, roomOf(key), selfCommand());
378
+ const read = await readHeld(seat, seat.guard, roomOf(seat), selfCommand());
287
379
  // Nothing left of them in the room: there is nothing to write out.
288
380
  if (!read.text)
289
381
  tookHeld(key, read.ids);
@@ -297,6 +389,95 @@ export async function runDaemon(home) {
297
389
  void pump(key);
298
390
  }
299
391
  }
392
+ /** What is new for one seat, for its session's hook. Like one round of
393
+ * the pump, but the text goes back to the hook, and the seat's position
394
+ * moves only when the hook says it wrote the text out (`hookTook`). No
395
+ * word within LENT_MS and the pump has the messages again. */
396
+ async function hookPull(key, token, how, signal, maxBytes) {
397
+ // Nothing changed in the room since the last look: no call to the relay.
398
+ if (signal?.aborted || !forHook.delete(key))
399
+ return null;
400
+ while (pumping.has(key) && !signal?.aborted)
401
+ await new Promise((resolve) => setTimeout(resolve, 50));
402
+ if (signal?.aborted) {
403
+ forHook.add(key);
404
+ return null;
405
+ }
406
+ const seat = find(key);
407
+ if (!seat || (lent.get(key) ?? 0) > Date.now())
408
+ return null;
409
+ pumping.add(key);
410
+ try {
411
+ let answer = await seatCall(seat, `/messages?after=${seat.after}`, { signal });
412
+ const before = seat.guard ?? freshGuard();
413
+ const otherRooms = seats.some((s) => s.sessionId === seat.sessionId && s.roomId !== seat.roomId);
414
+ const handOut = () => handOver(() => find(key) ?? seat, before, answer, roomOf(seat, signal), Date.now(), selfCommand(), otherRooms, true);
415
+ let result = await handOut();
416
+ // A full page, or more than one hook's text: there is more to read on the hook's next run.
417
+ if (answer.messages.length >= 100)
418
+ forHook.add(key);
419
+ // Whole messages only: the first half of the batch, until it fits or one message is left.
420
+ const overBudget = (text) => maxBytes !== undefined && Buffer.byteLength(text) > maxBytes;
421
+ while (result.text && (result.text.length > HOOK_TEXT_CHARS || overBudget(result.text)) && answer.messages.length > 1) {
422
+ const messages = answer.messages.slice(0, Math.floor(answer.messages.length / 2));
423
+ answer = { ...answer, messages, next_after: messages[messages.length - 1].id };
424
+ result = await handOut();
425
+ forHook.add(key);
426
+ }
427
+ const current = find(key);
428
+ if (!current)
429
+ return null;
430
+ signal?.throwIfAborted();
431
+ if (result.text && overBudget(result.text)) {
432
+ forHook.add(key);
433
+ return null;
434
+ }
435
+ const moved = { ...current, after: answer.next_after, guard: result.guard };
436
+ if (!result.text) {
437
+ if (answer.next_after !== current.after || JSON.stringify(result.guard) !== JSON.stringify(before)) {
438
+ seats = seats.map((s) => (keyOf(s) === key ? moved : s));
439
+ save();
440
+ log(`${key} hook: ${answer.messages.length} new, nothing for the session`);
441
+ }
442
+ if (result.guard.held.length)
443
+ report(current, { waiting: result.waiting });
444
+ return null;
445
+ }
446
+ hookLent.set(key, { token, from: current.after, moved, receipt: { through: result.through, waiting: result.waiting, messages: result.messages }, handed: result.handed, how });
447
+ lent.set(key, Date.now() + LENT_MS);
448
+ return result.text;
449
+ }
450
+ catch (error) {
451
+ // Still there for the next run, or for the pump when the turn ends.
452
+ forHook.add(key);
453
+ if (!signal?.aborted)
454
+ log(`${key} hook read failed: ${error instanceof Error ? error.message : String(error)}`);
455
+ return null;
456
+ }
457
+ finally {
458
+ pumping.delete(key);
459
+ again.delete(key);
460
+ }
461
+ }
462
+ /** The hook wrote out what it was given: the seat moves past it. */
463
+ function hookTook(key, token) {
464
+ const given = hookLent.get(key);
465
+ if (!given || given.token !== token)
466
+ return;
467
+ hookLent.delete(key);
468
+ const seat = find(key);
469
+ // Too late: the pump took the messages back and may have delivered them.
470
+ if (!seat || seat.after !== given.from || (lent.get(key) ?? 0) <= Date.now())
471
+ return;
472
+ lent.delete(key);
473
+ seats = seats.map((s) => (keyOf(s) === key ? given.moved : s));
474
+ save();
475
+ if (given.handed)
476
+ report(given.moved, { through: given.receipt.through, state: "delivered", waiting: given.receipt.waiting, messages: given.receipt.messages, how: given.how });
477
+ else
478
+ report(given.moved, { waiting: given.receipt.waiting });
479
+ log(`${key} handed ${given.handed} message(s) and answer(s) to the session's hook (${given.how === "woke" ? "woke it" : "mid-task"})`);
480
+ }
300
481
  function tookHeld(key, ids) {
301
482
  lent.delete(key);
302
483
  const seat = find(key);
@@ -313,6 +494,8 @@ export async function runDaemon(home) {
313
494
  const waking = createWaking({
314
495
  home,
315
496
  log,
497
+ deliver: deliverAsk,
498
+ releaseAsk,
316
499
  seats: () => seats,
317
500
  join: async (session, url) => {
318
501
  const { seat } = await joinRoom(home, session, url, {
@@ -326,7 +509,327 @@ export async function runDaemon(home) {
326
509
  },
327
510
  leave: (seat) => drop(keyOf(seat), true),
328
511
  });
329
- const respond = async (request) => {
512
+ /** What is new for each of the session's seats, under one token. */
513
+ async function pullAll(keys, token, how, sessionKey, signal, maxBytes) {
514
+ const room = [];
515
+ let remaining = maxBytes;
516
+ const waiting = [...(asksFor.get(sessionKey)?.values() ?? [])];
517
+ // The rooms first: each read hears its seat's switch, and a seat with an ask waiting reads it now.
518
+ for (const ask of waiting)
519
+ forHook.add(keyOf(ask.chat));
520
+ for (const key of keys) {
521
+ if (remaining !== undefined && remaining <= 0)
522
+ break;
523
+ const text = await hookPull(key, token, how, signal, remaining);
524
+ if (text) {
525
+ room.push(text);
526
+ if (remaining !== undefined)
527
+ remaining -= Buffer.byteLength(text) + 2;
528
+ }
529
+ }
530
+ if (signal?.aborted)
531
+ return null;
532
+ const texts = [];
533
+ // Asks to the agent go in by the same path, first: they are what it was sent (deliverAsk).
534
+ for (const ask of waiting) {
535
+ if (ask.done || ask.releasing || (ask.lent && ask.lent.until > Date.now()))
536
+ continue;
537
+ if (remaining !== undefined) {
538
+ const bytes = Buffer.byteLength(ask.text);
539
+ if (bytes > remaining)
540
+ continue;
541
+ remaining -= bytes + 2;
542
+ }
543
+ ask.lent = { token, until: Date.now() + LENT_MS };
544
+ texts.push(ask.text);
545
+ }
546
+ texts.push(...room);
547
+ return texts.length ? texts.join("\n\n") : null;
548
+ }
549
+ /** Asks to the agent waiting for a session's hook, by message id. */
550
+ const askSession = (harness, sessionId) => `${harness}:${sessionId}`;
551
+ const asksFor = new Map();
552
+ async function releaseAsk(chat, messageId) {
553
+ const pending = asksFor.get(askSession(chat.harness, chat.sessionId));
554
+ const ask = pending?.get(messageId);
555
+ if (!ask)
556
+ return false;
557
+ ask.releasing = true;
558
+ const stop = chat.harness === "codex" ? codexStops.get(chat.sessionId) : undefined;
559
+ if (stop && ask.lent?.token === stop.token)
560
+ await stop.settled;
561
+ const remaining = (ask.lent?.until ?? 0) - Date.now();
562
+ if (!ask.done && remaining > 0) {
563
+ await Promise.race([ask.taken, new Promise((resolve) => setTimeout(resolve, remaining).unref())]);
564
+ }
565
+ pending?.delete(messageId);
566
+ return ask.done === true;
567
+ }
568
+ function acknowledgeHook(sessionId, sessionKey, keys, token) {
569
+ for (const key of keys)
570
+ hookTook(key, token);
571
+ for (const [id, ask] of asksFor.get(sessionKey) ?? []) {
572
+ if (ask.done || ask.lent?.token !== token)
573
+ continue;
574
+ // Kept, marked done, until the wake's try hears it.
575
+ ask.done = true;
576
+ ask.took();
577
+ log(`${sessionId} took ask ${id} through its hook`);
578
+ }
579
+ }
580
+ function checkCodexStop(sessionId) {
581
+ const stop = codexStops.get(sessionId);
582
+ if (!stop)
583
+ return;
584
+ const { token, turnId, keys } = stop;
585
+ const status = stopDeliveryStatus(stop.profile, sessionId, turnId, token);
586
+ // Another Stop hook may take longer than the normal delivery lease.
587
+ // Never queue behind the same live turn while it can still accept this batch.
588
+ if ((status === "running" || status === "unknown") && (stop.until > Date.now() || keys.some((key) => {
589
+ const seat = find(key);
590
+ return seat && running(seat) && (status === "running" || !threadIdle(stop.profile, sessionId));
591
+ })))
592
+ return;
593
+ clearTimeout(stop.timer);
594
+ codexStops.delete(sessionId);
595
+ const sessionKey = askSession("codex", sessionId);
596
+ if (status === "accepted")
597
+ acknowledgeHook(sessionId, sessionKey, keys, token);
598
+ else {
599
+ if (busy.get(sessionId)?.turnId === turnId)
600
+ busy.delete(sessionId);
601
+ for (const key of keys) {
602
+ if (hookLent.get(key)?.token !== token)
603
+ continue;
604
+ hookLent.delete(key);
605
+ lent.delete(key);
606
+ forHook.add(key);
607
+ }
608
+ for (const ask of asksFor.get(sessionKey)?.values() ?? []) {
609
+ if (ask.lent?.token === token)
610
+ ask.lent = undefined;
611
+ }
612
+ }
613
+ stop.settle();
614
+ }
615
+ function holdCodexStop(sessionId, turnId, keys, token, profile) {
616
+ let settle = () => { };
617
+ const settled = new Promise((resolve) => (settle = resolve));
618
+ const stop = { token, turnId, keys, profile, until: Date.now() + LENT_MS, settled, settle, timer: undefined };
619
+ codexStops.set(sessionId, stop);
620
+ for (const key of keys) {
621
+ if (hookLent.get(key)?.token === token)
622
+ lent.set(key, Infinity);
623
+ }
624
+ for (const ask of asksFor.get(askSession("codex", sessionId))?.values() ?? []) {
625
+ if (ask.lent?.token === token)
626
+ ask.lent.until = Infinity;
627
+ }
628
+ const poll = () => {
629
+ checkCodexStop(sessionId);
630
+ if (codexStops.get(sessionId) === stop)
631
+ stop.timer = setTimeout(poll, 1000).unref();
632
+ else
633
+ for (const key of keys)
634
+ void pump(key);
635
+ };
636
+ stop.timer = setTimeout(poll, 1000).unref();
637
+ }
638
+ /** How an ask to the agent goes into its open window (waking.ts): through
639
+ * the session's hooks while they run or wait, as its room messages do, so
640
+ * a window has one way in; else into its inbox as before. Delivered once
641
+ * a hook wrote it out; a retry until then, which asks again with the same
642
+ * message id and so waits for the same hand-over. */
643
+ async function deliverAsk(chat, messageId, text) {
644
+ const { harness, sessionId } = chat;
645
+ const sessionKey = askSession(harness, sessionId);
646
+ const hooked = hookTakes(chat);
647
+ const waiting = asksFor.get(sessionKey)?.get(messageId);
648
+ // A hook wrote it out between two tries: it is in.
649
+ if (waiting?.done) {
650
+ asksFor.get(sessionKey)?.delete(messageId);
651
+ return { kind: "delivered" };
652
+ }
653
+ // No hook runs or waits (none ever did, or an interrupted turn's hold ran
654
+ // out): the inbox. Not while a hook holds the ask lent: it may still be
655
+ // writing it out. A queued ask is held for the inbox during the try and
656
+ // leaves the queue only when the inbox took it; with no inbox it stays
657
+ // for the session's next hook.
658
+ if (!hooked && !(waiting?.lent && waiting.lent.until > Date.now())) {
659
+ const held = { token: `inbox-${randomUUID()}`, until: Date.now() + LENT_MS };
660
+ if (waiting)
661
+ waiting.lent = held;
662
+ const outcome = await deliverTo(harness, sessionId, messageId, text, chat.codexHome);
663
+ if (outcome.kind === "retry") {
664
+ if (waiting?.lent === held)
665
+ waiting.lent = undefined;
666
+ return outcome;
667
+ }
668
+ if (waiting) {
669
+ asksFor.get(sessionKey)?.delete(messageId);
670
+ waiting.took();
671
+ }
672
+ return outcome;
673
+ }
674
+ let ask = waiting;
675
+ if (!ask) {
676
+ let took = () => { };
677
+ const taken = new Promise((resolve) => (took = resolve));
678
+ ask = { chat, text, took: () => took(), taken };
679
+ asksFor.set(sessionKey, (asksFor.get(sessionKey) ?? new Map()).set(messageId, ask));
680
+ }
681
+ if (harness === "claude-code")
682
+ waiters.get(sessionId)?.();
683
+ const done = await Promise.race([ask.taken.then(() => true), new Promise((resolve) => setTimeout(() => resolve(false), HOOK_WAIT_MS).unref())]);
684
+ if (!done)
685
+ return { kind: "retry", reason: "The session's hook has not taken it yet." };
686
+ if (asksFor.get(sessionKey)?.get(messageId) === ask)
687
+ asksFor.get(sessionKey)?.delete(messageId);
688
+ return { kind: "delivered" };
689
+ }
690
+ /** The hook's three asks. Every answer is quick except a Stop hook's wait,
691
+ * which lasts until something comes or HOOK_WAIT_MS passes. */
692
+ async function hookAnswer(request, closed) {
693
+ if (request.v !== HOOK_PROTOCOL) {
694
+ log(`${request.sessionId} hook speaks protocol ${request.v ?? "none"}, this daemon ${HOOK_PROTOCOL}: its messages go the old way`);
695
+ return { ok: false, error: `This hook speaks protocol ${request.v ?? "none"}; Station ${VERSION} speaks ${HOOK_PROTOCOL}. Join again to update it.` };
696
+ }
697
+ const sessionId = request.sessionId;
698
+ const harness = request.op === "codexHook" || (request.op === "hookRead" && request.harness === "codex") ? "codex" : "claude-code";
699
+ const sessionKey = askSession(harness, sessionId);
700
+ if (harness === "claude-code" && "configDir" in request && typeof request.configDir === "string")
701
+ claudeHomes.set(sessionId, claudeHome({ CLAUDE_CONFIG_DIR: request.configDir }));
702
+ // A hook runs in every session in the profile: one with no
703
+ // seat, or a computer whose person took hooks back, gets nothing, and fast.
704
+ const mine = seats.filter((s) => !s.left && s.sessionId === sessionId && s.harness === harness).map(keyOf);
705
+ if (!mine.length || !hooksAllowed(home))
706
+ return { ok: true, text: null };
707
+ if (request.op === "hookRead") {
708
+ if (harness !== "codex" || codexStops.get(sessionId)?.token !== request.token)
709
+ acknowledgeHook(sessionId, sessionKey, mine, request.token);
710
+ return { ok: true };
711
+ }
712
+ const token = randomUUID();
713
+ if (request.op === "codexHook") {
714
+ checkCodexStop(sessionId);
715
+ if (codexStops.has(sessionId))
716
+ return { ok: true, text: null };
717
+ const previous = busy.get(sessionId);
718
+ const stopping = request.event === "Stop";
719
+ if (stopping && previous && previous.turnId !== request.turnId)
720
+ return { ok: true, text: null };
721
+ const turn = previous?.turnId === request.turnId ? previous : { turnId: request.turnId, until: 0 };
722
+ turn.until = Date.now() + BUSY_MS;
723
+ busy.set(sessionId, turn);
724
+ try {
725
+ if (stopping && request.stopHookActive)
726
+ return { ok: true, text: null };
727
+ const profile = find(mine[0])?.codexHome ?? codexHome();
728
+ if (stopping && !rolloutPath(profile, sessionId))
729
+ return { ok: true, text: null };
730
+ if (stopping || turn !== previous)
731
+ for (const key of mine)
732
+ forHook.add(key);
733
+ const suffix = stopping ? `\n\n${stopDeliveryMarker(token)}` : "";
734
+ const text = await pullAll(mine, token, "mid_task", sessionKey, closed, stopping ? STOP_OUTPUT_BYTES - Buffer.byteLength(suffix) : undefined);
735
+ if (stopping && text && !closed.aborted) {
736
+ holdCodexStop(sessionId, request.turnId, mine, token, profile);
737
+ return { ok: true, text: text + suffix, token };
738
+ }
739
+ return text ? { ok: true, text, token } : { ok: true, text: null };
740
+ }
741
+ finally {
742
+ if (closed.aborted)
743
+ for (const key of mine) {
744
+ if (hookLent.get(key)?.token !== token)
745
+ continue;
746
+ hookLent.delete(key);
747
+ lent.delete(key);
748
+ forHook.add(key);
749
+ }
750
+ if (((stopping && !codexStops.has(sessionId)) || closed.aborted) && busy.get(sessionId) === turn)
751
+ busy.delete(sessionId);
752
+ }
753
+ }
754
+ if (request.op === "hook") {
755
+ if (request.event === "SessionEnd") {
756
+ busy.delete(sessionId);
757
+ // Its asks go the other way now (waking.ts tries again, or continues the chat).
758
+ asksFor.delete(sessionKey);
759
+ return { ok: true, text: null };
760
+ }
761
+ if (!inTurn({ harness, sessionId }))
762
+ log(`${sessionId} in a turn, by its hook`);
763
+ busy.set(sessionId, { until: Date.now() + BUSY_MS });
764
+ const text = await pullAll(mine, token, "mid_task", sessionKey);
765
+ return text ? { ok: true, text, token } : { ok: true, text: null };
766
+ }
767
+ // The turn ended and the Stop hook waits in the background. Its later
768
+ // asks say nothing of the turn: the person may have typed since.
769
+ if (!request.again && busy.delete(sessionId))
770
+ log(`${sessionId} turn ended, its Stop hook waits`);
771
+ for (const key of mine)
772
+ forHook.add(key);
773
+ const now = inTurn({ harness, sessionId }) ? null : await pullAll(mine, token, "woke", sessionKey);
774
+ if (now) {
775
+ busy.set(sessionId, { until: Date.now() + BUSY_MS });
776
+ return { ok: true, text: now, token };
777
+ }
778
+ return new Promise((resolve) => {
779
+ let done = false;
780
+ const finish = (response) => {
781
+ if (done)
782
+ return;
783
+ done = true;
784
+ clearTimeout(timer);
785
+ if (waiters.get(sessionId) === poke)
786
+ waiters.delete(sessionId);
787
+ closed.removeEventListener("abort", gone);
788
+ resolve(response);
789
+ };
790
+ // One pull at a time under this hook's token: two at once would each
791
+ // lend messages under it, and the hook's receipt would mark the batch
792
+ // it never got delivered. A poke during a pull pulls again after it.
793
+ let pulling = false;
794
+ let pokedAgain = false;
795
+ const poke = () => {
796
+ // Taken back meanwhile (station logout): the hook stops waiting, and wakes nothing.
797
+ if (!hooksAllowed(home))
798
+ return finish({ ok: true, text: null });
799
+ // A turn is under way: its step hooks hand messages over.
800
+ if (done || inTurn({ harness, sessionId }))
801
+ return;
802
+ if (pulling) {
803
+ pokedAgain = true;
804
+ return;
805
+ }
806
+ pulling = true;
807
+ void pullAll(mine, token, "woke", sessionKey).then((text) => {
808
+ pulling = false;
809
+ if (done)
810
+ return;
811
+ if (text) {
812
+ // The session wakes into a turn: what comes next waits for its hooks.
813
+ busy.set(sessionId, { until: Date.now() + BUSY_MS });
814
+ return finish({ ok: true, text, token });
815
+ }
816
+ if (pokedAgain) {
817
+ pokedAgain = false;
818
+ poke();
819
+ }
820
+ }, () => {
821
+ pulling = false;
822
+ });
823
+ };
824
+ // Claude Code stopped the hook (the session closed, or the person typed):
825
+ // what comes goes the old way until a hook runs again.
826
+ const gone = () => finish({ ok: true, text: null });
827
+ const timer = setTimeout(() => finish({ ok: true, wait: true }), HOOK_WAIT_MS);
828
+ waiters.set(sessionId, poke);
829
+ closed.addEventListener("abort", gone);
830
+ });
831
+ }
832
+ const respond = async (request, closed = new AbortController().signal) => {
330
833
  if (request.op === "ping" || request.op === "list")
331
834
  return { ok: true, seats, version: VERSION };
332
835
  if (request.op === "stop") {
@@ -348,6 +851,8 @@ export async function runDaemon(home) {
348
851
  save();
349
852
  return { ok: true };
350
853
  }
854
+ if (request.op === "hook" || request.op === "hookWait" || request.op === "hookRead" || request.op === "codexHook")
855
+ return hookAnswer(request, closed);
351
856
  if (request.op !== "read" && request.op !== "held" && request.op !== "heldRead")
352
857
  return { ok: false, error: "unknown request" };
353
858
  const key = keyOf(request);
@@ -366,13 +871,15 @@ export async function runDaemon(home) {
366
871
  const server = createServer((socket) => {
367
872
  let buffer = "";
368
873
  let answered = false;
874
+ const closed = new AbortController();
875
+ socket.on("close", () => closed.abort());
369
876
  socket.on("data", (chunk) => {
370
877
  buffer += chunk.toString("utf8");
371
878
  const end = buffer.indexOf("\n");
372
879
  if (end < 0 || answered)
373
880
  return;
374
881
  answered = true;
375
- new Promise((resolve) => resolve(respond(JSON.parse(buffer.slice(0, end)))))
882
+ new Promise((resolve) => resolve(respond(JSON.parse(buffer.slice(0, end)), closed.signal)))
376
883
  .catch((error) => ({ ok: false, error: error instanceof Error ? error.message : String(error) }))
377
884
  .then((response) => socket.end(`${JSON.stringify(response)}\n`));
378
885
  });
@@ -395,11 +902,13 @@ export async function runDaemon(home) {
395
902
  // A shell's agent reads for itself: the daemon has nothing to do for it.
396
903
  if (!delivers(seat.harness))
397
904
  continue;
398
- if (isRunning(seat.harness, seat.sessionId)) {
905
+ if (running(seat)) {
399
906
  missingSince.delete(seat.sessionId);
907
+ tellOpen(seat, true);
400
908
  void pump(key);
401
909
  }
402
910
  else {
911
+ tellOpen(seat, false);
403
912
  const since = missingSince.get(seat.sessionId) ?? Date.now();
404
913
  missingSince.set(seat.sessionId, since);
405
914
  if (Date.now() - since > GONE_MS)
@@ -419,7 +928,7 @@ export async function runDaemon(home) {
419
928
  waking.stop();
420
929
  // Station starts nothing on this computer from now: it hears so at once.
421
930
  const credentials = readCredentials(home);
422
- if (credentials)
931
+ if (credentials?.token)
423
932
  void call(credentials.relayUrl, "/cli/wakes", { token: credentials.token }, { method: "DELETE" }).catch(() => { });
424
933
  for (const close of closers.values())
425
934
  close();
@@ -431,6 +940,16 @@ export async function runDaemon(home) {
431
940
  process.on("SIGTERM", () => stop("SIGTERM"));
432
941
  process.on("SIGINT", () => stop("SIGINT"));
433
942
  }
943
+ /** What to tell the relay about a device-linked seat's window, once per
944
+ * change: `session_open: false` while it is closed and the daemon still
945
+ * reads the room for its return, so an ask to the agent as a whole goes to
946
+ * another computer meanwhile (the relay's wake.ts). Null: nothing new. */
947
+ export function windowOpenReport(said, key, seat, credentials, open) {
948
+ if (seat.via !== "cli" || credentials?.allowHooks === undefined || said.get(key) === open)
949
+ return null;
950
+ said.set(key, open);
951
+ return { session_open: open };
952
+ }
434
953
  /** Whether a daemon answers on the socket. */
435
954
  export function answers(socketPath) {
436
955
  return ask(socketPath, { op: "ping" }).then((response) => response.ok, () => false);