@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.fb770705136a

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.
Files changed (37) hide show
  1. package/dist/bridge/bridge.service.d.ts +3 -1
  2. package/dist/bridge/bridge.service.js +11 -2
  3. package/dist/bridge/bridge.types.d.ts +6 -0
  4. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  5. package/dist/runtime/host-database-capability-boundary.js +1 -0
  6. package/dist/runtime/host-facts.d.ts +35 -0
  7. package/dist/runtime/host-facts.js +95 -0
  8. package/dist/runtime/host-load-sampler.d.ts +83 -0
  9. package/dist/runtime/host-load-sampler.js +164 -0
  10. package/dist/runtime/host-pressure-stall.d.ts +41 -0
  11. package/dist/runtime/host-pressure-stall.js +121 -0
  12. package/dist/runtime/host-runtime-contract.d.ts +1 -0
  13. package/dist/runtime/host-runtime-contract.js +2 -0
  14. package/dist/session/phase-completion.artifacts.js +4 -0
  15. package/dist/session/pre-publication-process.js +2 -1
  16. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  17. package/dist/session/pre-publication-skipped-tests.js +109 -0
  18. package/dist/session/pre-publication-validation.js +23 -4
  19. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  20. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  21. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  22. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  23. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  24. package/dist/session/provider-cli/provider-cli.process.js +120 -28
  25. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  26. package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
  27. package/dist/session/provider-cli/provider-cli.service.js +105 -19
  28. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  29. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  30. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  31. package/dist/session/provider-cli/provider-output-state.js +9 -0
  32. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  33. package/dist/session/publishable-worktree-changes.js +193 -0
  34. package/dist/session/session.types.js +12 -0
  35. package/dist/version.d.ts +1 -1
  36. package/dist/version.js +1 -1
  37. package/package.json +1 -1
@@ -7,6 +7,7 @@ import type { SandboxPreflightResult } from "../sandbox/sandbox.types.js";
7
7
  import { type SandboxRuntime } from "../sandbox/runtime.js";
8
8
  import type { BridgeConnection, BridgeConnectionFactory, BridgeService } from "./bridge.base.js";
9
9
  import { type RunnerHostCapabilityProbe } from "./runner-host-capabilities.js";
10
+ import { type HostLoadSource } from "../runtime/host-load-sampler.js";
10
11
  import type { BridgeCancelHandler, BridgeChatTurnHandler, BridgeDispatchHandler, BridgeLeaseUpdateRequest, BridgeReapRequest, BridgeServiceConfig } from "./bridge.types.js";
11
12
  import { type ReadinessResultOutbox } from "./readiness-result-outbox.js";
12
13
  import { type DispatchResultOutbox } from "./dispatch-result-outbox.js";
@@ -29,6 +30,7 @@ export declare class ForgeBridgeService implements BridgeService {
29
30
  private readonly connections;
30
31
  private readonly hostCapabilityProbe;
31
32
  private readonly chatProcessRunner;
33
+ private readonly hostLoad;
32
34
  private connection;
33
35
  private heartbeatTimer;
34
36
  private heartbeatInFlight;
@@ -60,7 +62,7 @@ export declare class ForgeBridgeService implements BridgeService {
60
62
  private hostCapabilities;
61
63
  private readonly recoveredHostAttempts;
62
64
  private hostCapabilitiesDetected;
63
- constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox);
65
+ constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox, hostLoad?: HostLoadSource);
64
66
  connectOnce(): Promise<void>;
65
67
  private rememberRecoveredHostAttempts;
66
68
  private recoveredHostAttemptsForHello;
