@50arms/platform-mcp 0.1.455 → 0.1.457
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 +395 -35
- package/dist/machine-toolkit.js +186 -76
- 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,15 +204,341 @@ 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"];
|
|
541
|
+
var KERNEL_TOKEN_METRIC = "kernel_token_count";
|
|
216
542
|
var HEALTH_ITEM_LISTS = ["unowned_docker_resources", "orphan_processes"];
|
|
217
543
|
var ContractViolation = class extends Error {
|
|
218
544
|
constructor(command, path, what) {
|
|
@@ -221,18 +547,18 @@ var ContractViolation = class extends Error {
|
|
|
221
547
|
}
|
|
222
548
|
};
|
|
223
549
|
var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
224
|
-
var
|
|
550
|
+
var join2 = (path, key) => path === "" ? key : `${path}.${key}`;
|
|
225
551
|
function objectAt(v, path, fail) {
|
|
226
552
|
if (!isObject(v)) return fail(path, "must be an object");
|
|
227
553
|
return v;
|
|
228
554
|
}
|
|
229
555
|
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(
|
|
556
|
+
for (const k of keys) if (!(k in o)) fail(join2(path, k), "is required");
|
|
557
|
+
for (const k of Object.keys(o)) if (!keys.includes(k)) fail(join2(path, k), "is not part of the contract");
|
|
232
558
|
}
|
|
233
559
|
function stringAt(o, key, path, fail) {
|
|
234
560
|
const v = o[key];
|
|
235
|
-
if (typeof v !== "string" || v === "") return fail(
|
|
561
|
+
if (typeof v !== "string" || v === "") return fail(join2(path, key), "must be a non-empty string");
|
|
236
562
|
return v;
|
|
237
563
|
}
|
|
238
564
|
function listAt(v, path, fail) {
|
|
@@ -243,7 +569,7 @@ function checkItem(v, path, extra, fail) {
|
|
|
243
569
|
const o = objectAt(v, path, fail);
|
|
244
570
|
exactKeys(o, path, ["id", "detail", ...extra], fail);
|
|
245
571
|
stringAt(o, "id", path, fail);
|
|
246
|
-
if (typeof o.detail !== "string") fail(
|
|
572
|
+
if (typeof o.detail !== "string") fail(join2(path, "detail"), "must be a string");
|
|
247
573
|
for (const k of extra) stringAt(o, k, path, fail);
|
|
248
574
|
}
|
|
249
575
|
function checkItems(v, path, extra, fail) {
|
|
@@ -277,6 +603,8 @@ var VALIDATORS = {
|
|
|
277
603
|
const metrics = objectAt(o.metrics, "metrics", fail);
|
|
278
604
|
for (const name of REQUIRED_METRICS) if (!(name in metrics)) fail(`metrics.${name}`, "is required");
|
|
279
605
|
for (const [name, metric] of Object.entries(metrics)) checkMetric(metric, `metrics.${name}`, fail);
|
|
606
|
+
const tokens = metrics[KERNEL_TOKEN_METRIC]?.value;
|
|
607
|
+
if (typeof tokens === "number" && !Number.isInteger(tokens)) fail(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
|
|
280
608
|
const items = objectAt(o.items, "items", fail);
|
|
281
609
|
exactKeys(items, "items", HEALTH_ITEM_LISTS, fail);
|
|
282
610
|
for (const list of HEALTH_ITEM_LISTS) checkItems(items[list], `items.${list}`, [], fail);
|
|
@@ -305,7 +633,7 @@ var VALIDATORS = {
|
|
|
305
633
|
exactKeys(step, path, ["name", "status", "detail"], fail);
|
|
306
634
|
stringAt(step, "name", path, fail);
|
|
307
635
|
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(
|
|
636
|
+
if (typeof step.detail !== "string") fail(join2(path, "detail"), "must be a string");
|
|
309
637
|
});
|
|
310
638
|
},
|
|
311
639
|
"label-check"(o, fail) {
|
|
@@ -328,16 +656,6 @@ var realScheduler = (fire, ms) => {
|
|
|
328
656
|
return () => clearTimeout(timer);
|
|
329
657
|
};
|
|
330
658
|
|
|
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
659
|
// src/machine-daemon/report.ts
|
|
342
660
|
var REPORT_INTERVAL_MS = 5 * 60 * 1e3;
|
|
343
661
|
var REPORT_TICK_TOLERANCE_MS = 1e3;
|
|
@@ -386,6 +704,29 @@ function reportPayload(run) {
|
|
|
386
704
|
}
|
|
387
705
|
return { report: parsed };
|
|
388
706
|
}
|
|
707
|
+
var WHY_LABEL = { follow: "follower", reader_gone: "follower whose shell has exited,", cpu: "busy process" };
|
|
708
|
+
function foldOwnerless(payload, ownerless) {
|
|
709
|
+
if (!("report" in payload) || ownerless.length === 0) return payload;
|
|
710
|
+
const { report } = payload;
|
|
711
|
+
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}` }));
|
|
712
|
+
const count = report.metrics.orphan_process_count;
|
|
713
|
+
if (count === void 0) throw new Error("a validated health report carries orphan_process_count");
|
|
714
|
+
return {
|
|
715
|
+
report: {
|
|
716
|
+
...report,
|
|
717
|
+
metrics: { ...report.metrics, orphan_process_count: count.value !== null ? { ...count, value: count.value + items.length } : count },
|
|
718
|
+
items: { ...report.items, orphan_processes: [...report.items.orphan_processes, ...items] }
|
|
719
|
+
}
|
|
720
|
+
};
|
|
721
|
+
}
|
|
722
|
+
function undeliveredOf(text) {
|
|
723
|
+
try {
|
|
724
|
+
const { undelivered } = JSON.parse(text);
|
|
725
|
+
return Array.isArray(undelivered) && undelivered.every((id) => typeof id === "string") ? undelivered : null;
|
|
726
|
+
} catch {
|
|
727
|
+
return null;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
389
730
|
function storedKind(text) {
|
|
390
731
|
try {
|
|
391
732
|
const { stored } = JSON.parse(text);
|
|
@@ -397,18 +738,22 @@ function storedKind(text) {
|
|
|
397
738
|
function createReporter(deps) {
|
|
398
739
|
let lastStartMs = null;
|
|
399
740
|
let running = false;
|
|
741
|
+
let sampling = false;
|
|
400
742
|
let refused = false;
|
|
401
743
|
const run = async (startedAt) => {
|
|
402
|
-
const
|
|
744
|
+
const found = deps.leftovers.collect(startedAt);
|
|
745
|
+
const payload = foldOwnerless(reportPayload(await deps.runHealth()), found.ownerless);
|
|
403
746
|
const reportError = "report_error" in payload ? payload.report_error : null;
|
|
404
|
-
const sent = await postAsMachine(deps.config, deps.fetchFn, "/api/machines/report", payload);
|
|
747
|
+
const sent = await postAsMachine(deps.config, deps.fetchFn, "/api/machines/report", found.sessions.length === 0 ? payload : { ...payload, leftovers: { sessions: found.sessions } });
|
|
405
748
|
let outcome;
|
|
406
749
|
let error = reportError ?? sent.error;
|
|
407
750
|
if (sent.status === 200) {
|
|
408
751
|
const stored = storedKind(sent.text);
|
|
409
|
-
|
|
752
|
+
const undelivered = undeliveredOf(sent.text);
|
|
753
|
+
if (undelivered !== null) deps.leftovers.settle(found, undelivered, startedAt);
|
|
754
|
+
if (stored === null || undelivered === null) {
|
|
410
755
|
outcome = "failed";
|
|
411
|
-
error = "the dashboard answered 200 without saying what it stored";
|
|
756
|
+
error = "the dashboard answered 200 without saying what it stored and which sessions it could not remind";
|
|
412
757
|
deps.log(`report failed at ${startedAt.toISOString()}: ${error}`);
|
|
413
758
|
} else if (stored === "report_error" && reportError === null) {
|
|
414
759
|
outcome = "report-refused";
|
|
@@ -432,6 +777,20 @@ function createReporter(deps) {
|
|
|
432
777
|
if (deps.installed()) deps.writeStatus({ last_report_at: startedAt.toISOString(), last_report_outcome: outcome, last_report_error: error });
|
|
433
778
|
};
|
|
434
779
|
return {
|
|
780
|
+
async sample(at) {
|
|
781
|
+
if (sampling) {
|
|
782
|
+
deps.log("the last leftover sample is still running: skipping this one");
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
sampling = true;
|
|
786
|
+
try {
|
|
787
|
+
await deps.leftovers.sample(at);
|
|
788
|
+
} catch (err) {
|
|
789
|
+
deps.log(`leftover sampling failed at ${at.toISOString()}: ${errMessage(err)}; the next beat tries again`);
|
|
790
|
+
} finally {
|
|
791
|
+
sampling = false;
|
|
792
|
+
}
|
|
793
|
+
},
|
|
435
794
|
tick(startedAt) {
|
|
436
795
|
if (lastStartMs !== null && startedAt.getTime() - lastStartMs < REPORT_INTERVAL_MS - REPORT_TICK_TOLERANCE_MS) return null;
|
|
437
796
|
if (running) {
|
|
@@ -449,9 +808,9 @@ function createReporter(deps) {
|
|
|
449
808
|
}
|
|
450
809
|
|
|
451
810
|
// src/machine-daemon/state.ts
|
|
452
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync as
|
|
453
|
-
import { homedir } from "node:os";
|
|
454
|
-
import { dirname, join as
|
|
811
|
+
import { chmodSync, existsSync as existsSync2, mkdirSync, readFileSync as readFileSync3, renameSync, writeFileSync } from "node:fs";
|
|
812
|
+
import { homedir as homedir2 } from "node:os";
|
|
813
|
+
import { dirname, join as join3 } from "node:path";
|
|
455
814
|
var MACHINE_DAEMON_DIR_NAME = ".danxbot";
|
|
456
815
|
function createStatusWriter(write) {
|
|
457
816
|
let current = {
|
|
@@ -471,19 +830,19 @@ function createStatusWriter(write) {
|
|
|
471
830
|
return { beat: merge, report: merge };
|
|
472
831
|
}
|
|
473
832
|
function danxbotHome() {
|
|
474
|
-
return
|
|
833
|
+
return join3(homedir2(), MACHINE_DAEMON_DIR_NAME);
|
|
475
834
|
}
|
|
476
835
|
function daemonConfigPath(home = danxbotHome()) {
|
|
477
|
-
return
|
|
836
|
+
return join3(home, "machine-daemon.json");
|
|
478
837
|
}
|
|
479
838
|
function daemonStatusPath(home = danxbotHome()) {
|
|
480
|
-
return
|
|
839
|
+
return join3(home, "machine-daemon-status.json");
|
|
481
840
|
}
|
|
482
841
|
function daemonBundleDir(home = danxbotHome()) {
|
|
483
|
-
return
|
|
842
|
+
return join3(home, "machine-daemon");
|
|
484
843
|
}
|
|
485
844
|
function toolkitBundlePath(home = danxbotHome()) {
|
|
486
|
-
return
|
|
845
|
+
return join3(daemonBundleDir(home), "machine-toolkit.js");
|
|
487
846
|
}
|
|
488
847
|
function writeOwnerOnlyJson(file, value) {
|
|
489
848
|
mkdirSync(dirname(file), { recursive: true });
|
|
@@ -494,8 +853,8 @@ function writeOwnerOnlyJson(file, value) {
|
|
|
494
853
|
renameSync(tmp, file);
|
|
495
854
|
}
|
|
496
855
|
function readJsonIfPresent(file) {
|
|
497
|
-
if (!
|
|
498
|
-
return JSON.parse(
|
|
856
|
+
if (!existsSync2(file)) return null;
|
|
857
|
+
return JSON.parse(readFileSync3(file, "utf8"));
|
|
499
858
|
}
|
|
500
859
|
|
|
501
860
|
// src/machine-daemon/run.ts
|
|
@@ -522,22 +881,23 @@ async function runDaemonProcess() {
|
|
|
522
881
|
const status = createStatusWriter((value) => writeOwnerOnlyJson(daemonStatusPath(), value));
|
|
523
882
|
const stop = await runBeatLoop({
|
|
524
883
|
config,
|
|
525
|
-
collect: createMachineVitalsCollector({ diskPath:
|
|
884
|
+
collect: createMachineVitalsCollector({ diskPath: homedir3() }),
|
|
526
885
|
fetchFn,
|
|
527
886
|
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
528
887
|
now,
|
|
529
888
|
writeStatus: status.beat,
|
|
530
889
|
log,
|
|
531
890
|
pid: process.pid,
|
|
532
|
-
installed: () =>
|
|
891
|
+
installed: () => existsSync3(daemonConfigPath()),
|
|
533
892
|
readBearer: readBearerOnDisk,
|
|
534
893
|
reporter: createReporter({
|
|
535
894
|
config,
|
|
536
895
|
runHealth: () => runHealthChild({ spawnFn: spawn, nodePath: process.execPath, toolkitPath: toolkitBundlePath() }),
|
|
537
896
|
fetchFn,
|
|
897
|
+
leftovers: createSystemLeftoverTracker(),
|
|
538
898
|
writeStatus: status.report,
|
|
539
899
|
log,
|
|
540
|
-
installed: () =>
|
|
900
|
+
installed: () => existsSync3(daemonConfigPath())
|
|
541
901
|
})
|
|
542
902
|
});
|
|
543
903
|
return finishBeatStop(stop, () => disableAutostart({ platform: process.platform, run: runHidden }));
|
package/dist/machine-toolkit.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
// src/machine-toolkit/cli.ts
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
2
3
|
import { realpathSync } from "node:fs";
|
|
3
4
|
import { pathToFileURL } from "node:url";
|
|
4
5
|
|
|
@@ -15,6 +16,8 @@ var EXIT = {
|
|
|
15
16
|
refused: 3
|
|
16
17
|
};
|
|
17
18
|
var REQUIRED_METRICS = ["docker_data_disk_bytes", "unowned_docker_resource_count", "orphan_process_count"];
|
|
19
|
+
var PROCESS_START_METRIC = "process_start_ms";
|
|
20
|
+
var KERNEL_TOKEN_METRIC = "kernel_token_count";
|
|
18
21
|
var HEALTH_ITEM_LISTS = ["unowned_docker_resources", "orphan_processes"];
|
|
19
22
|
var ContractViolation = class extends Error {
|
|
20
23
|
constructor(command, path, what) {
|
|
@@ -79,6 +82,8 @@ var VALIDATORS = {
|
|
|
79
82
|
const metrics = objectAt(o.metrics, "metrics", fail2);
|
|
80
83
|
for (const name of REQUIRED_METRICS) if (!(name in metrics)) fail2(`metrics.${name}`, "is required");
|
|
81
84
|
for (const [name, metric] of Object.entries(metrics)) checkMetric(metric, `metrics.${name}`, fail2);
|
|
85
|
+
const tokens = metrics[KERNEL_TOKEN_METRIC]?.value;
|
|
86
|
+
if (typeof tokens === "number" && !Number.isInteger(tokens)) fail2(`metrics.${KERNEL_TOKEN_METRIC}.value`, "must be a whole number");
|
|
82
87
|
const items = objectAt(o.items, "items", fail2);
|
|
83
88
|
exactKeys(items, "items", HEALTH_ITEM_LISTS, fail2);
|
|
84
89
|
for (const list of HEALTH_ITEM_LISTS) checkItems(items[list], `items.${list}`, [], fail2);
|
|
@@ -243,77 +248,11 @@ function errMessage(err) {
|
|
|
243
248
|
return err instanceof Error ? err.message : String(err);
|
|
244
249
|
}
|
|
245
250
|
|
|
246
|
-
// src/machine-toolkit/
|
|
247
|
-
import {
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
}
|
|
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.455", readOwnManifest);
|
|
254
|
-
function envelope(now) {
|
|
255
|
-
return { contract_version: CONTRACT_VERSION, toolkit_version: TOOLKIT_VERSION, profile: PROFILE, measured_at: now.toISOString() };
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
// src/machine-toolkit/health.ts
|
|
259
|
-
var HEALTH_BUDGET_MS = 1e4;
|
|
260
|
-
var HEALTH_MARGIN_MS = 1500;
|
|
261
|
-
var MIN_ORPHAN_DEADLINE_MS = 500;
|
|
262
|
-
function orphanDeadlineMs(uptimeSeconds) {
|
|
263
|
-
return Math.max(MIN_ORPHAN_DEADLINE_MS, Math.floor(HEALTH_BUDGET_MS - uptimeSeconds * 1e3 - HEALTH_MARGIN_MS));
|
|
264
|
-
}
|
|
265
|
-
var unread = (reason) => ({ metric: metricUnread(reason), items: [] });
|
|
266
|
-
async function read(reader, what) {
|
|
267
|
-
try {
|
|
268
|
-
return await reader();
|
|
269
|
-
} catch (err) {
|
|
270
|
-
return unread(err instanceof DeadlineExceeded ? err.message : `${what} failed (${errorCode(err)})`);
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
async function collectHealth(src, opts = {}) {
|
|
274
|
-
const now = src.now();
|
|
275
|
-
const deadlineMs = opts.deadlineMs ?? orphanDeadlineMs(process.uptime());
|
|
276
|
-
const [dataDisk, unowned, orphans] = await Promise.all([
|
|
277
|
-
read(() => {
|
|
278
|
-
const disk = src.dataDisk();
|
|
279
|
-
return disk.bytes === null ? unread(disk.unavailableReason) : { metric: metricRead(disk.bytes), items: [] };
|
|
280
|
-
}, "reading docker_data.vhdx"),
|
|
281
|
-
read(() => {
|
|
282
|
-
const flags = src.flags();
|
|
283
|
-
if (flags === null) return unread("no real Docker sweep has written docker-flags.json on this machine yet");
|
|
284
|
-
const ageMs = Math.max(0, now.getTime() - new Date(flags.at).getTime());
|
|
285
|
-
if (ageMs > FLAGS_STALE_MS) return unread(`the last Docker sweep result is ${(ageMs / 36e5).toFixed(1)} h old (older than ${FLAGS_STALE_MS / 36e5} h): the hourly sweep has stopped, so its count is stale`);
|
|
286
|
-
const ageSeconds = Math.round(ageMs / 1e3);
|
|
287
|
-
const items = flags.flagged.filter((f) => f.reason.startsWith(UNOWNED_REASON_PREFIX)).map((f) => ({ id: f.id, detail: f.reason.slice(UNOWNED_REASON_PREFIX.length) }));
|
|
288
|
-
return { metric: metricRead(flags.unowned, "cached", ageSeconds), items };
|
|
289
|
-
}, "reading the Docker flags file"),
|
|
290
|
-
read(async () => {
|
|
291
|
-
if (src.compactionWindowOpen()) return unread("a compaction window is open, so processes are not listed until it closes");
|
|
292
|
-
const abort = new AbortController();
|
|
293
|
-
let report2;
|
|
294
|
-
try {
|
|
295
|
-
report2 = await withDeadline(src.orphans(now, abort.signal), deadlineMs, opts.schedule ?? realScheduler, "the process listing");
|
|
296
|
-
} catch (err) {
|
|
297
|
-
abort.abort();
|
|
298
|
-
throw err;
|
|
299
|
-
}
|
|
300
|
-
if (report2.unavailable.length > 0) return unread(report2.unavailable.map((u) => `${u.source} processes not listed (${u.code})`).join("; "));
|
|
301
|
-
const items = report2.findings.map((f) => ({ id: `${f.source}:${f.pid}`, detail: `${f.kind} started ${f.startedAt.toISOString()}: ${f.commandLine}` }));
|
|
302
|
-
return { metric: metricRead(items.length), items };
|
|
303
|
-
}, "listing processes")
|
|
304
|
-
]);
|
|
305
|
-
const report = {
|
|
306
|
-
...envelope(now),
|
|
307
|
-
metrics: {
|
|
308
|
-
docker_data_disk_bytes: dataDisk.metric,
|
|
309
|
-
unowned_docker_resource_count: unowned.metric,
|
|
310
|
-
orphan_process_count: orphans.metric
|
|
311
|
-
},
|
|
312
|
-
items: { unowned_docker_resources: unowned.items, orphan_processes: orphans.items }
|
|
313
|
-
};
|
|
314
|
-
assertContract("health", report);
|
|
315
|
-
return report;
|
|
316
|
-
}
|
|
251
|
+
// src/machine-toolkit/probe.ts
|
|
252
|
+
import { createHash } from "node:crypto";
|
|
253
|
+
import { existsSync as existsSync2, mkdirSync, renameSync, writeFileSync } from "node:fs";
|
|
254
|
+
import { join as join5 } from "node:path";
|
|
255
|
+
import { performance } from "node:perf_hooks";
|
|
317
256
|
|
|
318
257
|
// src/machine-toolkit/processes.ts
|
|
319
258
|
import { execFile } from "node:child_process";
|
|
@@ -351,7 +290,7 @@ function findOrphans(rows, now) {
|
|
|
351
290
|
}
|
|
352
291
|
return found.sort((a, b) => a.startedAt.getTime() - b.startedAt.getTime());
|
|
353
292
|
}
|
|
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";
|
|
293
|
+
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
294
|
function parseWindowsListing(stdout) {
|
|
356
295
|
const parsed = JSON.parse(stdout);
|
|
357
296
|
return (Array.isArray(parsed) ? parsed : [parsed]).map((p) => ({
|
|
@@ -361,7 +300,8 @@ function parseWindowsListing(stdout) {
|
|
|
361
300
|
startedAt: p.started ? new Date(p.started) : null,
|
|
362
301
|
name: p.name,
|
|
363
302
|
commandLine: p.cmd ?? "",
|
|
364
|
-
executablePath: p.exe ?? ""
|
|
303
|
+
executablePath: p.exe ?? "",
|
|
304
|
+
cpuTime100ns: p.cpu
|
|
365
305
|
}));
|
|
366
306
|
}
|
|
367
307
|
function parseWslListing(stdout, now) {
|
|
@@ -370,7 +310,7 @@ function parseWslListing(stdout, now) {
|
|
|
370
310
|
if (line.trim() === "") continue;
|
|
371
311
|
const m = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s*(.*)$/.exec(line);
|
|
372
312
|
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: "" });
|
|
313
|
+
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
314
|
}
|
|
375
315
|
return rows;
|
|
376
316
|
}
|
|
@@ -386,7 +326,7 @@ async function wslDistroRunning(run, signal) {
|
|
|
386
326
|
}
|
|
387
327
|
async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand, platform = process.platform, signal, wsl = "always") {
|
|
388
328
|
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
|
|
329
|
+
const allListings = [
|
|
390
330
|
{ source: "windows", read: async () => parseWindowsListing(await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_LISTING_SCRIPT], PROCESS_LISTING_TIMEOUT_MS, signal)) },
|
|
391
331
|
{
|
|
392
332
|
source: "wsl",
|
|
@@ -396,6 +336,7 @@ async function listProcesses(now = /* @__PURE__ */ new Date(), run = runCommand,
|
|
|
396
336
|
}
|
|
397
337
|
}
|
|
398
338
|
];
|
|
339
|
+
const listings = wsl === "never" ? allListings.filter((l) => l.source !== "wsl") : allListings;
|
|
399
340
|
const settled = await Promise.allSettled(listings.map((l) => l.read()));
|
|
400
341
|
const rows = [];
|
|
401
342
|
const unavailable = [];
|
|
@@ -410,6 +351,173 @@ async function reportOrphanProcesses(now = /* @__PURE__ */ new Date(), run = run
|
|
|
410
351
|
return { findings: findOrphans(rows, now), unavailable };
|
|
411
352
|
}
|
|
412
353
|
|
|
354
|
+
// src/machine-toolkit/probe.ts
|
|
355
|
+
var PROBE_START_TIMEOUT_MS = 15e3;
|
|
356
|
+
var TOKEN_QUERY_TIMEOUT_MS = 2e4;
|
|
357
|
+
var TOKEN_COUNT_UNSUPPORTED = "the kernel token count exists on Windows only";
|
|
358
|
+
function probeCommand(platform) {
|
|
359
|
+
return platform === "win32" ? { file: "cmd.exe", args: ["/c", "exit"] } : { file: "true", args: [] };
|
|
360
|
+
}
|
|
361
|
+
function probeProcessStart(opts) {
|
|
362
|
+
const { file, args } = probeCommand(opts.platform ?? process.platform);
|
|
363
|
+
const nowMs = opts.nowMs ?? (() => performance.now());
|
|
364
|
+
return new Promise((resolve, reject) => {
|
|
365
|
+
const startedAt = nowMs();
|
|
366
|
+
const child = opts.spawnFn(file, args, { windowsHide: true, stdio: "ignore", signal: opts.signal });
|
|
367
|
+
child.on("error", reject);
|
|
368
|
+
child.on("close", (code) => {
|
|
369
|
+
if (code !== 0) reject(Object.assign(new Error(`${file} exited ${code ?? "on a signal"}`), { code: "probe exit" }));
|
|
370
|
+
else resolve(Math.round(nowMs() - startedAt));
|
|
371
|
+
});
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
var TOKEN_PROBE_SOURCE = `using System;
|
|
375
|
+
using System.Runtime.InteropServices;
|
|
376
|
+
public static class DxTokeProbe {
|
|
377
|
+
[DllImport("ntdll.dll")] static extern int NtQuerySystemInformation(int cls, IntPtr buf, int len, out int ret);
|
|
378
|
+
public static int Main() {
|
|
379
|
+
int ret = 0; int size = 1 << 20; IntPtr buf; int st;
|
|
380
|
+
while (true) {
|
|
381
|
+
buf = Marshal.AllocHGlobal(size);
|
|
382
|
+
st = NtQuerySystemInformation(22, buf, size, out ret);
|
|
383
|
+
if (st == unchecked((int)0xC0000004)) { Marshal.FreeHGlobal(buf); size = ret + (1 << 16); continue; }
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
try {
|
|
387
|
+
if (st != 0) { Console.Error.Write("NtQuerySystemInformation status " + st); return 2; }
|
|
388
|
+
int count = Marshal.ReadInt32(buf); long off = 8;
|
|
389
|
+
for (int i = 0; i < count; i++) {
|
|
390
|
+
IntPtr p = new IntPtr(buf.ToInt64() + off);
|
|
391
|
+
if (Marshal.ReadInt32(p) == 0x656B6F54) { Console.Out.Write((long)(uint)Marshal.ReadInt32(p, 4) - (long)(uint)Marshal.ReadInt32(p, 8)); return 0; }
|
|
392
|
+
off += 40;
|
|
393
|
+
}
|
|
394
|
+
Console.Error.Write("no Toke pool tag"); return 3;
|
|
395
|
+
} finally { Marshal.FreeHGlobal(buf); }
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
`;
|
|
399
|
+
var TOKEN_COMPILE_TIMEOUT_MS = 15e3;
|
|
400
|
+
function cscPath(windir) {
|
|
401
|
+
return join5(windir ?? String.raw`C:\Windows`, "Microsoft.NET", "Framework64", "v4.0.30319", "csc.exe");
|
|
402
|
+
}
|
|
403
|
+
function tokenProbeExeName(source = TOKEN_PROBE_SOURCE) {
|
|
404
|
+
return `token-probe-${createHash("sha256").update(source).digest("hex").slice(0, 12)}.exe`;
|
|
405
|
+
}
|
|
406
|
+
var realTokenProbeFiles = {
|
|
407
|
+
exists: (path) => existsSync2(path),
|
|
408
|
+
mkdir: (dir) => void mkdirSync(dir, { recursive: true }),
|
|
409
|
+
write: (path, text) => writeFileSync(path, text, "utf-8"),
|
|
410
|
+
rename: (from, to) => renameSync(from, to)
|
|
411
|
+
};
|
|
412
|
+
async function ensureTokenProbeExe(opts) {
|
|
413
|
+
const files = opts.files ?? realTokenProbeFiles;
|
|
414
|
+
const exe = join5(opts.dir, tokenProbeExeName());
|
|
415
|
+
if (files.exists(exe)) return exe;
|
|
416
|
+
files.mkdir(opts.dir);
|
|
417
|
+
const tag = String(opts.pid ?? process.pid);
|
|
418
|
+
const source = exe.replace(/\.exe$/, ".cs");
|
|
419
|
+
const temp = join5(opts.dir, `token-probe-${tag}.tmp.exe`);
|
|
420
|
+
files.write(source, TOKEN_PROBE_SOURCE);
|
|
421
|
+
await opts.run(cscPath(opts.windir), ["-nologo", "-target:exe", `-out:${temp}`, source], TOKEN_COMPILE_TIMEOUT_MS, opts.signal);
|
|
422
|
+
files.rename(temp, exe);
|
|
423
|
+
return exe;
|
|
424
|
+
}
|
|
425
|
+
function parseTokenCount(stdout) {
|
|
426
|
+
const text = stdout.trim();
|
|
427
|
+
if (!/^-?\d+$/.test(text)) throw Object.assign(new Error(`the token query printed ${JSON.stringify(text.slice(0, 40))}`), { code: "token output" });
|
|
428
|
+
const n = Number(text);
|
|
429
|
+
if (!Number.isSafeInteger(n) || n < 0) throw Object.assign(new Error(`the token query printed ${text}`), { code: "token output" });
|
|
430
|
+
return n;
|
|
431
|
+
}
|
|
432
|
+
async function readKernelTokenCount(opts = {}) {
|
|
433
|
+
if ((opts.platform ?? process.platform) !== "win32") return { kind: "unsupported", reason: TOKEN_COUNT_UNSUPPORTED };
|
|
434
|
+
const run = opts.run ?? runCommand;
|
|
435
|
+
const exe = await ensureTokenProbeExe({ dir: opts.dir ?? join5(machineHome(), ".danxbot"), run, files: opts.files, windir: opts.windir ?? process.env.WINDIR, signal: opts.signal });
|
|
436
|
+
return { kind: "read", count: parseTokenCount(await run(exe, [], TOKEN_QUERY_TIMEOUT_MS, opts.signal)) };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// src/machine-toolkit/toolkit.ts
|
|
440
|
+
import { readFileSync as readFileSync2 } from "node:fs";
|
|
441
|
+
var PROFILE = "windows-wsl-docker";
|
|
442
|
+
function resolveToolkitVersion(stamped, readManifest) {
|
|
443
|
+
return stamped ?? readManifest();
|
|
444
|
+
}
|
|
445
|
+
var readOwnManifest = () => JSON.parse(readFileSync2(new URL("../../package.json", import.meta.url), "utf8")).version;
|
|
446
|
+
var TOOLKIT_VERSION = resolveToolkitVersion(false ? void 0 : "0.1.457", readOwnManifest);
|
|
447
|
+
function envelope(now) {
|
|
448
|
+
return { contract_version: CONTRACT_VERSION, toolkit_version: TOOLKIT_VERSION, profile: PROFILE, measured_at: now.toISOString() };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// src/machine-toolkit/health.ts
|
|
452
|
+
var HEALTH_BUDGET_MS = 1e4;
|
|
453
|
+
var HEALTH_MARGIN_MS = 1500;
|
|
454
|
+
var MIN_ORPHAN_DEADLINE_MS = 500;
|
|
455
|
+
function orphanDeadlineMs(uptimeSeconds) {
|
|
456
|
+
return Math.max(MIN_ORPHAN_DEADLINE_MS, Math.floor(HEALTH_BUDGET_MS - uptimeSeconds * 1e3 - HEALTH_MARGIN_MS));
|
|
457
|
+
}
|
|
458
|
+
var unread = (reason) => ({ metric: metricUnread(reason), items: [] });
|
|
459
|
+
async function read(reader, what) {
|
|
460
|
+
try {
|
|
461
|
+
return await reader();
|
|
462
|
+
} catch (err) {
|
|
463
|
+
return unread(err instanceof DeadlineExceeded ? err.message : `${what} failed (${errorCode(err)})`);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
async function probe(work, ms, schedule, what) {
|
|
467
|
+
const abort = new AbortController();
|
|
468
|
+
try {
|
|
469
|
+
return await withDeadline(work(abort.signal), ms, schedule, what);
|
|
470
|
+
} catch (err) {
|
|
471
|
+
abort.abort();
|
|
472
|
+
throw err;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
async function collectHealth(src, opts = {}) {
|
|
476
|
+
const now = src.now();
|
|
477
|
+
const deadlineMs = opts.deadlineMs ?? orphanDeadlineMs(process.uptime());
|
|
478
|
+
const schedule = opts.schedule ?? realScheduler;
|
|
479
|
+
const processStart = await read(async () => ({ metric: metricRead(await probe(src.processStartMs, PROBE_START_TIMEOUT_MS, schedule, "the process-start probe")), items: [] }), "timing a process start");
|
|
480
|
+
const [dataDisk, unowned, orphans, tokens] = await Promise.all([
|
|
481
|
+
read(() => {
|
|
482
|
+
const disk = src.dataDisk();
|
|
483
|
+
return disk.bytes === null ? unread(disk.unavailableReason) : { metric: metricRead(disk.bytes), items: [] };
|
|
484
|
+
}, "reading docker_data.vhdx"),
|
|
485
|
+
read(() => {
|
|
486
|
+
const flags = src.flags();
|
|
487
|
+
if (flags === null) return unread("no real Docker sweep has written docker-flags.json on this machine yet");
|
|
488
|
+
const ageMs = Math.max(0, now.getTime() - new Date(flags.at).getTime());
|
|
489
|
+
if (ageMs > FLAGS_STALE_MS) return unread(`the last Docker sweep result is ${(ageMs / 36e5).toFixed(1)} h old (older than ${FLAGS_STALE_MS / 36e5} h): the hourly sweep has stopped, so its count is stale`);
|
|
490
|
+
const ageSeconds = Math.round(ageMs / 1e3);
|
|
491
|
+
const items = flags.flagged.filter((f) => f.reason.startsWith(UNOWNED_REASON_PREFIX)).map((f) => ({ id: f.id, detail: f.reason.slice(UNOWNED_REASON_PREFIX.length) }));
|
|
492
|
+
return { metric: metricRead(flags.unowned, "cached", ageSeconds), items };
|
|
493
|
+
}, "reading the Docker flags file"),
|
|
494
|
+
read(async () => {
|
|
495
|
+
if (src.compactionWindowOpen()) return unread("a compaction window is open, so processes are not listed until it closes");
|
|
496
|
+
const report2 = await probe((signal) => src.orphans(now, signal), deadlineMs, schedule, "the process listing");
|
|
497
|
+
if (report2.unavailable.length > 0) return unread(report2.unavailable.map((u) => `${u.source} processes not listed (${u.code})`).join("; "));
|
|
498
|
+
const items = report2.findings.map((f) => ({ id: `${f.source}:${f.pid}`, detail: `${f.kind} started ${f.startedAt.toISOString()}: ${f.commandLine}` }));
|
|
499
|
+
return { metric: metricRead(items.length), items };
|
|
500
|
+
}, "listing processes"),
|
|
501
|
+
read(async () => {
|
|
502
|
+
const reading = await probe(src.kernelTokenCount, TOKEN_QUERY_TIMEOUT_MS, schedule, "the kernel token query");
|
|
503
|
+
return reading.kind === "read" ? { metric: metricRead(reading.count), items: [] } : unread(reading.reason);
|
|
504
|
+
}, "reading the kernel token count")
|
|
505
|
+
]);
|
|
506
|
+
const report = {
|
|
507
|
+
...envelope(now),
|
|
508
|
+
metrics: {
|
|
509
|
+
docker_data_disk_bytes: dataDisk.metric,
|
|
510
|
+
unowned_docker_resource_count: unowned.metric,
|
|
511
|
+
orphan_process_count: orphans.metric,
|
|
512
|
+
[PROCESS_START_METRIC]: processStart.metric,
|
|
513
|
+
[KERNEL_TOKEN_METRIC]: tokens.metric
|
|
514
|
+
},
|
|
515
|
+
items: { unowned_docker_resources: unowned.items, orphan_processes: orphans.items }
|
|
516
|
+
};
|
|
517
|
+
assertContract("health", report);
|
|
518
|
+
return report;
|
|
519
|
+
}
|
|
520
|
+
|
|
413
521
|
// src/machine-toolkit/cli.ts
|
|
414
522
|
async function runToolkitCli(args, io) {
|
|
415
523
|
const [command, ...rest] = args;
|
|
@@ -433,7 +541,9 @@ function collectFromThisMachine() {
|
|
|
433
541
|
dataDisk: () => readDockerDataDisk(),
|
|
434
542
|
flags: () => readFlags(),
|
|
435
543
|
orphans: (now, signal) => reportOrphanProcesses(now, void 0, void 0, signal, "when-running"),
|
|
436
|
-
compactionWindowOpen: () => compactionWindowOpen()
|
|
544
|
+
compactionWindowOpen: () => compactionWindowOpen(),
|
|
545
|
+
processStartMs: (signal) => probeProcessStart({ spawnFn: spawn, signal }),
|
|
546
|
+
kernelTokenCount: (signal) => readKernelTokenCount({ signal })
|
|
437
547
|
});
|
|
438
548
|
}
|
|
439
549
|
function isMainModule() {
|
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.457",
|
|
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",
|