omni-notify-mcp 1.3.324 → 1.3.325

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
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  /**
3
- * notify, always on — the one process per machine that starts at login.
3
+ * notify's daemon — the one process per machine, started by the boot supervisor.
4
4
  *
5
5
  * It runs the same server code as the stdio bridge (`startNotifyServer`) with no MCP client attached, so it
6
6
  * competes for the gateway port like every other BN process, and the one that binds it polls the channels,
@@ -15,7 +15,7 @@ import { join } from "path";
15
15
  import { fileURLToPath } from "url";
16
16
  import { ALWAYS_ON_PATH, CONFIG_DIR, PACKAGE_VERSION, startNotifyServer, yieldGateway } from "./notify.js";
17
17
  import { startNotifyDoor } from "./gateway/notifyDoor.js";
18
- import { announceTakeover } from "./shared/webhost/originHandover.js";
18
+ import { announceTakeover, inThisBoot } from "./shared/webhost/originHandover.js";
19
19
  import { TunnelRunner } from "./gateway/tunnel.js";
20
20
  const HEARTBEAT_MS = 10_000;
21
21
  function beat(pid = process.pid) {
@@ -24,7 +24,7 @@ function beat(pid = process.pid) {
24
24
  writeFileSync(staged, JSON.stringify({ pid, at: Date.now(), version: PACKAGE_VERSION }));
25
25
  renameSync(staged, ALWAYS_ON_PATH);
26
26
  }
27
- /** Run by the launchd job or systemd unit vscode-extension/alwaysOn.js installs, or on Windows by the login session's supervise loop in alwaysOn.js or the boot task's vscode-extension/originSupervisor.js, each of which starts it again when it exits. On Windows that supervisor is this process's IPC parent: the channel is open only while it lives, so a dead supervisor, or a reused pid, never reads as supervised. */
27
+ /** Run by the boot supervisor (BullseyeShared workspace-mcp/originSupervisor.js, under the login starter every Bullseye extension installs), or on Windows by the login session's supervise loop in alwaysOn.js, each of which starts it again when it exits. On Windows that supervisor is this process's IPC parent: the channel is open only while it lives, so a dead supervisor, or a reused pid, never reads as supervised. */
28
28
  function supervised() {
29
29
  if (process.platform === "win32")
30
30
  return process.connected === true;
@@ -53,7 +53,7 @@ function replaceWithInstalledBuild() {
53
53
  }
54
54
  process.exit(0);
55
55
  }
