Skip to content

Commit 19dc639

Browse files
feat(daemon): report the host CPU architecture in /health (callstack#3047)
1 parent 1433e11 commit 19dc639

12 files changed

Lines changed: 131 additions & 9 deletions

File tree

‎packages/contracts/src/daemon-http.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,20 +56,22 @@ export type DaemonHealthPayload = {
5656
version: string;
5757
rpcProtocolVersion: number;
5858
instanceId?: string;
59+
hostArch?: string;
5960
upstream?: unknown;
6061
};
6162

6263
export function buildDaemonHealthPayload(
6364
service: DaemonHealthPayload['service'],
6465
version: string,
65-
options: { upstream?: unknown; instanceId?: string } = {},
66+
options: { upstream?: unknown; instanceId?: string; hostArch?: string } = {},
6667
): DaemonHealthPayload {
6768
return {
6869
ok: true,
6970
service,
7071
version,
7172
rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
7273
...(options.instanceId !== undefined ? { instanceId: options.instanceId } : {}),
74+
...(options.hostArch !== undefined ? { hostArch: options.hostArch } : {}),
7375
...(options.upstream !== undefined ? { upstream: options.upstream } : {}),
7476
};
7577
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import assert from 'node:assert/strict';
2+
import { test } from 'vitest';
3+
import { type CommandExecutorOverride, withCommandExecutorOverride } from './exec.ts';
4+
import { resolveHostCpuArch } from './host-cpu-arch.ts';
5+
6+
function sysctlAnswering(result: { stdout?: string; exitCode?: number } | Error) {
7+
const calls: string[][] = [];
8+
const override: CommandExecutorOverride = async (command, args) => {
9+
calls.push([command, ...args]);
10+
if (result instanceof Error) throw result;
11+
return { stdout: result.stdout ?? '', stderr: '', exitCode: result.exitCode ?? 0 };
12+
};
13+
return { calls, override };
14+
}
15+
16+
test('an Apple silicon Mac reports arm64 even when Node runs as x64 under Rosetta', async () => {
17+
const sysctl = sysctlAnswering({ stdout: '1\n' });
18+
const arch = await withCommandExecutorOverride(sysctl.override, () =>
19+
resolveHostCpuArch('darwin', 'x64'),
20+
);
21+
assert.equal(arch, 'arm64');
22+
assert.deepEqual(sysctl.calls, [['/usr/sbin/sysctl', '-n', 'hw.optional.arm64']]);
23+
});
24+
25+
test('a Mac without the arm64 sysctl key falls back to the Node arch in Apple naming', async () => {
26+
for (const answer of [
27+
{ stdout: '', exitCode: 1 },
28+
{ stdout: '0\n' },
29+
new Error('spawn /usr/sbin/sysctl ENOENT'),
30+
]) {
31+
const sysctl = sysctlAnswering(answer);
32+
const arch = await withCommandExecutorOverride(sysctl.override, () =>
33+
resolveHostCpuArch('darwin', 'x64'),
34+
);
35+
assert.equal(arch, 'x86_64');
36+
}
37+
});
38+
39+
test('other platforms report the Node arch without running sysctl', async () => {
40+
const sysctl = sysctlAnswering({ stdout: '1\n' });
41+
await withCommandExecutorOverride(sysctl.override, async () => {
42+
assert.equal(await resolveHostCpuArch('linux', 'x64'), 'x86_64');
43+
assert.equal(await resolveHostCpuArch('linux', 'arm64'), 'arm64');
44+
assert.equal(await resolveHostCpuArch('linux', 'ppc64'), 'ppc64');
45+
});
46+
assert.deepEqual(sysctl.calls, []);
47+
});
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import { runCmd } from './exec.ts';
2+
3+
const SYSCTL_TIMEOUT_MS = 1_000;
4+
5+
let hostCpuArch: Promise<string> | undefined;
6+
7+
/**
8+
* The machine's native CPU architecture in Apple naming (`arm64`, `x86_64`), which is what
9+
* simulators on a Mac run by default. Other CPUs keep Node's `process.arch` name. Resolved once
10+
* per process.
11+
*/
12+
export function readHostCpuArch(): Promise<string> {
13+
hostCpuArch ??= resolveHostCpuArch(process.platform, process.arch);
14+
return hostCpuArch;
15+
}
16+
17+
export async function resolveHostCpuArch(
18+
platform: NodeJS.Platform,
19+
nodeArch: string,
20+
): Promise<string> {
21+
if (platform === 'darwin' && (await isAppleSiliconMac())) return 'arm64';
22+
return nodeArch === 'x64' ? 'x86_64' : nodeArch;
23+
}
24+
25+
// macOS: `hw.optional.arm64` is 1 on Apple silicon even inside a Rosetta-translated process,
26+
// where `process.arch` reports x64; Intel Macs do not define the key.
27+
async function isAppleSiliconMac(): Promise<boolean> {
28+
try {
29+
const result = await runCmd('/usr/sbin/sysctl', ['-n', 'hw.optional.arm64'], {
30+
allowFailure: true,
31+
timeoutMs: SYSCTL_TIMEOUT_MS,
32+
});
33+
return result.exitCode === 0 && result.stdout.trim() === '1';
34+
} catch {
35+
return false;
36+
}
37+
}

‎packages/host-kit/src/process.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export {
2525
writeHostStderr,
2626
} from './internal/host-process.ts';
2727
export { signalProcessGroupBestEffort } from './internal/exec.ts';
28+
export { readHostCpuArch } from './internal/host-cpu-arch.ts';
2829
export { reapOwnedProcessRecordsAtStartup } from './internal/owned-process-reaper.ts';
2930
export {
3031
createOwnedProcessRecordStore,

‎src/__tests__/daemon-proxy.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import http from 'node:http';
55
import { createDaemonProxyServer } from '../remote/daemon-proxy.ts';
66
import { createDaemonHttpServer } from '../daemon/server/http-server.ts';
77
import { getRequestSignal } from '@agent-device/host-kit/request';
8+
import { readHostCpuArch } from '@agent-device/host-kit/process';
89
import { executeRunScriptHttpRequest } from '@agent-device/maestro/run-script-http';
910
import {
1011
DAEMON_HTTP_NETWORK_ACCESS_HEADER,
@@ -458,6 +459,7 @@ test('daemon proxy leaves health endpoint unauthenticated', async (t) => {
458459
assert.equal(typeof payload.version, 'string');
459460
assert.equal(payload.rpcProtocolVersion, DAEMON_RPC_PROTOCOL_VERSION);
460461
assert.equal(typeof payload.instanceId, 'string');
462+
assert.equal(payload.hostArch, await readHostCpuArch());
461463
assert.deepEqual(payload.upstream, { ok: true });
462464
assert.equal(upstreamAuth, 'Bearer daemon-secret');
463465
assert.equal(upstreamTokenHeader, 'daemon-secret');

‎src/daemon-client/__tests__/daemon-client-health-compat.test.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,12 @@ import {
1515
* what the check itself accepts and refuses when a proxy sits in front of the daemon.
1616
*/
1717

18-
const DAEMON_LINK = { ok: true, service: 'agent-device-daemon', version: '98.0.0' } as const;
18+
const DAEMON_LINK = {
19+
ok: true,
20+
service: 'agent-device-daemon',
21+
version: '98.0.0',
22+
hostArch: 'arm64',
23+
} as const;
1924

2025
async function withHealthServer<T>(
2126
payload: Record<string, unknown>,
@@ -40,6 +45,7 @@ function proxyHealth(upstreamRpcProtocolVersion: number): Record<string, unknown
4045
service: 'agent-device-proxy',
4146
version: '99.0.0',
4247
rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
48+
hostArch: 'x86_64',
4349
upstream: { ...DAEMON_LINK, rpcProtocolVersion: upstreamRpcProtocolVersion },
4450
};
4551
}
@@ -51,10 +57,12 @@ test('a proxy whose daemon speaks the same protocol passes with the upstream lin
5157
const health = await readRemoteDaemonHealth({ baseUrl, token: 'proxy-token', pid: 0 });
5258
assert.equal(health.reachable, true);
5359
assert.equal(health.service, 'agent-device-proxy');
60+
assert.equal(health.hostArch, 'x86_64');
5461
assert.deepEqual(health.upstream, {
5562
service: 'agent-device-daemon',
5663
version: '98.0.0',
5764
rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION,
65+
hostArch: 'arm64',
5866
});
5967
});
6068
});
@@ -79,15 +87,17 @@ test('a proxy whose daemon speaks another protocol is refused, naming the daemon
7987
});
8088
});
8189

