Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Report how fast a Cloud home's machine is in its health report (#5190)
Milind Soni8181ece925a9
diff --git a/docs/cloud-pro.md b/docs/cloud-pro.mdindex a06942d645..8bb509639f 100644--- a/docs/cloud-pro.md+++ b/docs/cloud-pro.md@@ -1717,10 +1717,33 @@ wait for the next read, `truncated: true`):"firstHour": { "startedAt": 1790000000000, "apps": ["gmail"], "look": "delivered","ms": { "seen": 41000, "firstMessage": 52000, "offered": 61000, "firstApp": 118000, "firstLook": 171000, "briefOn": 172000, "phoneOffered": 172000 } },"value": { "sorted": 40, "drafted": 6, "prepped": 4, "routines": 0, "minutes": 110 },- "room": { "waits": 3, "waitMs": 360000, "stopped": 1, "killed": 1, "stallMinutes": 2 }+ "room": { "waits": 3, "waitMs": 360000, "stopped": 1, "killed": 1, "stallMinutes": 2 },+ "speed": { "windowS": 300, "steal": 1.2, "psi": { "cpu": 3.4, "memory": 0, "io": 0.8 }, "bootMs": 5400, "wakeMs": null,+ "turnStarts": [12, 3, 1, 0, 0, 0] }}```+**`speed`** says how fast the machine is for this home (`server/cloud-speed.ts`),+read from `/proc` when the report is built, with no timer or sampler of its+own. `windowS` is how many seconds the CPU figures cover: since the previous+read at least a minute before (a read sooner, such as the next page of the+same poll, repeats the last figures), or since the process started. `steal`+is the percent of all CPU time in that window the hypervisor ran something+else on this machine's CPUs (`/proc/stat`). `psi` is the percent of the window+in which some task waited for CPU, memory or disk (the kernel's pressure+`some` line, the home's own cgroup's in a container, else the machine's).+Each is `null` where the kernel doesn't expose it, and for a window whose+counter went down. `bootMs` is this process's start to its server listening;+`wakeMs`, on a boot that woke the home from a sleep it was stopped for with+a request waiting, the time from the machine's start (the process's, in a+container on a long-running server) to that request reaching the server.+Fly's own start before that, and a resume from a suspend, are not in it.+`turnStarts` counts people's messages since boot by how long each waited+from being stored to its engine's turn starting: up to 0.5, 1, 2, 5 and 15+seconds, and longer. A message sent while its thread runs a turn, a bot's, a+routine's and a steer are not counted. Older homes don't send `speed`: the+Admin reads that as unknown, never as zero.+**`room`** is the last day's memory pressure where the home watches it (a Cloudhome on Linux, `server/engine-memory.ts`), else `null`: how many tasks had towait for memory and how long they waited in all (a wait still going counts itsdiff --git a/server/cloud-health.test.ts b/server/cloud-health.test.tsindex 9ec83addb2..5a24134a54 100644--- a/server/cloud-health.test.ts+++ b/server/cloud-health.test.ts@@ -57,6 +57,20 @@ describe("a Cloud home's memory pressure in its health report", () => {});});+describe("a Cloud home's speed in its health report", () => {+ it("times a person's message to its engine's turn through the store and the bus, in a few numbers and fixed buckets", () => {+ const w = world();+ w.store.appendMessage(w.bot.threadId, { role: "user", kind: "text", text: "Sort my inbox, Tallyspoon", at: w.now() });+ w.advance(700);+ w.emit(w.bot.threadId, { type: "turn.started" });+ const { speed } = w.health.report(undefined);+ expect(speed).toMatchObject({ bootMs: null, wakeMs: null, turnStarts: [0, 1, 0, 0, 0, 0] });+ expect(Object.keys(speed).sort()).toEqual(["bootMs", "psi", "steal", "turnStarts", "wakeMs", "windowS"]);+ expect(JSON.stringify(speed)).not.toMatch(/Tallyspoon|inbox/);+ expect(JSON.stringify(speed).length).toBeLessThan(200);+ });+});+describe("a new Cloud's first hour in its health report", () => {it("carries the milestones and the Chief's counts, and null where there are none", () => {expect(world().health.report(undefined)).toMatchObject({ firstHour: null, value: null });diff --git a/server/cloud-health.ts b/server/cloud-health.tsindex bbff27e3cc..beb8cd939c 100644--- a/server/cloud-health.ts+++ b/server/cloud-health.ts@@ -12,6 +12,7 @@ import type { RoomReport } from "./engine-memory.ts";import type { FirstHourReport } from "./host/first-hour.ts";import type { ValueReport } from "./host/value-ledger.ts";import type { ProviderSnapshot, RuntimeEvent } from "./contracts.ts";+import { createCloudSpeed, type CloudSpeed } from "./cloud-speed.ts";import { classifyError } from "./drivers/retry.ts";import type { Message, StoreChange } from "./store.ts";@@ -253,6 +254,8 @@ export interface CloudHealthDeps {firstHour?: () => { firstHour?: FirstHourReport; value?: ValueReport };/** The last day's memory pressure (engine-memory.ts), where this home watches it. */room?: () => RoomReport;+ /** CPU steal and pressure, boot and wake times, and how long messages wait for their engine. */+ speed?: CloudSpeed;now?: () => number;}@@ -268,8 +271,9 @@ export function boxSummary(report: BoxReport | undefined): { box: BoxReport["boxexport function createCloudHealth(deps: CloudHealthDeps) {const now = deps.now ?? Date.now;const ledger = createCloudHealthLedger({ botOf: (threadId) => deps.store.botByThread(threadId)?.id ?? null, now });- deps.store.onChange((change) => { if (change.type === "message") ledger.noteMessage(change.threadId, change.message); });- deps.bus.subscribe((event) => ledger.noteEvent(event));+ const speed = deps.speed ?? createCloudSpeed({ now });+ deps.store.onChange((change) => { if (change.type === "message") { ledger.noteMessage(change.threadId, change.message); speed.noteMessage(change.threadId, change.message); } });+ deps.bus.subscribe((event) => { ledger.noteEvent(event); speed.noteEvent(event); });const connectors = backgroundLookup(deps.connectors, CONNECTORS_TTL_MS, now);const version = match(VERSION, deps.version) ?? "unknown", image = match(IMAGE, deps.image);@@ -290,6 +294,7 @@ export function createCloudHealth(deps: CloudHealthDeps) {return {ledger,+ speed,noteRoutineRun: ledger.noteRoutineRun,report(after: string | null | undefined) {const read = ledger.read(after);@@ -299,7 +304,7 @@ export function createCloudHealth(deps: CloudHealthDeps) {turns: read.turns, routines: read.routines, engines: engines(), connectors: connectorState(),browser: { available: browser.available, installing: browser.installing, interrupted: browser.interrupted },box: boxSummary(deps.box?.()),- firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null,+ firstHour: first?.firstHour ?? null, value: first?.value ?? null, room: deps.room?.() ?? null, speed: speed.report(),system: { ...memory, rssBytes: process.memoryUsage.rss(), load1: loadavg()[0] ?? 0, cpus: availableParallelism(), disk: diskBytes(deps.dataDir), eventLogWritable: writable(deps.eventsDir) },};let budget = CLOUD_HEALTH_MAX_BYTES - JSON.stringify({ ...base, cursor: ledger.cursor(read.seq), truncated: true, incidents: [] }).length;diff --git a/server/cloud-power.test.ts b/server/cloud-power.test.tsindex c0e1374a43..eccb0bf39c 100644--- a/server/cloud-power.test.ts+++ b/server/cloud-power.test.ts@@ -21,7 +21,7 @@ afterEach(() => {for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });});-function home(probes: Partial<CloudPowerProbes> = {}, onWoke?: () => void, bootedFromSleep = false) {+function home(probes: Partial<CloudPowerProbes> = {}, onWoke?: () => void, bootedFromSleep = false, onBootWakeRequest?: (at: number) => void) {let clock = START;const dataDir = mkdtempSync(join(tmpdir(), "omb-cloud-power-"));dirs.push(dataDir);@@ -30,7 +30,7 @@ function home(probes: Partial<CloudPowerProbes> = {}, onWoke?: () => void, booteconst power = createCloudPower({ dataDir, now: () => clock, broadcast: (payload) => sent.push(payload), probes: {turn: () => state.turn, run: () => state.run, handoff: () => state.handoff, liveCall: () => state.liveCall, computer: () => state.computer,maintenance: () => state.maintenance, nextDueAt: () => state.nextDueAt, ...probes,- }, onWoke, bootedFromSleep });+ }, onWoke, bootedFromSleep, onBootWakeRequest });powers.push(power);/** Moves the clock in ticks, as the 5-second timer would (a single big step is a resume). */const pass = (ms: number) => { for (let left = ms; left > 0; left -= 5_000) { clock += Math.min(5_000, left); power.tick(); } };@@ -53,6 +53,22 @@ describe("telling the Admin it woke", () => {plain.pass(10_000);expect(woke).toBe(2);});++ it("times only the request that a boot from a stopped sleep was waiting for: never a plain boot's, a resume's or a second one", () => {+ const requests: number[] = [];+ const plain = home({}, undefined, false, (at) => requests.push(at));+ plain.power.arrived("/api/events", {});+ expect(requests).toEqual([]);+ const fromSleep = home({}, undefined, true, (at) => requests.push(at));+ fromSleep.jump(1_200);+ fromSleep.power.arrived("/api/events", {});+ fromSleep.power.arrived("/api/sync/changes", {});+ expect(requests).toEqual([START + 1_200]);+ fromSleep.pass(5 * 60_000);+ fromSleep.jump(10 * 60_000);+ fromSleep.power.arrived("/api/events", {});+ expect(requests).toEqual([START + 1_200]);+ });});describe("the home's idle verdict", () => {diff --git a/server/cloud-power.ts b/server/cloud-power.tsindex 76d848a9ad..2048e0b8bc 100644--- a/server/cloud-power.ts+++ b/server/cloud-power.ts@@ -113,6 +113,8 @@ export function createCloudPower(options: {bootedFromSleep?: boolean;/** It just woke: the Admin hears at once, not at its next read (`createWokeNotifier`). */onWoke?: () => void;+ /** The first request after a boot from a stopped sleep reached the server, at this time: when that wake ended. */+ onBootWakeRequest?: (at: number) => void;}) {const now = options.now ?? Date.now;const bootedAt = now();@@ -121,7 +123,7 @@ export function createCloudPower(options: {let sleptUntil: number | null = options.bootedFromSleep ? bootedAt : null;if (options.bootedFromSleep) options.onWoke?.();/** The first request since `wokeAt` (`arrived`), and whether one came. */- let wokeBy: CloudPowerReport["wokeBy"] = null, wokeSeen = false;+ let wokeBy: CloudPowerReport["wokeBy"] = null, wokeSeen = false, bootWake = Boolean(options.bootedFromSleep);let sleepingSince: number | null = null, inFlight = 0;let sleepAbort = new AbortController();let lastTick = now();@@ -155,6 +157,7 @@ export function createCloudPower(options: {wokeAt = at;wokeBy = null;wokeSeen = false;+ bootWake = false;sleptUntil = at;endSleep();options.onWoke?.();@@ -205,6 +208,7 @@ export function createCloudPower(options: {if (wokeSeen || at - wokeAt > WOKE_BY_MS) return;wokeSeen = true;wokeBy = { by: wakeCode(path), background: !countsAsActivity(path, headers) };+ if (bootWake) options.onBootWakeRequest?.(at);},/** An authenticated request: someone using the home (`countsAsActivity`), and work in progress until it ends. */request(path: string, headers: IncomingHttpHeaders, res: Pick<ServerResponse, "once">) {diff --git a/server/cloud-speed.test.ts b/server/cloud-speed.test.tsnew file mode 100644index 0000000000..c12b0ba8b3--- /dev/null+++ b/server/cloud-speed.test.ts@@ -0,0 +1,170 @@+import { describe, expect, it } from "vitest";+import { SPEED_MIN_WINDOW_MS, TURN_START_BUCKETS_MS, createCloudSpeed, parseCpuStat, parsePressureTotal } from "./cloud-speed.ts";++const START = 1_800_000_000_000;++/** /proc/stat as a Fly machine with 2 shared CPUs shows it: user nice system idle iowait irq softirq steal guest guest_nice. */+const stat = (busy: number, idle: number, steal: number) => [+ `cpu ${busy} 0 0 ${idle} 0 0 0 ${steal} 0 0`,+ `cpu0 ${busy / 2} 0 0 ${idle / 2} 0 0 0 ${steal / 2} 0 0`,+ `cpu1 ${busy / 2} 0 0 ${idle / 2} 0 0 0 ${steal / 2} 0 0`,+ "intr 123456 0 0", "ctxt 987654", "btime 1799990000", "processes 4242", "procs_running 1", "procs_blocked 0", "",+].join("\n");+/** A pressure file; `full` is absent from the cpu file on kernels before 5.13. */+const pressure = (someTotal: number) => `some avg10=1.00 avg60=0.50 avg300=0.25 total=${someTotal}\nfull avg10=0.00 avg60=0.00 avg300=0.00 total=0\n`;++/** A machine whose /proc files the test sets, and the clocks the speed reads. */+function machine(files: Record<string, string>, uptimes: { machine: number; process: number } = { machine: 30, process: 4.2 }) {+ let wall = START, mono = 0;+ const speed = createCloudSpeed({ read: (path) => files[path] ?? null, now: () => wall, monotonic: () => mono,+ machineUptime: () => uptimes.machine, processUptime: () => uptimes.process });+ return { speed, files, pass: (ms: number) => { wall += ms; mono += ms; }, now: () => wall };+}++describe("reading /proc", () => {+ it("takes all CPU time and the stolen part from the first line, and nothing from a line it can't read", () => {+ expect(parseCpuStat(stat(600, 300, 100))).toEqual({ total: 1000, steal: 100 });+ // Guest time is counted inside user time already, so it never adds to the total.+ expect(parseCpuStat("cpu 100 0 50 800 0 0 0 50 40 0\n")).toEqual({ total: 1000, steal: 50 });+ // A kernel too old to count steal still gives the total.+ expect(parseCpuStat("cpu 100 0 50 850\n")).toEqual({ total: 1000, steal: null });+ expect(parseCpuStat("")).toBeNull();+ expect(parseCpuStat("cpu a b c d\n")).toBeNull();+ });++ it("takes the pressure file's cumulative \"some\" stall, in microseconds", () => {+ expect(parsePressureTotal(pressure(123_456))).toBe(123_456);+ expect(parsePressureTotal("full avg10=0.00 avg60=0.00 avg300=0.00 total=9\n")).toBeNull();+ expect(parsePressureTotal("")).toBeNull();+ });+});++describe("CPU steal and pressure", () => {+ it("is the share of CPU time stolen and of wall time stalled since the last read, a minute or more ago", () => {+ const m = machine({ "/proc/stat": stat(1000, 8000, 0), "/proc/pressure/cpu": pressure(0), "/proc/pressure/memory": pressure(0), "/proc/pressure/io": pressure(0) });+ m.pass(300_000);+ m.files["/proc/stat"] = stat(1000 + 3000, 8000 + 1000, 1000);+ m.files["/proc/pressure/cpu"] = pressure(45_000_000);+ m.files["/proc/pressure/memory"] = pressure(3_000_000);+ m.files["/proc/pressure/io"] = pressure(0);+ expect(m.speed.report()).toMatchObject({ windowS: 300, steal: 20, psi: { cpu: 15, memory: 1, io: 0 } });+ // A read a few seconds later (a paged answer) keeps those figures and leaves the window where it was.+ m.pass(5_000);+ m.files["/proc/stat"] = stat(4000, 9000, 1100);+ expect(m.speed.report()).toMatchObject({ windowS: 300, steal: 20 });+ // The next window starts where the last full one ended, so the steal seen in between counts in it.+ m.pass(SPEED_MIN_WINDOW_MS);+ m.files["/proc/stat"] = stat(4900, 9900, 1200);+ expect(m.speed.report()).toMatchObject({ windowS: 65, steal: 10 });+ });++ it("reads a container's own cgroup pressure before the whole machine's", () => {+ const m = machine({ "/proc/stat": stat(1000, 1000, 0), "/sys/fs/cgroup/cpu.pressure": pressure(0), "/proc/pressure/cpu": pressure(0) });+ m.pass(100_000);+ m.files["/sys/fs/cgroup/cpu.pressure"] = pressure(50_000_000);+ m.files["/proc/pressure/cpu"] = pressure(1_000_000);+ expect(m.speed.report().psi.cpu).toBe(50);+ });++ it("says null for pressure the kernel doesn't expose, and for steal without /proc/stat (not Linux)", () => {+ const m = machine({ "/proc/stat": stat(1000, 1000, 0) });+ m.pass(100_000);+ m.files["/proc/stat"] = stat(2000, 1500, 500);+ expect(m.speed.report()).toMatchObject({ steal: 25, psi: { cpu: null, memory: null, io: null } });+ const bare = machine({});+ bare.pass(100_000);+ expect(bare.speed.report()).toMatchObject({ windowS: 100, steal: null, psi: { cpu: null, memory: null, io: null } });+ });++ it("says nothing for a window whose counters went down (wrapped or reset), then counts again from there", () => {+ const m = machine({ "/proc/stat": stat(9_000, 9_000, 900), "/proc/pressure/cpu": pressure(80_000_000) });+ m.pass(100_000);+ m.files["/proc/stat"] = stat(100, 100, 10);+ m.files["/proc/pressure/cpu"] = pressure(1_000);+ expect(m.speed.report()).toMatchObject({ steal: null, psi: { cpu: null } });+ m.pass(100_000);+ m.files["/proc/stat"] = stat(1_100, 1_000, 110);+ m.files["/proc/pressure/cpu"] = pressure(10_001_000);+ expect(m.speed.report()).toMatchObject({ steal: 5, psi: { cpu: 10 } });+ });+});++describe("boot and wake", () => {+ it("is null until the server listens, then this process's start to listening", () => {+ const m = machine({});+ expect(m.speed.report()).toMatchObject({ bootMs: null, wakeMs: null });+ m.speed.ready();+ expect(m.speed.report()).toMatchObject({ bootMs: 4200, wakeMs: null });+ });++ it("times a wake from the machine's start when the process started with it, to the waiting request reaching the server", () => {+ const m = machine({}, { machine: 9.5, process: 4.2 });+ m.speed.ready();+ m.pass(300);+ m.speed.wakeRequest(m.now());+ expect(m.speed.report().wakeMs).toBe(9_800);+ m.pass(1_000);+ m.speed.wakeRequest(m.now());+ expect(m.speed.report().wakeMs).toBe(9_800);+ });++ it("times it from the process's start in a container on a server up for days", () => {+ const m = machine({}, { machine: 400_000, process: 6 });+ m.speed.ready();+ m.speed.wakeRequest(m.now() + 100);+ expect(m.speed.report().wakeMs).toBe(6_100);+ });++ it("is no wake when the first request came long after the boot (the Admin woke it with nothing waiting)", () => {+ const m = machine({}, { machine: 9.5, process: 4.2 });+ m.speed.ready();+ m.pass(60_000);+ m.speed.wakeRequest(m.now());+ expect(m.speed.report().wakeMs).toBeNull();+ });+});++describe("turn starts", () => {+ const person = { role: "user" as const, kind: "text" as const };+ const started = (threadId: string) => ({ type: "turn.started" as const, threadId });+ const completed = (threadId: string) => ({ type: "turn.completed" as const, threadId });+ const buckets = (counts: Record<number, number>) => Array.from({ length: TURN_START_BUCKETS_MS.length + 1 }, (_, index) => counts[index] ?? 0);++ it("counts how long a person's message waited for its engine's turn to start, in fixed buckets", () => {+ const m = machine({});+ for (const [thread, waited] of [["a", 120], ["b", 900], ["c", 4_000], ["d", 40_000]] as const) {+ m.speed.noteMessage(thread, { ...person, at: m.now() });+ m.pass(waited);+ m.speed.noteEvent(started(thread));+ }+ expect(m.speed.report().turnStarts).toEqual(buckets({ 0: 1, 1: 1, 3: 1, 5: 1 }));+ });++ it("leaves out a message sent while its thread runs a turn, a bot's, a peer's, a routine's and a steer, and counts the thread again once it is idle", () => {+ const m = machine({});+ m.speed.noteEvent(started("a"));+ m.speed.noteMessage("a", { ...person, at: m.now() });+ m.speed.noteMessage("b", { role: "bot", kind: "text", at: m.now() });+ m.speed.noteMessage("c", { ...person, at: m.now(), from: { botId: "peer" } as never });+ m.speed.noteMessage("d", { ...person, at: m.now(), steered: true });+ m.speed.noteMessage("e", { ...person, at: m.now(), automation: {} as never });+ m.pass(30_000);+ for (const thread of ["b", "c", "d", "e"]) m.speed.noteEvent(started(thread));+ m.speed.noteEvent(completed("a"));+ m.speed.noteEvent(started("a"));+ expect(m.speed.report().turnStarts).toEqual(buckets({}));+ m.speed.noteEvent(completed("a"));+ m.speed.noteMessage("a", { ...person, at: m.now() });+ m.pass(1_500);+ m.speed.noteEvent(started("a"));+ expect(m.speed.report().turnStarts).toEqual(buckets({ 2: 1 }));+ });++ it("drops a message whose turn never started", () => {+ const m = machine({});+ m.speed.noteMessage("a", { ...person, at: m.now() });+ m.pass(31 * 60_000);+ m.speed.noteEvent(started("a"));+ expect(m.speed.report().turnStarts).toEqual(buckets({}));+ });+});diff --git a/server/cloud-speed.ts b/server/cloud-speed.tsnew file mode 100644index 0000000000..3bd8bded1c--- /dev/null+++ b/server/cloud-speed.ts@@ -0,0 +1,155 @@+// How fast a Cloud home is, for the Admin's health read. Privacy invariant: numbers and+// fixed-bucket counts only, never what a message said, which bot it was for or where it came from. Everything is read+// when the report is built or counted on events the server already has: no timer and no sampler of its own.+import { readFileSync } from "node:fs";+import { uptime } from "node:os";+import type { RuntimeEvent } from "./contracts.ts";+import type { Message } from "./store.ts";++/** Upper bounds of the turn-start buckets (ms); one more bucket counts everything slower. The Admin reads the same edges. */+export const TURN_START_BUCKETS_MS = [500, 1_000, 2_000, 5_000, 15_000] as const;+/** A read this soon after the last one keeps that one's CPU figures: a window this short says little. */+export const SPEED_MIN_WINDOW_MS = 60_000;+/** A process that came up this soon after its kernel booted started with its machine (a Fly machine start), so a wake's+ * time runs from the kernel's start; anywhere else (a container on a long-running server) it runs from the process's. */+const WITH_MACHINE_MS = 120_000;+/** The first request this soon after the server listens is the one that woke the home; a later one found it awake. */+const WAKE_REQUEST_MS = 5_000;+/** A person's message whose turn has not started after this long never will (refused, a setup card): it is dropped. */+const ACCEPTED_TTL_MS = 30 * 60_000;+const ACCEPTED_CAP = 500;+/** A turn whose end never came through is taken as over after this long, so its thread is timed again. */+const LIVE_TTL_MS = 6 * 3_600_000;+const PSI_RESOURCES = ["cpu", "memory", "io"] as const;+type PsiResource = (typeof PSI_RESOURCES)[number];++export interface SpeedReport {+ /** Seconds the CPU figures cover: since the previous read at least a minute before, else since this process started. */+ windowS: number | null;+ /** Percent of all CPU time in the window the hypervisor ran something else on this machine's CPUs (steal). */+ steal: number | null;+ /** Percent of the window in which some task waited for CPU, memory or disk (the kernel's pressure "some" line); null+ * for a resource whose pressure the kernel doesn't expose. */+ psi: Record<PsiResource, number | null>;+ /** From this process's start to its server listening, ms. */+ bootMs: number | null;+ /** This boot woke the home from a sleep it was stopped for, and a request was waiting: ms from the machine's start+ * (or this process's, see WITH_MACHINE_MS) to that request reaching the server. */+ wakeMs: number | null;+ /** People's messages since this boot by how long they waited from being stored to their engine's turn starting, in+ * TURN_START_BUCKETS_MS order. */+ turnStarts: number[];+}++/** `/proc/stat`'s first line: all CPU time and the stolen part, in USER_HZ ticks. Guest time is inside user time already. */+export function parseCpuStat(text: string): { total: number; steal: number | null } | null {+ const fields = /^cpu\s+([\d\s]+)$/m.exec(text)?.[1]?.trim().split(/\s+/).map(Number);+ if (!fields || fields.length < 4 || fields.some((value) => !Number.isFinite(value))) return null;+ return { total: fields.slice(0, 8).reduce((sum, value) => sum + value, 0), steal: fields.length >= 8 ? fields[7]! : null };+}++/** A pressure file's cumulative "some" stall time, in microseconds. */+export function parsePressureTotal(text: string): number | null {+ const total = /^some\b.*\btotal=(\d+)/m.exec(text)?.[1];+ return total === undefined ? null : Number(total);+}++/** The pressure file of this home's own cgroup when it has one (a container), else the whole machine's. Kept for the+ * process's life, so every window compares one counter with itself. */+function pressurePath(resource: PsiResource, read: (path: string) => string | null): string | null {+ return [`/sys/fs/cgroup/${resource}.pressure`, `/proc/pressure/${resource}`].find((path) => {+ const text = read(path);+ return text !== null && parsePressureTotal(text) !== null;+ }) ?? null;+}++interface Sample { at: number; cpu: { total: number; steal: number | null } | null; psi: Record<PsiResource, number | null> }++const percent = (value: number) => Math.round(Math.min(100, Math.max(0, value)) * 10) / 10;+/** A counter that went down (wrapped, or the kernel's view reset) says nothing about this window. */+const grew = (before: number | null | undefined, after: number | null | undefined): number | null =>+ before === null || before === undefined || after === null || after === undefined || after < before ? null : after - before;++const readText = (path: string): string | null => { try { return readFileSync(path, "utf8"); } catch { return null; } };++export function createCloudSpeed(options: {+ read?: (path: string) => string | null;+ /** Wall clock, as the store stamps messages. */+ now?: () => number;+ /** A clock that only moves forward, for the windows. */+ monotonic?: () => number;+ /** Seconds since the kernel booted, and since this process started. */+ machineUptime?: () => number;+ processUptime?: () => number;+} = {}) {+ const read = options.read ?? readText, now = options.now ?? Date.now, monotonic = options.monotonic ?? (() => performance.now());+ const machineUptime = options.machineUptime ?? uptime, processUptime = options.processUptime ?? (() => process.uptime());+ const paths = Object.fromEntries(PSI_RESOURCES.map((resource) => [resource, pressurePath(resource, read)])) as Record<PsiResource, string | null>;+ const sample = (): Sample => {+ const stat = read("/proc/stat");+ const psi = Object.fromEntries(PSI_RESOURCES.map((resource) => {+ const text = paths[resource] ? read(paths[resource]) : null;+ return [resource, text === null ? null : parsePressureTotal(text)];+ })) as Record<PsiResource, number | null>;+ return { at: monotonic(), cpu: stat === null ? null : parseCpuStat(stat), psi };+ };+ let base = sample(), last: Pick<SpeedReport, "windowS" | "steal" | "psi"> | null = null;+ let bootMs: number | null = null, wakeFrom: number | null = null, readyAt: number | null = null, wakeMs: number | null = null;++ const turnStarts: number[] = Array.from({ length: TURN_START_BUCKETS_MS.length + 1 }, () => 0);+ const accepted = new Map<string, number>(), live = new Map<string, number>();++ const cpuFigures = (): Pick<SpeedReport, "windowS" | "steal" | "psi"> => {+ const current = sample(), ms = current.at - base.at;+ if (last && ms < SPEED_MIN_WINDOW_MS) return last;+ const total = grew(base.cpu?.total, current.cpu?.total), stolen = grew(base.cpu?.steal, current.cpu?.steal);+ const psi = Object.fromEntries(PSI_RESOURCES.map((resource) => {+ const stalled = grew(base.psi[resource], current.psi[resource]);+ return [resource, stalled === null || ms <= 0 ? null : percent(stalled / (ms * 10))];+ })) as Record<PsiResource, number | null>;+ base = current;+ last = { windowS: ms > 0 ? Math.round(ms / 1000) : null, steal: total && stolen !== null ? percent(stolen / total * 100) : null, psi };+ return last;+ };++ return {+ /** The server listens: this boot's time, and where a wake's time starts. */+ ready() {+ if (readyAt !== null) return;+ readyAt = now();+ const processSeconds = processUptime(), machineSeconds = machineUptime();+ bootMs = Math.round(processSeconds * 1000);+ wakeFrom = readyAt - Math.round((machineSeconds - processSeconds < WITH_MACHINE_MS / 1000 ? machineSeconds : processSeconds) * 1000);+ },+ /** The first request after a boot from a stopped sleep reached the server. */+ wakeRequest(at: number) {+ if (readyAt === null || wakeFrom === null || wakeMs !== null || at - readyAt > WAKE_REQUEST_MS) return;+ wakeMs = Math.max(0, at - wakeFrom);+ },+ /** A person's message, stored while its thread runs no turn, waits for its turn to start. */+ noteMessage(threadId: string, message: Pick<Message, "at" | "role" | "kind" | "steered" | "aside" | "from" | "peerAsk" | "automation">) {+ if (message.role !== "user" || message.kind !== "text" || message.steered || message.aside || message.from?.botId || message.peerAsk || message.automation) return;+ if ((live.get(threadId) ?? -Infinity) > now() - LIVE_TTL_MS || accepted.has(threadId)) return;+ for (const [id, at] of accepted) if (at < now() - ACCEPTED_TTL_MS || accepted.size >= ACCEPTED_CAP) accepted.delete(id); else break;+ accepted.set(threadId, message.at);+ },+ noteEvent(event: Pick<RuntimeEvent, "type" | "threadId">) {+ if (event.type === "turn.completed") { live.delete(event.threadId); return; }+ if (event.type !== "turn.started") return;+ live.delete(event.threadId);+ live.set(event.threadId, now());+ if (live.size > ACCEPTED_CAP) live.delete(live.keys().next().value as string);+ const at = accepted.get(event.threadId);+ if (at === undefined) return;+ accepted.delete(event.threadId);+ const waited = now() - at;+ if (waited < 0 || waited > ACCEPTED_TTL_MS) return;+ const bucket = TURN_START_BUCKETS_MS.findIndex((edge) => waited <= edge);+ turnStarts[bucket === -1 ? TURN_START_BUCKETS_MS.length : bucket]! += 1;+ },+ report(): SpeedReport {+ return { ...cpuFigures(), bootMs, wakeMs, turnStarts: [...turnStarts] };+ },+ };+}+export type CloudSpeed = ReturnType<typeof createCloudSpeed>;diff --git a/server/index.ts b/server/index.tsindex 9c1be57efc..c1f482d8d5 100644--- a/server/index.ts+++ b/server/index.ts@@ -15430,13 +15430,13 @@ restoreChannelMessages();if (movedAutoPins) console.log(`Works on: moved ${movedAutoPins} auto-pinned thread(s) to their bot's current Works on`);}-if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATA_DIR, broadcast: (payload) => broadcast(payload), log: (line) => console.warn(line), bootedFromSleep: startedFromSleep, onWoke: createWokeNotifier({ adminOrigin: CLOUD_HOME.adminOrigin, machineId: CLOUD_HOME.machineId, secret: CLOUD_HOME.bootstrapSecret, log: (line) => console.warn(line) }), probes: {+if (CLOUD_HOME) registerCloudPower(cloudPower = createCloudPower({ dataDir: DATA_DIR, broadcast: (payload) => broadcast(payload), log: (line) => console.warn(line), bootedFromSleep: startedFromSleep, onBootWakeRequest: (at) => cloudHealth?.speed.wakeRequest(at), onWoke: createWokeNotifier({ adminOrigin: CLOUD_HOME.adminOrigin, machineId: CLOUD_HOME.machineId, secret: CLOUD_HOME.bootstrapSecret, log: (line) => console.warn(line) }), probes: {turn: () => store.bots.some((bot) => botHasActiveTurn(bot.id)) || store.groups.some(groupIsWorking), run: () => Boolean(routines?.hasActiveRuns()), handoff: () => coordinator.pace() === "busy",liveCall: () => liveCalls.current() !== null, computer: () => cloudComputerPower.awake() || boatLifecycleBusyBots.size > 0, nextDueAt: () => { const due = [routines?.nextDueAt() ?? null, proactive.brief.nextWakeAt(), botWaits.nextWakeAt()].filter((at): at is number => at !== null); return due.length ? Math.min(...due) : null; },maintenance: () => workspaceMaintenance.active || providerFleetReloading || providerAuthSessions.active || browserEngineInstall !== null } }));server.listen(PORT, listenHost(server), async () => {- companyRuntimeReady();+ companyRuntimeReady(); cloudHealth?.speed.ready();console.log(`openmausbot server on http://127.0.0.1:${PORT}`);personWaits.boot(); browserSweep.start(); startCloudTeamPolicy({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, managed: managedPolicy, sessions }); moveFreeze.hold(() => appTriggers.start(), () => void appTriggers.stop()); startCloudHomeConnectedApps({ cloudHome: CLOUD_HOME !== null, dataDir: DATA_DIR, cloudGrant: CLOUD_ENV.OMB_CLOUD_CONNECTED_APPS_GRANT, apply: (access) => { composio.setManagedBrokerAccess(access); broadcast({ kind: "config", ...configStatus() }); } });void afterFirstEngineRead().then(() => { if (builtInBrowserEnabled(cfg)) chromeLauncher.start(); });