@santori/station 0.9.11 → 0.9.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/commands.js CHANGED
@@ -188,6 +188,19 @@ export const reads = {
188
188
  },
189
189
  };
190
190
  /** The tool's inputs from the words after the command. */
191
+ /** The room a command acts in: the one given with --room, else the room
192
+ * this session has a seat in. A tool that needs a room and gets neither
193
+ * says how to get one; one that can do without (a report to Station's
194
+ * team) goes with none. */
195
+ export function roomFor(me, tool, inputs, seat, threadHint = "") {
196
+ if (!("room" in (tool.inputSchema.properties ?? {})) || inputs.room !== undefined)
197
+ return inputs.room;
198
+ if (seat)
199
+ return `${seat.relayUrl}/${seat.roomId}`;
200
+ if (!(tool.inputSchema.required ?? []).includes("room"))
201
+ return undefined;
202
+ throw new Usage(`This session has no seat in a room. Run ${me} join <room-url> first, or name the room with --room.${threadHint}`);
203
+ }
191
204
  export async function inputsFrom(me, tool, argv, io = reads) {
192
205
  const cli = cliOf(tool);
193
206
  const known = props(tool);
@@ -240,8 +253,11 @@ export async function inputsFrom(me, tool, argv, io = reads) {
240
253
  throw wrong(`Could not read ${given.slice(1)}.`);
241
254
  }
242
255
  }
243
- else
244
- inputs[name] = scalar(given, prop);
256
+ else {
257
+ const value = scalar(given, prop);
258
+ // A flag that also takes a list, given again, is a list of each (`--to A --to B`).
259
+ inputs[name] = allows(prop, "array") && name in inputs ? [...(Array.isArray(inputs[name]) ? inputs[name] : [inputs[name]]), value] : value;
260
+ }
245
261
  }
246
262
  if (positional.length > cli.args.length)
247
263
  throw wrong(`${cli.command} takes ${cli.args.length === 1 ? "one thing" : `${cli.args.length} things`} without a flag; ${JSON.stringify(positional[cli.args.length])} is one too many.`);
package/dist/daemon.js CHANGED
@@ -42,8 +42,9 @@ import { call, seatOver } from "./relay.js";
42
42
  import { authFor, loadSeats, roomLabel, withOwner } from "./seats.js";
43
43
  import { HARNESS_NAMES, delivers, deliverTo, isRunning } from "./sessions.js";
44
44
  import { claudeHome } from "./claude.js";
45
+ import { codexHome, rolloutPath, STOP_OUTPUT_BYTES, stopDeliveryMarker, stopDeliveryStatus, threadIdle } from "./codex.js";
45
46
  import { clearJoinRequest, daemonEnv, joinRoom } from "./join.js";
46
- import { createWaking } from "./waking.js";
47
+ import { createWaking, wakeCredentials } from "./waking.js";
47
48
  const SAFETY_MS = 30_000;
48
49
  const RETRY_MS = 15_000;
49
50
  /** A session gone this long has ended; its seats leave their rooms. */