56
- /** The Stop the panel pressed is this machine's own setting, so a process a login entry started after it reads the same file and starts nothing. Absent, the machine has never been stopped and starts as it always has. */
56
+ /** The Stop the panel pressed is this machine's own setting until a Start or the next boot (#3849 Q782), so a process a login entry started after it in this boot reads the same file and starts nothing. Absent, the machine has never been stopped and starts as it always has. */
57
57
  function stoppedByHand() {
58
58
  const desired = join(CONFIG_DIR, "always-on-desired.json");
59
59
  if (!existsSync(desired))
@@ -65,10 +65,14 @@ function stoppedByHand() {
65
65
  catch (err) {
66
66
  throw new Error(`${desired} is not readable JSON, so whether a Stop was pressed on this machine cannot be known — ${err.message}`);
67
67
  }
68
- return pressed.desired === "stopped";
68
+ if (pressed.desired !== "stopped")
69
+ return false;
70
+ if (typeof pressed.at !== "number")
71
+ throw new Error(`${desired} names a Stop with no time it was pressed, so whether it was pressed in this boot cannot be known`);
72
+ return inThisBoot(pressed.at);
69
73
  }
70
74
  if (stoppedByHand()) {
71
- console.log("[BOOT] BullseyeNotify always-on — a Stop was pressed on this machine; nothing started, and nothing beats until Start is pressed in the panel.");
75
+ console.log("[BOOT] BullseyeNotify daemon — a Stop was pressed on this machine; nothing started, and nothing beats until Start is pressed in the panel or the machine reboots.");
72
76
  process.exit(0);
73
77
  }
74
78
  // The shared hand-over (src/shared/webhost/originHandover.js ensureResidentDoor) puts a later release on the chat door: the new build is started with --takeover over an IPC channel, says it waits, and binds once this build lets the door go.
@@ -678,7 +678,7 @@ async function listView(shelf) {
678
678
  }
679
679
  `;
680
680
  /** A service page's own half (#3849): once signed in, the gateway's `/screen/open` keeps the sign-in for the page's own
681
- * requests and names the one page this host's always-on service draws, and the visitor goes straight to it — no VS Code
681
+ * requests and names the one page this host's own service draws, and the visitor goes straight to it — no VS Code
682
682
  * window is chosen or needed. */
683
683
  const SERVICE_SCRIPT = String.raw `
684
684
  var main = document.getElementById("main"), title = document.getElementById("title"), btnRefresh = document.getElementById("refresh");
@@ -708,7 +708,7 @@ async function home() {
708
708
  }
709
709
  `;
710
710
  /** The page each service host of the public gateway serves (#2873): BN's look and BN's sign-in, then the page the
711
- * service's always-on process draws. The line under the header names the process that answered. */
711
+ * service's daemon draws. The line under the header names the process that answered. */
712
712
  export function serviceHtml({ name, host }) {
713
713
  const me = servingIdentity();
714
714
  const safe = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
@@ -25,11 +25,11 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
25
25
  import { createMcpServer, sessionIdentity } from "../notify.js";
26
26
  import { answerShutdown, healthBody, TAKEOVER_BIND } from "../shared/webhost/originHandover.js";
27
27
  /** BN's own port block: 7470 is the gateway, so the chat tools take the next free one. */
28
- // GATE: the door's port may be moved ONLY under the test gate, so a suite drives a real always-on process on a port it owns; without the gate it is 7475 and no environment can redirect it. vscode-extension/alwaysOn.js probes the same rule.
28
+ // GATE: the door's port may be moved ONLY under the test gate, so a suite drives a real daemon on a port it owns; without the gate it is 7475 and no environment can redirect it. vscode-extension/alwaysOn.js probes the same rule.
29
29
  export const NOTIFY_DOOR_PORT = process.env.NOTIFY_MCP_TEST_ENDPOINTS === "1" && Number(process.env.NOTIFY_DOOR_PORT) > 0 ? Number(process.env.NOTIFY_DOOR_PORT) : 7475;
30
30
  export const NOTIFY_DOOR_PATH = "/mcp";
31
31
  const RETRY_MS = 5_000;
32
- /** The name the always-on process answers `/health` with: the `server` the boot task's supervisor hands BN's port over by (vscode-extension/originSupervisor.js ORIGINS). */
32
+ /** The name the daemon answers `/health` with: the `server` the boot task's supervisor hands BN's port over by (BullseyeShared workspace-mcp/originSupervisor.js ORIGINS). */
33
33
  export const NOTIFY_SERVER = "bullseye-notify";
34
34
  function headerOf(req, name) {
35
35
  const value = req.headers[name];
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The Notify panel's logic, owned by the always-on service (#3512): the settings the notify server reads, how a value
2
+ * The Notify panel's logic, owned by the service (#3512): the settings the notify server reads, how a value
3
3
  * is checked and written, the conversation On/Off switch, and the one-line state of the channels. The VS Code panel and
4
4
  * the web page are thin clients of the routes in restDoor.ts — neither holds a copy of anything here, and neither needs
5
5
  * a VS Code window for it.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * BN's Settings and Public access pages (#3512), served by the always-on service beside the conversation page. They hold
2
+ * BN's Settings and Public access pages (#3512), served by the service beside the conversation page. They hold
3
3
  * no logic: each draws what a bearer route answers (`GET /v1/panel`, `GET /v1/public-access`) and sends every click back
4
4
  * to one (`POST /v1/settings`, `POST /v1/conversation-switch`, `POST /v1/public-access/<step>`). The VS Code panel frames
5
5
  * these very pages, so the panel and a browser with every editor closed show the same thing from the same service.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The Public access wizard (#2100), owned by the always-on service (#3512). It walks a user through creating a Cloudflare
2
+ * The Public access wizard (#2100), owned by the service (#3512). It walks a user through creating a Cloudflare
3
3
  * Tunnel, saves the token beside the gateway's own secret in config.json, downloads cloudflared into BN's folder, shows
4
4
  * this process running it (tunnel.ts) and checks the public hostname end to end. A cloudflared tunnel this machine already
5
5
  * has is detected and named, and the wizard will not start a second one. The VS Code panel and the web page are thin
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The HTTP/REST door of the Agent Gateway (design section g). The always-on process owns the port; every call
2
+ * The HTTP/REST door of the Agent Gateway (design section g). The daemon owns the port; every call
3
3
  * carries the conversation id and one bearer token from `config.json` (`agentGateway.token`), and nothing is
4
4
  * kept in the connection, so a restart between a send and its read loses nothing. No request is held longer
5
5
  * than the 55 s every blocking BN call is capped at, so starting work and reading its answer are separate calls.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The Cloudflare Tunnel connector of the Agent Gateway (#2100). The always-on process that holds the gateway door
2
+ * The Cloudflare Tunnel connector of the Agent Gateway (#2100). The daemon that holds the gateway door
3
3
  * also runs `cloudflared tunnel run` as its windowless child, so a user's own hostname reaches the door without a
4
4
  * hand-built tunnel. The token is `agentGateway.tunnel.token` in `config.json` — beside `agentGateway.token`, the
5
5
  * gateway secret this process already reads there — written by the extension's Public access wizard, and it reaches
package/dist/notify.js CHANGED
@@ -742,7 +742,7 @@ function takeSharedEntriesForSelf(saved) {
742
742
  for (const { deliveredTo, ...entry } of saved) {
743
743
  if (deliveredTo.includes(deliveredKey(SELF_TAG)) || alreadyDelivered(entry, SELF_TAG))
744
744
  continue;
745
- // The always-on process is the machine's queue: it holds every chat's undelivered entry in memory, tagged ones
745
+ // The daemon is the machine's queue: it holds every chat's undelivered entry in memory, tagged ones
746
746
  // included, because the HTTP chats it serves are the only readers of a tagged entry and each drains its own by
747
747
  // tag. A bridge (one host) takes only what is addressed to it. An entry a chat already drained is marked per tag
748
748
  // in the shared file, and that mark is what keeps a second reader from delivering it again.
@@ -959,7 +959,7 @@ function queueInboxEntry(entry) {
959
959
  }
960
960
  function ingestChatEntry(entry) {
961
961
  const { waiters } = ingestInboxEntry(entry, entry.origin ?? "telegram");
962
- // The always-on process serves no session of its own, so it cannot say who is connected — only that the shared inbox holds the message.
962
+ // The daemon serves no session of its own, so it cannot say who is connected — only that the shared inbox holds the message.
963
963
  if (QUEUE_ONLY)
964
964
  return entry.tag
965
965
  ? `📬 Queued for @${entry.tag}. Delivered when that session is connected.`
@@ -1135,7 +1135,7 @@ async function startTelegramListener() {
1135
1135
  }
1136
1136
  }
1137
1137
  }
1138
- // ── Slack inbound poller (always-on; folds slack-poll.sh → #16) ────────────────
1138
+ // ── Slack inbound poller (the daemon's; folds slack-poll.sh → #16) ────────────────
1139
1139
  function decodeB64Fields(obj) {
1140
1140
  if (Array.isArray(obj))
1141
1141
  return obj.map(decodeB64Fields);
@@ -2443,7 +2443,7 @@ export function createMcpServer(clientId, sessionTag) {
2443
2443
  }
2444
2444
  // ── Every host runs its own copy of this process ──────────────────────────────
2445
2445
  //
2446
- // Claude Code, GitHub Copilot Chat, Codex and the always-on daemon each run this program, so several can be
2446
+ // Claude Code, GitHub Copilot Chat, Codex and the daemon each run this program, so several can be
2447
2447
  // alive on one machine. What they must SHARE — the inbox — lives on disk under CONFIG_DIR. What only ONE may do —
2448
2448
  // the channel pollers, the REST/MCP door and the agent conversations — belongs to the process that binds the
2449
2449
  // gateway port: the OS lets exactly one succeed, every other process stays dormant and retries, and the first
@@ -2508,9 +2508,9 @@ function startOwnedWork() {
2508
2508
  AgentGateway.instance().boot();
2509
2509
  log("·", "listener", `this process (pid ${process.pid}, build ${PACKAGE_VERSION}) owns the Telegram, Slack, Discord and Teams pollers, the ntfy and SMS pollers, the agent's email door, and the agent conversations`);
2510
2510
  }
