omni-notify-mcp 1.3.447 → 1.3.449

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.
@@ -27,7 +27,11 @@ export const KEY_BAR = [
27
27
  { id: "end", label: "End", title: "End", seq: ["\x1b[F", "\x1bOF"] },
28
28
  ];
29
29
  export const NEW_LINE = { id: "newline", label: "⏎ Line", title: "New line", seq: ["\x1b[200~\n\x1b[201~", "\x1b[200~\n\x1b[201~"] };
30
+ const TERMINAL_REPLY = /^(?:\x1b\[[IO]|\x1b\[\??\d+;\d+R|\x1b\[[?>][0-9;]*c|\x1b\[\??[0-9;]*\$y)+$/;
31
+ export const NEW_LINE_IN_BOX = "\x1b\r";
30
32
  export function ctrlByte(data) {
33
+ if (data === "\r")
34
+ return "\x1b\r";
31
35
  if (data.length !== 1)
32
36
  return data;
33
37
  const code = data.charCodeAt(0);
@@ -123,6 +127,7 @@ var btnNew=document.getElementById("newagent"),btnConvs=document.getElementById(
123
127
  // A phone is a touch screen no wider than 600px on its short side. Its normal mode lays the page out at the screen's own width; its desktop-site mode lays it out wider and shrinks it to the glass, so everything the page draws outside the terminal is scaled up by that ratio and the terminal's font with it.
124
128
  var ctrlByte=${ctrlByte.toString()};
125
129
  var ctrlBarSeq=${ctrlBarSeq.toString()};
130
+ var TERMINAL_REPLY=${TERMINAL_REPLY.toString()},NEW_LINE_IN_BOX=${JSON.stringify(NEW_LINE_IN_BOX)};
126
131
  var KEY_BAR=${JSON.stringify(KEY_BAR)},NEW_LINE=${JSON.stringify(NEW_LINE)};
127
132
  var phone,phoneScale,refit=function(){};
128
133
  function sizePhone(){
@@ -404,8 +409,8 @@ async function cliAttach(id,origin){
404
409
  swipeTravel+=dy;
405
410
  while(Math.abs(swipeTravel)>=20){
406
411
  var down=swipeTravel>0;swipeTravel-=down?20:-20;
407
- if(term.modes.mouseTrackingMode==="none"){if(term.buffer.active.type==="alternate")ordered(id,"input",{data:(term.modes.applicationCursorKeysMode?"\\x1bO":"\\x1b[")+(down?"B":"A")});else term.scrollLines(down?1:-1);}
408
- else ordered(id,"input",{data:"\\x1b[<"+(down?65:64)+";"+Math.ceil(term.cols/2)+";"+Math.ceil(term.rows/2)+"M"});
412
+ if(term.modes.mouseTrackingMode==="none"){if(term.buffer.active.type==="alternate"){claim();ordered(id,"input",{data:(term.modes.applicationCursorKeysMode?"\\x1bO":"\\x1b[")+(down?"B":"A")});}else term.scrollLines(down?1:-1);}
413
+ else{claim();ordered(id,"input",{data:"\\x1b[<"+(down?65:64)+";"+Math.ceil(term.cols/2)+";"+Math.ceil(term.rows/2)+"M"});}
409
414
  }
410
415
  }
411
416
  // A phone's own scroller keeps gliding after the finger lifts, at the speed the finger left with, and slows to a stop:
@@ -431,6 +436,7 @@ async function cliAttach(id,origin){
431
436
  // Returning false hands that one key back to the browser: Ctrl+C copies the selected text and does not interrupt
432
437
  // the CLI unless nothing is selected, and Ctrl+V pastes the clipboard into the CLI.
433
438
  term.attachCustomKeyEventHandler(function(e){
439
+ if(e.key==="Enter"&&(e.ctrlKey||e.shiftKey)&&!e.altKey&&!e.metaKey){if(e.type==="keydown"){e.preventDefault();typed({data:NEW_LINE_IN_BOX},withhold);}return false;}
434
440
  if(e.type!=="keydown"||e.altKey)return true;
435
441
  var key=e.key.toLowerCase(),held=e.ctrlKey||e.metaKey;
436
442
  if((held&&key==="c")||(e.ctrlKey&&key==="insert"))return term.hasSelection()?false:true;
@@ -523,7 +529,7 @@ async function cliAttach(id,origin){
523
529
  },true);
524
530
  var keybar=document.getElementById("keybar"),ctrlHeld=false,ctrlKey=null;
525
531
  function disarm(){ctrlHeld=false;ctrlKey.classList.remove("armed");}
526
- var unacked=[],inputs=0,from=sender+"."+mine;function typed(body,mark){if(term.options.disableStdin){liveNotice("Not sent — this CLI is no longer connected. Press 🔌 Reattach.","error");return;}inputs+=1;var sent={id:inputs,frame:JSON.stringify(Object.assign({kind:"input",from:from,id:inputs},body))};unacked.push(sent);if(socket!==null&&socket.readyState===WebSocket.OPEN)socket.send(sent.frame);mark(sent.id);}
532
+ var unacked=[],inputs=0,from=sender+"."+mine;function typed(body,mark,auto){if(term.options.disableStdin){liveNotice("Not sent — this CLI is no longer connected. Press 🔌 Reattach.","error");return;}if(!owner&&!auto){claim();mark=withhold;}inputs+=1;var sent={id:inputs,frame:JSON.stringify(Object.assign({kind:"input",from:from,id:inputs},body))};unacked.push(sent);if(socket!==null&&socket.readyState===WebSocket.OPEN)socket.send(sent.frame);mark(sent.id);}
527
533
  function sendKey(data){if(ctrlHeld){disarm();data=ctrlBarSeq(data);}typed({data:data},withhold);}
528
534
  keybar.replaceChildren();keybar.hidden=false;
529
535
  [NEW_LINE].concat(KEY_BAR.slice(0,7),[{id:"ctrl",label:"Ctrl",title:"Ctrl (sticky)"}],KEY_BAR.slice(7)).forEach(function(key){
@@ -533,9 +539,17 @@ async function cliAttach(id,origin){
533
539
  else b.onclick=function(){sendKey(key.seq[term.modes.applicationCursorKeysMode?1:0]);term.focus();};
534
540
  keybar.append(b);
535
541
  });
536
- term.onData(function(data){if(ctrlHeld&&data.length===1){disarm();data=ctrlByte(data);}typed({data:data},function(id){predict(data,id);});});term.onBinary(function(data){typed({data:btoa(data),binary:true},withhold);});term.onResize(function(){forget();withhold(inputs);});
537
- refit=function(){if(mine!==view||!socket||socket.readyState!==WebSocket.OPEN||host.clientWidth===0||host.clientHeight===0)return;fitAddon.fit();ordered(id,"resize",{cols:term.cols,rows:term.rows});};
538
- if(observer)observer.disconnect();observer=new ResizeObserver(refit);host.addEventListener("pointerdown",refit);host.addEventListener("touchstart",refit,{passive:true});var wake=function(){if(!document.hidden)refit();},off=observer.disconnect.bind(observer);window.addEventListener("focus",wake);document.addEventListener("visibilitychange",wake);observer.disconnect=function(){window.removeEventListener("focus",wake);document.removeEventListener("visibilitychange",wake);off();};
542
+ term.onData(function(data){if(ctrlHeld&&data.length===1){disarm();data=ctrlByte(data);}typed({data:data},function(id){predict(data,id);},TERMINAL_REPLY.test(data));});term.onBinary(function(data){typed({data:btoa(data),binary:true},withhold);});term.onResize(function(){forget();withhold(inputs);});
543
+ var owner=false,claimed=null,held=null,shown=null,opening=true;
544
+ function fitShown(){var shell=term.element,screen=host.querySelector(".xterm-screen");if(owner||!screen||!screen.offsetWidth){shell.style.transform=shell.style.width=shell.style.height="";return;}shell.style.width=screen.offsetWidth+"px";shell.style.height=screen.offsetHeight+"px";shell.style.transformOrigin="0 0";shell.style.transform="scale("+Math.min(host.clientWidth/screen.offsetWidth,host.clientHeight/screen.offsetHeight)+")";}
545
+ function claim(){if(owner)return;owner=true;refit();}
546
+ refit=function(){if(mine!==view)return;fitShown();if(!owner||!socket||socket.readyState!==WebSocket.OPEN||host.clientWidth===0||host.clientHeight===0)return;fitAddon.fit();claimed={cols:term.cols,rows:term.rows};held=shown;ordered(id,"resize",claimed);};
547
+ function sized(frame){
548
+ shown={cols:frame.cols,rows:frame.rows};
549
+ if(owner&&claimed){if(frame.cols===claimed.cols&&frame.rows===claimed.rows)held=claimed;else if(!held)held=shown;else if(frame.cols!==held.cols||frame.rows!==held.rows){owner=false;claimed=held=null;}}
550
+ if(!owner&&(frame.cols!==term.cols||frame.rows!==term.rows))term.resize(frame.cols,frame.rows);
551
+ }
552
+ if(observer)observer.disconnect();observer=new ResizeObserver(refit);host.style.overflow="hidden";
539
553
  reattach.onclick=function(){cliAttach(id,origin);};
540
554
  if(reopened!==null&&reopened.id===id)liveNotice(REOPENED+(reopened.unsent?" What you typed while it was away was not sent.":""),"hint");
541
555
  reopened=null;
@@ -550,8 +564,8 @@ async function cliAttach(id,origin){
550
564
  var ws=new WebSocket((location.protocol==="https:"?"wss://":"ws://")+location.host+"/v1/terminals/"+id+"/ws",["bn-terminal","bn-bearer."+token]);socket=ws;
551
565
  var frames=Promise.resolve(),opened=false;
552
566
  setTimeout(function(){if(mine===view&&socket===ws&&ws.readyState===WebSocket.CONNECTING)abandon(ws,window.bullseyeConnection.failed());},window.bullseyeConnection.limit());
553
- ws.onopen=function(){if(mine!==view){ws.close();return;}opened=true;socketDown=false;heard();window.bullseyeConnection.opened(function(){return socket===ws&&ws.readyState===WebSocket.OPEN;},window.bullseyeConnection.live);term.options.disableStdin=false;refit();unacked.forEach(function(sent){ws.send(sent.frame);});term.focus();};
554
- ws.onmessage=function(event){if(socket===ws)heard();var frame=JSON.parse(event.data);if(frame.pong)return;if(frame.ack!==undefined){acked=Math.max(acked,frame.ack);unacked=unacked.filter(function(sent){return sent.id>frame.ack;});return;}var seen=acked;frames=frames.then(async function(){if(mine!==view)return;if(frame.files){if(frame.error)liveNotice(frame.error,"error");else{sentPaths=sentPaths.concat(frame.paths);liveNotice("Sent to CLI: "+frame.paths.map(function(sent){return phone?base(sent):sent;}).join(" · "));}return;}if(frame.error){liveNotice(frame.error,"error");return;}var behind=frame.reset?term.buffer.active.baseY-term.buffer.active.viewportY:0;if(frame.reset){forget();cursorShown=true;term.reset();}var shown=frame.data.match(/\\x1b\\[\\?25[hl]/g);if(shown)cursorShown=shown[shown.length-1].slice(-1)==="h";await new Promise(function(done){term.write(frame.data,done);});if(mine!==view)return;reconcile(seen);if(behind>0)term.scrollLines(-behind);cli.provider=frame.provider;cli.project=frame.project;liveRead();if(frame.ended){forget();liveEnded("CLI ended"+(frame.failure?" · "+frame.failure:""));}else if(frame.failure&&frame.failure!==cli.failure)liveNotice(frame.failure,"error");cli.failure=frame.failure;}).catch(fail);};
567
+ ws.onopen=function(){if(mine!==view){ws.close();return;}opened=true;socketDown=false;heard();window.bullseyeConnection.opened(function(){return socket===ws&&ws.readyState===WebSocket.OPEN;},window.bullseyeConnection.live);term.options.disableStdin=false;if(opening||unacked.length){opening=false;owner=false;claim();}else{owner=false;claimed=held=null;fitShown();}unacked.forEach(function(sent){ws.send(sent.frame);});term.focus();};
568
+ ws.onmessage=function(event){if(socket===ws)heard();var frame=JSON.parse(event.data);if(frame.pong)return;if(frame.ack!==undefined){acked=Math.max(acked,frame.ack);unacked=unacked.filter(function(sent){return sent.id>frame.ack;});return;}var seen=acked;frames=frames.then(async function(){if(mine!==view)return;if(frame.files){if(frame.error)liveNotice(frame.error,"error");else{sentPaths=sentPaths.concat(frame.paths);liveNotice("Sent to CLI: "+frame.paths.map(function(sent){return phone?base(sent):sent;}).join(" · "));}return;}if(frame.error){liveNotice(frame.error,"error");return;}sized(frame);var behind=frame.reset?term.buffer.active.baseY-term.buffer.active.viewportY:0;if(frame.reset){forget();cursorShown=true;term.reset();}var shown=frame.data.match(/\\x1b\\[\\?25[hl]/g);if(shown)cursorShown=shown[shown.length-1].slice(-1)==="h";await new Promise(function(done){term.write(frame.data,done);});if(mine!==view)return;fitShown();reconcile(seen);if(behind>0)term.scrollLines(-behind);cli.provider=frame.provider;cli.project=frame.project;liveRead();if(frame.ended){forget();liveEnded("CLI ended"+(frame.failure?" · "+frame.failure:""));}else if(frame.failure&&frame.failure!==cli.failure)liveNotice(frame.failure,"error");cli.failure=frame.failure;}).catch(fail);};
555
569
  ws.onclose=function(event){if(mine!==view)return;forget();var ending=event.code===1000||(event.code===1008&&event.reason==="Sign in again");if(ending){term.options.disableStdin=true;unacked=[];}if(event.code===1000){socketDown=false;window.bullseyeConnection.live();liveEnded("CLI ended");return;}if(event.code===1008&&event.reason==="Sign in again"){socketDown=false;window.bullseyeConnection.live();signIn("Your sign-in expired. Sign in again to return to this CLI.");return;}again(opened?window.bullseyeConnection.closed(reattached):window.bullseyeConnection.failed());};
556
570
  ws.onerror=function(){socketDown=true;liveFailed("reattaching to the same CLI…");};
557
571
  }
@@ -3248,8 +3248,8 @@ export async function clearStoryQueue(board, since) {
3248
3248
  // NULL-OK: field pressedAt is OPTIONAL and therefore it is ok to check for NULL
3249
3249
  return r !== undefined && r.origin === "press" && r.eligible && r.pressedAt !== undefined && (r.forced ?? r.pressedAt) > priorAuthorityOf(store.entries.find((e) => e.storyId === id));
3250
3250
  }));
3251
- // NULL-OK: field worker/archivedSessions/handStop is OPTIONAL and therefore it is ok to check for NULL
3252
- const kept = store.entries.filter((e) => e.worker !== undefined || e.archivedSessions !== undefined || e.handStop !== undefined || (e.forceEventAt ?? 0) >= since || his.has(e));
3251
+ // NULL-OK: field worker/archivedSessions/lastSession/handStop is OPTIONAL and therefore it is ok to check for NULL
3252
+ const kept = store.entries.filter((e) => e.worker !== undefined || e.archivedSessions !== undefined || e.lastSession !== undefined || e.handStop !== undefined || (e.forceEventAt ?? 0) >= since || his.has(e));
3253
3253
  const working = new Set([...kept.filter((e) => e.state === "starting" || e.state === "running" || (e.forceEventAt ?? 0) >= since || his.has(e)).map((e) => e.storyId), ...untaken]);
3254
3254
  let removed = store.entries.length - kept.length;
3255
3255
  const now = Date.now();
@@ -3963,7 +3963,7 @@ function idleWorker(worker, reading, now) {
3963
3963
  return parked !== undefined && parked.live && stopDue(worker, now) ? worker : undefined;
3964
3964
  }
3965
3965
  /** 🔴 #4143 — one pass reads a worker once, however many judgements are made on that reading. */
3966
- function once(read) {
3966
+ export function once(read) {
3967
3967
  let held;
3968
3968
  return () => (held ??= { value: read() }).value;
3969
3969
  }
@@ -4093,9 +4093,21 @@ async function passHeld(board, world, now) {
4093
4093
  refusals.set(id, refused);
4094
4094
  applied.set(id, r.requestId);
4095
4095
  }
4096
+ const stillListed = await world.sweepClosed(store.entries, (e, session) => {
4097
+ if (!(e.archivedSessions ?? []).some((s) => s.id === session.id))
4098
+ e.archivedSessions = [...(e.archivedSessions ?? []), session];
4099
+ step(e, now, "archived", `its story is no longer an open row on the board, so its conversation ${session.id} left every history list for the archive`);
4100
+ save();
4101
+ });
4096
4102
  for (const e of store.entries) {
4097
4103
  await slice();
4098
4104
  try {
4105
+ const listedWhy = stillListed.get(e.storyId);
4106
+ // NULL-OK: field listedWhy is OPTIONAL and therefore it is ok to check for NULL
4107
+ if (listedWhy !== undefined && !IN_LINE.has(e.state) && e.why !== listedWhy) {
4108
+ e.why = listedWhy;
4109
+ save();
4110
+ }
4099
4111
  dropUsageLimitQuestion(e, now);
4100
4112
  if (IN_LINE.has(e.state) && inArchive(e.worker) && world.closedWhy(e.storyId) === undefined) {
4101
4113
  const worker = e.worker;
@@ -4118,23 +4130,50 @@ async function passHeld(board, world, now) {
4118
4130
  continue;
4119
4131
  }
4120
4132
  }
4133
+ const last = e.lastSession;
4134
+ // NULL-OK: field worker/lastSession is OPTIONAL and therefore it is ok to check for NULL
4135
+ if (IN_LINE.has(e.state) && e.worker === undefined && last !== undefined && (e.archivedSessions ?? []).some((s) => s.id === last.id) && world.closedWhy(e.storyId) === undefined) {
4136
+ if (!archiveDue(e, now))
4137
+ continue;
4138
+ try {
4139
+ const moved = await world.restoreLast(last);
4140
+ const kept = e.archivedSessions.filter((s) => s.id !== last.id);
4141
+ if (kept.length === 0)
4142
+ delete e.archivedSessions;
4143
+ else
4144
+ e.archivedSessions = kept;
4145
+ delete e.archiveRefused;
4146
+ step(e, now, "restored", `its last worker's conversation ${last.id} was brought back from the archive (${movedWords(moved)}), so the story's next worker reads it first`);
4147
+ save();
4148
+ }
4149
+ catch (err) {
4150
+ if (!(err instanceof WorkerNotStarted))
4151
+ throw err;
4152
+ // OWNER: ITER/LOOP — the disk refused to bring this returning story's last conversation back, so it is not started without it, with the refusal on its trace, and is tried again after its wait; the next entry is read.
4153
+ noteArchiveRefusal(e, e, now, `its last worker's conversation ${last.id} could not be brought back from the archive, so its next worker is not started without it: ${err.message}`);
4154
+ save();
4155
+ continue;
4156
+ }
4157
+ }
4121
4158
  // NULL-OK: field archivedAt is OPTIONAL and therefore it is ok to check for NULL
4122
4159
  // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
4123
- const holder = e.worker === undefined ? (e.archivedSessions === undefined ? undefined : e) : e.worker.archivedAt === undefined ? undefined : e.worker;
4160
+ const holder = e.worker === undefined ? (e.archivedSessions === undefined && (e.lastSession === undefined || world.closedWhy(e.storyId) === undefined) ? undefined : e) : e.worker.archivedAt === undefined ? undefined : e.worker;
4124
4161
  // NULL-OK: field holder is OPTIONAL and therefore it is ok to check for NULL
4125
4162
  if (!IN_LINE.has(e.state) && holder !== undefined && archiveDue(holder, now)) {
4126
4163
  const worker = e.worker;
4127
- const cold = world.coldWhy(e.storyId) ?? agedOutWhy(e, now);
4164
+ const cold = world.coldWhy(e.storyId) ?? (world.closedWhy(e.storyId) === undefined ? undefined : agedOutWhy(e, now));
4128
4165
  // NULL-OK: field cold is OPTIONAL and therefore it is ok to check for NULL
4129
4166
  if (cold !== undefined) {
4130
4167
  // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
4131
4168
  const whose = worker === undefined ? "its archived sessions" : `its archived worker ${worker.jobId}`;
4132
4169
  try {
4133
4170
  // NULL-OK: field session is OPTIONAL and therefore it is ok to check for NULL
4134
- const own = worker?.session === undefined || !stopRouteOf(worker).ownFiles || (e.archivedSessions ?? []).some((s) => s.id === worker.session.id) ? [] : [worker.session];
4135
- const earlier = (e.archivedSessions ?? []).length;
4171
+ const own = worker?.session === undefined || !stopRouteOf(worker).ownFiles ? [] : [worker.session];
4172
+ // NULL-OK: field lastSession is OPTIONAL and therefore it is ok to check for NULL
4173
+ const sessions = [...own, ...(e.lastSession === undefined ? [] : [e.lastSession]), ...(e.archivedSessions ?? [])].filter((s, i, all) => all.findIndex((x) => x.id === s.id) === i);
4136
4174
  // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
4137
- const freed = await world.purge([...own, ...(e.archivedSessions ?? [])], worker?.codexDirect === true ? worker.jobId : undefined);
4175
+ const freed = await world.purge(sessions, worker?.codexDirect === true ? worker.jobId : undefined);
4176
+ const earlier = (e.archivedSessions ?? []).length;
4138
4177
  delete e.worker;
4139
4178
  delete e.lastSession;
4140
4179
  delete e.archivedSessions;
@@ -4552,6 +4591,9 @@ async function passHeld(board, world, now) {
4552
4591
  // NULL-OK: field limit is OPTIONAL and therefore it is ok to check for NULL
4553
4592
  if (w.parked.limit !== undefined && worker.limit?.said !== w.parked.limit.said)
4554
4593
  worker.limit = w.parked.limit;
4594
+ // NULL-OK: field limit is OPTIONAL and therefore it is ok to check for NULL
4595
+ else if (w.parked.limit !== undefined && worker.limit.at !== w.parked.limit.at)
4596
+ worker.limit = { ...worker.limit, at: w.parked.limit.at };
4555
4597
  if (!e.eligible) {
4556
4598
  const why = `its ${worker.provider} worker ${worker.jobId}'s turn is over and the story is no longer the queue's to work, so it is not woken`;
4557
4599
  step(e, now, "worker-ended", why);
@@ -4586,9 +4628,39 @@ async function passHeld(board, world, now) {
4586
4628
  e.state = "queued";
4587
4629
  const wakeAt = parkedWakeAt(worker, worker.parkedAt, w.parked);
4588
4630
  const due = now >= wakeAt;
4631
+ let movedOff = false;
4589
4632
  // NULL-OK: field limit is OPTIONAL and therefore it is ok to check for NULL
4590
- if (worker.limit !== undefined && (worker.limit.until === undefined || worker.limit.until > now) && !due)
4591
- e.why = `⏳ usage limit — parked with its lane free until ${new Date(wakeAt).toISOString()}, then woken in its own session: ${worker.limit.said}`;
4633
+ if (worker.limit !== undefined && (worker.limit.until === undefined || worker.limit.until > now) && !due) {
4634
+ const limit = worker.limit;
4635
+ // NULL-OK: field limitRoom is OPTIONAL and therefore it is ok to check for NULL
4636
+ const room = world.limitRoom === undefined ? { wake: false, why: "this queue reads no room for it" } : await world.limitRoom(e);
4637
+ const episode = limitEpisodeOf(limit);
4638
+ const moved = e.limitMoved?.episode === episode ? e.limitMoved : undefined;
4639
+ // NULL-OK: field moved is OPTIONAL and therefore it is ok to check for NULL
4640
+ const stoppedAgain = moved !== undefined && limit.at > moved.at;
4641
+ // NULL-OK: field moved is OPTIONAL and therefore it is ok to check for NULL
4642
+ if (room.wake && (moved === undefined || (moved.fresh !== true && !stoppedAgain))) {
4643
+ movedOff = true;
4644
+ const why = `⏳ usage limit — ${room.why}: its own session is woken now — ${limit.said}`;
4645
+ // NULL-OK: field moved is OPTIONAL and therefore it is ok to check for NULL
4646
+ if (moved === undefined) {
4647
+ e.limitMoved = { episode, at: now };
4648
+ step(e, now, "retry", why);
4649
+ }
4650
+ e.why = why;
4651
+ }
4652
+ else if (room.wake && moved.fresh !== true) {
4653
+ moved.fresh = true;
4654
+ const why = `its ${worker.provider} worker ${worker.jobId}'s own session stopped on the same usage limit again after it was woken off it, and ${room.why}, so the story starts fresh from that session's transcript — ${limit.said}`;
4655
+ dropWorker(e);
4656
+ delete e.nextTryAt;
4657
+ e.why = why;
4658
+ step(e, now, "worker-ended", why);
4659
+ continue;
4660
+ }
4661
+ else
4662
+ e.why = `⏳ usage limit — parked with its lane free until ${new Date(wakeAt).toISOString()}, then woken in its own session: ${limit.said} — ${room.wake ? "it was moved off this limit in its own session and fresh, and stopped on it again both times" : room.why}`;
4663
+ }
4592
4664
  // NULL-OK: field question is OPTIONAL and therefore it is ok to check for NULL
4593
4665
  if (e.forced !== true && asked !== undefined && asked.answer === undefined) {
4594
4666
  e.why = asked.prompt === true ? `parked on Meni's question since ${clockOf(asked.at)} with its lane free — woken first in line the moment he answers: ${asked.text}` : `parked on what it needs since ${clockOf(asked.at)} with its lane free — woken first in line at ${clockOf(worker.parkedAt + parkedWaitMs(worker, w.parked))} to look again: ${asked.text}`;
@@ -4601,7 +4673,7 @@ async function passHeld(board, world, now) {
4601
4673
  }
4602
4674
  }
4603
4675
  // NULL-OK: field question is OPTIONAL and therefore it is ok to check for NULL
4604
- if (e.forced === true || due || (unhanded(asked) !== undefined && asked?.approval !== true))
4676
+ if (e.forced === true || due || movedOff || (unhanded(asked) !== undefined && asked?.approval !== true))
4605
4677
  wakeable.set(e, w.parked.sessionId);
4606
4678
  continue;
4607
4679
  }
@@ -4862,6 +4934,14 @@ async function passHeld(board, world, now) {
4862
4934
  e.why = `its worker ${e.worker.jobId}'s conversation is brought back from the archive on the next pass, and only then woken — never a fresh worker beside it`;
4863
4935
  continue;
4864
4936
  }
4937
+ const last = e.lastSession;
4938
+ // NULL-OK: field worker/lastSession is OPTIONAL and therefore it is ok to check for NULL
4939
+ if (e.worker === undefined && last !== undefined && (e.archivedSessions ?? []).some((s) => s.id === last.id)) {
4940
+ // NULL-OK: field archiveRefused is OPTIONAL and therefore it is ok to check for NULL
4941
+ if (e.archiveRefused === undefined)
4942
+ e.why = `its last worker's conversation ${last.id} is brought back from the archive on the next pass, and only then is its next worker started, which reads it first`;
4943
+ continue;
4944
+ }
4865
4945
  const held = world.heldBy(e.storyId);
4866
4946
  // NULL-OK: field held is OPTIONAL and therefore it is ok to check for NULL
4867
4947
  if (held !== undefined && !holdIsItsDeadWorker(e, held, () => clearRefusal(e, world.worker(e, board)))) {
@@ -5344,8 +5424,6 @@ export async function placeWaiting(board, now, by, decide, visible) {
5344
5424
  return queueOrder(store).filter((e) => waiting.includes(e.storyId)).map((e) => e.storyId);
5345
5425
  });
5346
5426
  }
5347
- /** 🔴 #4143 — whether the story queue of `board` holds `storyId` done: its worker's sessions are archived, so none of them is ever woken again. */
5348
- export const doneInQueue = (board, storyId) => readQueueStore(board).entries.some((x) => x.storyId === storyId && x.state === "done");
5349
5427
  /** 🔴 #4154 — FleetView's investigator ruled ABORT on the worker `jobId` of this story: its entry leaves the line, so the stopped worker is never woken, and his next Start press brings the story back; undefined when no entry in line runs that worker. */
5350
5428
  export async function withdrawStory(board, storyId, jobId, why, now) {
5351
5429
  return withQueueLock(board, now, async () => {
@@ -5556,24 +5634,120 @@ export function claudeJobsOfStoryAnywhere(entry, board, since, home = claudeHome
5556
5634
  const briefed = /^Stories: #\d+ — \S/.test(first);
5557
5635
  return claudeJobsWhere((job) => startedOnStory(job, entry.storyId, board) || (briefed && job.intent.split("\n")[0] === first), since, home);
5558
5636
  }
5559
- /** 🔴 #4143 — a job a wake rewrote onto `storyId` in `board`: Claude Code's record of a woken job keeps the wake's words, the queue's own wake (in the board) or an investigation's (naming the board, this story and otherwise only stories the queue holds done, since a session still carrying an open story is that story's too), never the brief it was started with. */
5560
- const wokenOnStory = (job, storyId, board) => {
5637
+ /** 🔴 #4143 — the folders a story's workers ran in, as the transcript folders of its known sessions and the worker's own folder: a queue wake resumes a worker where it was started, the story's worktree when it had one. */
5638
+ function storyFolders(entry, board) {
5639
+ // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
5640
+ const sessions = [entry.worker?.session, entry.lastSession, ...(entry.archivedSessions ?? [])].filter((s) => s !== undefined);
5641
+ // NULL-OK: field cwd is OPTIONAL and therefore it is ok to check for NULL
5642
+ return { cwds: [board, ...(entry.worker?.cwd === undefined ? [] : [entry.worker.cwd])], transcripts: sessions.map((s) => path.dirname(s.transcript)) };
5643
+ }
5644
+ /** 🔴 #4143 — the story a brief of any launcher names on its first line, whatever title follows it. */
5645
+ const STARTED_STORY = /^Stories: #(\d+) /;
5646
+ /** 🔴 #4143 — a job a wake rewrote onto the story in `board`, or one any launcher started on it in a folder its workers ran in under a first line other than the queue's: Claude Code's record of a woken job keeps the wake's words, the queue's own wake or a brief naming the story (in a folder the story's workers ran in) or an investigation's (naming the board, this story and otherwise only stories no longer open on the board, since a session still carrying an open story is that story's too), never the brief it was started with. */
5647
+ const wokenOnStory = (job, entry, board, open) => {
5561
5648
  const opening = job.intent.split("\n", 1)[0];
5562
- const queued = WOKEN_STORY.exec(opening);
5563
- if (queued !== null)
5564
- return Number(queued[1]) === storyId && sameFolder(job.cwd, board);
5649
+ const queued = WOKEN_STORY.exec(opening) ?? STARTED_STORY.exec(opening);
5650
+ if (queued !== null) {
5651
+ if (Number(queued[1]) !== entry.storyId)
5652
+ return false;
5653
+ const folders = storyFolders(entry, board);
5654
+ // NULL-OK: field linkScanPath is OPTIONAL and therefore it is ok to check for NULL
5655
+ return folders.cwds.some((cwd) => sameFolder(job.cwd, cwd)) || (job.linkScanPath !== undefined && folders.transcripts.some((dir) => sameFolder(path.dirname(job.linkScanPath), dir)));
5656
+ }
5565
5657
  const decided = INVESTIGATION_WAKE.exec(opening);
5566
5658
  if (decided === null || !sameFolder(decided[1], board))
5567
5659
  return false;
5568
5660
  const named = decided[2].split(", ").map((s) => Number(s.slice(1)));
5569
- return named.includes(storyId) && named.every((id) => id === storyId || doneInQueue(board, id));
5661
+ return named.includes(entry.storyId) && named.every((id) => id === entry.storyId || !open(id));
5570
5662
  };
5571
- /** 🔴 #4143 — every job of the story on this machine: the ones {@link claudeJobsOfStoryAnywhere} finds and the ones a wake rewrote onto it. */
5572
- function claudeJobsEverOnStory(entry, board, home) {
5573
- const found = new Set(claudeJobsOfStoryAnywhere(entry, board, 0, home));
5574
- for (const id of claudeJobsWhere((job) => wokenOnStory(job, entry.storyId, board), 0, home))
5575
- found.add(id);
5576
- return [...found];
5663
+ /** 🔴 #4143 — whether a job is the story's: one {@link claudeJobsOfStoryAnywhere} finds, or one a wake rewrote onto it. */
5664
+ function jobOnStory(job, entry, board, open) {
5665
+ const first = entry.brief.split("\n")[0];
5666
+ return startedOnStory(job, entry.storyId, board) || (/^Stories: #\d+ — \S/.test(first) && job.intent.split("\n")[0] === first) || wokenOnStory(job, entry, board, open);
5667
+ }
5668
+ /** 🔴 #4143 — every job of the story on this machine. */
5669
+ function claudeJobsEverOnStory(entry, board, open, home) {
5670
+ return claudeJobsWhere((job) => jobOnStory(job, entry, board, open), 0, home);
5671
+ }
5672
+ /** 🔴 #4143 — the story numbers a job's first line names: a brief's, a queue wake's or an investigation wake's; every job of a story names it there. */
5673
+ function storiesOfJob(job) {
5674
+ const opening = job.intent.split("\n", 1)[0];
5675
+ const named = STARTED_STORY.exec(opening) ?? WOKEN_STORY.exec(opening);
5676
+ if (named !== null)
5677
+ return [Number(named[1])];
5678
+ const decided = INVESTIGATION_WAKE.exec(opening);
5679
+ return decided === null ? [] : decided[2].split(", ").map((s) => Number(s.slice(1)));
5680
+ }
5681
+ /** 🔴 #4143 — reads {@link ClaudeJobsByStory} off Claude Code's job records. */
5682
+ export function claudeJobsByStory(home = claudeHome()) {
5683
+ const index = new Map();
5684
+ const dir = path.join(home, "jobs");
5685
+ if (!fs.existsSync(dir))
5686
+ return index;
5687
+ for (const jobId of fs.readdirSync(dir)) {
5688
+ const job = jobRecordOf(jobId, home);
5689
+ if (typeof job === "string")
5690
+ continue;
5691
+ for (const storyId of storiesOfJob(job))
5692
+ index.set(storyId, [...(index.get(storyId) ?? []), jobId]);
5693
+ }
5694
+ return index;
5695
+ }
5696
+ /**
5697
+ * 🔴 #4143 — the invariant, once per queue pass off one reading of Claude Code's jobs: no job or conversation of a story of `board`
5698
+ * that is no longer an open row stays on a history list. Every listed job of such a story that no process holds leaves Claude Code's
5699
+ * list for the archive, its session handed to the story's queue entry through `record` before it moves, and deleted at once when the
5700
+ * story is cold and has no entry left to purge it; a job at its prompt is stopped and taken on the next pass, one mid-turn is let finish.
5701
+ * A story of the board is one with a queue entry or one the board shipped or archived; the queue's own unarchived worker is left to its
5702
+ * retire. A finished entry's last conversation that no job lists any more leaves `projects/` for the archive the same way. Answers,
5703
+ * per story, why something of it is still listed.
5704
+ */
5705
+ export async function sweepClosedStories(board, entries, index, story, cli, record, home = claudeHome(), temp = tmpdir()) {
5706
+ const held = new Map();
5707
+ const open = (id) => story(id) === "open";
5708
+ const byStory = new Map(entries.map((e) => [e.storyId, e]));
5709
+ const closed = new Set([...index.keys(), ...byStory.keys()].filter((id) => !open(id) && (byStory.has(id) || story(id) !== "unknown")));
5710
+ for (const storyId of closed) {
5711
+ const entry = byStory.get(storyId);
5712
+ // NULL-OK: field entry is OPTIONAL and therefore it is ok to check for NULL
5713
+ if (entry !== undefined && IN_LINE.has(entry.state))
5714
+ continue;
5715
+ const subject = entry ?? { storyId, brief: "" };
5716
+ // NULL-OK: field worker is OPTIONAL and therefore it is ok to check for NULL
5717
+ const own = entry?.worker !== undefined && entry.worker.archivedAt === undefined ? entry.worker.jobId : undefined;
5718
+ const ids = (index.get(storyId) ?? []).filter((id) => {
5719
+ const job = jobRecordOf(id, home);
5720
+ return id !== own && typeof job !== "string" && jobOnStory(job, subject, board, open);
5721
+ });
5722
+ const taken = [];
5723
+ const hand = (session) => {
5724
+ taken.push(session);
5725
+ // NULL-OK: field entry is OPTIONAL and therefore it is ok to check for NULL
5726
+ if (entry !== undefined)
5727
+ record(entry, session);
5728
+ };
5729
+ try {
5730
+ await retireJobsOfStory(storyId, ids, cli, hand, home);
5731
+ const last = entry?.lastSession;
5732
+ // NULL-OK: field lastSession/worker is OPTIONAL and therefore it is ok to check for NULL
5733
+ if (last !== undefined && own === undefined && fs.existsSync(last.transcript)) {
5734
+ if (liveClaudeSessions(home).has(last.id))
5735
+ throw new WorkerNotStarted(`a process still runs #${storyId}'s last session ${last.id}, so it is archived once that process has gone`);
5736
+ hand(last);
5737
+ moveConversation(last.transcript, archivedTranscriptOf(last.transcript, home));
5738
+ }
5739
+ // NULL-OK: field entry is OPTIONAL and therefore it is ok to check for NULL
5740
+ if (entry === undefined && story(storyId) === "cold" && taken.length > 0)
5741
+ purgeStoryWorker(taken, home, temp);
5742
+ }
5743
+ catch (err) {
5744
+ if (!(err instanceof WorkerNotStarted))
5745
+ throw err;
5746
+ // OWNER: ITER/LOOP — a job of this closed story still has a process, or the disk refused its move, so it stays listed with the reason on the story's entry and is taken on a later pass; the next story is read.
5747
+ held.set(storyId, `its story is no longer an open row, and something of it is still on a history list: ${err.message}`);
5748
+ }
5749
+ }
5750
+ return held;
5577
5751
  }
5578
5752
  // GATE: how long a just-started worker is read as alive before its process has written its own live record (1.4 s measured on HP)
5579
5753
  export const WORKER_START_GRACE_MS = 2 * 60_000;
@@ -5896,8 +6070,51 @@ const usageLimitOf = (job) => {
5896
6070
  if (Number.isNaN(recordedAt))
5897
6071
  throw new Error(`the job record of session ${job.sessionId} carries no readable updatedAt (${JSON.stringify(job.updatedAt)}), so the reset its usage-limit stop names (${job.needs}) cannot be placed in time`);
5898
6072
  const until = limitResetAt(job.needs, recordedAt);
5899
- return until === undefined ? { said: job.needs } : { said: job.needs, until };
6073
+ return until === undefined ? { said: job.needs, at: recordedAt } : { said: job.needs, until, at: recordedAt };
5900
6074
  };
6075
+ /** 🔴 #4555 — one usage-limit episode: the words of the stop and the instant its reset names, so the same words a day later (`resets 2am`) are a new episode. */
6076
+ // NULL-OK: field until is OPTIONAL and therefore it is ok to check for NULL
6077
+ const limitEpisodeOf = (limit) => `${limit.said}@${limit.until === undefined ? "no reset read" : limit.until}`;
6078
+ /**
6079
+ * 🔴 #4555 — a worker its account's usage limit stopped goes on NOW when this box's jobs run on something with room: a key
6080
+ * the settings route them to (`routedKey`), or a live subscription with room — a stale reading that still shows the
6081
+ * stopped account with room costs one wake and one fresh start, after which the episode waits. Otherwise it waits for its reset, and the words name every subscription and every key the reading saw. A key the
6082
+ * BYOK switch has not routed is named, never started on: this box's own BYOK fallback setting decides when work moves to a key.
6083
+ */
6084
+ export function limitRoomOf(reading, routedKey) {
6085
+ // NULL-OK: field routedKey is OPTIONAL and therefore it is ok to check for NULL
6086
+ if (routedKey !== undefined && routedKey.trim() !== "")
6087
+ return { wake: true, why: `Claude Code's jobs on this box now run on the key at ${routedKey}, so it goes on there now` };
6088
+ // NULL-OK: field accounts is OPTIONAL and therefore it is ok to check for NULL
6089
+ if (reading === undefined || reading.accounts === undefined)
6090
+ return { wake: false, why: `${roomWords(reading)}, so it waits for its reset` };
6091
+ const roomy = (a) => roomPctOf(a) > 0;
6092
+ const live = reading.accounts.find((a) => a.label === reading.live);
6093
+ // NULL-OK: field live is OPTIONAL and therefore it is ok to check for NULL
6094
+ if (live !== undefined && roomy(live))
6095
+ return { wake: true, why: `${live.label} is live on this box with ${live.roomPct}% room, so it goes on there now instead of waiting for the reset` };
6096
+ const elsewhere = reading.accounts.filter((a) => a !== live && roomy(a));
6097
+ // NULL-OK: field live is OPTIONAL and therefore it is ok to check for NULL
6098
+ const waits = elsewhere.length > 0 ? `${elsewhere.map((a) => `${a.label} has ${a.roomPct}% room`).join(" and ")} but ${reading.live === undefined ? "no account" : reading.live} is live on this box, so it goes on the moment the switch makes one of them live` : "no subscription has room and no key is routed on this box, so it waits for its reset";
6099
+ return { wake: false, why: `${waits} — ${roomWords(reading)}` };
6100
+ }
6101
+ /** 🔴 #4555 — the room an account can take work on: its read percent, or none when it refused work, could not be read or named no figure. */
6102
+ // NULL-OK: field unread is OPTIONAL and therefore it is ok to check for NULL
6103
+ const roomPctOf = (a) => (a.refused || a.unread !== undefined || a.roomPct === undefined ? 0 : a.roomPct);
6104
+ /** 🔴 #4555 — one provider's reading in words: every subscription with its room and refill, and every key with its funds. */
6105
+ export function roomWords(reading) {
6106
+ // NULL-OK: field reading is OPTIONAL and therefore it is ok to check for NULL
6107
+ if (reading === undefined)
6108
+ return "its room was not read";
6109
+ // NULL-OK: field accounts is OPTIONAL and therefore it is ok to check for NULL
6110
+ if (reading.accounts === undefined)
6111
+ return `its room was not read${reading.reason === undefined ? "" : ` (${reading.reason})`}`;
6112
+ // NULL-OK: field unread is OPTIONAL and therefore it is ok to check for NULL
6113
+ const account = (a) => `${a.label} ${a.unread !== undefined ? `unread (${a.unread})` : `${a.roomPct === undefined ? "no room figure" : `${a.roomPct}%`}${a.refused ? " refused" : ""}${a.resetsAt === undefined ? "" : ` refills ${new Date(a.resetsAt).toISOString()}`}`}`;
6114
+ // NULL-OK: field keys is OPTIONAL and therefore it is ok to check for NULL
6115
+ const keys = reading.keys === undefined ? "keys not read" : reading.keys.length === 0 ? "no key" : `keys ${reading.keys.map((k) => `${k.label} ${k.funds}`).join(", ")} (a key takes work only once this box's BYOK switch routes Claude Code to it)`;
6116
+ return `subscriptions ${reading.accounts.length === 0 ? "none" : reading.accounts.map(account).join(", ")}; ${keys}`;
6117
+ }
5901
6118
  /** 🔴 #4544 — when a parked worker is next woken: its parked wait, and never before the reset a usage-limit stop names. */
5902
6119
  const parkedWakeAt = (worker, parkedAt, parked) => Math.max(parkedAt + parkedWaitMs(worker, parked), worker.limit?.until ?? 0);
5903
6120
  /**
@@ -6169,17 +6386,25 @@ export async function retireStoryWorker(worker, cli, record, home = claudeHome()
6169
6386
  * still holds at its prompt is stopped, one still mid-turn is let finish, and either refuses this pass naming it, so the
6170
6387
  * story is archived once every process of it has gone; answers what of the worker's own conversation moved.
6171
6388
  */
6172
- export async function retireStory(entry, board, worker, cli, record, home = claudeHome()) {
6173
- await retireEarlierClaudeJobs(entry, board, worker.jobId, cli, (session) => record(session, "earlier"), home);
6389
+ export async function retireStory(entry, board, worker, cli, open, record, home = claudeHome()) {
6390
+ await retireEarlierClaudeJobs(entry, board, worker.jobId, cli, open, (session) => record(session, "earlier"), home);
6174
6391
  return retireStoryWorker(worker, cli, (session) => record(session, "own"), home);
6175
6392
  }
6176
6393
  /** 🔴 #4271 — every Claude job started on a done story in `board` other than `workerJob` leaves every history list for the archive, whichever provider ran its last worker; refuses while a process of one still holds it. */
6177
- export async function retireEarlierClaudeJobs(entry, board, workerJob, cli, record, home = claudeHome()) {
6178
- const storyId = entry.storyId;
6394
+ export function retireEarlierClaudeJobs(entry, board, workerJob, cli, open, record, home = claudeHome()) {
6395
+ return retireClaudeJobsOfStory(entry, board, [workerJob], cli, open, record, home);
6396
+ }
6397
+ /** 🔴 #4143 — every Claude job of a done story in `board` but the `kept` ones leaves every history list for the archive, each session handed to `record` before anything of it moves; refuses while a process of one still holds it. */
6398
+ async function retireClaudeJobsOfStory(entry, board, kept, cli, open, record, home = claudeHome()) {
6399
+ const earlier = new Set(claudeJobsEverOnStory(entry, board, open, home));
6400
+ for (const jobId of kept)
6401
+ earlier.delete(jobId);
6402
+ await retireJobsOfStory(entry.storyId, [...earlier], cli, record, home);
6403
+ }
6404
+ /** 🔴 #4143 — the given jobs of a done story leave every history list for the archive, each session handed to `record` before anything of it moves; one a process still holds at its prompt is stopped, one mid-turn is let finish, and either refuses this pass naming it. */
6405
+ async function retireJobsOfStory(storyId, jobIds, cli, record, home) {
6179
6406
  const held = [];
6180
- const earlier = new Set(claudeJobsEverOnStory(entry, board, home));
6181
- earlier.delete(workerJob);
6182
- for (const jobId of earlier) {
6407
+ for (const jobId of jobIds) {
6183
6408
  const job = jobRecordOf(jobId, home);
6184
6409
  if (job !== "torn" && job !== "gone" && liveClaudeSessions(home).has(job.sessionId)) {
6185
6410
  const atPrompt = TURN_OVER.has(job.state);
@@ -6196,8 +6421,10 @@ export async function retireEarlierClaudeJobs(entry, board, workerJob, cli, reco
6196
6421
  /** 🔴 #4143 — an archived worker's conversation goes back into `projects/`, where `claude --bg --resume` finds it to wake; answers which of its files moved. */
6197
6422
  export function restoreStoryWorker(worker, home = claudeHome()) {
6198
6423
  // NULL-OK: field session is OPTIONAL and therefore it is ok to check for NULL
6199
- return worker.session === undefined ? "unknown" : moveConversation(archivedTranscriptOf(worker.session.transcript, home), worker.session.transcript);
6424
+ return worker.session === undefined ? "unknown" : restoreSession(worker.session, home);
6200
6425
  }
6426
+ /** 🔴 #4143 — an archived conversation goes back into `projects/`; answers which of its files moved. */
6427
+ export const restoreSession = (session, home = claudeHome()) => moveConversation(archivedTranscriptOf(session.transcript, home), session.transcript);
6201
6428
  /** 🔴 #4143 — a Claude Code session id as Claude Code writes it, and the only shape a purge deletes by. */
6202
6429
  const SESSION_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
6203
6430
  /** 🔴 #4143 — the bytes under `target`, a file or a folder; a path that is not there holds none. */
@@ -536,9 +536,28 @@ const ROOM_PROVIDERS = Object.freeze(["claude", "codex", "copilot"]);
536
536
  class RoomReadError extends Error {
537
537
  }
538
538
  /**
539
- * @typedef {{ state: "room" } | { state: "out", resetsAtMs: number | undefined } | { state: "unread", reason: string }} RoomReading
539
+ * @typedef {{ label: string, roomPct: number | undefined, resetsAt: number | undefined, refused: boolean, unread?: string }} AccountRoom
540
+ * @typedef {{ label: string, funds: string }} KeyRoom
541
+ * @typedef {{ live?: string, accounts?: AccountRoom[], keys?: KeyRoom[] }} RoomDetail
542
+ * @typedef {({ state: "room" } | { state: "out", resetsAtMs: number | undefined } | { state: "unread", reason: string }) & RoomDetail} RoomReading
540
543
  * @typedef {Partial<Record<string, RoomReading>>} ProviderRooms
541
544
  */
545
+ /**
546
+ * #4555 — what one provider's reading saw account by account: the account live on this box, each subscription's room and refill, and each key that provider's CLI can run with its funds.
547
+ * @param {any} provider @param {any[] | undefined} keys undefined when the answer carried no key list @param {string} id @returns {RoomDetail}
548
+ */
549
+ function roomDetailOf(provider, keys, id) {
550
+ const accounts = provider.accounts.map((a) => ({
551
+ label: String(a.label ?? a.id),
552
+ roomPct: typeof a.roomPct === "number" ? a.roomPct : a.unlimited === true ? 100 : undefined,
553
+ resetsAt: typeof a.resetsAt === "number" ? a.resetsAt : undefined,
554
+ refused: a.refused === true,
555
+ ...(a.state === "read" ? {} : { unread: typeof a.reason === "string" ? a.reason : "its room could not be read" }),
556
+ }));
557
+ // NULL-OK: field keys is OPTIONAL and therefore it is ok to check for NULL
558
+ const runs = keys === undefined ? {} : { keys: keys.filter((k) => Array.isArray(k.agents) && k.agents.includes(id)).map((k) => ({ label: String(k.label ?? k.id), funds: String(k.funds) })) };
559
+ return { ...(typeof provider.live === "string" ? { live: provider.live } : {}), accounts, ...runs };
560
+ }
542
561
  /** @param {string} provider */
543
562
  function runsOnKeys(provider) {
544
563
  return provider === "opencode";
@@ -551,27 +570,29 @@ function billsAKey(provider, rooms) {
551
570
  * One provider's token room out of its `provider_room` entry: some left, spent until a refill, or a reading that could not be taken (never read as spent).
552
571
  * @param {any} provider @param {number} now @returns {RoomReading}
553
572
  */
554
- function roomReadingOf(provider, now) {
573
+ function roomReadingOf(provider, now, keys, id) {
555
574
  // NULL-OK: field provider is OPTIONAL and therefore it is ok to check for NULL
556
575
  if (provider === undefined || provider.state !== "read" || !Array.isArray(provider.accounts)) {
557
576
  return { state: "unread", reason: typeof provider?.reason === "string" ? provider.reason : "the provider was not read" };
558
577
  }
559
578
  const accounts = provider.accounts;
579
+ const detail = roomDetailOf(provider, keys, id);
560
580
  if (accounts.some((a) => a.state === "read" && a.refused !== true && (a.unlimited === true || (typeof a.roomPct === "number" && a.roomPct > 0))))
561
- return { state: "room" };
581
+ return { state: "room", ...detail };
562
582
  if (accounts.length === 0 || !accounts.every((a) => a.state === "read" && typeof a.roomPct === "number"))
563
- return { state: "unread", reason: "an account's room could not be read" };
583
+ return { state: "unread", reason: "an account's room could not be read", ...detail };
564
584
  if (accounts.some((a) => a.refused !== true && typeof a.resetsAt === "number" && a.resetsAt <= now))
565
- return { state: "unread", reason: "the reading predates an account's refill" };
585
+ return { state: "unread", reason: "the reading predates an account's refill", ...detail };
566
586
  const refills = accounts.filter((a) => a.refused !== true).map((a) => a.resetsAt).filter((r) => typeof r === "number");
567
- return { state: "out", resetsAtMs: refills.length === 0 ? undefined : Math.min(...refills) };
587
+ return { state: "out", resetsAtMs: refills.length === 0 ? undefined : Math.min(...refills), ...detail };
568
588
  }
569
589
  /**
570
590
  * The room of each provider a dispatcher can land on, out of `provider_room`'s own answer. A provider the answer does not carry is unread, never out.
571
- * @param {{ providers?: Record<string, any> }} answer @param {number} now @returns {ProviderRooms}
591
+ * @param {{ providers?: Record<string, any>, keys?: any[] }} answer @param {number} now @returns {ProviderRooms}
572
592
  */
573
593
  function roomsOf(answer, now) {
574
- return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, roomReadingOf(answer.providers?.[id], now)]));
594
+ const keys = Array.isArray(answer.keys) ? answer.keys : undefined;
595
+ return Object.fromEntries(ROOM_PROVIDERS.map((id) => [id, roomReadingOf(answer.providers?.[id], now, keys, id)]));
575
596
  }
576
597
  /** Every provider unread, with the reason the whole reading failed. @param {string} reason @returns {ProviderRooms} */
577
598
  function unreadRooms(reason) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omni-notify-mcp",
3
- "version": "1.3.447",
3
+ "version": "1.3.449",
4
4
  "homepage": "https://www.npmjs.com/package/omni-notify-mcp",
5
5
  "description": "Reach your AI agents from anywhere — and let them reach you. One resident process on 127.0.0.1:7475 serves the whole tool surface to Claude Code, GitHub Copilot Chat and Codex: desktop, Telegram, Slack, ntfy, Discord, Teams and SMS are configured in one file, and agents notify you when long work finishes or a decision is needed, ask you a question and wait for your answer, and receive and reply to the messages you send them — with Do Not Disturb and idle detection deciding what actually gets through.",
6
6
  "main": "dist/daemon.js",