82-
test('a daemon health payload without an upstream link parses as before', async (t) => {
90+
test('a daemon health payload without an upstream link or host arch parses as before', async (t) => {
8391
if (await skipWhenLoopbackUnavailable(t)) return;
8492

93+
const { hostArch: _hostArch, ...legacyLink } = DAEMON_LINK;
8594
await withHealthServer(
86-
{ ...DAEMON_LINK, rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION },
95+
{ ...legacyLink, rpcProtocolVersion: DAEMON_RPC_PROTOCOL_VERSION },
8796
async (baseUrl) => {
8897
const health = await readRemoteDaemonHealth({ baseUrl, token: 'daemon-token', pid: 0 });
8998
assert.equal(health.reachable, true);
9099
assert.equal(health.upstream, undefined);
100+
assert.equal('hostArch' in health, false);
91101
assert.equal(health.rpcProtocolVersion, DAEMON_RPC_PROTOCOL_VERSION);
92102
},
93103
);

‎src/daemon-client/daemon-client-transport.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,14 @@ export type RemoteDaemonHealth = {
4040
version?: string;
4141
rpcProtocolVersion?: number;
4242
instanceId?: string;
43+
hostArch?: string;
4344
/** The daemon behind a proxy, as the proxy's health reported it. */
4445
upstream?: RemoteDaemonHealthLink;
4546
};
4647

4748
type RemoteDaemonHealthLink = Pick<
4849
RemoteDaemonHealth,
49-
'service' | 'version' | 'rpcProtocolVersion' | 'instanceId'
50+
'service' | 'version' | 'rpcProtocolVersion' | 'instanceId' | 'hostArch'
5051
>;
5152

5253
export async function canConnect(
@@ -203,6 +204,7 @@ function readHealthLink(parsed: Record<string, unknown>): RemoteDaemonHealthLink
203204
rpcProtocolVersion:
204205
typeof parsed.rpcProtocolVersion === 'number' ? parsed.rpcProtocolVersion : undefined,
205206
...(typeof parsed.instanceId === 'string' ? { instanceId: parsed.instanceId } : {}),
207+
...(typeof parsed.hostArch === 'string' ? { hostArch: parsed.hostArch } : {}),
206208
};
207209
}
208210

‎src/daemon/server/http-instance-precondition.test.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { test } from 'vitest';
22
import assert from 'node:assert/strict';
3+
import { readHostCpuArch } from '@agent-device/host-kit/process';
34
import { createDaemonHttpServer } from './http-server.ts';
45
import {
56
DAEMON_HTTP_INSTANCE_HEADER,
@@ -26,7 +27,11 @@ test('a stale RPC instance is refused after authentication and before command di
2627
try {
2728
const port = await listenOnLoopback(server);
2829
const endpoint = `http://127.0.0.1:${port}`;
29-
const health = (await (await fetch(`${endpoint}/health`)).json()) as { instanceId: string };
30+
const health = (await (await fetch(`${endpoint}/health`)).json()) as {
31+
instanceId: string;
32+
hostArch: string;
33+
};
34+
assert.equal(health.hostArch, await readHostCpuArch());
3035
const rpc = (expectedInstance: string, authToken = 'daemon-secret') =>
3136
fetch(`${endpoint}/rpc`, {
3237
method: 'POST',

‎src/daemon/server/http-server.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import {
4141
DAEMON_HTTP_TENANT_HEADER,
4242
} from '@agent-device/contracts/daemon-http';
4343
import { readVersion } from '@agent-device/host-kit/version';
44+
import { readHostCpuArch } from '@agent-device/host-kit/process';
4445
import { readLeaseAllocateProviderFlags } from '@agent-device/contracts/lease-scope';
4546
import { sendRestJsonError, statusCodeForNormalizedError } from '../http-errors.ts';
4647
import { tryHandleUploadHttpRoute } from '../upload-http.ts';
@@ -574,6 +575,7 @@ export async function createDaemonHttpServer(options: {
574575
resolveRequestDiagnosticsPath?: (ref: DiagnosticsRecordRef) => string;
575576
}): Promise<http.Server> {
576577
const instanceId = randomUUID();
578+
const hostArch = await readHostCpuArch();
577579
const environment = options.env ?? process.env;
578580
const authHook = await loadHttpAuthHook(environment);
579581
const { handleRequest, token, retainArtifacts = false, resolveRequestDiagnosticsPath } = options;
@@ -583,7 +585,10 @@ export async function createDaemonHttpServer(options: {
583585
res.setHeader('content-type', 'application/json');
584586
res.end(
585587
JSON.stringify(
586-
buildDaemonHealthPayload('agent-device-daemon', readVersion(), { instanceId }),
588+
buildDaemonHealthPayload('agent-device-daemon', readVersion(), {
589+
instanceId,
590+
hostArch,
591+
}),
587592
),
588593
);
589594
return;

‎src/remote/daemon-proxy.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
buildDaemonHttpUrl,
1919
} from '@agent-device/contracts/daemon-http';
2020
import { readVersion } from '@agent-device/host-kit/version';
21+
import { readHostCpuArch } from '@agent-device/host-kit/process';
2122
import {
2223
carriesUnbackedHostPathInstallSource,
2324
sendHostPathInstallSourceRefused,
@@ -119,7 +120,11 @@ async function sendProxyHealth(
119120
res.setHeader('content-type', 'application/json');
120121
res.end(
121122
JSON.stringify(
122-
buildDaemonHealthPayload('agent-device-proxy', readVersion(), { upstream, instanceId }),
123+
buildDaemonHealthPayload('agent-device-proxy', readVersion(), {
124+
upstream,
125+
instanceId,
126+
hostArch: await readHostCpuArch(),
127+
}),
123128
),
124129
);
125130
}

0 commit comments

Comments
 (0)