Skip to content

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.

Merge batch 11-02 1102-i: #2550 #2554 #2551 (#2562)

0xken1529795af79738
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index 682ba5740..d5465d9e7 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -18,7 +18,6 @@ import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { promisify } from 'node:util'
import { isolatedTmux, type IsolatedTmux } from '../../src/testing/isolatedTmux.js'
-import { localCredentialHeaders } from '../../src/lib/localCredential.js'
import { artifactLog, artifactsEnabled } from './artifacts.js'
import { daemonEnvironment } from '../../src/testing/daemonEnvironment.js'
import { GH_FORBIDDEN_STUB } from '../../src/testing/ghStub.js'
@@ -451,7 +450,7 @@ export class IsolatedDaemon {
/** Credentials for this daemon's loopback TCP API; its Unix socket needs none. */
localHeaders(extra: Record<string, string> = {}): Record<string, string> {
- return { ...extra, ...localCredentialHeaders(this.dataDir) }
+ return { ...extra, 'X-Harness-Local': this.hookCredential() }
}
/**
diff --git a/cli/e2e/portHolder.e2e.ts b/cli/e2e/portHolder.e2e.ts
new file mode 100644
index 000000000..360ac984c
--- /dev/null
+++ b/cli/e2e/portHolder.e2e.ts
@@ -0,0 +1,48 @@
+/**
+ * Audit H1 (docs/security/2026-11-02-team-account-boundary.md), with the real daemon and the real hook. Another account
+ * holds the daemon's port from boot, before this user's daemon starts at login. Here a plain listener of this user stands
+ * for that account: no second account is made on a shared computer, so the refusal by account is proved in
+ * src/hookServer.spec.ts with a stand-in, and the lookup itself in src/lib/peerAccount.spec.ts.
+ */
+import { spawn } from 'node:child_process'
+import { existsSync } from 'node:fs'
+import { createServer, type IncomingMessage } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { join } from 'node:path'
+import { afterEach, expect, it } from 'vitest'
+import { CLI_ROOT, IsolatedDaemon, until } from './harness/daemon.js'
+
+const started: IsolatedDaemon[] = []
+afterEach(async () => { for (const each of started.splice(0)) await each.close() })
+
+it('a daemon that lost its port still hears hooks, and the holder of the port hears nothing', async () => {
+ const heard: Array<{ method?: string; url?: string; headers: IncomingMessage['headers'] }> = []
+ const holder = createServer((req, res) => { heard.push({ method: req.method, url: req.url, headers: req.headers }); req.resume(); res.end('{}') })
+ holder.on('upgrade', (req, socket) => { heard.push({ method: req.method, url: req.url, headers: req.headers }); socket.destroy() })
+ await new Promise<void>((resolve) => { holder.listen(0, '127.0.0.1', resolve) })
+ const port = (holder.address() as AddressInfo).port
+ try {
+ const d = await IsolatedDaemon.create({ port })
+ started.push(d)
+ await d.start({ ready: 'none' })
+ await until('the daemon to open its socket', () => existsSync(d.socketPath), 60_000)
+ await until('the daemon to move off the held port', () => /assigning a separate port/.test(d.log()), 60_000)
+ const hook = spawn(process.execPath, [join(CLI_ROOT, 'hook', 'notify.mjs'), '--port', String(port), '--data-dir', d.dataDir], {
+ stdio: ['pipe', 'ignore', 'ignore'],
+ env: { PATH: process.env.PATH, HOME: d.env.HOME, TMUX_PANE: '%999', TMUX_TMPDIR: d.root },
+ })
+ hook.stdin.end(JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt: 'a private prompt', session_id: '11111111-1111-4111-8111-111111111111', cwd: d.root }))
+ await new Promise<void>((resolve) => { hook.on('exit', () => resolve()) })
+ // The daemon took it, over the socket: it says what it did with a hook whose pane is not one of its own.
+ await until('the daemon to hear the hook', () => /\[hooks\] 11111111/.test(d.log()), 30_000)
+ // A start may ask the port who is there, with no secret: `GET /api/health` or `/api/status`, as anyone can. Nothing else
+ // reaches the holder: no hook, no request with a body, no header carrying a secret.
+ for (const request of heard) {
+ expect(`${request.method} ${request.url}`).toMatch(/^GET \/api\/(health|status)$/)
+ expect(Object.keys(request.headers).filter(name => /harness|authorization|cookie/i.test(name))).toEqual([])
+ }
+ } finally {
+ holder.closeAllConnections()
+ await new Promise<void>((resolve) => { holder.close(() => resolve()) })
+ }
+}, 180_000)
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjs
index 2c006f116..8a61e2351 100644
--- a/cli/hook/notify.mjs
+++ b/cli/hook/notify.mjs
@@ -277,16 +277,63 @@ function boundedPrompt(prompt) {
const DELIVERY_ID = randomUUID()
const FIRED_AT = Date.now() - Math.round(process.uptime() * 1000)
+/** Mirrors MAX_SOCKET_PATH_BYTES in src/lib/localSocket.ts. */
+const MAX_SOCKET_PATH_BYTES = 96
+
+/** A socket file only this account could have made: never send the credential to anything else. */
+function privateSocket(file) {
+ try {
+ const entry = lstatSync(file)
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
+ return entry.isSocket() && (entry.mode & 0o077) === 0 && (uid === null || entry.uid === uid)
+ } catch { return false }
+}
+
+/**
+ * The daemon's socket in this data folder. It is named for the daemon's configured port, and this hook's port may be
+ * the one the daemon was given instead when another account held that one, so the daemon's records say which
+ * (mirrors localSocketRoute in src/lib/localTransport.ts).
+ */
+function daemonSocket(port, dataDir) {
+ const named = join(dataDir, `daemon-${port}.sock`)
+ if (privateSocket(named)) return named
+ try {
+ for (const name of readdirSync(dataDir)) {
+ const configured = /^daemon-(\d+)\.json$/.exec(name)?.[1]
+ if (!configured) continue
+ const socket = join(dataDir, `daemon-${configured}.sock`)
+ if (JSON.parse(readPrivateStateFile(join(dataDir, name), 4096))?.port === port && privateSocket(socket)) return socket
+ }
+ } catch { /* An unreadable folder has no socket to offer. */ }
+ return null
+}
+
+/**
+ * How this hook reaches the daemon, and what it shows. Any account can bind the TCP port while the daemon restarts (audit
+ * H1, docs/security/2026-11-02-team-account-boundary.md), and whoever holds it would hear this request, the user's
+ * prompt in it included. So on macOS and Linux it goes over the 0600 socket; with none there the daemon is down, and
+ * this is the same as a failed post. A data folder too long to hold a socket is the one case with no way but TCP, and
+ * then the hook-only token goes, never the credential. Over the socket the credential still goes because a daemon from
+ * before the hook token (an update not yet handed over) checks it there. Windows is unchanged.
+ */
+function hookRoute(port) {
+ const dataDir = paths().dataDir
+ if (process.platform === 'win32') return { address: { host: '127.0.0.1', port }, token: readHookCredential() }
+ if (Buffer.byteLength(join(dataDir, `daemon-${port}.sock`)) > MAX_SOCKET_PATH_BYTES) return { address: { host: '127.0.0.1', port }, token: readHookCredential('hook-token') }
+ const socketPath = daemonSocket(port, dataDir)
+ return socketPath ? { address: { socketPath }, token: readHookCredential() } : null
+}
+
function post(port, path, body, onResponse) {
return new Promise((resolve) => {
const payload = JSON.stringify(body)
- const credential = readHookCredential()
+ const route = hookRoute(port)
+ const credential = route?.token
if (!credential) { resolve(false); return }
let connected = false
const req = http.request(
{
- host: '127.0.0.1',
- port,
+ ...route.address,
path,
method: 'POST',
headers: {
@@ -397,14 +444,14 @@ function hardenPrivateStateFileIfPresent(file, maxBytes = Number.MAX_SAFE_INTEGE
} finally { closeSync(fd) }
}
-function readHookCredential() {
+function readHookCredential(name = 'hook-credential') {
let fd = null
try {
const dataDir = paths().dataDir
- if (process.platform === 'win32') return readWindowsHookCredential(dataDir, join(dataDir, 'hook-credential'))
+ if (process.platform === 'win32') return readWindowsHookCredential(dataDir, join(dataDir, name))
secureStateDirectory(dataDir, false)
const uid = typeof process.getuid === 'function' ? process.getuid() : null
- const file = join(dataDir, 'hook-credential')
+ const file = join(dataDir, name)
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
const stat = fstatSync(fd)
if (!stat.isFile() || stat.size > 128 || (stat.mode & 0o777) !== 0o600) return ''
diff --git a/cli/src/agentClient/daemon.spec.ts b/cli/src/agentClient/daemon.spec.ts
index f0787a837..fefa089ea 100644
--- a/cli/src/agentClient/daemon.spec.ts
+++ b/cli/src/agentClient/daemon.spec.ts
@@ -1,7 +1,7 @@
import { EventEmitter } from 'node:events'
import { randomBytes } from 'node:crypto'
import http from 'node:http'
-import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { createServer } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -77,8 +77,9 @@ describe('a line to the daemon that cannot open', () => {
})
})
-it('dials the port this user recorded when another daemon took the configured port', async () => {
- const dataDir = mkdtempSync(join(tmpdir(), 'agent-daemon-port-'))
+it('where no socket can exist, dials the port this user recorded when another daemon took the configured port', async () => {
+ const dataDir = join(mkdtempSync(join(tmpdir(), 'agent-daemon-port-')), 'd'.repeat(100))
+ mkdirSync(dataDir, { mode: 0o700 })
const server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
try {
await new Promise<void>((resolve) => server.once('listening', resolve))
diff --git a/cli/src/agentClient/daemon.ts b/cli/src/agentClient/daemon.ts
index cab15bbce..f9f41fd91 100644
--- a/cli/src/agentClient/daemon.ts
+++ b/cli/src/agentClient/daemon.ts
@@ -6,16 +6,13 @@
* the paired relay (`machine_select` naming it).
*/
import { randomUUID } from 'node:crypto'
-import { localCredentialHeaders } from '../lib/localCredential.js'
-import { existsSync } from 'node:fs'
import { WebSocket } from 'ws'
import { env } from '../config/env.js'
import { readAuthSession } from '../lib/authSession.js'
-import { savedDaemonPort } from '../lib/daemonEndpoint.js'
+import { localWsTarget } from '../lib/localTransport.js'
import { daemonPipe, type LocalDaemonOptions } from '../lib/windows/daemonPipe.js'
import { pipeWebSocket } from '../lib/windows/pipeClient.js'
import { computerId, daemonUnreachableText } from '../lib/daemonState.js'
-import { unixSocketPath } from '../lib/localSocket.js'
import { paneOwner, sendPane } from '../messages/command.js'
export class AgentClientError extends Error {
@@ -61,19 +58,16 @@ export function whereFor(pane: string | undefined, owner: typeof paneOwner = pan
harnessPane: !!found || (!!pane && pane.startsWith('p') && sendPane({ HARNESS_PANE: pane }) === pane) }
}
-/** The Unix socket on macOS/Linux, or the authenticated daemon pipe on Windows. The Unix legacy
- * fallback uses loopback TCP and the local credential; Windows never sends that credential to a
- * port whose listener may belong to another OS user or outlive a stale daemon record. */
+/** The Unix socket on macOS/Linux, or the authenticated daemon pipe on Windows. Neither falls back to the port:
+ * its listener may belong to another OS user or outlive a stale daemon record (lib/localTransport.ts). */
export async function connectSocket(where: Where, options: LocalDaemonOptions = {}): Promise<ClientSocket> {
if ((options.platform ?? process.platform) === 'win32') {
const target = await (options.pipe ?? daemonPipe)(where.dataDir, where.port)
if (!target) throw new AgentClientError('DAEMON_UNREACHABLE', daemonUnreachableText(null, where.dataDir))
return pipeWebSocket(target)
}
- const path = unixSocketPath(where.dataDir, where.port)
- return path && existsSync(path)
- ? new WebSocket(`ws+unix://${path}:/api/local-ws`)
- : new WebSocket(`ws://127.0.0.1:${savedDaemonPort(where.dataDir, where.port)}/api/local-ws`, { headers: localCredentialHeaders(where.dataDir) })
+ const target = localWsTarget(where.dataDir, where.port)
+ return new WebSocket(target.url, { headers: target.headers })
}
export const DEFAULT_TIMEOUT_MS = 20_000
diff --git a/cli/src/agentClient/settings.spec.ts b/cli/src/agentClient/settings.spec.ts
index 707c55a29..0b6482307 100644
--- a/cli/src/agentClient/settings.spec.ts
+++ b/cli/src/agentClient/settings.spec.ts
@@ -1,4 +1,4 @@
-import { mkdtempSync, rmSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
@@ -122,8 +122,9 @@ describe('harness settings', () => {
expect(d.asked).toEqual([])
})
- it('shows the daemon this OS user\'s local credential, which its loopback port wants', async () => {
- const dataDir = mkdtempSync(join(tmpdir(), 'settings-cred-'))
+ it('shows the daemon this OS user\'s local credential only where no socket can exist', async () => {
+ const dataDir = join(mkdtempSync(join(tmpdir(), 'settings-cred-')), 'd'.repeat(100))
+ mkdirSync(dataDir, { mode: 0o700 })
try {
const credential = loadOrCreateHookCredential(dataDir)
const asked: Record<string, string>[] = []
diff --git a/cli/src/agentClient/settings.ts b/cli/src/agentClient/settings.ts
index 84f4e940b..ce30c884a 100644
--- a/cli/src/agentClient/settings.ts
+++ b/cli/src/agentClient/settings.ts
@@ -10,6 +10,7 @@
*/
import { AGENT_SETTING_NAMES, askThePersonFirst, PERSON_SAID_YES, type AgentSettings } from '../lib/agentSettings.js'
import { localCredentialHeaders } from '../lib/localCredential.js'
+import { daemonFetch } from '../lib/localTransport.js'
import { env } from '../config/env.js'
import { daemonUnreachableText } from '../lib/daemonState.js'
import { outsideCaller } from './model.js'
@@ -97,7 +98,7 @@ export async function settingsCommand(argv: readonly string[], deps: SettingsDep
}
let answer: Answer
try {
- const response = await (deps.fetch ?? fetch)(`http://127.0.0.1:${deps.port}/api/agent-settings`, {
+ const response = await (deps.fetch ?? daemonFetch(deps.dataDir ?? env.ADAPTER_DATA_DIR, deps.port))(`http://127.0.0.1:${deps.port}/api/agent-settings`, {
method: change ? 'PATCH' : 'GET',
// The local API's CSRF gate: a write must say it comes from this computer.
headers: { 'x-adapter-local': '1', ...localCredentialHeaders(deps.dataDir ?? env.ADAPTER_DATA_DIR), ...(change ? { 'content-type': 'application/json' } : {}) },
diff --git a/cli/src/cable/cableSession.spec.ts b/cli/src/cable/cableSession.spec.ts
index 5e2d3412f..d33a6c334 100644
--- a/cli/src/cable/cableSession.spec.ts
+++ b/cli/src/cable/cableSession.spec.ts
@@ -4084,6 +4084,21 @@ describe('swarm cards', () => {
} finally { await session.stop() }
})
+ it('on attach sends the focus after the cards, however late the restarted daemon reads them', async () => {
+ const state = { cards: null as SwarmCard[] | null, open: { superTabId: 'st1', projectId: 'proj2', fromDevice: false } }
+ const { session, port } = await connect(cardHost(state))
+ try {
+ port.say(PRO)
+ await vi.waitFor(() => expect(port.types()).toContain('notif.replace'))
+ expect(port.types().filter((t) => t.startsWith('supertab'))).toEqual([])
+ state.cards = [card('st1')]
+ await session.syncSwarmCards(false)
+ await vi.waitFor(() => expect(ofType(port, 'supertab.focus')).toHaveLength(1))
+ expect(port.types().filter((t) => t.startsWith('supertab'))).toEqual(['supertabs', 'supertab', 'supertab.focus'])
+ expect(ofType(port, 'supertab.focus')[0]).toEqual({ t: 'supertab.focus', tab: 'st1', lead: 'lead2' })
+ } finally { await session.stop() }
+ })
+
it('resync sends everything again, as attach does', async () => {
const state = { cards: [card('st1')], open: { superTabId: 'st1', projectId: 'proj2', fromDevice: false } }
const { session, port } = await connect(cardHost(state))
@@ -4818,6 +4833,10 @@ describe('swarm cards', () => {
expect(vi.mocked(host.superTabSelected!).mock.calls).toEqual([['st1', 'proj1', 'buddy'], ['st1', 'proj1', 'pm']])
// The cards still hear each side: the dial's faces follow from them as before.
expect(swarmCardSide.mock.calls).toEqual([['st1', 'buddy'], ['st1', 'pm']])
+ // A side the dial kept across a restart, with no finger on it: the cards hear it, and the window stays.
+ port.say({ t: 'supertab.side', tab: 'st1', side: 'buddy', kept: true }); await settle()
+ expect(swarmCardSide).toHaveBeenLastCalledWith('st1', 'buddy')
+ expect(vi.mocked(host.superTabSelected!).mock.calls).toHaveLength(2)
// The window's announce of the move it made for the dial is not sent back as a focus.
state.open = { ...onDesk(), fromDevice: true }
await session.syncSwarmCards(true)
diff --git a/cli/src/cable/cableSession.ts b/cli/src/cable/cableSession.ts
index 81fe96381..473f16fdd 100644
--- a/cli/src/cable/cableSession.ts
+++ b/cli/src/cable/cableSession.ts
@@ -1450,7 +1450,8 @@ export class CableSession {
const tab = str('tab') ?? '', side = str('side')
if (this.swarmBuddy && CARD_ID.test(tab) && (side === 'pm' || side === 'buddy')) {
this.host.swarmCardSide?.(tab, side)
- this.followSide(tab, side)
+ // `kept`: the side a restart took off the dial's face, with no finger on it. The window stays where the person left it.
+ if (msg.kept !== true) this.followSide(tab, side)
if (side === 'buddy') this.queued(() => this.readSharedBuddyNotices(tab)).catch((err) => this.log(`cable: Buddy notices not cleared (${(err as Error).message})`))
}
return
diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.ts
index 2e1b4a9a6..f4ab4759b 100644
--- a/cli/src/cliCommand.spec.ts
+++ b/cli/src/cliCommand.spec.ts
@@ -453,7 +453,7 @@ describe('the daemon\'s control calls, through the CLI', () => {
expect(direct).toEqual([])
})
- it('on mac and Linux still makes them over the loopback, as before', async () => {
+ it('on mac and Linux makes them over the loopback where no socket can exist', async () => {
const root = freshRoot()
const got: string[] = []
const server = createServer((req, res) => {
@@ -465,10 +465,12 @@ describe('the daemon\'s control calls, through the CLI', () => {
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
const PORT = String((server.address() as AddressInfo).port)
- const status = await runAsync(root, ['remote-password', 'status', '--json'], { PORT })
+ // A data folder too long to hold a socket: the one case on the port. With a socket, see lib/daemonEndpoint.spec.ts.
+ const ADAPTER_DATA_DIR = join(root, 'd'.repeat(100))
+ const status = await runAsync(root, ['remote-password', 'status', '--json'], { PORT, ADAPTER_DATA_DIR })
expect(status.status, status.stderr).toBe(0)
expect(JSON.parse(status.stdout)).toEqual({ hasPassword: true, fingerprint: 'fp-1', setAt: 7 })
- const sync = await runAsync(root, ['group', 'sync'], { PORT })
+ const sync = await runAsync(root, ['group', 'sync'], { PORT, ADAPTER_DATA_DIR })
expect(sync.status, sync.stderr).toBe(0)
expect(sync.stdout).toContain('Comparing with every reachable member now.')
expect(got).toEqual(['GET /api/remote-password/status local=1', 'POST /api/group/sync local=1'])
diff --git a/cli/src/cloud/bridge.ts b/cli/src/cloud/bridge.ts
index 73af6409f..13613ffc3 100644
--- a/cli/src/cloud/bridge.ts
+++ b/cli/src/cloud/bridge.ts
@@ -19,7 +19,10 @@ export interface Bridge {
}
/** Through Harness's own key (agents.ts `harnessKey`), never the one in the agents' configurations. */
-export function connectionsBridge(base: () => string = () => `http://127.0.0.1:${bridgePort()}/${harnessKey(new Store())}`): Bridge {
+export function connectionsBridge(base: () => string = () => {
+ const vault = new Store()
+ return `http://127.0.0.1:${bridgePort(process.env, vault)}/${harnessKey(vault)}`
+}): Bridge {
return {
async connections() {
const answer = await fetch(`${base()}/connections`, { signal: AbortSignal.timeout(10_000) })
diff --git a/cli/src/devices/client.spec.ts b/cli/src/devices/client.spec.ts
index a00e9f519..089dc81d4 100644
--- a/cli/src/devices/client.spec.ts
+++ b/cli/src/devices/client.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { EventEmitter } from 'node:events'
-import { mkdtempSync, rmSync } from 'node:fs'
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { loadOrCreateHookCredential } from '../lib/hookAuth.js'
@@ -71,8 +71,9 @@ describe('Devices DSH commands', () => {
expect(await reply).toEqual(snapshot())
expect(socket.close).toHaveBeenCalledOnce()
})
- it('shows the daemon this OS user\'s local credential on its loopback socket and fetches', async () => {
- const dataDir = mkdtempSync(join(tmpdir(), 'devices-cred-'))
+ it('shows the daemon this OS user\'s local credential on its loopback socket and fetches only where no socket can exist', async () => {
+ const dataDir = join(mkdtempSync(join(tmpdir(), 'devices-cred-')), 'd'.repeat(100))
+ mkdirSync(dataDir, { mode: 0o700 })
try {
const credential = loadOrCreateHookCredential(dataDir)
const socket = Object.assign(new EventEmitter(), { send: vi.fn(), close: vi.fn() })
diff --git a/cli/src/devices/client.ts b/cli/src/devices/client.ts
index 6cfc31a26..2be5e0100 100644
--- a/cli/src/devices/client.ts
+++ b/cli/src/devices/client.ts
@@ -2,6 +2,7 @@
import { randomUUID } from 'node:crypto'
import { env } from '../config/env.js'
import { localCredentialHeaders } from '../lib/localCredential.js'
+import { daemonFetch, localWsTarget } from '../lib/localTransport.js'
import type { ClientSocket } from '../lib/clientSocket.js'
import { deviceSettingsPatchSchema } from '../lib/harnessDevices.js'
@@ -10,7 +11,7 @@ export interface DevicesClientDeps {
/** The daemon's data dir, where its local credential is (lib/localCredential.ts). */
dataDir?: string
machineId(): Promise<string | null>
- /** A loopback socket to the daemon, carrying [headers] (its local credential). */
+ /** A line to the daemon: its private socket's address, or where there can be none its port and [headers]. */
connect(url: string, headers?: Record<string, string>): ClientSocket
fetch?: typeof fetch
request?: (machineId: string, type: string, payload?: Record<string, unknown>) => Promise<Record<string, unknown>>
@@ -21,7 +22,8 @@ export interface DevicesClientDeps {
export function deviceRequest(deps: DevicesClientDeps, machineId: string, type: string, payload: Record<string, unknown> = {}): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
- const socket = deps.connect(`ws://127.0.0.1:${deps.port}/api/local-ws`, localCredentialHeaders(deps.dataDir ?? env.ADAPTER_DATA_DIR))
+ const line = localWsTarget(deps.dataDir ?? env.ADAPTER_DATA_DIR, deps.port)
+ const socket = deps.connect(line.url, line.headers)
const requestId = randomUUID()
let settled = false, sent = false
const finish = (error: Error | null, reply?: Record<string, unknown>): void => {
@@ -59,8 +61,9 @@ interface Host { machineId: string; name: string; online: boolean }
async function ownedHosts(deps: DevicesClientDeps): Promise<Host[]> {
const localId = await deps.machineId()
if (!localId) throw new Error('Start Harness on this computer first.')
- const response = await (deps.fetch ?? fetch)(`http://127.0.0.1:${deps.port}/api/machines`, {
- headers: { 'x-adapter-local': '1', ...localCredentialHeaders(deps.dataDir ?? env.ADAPTER_DATA_DIR) }, signal: AbortSignal.timeout(8000),
+ const dataDir = deps.dataDir ?? env.ADAPTER_DATA_DIR
+ const response = await (deps.fetch ?? daemonFetch(dataDir, deps.port))(`http://127.0.0.1:${deps.port}/api/machines`, {
+ headers: { 'x-adapter-local': '1', ...localCredentialHeaders(dataDir) }, signal: AbortSignal.timeout(8000),
})
if (!response.ok) throw new Error('Could not read the account’s computers. Sign in and try again.')
const body = await response.json() as { data?: { machines?: Record<string, unknown>[] }; machines?: Record<string, unknown>[] }
diff --git a/cli/src/devicesCommand.spec.ts b/cli/src/devicesCommand.spec.ts
index ae04948e9..468fc6f2b 100644
--- a/cli/src/devicesCommand.spec.ts
+++ b/cli/src/devicesCommand.spec.ts
@@ -87,7 +87,8 @@ function cliEnv(port: number): NodeJS.ProcessEnv {
...process.env,
HOME: root,
HARNESS_AUTH_DIR: join(root, 'auth'),
- ADAPTER_DATA_DIR: join(root, 'data'),
+ // Too long to hold a socket: the one case where the CLI asks this fake daemon's port.
+ ADAPTER_DATA_DIR: join(root, 'd'.repeat(100)),
ADAPTER_RUNTIME_DIR: join(root, 'runtime'),
ADAPTER_CLI_DIR: join(root, 'cli'),
ADAPTER_COMPUTER_ID_FILE: join(root, 'computer-id'),
diff --git a/cli/src/e2e/harnessLocal.spec.ts b/cli/src/e2e/harnessLocal.spec.ts
index 23c42c6e1..7f8c33ad6 100644
--- a/cli/src/e2e/harnessLocal.spec.ts
+++ b/cli/src/e2e/harnessLocal.spec.ts
@@ -1,6 +1,10 @@
import { createServer, type Server } from 'node:http'
import type { AddressInfo } from 'node:net'
-import { afterEach, describe, expect, it } from 'vitest'
+import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { env } from '../config/env.js'
import { startHookServer, type HookServerHandlers } from '../hookServer.js'
import { machineId } from './harnessLocal.js'
@@ -9,7 +13,15 @@ import { machineId } from './harnessLocal.js'
// stopped at "daemon /api/status has no machineId" the day its daemon updated to 0.4.21 (2026-10-19), because
// the e2e asked without it. Against the real server, so a change to that gate fails here, not on grid-dev.
let server: Server | null = null
+const savedDataDir = env.ADAPTER_DATA_DIR
+beforeEach(() => {
+ // Too long to hold a socket: the case where the e2e asks a daemon's port. Over a socket no credential is shown at all.
+ env.ADAPTER_DATA_DIR = join(mkdtempSync(join(tmpdir(), 'harness-local-')), 'd'.repeat(100))
+ mkdirSync(env.ADAPTER_DATA_DIR, { mode: 0o700 })
+})
afterEach(async () => {
+ rmSync(dirname(env.ADAPTER_DATA_DIR), { recursive: true, force: true })
+ env.ADAPTER_DATA_DIR = savedDataDir
delete process.env.HARNESS_PORT
delete process.env.HARNESS_MACHINE_ID
await new Promise<void>((done) => (server ? server.close(() => done()) : done()))
diff --git a/cli/src/e2e/harnessLocal.ts b/cli/src/e2e/harnessLocal.ts
index 8c8fafd2f..11930b163 100644
--- a/cli/src/e2e/harnessLocal.ts
+++ b/cli/src/e2e/harnessLocal.ts
@@ -9,6 +9,7 @@ import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { env } from '../config/env.js'
import { localCredentialHeaders } from '../lib/localCredential.js'
+import { daemonFetch, localWsTarget } from '../lib/localTransport.js'
import type { GridOverride } from './gridSwitchDriver.js'
const execFileP = promisify(execFile)
@@ -28,7 +29,7 @@ export function localHeaders(): Record<string, string> {
}
export function daemonUrl(): string {
- return `ws://127.0.0.1:${daemonPort()}/api/local-ws`
+ return localWsTarget(env.ADAPTER_DATA_DIR, daemonPort()).url
}
/**
@@ -39,7 +40,7 @@ export function daemonUrl(): string {
*/
export async function machineId(): Promise<string> {
if (process.env.HARNESS_MACHINE_ID) return process.env.HARNESS_MACHINE_ID
- const res = await fetch(`http://127.0.0.1:${daemonPort()}/api/status`, { headers: localHeaders(), signal: AbortSignal.timeout(3_000) })
+ const res = await daemonFetch(env.ADAPTER_DATA_DIR, daemonPort())(`http://127.0.0.1:${daemonPort()}/api/status`, { headers: localHeaders(), signal: AbortSignal.timeout(3_000) })
if (!res.ok) throw new Error(`daemon /api/status answered ${res.status} — is \`harness\` running on port ${daemonPort()}?`)
const status = (await res.json()) as { machineId?: unknown; credentialRequired?: unknown }
// The public answer: this process could not show the credential (another OS user, or another data folder).
diff --git a/cli/src/engines/__fixtures__/native-version.golden.json b/cli/src/engines/__fixtures__/native-version.golden.json
index 3d9389836..5434572a0 100644
--- a/cli/src/engines/__fixtures__/native-version.golden.json
+++ b/cli/src/engines/__fixtures__/native-version.golden.json
@@ -14,11 +14,11 @@
"files": [
{
"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",
- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
},
{
"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",
- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
}
]
},
@@ -41,7 +41,7 @@
},
{
"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",
- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
}
]
},
@@ -60,11 +60,11 @@
"files": [
{
"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",
- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
},
{
"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",
- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
}
]
},
@@ -76,11 +76,11 @@
"files": [
{
"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",
- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
},
{
"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",
- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
}
]
},
@@ -99,11 +99,11 @@
"files": [
{
"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",
- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
},
{
"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",
- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
}
]
},
@@ -126,7 +126,7 @@
},
{
"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",
- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
}
]
},
@@ -145,11 +145,11 @@
"files": [
{
"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",
- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
},
{
"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",
- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
}
]
},
@@ -161,11 +161,11 @@
"files": [
{
"file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",
- "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
+ "source": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.<version>:4242) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n"
},
{
"file": "<root>/HOME/.config/opencode/plugins/launcher-register/tui.js",
- "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
+ "source": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.<version>:4242) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/ADAPTER_DATA_DIR/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.<version>:4242/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n"
}
]
}
diff --git a/cli/src/engines/__fixtures__/other-hooks.golden.json b/cli/src/engines/__fixtures__/other-hooks.golden.json
index 58b81cfa6..dc7b65500 100644
--- a/cli/src/engines/__fixtures__/other-hooks.golden.json
+++ b/cli/src/engines/__fixtures__/other-hooks.golden.json
@@ -14,13 +14,13 @@
"8f5114f5734c2d24": "{\n \"version\": 1,\n \"note\": \"café ✓\",\n \"hooks\": {\n \"sessionStart\": [\n {\n \"command\": \"foreign-start\"\n },\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ],\n \"afterFileEdit\": [\n {\n \"command\": \"foreign-edit\"\n }\n ],\n \"beforeSubmitPrompt\": [\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ],\n \"preToolUse\": [\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ],\n \"stop\": [\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ],\n \"sessionEnd\": [\n {\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\n \"failClosed\": false\n }\n ]\n }\n}\n",
"e161f02becaa47e8": "{\"hooks\":{\"sessionStart\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}],\"beforeSubmitPrompt\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}],\"preToolUse\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}],\"stop\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}],\"sessionEnd\":[{\"command\":\"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine cursor\",\"failClosed\":false}]},\"version\":1}",
"d979437596e2baaf": "{\n \"version\": 1,\n \"note\": \"café ✓\",\n \"hooks\": {\n \"sessionStart\": [\n {\n \"command\": \"foreign-start\"\n }\n ],\n \"afterFileEdit\": [\n {\n \"command\": \"foreign-edit\"\n }\n ]\n }\n}\n",
- "8de376ba3baa5c8f": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.0.0.1:19473) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n",
+ "b42eab635c185981": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.0.0.1:19473) which session this pane shows, as the 1.x plugin does. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport default {\n id: \"harness-session-register\",\n setup(ctx) {\n const pane = process.env.TMUX_PANE\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const router = ctx && ctx.ui && ctx.ui.router\n if ((!pane && !ptyPane) || !router || typeof router.current !== \"function\") return\n const posted = new Set()\n let busy = false\n const post = async (sessionID) => {\n const token = hookToken()\n if (!token || !sessionID || posted.has(sessionID) || busy) return\n busy = true\n try {\n let info\n try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}\n if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task card\n const cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()\n const res = await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: pane ? [{ backend: \"tmux\", paneId: pane }] : [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }],\n }),\n })\n if (res && res.ok) posted.add(sessionID)\n } catch {} finally { busy = false }\n }\n const check = () => {\n try { const at = router.current(); if (at && at.type === \"session\" && at.sessionID) post(at.sessionID) } catch {}\n }\n check()\n const timer = setInterval(check, 1000)\n if (timer && typeof timer.unref === \"function\") timer.unref()\n return () => clearInterval(timer)\n },\n}\n",
"3cd1ae59e87ad8ec": "// someone else's plugin\nexport default {}\n",
- "4bfbdceafa84276e": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n",
- "8e291cfd70ebba26": "// session-register — auto-installed by the machine adapter. Binds this Kilo session to the\n// local machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"kilo\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n",
- "e3b07beb0331f78f": "// session-register — auto-installed by the machine adapter. Binds this Pi session to the local\n// machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\n\nexport default function (pi: ExtensionAPI) {\n let announced = false; // posted at least once (the transcript may not exist yet)\n let registered = false; // posted with a real, on-disk transcript — nothing left to do\n\n const register = async (ctx: any) => {\n const pane = process.env.TMUX_PANE;\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\");\n let token = \"\";\n try { token = readFileSync(\"<root>/data/hook-credential\", \"utf8\").trim(); } catch {}\n if ((!pane && !ptyPane) || !token) return;\n // Pi knows the session file path immediately but only WRITES it once the first assistant message\n // lands. Sending a path that isn't on disk yet is rejected by the daemon (it validates the file),\n // so announce without one first and attach the real path on a later turn.\n const file = ctx?.sessionManager?.getSessionFile?.() ?? null;\n const ready = !!file && existsSync(file);\n if (registered || (announced && !ready)) return;\n const sessionId = ctx?.sessionManager?.getSessionId?.();\n if (!sessionId) return;\n try {\n const res = await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"pi\",\n pluginVersion: \"<version>\",\n sessionId,\n transcriptPath: ready ? file : undefined,\n cwd: ctx?.cwd ?? undefined,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n });\n if (!res.ok) return; // daemon refused (e.g. transcript not readable yet) — retry on the next turn\n announced = true;\n if (ready) registered = true;\n } catch {}\n };\n\n // session_start fires before the transcript exists; the turn hooks catch it once it does.\n pi.on(\"session_start\", async (_event, ctx) => { await register(ctx); });\n pi.on(\"turn_start\", async (_event, ctx) => { await register(ctx); });\n pi.on(\"turn_end\", async (_event, ctx) => { await register(ctx); });\n}\n",
+ "86391f37154d09af": "// session-register — auto-installed by the machine adapter. Binds this OpenCode session to the\n// local machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"opencode\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n",
+ "6f9caf1088585abe": "// session-register — auto-installed by the machine adapter. Binds this Kilo session to the\n// local machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { readFileSync } from \"node:fs\"\nconst hookToken = () => { try { return readFileSync(\"<root>/data/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nexport const MachineRegister = async ({ directory, worktree, project, client }) => {\n const seen = new Set()\n const post = async (sessionID) => {\n const pane = process.env.TMUX_PANE\n // A Harness pty host pane (Windows) names itself HARNESS_PANE=<instance>:%N, and has no TMUX_PANE.\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\")\n const token = hookToken()\n if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) return\n seen.add(sessionID)\n try {\n await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"kilo\",\n pluginVersion: \"<version>\",\n sessionId: sessionID,\n cwd: directory || worktree || (project && project.worktree) || null,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n })\n } catch {}\n }\n return {\n event: async ({ event }) => {\n if (!event) return\n if (event.type === \"session.created\" || event.type === \"session.updated\") {\n const p = event.properties || {}\n const info = p.info || {}\n if (info.parentID) return // sub-agent child session — shown under its parent's Task card, not a top-level agent\n await post(info.id || p.sessionID || p.sessionId)\n }\n },\n }\n}\n",
+ "2fdcafede309e332": "// session-register — auto-installed by the machine adapter. Binds this Pi session to the local\n// machine daemon (127.0.0.1:19473) so it can be mirrored to web/device. No-op if machine isn't running.\nimport { existsSync, readFileSync } from \"node:fs\";\nimport type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\n\nexport default function (pi: ExtensionAPI) {\n let announced = false; // posted at least once (the transcript may not exist yet)\n let registered = false; // posted with a real, on-disk transcript — nothing left to do\n\n const register = async (ctx: any) => {\n const pane = process.env.TMUX_PANE;\n const ptyPane = pane ? null : /^(p\\d{1,4}(?:-(?:[0-9A-Za-z.-]{1,32}|h[0-9a-f]{12}))?):(%\\d{1,9})$/.exec(process.env.HARNESS_PANE || \"\");\n let token = \"\";\n try { token = readFileSync(\"<root>/data/hook-token\", \"utf8\").trim(); } catch {}\n if ((!pane && !ptyPane) || !token) return;\n // Pi knows the session file path immediately but only WRITES it once the first assistant message\n // lands. Sending a path that isn't on disk yet is rejected by the daemon (it validates the file),\n // so announce without one first and attach the real path on a later turn.\n const file = ctx?.sessionManager?.getSessionFile?.() ?? null;\n const ready = !!file && existsSync(file);\n if (registered || (announced && !ready)) return;\n const sessionId = ctx?.sessionManager?.getSessionId?.();\n if (!sessionId) return;\n try {\n const res = await fetch(\"http://127.0.0.1:19473/api/hook/session-start\", {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", \"x-harness-hook-token\": token },\n body: JSON.stringify({\n engine: \"pi\",\n pluginVersion: \"<version>\",\n sessionId,\n transcriptPath: ready ? file : undefined,\n cwd: ctx?.cwd ?? undefined,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: \"tmux\", paneId: pane }] : []),\n ...(ptyPane ? [{ backend: \"ptyhost\", instance: ptyPane[1], paneId: ptyPane[2] }] : []),\n ],\n }),\n });\n if (!res.ok) return; // daemon refused (e.g. transcript not readable yet) — retry on the next turn\n announced = true;\n if (ready) registered = true;\n } catch {}\n };\n\n // session_start fires before the transcript exists; the turn hooks catch it once it does.\n pi.on(\"session_start\", async (_event, ctx) => { await register(ctx); });\n pi.on(\"turn_start\", async (_event, ctx) => { await register(ctx); });\n pi.on(\"turn_end\", async (_event, ctx) => { await register(ctx); });\n}\n",
"2351a62515202212": "// someone else's extension\nexport default function () {}\n",
- "b97cffdaf15d26d4": "// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local\n// machine daemon (127.0.0.1:19473) and writes the transcript the daemon tails, because Amp keeps none\n// on disk. No-op outside tmux.\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport const description = 'Mirrors this Amp thread to the machine adapter (web + device)'\n\nconst SESSIONS_DIR = \"<root>/home/.harness/cli/data/amp-sessions\"\n\nexport default function (amp: any) {\n const pane = process.env.TMUX_PANE\n if (!pane) return\n\n // NOT `process.cwd()`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports\n // `<project>/.amp/plugins` (measured). `PWD` is inherited from the shell that launched plain Amp.\n const workdir = process.env.PWD || process.cwd()\n\n const emitted = new Set()\n // Turn ids already opened/closed. Amp re-dispatches a message it could not deliver, firing agent.start\n // a SECOND time for the same message id (measured: two identical turn_start records 61s apart, then a\n // turn_end 'done' and a turn_end 'error' for the one turn). Written straight through, that is two turns\n // on web and device and two user bubbles in history.\n const turnsStarted = new Set()\n const turnsEnded = new Set()\n // Tool ids already written, so a tool seen BOTH as an event and as a message block is written once.\n const toolCalls = new Set()\n const toolResults = new Set()\n let registered = false\n let file = ''\n let seeded = false\n\n const line = (record: any) => {\n try {\n mkdirSync(SESSIONS_DIR, { recursive: true, mode: 0o700 })\n appendFileSync(file, JSON.stringify(record) + '\\n')\n } catch {}\n }\n\n const open = (threadId: string) => {\n if (file) return\n file = join(SESSIONS_DIR, threadId + '.jsonl')\n // `cwd` on the first line is what lets the daemon re-find this session by directory after a restart,\n // the same way it reads claude's and pi's transcripts. It must be a top-level string field.\n line({ t: 'session', threadId, cwd: workdir, at: Date.now() })\n }\n\n const register = async (threadId: string) => {\n open(threadId)\n if (registered || !existsSync(file)) return\n try {\n const token = readFileSync(\"<root>/data/hook-credential\", 'utf8').trim()\n if (!token) return\n const res = await fetch('http://127.0.0.1:19473/api/hook/session-start', {\n method: 'POST',\n headers: { 'content-type': 'application/json', 'x-harness-hook-token': token },\n body: JSON.stringify({\n engine: 'amp',\n pluginVersion: \"<version>\",\n sessionId: threadId,\n transcriptPath: file,\n cwd: workdir,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: 'tmux', paneId: pane }] : []),\n ],\n }),\n })\n if (res.ok) registered = true\n } catch {}\n }\n\n const resultId = (block: any) => String(block.toolUseID || block.tool_use_id || '')\n\n /**\n * Write everything in the thread that has not been written yet.\n *\n * This reads message BLOCKS rather than events, because the events do not cover the thread:\n *\n * - no event carries assistant text at all, and\n * - `tool.call`/`tool.result` only fire for tools the CLIENT executes. MEASURED: a `web_search`\n * turn produced no tool event and no tool lease in Amp's own log, yet the message plainly held a\n * `tool_use` block — Amp runs that tool on its server. Skipping blocks meant a search rendered as\n * nothing at all on web and device while the pane showed \"Explored 1 search\".\n *\n * `seed` marks what already exists WITHOUT writing it, for a thread that is being resumed: those\n * messages belong to earlier turns, and replaying them made a fresh turn open with an old answer in it.\n */\n const drain = async (ctx: any) => {\n let messages: any[] = []\n try { messages = await ctx.thread.messages({ from: 'end', limit: 20 }) } catch { return }\n // The FIRST drain of this plugin instance only claims what it finds; it writes nothing. That covers\n // both ways a plugin meets a thread that already has messages: a resumed thread, and a plugin reload\n // (Amp loads a plugin ONCE per process, so reload is how a running pane picks up a new build). Without\n // it, the next prompt replayed the whole recent history as if it had just happened.\n const seed = !seeded\n seeded = true\n // The seed pass would swallow the very prompt the turn needs to open on. Measured: `session.start`\n // does NOT fire when Amp launches — it fires on the first submit, and by then the thread already\n // holds one `user` message. So the seed has to tell history from the live prompt, and the test is\n // whether anything answered it: the LAST user text block with no assistant message after it is\n // waiting, not past. On a resumed thread the last message is an assistant one, so nothing opens.\n let liveUserId = ''\n for (const message of messages) {\n if (message.role === 'assistant') { liveUserId = ''; continue }\n const parts = Array.isArray(message.content) ? message.content : []\n const hasText = parts.some((b: any) => b && b.type === 'text' && typeof b.text === 'string' && b.text)\n if (hasText) liveUserId = String(message.id)\n }\n for (const message of messages) {\n const blocks = Array.isArray(message.content) ? message.content : []\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i]\n if (!block) continue\n if (block.type === 'text' || block.type === 'thinking') {\n const key = String(message.id) + '#' + i\n if (emitted.has(key)) continue\n const text = typeof block.text === 'string' ? block.text : block.thinking\n if (typeof text !== 'string' || !text) continue\n emitted.add(key)\n // A user TEXT block opens the turn.\n //\n // Amp used to announce that with an `agent.start` event, and the handler below wrote\n // `turn_start` from it. That event no longer fires — probed with a plugin that registered for\n // sixteen candidate names on amp 0.0.1786681855 and saw only `session.start`, `tool.call`,\n // `tool.result` and `agent.end`. The prompt now reaches a plugin no earlier than\n // `agent.end`, which is the END of the turn, far too late to open one.\n //\n // So it is taken from the thread instead, where drain was already reading it and dropping it:\n // measured at the first `tool.call` of a turn, `messages()` already returns the prompt, oldest\n // first. Without this the turn opens with an empty question on web and device, and the recap\n // loses what was asked.\n //\n // Only a TEXT block qualifies: a tool_result is also carried on a `user` message, so matching\n // the role alone would open a turn on every tool that returned.\n if (message.role !== 'assistant') {\n const turnId = String(message.id)\n if (turnsStarted.has(turnId)) continue\n turnsStarted.add(turnId)\n if (!seed || turnId === liveUserId) line({ t: 'turn_start', id: turnId, message: text, at: Date.now() })\n continue\n }\n if (!seed) line({ t: block.type, id: message.id, i, text })\n } else if (block.type === 'tool_use') {\n const id = String(block.id || '')\n if (!id || toolCalls.has(id)) continue\n toolCalls.add(id)\n if (!seed) line({ t: 'tool_call', id, tool: block.name, input: block.input })\n } else if (block.type === 'tool_result') {\n const id = resultId(block)\n if (!id || toolResults.has(id)) continue\n toolResults.add(id)\n // A server-run tool puts its payload under `run`; a client-run one under `content`/`output`.\n if (!seed) line({ t: 'tool_result', id, status: 'done', output: block.run ?? block.content ?? block.output })\n }\n }\n }\n }\n\n amp.on('session.start', async (event: any, ctx: any) => {\n await register(event.thread.id)\n await drain(ctx)\n })\n\n amp.on('agent.start', async (event: any, ctx: any) => {\n await register(event.thread.id)\n const id = String(event.id)\n if (!turnsStarted.has(id)) {\n turnsStarted.add(id)\n line({ t: 'turn_start', id: event.id, message: event.message, at: Date.now() })\n }\n await drain(ctx)\n })\n\n amp.on('tool.call', async (event: any, ctx: any) => {\n await register(event.thread.id)\n // CLAIM THE ID FIRST. `drain` runs before this card so a message's prose lands ahead of the tool it\n // called — but by then the tool_use block for THIS tool is already in the thread, so draining without\n // claiming wrote the card twice (measured: one Task turn produced two identical `skill` cards).\n toolCalls.add(String(event.toolUseID))\n await drain(ctx)\n line({ t: 'tool_call', id: event.toolUseID, tool: event.tool, input: event.input })\n })\n\n amp.on('tool.result', async (event: any, ctx: any) => {\n // Same rule as tool.call: claim before draining.\n toolResults.add(String(event.toolUseID))\n line({\n t: 'tool_result',\n id: event.toolUseID,\n tool: event.tool,\n status: event.status,\n output: event.output,\n })\n await drain(ctx)\n })\n\n amp.on('agent.end', async (event: any, ctx: any) => {\n await drain(ctx)\n // `message` is the prompt that STARTED this turn, and agent.end carries it even when\n // agent.start never fired (a prompt queued while Amp was connecting). Recording it here is what\n // lets history still show what was asked — see the replay branch in the normalizer.\n const id = String(event.id)\n if (turnsEnded.has(id)) return\n turnsEnded.add(id)\n line({ t: 'turn_end', id: event.id, status: event.status, message: event.message, at: Date.now() })\n })\n}\n",
+ "2a463c0e77737a30": "// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local\n// machine daemon (127.0.0.1:19473) and writes the transcript the daemon tails, because Amp keeps none\n// on disk. No-op outside tmux.\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport const description = 'Mirrors this Amp thread to the machine adapter (web + device)'\n\nconst SESSIONS_DIR = \"<root>/home/.harness/cli/data/amp-sessions\"\n\nexport default function (amp: any) {\n const pane = process.env.TMUX_PANE\n if (!pane) return\n\n // NOT `process.cwd()`: Bun runs a plugin with the PLUGIN's directory as its cwd, so that reports\n // `<project>/.amp/plugins` (measured). `PWD` is inherited from the shell that launched plain Amp.\n const workdir = process.env.PWD || process.cwd()\n\n const emitted = new Set()\n // Turn ids already opened/closed. Amp re-dispatches a message it could not deliver, firing agent.start\n // a SECOND time for the same message id (measured: two identical turn_start records 61s apart, then a\n // turn_end 'done' and a turn_end 'error' for the one turn). Written straight through, that is two turns\n // on web and device and two user bubbles in history.\n const turnsStarted = new Set()\n const turnsEnded = new Set()\n // Tool ids already written, so a tool seen BOTH as an event and as a message block is written once.\n const toolCalls = new Set()\n const toolResults = new Set()\n let registered = false\n let file = ''\n let seeded = false\n\n const line = (record: any) => {\n try {\n mkdirSync(SESSIONS_DIR, { recursive: true, mode: 0o700 })\n appendFileSync(file, JSON.stringify(record) + '\\n')\n } catch {}\n }\n\n const open = (threadId: string) => {\n if (file) return\n file = join(SESSIONS_DIR, threadId + '.jsonl')\n // `cwd` on the first line is what lets the daemon re-find this session by directory after a restart,\n // the same way it reads claude's and pi's transcripts. It must be a top-level string field.\n line({ t: 'session', threadId, cwd: workdir, at: Date.now() })\n }\n\n const register = async (threadId: string) => {\n open(threadId)\n if (registered || !existsSync(file)) return\n try {\n const token = readFileSync(\"<root>/data/hook-token\", 'utf8').trim()\n if (!token) return\n const res = await fetch('http://127.0.0.1:19473/api/hook/session-start', {\n method: 'POST',\n headers: { 'content-type': 'application/json', 'x-harness-hook-token': token },\n body: JSON.stringify({\n engine: 'amp',\n pluginVersion: \"<version>\",\n sessionId: threadId,\n transcriptPath: file,\n cwd: workdir,\n tmuxPane: pane,\n callerPid: process.pid,\n runtimeHints: [\n ...(pane ? [{ backend: 'tmux', paneId: pane }] : []),\n ],\n }),\n })\n if (res.ok) registered = true\n } catch {}\n }\n\n const resultId = (block: any) => String(block.toolUseID || block.tool_use_id || '')\n\n /**\n * Write everything in the thread that has not been written yet.\n *\n * This reads message BLOCKS rather than events, because the events do not cover the thread:\n *\n * - no event carries assistant text at all, and\n * - `tool.call`/`tool.result` only fire for tools the CLIENT executes. MEASURED: a `web_search`\n * turn produced no tool event and no tool lease in Amp's own log, yet the message plainly held a\n * `tool_use` block — Amp runs that tool on its server. Skipping blocks meant a search rendered as\n * nothing at all on web and device while the pane showed \"Explored 1 search\".\n *\n * `seed` marks what already exists WITHOUT writing it, for a thread that is being resumed: those\n * messages belong to earlier turns, and replaying them made a fresh turn open with an old answer in it.\n */\n const drain = async (ctx: any) => {\n let messages: any[] = []\n try { messages = await ctx.thread.messages({ from: 'end', limit: 20 }) } catch { return }\n // The FIRST drain of this plugin instance only claims what it finds; it writes nothing. That covers\n // both ways a plugin meets a thread that already has messages: a resumed thread, and a plugin reload\n // (Amp loads a plugin ONCE per process, so reload is how a running pane picks up a new build). Without\n // it, the next prompt replayed the whole recent history as if it had just happened.\n const seed = !seeded\n seeded = true\n // The seed pass would swallow the very prompt the turn needs to open on. Measured: `session.start`\n // does NOT fire when Amp launches — it fires on the first submit, and by then the thread already\n // holds one `user` message. So the seed has to tell history from the live prompt, and the test is\n // whether anything answered it: the LAST user text block with no assistant message after it is\n // waiting, not past. On a resumed thread the last message is an assistant one, so nothing opens.\n let liveUserId = ''\n for (const message of messages) {\n if (message.role === 'assistant') { liveUserId = ''; continue }\n const parts = Array.isArray(message.content) ? message.content : []\n const hasText = parts.some((b: any) => b && b.type === 'text' && typeof b.text === 'string' && b.text)\n if (hasText) liveUserId = String(message.id)\n }\n for (const message of messages) {\n const blocks = Array.isArray(message.content) ? message.content : []\n for (let i = 0; i < blocks.length; i++) {\n const block = blocks[i]\n if (!block) continue\n if (block.type === 'text' || block.type === 'thinking') {\n const key = String(message.id) + '#' + i\n if (emitted.has(key)) continue\n const text = typeof block.text === 'string' ? block.text : block.thinking\n if (typeof text !== 'string' || !text) continue\n emitted.add(key)\n // A user TEXT block opens the turn.\n //\n // Amp used to announce that with an `agent.start` event, and the handler below wrote\n // `turn_start` from it. That event no longer fires — probed with a plugin that registered for\n // sixteen candidate names on amp 0.0.1786681855 and saw only `session.start`, `tool.call`,\n // `tool.result` and `agent.end`. The prompt now reaches a plugin no earlier than\n // `agent.end`, which is the END of the turn, far too late to open one.\n //\n // So it is taken from the thread instead, where drain was already reading it and dropping it:\n // measured at the first `tool.call` of a turn, `messages()` already returns the prompt, oldest\n // first. Without this the turn opens with an empty question on web and device, and the recap\n // loses what was asked.\n //\n // Only a TEXT block qualifies: a tool_result is also carried on a `user` message, so matching\n // the role alone would open a turn on every tool that returned.\n if (message.role !== 'assistant') {\n const turnId = String(message.id)\n if (turnsStarted.has(turnId)) continue\n turnsStarted.add(turnId)\n if (!seed || turnId === liveUserId) line({ t: 'turn_start', id: turnId, message: text, at: Date.now() })\n continue\n }\n if (!seed) line({ t: block.type, id: message.id, i, text })\n } else if (block.type === 'tool_use') {\n const id = String(block.id || '')\n if (!id || toolCalls.has(id)) continue\n toolCalls.add(id)\n if (!seed) line({ t: 'tool_call', id, tool: block.name, input: block.input })\n } else if (block.type === 'tool_result') {\n const id = resultId(block)\n if (!id || toolResults.has(id)) continue\n toolResults.add(id)\n // A server-run tool puts its payload under `run`; a client-run one under `content`/`output`.\n if (!seed) line({ t: 'tool_result', id, status: 'done', output: block.run ?? block.content ?? block.output })\n }\n }\n }\n }\n\n amp.on('session.start', async (event: any, ctx: any) => {\n await register(event.thread.id)\n await drain(ctx)\n })\n\n amp.on('agent.start', async (event: any, ctx: any) => {\n await register(event.thread.id)\n const id = String(event.id)\n if (!turnsStarted.has(id)) {\n turnsStarted.add(id)\n line({ t: 'turn_start', id: event.id, message: event.message, at: Date.now() })\n }\n await drain(ctx)\n })\n\n amp.on('tool.call', async (event: any, ctx: any) => {\n await register(event.thread.id)\n // CLAIM THE ID FIRST. `drain` runs before this card so a message's prose lands ahead of the tool it\n // called — but by then the tool_use block for THIS tool is already in the thread, so draining without\n // claiming wrote the card twice (measured: one Task turn produced two identical `skill` cards).\n toolCalls.add(String(event.toolUseID))\n await drain(ctx)\n line({ t: 'tool_call', id: event.toolUseID, tool: event.tool, input: event.input })\n })\n\n amp.on('tool.result', async (event: any, ctx: any) => {\n // Same rule as tool.call: claim before draining.\n toolResults.add(String(event.toolUseID))\n line({\n t: 'tool_result',\n id: event.toolUseID,\n tool: event.tool,\n status: event.status,\n output: event.output,\n })\n await drain(ctx)\n })\n\n amp.on('agent.end', async (event: any, ctx: any) => {\n await drain(ctx)\n // `message` is the prompt that STARTED this turn, and agent.end carries it even when\n // agent.start never fired (a prompt queued while Amp was connecting). Recording it here is what\n // lets history still show what was asked — see the replay branch in the normalizer.\n const id = String(event.id)\n if (turnsEnded.has(id)) return\n turnsEnded.add(id)\n line({ t: 'turn_end', id: event.id, status: event.status, message: event.message, at: Date.now() })\n })\n}\n",
"f2535bcde1fe8de5": "// someone else's plugin\nexport default function () {}\n",
"988dbdec0e4eb48d": "\n\n# machine-adapter: session discovery (managed block — safe to delete)\nhooks:\n on_session_start:\n - command: \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine hermes\"\n timeout: 10\n pre_llm_call:\n - command: \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine hermes\"\n timeout: 10\n# machine-adapter: end\n",
"1b00ee446739f819": "{\n \"approvals\": [\n {\n \"event\": \"on_session_start\",\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine hermes\"\n },\n {\n \"event\": \"pre_llm_call\",\n \"command\": \"'<node>' '<script>' --port 19473 --data-dir '<root>/data' --claude-projects-dir '<root>/home/.claude/projects' --codex-home '<root>/home/.codex' --grok-home '<root>/home/.grok' --cursor-home '<root>/home/.cursor' --hermes-home '<root>/home/.hermes' --commandcode-home '<root>/home/.commandcode' --devin-home '<root>/home/.local/share/devin/cli' --agy-home '<root>/home/.gemini/antigravity-cli' --copilot-home '<root>/home/.copilot' --engine hermes\"\n }\n ]\n}\n",
@@ -1037,7 +1037,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1077,7 +1077,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1117,7 +1117,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1157,7 +1157,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1197,7 +1197,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1237,7 +1237,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1277,7 +1277,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1317,7 +1317,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1357,7 +1357,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1397,7 +1397,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1437,7 +1437,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1477,7 +1477,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1517,7 +1517,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1557,7 +1557,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1597,7 +1597,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1636,7 +1636,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1676,7 +1676,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1716,7 +1716,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1756,7 +1756,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
},
"elsewhere/real": {
"type": "file",
@@ -1804,7 +1804,7 @@
"elsewhere/real": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1844,7 +1844,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1884,7 +1884,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1924,7 +1924,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -1963,7 +1963,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "444",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2003,7 +2003,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2116,7 +2116,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2159,7 +2159,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js.<pid>.tmp": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2199,7 +2199,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "600",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2238,7 +2238,7 @@
"home/.config/opencode/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "4bfbdceafa84276e"
+ "text": "86391f37154d09af"
},
"home/.config/opencode/plugins": {
"type": "dir",
@@ -2251,7 +2251,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2289,7 +2289,7 @@
"home/.config/opencode/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "4bfbdceafa84276e"
+ "text": "86391f37154d09af"
},
"home/.config/opencode/plugins": {
"type": "dir",
@@ -2302,7 +2302,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2342,7 +2342,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2387,7 +2387,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2436,7 +2436,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2486,7 +2486,7 @@
"home/.config/opencode/plugins/launcher-register/tui.js": {
"type": "file",
"mode": "644",
- "text": "8de376ba3baa5c8f"
+ "text": "b42eab635c185981"
}
}
},
@@ -2522,7 +2522,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2558,7 +2558,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2594,7 +2594,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2630,7 +2630,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2666,7 +2666,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2702,7 +2702,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2738,7 +2738,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2774,7 +2774,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2810,7 +2810,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2846,7 +2846,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2882,7 +2882,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2918,7 +2918,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2954,7 +2954,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -2990,7 +2990,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3026,7 +3026,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3061,7 +3061,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3097,7 +3097,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3133,7 +3133,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3169,7 +3169,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
},
"elsewhere/real": {
"type": "file",
@@ -3213,7 +3213,7 @@
"elsewhere/real": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3249,7 +3249,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3285,7 +3285,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3321,7 +3321,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3356,7 +3356,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "444",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3392,7 +3392,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3493,7 +3493,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3532,7 +3532,7 @@
"home/.config/kilo/plugin/launcher-register.js.<pid>.tmp": {
"type": "file",
"mode": "644",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3568,7 +3568,7 @@
"home/.config/kilo/plugin/launcher-register.js": {
"type": "file",
"mode": "600",
- "text": "8e291cfd70ebba26"
+ "text": "6f9caf1088585abe"
}
}
},
@@ -3604,7 +3604,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3640,7 +3640,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3676,7 +3676,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3712,7 +3712,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3748,7 +3748,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3784,7 +3784,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3820,7 +3820,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3856,7 +3856,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3892,7 +3892,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3928,7 +3928,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -3964,7 +3964,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4000,7 +4000,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4036,7 +4036,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4072,7 +4072,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4108,7 +4108,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4143,7 +4143,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4179,7 +4179,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4215,7 +4215,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4251,7 +4251,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
},
"elsewhere/real": {
"type": "file",
@@ -4295,7 +4295,7 @@
"elsewhere/real": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4331,7 +4331,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4367,7 +4367,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4403,7 +4403,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4438,7 +4438,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "444",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4474,7 +4474,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4575,7 +4575,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4614,7 +4614,7 @@
"home/.pi/agent/extensions/launcher-register.ts.<pid>.tmp": {
"type": "file",
"mode": "644",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4650,7 +4650,7 @@
"home/.pi/agent/extensions/launcher-register.ts": {
"type": "file",
"mode": "600",
- "text": "e3b07beb0331f78f"
+ "text": "2fdcafede309e332"
}
}
},
@@ -4687,7 +4687,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -4740,7 +4740,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -4793,7 +4793,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -4846,7 +4846,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -4899,7 +4899,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -4952,7 +4952,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5005,7 +5005,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5058,7 +5058,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5111,7 +5111,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5164,7 +5164,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5217,7 +5217,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5270,7 +5270,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5323,7 +5323,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5376,7 +5376,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5429,7 +5429,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5480,7 +5480,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
}
}
},
@@ -5517,7 +5517,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5570,7 +5570,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5623,7 +5623,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5683,7 +5683,7 @@
"elsewhere/real": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
}
}
},
@@ -5720,7 +5720,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5773,7 +5773,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5826,7 +5826,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -5877,7 +5877,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "444",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
}
}
},
@@ -5914,7 +5914,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -6064,7 +6064,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -6119,7 +6119,7 @@
"home/.config/amp/plugins/launcher-register.ts.<pid>.tmp": {
"type": "file",
"mode": "644",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
@@ -6172,7 +6172,7 @@
"home/.config/amp/plugins/launcher-register.ts": {
"type": "file",
"mode": "600",
- "text": "b97cffdaf15d26d4"
+ "text": "2a463c0e77737a30"
},
"home/.harness": {
"type": "dir",
diff --git a/cli/src/engines/nativeHooks.ts b/cli/src/engines/nativeHooks.ts
index 83c433701..a6c7a4129 100644
--- a/cli/src/engines/nativeHooks.ts
+++ b/cli/src/engines/nativeHooks.ts
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path'
import { hookPreparationRoutes, runHookPreparation, type HookPreparationProof } from './kit/nativeHookFiles.js'
import { nativeHookLocations, type NativeHookOptions } from './kit/nativeLocations.js'
import { env } from '../config/env.js'
+import { hookTokenPath } from '../lib/hookAuth.js'
import { VERSION } from '../version.js'
import { OPENCODE_LEGACY_PLUGIN, OPENCODE_TUI_PLUGIN, OPENCODE_LEGACY_REMOVAL, OPENCODE_VERSION } from './opencode/contract.js'
import { KILO_PLUGIN } from './kilo/contract.js'
@@ -30,7 +31,7 @@ export const installCommandCodeHooks = (port: number, options?: NativeHookOption
export const installDevinHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...DEVIN_HOOK_SETTINGS, file: nativeHookLocations(options.environment).DEVIN_CONFIG_PATH } : DEVIN_HOOK_SETTINGS, port, options)
const pluginValues = (port: number) => ({
- port: String(port), credential: JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential')), version: JSON.stringify(VERSION),
+ port: String(port), credential: JSON.stringify(hookTokenPath(env.ADAPTER_DATA_DIR)), version: JSON.stringify(VERSION),
})
export const installKiloPlugin = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativePlugin(options?.environment ? { ...KILO_PLUGIN, file: join(nativeHookLocations(options.environment).KILO_PLUGIN_DIR, 'launcher-register.js') } : KILO_PLUGIN, pluginValues(port), options)
export const installPiExtension = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativePlugin(options?.environment ? { ...PI_EXTENSION, file: join(nativeHookLocations(options.environment).PI_AGENT_DIR, 'extensions', 'launcher-register.ts') } : PI_EXTENSION, pluginValues(port), options)
diff --git a/cli/src/engines/otherAdmission.golden.spec.ts b/cli/src/engines/otherAdmission.golden.spec.ts
index 7469866a3..067584a3a 100644
--- a/cli/src/engines/otherAdmission.golden.spec.ts
+++ b/cli/src/engines/otherAdmission.golden.spec.ts
@@ -133,7 +133,8 @@ describe('how the core admits a Hermes session and learns its home', () => {
const started = await m.hookServer.startHookServer(0, {
onRegistered: (entry) => { registered.push({ sessionId: entry.sessionId, engine: entry.engine, hermesHome: entry.hermesHome ?? null }) },
onSessionEnd: () => {},
- })
+ // This spec fakes the platform, so the real lookup of who is calling cannot run (lib/peerAccount.spec.ts tests it).
+ }, { peerAccount: async () => true })
server = started.server
const headers = { 'content-type': 'application/json', 'x-harness-hook-token': m.hookAuth.readHookCredential(join(root, 'data'))! }
const results: unknown[] = []
diff --git a/cli/src/hookAdmission.golden.spec.ts b/cli/src/hookAdmission.golden.spec.ts
index 390299d6c..8e8704f24 100644
--- a/cli/src/hookAdmission.golden.spec.ts
+++ b/cli/src/hookAdmission.golden.spec.ts
@@ -82,7 +82,8 @@ it.each(['linux', 'darwin'])('preserves healthy native hook admission on %s', as
onTurnStop: value => { turns.push({ stop: value }) },
onToolStart: value => { turns.push({ tool: value }) },
onSessionEnd: (sessionId, reason) => { ends.push({ sessionId, reason }) },
- })
+ // This spec fakes the platform and child_process, so the real lookup of who is calling cannot run (lib/peerAccount.spec.ts tests it).
+ }, { peerAccount: async () => true })
server = started.server
const send = async (endpoint: string, body: Record<string, unknown>, authorized = true) => {
const response = await fetch(`http://127.0.0.1:${started.port}/api/hook/${endpoint}`, {
diff --git a/cli/src/hookNotify.spec.ts b/cli/src/hookNotify.spec.ts
index ddfc8d28f..aff75e31e 100644
--- a/cli/src/hookNotify.spec.ts
+++ b/cli/src/hookNotify.spec.ts
@@ -1,7 +1,7 @@
import { execFileSync, spawn, spawnSync } from 'child_process'
import { createServer } from 'http'
-import { createServer as createNetServer } from 'net'
-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'
+import { connect as netConnect, createServer as createNetServer } from 'net'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, symlinkSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { dirname, join } from 'path'
import { fileURLToPath, pathToFileURL } from 'url'
@@ -34,6 +34,25 @@ afterEach(async () => {
for (const dir of tmpDirs.splice(0)) rmSync(dir, { recursive: true, force: true })
})
+/**
+ * The daemon's socket, as the hook now reaches it (audit H1), in front of a test's fake daemon on [port]. A connection
+ * to a port nobody holds is cut, as a daemon that is down. A folder that does not exist yet stays without one.
+ */
+async function daemonSocketFor(port: number, dataDir: string | undefined): Promise<void> {
+ if (!dataDir || !existsSync(dataDir)) return
+ const path = join(dataDir, `daemon-${port}.sock`)
+ if (existsSync(path)) return
+ const proxy = createNetServer((client) => {
+ const upstream = netConnect(port, '127.0.0.1')
+ client.on('error', () => upstream.destroy())
+ upstream.on('error', () => client.destroy())
+ client.pipe(upstream).pipe(client)
+ })
+ netServers.push(proxy)
+ await new Promise<void>((resolve) => { proxy.listen(path, resolve) })
+ chmodSync(path, 0o600)
+}
+
interface RunHookOpts {
port: number
tmuxPane?: string
@@ -184,6 +203,7 @@ fs.readFileSync = (path, ...args) => {
mkdirSync(hookDataDir, { recursive: true, mode: 0o700 })
try { writeFileSync(join(hookDataDir, 'hook-credential'), `${'a'.repeat(43)}\n`, { mode: 0o600, flag: 'wx' }) } catch { /* already exists */ }
}
+ daemonSocketFor(opts.port, hookDataDir).then(() => {
const child = spawn(process.execPath, args, {
env,
stdio: ['pipe', 'pipe', 'inherit'],
@@ -198,6 +218,7 @@ fs.readFileSync = (path, ...args) => {
session_id: 'session-test',
reason: 'logout',
}))
+ }, reject)
})
}
@@ -1798,6 +1819,7 @@ describe('a hook reaches the daemon that made its pane', () => {
const atDev = await collect({}, dev.credential)
publishHookRoute(release.dataDir, atRelease.port, routes)
publishHookRoute(dev.dataDir, atDev.port, routes)
+ await daemonSocketFor(atRelease.port, release.dataDir)
// The dev daemon started last: the command is its own. The pane is the release daemon's.
await runHook({
port: atDev.port, dataDir: dev.dataDir, tmuxPane: '%7', paneOwner: release.tag,
@@ -1872,6 +1894,7 @@ describe('a hook reaches the daemon that made its pane', () => {
expect(atDev.requests).toHaveLength(6)
// And with the record in order, the same hook goes to the release daemon.
publishHookRoute(release.dataDir, atRelease.port, routes)
+ await daemonSocketFor(atRelease.port, release.dataDir)
await hook(release.tag)
expect(atRelease.requests).toHaveLength(1)
})
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index 5a06da7f8..636b3d4e8 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -1148,6 +1148,83 @@ it.each(['/api/hook/session-end', '/api/hook/turn-start', '/api/hook/tool-start'
},
)
+describe('audit H1: what a secret heard on the daemon\'s port can do', () => {
+ const call = (port: number, path: string, headers: Record<string, string>, method = 'GET') =>
+ fetch(`http://127.0.0.1:${port}${path}`, { method, headers, ...(method === 'POST' ? { body: '{}' } : {}) })
+
+ const serve = async (peerAccount: () => Promise<boolean>) => {
+ const started = await startHookServer(0, {
+ onRegistered: vi.fn(), onSessionEnd: vi.fn(), onStatus: async () => ({ supported: true, secretDetail: 'x' }),
+ onAutonomousDeviceRequest: async () => ({ status: 200, body: { ok: true } }),
+ }, { peerAccount })
+ return { port: started.port, close: () => new Promise<void>((resolve) => { started.server.closeAllConnections(); started.server.close(() => resolve()) }) }
+ }
+ const credential = () => readFileSync(join(env.ADAPTER_DATA_DIR, 'hook-credential'), 'utf8').trim()
+ const hookToken = () => readFileSync(join(env.ADAPTER_DATA_DIR, 'hook-token'), 'utf8').trim()
+
+ it('the credential opens nothing for a caller of another account', async () => {
+ const asked = vi.fn(async () => false)
+ const { port, close } = await serve(asked)
+ try {
+ const secret = credential()
+ expect((await call(port, '/api/machines', { 'X-Harness-Local': secret })).status).toBe(401)
+ expect((await call(port, '/api/machines', { Authorization: `Bearer ${secret}` })).status).toBe(401)
+ expect(await (await call(port, '/api/status', { 'X-Harness-Local': secret })).json()).not.toHaveProperty('secretDetail')
+ expect((await call(port, '/api/autonomous-device/status', { Authorization: `Bearer ${secret}` })).status).toBe(403)
+ expect(asked).toHaveBeenCalled()
+ } finally { await close() }
+ })
+
+ it('the credential works for a caller of this account', async () => {
+ const { port, close } = await serve(async () => true)
+ try {
+ expect(await (await call(port, '/api/status', { 'X-Harness-Local': credential() })).json()).toHaveProperty('secretDetail')
+ expect((await call(port, '/api/autonomous-device/status', { Authorization: `Bearer ${credential()}` })).status).toBe(200)
+ } finally { await close() }
+ })
+
+ it('a wrong credential never makes the daemon ask who is calling', async () => {
+ const asked = vi.fn(async () => true)
+ const { port, close } = await serve(asked)
+ try {
+ expect((await call(port, '/api/machines', { 'X-Harness-Local': 'w'.repeat(43) })).status).toBe(401)
+ expect(asked).not.toHaveBeenCalled()
+ } finally { await close() }
+ })
+
+ it('the hook token opens the hook routes and nothing else', async () => {
+ const { port, close } = await serve(async () => true)
+ try {
+ const token = hookToken()
+ expect(token).not.toBe(credential())
+ expect((await call(port, '/api/hook/session-start', { 'x-harness-hook-token': token }, 'POST')).status).not.toBe(401)
+ const shown: Array<Record<string, string>> = [{ 'X-Harness-Local': token }, { Authorization: `Bearer ${token}` }, { 'x-harness-hook-token': token }]
+ for (const headers of shown) {
+ expect((await call(port, '/api/machines', headers)).status).toBe(401)
+ expect(await (await call(port, '/api/status', headers)).json()).not.toHaveProperty('secretDetail')
+ expect((await call(port, '/api/autonomous-device/status', headers)).status).toBe(403)
+ }
+ } finally { await close() }
+ })
+
+ it('a hook token or credential opens no hook route for a caller of another account', async () => {
+ const { port, close } = await serve(async () => false)
+ try {
+ for (const secret of [hookToken(), credential()]) {
+ expect((await call(port, '/api/hook/session-start', { 'x-harness-hook-token': secret }, 'POST')).status).toBe(401)
+ expect((await call(port, '/api/hook/session-end', { 'x-harness-hook-token': secret }, 'POST')).status).toBe(401)
+ }
+ } finally { await close() }
+ })
+
+ it('an engine plugin loaded before the hook token keeps reporting with the credential', async () => {
+ const { port, close } = await serve(async () => true)
+ try {
+ expect((await call(port, '/api/hook/session-start', { 'x-harness-hook-token': credential() }, 'POST')).status).not.toBe(401)
+ } finally { await close() }
+ })
+})
+
describe('the loopback port wants this OS user\'s local credential', () => {
// Another OS user's process reaches 127.0.0.1 too — a guest's harness running as its own user
// (docs/plans/2026-10-19-guest-machine-sharing-plan.md). Only this user can read the 0600 credential.
diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.ts
index be4b23da5..aa53f6351 100644
--- a/cli/src/hookServer.ts
+++ b/cli/src/hookServer.ts
@@ -23,7 +23,8 @@ import { registry, type RegisterInput, type RegisteredSession } from './lib/regi
import { sid } from './lib/log.js'
import { VERSION } from './version.js'
import { env } from './config/env.js'
-import { hookCredentialMatches, loadOrCreateHookCredential } from './lib/hookAuth.js'
+import { hookCredentialMatches, loadOrCreateHookCredential, loadOrCreateHookToken } from './lib/hookAuth.js'
+import { peerIsThisAccount, type PeerAccount } from './lib/peerAccount.js'
import { LOCAL_CREDENTIAL_REQUIRED, localCredentialMatches } from './lib/localCredential.js'
import { routeStoreRequest, type StoreHandler } from './lib/storeProxy.js'
import type { HookTerminalHint } from './lib/terminalTypes.js'
@@ -397,6 +398,8 @@ async function inspectHermesKind(sessionId: string, knownHome?: string): Promise
}
export interface HookServerOptions {
+ /** Whether a TCP caller runs as this OS account (lib/peerAccount.ts). A test's stand-in for another account. */
+ peerAccount?: PeerAccount
/** Also serve on this Unix socket, or with pipeToken the Windows pipe (see lib/localSocket.ts). Null or absent: TCP only. */
socketPath?: string | null
/** Windows: the daemon's token. When given, `socketPath` is a pipe whose every request proves it (lib/localSocket.ts). */
@@ -426,6 +429,8 @@ export function startHookServer(
options: HookServerOptions = {},
): Promise<{ server: http.Server; port: number; localSocket: LocalSocketServer | null }> {
const hookCredential = loadOrCreateHookCredential(env.ADAPTER_DATA_DIR)
+ const hookToken = loadOrCreateHookToken(env.ADAPTER_DATA_DIR)
+ const peerAccount: PeerAccount = options.peerAccount ?? peerIsThisAccount
const admissions = createPendingAdmissions({ isProcessCurrent: (key, scope) => admissionProcessScope(registry.byAgent(key)) === scope })
let admissionArrival = 0
const admissionHolds = new Map<string, Map<string, string>>()
@@ -483,15 +488,18 @@ export function startHookServer(
// send it, can trigger actions. A local process could still call it — same trust level as the
// CLI, which is acceptable on loopback.
const localOk = req.headers['x-adapter-local'] === '1'
- // An engine hook's token. Today the daemon's own credential; a guest's harness will carry a token
- // scoped to its own agent (docs/plans/2026-10-19-guest-machine-sharing-plan.md), checked here.
- const hookTokenMatches = (request: http.IncomingMessage): boolean =>
- hookCredentialMatches(hookCredential, request.headers['x-harness-hook-token'])
- const hookOk = hookTokenMatches(req)
+ // An engine hook's token, which opens these hook routes and nothing else (lib/hookAuth.ts). The credential
+ // is still taken here: an engine's loaded plugin keeps the copy it started with until its pane restarts. A
+ // guest's harness will carry a token scoped to its own agent (docs/plans/2026-10-19-guest-machine-sharing-plan.md).
+ // Over TCP either may have been heard by another account that held this port during a restart (audit H1), which
+ // could then forge session ends or turn stops here, so it counts only from this one. Asked only once it matched.
+ const suppliedHookToken = req.headers['x-harness-hook-token']
+ const hookOk = trustedLocal || ((hookCredentialMatches(hookToken, suppliedHookToken) || hookCredentialMatches(hookCredential, suppliedHookToken)) && await peerAccount(req.socket))
// The loopback port takes any local OS user's process, so over TCP every route but the few below
// wants the daemon's local credential (lib/localCredential.ts): the 0600 file only this OS user can
- // read. Over the daemon's Unix socket the filesystem already said who this is.
- const credentialOk = trustedLocal || localCredentialMatches(hookCredential, req)
+ // read. Over the daemon's Unix socket the filesystem already said who this is. Over TCP the credential may have
+ // been heard by another account that held this port during a restart (audit H1), so it counts only from this one.
+ const credentialOk = trustedLocal || (localCredentialMatches(hookCredential, req) && await peerAccount(req.socket))
// Open without it: liveness, the status a discovery reads (cut down, below), the hook routes (their
// own token, above) and the native device routes (their own bearer, just below).
const open = (req.method === 'GET' && (url === '/api/health' || url === '/api/status'))
@@ -502,7 +510,7 @@ export function startHookServer(
const peer = req.socket.remoteAddress
const loopback = trustedLocal || peer === '127.0.0.1' || peer === '::1' || peer === '::ffff:127.0.0.1'
const bearer = req.headers.authorization?.startsWith('Bearer ') ? req.headers.authorization.slice(7) : undefined
- if (!loopback || req.headers.origin || !hookCredentialMatches(hookCredential, bearer)) {
+ if (!loopback || req.headers.origin || !hookCredentialMatches(hookCredential, bearer) || !credentialOk) {
json(403, { error: { code: 'FORBIDDEN', message: 'Authenticated native loopback client required' } }); return
}
if (!handlers.onAutonomousDeviceRequest) { json(503, { error: { code: 'UNAVAILABLE', message: 'Autonomous device service unavailable' } }); return }
diff --git a/cli/src/lib/autonomous-device/addonCommand.spec.ts b/cli/src/lib/autonomous-device/addonCommand.spec.ts
index 38b1c26d5..89d71db3c 100644
--- a/cli/src/lib/autonomous-device/addonCommand.spec.ts
+++ b/cli/src/lib/autonomous-device/addonCommand.spec.ts
@@ -2,6 +2,8 @@ import { createHash } from 'node:crypto'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { runAutonomousDeviceCommand } from './command.js'
import { pickMachine, runAddonCommand } from './addonCommand.js'
+// Too long to hold a socket, so these calls reach the stubbed fetch rather than one.
+const UNUSED = `/unused-${'x'.repeat(100)}`
vi.mock('../hookAuth.js', () => ({ readHookCredential: () => 'hook-test-credential' }))
afterEach(() => vi.restoreAllMocks())
@@ -11,9 +13,9 @@ const quiet = () => vi.spyOn(console, 'log').mockImplementation(() => {})
describe('harness autonomous-device addon', () => {
it('reads what devices published, for one device when named', async () => {
const fetch = ok({ devices: [] }); quiet()
- expect(await runAutonomousDeviceCommand(['addon', 'state'], '/unused', 18473)).toBe(0)
+ expect(await runAutonomousDeviceCommand(['addon', 'state'], UNUSED, 18473)).toBe(0)
expect(String(fetch.mock.calls[0][0])).toBe('http://127.0.0.1:18473/api/autonomous-device/addon/state')
- expect(await runAutonomousDeviceCommand(['addon', 'state', '--device', 'a b'], '/unused', 18473)).toBe(0)
+ expect(await runAutonomousDeviceCommand(['addon', 'state', '--device', 'a b'], UNUSED, 18473)).toBe(0)
expect(String(fetch.mock.calls[1][0])).toBe('http://127.0.0.1:18473/api/autonomous-device/addon/state?deviceId=a%20b')
expect(fetch.mock.calls[1][1]).toMatchObject({ method: 'GET', headers: { Authorization: 'Bearer hook-test-credential' } })
})
@@ -21,7 +23,7 @@ describe('harness autonomous-device addon', () => {
it('posts a proposal with what was given, a fresh key, and the add-on named by --addon', async () => {
const fetch = ok({ proposal: { proposalId: 'p' } }); quiet()
expect(await runAutonomousDeviceCommand(['addon', 'propose', '--act', 'light', '--holds-ms', '30000', '--why', 'evening', '--sure', '0.6',
- '--params', '{"colour":"warm","level":2}', '--note', 'A warm evening light.', '--addon', 'evening-glow', '--device', 'lamp'], '/unused', 18473)).toBe(0)
+ '--params', '{"colour":"warm","level":2}', '--note', 'A warm evening light.', '--addon', 'evening-glow', '--device', 'lamp'], UNUSED, 18473)).toBe(0)
expect(String(fetch.mock.calls[0][0])).toBe('http://127.0.0.1:18473/api/autonomous-device/addon/propose')
const body = JSON.parse(String(fetch.mock.calls[0][1]?.body))
expect(body).toEqual({ addon: 'evening-glow', act: 'light', holdsMs: 30000, idempotencyKey: expect.stringMatching(/^[0-9a-f]{32}$/),
@@ -32,7 +34,7 @@ describe('harness autonomous-device addon', () => {
const fetch = ok({ proposal: {} }); quiet()
vi.stubEnv('CLAUDECODE', '1'); vi.stubEnv('CLAUDE_CODE_SESSION_ID', 'abc-123')
try {
- expect(await runAutonomousDeviceCommand(['addon', 'propose', '--act', 'mood', '--holds-ms', '5000', '--key', 'once'], '/unused', 18473)).toBe(0)
+ expect(await runAutonomousDeviceCommand(['addon', 'propose', '--act', 'mood', '--holds-ms', '5000', '--key', 'once'], UNUSED, 18473)).toBe(0)
} finally { vi.unstubAllEnvs() }
// The engine and a short hash: the session's own id never reaches the device.
const hash = createHash('sha256').update('claude-code:abc-123').digest('hex').slice(0, 12)
@@ -44,14 +46,14 @@ describe('harness autonomous-device addon', () => {
it('says the key a failed propose used, for a retry that sends it at most once', async () => {
vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(JSON.stringify({ error: { code: 'OUTCOME_UNKNOWN', message: 'maybe' } }), { status: 504 }))
const log = quiet()
- expect(await runAutonomousDeviceCommand(['addon', 'propose', '--act', 'mood', '--holds-ms', '5000', '--addon', 'x', '--key', 'k7', '--json'], '/unused', 18473)).toBe(1)
+ expect(await runAutonomousDeviceCommand(['addon', 'propose', '--act', 'mood', '--holds-ms', '5000', '--addon', 'x', '--key', 'k7', '--json'], UNUSED, 18473)).toBe(1)
expect(JSON.parse(String(log.mock.calls[0][0]))).toEqual({ error: { code: 'OUTCOME_UNKNOWN', message: 'maybe' }, idempotencyKey: 'k7' })
})
it('reads one proposal back', async () => {
const fetch = ok({ proposal: null }); quiet()
const id = '0b6c3c3e-8f3a-4f5a-9d2b-6f1e2a3b4c5d'
- expect(await runAutonomousDeviceCommand(['addon', 'proposal', id, '--json'], '/unused', 18473)).toBe(0)
+ expect(await runAutonomousDeviceCommand(['addon', 'proposal', id, '--json'], UNUSED, 18473)).toBe(0)
expect(String(fetch.mock.calls[0][0])).toBe(`http://127.0.0.1:18473/api/autonomous-device/addon/proposal?proposalId=${id}`)
})
@@ -67,7 +69,7 @@ describe('harness autonomous-device addon', () => {
['addon', 'state', '--act', 'light'], ['addon', 'proposal'], ['addon', 'state', 'extra'],
...['', '0x1', '1e0', '1.5', '-0.1', 'nan'].map(sure => ['addon', 'propose', '--act', 'light', '--holds-ms', '5000', '--addon', 'x', '--sure', sure]),
...['', '5e3', '5000.5', '-5000'].map(holds => ['addon', 'propose', '--act', 'light', '--holds-ms', holds, '--addon', 'x']),
- ]) expect(await runAutonomousDeviceCommand(argv, '/unused', 18473)).toBe(1)
+ ]) expect(await runAutonomousDeviceCommand(argv, UNUSED, 18473)).toBe(1)
} finally { vi.unstubAllEnvs() }
expect(fetch).not.toHaveBeenCalled()
})
@@ -81,13 +83,13 @@ describe('harness autonomous-device addon --machine', () => {
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(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(await runAddonCommand(['state', '--machine', 'lamp', '--device', 'x'], UNUSED, 18473, {}, ask)).toBe(1)
expect(fetch).not.toHaveBeenCalled()
})
})
diff --git a/cli/src/lib/autonomous-device/addonCommand.ts b/cli/src/lib/autonomous-device/addonCommand.ts
index 4c5e1c18d..2d6af7aab 100644
--- a/cli/src/lib/autonomous-device/addonCommand.ts
+++ b/cli/src/lib/autonomous-device/addonCommand.ts
@@ -4,6 +4,7 @@ import { outsideCaller } from '../../agentClient/model.js'
import { WebSocket } from 'ws'
import { deviceRequest } from '../../devices/client.js'
import { localCredentialHeaders } from '../localCredential.js'
+import { daemonFetch } from '../localTransport.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>]'
@@ -17,7 +18,7 @@ export type MachineAsk = (machine: string, op: string, input: Record<string, unk
/** The owner's machine `--machine` names, by id or name (case-blind), as this daemon lists the account's machines. */
export async function machineIdOf(word: string, dataDir: string, port: number): Promise<string> {
- const response = await fetch(`http://127.0.0.1:${port}/api/machines`, {
+ const response = await daemonFetch(dataDir, port)(`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>[] }
@@ -130,7 +131,7 @@ export async function runAddonCommand(argv: string[], dataDir: string, port: num
const credential = readHookCredential(dataDir)
if (!credential) { print({ error: { code: 'DAEMON_UNAVAILABLE', message: 'Start Harness with harness start first.' } }); return 1 }
try {
- const result = await fetch(`http://127.0.0.1:${port}/api/autonomous-device/${path}`, {
+ const result = await daemonFetch(dataDir, port)(`http://127.0.0.1:${port}/api/autonomous-device/${path}`, {
method, redirect: 'error', signal: AbortSignal.timeout(15_000),
headers: { Authorization: `Bearer ${credential}`, ...(body ? { 'Content-Type': 'application/json' } : {}) },
...(body ? { body: JSON.stringify(body) } : {}),
diff --git a/cli/src/lib/autonomous-device/command.spec.ts b/cli/src/lib/autonomous-device/command.spec.ts
index 6d4421d6e..5a88dfc78 100644
--- a/cli/src/lib/autonomous-device/command.spec.ts
+++ b/cli/src/lib/autonomous-device/command.spec.ts
@@ -1,14 +1,16 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { Readable } from 'node:stream'
import { runAutonomousDeviceCommand } from './command.js'
+// Too long to hold a socket, so these calls reach the stubbed fetch rather than one.
+const UNUSED = `/unused-${'x'.repeat(100)}`
vi.mock('../hookAuth.js', () => ({ readHookCredential: () => 'hook-test-credential' }))
afterEach(() => vi.restoreAllMocks())
describe('Autonomous device pairing command direction', () => {
it('refuses the removed LAN listener and blanket revoke options', async () => {
const fetch = vi.spyOn(globalThis, 'fetch')
vi.spyOn(console, 'log').mockImplementation(() => {})
- expect(await runAutonomousDeviceCommand(['listen'], '/unused', 18473)).toBe(1)
- expect(await runAutonomousDeviceCommand(['revoke', '--all'], '/unused', 18473)).toBe(1)
+ expect(await runAutonomousDeviceCommand(['listen'], UNUSED, 18473)).toBe(1)
+ expect(await runAutonomousDeviceCommand(['revoke', '--all'], UNUSED, 18473)).toBe(1)
expect(fetch).not.toHaveBeenCalled()
})
it('takes the device code from stdin and binds it to the displayed pending intent', async () => {
@@ -16,14 +18,14 @@ describe('Autonomous device pairing command direction', () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
vi.spyOn(process, 'stdin', 'get').mockReturnValue(Readable.from(['K7P4X9\n']) as typeof process.stdin)
const device = 'os._autonomous._tcp.local'
- expect(await runAutonomousDeviceCommand(['pair', '--code-stdin', '--device', device], '/unused', 18473)).toBe(0)
+ expect(await runAutonomousDeviceCommand(['pair', '--code-stdin', '--device', device], UNUSED, 18473)).toBe(0)
expect(JSON.parse(String(fetch.mock.calls[0][1]?.body))).toEqual({ code: 'K7P4X9', device })
expect(log.mock.calls.flat().join()).not.toContain('K7P4X9')
})
it('refuses missing code or simultaneous positional and stdin sources', async () => {
const fetch = vi.spyOn(globalThis, 'fetch'), log = vi.spyOn(console, 'log').mockImplementation(() => {})
- expect(await runAutonomousDeviceCommand(['pair'], '/unused', 18473)).toBe(1)
- expect(await runAutonomousDeviceCommand(['pair', 'K7P4X9', '--code-stdin'], '/unused', 18473)).toBe(1)
+ expect(await runAutonomousDeviceCommand(['pair'], UNUSED, 18473)).toBe(1)
+ expect(await runAutonomousDeviceCommand(['pair', 'K7P4X9', '--code-stdin'], UNUSED, 18473)).toBe(1)
expect(fetch).not.toHaveBeenCalled()
expect(log.mock.calls.flat().join()).not.toContain('K7P4X9')
})
diff --git a/cli/src/lib/autonomous-device/command.ts b/cli/src/lib/autonomous-device/command.ts
index 48d365981..adb1c5a79 100644
--- a/cli/src/lib/autonomous-device/command.ts
+++ b/cli/src/lib/autonomous-device/command.ts
@@ -1,3 +1,4 @@
+import { daemonFetch } from '../localTransport.js'
import { readHookCredential } from '../hookAuth.js'
import { runAddonCommand } from './addonCommand.js'
@@ -36,7 +37,7 @@ export async function runAutonomousDeviceCommand(argv: string[], dataDir: string
try {
const body = verb === 'pair' ? { code: fromStdin ? await stdinCode() : args[1], ...(device ? { device } : {}) }
: verb === 'revoke' ? { id: args[1] } : {}
- const result = await fetch(`http://127.0.0.1:${port}/api/autonomous-device/${route}`, {
+ const result = await daemonFetch(dataDir, port)(`http://127.0.0.1:${port}/api/autonomous-device/${route}`, {
method: mutation ? 'POST' : 'GET', redirect: 'error', signal: AbortSignal.timeout(45_000),
headers: { Authorization: `Bearer ${credential}`, ...(mutation ? { 'Content-Type': 'application/json' } : {}) },
...(mutation ? { body: JSON.stringify(body) } : {}),
diff --git a/cli/src/lib/connectors/agents.ts b/cli/src/lib/connectors/agents.ts
index dd99e0f31..8239d1baf 100644
--- a/cli/src/lib/connectors/agents.ts
+++ b/cli/src/lib/connectors/agents.ts
@@ -14,10 +14,27 @@ import { delimiter, dirname, join } from 'node:path'
import { CODE, locked, writePrivate, type Store } from './store.js'
import { transport } from './rest.js'
-/** The bridge's fixed address, which every agent entry names. HARNESS_CONNECTIONS_PORT moves it (tests). */
-export function bridgePort(env: NodeJS.ProcessEnv = process.env): number {
- const port = Number(env.HARNESS_CONNECTIONS_PORT ?? 51793)
- return Number.isInteger(port) && port >= 0 && port < 65536 ? port : 51793
+const validPort = (port: unknown): port is number => typeof port === 'number' && Number.isInteger(port) && port >= 0 && port < 65536
+
+/**
+ * The bridge's address, which every agent entry names: 51793, or the port [vault] saved because another account held
+ * that one (saveBridgePort). HARNESS_CONNECTIONS_PORT fixes it (tests).
+ */
+export function bridgePort(env: NodeJS.ProcessEnv = process.env, vault?: Store): number {
+ if (env.HARNESS_CONNECTIONS_PORT !== undefined) {
+ const port = Number(env.HARNESS_CONNECTIONS_PORT)
+ return validPort(port) ? port : 51793
+ }
+ const saved = vault?.file('bridge.json').port
+ return validPort(saved) && saved > 0 ? saved : 51793
+}
+
+/**
+ * Remember the port the bridge moved to. A Team account's daemon starts at boot and this user's only at login, so that
+ * account can hold 51793 before this bridge ever starts (audit H1), and it then would hear every agent's tool calls.
+ */
+export function saveBridgePort(vault: Store, port: number): void {
+ locked(vault.root, () => { writePrivate(join(vault.root, 'bridge.json'), { ...vault.file('bridge.json'), port }) })
}
/** The capability in every bridge address, so only this user's agents can use it. */
@@ -26,7 +43,7 @@ export function bridgeKey(vault: Store): string {
const key = vault.file('bridge.json').key
if (typeof key === 'string' && key.length >= 32) return key
const fresh = randomBytes(32).toString('base64url')
- writePrivate(join(vault.root, 'bridge.json'), { key: fresh })
+ writePrivate(join(vault.root, 'bridge.json'), { ...vault.file('bridge.json'), key: fresh })
return fresh
})
}
@@ -156,7 +173,7 @@ export function agents(env: NodeJS.ProcessEnv = process.env): Agent[] {
export function sync(vault: Store, env: NodeJS.ProcessEnv = process.env, list: Agent[] = agents(env)): Record<string, string[]> {
const codes = Object.entries(vault.tokens()).filter(([code, token]) => transport(token) !== 'none' && CODE.test(code)).map(([code]) => code)
const key = codes.length ? bridgeKey(vault) : ''
- const wanted = Object.fromEntries(codes.map(code => [code, bridgeUrl(key, code, bridgePort(env))]))
+ const wanted = Object.fromEntries(codes.map(code => [code, bridgeUrl(key, code, bridgePort(env, vault))]))
return locked(vault.root, () => {
const record = vault.file('projections.json') as Record<string, unknown>
const changed: Record<string, string[]> = {}
diff --git a/cli/src/lib/connectors/bridge.ts b/cli/src/lib/connectors/bridge.ts
index 764cc8634..1f26a6e88 100644
--- a/cli/src/lib/connectors/bridge.ts
+++ b/cli/src/lib/connectors/bridge.ts
@@ -16,6 +16,7 @@ import { label } from './catalog.js'
import { bearer, needsRefresh, refreshable, type Store, type Token } from './store.js'
import { refresh } from './renew.js'
import { answer as answerRest, transport } from './rest.js'
+import { peerIsThisAccount, type PeerAccount } from '../peerAccount.js'
/** Headers an MCP client sends that the service must see. Authorization never comes from the agent. */
const FORWARD = ['accept', 'content-type', 'mcp-session-id', 'mcp-protocol-version', 'last-event-id']
@@ -50,6 +51,8 @@ export interface BridgeOptions {
/** Harness's own capability (agents.ts harnessKey), never in an agent's configuration: only it lists the
* connections or calls a key-only connection's API. Absent, those two addresses answer nothing. */
harnessKey?: () => string
+ /** Whether a caller runs as this OS account (lib/peerAccount.ts). A test's stand-in for another account. */
+ peerAccount?: PeerAccount
}
type Target = { kind: 'mcp'; code: string } | { kind: 'api'; code: string; path: string } | { kind: 'list' }
@@ -150,7 +153,12 @@ export function createBridge(vault: Store, options: BridgeOptions): Server {
fail(response, 403, 'Forbidden.'); return
}
const address = target(request.url ?? '/')
- if (!address) { fail(response, 404, 'Unknown connection address. Run harness connections sync.'); return }
+ // An MCP client can only speak HTTP to the address in its configuration, so it cannot check who holds this port,
+ // and another account that took it during a restart hears the key (audit H1). A key heard must open nothing. Answered
+ // as an unknown key is, so the answer does not say the key was right.
+ if (!address || !await (options.peerAccount ?? peerIsThisAccount)(request.socket)) {
+ fail(response, 404, 'Unknown connection address. Run harness connections sync.'); return
+ }
if (address.kind === 'list') { list(response); return }
const code = address.code
if (request.headers['transfer-encoding'] && !request.headers['content-length']) { fail(response, 411, 'Send the request with a Content-Length.'); return }
diff --git a/cli/src/lib/connectors/connectors.spec.ts b/cli/src/lib/connectors/connectors.spec.ts
index e9419625a..a69b2b089 100644
--- a/cli/src/lib/connectors/connectors.spec.ts
+++ b/cli/src/lib/connectors/connectors.spec.ts
@@ -5,6 +5,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync, chmodSync } from 'node:fs'
import { createServer, request as httpRequest } from 'node:http'
+import type { AddressInfo } from 'node:net'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { FakeGateway, FakeService } from '../../testing/connectorServers.js'
@@ -95,6 +96,25 @@ describe('signing in from this computer (MCP OAuth)', () => {
})
})
+describe('a bridge key another account heard', () => {
+ it('opens nothing: the same answer as an unknown key, and the service is never called', async () => {
+ const vault = new Store(mkdtempSync(join(tmpdir(), 'bridge-peer-')), {})
+ const key = bridgeKey(vault)
+ const asked: unknown[] = []
+ const bridge = createBridge(vault, { key: () => key, peerAccount: async (socket) => { asked.push(socket); return false } })
+ await new Promise<void>(resolve => { bridge.listen(0, '127.0.0.1', resolve) })
+ try {
+ const port = (bridge.address() as AddressInfo).port
+ const heard = await fetch(`http://127.0.0.1:${port}/${key}/linear/mcp`, { method: 'POST', body: '{}' })
+ const unknown = await fetch(`http://127.0.0.1:${port}/wrong/linear/mcp`, { method: 'POST', body: '{}' })
+ expect(heard.status).toBe(404)
+ expect(await heard.text()).toBe(await unknown.text())
+ // Only a request with the right key asks who is calling: a stranger cannot make the bridge run lsof.
+ expect(asked).toHaveLength(1)
+ } finally { bridge.closeAllConnections(); bridge.close(); rmSync(vault.root, { recursive: true, force: true }) }
+ })
+})
+
describe('the bridge', () => {
let fake: FakeService
let port: number
diff --git a/cli/src/lib/daemonEndpoint.spec.ts b/cli/src/lib/daemonEndpoint.spec.ts
index fc0193e52..261332902 100644
--- a/cli/src/lib/daemonEndpoint.spec.ts
+++ b/cli/src/lib/daemonEndpoint.spec.ts
@@ -1,5 +1,5 @@
import { createServer } from 'node:http'
-import { chmodSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
@@ -122,7 +122,9 @@ describe('per-user daemon discovery', () => {
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
cleanup.push(() => new Promise<void>((resolve) => { server.closeAllConnections(); server.close(() => resolve()) }))
const port = (server.address() as { port: number }).port
- const dataDir = directory()
+ // Too long to hold a socket: the one case where the credential goes to the port.
+ const dataDir = join(directory(), 'd'.repeat(100))
+ mkdirSync(dataDir, { mode: 0o700 })
const credential = loadOrCreateHookCredential(dataDir)
expect(await legacyDaemonStatus(port, 43210, 'this-user', dataDir)).toEqual(status)
expect(await legacyDaemonStatus(port, 43210, 'this-user')).toEqual(status)
diff --git a/cli/src/lib/daemonEndpoint.ts b/cli/src/lib/daemonEndpoint.ts
index 81d1a63f8..653841ba1 100644
--- a/cli/src/lib/daemonEndpoint.ts
+++ b/cli/src/lib/daemonEndpoint.ts
@@ -1,6 +1,7 @@
import { request } from 'node:http'
import { lstatSync } from 'node:fs'
import { localCredentialHeaders } from './localCredential.js'
+import { daemonFetch } from './localTransport.js'
import { localSocketPath } from './localSocket.js'
import { readDaemonRecord, writeDaemonRecord, type DaemonPipeRecord } from './daemonRecord.js'
import { daemonPipe, type LocalDaemonOptions } from './windows/daemonPipe.js'
@@ -72,8 +73,9 @@ const NULL_BODY = new Set([204, 205, 304])
/**
* A control call to the running daemon (cli.ts `daemonCall`: `harness pair`, `harness devices`, …). On Windows it
* goes over the daemon's pipe when there is one, and only an answer that proves the token is taken. It falls back
- * to loopback TCP, as on every other OS, when there is nothing to reach: no record, a daemon proven gone, or
- * nothing listening. A pipe that answers without the proof is not retried over TCP: whatever answered took the
+ * to loopback TCP when there is nothing to reach: no record, a daemon proven gone, or nothing listening. On macOS and
+ * Linux it goes over the daemon's private socket, and never the port while a socket can exist (lib/localTransport.ts).
+ * A pipe that answers without the proof is not retried over TCP: whatever answered took the
* daemon's name, and the caller is told so.
*/
export async function localDaemonCall(
@@ -95,9 +97,9 @@ export async function localDaemonCall(
}
}
}
- return (options.fetch ?? fetch)(`http://127.0.0.1:${options.tcpPort}${path}`, {
+ return (options.fetch ?? daemonFetch(dataDir, configuredPort, fetch, options.platform))(`http://127.0.0.1:${options.tcpPort}${path}`, {
method,
- headers: { ...headers, ...localCredentialHeaders(dataDir) },
+ headers: { ...headers, ...localCredentialHeaders(dataDir, options.platform) },
body: text,
})
}
diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.ts
index 6237b35d3..dd0100333 100644
--- a/cli/src/lib/discoveryScripts.spec.ts
+++ b/cli/src/lib/discoveryScripts.spec.ts
@@ -105,7 +105,7 @@ describe('generated discovery scripts', () => {
version.major = 2
vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)
vi.stubEnv('ADAPTER_DATA_DIR', data)
- writeFileSync(join(data, 'hook-credential'), 'tok-123\n')
+ writeFileSync(join(data, 'hook-token'), 'tok-123\n')
const { installOpencodePlugin } = await import('./hooks.js')
await installOpencodePlugin(18473)
diff --git a/cli/src/lib/hookAuth.ts b/cli/src/lib/hookAuth.ts
index ac0981953..344a74ed9 100644
--- a/cli/src/lib/hookAuth.ts
+++ b/cli/src/lib/hookAuth.ts
@@ -4,6 +4,12 @@ import { join } from 'node:path'
import { requireWindowsStateFile, secureStateDirectory, syncStateDirectory } from './secureState.js'
const FILE_NAME = 'hook-credential'
+/**
+ * What an engine's hook shows over TCP: it opens `/api/hook/*` and nothing else. A hook that can only post to a port
+ * hands its token to whoever holds that port (audit H1, docs/security/2026-11-02-team-account-boundary.md), so that
+ * token must not be the credential that drives the local API and its shell.
+ */
+const HOOK_TOKEN_FILE = 'hook-token'
const TOKEN_RE = /^[A-Za-z0-9_-]{43}$/
export function hookCredentialPath(dataDir: string): string {
@@ -19,11 +25,26 @@ function secureDataDirectory(dataDir: string): boolean {
}
}
+export function hookTokenPath(dataDir: string): string {
+ return join(dataDir, HOOK_TOKEN_FILE)
+}
+
export function readHookCredential(dataDir: string): string | null {
+ return readSecret(dataDir, hookCredentialPath(dataDir))
+}
+
+export function loadOrCreateHookCredential(dataDir: string): string {
+ return loadOrCreateSecret(dataDir, hookCredentialPath(dataDir))
+}
+
+export function loadOrCreateHookToken(dataDir: string): string {
+ return loadOrCreateSecret(dataDir, hookTokenPath(dataDir))
+}
+
+function readSecret(dataDir: string, file: string): string | null {
let fd: number | null = null
try {
if (!secureDataDirectory(dataDir)) return null
- const file = hookCredentialPath(dataDir)
// Windows: the file itself must be a real file in the profile (secureState.ts); its open follows links.
if (process.platform === 'win32') requireWindowsStateFile(file)
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
@@ -44,8 +65,8 @@ export function readHookCredential(dataDir: string): string | null {
}
}
-export function loadOrCreateHookCredential(dataDir: string): string {
- const existing = readHookCredential(dataDir)
+function loadOrCreateSecret(dataDir: string, file: string): string {
+ const existing = readSecret(dataDir, file)
if (existing) return existing
try {
secureStateDirectory(dataDir)
@@ -53,12 +74,11 @@ export function loadOrCreateHookCredential(dataDir: string): string {
throw new Error('hook credential directory has unsafe owner, mode, or type')
}
const value = randomBytes(32).toString('base64url')
- const file = hookCredentialPath(dataDir)
let fd: number
try {
fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)
} catch (error) {
- const raced = readHookCredential(dataDir)
+ const raced = readSecret(dataDir, file)
if (raced) return raced
throw error
}
diff --git a/cli/src/lib/localCredential.spec.ts b/cli/src/lib/localCredential.spec.ts
index 220fec407..4e0c710c4 100644
--- a/cli/src/lib/localCredential.spec.ts
+++ b/cli/src/lib/localCredential.spec.ts
@@ -18,12 +18,13 @@ describe('the daemon\'s local credential', () => {
const dir = dataDir()
const credential = loadOrCreateHookCredential(dir)
expect(readLocalCredential(dir)).toBe(credential)
- expect(localCredentialHeaders(dir)).toEqual({ [LOCAL_CREDENTIAL_HEADER]: credential })
+ // Windows, whose rules are its callers'. On macOS and Linux see team/localCredential.spec.ts.
+ expect(localCredentialHeaders(dir, 'win32')).toEqual({ [LOCAL_CREDENTIAL_HEADER]: credential })
})
it('adds no header when there is no credential to read, or one another user could have written', () => {
const dir = dataDir()
- expect(localCredentialHeaders(dir)).toEqual({})
+ expect(localCredentialHeaders(dir, 'win32')).toEqual({})
loadOrCreateHookCredential(dir)
chmodSync(hookCredentialPath(dir), 0o644)
expect(readLocalCredential(dir)).toBeNull()
diff --git a/cli/src/lib/localCredential.ts b/cli/src/lib/localCredential.ts
index 459e63775..df0beaa88 100644
--- a/cli/src/lib/localCredential.ts
+++ b/cli/src/lib/localCredential.ts
@@ -1,5 +1,6 @@
import type { IncomingMessage } from 'node:http'
import { hookCredentialMatches, readHookCredential } from './hookAuth.js'
+import { unixSocketPath } from './localSocket.js'
/**
* The daemon's local credential: what a process must show to use its loopback TCP API (REST and the
@@ -11,6 +12,10 @@ import { hookCredentialMatches, readHookCredential } from './hookAuth.js'
*
* Sent as `X-Harness-Local: <credential>`, or `Authorization: Bearer <credential>` for a client that
* can only set that one.
+ *
+ * Reaching a port proves nothing: another account can bind it while the daemon restarts, and would hear the credential
+ * (audit H1). So where the socket can exist, nothing here adds the credential to a TCP request, and clients use the
+ * socket (lib/localTransport.ts). The daemon also refuses it from another account (lib/peerAccount.ts), for old clients.
*/
export const LOCAL_CREDENTIAL_HEADER = 'X-Harness-Local'
@@ -22,8 +27,12 @@ export function readLocalCredential(dataDir: string): string | null {
return readHookCredential(dataDir)
}
-/** The headers a client adds to every loopback TCP request: none when it cannot read the credential. */
-export function localCredentialHeaders(dataDir: string): Record<string, string> {
+/**
+ * The headers a client adds to a loopback TCP request: none when it cannot read the credential, and none on macOS and
+ * Linux unless the data folder's path is too long to hold the socket, the one case with no way but TCP.
+ */
+export function localCredentialHeaders(dataDir: string, platform: NodeJS.Platform = process.platform): Record<string, string> {
+ if (platform !== 'win32' && unixSocketPath(dataDir, 65_535, platform)) return {}
const credential = readLocalCredential(dataDir)
return credential ? { [LOCAL_CREDENTIAL_HEADER]: credential } : {}
}
diff --git a/cli/src/lib/localSocket.ts b/cli/src/lib/localSocket.ts
index d4218a7bf..2ccb7c196 100644
--- a/cli/src/lib/localSocket.ts
+++ b/cli/src/lib/localSocket.ts
@@ -7,7 +7,9 @@
* user's processes can connect. A request that arrives over it is from this user, and needs none of
* the address checks a TCP request does — its peer has no address at all.
*
- * TCP stays: the CLI, engine hooks and scripts still use it, as do app builds that predate this. On Windows the
+ * TCP stays for what cannot use this (MCP clients, engine plugins, Store agents, old app builds) and for a data folder
+ * too long for a socket. The CLI, engine hooks and the app use only this socket while it can exist: any account can
+ * bind the port once it is free (audit H1, lib/localTransport.ts). On Windows the
* daemon serves a named pipe instead (`listenAuthenticated` below). Reaching that pipe is no credential, so every
* request over it proves the daemon's token (lib/windows/pipeAuth.ts).
*/
diff --git a/cli/src/lib/localTransport.ts b/cli/src/lib/localTransport.ts
new file mode 100644
index 000000000..585788088
--- /dev/null
+++ b/cli/src/lib/localTransport.ts
@@ -0,0 +1,83 @@
+/**
+ * How a client on this computer reaches the daemon. On macOS and Linux that is the daemon's Unix socket, 0600 in a 0700
+ * folder, and only that: any account can bind the TCP port while the daemon restarts (a Team agent, audit H1), and would
+ * hear what is sent to it, which is the local credential and also the request itself: a message, a file. With the
+ * socket gone the daemon is down, and the client says so. TCP remains where a socket cannot exist, a data folder whose
+ * path is too long for one, and on Windows, whose own proven pipe is handled by its callers.
+ *
+ * The folder's mode is the guarantee here, as for every client of this socket (lib/localSocket.ts): nobody else can
+ * have put a socket in it.
+ */
+import { existsSync, readdirSync } from 'node:fs'
+import { request } from 'node:http'
+import { join } from 'node:path'
+import { Readable } from 'node:stream'
+import type { ReadableStream as NodeReadableStream } from 'node:stream/web'
+import { readDaemonRecord } from './daemonRecord.js'
+import { localCredentialHeaders } from './localCredential.js'
+import { localSocketName, unixSocketPath } from './localSocket.js'
+
+const LOCAL_WS_PATH = '/api/local-ws'
+
+/**
+ * The daemon's socket for [port], or null where it has none. A socket is named for the port the daemon was configured
+ * with; [port] may be the one it was given instead, when another account held that one, so its records say which.
+ * With neither there, the expected path: connecting to it fails as a daemon that is down does.
+ */
+export function localSocketRoute(dataDir: string, port: number, platform: NodeJS.Platform = process.platform): string | null {
+ const expected = unixSocketPath(dataDir, port, platform)
+ if (!expected || existsSync(expected)) return expected
+ let names: string[] = []
+ try { names = readdirSync(dataDir) } catch { return expected }
+ for (const name of names) {
+ const configured = /^daemon-(\d+)\.json$/.exec(name)?.[1]
+ if (!configured || readDaemonRecord(dataDir, Number(configured), platform)?.port !== port) continue
+ const socket = join(dataDir, localSocketName(Number(configured)))
+ if (existsSync(socket)) return socket
+ }
+ return expected
+}
+
+/** Where a WebSocket to the daemon goes, and the headers it carries: none over the socket. */
+export function localWsTarget(dataDir: string, port: number, platform: NodeJS.Platform = process.platform): { url: string; headers: Record<string, string> } {
+ const socket = localSocketRoute(dataDir, port, platform)
+ if (socket) return { url: `ws+unix://${socket}:${LOCAL_WS_PATH}`, headers: {} }
+ return { url: `ws://127.0.0.1:${readDaemonRecord(dataDir, port, platform)?.port ?? port}${LOCAL_WS_PATH}`, headers: localCredentialHeaders(dataDir, platform) }
+}
+
+/** One request over the socket, answered as `fetch` answers. The body is whole first: these are JSON and forms up to 10 MB. */
+async function overSocket(socketPath: string, input: Request): Promise<Response> {
+ const url = new URL(input.url)
+ const body = input.body ? Buffer.from(await input.arrayBuffer()) : null
+ const headers = Object.fromEntries(input.headers)
+ if (body) headers['content-length'] = String(body.length)
+ return new Promise((resolve, reject) => {
+ const req = request({ socketPath, method: input.method, path: `${url.pathname}${url.search}`, headers, signal: input.signal }, (res) => {
+ const answer = new Headers()
+ for (const [name, value] of Object.entries(res.headers)) {
+ if (value !== undefined) answer.set(name, Array.isArray(value) ? value.join(', ') : value)
+ }
+ const status = res.statusCode ?? 502
+ // A Response may have no body with these (and refuses one).
+ if ([101, 204, 205, 304].includes(status)) { res.resume(); resolve(new Response(null, { status, headers: answer })); return }
+ resolve(new Response(Readable.toWeb(res) as NodeReadableStream as ReadableStream, { status, headers: answer }))
+ })
+ // As fetch fails: a TypeError with the reason as its cause, which the callers' "is it running" texts read.
+ req.on('error', (error) => { reject(input.signal.aborted ? error : Object.assign(new TypeError('fetch failed'), { cause: error })) })
+ req.end(body ?? undefined)
+ })
+}
+
+/**
+ * `fetch` for the daemon on [port] of [dataDir]: a request to its loopback address goes over its socket where it can
+ * have one. Any other address, such as a storage link, is the ordinary [base].
+ */
+export function daemonFetch(dataDir: string, port: number, base: typeof fetch = fetch, platform: NodeJS.Platform = process.platform): typeof fetch {
+ return (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : String(input))
+ const saved = readDaemonRecord(dataDir, port, platform)?.port
+ const daemon = url.hostname === '127.0.0.1' && (Number(url.port) === port || Number(url.port) === saved)
+ const socket = daemon ? localSocketRoute(dataDir, port, platform) : null
+ return socket ? overSocket(socket, new Request(input, init)) : base(input, init)
+ }
+}
diff --git a/cli/src/lib/newCommand.ts b/cli/src/lib/newCommand.ts
index 120a3f384..8ccb12544 100644
--- a/cli/src/lib/newCommand.ts
+++ b/cli/src/lib/newCommand.ts
@@ -1,4 +1,6 @@
import { randomUUID } from 'node:crypto'
+import { env } from '../config/env.js'
+import { localWsTarget } from './localTransport.js'
import { readdir, readFile, realpath } from 'node:fs/promises'
import { dirname, isAbsolute, join, posix, resolve, win32 } from 'node:path'
import { addressOf, atMachineRefusal, EXIT, machineOption, refusalNext, REFUSED_CODES, step, VIA_MCP_ENV } from '../agentClient/commands.js'
@@ -483,7 +485,7 @@ export function daemonSession(deps: Pick<NewCommandDeps, 'port' | 'connect' | 't
close: () => void
}> {
return new Promise((resolveSession, rejectSession) => {
- const socket = deps.connect(`ws://127.0.0.1:${deps.port}/api/local-ws`)
+ const socket = deps.connect(localWsTarget(env.ADAPTER_DATA_DIR, deps.port).url)
const waiting = new Map<string, { done: (payload: Record<string, unknown>) => void; fail: (error: Error) => void; timer: NodeJS.Timeout }>()
let ready = false
const failAll = (error: Error): void => {
diff --git a/cli/src/lib/peerAccount.spec.ts b/cli/src/lib/peerAccount.spec.ts
new file mode 100644
index 000000000..c31df5521
--- /dev/null
+++ b/cli/src/lib/peerAccount.spec.ts
@@ -0,0 +1,93 @@
+import { createServer, connect, type AddressInfo, type Socket } from 'node:net'
+import { afterEach, describe, expect, it } from 'vitest'
+import { lsofShowsPeer, peerIsThisAccount, portHolderIsThisAccount, procNetListener, procNetOwner } from './peerAccount.js'
+
+describe('who is at the other end of a loopback connection', () => {
+ const opened: Array<() => unknown> = []
+ afterEach(() => { for (const close of opened.splice(0)) close() })
+
+ const pair = async (): Promise<Socket> => {
+ const server = createServer()
+ opened.push(() => server.close())
+ await new Promise<void>(resolve => { server.listen(0, '127.0.0.1', resolve) })
+ const accepted = new Promise<Socket>(resolve => { server.once('connection', resolve) })
+ const client = connect((server.address() as AddressInfo).port, '127.0.0.1')
+ opened.push(() => client.destroy())
+ const socket = await accepted
+ opened.push(() => socket.destroy())
+ return socket
+ }
+
+ it('says yes for a process of this account, by the real lookup', async () => {
+ expect(await peerIsThisAccount(await pair())).toBe(true)
+ })
+
+ it('says no once the caller has gone', async () => {
+ const socket = await pair()
+ const gone = { localAddress: '127.0.0.1', remoteAddress: '127.0.0.1', localPort: socket.localPort, remotePort: 1 } as unknown as Socket
+ expect(await peerIsThisAccount(gone)).toBe(false)
+ })
+
+ it('says no for a socket with no peer port', async () => {
+ expect(await peerIsThisAccount({} as unknown as Socket)).toBe(false)
+ })
+
+ it('says no for a caller on another loopback address, even with the ports of a connection of this account', async () => {
+ const socket = await pair()
+ const other = { remoteAddress: '127.0.0.2', localAddress: socket.localAddress, remotePort: socket.remotePort, localPort: socket.localPort } as unknown as Socket
+ expect(await peerIsThisAccount(other)).toBe(false)
+ expect(await peerIsThisAccount({ ...other, remoteAddress: '127.0.0.1', localAddress: '127.0.0.3' } as unknown as Socket)).toBe(false)
+ // The very same ports, from 127.0.0.1: the real connection of this account.
+ expect(await peerIsThisAccount(socket)).toBe(true)
+ })
+
+ it('asks once per connection', async () => {
+ const socket = await pair()
+ expect(peerIsThisAccount(socket)).toBe(peerIsThisAccount(socket))
+ })
+
+ it('leaves Windows to its proven pipe', async () => {
+ expect(await peerIsThisAccount({} as unknown as Socket, 'win32')).toBe(true)
+ })
+
+ it('reads the owner of the client end from /proc/net/tcp, not the server end', () => {
+ const table = [
+ ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode',
+ ' 0: 0100007F:4849 0100007F:C000 01 00000000:00000000 00:00000000 00000000 501 0 1',
+ ' 1: 0100007F:C000 0100007F:4849 01 00000000:00000000 00:00000000 00000000 1002 0 2',
+ ].join('\n')
+ expect(procNetOwner(table, 0xC000, 0x4849)).toBe(1002)
+ expect(procNetOwner(table, 0xC001, 0x4849)).toBeNull()
+ // The same ports on another address are another connection.
+ expect(procNetOwner(table.replace('0100007F:C000 0100007F:4849', '0200007F:C000 0100007F:4849'), 0xC000, 0x4849)).toBeNull()
+ })
+
+ it('reads the owner of a listener, by real lookup and from /proc/net/tcp', async () => {
+ const server = createServer()
+ opened.push(() => server.close())
+ await new Promise<void>(resolve => { server.listen(0, '127.0.0.1', resolve) })
+ expect(await portHolderIsThisAccount((server.address() as AddressInfo).port)).toBe(true)
+ expect(await portHolderIsThisAccount(1, 'win32')).toBeNull()
+ const table = [
+ ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode',
+ ' 0: 0100007F:C94F 00000000:0000 0A 00000000:00000000 00:00000000 00000000 1002 0 1',
+ ' 1: 0100007F:C950 0100007F:0050 01 00000000:00000000 00:00000000 00000000 501 0 2',
+ ].join('\n')
+ expect(procNetListener(table, 0xC94F)).toBe(1002)
+ expect(procNetListener(table, 0xC950)).toBeNull()
+ // Node's plain listen(port) is on `::`, dual-stack: it blocks 127.0.0.1 and shows only in /proc/net/tcp6.
+ const row = (address: string) => ` 0: ${address}:C94F 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 1003 0 3`
+ for (const address of ['00000000000000000000000000000000', '00000000000000000000000001000000', '0000000000000000FFFF00000100007F', '0000000000000000FFFF000000000000']) {
+ expect(procNetListener(`header\n${row(address)}`, 0xC94F), address).toBe(1003)
+ }
+ // Another address's listener does not hold 127.0.0.1's port.
+ expect(procNetListener(`header\n${row('0000000000000000FFFF00000200007F')}`, 0xC94F)).toBeNull()
+ })
+
+ it('counts only the client end in lsof output: the server end shows the same ports reversed', () => {
+ expect(lsofShowsPeer('p1\nf3\nn127.0.0.1:50000->127.0.0.1:18473\n', 50000, 18473)).toBe(true)
+ // What a daemon sees of its own accepted socket when the caller is another account.
+ expect(lsofShowsPeer('p1\nf3\nn127.0.0.1:18473->127.0.0.1:50000\n', 50000, 18473)).toBe(false)
+ expect(lsofShowsPeer('', 50000, 18473)).toBe(false)
+ })
+})
diff --git a/cli/src/lib/peerAccount.ts b/cli/src/lib/peerAccount.ts
new file mode 100644
index 000000000..fdaececd7
--- /dev/null
+++ b/cli/src/lib/peerAccount.ts
@@ -0,0 +1,122 @@
+/**
+ * Whether the process at the other end of a loopback TCP connection runs as this OS account.
+ *
+ * Any account can bind a free loopback port, so while the daemon or the bridge restarts another account (a Team
+ * agent) can sit on its port and hear what clients send (audit H1, docs/security/2026-11-02-team-account-boundary.md).
+ * A client that can only speak HTTP to a fixed address cannot avoid that: an MCP client's address carries its key, and
+ * older clients send the local credential. So a secret heard must open nothing: the listeners also ask who is calling.
+ *
+ * Asked only after the secret matched, so a stranger cannot make the daemon spawn anything, and once per connection.
+ * A lookup that fails answers no: this guards a credential, and a client refused can say so and retry.
+ */
+import { execFile } from 'node:child_process'
+import { readFile } from 'node:fs/promises'
+import type { Socket } from 'node:net'
+
+export type PeerAccount = (socket: Socket) => Promise<boolean>
+
+const LSOF_MS = 3_000
+
+/** Linux: the row of /proc/net/tcp whose local end is the peer's and whose remote end is ours, and that row's uid. */
+export function procNetOwner(table: string, peerPort: number, ownPort: number): number | null {
+ const hex = (port: number) => port.toString(16).toUpperCase().padStart(4, '0')
+ for (const line of table.split('\n').slice(1)) {
+ const fields = line.trim().split(/\s+/)
+ if (fields[1] === `0100007F:${hex(peerPort)}` && fields[2] === `0100007F:${hex(ownPort)}`) {
+ const uid = Number(fields[7])
+ return Number.isInteger(uid) ? uid : null
+ }
+ }
+ return null
+}
+
+/**
+ * macOS: whether `lsof -Fn` shows the client's end of the connection among this account's sockets. The daemon's own
+ * end names the same two ports the other way round (`own->peer`), so only a line starting at the peer's port counts.
+ */
+export function lsofShowsPeer(output: string, peerPort: number, ownPort: number): boolean {
+ return output.split('\n').some(line => /^n127\.0\.0\.1:(\d+)->127\.0\.0\.1:(\d+)$/.exec(line)?.slice(1).join() === `${peerPort},${ownPort}`)
+}
+
+function lsof(peerPort: number, ownPort: number, uid: number): Promise<boolean> {
+ return new Promise((resolve) => {
+ execFile('/usr/sbin/lsof', ['-nP', '-a', '-u', String(uid), `[email protected]:${peerPort}`, '-Fn'], { timeout: LSOF_MS }, (error, stdout) => {
+ // lsof exits 1 when it found nothing: that is an answer, and its empty output says no.
+ if (error && typeof error.code !== 'number') console.warn(`[peer] could not ask lsof who is calling: ${error.message}`)
+ resolve(lsofShowsPeer(stdout ?? '', peerPort, ownPort))
+ })
+ })
+}
+
+async function ask(socket: Socket, platform: NodeJS.Platform): Promise<boolean> {
+ const peerPort = socket.remotePort, ownPort = socket.localPort
+ const uid = process.getuid?.()
+ if (uid === undefined || !peerPort || !ownPort) return false
+ // Both lookups below name 127.0.0.1 at both ends, which is what a client dialling this listener uses. All of 127/8 is
+ // loopback, so another account can call from 127.0.0.2 on the same port number as a connection of this account's, and
+ // would be read as that connection. Only an exact pair of addresses makes the pair of ports name one connection.
+ if (socket.remoteAddress !== '127.0.0.1' || socket.localAddress !== '127.0.0.1') return false
+ if (platform === 'linux') {
+ try { return procNetOwner(await readFile('/proc/net/tcp', 'utf8'), peerPort, ownPort) === uid } catch { return false }
+ }
+ return lsof(peerPort, ownPort, uid)
+}
+
+/**
+ * The addresses of a listener that keeps 127.0.0.1's port from being bound: 127.0.0.1 and any address, and for IPv6 the
+ * same mapped, `::` and `::1`. Node's plain `listen(port)` is on `::`, dual-stack, and shows only in /proc/net/tcp6.
+ */
+const LISTENER_ADDRESSES = ['0100007F', '00000000', '00000000000000000000000000000000', '00000000000000000000000001000000',
+ '0000000000000000FFFF00000100007F', '0000000000000000FFFF000000000000']
+
+/** Linux: the owner of the listener on loopback [port] in /proc/net/tcp and tcp6's text, or null when none is listening. */
+export function procNetListener(table: string, port: number): number | null {
+ const hex = port.toString(16).toUpperCase().padStart(4, '0')
+ const holds = new Set(LISTENER_ADDRESSES.map(address => `${address}:${hex}`))
+ for (const line of table.split('\n')) {
+ const fields = line.trim().split(/\s+/)
+ if (fields[3] === '0A' && holds.has(fields[1] ?? '')) {
+ const uid = Number(fields[7])
+ return Number.isInteger(uid) ? uid : null
+ }
+ }
+ return null
+}
+
+/**
+ * Whether the process listening on loopback [port] runs as this account: null when that cannot be said (a listener gone
+ * by now, a lookup that failed, Windows). macOS shows an account only its own sockets, so a port that is taken but not
+ * among them is another account's.
+ */
+export async function portHolderIsThisAccount(port: number, platform: NodeJS.Platform = process.platform): Promise<boolean | null> {
+ const uid = process.getuid?.()
+ if (platform === 'win32' || uid === undefined) return null
+ if (platform === 'linux') {
+ // A kernel with no IPv6 has no tcp6, and /proc/net/tcp alone says who holds the port then.
+ const tables = await Promise.all(['/proc/net/tcp', '/proc/net/tcp6'].map(file => readFile(file, 'utf8').catch(() => '')))
+ const owner = procNetListener(tables.join('\n'), port)
+ return owner === null ? null : owner === uid
+ }
+ return new Promise((resolve) => {
+ execFile('/usr/sbin/lsof', ['-nP', '-a', '-u', String(uid), `-iTCP:${port}`, '-sTCP:LISTEN', '-Fn'], { timeout: LSOF_MS }, (error, stdout) => {
+ if (error && typeof error.code !== 'number') { resolve(null); return }
+ resolve(/^n/m.test(stdout ?? ''))
+ })
+ })
+}
+
+const answers = new WeakMap<Socket, Promise<boolean>>()
+
+/** Windows reaches the daemon over its proven pipe and has neither lookup: its TCP rules are unchanged. */
+export function peerIsThisAccount(socket: Socket, platform: NodeJS.Platform = process.platform): Promise<boolean> {
+ if (platform === 'win32') return Promise.resolve(true)
+ let answer = answers.get(socket)
+ if (!answer) {
+ answer = ask(socket, platform).then((yes) => {
+ if (!yes) console.warn(`[peer] refused a valid secret on 127.0.0.1:${socket.localPort}: the caller is not this account`)
+ return yes
+ })
+ answers.set(socket, answer)
+ }
+ return answer
+}
diff --git a/cli/src/lib/registry.admission.spec.ts b/cli/src/lib/registry.admission.spec.ts
index 2c8e917a3..3f86c2f66 100644
--- a/cli/src/lib/registry.admission.spec.ts
+++ b/cli/src/lib/registry.admission.spec.ts
@@ -381,7 +381,8 @@ async function httpFixture(blocked: (agentId: string) => boolean = () => false,
onPromptSubmitted: (_id, text) => prompts.push(text),
onAdmissionHeld: (_id, reason) => reasons.push(reason),
...overrides,
- }, { admissionReceiptCapacity, admissionBytesCapacity })
+ // The order of concurrent retries is what this file pins; each real lookup of who is calling takes its own time.
+ }, { admissionReceiptCapacity, admissionBytesCapacity, peerAccount: async () => true })
server = started.server
const post = async (override: Record<string, unknown> = {}, order: { id?: string; firedAt?: number } = {}, path = 'session-start') => {
const response = await fetch(`http://127.0.0.1:${started.port}/api/hook/${path}`, {
diff --git a/cli/src/localWsServer.spec.ts b/cli/src/localWsServer.spec.ts
index 2b900bddb..7ad4f7553 100644
--- a/cli/src/localWsServer.spec.ts
+++ b/cli/src/localWsServer.spec.ts
@@ -1,3 +1,4 @@
+import type { Socket } from 'node:net'
import http from 'node:http'
import net, { type AddressInfo } from 'node:net'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -222,6 +223,30 @@ describe('local CLI WebSocket', () => {
}
})
+ // Audit H1: another account may have heard it while it held this port during a restart.
+ it('refuses a TCP upgrade with the right credential from another account', async () => {
+ const credential = 'c'.repeat(43)
+ const url = await start(new FakeBackend(), { localCredential: credential, peerAccount: async () => false })
+ const ws = new WebSocket(url, { headers: { 'x-harness-local': credential } })
+ expect(await new Promise<number>((resolve) => ws.once('unexpected-response', (_req, res) => resolve(res.statusCode ?? 0)))).toBe(401)
+ })
+
+ it('survives a client that resets while the lookup of who it is runs', async () => {
+ const credential = 'c'.repeat(43)
+ let release: (mine: boolean) => void = () => {}
+ let held: Socket | undefined
+ const url = await start(new FakeBackend(), { localCredential: credential, peerAccount: (socket) => { held = socket; return new Promise((resolve) => { release = resolve }) } })
+ const ws = new WebSocket(url, { headers: { 'x-harness-local': credential } })
+ ws.on('error', () => {})
+ for (let n = 0; n < 200 && !held; n++) await new Promise(resolve => setTimeout(resolve, 5))
+ expect(held!.listenerCount('error')).toBeGreaterThan(0)
+ held!.emit('error', new Error('read ECONNRESET'))
+ held!.destroy()
+ release(true)
+ await new Promise(resolve => setTimeout(resolve, 20))
+ expect(ws.readyState).not.toBe(WebSocket.OPEN)
+ })
+
it('takes an upgrade over the daemon\'s socket with no credential, the TCP port still wanting one', async () => {
const dir = mkdtempSync('/tmp/lws-cred-')
const socketPath = join(dir, 'daemon.sock')
diff --git a/cli/src/localWsServer.ts b/cli/src/localWsServer.ts
index 06e940eef..2ca9183c9 100644
--- a/cli/src/localWsServer.ts
+++ b/cli/src/localWsServer.ts
@@ -9,6 +9,7 @@ import { isLoopbackRequest, loopbackHosts } from './lib/loopbackRequest.js'
import { isTrustedLocal, pipeProofOf } from './lib/localSocket.js'
import { PIPE_PROOF_HEADER } from './lib/windows/pipeAuth.js'
import { localCredentialMatches } from './lib/localCredential.js'
+import { peerIsThisAccount, type PeerAccount } from './lib/peerAccount.js'
import type { Frame, LocalClientSink } from './backendSocket.js'
import {
decodeTerminalLocal,
@@ -56,6 +57,8 @@ export interface LocalWsServerOptions {
/** The daemon's local credential (lib/localCredential.ts). Given, a TCP upgrade must carry it: the
* loopback port takes any local OS user's process, the Unix socket only this user's. */
localCredential?: string
+ /** Whether a TCP caller runs as this OS account (lib/peerAccount.ts). A test's stand-in for another account. */
+ peerAccount?: PeerAccount
/** Serves a `machine_select` for any OTHER machine this signed-in user owns, by relaying to
* backend's `/api/web-ws` — see lib/remoteRelay.ts — and one for a harness shared with this account
* (`shareId`, sharing/relay.ts). Both are the gateway's. Omit to keep today's own-machine-only behavior. */
@@ -355,7 +358,20 @@ export function attachLocalWsServer(server: http.Server, options: LocalWsServerO
rejectUpgrade(socket, 401, 'Unauthorized')
return
}
- wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req))
+ if (options.localCredential === undefined) {
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req))
+ return
+ }
+ // A credential another account heard while it held this port during a restart (audit H1) must open nothing.
+ // Nothing else listens on this socket until the upgrade: a client's reset while the lookup runs would be uncaught.
+ const ignoreReset = (): void => {}
+ socket.on('error', ignoreReset)
+ void (options.peerAccount ?? peerIsThisAccount)(req.socket).then((mine) => {
+ socket.off('error', ignoreReset)
+ if (socket.destroyed) return
+ if (!mine) { rejectUpgrade(socket, 401, 'Unauthorized'); return }
+ wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req))
+ }, () => { socket.off('error', ignoreReset); rejectUpgrade(socket, 401, 'Unauthorized') })
}
const servers = [server, ...(options.localSocketServer ? [options.localSocketServer] : [])]
for (const each of servers) each.on('upgrade', onUpgrade)
diff --git a/cli/src/messages/rpc.ts b/cli/src/messages/rpc.ts
index 9ceb16cb5..b4b957bc4 100644
--- a/cli/src/messages/rpc.ts
+++ b/cli/src/messages/rpc.ts
@@ -5,10 +5,8 @@
*/
import { randomBytes } from 'node:crypto'
import { env } from '../config/env.js'
-import { localCredentialHeaders } from '../lib/localCredential.js'
-import { existsSync } from 'node:fs'
import { WebSocket } from 'ws'
-import { unixSocketPath } from '../lib/localSocket.js'
+import { localWsTarget } from '../lib/localTransport.js'
import { daemonPipe, type LocalDaemonOptions } from '../lib/windows/daemonPipe.js'
import { pipeWebSocket } from '../lib/windows/pipeClient.js'
import { NOT_RUNNING, pidIn, unreachableText } from '../lib/unreachable.js'
@@ -23,19 +21,17 @@ export interface RpcTarget { port: number; machineId: string; dataDir?: string;
export type Rpc = (target: RpcTarget, payload: Record<string, unknown>, timeoutMs?: number) => Promise<Record<string, unknown>>
/**
- * The Unix socket on macOS/Linux, with the loopback port and the local credential as its legacy fallback. On Windows
- * only the daemon's proven pipe (agentClient/daemon.ts `connectSocket` does the same): the configured port may be
- * another OS user's daemon on a shared PC, and this user's credential must never reach it.
+ * The Unix socket on macOS/Linux; on Windows the daemon's proven pipe (agentClient/daemon.ts `connectSocket` does the
+ * same). Never the port when those are gone: it may be another OS user's, and this user's credential and messages must
+ * never reach it (lib/localTransport.ts).
*/
export function createMessagesRpc(options: LocalDaemonOptions = {}): Rpc {
const windows = (options.platform ?? process.platform) === 'win32'
return (target, payload, timeoutMs = 20_000) => new Promise((resolve, reject) => {
let ws: WebSocket | null = null
if (!windows) {
- const socketPath = target.dataDir ? unixSocketPath(target.dataDir, target.port) : null
- ws = socketPath && existsSync(socketPath)
- ? new WebSocket(`ws+unix://${socketPath}:/api/local-ws`)
- : new WebSocket(`ws://127.0.0.1:${target.port}/api/local-ws`, { headers: localCredentialHeaders(target.dataDir ?? env.ADAPTER_DATA_DIR) })
+ const line = localWsTarget(target.dataDir ?? env.ADAPTER_DATA_DIR, target.port)
+ ws = new WebSocket(line.url, { headers: line.headers })
}
const requestId = randomBytes(16).toString('hex')
let finished = false, selected = false
diff --git a/cli/src/orchestrator/command.spec.ts b/cli/src/orchestrator/command.spec.ts
index b3fa4019b..6e7708ab1 100644
--- a/cli/src/orchestrator/command.spec.ts
+++ b/cli/src/orchestrator/command.spec.ts
@@ -1,4 +1,5 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { env } from '../config/env.js'
import { WebSocketServer } from 'ws'
import * as authSession from '../lib/authSession.js'
import { summarizeOrchestratorReply, parseOrchestratorArgs, localOrchestratorRequest, orchestratorCommand } from './command.js'
@@ -69,7 +70,11 @@ describe('orchestrator argument validation', () => {
describe('real loopback orchestrator transport', () => {
const servers: WebSocketServer[] = []
+ const savedDataDir = env.ADAPTER_DATA_DIR
+ // Too long to hold a socket: the case where this asks the fake daemon's port.
+ beforeEach(() => { env.ADAPTER_DATA_DIR = `/unused-${'x'.repeat(100)}` })
afterEach(async () => {
+ env.ADAPTER_DATA_DIR = savedDataDir
vi.restoreAllMocks()
await Promise.all(servers.splice(0).map(server => new Promise<void>(resolve => { for (const client of server.clients) client.terminate(); server.close(() => resolve()) })))
})
diff --git a/cli/src/orchestrator/command.ts b/cli/src/orchestrator/command.ts
index eb34fe486..e6912c708 100644
--- a/cli/src/orchestrator/command.ts
+++ b/cli/src/orchestrator/command.ts
@@ -1,5 +1,5 @@
import { randomBytes } from 'node:crypto'
-import { localCredentialHeaders } from '../lib/localCredential.js'
+import { localWsTarget } from '../lib/localTransport.js'
import { WebSocket } from 'ws'
import { env } from '../config/env.js'
import { readAuthSession } from '../lib/authSession.js'
@@ -7,7 +7,8 @@ import { readAuthSession } from '../lib/authSession.js'
export function localOrchestratorRequest(port: number, machineId: string, payload: Record<string, unknown>, timeoutMs = 30_000): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
const requestId = randomBytes(16).toString('hex')
- const ws = new WebSocket(`ws://127.0.0.1:${port}/api/local-ws`, { headers: localCredentialHeaders(env.ADAPTER_DATA_DIR) })
+ const line = localWsTarget(env.ADAPTER_DATA_DIR, port)
+ const ws = new WebSocket(line.url, { headers: line.headers })
let settled = false
const finish = (error?: Error, reply?: Record<string, unknown>): void => {
if (settled) return
diff --git a/cli/src/remoteCommand.spec.ts b/cli/src/remoteCommand.spec.ts
index 1906a9b84..83d207765 100644
--- a/cli/src/remoteCommand.spec.ts
+++ b/cli/src/remoteCommand.spec.ts
@@ -6,6 +6,7 @@ import { describe, expect, it, vi } from 'vitest'
import {
LoopbackClient, LoopbackError, handoffTerminal, openRemoteTerminal, orderForPicker, pickMachine, remoteCommand, remoteFailureLine,
type LoopbackSocket, type RemoteCommandDeps, type RemoteMachineChoice,
+ loopbackUrl,
} from './remoteCommand.js'
const machines: RemoteMachineChoice[] = [
@@ -36,7 +37,7 @@ class FakeDaemon {
readonly sent: Array<{ type: string; payload: Record<string, unknown> }> = []
constructor(private readonly answer: (socket: FakeSocket, frame: { type: string; payload: Record<string, unknown> }) => void) {}
connect = (url: string): LoopbackSocket => {
- expect(url).toBe('ws://127.0.0.1:18473/api/local-ws')
+ expect(url).toMatch(/^ws\+unix:\/\/.*\/daemon-18473\.sock:\/api\/local-ws$/)
const socket = new FakeSocket((frame) => { this.sent.push(frame); this.answer(socket, frame) })
setTimeout(() => socket.emit('open'), 0)
return socket
@@ -170,7 +171,7 @@ describe('the loopback calls', () => {
it('a daemon that never answers is a TIMEOUT, not a hang', async () => {
const silent = new FakeDaemon(() => {})
- const client = new LoopbackClient('ws://127.0.0.1:18473/api/local-ws', silent.connect)
+ const client = new LoopbackClient(loopbackUrl(18473), silent.connect)
await expect(client.select('box-1', 30)).rejects.toMatchObject({ code: 'TIMEOUT' })
client.close()
})
diff --git a/cli/src/remoteCommand.ts b/cli/src/remoteCommand.ts
index a725836a2..bd7f25202 100644
--- a/cli/src/remoteCommand.ts
+++ b/cli/src/remoteCommand.ts
@@ -15,6 +15,7 @@
*/
import { randomUUID } from 'node:crypto'
import { localCredentialHeaders } from './lib/localCredential.js'
+import { localWsTarget } from './lib/localTransport.js'
import { env } from './config/env.js'
import { emitKeypressEvents } from 'node:readline'
import { WebSocket } from 'ws'
@@ -225,8 +226,9 @@ export class LoopbackClient {
}
}
-export function loopbackUrl(port: number): string {
- return `ws://127.0.0.1:${port}/api/local-ws`
+/** The daemon's private socket where it can have one: never a port another account may hold (lib/localTransport.ts). */
+export function loopbackUrl(port: number, dataDir: string = env.ADAPTER_DATA_DIR): string {
+ return localWsTarget(dataDir, port).url
}
/** A `terminal` agent on [machineId], created the way the desktop's ⌘⇧T creates one: at home. */
diff --git a/cli/src/services/connectors.spec.ts b/cli/src/services/connectors.spec.ts
index ad77b67ee..2beeae8ff 100644
--- a/cli/src/services/connectors.spec.ts
+++ b/cli/src/services/connectors.spec.ts
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { bridgePort, saveBridgePort } from '../lib/connectors/agents.js'
import { mkdtempSync, rmSync } from 'node:fs'
import { createServer } from 'node:net'
import { tmpdir } from 'node:os'
@@ -130,6 +131,112 @@ describe('the connectors service', () => {
expect(await requests.connectors!({ action: 'list' }, OWNER)).toEqual({ error: 'CONNECTORS_FAILED', detail: 'Connections are unavailable. Try again.' })
})
+ it('moves off a port another account holds, tells agents, and comes back to the saved port next time', async () => {
+ const holder = createServer()
+ await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', resolve))
+ const taken = (holder.address() as { port: number }).port
+ // No port named: the bridge's own choice, which is the one that may move.
+ const { HARNESS_CONNECTIONS_PORT: _named, ...free } = env
+ const vault = new Store(join(home, 'store'), free)
+ // Stands for 51793, which the bridge asks for by default: a Team daemon has held it since boot.
+ saveBridgePort(vault, taken)
+ const said = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ startConnectors(fakeCore(), { vault, env: free, offered: async () => ({}), retryMs: 5, holderIsMine: async () => false })
+ let moved = taken
+ for (let n = 0; n < 200 && moved === taken; n++) {
+ await new Promise(resolve => setTimeout(resolve, 10))
+ moved = bridgePort(free, new Store(join(home, 'store'), free))
+ }
+ expect(moved).not.toBe(taken)
+ expect(said.mock.calls.flat().join(' ')).toContain(`bridge port ${taken} is not available`)
+ expect(said.mock.calls.flat().join(' ')).toContain(`the bridge moved to port ${moved}`)
+ expect(await fetch(`http://127.0.0.1:${moved}/x/linear/mcp`, { method: 'POST', body: '{}' }).then(answer => answer.status)).toBe(404)
+ // Once the holder lets go, agents still on the old address recover: the bridge answers there too.
+ await new Promise<void>(resolve => holder.close(() => resolve()))
+ let status = 0
+ for (let n = 0; n < 200 && !status; n++) {
+ await new Promise(resolve => setTimeout(resolve, 10))
+ status = await fetch(`http://127.0.0.1:${taken}/x/linear/mcp`, { method: 'POST', body: '{}' }).then(answer => answer.status, () => 0)
+ }
+ expect(status).toBe(404)
+ } finally {
+ said.mockRestore()
+ holder.close()
+ }
+ }, 30_000)
+
+ it.each([
+ ['its own account holds the port, by the real lookup', undefined],
+ ['nobody can say who holds it', async () => null],
+ ])('never moves when %s', async (_name, holderIsMine) => {
+ const holder = createServer()
+ await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', resolve))
+ const taken = (holder.address() as { port: number }).port
+ const { HARNESS_CONNECTIONS_PORT: _named, ...free } = env
+ const vault = new Store(join(home, 'store'), free)
+ saveBridgePort(vault, taken)
+ const said = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ startConnectors(fakeCore(), { vault, env: free, offered: async () => ({}), retryMs: 5, ...(holderIsMine ? { holderIsMine } : {}) })
+ // Well past the tries before it asks, with time for the lookup.
+ await new Promise(resolve => setTimeout(resolve, 400))
+ expect(bridgePort(free, new Store(join(home, 'store'), free))).toBe(taken)
+ expect(said.mock.calls.flat().join(' ')).not.toContain('moved')
+ await new Promise<void>(resolve => holder.close(() => resolve()))
+ let status = 0
+ for (let n = 0; n < 200 && !status; n++) {
+ await new Promise(resolve => setTimeout(resolve, 10))
+ status = await fetch(`http://127.0.0.1:${taken}/x/linear/mcp`, { method: 'POST', body: '{}' }).then(answer => answer.status, () => 0)
+ }
+ expect(status).toBe(404)
+ } finally {
+ said.mockRestore()
+ holder.close()
+ }
+ // Its waits add up past the default 5 s on a loaded machine: it timed out once in a full coverage run.
+ }, 30_000)
+
+ it('does not move on one answer: a handover ending just then reads as another account, so it tries the port again first', async () => {
+ const holder = createServer()
+ await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', resolve))
+ const taken = (holder.address() as { port: number }).port
+ const { HARNESS_CONNECTIONS_PORT: _named, ...free } = env
+ const vault = new Store(join(home, 'store'), free)
+ saveBridgePort(vault, taken)
+ const said = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ let asked = 0
+ try {
+ // Another account's by one answer, then this account's every time after, as a port another listener took over.
+ startConnectors(fakeCore(), { vault, env: free, offered: async () => ({}), retryMs: 5, holderIsMine: async () => { asked++; return asked % 2 === 0 } })
+ for (let n = 0; n < 200 && asked < 6; n++) await new Promise(resolve => setTimeout(resolve, 10))
+ expect(asked).toBeGreaterThanOrEqual(6)
+ expect(bridgePort(free, new Store(join(home, 'store'), free))).toBe(taken)
+ expect(said.mock.calls.flat().join(' ')).not.toContain('moved')
+ } finally {
+ said.mockRestore()
+ await new Promise<void>(resolve => holder.close(() => resolve()))
+ }
+ }, 30_000)
+
+ it('says so when the port it moved to cannot be saved', async () => {
+ const holder = createServer()
+ await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', resolve))
+ const { HARNESS_CONNECTIONS_PORT: _named, ...free } = env
+ const vault = new Store(join(home, 'store'), free)
+ saveBridgePort(vault, (holder.address() as { port: number }).port)
+ const said = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ startConnectors(fakeCore(), { vault, env: free, offered: async () => ({}), retryMs: 5, holderIsMine: async () => false })
+ vi.spyOn(vault, 'file').mockImplementation(() => { throw new Error('disk full') })
+ for (let n = 0; n < 200 && !said.mock.calls.flat().join(' ').includes('could not save'); n++) await new Promise(resolve => setTimeout(resolve, 10))
+ expect(said.mock.calls.flat().join(' ')).toContain("could not save the bridge's new port: disk full")
+ } finally {
+ said.mockRestore()
+ await new Promise<void>(resolve => holder.close(() => resolve()))
+ }
+ })
+
it('waits for its port while another process holds it', async () => {
const holder = createServer()
await new Promise<void>(resolve => holder.listen(0, '127.0.0.1', resolve))
diff --git a/cli/src/services/connectors.ts b/cli/src/services/connectors.ts
index 26c40f4d2..dbced176d 100644
--- a/cli/src/services/connectors.ts
+++ b/cli/src/services/connectors.ts
@@ -14,8 +14,10 @@
* account's machines (lib/connectors/vaultSync.ts).
*/
import type { Server } from 'node:http'
+import type { AddressInfo } from 'node:net'
import type { CoreApi, ServiceRequests } from '../core/api.js'
-import { bridgePort, sync } from '../lib/connectors/agents.js'
+import { bridgePort, saveBridgePort, sync } from '../lib/connectors/agents.js'
+import { portHolderIsThisAccount } from '../lib/peerAccount.js'
import { createBridge } from '../lib/connectors/bridge.js'
import { services, type GatewayRow } from '../lib/connectors/catalog.js'
import { addApiKey, addCustom, cards, disconnect, Flows, signInFor } from '../lib/connectors/connect.js'
@@ -41,25 +43,73 @@ export interface ConnectorsDeps {
vaultPort: VaultPort | null
}
-/** Listen on the bridge's fixed port; while another process holds it (a core handing over), try again. */
-function listen(bridge: Server, port: number, retryMs: number): void {
- bridge.on('error', () => { setTimeout(() => bridge.listen(port, '127.0.0.1'), retryMs).unref() })
+/** How many tries a held port gets before asking whose it is. */
+const TRIES_BEFORE_ASKING = 3
+
+interface Moving {
+ /** Whether this account holds the port: a daemon handing over, or a second daemon of this account sharing the vault. */
+ holderIsMine(port: number): Promise<boolean | null>
+ moved(port: number, from: number): void
+}
+
+/**
+ * Listen on [port]. Another process holding it means agents' connections reach that process, not this bridge, so that is
+ * said once. Only another account's hold moves the bridge ([moving]): it can last from boot until this user logs in
+ * (audit H1). A hold of this account's own is waited out, however long: the vault and the agents' configurations are the
+ * account's, so a second daemon or a slow handover that moved would take the agents with it.
+ */
+function listen(bridge: Server, port: number, retryMs: number, moving?: Moving): void {
+ let tries = 0
+ let leaving = false
+ // macOS reads a listener that has just gone as another account's, so one answer may be a handover ending: it takes two
+ // in a row, with a try of the port between them.
+ let notMine = 0
+ bridge.on('listening', () => {
+ if (leaving) moving!.moved((bridge.address() as AddressInfo).port, port)
+ leaving = false
+ tries = 0
+ })
+ const again = (): void => { setTimeout(() => bridge.listen(leaving ? 0 : port, '127.0.0.1'), retryMs).unref() }
+ bridge.on('error', (error: Error) => {
+ tries++
+ if (tries === 1) console.warn(`[connections] bridge port ${port} is not available (${error.message}); trying again every ${retryMs} ms`)
+ if (!moving || tries < TRIES_BEFORE_ASKING || leaving) { again(); return }
+ void moving.holderIsMine(port).then((mine) => {
+ notMine = mine === false ? notMine + 1 : 0
+ leaving = notMine >= 2
+ again()
+ })
+ })
bridge.listen(port, '127.0.0.1')
}
-export function startConnectors(core: CoreApi, overrides: Partial<ConnectorsDeps> = {}): ServiceRequests {
+export function startConnectors(core: CoreApi, overrides: Partial<ConnectorsDeps> & { holderIsMine?: (port: number) => Promise<boolean | null> } = {}): ServiceRequests {
const env = overrides.env ?? process.env
+ const store = overrides.vault ?? new Store(undefined, env)
const deps: ConnectorsDeps = {
- vault: overrides.vault ?? new Store(undefined, env), port: overrides.port ?? bridgePort(env),
+ vault: store, port: overrides.port ?? bridgePort(env, store),
offered: overrides.offered ?? (() => gateway.available()), env, retryMs: overrides.retryMs ?? 5_000,
vaultPort: overrides.vaultPort !== undefined ? overrides.vaultPort
: core.account.signedIn() ? vaultPortOf((op, payload = {}) => answerVaultOp(core.account, { ...payload, op })) : null,
}
const { vault } = deps
const flows = new Flows(vault, env)
- const bridge = createBridge(vault, { key: () => String(vault.file('bridge.json').key ?? ''), harnessKey: () => String(vault.file('harness-key.json').key ?? '') })
+ const bridgeKeys = { key: () => String(vault.file('bridge.json').key ?? ''), harnessKey: () => String(vault.file('harness-key.json').key ?? '') }
+ const bridge = createBridge(vault, bridgeKeys)
bridge.unref()
- listen(bridge, deps.port, deps.retryMs)
+ // A port a test or HARNESS_CONNECTIONS_PORT names stays that port.
+ const movable = overrides.port === undefined && env.HARNESS_CONNECTIONS_PORT === undefined
+ listen(bridge, deps.port, deps.retryMs, movable ? {
+ holderIsMine: overrides.holderIsMine ?? portHolderIsThisAccount,
+ moved: (port, from) => {
+ console.warn(`[connections] another account holds port ${from}; the bridge moved to port ${port}, and agents started from now on use it`)
+ try { saveBridgePort(vault, port); sync(vault, env) } catch (error) { console.warn(`[connections] could not save the bridge's new port: ${(error as Error).message}`) }
+ // Agents already running keep the old address: they recover here as soon as the other account lets go of it.
+ const old = createBridge(vault, bridgeKeys)
+ old.unref()
+ listen(old, from, deps.retryMs)
+ },
+ } : undefined)
try { sync(vault, env) } catch { /* A config that cannot be written now is written at the next connect. */ }
// Connections the same on every computer of the account: read now, at each `connectors_changed`, and
diff --git a/cli/src/superTabs/attach.spec.ts b/cli/src/superTabs/attach.spec.ts
index f12312ff7..4d608c155 100644
--- a/cli/src/superTabs/attach.spec.ts
+++ b/cli/src/superTabs/attach.spec.ts
@@ -84,7 +84,8 @@ function direct(put = () => new Response(null, { status: 200 })) {
it('sends a file of up to 10 MB by the form, and a larger one by a link: straight to storage, then complete', async () => {
const folder = dir('attach-direct-')
- const credential = loadOrCreateHookCredential(folder)
+ // The credential is there, and over the socket a call does not show it (audit H1).
+ loadOrCreateHookCredential(folder)
const target = { tabId: 'tab', conversationId: 'c1', port: 14001, dataDir: folder }
const small = sparse(folder, 'small.bin', 10 * MiB), big = sparse(folder, 'big.bin', 10 * MiB + 1)
const fetcher = direct()
@@ -98,8 +99,8 @@ it('sends a file of up to 10 MB by the form, and a larger one by a link: straigh
const [form, link, put, complete] = fetcher.mock.calls.map(([, init]) => init!)
// 10 MB exactly still goes by the form, as before.
expect((form!.body as FormData).get('file')).toMatchObject({ name: 'small.bin', size: 10 * MiB })
- // The daemon's calls carry its write gate and local credential, and only those.
- for (const local of [link!, complete!]) expect(local.headers).toEqual({ 'x-adapter-local': '1', 'X-Harness-Local': credential, 'content-type': 'application/json' })
+ // The daemon's calls carry its write gate, and only that.
+ for (const local of [link!, complete!]) expect(local.headers).toEqual({ 'x-adapter-local': '1', 'content-type': 'application/json' })
expect(JSON.parse(String(link!.body))).toEqual({ conversationId: 'c1', name: 'big.bin', mime: 'application/octet-stream', size: 10 * MiB + 1 })
expect(JSON.parse(String(complete!.body))).toEqual({})
// Storage gets exactly the signed headers and the length, never a credential: the link is the credential.
diff --git a/cli/src/superTabs/attach.ts b/cli/src/superTabs/attach.ts
index 8a54ceb6d..1a20385b4 100644
--- a/cli/src/superTabs/attach.ts
+++ b/cli/src/superTabs/attach.ts
@@ -3,6 +3,7 @@ import { closeSync, constants, fstatSync, lstatSync, openAsBlob, openSync, readS
import { stat } from 'node:fs/promises'
import { basename, extname, isAbsolute, relative, sep } from 'node:path'
import { localCredentialHeaders } from '../lib/localCredential.js'
+import { daemonFetch } from '../lib/localTransport.js'
import { ATTACHMENT_TOTAL_MS } from '../lib/superTabAttachmentProxy.js'
import { object } from './wire.js'
import { formatSize, MAX_ATTACHMENT_BYTES, MAX_FORM_ATTACHMENT_BYTES } from './attachments.js'
@@ -173,7 +174,8 @@ export function readInsideFolder(paths: string[], folder: string): CheckedFile[]
/** Uploads each file of `post --attach` and answers the ids `message.send` names. Repeating a post whose message already
* went out uploads nothing and names that message's files, so the send returns its receipt. */
export async function uploadAttachments(paths: Array<string | CheckedFile>, operationId: string, target: UploadTarget, request: Request,
- fetcher: typeof fetch = fetch): Promise<string[]> {
+ // Through the daemon's private socket: a file, and any credential, must not reach whoever holds its port (audit H1).
+ fetcher: typeof fetch = daemonFetch(target.dataDir, target.port)): Promise<string[]> {
// A file too large is refused before any request, and so uploads none of the others. One not there is left to the check
// below, after the answer whether the post already went out: a repeat of one that did still names its files.
for (const path of paths) {
diff --git a/cli/src/superTabs/cards.spec.ts b/cli/src/superTabs/cards.spec.ts
index 69e3f2741..4cb55e65a 100644
--- a/cli/src/superTabs/cards.spec.ts
+++ b/cli/src/superTabs/cards.spec.ts
@@ -315,6 +315,31 @@ describe('SwarmCards.tick', () => {
expect(t.seen.at(-1)).toEqual([])
})
+ it('holds the first list while a Swarm could not be read yet, and only for a minute: a list without it says it went', async () => {
+ const t = setup({ t1: { lastChangedAt: 1, state: swarm() }, t2: { lastChangedAt: 1, state: swarm({ name: 'two' }) } })
+ t.failing.set('t1', 500)
+ await t.cards.tick()
+ expect(t.seen).toEqual([])
+ t.failing.delete('t1')
+ await t.cards.tick()
+ expect(t.seen.at(-1)?.map(c => c.id)).toEqual(['t1', 't2'])
+ // Refused is an answer: no wait.
+ const refused = setup({ t1: { lastChangedAt: 1, state: swarm() }, t2: { lastChangedAt: 1, state: swarm({ name: 'two' }) } })
+ refused.failing.set('t1', 403)
+ await refused.cards.tick()
+ expect(refused.seen.at(-1)?.map(c => c.id)).toEqual(['t2'])
+ // One that keeps failing does not hide the others for long.
+ const stuck = setup({ t1: { lastChangedAt: 1, state: swarm() }, t2: { lastChangedAt: 1, state: swarm({ name: 'two' }) } })
+ stuck.failing.set('t1', 500)
+ await stuck.cards.tick()
+ stuck.advance(59_000)
+ await stuck.cards.tick()
+ expect(stuck.seen).toEqual([])
+ stuck.advance(2_000)
+ await stuck.cards.tick()
+ expect(stuck.seen.at(-1)?.map(c => c.id)).toEqual(['t2'])
+ })
+
it('keeps a tab it already read when another failure happens on re-read', async () => {
const t = setup({ t1: { lastChangedAt: 1, state: swarm() } })
await t.cards.tick()
diff --git a/cli/src/superTabs/cards.ts b/cli/src/superTabs/cards.ts
index e10fc1835..3b23d121e 100644
--- a/cli/src/superTabs/cards.ts
+++ b/cli/src/superTabs/cards.ts
@@ -224,6 +224,9 @@ const cachedKey = (tabId: string, leadId: string, chatId: string | undefined, ch
const isSide = (v: unknown): v is CardSide => v === 'pm' || v === 'buddy'
const tabOf = (read: SwarmRead): TabCache => ({ lastChangedAt: read.lastChangedAt, state: read.state })
+/** How long the first list waits for a Swarm whose read failed, before going without it. */
+const UNREAD_HOLD_MS = 60_000
+
export class SwarmCards {
onCards?: (cards: SwarmCard[]) => void
onRecap?: (recap: LeadRecap) => void
@@ -241,6 +244,9 @@ export class SwarmCards {
/** Whether a harness is here and in a turn, as the last poll read it; null before the first. */
private live: ((harnessId: string) => { inTurn: boolean; since?: number } | null) | null = null
private last: string | null = null
+ /** The first list is held back: a Swarm in it could not be read yet, and a list without it tells the dial that Swarm went. */
+ private holding = false
+ private unreadSince: number | null = null
/** When each shown Lead's clock started (ms, `${card}/${lead}`), as the list last sent said. */
private lastStarts = new Map<string, number>()
private me: string | undefined
@@ -386,6 +392,7 @@ export class SwarmCards {
private async poll(): Promise<void> {
const rows = await this.listTabs()
const known = new Map<string, TabCache>()
+ let unread = false
await Promise.all(rows.map(async row => {
const id = row.id as string, held = this.tabs.get(id)
// A row without a numeric change time cannot say it is unchanged: that tab is always read again.
@@ -393,10 +400,17 @@ export class SwarmCards {
try { known.set(id, tabOf(await this.reads.read(id))) } catch (error) {
// Lost access drops only this card; any other failure keeps what was read before.
const status = error instanceof SuperTabHostError ? error.status : 0
- if (held && status !== 401 && status !== 403) known.set(id, held)
+ if (status === 401 || status === 403) return
+ if (held) known.set(id, held)
+ else unread = true
}
}))
this.tabs = known
+ // After a restart nothing is held, so one passing failure (a 5xx, a timeout) would leave that Swarm out of the first list,
+ // and the dial takes a list without a Swarm to mean it went. Bounded: a Swarm that keeps failing must not hide the others.
+ const first = unread && this.last === null
+ this.unreadSince = first ? this.unreadSince ?? this.now() : null
+ this.holding = this.unreadSince !== null && this.now() - this.unreadSince < UNREAD_HOLD_MS
// A Swarm that left the cards (access lost) takes the dial's side with it.
for (const tabId of [...this.sides.keys()]) if (!known.has(tabId)) this.sides.delete(tabId)
this.rows = rows.map(row => ({ id: row.id as string, name: row.name }))
@@ -414,6 +428,7 @@ export class SwarmCards {
/** The cards from the last reads, said when they changed. */
private emit(): void {
+ if (this.holding) return
const live = this.live ?? (() => null)
const cards: SwarmCard[] = []
for (const row of this.rows) {
diff --git a/cli/src/team/boundary.spec.ts b/cli/src/team/boundary.spec.ts
index c5b25cad2..65cb50297 100644
--- a/cli/src/team/boundary.spec.ts
+++ b/cli/src/team/boundary.spec.ts
@@ -21,6 +21,12 @@ import { tmpdir } from 'node:os'
import { join, relative } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it } from 'vitest'
+import { env } from '../config/env.js'
+import { startHookServer, type HookServerHandlers } from '../hookServer.js'
+import { bridgeKey } from '../lib/connectors/agents.js'
+import { createBridge } from '../lib/connectors/bridge.js'
+import { portHolderIsThisAccount } from '../lib/peerAccount.js'
+import { Store } from '../lib/connectors/store.js'
import { SENTINEL_NAME } from './layout.js'
import { realPrivacyDeps, runPrivacyCheck } from './privacy.js'
import { buildLinuxSetupScript, buildSetupScript, type SetupScriptInput } from './script.js'
@@ -295,13 +301,85 @@ describe('the privacy check, on the real file system', () => {
})
})
-/** A hole the audit found (finding H1), pinned as it is today: this turns red the day it is closed, and then says the opposite. */
+/**
+ * Audit H1 against a real other account and the real lookup: `nobody`, with a secret it heard. On a Mac with no passwordless
+ * sudo, this does not run; there the refusal is tested with a stand-in (hookServer.spec.ts, connectors.spec.ts).
+ */
+describe.runIf(sudoNobody)('a secret another account heard opens nothing, as nobody', () => {
+ /** One request as `nobody`: its status and body, from the real Node client. */
+ const askAsNobody = async (url: string, init: { method?: string; headers?: Record<string, string>; body?: string }): Promise<{ status: number; text: string }> => {
+ const script = `fetch(${JSON.stringify(url)}, ${JSON.stringify(init)}).then(async r => console.log(JSON.stringify({ status: r.status, text: await r.text() })), e => { console.error(e); process.exit(9) })`
+ // Not asNobody: its spawnSync would hold this process, which is the server being asked, until the timeout.
+ const child = spawn('sudo', ['-n', '-u', 'nobody', process.execPath, '-e', script], { cwd: '/', stdio: ['ignore', 'pipe', 'pipe'], timeout: 20_000 })
+ let output = ''
+ child.stdout.on('data', (chunk: Buffer) => { output += chunk.toString() })
+ child.stderr.on('data', (chunk: Buffer) => { output += chunk.toString() })
+ const status = await new Promise<number | null>((resolve) => { child.on('close', resolve) })
+ expect(status, output).toBe(0)
+ return JSON.parse(output.trim().split('\n').at(-1)!) as { status: number; text: string }
+ }
+
+ it('the daemon refuses the credential and the hook token from nobody, and takes them from this account', async () => {
+ const started = await startHookServer(0, { onRegistered: () => {}, onSessionEnd: () => {}, onStatus: async () => ({ secretDetail: 'x' }) } as unknown as HookServerHandlers)
+ try {
+ const credential = readFileSync(join(env.ADAPTER_DATA_DIR, 'hook-credential'), 'utf8').trim()
+ const hookToken = readFileSync(join(env.ADAPTER_DATA_DIR, 'hook-token'), 'utf8').trim()
+ const base = `http://127.0.0.1:${started.port}`
+ expect((await askAsNobody(`${base}/api/machines`, { headers: { 'X-Harness-Local': credential } })).status).toBe(401)
+ expect((await askAsNobody(`${base}/api/status`, { headers: { 'X-Harness-Local': credential } })).text).not.toContain('secretDetail')
+ expect((await askAsNobody(`${base}/api/hook/session-end`, { method: 'POST', headers: { 'x-harness-hook-token': hookToken }, body: '{}' })).status).toBe(401)
+ expect(await (await fetch(`${base}/api/status`, { headers: { 'X-Harness-Local': credential } })).text()).toContain('secretDetail')
+ expect((await fetch(`${base}/api/hook/session-end`, { method: 'POST', headers: { 'x-harness-hook-token': hookToken }, body: '{}' })).status).not.toBe(401)
+ } finally {
+ started.server.closeAllConnections()
+ await new Promise<void>((resolve) => { started.server.close(() => resolve()) })
+ await started.localSocket?.close()
+ }
+ }, 60_000)
+
+ it('a listener of nobody on a plain listen(port), on `::`, reads as another account\'s', async () => {
+ // It exits by itself: this process may not stop another account's.
+ const script = `const s = require('node:net').createServer().listen(0, () => console.log(s.address().port)); setTimeout(() => process.exit(0), 8000)`
+ const child = spawn('sudo', ['-n', '-u', 'nobody', process.execPath, '-e', script], { cwd: '/', stdio: ['ignore', 'pipe', 'inherit'] })
+ const port = await new Promise<number>((resolve, reject) => {
+ child.stdout.once('data', (chunk: Buffer) => resolve(Number(chunk.toString().trim())))
+ child.once('close', () => reject(new Error('the listener ended before it named its port')))
+ })
+ try {
+ expect(await portHolderIsThisAccount(port)).toBe(false)
+ } finally {
+ await new Promise((resolve) => { child.once('close', resolve) })
+ }
+ }, 30_000)
+
+ it('the bridge answers nobody with the right key as it answers an unknown key', async () => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'hb-')))
+ const vault = new Store(root, {})
+ const key = bridgeKey(vault)
+ const bridge = createBridge(vault, { key: () => key })
+ await new Promise<void>((resolve) => { bridge.listen(0, '127.0.0.1', resolve) })
+ try {
+ const base = `http://127.0.0.1:${(bridge.address() as AddressInfo).port}`
+ const heard = await askAsNobody(`${base}/${key}/linear/mcp`, { method: 'POST', body: '{}' })
+ const unknown = await askAsNobody(`${base}/wrong/linear/mcp`, { method: 'POST', body: '{}' })
+ expect(heard).toEqual(unknown)
+ const mine = await fetch(`${base}/${key}/linear/mcp`, { method: 'POST', body: '{}' })
+ expect(await mine.text()).not.toBe(unknown.text)
+ } finally {
+ bridge.closeAllConnections()
+ await new Promise<void>((resolve) => { bridge.close(() => resolve()) })
+ rmSync(root, { recursive: true, force: true })
+ }
+ }, 60_000)
+})
+
+/** A hole the audit found (finding H1), now closed: the real hook, with a made-up credential, against a plain listener on the port. Its other cases are in localCredential.spec.ts. */
describe('the owner\'s credential and whoever holds the daemon\'s port', () => {
const NOTIFY = fileURLToPath(new URL('../../hook/notify.mjs', import.meta.url))
/** Made up for this test: never a real credential. */
const CREDENTIAL = 'A'.repeat(43)
- it('H1, still open: an engine hook hands its credential to any listener on the daemon\'s port', async () => {
+ it('H1: an engine hook hands its credential to no listener on the daemon\'s port', async () => {
const root = realpathSync(mkdtempSync(join(tmpdir(), 'hc-')))
const data = join(root, 'data')
mkdirSync(data, { mode: 0o700 })
@@ -323,7 +401,8 @@ describe('the owner\'s credential and whoever holds the daemon\'s port', () => {
})
hook.stdin.end(JSON.stringify({ hook_event_name: 'SessionStart', session_id: '11111111-1111-4111-8111-111111111111', cwd: root, source: 'startup' }))
await new Promise<void>(resolve => { hook.on('exit', () => resolve()) })
- expect(heard).toContain(CREDENTIAL)
+ // Nothing at all: the hook goes over the daemon's 0600 socket, and with none there the daemon is down.
+ expect(heard).toEqual([])
} finally {
await new Promise<void>(resolve => { impostor.close(() => resolve()) })
rmSync(root, { recursive: true, force: true })
diff --git a/cli/src/team/localCredential.spec.ts b/cli/src/team/localCredential.spec.ts
new file mode 100644
index 000000000..0b5bca3d5
--- /dev/null
+++ b/cli/src/team/localCredential.spec.ts
@@ -0,0 +1,214 @@
+/**
+ * Audit H1 (docs/security/2026-11-02-team-account-boundary.md): while the daemon restarts, any account can bind its port.
+ * A listener here stands for that account. The listener runs as this user: what is tested is what it is sent, and for
+ * what it could do with that, a stand-in says the caller is another account.
+ */
+import { spawn } from 'node:child_process'
+import { chmodSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer, type IncomingMessage, type Server } from 'node:http'
+import type { AddressInfo } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { afterEach, describe, expect, it } from 'vitest'
+import { connectSocket } from '../agentClient/daemon.js'
+import { deviceRequest } from '../devices/client.js'
+import { createMessagesRpc } from '../messages/rpc.js'
+import { daemonFetch, localSocketRoute, localWsTarget } from '../lib/localTransport.js'
+import { localCredentialHeaders } from '../lib/localCredential.js'
+import { uploadAttachments } from '../superTabs/attach.js'
+import { WebSocket } from 'ws'
+
+const NOTIFY = fileURLToPath(new URL('../../hook/notify.mjs', import.meta.url))
+/** Made up for this test: never a real credential. */
+const CREDENTIAL = 'A'.repeat(43)
+const HOOK_TOKEN = 'B'.repeat(43)
+
+type Heard = { url: string; headers: IncomingMessage['headers']; body: string }
+
+describe('audit H1: whoever holds the daemon\'s port hears nothing it can use', () => {
+ const cleanup: Array<() => Promise<unknown> | unknown> = []
+ afterEach(async () => { for (const step of cleanup.splice(0).reverse()) await step() })
+
+ const dataFolder = (long = false): { root: string; data: string } => {
+ const root = realpathSync(mkdtempSync(join(tmpdir(), 'hc-')))
+ cleanup.push(() => rmSync(root, { recursive: true, force: true }))
+ const data = long ? join(root, 'd'.repeat(100)) : join(root, 'data')
+ mkdirSync(data, { mode: 0o700 })
+ writeFileSync(join(data, 'hook-credential'), CREDENTIAL, { mode: 0o600 })
+ writeFileSync(join(data, 'hook-token'), HOOK_TOKEN, { mode: 0o600 })
+ return { root, data }
+ }
+
+ const listen = async (server: Server, at: number | string): Promise<void> => {
+ cleanup.push(() => new Promise<void>((resolve) => { server.closeAllConnections(); server.close(() => resolve()) }))
+ await new Promise<void>((resolve) => { typeof at === 'number' ? server.listen(at, '127.0.0.1', resolve) : server.listen(at, resolve) })
+ }
+
+ /** A plain listener: a Team agent on the port. It records all it is sent and takes any WebSocket's upgrade request. */
+ const holder = async (at: number | string = 0): Promise<{ port: number; heard: Heard[] }> => {
+ const heard: Heard[] = []
+ const server = createServer((req, res) => {
+ const chunks: Buffer[] = []
+ req.on('data', (chunk: Buffer) => chunks.push(chunk))
+ req.on('end', () => {
+ heard.push({ url: req.url ?? '', headers: req.headers, body: Buffer.concat(chunks).toString() })
+ res.writeHead(200, { 'content-type': 'application/json' }); res.end('{}')
+ })
+ })
+ server.on('upgrade', (req, socket) => {
+ heard.push({ url: req.url ?? '', headers: req.headers, body: '' })
+ socket.destroy()
+ })
+ await listen(server, at)
+ // The daemon's socket is 0600 (lib/localSocket.ts), and a hook refuses any other.
+ if (typeof at === 'string') chmodSync(at, 0o600)
+ const address = server.address()
+ return { port: typeof address === 'string' ? 0 : (address as AddressInfo).port, heard }
+ }
+
+ const runHook = async (root: string, data: string, port: number): Promise<void> => {
+ const hook = spawn(process.execPath, [NOTIFY, '--port', String(port), '--data-dir', data], {
+ stdio: ['pipe', 'ignore', 'ignore'],
+ // Its own empty tmux folder, so the pane's routing reads no real tmux server.
+ env: { PATH: process.env.PATH, HOME: root, TMUX_PANE: '%999', TMUX_TMPDIR: root },
+ })
+ hook.stdin.end(JSON.stringify({ hook_event_name: 'UserPromptSubmit', prompt: 'a private prompt', session_id: '11111111-1111-4111-8111-111111111111', cwd: root }))
+ await new Promise<void>((resolve) => { hook.on('exit', () => resolve()) })
+ }
+
+ const secretIn = (heard: Heard[]): boolean => JSON.stringify(heard).includes(CREDENTIAL)
+
+ it('an engine hook sends a listener on the port nothing at all: no credential, no prompt', async () => {
+ const { root, data } = dataFolder()
+ const { port, heard } = await holder()
+ await runHook(root, data, port)
+ expect(heard).toEqual([])
+ }, 30_000)
+
+ it('an engine hook reports over the socket, with the listener on the port still hearing nothing', async () => {
+ const { root, data } = dataFolder()
+ const { port, heard } = await holder()
+ const daemon = await holder(join(data, `daemon-${port}.sock`))
+ await runHook(root, data, port)
+ expect(heard).toEqual([])
+ expect(daemon.heard.length).toBeGreaterThan(0)
+ }, 30_000)
+
+ it('an engine hook finds the socket by the daemon\'s record when its port is the one the daemon was given instead', async () => {
+ const { root, data } = dataFolder()
+ const { port, heard } = await holder()
+ const daemon = await holder(join(data, 'daemon-18473.sock'))
+ writeFileSync(join(data, 'daemon-18473.json'), JSON.stringify({ port }), { mode: 0o600 })
+ await runHook(root, data, port)
+ expect(heard).toEqual([])
+ expect(daemon.heard.length).toBeGreaterThan(0)
+ }, 30_000)
+
+ it('where a socket cannot exist, a hook sends only its own token over TCP', async () => {
+ const { root, data } = dataFolder(true)
+ const { port, heard } = await holder()
+ await runHook(root, data, port)
+ expect(heard.length).toBeGreaterThan(0)
+ expect(secretIn(heard)).toBe(false)
+ expect(heard[0]!.headers['x-harness-hook-token']).toBe(HOOK_TOKEN)
+ }, 30_000)
+
+ it('an engine hook refuses a socket another account could reach: not 0600', async () => {
+ const { root, data } = dataFolder()
+ const { port } = await holder()
+ const path = join(data, `daemon-${port}.sock`)
+ const open = await holder(path)
+ chmodSync(path, 0o666)
+ await runHook(root, data, port)
+ expect(open.heard).toEqual([])
+ }, 30_000)
+
+ it('a TCP request from a client carries no credential where the socket can exist', () => {
+ const { data } = dataFolder()
+ expect(localCredentialHeaders(data)).toEqual({})
+ })
+
+ it('keeps the credential for the one case with no socket, and for Windows', () => {
+ expect(localCredentialHeaders(dataFolder(true).data)).toEqual({ 'X-Harness-Local': CREDENTIAL })
+ expect(localCredentialHeaders(dataFolder().data, 'win32')).toEqual({ 'X-Harness-Local': CREDENTIAL })
+ })
+
+ it('agentClient: with the socket gone, the port hears nothing and the caller is told', async () => {
+ const { data } = dataFolder()
+ const { port, heard } = await holder()
+ const socket = await connectSocket({ dataDir: data, port, machineId: 'm' })
+ const failed = await new Promise<NodeJS.ErrnoException>((resolve) => { socket.on('error', resolve) })
+ expect(failed.code).toBe('ENOENT')
+ expect(heard).toEqual([])
+ })
+
+ it('messages: with the socket gone, the port hears nothing and the caller is told', async () => {
+ const { data } = dataFolder()
+ const { port, heard } = await holder()
+ await expect(createMessagesRpc()({ port, machineId: 'm', dataDir: data }, { op: 'x' }, 5_000)).rejects.toMatchObject({ code: 'DAEMON_UNREACHABLE' })
+ expect(heard).toEqual([])
+ })
+
+ it('devices: with the socket gone, the port hears nothing and the caller is told', async () => {
+ const { data } = dataFolder()
+ const { port, heard } = await holder()
+ const deps = { port, dataDir: data, machineId: async () => 'm', connect: (url: string, headers?: Record<string, string>) => new WebSocket(url, { headers }) }
+ await expect(deviceRequest(deps, 'm', 'device_x')).rejects.toThrow(/ENOENT/)
+ expect(heard).toEqual([])
+ })
+
+ it('attachments: with the socket gone, the port hears neither the credential nor the file', async () => {
+ const { root, data } = dataFolder()
+ const { port, heard } = await holder()
+ const file = join(root, 'private.txt')
+ writeFileSync(file, 'private file')
+ const ask = async () => ({ value: { agentId: 'a' } })
+ await expect(uploadAttachments([file], 'op', { tabId: 't', conversationId: 'c', port, dataDir: data }, ask)).rejects.toThrow()
+ expect(heard).toEqual([])
+ })
+
+ it('attachments: a form goes whole over the socket, with its content type', async () => {
+ const { root, data } = dataFolder()
+ const { port, heard } = await holder()
+ const server = createServer((req, res) => {
+ const chunks: Buffer[] = []
+ req.on('data', (chunk: Buffer) => chunks.push(chunk))
+ req.on('end', () => {
+ expect(req.headers['content-type']).toMatch(/^multipart\/form-data/)
+ expect(Buffer.concat(chunks).toString()).toContain('a file for the daemon')
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end(JSON.stringify({ data: { attachment: { id: 'stored' } } }))
+ })
+ })
+ await listen(server, join(data, `daemon-${port}.sock`))
+ const file = join(root, 'note.txt')
+ writeFileSync(file, 'a file for the daemon')
+ const ask = async () => ({ value: { agentId: 'a' } })
+ expect(await uploadAttachments([file], 'op', { tabId: 't', conversationId: 'c', port, dataDir: data }, ask)).toEqual(['stored'])
+ expect(heard).toEqual([])
+ })
+
+ it('daemonFetch leaves every other address to plain fetch: a storage link has no socket', async () => {
+ const { data } = dataFolder()
+ const elsewhere = await holder()
+ const seen: string[] = []
+ const base = (async (input: Parameters<typeof fetch>[0]) => { seen.push(String(input)); return new Response('{}') }) as typeof fetch
+ await daemonFetch(data, elsewhere.port + 1, base)(`http://127.0.0.1:${elsewhere.port}/upload`)
+ expect(seen).toEqual([`http://127.0.0.1:${elsewhere.port}/upload`])
+ })
+
+ it('daemonFetch answers no body for a 204', async () => {
+ const { data } = dataFolder()
+ const server = createServer((_req, res) => { res.writeHead(204); res.end() })
+ await listen(server, join(data, 'daemon-4242.sock'))
+ const answer = await daemonFetch(data, 4242)('http://127.0.0.1:4242/x', { method: 'POST', body: '{}' })
+ expect(answer.status).toBe(204)
+ })
+
+ it('finds no socket on Windows, and TCP there keeps its record\'s port', () => {
+ const { data } = dataFolder()
+ expect(localSocketRoute(data, 4242, 'win32')).toBeNull()
+ expect(localWsTarget(data, 4242, 'win32').url).toBe('ws://127.0.0.1:4242/api/local-ws')
+ })
+})
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 5a4406af7..ffbb906c1 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -307,15 +307,15 @@ The native desktop target uses the CLI for cloud access and SSO tokens:
the only one asking. A hidden tab reads nothing on this pace; the one read it still makes is the
5-minute safety net every window keeps (`machineListSafetyNetInterval`). The browser's connect
page and asleep band keep no timer of their own.
-- **Both REST and the local WS prefer the daemon's Unix socket** (`lib/ws/local_daemon_transport.dart`;
+- **Both REST and the local WS use the daemon's Unix socket** (`lib/ws/local_daemon_transport.dart`;
CLI `lib/localSocket.ts`): `~/.harness/cli/data/daemon-<port>.sock`, 0600, named for the port in
- `localCliBaseUrl` so it always leads to the same daemon as the TCP fallback. The loopback port takes
- any local user's process; the socket only this user's. One `LocalDaemonTransport`, owned by
- `LocalCliDiscovery`, is shared by `ApiClient` (a Dio adapter that only routes the daemon's own
- address) and `WsPool`/`WsConn`. Discovery probes the socket first and the port second; a request or
- dial that cannot reach the socket retries on the port, and each WS connect re-checks whether the
- socket file exists, so a daemon restart does not strand the app on TCP. Windows and paths over 96
- bytes have no socket. The CLI, engine hooks and the dashboard stay on TCP. Under `flutter test`
+ `localCliBaseUrl`. The loopback port takes any local user's process and any account can bind it once
+ it is free, after a reboot until this user logs in or during a restart (audit H1); the socket is this
+ user's alone. So while a socket can exist the app never asks the port: with the socket gone, the
+ daemon is down. One `LocalDaemonTransport`, owned by `LocalCliDiscovery`, is shared by `ApiClient` (a
+ Dio adapter that only routes the daemon's own address) and `WsPool`/`WsConn`. Each WS connect
+ re-checks whether the socket file exists. Windows and paths over 96 bytes have no socket, and only
+ those use the port. Under `flutter test`
`LocalDaemonTransport.detect` finds no socket, so tests never reach a real daemon.
- **On Windows the trusted routes go over the daemon's pipe** (`ws/trusted_pipe.dart`, B's §2):
`POST /api/auth/handoff`, and this computer's window connection (`WsConn.trustedLocal`), where
diff --git a/desktop/lib/ws/local_cli_discovery.dart b/desktop/lib/ws/local_cli_discovery.dart
index 524e0dce9..66357e1f5 100644
--- a/desktop/lib/ws/local_cli_discovery.dart
+++ b/desktop/lib/ws/local_cli_discovery.dart
@@ -520,9 +520,9 @@ class LocalCliDiscovery {
return const LocalCliProbe.down('computer id mismatch');
}
final base = Uri.parse(config.localCliBaseUrl);
- // The socket first: only this user can have opened it. A daemon that
- // answers there — ready or not — is the daemon; one that does not may
- // predate the socket, so the port is asked next.
+ // The socket: only this user can have opened it. A daemon that answers
+ // there — ready or not — is the daemon. One that does not is down: the port
+ // is another matter, as any account may hold it (audit H1).
final socket = transport.candidate;
if (socket != null && transport.socketPresent) {
final viaSocket = await _probeStatus(
@@ -538,6 +538,9 @@ class LocalCliDiscovery {
}
}
transport.useTcp();
+ if (!transport.portAllowed) {
+ return const LocalCliProbe.down('the daemon socket did not answer');
+ }
if (base.host != '127.0.0.1' && base.host != 'localhost') {
return const LocalCliProbe.down('the local CLI address is not loopback');
}
diff --git a/desktop/lib/ws/local_daemon_transport.dart b/desktop/lib/ws/local_daemon_transport.dart
index a5e6bfd93..b2c61b72d 100644
--- a/desktop/lib/ws/local_daemon_transport.dart
+++ b/desktop/lib/ws/local_daemon_transport.dart
@@ -15,9 +15,13 @@ import 'windows_pipe.dart';
///
/// The loopback port takes requests from any process on this computer, any
/// user's; the socket file is 0600 in a 0700 directory, so only this user's
-/// processes can open it. The app prefers it for both REST and the local
-/// WebSocket and falls back to the port — for a daemon that predates the
-/// socket, one that could not open it, or a moment when it is missing.
+/// processes can open it. The app uses it for both REST and the local
+/// WebSocket, and never falls back to the port while a socket can exist: any
+/// account can bind that port once it is free, after a reboot until this user
+/// logs in or during a restart, and would hear the credential and the request
+/// (audit H1, docs/security/2026-11-02-team-account-boundary.md). With the
+/// socket missing, the daemon is down. The port remains only for a data folder
+/// whose path is too long to hold a socket.
///
/// There is one socket per control port, `daemon-<port>.sock`, named for the
/// port the app would otherwise dial: the socket and the fallback always lead
@@ -55,8 +59,8 @@ const daemonCredentialHeader = 'X-Harness-Local';
/// The daemon's local credential: its `hook-credential` file, 0600 and this
/// user's, in [defaultDaemonDataDir]. The loopback port takes any OS user's
/// process — another account's harness running as its own user on this
-/// computer included — so every call over the port shows it; the socket needs
-/// none. Null where it cannot be read.
+/// computer included — so a call over the port shows it, in the one case with
+/// no socket; the socket needs none. Null where it cannot be read.
String? readDaemonCredential({Map<String, String>? environment}) {
final dataDir = defaultDaemonDataDir(environment: environment);
if (dataDir == null) return null;
@@ -155,12 +159,20 @@ class LocalDaemonTransport {
/// one (tests).
final String? Function()? credential;
- /// The credential for non-Windows loopback TCP. Windows never sends it to a
- /// port, since a stale record can name a port another process now owns.
+ /// Whether this app may ask the daemon's loopback port at all: not where a
+ /// socket can exist, since whoever holds the port is not known to be the
+ /// daemon.
+ bool get portAllowed => candidate == null;
+
+ /// The credential for loopback TCP where no socket can exist. Windows never
+ /// sends it to a port, since a stale record can name a port another process
+ /// now owns.
Map<String, String> tcpHeaders() {
// A stale Windows daemon record can name a port another process now owns.
// Never show the credential to a TCP listener when a private pipe is used.
- if (Platform.isWindows || trustedPipe != null) return const {};
+ if (Platform.isWindows || trustedPipe != null || !portAllowed) {
+ return const {};
+ }
final value = credential?.call();
return value == null ? const {} : {daemonCredentialHeader: value};
}
@@ -197,7 +209,7 @@ bool isConnectionFailure(Object error) {
}
/// Sends Windows daemon REST over its authenticated pipe. Elsewhere it uses
-/// the Unix socket when available and falls back to the loopback port.
+/// the Unix socket, and the loopback port only where no socket can exist.
class LocalDaemonHttpAdapter implements HttpClientAdapter {
LocalDaemonHttpAdapter(this.transport, {required this.daemonBase});
@@ -238,6 +250,12 @@ class LocalDaemonHttpAdapter implements HttpClientAdapter {
}
// Over the port, the daemon wants its local credential.
Future<ResponseBody> overPort() {
+ if (toDaemon && !transport.portAllowed) {
+ throw DioException.connectionError(
+ requestOptions: options,
+ reason: 'The local daemon socket is not available',
+ );
+ }
if (toDaemon) options.headers.addAll(transport.tcpHeaders());
return _tcp.fetch(
toDaemon ? _onTcpPort(options) : options,
@@ -251,8 +269,8 @@ class LocalDaemonHttpAdapter implements HttpClientAdapter {
return await _unixFor(path).fetch(options, requestStream, cancelFuture);
} catch (error) {
if (!isConnectionFailure(error)) rethrow;
- // Nothing was sent: the socket could not be opened. The port can still
- // serve this request, and discovery will find the socket again later.
+ // Nothing was sent: the socket could not be opened. Discovery will find
+ // the socket again later; this request fails as a daemon that is down.
transport.useTcp();
return overPort();
}
diff --git a/desktop/lib/ws/ws_conn.dart b/desktop/lib/ws/ws_conn.dart
index 8c6e698d0..6f35b28ac 100644
--- a/desktop/lib/ws/ws_conn.dart
+++ b/desktop/lib/ws/ws_conn.dart
@@ -445,10 +445,10 @@ class WsConn {
throw StateError('The local daemon pipe is unavailable');
}
final transport =
- localTransport ??
- LocalDaemonTransport(
- credential: kUnderTest ? null : readDaemonCredential,
- );
+ localTransport ?? LocalDaemonTransport.detect(uri);
+ if (!transport.portAllowed) {
+ throw StateError('The local daemon socket is unavailable');
+ }
return IOWebSocketChannel.connect(uri, headers: transport.tcpHeaders());
}
diff --git a/desktop/test/local_daemon_transport_test.dart b/desktop/test/local_daemon_transport_test.dart
index 00fb7d332..c49b5d8d6 100644
--- a/desktop/test/local_daemon_transport_test.dart
+++ b/desktop/test/local_daemon_transport_test.dart
@@ -169,7 +169,7 @@ void main() {
);
});
- test('goes with REST over the port, never down the socket', () async {
+ test('never goes down the socket, and never to the port once it is gone', () async {
final tcp = await start(_Daemon.tcp());
final unix = await start(_Daemon.unix(socketPath));
final transport = LocalDaemonTransport(
@@ -188,16 +188,37 @@ void main() {
await unix.close();
daemons.remove(unix);
if (File(socketPath).existsSync()) File(socketPath).deleteSync();
+ // The port's listener stands for another account that took it (audit H1).
+ await expectLater(api.me(), throwsA(anything));
+ expect(tcp.hits, isEmpty);
+ expect(tcp.credentials, isEmpty);
+ });
+
+ test('goes with REST over the port where no socket can exist', () async {
+ final tcp = await start(_Daemon.tcp());
+ final transport = LocalDaemonTransport(credential: () => credential);
+ final api = ApiClient(
+ config: configFor(tcp),
+ session: AuthSession(),
+ localTransport: transport,
+ );
+
expect(await api.me(), {'via': 'tcp'});
expect(tcp.credentials.last, credential);
});
- test('goes with the local WebSocket over the port', () async {
- final tcp = await start(_Daemon.tcp());
+ test('is not offered to a port while a socket can exist', () {
final transport = LocalDaemonTransport(
candidate: socketPath,
credential: () => credential,
- )..useTcp();
+ );
+ expect(transport.portAllowed, isFalse);
+ expect(transport.tcpHeaders(), isEmpty);
+ });
+
+ test('goes with the local WebSocket over the port where no socket can exist', () async {
+ final tcp = await start(_Daemon.tcp());
+ final transport = LocalDaemonTransport(credential: () => credential);
final conn = WsConn(
wsBaseUrl: 'wss://unused.example',
autonomousEnv: 'prod',
@@ -239,7 +260,9 @@ void main() {
expect(tcp.hits, isEmpty);
});
- test('falls back to the port when there is no socket', () async {
+ test('finds no daemon, and asks no port, when the socket is gone', () async {
+ // The port's listener stands for another account: after a reboot it holds the
+ // port until this user logs in, and could answer anything (audit H1).
final tcp = await start(_Daemon.tcp());
final transport = LocalDaemonTransport(candidate: socketPath)..useSocket();
final endpoint = await LocalCliDiscovery(
@@ -248,15 +271,28 @@ void main() {
transport: transport,
).discover();
+ expect(endpoint, isNull);
+ expect(transport.socketPath, isNull);
+ expect(tcp.hits, isEmpty);
+ });
+
+ test('asks the port where no socket can exist', () async {
+ final tcp = await start(_Daemon.tcp());
+ final transport = LocalDaemonTransport();
+ final endpoint = await LocalCliDiscovery(
+ config: configFor(tcp),
+ identity: LocalMachineIdentity(computerIdFile: identityFile),
+ transport: transport,
+ ).discover();
+
expect(endpoint, isNotNull);
expect(endpoint!.socketPath, isNull);
- expect(transport.socketPath, isNull);
expect(tcp.hits, ['/api/status']);
});
});
group('REST', () {
- test('goes over the socket, and back to the port once it is gone', () async {
+ test('goes over the socket, and fails as a daemon that is down once it is gone', () async {
final tcp = await start(_Daemon.tcp());
final unix = await start(_Daemon.unix(socketPath));
final transport = LocalDaemonTransport(candidate: socketPath)..useSocket();
@@ -273,7 +309,8 @@ void main() {
daemons.remove(unix);
// Closing the server removes its socket file; make sure nothing is left to dial.
if (File(socketPath).existsSync()) File(socketPath).deleteSync();
- expect(await api.me(), {'via': 'tcp'});
+ await expectLater(api.me(), throwsA(anything));
+ expect(tcp.hits, isEmpty);
expect(transport.socketPath, isNull);
});
@@ -345,15 +382,15 @@ void main() {
expect(tcp.selects, 0);
});
- test('falls back to the port when the socket is not there', () async {
+ test('never dials the port when the socket is not there', () async {
final tcp = await start(_Daemon.tcp());
final transport = LocalDaemonTransport(candidate: socketPath)..useSocket();
final conn = connFor(tcp, transport);
addTearDown(conn.close);
await conn.connect();
- await until(() => tcp.selects > 0);
+ await Future<void>.delayed(const Duration(milliseconds: 200));
- expect(tcp.selects, 1);
+ expect(tcp.selects, 0);
expect(transport.socketPath, isNull);
});
});
diff --git a/devices/harness-device/firmware/main/cable_client.c b/devices/harness-device/firmware/main/cable_client.c
index 41ebd2235..8c8e65793 100644
--- a/devices/harness-device/firmware/main/cable_client.c
+++ b/devices/harness-device/firmware/main/cable_client.c
@@ -407,6 +407,18 @@ void cable_client_supertab_side(const char *tab, bool buddy)
send_json(root);
}
+// The Buddy side a restart took off the face, for a daemon that remembers none: `kept` says no finger moved, so the
+// window stays where it is. An older daemon ignores the word, and its window follows.
+void cable_client_supertab_side_kept(const char *tab)
+{
+ if (!tab || !tab[0] || strlen(tab) >= ID_MAX) return;
+ cJSON *root = msg("supertab.side");
+ msg_string(&root, "tab", tab);
+ msg_string(&root, "side", "buddy");
+ msg_bool(&root, "kept", true);
+ send_json(root);
+}
+
void cable_client_send_turn(const char *agent_id, const char *text)
{
diff --git a/devices/harness-device/firmware/main/cable_client.h b/devices/harness-device/firmware/main/cable_client.h
index 63dfa7b51..0e73a0e81 100644
--- a/devices/harness-device/firmware/main/cable_client.h
+++ b/devices/harness-device/firmware/main/cable_client.h
@@ -236,6 +236,7 @@ void cable_client_supertab_send(const char *t, const char *tab, const char *lead
// `supertab.side` {tab, side}: the dial swiped that Swarm to its Buddy side (true) or its PM side (spec
// 2026-10-29-round-dial-pm-buddy). A tab id it cannot hold sends nothing.
void cable_client_supertab_side(const char *tab, bool buddy);
+void cable_client_supertab_side_kept(const char *tab);
// Send what the user asked for, into `agent_id`. Fire-and-forget: everything after this arrives back as
// `turn.started` / `turn.done`, or as `turn.error` in words a person can act on.
diff --git a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
index 4a902154a..cbbd893bb 100644
--- a/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
+++ b/devices/harness-device/firmware/main/ui/habitat/ui_habitat.c
@@ -588,7 +588,8 @@ static int workspace_index(const char *id)
* where the dial is in it. A Lead id is not an agent id: it reaches the cable only in supertab.* requests (A_SUPERTAB),
* never in focus, agent.open or voice.begin. Voice goes to the Lead's `local` harness id.
*/
-enum { SUPERTAB_RECAP_GET, SUPERTAB_OPEN, SUPERTAB_SELECT, SUPERTAB_SIDE }; // SIDE: id "buddy" or "pm"
+// SIDE: id "buddy" or "pm". SIDE_KEPT: the side a restart took off the face, told to the daemon without moving the window.
+enum { SUPERTAB_RECAP_GET, SUPERTAB_OPEN, SUPERTAB_SELECT, SUPERTAB_SIDE, SUPERTAB_SIDE_KEPT };
#define SWARM_WAITS 16
#define SWARM_SAID 24 // one per inbox entry the Lead messages can fill (NOTICES)
static EXT_RAM_BSS_ATTR ht_supertabs_t swarm;
@@ -599,8 +600,10 @@ static EXT_RAM_BSS_ATTR struct {
bool retried; // its recap was asked for a second time
struct { char tab[ID_MAX], lead[ID_MAX]; } focus[HT_SUPERTABS_MAX]; // the Lead the desktop last showed, per Swarm
char pending[ID_MAX]; // a Swarm the desktop opened before its `swarms` frame said so (ui_supertab_focus)
- // The Swarm and Lead an emptied list took off the face, not the person, and when: it comes back if the Swarm does.
- struct { char tab[ID_MAX], lead[ID_MAX]; uint32_t at; } lost;
+ // The Swarm, Lead and side a session down or an emptied list took off the face, not the person: stale until that
+ // Swarm's card returns, and it comes back then (swarm_regain). The person touching the dial, or a list that came back
+ // without that Swarm, ends it.
+ struct swarm_lost { char tab[ID_MAX], lead[ID_MAX]; bool buddy; } lost;
bool auto_tabs; // TABS opened by the dial itself, not touched since: it browses no desk tab
// Super Tab waits from this machine's harnesses, shown only through the Lead whose `local` names the harness.
struct { char agent[ID_MAX], request[80], swarm[HT_SUPERTAB_NAME], text[240]; bool stuck, shown; } waits[SWARM_WAITS];
@@ -772,6 +775,7 @@ static void swarm_enter(const ht_supertab_t *t, const char *lead, bool select)
if (swarm_mode() && strcmp(sw.tab, t->id)) swarm_leave();
if (workspace.phase != HT_WORKSPACE_IDLE) ht_workspace_cancel_request(&workspace);
s.loading = false;
+ sw.lost.tab[0] = 0; sw.auto_tabs = false; // this face supersedes the one a restart took, and the TABS it left
COPY(sw.tab, t->id);
sw.desk[0] = 0; swarm_desk_note();
int i = swarm_lead_index(t, lead);
@@ -3373,6 +3377,7 @@ static void worker(void *unused)
static const char *ops[] = {"supertab.recap.get", "supertab.open", "supertab.select"};
if (a.value >= SUPERTAB_RECAP_GET && a.value <= SUPERTAB_SELECT) cable_client_supertab_send(ops[a.value], a.text, a.id);
else if (a.value == SUPERTAB_SIDE) cable_client_supertab_side(a.text, !strcmp(a.id, "buddy"));
+ else if (a.value == SUPERTAB_SIDE_KEPT) cable_client_supertab_side_kept(a.text);
break;
}
case A_NOTICE_READ:
@@ -5054,9 +5059,10 @@ static int desk_row_count;
static char desk_selected[ID_MAX];
// Whether a desktop focus may take the dial into a Swarm now: from HOME or an agent, never while talking, nor over a
// question or a form.
+// A TABS the dial opened by itself is no screen of the person's: the app's focus and a returning Swarm take it over.
static bool swarm_may_follow(void)
{
- return !s.voice_open && !question_view(s.view) && (s.view == HOME || s.view == AGENT);
+ return !s.voice_open && !question_view(s.view) && (s.view == HOME || s.view == AGENT || (s.view == TABS && sw.auto_tabs));
}
static void swarms_apply(void)
{
@@ -5205,17 +5211,17 @@ static void swarm_tabs_changed(void)
int index = tab_index_of(focused);
ht_tab_carousel_reset(&tab_carousel, tabs_total(), index >= 0 ? index : tab_index_here());
}
-// A daemon that had just started said "no Swarms" before it had read them, and the real list came 2 s later (Diego's dial,
-// 2026-10-29): the Swarm the list took off the face comes back on the Lead it showed, with no pick sent, as long as the
-// person has not moved on. Only that Swarm, within 10 s; one that really went stays gone.
+// A daemon that restarts (each CLI update) drops the session and takes 5-40 s to resend the Swarm cards, and one that had
+// just started said "no Swarms" before it had read them (Diego's dial, 2026-10-29, 2026-11-02): the Swarm taken off the face
+// comes back on the Lead and side it showed, with no pick sent, however long that took, as long as the person has not moved
+// on. A daemon that remembers no side is told it, without moving the window. Only that Swarm; one that really went stays gone (ui_supertabs_ids).
static bool swarm_regain(const ht_supertab_t *t)
{
- if (!t || !sw.lost.tab[0] || swarm_mode() || strcmp(t->id, sw.lost.tab)) return false;
- bool fresh = (int32_t)(ms() - sw.lost.at) < 10000;
- bool untouched = s.view == TABS ? sw.auto_tabs : swarm_may_follow();
- if (!fresh || !untouched) { sw.lost.tab[0] = 0; return false; }
+ if (!t || !sw.lost.tab[0] || swarm_mode() || strcmp(t->id, sw.lost.tab) || !swarm_may_follow()) return false;
char lead[ID_MAX]; COPY(lead, sw.lost.lead);
- sw.lost.tab[0] = 0;
+ bool buddies = false;
+ for (int i = 0; i < t->lead_n; i++) buddies |= t->leads[i].buddies;
+ if (sw.lost.buddy && buddies && !swarm_side_buddy(t->id)) { swarm_side_put(t->id, true); swarm_send(SUPERTAB_SIDE_KEPT, t->id, "buddy"); }
swarm_enter(t, lead, false);
return true;
}
@@ -5227,11 +5233,17 @@ void ui_supertabs_ids(const char ids[][ID_MAX], int n)
swarm_events(ev, count);
if (swarm_mode() && !swarm_here()) {
// The Swarm on the face is gone: back to the list. Remembered, for a list that came empty before the real one.
- COPY(sw.lost.tab, sw.tab); COPY(sw.lost.lead, sw.lead); sw.lost.at = ms();
+ COPY(sw.lost.tab, sw.tab); COPY(sw.lost.lead, sw.lead); sw.lost.buddy = swarm_side_buddy(sw.tab);
sw.tab[0] = sw.lead[0] = sw.desk[0] = 0;
ht_supertabs_recap_open(&swarm, "", "", ms());
if (s.view == HOME || s.view == AGENT || s.view == AGENTS) { tabs_open(); sw.auto_tabs = s.view == TABS; }
}
+ // The cards are back, without it: that Swarm really went. An empty list says nothing yet: it may not have read them.
+ if (n > 0 && sw.lost.tab[0]) {
+ bool listed = false;
+ for (int i = 0; i < n; i++) listed |= !strcmp(ids[i], sw.lost.tab);
+ if (!listed) sw.lost.tab[0] = 0;
+ }
swarms_apply();
swarm_tabs_changed();
change();
@@ -5325,6 +5337,8 @@ void ui_supertab_focus(const char *tab, const char *lead)
// As `focus` today: never while talking, nor over a question or a form.
bool free = !s.voice_open && !question_view(s.view) && s.view != FORM && s.view != DRAFT && s.view != DRAFT_OPTIONS;
sw.pending[0] = 0;
+ // The app is on another Lead of the Swarm coming back: the face comes back on that one.
+ if (i >= 0 && !strcmp(sw.lost.tab, tab)) COPY(sw.lost.lead, lead);
if (swarm_regain(t)) { change(); display_unlock(); return; }
if (t && (i >= 0 || !lead[0]) && free) {
if (swarm_mode() && !strcmp(sw.tab, tab)) {
@@ -5450,7 +5464,12 @@ void ui_supertabs_clear(void)
for (int i = s.notice_count - 1; i >= 0; i--) if (s.notice[i].swarm) notice_remove(s.notice[i].agent_id, true);
notice_sync_view();
ht_supertabs_reset(&swarm);
+ // What is on the face stays, stale, until its card returns (swarm_regain); a face already waiting for one keeps waiting.
+ struct swarm_lost lost = sw.lost;
+ bool auto_tabs = sw.auto_tabs;
+ if (swarm_mode()) { COPY(lost.tab, sw.tab); COPY(lost.lead, sw.lead); lost.buddy = swarm_side_buddy(sw.tab); }
memset(&sw, 0, sizeof sw);
+ sw.lost = lost; sw.auto_tabs = auto_tabs;
swarms_apply();
swarm_tabs_changed();
change();
diff --git a/devices/harness-device/firmware/test/test_touch_ui.py b/devices/harness-device/firmware/test/test_touch_ui.py
index 70796b5cb..f9537fedc 100644
--- a/devices/harness-device/firmware/test/test_touch_ui.py
+++ b/devices/harness-device/firmware/test/test_touch_ui.py
@@ -202,7 +202,7 @@ static bool queue(action_t a) {
if (a.kind==A_NOTICE_READ) { notice_reads_sent++; notice_read_queued=a; }
if (a.kind==A_DESKTOP) { desktop_opens++; COPY(opened_agent,a.id); }
if (a.kind==A_SUPERTAB && swarm_sent<64) {
- static const char *ops[]={"recap.get","open","select","side"};
+ static const char *ops[]={"recap.get","open","select","side","side-kept"};
snprintf(swarm_wire[swarm_sent++],sizeof swarm_wire[0],"%s %s %s",ops[a.value],a.text,a.id);
}
if (a.kind==A_STOP_YES) COPY(stopped_agent,a.id);
@@ -1674,8 +1674,10 @@ static void swarm_pane_checks(const char *dir) {
ui_supertabs_ids(none, 0); assert(s.view == TABS);
ui_supertabs_ids(ids, 3); openharness_card(); ht_supertabs_put(&swarm, &card, ms(), NULL, 0);
ui_supertab_focus("s1", "L2"); assert(swarm_mode() && !strcmp(sw.lead, "L2") && s.view == HOME);
- // A Swarm that really went, back only after 10 s: TABS stays, and the person's touch browses as before.
- ui_supertabs_ids(none, 0); fake_ms += 10000; ui_supertabs_ids(ids, 3); card_send();
+ // A Swarm that really went (the list came back without it), back later: TABS stays, and the person's touch browses as before.
+ { const char others[2][ID_MAX] = {"s3", "s2"}; ui_supertabs_ids(others, 2); }
+ assert(!swarm_mode() && s.view == TABS);
+ ui_supertabs_ids(ids, 3); openharness_card(); card_send();
assert(!swarm_mode() && s.view == TABS);
habitat_touch(true, 233, 233, fake_ms);
ht_tab_carousel_reset(&tab_carousel, tabs_total(), tab_index_of("t2")); tabs_sync(); assert(tab_switches == switched + 1);
@@ -2082,6 +2084,60 @@ static bool pm_dots(void) { return disc_at(442, 218, 12, 0xeaeaf0) && disc_at(44
static bool buddy_dots(void) { return disc_at(442, 218, 9, 0x55565f) && disc_at(442, 248, 12, 0xc49bff); }
static bool any_dot(void) { return disc_at(442, 218, 12, 0xeaeaf0) || disc_at(442, 218, 9, 0x55565f); }
static bool badge(void) { return disc_at(449, 241, 14, 0x000000) && disc_at(449, 241, 10, 0xc49bff); }
+/*
+ * Diego's dial, 2026-11-02: every daemon restart (each CLI update) dropped the dial on the tabs list, because the Swarm cards
+ * took 5-40 s to come back. The face comes back on its Swarm, Lead and side whenever the cards do, unless the person moved on.
+ */
+static void swarm_restart_checks(void) {
+ const char none[1][ID_MAX] = {""}, ids[3][ID_MAX] = {"s1", "s3", "s2"}, others[2][ID_MAX] = {"s3", "s2"};
+ // The session goes down for 40 s and the cards come back: the same Lead, on the same screen, with no pick sent.
+ swarm_setup(); enter_at("s1", "L2"); s.view = HOME; swarm_sent = 0;
+ ui_supertabs_clear(); sw.opened = false; s.connected = false; assert(!swarm_mode() && s.view == HOME);
+ fake_ms += 40000; s.connected = true;
+ ui_supertabs_ids(ids, 3); assert(s.view == HOME);
+ openharness_card(); card_send();
+ assert(swarm_mode() && !strcmp(sw.tab, "s1") && !strcmp(sw.lead, "L2") && s.view == HOME && !wire_has(0, "select s1 L2"));
+ // The app is on another Lead of that Swarm by now: the face follows it.
+ ui_supertab_focus("s1", "L3"); assert(!strcmp(sw.lead, "L3") && s.view == HOME);
+ // The same when the focus comes before the card has brought the face back.
+ swarm_setup(); enter_at("s1", "L2"); s.view = HOME;
+ ui_supertabs_clear(); fake_ms += 40000; ui_supertabs_ids(ids, 3); openharness_card(); ht_supertabs_put(&swarm, &card, ms(), NULL, 0);
+ ui_supertab_focus("s1", "L3"); assert(swarm_mode() && !strcmp(sw.lead, "L3") && s.view == HOME);
+ // The daemon came back with an empty list (it had not read them yet, or signed in late): TABS for now, the face after 40 s.
+ swarm_setup(); enter_at("s1", "L2"); s.view = HOME;
+ ui_supertabs_ids(none, 0); assert(!swarm_mode() && s.view == TABS && sw.auto_tabs);
+ fake_ms += 40000; ui_supertabs_ids(ids, 3); openharness_card(); card_send();
+ assert(swarm_mode() && !strcmp(sw.lead, "L2") && s.view == HOME && !sw.auto_tabs);
+ // That TABS, then a session down too: it still comes back.
+ swarm_setup(); enter_at("s1", "L2"); s.view = HOME;
+ ui_supertabs_ids(none, 0); ui_supertabs_clear(); assert(s.view == TABS && sw.auto_tabs);
+ fake_ms += 40000; ui_supertabs_ids(ids, 3); openharness_card(); card_send();
+ assert(swarm_mode() && !strcmp(sw.lead, "L2") && s.view == HOME);
+ // The Swarm on the face really went, and the app is on another: the auto-opened TABS follows the app.
+ swarm_setup(); enter_at("s1", "L2"); s.view = HOME;
+ ui_supertabs_ids(none, 0); ui_supertabs_ids(others, 2); assert(s.view == TABS && sw.auto_tabs);
+ card_begin("s2", "t2", "playground"); card_lead("P0", "sandbox", "claude", "h9", "work", 0, 12); card_send();
+ COPY(s.selected_tab, "t2"); ui_supertab_focus("s2", "P0");
+ assert(swarm_mode() && !strcmp(sw.tab, "s2") && !strcmp(sw.lead, "P0") && s.view == HOME);
+ // The Swarm really gone once the cards are back: it does not come back over the dial later.
+ swarm_setup(); enter_at("s1", "L2"); s.view = HOME;
+ ui_supertabs_clear(); fake_ms += 40000; ui_supertabs_ids(others, 2);
+ ui_supertabs_ids(ids, 3); openharness_card(); card_send(); assert(!swarm_mode());
+ // The person touched the dial meanwhile: that is their screen now, and the Swarm stays off the face.
+ swarm_setup(); enter_at("s1", "L2"); s.view = HOME;
+ ui_supertabs_clear(); habitat_touch(true, 233, 233, fake_ms); habitat_touch_cancel(); fake_ms += 40000;
+ ui_supertabs_ids(ids, 3); openharness_card(); card_send(); assert(!swarm_mode());
+ // A person's own TABS is never followed off, by the focus either.
+ swarm_setup(); s.view = HOME; dispatch((action_t){.kind = A_TABS}); assert(s.view == TABS && !sw.auto_tabs);
+ COPY(s.selected_tab, "t1"); ui_supertab_focus("s1", "L2"); assert(!swarm_mode() && s.view == TABS);
+ // The side comes back too, and the new daemon, which remembers none, is told it.
+ buddy_setup(); enter_at("s1", "B1"); s.view = HOME; swipe_up(); assert(swarm_side_buddy("s1"));
+ ui_supertabs_clear(); assert(!swarm_side_buddy("s1")); fake_ms += 40000; swarm_sent = 0;
+ { const char one[1][ID_MAX] = {"s1"}; ui_supertabs_ids(one, 1); }
+ buddy_card("lead");
+ assert(swarm_mode() && !strcmp(sw.lead, "B1") && swarm_side_buddy("s1") && wire_has(0, "side-kept s1 buddy") && !wire_has(0, "side s1 buddy"));
+ puts("Swarm restart: the face keeps its Swarm, Lead and side across a session down or an empty list with no time limit, follows the app, and only the person or a Swarm really gone ends it");
+}
static void swarm_buddy_checks(const char *dir) {
// 7a the PM side: today's face and two dots, the upper one lit.
buddy_setup();
@@ -3865,6 +3921,7 @@ int main(int argc, char **argv) {
puts("touch UI: PASS (production contacts/renderers; voice start/finish/discard, target pinning, sensor cancellation, immediate scroll, swipes, round trips, congestion and holds)");
// Last, so every face above renders exactly as it did before chats: the faces are compared byte for byte.
swarm_chat_checks(argc>1 ? argv[1] : NULL);
+ swarm_restart_checks();
swarm_buddy_checks(argc>1 ? argv[1] : NULL);
}
'''
diff --git a/docs/plans/2026-11-02-dial-keeps-screen-across-restart-plan.md b/docs/plans/2026-11-02-dial-keeps-screen-across-restart-plan.md
new file mode 100644
index 000000000..b4c145689
--- /dev/null
+++ b/docs/plans/2026-11-02-dial-keeps-screen-across-restart-plan.md
@@ -0,0 +1,45 @@
+# Round dial keeps its screen across a daemon restart: plan
+
+**Goal:** After a daemon restart (each CLI update), the dial stays on the Swarm, Lead and side it was on, instead of dropping to
+the tabs list. Task #2051, asked for by Diego's Buddy on 2026-11-02.
+
+**Why it dropped:** a session down wiped all Swarm state (`ui_supertabs_clear`). An empty list opened TABS, and `swarm_regain`
+restored the face only within 10 s, while a restart takes 5-40 s to resend the Swarm cards.
+
+## Design
+
+- **Stale, not wiped.** A session down moves the face's Swarm, Lead and side into `sw.lost`. The cards and inbox entries still go:
+ nothing is shown as current while the link is down.
+- **No time limit.** The face comes back when that Swarm's card returns, however long it took.
+- **What ends it:** the person touching the dial, or a non-empty list without that Swarm. An empty list says nothing: the daemon
+ may not have read the cards yet.
+- **The side.** A restarted daemon remembers no side, so the dial tells it the one it kept, when that Swarm still has Buddies.
+- **Following the app.** A TABS the dial opened by itself counts as followable (`swarm_may_follow`), so the app's focus and a
+ returning Swarm take it over. A person's own TABS is never followed off.
+- **Focus order in the CLI.** `pushSwarmFocus` is only called at the end of `pushSwarmCards`, so the focus already comes after the
+ cards. No CLI code changes: a spec pins the order on attach when the daemon reads the cards late.
+
+## Design rules
+
+- Growth: N/A because nothing is stored; one fixed-size struct in RAM, gone at reboot.
+- Concurrency: under the display lock, as all Swarm state is.
+- Read cost and scale: N/A because no reads are added; one short scan of a list of at most 16 ids.
+- Compatibility: no frame changes. An older daemon ignores nothing new; the side frame already exists.
+- Migration and rollback: N/A because no stored data.
+- Audience: a kept id only ever matches a card the daemon sends this reader. Another account's list has no such id, and it is
+ then forgotten.
+- Identity: N/A because no person or login is read.
+- Failure: if the cards never come, the dial stays where it is, as it does today, and the next non-empty list settles it.
+- Platforms: round dial firmware only; a spec on the CLI side.
+
+## Steps
+
+1. Scene tests in `test_touch_ui.py`: session down 40 s, an empty list, app focus on another Lead or Swarm, a Swarm really gone, the
+ person touching the dial, the person's own TABS, the side.
+2. Change `ui_habitat.c`: keep `sw.lost` across `ui_supertabs_clear`, drop the time limit, forget on a list without it, follow on an
+ auto-opened TABS, restore the side.
+3. CLI spec for the focus order on attach.
+
+## Not covered
+
+Not run on a real dial: firmware is never flashed from this work. The tests run the production handler on the host.
diff --git a/docs/plans/2026-11-02-local-credential-listener-plan.md b/docs/plans/2026-11-02-local-credential-listener-plan.md
new file mode 100644
index 000000000..130cf7008
--- /dev/null
+++ b/docs/plans/2026-11-02-local-credential-listener-plan.md
@@ -0,0 +1,55 @@
+# Local credential reaches only the real daemon (audit H1)
+
+**Goal:** a process of another account that takes the daemon's port (18473) or the bridge's (51793) while they
+restart learns nothing it can use. Requested by Scholes, task #2016; finding H1 in
+docs/security/2026-11-02-team-account-boundary.md (PR #2538).
+
+## Decisions
+
+1. **Unix socket only on macOS and Linux.** Hooks and CLI clients reach the daemon over `daemon-<port>.sock` (0600
+ in a 0700 folder). When the path fits and the socket is gone, the daemon is down: the client reports that and
+ never tries TCP, because the body (prompts, files) would reach the holder too. TCP stays only where a socket
+ cannot exist: a data folder too long for one. Windows is unchanged.
+2. **Hooks get their own token.** A new 0600 `hook-token` opens `/api/hook/*` and nothing else. Engine plugins
+ (OpenCode, Kilo, Pi, Amp) cannot use a socket from every runtime, so they send it over TCP. Copies already
+ loaded keep sending the credential, which hook routes still accept.
+3. **A credential or key heard is useless.** MCP clients only speak HTTP to the address in their config, and old
+ clients, Store agents and Desktop's fallback still send the credential, so hearing alone must open nothing.
+ The daemon and the bridge accept a credential or key over TCP only from a connection this OS account owns:
+ `/proc/net/tcp` on Linux, `lsof -u` on macOS (88 ms measured, once per connection, and only after the secret
+ matched, so a stranger cannot make it spawn anything). A lookup that fails refuses.
+
+## Steps (test first)
+
+1. `lib/peerAccount.ts`, with real same-account and absent-peer tests.
+2. `hook-token` in `lib/hookAuth.ts`; hookServer, localWsServer and bridge use both.
+3. `lib/localTransport.ts`: socket lookup, fetch over the socket, WebSocket target. `localCredentialHeaders` gives
+ nothing when a socket can exist, so no sender can leak by mistake.
+4. notify.mjs posts over the socket; plugins read `hook-token`.
+5. Convert every CLI sender of the credential.
+6. Invert "H1, still open" once #2538 lands; until then the same test is in `src/team/localCredential.spec.ts`.
+
+## Design
+
+- **Growth:** one 43-byte file per data folder; the peer cache is a WeakMap on the socket, gone with it.
+- **Concurrency:** token creation uses O_EXCL, and a loser reads the winner's. Lookups are one per connection.
+- **Read cost:** one lookup per TCP connection carrying a valid secret; none on the socket.
+- **Scale:** at 10x CLI TCP calls lookups cost CPU, but converted clients use the socket. First warning: the
+ `[peer]` refusal log line.
+- **Compatibility:** an old daemon accepts the new hook over its socket, which still carries the credential. Old
+ clients over TCP work from this account. A new CLI with an old daemon uses the socket, which old daemons have.
+- **Migration + rollback:** `hook-token` is made at start. Rolling back leaves an unused file; plugins are
+ reinstalled at start.
+- **Audience:** the server enforces it, by the peer's OS account.
+- **Identity:** the peer's OS uid, never a login.
+- **Failure:** a failed lookup refuses with a logged reason; a taken bridge port is logged.
+- **Platforms:** macOS and Linux change. Windows keeps its proven pipe and has no peer lookup.
+
+## Left open, on purpose
+
+- An MCP client still sends its key and tool calls to whoever holds 51793. The key opens nothing for them, but
+ they can read those calls and answer them falsely. Closing that needs a stdio shim: its own task.
+- A plugin's session-start body and `hook-token` reach a holder of 18473, as does any hook in a data folder too
+ long for a socket. The holder hears them, but the daemon refuses the token from another account.
+- Store agents, companions and Desktop's fallback still send the credential over TCP. It opens nothing for another
+ account, but they should move to the socket: follow-up task.
diff --git a/docs/security/2026-11-02-team-account-boundary.md b/docs/security/2026-11-02-team-account-boundary.md
index e788a1bdf..40a73f7e2 100644
--- a/docs/security/2026-11-02-team-account-boundary.md
+++ b/docs/security/2026-11-02-team-account-boundary.md
@@ -14,7 +14,7 @@ Team agent the owner's full rights (H1, H2), and files and command lines the own
| ID | Rating | Finding | Status |
|---|---|---|---|
-| H1 | **High** | The owner's local credential goes to whoever holds the daemon's port | Proved with the real hook, fix requested |
+| H1 | **High** | The owner's local credential goes to whoever holds the daemon's port | Fixed for hooks, the CLI and Desktop (task #2016); what stays open is under its fix |
| H2 | **High** | A Team agent's branch runs with the owner's rights when an owner's agent builds it | Read in code, fix requested |
| M1 | **Medium** | The owner's files in the shared `/tmp` are readable, and can be planted | Seen on the Mac Studio, fix requested |
| M2 | **Medium** | Tokens on tmux's command line show in `ps` to every account | Seen on the Mac Studio, fix requested |
@@ -60,6 +60,12 @@ plain listener on the port. The listener ran as this user, in a fixture. Neither
Windows' pipe does (`lib/windows/pipeAuth.ts`). That covers the CLI's and Desktop's clients: a token for hooks alone would leave
them open. Same for the bridge's key.
+**Fixed (task #2016):** on macOS and Linux, hooks, the CLI and Desktop use only the socket while one can exist. Hooks have their own
+token that opens the hook routes alone. A credential or bridge key over TCP counts only from a process of this OS account
+(`lib/peerAccount.ts`). The bridge moves off a port another account holds and tells agents. The refusal is tested against a real other account (`nobody`) on CI's Linux; on macOS only
+with a stand-in for the lookup. No real Team account or reboot was tried. **Still open:** an MCP client sends its tool calls to
+whoever holds its bridge address, who can answer them falsely; an engine plugin's session-start and hook token reach whoever holds the daemon's port, who hears them but cannot use the token from another account; and Store agents, companions and old clients still send the credential over TCP, where it opens nothing for another account.
+
### H2. A Team agent's branch runs with the owner's rights (High)
A Team agent gets a GitHub token that may write (`backend/src/github/app.ts:14`), so it can push a branch. The project's workflow then
diff --git a/mobile/lib/swarm/swarm_message_row.dart b/mobile/lib/swarm/swarm_message_row.dart
index 7b6932ef7..f11680050 100644
--- a/mobile/lib/swarm/swarm_message_row.dart
+++ b/mobile/lib/swarm/swarm_message_row.dart
@@ -467,13 +467,7 @@ class SwarmMessageRow extends StatelessWidget {
label: inThread ? 'Reply in thread' : 'Reply',
onTap: reply,
),
- SwarmSmallButton(
- icon: LucideIcons.copy,
- label: 'Copy',
- onTap: () => unawaited(
- Clipboard.setData(ClipboardData(text: message.text)),
- ),
- ),
+ SwarmCopyButton(text: message.text),
],
),
),
@@ -782,6 +776,59 @@ class SwarmSmallButton extends StatelessWidget {
}
}
+/// How long Copy reads Copied after a copy.
+const kSwarmCopiedFor = Duration(seconds: 3);
+
+/// A message's Copy (Tony, 11-02): once the clipboard has [text] it reads
+/// Copied with a check for [kSwarmCopiedFor]. Taps meanwhile neither copy again
+/// nor restart that time. A copy that failed stays Copy, to try again.
+class SwarmCopyButton extends StatefulWidget {
+ const SwarmCopyButton({super.key, required this.text});
+
+ final String text;
+
+ @override
+ State<SwarmCopyButton> createState() => _SwarmCopyButtonState();
+}
+
+class _SwarmCopyButtonState extends State<SwarmCopyButton> {
+ bool _copying = false;
+ Timer? _reset;
+
+ bool get _copied => _reset != null;
+
+ Future<void> _copy() async {
+ if (_copying || _copied) return;
+ _copying = true;
+ try {
+ await Clipboard.setData(ClipboardData(text: widget.text));
+ } on PlatformException {
+ return;
+ } finally {
+ _copying = false;
+ }
+ if (!mounted) return;
+ setState(() {
+ _reset = Timer(kSwarmCopiedFor, () {
+ if (mounted) setState(() => _reset = null);
+ });
+ });
+ }
+
+ @override
+ void dispose() {
+ _reset?.cancel();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => SwarmSmallButton(
+ icon: _copied ? LucideIcons.check : LucideIcons.copy,
+ label: _copied ? 'Copied' : 'Copy',
+ onTap: () => unawaited(_copy()),
+ );
+}
+
/// A file's size as a chat shows it: whole kilobytes, rounded up, or megabytes to one place.
String swarmFileSize(int bytes) {
final kb = (bytes / 1024).ceil();
diff --git a/mobile/test/swarm/swarm_chat_test.dart b/mobile/test/swarm/swarm_chat_test.dart
index b109c6e78..85eb61c17 100644
--- a/mobile/test/swarm/swarm_chat_test.dart
+++ b/mobile/test/swarm/swarm_chat_test.dart
@@ -2293,6 +2293,41 @@ void main() {
expect(key('swarm-reply-bar'), findsNothing);
});
+ testWidgets('in the main chat, Copy on a message says Copied, then Copy '
+ 'again (Tony, 11-02)', (tester) async {
+ final copied = <String?>[];
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {
+ if (call.method == 'Clipboard.setData') {
+ copied.add((call.arguments as Map)['text'] as String?);
+ }
+ return null;
+ });
+ addTearDown(
+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, null),
+ );
+ const words = 'The build is green';
+ await pump(tester, backend([message('m1', 1, text: words)]));
+ await tester.tap(find.text(words));
+ await tester.pumpAndSettle();
+
+ Finder inRow(String label) => find.descendant(
+ of: key('swarm-message-m1'),
+ matching: find.text(label),
+ );
+ await tester.tap(inRow('Copy'));
+ await tester.pumpAndSettle();
+ expect(copied, [words]);
+ expect(inRow('Copied'), findsOneWidget);
+
+ await tester.tap(inRow('Copied'));
+ await tester.pump(kSwarmCopiedFor);
+ await tester.pump();
+ expect(copied, [words], reason: 'one copy');
+ expect(inRow('Copy'), findsOneWidget);
+ });
+
testWidgets('in a thread, a tap on a message offers Copy, as in the chat, '
'and Copy copies its text (Dee, 11-01)', (tester) async {
String? copied;
@@ -2322,6 +2357,14 @@ void main() {
await tester.tap(copy);
await tester.pumpAndSettle();
expect(copied, text);
+ expect(
+ find.descendant(
+ of: key('swarm-thread-message-$id'),
+ matching: find.text('Copied'),
+ ),
+ findsOneWidget,
+ reason: '$id says it copied',
+ );
}
});
diff --git a/mobile/test/swarm/swarm_copy_button_test.dart b/mobile/test/swarm/swarm_copy_button_test.dart
new file mode 100644
index 000000000..13e57c966
--- /dev/null
+++ b/mobile/test/swarm/swarm_copy_button_test.dart
@@ -0,0 +1,229 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/swarm/model.dart';
+import 'package:harness_mobile/swarm/swarm_message_row.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+/// Copy on a message says it worked (Tony, 11-02): Copied with a check for
+/// about 3 seconds, in the main chat and in threads. Taps meanwhile neither
+/// copy again nor restart the 3 seconds.
+void main() {
+ late List<String> copied;
+
+ /// What the clipboard does with a copy; by default it takes it at once.
+ late Future<void> Function() clipboard;
+
+ setUp(() {
+ copied = [];
+ clipboard = () async {};
+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, (call) async {
+ if (call.method == 'Clipboard.setData') {
+ copied.add((call.arguments as Map)['text'] as String);
+ await clipboard();
+ }
+ return null;
+ });
+ });
+ tearDown(
+ () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
+ .setMockMethodCallHandler(SystemChannels.platform, null),
+ );
+
+ Widget row(String id, String text, {bool inThread = false}) => MaterialApp(
+ home: Scaffold(
+ body: ListView(
+ children: [
+ SwarmMessageRow(
+ message: SuperTabMessage.fromJson({
+ 'id': id,
+ 'conversationId': 'g1',
+ 'text': text,
+ 'sequence': 1,
+ 'author': {'kind': 'agent', 'id': 'agent-lead', 'name': 'Lead'},
+ 'createdAt': DateTime.utc(2026, 11, 2).toIso8601String(),
+ }),
+ name: 'River',
+ look: (picture: null, status: null),
+ role: 'PM',
+ mentions: SwarmMentions(const []),
+ grouped: false,
+ lit: false,
+ quote: null,
+ actions: true,
+ onTap: () {},
+ onReply: () {},
+ inThread: inThread,
+ ),
+ ],
+ ),
+ ),
+ );
+
+ void expectCopy(WidgetTester tester) {
+ expect(find.text('Copy'), findsOneWidget);
+ expect(find.text('Copied'), findsNothing);
+ expect(find.byIcon(LucideIcons.copy), findsOneWidget);
+ expect(find.byIcon(LucideIcons.check), findsNothing);
+ }
+
+ void expectCopied(WidgetTester tester) {
+ expect(find.text('Copied'), findsOneWidget);
+ expect(find.text('Copy'), findsNothing);
+ expect(find.byIcon(LucideIcons.check), findsOneWidget);
+ expect(find.byIcon(LucideIcons.copy), findsNothing);
+ }
+
+ for (final inThread in [false, true]) {
+ final where = inThread ? 'in a thread' : 'in the main chat';
+
+ testWidgets('$where, Copy reads Copied with a check, for about 3 seconds, '
+ 'then Copy again', (tester) async {
+ await tester.pumpWidget(row('m1', 'the words', inThread: inThread));
+ expectCopy(tester);
+
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expect(copied, ['the words']);
+ expectCopied(tester);
+
+ await tester.pump(const Duration(milliseconds: 2900));
+ expectCopied(tester);
+ await tester.pump(const Duration(milliseconds: 200));
+ expectCopy(tester);
+ });
+ }
+
+ testWidgets('taps while it says Copied neither copy again nor restart the '
+ '3 seconds', (tester) async {
+ await tester.pumpWidget(row('m1', 'the words'));
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+
+ for (var i = 0; i < 3; i++) {
+ await tester.pump(const Duration(milliseconds: 900));
+ await tester.tap(find.text('Copied'));
+ await tester.pump();
+ }
+ expect(copied, ['the words'], reason: 'one copy');
+ expectCopied(tester);
+
+ // 2.7 s gone: a restart on the last tap would hold it for 3 s more.
+ await tester.pump(const Duration(milliseconds: 400));
+ expectCopy(tester);
+ });
+
+ testWidgets('it copies again once it reads Copy again', (tester) async {
+ await tester.pumpWidget(row('m1', 'the words'));
+ await tester.tap(find.text('Copy'));
+ await tester.pump(const Duration(seconds: 3));
+ await tester.pump();
+ expectCopy(tester);
+
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expect(copied, ['the words', 'the words']);
+ expectCopied(tester);
+ });
+
+ testWidgets('a second tap while the clipboard is still taking the first '
+ 'copies once', (tester) async {
+ final taking = Completer<void>();
+ clipboard = () => taking.future;
+ await tester.pumpWidget(row('m1', 'the words'));
+
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expect(copied, ['the words']);
+ expectCopy(tester);
+
+ taking.complete();
+ await tester.pump();
+ await tester.pump();
+ expectCopied(tester);
+ });
+
+ testWidgets('a copy that failed never says Copied, and can be tried again', (
+ tester,
+ ) async {
+ clipboard = () async => throw PlatformException(code: 'clipboard');
+ await tester.pumpWidget(row('m1', 'the words'));
+
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ expectCopy(tester);
+
+ clipboard = () async {};
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expect(copied, ['the words', 'the words']);
+ expectCopied(tester);
+ });
+
+ testWidgets('the row showing another message is not Copied, and copies that '
+ 'message', (tester) async {
+ await tester.pumpWidget(row('m1', 'the words'));
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expectCopied(tester);
+
+ await tester.pumpWidget(row('m2', 'other words'));
+ expectCopy(tester);
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expect(copied, ['the words', 'other words']);
+ });
+
+ testWidgets('it copies the words the message has now', (tester) async {
+ await tester.pumpWidget(row('m1', 'the words'));
+ await tester.pumpWidget(row('m1', 'edited words'));
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expect(copied, ['edited words']);
+ });
+
+ testWidgets('the row leaving while it says Copied leaves nothing running', (
+ tester,
+ ) async {
+ await tester.pumpWidget(row('m1', 'the words'));
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expectCopied(tester);
+
+ await tester.pumpWidget(const SizedBox());
+ // A timer still running fails this test when it ends.
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('the row leaving while the clipboard is taking the copy changes '
+ 'nothing after it', (tester) async {
+ final taking = Completer<void>();
+ clipboard = () => taking.future;
+ await tester.pumpWidget(row('m1', 'the words'));
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+
+ await tester.pumpWidget(const SizedBox());
+ taking.complete();
+ await tester.pump();
+ await tester.pump();
+ expect(tester.takeException(), isNull);
+ });
+
+ testWidgets('a screen reader hears Copied too', (tester) async {
+ final semantics = tester.ensureSemantics();
+ await tester.pumpWidget(row('m1', 'the words'));
+ expect(find.bySemanticsLabel('Copy'), findsOneWidget);
+
+ await tester.tap(find.text('Copy'));
+ await tester.pump();
+ expect(find.bySemanticsLabel('Copied'), findsOneWidget);
+ semantics.dispose();
+ });
+}