Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/user-intent-kit/bin/uik-daemon.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ if (userId.toLowerCase() === agentHandle.replace(/^@/, '').toLowerCase()) {
}

const client = new IntentClient({ baseUrl, apiKey, userId, deviceId });
const iak = new IAKAdapter(client, { agentHandle });
const iak = new IAKAdapter(client, { agentHandle, machine: deviceId });
const desktop = new DesktopAdapter(client, { pollIntervalMs });

desktop.start();
Expand Down
2 changes: 1 addition & 1 deletion packages/user-intent-kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
"./adapters/browser": "./src/adapters/browser.js"
},
"scripts": {
"test": "node --test test/client.test.js",
"test": "node --test test/*.test.js",
"daemon": "node bin/uik-daemon.js"
},
"keywords": [
Expand Down
18 changes: 16 additions & 2 deletions packages/user-intent-kit/src/adapters/iak.js
Original file line number Diff line number Diff line change
@@ -1,34 +1,48 @@
// SPDX-License-Identifier: AGPL-3.0

import { collectHostTelemetry } from '../host-telemetry.js';

/**
* IAK Adapter - integrates user-intent-kit with IDE Agent Kit.
*
* Publishes: active agent, current task, tmux session status.
* Publishes: active agent, current task, tmux session status, host vitals.
* Subscribes: user availability (suppress nudges during meetings).
*/
export class IAKAdapter {
#client;
#agentHandle;
#machine;

/**
* @param {import('../client.js').IntentClient} client
* @param {object} opts
* @param {string} opts.agentHandle - e.g. "@claudemm"
* @param {string} [opts.machine] - stable device name published in host
* vitals. Defaults to the client's configured deviceId, so callers that
* predate host vitals keep naming their machine: `host` replaces the
* stored value wholesale, so publishing it without a name would overwrite
* a known hostname with anonymous load readings.
*/
constructor(client, { agentHandle }) {
constructor(client, { agentHandle, machine }) {
this.#client = client;
this.#agentHandle = agentHandle;
this.#machine = machine ?? client?.deviceId ?? undefined;
}

/**
* Publish current agent status to intent state.
* Call this on each room poll cycle.
*
* `host` carries the machine's vitals as an object. It was previously a bare
* string on some publishers, which gave the dashboard nowhere to put a
* temperature or a load figure.
*/
async publishStatus({ status = 'active', currentTask = null }) {
const name = this.#agentHandle.replace(/^@/, '');
await this.#client.patchAgent(name, {
status,
last_task: currentTask,
host: collectHostTelemetry({ machine: this.#machine }),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the machine name for existing adapter callers

When callers omit the newly optional machine argument, this heartbeat still writes a complete host object but without its machine field. This affects the built-in iakAdapterFromConfig path in src/intent.mjs, which has a configured deviceId but constructs IAKAdapter with only agentHandle, as well as the documented existing constructor calls. Consequently each PATCH can replace a previously stored hostname with anonymous load readings, preventing the dashboard from associating the vitals with a machine; default this value from client.deviceId or propagate the configured device ID.

Useful? React with 👍 / 👎.

});
}

Expand Down
5 changes: 5 additions & 0 deletions packages/user-intent-kit/src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ export class IntentClient {
this.#heartbeatTimer = null;
}

/** Device slot this client writes to, or null for a read-only client. */
get deviceId() {
return this.#deviceId;
}

// --- Profile (static layer) ---

async getProfile() {
Expand Down
130 changes: 130 additions & 0 deletions packages/user-intent-kit/src/host-telemetry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: AGPL-3.0

/**
* Host vitals for the UIK agent record (CPU load, temperature, power).
*
* Contract: every field is OPTIONAL and a value we cannot read is OMITTED,
* never zeroed. A zero renders in the dashboard as a real reading — an idle
* box and an unreadable sensor must not look the same.
*
* Nothing here throws: telemetry is decoration on the heartbeat, so a failed
* sensor read must never take the agent offline.
*
* The platform reads are injectable (`sources`) so the contract can be tested
* on any machine. Without that, a suite running on macOS never exercises the
* Linux thermal path at all, and "the tests pass" would mean only that they
* passed on whichever box happened to run them.
*/

import { readFileSync, readdirSync } from 'node:fs';
import { cpus, loadavg, platform } from 'node:os';

/** Plausible CPU die temperatures. Outside this, assume the sensor lied. */
const TEMP_MIN_C = 1;
const TEMP_MAX_C = 150;

const THERMAL_ROOT = '/sys/class/thermal';

/** Real sensor reads. Swapped out wholesale in tests. */
export const defaultSources = {
platform: () => platform(),
loadavg: () => loadavg(),
cpuCount: () => cpus()?.length,
listThermalZones: () => readdirSync(THERMAL_ROOT).filter((z) => z.startsWith('thermal_zone')),
readThermalZone: (zone) => readFileSync(`${THERMAL_ROOT}/${zone}/temp`, 'utf8'),
};

/**
* CPU load, normalised so devices of different sizes are comparable.
*
* Raw loadavg is meaningless across a fleet: 1.8 is ~18% of a 10-core M4 but
* ~45% of a 4-core Pi. The dashboard compares boxes side by side, so it needs
* the percentage, and we publish the raw figure alongside it for anyone who
* wants the familiar number.
*
* @returns {{load_1m?: number, load_pct?: number, cpu_count?: number}}
*/
function readLoad(sources) {
// Windows has no load average; Node reports [0, 0, 0] there. That is an
// absent sensor, not an idle machine, so report nothing at all.
if (sources.platform() === 'win32') return {};

const [oneMinute] = sources.loadavg() || [];
if (!Number.isFinite(oneMinute)) return {};

const out = { load_1m: Math.round(oneMinute * 100) / 100 };

const count = sources.cpuCount();
if (Number.isFinite(count) && count > 0) {
out.cpu_count = count;
out.load_pct = Math.round((oneMinute / count) * 100);
}
return out;
}

/**
* CPU temperature from the Linux thermal zones (Raspberry Pi and friends).
*
* sysfs reports millidegrees. A board exposes several zones and they do not
* agree; the hottest plausible one is what "the CPU temperature" means to
* someone reading a dashboard, so that is what we publish.
*
* @returns {number|undefined} degrees Celsius
*/
function readLinuxTempC(sources) {
let zones;
try {
zones = sources.listThermalZones();
} catch {
return undefined;
}

let hottest;
for (const zone of zones || []) {
try {
const celsius = Number(String(sources.readThermalZone(zone)).trim()) / 1000;
if (celsius >= TEMP_MIN_C && celsius <= TEMP_MAX_C) {
if (hottest === undefined || celsius > hottest) hottest = celsius;
}
} catch {
// Unreadable zone: skip it, keep whatever the other zones gave us.
}
}
return hottest === undefined ? undefined : Math.round(hottest * 10) / 10;
}

/**
* Collect what this host can actually report.
*
* Temperature and power on macOS live behind `powermetrics`, which requires
* root. We deliberately do not shell out to sudo from a long-running daemon,
* so a Mac publishes load only until a privileged helper feeds it a reading.
* That is why a Mac shows load but no temperature: the sensor is gated, not
* missing.
*
* @param {object} [opts]
* @param {string} [opts.machine] - stable device name (e.g. "mac-mini")
* @param {object} [opts.sources] - injectable sensor reads, for tests
* @returns {object} only the fields that were readable
*/
export function collectHostTelemetry({ machine, sources = defaultSources } = {}) {
const host = {};
if (machine) host.machine = machine;

try {
Object.assign(host, readLoad(sources));
} catch {
// Load is best-effort like everything else here.
}

try {
if (sources.platform() === 'linux') {
const tempC = readLinuxTempC(sources);
if (tempC !== undefined) host.temp_c = tempC;
}
} catch {
// No thermal zones exposed; publish without a temperature.
}

return host;
}
1 change: 1 addition & 0 deletions packages/user-intent-kit/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ export { IAKAdapter } from './adapters/iak.js';
export { OpenClawAdapter } from './adapters/openclaw.js';
export { DesktopAdapter } from './adapters/desktop.js';
export { BrowserAdapter } from './adapters/browser.js';
export { collectHostTelemetry } from './host-telemetry.js';
155 changes: 155 additions & 0 deletions packages/user-intent-kit/test/host-telemetry.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// SPDX-License-Identifier: AGPL-3.0

import { test } from 'node:test';
import assert from 'node:assert/strict';

import { collectHostTelemetry } from '../src/host-telemetry.js';

/**
* Fake sensors. The real ones only report whatever the machine running the
* suite happens to expose, so on a Mac the Linux thermal path would never run
* and "tests pass" would say nothing about the Pi.
*/
function sources({ platform = 'linux', load = [1.8, 1.7, 1.6], cpuCount = 4, zones = {} } = {}) {
return {
platform: () => platform,
loadavg: () => load,
cpuCount: () => cpuCount,
listThermalZones: () => Object.keys(zones),
readThermalZone: (zone) => {
const value = zones[zone];
if (value instanceof Error) throw value;
return value;
},
};
}

// --- the omit-not-zero contract, the whole point of this module ---

test('a sensor reading 0 is omitted, not published as a temperature', () => {
const host = collectHostTelemetry({ sources: sources({ zones: { thermal_zone0: '0' } }) });
assert.ok(!('temp_c' in host), 'published a 0 C reading as if it were real');
});

test('an implausible sensor reading is omitted rather than published', () => {
for (const bogus of ['999000', '-40000', 'not-a-number', '']) {
const host = collectHostTelemetry({ sources: sources({ zones: { thermal_zone0: bogus } }) });
assert.ok(!('temp_c' in host), `published implausible reading ${bogus}`);
}
});

test('no field is ever published as null or undefined', () => {
const host = collectHostTelemetry({ machine: 'pi', sources: sources({ zones: { thermal_zone0: '43500' } }) });
for (const [key, value] of Object.entries(host)) {
assert.notEqual(value, null, `${key} published as null`);
assert.notEqual(value, undefined, `${key} published as undefined`);
}
});

// --- Linux thermal zones (the Pi) ---

test('publishes CPU temperature from the Linux thermal zones', () => {
const host = collectHostTelemetry({ sources: sources({ zones: { thermal_zone0: '43500' } }) });
assert.equal(host.temp_c, 43.5);
});

test('reports the hottest plausible zone, ignoring implausible ones', () => {
const host = collectHostTelemetry({
sources: sources({
zones: { thermal_zone0: '43500', thermal_zone1: '51200', thermal_zone2: '999000' },
}),
});
assert.equal(host.temp_c, 51.2);
});

test('an unreadable zone does not lose the readable ones', () => {
const host = collectHostTelemetry({
sources: sources({
zones: { thermal_zone0: new Error('EACCES'), thermal_zone1: '47000' },
}),
});
assert.equal(host.temp_c, 47);
});

test('a host with no thermal zones at all publishes no temperature', () => {
const bare = sources();
bare.listThermalZones = () => {
throw new Error('ENOENT');
};
const host = collectHostTelemetry({ sources: bare });
assert.ok(!('temp_c' in host));
assert.ok('load_1m' in host, 'a missing thermal sensor must not suppress load');
});

// --- platform gates ---

test('macOS publishes load but never a temperature', () => {
// powermetrics needs root and the daemon deliberately does not use sudo.
const host = collectHostTelemetry({
machine: 'mac-mini',
sources: sources({ platform: 'darwin', zones: { thermal_zone0: '43500' } }),
});
assert.ok(!('temp_c' in host), 'macOS published a temperature it cannot read');
assert.equal(host.load_1m, 1.8);
});

test('Windows reports no load rather than a fake zero', () => {
const host = collectHostTelemetry({ sources: sources({ platform: 'win32', load: [0, 0, 0] }) });
assert.ok(!('load_1m' in host), 'published Node\'s [0,0,0] placeholder as real load');
assert.ok(!('load_pct' in host));
});

// --- load normalisation ---

test('normalises load against core count so devices are comparable', () => {
// The same 1.8 load means something different on each box.
const pi = collectHostTelemetry({ sources: sources({ cpuCount: 4 }) });
const mini = collectHostTelemetry({ sources: sources({ cpuCount: 10 }) });

assert.equal(pi.load_pct, 45);
assert.equal(mini.load_pct, 18);
assert.equal(pi.load_1m, mini.load_1m, 'raw load is identical; only the percentage separates them');
});

test('publishes raw load even when core count is unavailable', () => {
const noCpus = sources();
noCpus.cpuCount = () => undefined;
const host = collectHostTelemetry({ sources: noCpus });
assert.equal(host.load_1m, 1.8);
assert.ok(!('load_pct' in host), 'cannot normalise without a core count');
assert.ok(!('cpu_count' in host));
});

// --- misc contract ---

test('passes the machine name through', () => {
assert.equal(collectHostTelemetry({ machine: 'mac-mini', sources: sources() }).machine, 'mac-mini');
});

test('omits the machine name rather than inventing one', () => {
assert.ok(!('machine' in collectHostTelemetry({ sources: sources() })));
});

test('never throws, whatever the sensors do', () => {
const hostile = {
platform: () => 'linux',
loadavg: () => {
throw new Error('boom');
},
cpuCount: () => {
throw new Error('boom');
},
listThermalZones: () => {
throw new Error('boom');
},
readThermalZone: () => {
throw new Error('boom');
},
};
assert.doesNotThrow(() => collectHostTelemetry({ machine: 'x', sources: hostile }));
assert.deepEqual(collectHostTelemetry({ machine: 'x', sources: hostile }), { machine: 'x' });
});

test('works against the real machine without arguments', () => {
assert.doesNotThrow(() => collectHostTelemetry());
});
Loading
Loading