2511
- // GATE: an always-on beat older than this is presumed dead; it is vscode-extension/alwaysOn.js's own STALE_MS.
2511
+ // GATE: a daemon's beat older than this is presumed dead; it is vscode-extension/alwaysOn.js's own STALE_MS.
2512
2512
  const DAEMON_BEAT_STALE_MS = 30_000;
2513
- /** Written by the always-on process (daemon.ts) on its beat, read by vscode-extension/alwaysOn.js. */
2513
+ /** Written by the daemon (daemon.ts) on its beat, read by vscode-extension/alwaysOn.js. */
2514
2514
  export const ALWAYS_ON_PATH = join(CONFIG_DIR, "always-on.json");
2515
2515
  /** An always-on process is alive and beating — of the given build, when one is named. */
2516
2516
  function daemonBeats(version) {
@@ -2541,15 +2541,15 @@ let supersededSaid = false;
2541
2541
  /** The next release asked for the chat door over `POST /shutdown` (the shared hand-over): this process is superseded by it as it is by a newer manifest, though no manifest beside it moved. */
2542
2542
  let yielding = false;
2543
2543
  let reaskOwnership = () => { };
2544
- /** The always-on process's answer to the hand-over's `POST /shutdown`: the gateway passes to the release that asked, through the same step-aside a newer manifest triggers, so the pollers drain before the port is let go. */
2544
+ /** The daemon's answer to the hand-over's `POST /shutdown`: the gateway passes to the release that asked, through the same step-aside a newer manifest triggers, so the pollers drain before the port is let go. */
2545
2545
  export function yieldGateway() {
2546
2546
  yielding = true;
2547
2547
  reaskOwnership();
2548
2548
  }
2549
2549
  /**
2550
2550
  * Once the extension installs a newer build, this process is superseded and the gateway passes to the installed build:
2551
- * a superseded process never takes it while an always-on process beats, and one that holds it steps aside once no
2552
- * answer is in flight — the always-on process at once, since it starts the installed build in its place, and a
2551
+ * a superseded process never takes it while a daemon beats, and one that holds it steps aside once no
2552
+ * answer is in flight — the daemon at once, since it starts the installed build in its place, and a
2553
2553
  * bridge once the installed build's always-on process beats to take it over.
2554
2554
  */
2555
2555
  function tryOwnGateway(polling, host) {
@@ -361,6 +361,8 @@ export class SchedulerBeat {
361
361
  // acted on, which is the SAFE direction. It is a subprocess guard, never a throttle on the kill decision, which has
362
362
  // no clock at all.
363
363
  const SAMPLE_TIMEOUT_MS = 15_000;
364
+ /** #3934 — the variable every lane's shell call is started with, naming the lane; a process inherits it from whatever started it, a detached one included. */
365
+ export const LANE_ENV = "BULLSEYE_LANE";
364
366
  /**
365
367
  * The executable name a command line starts with, folded to bare + lowercase — `"C:\Program Files\Git\usr\
366
368
  * bin\sleep.exe" 20` answers `sleep.exe`. The first whitespace token, quotes stripped, then its basename, so
@@ -473,6 +475,43 @@ public static class AgentSessionProcessTable {
473
475
  [DllImport("kernel32.dll")] static extern bool K32GetProcessMemoryInfo(IntPtr handle, out Memory memory, uint cb);
474
476
  [DllImport("ntdll.dll")] static extern int NtQueryInformationProcess(IntPtr handle, int infoClass, IntPtr buffer, int length, out int returned);
475
477
  static Dictionary<string, string> commands = new Dictionary<string, string>();
478
+ static Dictionary<string, string> laneTags = new Dictionary<string, string>();
479
+ [DllImport("kernel32.dll")] static extern bool ReadProcessMemory(IntPtr process, IntPtr address, byte[] buffer, IntPtr size, out IntPtr read);
480
+ static IntPtr PointerAt(IntPtr process, IntPtr address) {
481
+ var cell = new byte[8];
482
+ IntPtr read;
483
+ if (!ReadProcessMemory(process, address, cell, new IntPtr(8), out read) || read.ToInt64() != 8) return IntPtr.Zero;
484
+ return new IntPtr(BitConverter.ToInt64(cell, 0));
485
+ }
486
+ static string LaneTagOf(uint pid) {
487
+ IntPtr handle = OpenProcess(0x1000 | 0x0010, false, pid);
488
+ if (handle == IntPtr.Zero) return "";
489
+ try {
490
+ IntPtr basic = Marshal.AllocHGlobal(48);
491
+ int returned;
492
+ IntPtr peb;
493
+ try {
494
+ if (IntPtr.Size != 8 || NtQueryInformationProcess(handle, 0, basic, 48, out returned) != 0) return "";
495
+ peb = Marshal.ReadIntPtr(basic, 8);
496
+ } finally { Marshal.FreeHGlobal(basic); }
497
+ IntPtr parameters = PointerAt(handle, IntPtr.Add(peb, 0x20));
498
+ if (parameters == IntPtr.Zero) return "";
499
+ IntPtr environment = PointerAt(handle, IntPtr.Add(parameters, 0x80));
500
+ long size = PointerAt(handle, IntPtr.Add(parameters, 0x3F0)).ToInt64();
501
+ if (environment == IntPtr.Zero || size <= 0 || size > 1048576) return "";
502
+ var block = new byte[size];
503
+ IntPtr got;
504
+ if (!ReadProcessMemory(handle, environment, block, new IntPtr(size), out got)) return "";
505
+ string text = "\\0" + Encoding.Unicode.GetString(block, 0, (int)got.ToInt64());
506
+ const string marker = "\\0BULLSEYE_LANE=";
507
+ int at = text.IndexOf(marker, StringComparison.Ordinal);
508
+ if (at == -1) return "";
509
+ int from = at + marker.Length, end = text.IndexOf('\\0', from);
510
+ string tag = end == -1 ? text.Substring(from) : text.Substring(from, end - from);
511
+ foreach (char c in tag) if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == ':' || c == '.')) return "";
512
+ return tag;
513
+ } finally { CloseHandle(handle); }
514
+ }
476
515
  static string CommandOf(IntPtr handle) {
477
516
  int length;
478
517
  NtQueryInformationProcess(handle, 60, IntPtr.Zero, 0, out length);
@@ -486,6 +525,7 @@ public static class AgentSessionProcessTable {
486
525
  public static string Table() {
487
526
  var rows = new StringBuilder();
488
527
  var kept = new Dictionary<string, string>();
528
+ var keptTags = new Dictionary<string, string>();
489
529
  IntPtr snap = CreateToolhelp32Snapshot(2, 0);
490
530
  if (snap == new IntPtr(-1)) throw new InvalidOperationException("no process snapshot");
491
531
  try {
@@ -495,6 +535,7 @@ public static class AgentSessionProcessTable {
495
535
  long created = 0, exited, kernel = 0, user = 0;
496
536
  ulong workingSet = 0;
497
537
  string command = "";
538
+ string tag = "";
498
539
  IntPtr handle = OpenProcess(0x1000, false, entry.pid);
499
540
  if (handle != IntPtr.Zero) {
500
541
  try {
@@ -505,12 +546,15 @@ public static class AgentSessionProcessTable {
505
546
  if (!commands.TryGetValue(key, out command)) command = CommandOf(handle);
506
547
  if (command == null) command = "";
507
548
  else kept[key] = command;
549
+ if (!laneTags.TryGetValue(key, out tag)) tag = LaneTagOf(entry.pid);
550
+ keptTags[key] = tag;
508
551
  } finally { CloseHandle(handle); }
509
552
  }
510
- rows.Append(entry.pid).Append('\\t').Append(entry.ppid).Append('\\t').Append(kernel + user).Append('\\t').Append(workingSet).Append('\\t').Append(created).Append('\\t').Append(command.Replace("\\r", " ").Replace("\\n", " ")).Append('\\n');
553
+ rows.Append(entry.pid).Append('\\t').Append(entry.ppid).Append('\\t').Append(kernel + user).Append('\\t').Append(workingSet).Append('\\t').Append(created).Append('\\t').Append(tag).Append('\\t').Append(command.Replace("\\r", " ").Replace("\\n", " ")).Append('\\n');
511
554
  }
512
555
  } finally { CloseHandle(snap); }
513
556
  commands = kept;
557
+ laneTags = keptTags;
514
558
  return rows.ToString();
515
559
  }
516
560
  [DllImport("iphlpapi.dll")] static extern uint GetExtendedTcpTable(IntPtr table, ref int size, bool order, int family, int tableClass, uint reserved);
@@ -540,11 +584,90 @@ public static class AgentSessionProcessTable {
540
584
  }
541
585
  return pids.ToString();
542
586
  }
587
+ [StructLayout(LayoutKind.Sequential)]
588
+ struct Accounting { public long user, kernel, periodUser, periodKernel; public uint faults, total, active, terminated; }
589
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] static extern IntPtr CreateJobObjectW(IntPtr attributes, string name);
590
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
591
+ [DllImport("kernel32.dll")] static extern bool IsProcessInJob(IntPtr process, IntPtr job, out bool inside);
592
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool QueryInformationJobObject(IntPtr job, int infoClass, out Accounting info, int length, IntPtr returned);
593
+ [DllImport("kernel32.dll", SetLastError = true)] static extern bool QueryInformationJobObject(IntPtr job, int infoClass, IntPtr info, int length, IntPtr returned);
594
+ static Dictionary<string, IntPtr> jobs = new Dictionary<string, IntPtr>();
595
+ static long JobTicks(IntPtr job, out uint total, out uint active) {
596
+ Accounting a;
597
+ if (!QueryInformationJobObject(job, 1, out a, Marshal.SizeOf(typeof(Accounting)), IntPtr.Zero)) throw new InvalidOperationException("job accounting unread: " + Marshal.GetLastWin32Error());
598
+ total = a.total; active = a.active;
599
+ return a.user + a.kernel;
600
+ }
601
+ static string JobPids(IntPtr job) {
602
+ for (int room = 256; ; room *= 4) {
603
+ IntPtr buffer = Marshal.AllocHGlobal(8 + room * IntPtr.Size);
604
+ try {
605
+ if (QueryInformationJobObject(job, 3, buffer, 8 + room * IntPtr.Size, IntPtr.Zero)) {
606
+ var ids = new StringBuilder();
607
+ int listed = Marshal.ReadInt32(buffer, 4);
608
+ for (int i = 0; i < listed; i++) ids.Append(i == 0 ? "" : ",").Append(Marshal.ReadIntPtr(buffer, 8 + i * IntPtr.Size).ToInt64());
609
+ return ids.ToString();
610
+ }
611
+ if (Marshal.GetLastWin32Error() != 234) throw new InvalidOperationException("job process list unread: " + Marshal.GetLastWin32Error());
612
+ } finally { Marshal.FreeHGlobal(buffer); }
613
+ }
614
+ }
615
+ static IntPtr JobOf(string name) {
616
+ IntPtr job;
617
+ if (jobs.TryGetValue(name, out job)) return job;
618
+ job = CreateJobObjectW(IntPtr.Zero, "Local\\\\FleetViewLane-" + name);
619
+ if (job == IntPtr.Zero) throw new InvalidOperationException("job " + name + " not created: " + Marshal.GetLastWin32Error());
620
+ jobs[name] = job;
621
+ return job;
622
+ }
623
+ public static string Lanes(string request) {
624
+ var rows = new StringBuilder();
625
+ var asked = new HashSet<string>();
626
+ foreach (var lane in request.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) {
627
+ int eq = lane.IndexOf('=');
628
+ string name = eq == -1 ? lane : lane.Substring(0, eq);
629
+ asked.Add(name);
630
+ try {
631
+ IntPtr job = JobOf(name);
632
+ long jump = 0;
633
+ var refused = new StringBuilder();
634
+ var assigned = new StringBuilder();
635
+ foreach (var who in eq == -1 ? new string[0] : lane.Substring(eq + 1).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)) {
636
+ int at = who.IndexOf('@');
637
+ uint pid = uint.Parse(who.Substring(0, at));
638
+ long start = long.Parse(who.Substring(at + 1));
639
+ IntPtr handle = OpenProcess(0x1000 | 0x0100 | 0x0001, false, pid);
640
+ if (handle == IntPtr.Zero) { refused.Append(refused.Length == 0 ? "" : ",").Append(pid).Append(":gone"); continue; }
641
+ try {
642
+ long created, exited, kernel, user;
643
+ bool inside;
644
+ if (!GetProcessTimes(handle, out created, out exited, out kernel, out user) || (created - 116444736000000000L) / 10000 != start) { refused.Append(refused.Length == 0 ? "" : ",").Append(pid).Append(":reused"); continue; }
645
+ if (IsProcessInJob(handle, job, out inside) && inside) continue;
646
+ uint total, active;
647
+ long before = JobTicks(job, out total, out active);
648
+ if (!AssignProcessToJobObject(job, handle)) { refused.Append(refused.Length == 0 ? "" : ",").Append(pid).Append(':').Append(Marshal.GetLastWin32Error()); continue; }
649
+ jump += JobTicks(job, out total, out active) - before;
650
+ assigned.Append(assigned.Length == 0 ? "" : ",").Append(pid);
651
+ } finally { CloseHandle(handle); }
652
+ }
653
+ uint processes, live;
654
+ long ticks = JobTicks(job, out processes, out live);
655
+ rows.Append(name).Append('\\t').Append(ticks).Append('\\t').Append(jump).Append('\\t').Append(processes).Append('\\t').Append(live).Append('\\t').Append(JobPids(job)).Append('\\t').Append(assigned.ToString()).Append('\\t').Append(refused.ToString()).Append('\\n');
656
+ } catch (InvalidOperationException e) {
657
+ rows.Append(name).Append("\\tunread\\t").Append(e.GetType().Name).Append(": ").Append(e.Message.Replace("\\t", " ").Replace("\\r", " ").Replace("\\n", " ")).Append('\\n');
658
+ }
659
+ }
660
+ foreach (var name in new List<string>(jobs.Keys)) {
661
+ if (!asked.Contains(name)) { CloseHandle(jobs[name]); jobs.Remove(name); }
662
+ }
663
+ return rows.ToString();
664
+ }
543
665
  }
544
666
  '@
545
667
  [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
546
668
  while ($null -ne ($request = [Console]::In.ReadLine())) {
547
669
  if ($request.StartsWith('ports ')) { [Console]::Out.Write([AgentSessionProcessTable]::Listeners($request.Substring(6))) }
670
+ elseif ($request.StartsWith('lanes ')) { [Console]::Out.Write([AgentSessionProcessTable]::Lanes($request.Substring(6))) }
548
671
  else { [Console]::Out.Write([AgentSessionProcessTable]::Table()) }
549
672
  [Console]::Out.Write("${TABLE_END}\`n")
550
673
  [Console]::Out.Flush()
@@ -654,11 +777,28 @@ class TableReader {
654
777
  child.kill();
655
778
  }
656
779
  }
780
+ /** #3934 — whether this OS lets FleetView count the CPU of a process that ended between two readings: Windows, through each lane's kernel job; elsewhere a process is counted only while a reading sees it. */
781
+ export const ACCOUNTS_ENDED_PROCESSES = process.platform === "win32";
782
+ /** #3934 — one lane's kernel job could not be read or joined: the lane, and the OS's own words. */
783
+ export class LaneJobUnreadable extends Error {
784
+ lane;
785
+ why;
786
+ constructor(lane, why) {
787
+ super(`the kernel job of lane ${lane} could not be read — ${why}`);
788
+ this.lane = lane;
789
+ this.why = why;
790
+ this.name = "LaneJobUnreadable";
791
+ }
792
+ }
793
+ /** The job name a lane is known by in every window — its id with every character the request line uses taken out. */
794
+ export function laneJobName(lane) {
795
+ return lane.replace(/[^\w-]/g, "_");
796
+ }
657
797
  export class ProcessTable {
658
798
  windows;
659
799
  msys;
660
800
  constructor(gitBash) {
661
- this.windows = new TableReader(() => ({ file: "powershell", args: ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(WINDOWS_TABLE_SCRIPT, "utf16le").toString("base64")] }));
801
+ this.windows = new TableReader(() => ({ file: "powershell", args: ["-NoProfile", "-NonInteractive", "-Command", "Invoke-Expression $env:AGENT_SESSION_WINDOWS_TABLE"], env: { ...process.env, AGENT_SESSION_WINDOWS_TABLE: WINDOWS_TABLE_SCRIPT } }));
662
802
  this.msys = new TableReader(() => ({ file: gitBash(), args: ["-c", 'eval "$AGENT_SESSION_MSYS_TABLE"'], env: { ...process.env, AGENT_SESSION_MSYS_TABLE: MSYS_TABLE_SCRIPT } }));
663
803
  }
664
804
  dispose() {
@@ -672,7 +812,91 @@ export class ProcessTable {
672
812
  return joinMsysParents(parseWindows(windows), parseMsysTable(msys));
673
813
  }
674
814
  const read = await run("ps", ["-eo", "pid=,ppid=,time=,rss=,etime=,args="]);
675
- return read.ok ? parsePosix(read.out, Date.now()) : throwProcessRead();
815
+ return read.ok ? this.posixTags(parsePosix(read.out, Date.now())) : throwProcessRead();
816
+ }
817
+ posixTagCache = new Map();
818
+ /**
819
+ * 🔴 #3934 — THE LANE TAG ON LINUX AND macOS, as the Windows reader reads it off each process's environment: Linux from
820
+ * `/proc/<pid>/environ`, macOS from `ps -E`, each process read once per start. A process whose environment this user may
821
+ * not read carries no tag — it is never one of this user's lanes' calls. On macOS only a process `ps -E` listed is kept: one
822
+ * it did not list has ended since the table, and is read again while it is still in one; a `ps -E` that listed none is
823
+ * {@link ProcessTableUnreadable}.
824
+ */
825
+ async posixTags(rows) {
826
+ const fresh = rows.filter((p) => !this.posixTagCache.has(processIdentity(p)));
827
+ if (process.platform === "darwin" && fresh.length > 0) {
828
+ const read = await run("ps", ["-E", "-ww", "-o", "pid=", "-o", "command=", "-p", fresh.map((p) => p.pid).join(",")]);
829
+ const listed = new Map();
830
+ for (const line of read.out.split(/\r?\n/)) {
831
+ const row = /^\s*(\d+)\s(.*)$/.exec(line);
832
+ if (row !== null) {
833
+ listed.set(Number(row[1]), /(?:^|\s)BULLSEYE_LANE=([A-Za-z0-9_:.-]+)(?:\s|$)/.exec(row[2])?.[1] ?? "");
834
+ }
835
+ }
836
+ if (!read.ok && listed.size === 0) {
837
+ throw new ProcessTableUnreadable(`the environments of ${fresh.length} processes could not be read (ps -E listed none)`);
838
+ }
839
+ for (const p of fresh) {
840
+ const tag = listed.get(p.pid);
841
+ // NULL-OK: field tag is OPTIONAL and therefore it is ok to check for NULL
842
+ if (tag !== undefined) {
843
+ this.posixTagCache.set(processIdentity(p), tag);
844
+ }
845
+ }
846
+ }
847
+ else {
848
+ fresh.forEach((p) => this.posixTagCache.set(processIdentity(p), environTag(p.pid)));
849
+ }
850
+ const kept = new Map(rows.flatMap((p) => {
851
+ const tag = this.posixTagCache.get(processIdentity(p));
852
+ // NULL-OK: field tag is OPTIONAL and therefore it is ok to check for NULL
853
+ return tag === undefined ? [] : [[processIdentity(p), tag]];
854
+ }));
855
+ this.posixTagCache = kept;
856
+ return rows.map((p) => {
857
+ const tag = kept.get(processIdentity(p));
858
+ // NULL-OK: field tag is OPTIONAL and therefore it is ok to check for NULL
859
+ return tag === undefined || tag === "" ? p : { ...p, lane: tag };
860
+ });
861
+ }
862
+ /**
863
+ * 🔴 #3934 — EACH LANE'S KERNEL JOB, Windows only ({@link ACCOUNTS_ENDED_PROCESSES}). Every process handed in is put in its
864
+ * lane's named job (`Local\FleetViewLane-<lane>`, shared by every window) unless it is there already, and from then on the
865
+ * kernel itself counts the CPU of everything it starts — a child that starts and ends between two readings, and a detached
866
+ * one, included — and keeps the time of every process that has ended. A process is matched by pid AND start, so a reused
867
+ * pid is refused, never put in. A lane absent from the request has its handle let go; its job lives on while its processes do.
868
+ */
869
+ async laneJobs(lanes) {
870
+ if (!ACCOUNTS_ENDED_PROCESSES) {
871
+ throw new Error(`laneJobs is the Windows job reading and was asked on ${process.platform}`);
872
+ }
873
+ const request = [...lanes].map(([lane, procs]) => `${laneJobName(lane)}=${procs.map((p) => `${p.pid}@${p.startedAt}`).join(",")}`).join(";");
874
+ const byName = new Map([...lanes.keys()].map((lane) => [laneJobName(lane), lane]));
875
+ const out = new Map();
876
+ for (const line of (await this.windows.read(`lanes ${request}`)).split(/\r?\n/)) {
877
+ const cells = line.split("\t");
878
+ const lane = byName.get(cells[0]);
879
+ // NULL-OK: field lane is OPTIONAL and therefore it is ok to check for NULL
880
+ if (lane !== undefined && cells[1] === "unread") {
881
+ throw new LaneJobUnreadable(lane, cells.slice(2).join(" "));
882
+ }
883
+ if (cells.length !== 8 || lane === undefined || !/^\d+$/.test(cells[1]) || !/^\d+$/.test(cells[2])) {
884
+ continue;
885
+ }
886
+ out.set(lane, {
887
+ cpuMs: Number(BigInt(cells[1]) / 10000n),
888
+ jumpMs: Number(BigInt(cells[2]) / 10000n),
889
+ processes: Number(cells[3]),
890
+ live: Number(cells[4]),
891
+ pids: cells[5] === "" ? [] : cells[5].split(",").map(Number),
892
+ assigned: cells[6] === "" ? [] : cells[6].split(",").map(Number),
893
+ refused: cells[7] === "" ? [] : cells[7].split(","),
894
+ });
895
+ }
896
+ if (out.size !== lanes.size) {
897
+ throw new ProcessTableUnreadable(`the lane jobs were read for ${out.size} of ${lanes.size} lanes`);
898
+ }
899
+ return out;
676
900
  }
677
901
  async listeners(ports) {
678
902
  if (process.platform === "win32") {
@@ -684,17 +908,37 @@ export class ProcessTable {
684
908
  }
685
909
  /** FILETIME ticks (100 ns since 1601-01-01 UTC) between that epoch and 1970's. */
686
910
  const FILETIME_UNIX_EPOCH = 116444736000000000n;
911
+ /** #3934 — what a `BULLSEYE_LANE` tag may hold; a process carrying none, or anything else, is listed with no lane. */
912
+ const LANE_TAG = /^[A-Za-z0-9_:.-]+$/;
913
+ /** #3934 — the lane tag in a Linux process's `/proc/<pid>/environ`; none for a process that carries none or whose environment this user may not read. */
914
+ function environTag(pid) {
915
+ let env;
916
+ try {
917
+ env = fs.readFileSync(`/proc/${pid}/environ`, "latin1");
918
+ }
919
+ catch (err) {
920
+ const code = err.code;
921
+ if (code !== "ENOENT" && code !== "EACCES" && code !== "ESRCH" && code !== "EPERM") {
922
+ throw err;
923
+ }
924
+ return "";
925
+ }
926
+ const tag = env.split("\0").find((v) => v.startsWith("BULLSEYE_LANE="));
927
+ // NULL-OK: field tag is OPTIONAL and therefore it is ok to check for NULL
928
+ const value = tag === undefined ? "" : tag.slice("BULLSEYE_LANE=".length);
929
+ return LANE_TAG.test(value) ? value : "";
930
+ }
687
931
  /**
688
- * One row per line — pid, ppid, CPU (100 ns ticks), working set (bytes), creation (FILETIME), then the command line —
689
- * split on the FIRST five tabs so a tab inside the command survives. A line that is not that shape is skipped, never
690
- * invented into a row.
932
+ * One row per line — pid, ppid, CPU (100 ns ticks), working set (bytes), creation (FILETIME), the lane tag its environment
933
+ * carries (#3934, empty for none), then the command line — split on the FIRST six tabs so a tab inside the command survives.
934
+ * A line that is not that shape is skipped, never invented into a row.
691
935
  */
692
936
  export function parseWindows(out) {
693
937
  const rows = [];
694
938
  for (const line of out.split(/\r?\n/)) {
695
939
  const cells = [];
696
940
  let from = 0;
697
- for (let i = 0; i < 5; i++) {
941
+ for (let i = 0; i < 6; i++) {
698
942
  const tab = line.indexOf("\t", from);
699
943
  if (tab === -1) {
700
944
  break;
@@ -702,7 +946,7 @@ export function parseWindows(out) {
702
946
  cells.push(line.slice(from, tab));
703
947
  from = tab + 1;
704
948
  }
705
- if (cells.length < 5 || !cells.every((c) => /^\d+$/.test(c))) {
949
+ if (cells.length < 6 || !cells.slice(0, 5).every((c) => /^\d+$/.test(c))) {
706
950
  continue;
707
951
  }
708
952
  const created = BigInt(cells[4]);
@@ -712,6 +956,7 @@ export function parseWindows(out) {
712
956
  cpuMs: Number(BigInt(cells[2]) / 10000n),
713
957
  memBytes: Number(cells[3]),
714
958
  startedAt: created === 0n ? 0 : Number((created - FILETIME_UNIX_EPOCH) / 10000n),
959
+ ...(LANE_TAG.test(cells[5]) ? { lane: cells[5] } : {}),
715
960
  cmd: line.slice(from),
716
961
  });
717
962
  }
@@ -1136,8 +1381,8 @@ function opencodeToolActivity(tool) {
1136
1381
  return "using a tool";
1137
1382
  }
1138
1383
  // GATE: the HTTP statuses on which the provider refused THIS key (unauthorized, payment, forbidden, rate-limited) — the turn moves to the next key; any other failure is the turn's own and moves nothing
1139
- const KEY_REFUSAL_STATUSES = new Set([401, 402, 403, 429]);
1140
- const KEY_REFUSAL_WORDS = /credit balance is too low|insufficient (?:balance|funds|credit|quota)|out of (?:funds|credit)|invalid x-api-key/i;
1384
+ export const KEY_REFUSAL_STATUSES = new Set([401, 402, 403, 429]);
1385
+ export const KEY_REFUSAL_WORDS = /credit balance is too low|insufficient (?:balance|funds|credit|quota)|out of (?:funds|credit)|invalid x-api-key/i;
1141
1386
  // GATE: OpenCode's own log line for a call of the turn's main agent that the provider rate-limited — the CLI then retries it in silence for as long as the provider's retry-after says, so the turn ends this attempt and moves to the next key
1142
1387
  const RETRIED_RATE_LIMIT = /level=ERROR .*message="stream error" .*session\.id=(ses_[A-Za-z0-9]+) .*small=false .*mode=primary .*error\.error="(?:AI_APICallError: )?([^"]*(?:rate.?limit|too many requests)[^"]*)"/i;
1143
1388
  const KEY_RETRY_PROMPT = "The provider refused the key your last reply was being written on, so that reply never arrived. Carry on from the last message.";