@@ -33,6 +33,7 @@ import { codexSandboxProviderAuthAdapter, sandboxProviderAuthAdapterFor, sandbox
33
33
  import { assertBridgeChatCallbackPayload, bridgeChatMaxProviderThreadIdChars, bridgeChatProtocolVersion, isTerminalChatTurnCallbackKind, parseChatTurnDispatchPacket, } from "./bridge-chat.types.js";
34
34
  import { formatBytes } from "../shared/format/format-bytes.js";
35
35
  import { emptyRunnerHostCapabilitySnapshot, ProcessRunnerHostCapabilityProbe, } from "./runner-host-capabilities.js";
36
+ import { HostLoadSampler } from "../runtime/host-load-sampler.js";
36
37
  import { FileReadinessResultOutbox } from "./readiness-result-outbox.js";
37
38
  import { dispatchResultQuarantineDirectory, FileDispatchResultOutbox } from "./dispatch-result-outbox.js";
38
39
  /**
@@ -53,6 +54,7 @@ export class ForgeBridgeService {
53
54
  connections;
54
55
  hostCapabilityProbe;
55
56
  chatProcessRunner;
57
+ hostLoad;
56
58
  connection = null;
57
59
  heartbeatTimer = null;
58
60
  heartbeatInFlight = false;
@@ -87,11 +89,12 @@ export class ForgeBridgeService {
87
89
  // leaves those attempts on Forge's conservative unknown-outcome path.
88
90
  recoveredHostAttempts = new Map();
89
91
  hostCapabilitiesDetected = false;
90
- constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox) {
92
+ constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox, hostLoad = new HostLoadSampler()) {
91
93
  this.config = config;
92
94
  this.connections = connections;
93
95
  this.hostCapabilityProbe = hostCapabilityProbe;
94
96
  this.chatProcessRunner = chatProcessRunner;
97
+ this.hostLoad = hostLoad;
95
98
  this.enforceHostDatabaseCapabilityBoundary = sessions === undefined;
96
99
  if (this.enforceHostDatabaseCapabilityBoundary) {
97
100
  establishHostDatabaseCapabilityBoundary();
@@ -156,6 +159,9 @@ export class ForgeBridgeService {
156
159
  this.hostCapabilities = await this.hostCapabilityProbe.detect(this.config);
157
160
  this.hostCapabilitiesDetected = true;
158
161
  }
162
+ // Static host facts and the first load sample ride on Hello; the sampler
163
+ // keeps refreshing its cached snapshot for later heartbeats.
164
+ await this.hostLoad.start().catch(() => undefined);
159
165
  const connection = this.connections.create(this.config);
160
166
  this.connection = connection;
161
167
  this.transportRecovery = null;
@@ -306,6 +312,7 @@ export class ForgeBridgeService {
306
312
  this.abortActiveSessions("bridge stopping");
307
313
  this.abortActiveReadinessProbes("bridge stopping");
308
314
  await this.stopConnection();
315
+ this.hostLoad.stop();
309
316
  await this.preflight.release();
310
317
  }
311
318
  async handleChatTurn(rawDispatch) {
@@ -1686,7 +1693,7 @@ export class ForgeBridgeService {
1686
1693
  pendingCommitmentMemoryBytes: Math.max(0, used.memoryBytes - activeResources.memoryBytes),
1687
1694
  }) : null;
1688
1695
  return {
1689
- schemaVersion: 6,
1696
+ schemaVersion: 7,
1690
1697
  activeSessionCount: this.activeSessions.size,
1691
1698
  cliProviders: this.config.cliProviders,
1692
1699
  providerStatuses: this.config.providerStatuses,
@@ -1709,6 +1716,8 @@ export class ForgeBridgeService {
1709
1716
  playwrightProjects: this.hostCapabilities.playwrightProjects,
1710
1717
  browserLaunch: this.hostCapabilities.browserLaunch,
1711
1718
  providerConnectivity: this.hostCapabilities.providerConnectivity,
1719
+ host: this.hostLoad.facts(),
1720
+ load: this.hostLoad.current(),
1712
1721
  maxConcurrentSandboxes: capacity.sandboxSlots,
1713
1722
  reservedSandboxCount: reserved,
1714
1723
  activeSandboxCount: runtimeState.active,
@@ -3,6 +3,8 @@ import type { SandboxFeatureMatrix } from "../sandbox/sandbox.types.js";
3
3
  import type { HostRuntimeCapacitySnapshot } from "../runtime/host-runtime-lease.js";
4
4
  import type { MemoryAdmissionDiagnostics } from "../runtime/memory-capacity.js";
5
5
  import type { DockerEngineCapabilitySnapshot } from "../runtime/docker-engine-probe.js";
6
+ import type { HostFacts } from "../runtime/host-facts.js";
7
+ import type { HostLoadSnapshot } from "../runtime/host-load-sampler.js";
6
8
  import type { BridgeChatCapability, ChatTurnCancelPacket } from "./bridge-chat.types.js";
7
9
  export interface BridgeServiceConfig {
8
10
  readonly serverUrl: string;
@@ -142,6 +144,10 @@ export interface BridgeCapabilities {
142
144
  readonly playwrightProjects?: readonly string[] | null;
143
145
  readonly browserLaunch?: boolean | null;
144
146
  readonly providerConnectivity?: Readonly<Record<string, boolean>> | null;
147
+ /** Static host hardware facts (schema 7). Material: changes are persisted immediately. */
148
+ readonly host?: HostFacts | null;
149
+ /** Live host load sample (schema 7). Never material: heartbeats with only load changes are not persisted. */
150
+ readonly load?: HostLoadSnapshot | null;
145
151
  }
