The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat(cli): add-ons for a device that is a Harness machine (#1654) (#1717)
daniel-autoa7ef2496f72c
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 145f51782..668a2e536 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -872,7 +872,7 @@ export class BackendSocket {private emitReply(connId: string, type: string, requestId: unknown, payload: Record<string, unknown>): void {const resultType = rpcResultType(type)// Before the E2EE wrap: an RPC reply is only readable here.- if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'git_pull_requests_status' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })+ if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('viewer_') && type !== 'phone_pair' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'machine_addon' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'orchestrator' && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'git_pull_requests_status' && type !== 'agent_handoff_prepare' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) logFrame('→', connId ? `conn:${sid(connId)}` : 'backend', { type: resultType, payload: { requestId, ...payload } })if (this.localClients.has(connId)) {this.sendTo(connId, { type: resultType, payload: { requestId, ...payload } })return@@ -933,7 +933,7 @@ export class BackendSocket {// actually asked for rather than as an opaque __e2e envelope.// Terminal frames contain raw keystrokes, paste text and screen bytes after// unwrap. Never pass them to the frame logger, even in diagnostic mode.- if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'git_pull_requests_status' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {+ if (env.LOG_FRAMES && !MESSAGE_REQUESTS.has(type) && !ROUTE_COMMAND_TYPES.has(type) && !type.startsWith('terminal_') && !type.startsWith('viewer_') && !type.startsWith('grid_fleet_') && type !== 'agent_read_file' && type !== 'project_preview' && type !== 'git_project_info' && type !== 'scm_project_info' && type !== 'git_pull_request' && type !== 'git_pull_requests_status' && type !== 'agent_handoff_prepare' && type !== 'orchestrator' && type !== 'api_connections' && type !== 'connectors' && type !== 'os_device' && type !== 'machine_addon' && type !== 'browser_open' && type !== 'browser_callback' && type !== 'phone_pair' && !SHARE_REQUEST_TYPES.has(type) && !type.startsWith('pair')) {logFrame('←', connId ? `conn:${sid(connId)}` : 'backend', frame)}const launchMeasured = productUsageLaunch(type, (frame.payload as { creationId?: unknown } | undefined)?.creationId,@@ -1028,7 +1028,9 @@ export class BackendSocket {// A request a service answers, in its own process or in this one: routed to it, or answered// SERVICE_UNAVAILABLE while it is off. Never waited on in line: the next frame is not held for it.// Who asked is established here, after the gates above, and the service trusts only that.- const asker: Asker = { local, owner, ...(!local ? { accountOwner: this.remoteClient(connId)?.accountOwner === true } : {}),+ const client = local ? null : this.remoteClient(connId)+ const asker: Asker = { local, owner, ...(!local ? { accountOwner: client?.accountOwner === true } : {}),+ ...(client?.machineId ? { machine: { machineId: client.machineId, label: client.label } } : {}),...(guest !== undefined ? { guest } : {}),connection: connId, ...(typeof requestId === 'string' ? { requestId } : {}) }// A window that draws row state asks for the models list with `rowState`, and the list's changes arediff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 4e622f7b3..f17095ac2 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -616,6 +616,9 @@ export interface Asker {accountOwner?: boolean/** A guest's session (RemoteClient.guest): the account it is shared with. Never `owner`. */guest?: string+ /** Another of the owner's machines, when the request came over that machine's own link: its id as its pairing+ * record holds it, and the label it was paired under. Set by the core from the gateway's record, never the payload. */+ machine?: { machineId: string; label: string | null }/** The connection it came over (a window's, a remote client's), as the core names it, and the id it* asked under: what a service keys work by that belongs to one connection (the Model Manager's grid* commands, which a cancel on the same connection stops; a limit on how many at once per connection).@@ -708,6 +711,9 @@ export const SHARED_MACHINES_OFF: SharedMachinesCorePort = { guestLaunch: async/** A Harness OS computer managed from the owner's phone: whether it runs Harness OS, its update, and its Wi-Fi,* in the edge host (services/osDevice.ts). */export const OS_DEVICE_REQUESTS = ['os_device'] as const+/** Add-ons for a device that is this Harness machine (lib/autonomous-device/machineAddons.ts): the owner's machines+ * read what it published and propose to it, each proposal stamped with the machine it came from. */+export const MACHINE_ADDON_REQUESTS = ['machine_addon'] as const/*** Models (services/models.ts).*@@ -748,6 +754,8 @@ const MINUTE = 60_000export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, number>>>> = {// Fifty GitHub reads, four at a time, each with an eight-second subprocess deadline.projects: { git_pull_requests_status: 120_000 },+ // The device's own service waits up to 20 s for its next proposal (lib/autonomous-device/machineAddons.ts).+ machineAddons: { machine_addon: 30_000 },models: {grid_fleet_run: GRID_FLEET_MAX_TIMEOUT_MS + MINUTE,grid_fleet_models_list: 15 * MINUTE, grid_fleet_model_download: 15 * MINUTE, grid_fleet_model_start: 15 * MINUTE,@@ -1453,6 +1461,8 @@ export interface RemoteClient {label: string | nullidentity: stringdirect: boolean+ /** The machine this session's identity was paired as, when it is one of the owner's machines (`kind: 'machine'`). */+ machineId?: string}/** How a remote client's frame arrived: the backend's relay, or a paired client's own P2P channel. */diff --git a/cli/src/core/devicesWake.ts b/cli/src/core/devicesWake.tsindex 93bda88b9..4d1f6f0ba 100644--- a/cli/src/core/devicesWake.ts+++ b/cli/src/core/devicesWake.ts@@ -20,8 +20,8 @@import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'import { join } from 'node:path'-/** The services in the devices' process, which a request or a notice for wakes. */-export const DEVICES_ON_DEMAND = ['devices', 'wifi'] as const+/** The services in the devices' process, which a request or a notice for wakes: a device that is this machine's add-ons too. */+export const DEVICES_ON_DEMAND = ['devices', 'wifi', 'machineAddons'] as const/** How often /dev is looked at for a dial's port while there is none: the dial's own scan's cadence. */export const DIAL_LOOK_MS = 2_000/** The Wi-Fi device's direct links (lib/autonomous-device/direct.ts) and the gateway's pairings (lib/e2ee/store.ts),diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.tsindex 0811b2246..71162d694 100644--- a/cli/src/core/experimentQueries.spec.ts+++ b/cli/src/core/experimentQueries.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from 'vitest'import type { RegisteredSession } from '../lib/registry.js'import { fakeCore } from '../testing/fakeCore.js'-import { answerExperimentQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'+import { answerExperimentQuery, answerMachineAddonsQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w' }) as RegisteredSessionconst experiments = new Set(['orchestrator'])@@ -290,3 +290,15 @@ it('lets only the Swarm service reopen a Lead or close a member, by a valid agenexpect(keepLeadAlive).toHaveBeenCalledTimes(1)expect(closeMember).toHaveBeenCalledTimes(2)})++describe('what the add-ons of a device that is this machine ask of the core', () => {+ it('is told this daemon\'s address, though not an experiment, and nothing else of the experiments\' doors', async () => {+ const core = fakeCore({ daemon: { machineId: () => 'm_account' } as never })+ expect(answerMachineAddonsQuery(core, 'machineAddons', 'daemon')).toEqual({ command: 'harness', port: 18473, machineId: 'm_account', autonomousEnv: 'prod' })+ // The experiments' check alone would refuse it: the reason the core asks this first (core/main.ts).+ expect(await answerExperimentQuery(core, experiments, 'machineAddons', 'daemon', {})).toEqual({ error: 'NOT_AN_EXPERIMENT' })+ expect(answerMachineAddonsQuery(core, 'machineAddons', 'shown')).toBeNull()+ expect(answerMachineAddonsQuery(core, 'wifi', 'daemon')).toBeNull()+ })+})+diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.tsindex fc86f68fa..04a461f34 100644--- a/cli/src/core/experimentQueries.ts+++ b/cli/src/core/experimentQueries.ts@@ -65,6 +65,13 @@ export function daemonAddress(core: Pick<CoreApi, 'daemon'>): Payload {return { command: core.daemon.command, port: core.daemon.port, machineId: core.daemon.machineId(), autonomousEnv: core.daemon.autonomousEnv }}+/** What the add-ons of a device that is this machine ask in their own process (services/machineAddonsProcess.ts):+ * this daemon's address, for the account's machine id. Answered before the experiments' check, which would refuse+ * it as NOT_AN_EXPERIMENT; any other query of theirs is not answered here. */+export function answerMachineAddonsQuery(core: Pick<CoreApi, 'daemon'>, service: string, query: string): Payload | null {+ return service === 'machineAddons' && query === 'daemon' ? daemonAddress(core) : null+}+/** The answer to an experiment's query, or null when it is not one of these. */export async function answerExperimentQuery(core: Core, experiments: ReadonlySet<string>, service: string, query: string, payload: Payload): Promise<Payload | null> {if (!QUERIES.has(query)) return nulldiff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex e7d6cd3cb..f7ae28c75 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -187,7 +187,7 @@ import { createEngineHooks, installEngineHooks, installOpencodePluginBeforeSpawnimport { createCursorDiscovery } from './engines/cursorDiscovery.js'import { createCursorTaskHooks, loadPendingCursorTasks } from './engines/cursorTasks.js'import { databaseHistory, hermesDb } from './transcripts/databaseHistory.js'-import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, SHARED_MACHINES_FALLBACKS, SHARED_MACHINES_OFF, SHARED_MACHINES_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, OS_DEVICE_REQUESTS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'+import { CLOUD_FALLBACKS, CLOUD_REQUESTS, type CloudCore, CONNECTORS_REQUESTS, SHARED_MACHINES_FALLBACKS, SHARED_MACHINES_OFF, SHARED_MACHINES_REQUESTS, MEMORY_REQUESTS, ROUTER_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, MACHINE_ADDON_REQUESTS, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, OS_DEVICE_REQUESTS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_FALLBACKS, STORE_OFF, STORE_REQUESTS, MESSAGES_FALLBACKS, MESSAGES_REQUESTS, TURN_DELIVERERS, USAGE_FALLBACKS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type WindowFocus } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { SUPER_TAB_REQUESTS, SUPER_TAB_FALLBACKS } from './api.js'import { startStalls } from './stall.js'@@ -209,7 +209,7 @@ import { createDeliveries } from './deliveries.js'import { createTerminalWatch } from './terminalWatch.js'import { createSharingLink } from './sharingLink.js'import { createAgentSettingsSync, createExperimentHooks, wakeExperiments } from './experiments.js'-import { answerExperimentQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'+import { answerExperimentQuery, answerMachineAddonsQuery, createForExperiment, creationForExperiment } from './experimentQueries.js'import { createSuperTabAttention } from './superTabAttention.js'import { createSuperTabTerminal } from './superTabTerminal.js'import { createSuperTabCards } from './superTabCards.js'@@ -236,7 +236,7 @@ import { wakeGateway } from './gatewayWake.js'import { createViewersWake, VIEWERS_ON_DEMAND, wakeViewers } from './viewersWake.js'import { createWifiLink } from './wifiLink.js'import { wifiDoors } from './wifiAgents.js'-import { autonomousDeviceLocalRequest, deviceAddonRoutes } from '../lib/deviceManagementHttp.js'+import { autonomousDeviceLocalRequest, deviceAddonRoutes, machineAddonRoutes } from '../lib/deviceManagementHttp.js'import { loadOrCreateHookCredential } from '../lib/hookAuth.js'import { attachLocalWsServer, LOCAL_WS_PATH, LOCAL_WS_PROTOCOL_VERSION } from '../localWsServer.js'import { TERMINAL_BINARY_VERSION } from '../lib/terminalBinary.js'@@ -1460,7 +1460,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The requests each service that can run in its own process answers, as core/api.ts declares them.const requestsOf: Record<string, readonly string[]> = {search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS, handoff: HANDOFF_REQUESTS, connectors: CONNECTORS_REQUESTS, sharedMachines: SHARED_MACHINES_REQUESTS,- devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS, shell: SHELL_REQUESTS, messages: MESSAGES_REQUESTS, osDevice: OS_DEVICE_REQUESTS,+ devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS, shell: SHELL_REQUESTS, messages: MESSAGES_REQUESTS, osDevice: OS_DEVICE_REQUESTS, machineAddons: MACHINE_ADDON_REQUESTS,...Object.fromEntries(Object.entries(EXPERIMENTS).map(([name, experiment]) => [name, experiment.requests])),}// The experiments (core/api.ts `EXPERIMENTS`): each may act on the core through the hooks an experiment has.@@ -1560,6 +1560,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {?? (service === 'messages' ? await messagesLink.answer(query, payload) : null)?? await answerConnectorsQuery(coreApi, service, query, payload)?? await answerSharedMachinesQuery(sharedMachinesAccount, service, query, payload)+ ?? answerMachineAddonsQuery(coreApi, service, query)?? await answerExperimentQuery(coreApi, experiments, service, query, payload)?? await terminalWatch.answer(service, query, payload)?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)@@ -1708,6 +1709,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {{ port: inlineSharedMachinesPort(sharedMachinesAccount, core.account.signedIn()), ports: staged }), coreApi, SHARED_MACHINES_FALLBACKS, SHARED_MACHINES_REQUESTS)// A Harness OS computer managed from the owner's phone: its update and its Wi-Fi (services/osDevice.ts): here, or in the edge host.if (!outOfProcess.has('osDevice')) serviceHost.serve('osDevice', inline!.startOsDevice, coreApi, OS_DEVICE_REQUESTS)+ // Add-ons of a device that is this machine (services/machineAddons.ts, openharness#1654): here, or in the edge host.+ if (!outOfProcess.has('machineAddons')) serviceHost.serve('machineAddons', inline!.startMachineAddons, coreApi, MACHINE_ADDON_REQUESTS)// The recaps: in this process, or in the edge host (services/recapsProcess.ts), told each turn's lifecycle.if (outOfProcess.has('recaps')) ports.recaps = recapsLink.port; else serviceHost.start('recaps', inline!.startRecaps, coreApi, RECAPS_FALLBACKS)// Cleaning up after agents: the harnesses a closed harness started, and those idle half an hour (services/agentCleanup.ts).@@ -2083,6 +2086,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {return { receipt: answer.receipt }},...deviceAddonRoutes((op, input) => ports.wifi?.addon(op, input) ?? Promise.resolve({ unavailable: true as const })),+ // The device's own service, on this machine: the same `machine_addon` door, asked as a process here.+ ...machineAddonRoutes((op, input, waitMs) => outOfProcess.has('machineAddons')+ ? serviceLinks.call('machineAddons', 'machine_addon', { op, input }, waitMs + 5_000)+ : new Promise((resolve) => { if (!serviceHost.route('machine_addon', { op, input }, { local: true, owner: true }, resolve)) resolve({ error: 'SERVICE_UNAVAILABLE' }) })),}, method, target, body)},resolveHookAgent: engineHooks.resolveHookAgent,diff --git a/cli/src/gateway/gateway.ts b/cli/src/gateway/gateway.tsindex 8054625d1..888ae25eb 100644--- a/cli/src/gateway/gateway.ts+++ b/cli/src/gateway/gateway.ts@@ -168,6 +168,7 @@ export class RelayGateway implements GatewayPort {this.core.client(connId, {role, label: this.e2ee.sessionLabel(connId), identity, direct: this.directDeviceSinks.has(connId),accountOwner: role === 'web' && !!peer && !peer.shared,+ ...(peer?.kind === 'machine' && peer.machineId && !peer.shared ? { machineId: peer.machineId } : {}),// Trusted only because this machine is shared: that account's guest, never the owner....(peer?.shared ? { guest: peer.sharedWith ?? '' } : {}),})diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.tsindex a7e75a6c9..13dd781c8 100644--- a/cli/src/harnessd/master.spec.ts+++ b/cli/src/harnessd/master.spec.ts@@ -347,11 +347,11 @@ describe('runMaster', { timeout: 60_000 }, () => {exit: (code) => exits.push(code), onSignal: (signal, listener) => signals.set(signal, listener),})await until('the core and a service to be running', () => supervisor.status().state === 'running' && existsSync(ran) && existsSync(`${ran}search`))- await until('the devices\' process the core asked for', () => existsSync(`${ran}devices,wifi`))+ await until('the devices\' process the core asked for', () => existsSync(`${ran}devices,wifi,machineAddons`))const libexec = join(realpathSync(runtime), 'node-v1', 'libexec', 'harnessd')expect(readFileSync(ran, 'utf8')).toBe(join(libexec, 'harnessd-core'))expect(readFileSync(`${ran}search`, 'utf8')).toBe(join(libexec, 'harnessd-search'))- expect(readFileSync(`${ran}devices,wifi`, 'utf8')).toBe(join(libexec, 'harnessd-devices'))+ expect(readFileSync(`${ran}devices,wifi,machineAddons`, 'utf8')).toBe(join(libexec, 'harnessd-devices'))signals.get('SIGTERM')!()await until('the master to finish', () => exits.length > 0)})diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.tsindex d610414a4..ae031bbaa 100644--- a/cli/src/harnessd/services.spec.ts+++ b/cli/src/harnessd/services.spec.ts@@ -475,9 +475,9 @@ describe('ServiceSupervisor', () => {it('runs the devices only once there is one, asked for by a core of protocol 4, and from the start when named (tests)', () => {const [devices] = serviceSpecs({}, SERVICE_HOSTS).filter((spec) => spec.name === 'devices')- expect(devices).toMatchObject({ services: ['devices', 'wifi'], onDemand: true, askedSince: 4 })+ expect(devices).toMatchObject({ services: ['devices', 'wifi', 'machineAddons'], onDemand: true, askedSince: 4 })const [named] = serviceSpecs({ HARNESSD_SERVICES: 'devices' }, SERVICE_HOSTS)- expect(named.services).toEqual(['devices', 'wifi'])+ expect(named.services).toEqual(['devices', 'wifi', 'machineAddons'])expect(named.onDemand).toBeUndefined()})diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex 4816bf9b9..4e61e8f2a 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -436,7 +436,7 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// on a link of its own: its receipts, its streams and its Store preparations. Started only once there is// a device, or a request for one (core/devicesWake.ts): about 72 MiB at idle, which a computer with none// never pays.- devices: { services: ['devices', 'wifi'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true, askedSince: 4 },+ devices: { services: ['devices', 'wifi', 'machineAddons'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true, askedSince: 4 },}/** Every service this build can run outside the core's process: what `HARNESSD_SERVICES` names. */diff --git a/cli/src/lib/autonomous-device/addonCommand.spec.ts b/cli/src/lib/autonomous-device/addonCommand.spec.tsindex 14a502357..38b1c26d5 100644--- a/cli/src/lib/autonomous-device/addonCommand.spec.ts+++ b/cli/src/lib/autonomous-device/addonCommand.spec.ts@@ -1,6 +1,7 @@import { createHash } from 'node:crypto'import { afterEach, describe, expect, it, vi } from 'vitest'import { runAutonomousDeviceCommand } from './command.js'+import { pickMachine, runAddonCommand } from './addonCommand.js'vi.mock('../hookAuth.js', () => ({ readHookCredential: () => 'hook-test-credential' }))afterEach(() => vi.restoreAllMocks())@@ -71,3 +72,37 @@ describe('harness autonomous-device addon', () => {expect(fetch).not.toHaveBeenCalled()})})++describe('harness autonomous-device addon --machine', () => {+ it('asks the named machine over its link, with the same proposal, and says the key when it fails', async () => {+ const fetch = vi.spyOn(globalThis, 'fetch'); const log = quiet()+ const asked: Array<[string, string, Record<string, unknown>]> = []+ const ask = async (machine: string, op: string, input: Record<string, unknown>) => {+ asked.push([machine, op, input])+ return op === 'propose' ? { error: { code: 'MACHINE_REQUIRED', message: 'no machine' } } : { result: { devices: [] } }+ }+ expect(await runAddonCommand(['state', '--machine', 'lamp-4ace'], '/unused', 18473, {}, ask)).toBe(0)+ expect(await runAddonCommand(['proposal', 'p1', '--machine', 'lamp-4ace'], '/unused', 18473, {}, ask)).toBe(0)+ expect(await runAddonCommand(['propose', '--machine', 'lamp-4ace', '--act', 'say', '--holds-ms', '30000', '--note', 'hi', '--addon', 'slack', '--key', 'k1'], '/unused', 18473, {}, ask)).toBe(1)+ expect(asked).toEqual([['lamp-4ace', 'state', {}], ['lamp-4ace', 'proposal', { proposalId: 'p1' }],+ ['lamp-4ace', 'propose', { addon: 'slack', act: 'say', holdsMs: 30000, idempotencyKey: 'k1', note: 'hi' }]])+ expect(JSON.parse(String(log.mock.calls.at(-1)?.[0]))).toEqual({ error: { code: 'MACHINE_REQUIRED', message: 'no machine' }, idempotencyKey: 'k1' })+ expect(await runAddonCommand(['state', '--machine', 'lamp', '--device', 'x'], '/unused', 18473, {}, ask)).toBe(1)+ expect(fetch).not.toHaveBeenCalled()+ })+})++describe('the machine --machine names', () => {+ const rows = [{ machineId: 'm_lamp', name: 'lamp-4ace' }, { machineId: 'm_a', name: 'Office' }, { machineId: 'm_b', hostname: 'office' },+ { machineId: 'm_shared', name: 'kim', isShared: true }]+ it('is an id, or the one machine of that name, case-blind; this machine too, as its own row', () => {+ expect(pickMachine('m_lamp', rows)).toBe('m_lamp')+ expect(pickMachine('LAMP-4ACE', rows)).toBe('m_lamp')+ expect(pickMachine('m_b', rows)).toBe('m_b')+ })+ it('refuses two machines of one name, and a machine shared with this account', () => {+ expect(() => pickMachine('office', rows)).toThrow(expect.objectContaining({ code: 'AMBIGUOUS' }))+ expect(() => pickMachine('kim', rows)).toThrow(expect.objectContaining({ code: 'MACHINE_NOT_FOUND' }))+ })+})+diff --git a/cli/src/lib/autonomous-device/addonCommand.ts b/cli/src/lib/autonomous-device/addonCommand.tsindex 1a1311de6..4dd3a36e5 100644--- a/cli/src/lib/autonomous-device/addonCommand.ts+++ b/cli/src/lib/autonomous-device/addonCommand.ts@@ -1,12 +1,46 @@import { createHash, randomUUID } from 'node:crypto'import { readHookCredential } from '../hookAuth.js'import { outsideCaller } from '../../agentClient/model.js'+import { WebSocket } from 'ws'+import { deviceRequest } from '../../devices/client.js'+import { localCredentialHeaders } from '../localCredential.js'const USAGE = 'Usage: harness autonomous-device addon state [--device <id>]'+ ' | addon propose --act <act> --holds-ms <ms> [--why <why>] [--sure <0..1>] [--params <json>] [--note <text>] [--addon <name>] [--key <key>] [--device <id>]'- + ' | addon proposal <proposalId> [--json]. To retry a propose that got no answer, pass the same --key, which it prints.'+ + ' | addon proposal <proposalId> [--json]. --machine <name> instead of --device: a device that is one of your Harness machines.'+ + ' To retry a propose that got no answer, pass the same --key, which it prints.'-const VALUE_FLAGS = new Set(['--device', '--act', '--holds-ms', '--why', '--sure', '--params', '--note', '--addon', '--key'])+const VALUE_FLAGS = new Set(['--device', '--machine', '--act', '--holds-ms', '--why', '--sure', '--params', '--note', '--addon', '--key'])++/** Asks another of the owner's machines (`machine_addon`, lib/autonomous-device/machineAddons.ts): its answer, or a throw. */+export type MachineAsk = (machine: string, op: string, input: Record<string, unknown>) => Promise<Record<string, unknown>>++/** The owner's machine `--machine` names, by id or name (case-blind), as this daemon lists the account's machines. */+async function machineIdOf(word: string, dataDir: string, port: number): Promise<string> {+ const response = await fetch(`http://127.0.0.1:${port}/api/machines`, {+ headers: { 'x-adapter-local': '1', ...localCredentialHeaders(dataDir) }, signal: AbortSignal.timeout(8000) })+ if (!response.ok) throw Object.assign(new Error('Could not read the account\'s machines. Sign in and try again.'), { code: 'MACHINES_UNAVAILABLE' })+ const body = await response.json() as { data?: { machines?: Record<string, unknown>[] }; machines?: Record<string, unknown>[] }+ return pickMachine(word, body.data?.machines ?? body.machines ?? [])+}++/** The machine `word` names among the account's own: its id, or else its one name. Two of the same name is refused. */+export function pickMachine(word: string, machines: Record<string, unknown>[]): string {+ const rows = machines.filter(row => typeof row.machineId === 'string' && !row.isShared)+ const byId = rows.find(row => row.machineId === word)+ if (byId) return byId.machineId as string+ const lower = word.toLowerCase()+ const named = rows.filter(row => [row.name, row.hostname].some(name => typeof name === 'string' && name.toLowerCase() === lower))+ if (named.length > 1) throw Object.assign(new Error(`${named.length} of your machines are called ${word}: name one by its id.`), { code: 'AMBIGUOUS' })+ if (!named.length) throw Object.assign(new Error(`None of your machines is called ${word}.`), { code: 'MACHINE_NOT_FOUND' })+ return named[0].machineId as string+}++const askMachine = (dataDir: string, port: number): MachineAsk => async (machine, op, input) => {+ const machineId = await machineIdOf(machine, dataDir, port)+ return deviceRequest({ port, dataDir, machineId: async () => null, connect: (url, headers) => new WebSocket(url, { headers }) },+ machineId, 'machine_addon', { op, input })+}/*** The add-on's name a device is told: `--addon`, or the agent whose shell runs this, as its engine and a short@@ -27,7 +61,8 @@ const SURE = /^(0(\.\d{1,6})?|1(\.0{1,6})?|\.\d{1,6})$/const WHOLE = /^\d{1,6}$//** `harness autonomous-device addon …`: read what paired devices publish, or propose to one. */-export async function runAddonCommand(argv: string[], dataDir: string, port: number, env: NodeJS.ProcessEnv = process.env): Promise<number> {+export async function runAddonCommand(argv: string[], dataDir: string, port: number, env: NodeJS.ProcessEnv = process.env,+ ask: MachineAsk = askMachine(dataDir, port)): Promise<number> {const json = argv.includes('--json'), args: string[] = [], flags = new Map<string, string>()let invalid = falsefor (let i = 0; i < argv.length; i++) {@@ -42,8 +77,9 @@ export async function runAddonCommand(argv: string[], dataDir: string, port: numconst print = (value: unknown) => console.log(JSON.stringify(value, null, json ? undefined : 2))const usage = (message = USAGE) => { print({ error: { code: 'INVALID_ARGUMENT', message } }); return 1 }const verb = args[0]- const allowed = verb === 'state' ? ['--device'] : verb === 'proposal' ? [] : verb === 'propose' ? [...VALUE_FLAGS] : null+ const allowed = verb === 'state' ? ['--device', '--machine'] : verb === 'proposal' ? ['--machine'] : verb === 'propose' ? [...VALUE_FLAGS] : nullif (invalid || !allowed || [...flags.keys()].some(f => !allowed.includes(f)) || args.length !== (verb === 'proposal' ? 2 : 1)) return usage()+ if (flags.has('--machine') && flags.has('--device')) return usage('Name a paired device with --device, or a machine with --machine, not both')let path: string, method = 'GET', body: Record<string, unknown> | undefinedif (verb === 'state') {@@ -71,6 +107,26 @@ export async function runAddonCommand(argv: string[], dataDir: string, port: num...(flags.has('--device') ? { deviceId: flags.get('--device') } : {}) }path = 'addon/propose'; method = 'POST'}+ const machine = flags.get('--machine')+ if (machine) {+ const input = verb === 'proposal' ? { proposalId: args[1] } : verb === 'state' ? {} : body!+ try {+ const answer = await ask(machine, verb, input)+ const error = answer.error as { code?: unknown } | string | undefined+ if (error !== undefined) {+ // An older machine answers a bare code; this one says what went wrong.+ print({ error: typeof error === 'string' ? { code: error, message: error } : error, ...(body ? { idempotencyKey: body.idempotencyKey } : {}) })+ return 1+ }+ print(answer.result ?? answer)+ return 0+ } catch (error) {+ const code = (error as { code?: unknown }).code+ print({ error: { code: typeof code === 'string' ? code : 'OUTCOME_UNKNOWN', message: error instanceof Error ? error.message : String(error) },+ ...(body ? { idempotencyKey: body.idempotencyKey } : {}) })+ return 1+ }+ }const credential = readHookCredential(dataDir)if (!credential) { print({ error: { code: 'DAEMON_UNAVAILABLE', message: 'Start Harness with harness start first.' } }); return 1 }try {diff --git a/cli/src/lib/autonomous-device/addons.ts b/cli/src/lib/autonomous-device/addons.tsindex 791a967d8..304922499 100644--- a/cli/src/lib/autonomous-device/addons.ts+++ b/cli/src/lib/autonomous-device/addons.ts@@ -76,9 +76,12 @@ export const AddonProposeSchema = z.strictObject({export type AddonPropose = z.infer<typeof AddonProposeSchema>export type ProposalState = 'sent' | 'kept' | 'dropped' | 'expired'+/** The machine a proposal came from, as the link that carried it proves it (Asker.machine), never as its payload says. */+export interface ProposalSource { machineId: string; label: string | null }export interface AddonProposal {proposalId: string; deviceId: string; addon: string; idempotencyKey: stringact: string; why?: string; sure?: number; holdsMs: number; params?: Record<string, unknown>; note?: string+ from?: ProposalSourcestate: ProposalState; reason: string | null; sentAt: number; expiresAt: number; decidedAt: number | null}export interface AddonTopicValue { value: Record<string, unknown>; at: number | null; receivedAt: number }@@ -146,8 +149,9 @@ export class DeviceAddons {return { proposalId, state: p.state }}- /** An agent's proposal: validated, rate-limited, then sent to the device's links. */- propose(input: unknown): AddonProposal {+ /** An agent's proposal: validated, rate-limited, then sent to the device's links, with the machine it came+ * from when the caller proved one. */+ propose(input: unknown, from?: ProposalSource): AddonProposal {const parsed = AddonProposeSchema.safeParse(input)if (!parsed.success) fail('INVALID_REQUEST', parsed.error.issues[0]?.message ?? 'Invalid proposal')const req = parsed.data!@@ -157,7 +161,8 @@ export class DeviceAddons {const { deviceId: _target, idempotencyKey: _key, ...intent } = reqconst digest = createHash('sha256').update(canonical(intent)).digest('hex')for (const existing of this.proposals.values()) {- if (existing.addon !== req.addon || existing.idempotencyKey !== req.idempotencyKey) continue+ // A key is the proposing machine's own: another machine's same key is another proposal, and says nothing of it.+ if (existing.addon !== req.addon || existing.idempotencyKey !== req.idempotencyKey || existing.from?.machineId !== from?.machineId) continueif (existing.digest !== digest || (req.deviceId && req.deviceId !== existing.deviceId)) fail('IDEMPOTENCY_CONFLICT', 'Key already belongs to a different proposal')return this.view(existing)}@@ -173,6 +178,7 @@ export class DeviceAddons {const proposal = { proposalId: randomUUID(), deviceId, addon: req.addon, idempotencyKey: req.idempotencyKey, act: req.act,...(req.why ? { why: req.why } : {}), ...(req.sure !== undefined ? { sure: req.sure } : {}), holdsMs: req.holdsMs,...(req.params ? { params: structuredClone(req.params) } : {}), ...(req.note ? { note: req.note } : {}),+ ...(from ? { from: { machineId: from.machineId, label: from.label } } : {}),state: 'sent' as ProposalState, reason: null, sentAt: now, expiresAt: now + req.holdsMs, decidedAt: null, digest }this.proposals.set(proposal.proposalId, proposal)const { deviceId: _d, idempotencyKey: _i, state: _s, reason: _r, sentAt: _t, decidedAt: _a, digest: _g, ...payload } = proposaldiff --git a/cli/src/lib/autonomous-device/machineAddons.spec.ts b/cli/src/lib/autonomous-device/machineAddons.spec.tsnew file mode 100644index 000000000..c1edd245b--- /dev/null+++ b/cli/src/lib/autonomous-device/machineAddons.spec.ts@@ -0,0 +1,144 @@+import { describe, expect, it } from 'vitest'+import type { Asker } from '../../core/api.js'+import { INBOX_MAX, MachineAddons } from './machineAddons.js'++const LAMP = 'm_lamp'+const OFFICE: Asker = { local: false, owner: true, accountOwner: true, machine: { machineId: 'm_office', label: 'office' } }+const LAPTOP: Asker = { local: false, owner: true, accountOwner: true, machine: { machineId: 'm_laptop', label: 'laptop' } }++function fixture() {+ let clock = 1_000_000+ const addons = new MachineAddons({ machineId: () => LAMP, now: () => clock })+ let keys = 0+ const propose = (asker: Asker, fields: Record<string, unknown> = {}) =>+ addons.request({ op: 'propose', input: { addon: 'slack-summary', idempotencyKey: `k${++keys}`, act: 'say', holdsMs: 10_000, note: 'Three new in #team.', ...fields } }, asker)+ return { addons, propose, tick: (ms: number) => { clock += ms } }+}++describe('machine add-ons: a device that is this Harness machine', () => {+ it('serves what its own service published to the owner\'s machines, and clears it at the service\'s hello', () => {+ const f = fixture()+ expect(f.addons.publish([{ topic: 'voice/state', value: { state: 'listening' } }])).toEqual({ topics: 1, instance: f.addons.instance })+ expect(f.addons.request({ op: 'state' }, OFFICE)).toEqual({ result: { devices: [{ deviceId: LAMP, online: true,+ topics: { 'voice/state': { value: { state: 'listening' }, at: null, receivedAt: 1_000_000 } } }] } })+ f.addons.hello()+ expect(f.addons.request({ op: 'state' }, OFFICE)).toEqual({ result: { devices: [] } })+ })++ it('stamps a proposal with the machine the link proved, never one the payload names, and targets this machine', async () => {+ const f = fixture()+ f.addons.publish([{ topic: 'voice/state', value: { state: 'resting' } }])+ const answer = f.propose(OFFICE, { deviceId: 'someone-else' }) as { result: { proposal: Record<string, unknown> } }+ expect(answer.result.proposal).toMatchObject({ deviceId: LAMP, addon: 'slack-summary', state: 'sent', from: { machineId: 'm_office', label: 'office' } })+ expect(f.addons.request({ op: 'propose', input: { addon: 'x', idempotencyKey: 'k', act: 'say', holdsMs: 5000, from: { machineId: 'm_x' } } }, OFFICE))+ .toMatchObject({ error: { code: 'INVALID_REQUEST' } })+ const { proposals, next } = await f.addons.proposals(0)+ expect(next).toBe(1)+ expect(proposals).toEqual([{ seq: 1, proposal: expect.objectContaining({ proposalId: answer.result.proposal.proposalId, note: 'Three new in #team.',+ from: { machineId: 'm_office', label: 'office' } }) }])+ })++ it('lets the owner\'s machines alone in, and needs a proven machine to propose', () => {+ const f = fixture()+ f.addons.publish([{ topic: 'voice/state', value: {} }])+ for (const asker of [{ local: false, owner: false }, { local: false, owner: true, accountOwner: false },+ { local: false, owner: false, guest: '[email protected]', accountOwner: false, machine: { machineId: 'm_kim', label: null } }] as Asker[]) {+ expect(f.addons.request({ op: 'state' }, asker)).toMatchObject({ error: { code: 'OWNER_REQUIRED' } })+ }+ // The owner's phone or browser: may read, but a proposal says which computer it came from, and this one is none.+ expect(f.addons.request({ op: 'state' }, { local: false, owner: true, accountOwner: true })).toHaveProperty('result')+ expect(f.propose({ local: false, owner: true, accountOwner: true })).toMatchObject({ error: { code: 'MACHINE_REQUIRED' } })+ // An agent on the device itself: this machine.+ expect(f.propose({ local: true, owner: true })).toMatchObject({ result: { proposal: { from: { machineId: LAMP, label: null } } } })+ })++ it('reads a proposal back to the machine that made it alone, with the decision the device\'s service gave', () => {+ const f = fixture()+ f.addons.publish([{ topic: 'voice/state', value: {} }])+ const id = ((f.propose(OFFICE) as { result: { proposal: { proposalId: string } } }).result.proposal.proposalId)+ expect(f.addons.decide({ proposalId: id, decision: 'kept', reason: 'quiet, at the desk' })).toEqual({ proposalId: id, state: 'kept' })+ expect(f.addons.request({ op: 'proposal', input: { proposalId: id } }, OFFICE)).toMatchObject({ result: { proposal: { state: 'kept', reason: 'quiet, at the desk' } } })+ expect(f.addons.request({ op: 'proposal', input: { proposalId: id } }, LAPTOP)).toMatchObject({ error: { code: 'PROPOSAL_UNKNOWN' } })+ expect(() => f.addons.decide({ proposalId: id, decision: 'dropped' })).toThrow('already kept')+ })++ it('keeps v1\'s bounds: no device to propose to until the service publishes, and the same rates', () => {+ const f = fixture()+ expect(f.propose(OFFICE)).toMatchObject({ error: { code: 'DEVICE_NOT_FOUND' } })+ f.addons.publish([{ topic: 'voice/state', value: {} }])+ expect(f.propose(OFFICE, { note: 'x'.repeat(301) })).toMatchObject({ error: { code: 'PAYLOAD_TOO_LARGE' } })+ expect(f.addons.request({ op: 'unknown' }, OFFICE)).toMatchObject({ error: { code: 'INVALID_REQUEST' } })+ })++ it('wakes a waiting take at the next proposal, keeps a short inbox, and says when the cursor is ahead of it', async () => {+ const f = fixture()+ f.addons.publish([{ topic: 'voice/state', value: {} }])+ const waiting = f.addons.proposals(0, 5_000)+ f.propose(OFFICE)+ expect((await waiting).proposals).toHaveLength(1)+ expect(await f.addons.proposals(1)).toEqual({ proposals: [], next: 1, instance: f.addons.instance })+ expect(await f.addons.proposals(7)).toMatchObject({ reset: true, next: 1, proposals: [{ seq: 1 }] })+ for (let i = 0; i < INBOX_MAX + 3; i++) {+ f.tick(60_000)+ const answer = f.propose(OFFICE) as { result?: unknown; error?: unknown }+ expect(answer).toHaveProperty('result')+ const sent = await f.addons.proposals(0)+ f.addons.decide({ proposalId: (sent.proposals.at(-1)!.proposal as { proposalId: string }).proposalId, decision: 'dropped' })+ }+ const all = await f.addons.proposals(0)+ expect(all.proposals).toHaveLength(INBOX_MAX)+ expect(all.proposals[0].seq).toBe(all.next - INBOX_MAX + 1)+ })++ it('takes publishes and decisions over `machine_addon` from a process on this machine alone', async () => {+ const f = fixture()+ expect(await f.addons.request({ op: 'publish', input: { values: [{ topic: 'voice/state', value: {} }] } }, OFFICE)).toMatchObject({ error: { code: 'LOCAL_ONLY' } })+ expect(await f.addons.request({ op: 'publish', input: { values: [{ topic: 'voice/state', value: {} }] } }, { local: true, owner: true })).toMatchObject({ result: { topics: 1 } })+ const id = ((f.propose(OFFICE) as { result: { proposal: { proposalId: string } } }).result.proposal.proposalId)+ expect(await f.addons.request({ op: 'proposals', input: { after: 0 } }, { local: true, owner: true })).toMatchObject({ result: { next: 1, proposals: [{ seq: 1 }] } })+ expect(await f.addons.request({ op: 'decision', input: { proposalId: id, decision: 'maybe' } }, { local: true, owner: true })).toMatchObject({ error: { code: 'INVALID_REQUEST' } })+ expect(await f.addons.request({ op: 'decision', input: { proposalId: id, decision: 'dropped' } }, { local: true, owner: true })).toEqual({ result: { proposalId: id, state: 'dropped' } })+ expect(await f.addons.request({ op: 'hello' }, { local: true, owner: true })).toMatchObject({ result: { topics: 0 } })+ })++ it('tells the device\'s service that the store it published to is gone: another instance, or a cursor ahead of it', async () => {+ const before = fixture()+ before.addons.publish([{ topic: 'voice/state', value: {} }])+ const old = before.addons.instance+ // The daemon or its process restarted: a new store, empty, at cursor 0.+ const after = fixture()+ expect(after.addons.instance).not.toBe(old)+ expect(await after.addons.proposals(0, 0, old)).toEqual({ proposals: [], next: 0, instance: after.addons.instance, reset: true })+ expect(after.propose(OFFICE)).toMatchObject({ error: { code: 'DEVICE_NOT_FOUND' } })+ // A restarted store already past the old cursor reads from its start, so nothing new is skipped.+ after.addons.publish([{ topic: 'voice/state', value: {} }])+ for (let i = 0; i < 3; i++) { after.propose(OFFICE); after.tick(1) }+ expect(await after.addons.proposals(2, 0, old)).toMatchObject({ reset: true, next: 3, proposals: [{ seq: 1 }, { seq: 2 }, { seq: 3 }] })+ expect(await after.addons.proposals(2, 0, after.addons.instance)).toEqual({ proposals: [expect.objectContaining({ seq: 3 })], next: 3, instance: after.addons.instance })+ })++ it('says when proposals after the cursor were dropped from the inbox', async () => {+ const f = fixture()+ f.addons.publish([{ topic: 'voice/state', value: {} }])+ for (let i = 0; i < INBOX_MAX + 8; i++) {+ f.tick(60_000)+ f.propose(OFFICE)+ const last = (await f.addons.proposals(f.addons['seq'] - 1)).proposals.at(-1)!+ f.addons.decide({ proposalId: (last.proposal as { proposalId: string }).proposalId, decision: 'dropped' })+ }+ expect(await f.addons.proposals(0)).toMatchObject({ gap: true, proposals: { length: INBOX_MAX } })+ expect(await f.addons.proposals(8)).not.toHaveProperty('gap')+ expect(await f.addons.proposals(INBOX_MAX + 8)).not.toHaveProperty('gap')+ })++ it('keeps each machine\'s idempotency keys its own: the same key from another machine is another proposal', () => {+ const f = fixture()+ f.addons.publish([{ topic: 'voice/state', value: {} }])+ const input = { addon: 'slack-summary', idempotencyKey: 'same', act: 'say', holdsMs: 10_000, note: 'one' }+ const a = f.addons.request({ op: 'propose', input }, OFFICE) as { result: { proposal: { proposalId: string } } }+ const b = f.addons.request({ op: 'propose', input: { ...input, note: 'two' } }, LAPTOP) as { result: { proposal: { proposalId: string } } }+ expect(b.result.proposal.proposalId).not.toBe(a.result.proposal.proposalId)+ expect((f.addons.request({ op: 'propose', input }, OFFICE) as typeof a).result.proposal.proposalId).toBe(a.result.proposal.proposalId)+ expect(f.addons.request({ op: 'propose', input: { ...input, note: 'changed' } }, OFFICE)).toMatchObject({ error: { code: 'IDEMPOTENCY_CONFLICT' } })+ })+})diff --git a/cli/src/lib/autonomous-device/machineAddons.ts b/cli/src/lib/autonomous-device/machineAddons.tsnew file mode 100644index 000000000..b04e36925--- /dev/null+++ b/cli/src/lib/autonomous-device/machineAddons.ts@@ -0,0 +1,146 @@+import { randomUUID } from 'node:crypto'+import type { Asker, ServiceRequests } from '../../core/api.js'+import { DeviceAddonError, DeviceAddons, type AddonProposal, type ProposalSource } from './addons.js'++/**+ * Add-ons for a device that is itself a Harness machine (openharness#1654): the lampOS V2 lamp runs Harness and+ * is one of its person's machines, so it has no paired device channel to publish on. Its own add-on service, a+ * process of the same user on that machine, publishes and decides through this daemon's credential-checked+ * loopback routes; agents on the person's other machines read and propose over the machine link+ * (`machine_addon`, sealed like every machine request), and agents on the device itself through the same request.+ *+ * The contract, bounds, rates and lifetimes are v1's (addons.ts, docs/autonomous-device-addons.md), kept in RAM+ * and never judged here. Two things are added: each proposal says the machine it came from, as the link proved+ * it (`Asker.machine`), so the device can ask its person's yes per computer; and the device's own service takes+ * its proposals from a short inbox (`proposals`), waiting for the next one rather than polling.+ */+export const MACHINE_ADDON_OPS = ['state', 'propose', 'proposal'] as const+/** Only a process on this machine: the device's own service. */+export const LOCAL_OPS = ['hello', 'publish', 'decision', 'proposals'] as const+export type MachineAddonOp = typeof MACHINE_ADDON_OPS[number]+/** Proposals kept for the device's service to take; older ones are past their 30 s hold long before. */+export const INBOX_MAX = 32+/** The longest a take waits for the next proposal. */+export const TAKE_WAIT_MAX_MS = 20_000++export interface InboxEntry { seq: number; proposal: Record<string, unknown> }+export interface MachineAddonsOptions {+ /** This machine's id: the device the published state belongs to. */+ machineId: () => string+ now?: () => number+}++type Answer = { result: Record<string, unknown> } | { error: { code: string; message: string } }+const object = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value)++export class MachineAddons {+ private readonly addons: DeviceAddons+ private inbox: InboxEntry[] = []+ private seq = 0+ private readonly waiters = new Set<() => void>()+ /** This store's own id: a new one after any restart, so the device's service can tell it lost everything. */+ readonly instance = randomUUID()++ constructor(private readonly options: MachineAddonsOptions) {+ this.addons = new DeviceAddons({ machineId: '', serverInstanceId: randomUUID(), now: options.now,+ send: (_deviceId, frame) => { if (frame.kind === 'addon.proposal') this.received(frame.payload as Record<string, unknown>) } })+ }++ private get self(): string { return this.options.machineId() }++ private received(proposal: Record<string, unknown>): void {+ this.inbox.push({ seq: ++this.seq, proposal: structuredClone(proposal) })+ if (this.inbox.length > INBOX_MAX) this.inbox.splice(0, this.inbox.length - INBOX_MAX)+ for (const wake of [...this.waiters]) wake()+ }++ // ── the device's own service, over this machine's loopback (lib/deviceManagementHttp.ts) ─────────────++ /** The service started: what it published before is cleared, as a device's hello clears it. */+ hello(): Record<string, unknown> {+ this.addons.hello(this.self)+ return { topics: 0, instance: this.instance }+ }++ publish(values: unknown): Record<string, unknown> {+ return { ...this.addons.request(this.self, { type: 'addon.publish', requestId: randomUUID(), values }), instance: this.instance }+ }++ decide(input: { proposalId: unknown; decision: unknown; reason?: unknown }): Record<string, unknown> {+ return this.addons.request(this.self, { type: 'addon.decision', requestId: randomUUID(), proposalId: input.proposalId,+ decision: input.decision, ...(input.reason !== undefined ? { reason: input.reason } : {}) })+ }++ /**+ * The proposals after `after`, waiting up to `waitMs` for one when there are none. `next` is the cursor for the+ * next take, and `instance` this store's. `reset`: the store is not the one `instance` named, or the cursor is+ * ahead of it: it restarted and holds nothing the service published, which publishes again after a hello;+ * the take reads from the start. `gap`: proposals after the cursor were dropped from the inbox before this take.+ */+ async proposals(after: number, waitMs = 0, instance?: string): Promise<{ proposals: InboxEntry[]; next: number; instance: string; reset?: true; gap?: true }> {+ const reset = (instance !== undefined && instance !== this.instance) || after > this.seq+ const from = reset ? 0 : after+ if (!reset && waitMs > 0 && !this.inbox.some(entry => entry.seq > from)) {+ await new Promise<void>(resolve => {+ const wake = (): void => { clearTimeout(timer); this.waiters.delete(wake); resolve() }+ const timer = setTimeout(wake, Math.min(waitMs, TAKE_WAIT_MAX_MS))+ this.waiters.add(wake)+ })+ }+ const first = this.inbox[0]?.seq ?? this.seq + 1+ const gap = !reset && from < first - 1+ return { proposals: this.inbox.filter(entry => entry.seq > from).map(entry => structuredClone(entry)), next: this.seq,+ instance: this.instance, ...(reset ? { reset: true as const } : {}), ...(gap ? { gap: true as const } : {}) }+ }++ // ── agents: on the person's other machines over the machine link, or on this one ────────────────────++ /** `machine_addon` {op, input}: who may ask, and the machine a proposal is said to come from, are the asker's. */+ request(payload: Record<string, unknown>, asker: Asker): Answer | Promise<Answer> {+ if ((LOCAL_OPS as readonly unknown[]).includes(payload.op)) return this.local(payload, asker)+ if (asker.guest !== undefined || !asker.owner || (!asker.local && asker.accountOwner !== true)) {+ return { error: { code: 'OWNER_REQUIRED', message: 'Only the owner\'s own machines may use this machine\'s add-ons.' } }+ }+ const op = payload.op, input = object(payload.input) ? payload.input : {}+ const from: ProposalSource | undefined = asker.local ? { machineId: this.self, label: null } : asker.machine+ try {+ if (op === 'state') return { result: { devices: this.addons.state(this.self) } }+ if (op === 'propose') {+ if (!from) return { error: { code: 'MACHINE_REQUIRED', message: 'A proposal comes from one of the owner\'s machines, which this link did not prove.' } }+ const { deviceId: _ignored, ...rest } = input+ return { result: { proposal: this.addons.propose({ ...rest, deviceId: this.self }, from) } }+ }+ if (op === 'proposal') {+ const found = this.addons.proposal(typeof input.proposalId === 'string' ? input.proposalId : '')+ // A machine reads back its own proposals only; another's reads as one never sent.+ const visible = found && (asker.local || found.from?.machineId === from?.machineId) ? found : null+ if (!visible) return { error: { code: 'PROPOSAL_UNKNOWN', message: 'No such proposal' } }+ return { result: { proposal: visible as AddonProposal } }+ }+ return { error: { code: 'INVALID_REQUEST', message: `op is one of ${MACHINE_ADDON_OPS.join(', ')}` } }+ } catch (error) {+ if (error instanceof DeviceAddonError) return { error: { code: error.code, message: error.message } }+ throw error+ }+ }++ private async local(payload: Record<string, unknown>, asker: Asker): Promise<Answer> {+ if (!asker.local || !asker.owner) return { error: { code: 'LOCAL_ONLY', message: 'Only the device\'s own service, on this machine, publishes and decides.' } }+ const input = object(payload.input) ? payload.input : {}+ try {+ if (payload.op === 'hello') return { result: this.hello() }+ if (payload.op === 'publish') return { result: this.publish(input.values) }+ if (payload.op === 'decision') return { result: this.decide({ proposalId: input.proposalId, decision: input.decision, reason: input.reason }) }+ const whole = (value: unknown): number => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0+ const instance = typeof input.instance === 'string' ? input.instance : undefined+ return { result: { ...await this.proposals(whole(input.after), whole(input.waitMs), instance) } }+ } catch (error) {+ if (error instanceof DeviceAddonError) return { error: { code: error.code, message: error.message } }+ throw error+ }+ }++ requests(): ServiceRequests {+ return { machine_addon: (payload, asker) => this.request(payload, asker) }+ }+}diff --git a/cli/src/lib/autonomous-device/parts.spec.ts b/cli/src/lib/autonomous-device/parts.spec.tsindex c167ca1b5..7c3623b7e 100644--- a/cli/src/lib/autonomous-device/parts.spec.ts+++ b/cli/src/lib/autonomous-device/parts.spec.ts@@ -53,6 +53,7 @@ describe('the Wi-Fi device pieces the core starts', () => {pairStart: () => runningDevicePart(missing, 'Wi-Fi device link').pair('device', 'ABC234'),pairStatus: () => ({}), list: () => ({}), status: () => ({}), revoke: () => ({}), receipt: () => ({}),addonState: () => ({}), addonPropose: () => ({}), addonProposal: () => ({}),+ machineAddonHello: () => ({}), machineAddonPublish: () => ({}), machineAddonDecision: () => ({}), machineAddonProposals: () => ({}),}expect(await autonomousDeviceLocalRequest(management, 'GET', '/api/autonomous-device/discover', undefined)).toEqual({status: 503,diff --git a/cli/src/lib/deviceManagementHttp.spec.ts b/cli/src/lib/deviceManagementHttp.spec.tsindex f5b78755a..246ad7d8c 100644--- a/cli/src/lib/deviceManagementHttp.spec.ts+++ b/cli/src/lib/deviceManagementHttp.spec.ts@@ -14,9 +14,38 @@ function fixture() {addonState: vi.fn().mockReturnValue({ devices: [] }),addonPropose: vi.fn().mockReturnValue({ proposal: { proposalId: 'p' } }),addonProposal: vi.fn().mockReturnValue({ proposal: null }),+ machineAddonHello: vi.fn().mockReturnValue({ topics: 0 }),+ machineAddonPublish: vi.fn().mockReturnValue({ topics: 1 }),+ machineAddonDecision: vi.fn().mockReturnValue({ proposalId: 'p', state: 'kept' }),+ machineAddonProposals: vi.fn().mockResolvedValue({ proposals: [], next: 0 }),} satisfies AutonomousDeviceManagement}+describe('the device that is this machine: its own add-on service', () => {+ it('takes a hello, a publish, a decision and a take of its proposals, and nothing else in their bodies or queries', async () => {+ const service = fixture()+ expect(await autonomousDeviceLocalRequest(service, 'POST', '/api/autonomous-device/machine-addon/hello')).toEqual({ status: 200, body: { topics: 0 } })+ const values = [{ topic: 'voice/state', value: { state: 'listening' } }]+ expect((await autonomousDeviceLocalRequest(service, 'POST', '/api/autonomous-device/machine-addon/publish', { values })).status).toBe(200)+ expect(service.machineAddonPublish).toHaveBeenCalledWith({ values })+ expect((await autonomousDeviceLocalRequest(service, 'POST', '/api/autonomous-device/machine-addon/publish', { values, extra: 1 })).status).toBe(400)+ expect((await autonomousDeviceLocalRequest(service, 'POST', '/api/autonomous-device/machine-addon/decision', { proposalId: 'p', decision: 'kept', reason: 'quiet' })).status).toBe(200)+ expect(service.machineAddonDecision).toHaveBeenCalledWith({ proposalId: 'p', decision: 'kept', reason: 'quiet' })+ expect((await autonomousDeviceLocalRequest(service, 'POST', '/api/autonomous-device/machine-addon/decision', { proposalId: 'p', decision: 'kept', who: 'x' })).status).toBe(400)+ expect(await autonomousDeviceLocalRequest(service, 'GET', '/api/autonomous-device/machine-addon/proposals?after=3&waitMs=20000')).toEqual({ status: 200, body: { proposals: [], next: 0 } })+ expect(service.machineAddonProposals).toHaveBeenLastCalledWith({ after: 3, waitMs: 20000 })+ await autonomousDeviceLocalRequest(service, 'GET', '/api/autonomous-device/machine-addon/proposals')+ expect(service.machineAddonProposals).toHaveBeenLastCalledWith({ after: 0, waitMs: 0 })+ const instance = '0f8fad5b-d9cb-469f-a165-70867728950e'+ await autonomousDeviceLocalRequest(service, 'GET', `/api/autonomous-device/machine-addon/proposals?after=1&instance=${instance}`)+ expect(service.machineAddonProposals).toHaveBeenLastCalledWith({ after: 1, waitMs: 0, instance })+ for (const query of ['?after=-1', '?after=1&after=2', '?waitMs=123456', '?other=1', '?instance=nope', `?instance=${'a'.repeat(36)}&instance=x`]) {+ expect((await autonomousDeviceLocalRequest(service, 'GET', `/api/autonomous-device/machine-addon/proposals${query}`)).status).toBe(400)+ }+ expect((await autonomousDeviceLocalRequest(service, 'POST', '/api/autonomous-device/machine-addon/hello', { x: 1 })).status).toBe(400)+ })+})+describe('device local management validation', () => {it('passes the human-entered device code and returns service data without an extra envelope', async () => {const service = fixture()diff --git a/cli/src/lib/deviceManagementHttp.ts b/cli/src/lib/deviceManagementHttp.tsindex 927f8e71a..2578133eb 100644--- a/cli/src/lib/deviceManagementHttp.ts+++ b/cli/src/lib/deviceManagementHttp.ts@@ -13,6 +13,11 @@ export interface AutonomousDeviceManagement {addonState(target: { deviceId?: string }): unknown | Promise<unknown>addonPropose(proposal: Record<string, unknown>): unknown | Promise<unknown>addonProposal(target: { proposalId: string }): unknown | Promise<unknown>+ /** A device that is this machine: its own add-on service (lib/autonomous-device/machineAddons.ts). */+ machineAddonHello(): unknown | Promise<unknown>+ machineAddonPublish(input: { values: unknown }): unknown | Promise<unknown>+ machineAddonDecision(input: { proposalId: unknown; decision: unknown; reason?: unknown }): unknown | Promise<unknown>+ machineAddonProposals(target: { after: number; waitMs: number; instance?: string }): unknown | Promise<unknown>}export interface AutonomousDeviceLocalResponse { status: number; body: unknown }@@ -33,6 +38,24 @@ export function deviceAddonRoutes(ask: (op: WifiAddonOp, input: Record<string, u}}+/** The routes of the device that is this machine, over its add-ons' one `machine_addon` door (services/machineAddons.ts). */+export function machineAddonRoutes(ask: (op: string, input: Record<string, unknown>, waitMs: number) => Promise<Record<string, unknown>>):+ Pick<AutonomousDeviceManagement, 'machineAddonHello' | 'machineAddonPublish' | 'machineAddonDecision' | 'machineAddonProposals'> {+ const call = async (op: string, input: Record<string, unknown>, waitMs = 0): Promise<Record<string, unknown>> => {+ const answer = await ask(op, input, waitMs)+ const error = answer.error+ if (typeof error === 'string') throw Object.assign(new Error('The add-ons of this machine are not running. See the daemon\'s log.'), { code: 'UNAVAILABLE' })+ if (object(error)) throw Object.assign(new Error(String(error.message)), { code: String(error.code) })+ return object(answer.result) ? answer.result : {}+ }+ return {+ machineAddonHello: () => call('hello', {}),+ machineAddonPublish: ({ values }) => call('publish', { values }),+ machineAddonDecision: (input) => call('decision', input),+ machineAddonProposals: ({ after, waitMs, instance }) => call('proposals', { after, waitMs, ...(instance ? { instance } : {}) }, waitMs),+ }+}+const routes: Record<string, string> = {'/api/autonomous-device/discover': 'GET','/api/autonomous-device/pair/start': 'POST',@@ -44,6 +67,10 @@ const routes: Record<string, string> = {'/api/autonomous-device/addon/state': 'GET','/api/autonomous-device/addon/propose': 'POST','/api/autonomous-device/addon/proposal': 'GET',+ '/api/autonomous-device/machine-addon/hello': 'POST',+ '/api/autonomous-device/machine-addon/publish': 'POST',+ '/api/autonomous-device/machine-addon/decision': 'POST',+ '/api/autonomous-device/machine-addon/proposals': 'GET',}/** The routes that take a query string, and the one parameter each may carry. */@@ -89,7 +116,8 @@ export async function autonomousDeviceLocalRequest(if (!expected) return failure(404, 'NOT_FOUND', 'Unknown device management endpoint')if (method !== expected) return failure(405, 'METHOD_NOT_ALLOWED', 'Method not allowed')if (method === 'GET' && body !== undefined) return bad()- if (url.pathname !== '/api/autonomous-device/receipt' && !Object.hasOwn(queries, url.pathname) && url.search) return bad()+ if (url.pathname !== '/api/autonomous-device/receipt' && url.pathname !== '/api/autonomous-device/machine-addon/proposals'+ && !Object.hasOwn(queries, url.pathname) && url.search) return bad()const input = body === undefined ? {} : bodyif (!object(input)) return bad()const keys = Object.keys(input)@@ -117,6 +145,24 @@ export async function autonomousDeviceLocalRequest(case '/api/autonomous-device/addon/propose':call = () => service.addonPropose(input)break+ case '/api/autonomous-device/machine-addon/publish':+ if (keys.length !== 1 || keys[0] !== 'values') return bad()+ call = () => service.machineAddonPublish({ values: input.values })+ break+ case '/api/autonomous-device/machine-addon/decision':+ if (keys.some(key => !['proposalId', 'decision', 'reason'].includes(key))) return bad()+ call = () => service.machineAddonDecision({ proposalId: input.proposalId, decision: input.decision,+ ...(input.reason !== undefined ? { reason: input.reason } : {}) })+ break+ case '/api/autonomous-device/machine-addon/proposals': {+ const query = url.searchParams+ if ([...query.keys()].some(key => !['after', 'waitMs', 'instance'].includes(key))+ || ['after', 'waitMs', 'instance'].some(key => query.getAll(key).length > 1)) return bad()+ const after = query.get('after') ?? '0', waitMs = query.get('waitMs') ?? '0', instance = query.get('instance')+ if (!/^\d{1,15}$/.test(after) || !/^\d{1,5}$/.test(waitMs) || (instance !== null && !/^[0-9a-f-]{36}$/i.test(instance))) return bad()+ call = () => service.machineAddonProposals({ after: Number(after), waitMs: Number(waitMs), ...(instance ? { instance } : {}) })+ break+ }case '/api/autonomous-device/addon/state':case '/api/autonomous-device/addon/proposal': {const rule = queries[url.pathname]@@ -136,6 +182,7 @@ export async function autonomousDeviceLocalRequest(case '/api/autonomous-device/discover': call = () => service.discover(); breakcase '/api/autonomous-device/pair/status': call = () => service.pairStatus(); breakcase '/api/autonomous-device/list': call = () => service.list(); break+ case '/api/autonomous-device/machine-addon/hello': call = () => service.machineAddonHello(); breakdefault: call = () => service.status()}}diff --git a/cli/src/lib/e2ee/applicationFrames.ts b/cli/src/lib/e2ee/applicationFrames.tsindex 385c993e7..ecf13e42d 100644--- a/cli/src/lib/e2ee/applicationFrames.ts+++ b/cli/src/lib/e2ee/applicationFrames.ts@@ -32,6 +32,8 @@ const MACHINE_REQUESTS = new Set([...SHELL_REQUESTS, 'agent_purge', 'agent_workt'cloud_transcript', 'cloud_send', 'cloud_agents',// A Harness OS computer managed from the phone (services/osDevice.ts): a Wi-Fi join carries the network's password.'os_device',+ // Add-ons of a device that is this machine (lib/autonomous-device/machineAddons.ts): a proposal's note and what it published.+ 'machine_addon',// Sharing a machine across accounts (services/sharedMachines.ts): the addresses it is shared with, and where// a guest may start a harness (the owner's folders).'shared_machines', 'guest_folders',diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 242f549a4..1b9f50581 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -43,6 +43,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['connectors', async () => (await import('./services/connectorsProcess.js')).runConnectorsService],['sharedMachines', async () => (await import('./services/sharedMachinesProcess.js')).runSharedMachinesService],['osDevice', async () => (await import('./services/osDeviceProcess.js')).runOsDeviceService],+ ['machineAddons', async () => (await import('./services/machineAddonsProcess.js')).runMachineAddonsService],['recaps', async () => (await import('./services/recapsProcess.js')).runRecapsService],['agentCleanup', async () => (await import('./services/agentCleanupProcess.js')).runAgentCleanupService],['store', async () => (await import('./services/storeProcess.js')).runStoreService],diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex 1982b9913..bd5c037f3 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -19,6 +19,7 @@ import { startMessagesInCore } from './messages.js'import { startMonitor } from './monitor.js'import { startOrchestrator } from './orchestrator.js'import { startOsDevice } from './osDevice.js'+import { startMachineAddons } from './machineAddons.js'import { startProjects } from './projects.js'import { startRecaps } from './recaps.js'import { startRouter } from './router.js'@@ -37,6 +38,6 @@ import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startProjects, startRecaps, startRouter, startSearch, startSharedMachines, startSharing, startShell, startStoreInCore, startSuperTabs, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, submissionFor, nativeControlFor, modelControlFor, questionControlFor, startAgentCleanup, startCloud, startConnectors, startDevices, startHandoff, startGateway, startMemory, startModels, startMonitor, startOrchestrator, startOsDevice, startMachineAddons, startProjects, startRecaps, startRouter, startSearch, startSharedMachines, startSharing, startShell, startStoreInCore, startSuperTabs, startMessagesInCore, startUsageInCore, startViewers, startWifi, startWindowNames, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex 12777e351..229626f1f 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -33,6 +33,7 @@ export { startModels } from './models.js'export { startMonitor } from './monitor.js'export { startOrchestrator } from './orchestrator.js'export { startOsDevice } from './osDevice.js'+export { startMachineAddons } from './machineAddons.js'export { startProjects } from './projects.js'export { startRecaps } from './recaps.js'export { startRouter } from './router.js'diff --git a/cli/src/services/machineAddons.ts b/cli/src/services/machineAddons.tsnew file mode 100644index 000000000..757b97b28--- /dev/null+++ b/cli/src/services/machineAddons.ts@@ -0,0 +1,14 @@+/**+ * Add-ons for a device that is this Harness machine (lib/autonomous-device/machineAddons.ts, openharness#1654): the+ * device's own service over this machine's loopback routes, and the owner's machines over the machine link, both+ * through the one `machine_addon` request. In the devices' process (started at its first request), or in the core's+ * process with the services there.+ */+import type { CoreApi, ServiceRequests } from '../core/api.js'+import { MachineAddons } from '../lib/autonomous-device/machineAddons.js'++export { MACHINE_ADDON_REQUESTS } from '../core/api.js'++export function startMachineAddons(core: CoreApi): ServiceRequests {+ return new MachineAddons({ machineId: () => core.daemon.machineId() }).requests()+}diff --git a/cli/src/services/machineAddonsProcess.spec.ts b/cli/src/services/machineAddonsProcess.spec.tsnew file mode 100644index 000000000..8b8f45f09--- /dev/null+++ b/cli/src/services/machineAddonsProcess.spec.ts@@ -0,0 +1,58 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { MACHINE_ADDON_REQUESTS } from '../core/api.js'+import { runServiceProcess, type ServiceProcessOptions } from './process.js'+import { runMachineAddonsService } from './machineAddonsProcess.js'+import { answerExperimentQuery, answerMachineAddonsQuery } from '../core/experimentQueries.js'+import { fakeCore } from '../testing/fakeCore.js'++// The real default reaches a real socket: never in a test.+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))++const LOCAL = { local: true, owner: true }+const PUBLISH = { op: 'publish', input: { values: [{ topic: 'voice/state', value: {} }] } }+const PROPOSE = { op: 'propose', input: { addon: 'a', idempotencyKey: 'k', act: 'say', holdsMs: 5000, note: 'hi' } }++function setup() {+ let wire!: ServiceProcessOptions+ // The real processCoreApi: only the process's socket is swapped, and the core it connects is a query.+ runMachineAddonsService({ dataDir: '/not-a-real-data-dir', socketPath: '/not-a-real-socket', machineId: 'computer-id', token: 't',+ run: (given) => { wire = given; return { stop: vi.fn() } } })+ // The core's own answers, in core/main.ts's order: the machine add-ons' door before the experiments' check.+ const core = fakeCore({ daemon: { machineId: () => 'm_account' } as never })+ const query = vi.fn(async (name: string, payload: Record<string, unknown> = {}) =>+ answerMachineAddonsQuery(core, 'machineAddons', name) ?? await answerExperimentQuery(core, new Set(['orchestrator']), 'machineAddons', name, payload) ?? {})+ return { wire: () => wire, query }+}++describe('the add-ons of a device that is this machine, in their own process', () => {+ afterEach(() => vi.clearAllMocks())++ it('names the device by the account\'s machine id the core says, never the computer id it is started with', async () => {+ const t = setup()+ expect(t.wire()).toMatchObject({ name: 'machineAddons', machineId: 'computer-id' })+ const ask = t.wire().requests.machine_addon!+ t.wire().onConnected!({ query: t.query } as never)+ await ask(PUBLISH, LOCAL)+ expect(t.query).toHaveBeenCalledWith('daemon', {})+ expect(await ask({ op: 'state' }, LOCAL)).toMatchObject({ result: { devices: [{ deviceId: 'm_account' }] } })+ expect(await ask(PROPOSE, LOCAL)).toMatchObject({ result: { proposal: { deviceId: 'm_account', from: { machineId: 'm_account' } } } })+ })++ it('refuses, never runs as no machine, until the core has said this machine\'s id; a request asks for it', async () => {+ const t = setup()+ const ask = t.wire().requests.machine_addon!+ expect(await ask(PUBLISH, LOCAL)).toMatchObject({ error: { code: 'UNAVAILABLE' } })+ const late = vi.fn(async () => ({}))+ t.wire().onConnected!({ query: late } as never)+ expect(await ask({ op: 'state' }, LOCAL)).toMatchObject({ error: { code: 'UNAVAILABLE' } })+ t.wire().onConnected!({ query: t.query } as never)+ expect(await ask(PUBLISH, LOCAL)).toMatchObject({ result: { topics: 1 } })+ })++ it('runs as a real service by default, answering every request the core routes to it', () => {+ runMachineAddonsService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ const options = vi.mocked(runServiceProcess).mock.calls.at(-1)![0]+ expect(options.name).toBe('machineAddons')+ expect(Object.keys(options.requests)).toEqual([...MACHINE_ADDON_REQUESTS])+ })+})diff --git a/cli/src/services/machineAddonsProcess.ts b/cli/src/services/machineAddonsProcess.tsnew file mode 100644index 000000000..5e236b599--- /dev/null+++ b/cli/src/services/machineAddonsProcess.ts@@ -0,0 +1,51 @@+/**+ * Add-ons for a device that is this machine, in their own process (`harness __service machineAddons`, in the devices'+ * process): the same handler as in the core's process (services/machineAddons.ts). It asks the core only where this+ * daemon runs (`daemon`), for this machine's account id; what it holds is RAM, bounded as v1's add-ons are.+ */+import type { DaemonAddress } from '../core/api.js'+import { startMachineAddons } from './machineAddons.js'+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { daemonIn, processCoreApi } from './processCoreApi.js'++export interface MachineAddonsServiceOptions {+ dataDir: string+ socketPath: string+ /** The computer's id, which the owner's other machines don't know this machine by: never the device's name. */+ machineId: string+ token: string+ /** Swapped in tests for one that does not touch the real socket or process. */+ run?: typeof runServiceProcess+}++export function runMachineAddonsService(options: MachineAddonsServiceOptions): ServiceProcess {+ let core: CoreConnection | null = null+ let daemon: DaemonAddress | null = null+ let reading: Promise<void> | null = null+ // The account's machine id, as the core says it: asked once a core connects, and again by a request before then.+ const known = (): Promise<void> => {+ if (daemon?.machineId()) return Promise.resolve()+ const connection = core+ if (!connection) return Promise.reject(new Error('Core disconnected'))+ return reading ??= connection.query('daemon', {}).then((address) => {+ if (core === connection) daemon = daemonIn(address)+ }).finally(() => { reading = null })+ }+ const requests = startMachineAddons(processCoreApi(options.dataDir, 'machineAddons', { daemon: () => daemon }))+ return (options.run ?? runServiceProcess)({+ name: 'machineAddons',+ socketPath: options.socketPath,+ machineId: options.machineId,+ token: options.token,+ requests: {+ machine_addon: async (payload, asker, closed) => {+ await known().catch(() => {})+ // Never as `''`: a device named nothing would take no proposal and be listed as no machine.+ if (!daemon?.machineId()) return { error: { code: 'UNAVAILABLE', message: 'This machine\'s id is not known yet. Try again in a moment.' } }+ return requests.machine_addon!(payload, asker, closed)+ },+ },+ onConnected: (connection) => { core = connection; void known().catch(() => {}) },+ onDisconnected: () => { core = null },+ })+}diff --git a/cli/src/services/process.ts b/cli/src/services/process.tsindex 39de05331..daea35973 100644--- a/cli/src/services/process.ts+++ b/cli/src/services/process.ts@@ -91,6 +91,11 @@ export function serviceFaults(env: NodeJS.ProcessEnv, name: string): ServiceFaul}const describe = (error: unknown): string => (error instanceof Error ? error.message : String(error))+/** Another of the owner's machines (Asker.machine), as the core said it; read as none when malformed. */+const machineOf = (value: unknown): { machineId: string; label: string | null } | null => {+ const m = value as { machineId?: unknown; label?: unknown } | null+ return m && typeof m.machineId === 'string' && m.machineId && (typeof m.label === 'string' || m.label === null) ? { machineId: m.machineId, label: m.label } : null+}/** A service running in this process. Its stop may take a moment (the viewers stop their servers). */export interface ServiceProcess {@@ -231,7 +236,7 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProcescatch (error) { log(`[service ${options.name}] binary frame failed · ${describe(error)}`) }return}- let frame: { type?: unknown; payload?: Payload; asker?: { local?: unknown; owner?: unknown; accountOwner?: unknown; guest?: unknown; connection?: unknown; requestId?: unknown } }+ let frame: { type?: unknown; payload?: Payload; asker?: { local?: unknown; owner?: unknown; accountOwner?: unknown; guest?: unknown; machine?: unknown; connection?: unknown; requestId?: unknown } }try { frame = JSON.parse(raw.toString()) as typeof frame } catch { return }const payload = frame.payload ?? {}if (frame.type === 'connected') {@@ -276,6 +281,7 @@ export function runServiceProcess(options: ServiceProcessOptions): ServiceProces...(typeof frame.asker?.accountOwner === 'boolean' ? { accountOwner: frame.asker.accountOwner } : {}),// A guest's session (core/guestPolicy.ts): whose guest it is, for the few requests a guest may make here....(typeof frame.asker?.guest === 'string' ? { guest: frame.asker.guest } : {}),+ ...(machineOf(frame.asker?.machine) ? { machine: machineOf(frame.asker?.machine)! } : {}),...(typeof frame.asker?.connection === 'string' ? { connection: frame.asker.connection } : {}),...(typeof frame.asker?.requestId === 'string' ? { requestId: frame.asker.requestId } : {}),}diff --git a/docs/autonomous-device-addons.md b/docs/autonomous-device-addons.mdindex 50d50db21..4a4570706 100644--- a/docs/autonomous-device-addons.md+++ b/docs/autonomous-device-addons.md@@ -159,6 +159,59 @@ most once. A read with no answer is `UNAVAILABLE` (503).`RATE_LIMITED` 429, `BACKPRESSURE` 429, `UNAVAILABLE` 503 when the Wi-Fi device service is not running,`OUTCOME_UNKNOWN` 504 for a propose with no answer in time.+## A device that is a Harness machine++Some devices run Harness themselves: the lampOS V2 lamp is a signed-in Harness machine on its person's+account, so it has no paired device channel to publish on (openharness#1654). Its add-ons go through its+own daemon instead. The contract, bounds, rates and lifetimes are the ones above; two things are added.++**The device's own service**, a process of the same OS user on that machine, uses the credential-checked+loopback routes, like the other `autonomous-device` routes:++| Route | Input / result |+|---|---|+| POST `/api/autonomous-device/machine-addon/hello` | `{}` → `{topics:0}`: what it published before is cleared, as a device's hello clears it. Send it at start |+| POST `/api/autonomous-device/machine-addon/publish` | `{values}`, as `addon.publish` takes them → `{topics}` |+| POST `/api/autonomous-device/machine-addon/decision` | `{proposalId,decision,reason?}`, as `addon.decision` → `{proposalId,state}` |+| GET `/api/autonomous-device/machine-addon/proposals?after=<seq>&waitMs=<ms>` | `{proposals:[{seq,proposal}],next,reset?}` |++`proposals` is the device's inbox in place of the `addon.proposal` event: the proposals after `after`, each+as the event's payload with its `seq`, and `next` for the next take. With none, it waits up to `waitMs`+(at most 20 s) for one. The inbox keeps the last 32; `gap: true` says proposals after the cursor were+dropped from it before this take.++**Restarts.** Everything is in RAM, and the daemon or its devices' process may restart at any time (every+Harness update does). Every `hello`, `publish` and `proposals` answer carries `instance`, the store's own id,+new after each restart. The service passes the last one it saw as `proposals?instance=`. When the store is+another one, or the cursor is ahead of it, the answer says `reset: true` and reads from the start: what+the service published is gone, and the owner's machines get `DEVICE_NOT_FOUND` until it publishes again.+**On `reset`, the service sends `hello` and publishes its whole set again**, as a device does after+`addon.republish`.++**Agents** on the owner's other machines reach the device over the existing machine link, as the+sealed `machine_addon` request (`{op:"state"|"propose"|"proposal",input}`), and the CLI takes+`--machine` for it:++```sh+harness autonomous-device addon state --machine lamp-4ace --json+harness autonomous-device addon propose --machine lamp-4ace --act say --holds-ms 30000 --note '…' --json+harness autonomous-device addon proposal <proposalId> --machine lamp-4ace --json+```++- **Only the owner's machines.** A guest, a device, an observer, or a session that isn't the account's+ own is refused `OWNER_REQUIRED`. The device's service routes are for a process on that machine alone+ (`LOCAL_ONLY` over the link).+- **Each proposal says the machine it came from:** `from: {machineId, label}`, taken from the pairing+ record of the link that carried it (`Asker.machine`), never from the payload, which may not carry one.+ A device can then ask its person's yes per computer. The owner's phone or browser may read `state`, but a+ proposal needs a machine (`MACHINE_REQUIRED`). An agent on the device itself proposes as that machine.+- **A machine reads back its own proposals alone.** Another machine's reads as `PROPOSAL_UNKNOWN`, and its+ idempotency keys are its own: the same key from another machine is another proposal.+- `--machine` takes a machine's id or its name. Two of the account's machines with that name are refused+ `AMBIGUOUS`: name one by its id.+- A proposal's target is always the device that is that machine: `deviceId` in the input is ignored.+- It runs in the devices' process (`services/machineAddons.ts`), started at its first request, in RAM; a daemon restart forgets it all.+## Lifetime- A device's link closing marks it `online: false`: its values stay readable, and nothing is@@ -173,7 +226,8 @@ most once. A read with no answer is `UNAVAILABLE` (503).`service.ts` advertises and routes the two requests; `services/wifi.ts`, `core/wifiLink.ts` and`services/wifiProcess.ts` carry the agent-facing operation across the service process boundary as`harness device receipt` is carried; `lib/deviceManagementHttp.ts` validates the routes;-`addonCommand.ts` is the CLI. Unit tests cover each layer; `services/wifi.spec.ts` runs the real+`addonCommand.ts` is the CLI. A device that is a Harness machine: `machineAddons.ts` beside them, served by+`services/machineAddons.ts`. Unit tests cover each layer; `services/wifi.spec.ts` runs the realservice and relay end to end with a fake core (publish, state, a proposal sealed to that device, itsdecision, unpairing). Not shown: a physical device. No device implements it yet.