@@ -102,8 +103,10 @@ export async function runDaemon(home) {
102
103
  const waitingSent = new Map();
103
104
  /** Seats whose held messages `station wait` is writing out, and until when. */
104
105
  const lent = new Map();
105
- /** Sessions in a turn, by their hook's word, and until when that word holds. */
106
+ /** Sessions in a turn, by their hook's word, until when that word holds,
107
+ * and for Codex the turn's id. */
106
108
  const busy = new Map();
109
+ const codexStops = new Map();
107
110
  /** The Claude Code profile each session's hook runs under, by its own
108
111
  * CLAUDE_CONFIG_DIR: the session's registry entry is there, not always
109
112
  * in the daemon's. */
@@ -138,7 +141,7 @@ export async function runDaemon(home) {
138
141
  * sent once per reason, not on every retry. */
139
142
  const report = (seat, receipt) => {
140
143
  const key = keyOf(seat);
141
- if (receipt.through === undefined && waitingSent.get(key) === receipt.waiting)
144
+ if (receipt.through === undefined && !receipt.station?.length && waitingSent.get(key) === receipt.waiting)
142
145
  return;
143
146
  waitingSent.set(key, receipt.waiting);
144
147
  void seatCall(seat, "/delivery", { body: receipt }).catch((error) => log(`${key} receipt not sent: ${error instanceof Error ? error.message : String(error)}`));
@@ -146,12 +149,12 @@ export async function runDaemon(home) {
146
149
  let emptySince = seats.some((s) => !s.left) ? null : Date.now();
147
150
  const save = () => writeJson(paths.seats, seats);
148
151
  const find = (key) => seats.find((seat) => keyOf(seat) === key && !seat.left) ?? null;
149
- const participantsFor = async (seat, authors) => {
152
+ const participantsFor = async (seat, authors, signal) => {
150
153
  const key = keyOf(seat);
151
154
  const known = people.get(key) ?? [];
152
155
  if (authors.every((id) => known.some((p) => p.id === id)))
153
156
  return known;
154
- const room = await seatCall(seat, "");
157
+ const room = await seatCall(seat, "", { signal });
155
158
  people.set(key, room.participants);
156
159
  // Someone new spoke: maybe the person this seat works for, come in late.
157
160
  const learned = withOwner(seat, room.owner);
@@ -165,10 +168,34 @@ export async function runDaemon(home) {
165
168
  /** Reads a seat's room for the hand-over: its people, and held messages
166
169
  * again by id. As that seat, even when it left meanwhile: its caller then
167
170
  * 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`)),
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 })),
171
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
+ }
172
199
  async function pump(key) {
173
200
  // A shell's agent reads for itself with station wait.
174
201
  const target = find(key);
@@ -177,19 +204,11 @@ export async function runDaemon(home) {
177
204
  // `station wait` or the hook is writing messages out: do not deliver them too.
178
205
  if ((lent.get(key) ?? 0) > Date.now())
179
206
  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
- }
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;
193
212
  }
194
213
  if (pumping.has(key)) {
195
214
  again.add(key);
@@ -199,17 +218,26 @@ export async function runDaemon(home) {
199
218
  try {
200
219
  let seat = find(key);
201
220
  while (seat) {
202
- 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`);
203
223
  if (!find(key))
204
224
  break;
205
225
  const before = seat.guard ?? freshGuard();
206
226
  const otherRooms = seats.some((s) => s.sessionId === seat.sessionId && s.roomId !== seat.roomId);
207
227
  const result = await handOver(() => find(key) ?? seat, before, answer, roomOf(seat), Date.now(), selfCommand(), otherRooms);
208
- const { text, handed, guard } = result;
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) } : {};
209
233
  seat = find(key);
210
234
  if (!seat)
211
235
  break;
212
236
  if (text) {
237
+ if (seat.harness === "codex" && hookTakes(seat)) {
238
+ forHook.add(key);
239
+ break;
240
+ }
213
241
  if (!delivers(seat.harness) || !running(seat)) {
214
242
  // The tick decides whether it ended.
215
243
  if (handed)
@@ -230,9 +258,9 @@ export async function runDaemon(home) {
230
258
  log(`${key} delivered ${handed} message(s) and answer(s)${guard.held.length ? `, holding ${guard.held.length}` : ""}`);
231
259
  // The receipt stops before the first held message: those did not go in.
232
260
  if (handed)
233
- 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 });
234
262
  else
235
- report(seat, { waiting: result.waiting });
263
+ report(seat, { waiting: result.waiting, ...station });
236
264
  }
237
265
  else if (guard.held.length)
238
266
  report(seat, { waiting: result.waiting });
@@ -343,7 +371,7 @@ export async function runDaemon(home) {
343
371
  while (pumping.has(key))
344
372
  await new Promise((resolve) => setTimeout(resolve, 50));
345
373
  const seat = find(key);
346
- if (!seat?.guard?.held.length)
374
+ if (!seat?.guard?.held.length || lent.get(key) === Infinity)
347
375
  return { text: null, ids: [] };
348
376
  pumping.add(key);
349
377
  try {
@@ -365,27 +393,32 @@ export async function runDaemon(home) {
365
393
  * the pump, but the text goes back to the hook, and the seat's position
366
394
  * moves only when the hook says it wrote the text out (`hookTook`). No
367
395
  * word within LENT_MS and the pump has the messages again. */
368
- async function hookPull(key, token, how) {
396
+ async function hookPull(key, token, how, signal, maxBytes) {
369
397
  // Nothing changed in the room since the last look: no call to the relay.
370
- if (!forHook.delete(key))
398
+ if (signal?.aborted || !forHook.delete(key))
371
399
  return null;
372
- while (pumping.has(key))
400
+ while (pumping.has(key) && !signal?.aborted)
373
401
  await new Promise((resolve) => setTimeout(resolve, 50));
402
+ if (signal?.aborted) {
403
+ forHook.add(key);
404
+ return null;
405
+ }
374
406
  const seat = find(key);
375
407
  if (!seat || (lent.get(key) ?? 0) > Date.now())
376
408
  return null;
377
409
  pumping.add(key);
378
410
  try {
379
- let answer = await seatCall(seat, `/messages?after=${seat.after}`);
411
+ let answer = await seatCall(seat, `/messages?after=${seat.after}`, { signal });
380
412
  const before = seat.guard ?? freshGuard();
381
413
  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);
414
+ const handOut = () => handOver(() => find(key) ?? seat, before, answer, roomOf(seat, signal), Date.now(), selfCommand(), otherRooms, true);
383
415
  let result = await handOut();
384
416
  // A full page, or more than one hook's text: there is more to read on the hook's next run.
385
417
  if (answer.messages.length >= 100)
386
418
  forHook.add(key);
387
419
  // 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) {
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) {
389
422
  const messages = answer.messages.slice(0, Math.floor(answer.messages.length / 2));
390
423
  answer = { ...answer, messages, next_after: messages[messages.length - 1].id };
391
424
  result = await handOut();
@@ -394,6 +427,11 @@ export async function runDaemon(home) {
394
427
  const current = find(key);
395
428
  if (!current)
396
429
  return null;
430
+ signal?.throwIfAborted();
431
+ if (result.text && overBudget(result.text)) {
432
+ forHook.add(key);
433
+ return null;
434
+ }
397
435
  const moved = { ...current, after: answer.next_after, guard: result.guard };
398
436
  if (!result.text) {
399
437
  if (answer.next_after !== current.after || JSON.stringify(result.guard) !== JSON.stringify(before)) {
@@ -412,7 +450,8 @@ export async function runDaemon(home) {
412
450
  catch (error) {
413
451
  // Still there for the next run, or for the pump when the turn ends.
414
452
  forHook.add(key);
415
- log(`${key} hook read failed: ${error instanceof Error ? error.message : String(error)}`);
453
+ if (!signal?.aborted)
454
+ log(`${key} hook read failed: ${error instanceof Error ? error.message : String(error)}`);
416
455
  return null;
417
456
  }
418
457
  finally {
@@ -456,6 +495,7 @@ export async function runDaemon(home) {
456
495
  home,
457
496
  log,
458
497
  deliver: deliverAsk,
498
+ releaseAsk,
459
499
  seats: () => seats,
460
500
  join: async (session, url) => {
461
501
  const { seat } = await joinRoom(home, session, url, {
@@ -470,22 +510,36 @@ export async function runDaemon(home) {
470
510
  leave: (seat) => drop(keyOf(seat), true),
471
511
  });
472
512
  /** What is new for each of the session's seats, under one token. */
473
- async function pullAll(keys, token, how, sessionId) {
513
+ async function pullAll(keys, token, how, sessionKey, signal, maxBytes) {
474
514
  const room = [];
475
- const waiting = [...((sessionId ? asksFor.get(sessionId) : undefined)?.values() ?? [])];
515
+ let remaining = maxBytes;
516
+ const waiting = [...(asksFor.get(sessionKey)?.values() ?? [])];
476
517
  // The rooms first: each read hears its seat's switch, and a seat with an ask waiting reads it now.
477
518
  for (const ask of waiting)
478
519
  forHook.add(keyOf(ask.chat));
479
520
  for (const key of keys) {
480
- const text = await hookPull(key, token, how);
481
- if (text)
521
+ if (remaining !== undefined && remaining <= 0)
522
+ break;
523
+ const text = await hookPull(key, token, how, signal, remaining);
524
+ if (text) {
482
525
  room.push(text);
526
+ if (remaining !== undefined)
527
+ remaining -= Buffer.byteLength(text) + 2;
528
+ }
483
529
  }
530
+ if (signal?.aborted)
531
+ return null;
484
532
  const texts = [];
485
533
  // Asks to the agent go in by the same path, first: they are what it was sent (deliverAsk).
486
534
  for (const ask of waiting) {
487
- if (ask.done || (ask.lent && ask.lent.until > Date.now()))
535
+ if (ask.done || ask.releasing || (ask.lent && ask.lent.until > Date.now()))
488
536
  continue;
537
+ if (remaining !== undefined) {
538
+ const bytes = Buffer.byteLength(ask.text);
539
+ if (bytes > remaining)
540
+ continue;
541
+ remaining -= bytes + 2;
542
+ }
489
543
  ask.lent = { token, until: Date.now() + LENT_MS };
490
544
  texts.push(ask.text);
491
545
  }
@@ -493,7 +547,94 @@ export async function runDaemon(home) {
493
547
  return texts.length ? texts.join("\n\n") : null;
494
548
  }
495
549
  /** Asks to the agent waiting for a session's hook, by message id. */
550
+ const askSession = (harness, sessionId) => `${harness}:${sessionId}`;
496
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
+ }
497
638
  /** How an ask to the agent goes into its open window (waking.ts): through
498
639
  * the session's hooks while they run or wait, as its room messages do, so
499
640
  * a window has one way in; else into its inbox as before. Delivered once
@@ -501,11 +642,12 @@ export async function runDaemon(home) {
501
642
  * message id and so waits for the same hand-over. */
502
643
  async function deliverAsk(chat, messageId, text) {
503
644
  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);
645
+ const sessionKey = askSession(harness, sessionId);
646
+ const hooked = hookTakes(chat);
647
+ const waiting = asksFor.get(sessionKey)?.get(messageId);
506
648
  // A hook wrote it out between two tries: it is in.
507
649
  if (waiting?.done) {
508
- asksFor.get(sessionId)?.delete(messageId);
650
+ asksFor.get(sessionKey)?.delete(messageId);
509
651
  return { kind: "delivered" };
510
652
  }
511
653
  // No hook runs or waits (none ever did, or an interrupted turn's hold ran
@@ -524,7 +666,7 @@ export async function runDaemon(home) {
524
666
  return outcome;
525
667
  }
526
668
  if (waiting) {
527
- asksFor.get(sessionId)?.delete(messageId);
669
+ asksFor.get(sessionKey)?.delete(messageId);
528
670
  waiting.took();
529
671
  }
530
672
  return outcome;
@@ -534,14 +676,15 @@ export async function runDaemon(home) {
534
676
  let took = () => { };
535
677
  const taken = new Promise((resolve) => (took = resolve));
536
678
  ask = { chat, text, took: () => took(), taken };
537
- asksFor.set(sessionId, (asksFor.get(sessionId) ?? new Map()).set(messageId, ask));
679
+ asksFor.set(sessionKey, (asksFor.get(sessionKey) ?? new Map()).set(messageId, ask));
538
680
  }
539
- waiters.get(sessionId)?.();
681
+ if (harness === "claude-code")
682
+ waiters.get(sessionId)?.();
540
683
  const done = await Promise.race([ask.taken.then(() => true), new Promise((resolve) => setTimeout(() => resolve(false), HOOK_WAIT_MS).unref())]);
541
684
  if (!done)
542
685
  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);
686
+ if (asksFor.get(sessionKey)?.get(messageId) === ask)
687
+ asksFor.get(sessionKey)?.delete(messageId);
545
688
  return { kind: "delivered" };
546
689
  }
547
690
  /** The hook's three asks. Every answer is quick except a Stop hook's wait,
@@ -552,51 +695,84 @@ export async function runDaemon(home) {
552
695
  return { ok: false, error: `This hook speaks protocol ${request.v ?? "none"}; Station ${VERSION} speaks ${HOOK_PROTOCOL}. Join again to update it.` };
553
696
  }
554
697
  const sessionId = request.sessionId;
555
- if (typeof request.configDir === "string")
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")
556
701
  claudeHomes.set(sessionId, claudeHome({ CLAUDE_CONFIG_DIR: request.configDir }));
557
- // A hook runs in every Claude Code session on the computer: one with no
702
+ // A hook runs in every session in the profile: one with no
558
703
  // 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);
704
+ const mine = seats.filter((s) => !s.left && s.sessionId === sessionId && s.harness === harness).map(keyOf);
560
705
  if (!mine.length || !hooksAllowed(home))
561
706
  return { ok: true, text: null };
562
707
  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
- }
708
+ if (harness !== "codex" || codexStops.get(sessionId)?.token !== request.token)
709
+ acknowledgeHook(sessionId, sessionKey, mine, request.token);
574
710
  return { ok: true };
575
711
  }
576
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
+ }
577
754
  if (request.op === "hook") {
578
755
  if (request.event === "SessionEnd") {
579
756
  busy.delete(sessionId);
580
757
  // Its asks go the other way now (waking.ts tries again, or continues the chat).
581
- asksFor.delete(sessionId);
758
+ asksFor.delete(sessionKey);
582
759
  return { ok: true, text: null };
583
760
  }
584
- if (!((busy.get(sessionId) ?? 0) > Date.now()))
761
+ if (!inTurn({ harness, sessionId }))
585
762
  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);
763
+ busy.set(sessionId, { until: Date.now() + BUSY_MS });
764
+ const text = await pullAll(mine, token, "mid_task", sessionKey);
588
765
  return text ? { ok: true, text, token } : { ok: true, text: null };
589
766
  }
590
767
  // The turn ended and the Stop hook waits in the background. Its later
591
768
  // asks say nothing of the turn: the person may have typed since.
592
769
  if (!request.again && busy.delete(sessionId))
593
770
  log(`${sessionId} turn ended, its Stop hook waits`);
594
- const inTurn = () => (busy.get(sessionId) ?? 0) > Date.now();
595
771
  for (const key of mine)
596
772
  forHook.add(key);
597
- const now = inTurn() ? null : await pullAll(mine, token, "woke", sessionId);
773
+ const now = inTurn({ harness, sessionId }) ? null : await pullAll(mine, token, "woke", sessionKey);
598
774
  if (now) {
599
- busy.set(sessionId, Date.now() + BUSY_MS);
775
+ busy.set(sessionId, { until: Date.now() + BUSY_MS });
600
776
  return { ok: true, text: now, token };
601
777
  }
602
778
  return new Promise((resolve) => {
@@ -621,20 +797,20 @@ export async function runDaemon(home) {
621
797
  if (!hooksAllowed(home))
622
798
  return finish({ ok: true, text: null });
623
799
  // A turn is under way: its step hooks hand messages over.
624
- if (done || inTurn())
800
+ if (done || inTurn({ harness, sessionId }))
625
801
  return;
626
802
  if (pulling) {
627
803
  pokedAgain = true;
628
804
  return;
629
805
  }
630
806
  pulling = true;
631
- void pullAll(mine, token, "woke", sessionId).then((text) => {
807
+ void pullAll(mine, token, "woke", sessionKey).then((text) => {
632
808
  pulling = false;
633
809
  if (done)
634
810
  return;
635
811
  if (text) {
636
812
  // The session wakes into a turn: what comes next waits for its hooks.
637
- busy.set(sessionId, Date.now() + BUSY_MS);
813
+ busy.set(sessionId, { until: Date.now() + BUSY_MS });
638
814
  return finish({ ok: true, text, token });
639
815
  }
640
816
  if (pokedAgain) {
@@ -675,7 +851,7 @@ export async function runDaemon(home) {
675
851
  save();
676
852
  return { ok: true };
677
853
  }
678
- if (request.op === "hook" || request.op === "hookWait" || request.op === "hookRead")
854
+ if (request.op === "hook" || request.op === "hookWait" || request.op === "hookRead" || request.op === "codexHook")
679
855
  return hookAnswer(request, closed);
680
856
  if (request.op !== "read" && request.op !== "held" && request.op !== "heldRead")
681
857
  return { ok: false, error: "unknown request" };
@@ -751,7 +927,7 @@ export async function runDaemon(home) {
751
927
  clearInterval(tick);
752
928
  waking.stop();
753
929
  // Station starts nothing on this computer from now: it hears so at once.
754
- const credentials = readCredentials(home);
930
+ const credentials = wakeCredentials(home);
755
931
  if (credentials?.token)
756
932
  void call(credentials.relayUrl, "/cli/wakes", { token: credentials.token }, { method: "DELETE" }).catch(() => { });
757
933
  for (const close of closers.values())
package/dist/frame.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // What a session reads when room messages arrive: who in the room said
2
2
  // what, and whether that is the person the session works for. Claude Code
3
3
  // also marks it as from another session; Codex shows it as a user message.
4
- import { askedText, askNewsText, chatHeader, decisionText, hearerOf, lineOf, noteFor, threadHint, whereOf } from "./mark.js";
4
+ import { ASK_NEWS, askedText, askNewsText, chatHeader, decisionText, hearerOf, lineOf, noteFor, firstOfEach, threadHint, whereOf } from "./mark.js";
5
5
  import { roomLabel } from "./seats.js";
6
6
  /** The seat as a reader of its room: who it works for, from what the
7
7
  * room says (mark.ts owns the rule and the words). */
@@ -22,10 +22,9 @@ export function decisionFrame(seat, decisions, participants) {
22
22
  const person = participants.find((p) => p.id === decisions[0]?.participant_id)?.name ?? "The person you work for";
23
23
  return decisionText(roomLabel(seat), person, decisions.map((m) => ({ approved: m.event?.type === "approved", request: m.event?.request ?? "your request" })));
24
24
  }
25
- const ASK_NEWS = ["unreached", "handed", "out", "lapsed"];
26
- /** What became of this seat's own asks: Station could not reach an agent,
27
- * or handed the ask to another, or the agent holding it ran out of usage
28
- * or let its lease lapse.
25
+ /** What became of this seat's own asks: an agent got it, took it or finished it,
26
+ * Station could not reach an agent, or handed the ask to another, or the
27
+ * agent holding it ran out of usage or let its lease lapse.
29
28
  * The event is about the sender's seat. */
30
29
  export function askNewsFor(seat, messages) {
31
30
  return messages.filter((m) => m.kind === "event" && ASK_NEWS.includes(String(m.event?.type)) && m.participant_id === seat.participantId);
@@ -58,7 +57,11 @@ export function frame(seat, messages, participants, command = "station", before
58
57
  const hearer = hearerFor(seat, participants, command);
59
58
  const byId = new Map(participants.map((p) => [p.id, p]));
60
59
  const authorOf = (message) => byId.get(message.participant_id ?? "");
61
- const line = (message) => lineOf(hearer, authorOf(message), message.body, whereOf(hearer, message, participants));
60
+ // Each author's mention on its first line only, across both lists.
61
+ const all = [...messages, ...before];
62
+ const firsts = firstOfEach(all.map(authorOf));
63
+ const first = new Map(all.map((message, i) => [message, firsts[i]]));
64
+ const line = (message) => lineOf(hearer, authorOf(message), message.body, whereOf(hearer, message, participants), first.get(message));
62
65
  const note = noteFor(hearer, [...messages, ...before].map(authorOf));
63
66
  // Codex shows this as an ordinary user message, so the header says where it came from.
64
67
  // The mark goes before the messages: Codex cuts a long delivery at its end.
package/dist/home.js CHANGED
@@ -24,11 +24,10 @@ export const files = (home) => ({
24
24
  log: join(home, "daemon.log"),
25
25
  /** The tools Station listed last, for a session that starts while it cannot be reached (mcp.ts). */
26
26
  tools: join(home, "tools.json"),
27
- /** The five folded tools Station listed last for `station mcp`, kept apart from the commands' list. */
27
+ /** The folded tools Station listed last for `station mcp`, kept apart from the commands' list. */
28
28
  mcpTools: join(home, "tools-mcp.json"),
29
29
  /** A `station login` under way (login.ts). */
30
30
  login: join(home, "login.json"),
31
- loginReply: join(home, "login-reply.json"),
32
31
  /** This computer's own identity while it has no sign-in (guest.ts). */
33
32
  guest: join(home, "guest.json"),
34
33
  /** This install's own id (installId). */