146
152
  export interface SandboxMemoryCapacityDiagnostics {
147
153
  readonly defaultWorkerMemoryLimitBytes: number;
@@ -1,4 +1,4 @@
1
- export declare const hostDatabaseCapabilityEnvironmentNames: readonly ["FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING", "FORGE_TEST_POSTGRES_CONNECTION_STRING"];
1
+ export declare const hostDatabaseCapabilityEnvironmentNames: readonly ["FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING", "FORGE_TEST_POSTGRES_CONNECTION_STRING", "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING"];
2
2
  export interface HostDatabaseCapabilityBoundaryOptions {
3
3
  readonly platform?: NodeJS.Platform;
4
4
  readonly processEnvironment?: NodeJS.ProcessEnv;
@@ -3,6 +3,7 @@ import path from "node:path";
3
3
  export const hostDatabaseCapabilityEnvironmentNames = [
4
4
  "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING",
5
5
  "FORGE_TEST_POSTGRES_CONNECTION_STRING",
6
+ "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING",
6
7
  ];
7
8
  const boundaryAttestationEnvironment = "FORGE_HOST_DATABASE_CAPABILITY_BOUNDARY";
8
9
  const boundaryAttestationValue = "user_store_clear";
@@ -0,0 +1,35 @@
1
+ import os from "node:os";
2
+ /** Static hardware and OS facts a bridge host reports once per process (decision 0013). */
3
+ export interface HostFacts {
4
+ readonly cpuModel: string | null;
5
+ readonly physicalCores: number | null;
6
+ readonly logicalThreads: number;
7
+ readonly totalMemoryBytes: number;
8
+ readonly architecture: string;
9
+ readonly platform: string;
10
+ readonly osName: string | null;
11
+ readonly kernelVersion: string | null;
12
+ readonly psiAvailable: boolean;
13
+ }
14
+ export type HostFileReader = (filePath: string) => Promise<string>;
15
+ export interface HostEnvironment {
16
+ readonly platform: NodeJS.Platform;
17
+ readonly procRoot: string;
18
+ readonly etcRoot: string;
19
+ readonly cgroupRoot: string;
20
+ readonly readFile: HostFileReader;
21
+ readonly cpus: () => readonly Pick<os.CpuInfo, "model">[];
22
+ readonly totalMemoryBytes: () => number;
23
+ readonly freeMemoryBytes: () => number;
24
+ readonly architecture: () => string;
25
+ readonly kernelRelease: () => string;
26
+ readonly osType: () => string;
27
+ readonly osVersion: () => string;
28
+ }
29
+ export declare function defaultHostEnvironment(overrides?: Partial<HostEnvironment>): HostEnvironment;
30
+ export declare function detectHostFacts(environment?: HostEnvironment): Promise<HostFacts>;
31
+ /** PSI is available when the system-wide CPU pressure file exists and parses. */
32
+ export declare function probePsi(environment: HostEnvironment): Promise<boolean>;
33
+ export declare function readOptional(environment: HostEnvironment, filePath: string): Promise<string | null>;
34
+ /** Counts unique (physical id, core id) pairs; null when the topology is not exposed. */
35
+ export declare function physicalCoreCount(cpuinfo: string): number | null;
@@ -0,0 +1,95 @@
1
+ import fs from "node:fs/promises";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { parsePressureStall } from "./host-pressure-stall.js";
5
+ export function defaultHostEnvironment(overrides = {}) {
6
+ return {
7
+ platform: process.platform,
8
+ procRoot: "/proc",
9
+ etcRoot: "/etc",
10
+ cgroupRoot: "/sys/fs/cgroup",
11
+ readFile: filePath => fs.readFile(filePath, "utf8"),
12
+ cpus: () => os.cpus(),
13
+ totalMemoryBytes: () => os.totalmem(),
14
+ freeMemoryBytes: () => os.freemem(),
15
+ architecture: () => os.arch(),
16
+ kernelRelease: () => os.release(),
17
+ osType: () => os.type(),
18
+ osVersion: () => os.version(),
19
+ ...overrides,
20
+ };
21
+ }
22
+ export async function detectHostFacts(environment = defaultHostEnvironment()) {
23
+ const cpus = safe(() => environment.cpus(), []);
24
+ const linux = environment.platform === "linux";
25
+ const [cpuinfo, osRelease, psiAvailable] = linux
26
+ ? await Promise.all([
27
+ readOptional(environment, path.posix.join(environment.procRoot, "cpuinfo")),
28
+ readOptional(environment, path.posix.join(environment.etcRoot, "os-release")),
29
+ probePsi(environment),
30
+ ])
31
+ : [null, null, false];
32
+ return {
33
+ cpuModel: cleanText(cpus[0]?.model) ?? (cpuinfo ? cpuinfoModel(cpuinfo) : null),
34
+ physicalCores: cpuinfo ? physicalCoreCount(cpuinfo) : null,
35
+ logicalThreads: Math.max(1, cpus.length),
36
+ totalMemoryBytes: Math.max(0, safe(() => environment.totalMemoryBytes(), 0)),
37
+ architecture: safe(() => environment.architecture(), "unknown"),
38
+ platform: environment.platform,
39
+ osName: (osRelease ? prettyOsName(osRelease) : null)
40
+ ?? cleanText(`${safe(() => environment.osType(), "")} ${safe(() => environment.osVersion(), "")}`),
41
+ kernelVersion: cleanText(safe(() => environment.kernelRelease(), "")),
42
+ psiAvailable,
43
+ };
44
+ }
45
+ /** PSI is available when the system-wide CPU pressure file exists and parses. */
46
+ export async function probePsi(environment) {
47
+ if (environment.platform !== "linux")
48
+ return false;
49
+ const content = await readOptional(environment, path.posix.join(environment.procRoot, "pressure", "cpu"));
50
+ return content !== null && parsePressureStall(content) !== null;
51
+ }
52
+ export async function readOptional(environment, filePath) {
53
+ try {
54
+ return await environment.readFile(filePath);
55
+ }
56
+ catch {
57
+ // Missing, unreadable, or kernel-disabled (EOPNOTSUPP) files mean "not reported".
58
+ return null;
59
+ }
60
+ }
61
+ /** Counts unique (physical id, core id) pairs; null when the topology is not exposed. */
62
+ export function physicalCoreCount(cpuinfo) {
63
+ const cores = new Set();
64
+ for (const block of cpuinfo.split(/\r?\n\s*\r?\n/u)) {
65
+ const physicalId = field(block, "physical id") ?? "0";
66
+ const coreId = field(block, "core id");
67
+ if (coreId !== null)
68
+ cores.add(`${physicalId}:${coreId}`);
69
+ }
70
+ return cores.size > 0 ? cores.size : null;
71
+ }
72
+ function cpuinfoModel(cpuinfo) {
73
+ return cleanText(field(cpuinfo, "model name") ?? field(cpuinfo, "Model") ?? undefined);
74
+ }
75
+ function prettyOsName(osRelease) {
76
+ const match = /^PRETTY_NAME=(.*)$/mu.exec(osRelease);
77
+ return match ? cleanText(match[1].trim().replace(/^["']|["']$/gu, "")) : null;
78
+ }
79
+ function field(block, name) {
80
+ const escaped = name.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
81
+ const match = new RegExp(`^${escaped}\\s*:\\s*(.*)$`, "mu").exec(block);
82
+ return match ? match[1].trim() : null;
83
+ }
84
+ function cleanText(value) {
85
+ const clean = value?.replace(/\s+/gu, " ").trim();
86
+ return clean ? clean.slice(0, 200) : null;
87
+ }
88
+ function safe(read, fallback) {
89
+ try {
90
+ return read();
91
+ }
92
+ catch {
93
+ return fallback;
94
+ }
95
+ }
@@ -0,0 +1,83 @@
1
+ import { type HostEnvironment, type HostFacts } from "./host-facts.js";
2
+ import { type PressureStallResource } from "./host-pressure-stall.js";
3
+ export interface HostSystemPressure {
4
+ readonly cpu: PressureStallResource | null;
5
+ readonly memory: PressureStallResource | null;
6
+ readonly io: PressureStallResource | null;
7
+ }
8
+ /** Load attributed to the systemd unit (cgroup v2) the bridge itself runs in. */
9
+ export interface HostOwnCgroupLoad {
10
+ readonly unit: string;
11
+ readonly cpuPressure: PressureStallResource | null;
12
+ readonly memoryPressure: PressureStallResource | null;
13
+ /** CPU cores consumed by the unit, from `cpu.stat` usage deltas between samples. */
14
+ readonly cpuCoresInUse: number | null;
15
+ /** Anonymous memory (`memory.stat` anon): the RSS-like figure, excluding page cache. */
16
+ readonly memoryAnonBytes: number | null;
17
+ /** All memory charged to the unit (`memory.current`), including page cache. */
18
+ readonly memoryChargedBytes: number | null;
19
+ }
20
+ /** Live host load. Reported in every heartbeat but never a material capability signal. */
21
+ export interface HostLoadSnapshot {
22
+ readonly sampledAt: string;
23
+ readonly psiAvailable: boolean;
24
+ readonly systemPressure: HostSystemPressure | null;
25
+ /** True only when the bridge runs in a cgroup of its own (see isDedicatedBridgeUnit). */
26
+ readonly ownCgroupDedicated: boolean;
27
+ /** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
28
+ readonly ownCgroup: HostOwnCgroupLoad | null;
29
+ readonly memoryAvailableBytes: number | null;
30
+ }
31
+ /** What the bridge service needs: static facts plus the latest cached load sample. */
32
+ export interface HostLoadSource {
33
+ start(): Promise<void>;
34
+ stop(): void;
35
+ facts(): HostFacts | null;
36
+ current(): HostLoadSnapshot | null;
37
+ }
38
+ export interface HostLoadSamplerOptions {
39
+ readonly environment?: HostEnvironment;
40
+ readonly intervalMs?: number;
41
+ /** Wall clock for `sampledAt`. */
42
+ readonly now?: () => number;
43
+ /** Monotonic clock (ms) for usage deltas, so wall-clock steps cannot skew cores in use. */
44
+ readonly monotonicNow?: () => number;
45
+ /** Systemd unit the operator dedicates to the bridge (FORGE_BRIDGE_CGROUP_UNIT). */
46
+ readonly cgroupUnit?: string | null;
47
+ }
48
+ export declare const defaultHostLoadSampleIntervalMs = 5000;
49
+ /**
50
+ * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
51
+ * latest snapshot. Every read is async and failure-tolerant: a host without PSI
52
+ * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
53
+ */
54
+ export declare class HostLoadSampler implements HostLoadSource {
55
+ private readonly environment;
56
+ private readonly intervalMs;
57
+ private readonly now;
58
+ private readonly monotonicNow;
59
+ private readonly cgroupUnit;
60
+ private generation;
61
+ private timer;
62
+ private starting;
63
+ private inFlight;
64
+ private hostFacts;
65
+ private latest;
66
+ private cpuMark;
67
+ constructor(options?: HostLoadSamplerOptions);
68
+ facts(): HostFacts | null;
69
+ current(): HostLoadSnapshot | null;
70
+ /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
71
+ start(): Promise<void>;
72
+ stop(): void;
73
+ /** Takes one sample now and caches it. Concurrent callers share one read. */
74
+ sample(): Promise<HostLoadSnapshot>;
75
+ private startOnce;
76
+ private readSnapshot;
77
+ private readSystemPressure;
78
+ private readOwnCgroup;
79
+ private coresInUse;
80
+ private readMemoryAvailable;
81
+ private fallbackFreeMemory;
82
+ private readPressure;
83
+ }
@@ -0,0 +1,164 @@
1
+ import path from "node:path";
2
+ import { defaultHostEnvironment, detectHostFacts, readOptional, } from "./host-facts.js";
3
+ import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
4
+ export const defaultHostLoadSampleIntervalMs = 5_000;
5
+ /**
6
+ * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
7
+ * latest snapshot. Every read is async and failure-tolerant: a host without PSI
8
+ * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
9
+ */
10
+ export class HostLoadSampler {
11
+ environment;
12
+ intervalMs;
13
+ now;
14
+ monotonicNow;
15
+ cgroupUnit;
16
+ generation = 0;
17
+ timer = null;
18
+ starting = null;
19
+ inFlight = null;
20
+ hostFacts = null;
21
+ latest = null;
22
+ cpuMark = null;
23
+ constructor(options = {}) {
24
+ this.environment = options.environment ?? defaultHostEnvironment();
25
+ this.intervalMs = options.intervalMs !== undefined && Number.isFinite(options.intervalMs) && options.intervalMs > 0
26
+ ? options.intervalMs
27
+ : defaultHostLoadSampleIntervalMs;
28
+ this.now = options.now ?? Date.now;
29
+ this.monotonicNow = options.monotonicNow ?? (() => performance.now());
30
+ this.cgroupUnit = options.cgroupUnit !== undefined
31
+ ? options.cgroupUnit
32
+ : process.env.FORGE_BRIDGE_CGROUP_UNIT?.trim() || null;
33
+ }
34
+ facts() {
35
+ return this.hostFacts;
36
+ }
37
+ current() {
38
+ return this.latest;
39
+ }
40
+ /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
41
+ start() {
42
+ if (this.timer)
43
+ return Promise.resolve();
44
+ this.starting ??= this.startOnce().finally(() => {
45
+ this.starting = null;
46
+ });
47
+ return this.starting;
48
+ }
49
+ stop() {
50
+ // Invalidates an in-progress start() so it cannot arm the interval afterwards.
51
+ this.generation += 1;
52
+ if (this.timer)
53
+ clearInterval(this.timer);
54
+ this.timer = null;
55
+ }
56
+ /** Takes one sample now and caches it. Concurrent callers share one read. */
57
+ sample() {
58
+ this.inFlight ??= this.readSnapshot()
59
+ .then(snapshot => {
60
+ this.latest = snapshot;
61
+ return snapshot;
62
+ })
63
+ .finally(() => {
64
+ this.inFlight = null;
65
+ });
66
+ return this.inFlight;
67
+ }
68
+ async startOnce() {
69
+ const generation = this.generation;
70
+ if (!this.hostFacts) {
71
+ this.hostFacts = await detectHostFacts(this.environment).catch(() => null);
72
+ }
73
+ await this.sample().catch(() => undefined);
74
+ if (this.timer || generation !== this.generation)
75
+ return;
76
+ this.timer = setInterval(() => {
77
+ void this.sample().catch(() => undefined);
78
+ }, this.intervalMs);
79
+ this.timer.unref?.();
80
+ }
81
+ async readSnapshot() {
82
+ const sampledAtMs = this.now();
83
+ const monotonicMs = this.monotonicNow();
84
+ const linux = this.environment.platform === "linux";
85
+ const [systemPressure, ownCgroup, memoryAvailableBytes] = linux
86
+ ? await Promise.all([this.readSystemPressure(), this.readOwnCgroup(monotonicMs), this.readMemoryAvailable()])
87
+ : [null, null, this.fallbackFreeMemory()];
88
+ return {
89
+ sampledAt: new Date(sampledAtMs).toISOString(),
90
+ psiAvailable: systemPressure !== null,
91
+ systemPressure,
92
+ ownCgroupDedicated: ownCgroup !== null,
93
+ ownCgroup,
94
+ memoryAvailableBytes,
95
+ };
96
+ }
97
+ async readSystemPressure() {
98
+ const pressureRoot = path.posix.join(this.environment.procRoot, "pressure");
99
+ const [cpu, memory, io] = await Promise.all(["cpu", "memory", "io"].map(resource => this.readPressure(path.posix.join(pressureRoot, resource))));
100
+ // CPU pressure is the governor's primary signal; without it PSI is unavailable.
101
+ return cpu ? { cpu, memory: memory ?? null, io: io ?? null } : null;
102
+ }
103
+ async readOwnCgroup(monotonicMs) {
104
+ const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
105
+ const cgroupPath = membership ? parseUnifiedCgroupPath(membership) : null;
106
+ const unit = cgroupPath ? cgroupLeafName(cgroupPath) : null;
107
+ if (!cgroupPath || !unit || !isDedicatedBridgeUnit(unit, this.cgroupUnit)) {
108
+ this.cpuMark = null;
109
+ return null;
110
+ }
111
+ const directory = path.posix.join(this.environment.cgroupRoot, cgroupPath);
112
+ if (!directory.startsWith(`${this.environment.cgroupRoot.replace(/\/+$/u, "")}/`))
113
+ return null;
114
+ const [cpuPressure, memoryPressure, cpuStat, memoryStat, memoryCurrent] = await Promise.all([
115
+ this.readPressure(path.posix.join(directory, "cpu.pressure")),
116
+ this.readPressure(path.posix.join(directory, "memory.pressure")),
117
+ readOptional(this.environment, path.posix.join(directory, "cpu.stat")),
118
+ readOptional(this.environment, path.posix.join(directory, "memory.stat")),
119
+ readOptional(this.environment, path.posix.join(directory, "memory.current")),
120
+ ]);
121
+ const usageUsec = cpuStat ? parseCgroupCpuUsageUsec(cpuStat) : null;
122
+ const memoryAnonBytes = memoryStat ? parseCgroupMemoryAnonBytes(memoryStat) : null;
123
+ const memoryChargedBytes = memoryCurrent ? parseNonNegativeInteger(memoryCurrent) : null;
124
+ // Ownership is settled by membership and the unit name above; metric files that are
125
+ // unavailable yield null values (and reset the CPU mark) but never demote the unit to shared.
126
+ return {
127
+ unit,
128
+ cpuPressure,
129
+ memoryPressure,
130
+ cpuCoresInUse: this.coresInUse(cgroupPath, usageUsec, monotonicMs),
131
+ memoryAnonBytes,
132
+ memoryChargedBytes,
133
+ };
134
+ }
135
+ coresInUse(cgroupPath, usageUsec, atMs) {
136
+ const previous = this.cpuMark;
137
+ this.cpuMark = usageUsec === null ? null : { cgroupPath, usageUsec, atMs };
138
+ if (!previous || usageUsec === null || previous.cgroupPath !== cgroupPath)
139
+ return null;
140
+ const elapsedUsec = (atMs - previous.atMs) * 1_000;
141
+ const usedUsec = usageUsec - previous.usageUsec;
142
+ // A restarted unit resets its counter; elapsed time comes from a monotonic clock.
143
+ if (elapsedUsec <= 0 || usedUsec < 0)
144
+ return null;
145
+ return Math.round((usedUsec / elapsedUsec) * 100) / 100;
146
+ }
147
+ async readMemoryAvailable() {
148
+ const meminfo = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "meminfo"));
149
+ return (meminfo ? parseMemAvailableBytes(meminfo) : null) ?? this.fallbackFreeMemory();
150
+ }
151
+ fallbackFreeMemory() {
152
+ try {
153
+ const free = this.environment.freeMemoryBytes();
154
+ return Number.isFinite(free) && free >= 0 ? free : null;
155
+ }
156
+ catch {
157
+ return null;
158
+ }
159
+ }
160
+ async readPressure(filePath) {
161
+ const content = await readOptional(this.environment, filePath);
162
+ return content ? parsePressureStall(content) : null;
163
+ }
164
+ }
@@ -0,0 +1,41 @@
1
+ export interface PressureStallAverages {
2
+ /** Percent of wall time stalled over the last 10 seconds (0-100). */
3
+ readonly avg10: number;
4
+ readonly avg60: number;
5
+ readonly avg300: number;
6
+ }
7
+ export interface PressureStallResource {
8
+ readonly some: PressureStallAverages | null;
9
+ readonly full: PressureStallAverages | null;
10
+ }
11
+ /**
12
+ * Parses one PSI file. Returns null when the content has no well-formed
13
+ * `some`/`full` line, so callers can report PSI as unavailable instead of
14
+ * publishing zeros for a file they could not interpret.
15
+ */
16
+ export declare function parsePressureStall(content: string): PressureStallResource | null;
17
+ /** Reads `usage_usec` from a cgroup v2 `cpu.stat` file. */
18
+ export declare function parseCgroupCpuUsageUsec(content: string): number | null;
19
+ /** Reads anonymous (RSS-like, excludes page cache) bytes from cgroup v2 `memory.stat`. */
20
+ export declare function parseCgroupMemoryAnonBytes(content: string): number | null;
21
+ /** Reads a single non-negative integer file such as cgroup v2 `memory.current`. */
22
+ export declare function parseNonNegativeInteger(content: string): number | null;
23
+ /** Reads `MemAvailable` (bytes) from /proc/meminfo. */
24
+ export declare function parseMemAvailableBytes(content: string): number | null;
25
+ /**
26
+ * Resolves the unified (cgroup v2) hierarchy path from /proc/self/cgroup.
27
+ * Returns null on pure cgroup v1 hosts (no `0::` entry) and for the root cgroup.
28
+ */
29
+ export declare function parseUnifiedCgroupPath(content: string): string | null;
30
+ /** The leaf cgroup name, e.g. `forge-bridge.service`. */
31
+ export declare function cgroupLeafName(cgroupPath: string): string | null;
32
+ /**
33
+ * Whether the bridge's cgroup is dedicated to it, so its usage can later be
34
+ * subtracted from system pressure as "Forge's own load". Only a systemd
35
+ * `.service` qualifies by default, or exactly the unit an operator names via
36
+ * FORGE_BRIDGE_CGROUP_UNIT. A `.scope` is rejected: a bridge started from a
37
+ * terminal, SSH session or desktop app shares `session-N.scope` /
38
+ * `app-*.scope` with unrelated work (possibly the owner's game).
39
+ * Container cgroups (e.g. `docker-<id>.scope`) are added in decision 0013 step 2.
40
+ */
41
+ export declare function isDedicatedBridgeUnit(unit: string, configuredUnit: string | null | undefined): boolean;
@@ -0,0 +1,121 @@
1
+ // Linux Pressure Stall Information (PSI) parsing shared by the host load sampler.
2
+ // Format (system-wide /proc/pressure/<resource> and cgroup v2 <resource>.pressure):
3
+ // some avg10=0.12 avg60=0.34 avg300=0.56 total=123456
4
+ // full avg10=0.00 avg60=0.00 avg300=0.00 total=0
5
+ const pressureLinePattern = /^(some|full)\s+(.*)$/u;
6
+ /**
7
+ * Parses one PSI file. Returns null when the content has no well-formed
8
+ * `some`/`full` line, so callers can report PSI as unavailable instead of
9
+ * publishing zeros for a file they could not interpret.
10
+ */
11
+ export function parsePressureStall(content) {
12
+ let some = null;
13
+ let full = null;
14
+ for (const rawLine of content.split(/\r?\n/u)) {
15
+ const match = pressureLinePattern.exec(rawLine.trim());
16
+ if (!match)
17
+ continue;
18
+ const averages = parseAverages(match[2]);
19
+ if (!averages)
20
+ continue;
21
+ if (match[1] === "some")
22
+ some = averages;
23
+ else
24
+ full = averages;
25
+ }
26
+ return some || full ? { some, full } : null;
27
+ }
28
+ const pressureFieldPattern = /^(avg10|avg60|avg300|total)=(\d+(?:\.\d+)?)$/u;
29
+ /** A PSI line must carry exactly avg10, avg60, avg300 and an integer total; anything else is malformed. */
30
+ function parseAverages(fields) {
31
+ const values = new Map();
32
+ for (const field of fields.trim().split(/\s+/u)) {
33
+ const match = pressureFieldPattern.exec(field);
34
+ if (!match || values.has(match[1]))
35
+ return null;
36
+ values.set(match[1], Number(match[2]));
37
+ }
38
+ const avg10 = values.get("avg10");
39
+ const avg60 = values.get("avg60");
40
+ const avg300 = values.get("avg300");
41
+ const total = values.get("total");
42
+ if (avg10 === undefined || avg60 === undefined || avg300 === undefined
43
+ || total === undefined || !Number.isSafeInteger(total))
44
+ return null;
45
+ return { avg10: clampPercent(avg10), avg60: clampPercent(avg60), avg300: clampPercent(avg300) };
46
+ }
47
+ function clampPercent(value) {
48
+ return Math.min(100, Math.max(0, value));
49
+ }
50
+ /** Reads `usage_usec` from a cgroup v2 `cpu.stat` file. */
51
+ export function parseCgroupCpuUsageUsec(content) {
52
+ const match = /^usage_usec\s+(\d+)\s*$/mu.exec(content);
53
+ if (!match)
54
+ return null;
55
+ const value = Number(match[1]);
56
+ return Number.isSafeInteger(value) ? value : null;
57
+ }
58
+ /** Reads anonymous (RSS-like, excludes page cache) bytes from cgroup v2 `memory.stat`. */
59
+ export function parseCgroupMemoryAnonBytes(content) {
60
+ const match = /^anon\s+(\d+)\s*$/mu.exec(content);
61
+ if (!match)
62
+ return null;
63
+ const value = Number(match[1]);
64
+ return Number.isSafeInteger(value) ? value : null;
65
+ }
66
+ /** Reads a single non-negative integer file such as cgroup v2 `memory.current`. */
67
+ export function parseNonNegativeInteger(content) {
68
+ const trimmed = content.trim();
69
+ if (!/^\d+$/u.test(trimmed))
70
+ return null;
71
+ const value = Number(trimmed);
72
+ return Number.isSafeInteger(value) ? value : null;
73
+ }
74
+ /** Reads `MemAvailable` (bytes) from /proc/meminfo. */
75
+ export function parseMemAvailableBytes(content) {
76
+ const match = /^MemAvailable:\s+(\d+)\s*kB\s*$/mu.exec(content);
77
+ if (!match)
78
+ return null;
79
+ const value = Number(match[1]) * 1024;
80
+ return Number.isSafeInteger(value) ? value : null;
81
+ }
82
+ /**
83
+ * Resolves the unified (cgroup v2) hierarchy path from /proc/self/cgroup.
84
+ * Returns null on pure cgroup v1 hosts (no `0::` entry) and for the root cgroup.
85
+ */
86
+ export function parseUnifiedCgroupPath(content) {
87
+ for (const rawLine of content.split(/\r?\n/u)) {
88
+ const line = rawLine.trim();
89
+ if (!line.startsWith("0::"))
90
+ continue;
91
+ const cgroupPath = line.slice(3).trim();
92
+ if (!cgroupPath.startsWith("/") || cgroupPath === "/")
93
+ return null;
94
+ if (cgroupPath.split("/").some(segment => segment === ".."))
95
+ return null;
96
+ return cgroupPath;
97
+ }
98
+ return null;
99
+ }
100
+ /** The leaf cgroup name, e.g. `forge-bridge.service`. */
101
+ export function cgroupLeafName(cgroupPath) {
102
+ return cgroupPath.split("/").filter(Boolean).at(-1) ?? null;
103
+ }
104
+ /**
105
+ * Whether the bridge's cgroup is dedicated to it, so its usage can later be
106
+ * subtracted from system pressure as "Forge's own load". Only a systemd
107
+ * `.service` qualifies by default, or exactly the unit an operator names via
108
+ * FORGE_BRIDGE_CGROUP_UNIT. A `.scope` is rejected: a bridge started from a
109
+ * terminal, SSH session or desktop app shares `session-N.scope` /
110
+ * `app-*.scope` with unrelated work (possibly the owner's game).
111
+ * Container cgroups (e.g. `docker-<id>.scope`) are added in decision 0013 step 2.
112
+ */
113
+ export function isDedicatedBridgeUnit(unit, configuredUnit) {
114
+ const configured = configuredUnit?.trim();
115
+ if (configured)
116
+ return unit === configured;
117
+ // `app-*` services are desktop-launched apps (XDG naming); `user@N` is the whole user manager.
118
+ return /^[^@\s]+(@[^\s]+)?\.service$/u.test(unit)
119
+ && !/^app-/u.test(unit)
120
+ && !/^user@\d+\.service$/u.test(unit);
121
+ }