@50arms/platform-mcp 0.1.453 → 0.1.456
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/leftover-wire.js +30 -0
- package/dist/listen.js +18 -0
- package/dist/machine-daemon/beat.js +1 -0
- package/dist/machine-daemon/leftovers.js +311 -0
- package/dist/machine-daemon.js +392 -35
- package/dist/machine-toolkit.js +7 -5
- package/dist/route-board-scope.generated.js +1 -0
- package/dist/urgent-records.js +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DX-7107 - the leftover-process wire shape, declared once: the machine daemon (`machine-daemon/leftovers.ts`) builds it, `POST /api/machines/report` reads it (`readLeftoverProcess`), and the dashboard turns it into the
|
|
3
|
+
* reminder a session's stream writes (`src/issues/leftover-processes-message.ts`).
|
|
4
|
+
*/
|
|
5
|
+
/** The daemon cuts a command line here, so the dashboard and the daemon agree on one length. */
|
|
6
|
+
export const LEFTOVER_COMMAND_MAX_CHARS = 140;
|
|
7
|
+
/**
|
|
8
|
+
* Why the watchdog flagged a process: `follow` a `tail -f` or line-buffered filter that has run long, `reader_gone` one whose launching shell has exited (its pipe's far end is gone), `cpu` a session's process that held a core for hours.
|
|
9
|
+
*/
|
|
10
|
+
export const LEFTOVER_WHY = ["follow", "reader_gone", "cpu"];
|
|
11
|
+
function isObject(v) {
|
|
12
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
13
|
+
}
|
|
14
|
+
/** Reads one reported process; `null` when it is not the shape above. */
|
|
15
|
+
export function readLeftoverProcess(v) {
|
|
16
|
+
if (!isObject(v))
|
|
17
|
+
return null;
|
|
18
|
+
const { pid, command, age_seconds, cpu_percent, why } = v;
|
|
19
|
+
if (!Number.isSafeInteger(pid) || pid <= 0)
|
|
20
|
+
return null;
|
|
21
|
+
if (typeof command !== "string" || command.trim() === "" || command.length > LEFTOVER_COMMAND_MAX_CHARS + 3)
|
|
22
|
+
return null;
|
|
23
|
+
if (typeof age_seconds !== "number" || !Number.isFinite(age_seconds) || age_seconds < 0)
|
|
24
|
+
return null;
|
|
25
|
+
if (cpu_percent !== null && (typeof cpu_percent !== "number" || !Number.isFinite(cpu_percent) || cpu_percent < 0))
|
|
26
|
+
return null;
|
|
27
|
+
if (!LEFTOVER_WHY.includes(why))
|
|
28
|
+
return null;
|
|
29
|
+
return { pid: pid, command, age_seconds, cpu_percent: cpu_percent, why: why };
|
|
30
|
+
}
|
package/dist/listen.js
CHANGED
|
@@ -544,6 +544,21 @@ export function formatAssignmentLine(event) {
|
|
|
544
544
|
throw new Error(`malformed assignment message: ${invalid}`);
|
|
545
545
|
return pacingRelayLine(event.text);
|
|
546
546
|
}
|
|
547
|
+
/** Why a leftover-processes message cannot be read, or `null` when it can. */
|
|
548
|
+
export function invalidLeftoverProcessesReason(value) {
|
|
549
|
+
if (!isRecord(value))
|
|
550
|
+
return "the leftover-processes message is not an object";
|
|
551
|
+
if (typeof value.text !== "string" || value.text.trim() === "")
|
|
552
|
+
return "text is empty";
|
|
553
|
+
return null;
|
|
554
|
+
}
|
|
555
|
+
/** The one readable line for a leftover-processes message: the dashboard's text, on one line, cut like a pacing line. Throws, naming the fault, on a malformed message. */
|
|
556
|
+
export function formatLeftoverProcessesLine(event) {
|
|
557
|
+
const invalid = invalidLeftoverProcessesReason(event);
|
|
558
|
+
if (invalid !== null)
|
|
559
|
+
throw new Error(`malformed leftover-processes message: ${invalid}`);
|
|
560
|
+
return pacingRelayLine(event.text);
|
|
561
|
+
}
|
|
547
562
|
/** Why an owed-comment message cannot be read, or `null` when it can. */
|
|
548
563
|
export function invalidOwedCommentReason(value) {
|
|
549
564
|
if (!isRecord(value))
|
|
@@ -832,6 +847,9 @@ export async function runListener(options, deps) {
|
|
|
832
847
|
// DX-6866 - a docs draft owed on this session's plan: the same one-line frame.
|
|
833
848
|
if (message.event === "docs_draft")
|
|
834
849
|
return emitAdvisory(message, "docs draft message", invalidAssignmentReason, (p) => formatAssignmentLine(p), () => ({ source: "docs_draft" }));
|
|
850
|
+
// DX-7107 - processes this session started and left running: a reminder, non-urgent and session-scoped like an owed comment.
|
|
851
|
+
if (message.event === "leftover_processes")
|
|
852
|
+
return emitAdvisory(message, "leftover-processes message", invalidLeftoverProcessesReason, (p) => formatLeftoverProcessesLine(p), () => ({ source: "leftover_processes" }), "session");
|
|
835
853
|
if (message.event === "assignment")
|
|
836
854
|
return emitAdvisory(message, "assignment message", invalidAssignmentReason, (p) => formatAssignmentLine(p), () => ({ source: "assignment" }), "session");
|
|
837
855
|
// DX-4993 - the compaction control: level-triggered, no id, no replay. A frame that cannot be read is a fault line (never silence), and the next frame still lands.
|
|
@@ -69,6 +69,7 @@ export async function runBeatLoop(deps) {
|
|
|
69
69
|
}
|
|
70
70
|
if (deps.reporter.refused())
|
|
71
71
|
return stopOnRefusal(deps);
|
|
72
|
+
void deps.reporter.sample(beatAt);
|
|
72
73
|
deps.reporter.tick(beatAt);
|
|
73
74
|
if (deps.maxTicks !== undefined && ticks >= deps.maxTicks)
|
|
74
75
|
return { reason: "ticks-exhausted" };
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DX-7107 (DEC-735, DX-6868 note 49450 sections 3F, 3G, 3I) - the leftover-process watchdog. Agent sessions leave processes behind that outlive the work that started them: a `tail -f LOG | grep` pipeline
|
|
3
|
+
* (a Bash call ends its own shell and never the follower), a background task burning a core for a day. The watchdog REMINDS the session that owns such a process and never ends anything: the process
|
|
4
|
+
* may still be doing useful work.
|
|
5
|
+
*
|
|
6
|
+
* WHAT LOOKS LEFTOVER (Windows processes; the WSL side has no Windows parent chain, is not listed here, and its orphans are the health report's `reportOrphanProcesses`):
|
|
7
|
+
* reader_gone - a `tail -f` / `-F` / `--follow`, or a `--line-buffered` filter (`grep`, `sed`, `awk`), whose launching shell has exited ({@link READER_GONE_MIN_AGE_MS} ago at least): a follower never ends by itself, so a
|
|
8
|
+
* pipeline whose Bash call ended is both rows. The ledger knows the shell from the first sample that saw the process.
|
|
9
|
+
* follow - the same kinds of process running longer than {@link FOLLOW_MIN_AGE_MS} with a shell still around or none ever found.
|
|
10
|
+
* cpu - a process of a session that held at least {@link HOT_CPU_FRACTION} of one core for at least {@link HOT_MIN_MS} without a cool minute (below {@link COOL_CPU_FRACTION}).
|
|
11
|
+
* "No recent output to the session" cannot be observed from a process listing and is not checked.
|
|
12
|
+
*
|
|
13
|
+
* WHO OWNS IT, in this order (measured 2026-11-10, DX-7107 note): (1) the parent chain up to a `claude.exe` whose `~/.claude/sessions/<pid>.json` names a session. A Git-for-Windows (MSYS) process shows a
|
|
14
|
+
* dead Windows parent even while its shell lives, so its link is MSYS's own parent id, read from Git's `ps -W` (`msysParents`); (2) the ledger, which remembers the owner found while the chain was live, because
|
|
15
|
+
* the process outlives its shell and then no chain reaches `claude.exe` any more; (3) for a hot process nobody owns, its own environment (`CLAUDE_CODE_SESSION_ID`, read from the process block): present for python and node, ABSENT for MSYS `tail.exe` / `grep.exe`. A follower no chain and no ledger entry names is OWNERLESS, and so is
|
|
16
|
+
* a process whose session has ended or that the dashboard cannot reach: those go to a person in the health report's orphan list, never to a session.
|
|
17
|
+
*
|
|
18
|
+
* The ledger holds every Windows process of the table (a few hundred rows): a hot process nobody owns is told from one that is busy for its own reasons only by watching it, and a process with no row has no history.
|
|
19
|
+
*
|
|
20
|
+
* Each process is reminded at most once per {@link REMIND_INTERVAL_MS}, counted from a 200 answer that names its session delivered.
|
|
21
|
+
*/
|
|
22
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
import { LEFTOVER_COMMAND_MAX_CHARS } from "../leftover-wire.js";
|
|
26
|
+
import { listProcesses, runCommand } from "../machine-toolkit/processes.js";
|
|
27
|
+
export const FOLLOW_MIN_AGE_MS = 30 * 60 * 1000;
|
|
28
|
+
export const HOT_CPU_FRACTION = 0.5;
|
|
29
|
+
export const COOL_CPU_FRACTION = 0.2;
|
|
30
|
+
export const HOT_MIN_MS = 3 * 60 * 60 * 1000;
|
|
31
|
+
export const REMIND_INTERVAL_MS = 6 * 60 * 60 * 1000;
|
|
32
|
+
/** A follower whose shell has gone is flagged after this short grace: a shell and its last child exit within moments of each other. */
|
|
33
|
+
export const READER_GONE_MIN_AGE_MS = 2 * 60 * 1000;
|
|
34
|
+
/** A failed environment read is not tried again for this long. */
|
|
35
|
+
export const ENV_RETRY_BACKOFF_MS = 30 * 60 * 1000;
|
|
36
|
+
const MAX_CHAIN_HOPS = 32;
|
|
37
|
+
const ENV_READ_TIMEOUT_MS = 20_000;
|
|
38
|
+
const PS_TIMEOUT_MS = 20_000;
|
|
39
|
+
const keyOf = (pid, startedAtMs) => `${pid}:${startedAtMs}`;
|
|
40
|
+
/** A FILETIME (100 ns since 1601) as epoch milliseconds. */
|
|
41
|
+
export function fileTimeToMs(fileTime) {
|
|
42
|
+
return Number(BigInt(fileTime) / 10000n) - 11_644_473_600_000;
|
|
43
|
+
}
|
|
44
|
+
/** The sessions Claude Code recorded, by their `claude.exe` pid: `~/.claude/sessions/<pid>.json` holds the pid, the session id and the process start (`procStart`, a FILETIME). Unreadable files are skipped: a half-written one is rewritten whole. */
|
|
45
|
+
export function readClaudeSessionFiles(dir = join(homedir(), ".claude", "sessions")) {
|
|
46
|
+
const sessions = new Map();
|
|
47
|
+
if (!existsSync(dir))
|
|
48
|
+
return sessions;
|
|
49
|
+
for (const file of readdirSync(dir)) {
|
|
50
|
+
if (!/^\d+\.json$/.test(file))
|
|
51
|
+
continue;
|
|
52
|
+
try {
|
|
53
|
+
const v = JSON.parse(readFileSync(join(dir, file), "utf8"));
|
|
54
|
+
if (typeof v.pid === "number" && typeof v.sessionId === "string" && typeof v.procStart === "string")
|
|
55
|
+
sessions.set(v.pid, { sessionId: v.sessionId, startedAtMs: fileTimeToMs(v.procStart) });
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return sessions;
|
|
62
|
+
}
|
|
63
|
+
const FOLLOW_ARG = /(?:^|\s)(?:-[a-zA-Z]*[fF][a-zA-Z]*|--follow(?:=\S+)?)(?=\s|$)/;
|
|
64
|
+
const FILTER_NAMES = new Set(["grep.exe", "egrep.exe", "fgrep.exe", "sed.exe", "awk.exe", "gawk.exe"]);
|
|
65
|
+
/** Whether the row is a follower (`tail -f`) or the line-buffered reader of one's pipe. */
|
|
66
|
+
export function isFollowRow(row) {
|
|
67
|
+
const name = row.name.toLowerCase();
|
|
68
|
+
if (name === "tail.exe")
|
|
69
|
+
return FOLLOW_ARG.test(row.commandLine.replace(/^"[^"]*"|^\S+/, ""));
|
|
70
|
+
return FILTER_NAMES.has(name) && /(?:^|\s)--line-buffered(?=\s|$)/.test(row.commandLine);
|
|
71
|
+
}
|
|
72
|
+
function shortCommand(commandLine) {
|
|
73
|
+
const flat = commandLine.replace(/\s+/g, " ").trim();
|
|
74
|
+
return flat.length > LEFTOVER_COMMAND_MAX_CHARS ? `${flat.slice(0, LEFTOVER_COMMAND_MAX_CHARS)}...` : flat;
|
|
75
|
+
}
|
|
76
|
+
/** The session id in each of `pids`' environments (null: the variable is absent). Windows only: the block is read through `NtQueryInformationProcess` and `ReadProcessMemory`, same user, no elevation. */
|
|
77
|
+
export const ENV_READ_SCRIPT = (pids) => `
|
|
78
|
+
$ErrorActionPreference = 'Stop'
|
|
79
|
+
Add-Type -TypeDefinition @'
|
|
80
|
+
using System; using System.Runtime.InteropServices; using System.Text;
|
|
81
|
+
public static class PEnv {
|
|
82
|
+
[DllImport("ntdll.dll")] static extern int NtQueryInformationProcess(IntPtr h, int cls, ref PBI pbi, int len, out int ret);
|
|
83
|
+
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(int acc, bool inh, int pid);
|
|
84
|
+
[DllImport("kernel32.dll")] static extern bool ReadProcessMemory(IntPtr h, IntPtr addr, byte[] buf, int size, out int read);
|
|
85
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
|
|
86
|
+
[StructLayout(LayoutKind.Sequential)] struct PBI { public IntPtr Exit, Peb, Aff, Prio, Pid, Parent; }
|
|
87
|
+
static IntPtr Ptr(IntPtr h, IntPtr a) { var b = new byte[8]; int r; ReadProcessMemory(h, a, b, 8, out r); return (IntPtr)BitConverter.ToInt64(b, 0); }
|
|
88
|
+
public static string Env(int pid) {
|
|
89
|
+
IntPtr h = OpenProcess(0x1010, false, pid); if (h == IntPtr.Zero) return "";
|
|
90
|
+
try {
|
|
91
|
+
var pbi = new PBI(); int ret; if (NtQueryInformationProcess(h, 0, ref pbi, Marshal.SizeOf(pbi), out ret) != 0) return "";
|
|
92
|
+
IntPtr pp = Ptr(h, IntPtr.Add(pbi.Peb, 0x20)); IntPtr env = Ptr(h, IntPtr.Add(pp, 0x80));
|
|
93
|
+
var buf = new byte[1 << 20]; int rd; ReadProcessMemory(h, env, buf, buf.Length, out rd);
|
|
94
|
+
return Encoding.Unicode.GetString(buf, 0, rd);
|
|
95
|
+
} finally { CloseHandle(h); }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
'@
|
|
99
|
+
foreach ($id in @(${pids.join(",")})) {
|
|
100
|
+
$hit = ([PEnv]::Env([int]$id)).Split([char]0) | Where-Object { $_ -like 'CLAUDE_CODE_SESSION_ID=*' } | Select-Object -First 1
|
|
101
|
+
if ($hit) { "$id=" + $hit.Substring(24) }
|
|
102
|
+
}
|
|
103
|
+
`;
|
|
104
|
+
const SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
105
|
+
/** Reads `CLAUDE_CODE_SESSION_ID` out of each process's environment; a pid that answers nothing is absent from the map. `run` is the same injectable command runner the listings use (windowsHide set there). */
|
|
106
|
+
export async function readSessionsFromEnvironment(pids, run = runCommand) {
|
|
107
|
+
const found = new Map();
|
|
108
|
+
if (pids.length === 0)
|
|
109
|
+
return found;
|
|
110
|
+
const stdout = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ENV_READ_SCRIPT(pids)], ENV_READ_TIMEOUT_MS);
|
|
111
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
112
|
+
const m = /^(\d+)=(\S+)$/.exec(line.trim());
|
|
113
|
+
if (m && SESSION_ID_RE.test(m[2]))
|
|
114
|
+
found.set(Number(m[1]), m[2]);
|
|
115
|
+
}
|
|
116
|
+
return found;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Git's `ps.exe`, found beside a running MSYS program (`...\usr\bin\tail.exe`) in the process table itself, so wherever Git is installed. No MSYS process running means no process to link and no `ps.exe` is needed: `null`.
|
|
120
|
+
*/
|
|
121
|
+
export function gitPsPathFrom(rows, exists = existsSync) {
|
|
122
|
+
for (const row of rows) {
|
|
123
|
+
const m = /^(.*\\usr\\bin)\\[^\\]+\.exe$/i.exec(row.executablePath);
|
|
124
|
+
if (m !== null && exists(`${m[1]}\\ps.exe`))
|
|
125
|
+
return `${m[1]}\\ps.exe`;
|
|
126
|
+
}
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Windows pid -> the Windows pid of its MSYS parent, for the processes `ps -W` shows with an MSYS parent. A Windows-native process lists its own id twice and has no entry. With no MSYS program running there is nothing to link, so the map is
|
|
131
|
+
* empty without a command; any failure of the command throws, and that beat's sample is retried at the next.
|
|
132
|
+
*/
|
|
133
|
+
export async function readMsysParents(processes, run = runCommand, exists = existsSync) {
|
|
134
|
+
const psPath = gitPsPathFrom(processes, exists);
|
|
135
|
+
if (psPath === null)
|
|
136
|
+
return new Map();
|
|
137
|
+
const stdout = await run(psPath, ["-W"], PS_TIMEOUT_MS);
|
|
138
|
+
const rows = [];
|
|
139
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
140
|
+
const m = /^[\sI]*(\d+)\s+(\d+)\s+\d+\s+(\d+)\s/.exec(line);
|
|
141
|
+
if (m)
|
|
142
|
+
rows.push({ pid: Number(m[1]), ppid: Number(m[2]), winpid: Number(m[3]) });
|
|
143
|
+
}
|
|
144
|
+
const winpidOfMsysPid = new Map(rows.filter((r) => r.pid !== r.winpid).map((r) => [r.pid, r.winpid]));
|
|
145
|
+
const parents = new Map();
|
|
146
|
+
for (const r of rows) {
|
|
147
|
+
const parent = r.pid === r.winpid ? undefined : winpidOfMsysPid.get(r.ppid);
|
|
148
|
+
if (parent !== undefined)
|
|
149
|
+
parents.set(r.winpid, parent);
|
|
150
|
+
}
|
|
151
|
+
return parents;
|
|
152
|
+
}
|
|
153
|
+
export function createLeftoverTracker(deps) {
|
|
154
|
+
const ledger = new Map();
|
|
155
|
+
let live = new Map();
|
|
156
|
+
let liveSessionIds = new Set();
|
|
157
|
+
let envRetryAfterMs = 0;
|
|
158
|
+
const parentRowOf = (row, byPid, msys) => {
|
|
159
|
+
const parent = byPid.get(msys.get(row.pid) ?? row.ppid);
|
|
160
|
+
if (parent === undefined)
|
|
161
|
+
return undefined;
|
|
162
|
+
// A parent that started after its child is a later process that reused the id.
|
|
163
|
+
if (parent.startedAt !== null && row.startedAt !== null && parent.startedAt.getTime() > row.startedAt.getTime())
|
|
164
|
+
return undefined;
|
|
165
|
+
return parent;
|
|
166
|
+
};
|
|
167
|
+
const ownerByChain = (row, byPid, msys, sessions) => {
|
|
168
|
+
let child = row;
|
|
169
|
+
for (let hop = 0; hop < MAX_CHAIN_HOPS; hop++) {
|
|
170
|
+
const parent = parentRowOf(child, byPid, msys);
|
|
171
|
+
if (parent === undefined)
|
|
172
|
+
return null;
|
|
173
|
+
const session = sessions.get(parent.pid);
|
|
174
|
+
// The recorded start must match the running process: a session file left by an older `claude.exe` with the same pid names another session.
|
|
175
|
+
if (session !== undefined && parent.name.toLowerCase() === "claude.exe" && parent.startedAt !== null && Math.abs(parent.startedAt.getTime() - session.startedAtMs) < 5000)
|
|
176
|
+
return session.sessionId;
|
|
177
|
+
child = parent;
|
|
178
|
+
}
|
|
179
|
+
return null;
|
|
180
|
+
};
|
|
181
|
+
return {
|
|
182
|
+
async sample(at) {
|
|
183
|
+
const { rows, unavailable } = await deps.listing(at);
|
|
184
|
+
if (unavailable.length > 0)
|
|
185
|
+
throw new Error(`the process table is unavailable (${unavailable.map((u) => `${u.source}: ${u.reason}`).join("; ")}): the ledger is kept as it was`);
|
|
186
|
+
const windows = rows.filter((r) => r.source === "windows" && r.startedAt !== null);
|
|
187
|
+
const byPid = new Map(windows.map((r) => [r.pid, r]));
|
|
188
|
+
const sessions = deps.claudeSessions();
|
|
189
|
+
const msys = await deps.msysParents(windows);
|
|
190
|
+
liveSessionIds = new Set(windows.filter((r) => r.name.toLowerCase() === "claude.exe" && sessions.get(r.pid) !== undefined).map((r) => sessions.get(r.pid).sessionId));
|
|
191
|
+
const nowLive = new Map();
|
|
192
|
+
const nowMs = at.getTime();
|
|
193
|
+
for (const row of windows) {
|
|
194
|
+
const startedAtMs = row.startedAt.getTime();
|
|
195
|
+
const key = keyOf(row.pid, startedAtMs);
|
|
196
|
+
nowLive.set(key, row);
|
|
197
|
+
let entry = ledger.get(key);
|
|
198
|
+
const owner = ownerByChain(row, byPid, msys, sessions);
|
|
199
|
+
if (entry === undefined) {
|
|
200
|
+
const shell = parentRowOf(row, byPid, msys);
|
|
201
|
+
entry = { pid: row.pid, startedAtMs, owner, envChecked: false, shellKey: shell?.startedAt ? keyOf(shell.pid, shell.startedAt.getTime()) : null, unreachable: false, lastCpu100ns: null, lastSeenMs: nowMs, hotSinceMs: null, hotCpuStart100ns: null, hotStartWallMs: null, lastCpuPercent: null, remindedAtMs: null };
|
|
202
|
+
ledger.set(key, entry);
|
|
203
|
+
}
|
|
204
|
+
else if (entry.owner === null && owner !== null) {
|
|
205
|
+
entry.owner = owner;
|
|
206
|
+
}
|
|
207
|
+
if (row.cpuTime100ns !== null && entry.lastCpu100ns !== null && nowMs > entry.lastSeenMs) {
|
|
208
|
+
const fraction = (row.cpuTime100ns - entry.lastCpu100ns) / 10000 / (nowMs - entry.lastSeenMs);
|
|
209
|
+
if (fraction >= HOT_CPU_FRACTION && entry.hotSinceMs === null) {
|
|
210
|
+
entry.hotSinceMs = entry.lastSeenMs;
|
|
211
|
+
entry.hotCpuStart100ns = entry.lastCpu100ns;
|
|
212
|
+
entry.hotStartWallMs = entry.lastSeenMs;
|
|
213
|
+
}
|
|
214
|
+
else if (fraction < COOL_CPU_FRACTION) {
|
|
215
|
+
entry.hotSinceMs = null;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (entry.hotSinceMs !== null && entry.hotCpuStart100ns !== null && entry.hotStartWallMs !== null && row.cpuTime100ns !== null && nowMs > entry.hotStartWallMs) {
|
|
219
|
+
entry.lastCpuPercent = ((row.cpuTime100ns - entry.hotCpuStart100ns) / 10000 / (nowMs - entry.hotStartWallMs)) * 100;
|
|
220
|
+
}
|
|
221
|
+
entry.lastCpu100ns = row.cpuTime100ns;
|
|
222
|
+
entry.lastSeenMs = nowMs;
|
|
223
|
+
}
|
|
224
|
+
for (const key of [...ledger.keys()])
|
|
225
|
+
if (!nowLive.has(key))
|
|
226
|
+
ledger.delete(key);
|
|
227
|
+
live = nowLive;
|
|
228
|
+
// A hot process nobody owns may still carry its session in its environment (python, node); read each once.
|
|
229
|
+
const unknown = [...ledger.entries()].filter(([, e]) => e.owner === null && !e.envChecked && e.hotSinceMs !== null && nowMs - e.hotSinceMs >= HOT_MIN_MS);
|
|
230
|
+
if (unknown.length > 0 && nowMs >= envRetryAfterMs) {
|
|
231
|
+
let fromEnv;
|
|
232
|
+
try {
|
|
233
|
+
fromEnv = await deps.sessionsFromEnvironment(unknown.map(([, e]) => e.pid));
|
|
234
|
+
}
|
|
235
|
+
catch (err) {
|
|
236
|
+
// Fails loud once, then waits: the read is a powershell start, and a broken one would be re-run every beat.
|
|
237
|
+
envRetryAfterMs = nowMs + ENV_RETRY_BACKOFF_MS;
|
|
238
|
+
throw err;
|
|
239
|
+
}
|
|
240
|
+
for (const [, e] of unknown) {
|
|
241
|
+
e.envChecked = true;
|
|
242
|
+
e.owner = fromEnv.get(e.pid) ?? null;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
collect(at) {
|
|
247
|
+
const nowMs = at.getTime();
|
|
248
|
+
const sessions = new Map();
|
|
249
|
+
const reminded = new Map();
|
|
250
|
+
const ownerless = [];
|
|
251
|
+
for (const [key, entry] of ledger) {
|
|
252
|
+
const row = live.get(key);
|
|
253
|
+
if (row === undefined)
|
|
254
|
+
continue;
|
|
255
|
+
const ageMs = nowMs - entry.startedAtMs;
|
|
256
|
+
const follower = isFollowRow(row);
|
|
257
|
+
const readerGone = follower && entry.shellKey !== null && !live.has(entry.shellKey) && ageMs >= READER_GONE_MIN_AGE_MS;
|
|
258
|
+
const follow = follower && ageMs >= FOLLOW_MIN_AGE_MS;
|
|
259
|
+
const hot = entry.owner !== null && entry.hotSinceMs !== null && nowMs - entry.hotSinceMs >= HOT_MIN_MS;
|
|
260
|
+
if (!readerGone && !follow && !hot)
|
|
261
|
+
continue;
|
|
262
|
+
const process = {
|
|
263
|
+
pid: entry.pid,
|
|
264
|
+
command: shortCommand(row.commandLine),
|
|
265
|
+
age_seconds: Math.floor(ageMs / 1000),
|
|
266
|
+
cpu_percent: hot && entry.lastCpuPercent !== null ? Math.round(entry.lastCpuPercent) : null,
|
|
267
|
+
why: readerGone ? "reader_gone" : follow ? "follow" : "cpu",
|
|
268
|
+
};
|
|
269
|
+
if (entry.owner === null) {
|
|
270
|
+
ownerless.push({ ...process, reason: "no session found" });
|
|
271
|
+
}
|
|
272
|
+
else if (!liveSessionIds.has(entry.owner)) {
|
|
273
|
+
ownerless.push({ ...process, reason: "session ended" });
|
|
274
|
+
}
|
|
275
|
+
else {
|
|
276
|
+
if (entry.unreachable)
|
|
277
|
+
ownerless.push({ ...process, reason: "session not on this dashboard" });
|
|
278
|
+
if (entry.remindedAtMs === null || nowMs - entry.remindedAtMs >= REMIND_INTERVAL_MS) {
|
|
279
|
+
sessions.set(entry.owner, [...(sessions.get(entry.owner) ?? []), process]);
|
|
280
|
+
reminded.set(entry.owner, [...(reminded.get(entry.owner) ?? []), key]);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
return { sessions: [...sessions].map(([session_id, processes]) => ({ session_id, processes })), ownerless, reminded };
|
|
285
|
+
},
|
|
286
|
+
settle(collection, undelivered, at) {
|
|
287
|
+
for (const [sessionId, keys] of collection.reminded) {
|
|
288
|
+
for (const key of keys) {
|
|
289
|
+
const entry = ledger.get(key);
|
|
290
|
+
if (entry === undefined)
|
|
291
|
+
continue;
|
|
292
|
+
// An undelivered session is told to a person and asked again at the next report; the mark clears when the dashboard takes the reminder.
|
|
293
|
+
entry.unreachable = undelivered.includes(sessionId);
|
|
294
|
+
if (!entry.unreachable)
|
|
295
|
+
entry.remindedAtMs = at.getTime();
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
},
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
/** The real tracker: the Windows process table (no WSL listing: its rows could not be mapped to a session), Git's `ps -W`, `~/.claude/sessions` and the environment read. The watchdog is Windows-only: on another platform nothing is ever watched. */
|
|
302
|
+
export function createSystemLeftoverTracker(run = runCommand, platform = process.platform) {
|
|
303
|
+
if (platform !== "win32")
|
|
304
|
+
return { sample: async () => { }, collect: () => ({ sessions: [], ownerless: [], reminded: new Map() }), settle: () => { } };
|
|
305
|
+
return createLeftoverTracker({
|
|
306
|
+
listing: (now) => listProcesses(now, run, platform, undefined, "never"),
|
|
307
|
+
msysParents: (rows) => readMsysParents(rows, run),
|
|
308
|
+
claudeSessions: () => readClaudeSessionFiles(),
|
|
309
|
+
sessionsFromEnvironment: (pids) => readSessionsFromEnvironment(pids, run),
|
|
310
|
+
});
|
|
311
|
+
}
|
package/dist/machine-daemon.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/machine-daemon/run.ts
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { existsSync as
|
|
4
|
-
import { homedir as
|
|
3
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
4
|
+
import { homedir as homedir3 } from "node:os";
|
|
5
5
|
|
|
6
6
|
// ../machine-vitals/src/probes.ts
|
|
7
7
|
import { statfsSync, readFileSync } from "node:fs";
|
|
@@ -204,12 +204,337 @@ async function runBeatLoop(deps) {
|
|
|
204
204
|
deps.log(`beat failed at ${beatAt.toISOString()}: ${outcome.error}; retrying on the next tick`);
|
|
205
205
|
}
|
|
206
206
|
if (deps.reporter.refused()) return stopOnRefusal(deps);
|
|
207
|
+
void deps.reporter.sample(beatAt);
|
|
207
208
|
deps.reporter.tick(beatAt);
|
|
208
209
|
if (deps.maxTicks !== void 0 && ticks >= deps.maxTicks) return { reason: "ticks-exhausted" };
|
|
209
210
|
await deps.sleep(Math.max(0, next.getTime() - deps.now().getTime()));
|
|
210
211
|
}
|
|
211
212
|
}
|
|
212
213
|
|
|
214
|
+
// src/machine-daemon/leftovers.ts
|
|
215
|
+
import { existsSync, readdirSync, readFileSync as readFileSync2 } from "node:fs";
|
|
216
|
+
import { homedir } from "node:os";
|
|
217
|
+
import { join } from "node:path";
|
|
218
|
+
|
|
219
|
+
// src/leftover-wire.ts
|
|
220
|
+
var LEFTOVER_COMMAND_MAX_CHARS = 140;
|
|
221
|
+
|
|
222
|
+
// src/machine-toolkit/processes.ts
|
|
223
|
+
import { execFile } from "node:child_process";
|
|
224
|
+
|
|
225
|
+
// src/machine-toolkit/errors.ts
|
|
226
|
+
function errorCode(err) {
|
|
227
|
+
const failure = err;
|
|
228
|
+
if (typeof failure?.code === "string" || typeof failure?.code === "number") return String(failure.code);
|
|
229
|
+
return failure?.killed === true ? "timed out" : "unexpected error";
|
|
230
|
+
}
|
|
231
|
+
function errMessage(err) {
|
|
232
|
+
return err instanceof Error ? err.message : String(err);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/machine-toolkit/processes.ts
|
|
236
|
+
var ORPHAN_MIN_AGE_MS = 10 * 60 * 1e3;
|
|
237
|
+
var PROCESS_LISTING_TIMEOUT_MS = 2e4;
|
|
238
|
+
var WSL_DISTRO = "Ubuntu";
|
|
239
|
+
var DOCKER_DESKTOP_DISTROS = /* @__PURE__ */ new Set(["docker-desktop", "docker-desktop-data"]);
|
|
240
|
+
var LISTING_MAX_BUFFER_BYTES = 64 * 1024 * 1024;
|
|
241
|
+
var WINDOWS_LISTING_SCRIPT = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; ppid = $_.ParentProcessId; started = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null }); name = $_.Name; cmd = $_.CommandLine; exe = $_.ExecutablePath; cpu = ([uint64]$_.KernelModeTime + [uint64]$_.UserModeTime) } } | ConvertTo-Json -Compress";
|
|
242
|
+
function parseWindowsListing(stdout) {
|
|
243
|
+
const parsed = JSON.parse(stdout);
|
|
244
|
+
return (Array.isArray(parsed) ? parsed : [parsed]).map((p) => ({
|
|
245
|
+
source: "windows",
|
|
246
|
+
pid: p.pid,
|
|
247
|
+
ppid: p.ppid,
|
|
248
|
+
startedAt: p.started ? new Date(p.started) : null,
|
|
249
|
+
name: p.name,
|
|
250
|
+
commandLine: p.cmd ?? "",
|
|
251
|
+
executablePath: p.exe ?? "",
|
|
252
|
+
cpuTime100ns: p.cpu
|
|
253
|
+
}));
|
|
254
|
+
}
|
|
255
|
+
function parseWslListing(stdout, now) {
|
|
256
|
+
const rows = [];
|
|
257
|
+
for (const line of stdout.split("\n")) {
|
|
258
|
+
if (line.trim() === "") continue;
|
|
259
|
+
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s*(.*)$/.exec(line);
|
|
260
|
+
if (!m) throw new Error(`wsl ps printed a line this report cannot read: ${JSON.stringify(line)}`);
|
|
261
|
+
rows.push({ source: "wsl", pid: Number(m[1]), ppid: Number(m[2]), startedAt: new Date(now.getTime() - Number(m[3]) * 1e3), name: m[4], commandLine: m[5], executablePath: "", cpuTime100ns: null });
|
|
262
|
+
}
|
|
263
|
+
return rows;
|
|
264
|
+
}
|
|
265
|
+
var runCommand = (file, args, timeoutMs, signal) => new Promise((resolve, reject) => {
|
|
266
|
+
execFile(file, args, { timeout: timeoutMs, maxBuffer: LISTING_MAX_BUFFER_BYTES, windowsHide: true, signal }, (err, stdout) => err ? reject(err) : resolve(stdout));
|
|
267
|
+
});
|
|
268
|
+
async function wslDistroRunning(run, signal) {
|
|
269
|
+
const stdout = await run("wsl.exe", ["--list", "--running", "--quiet"], PROCESS_LISTING_TIMEOUT_MS, signal);
|
|
270
|
+
const running = stdout.replace(/\0/g, "").split(/\r?\n/).map((line) => line.trim()).filter((line) => line !== "" && !DOCKER_DESKTOP_DISTROS.has(line));
|
|
271
|
+
if (running.length === 0) return false;
|
|
272
|
+
if (running.includes(WSL_DISTRO)) return true;
|
|
273
|
+
throw Object.assign(new Error(`${WSL_DISTRO} is not among the running WSL distros: ${running.join(", ")}`), { code: "distro not running" });
|
|
274
|
+
}
|
|
275
|
+
async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand, platform = process.platform, signal, wsl = "always") {
|
|
276
|
+
if (platform !== "win32") return { rows: [], unavailable: [{ source: "windows", reason: "orphan-process listing is implemented for the Windows dev machine only", code: "unsupported platform" }] };
|
|
277
|
+
const allListings = [
|
|
278
|
+
{ source: "windows", read: async () => parseWindowsListing(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_LISTING_SCRIPT], PROCESS_LISTING_TIMEOUT_MS, signal)) },
|
|
279
|
+
{
|
|
280
|
+
source: "wsl",
|
|
281
|
+
read: async () => {
|
|
282
|
+
if (wsl === "when-running" && !await wslDistroRunning(run, signal)) return [];
|
|
283
|
+
return parseWslListing(await run("wsl.exe", ["-d", WSL_DISTRO, "--", "ps", "-eo", "pid=,ppid=,etimes=,comm=,args="], PROCESS_LISTING_TIMEOUT_MS, signal), now);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
];
|
|
287
|
+
const listings = wsl === "never" ? allListings.filter((l) => l.source !== "wsl") : allListings;
|
|
288
|
+
const settled = await Promise.allSettled(listings.map((l) => l.read()));
|
|
289
|
+
const rows = [];
|
|
290
|
+
const unavailable = [];
|
|
291
|
+
settled.forEach((s, i) => {
|
|
292
|
+
if (s.status === "fulfilled") rows.push(...s.value);
|
|
293
|
+
else unavailable.push({ source: listings[i].source, reason: errMessage(s.reason), code: errorCode(s.reason) });
|
|
294
|
+
});
|
|
295
|
+
return { rows, unavailable };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// src/machine-daemon/leftovers.ts
|
|
299
|
+
var FOLLOW_MIN_AGE_MS = 30 * 60 * 1e3;
|
|
300
|
+
var HOT_CPU_FRACTION = 0.5;
|
|
301
|
+
var COOL_CPU_FRACTION = 0.2;
|
|
302
|
+
var HOT_MIN_MS = 3 * 60 * 60 * 1e3;
|
|
303
|
+
var REMIND_INTERVAL_MS = 6 * 60 * 60 * 1e3;
|
|
304
|
+
var READER_GONE_MIN_AGE_MS = 2 * 60 * 1e3;
|
|
305
|
+
var ENV_RETRY_BACKOFF_MS = 30 * 60 * 1e3;
|
|
306
|
+
var MAX_CHAIN_HOPS = 32;
|
|
307
|
+
var ENV_READ_TIMEOUT_MS = 2e4;
|
|
308
|
+
var PS_TIMEOUT_MS = 2e4;
|
|
309
|
+
var keyOf = (pid, startedAtMs) => `${pid}:${startedAtMs}`;
|
|
310
|
+
function fileTimeToMs(fileTime) {
|
|
311
|
+
return Number(BigInt(fileTime) / 10000n) - 116444736e5;
|
|
312
|
+
}
|
|
313
|
+
function readClaudeSessionFiles(dir = join(homedir(), ".claude", "sessions")) {
|
|
314
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
315
|
+
if (!existsSync(dir)) return sessions;
|
|
316
|
+
for (const file of readdirSync(dir)) {
|
|
317
|
+
if (!/^\d+\.json$/.test(file)) continue;
|
|
318
|
+
try {
|
|
319
|
+
const v = JSON.parse(readFileSync2(join(dir, file), "utf8"));
|
|
320
|
+
if (typeof v.pid === "number" && typeof v.sessionId === "string" && typeof v.procStart === "string") sessions.set(v.pid, { sessionId: v.sessionId, startedAtMs: fileTimeToMs(v.procStart) });
|
|
321
|
+
} catch {
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return sessions;
|
|
326
|
+
}
|
|
327
|
+
var FOLLOW_ARG = /(?:^|\s)(?:-[a-zA-Z]*[fF][a-zA-Z]*|--follow(?:=\S+)?)(?=\s|$)/;
|
|
328
|
+
var FILTER_NAMES = /* @__PURE__ */ new Set(["grep.exe", "egrep.exe", "fgrep.exe", "sed.exe", "awk.exe", "gawk.exe"]);
|
|
329
|
+
function isFollowRow(row) {
|
|
330
|
+
const name = row.name.toLowerCase();
|
|
331
|
+
if (name === "tail.exe") return FOLLOW_ARG.test(row.commandLine.replace(/^"[^"]*"|^\S+/, ""));
|
|
332
|
+
return FILTER_NAMES.has(name) && /(?:^|\s)--line-buffered(?=\s|$)/.test(row.commandLine);
|
|
333
|
+
}
|
|
334
|
+
function shortCommand(commandLine) {
|
|
335
|
+
const flat = commandLine.replace(/\s+/g, " ").trim();
|
|
336
|
+
return flat.length > LEFTOVER_COMMAND_MAX_CHARS ? `${flat.slice(0, LEFTOVER_COMMAND_MAX_CHARS)}...` : flat;
|
|
337
|
+
}
|
|
338
|
+
var ENV_READ_SCRIPT = (pids) => `
|
|
339
|
+
$ErrorActionPreference = 'Stop'
|
|
340
|
+
Add-Type -TypeDefinition @'
|
|
341
|
+
using System; using System.Runtime.InteropServices; using System.Text;
|
|
342
|
+
public static class PEnv {
|
|
343
|
+
[DllImport("ntdll.dll")] static extern int NtQueryInformationProcess(IntPtr h, int cls, ref PBI pbi, int len, out int ret);
|
|
344
|
+
[DllImport("kernel32.dll")] static extern IntPtr OpenProcess(int acc, bool inh, int pid);
|
|
345
|
+
[DllImport("kernel32.dll")] static extern bool ReadProcessMemory(IntPtr h, IntPtr addr, byte[] buf, int size, out int read);
|
|
346
|
+
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr h);
|
|
347
|
+
[StructLayout(LayoutKind.Sequential)] struct PBI { public IntPtr Exit, Peb, Aff, Prio, Pid, Parent; }
|
|
348
|
+
static IntPtr Ptr(IntPtr h, IntPtr a) { var b = new byte[8]; int r; ReadProcessMemory(h, a, b, 8, out r); return (IntPtr)BitConverter.ToInt64(b, 0); }
|
|
349
|
+
public static string Env(int pid) {
|
|
350
|
+
IntPtr h = OpenProcess(0x1010, false, pid); if (h == IntPtr.Zero) return "";
|
|
351
|
+
try {
|
|
352
|
+
var pbi = new PBI(); int ret; if (NtQueryInformationProcess(h, 0, ref pbi, Marshal.SizeOf(pbi), out ret) != 0) return "";
|
|
353
|
+
IntPtr pp = Ptr(h, IntPtr.Add(pbi.Peb, 0x20)); IntPtr env = Ptr(h, IntPtr.Add(pp, 0x80));
|
|
354
|
+
var buf = new byte[1 << 20]; int rd; ReadProcessMemory(h, env, buf, buf.Length, out rd);
|
|
355
|
+
return Encoding.Unicode.GetString(buf, 0, rd);
|
|
356
|
+
} finally { CloseHandle(h); }
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
'@
|
|
360
|
+
foreach ($id in @(${pids.join(",")})) {
|
|
361
|
+
$hit = ([PEnv]::Env([int]$id)).Split([char]0) | Where-Object { $_ -like 'CLAUDE_CODE_SESSION_ID=*' } | Select-Object -First 1
|
|
362
|
+
if ($hit) { "$id=" + $hit.Substring(24) }
|
|
363
|
+
}
|
|
364
|
+
`;
|
|
365
|
+
var SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
366
|
+
async function readSessionsFromEnvironment(pids, run = runCommand) {
|
|
367
|
+
const found = /* @__PURE__ */ new Map();
|
|
368
|
+
if (pids.length === 0) return found;
|
|
369
|
+
const stdout = await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", ENV_READ_SCRIPT(pids)], ENV_READ_TIMEOUT_MS);
|
|
370
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
371
|
+
const m = /^(\d+)=(\S+)$/.exec(line.trim());
|
|
372
|
+
if (m && SESSION_ID_RE.test(m[2])) found.set(Number(m[1]), m[2]);
|
|
373
|
+
}
|
|
374
|
+
return found;
|
|
375
|
+
}
|
|
376
|
+
function gitPsPathFrom(rows, exists = existsSync) {
|
|
377
|
+
for (const row of rows) {
|
|
378
|
+
const m = /^(.*\\usr\\bin)\\[^\\]+\.exe$/i.exec(row.executablePath);
|
|
379
|
+
if (m !== null && exists(`${m[1]}\\ps.exe`)) return `${m[1]}\\ps.exe`;
|
|
380
|
+
}
|
|
381
|
+
return null;
|
|
382
|
+
}
|
|
383
|
+
async function readMsysParents(processes, run = runCommand, exists = existsSync) {
|
|
384
|
+
const psPath = gitPsPathFrom(processes, exists);
|
|
385
|
+
if (psPath === null) return /* @__PURE__ */ new Map();
|
|
386
|
+
const stdout = await run(psPath, ["-W"], PS_TIMEOUT_MS);
|
|
387
|
+
const rows = [];
|
|
388
|
+
for (const line of stdout.split(/\r?\n/)) {
|
|
389
|
+
const m = /^[\sI]*(\d+)\s+(\d+)\s+\d+\s+(\d+)\s/.exec(line);
|
|
390
|
+
if (m) rows.push({ pid: Number(m[1]), ppid: Number(m[2]), winpid: Number(m[3]) });
|
|
391
|
+
}
|
|
392
|
+
const winpidOfMsysPid = new Map(rows.filter((r) => r.pid !== r.winpid).map((r) => [r.pid, r.winpid]));
|
|
393
|
+
const parents = /* @__PURE__ */ new Map();
|
|
394
|
+
for (const r of rows) {
|
|
395
|
+
const parent = r.pid === r.winpid ? void 0 : winpidOfMsysPid.get(r.ppid);
|
|
396
|
+
if (parent !== void 0) parents.set(r.winpid, parent);
|
|
397
|
+
}
|
|
398
|
+
return parents;
|
|
399
|
+
}
|
|
400
|
+
function createLeftoverTracker(deps) {
|
|
401
|
+
const ledger = /* @__PURE__ */ new Map();
|
|
402
|
+
let live = /* @__PURE__ */ new Map();
|
|
403
|
+
let liveSessionIds = /* @__PURE__ */ new Set();
|
|
404
|
+
let envRetryAfterMs = 0;
|
|
405
|
+
const parentRowOf = (row, byPid, msys) => {
|
|
406
|
+
const parent = byPid.get(msys.get(row.pid) ?? row.ppid);
|
|
407
|
+
if (parent === void 0) return void 0;
|
|
408
|
+
if (parent.startedAt !== null && row.startedAt !== null && parent.startedAt.getTime() > row.startedAt.getTime()) return void 0;
|
|
409
|
+
return parent;
|
|
410
|
+
};
|
|
411
|
+
const ownerByChain = (row, byPid, msys, sessions) => {
|
|
412
|
+
let child = row;
|
|
413
|
+
for (let hop = 0; hop < MAX_CHAIN_HOPS; hop++) {
|
|
414
|
+
const parent = parentRowOf(child, byPid, msys);
|
|
415
|
+
if (parent === void 0) return null;
|
|
416
|
+
const session = sessions.get(parent.pid);
|
|
417
|
+
if (session !== void 0 && parent.name.toLowerCase() === "claude.exe" && parent.startedAt !== null && Math.abs(parent.startedAt.getTime() - session.startedAtMs) < 5e3) return session.sessionId;
|
|
418
|
+
child = parent;
|
|
419
|
+
}
|
|
420
|
+
return null;
|
|
421
|
+
};
|
|
422
|
+
return {
|
|
423
|
+
async sample(at) {
|
|
424
|
+
const { rows, unavailable } = await deps.listing(at);
|
|
425
|
+
if (unavailable.length > 0) throw new Error(`the process table is unavailable (${unavailable.map((u) => `${u.source}: ${u.reason}`).join("; ")}): the ledger is kept as it was`);
|
|
426
|
+
const windows = rows.filter((r) => r.source === "windows" && r.startedAt !== null);
|
|
427
|
+
const byPid = new Map(windows.map((r) => [r.pid, r]));
|
|
428
|
+
const sessions = deps.claudeSessions();
|
|
429
|
+
const msys = await deps.msysParents(windows);
|
|
430
|
+
liveSessionIds = new Set(windows.filter((r) => r.name.toLowerCase() === "claude.exe" && sessions.get(r.pid) !== void 0).map((r) => sessions.get(r.pid).sessionId));
|
|
431
|
+
const nowLive = /* @__PURE__ */ new Map();
|
|
432
|
+
const nowMs = at.getTime();
|
|
433
|
+
for (const row of windows) {
|
|
434
|
+
const startedAtMs = row.startedAt.getTime();
|
|
435
|
+
const key = keyOf(row.pid, startedAtMs);
|
|
436
|
+
nowLive.set(key, row);
|
|
437
|
+
let entry = ledger.get(key);
|
|
438
|
+
const owner = ownerByChain(row, byPid, msys, sessions);
|
|
439
|
+
if (entry === void 0) {
|
|
440
|
+
const shell = parentRowOf(row, byPid, msys);
|
|
441
|
+
entry = { pid: row.pid, startedAtMs, owner, envChecked: false, shellKey: shell?.startedAt ? keyOf(shell.pid, shell.startedAt.getTime()) : null, unreachable: false, lastCpu100ns: null, lastSeenMs: nowMs, hotSinceMs: null, hotCpuStart100ns: null, hotStartWallMs: null, lastCpuPercent: null, remindedAtMs: null };
|
|
442
|
+
ledger.set(key, entry);
|
|
443
|
+
} else if (entry.owner === null && owner !== null) {
|
|
444
|
+
entry.owner = owner;
|
|
445
|
+
}
|
|
446
|
+
if (row.cpuTime100ns !== null && entry.lastCpu100ns !== null && nowMs > entry.lastSeenMs) {
|
|
447
|
+
const fraction = (row.cpuTime100ns - entry.lastCpu100ns) / 1e4 / (nowMs - entry.lastSeenMs);
|
|
448
|
+
if (fraction >= HOT_CPU_FRACTION && entry.hotSinceMs === null) {
|
|
449
|
+
entry.hotSinceMs = entry.lastSeenMs;
|
|
450
|
+
entry.hotCpuStart100ns = entry.lastCpu100ns;
|
|
451
|
+
entry.hotStartWallMs = entry.lastSeenMs;
|
|
452
|
+
} else if (fraction < COOL_CPU_FRACTION) {
|
|
453
|
+
entry.hotSinceMs = null;
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
if (entry.hotSinceMs !== null && entry.hotCpuStart100ns !== null && entry.hotStartWallMs !== null && row.cpuTime100ns !== null && nowMs > entry.hotStartWallMs) {
|
|
457
|
+
entry.lastCpuPercent = (row.cpuTime100ns - entry.hotCpuStart100ns) / 1e4 / (nowMs - entry.hotStartWallMs) * 100;
|
|
458
|
+
}
|
|
459
|
+
entry.lastCpu100ns = row.cpuTime100ns;
|
|
460
|
+
entry.lastSeenMs = nowMs;
|
|
461
|
+
}
|
|
462
|
+
for (const key of [...ledger.keys()]) if (!nowLive.has(key)) ledger.delete(key);
|
|
463
|
+
live = nowLive;
|
|
464
|
+
const unknown = [...ledger.entries()].filter(([, e]) => e.owner === null && !e.envChecked && e.hotSinceMs !== null && nowMs - e.hotSinceMs >= HOT_MIN_MS);
|
|
465
|
+
if (unknown.length > 0 && nowMs >= envRetryAfterMs) {
|
|
466
|
+
let fromEnv;
|
|
467
|
+
try {
|
|
468
|
+
fromEnv = await deps.sessionsFromEnvironment(unknown.map(([, e]) => e.pid));
|
|
469
|
+
} catch (err) {
|
|
470
|
+
envRetryAfterMs = nowMs + ENV_RETRY_BACKOFF_MS;
|
|
471
|
+
throw err;
|
|
472
|
+
}
|
|
473
|
+
for (const [, e] of unknown) {
|
|
474
|
+
e.envChecked = true;
|
|
475
|
+
e.owner = fromEnv.get(e.pid) ?? null;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
},
|
|
479
|
+
collect(at) {
|
|
480
|
+
const nowMs = at.getTime();
|
|
481
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
482
|
+
const reminded = /* @__PURE__ */ new Map();
|
|
483
|
+
const ownerless = [];
|
|
484
|
+
for (const [key, entry] of ledger) {
|
|
485
|
+
const row = live.get(key);
|
|
486
|
+
if (row === void 0) continue;
|
|
487
|
+
const ageMs = nowMs - entry.startedAtMs;
|
|
488
|
+
const follower = isFollowRow(row);
|
|
489
|
+
const readerGone = follower && entry.shellKey !== null && !live.has(entry.shellKey) && ageMs >= READER_GONE_MIN_AGE_MS;
|
|
490
|
+
const follow = follower && ageMs >= FOLLOW_MIN_AGE_MS;
|
|
491
|
+
const hot = entry.owner !== null && entry.hotSinceMs !== null && nowMs - entry.hotSinceMs >= HOT_MIN_MS;
|
|
492
|
+
if (!readerGone && !follow && !hot) continue;
|
|
493
|
+
const process2 = {
|
|
494
|
+
pid: entry.pid,
|
|
495
|
+
command: shortCommand(row.commandLine),
|
|
496
|
+
age_seconds: Math.floor(ageMs / 1e3),
|
|
497
|
+
cpu_percent: hot && entry.lastCpuPercent !== null ? Math.round(entry.lastCpuPercent) : null,
|
|
498
|
+
why: readerGone ? "reader_gone" : follow ? "follow" : "cpu"
|
|
499
|
+
};
|
|
500
|
+
if (entry.owner === null) {
|
|
501
|
+
ownerless.push({ ...process2, reason: "no session found" });
|
|
502
|
+
} else if (!liveSessionIds.has(entry.owner)) {
|
|
503
|
+
ownerless.push({ ...process2, reason: "session ended" });
|
|
504
|
+
} else {
|
|
505
|
+
if (entry.unreachable) ownerless.push({ ...process2, reason: "session not on this dashboard" });
|
|
506
|
+
if (entry.remindedAtMs === null || nowMs - entry.remindedAtMs >= REMIND_INTERVAL_MS) {
|
|
507
|
+
sessions.set(entry.owner, [...sessions.get(entry.owner) ?? [], process2]);
|
|
508
|
+
reminded.set(entry.owner, [...reminded.get(entry.owner) ?? [], key]);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return { sessions: [...sessions].map(([session_id, processes]) => ({ session_id, processes })), ownerless, reminded };
|
|
513
|
+
},
|
|
514
|
+
settle(collection, undelivered, at) {
|
|
515
|
+
for (const [sessionId, keys] of collection.reminded) {
|
|
516
|
+
for (const key of keys) {
|
|
517
|
+
const entry = ledger.get(key);
|
|
518
|
+
if (entry === void 0) continue;
|
|
519
|
+
entry.unreachable = undelivered.includes(sessionId);
|
|
520
|
+
if (!entry.unreachable) entry.remindedAtMs = at.getTime();
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
function createSystemLeftoverTracker(run = runCommand, platform = process.platform) {
|
|
527
|
+
if (platform !== "win32") return { sample: async () => {
|
|
528
|
+
}, collect: () => ({ sessions: [], ownerless: [], reminded: /* @__PURE__ */ new Map() }), settle: () => {
|
|
529
|
+
} };
|
|
530
|
+
return createLeftoverTracker({
|
|
531
|
+
listing: (now) => listProcesses(now, run, platform, void 0, "never"),
|
|
532
|
+
msysParents: (rows) => readMsysParents(rows, run),
|
|
533
|
+
claudeSessions: () => readClaudeSessionFiles(),
|
|
534
|
+
sessionsFromEnvironment: (pids) => readSessionsFromEnvironment(pids, run)
|
|
535
|
+
});
|
|
536
|
+
}
|
|
537
|
+
|
|
213
538
|
// src/machine-toolkit/contract.ts
|
|
214
539
|
var CONTRACT_VERSION = 2;
|
|
215
540
|
var REQUIRED_METRICS = ["docker_data_disk_bytes", "unowned_docker_resource_count", "orphan_process_count"];
|
|
@@ -221,18 +546,18 @@ var ContractViolation = class extends Error {
|
|
|
221
546
|
}
|
|
222
547
|
};
|
|
223
548
|
var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
224
|
-
var
|
|
549
|
+
var join2 = (path, key) => path === "" ? key : `${path}.${key}`;
|
|
225
550
|
function objectAt(v, path, fail) {
|
|
226
551
|
if (!isObject(v)) return fail(path, "must be an object");
|
|
227
552
|
return v;
|
|
228
553
|
}
|
|
229
554
|
function exactKeys(o, path, keys, fail) {
|
|
230
|
-
for (const k of keys) if (!(k in o)) fail(
|
|
231
|
-
for (const k of Object.keys(o)) if (!keys.includes(k)) fail(
|
|
555
|
+
for (const k of keys) if (!(k in o)) fail(join2(path, k), "is required");
|
|
556
|
+
for (const k of Object.keys(o)) if (!keys.includes(k)) fail(join2(path, k), "is not part of the contract");
|
|
232
557
|
}
|
|
233
558
|
function stringAt(o, key, path, fail) {
|
|
234
559
|
const v = o[key];
|
|
235
|
-
if (typeof v !== "string" || v === "") return fail(
|
|
560
|
+
if (typeof v !== "string" || v === "") return fail(join2(path, key), "must be a non-empty string");
|
|
236
561
|
return v;
|
|
237
562
|
}
|
|
238
563
|
function listAt(v, path, fail) {
|
|
@@ -243,7 +568,7 @@ function checkItem(v, path, extra, fail) {
|
|
|
243
568
|
const o = objectAt(v, path, fail);
|
|
244
569
|
exactKeys(o, path, ["id", "detail", ...extra], fail);
|
|
245
570
|
stringAt(o, "id", path, fail);
|
|
246
|
-
if (typeof o.detail !== "string") fail(
|
|
571
|
+
if (typeof o.detail !== "string") fail(join2(path, "detail"), "must be a string");
|
|
247
572
|
for (const k of extra) stringAt(o, k, path, fail);
|
|
248
573
|
}
|
|
249
574
|
function checkItems(v, path, extra, fail) {
|
|
@@ -305,7 +630,7 @@ var VALIDATORS = {
|
|
|
305
630
|
exactKeys(step, path, ["name", "status", "detail"], fail);
|
|
306
631
|
stringAt(step, "name", path, fail);
|
|
307
632
|
if (step.status !== "done" && step.status !== "skipped" && step.status !== "failed") fail(`${path}.status`, "must be 'done', 'skipped' or 'failed'");
|
|
308
|
-
if (typeof step.detail !== "string") fail(
|
|
633
|
+
if (typeof step.detail !== "string") fail(join2(path, "detail"), "must be a string");
|
|
309
634
|
});
|
|
310
635
|
},
|
|
311
636
|
"label-check"(o, fail) {
|
|
@@ -328,16 +653,6 @@ var realScheduler = (fire, ms) => {
|
|
|
328
653
|
return () => clearTimeout(timer);
|
|
329
654
|
};
|
|
330
655
|
|
|
331
|
-
// src/machine-toolkit/errors.ts
|
|
332
|
-
function errorCode(err) {
|
|
333
|
-
const failure = err;
|
|
334
|
-
if (typeof failure?.code === "string" || typeof failure?.code === "number") return String(failure.code);
|
|
335
|
-
return failure?.killed === true ? "timed out" : "unexpected error";
|
|
336
|
-
}
|
|
337
|
-
function errMessage(err) {
|
|
338
|
-
return err instanceof Error ? err.message : String(err);
|
|
339
|
-
}
|
|
340
|
-
|
|
341
656
|
// src/machine-daemon/report.ts
|
|
342
657
|
var REPORT_INTERVAL_MS = 5 * 60 * 1e3;
|
|
343
658
|
var REPORT_TICK_TOLERANCE_MS = 1e3;
|
|
@@ -386,6 +701,29 @@ function reportPayload(run) {
|
|
|
386
701
|
}
|
|
387
702
|
return { report: parsed };
|
|
388
703
|
}
|
|
704
|
+
var WHY_LABEL = { follow: "follower", reader_gone: "follower whose shell has exited,", cpu: "busy process" };
|
|
705
|
+
function foldOwnerless(payload, ownerless) {
|
|
706
|
+
if (!("report" in payload) || ownerless.length === 0) return payload;
|
|
707
|
+
const { report } = payload;
|
|
708
|
+
const items = ownerless.map((p) => ({ id: `leftover:${p.pid}`, detail: `${WHY_LABEL[p.why]} pid ${p.pid}, running ${Math.floor(p.age_seconds / 3600)} h, no session to remind (${p.reason}): ${p.command}` }));
|
|
709
|
+
const count = report.metrics.orphan_process_count;
|
|
710
|
+
if (count === void 0) throw new Error("a validated health report carries orphan_process_count");
|
|
711
|
+
return {
|
|
712
|
+
report: {
|
|
713
|
+
...report,
|
|
714
|
+
metrics: { ...report.metrics, orphan_process_count: count.value !== null ? { ...count, value: count.value + items.length } : count },
|
|
715
|
+
items: { ...report.items, orphan_processes: [...report.items.orphan_processes, ...items] }
|
|
716
|
+
}
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
function undeliveredOf(text) {
|
|
720
|
+
try {
|
|
721
|
+
const { undelivered } = JSON.parse(text);
|
|
722
|
+
return Array.isArray(undelivered) && undelivered.every((id) => typeof id === "string") ? undelivered : null;
|
|
723
|
+
} catch {
|
|
724
|
+
return null;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
389
727
|
function storedKind(text) {
|
|
390
728
|
try {
|
|
391
729
|
const { stored } = JSON.parse(text);
|
|
@@ -397,18 +735,22 @@ function storedKind(text) {
|
|
|
397
735
|
function createReporter(deps) {
|
|
398
736
|
let lastStartMs = null;
|
|
399
737
|
let running = false;
|
|
738
|
+
let sampling = false;
|
|
400
739
|
let refused = false;
|
|
401
740
|
const run = async (startedAt) => {
|
|
402
|
-
const
|
|
741
|
+
const found = deps.leftovers.collect(startedAt);
|
|
742
|
+
const payload = foldOwnerless(reportPayload(await deps.runHealth()), found.ownerless);
|
|
403
743
|
const reportError = "report_error" in payload ? payload.report_error : null;
|
|
404
|
-
const sent = await postAsMachine(deps.config, deps.fetchFn, "/api/machines/report", payload);
|
|
744
|
+
const sent = await postAsMachine(deps.config, deps.fetchFn, "/api/machines/report", found.sessions.length === 0 ? payload : { ...payload, leftovers: { sessions: found.sessions } });
|
|
405
745
|
let outcome;
|
|
406
746
|
let error = reportError ?? sent.error;
|
|
407
747
|
if (sent.status === 200) {
|
|
408
748
|
const stored = storedKind(sent.text);
|
|
409
|
-
|
|
749
|
+
const undelivered = undeliveredOf(sent.text);
|
|
750
|
+
if (undelivered !== null) deps.leftovers.settle(found, undelivered, startedAt);
|
|
751
|
+
if (stored === null || undelivered === null) {
|
|
410
752
|
outcome = "failed";
|
|
411
|
-
error = "the dashboard answered 200 without saying what it stored";
|
|
753
|
+
error = "the dashboard answered 200 without saying what it stored and which sessions it could not remind";
|
|
412
754
|
deps.log(`report failed at ${startedAt.toISOString()}: ${error}`);
|
|
413
755
|
} else if (stored === "report_error" && reportError === null) {
|
|
414
756
|
outcome = "report-refused";
|
|
@@ -432,6 +774,20 @@ function createReporter(deps) {
|
|
|
432
774
|
if (deps.installed()) deps.writeStatus({ last_report_at: startedAt.toISOString(), last_report_outcome: outcome, last_report_error: error });
|
|
433
775
|
};
|
|
434
776
|
return {
|
|
777
|
+
async sample(at) {
|
|
778
|
+
if (sampling) {
|
|
779
|
+
deps.log("the last leftover sample is still running: skipping this one");
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
sampling = true;
|
|
783
|
+
try {
|
|
784
|
+
await deps.leftovers.sample(at);
|
|
785
|
+
} catch (err) {
|
|
786
|
+
deps.log(`leftover sampling failed at ${at.toISOString()}: ${errMessage(err)}; the next beat tries again`);
|
|
787
|
+
} finally {
|
|
788
|
+
sampling = false;
|
|
789
|
+
}
|
|
790
|
+
},
|
|
435
791
|
tick(startedAt) {
|
|
436
792
|
if (lastStartMs !== null && startedAt.getTime() - lastStartMs < REPORT_INTERVAL_MS - REPORT_TICK_TOLERANCE_MS) return null;
|
|
437
793
|
if (running) {
|
|
@@ -449,9 +805,9 @@ function createReporter(deps) {
|
|
|
449
805
|
}
|
|
450
806
|
|
|
451
807
|
// src/machine-daemon/state.ts
|
|
452
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync as
|
|
453
|
-
import { homedir } from "node:os";
|
|
454
|
-
import { dirname, join as
|
|
808
|
+
import { chmodSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync3, renameSync, writeFileSync } from "node:fs";
|
|
809
|
+
import { homedir as homedir2 } from "node:os";
|
|
810
|
+
import { dirname, join as join3 } from "node:path";
|
|
455
811
|
var MACHINE_DAEMON_DIR_NAME = ".danxbot";
|
|
456
812
|
function createStatusWriter(write) {
|
|
457
813
|
let current = {
|
|
@@ -471,19 +827,19 @@ function createStatusWriter(write) {
|
|
|
471
827
|
return { beat: merge, report: merge };
|
|
472
828
|
}
|
|
473
829
|
function danxbotHome() {
|
|
474
|
-
return
|
|
830
|
+
return join3(homedir2(), MACHINE_DAEMON_DIR_NAME);
|
|
475
831
|
}
|
|
476
832
|
function daemonConfigPath(home = danxbotHome()) {
|
|
477
|
-
return
|
|
833
|
+
return join3(home, "machine-daemon.json");
|
|
478
834
|
}
|
|
479
835
|
function daemonStatusPath(home = danxbotHome()) {
|
|
480
|
-
return
|
|
836
|
+
return join3(home, "machine-daemon-status.json");
|
|
481
837
|
}
|
|
482
838
|
function daemonBundleDir(home = danxbotHome()) {
|
|
483
|
-
return
|
|
839
|
+
return join3(home, "machine-daemon");
|
|
484
840
|
}
|
|
485
841
|
function toolkitBundlePath(home = danxbotHome()) {
|
|
486
|
-
return
|
|
842
|
+
return join3(daemonBundleDir(home), "machine-toolkit.js");
|
|
487
843
|
}
|
|
488
844
|
function writeOwnerOnlyJson(file, value) {
|
|
489
845
|
mkdirSync(dirname(file), { recursive: true });
|
|
@@ -494,8 +850,8 @@ function writeOwnerOnlyJson(file, value) {
|
|
|
494
850
|
renameSync(tmp, file);
|
|
495
851
|
}
|
|
496
852
|
function readJsonIfPresent(file) {
|
|
497
|
-
if (!
|
|
498
|
-
return JSON.parse(
|
|
853
|
+
if (!existsSync2(file)) return null;
|
|
854
|
+
return JSON.parse(readFileSync3(file, "utf8"));
|
|
499
855
|
}
|
|
500
856
|
|
|
501
857
|
// src/machine-daemon/run.ts
|
|
@@ -522,22 +878,23 @@ async function runDaemonProcess() {
|
|
|
522
878
|
const status = createStatusWriter((value) => writeOwnerOnlyJson(daemonStatusPath(), value));
|
|
523
879
|
const stop = await runBeatLoop({
|
|
524
880
|
config,
|
|
525
|
-
collect: createMachineVitalsCollector({ diskPath:
|
|
881
|
+
collect: createMachineVitalsCollector({ diskPath: homedir3() }),
|
|
526
882
|
fetchFn,
|
|
527
883
|
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
528
884
|
now,
|
|
529
885
|
writeStatus: status.beat,
|
|
530
886
|
log,
|
|
531
887
|
pid: process.pid,
|
|
532
|
-
installed: () =>
|
|
888
|
+
installed: () => existsSync3(daemonConfigPath()),
|
|
533
889
|
readBearer: readBearerOnDisk,
|
|
534
890
|
reporter: createReporter({
|
|
535
891
|
config,
|
|
536
892
|
runHealth: () => runHealthChild({ spawnFn: spawn, nodePath: process.execPath, toolkitPath: toolkitBundlePath() }),
|
|
537
893
|
fetchFn,
|
|
894
|
+
leftovers: createSystemLeftoverTracker(),
|
|
538
895
|
writeStatus: status.report,
|
|
539
896
|
log,
|
|
540
|
-
installed: () =>
|
|
897
|
+
installed: () => existsSync3(daemonConfigPath())
|
|
541
898
|
})
|
|
542
899
|
});
|
|
543
900
|
return finishBeatStop(stop, () => disableAutostart({ platform: process.platform, run: runHidden }));
|
package/dist/machine-toolkit.js
CHANGED
|
@@ -250,7 +250,7 @@ function resolveToolkitVersion(stamped, readManifest) {
|
|
|
250
250
|
return stamped ?? readManifest();
|
|
251
251
|
}
|
|
252
252
|
var readOwnManifest = () => JSON.parse(readFileSync2(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
253
|
-
var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.
|
|
253
|
+
var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.456", readOwnManifest);
|
|
254
254
|
function envelope(now) {
|
|
255
255
|
return { contract_version: CONTRACT_VERSION, toolkit_version: TOOLKIT_VERSION, profile: PROFILE, measured_at: now.toISOString() };
|
|
256
256
|
}
|
|
@@ -351,7 +351,7 @@ function findOrphans(rows, now) {
|
|
|
351
351
|
}
|
|
352
352
|
return found.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());
|
|
353
353
|
}
|
|
354
|
-
var WINDOWS_LISTING_SCRIPT = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; ppid = $_.ParentProcessId; started = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null }); name = $_.Name; cmd = $_.CommandLine; exe = $_.ExecutablePath } } | ConvertTo-Json -Compress";
|
|
354
|
+
var WINDOWS_LISTING_SCRIPT = "[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Get-CimInstance Win32_Process | ForEach-Object { [pscustomobject]@{ pid = $_.ProcessId; ppid = $_.ParentProcessId; started = $(if ($_.CreationDate) { $_.CreationDate.ToUniversalTime().ToString('o') } else { $null }); name = $_.Name; cmd = $_.CommandLine; exe = $_.ExecutablePath; cpu = ([uint64]$_.KernelModeTime + [uint64]$_.UserModeTime) } } | ConvertTo-Json -Compress";
|
|
355
355
|
function parseWindowsListing(stdout) {
|
|
356
356
|
const parsed = JSON.parse(stdout);
|
|
357
357
|
return (Array.isArray(parsed) ? parsed : [parsed]).map((p) => ({
|
|
@@ -361,7 +361,8 @@ function parseWindowsListing(stdout) {
|
|
|
361
361
|
startedAt: p.started ? new Date(p.started) : null,
|
|
362
362
|
name: p.name,
|
|
363
363
|
commandLine: p.cmd ?? "",
|
|
364
|
-
executablePath: p.exe ?? ""
|
|
364
|
+
executablePath: p.exe ?? "",
|
|
365
|
+
cpuTime100ns: p.cpu
|
|
365
366
|
}));
|
|
366
367
|
}
|
|
367
368
|
function parseWslListing(stdout, now) {
|
|
@@ -370,7 +371,7 @@ function parseWslListing(stdout, now) {
|
|
|
370
371
|
if (line.trim() === "") continue;
|
|
371
372
|
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s*(.*)$/.exec(line);
|
|
372
373
|
if (!m) throw new Error(`wsl ps printed a line this report cannot read: ${JSON.stringify(line)}`);
|
|
373
|
-
rows.push({ source: "wsl", pid: Number(m[1]), ppid: Number(m[2]), startedAt: new Date(now.getTime() - Number(m[3]) * 1e3), name: m[4], commandLine: m[5], executablePath: "" });
|
|
374
|
+
rows.push({ source: "wsl", pid: Number(m[1]), ppid: Number(m[2]), startedAt: new Date(now.getTime() - Number(m[3]) * 1e3), name: m[4], commandLine: m[5], executablePath: "", cpuTime100ns: null });
|
|
374
375
|
}
|
|
375
376
|
return rows;
|
|
376
377
|
}
|
|
@@ -386,7 +387,7 @@ async function wslDistroRunning(run, signal) {
|
|
|
386
387
|
}
|
|
387
388
|
async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand, platform = process.platform, signal, wsl = "always") {
|
|
388
389
|
if (platform !== "win32") return { rows: [], unavailable: [{ source: "windows", reason: "orphan-process listing is implemented for the Windows dev machine only", code: "unsupported platform" }] };
|
|
389
|
-
const
|
|
390
|
+
const allListings = [
|
|
390
391
|
{ source: "windows", read: async () => parseWindowsListing(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_LISTING_SCRIPT], PROCESS_LISTING_TIMEOUT_MS, signal)) },
|
|
391
392
|
{
|
|
392
393
|
source: "wsl",
|
|
@@ -396,6 +397,7 @@ async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand,
|
|
|
396
397
|
}
|
|
397
398
|
}
|
|
398
399
|
];
|
|
400
|
+
const listings = wsl === "never" ? allListings.filter((l) => l.source !== "wsl") : allListings;
|
|
399
401
|
const settled = await Promise.allSettled(listings.map((l) => l.read()));
|
|
400
402
|
const rows = [];
|
|
401
403
|
const unavailable = [];
|
|
@@ -30,6 +30,7 @@ export const GET_ROUTE_BOARD_SCOPE = [
|
|
|
30
30
|
["/api/issues/:id/usage-runs", "refuse"],
|
|
31
31
|
["/api/issues/:id/usage-series", "refuse"],
|
|
32
32
|
["/api/issues/:issueId/dispatches", "refuse"],
|
|
33
|
+
["/api/item-versions", "refuse"],
|
|
33
34
|
["/api/landing-queue/pipeline-health", "refuse"],
|
|
34
35
|
["/api/model-ledger", "refuse"],
|
|
35
36
|
["/api/notifications", "refuse"],
|
package/dist/urgent-records.js
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@50arms/platform-mcp",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.456",
|
|
4
4
|
"description": "Stdio MCP server fronting the 50 Arms dashboard API for agents (operator sessions and dispatched workers alike): the generic 50arms_api/50arms_api_list/50arms_api_spec tools reach any route the caller's credential may call, plus dedicated agent-specific tools (session_connect, request_permission, attach_file, and 50arms_slack_reply) (DX-3465, PLN-11 R-25).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|