The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Merge batch 11-02 1102-p: #2585 #2583 (#2595)
0xken15680b3224a573
diff --git a/cli/hook/notify.mjs b/cli/hook/notify.mjsindex 8a61e2351..c4f616c85 100644--- a/cli/hook/notify.mjs+++ b/cli/hook/notify.mjs@@ -294,15 +294,22 @@ function privateSocket(file) {* 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 socketIn(dataDir, port) {+ const beside = join(dataDir, `daemon-${port}.sock`)+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH_BYTES) return beside+ const short = join(homedir(), '.harness', 's', createHash('sha256').update(dataDir).digest('hex').slice(0, 16), `daemon-${port}.sock`)+ return Buffer.byteLength(short) <= MAX_SOCKET_PATH_BYTES ? short : null+}+function daemonSocket(port, dataDir) {- const named = join(dataDir, `daemon-${port}.sock`)- if (privateSocket(named)) return named+ const named = socketIn(dataDir, port)+ if (named && privateSocket(named)) return namedtry {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+ const socket = socketIn(dataDir, Number(configured))+ if (socket && JSON.parse(readPrivateStateFile(join(dataDir, name), 4096))?.port === port && privateSocket(socket)) return socket}} catch { /* An unreadable folder has no socket to offer. */ }return null@@ -312,14 +319,14 @@ function daemonSocket(port, dataDir) {* 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+ * this is the same as a failed post. A data folder too long to hold a socket has one under the home folder (socketIn). A home too long as well 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().dataDirif (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') }+ if (!socketIn(dataDir, port)) return { address: { host: '127.0.0.1', port }, token: readHookCredential('hook-token') }const socketPath = daemonSocket(port, dataDir)return socketPath ? { address: { socketPath }, token: readHookCredential() } : null}diff --git a/cli/src/agentClient/daemon.spec.ts b/cli/src/agentClient/daemon.spec.tsindex fefa089ea..3d2fad847 100644--- a/cli/src/agentClient/daemon.spec.ts+++ b/cli/src/agentClient/daemon.spec.ts@@ -5,7 +5,7 @@ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fimport { createServer } from 'node:net'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { connectSocket, openDaemon, whereFor, type ClientSocket } from './daemon.js'import { saveDaemonPort } from '../lib/daemonEndpoint.js'import { WebSocketServer } from 'ws'@@ -15,6 +15,10 @@ import { localSocketPath } from '../lib/localSocket.js'import { NOT_RUNNING, SANDBOXED } from '../lib/unreachable.js'import { newPipePath } from '../lib/windows/pipeAuth.js'+// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })+/** A real named pipe on Windows; a short Unix socket with the same auth name elsewhere. */function pipeFixture(): { path: string; close: () => void } {if (process.platform === 'win32') return { path: newPipePath(), close: () => {} }diff --git a/cli/src/agentClient/settings.spec.ts b/cli/src/agentClient/settings.spec.tsindex 0b6482307..3df8a778c 100644--- a/cli/src/agentClient/settings.spec.ts+++ b/cli/src/agentClient/settings.spec.ts@@ -1,10 +1,14 @@import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { describe, expect, it } from 'vitest'+import { describe, expect, it, beforeEach, afterEach, vi } from 'vitest'import { loadOrCreateHookCredential } from '../lib/hookAuth.js'import { settingsCommand, SETTINGS_SIGNED_OUT, SETTINGS_USAGE } from './settings.js'+// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })+/** This computer's daemon as `harness settings` meets it: its answers to `/api/agent-settings`, and what was asked. */function daemon(answer: (method: string, body: unknown) => { status: number; body: unknown } | Error, env: NodeJS.ProcessEnv = {}) {const asked: Array<{ url: string; method: string; headers: Record<string, string>; body: unknown }> = []diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex f34c7af0b..65d88b670 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -78,7 +78,7 @@ import { describeMasterStatus, readStatusFile } from './harnessd/master.js'import { namedNode } from './harnessd/processName.js'import { probeThisMaster, startMaster, startMasterInForeground } from './masterProcess.js'import { startServiceProcess } from './serviceProcess.js'-import { askDataFolderServer, isLocalSocketName, localSocketPath, refuseServedDataFolder, servedFolderDeps } from './lib/localSocket.js'+import { askDataFolderServer, isLocalSocketName, localSocketPath, refuseServedDataFolder, shortSocketFolder, servedFolderDeps } from './lib/localSocket.js'import { legacyDaemonStatus, localDaemonCall, localDaemonStatus } from './lib/daemonEndpoint.js'import { PipeUnproven } from './lib/windows/pipeClient.js'import { ptyManifestUrl, ptyPlatformKey, type PtyEntry } from './lib/windows/ptyPayload.js'@@ -1816,6 +1816,8 @@ function clearAdapterState(): void {if (isLocalSocketName(name) || /^daemon-\d+\.json$/.test(name)) rmSync(join(dir, name), { force: true })}} catch { /* no such directory */ }+ // A folder too long for a socket keeps its sockets here.+ rmSync(shortSocketFolder(dir), { recursive: true, force: true })}if (dataDir === cliDir) rmStateFiles(dataDir)else rmSync(dataDir, { recursive: true, force: true })diff --git a/cli/src/cliCommand.spec.ts b/cli/src/cliCommand.spec.tsindex 7948a85ae..00e9def70 100644--- a/cli/src/cliCommand.spec.ts+++ b/cli/src/cliCommand.spec.ts@@ -519,12 +519,15 @@ 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)- // A data folder too long to hold a socket: the one case on the port. With a socket, see lib/daemonEndpoint.spec.ts.+ // A data folder too long to hold a socket and a home too long as well: 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 })+ const HOME = join(root, 'h'.repeat(100))+ mkdirSync(HOME, { recursive: true })+ const status = await runAsync(root, ['remote-password', 'status', '--json'], { PORT, ADAPTER_DATA_DIR, HOME })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, ADAPTER_DATA_DIR })+ const sync = await runAsync(root, ['group', 'sync'], { PORT, ADAPTER_DATA_DIR, HOME })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.socket.spec.ts b/cli/src/cloud/bridge.socket.spec.tsindex 9cc223274..38645872f 100644--- a/cli/src/cloud/bridge.socket.spec.ts+++ b/cli/src/cloud/bridge.socket.spec.ts@@ -1,20 +1,21 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { chmodSync, mkdtempSync, writeFileSync } from 'node:fs'+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'import { createServer, type Server } from 'node:http'import type { AddressInfo } from 'node:net'-import { join } from 'node:path'+import { dirname, join } from 'node:path'import { bridgeKey, bridgeSocketPath, harnessKey, retireBridgeKey, rotateHarnessKey, KEY_GRACE_MS } from '../lib/connectors/agents.js'import { serveBridgeSocket } from '../lib/connectors/bridge.js'import type { LocalSocketServer } from '../lib/localSocket.js'import { Store } from '../lib/connectors/store.js'import { fakeCore } from '../testing/fakeCore.js'import { startConnectors } from '../services/connectors.js'-import { fetchOverSocket, socketIsPrivate } from '../lib/localTransport.js'+import { daemonFetch, fetchOverSocket, socketIsPrivate } from '../lib/localTransport.js'+import { unixSocketPath } from '../lib/localSocket.js'import { bridgeRoute, connectionsBridge } from './bridge.js'import { McpClient } from './mcp.js'const closers: Array<() => unknown> = []-afterEach(async () => { vi.useRealTimers(); for (const close of closers.splice(0)) await close() })+afterEach(async () => { vi.useRealTimers(); for (const close of closers.splice(0)) await close(); rmSync(home, { recursive: true, force: true }) })let vault: Store, env: NodeJS.ProcessEnv, home: stringbeforeEach(() => {@@ -126,13 +127,67 @@ describe('cloud agents and the bridge', () => {expect(answer.status).toBe(200)})- it('where no socket can be, the route is the port, as before', () => {+ it('a long vault\'s route is its short socket, and only a home too long as well is the port', () => {const long = new Store(join(home, 'x'.repeat(120)), env)+ expect(bridgeSocketPath(long)).toMatch(/\/\.harness\/s\/[0-9a-f]{16}\/bridge\.sock$/)+ expect(bridgeRoute(long).base).toMatch(/^http:\/\/connections\.invalid\//)+ vi.stubEnv('HOME', `/${'h'.repeat(120)}`)+ closers.push(() => vi.unstubAllEnvs())expect(bridgeSocketPath(long)).toBeNull()expect(bridgeRoute(long).base).toMatch(/^http:\/\/127\.0\.0\.1:\d+\//)})})+describe('a long data folder\'s short socket', () => {+ it('is not used when it is not private: nothing is sent to it, and nothing to the port', async () => {+ const hold = await holder()+ const data = join(home, 'd'.repeat(100))+ vi.stubEnv('HOME', home)+ closers.push(() => vi.unstubAllEnvs())+ const path = unixSocketPath(data, hold.port)!+ expect(path).toContain('/.harness/s/')+ const heard: string[] = []+ const server = createServer((request, response) => { heard.push(String(request.url)); response.writeHead(200).end('{}') })+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })+ await new Promise<void>(ready => server.listen(path, ready))+ closers.push(() => new Promise(done => { server.closeAllConnections(); server.close(done) }))+ const send = daemonFetch(data, hold.port)+ chmodSync(path, 0o600)+ expect((await send(`http://127.0.0.1:${hold.port}/api/status`)).status).toBe(200)+ expect(heard).toHaveLength(1)+ chmodSync(path, 0o666)+ await expect(send(`http://127.0.0.1:${hold.port}/api/status`)).rejects.toThrow()+ expect(heard).toHaveLength(1)+ expect(hold.heard).toEqual([])+ })+})++describe('a long data folder whose daemon was given another port', () => {+ it('follows its record to the short socket, and refuses it when it is not private', async () => {+ const hold = await holder()+ const data = join(home, 'd'.repeat(100))+ mkdirSync(data, { recursive: true, mode: 0o700 })+ vi.stubEnv('HOME', home)+ closers.push(() => vi.unstubAllEnvs())+ // Configured for 1, given the holder's port: the socket is named for the one it was configured with.+ writeFileSync(join(data, 'daemon-1.json'), JSON.stringify({ port: hold.port }), { mode: 0o600 })+ const path = unixSocketPath(data, 1)!+ const heard: string[] = []+ const server = createServer((request, response) => { heard.push(String(request.url)); response.writeHead(200).end('{}') })+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 })+ await new Promise<void>(ready => server.listen(path, ready))+ closers.push(() => new Promise(done => { server.closeAllConnections(); server.close(done) }))+ chmodSync(path, 0o600)+ const send = daemonFetch(data, hold.port)+ expect((await send(`http://127.0.0.1:${hold.port}/api/status`)).status).toBe(200)+ expect(heard).toHaveLength(1)+ chmodSync(path, 0o666)+ await expect(send(`http://127.0.0.1:${hold.port}/api/status`)).rejects.toThrow()+ expect(heard).toHaveLength(1)+ expect(hold.heard).toEqual([])+ })+})+describe('the keys that crossed the port', () => {it('the service takes Harness\'s key on its socket and not on its port, and the agents\' old key on its port for now', async () => {const agents = bridgeKey(vault), stale = harnessKey(vault)diff --git a/cli/src/devices/client.spec.ts b/cli/src/devices/client.spec.tsindex 089dc81d4..b2cd1f19b 100644--- a/cli/src/devices/client.spec.ts+++ b/cli/src/devices/client.spec.ts@@ -1,4 +1,4 @@-import { describe, expect, it, vi } from 'vitest'+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'import { EventEmitter } from 'node:events'import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'@@ -6,6 +6,10 @@ import { join } from 'node:path'import { loadOrCreateHookCredential } from '../lib/hookAuth.js'import { devicesCommand, deviceRequest, type DevicesClientDeps } from './client.js'+// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })+const snapshot = (brightness = 80) => ({ status: { devices: [{ id: 'usb', attached: true, settings: { brightness } }] } })function fixture() {const request = vi.fn(async (_id: string, _type: string, _payload?: Record<string, unknown>) => snapshot() as Record<string, unknown>)diff --git a/cli/src/devicesCommand.spec.ts b/cli/src/devicesCommand.spec.tsindex 468fc6f2b..d3781d3bd 100644--- a/cli/src/devicesCommand.spec.ts+++ b/cli/src/devicesCommand.spec.ts@@ -1,12 +1,15 @@+import { mkdirSync as nodeMkdir } from 'node:fs'import { execFileSync, spawn, spawnSync } from 'child_process'import { createServer, type Server } from 'http'import { createWriteStream, mkdtempSync, rmSync } from 'fs'import { tmpdir } from 'os'import { join } from 'path'import { fileURLToPath } from 'url'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, beforeEach, vi } from 'vitest'import { useBundledCli } from './__fixtures__/bundledCli.js'+const mkdirSyncReturning = (path: string): string => { nodeMkdir(path, { recursive: true }); return path }+const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))const cli = useBundledCli()const DAY = 86_400_000@@ -85,7 +88,8 @@ function cliEnv(port: number): NodeJS.ProcessEnv {dirs.push(root)return {...process.env,- HOME: root,+ // Too long as well: a folder too long for a socket otherwise has one under the home folder.+ HOME: join(mkdirSyncReturning(join(root, 'h'.repeat(100)))),HARNESS_AUTH_DIR: join(root, 'auth'),// 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)),diff --git a/cli/src/e2e/harnessLocal.spec.ts b/cli/src/e2e/harnessLocal.spec.tsindex 7f8c33ad6..93fd1ab64 100644--- a/cli/src/e2e/harnessLocal.spec.ts+++ b/cli/src/e2e/harnessLocal.spec.ts@@ -3,11 +3,15 @@ import type { AddressInfo } from 'node:net'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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { env } from '../config/env.js'import { startHookServer, type HookServerHandlers } from '../hookServer.js'import { machineId } from './harnessLocal.js'+// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })+// The e2e reads the daemon it drives through the daemon's own local API, which since guest machine sharing// (bc7f56ff9) answers the full /api/status only to a caller that shows the local credential. grid-dev's run// stopped at "daemon /api/status has no machineId" the day its daemon updated to 0.4.21 (2026-10-19), becausediff --git a/cli/src/engines/__fixtures__/native-version.golden.json b/cli/src/engines/__fixtures__/native-version.golden.jsonindex 5434572a0..45bb5c9ff 100644--- a/cli/src/engines/__fixtures__/native-version.golden.json+++ b/cli/src/engines/__fixtures__/native-version.golden.json@@ -1,172 +1,172 @@{- "linux:v1": {- "installed": true,- "first": 1,- "repeat": 1,- "calls": [- [- "/fixture/bin/opencode",- [- "--version"- ]- ]- ],- "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-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-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"- }+ "linux:v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"]- },- "linux:v2": {- "installed": true,- "first": 2,- "repeat": 2,- "calls": [- [- "/fixture/bin/opencode",- [- "--version"- ]- ]- ],- "files": [- {- "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",- "source": null- },- {- "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-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"- }+ ]+ ],+ "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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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"+ }+ ]+ },+ "linux:v2": {+ "installed": true,+ "first": 2,+ "repeat": 2,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"]- },- "linux:downgrade-v1": {- "installed": true,- "first": 1,- "repeat": 1,- "calls": [- [- "/fixture/bin/opencode",- [- "--version"- ]- ]- ],- "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-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-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"- }+ ]+ ],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": null+ },+ {+ "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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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"+ }+ ]+ },+ "linux:downgrade-v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"]- },- "linux:current-v1": {- "installed": true,- "first": 1,- "repeat": 1,- "calls": [],- "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-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-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"- }+ ]+ ],+ "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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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"+ }+ ]+ },+ "linux:current-v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [],+ "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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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"+ }+ ]+ },+ "darwin:v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"]- },- "darwin:v1": {- "installed": true,- "first": 1,- "repeat": 1,- "calls": [- [- "/fixture/bin/opencode",- [- "--version"- ]- ]- ],- "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-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-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"- }+ ]+ ],+ "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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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"+ }+ ]+ },+ "darwin:v2": {+ "installed": true,+ "first": 2,+ "repeat": 2,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"]- },- "darwin:v2": {- "installed": true,- "first": 2,- "repeat": 2,- "calls": [- [- "/fixture/bin/opencode",- [- "--version"- ]- ]- ],- "files": [- {- "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",- "source": null- },- {- "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-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"- }+ ]+ ],+ "files": [+ {+ "file": "<root>/HOME/.config/opencode/plugin/launcher-register.js",+ "source": null+ },+ {+ "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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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"+ }+ ]+ },+ "darwin:downgrade-v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [+ [+ "/fixture/bin/opencode",+ [+ "--version"]- },- "darwin:downgrade-v1": {- "installed": true,- "first": 1,- "repeat": 1,- "calls": [- [- "/fixture/bin/opencode",- [- "--version"- ]- ]- ],- "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-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-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"- }- ]- },- "darwin:current-v1": {- "installed": true,- "first": 1,- "repeat": 1,- "calls": [],- "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-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-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"- }- ]- }+ ]+ ],+ "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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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"+ }+ ]+ },+ "darwin:current-v1": {+ "installed": true,+ "first": 1,+ "repeat": 1,+ "calls": [],+ "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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"<root>/ADAPTER_DATA_DIR/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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.jsonindex dc7b65500..81c69e336 100644--- a/cli/src/engines/__fixtures__/other-hooks.golden.json+++ b/cli/src/engines/__fixtures__/other-hooks.golden.json@@ -14,13 +14,8 @@"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",- "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",- "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",- "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",@@ -65,7 +60,24 @@"ea6df51da052bef4": "{\n \"theirs\": {\n \"enabled\": true,\n \"Stop\": [\n {\n \"type\": \"command\",\n \"command\": \"foreign-stop\"\n }\n ]\n }\n}\n","f1d871558bc6b03b": "{\n \"version\": 1,\n \"hooks\": {\n \"sessionStart\": [\n {\n \"type\": \"command\",\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 copilot --copilot-event sessionStart\"\n }\n ],\n \"userPromptSubmitted\": [\n {\n \"type\": \"command\",\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 copilot --copilot-event userPromptSubmitted\"\n }\n ],\n \"agentStop\": [\n {\n \"type\": \"command\",\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 copilot --copilot-event agentStop\"\n }\n ],\n \"sessionEnd\": [\n {\n \"type\": \"command\",\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 copilot --copilot-event sessionEnd\"\n }\n ]\n }\n}\n","df185b4913284039": "{\"version\":1,\"hooks\":{\"sessionStart\":[{\"type\":\"command\",\"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 copilot --copilot-event sessionStart\"}],\"userPromptSubmitted\":[{\"type\":\"command\",\"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 copilot --copilot-event userPromptSubmitted\"}],\"agentStop\":[{\"type\":\"command\",\"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 copilot --copilot-event agentStop\"}],\"sessionEnd\":[{\"type\":\"command\",\"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 copilot --copilot-event sessionEnd\"}]}}",- "3d5035418d5226f3": "{\n \"version\": 1,\n \"hooks\": {\n \"sessionStart\": [\n {\n \"type\": \"command\",\n \"command\": \"foreign-start\"\n }\n ]\n }\n}\n"+ "3d5035418d5226f3": "{\n \"version\": 1,\n \"hooks\": {\n \"sessionStart\": [\n {\n \"type\": \"command\",\n \"command\": \"foreign-start\"\n }\n ]\n }\n}\n",+ "ee4db07d82574649": "// session-register — auto-installed by the machine adapter. Binds this Pi session to the local\n// machine daemon (127.0.0.1:19474) 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\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\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 harnessFetch(\"http://127.0.0.1:19474/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",+ "fe5dc71d557d28f9": "// 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\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\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 harnessFetch('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",+ "148abe7c5b7b3a8d": "// 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 \"\" } }\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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",+ "c9014cb63a914d05": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.0.0.1:19474) 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(\"/opt/old/data/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"/opt/old/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"http://127.0.0.1:19474/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",+ "e36fbe8da025a902": "// 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 \"\" } }\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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",+ "f2a0ee32c639505c": "// 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\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\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 harnessFetch(\"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}",+ "a89625233da4b636": "// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local\n// machine daemon (127.0.0.1:19474) 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\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\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 harnessFetch('http://127.0.0.1:19474/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",+ "f9bdf2bb7e210715": "// session-register — auto-installed by the machine adapter. Binds this Pi session to the local\n// machine daemon (127.0.0.1:19474) 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\nconst harnessSocket = \"/opt/old/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\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(\"/opt/old/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 harnessFetch(\"http://127.0.0.1:19474/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",+ "4882239f7d22747c": "// 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\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\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 harnessFetch('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}",+ "4a70bbe32af8193d": "// session-register — auto-installed by the machine adapter. Binds this Amp thread to the local\n// machine daemon (127.0.0.1:19474) 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\nconst harnessSocket = \"/opt/old/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\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(\"/opt/old/data/hook-token\", 'utf8').trim()\n if (!token) return\n const res = await harnessFetch('http://127.0.0.1:19474/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",+ "b2d6dd4165be50af": "// session-register — auto-installed by the machine adapter. Binds this Kilo session to the\n// local machine daemon (127.0.0.1:19474) 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(\"/opt/old/data/hook-token\", \"utf8\").trim() } catch { return \"\" } }\nconst harnessSocket = \"/opt/old/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"http://127.0.0.1:19474/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",+ "f9d10aad86a45fce": "// 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 \"\" } }\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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",+ "180a82db1b501779": "// 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 \"\" } }\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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}",+ "a1d771dcda304b56": "// 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\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\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 harnessFetch(\"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",+ "ae28f4646a6e33eb": "// 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 \"\" } }\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"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}",+ "d7b9e284664f72ec": "// session-register (OpenCode 2 TUI) — auto-installed by the machine adapter. Tells the local machine\n// daemon (127.0.0.1:19474) 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 \"\" } }\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"http://127.0.0.1:19474/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",+ "6a284957b3f02006": "// session-register — auto-installed by the machine adapter. Binds this Kilo session to the\n// local machine daemon (127.0.0.1:19474) 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 \"\" } }\nconst harnessSocket = \"<root>/data/daemon-18473.sock\"\nconst harnessFetch = async (url, init) => {\n if (!harnessSocket) return fetch(url, init)\n const { lstatSync } = await import(\"node:fs\")\n const { dirname } = await import(\"node:path\")\n const { request } = await import(\"node:http\")\n const uid = process.getuid?.()\n const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))\n if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0\n || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error(\"The Harness socket is not private.\")\n return new Promise((resolve, reject) => {\n const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,\n headers: { ...init.headers, \"content-length\": String(Buffer.byteLength(init.body)) } }, (answer) => {\n answer.resume()\n answer.on(\"end\", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))\n answer.on(\"error\", reject)\n })\n asked.on(\"error\", reject)\n asked.end(init.body)\n })\n}\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 harnessFetch(\"http://127.0.0.1:19474/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"},"outcomes": {"cursor: no file": {@@ -1037,7 +1049,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -1077,7 +1089,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -1597,7 +1609,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -1636,7 +1648,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -1676,7 +1688,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -1716,7 +1728,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -1804,7 +1816,7 @@"elsewhere/real": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -1963,7 +1975,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "444",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -2238,7 +2250,7 @@"home/.config/opencode/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "86391f37154d09af"+ "text": "148abe7c5b7b3a8d"},"home/.config/opencode/plugins": {"type": "dir",@@ -2251,7 +2263,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -2289,7 +2301,7 @@"home/.config/opencode/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "86391f37154d09af"+ "text": "148abe7c5b7b3a8d"},"home/.config/opencode/plugins": {"type": "dir",@@ -2302,7 +2314,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -2342,7 +2354,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -2387,7 +2399,7 @@"home/.config/opencode/plugins/launcher-register/tui.js": {"type": "file","mode": "644",- "text": "b42eab635c185981"+ "text": "f9d10aad86a45fce"}}},@@ -2522,7 +2534,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "6f9caf1088585abe"+ "text": "e36fbe8da025a902"}}},@@ -2558,7 +2570,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "6f9caf1088585abe"+ "text": "e36fbe8da025a902"}}},@@ -3026,7 +3038,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "6f9caf1088585abe"+ "text": "e36fbe8da025a902"}}},@@ -3061,7 +3073,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "6f9caf1088585abe"+ "text": "e36fbe8da025a902"}}},@@ -3097,7 +3109,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "6f9caf1088585abe"+ "text": "e36fbe8da025a902"}}},@@ -3133,7 +3145,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "644",- "text": "6f9caf1088585abe"+ "text": "e36fbe8da025a902"}}},@@ -3213,7 +3225,7 @@"elsewhere/real": {"type": "file","mode": "644",- "text": "6f9caf1088585abe"+ "text": "e36fbe8da025a902"}}},@@ -3356,7 +3368,7 @@"home/.config/kilo/plugin/launcher-register.js": {"type": "file","mode": "444",- "text": "6f9caf1088585abe"+ "text": "e36fbe8da025a902"}}},@@ -3604,7 +3616,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "2fdcafede309e332"+ "text": "a1d771dcda304b56"}}},@@ -3640,7 +3652,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "2fdcafede309e332"+ "text": "a1d771dcda304b56"}}},@@ -4108,7 +4120,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "2fdcafede309e332"+ "text": "a1d771dcda304b56"}}},@@ -4143,7 +4155,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "2fdcafede309e332"+ "text": "a1d771dcda304b56"}}},@@ -4179,7 +4191,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "2fdcafede309e332"+ "text": "a1d771dcda304b56"}}},@@ -4215,7 +4227,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "644",- "text": "2fdcafede309e332"+ "text": "a1d771dcda304b56"}}},@@ -4295,7 +4307,7 @@"elsewhere/real": {"type": "file","mode": "644",- "text": "2fdcafede309e332"+ "text": "a1d771dcda304b56"}}},@@ -4438,7 +4450,7 @@"home/.pi/agent/extensions/launcher-register.ts": {"type": "file","mode": "444",- "text": "2fdcafede309e332"+ "text": "a1d771dcda304b56"}}},@@ -4687,7 +4699,7 @@"home/.config/amp/plugins/launcher-register.ts": {"type": "file","mode": "644",- "text": "2a463c0e77737a30"+ "text": "fe5dc71d557d28f9"},"home/.harness": {"type": "dir",@@ -4740,7 +4752,7 @@"home/.config/amp/plugins/launcher-register.ts": {"type": "file","mode": "644",- "text": "2a463c0e77737a30"+ "text": "fe5dc71d557d28f9"},"home/.harness": {"type": "dir",@@ -5429,7 +5441,7 @@"home/.config/amp/plugins/launcher-register.ts": {"type": "file","mode": "644",- "text": "2a463c0e77737a30"+ "text": "fe5dc71d557d28f9"},"home/.harness": {"type": "dir",@@ -5480,7 +5492,7 @@"home/.config/amp/plugins/launcher-register.ts": {"type": "file","mode": "644",- "text": "2a463c0e77737a30"+ "text": "fe5dc71d557d28f9"}}},@@ -5517,7 +5529,7 @@"home/.config/amp/plugins/launcher-register.ts": {"type": "file","mode": "644",- "text": "2a463c0e77737a30"+ "text": "fe5dc71d557d28f9"},"home/.harness": {"type": "dir",@@ -5570,7 +5582,7 @@"home/.config/amp/plugins/launcher-register.ts": {"type": "file","mode": "644",- "text": "2a463c0e77737a30"+ "text": "fe5dc71d557d28f9"},"home/.harness": {"type": "dir",@@ -5683,7 +5695,7 @@"elsewhere/real": {"type": "file","mode": "644",- "text": "2a463c0e77737a30"+ "text": "fe5dc71d557d28f9"}}},@@ -5877,7 +5889,7 @@"home/.config/amp/plugins/launcher-register.ts": {"type": "file","mode": "444",- "text": "2a463c0e77737a30"+ "text": "fe5dc71d557d28f9"}}},diff --git a/cli/src/engines/amp/contract.ts b/cli/src/engines/amp/contract.tsindex 63649f588..7f1395772 100644--- a/cli/src/engines/amp/contract.ts+++ b/cli/src/engines/amp/contract.ts@@ -1,5 +1,6 @@import { join as hookPath } from 'node:path'import { env as hookEnvironment } from '../../config/env.js'+import { PLUGIN_FETCH } from '../kit/pluginFetch.js'/*** What the core knows of Amp without loading its code: declared data, read by the kit* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports no Amp interpreter.@@ -28,7 +29,9 @@ const SESSIONS_DIR = `,JSON.stringify(hookEnvironment.AMP_SESSIONS_DIR),`-export default function (amp: any) {+`,+...PLUGIN_FETCH,+`export default function (amp: any) {const pane = process.env.TMUX_PANEif (!pane) return@@ -73,7 +76,7 @@ export default function (amp: any) {{ argument: 'credential' },`, 'utf8').trim()if (!token) return- const res = await fetch('http://127.0.0.1:`,+ const res = await harnessFetch('http://127.0.0.1:`,{ argument: 'port' },`/api/hook/session-start', {method: 'POST',diff --git a/cli/src/engines/kilo/contract.ts b/cli/src/engines/kilo/contract.tsindex 5ef7a9723..9ea1e1576 100644--- a/cli/src/engines/kilo/contract.ts+++ b/cli/src/engines/kilo/contract.ts@@ -1,5 +1,6 @@import { join as hookPath } from 'node:path'import { env as hookEnvironment } from '../../config/env.js'+import { PLUGIN_FETCH } from '../kit/pluginFetch.js'/*** What the core knows of Kilo without loading its code: declared data, read by the kit* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing.@@ -24,7 +25,9 @@ import { readFileSync } from "node:fs"const hookToken = () => { try { return readFileSync(`,{ argument: 'credential' },`, "utf8").trim() } catch { return "" } }-export const MachineRegister = async ({ directory, worktree, project, client }) => {+`,+...PLUGIN_FETCH,+`export const MachineRegister = async ({ directory, worktree, project, client }) => {const seen = new Set()const post = async (sessionID) => {const pane = process.env.TMUX_PANE@@ -34,7 +37,7 @@ export const MachineRegister = async ({ directory, worktree, project, client })if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) returnseen.add(sessionID)try {- await fetch("http://127.0.0.1:`,+ await harnessFetch("http://127.0.0.1:`,{ argument: 'port' },`/api/hook/session-start", {method: "POST",diff --git a/cli/src/engines/kit/nativePlugin.ts b/cli/src/engines/kit/nativePlugin.tsindex a328262d3..fa10882cc 100644--- a/cli/src/engines/kit/nativePlugin.ts+++ b/cli/src/engines/kit/nativePlugin.ts@@ -4,16 +4,17 @@ import { HookPreparationHeld, inspectHookFile, type HookFilePublication, runHookexport interface NativePlugin {file: string- template: readonly (string | { argument: 'port' | 'credential' | 'version' })[]+ template: readonly (string | { argument: 'port' | 'credential' | 'version' | 'socket' })[]directories?: readonly { path: string; mode?: number }[]messages: { current: string; installed: string; after: readonly string[]; failed: string }}-export interface NativePluginValues { port: string; credential: string; version: string }+/** `socket`: the daemon's private socket as JSON, or `null` where it can have none (Windows, or a home too long as well). Absent reads as `null`. */+export interface NativePluginValues { port: string; credential: string; version: string; socket?: string }export interface PreparedNativePlugin { verify(): void; commit(attempt: HookPreparationAttempt): Promise<HookFilePublication> }/** Joining parts once keeps a path's contents literal, even when it resembles a template argument. */export function nativePluginSource(rule: NativePlugin, values: NativePluginValues): string {- return rule.template.map(part => typeof part === 'string' ? part : values[part.argument]).join('')+ return rule.template.map(part => typeof part === 'string' ? part : values[part.argument] ?? 'null').join('')}/** Observe every destination before a multi-file installation changes any of them. */diff --git a/cli/src/engines/kit/pluginFetch.ts b/cli/src/engines/kit/pluginFetch.tsnew file mode 100644index 000000000..e2344274a--- /dev/null+++ b/cli/src/engines/kit/pluginFetch.ts@@ -0,0 +1,34 @@+// Plain text and nothing else: an engine's contract imports this, and contracts load no other code (architecture.spec.ts).++/**+ * `fetch` for a plugin's one post to the daemon. Any account can bind the TCP port while the daemon restarts, and would hear the hook token+ * and the session in it (audit H1), so where a socket can be the post goes over it, and only if it is this account's, owner only, in a folder+ * nobody else can write to. Otherwise it fails as a post does, and nothing goes to the port. `node:http` because a plugin's runtime (Bun, Node)+ * has it, where `fetch`'s socket option is Bun's alone.+ */+export const PLUGIN_FETCH = [+`const harnessSocket = `,+{ argument: 'socket' },+`+const harnessFetch = async (url, init) => {+ if (!harnessSocket) return fetch(url, init)+ const { lstatSync } = await import("node:fs")+ const { dirname } = await import("node:path")+ const { request } = await import("node:http")+ const uid = process.getuid?.()+ const file = lstatSync(harnessSocket), folder = lstatSync(dirname(harnessSocket))+ if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0+ || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error("The Harness socket is not private.")+ return new Promise((resolve, reject) => {+ const asked = request({ socketPath: harnessSocket, method: init.method, path: new URL(url).pathname,+ headers: { ...init.headers, "content-length": String(Buffer.byteLength(init.body)) } }, (answer) => {+ answer.resume()+ answer.on("end", () => resolve({ ok: answer.statusCode >= 200 && answer.statusCode < 300, status: answer.statusCode }))+ answer.on("error", reject)+ })+ asked.on("error", reject)+ asked.end(init.body)+ })+}+`,+] as constdiff --git a/cli/src/engines/nativeHooks.ts b/cli/src/engines/nativeHooks.tsindex a6c7a4129..4de066d18 100644--- a/cli/src/engines/nativeHooks.ts+++ b/cli/src/engines/nativeHooks.ts@@ -22,6 +22,7 @@ import { CURSOR_HOOK_SETTINGS } from './cursor/contract.js'import { COMMANDCODE_HOOK_SETTINGS } from './commandcode/contract.js'import { DEVIN_HOOK_SETTINGS } from './devin/contract.js'import { installNativeHookSettings } from './kit/nativeHookSettings.js'+import { unixSocketPath } from '../lib/localSocket.js'export const installGrokHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...GROK_HOOK_SETTINGS, file: join(nativeHookLocations(options.environment).GROK_HOME, 'hooks', 'harness.json') } : GROK_HOOK_SETTINGS, port, options)export const installAgyHooks = (port: number, options?: NativeHookOptions): Promise<boolean> => installNativeHookSettings(options?.environment ? { ...AGY_HOOK_SETTINGS, file: join(nativeHookLocations(options.environment).AGY_CONFIG_DIR, 'hooks.json') } : AGY_HOOK_SETTINGS, port, options)@@ -32,6 +33,8 @@ export const installDevinHooks = (port: number, options?: NativeHookOptions): Prconst pluginValues = (port: number) => ({port: String(port), credential: JSON.stringify(hookTokenPath(env.ADAPTER_DATA_DIR)), version: JSON.stringify(VERSION),+ // Named for the configured port, as the daemon's socket is, whichever port it was given.+ socket: JSON.stringify(unixSocketPath(env.ADAPTER_DATA_DIR, env.PORT)),})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/opencode/contract.ts b/cli/src/engines/opencode/contract.tsindex 7c90a444f..52f53e795 100644--- a/cli/src/engines/opencode/contract.ts+++ b/cli/src/engines/opencode/contract.ts@@ -1,5 +1,6 @@import { join as hookPath, dirname as hookParent } from 'node:path'import { env as hookEnvironment } from '../../config/env.js'+import { PLUGIN_FETCH } from '../kit/pluginFetch.js'/*** What the core knows of OpenCode without loading its code: declared data, read in line where a launch is built* (docs/design/2026-10-08-other-engines-out-of-core.md). It imports nothing of OpenCode's code.@@ -66,7 +67,9 @@ import { readFileSync } from "node:fs"const hookToken = () => { try { return readFileSync(`,{ argument: 'credential' },`, "utf8").trim() } catch { return "" } }-export const MachineRegister = async ({ directory, worktree, project, client }) => {+`,+...PLUGIN_FETCH,+`export const MachineRegister = async ({ directory, worktree, project, client }) => {const seen = new Set()const post = async (sessionID) => {const pane = process.env.TMUX_PANE@@ -76,7 +79,7 @@ export const MachineRegister = async ({ directory, worktree, project, client })if ((!pane && !ptyPane) || !token || !sessionID || seen.has(sessionID)) returnseen.add(sessionID)try {- await fetch("http://127.0.0.1:`,+ await harnessFetch("http://127.0.0.1:`,{ argument: 'port' },`/api/hook/session-start", {method: "POST",@@ -136,7 +139,9 @@ import { readFileSync } from "node:fs"const hookToken = () => { try { return readFileSync(`,{ argument: 'credential' },`, "utf8").trim() } catch { return "" } }-export default {+`,+...PLUGIN_FETCH,+`export default {id: "harness-session-register",setup(ctx) {const pane = process.env.TMUX_PANE@@ -154,7 +159,7 @@ export default {try { info = await (ctx.data && ctx.data.session && ctx.data.session.get ? ctx.data.session.get(sessionID) : undefined) } catch {}if (info && info.parentID) { posted.add(sessionID); return } // a sub-agent's — shown under its parent's Task cardconst cwd = (info && info.location && info.location.directory) || (ctx.location && ctx.location.directory) || process.cwd()- const res = await fetch("http://127.0.0.1:`,+ const res = await harnessFetch("http://127.0.0.1:`,{ argument: 'port' },`/api/hook/session-start", {method: "POST",diff --git a/cli/src/engines/pi/contract.ts b/cli/src/engines/pi/contract.tsindex c25a92b02..cfddbf4f8 100644--- a/cli/src/engines/pi/contract.ts+++ b/cli/src/engines/pi/contract.ts@@ -2,6 +2,7 @@ import { join as hookPath } from 'node:path'import { env as hookEnvironment } from '../../config/env.js'/** Pi's folder is lossy. Only its complete first entry establishes the session id and cwd. */import type { SessionFolder, SessionHeader } from '../kit/sessionIdentity.js'+import { PLUGIN_FETCH } from '../kit/pluginFetch.js'// Pi accepts custom ids. A .jsonl suffix makes --session interpret the value as a file instead.export const PI_SESSION_ID = /^(?!.*\.jsonl$)[A-Za-z0-9][A-Za-z0-9._-]{0,126}[A-Za-z0-9]$/@@ -29,7 +30,9 @@ export const PI_EXTENSION = {import { existsSync, readFileSync } from "node:fs";import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";-export default function (pi: ExtensionAPI) {+`,+...PLUGIN_FETCH,+`export default function (pi: ExtensionAPI) {let announced = false; // posted at least once (the transcript may not exist yet)let registered = false; // posted with a real, on-disk transcript — nothing left to do@@ -50,7 +53,7 @@ export default function (pi: ExtensionAPI) {const sessionId = ctx?.sessionManager?.getSessionId?.();if (!sessionId) return;try {- const res = await fetch("http://127.0.0.1:`,+ const res = await harnessFetch("http://127.0.0.1:`,{ argument: 'port' },`/api/hook/session-start", {method: "POST",diff --git a/cli/src/engines/pluginPosts.spec.ts b/cli/src/engines/pluginPosts.spec.tsnew file mode 100644index 000000000..2ee82b54d--- /dev/null+++ b/cli/src/engines/pluginPosts.spec.ts@@ -0,0 +1,126 @@+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { join } from 'node:path'+import { pathToFileURL } from 'node:url'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { env } from '../config/env.js'+import { AMP_PLUGIN } from './amp/contract.js'+import { KILO_PLUGIN } from './kilo/contract.js'+import { nativePluginSource, type NativePlugin } from './kit/nativePlugin.js'+import { OPENCODE_LEGACY_PLUGIN, OPENCODE_TUI_PLUGIN } from './opencode/contract.js'+import { PI_EXTENSION } from './pi/contract.js'++const TOKEN = 'c'.repeat(43)+let dir = '', short = '', closers: Server[] = [], index = 0+beforeEach(() => {+ const tmp = join(import.meta.dirname, '..', '.tmp')+ mkdirSync(tmp, { recursive: true })+ dir = mkdtempSync(join(tmp, 'plugin-post-'))+ short = mkdtempSync(join('/tmp', 'pp-'))+ chmodSync(short, 0o700)+ writeFileSync(join(dir, 'hook-token'), `${TOKEN}\n`)+ vi.stubEnv('TMUX_PANE', '%7')+})+afterEach(async () => {+ vi.unstubAllEnvs()+ for (const server of closers.splice(0)) await new Promise(done => { server.closeAllConnections(); server.close(done) })+ rmSync(dir, { recursive: true, force: true })+ rmSync(short, { recursive: true, force: true })+})++interface Heard { url?: string; token?: string; body: string }+function recorder(): { server: Server; heard: Heard[] } {+ const heard: Heard[] = []+ const server = createServer((request, response) => {+ let body = ''+ request.on('data', part => { body += part })+ request.on('end', () => {+ heard.push({ url: request.url, token: request.headers['x-harness-hook-token'] as string | undefined, body })+ response.writeHead(200, { 'content-type': 'application/json' }).end('{}')+ })+ })+ closers.push(server)+ return { server, heard }+}+async function holder(): Promise<{ heard: Heard[]; port: number }> {+ const { server, heard } = recorder()+ await new Promise<void>(ready => server.listen(0, '127.0.0.1', ready))+ return { heard, port: (server.address() as AddressInfo).port }+}+async function daemon(): Promise<{ heard: Heard[]; path: string }> {+ const { server, heard } = recorder(), path = join(short, 'daemon-1.sock')+ await new Promise<void>(ready => server.listen(path, ready))+ chmodSync(path, 0o600)+ return { heard, path }+}++async function load(rule: NativePlugin, name: string, port: number, socket: string | null): Promise<any> {+ const file = join(dir, `${index++}-${name}`)+ // Amp's plugin keeps its transcript in a folder named in its source: never the real one here.+ const source = nativePluginSource(rule, { port: String(port), credential: JSON.stringify(join(dir, 'hook-token')), version: '"test"', socket: JSON.stringify(socket) })+ .replace(JSON.stringify(env.AMP_SESSIONS_DIR), JSON.stringify(join(dir, 'amp')))+ writeFileSync(file, source)+ return import(pathToFileURL(file).href)+}++/** Each plugin's own way of announcing a session. */+const PLUGINS: Array<[string, NativePlugin, string, (plugin: any) => Promise<unknown>]> = [+ ['OpenCode', OPENCODE_LEGACY_PLUGIN, 'opencode.mjs', async (plugin) => {+ const hooks = await plugin.MachineRegister({ directory: '/work' })+ await hooks.event({ event: { type: 'session.created', properties: { info: { id: 'ses_1' } } } })+ }],+ ['Kilo', KILO_PLUGIN, 'kilo.mjs', async (plugin) => {+ const hooks = await plugin.MachineRegister({ directory: '/work' })+ await hooks.event({ event: { type: 'session.created', properties: { info: { id: 'ses_1' } } } })+ }],+ ['OpenCode 2', OPENCODE_TUI_PLUGIN, 'tui.mjs', async (plugin) => {+ const stop = plugin.default.setup({ ui: { router: { current: () => ({ type: 'session', sessionID: 'ses_1' }) } }, data: { session: { get: async () => ({}) } }, location: { directory: '/work' } })+ await new Promise(done => setTimeout(done, 200))+ stop?.()+ }],+ ['Pi', PI_EXTENSION, 'pi.ts', async (plugin) => {+ const handlers: Record<string, (event: unknown, ctx: unknown) => Promise<void>> = {}+ plugin.default({ on: (name: string, run: (event: unknown, ctx: unknown) => Promise<void>) => { handlers[name] = run } })+ await handlers.session_start!({}, { sessionManager: { getSessionFile: () => null, getSessionId: () => 'ses_1' }, cwd: '/work' })+ }],+ ['Amp', AMP_PLUGIN, 'amp.ts', async (plugin) => {+ const handlers: Record<string, (event: unknown, ctx: unknown) => Promise<void>> = {}+ plugin.default({ on: (name: string, run: (event: unknown, ctx: unknown) => Promise<void>) => { handlers[name] = run } })+ await handlers['session.start']!({ thread: { id: 'ses_1' } }, {})+ }],+]++describe.each(PLUGINS)('%s\'s plugin', (_name, rule, file, announce) => {+ it('posts over the socket, with its token, and a holder of the port hears nothing', async () => {+ const hold = await holder(), real = await daemon()+ await announce(await load(rule, file, hold.port, real.path))+ await vi.waitFor(() => expect(real.heard).toHaveLength(1))+ expect(real.heard[0]).toMatchObject({ url: '/api/hook/session-start', token: TOKEN })+ expect(JSON.parse(real.heard[0]!.body)).toMatchObject({ sessionId: 'ses_1' })+ expect(hold.heard).toEqual([])+ })++ it('with the socket gone posts nothing, and the port is not tried', async () => {+ const hold = await holder()+ await announce(await load(rule, file, hold.port, join(short, 'gone.sock')))+ await new Promise(done => setTimeout(done, 50))+ expect(hold.heard).toEqual([])+ })++ it('a socket that is not private is not used', async () => {+ const hold = await holder(), real = await daemon()+ chmodSync(real.path, 0o666)+ await announce(await load(rule, file, hold.port, real.path))+ await new Promise(done => setTimeout(done, 50))+ expect(real.heard).toEqual([])+ expect(hold.heard).toEqual([])+ })++ it('where no socket can be (Windows, or a home too long as well), posts to the port as before', async () => {+ const hold = await holder()+ await announce(await load(rule, file, hold.port, null))+ await vi.waitFor(() => expect(hold.heard).toHaveLength(1))+ expect(hold.heard[0]).toMatchObject({ url: '/api/hook/session-start', token: TOKEN })+ })+})diff --git a/cli/src/engines/removeHooks.ts b/cli/src/engines/removeHooks.tsindex 9916f7ce8..8c7ab7545 100644--- a/cli/src/engines/removeHooks.ts+++ b/cli/src/engines/removeHooks.ts@@ -129,6 +129,7 @@ function codexHooksNow(home: string): Settings {export const PLUGIN_CHANGED = "Harness's plugin, changed since Harness wrote it; delete it yourself if you no longer need it."/** What a value of a plugin's template can be: a port, or one JSON string (nativePlugin.ts `NativePluginValues`). */const SLOTS = {+ socket: '"(?:[^"\\\\]|\\\\.)*"|null',port: String.raw`\d{1,5}`,credential: String.raw`"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"`,version: String.raw`"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"`,diff --git a/cli/src/lib/autonomous-device/addonCommand.spec.ts b/cli/src/lib/autonomous-device/addonCommand.spec.tsindex 89d71db3c..d23beab9d 100644--- a/cli/src/lib/autonomous-device/addonCommand.spec.ts+++ b/cli/src/lib/autonomous-device/addonCommand.spec.ts@@ -1,7 +1,11 @@import { createHash } from 'node:crypto'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it, vi, beforeEach } from 'vitest'import { runAutonomousDeviceCommand } from './command.js'import { pickMachine, runAddonCommand } from './addonCommand.js'++// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })// 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' }))diff --git a/cli/src/lib/autonomous-device/command.spec.ts b/cli/src/lib/autonomous-device/command.spec.tsindex 5a88dfc78..c99b9b579 100644--- a/cli/src/lib/autonomous-device/command.spec.ts+++ b/cli/src/lib/autonomous-device/command.spec.ts@@ -1,6 +1,10 @@-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, describe, expect, it, vi, beforeEach } from 'vitest'import { Readable } from 'node:stream'import { runAutonomousDeviceCommand } from './command.js'++// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })// 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' }))diff --git a/cli/src/lib/connectors/agents.ts b/cli/src/lib/connectors/agents.tsindex dedd44722..62a01350d 100644--- a/cli/src/lib/connectors/agents.ts+++ b/cli/src/lib/connectors/agents.ts@@ -17,6 +17,7 @@ import { managedNodePath } from '../nodeRuntime.js'import { MCP_SHIM_SOURCE } from './mcpShimSource.js'import { CODE, locked, writePrivate, type Store } from './store.js'import { transport } from './rest.js'+import { socketPathIn } from '../localSocket.js'const validPort = (port: unknown): port is number => typeof port === 'number' && Number.isInteger(port) && port >= 0 && port < 65536@@ -104,14 +105,9 @@ export function bridgeUrl(key: string, code: string, port = bridgePort()): strinreturn `http://127.0.0.1:${port}/${key}/${code}/mcp`}-/** sockaddr_un has 104 bytes on macOS and the socket is staged under a name no longer (lib/localSocket.ts). */-const MAX_SOCKET_PATH_BYTES = 96--/** The bridge's 0600 socket for MCP clients, in the vault's private folder, or null where there is none. */+/** The bridge's 0600 socket for MCP clients, in the vault's private folder or its short one, or null where there is none. */export function bridgeSocketPath(vault: Store, platform: NodeJS.Platform = process.platform): string | null {- if (platform === 'win32') return null- const path = join(vault.root, 'bridge.sock')- return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null+ return platform === 'win32' ? null : socketPathIn(vault.root, 'bridge.sock')}/** How an MCP client reaches one connection. */diff --git a/cli/src/lib/connectors/mcpShim.spec.ts b/cli/src/lib/connectors/mcpShim.spec.tsindex 05750f6e2..89d4ef195 100644--- a/cli/src/lib/connectors/mcpShim.spec.ts+++ b/cli/src/lib/connectors/mcpShim.spec.ts@@ -413,7 +413,7 @@ describe.skipIf(process.platform === 'win32')('the MCP clients\' way to the bridsync(vault, { ...env, CLAUDE_CONFIG_DIR: home })expect(claudeEntry('linear').url).toBeUndefined()const long = new Store(join(home, 'x'.repeat(120)), env)- expect(bridgeSocketPath(long)).toBeNull()+ expect(bridgeSocketPath(long)).toMatch(/\/\.harness\/s\/[0-9a-f]{16}\/bridge\.sock$/)expect(bridgeSocketPath(vault, 'win32')).toBeNull()})})diff --git a/cli/src/lib/daemonEndpoint.spec.ts b/cli/src/lib/daemonEndpoint.spec.tsindex 261332902..bbbb5e467 100644--- a/cli/src/lib/daemonEndpoint.spec.ts+++ b/cli/src/lib/daemonEndpoint.spec.ts@@ -2,12 +2,16 @@ import { createServer } from 'node:http'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'+import { afterEach, describe, expect, it, beforeEach, vi } from 'vitest'import { loadOrCreateHookCredential } from './hookAuth.js'import { legacyDaemonStatus, localDaemonCall, localDaemonStatus, saveDaemonPort, savedDaemonPort } from './daemonEndpoint.js'import { readDaemonRecord } from './daemonRecord.js'import { listenLocalSocket, localSocketPath } from './localSocket.js'+// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })+const cleanup: Array<() => void | Promise<void>> = []afterEach(async () => { for (const close of cleanup.splice(0).reverse()) await close() })function directory(): string {diff --git a/cli/src/lib/discoveryScripts.spec.ts b/cli/src/lib/discoveryScripts.spec.tsindex dd0100333..7a8b96a66 100644--- a/cli/src/lib/discoveryScripts.spec.ts+++ b/cli/src/lib/discoveryScripts.spec.ts@@ -99,10 +99,13 @@ describe('generated discovery scripts', () => {// pane shows. The legacy file must be absent: 2.0 also discovers it, then refuses its old API.it('installs only the compatible OpenCode 2 plugin, posting the session the pane shows', async () => {const config = scratch()- const data = scratch()+ // No socket can be, so this reads the post where a test can see it (pluginPosts.spec.ts covers the socket).+ const data = join(scratch(), 'd'.repeat(100))+ mkdirSync(data, { recursive: true })const pluginDir = join(config, 'plugin')vi.resetModules()version.major = 2+ vi.stubEnv('HOME', `/${'h'.repeat(120)}`)vi.stubEnv('OPENCODE_PLUGIN_DIR', pluginDir)vi.stubEnv('ADAPTER_DATA_DIR', data)writeFileSync(join(data, 'hook-token'), 'tok-123\n')diff --git a/cli/src/lib/localSocket.spec.ts b/cli/src/lib/localSocket.spec.tsindex 2a2bc1a11..5945a7de7 100644--- a/cli/src/lib/localSocket.spec.ts+++ b/cli/src/lib/localSocket.spec.ts@@ -1,13 +1,13 @@-import { randomBytes } from 'node:crypto'+import { createHash, randomBytes } from 'node:crypto'import { createServer, request } from 'node:http'import { connect } from 'node:net'-import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'+import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'-import { join } from 'node:path'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { dirname, join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {askDataFolderServer, isLocalSocketName, isTrustedLocal, listenLocalSocket, localSocketListenPath, localSocketName, localSocketPath, ORPHAN_STILL_SERVING,- ORPHAN_WAIT_MS, refuseServedDataFolder, servedFolderDeps, unixSocketPath, type DataFolderServer, type LocalSocketServer, type ServedFolderDeps,+ ORPHAN_WAIT_MS, refuseServedDataFolder, servedFolderDeps, socketPathIn, unixSocketPath, type DataFolderServer, type LocalSocketServer, type ServedFolderDeps,} from './localSocket.js'import { daemonPipe } from './windows/daemonPipe.js'import { writeDaemonRecord } from './daemonRecord.js'@@ -59,11 +59,10 @@ describe('localSocketPath', () => {expect(localSocketPath('/Users/me/.harness/cli/data', 18473, 'darwin')).toBe('/Users/me/.harness/cli/data/daemon-18473.sock')expect(localSocketPath('/home/me/.harness/cli/data', 18474, 'linux')).toBe('/home/me/.harness/cli/data/daemon-18474.sock')expect(localSocketPath('C:\\Users\\me\\.harness', 18473, 'win32')).toBeNull()- expect(localSocketPath(`/tmp/${'x'.repeat(100)}`, 18473, 'darwin')).toBeNull()// 96 bytes fits (the staging name adds 4, still under macOS's 104 with the terminator); 97 does not.const dirFor = (total: number) => `/${'d'.repeat(total - '/daemon-18473.sock'.length - 1)}`expect(localSocketPath(dirFor(96), 18473, 'darwin')).toHaveLength(96)- expect(localSocketPath(dirFor(97), 18473, 'darwin')).toBeNull()+ expect(localSocketPath(dirFor(97), 18473, 'darwin')).toMatch(/\/\.harness\/s\/[0-9a-f]{16}\/daemon-18473\.sock$/)expect(isLocalSocketName('daemon-18473.sock')).toBe(true)expect(isLocalSocketName('daemon.sock')).toBe(false)expect(isLocalSocketName('daemon-18473.sock.bak')).toBe(false)@@ -392,3 +391,63 @@ describe('who serves a data folder, over the Windows pipe', () => {}})})++describe('a data folder too long to hold a socket', () => {+ const long = `/data/${'x'.repeat(120)}`+ const hash = (folder: string): string => createHash('sha256').update(folder).digest('hex').slice(0, 16)++ it('keeps a short folder\'s socket where it is', () => {+ expect(socketPathIn('/d', 'daemon-1.sock', '/h')).toBe('/d/daemon-1.sock')+ })++ it('gets one under the home folder, the same each time and another for another folder', () => {+ const path = socketPathIn(long, 'daemon-1.sock', '/h')+ expect(path).toBe(`/h/.harness/s/${hash(long)}/daemon-1.sock`)+ expect(socketPathIn(long, 'daemon-1.sock', '/h')).toBe(path)+ expect(socketPathIn(`${long}y`, 'daemon-1.sock', '/h')).not.toBe(path)+ })++ it('has none when the home folder is too long as well: the one case left on TCP', () => {+ expect(socketPathIn(long, 'daemon-1.sock', `/${'h'.repeat(120)}`)).toBeNull()+ })++ it('pins the rule every client copies', () => {+ expect(socketPathIn(long, 'bridge.sock', '/h')).toBe(`/h/.harness/s/${hash(long)}/bridge.sock`)+ // Desktop's test pins the same hash (desktop/test/local_daemon_transport_test.dart).+ expect(hash(`/${'x'.repeat(100)}`)).toBe('e50e7828cbafcbee')+ expect(hash('/x')).toBe('b3d1db318671a024')+ })++ describe('listening', () => {+ let home: string, closers: Array<() => Promise<unknown>>+ beforeEach(() => { home = mkdtempSync(join('/tmp', 'ls-')); closers = [] })+ afterEach(async () => { for (const close of closers) await close(); rmSync(home, { recursive: true, force: true }) })++ it('makes the short folder 0700 and the socket 0600', async () => {+ const path = socketPathIn(long, 'daemon-1.sock', home)!+ const listening = await listenLocalSocket(() => {}, path)+ closers.push(listening.close)+ expect(lstatSync(dirname(path)).mode & 0o777).toBe(0o700)+ expect(lstatSync(join(home, '.harness', 's')).mode & 0o777).toBe(0o700)+ expect(lstatSync(path).mode & 0o777).toBe(0o600)+ })++ it('tightens a looser short folder before it listens', async () => {+ const path = socketPathIn(long, 'daemon-1.sock', home)!+ mkdirSync(dirname(path), { recursive: true, mode: 0o777 })+ chmodSync(dirname(path), 0o777)+ const listening = await listenLocalSocket(() => {}, path)+ closers.push(listening.close)+ expect(lstatSync(dirname(path)).mode & 0o777).toBe(0o700)+ })++ it('refuses a short folder that is a link', async () => {+ const path = socketPathIn(long, 'daemon-1.sock', home)!+ mkdirSync(dirname(dirname(path)), { recursive: true, mode: 0o700 })+ const elsewhere = mkdtempSync(join('/tmp', 'ls-other-'))+ closers.push(async () => rmSync(elsewhere, { recursive: true, force: true }))+ symlinkSync(elsewhere, dirname(path))+ await expect(listenLocalSocket(() => {}, path)).rejects.toThrow(/not private/)+ })+ })+})diff --git a/cli/src/lib/localSocket.ts b/cli/src/lib/localSocket.tsindex 2ccb7c196..9f04c5c5f 100644--- a/cli/src/lib/localSocket.ts+++ b/cli/src/lib/localSocket.ts@@ -13,13 +13,14 @@* 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).*/-import { randomBytes } from 'node:crypto'+import { createHash, randomBytes } from 'node:crypto'import http from 'node:http'import { connect } from 'node:net'import type { IncomingMessage } from 'node:http'import type { Socket } from 'node:net'import type { Duplex } from 'node:stream'-import { chmodSync, linkSync, lstatSync, renameSync, unlinkSync, type Stats } from 'node:fs'+import { chmodSync, linkSync, lstatSync, mkdirSync, renameSync, unlinkSync, type Stats } from 'node:fs'+import { homedir } from 'node:os'import { dirname, join } from 'node:path'import { readDaemonRecord } from './daemonRecord.js'import { daemonPipe, type LocalDaemonOptions } from './windows/daemonPipe.js'@@ -51,11 +52,25 @@ const trustedSockets = new WeakSet<Socket>()/** Requests over the daemon's pipe whose auth checked out, and the proof each answer to them carries. */const pipeProofs = new WeakMap<IncomingMessage, string>()-/** The daemon's Unix socket for `port` in this data directory, or null where there is none: Windows, or a path too long. */+/** Where a folder too long to hold a socket keeps its sockets: under the home folder, as /tmp is shared and TMPDIR differs between launchd+ * and a shell, so clients would disagree. The same rule is in cli/hook/notify.mjs, store/tools/local-daemon.mjs and Desktop's+ * local_daemon_transport.dart. */+export function shortSocketFolder(folder: string, home: string = homedir()): string {+ return join(home, '.harness', 's', createHash('sha256').update(folder).digest('hex').slice(0, 16))+}++/** `name` in [folder], or in its short folder when that path is too long for a socket; null when even that is, the one case left on TCP. */+export function socketPathIn(folder: string, name: string, home: string = homedir()): string | null {+ const beside = join(folder, name)+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH_BYTES) return beside+ const short = join(shortSocketFolder(folder, home), name)+ return Buffer.byteLength(short) <= MAX_SOCKET_PATH_BYTES ? short : null+}++/** The daemon's Unix socket for `port` in this data directory, or null where there is none: Windows, or a home too long as well. */export function unixSocketPath(dataDir: string, port: number, platform: NodeJS.Platform = process.platform): string | null {if (platform === 'win32') return null- const path = join(dataDir, localSocketName(port))- return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null+ return socketPathIn(dataDir, localSocketName(port))}/**@@ -103,6 +118,18 @@ export interface LocalSocketServer {closeSync: () => void}+/** A short folder (shortSocketFolder) is made here, and it and its parent are this account's real folders, owner only, before a socket goes in. */+function prepareShortFolder(path: string): void {+ const folder = dirname(path)+ if (!/[\\/]\.harness[\\/]s[\\/][0-9a-f]{16}$/.test(folder)) return+ mkdirSync(folder, { recursive: true, mode: 0o700 })+ for (const each of [dirname(folder), folder]) {+ const seen = lstatSync(each), uid = process.getuid?.()+ if (!seen.isDirectory() || (uid !== undefined && seen.uid !== uid)) throw new Error(`${each} is not private: it must be this account's own folder.`)+ chmodSync(each, 0o700)+ }+}+/*** Serve `handler` on a Unix socket at `path`. Refuse a live listener or a non-socket file, and remove* only a stale socket. CLI startup is serialized by the per-user spawn lock; two daemons that start at@@ -112,6 +139,7 @@ export async function listenLocalSocket(handler: http.RequestListener, path: strif (options.token) return listenAuthenticated(handler, path, options.token)// A Harness pipe, or any endpoint on Windows, is never trusted by reachability: it needs the daemon's token.if (pipeIdOf(path) || process.platform === 'win32') throw new Error(`${path} needs the daemon's token: reaching a pipe is no credential`)+ prepareShortFolder(path)// A TCP collision can now move this user to another port. Holding a TCP port no longer proves// an existing Unix socket is stale: never unlink a live daemon belonging to this user.await refuseLiveSocket(path)diff --git a/cli/src/lib/localTransport.ts b/cli/src/lib/localTransport.tsindex dcbbfafb8..734d19f47 100644--- a/cli/src/lib/localTransport.ts+++ b/cli/src/lib/localTransport.ts@@ -15,7 +15,7 @@ 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'+import { unixSocketPath } from './localSocket.js'const LOCAL_WS_PATH = '/api/local-ws'@@ -26,14 +26,18 @@ const LOCAL_WS_PATH = '/api/local-ws'*/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+ // A data folder's own mode covers its socket; a short folder's lies elsewhere, so it is checked, and one that isn't private is refused as+ // a daemon that is down is: connecting to this name fails.+ const checked = (socket: string): string => !socket.startsWith(dataDir) && !socketIsPrivate(socket) ? `${socket}.not-private` : socket+ if (!expected) return expected+ if (existsSync(expected)) return checked(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+ const socket = unixSocketPath(dataDir, Number(configured), platform)+ if (socket && existsSync(socket)) return checked(socket)}return expected}diff --git a/cli/src/orchestrator/command.spec.ts b/cli/src/orchestrator/command.spec.tsindex 6e7708ab1..d7f1d36f6 100644--- a/cli/src/orchestrator/command.spec.ts+++ b/cli/src/orchestrator/command.spec.ts@@ -4,6 +4,10 @@ import { WebSocketServer } from 'ws'import * as authSession from '../lib/authSession.js'import { summarizeOrchestratorReply, parseOrchestratorArgs, localOrchestratorRequest, orchestratorCommand } from './command.js'+// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })+describe('orchestrator tool output', () => {it('keeps large projects readable without discarding worker results or mutating UI state', () => {const reply = { project: {diff --git a/cli/src/team/localCredential.spec.ts b/cli/src/team/localCredential.spec.tsindex 0b5bca3d5..befdcaec6 100644--- a/cli/src/team/localCredential.spec.ts+++ b/cli/src/team/localCredential.spec.ts@@ -3,6 +3,7 @@* 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 { createHash } from 'node:crypto'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'@@ -10,7 +11,7 @@ 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 { afterEach, describe, expect, it, beforeEach, vi } from 'vitest'import { connectSocket } from '../agentClient/daemon.js'import { deviceRequest } from '../devices/client.js'import { createMessagesRpc } from '../messages/rpc.js'@@ -19,6 +20,10 @@ import { localCredentialHeaders } from '../lib/localCredential.js'import { uploadAttachments } from '../superTabs/attach.js'import { WebSocket } from 'ws'+// A folder too long for a socket now has one under the home folder: only a home too long as well is left on the port.+beforeEach(() => { vi.stubEnv('HOME', `/${'h'.repeat(120)}`) })+afterEach(() => { vi.unstubAllEnvs() })+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)@@ -67,11 +72,11 @@ describe('audit H1: whoever holds the daemon\'s port hears nothing it can use',return { port: typeof address === 'string' ? 0 : (address as AddressInfo).port, heard }}- const runHook = async (root: string, data: string, port: number): Promise<void> => {+ const runHook = async (root: string, data: string, port: number, home: string = root): 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 },+ env: { PATH: process.env.PATH, HOME: home, 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()) })@@ -105,10 +110,32 @@ describe('audit H1: whoever holds the daemon\'s port hears nothing it can use',expect(daemon.heard.length).toBeGreaterThan(0)}, 30_000)- it('where a socket cannot exist, a hook sends only its own token over TCP', async () => {+ it('a data folder too long for a socket: the hook uses its short one, and a holder of the port hears nothing', async () => {const { root, data } = dataFolder(true)+ const home = realpathSync(mkdtempSync(join('/tmp', 'hc-')))+ cleanup.push(() => rmSync(home, { recursive: true, force: true }))+ const folder = join(home, '.harness', 's', createHash('sha256').update(data).digest('hex').slice(0, 16))+ mkdirSync(folder, { recursive: true, mode: 0o700 })const { port, heard } = await holder()- await runHook(root, data, port)+ const daemon = await holder(join(folder, `daemon-${port}.sock`))+ await runHook(root, data, port, home)+ expect(heard).toEqual([])+ expect(daemon.heard.length).toBeGreaterThan(0)+ }, 30_000)++ it('the same with its short socket gone: nothing goes to the port', async () => {+ const { root, data } = dataFolder(true)+ const home = realpathSync(mkdtempSync(join('/tmp', 'hc-')))+ cleanup.push(() => rmSync(home, { recursive: true, force: true }))+ const { port, heard } = await holder()+ await runHook(root, data, port, home)+ expect(heard).toEqual([])+ }, 30_000)++ it('where no socket can exist, a home too long as well, 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, `/${'h'.repeat(120)}`)expect(heard.length).toBeGreaterThan(0)expect(secretIn(heard)).toBe(false)expect(heard[0]!.headers['x-harness-hook-token']).toBe(HOOK_TOKEN)diff --git a/companions/scripts/memory-native-opencode-binding-probe.mjs b/companions/scripts/memory-native-opencode-binding-probe.mjsindex 381f61d6a..bc57f5715 100644--- a/companions/scripts/memory-native-opencode-binding-probe.mjs+++ b/companions/scripts/memory-native-opencode-binding-probe.mjs@@ -63,7 +63,7 @@ try {binding = new OpenCodeMemoryBinding({ current: owner })const plugin = join(fixture, 'plugin.mjs')await writeFile(plugin, `const hookToken = () => 'synthetic-hook-token';- export const Fixture = async ({client}) => { ${opencodeMemoryPluginSource(model.address().port)}; return { 'chat.message': memoryMessage, 'chat.params': memoryParams } }`, { mode: 0o600 })+ export const Fixture = async ({client}) => { ${opencodeMemoryPluginSource(model.address().port, null)}; return { 'chat.message': memoryMessage, 'chat.params': memoryParams } }`, { mode: 0o600 })const selectedModel = 'memory-fixture/alias'const config = { autoupdate: false, share: 'disabled', snapshot: false, permission: { '*': 'deny' },plugin: [pathToFileURL(plugin).href], mcp: {}, instructions: [], enabled_providers: ['memory-fixture'],diff --git a/companions/scripts/memory-native-opencode-recall-probe.mjs b/companions/scripts/memory-native-opencode-recall-probe.mjsindex 9b77f193b..b66500129 100644--- a/companions/scripts/memory-native-opencode-recall-probe.mjs+++ b/companions/scripts/memory-native-opencode-recall-probe.mjs@@ -103,8 +103,8 @@ try {const plugin = join(directory, 'recall.mjs')await writeFile(plugin, `const hookToken = () => 'synthetic-hook-token';export const Fixture = async ({client}) => {- ${opencodeMemoryPluginSource(server.address().port)}- ${opencodeRecallPluginSource(server.address().port)}+ ${opencodeMemoryPluginSource(server.address().port, null)}+ ${opencodeRecallPluginSource(server.address().port, null)}const post = async (route, body) => {const response = await fetch(${JSON.stringify(url)} + route, { method: 'POST', signal: AbortSignal.timeout(400),headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })diff --git a/companions/scripts/memory-native-opencode-source-probe.mjs b/companions/scripts/memory-native-opencode-source-probe.mjsindex c30c4222e..e85ffbaf1 100644--- a/companions/scripts/memory-native-opencode-source-probe.mjs+++ b/companions/scripts/memory-native-opencode-source-probe.mjs@@ -77,7 +77,7 @@ try {}const plugin = join(directory, 'origin.mjs')await writeFile(plugin, `const hookToken = () => ''; export const Fixture = async ({client}) => {- ${opencodeMemoryPluginSource(1)}; return { 'chat.message': memoryMessage } }`, { mode: 0o600 })+ ${opencodeMemoryPluginSource(1, null)}; return { 'chat.message': memoryMessage } }`, { mode: 0o600 })const config = { autoupdate: false, share: 'disabled', snapshot: false,plugin: markOrigins ? [pathToFileURL(plugin).href] : [], mcp: {}, instructions: [],compaction: { auto: true, prune: false },diff --git a/companions/src/memory/adapters/opencodeMemoryPlugin.spec.ts b/companions/src/memory/adapters/opencodeMemoryPlugin.spec.tsindex c46c6271e..9ec8e5c73 100644--- a/companions/src/memory/adapters/opencodeMemoryPlugin.spec.ts+++ b/companions/src/memory/adapters/opencodeMemoryPlugin.spec.ts@@ -10,7 +10,7 @@ function fixture() {return new Response(JSON.stringify({ observe: true, challenge: 'one-use-grant' }), { status: 200 })})const health = vi.fn(async () => ({ data: { version: '1.18.34' } }))- const { hook, submitted } = new Function('client', 'hookToken', `${opencodeMemoryPluginSource(12345)}; return { hook: memoryParams, submitted: memoryMessage }`)({ _client: { get: health } }, () => 'synthetic-hook-token')+ const { hook, submitted } = new Function('client', 'hookToken', `${opencodeMemoryPluginSource(12345, null)}; return { hook: memoryParams, submitted: memoryMessage }`)({ _client: { get: health } }, () => 'synthetic-hook-token')const input = { sessionID: 'native', agent: 'build', message: { id: 'user-one', sessionID: 'native', role: 'user', agent: 'build', model: { providerID: 'selected', modelID: 'alias', variant: 'high' } },provider: { id: 'selected', name: 'Selected', key: 'native-api-account', options: { baseURL: 'https://selected.invalid/v1' } },model: { providerID: 'selected', id: 'alias', name: 'Alias', api: { id: 'provider-native-id', npm: '@ai-sdk/openai-compatible', url: 'https://catalog.invalid/v1' },diff --git a/companions/src/memory/adapters/opencodeMemoryPlugin.ts b/companions/src/memory/adapters/opencodeMemoryPlugin.tsindex c667d05df..9f008b9c9 100644--- a/companions/src/memory/adapters/opencodeMemoryPlugin.ts+++ b/companions/src/memory/adapters/opencodeMemoryPlugin.ts@@ -1,6 +1,8 @@+import { pluginFetchSource } from './opencodePluginFetch.js'+/** Standalone source embedded in the existing 1.x plugin; no additional installation artifact. */-export function opencodeMemoryPluginSource(port: number): string {- return `+export function opencodeMemoryPluginSource(port: number, socket: string | null): string {+ return `${pluginFetchSource('memoryFetch', socket)}const memoryMessages = new Map()const memoryMessage = async (input, output) => {const message = output.message@@ -24,7 +26,7 @@ export function opencodeMemoryPluginSource(port: number): string {const memoryRequest = async (sessionID, input) => {const pane = process.env.TMUX_PANE, token = hookToken()if (!pane || !token || !sessionID) return null- const response = await fetch("http://127.0.0.1:${port}/api/hook/opencode-memory-runtime", {+ const response = await memoryFetch("http://127.0.0.1:${port}/api/hook/opencode-memory-runtime", {method: "POST", signal: AbortSignal.timeout(400),headers: { "content-type": "application/json", "x-harness-hook-token": token },body: JSON.stringify({ engine: "opencode", sessionId: sessionID, callerPid: process.pid,diff --git a/companions/src/memory/adapters/opencodePluginFetch.ts b/companions/src/memory/adapters/opencodePluginFetch.tsnew file mode 100644index 000000000..a5f98b1b3--- /dev/null+++ b/companions/src/memory/adapters/opencodePluginFetch.ts@@ -0,0 +1,32 @@+/**+ * `fetch` for a plugin's post to the daemon, as a named function in its source. Any account can bind the TCP port while the daemon restarts,+ * and would hear the hook token and read or answer what is posted (audit H1). So where a socket can be, the post goes over it, and only if it+ * is this account's, owner only, in a folder nobody else can write to; otherwise it fails, and nothing goes to the port. `socket` is null only+ * where the daemon can have none: Windows, or a home too long as well. `node:http` because OpenCode's runtime and Node both have it.+ */+export function pluginFetchSource(name: string, socket: string | null): string {+ return `+ const ${name} = async (url, init) => {+ const socket = ${JSON.stringify(socket)}+ if (!socket) return fetch(url, init)+ const { lstatSync } = await import("node:fs")+ const { dirname } = await import("node:path")+ const { request } = await import("node:http")+ const { Readable } = await import("node:stream")+ const uid = process.getuid?.()+ const file = lstatSync(socket), folder = lstatSync(dirname(socket))+ if (!file.isSocket() || (file.mode & 0o077) !== 0 || !folder.isDirectory() || (folder.mode & 0o022) !== 0+ || (uid !== undefined && (file.uid !== uid || folder.uid !== uid))) throw new Error("The Harness socket is not private.")+ return new Promise((resolve, reject) => {+ const asked = request({ socketPath: socket, method: init.method, path: new URL(url).pathname, signal: init.signal,+ headers: { ...init.headers, "content-length": String(Buffer.byteLength(init.body)) } }, (answer) => {+ // A Response may have no body with these, and refuses one.+ try { resolve(new Response([101, 204, 205, 304].includes(answer.statusCode) ? null : Readable.toWeb(answer), { status: answer.statusCode })) }+ catch (error) { reject(error) }+ })+ asked.on("error", reject)+ asked.end(init.body)+ })+ }+`+}diff --git a/companions/src/memory/adapters/opencodePluginSocket.spec.ts b/companions/src/memory/adapters/opencodePluginSocket.spec.tsnew file mode 100644index 000000000..711443612--- /dev/null+++ b/companions/src/memory/adapters/opencodePluginSocket.spec.ts@@ -0,0 +1,104 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { createServer, type Server } from 'node:http'+import type { AddressInfo } from 'node:net'+import { join } from 'node:path'+import { pathToFileURL } from 'node:url'+import { pluginFetchSource } from './opencodePluginFetch.js'+import { opencodeMemoryPluginSource } from './opencodeMemoryPlugin.js'+import { opencodeRecallPluginSource } from './opencodeRecallPlugin.js'++const TOKEN = 'synthetic-hook-token'+let folder = '', servers: Server[] = []+beforeEach(() => { folder = mkdtempSync(join('/tmp', 'op-')); chmodSync(folder, 0o700); vi.stubEnv('TMUX_PANE', '%42') })+afterEach(async () => {+ vi.unstubAllEnvs()+ for (const server of servers.splice(0)) await new Promise(done => { server.closeAllConnections(); server.close(done) })+ rmSync(folder, { recursive: true, force: true })+})++type Reply = (response: import('node:http').ServerResponse) => void+function recorder(reply: Reply = (response) => response.writeHead(200, { 'content-type': 'application/json' }).end('{"observe":true,"challenge":"g"}')): { server: Server; heard: Array<{ url?: string; token?: unknown; body: string }> } {+ const heard: Array<{ url?: string; token?: unknown; body: string }> = []+ const server = createServer((request, response) => {+ let body = ''+ request.on('data', part => { body += part })+ request.on('end', () => { heard.push({ url: request.url, token: request.headers['x-harness-hook-token'], body }); reply(response) })+ })+ servers.push(server)+ return { server, heard }+}+const holder = async () => {+ const { server, heard } = recorder()+ await new Promise<void>(ready => server.listen(0, '127.0.0.1', ready))+ return { heard, port: (server.address() as AddressInfo).port }+}+const daemon = async (reply?: Reply) => {+ const { server, heard } = recorder(reply), path = join(folder, 'daemon-1.sock')+ await new Promise<void>(ready => server.listen(path, ready))+ chmodSync(path, 0o600)+ return { heard, path }+}++/** A plugin runs as a module in its engine, so it is loaded as one here: `import()` needs that. */+let loaded = 0+const module_ = async <T>(source: string, name: string): Promise<T> => {+ const file = join(folder, `plugin-${loaded++}.mjs`)+ writeFileSync(file, `const client = {}; const hookToken = () => ${JSON.stringify(TOKEN)};\n${source}\nexport { ${name} }`)+ return (await import(/* @vite-ignore */ pathToFileURL(file).href) as Record<string, T>)[name]!+}+const memory = (port: number, socket: string | null) => module_<(sessionID: string, input: unknown) => Promise<unknown>>(opencodeMemoryPluginSource(port, socket), 'memoryRequest')+const recall = (port: number, socket: string | null) => module_<(route: string, sessionID: string, body: unknown, signal?: AbortSignal) => Promise<unknown>>(opencodeRecallPluginSource(port, socket), 'recallRequest')++describe.each([+ ['memory', async (port: number, socket: string | null) => (await memory(port, socket))('s', { kind: 'probe' })],+ ['recall', async (port: number, socket: string | null) => (await recall(port, socket))('memory-context', 's', {})],+] as const)('the %s plugin', (_name, post) => {+ it('posts over the socket with its token, reads the answer, and a holder of the port hears nothing', async () => {+ const hold = await holder(), real = await daemon()+ expect(await post(hold.port, real.path)).toMatchObject({ observe: true })+ expect(real.heard).toHaveLength(1)+ expect(real.heard[0]!.token).toBe(TOKEN)+ expect(hold.heard).toEqual([])+ })++ it('with the socket gone sends nothing to the port', async () => {+ const hold = await holder()+ await expect(post(hold.port, join(folder, 'gone.sock'))).rejects.toThrow()+ expect(hold.heard).toEqual([])+ })++ it('does not use a socket that is not private', async () => {+ const hold = await holder(), real = await daemon()+ chmodSync(real.path, 0o666)+ await expect(post(hold.port, real.path)).rejects.toThrow(/not private/)+ expect(real.heard).toEqual([])+ expect(hold.heard).toEqual([])+ })+})++describe('the recall plugin over the socket', () => {+ it('drops an answer over its limit', async () => {+ const hold = await holder(), real = await daemon((response) => response.writeHead(200).end('x'.repeat(70_000)))+ expect(await (await recall(hold.port, real.path))('memory-context', 's', {})).toBeNull()+ })++ it('an answer with no body, a 204, gives null and throws nothing outside the call', async () => {+ const hold = await holder(), real = await daemon((response) => response.writeHead(204).end())+ await expect((await recall(hold.port, real.path))('memory-context', 's', {})).resolves.toBeNull()+ })++ it('an abort cuts the request', async () => {+ const hold = await holder(), real = await daemon(() => { /* never answers */ })+ const stop = new AbortController()+ const asked = (await recall(hold.port, real.path))('memory-context', 's', {}, stop.signal)+ await vi.waitFor(() => expect(real.heard).toHaveLength(1))+ stop.abort()+ await expect(asked).rejects.toThrow()+ })+})++it('names its function, so both plugins can share one scope', () => {+ expect(pluginFetchSource('a', null)).toContain('const a = async')+ expect(pluginFetchSource('a', '/s')).toContain('"/s"')+})diff --git a/companions/src/memory/adapters/opencodeRecallPlugin.spec.ts b/companions/src/memory/adapters/opencodeRecallPlugin.spec.tsindex 1dd326617..aa415b7bc 100644--- a/companions/src/memory/adapters/opencodeRecallPlugin.spec.ts+++ b/companions/src/memory/adapters/opencodeRecallPlugin.spec.ts@@ -12,7 +12,7 @@ function fixture() {const fetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async url => new Response(JSON.stringify(String(url).endsWith('memory-context') ? { additionalContext: context, memoryReceiptId: receipt } : { recorded: true })))const health = vi.fn(async () => ({ data: { version: '1.18.34' } }))- const hooks = new Function('client', 'hookToken', `${opencodeRecallPluginSource(12345)};+ const hooks = new Function('client', 'hookToken', `${opencodeRecallPluginSource(12345, null)};return { submitted: recallMessage, transform: recallTransform, compacting: recallCompacting, continuation: recallAutoContinue }`)({ _client: { get: health } }, () => token)const row = { info: { id: 'user-one', sessionID: 'native', role: 'user', agent: 'build' },diff --git a/companions/src/memory/adapters/opencodeRecallPlugin.ts b/companions/src/memory/adapters/opencodeRecallPlugin.tsindex 352b82c76..994dffa1c 100644--- a/companions/src/memory/adapters/opencodeRecallPlugin.ts+++ b/companions/src/memory/adapters/opencodeRecallPlugin.ts@@ -1,6 +1,8 @@+import { pluginFetchSource } from './opencodePluginFetch.js'+/** Native transport only. Retrieval, evidence, scope and controls remain in Harness's shared core. */-export function opencodeRecallPluginSource(port: number): string {- return `+export function opencodeRecallPluginSource(port: number, socket: string | null): string {+ return `${pluginFetchSource('recallFetch', socket)}const recallTurns = new Map(), recallCompactions = new Set(), recallParts = new Set()let recallVersionconst recallMessage = async (input, output) => {@@ -27,7 +29,7 @@ export function opencodeRecallPluginSource(port: number): string {const recallRequest = async (route, sessionID, body, signal) => {const pane = process.env.TMUX_PANE, token = hookToken()if (!pane || !token) return null- const response = await fetch("http://127.0.0.1:${port}/api/hook/" + route, {+ const response = await recallFetch("http://127.0.0.1:${port}/api/hook/" + route, {method: "POST", signal, headers: { "content-type": "application/json", "x-harness-hook-token": token },body: JSON.stringify({ engine: "opencode", sessionId: sessionID, callerPid: process.pid,tmuxPane: pane, runtimeHints: [{ backend: "tmux", paneId: pane }], ...body }),diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex c327d40ef..034130990 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -68,6 +68,7 @@ import 'project_options.dart';import 'switch_pm.dart';import 'project_status_card.dart';import 'pane_layout.dart';+import 'view_room.dart';import '../widgets/dial_list_scroll.dart';import '../widgets/laid_out_list.dart';@@ -2199,7 +2200,10 @@ class _SuperTabViewState extends State<SuperTabView>if (snapshot.isProjectLead(group.id)) {return 'Message #${snapshot.projectFor(group.id)!.name}';}- if (_buddyName(group) case final buddy?) return 'Message $buddy';+ if (_buddyName(group) case final buddy?) {+ // A Buddy's name is its person's and long: a phone's one line says Buddy.+ return _phone ? 'Message Buddy' : 'Message $buddy';+ }return 'Message ${group.title}';}@@ -2208,6 +2212,79 @@ class _SuperTabViewState extends State<SuperTabView>/// icons. Desktop, which sets no [WorkspaceChrome.compactBelow], never.bool get _phone => workspaceIsCompact(context);+ /// Keeps the field mounted when a phone turns past the compact width: a+ /// remounted field keeps focus but loses its text input connection.+ final _composerFieldKey = GlobalKey();++ /// The height above the keyboard below which a phone's composer keeps one row.+ static const _phoneComposerTwoRowsFrom = 320.0;++ /// The lines a phone's field may grow to with [room] above the keyboard: 5,+ /// less what the header and the actions need on a small phone, whose pane+ /// overflowed otherwise (320x568 with a 216 px keyboard, review of #2583).+ /// Never 1: a field of one line is single-line, which strips line breaks+ /// from a draft ("one\ntwo" became "onetwo", test of #2583).+ int _phoneComposerLines(double room) {+ final line = MediaQuery.textScalerOf(context).scale(20);+ return ((room - 275) / line).floor().clamp(2, 5);+ }++ /// The composer's field and its controls: a row on a wide window. A phone+ /// gives the field the width and the controls a row below (Huy, 2026-11-02:+ /// the field had about 40% of the row): [options] and [attach] at the left,+ /// wrapping if they must, and [send] at the right.+ Widget _composerLayout({+ required double room,+ required Widget field,+ required List<Widget> options,+ required Widget attach,+ required Widget send,+ }) {+ // Too little height for a second row (a phone on its side with its keyboard+ // up): the actions take the row's end again. A narrow phone with so little+ // height gets the squeezed row, which beats a composer that overflows.+ if (_phone && room >= _phoneComposerTwoRowsFrom) {+ return Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.only(+ right: grid.AppDesktop.controlGap,+ bottom: grid.AppDesktop.controlGap,+ ),+ child: field,+ ),+ Row(+ key: const ValueKey('super-message-composer-actions'),+ crossAxisAlignment: CrossAxisAlignment.end,+ children: [+ Expanded(+ child: Wrap(+ crossAxisAlignment: WrapCrossAlignment.center,+ children: [...options, attach],+ ),+ ),+ send,+ ],+ ),+ ],+ );+ }+ return ConstrainedBox(+ constraints: BoxConstraints(minHeight: grid.AppControl.heightFieldScaled),+ child: Row(+ crossAxisAlignment: CrossAxisAlignment.center,+ children: [+ Expanded(child: field),+ ...options,+ attach,+ send,+ ],+ ),+ );+ }+/// Whether ⋮ carries the views a wider header draws as icons.bool get _menuNamesViews =>_phone && !_devicesVisible && !_listViewHoldsThePane;@@ -3720,13 +3797,42 @@ class _SuperTabViewState extends State<SuperTabView>key: const ValueKey('super-message-composer-row'),listenable: _composer,builder: (context, field) => Padding(- padding: EdgeInsets.fromLTRB(- 24,- 12,- 24,- pastedFolders().isEmpty ? 16 : 6,- ),- child: field,+ // On a phone the box sits against the keyboard, with the width.+ padding: _phone+ ? const EdgeInsets.all(grid.AppDesktop.controlGap)+ : EdgeInsets.fromLTRB(+ 24,+ 12,+ 24,+ pastedFolders().isEmpty ? 16 : 6,+ ),+ child: _phone+ ? Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ if (c.offersChatSessions &&+ _chatSessions.contains(chatId) &&+ c.threadSessionBlocked == null)+ Padding(+ padding: const EdgeInsets.only(+ bottom: grid.AppDesktop.controlGap,+ ),+ child: Text(+ 'Your message starts its own thread and Buddy session',+ key: const ValueKey('super-chat-session-note'),+ style: DesktopChrome.metadata(+ color: DesktopChrome.muted,+ ),+ ),+ ),+ KeyedSubtree(+ key: const ValueKey('super-message-composer-box'),+ child: field!,+ ),+ ],+ )+ : field,),child: Focus(onKeyEvent: (node, event) {@@ -3793,67 +3899,63 @@ class _SuperTabViewState extends State<SuperTabView>crossAxisAlignment: CrossAxisAlignment.stretch,children: [SuperTabComposerChips(controller: c, files: _files),- ConstrainedBox(- constraints: BoxConstraints(- minHeight: grid.AppControl.heightFieldScaled,- ),- child: Row(- crossAxisAlignment: CrossAxisAlignment.center,- children: [- Expanded(- child: NewHarnessPasteTarget(- attachments: _files,- enabled: writable && !busy,- focusNode: _focus,- child: TextField(- key: const ValueKey(- 'super-message-composer',- ),- controller: _composer,- focusNode: _focus,- autofocus: !_terminalsVisible,- enabled: writable,- minLines: 1,- maxLines:- MediaQuery.sizeOf(context).height <- 600- ? 3- : 8,- maxLength: kComposerMaxLength,- inputFormatters: [_tagBackspace],- keyboardType: TextInputType.multiline,- textAlignVertical:- TextAlignVertical.center,- style: DesktopChrome.text(),- decoration: InputDecoration(- // The row centers the line. Inheriting a decorated- // field's minimum height leaves slack below its text.- isCollapsed: true,- constraints: const BoxConstraints(),- visualDensity: VisualDensity.standard,- hintStyle: DesktopChrome.text(- color: DesktopChrome.muted,- ),- contentPadding: EdgeInsets.zero,- hintText:- _readsFirst && c.snapshot == null- ? null- : group == null- ? 'Loading conversation…'- : c.canWrite- ? _messageHint(group)- : 'Read-only conversation',- border: InputBorder.none,- enabledBorder: InputBorder.none,- focusedBorder: InputBorder.none,- disabledBorder: InputBorder.none,- filled: false,- counterText: '',- ),- onChanged: _composerEdited,+ ViewRoom(+ builder: (context, room) => _composerLayout(+ room: room,+ field: NewHarnessPasteTarget(+ key: _composerFieldKey,+ attachments: _files,+ enabled: writable && !busy,+ focusNode: _focus,+ child: TextField(+ key: const ValueKey('super-message-composer'),+ controller: _composer,+ focusNode: _focus,+ autofocus: !_terminalsVisible,+ enabled: writable,+ minLines: 1,+ // A phone's keyboard takes the height, so+ // its height says nothing about the room+ // a draft should have (Huy, 2026-11-02).+ maxLines: _phone+ ? _phoneComposerLines(room)+ : MediaQuery.sizeOf(context).height < 600+ ? 3+ : 8,+ maxLength: kComposerMaxLength,+ inputFormatters: [_tagBackspace],+ keyboardType: TextInputType.multiline,+ textAlignVertical: TextAlignVertical.center,+ style: DesktopChrome.text(),+ decoration: InputDecoration(+ // The row centers the line. Inheriting a decorated+ // field's minimum height leaves slack below its text.+ isCollapsed: true,+ constraints: const BoxConstraints(),+ visualDensity: VisualDensity.standard,+ hintStyle: DesktopChrome.text(+ color: DesktopChrome.muted,),+ contentPadding: EdgeInsets.zero,+ hintMaxLines: _phone ? 1 : null,+ hintText: _readsFirst && c.snapshot == null+ ? null+ : group == null+ ? 'Loading conversation…'+ : c.canWrite+ ? _messageHint(group)+ : 'Read-only conversation',+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ filled: false,+ counterText: '',),+ onChanged: _composerEdited,),+ ),+ options: [if (c.offersChatSessions)Padding(padding: const EdgeInsets.only(@@ -3870,40 +3972,38 @@ class _SuperTabViewState extends State<SuperTabView>),child: _chatSessionProject(writable),),- fingerTarget(- enabled: _phone,- NewHarnessAttachButton(- attachments: _files,- enabled: writable && !busy,- ),+ ],+ attach: fingerTarget(+ enabled: _phone,+ NewHarnessAttachButton(+ attachments: _files,+ enabled: writable && !busy,),- ListenableBuilder(- listenable: Listenable.merge([- _composer,- _files,- ]),- builder: (context, _) => fingerTarget(- enabled: _phone,- AppIconButton(- icon: AppIcons.arrowUp,- tooltip: 'Send message',- color: DesktopChrome.accent,- onPressed:- writable &&- !c.uploading &&- ((!busy && !c.hasPendingAction) ||- (_files.isEmpty &&- c.canQueueText)) &&- (_composer.text- .trim()- .isNotEmpty ||- !_files.isEmpty)- ? () => unawaited(_send())- : null,- ),+ ),+ send: ListenableBuilder(+ listenable: Listenable.merge([+ _composer,+ _files,+ ]),+ builder: (context, _) => fingerTarget(+ enabled: _phone,+ AppIconButton(+ icon: AppIcons.arrowUp,+ tooltip: 'Send message',+ color: DesktopChrome.accent,+ onPressed:+ writable &&+ !c.uploading &&+ ((!busy && !c.hasPendingAction) ||+ (_files.isEmpty &&+ c.canQueueText)) &&+ (_composer.text.trim().isNotEmpty ||+ !_files.isEmpty)+ ? () => unawaited(_send())+ : null,),),- ],+ ),),),],@@ -3915,8 +4015,9 @@ class _SuperTabViewState extends State<SuperTabView>),),// While New session can be chosen here, its line's place is kept, so- // the box never moves as the choice is toggled.- if (c.offersChatSessions)+ // the box never moves as the choice is toggled. Not on a phone, where+ // that line held the box off the keyboard: it shows above the box.+ if (c.offersChatSessions && !_phone)Container(alignment: Alignment.centerLeft,padding: const EdgeInsets.only(diff --git a/desktop/lib/super_tabs/view_room.dart b/desktop/lib/super_tabs/view_room.dartnew file mode 100644index 000000000..ebbb4318f--- /dev/null+++ b/desktop/lib/super_tabs/view_room.dart@@ -0,0 +1,40 @@+import 'package:flutter/widgets.dart';++/// Builds with the height left on screen above an on-screen keyboard. Reads the+/// view itself: a Scaffold hands its body a MediaQuery with the keyboard's inset+/// taken out and its size whole, so the body never sees it there.+class ViewRoom extends StatefulWidget {+ const ViewRoom({super.key, required this.builder});++ final Widget Function(BuildContext context, double room) builder;++ @override+ State<ViewRoom> createState() => _ViewRoomState();+}++class _ViewRoomState extends State<ViewRoom> with WidgetsBindingObserver {+ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ void didChangeMetrics() => setState(() {});++ @override+ Widget build(BuildContext context) {+ final view = View.of(context);+ return widget.builder(+ context,+ (view.physicalSize.height - view.viewInsets.bottom) /+ view.devicePixelRatio,+ );+ }+}diff --git a/desktop/lib/ws/local_daemon_transport.dart b/desktop/lib/ws/local_daemon_transport.dartindex b2c61b72d..67f592a3a 100644--- a/desktop/lib/ws/local_daemon_transport.dart+++ b/desktop/lib/ws/local_daemon_transport.dart@@ -10,6 +10,7 @@ import '../core/test_run.dart';import 'daemon_pipe_record.dart';import 'trusted_pipe.dart';import 'windows_pipe.dart';+import 'package:cryptography/dart.dart';/// The daemon's Unix socket, beside its loopback port (CLI `lib/localSocket.ts`).///@@ -20,8 +21,8 @@ import 'windows_pipe.dart';/// 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.+/// socket missing, the daemon is down. The port remains only where neither the+/// data folder nor the home folder is short enough 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@@ -36,7 +37,7 @@ const _maxSocketPathBytes = 96;/// Where the socket of the daemon on [port] would be —/// `$ADAPTER_DATA_DIR/daemon-<port>.sock`, by default/// `~/.harness/cli/data/daemon-<port>.sock` — or null where there is none-/// (Windows, or a path too long to be a socket).+/// (Windows, or a home too long as well).String? defaultDaemonSocketPath(int port, {Map<String, String>? environment,@@ -49,7 +50,16 @@ String? defaultDaemonSocketPath();if (dataDir == null) return null;final path = '$dataDir/${daemonSocketName(port)}';- return utf8.encode(path).length <= _maxSocketPathBytes ? path : null;+ if (utf8.encode(path).length <= _maxSocketPathBytes) return path;+ // Too long to hold a socket: the daemon's is under the home folder, named by+ // the folder's hash (CLI `lib/localSocket.ts` `socketPathIn`).+ // No HOME: the empty path has no socket, so this reads as the daemon being+ // down, never as a place with no socket at all, which would allow the port.+ final home = (environment ?? Platform.environment)['HOME'] ?? '';+ final hash = const DartSha256().hashSync(utf8.encode(dataDir)).bytes;+ final hex = hash.take(8).map((b) => b.toRadixString(16).padLeft(2, '0')).join();+ final short = '$home/.harness/s/$hex/${daemonSocketName(port)}';+ return utf8.encode(short).length <= _maxSocketPathBytes ? short : null;}/// The header a call to the daemon's loopback PORT carries its localdiff --git a/desktop/test/local_daemon_transport_test.dart b/desktop/test/local_daemon_transport_test.dartindex c49b5d8d6..9c2fc44b1 100644--- a/desktop/test/local_daemon_transport_test.dart+++ b/desktop/test/local_daemon_transport_test.dart@@ -135,12 +135,44 @@ void main() {'/srv/h/daemon-18474.sock',);expect(defaultDaemonSocketPath(18473, environment: {'HOME': '/Users/me'}, isWindows: true), isNull);+ // Too long for a socket: under the home folder, by the folder's hash, the+ // same hash as the CLI's (pinned for `/x` in cli localSocket.spec.ts).+ expect(+ defaultDaemonSocketPath(+ 18473,+ environment: {'HOME': '/h', 'ADAPTER_DATA_DIR': '/${'x' * 100}'},+ isWindows: false,+ ),+ matches(RegExp(r'^/h/\.harness/s/[0-9a-f]{16}/daemon-18473\.sock$')),+ );expect(defaultDaemonSocketPath(18473, environment: {'HOME': '/${'x' * 100}'}, isWindows: false),isNull,);});+ test('a long folder\'s socket matches the CLI\'s hash', () {+ // sha256('/' + 'x' * 100)[0..16], as cli/src/lib/localSocket.ts computes it.+ expect(+ defaultDaemonSocketPath(+ 1,+ environment: {'HOME': '/h', 'ADAPTER_DATA_DIR': '/${'x' * 100}'},+ isWindows: false,+ ),+ '/h/.harness/s/e50e7828cbafcbee/daemon-1.sock',+ );+ });++ test('a long folder with no HOME still has a socket to fail on, so the port is not allowed', () {+ final path = defaultDaemonSocketPath(+ 1,+ environment: {'ADAPTER_DATA_DIR': '/${'x' * 100}'},+ isWindows: false,+ );+ expect(path, isNotNull);+ expect(File(path!).existsSync(), isFalse);+ });+test('is never looked for under flutter test', () {expect(LocalDaemonTransport.detect(Uri.parse('http://127.0.0.1:18473')).candidate,diff --git a/desktop/test/super_tab_phone_composer_test.dart b/desktop/test/super_tab_phone_composer_test.dartnew file mode 100644index 000000000..c6cbdf776--- /dev/null+++ b/desktop/test/super_tab_phone_composer_test.dart@@ -0,0 +1,366 @@+// The message box on a phone's browser (Huy, 2026-11-02, IMG_4431): the field+// had about 40% of the width, sharing its row with New session, attach and+// send, its hint wrapped, and a line kept free under the box held it off the+// keyboard. On a phone the field has the width and the actions a row below.++import 'dart:typed_data';++import 'package:flutter/material.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/widgets/app_icon_button.dart';+import 'package:harness/state/harness_attachments.dart';++import 'support/super_tab_fixture.dart';+import 'support/super_tab_phone.dart';++const _phone = Size(390, 844);+final _surface = find.byKey(const ValueKey('super-message-composer-surface'));+final _field = find.byKey(const ValueKey('super-message-composer'));+final _actions = find.byKey(const ValueKey('super-message-composer-actions'));+final _send = find.byTooltip('Send message');+final _attach = find+ .descendant(of: _surface, matching: find.byType(AppIconButton))+ .first;++final _session = find.byKey(const ValueKey('super-chat-new-session'));+final _note = find.byKey(const ValueKey('super-chat-session-note'));++/// The reader's own Buddy chat ('offline' in the fixture), with New session on+/// offer and a long Buddy name, as in Huy's screenshot.+ConversationServer _buddyChat() {+ final server = ConversationServer()..threads = true;+ server.state['threadSessions'] = true;+ server.state['sessionsFromChat'] = true;+ final chat =+ (server.state['conversations'] as List)[1] as Map<String, dynamic>+ ..['kind'] = 'buddy'+ ..['buddyOwnerId'] = 'owner'+ ..['title'] = "phamngochuy.1989's Buddy";+ (server.state['agents'] as List).add({+ 'id': 'buddy-main',+ 'name': "phamngochuy.1989's Buddy",+ 'displayName': "phamngochuy.1989's Buddy",+ 'machineId': 'mac',+ 'harnessId': 'h-main',+ 'contributorId': 'owner',+ 'buddyOf': {'personId': 'owner', 'generation': 'g1'},+ 'configuration': {'engine': 'claude'},+ });+ chat['agentIds'] = ['buddy-main'];+ server.append('Hello', conversationId: 'offline');+ return server;+}++void main() {+ testWidgets(+ 'on a phone the field spans the box and the actions sit below it',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(tester, _phone);+ final surface = tester.getRect(_surface), field = tester.getRect(_field);+ expect(surface.width - field.width, lessThanOrEqualTo(32));+ expect(_actions, findsOneWidget);+ expect(tester.getRect(_actions).top, greaterThanOrEqualTo(field.bottom));+ expect(tester.getRect(_send).top, greaterThanOrEqualTo(field.bottom));+ // Send at the right, attach at the left, each a finger's size.+ expect(tester.getRect(_attach).right, lessThan(surface.center.dx));+ expect(tester.getRect(_send).left, greaterThan(surface.center.dx));+ expect(tester.getSize(_send).height, greaterThanOrEqualTo(44));+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ },+ );++ testWidgets(+ 'the field grows to 5 lines, then scrolls, and the actions stay',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(tester, _phone);+ final one = tester.getSize(_field).height;+ await tester.enterText(_field, List.filled(5, 'line').join('\n'));+ await tester.pump();+ final five = tester.getSize(_field).height;+ expect(five, greaterThan(one * 4));+ await tester.enterText(_field, List.filled(12, 'line').join('\n'));+ await tester.pump();+ expect(tester.getSize(_field).height, five);+ expect(tester.getRect(_send).bottom, lessThanOrEqualTo(_phone.height));+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ },+ );++ testWidgets(+ '5 lines hold on a short screen too: the keyboard takes the height',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(tester, const Size(390, 500));+ final one = tester.getSize(_field).height;+ await tester.enterText(_field, List.filled(8, 'line').join('\n'));+ await tester.pump();+ expect(tester.getSize(_field).height, greaterThan(one * 4));+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ },+ );++ testWidgets('a draft and its focus survive turning past the phone width', (+ tester,+ ) async {+ final (_, c) = await mountPhoneSuperTab(tester, _phone);+ await tester.tap(_field);+ await tester.enterText(_field, 'a draft');+ await tester.pump();+ tester.view.physicalSize = const Size(1280, 800);+ await tester.pumpAndSettle();+ expect(tester.widget<TextField>(_field).controller!.text, 'a draft');+ expect(tester.widget<TextField>(_field).focusNode!.hasFocus, isTrue);+ expect(tester.testTextInput.isVisible, isTrue);+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ });++ testWidgets('a wider window keeps one row', (tester) async {+ final (_, c) = await mountPhoneSuperTab(+ tester,+ const Size(1280, 800),+ desktop: true,+ );+ expect(_actions, findsNothing);+ final field = tester.getRect(_field), send = tester.getRect(_send);+ expect(send.left, greaterThanOrEqualTo(field.right));+ expect(send.center.dy, closeTo(field.center.dy, 12));+ await unmountPhoneSuperTab(tester, c);+ });++ testWidgets(+ 'the box sits against the bottom, with nothing kept free under it',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(tester, _phone);+ expect(+ _phone.height - tester.getRect(_surface).bottom,+ lessThanOrEqualTo(8),+ );+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ },+ );++ testWidgets(+ 'in a Buddy chat: a one-line hint, New session below the field, its note above the box, nothing under it',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(+ tester,+ _phone,+ server: _buddyChat(),+ initial: 'offline',+ );+ expect(find.text('Message Buddy'), findsOneWidget);+ expect(tester.widget<TextField>(_field).decoration!.hintMaxLines, 1);+ expect(+ tester.getRect(_session).top,+ greaterThanOrEqualTo(tester.getRect(_field).bottom),+ );+ expect(+ tester.getRect(_session).right,+ lessThan(tester.getRect(_send).left),+ );+ expect(_note, findsNothing);+ expect(+ _phone.height - tester.getRect(_surface).bottom,+ lessThanOrEqualTo(8),+ );+ await tester.enterText(_field, 'a draft');+ await tester.tap(_session);+ await tester.pump();+ expect(+ tester.getRect(_note).bottom,+ lessThanOrEqualTo(tester.getRect(_surface).top),+ );+ expect(+ _phone.height - tester.getRect(_surface).bottom,+ lessThanOrEqualTo(8),+ );+ // The field kept its input through the line coming in above it.+ expect(tester.widget<TextField>(_field).controller!.text, 'a draft');+ expect(tester.testTextInput.isVisible, isTrue);+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ },+ );++ testWidgets('a narrow phone with large text does not overflow', (+ tester,+ ) async {+ final (_, c) = await mountPhoneSuperTab(+ tester,+ const Size(320, 640),+ server: _buddyChat(),+ initial: 'offline',+ textScale: 1.5,+ );+ expect(_actions, findsOneWidget);+ expect(tester.getRect(_send).right, lessThanOrEqualTo(320));+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ });++ testWidgets('a long chat title stays one line in its hint', (tester) async {+ final (_, c) = await mountPhoneSuperTab(+ tester,+ _phone,+ seed: (server) {+ ((server.state['conversations'] as List).first as Map)['title'] = 'A very long conversation title that would have wrapped on this phone';+ },+ );+ expect(tester.widget<TextField>(_field).decoration!.hintMaxLines, 1);+ expect(tester.getSize(_field).height, lessThan(30));+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ });++ // Found in review at 696bfb0c4: a 5-line field on a small phone with the+ // keyboard up overflowed the pane by 23 px.+ for (final (height, keyboard) in [+ (568.0, 216.0),+ (568.0, 260.0),+ (667.0, 260.0),+ ]) {+ testWidgets(+ 'a long draft with New session on fits a 320x$height phone with a ${keyboard}px keyboard',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(+ tester,+ Size(320, height),+ server: _buddyChat(),+ initial: 'offline',+ );+ tester.view.viewInsets = FakeViewPadding(bottom: keyboard);+ addTearDown(tester.view.resetViewInsets);+ await tester.pumpAndSettle();+ await tester.enterText(_field, List.filled(12, 'line').join('\n'));+ await tester.tap(_session);+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ expect(+ tester.getRect(_send).bottom,+ lessThanOrEqualTo(height - keyboard),+ );+ await unmountPhoneSuperTab(tester, c);+ },+ );+ }++ testWidgets('the keyboard closing gives the field its 5 lines back', (+ tester,+ ) async {+ final (_, c) = await mountPhoneSuperTab(tester, const Size(320, 568));+ tester.view.viewInsets = const FakeViewPadding(bottom: 216);+ addTearDown(tester.view.resetViewInsets);+ await tester.pumpAndSettle();+ await tester.enterText(_field, List.filled(12, 'line').join('\n'));+ await tester.pumpAndSettle();+ final small = tester.getSize(_field).height;+ tester.view.resetViewInsets();+ await tester.pumpAndSettle();+ expect(tester.getSize(_field).height, greaterThan(small));+ expect(+ tester.widget<TextField>(_field).controller!.text.split('\n'),+ hasLength(12),+ );+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ });++ testWidgets('a phone on its side with its keyboard up keeps one row', (+ tester,+ ) async {+ final (_, c) = await mountPhoneSuperTab(tester, const Size(667, 375));+ expect(_actions, findsOneWidget);+ tester.view.viewInsets = const FakeViewPadding(bottom: 190);+ addTearDown(tester.view.resetViewInsets);+ await tester.pumpAndSettle();+ expect(_actions, findsNothing);+ await tester.enterText(_field, 'a draft');+ await tester.pumpAndSettle();+ expect(tester.widget<TextField>(_field).controller!.text, 'a draft');+ expect(tester.testTextInput.isVisible, isTrue);+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ });++ testWidgets(+ 'a short screen with a file, the note and a long draft does not overflow',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(+ tester,+ const Size(390, 320),+ server: _buddyChat(),+ initial: 'offline',+ );+ c.attachments('offline').add([+ HarnessAttachment('notes.txt', Uint8List(4)),+ ]);+ await tester.tap(_session);+ await tester.enterText(_field, List.filled(12, 'line').join('\n'));+ await tester.pumpAndSettle();+ expect(_note, findsOneWidget);+ expect(find.text('notes.txt'), findsOneWidget);+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ },+ );++ testWidgets(+ 'a narrow phone with under 280 px left keeps one row, squeezed but whole',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(+ tester,+ const Size(320, 568),+ server: _buddyChat(),+ initial: 'offline',+ );+ tester.view.viewInsets = const FakeViewPadding(bottom: 300);+ addTearDown(tester.view.resetViewInsets);+ await tester.pumpAndSettle();+ await tester.enterText(_field, List.filled(12, 'line').join('\n'));+ await tester.tap(_session);+ await tester.pumpAndSettle();+ expect(tester.takeException(), isNull);+ expect(tester.getRect(_send).right, lessThanOrEqualTo(320));+ await unmountPhoneSuperTab(tester, c);+ },+ );++ // The Tester at b68a639b7: a field of one line is a single-line field, which+ // strips line breaks, so a draft of three lines became "onetwothree".+ for (final (size, keyboard) in [+ (const Size(320, 308), 0.0),+ (const Size(390, 308), 0.0),+ (const Size(320, 568), 260.0),+ (const Size(320, 568), 300.0),+ (const Size(667, 375), 190.0),+ ]) {+ testWidgets(+ 'line breaks survive at ${size.width}x${size.height} with a ${keyboard}px keyboard, and nothing overflows',+ (tester) async {+ final (_, c) = await mountPhoneSuperTab(+ tester,+ size,+ server: _buddyChat(),+ initial: 'offline',+ );+ tester.view.viewInsets = FakeViewPadding(bottom: keyboard);+ addTearDown(tester.view.resetViewInsets);+ await tester.pumpAndSettle();+ await tester.enterText(_field, 'one\ntwo\nthree');+ await tester.pumpAndSettle();+ expect(+ tester.widget<TextField>(_field).controller!.text,+ 'one\ntwo\nthree',+ );+ // At least the 2 lines main gives there.+ expect(tester.getSize(_field).height, greaterThanOrEqualTo(40));+ expect(tester.takeException(), isNull);+ await unmountPhoneSuperTab(tester, c);+ },+ );+ }+}diff --git a/desktop/test/support/super_tab_phone.dart b/desktop/test/support/super_tab_phone.dartindex 0b311f9b1..123fc2847 100644--- a/desktop/test/support/super_tab_phone.dart+++ b/desktop/test/support/super_tab_phone.dart@@ -20,16 +20,24 @@ Future<(ConversationServer, SuperTabController)> mountPhoneSuperTab(bool terminalsVisible = false,bool desktop = false,void Function(ConversationServer server)? seed,+ ConversationServer? server,+ String? initial,+ double textScale = 1,}) async {tester.view.devicePixelRatio = 1;tester.view.physicalSize = size;addTearDown(tester.view.reset);- final server = ConversationServer()..append('Ship the phone header.');- final lead = (server.state['conversations'] as List).first as Map;- lead['agentIds'] = ['builder'];- seed?.call(server);- final controller = server.controller();+ final given = server;+ final server0 =+ given ?? (ConversationServer()..append('Ship the phone header.'));+ if (given == null) {+ final lead = (server0.state['conversations'] as List).first as Map;+ lead['agentIds'] = ['builder'];+ }+ seed?.call(server0);+ final controller = server0.controller();await controller.refresh();+ if (initial != null) await controller.select(initial);final view = Scaffold(body: SuperTabView(controller: controller,@@ -43,13 +51,18 @@ Future<(ConversationServer, SuperTabController)> mountPhoneSuperTab();await tester.pumpWidget(MaterialApp(+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(textScale)),+ child: child!,+ ),home: desktop? view: WorkspaceChromeScope(chrome: _phoneChrome, child: view),),);await tester.pumpAndSettle();- return (server, controller);+ return (server0, controller);}Future<void> unmountPhoneSuperTab(diff --git a/docs/plans/2026-11-02-mobile-web-composer-plan.md b/docs/plans/2026-11-02-mobile-web-composer-plan.mdnew file mode 100644index 000000000..476be9a8f--- /dev/null+++ b/docs/plans/2026-11-02-mobile-web-composer-plan.md@@ -0,0 +1,62 @@+# Mobile web: two-level message composer Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** On mobile web the message field spans the full width and grows to about 5 lines, with New session and attach left and send right on a row below it, right above the keyboard.++**Architecture:** One branch in `SuperTabView`'s composer on `_phone` (`workspaceIsCompact`, true only on the web below `compactBelow`), which already decides every phone layout there. The field and each action stay the same widgets, so sending, drafts, drop and paste are shared; only their arrangement differs. Nothing changes where `_phone` is false.++**Tech Stack:** Flutter 3.47, widget tests with `test/support/super_tab_phone.dart`.++**Spec:** Task #2114 (Huy, IMG_4431), its ASCII mockup in the task chat.++## Global Constraints++- Mobile web only; desktop and wide layouts unchanged.+- The Harness design language: existing tokens and widgets (`AppIconButton`, `SuperTabComposerToggle`, `DesktopChrome`), finger-size targets on a phone.+- Short placeholder: "Message Buddy" in the reader's Buddy chat, on one line.+- The field grows to 5 lines, then scrolls.+- Safari's own password/card/location row above the keyboard cannot be removed from a web page: the composer sits against it.+- PR body starts: `Requested by [email protected] through Harness.`++## Review Focus++- A long draft at 5 lines: the field scrolls inside itself and the send row stays visible, even with little height left above the keyboard.+- Typing across a rotation or a resize past the compact width: the draft, its cursor and focus survive the change of arrangement.+- Text scaled up, or a narrow 320 px phone with New session and its project menu both showing: the action row does not overflow.+- A chat that does not offer New session (a task, the project chat): attach and send still sit on the row below, send at the right.+- Files attached: their chips stay above the field, and a long title's placeholder stays on one line in every chat.++---++### Task 1: The phone arrangement++**Files:**+- Modify: `desktop/lib/super_tabs/view.dart` (composer around `super-message-composer-surface`, the note below it, `_messageHint`)+- Test: `desktop/test/super_tab_phone_composer_test.dart` (new)++**Interfaces:**+- Consumes: `mountPhoneSuperTab(tester, Size)`, `unmountPhoneSuperTab` from `test/support/super_tab_phone.dart`.+- Produces: `ValueKey('super-message-composer-actions')` on the row below the field, for the Tester and later tests.++- [ ] **Step 1: Write the failing tests** at 390x844: the field spans the surface's inner width; the actions sit below it, attach left of send and send at the right edge; 5 lines of text grow the field and 8 do not grow it further; a 1 line hint; at 320 px with New session no overflow; 1280 wide keeps one row.+- [ ] **Step 2: Run them and watch them fail** with `flutter test test/super_tab_phone_composer_test.dart`.+- [ ] **Step 3: Implement**: build the field and actions once; `_phone` lays them out as a Column, else the existing Row. `maxLines` 5 on a phone. Short hint on a phone.+- [ ] **Step 4: Run them and watch them pass.**+- [ ] **Step 5: Commit.**++### Task 2: Against the keyboard++**Files:**+- Modify: `desktop/lib/super_tabs/view.dart` (row padding, `super-chat-session-note`)+- Test: `desktop/test/super_tab_phone_composer_test.dart`++**Interfaces:**+- Consumes: `super-message-composer-surface`, `super-chat-session-note`.+- Produces: nothing new.++- [ ] **Step 1: Write the failing tests**: on a phone, the distance from the surface's bottom to the screen's bottom is at most 8 with New session off and on; the note, shown only while on, sits above the surface; a wider window keeps its reserved line.+- [ ] **Step 2: Run them and watch them fail.**+- [ ] **Step 3: Implement**: on a phone no reserved note line, the note above the box only while on, side padding 12, bottom 8.+- [ ] **Step 4: Run them, and the composer test files that name changed symbols (`grep -l super-message-composer`, `super-chat-session-note`).**+- [ ] **Step 5: Commit, open the pull request, add the review step (Rowan) and test step (Tester on Tony's Mac).**diff --git a/docs/plans/2026-11-02-opencode-plugins-long-folder-socket-plan.md b/docs/plans/2026-11-02-opencode-plugins-long-folder-socket-plan.mdnew file mode 100644index 000000000..f49f927ee--- /dev/null+++ b/docs/plans/2026-11-02-opencode-plugins-long-folder-socket-plan.md@@ -0,0 +1,108 @@+# OpenCode plugins and long data folders stop sending tokens to the port: Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** The CLI's engine plugins (OpenCode, Kilo, Pi, Amp), companions' OpenCode plugins, and any client of a daemon whose data folder is too long for a socket, send nothing to the daemon's or the bridge's TCP port on macOS and Linux.++**Architecture:** One rule for a socket's path, in every client: `<folder>/<name>` when it fits in 96 bytes, else `<home>/.harness/s/<first 16 hex of sha256(folder)>/<name>`, a 0700 folder of this account's. Home, not a temp folder: `/tmp` is shared (audit M1) and `TMPDIR` differs between launchd and a shell, so clients would disagree. The plugins take the socket's path and post through `node:http`, which OpenCode's runtime and Node both have.++**Tech Stack:** TypeScript and Node built-ins in the CLI; plain Node ESM in `notify.mjs` and Store's `localDaemon.mjs`; Dart with `cryptography` in Desktop.++**Spec:** Task #2112 (left open by #2566 and #2576). Audit H1: `docs/security/2026-11-02-team-account-boundary.md`.++## Global Constraints++- No path may send a key, token or request to the port where a socket can be. No fallback to TCP.+- A client checks the socket before sending: this account's, owner only, in a real folder nobody else can write to.+- The default data folder's socket does not move: same path, same behaviour.+- Windows is unchanged.+- Store packages stay free of dependencies, and `localDaemon.mjs` stays identical in every copy.+- No test writes to the real `~/.harness`: a test that makes a long-folder socket sets `HOME`.++## Review Focus++1. A home so long the short path doesn't fit either: the one remaining TCP case, as today, and it says so in the code.+2. `.harness/s` already there, and looser or owned by another account: the daemon tightens or refuses, and clients refuse it.+3. `HOME` differing between the daemon and a client (`env -i`, a guest): the client finds no socket and says the daemon is down; nothing goes to the port.+4. Two data folders at once: different hashes, so neither takes the other's socket.+5. A plugin's answer over 64 KB, or a timeout mid-answer: `null`, as the `fetch` version gave, and the request is cut.++## Design++- Growth: `harness reset` removes this data folder's short folder; otherwise one folder per long data folder.+- Concurrency: one listener per socket, as today (`listenLocalSocket`).+- Read cost: N/A because the rule is a string and one hash, once per lookup.+- Scale: N/A because no client makes more connections than it did.+- Compatibility: an old client on a long folder still uses TCP, and a daemon from #2550 refuses its secret from another account. A new client with an old daemon on a long folder finds no socket and says it is down until the daemon updates.+- Migration + rollback: no data. A rollback returns long folders to TCP.+- Audience: the filesystem enforces it.+- Identity: the OS account; no login is read.+- Failure: a folder that cannot be made or is not private fails the listen, which is logged, and clients say the daemon is down.+- Platforms: macOS and Linux. TUI is unchanged: it never used the port, and on a long folder it still can't connect (in the PR's Still open).++---++### Task 1: The rule, in the CLI++**Files:**+- Modify: `cli/src/lib/localSocket.ts`, `cli/src/lib/localTransport.ts`, `cli/src/lib/connectors/agents.ts`, `cli/src/cli.ts` (reset)+- Test: `cli/src/lib/localSocket.spec.ts`, `cli/src/cloud/bridge.socket.spec.ts`++**Interfaces:**+- Produces: `socketPathIn(folder: string, name: string, home?: string): string | null` in `localSocket.ts`; `unixSocketPath` and `bridgeSocketPath` both use it.++- [ ] **Step 1: Write the failing tests:** `socketPathIn` keeps a short path; a long folder gives `<home>/.harness/s/<16 hex>/daemon-1.sock`, the same each time and different for another folder; a long home gives `null`. `listenLocalSocket` on that path makes a 0700 folder and a 0600 socket, and refuses a folder of the wrong owner or mode it can't tighten.+- [ ] **Step 2: Run:** `npx vitest run src/lib/localSocket.spec.ts`. Expected: FAIL, `socketPathIn` is not defined.+- [ ] **Step 3: Implement** `socketPathIn`; `listenLocalSocket` makes the short folder; `localSocketRoute` uses the rule for recorded ports; reset removes the short folder.+- [ ] **Step 4: Run** the same, plus every spec that named a long folder as TCP, now with a long `HOME`. Expected: PASS.+- [ ] **Step 5: Commit.**++### Task 2: A long folder sends nothing to the port, in every other client++**Files:**+- Modify: `cli/hook/notify.mjs`, `store/tools/local-daemon.mjs` and its four copies, `desktop/lib/ws/local_daemon_transport.dart`+- Test: `store/tools/port-holder.test.mjs`, `cli/e2e/hookclient.e2e.ts` or the hook's own spec, `desktop/test/local_daemon_transport_test.dart`++**Interfaces:**+- Consumes: the rule from Task 1, as a pinned vector: folder `/x` gives hash `sha256('/x')[0..16]`, the same in Node and Dart.++- [ ] **Step 1: Write the failing tests:** each Store client with a long data folder and a listener on the port: it hears nothing, and each works over a fake daemon on the short socket. The hook: nothing on the port, and the post arrives over the short socket. Desktop: the same path as the vector.+- [ ] **Step 2: Run:** `node --test store/tools/port-holder.test.mjs`. Expected: FAIL, the holder hears the credential.+- [ ] **Step 3: Implement** the rule in each.+- [ ] **Step 4: Run** the same and each package's suite. Expected: PASS.+- [ ] **Step 5: Commit.**++### Task 3: The OpenCode plugins post over the socket++**Files:**+- Modify: `companions/src/memory/adapters/opencodeMemoryPlugin.ts`, `opencodeRecallPlugin.ts`, the three `companions/scripts/memory-native-opencode-*-probe.mjs` that embed them+- Test: both adapters' specs++**Interfaces:**+- Produces: `opencodeMemoryPluginSource(socket: string)`, `opencodeRecallPluginSource(socket: string)`.++- [ ] **Step 1: Write the failing tests:** with a listener on a port and a real server on a private socket, each plugin's post arrives on the socket with its token, and the listener hears nothing. A socket that isn't private: no post, `null`. An answer over 64 KB: `null`. An abort: `null`, and the request is cut.+- [ ] **Step 2: Run:** `npx vitest run src/memory/adapters`. Expected: FAIL, the plugin called `fetch` on the port.+- [ ] **Step 3: Implement** one helper in each source, on `node:http` and `node:fs`, loaded by dynamic import.+- [ ] **Step 4: Run** the same. Expected: PASS.+- [ ] **Step 5: Commit.**++### Task 4: The CLI's engine plugins post over the socket++**Files:**+- Modify: `cli/src/engines/{opencode,kilo,pi,amp}/contract.ts`, their shared template kit, and their golden fixtures+- Test: a new `cli/src/engines/pluginPosts.spec.ts`++**Interfaces:**+- Consumes: `unixSocketPath` from Task 1.+- Produces: a template argument `socket: string | null`, and one `harnessPost(path, body)` helper in each plugin's source. A plugin's version moves, so a daemon reinstalls it at start.++- [ ] **Step 1: Write the failing test:** each of the four plugins, rendered and run in Node with a listener on the port and a server on a private socket: the session-start and its token arrive on the socket, and the listener hears nothing. With the socket missing or not private: no post, and nothing on the port. With no socket (Windows, or a home too long): the post goes to the port, as today.+- [ ] **Step 2: Run:** `npx vitest run src/engines/pluginPosts.spec.ts`. Expected: FAIL, the listener hears the token.+- [ ] **Step 3: Implement** the helper on `node:http` and `node:fs`, and the argument.+- [ ] **Step 4: Run** the same and the engines' golden specs. Expected: PASS once the goldens are regenerated, with the diff read.+- [ ] **Step 5: Commit.**++## Left open++- No real OpenCode, Kilo, Pi or Amp session has run the new plugin source unless one is installed where the Tester runs.diff --git a/store/agents/autonomous-grid/lib/localDaemon.mjs b/store/agents/autonomous-grid/lib/localDaemon.mjsindex dc4cdf86d..b7a10e28d 100644--- a/store/agents/autonomous-grid/lib/localDaemon.mjs+++ b/store/agents/autonomous-grid/lib/localDaemon.mjs@@ -23,11 +23,17 @@ export function daemonDataDir(env = process.env) {return env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')}-/** The daemon's socket for `port`, or null where it can have none: Windows, or a path too long. */+/**+ * The daemon's socket for `port`: in its data folder, or where that path is too long for a socket, in a 0700 folder under the home folder+ * named by the folder's hash (the CLI's `socketPathIn`). Null where it can have none: Windows, or a home too long as well.+ */export function daemonSocketPath(port, env = process.env, platform = process.platform) {if (platform === 'win32') return null- const path = join(daemonDataDir(env), `daemon-${port}.sock`)- return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null+ const folder = daemonDataDir(env), name = `daemon-${port}.sock`, beside = join(folder, name)+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH_BYTES) return beside+ const hash = createHash('sha256').update(folder).digest('hex').slice(0, 16)+ const short = join(env.HOME || homedir(), '.harness', 's', hash, name)+ return Buffer.byteLength(short) <= MAX_SOCKET_PATH_BYTES ? short : null}/** Whether `path` is the daemon's: a socket of this account's, owner only, in a real folder nobody else can write to. */diff --git a/store/agents/autonomous-grid/test/credential.test.mjs b/store/agents/autonomous-grid/test/credential.test.mjsindex 6e76fed94..983f55319 100644--- a/store/agents/autonomous-grid/test/credential.test.mjs+++ b/store/agents/autonomous-grid/test/credential.test.mjs@@ -8,6 +8,9 @@ import { harnessExecute, localCredentialHeaders } from '../lib/harness.mjs';import { daemonWake } from '../lib/wake.mjs';import { fakeBridge } from './fakes.mjs';+// A folder too long for a socket has one under the home folder: only a home too long as well is left on the port.+process.env.HOME = `/${'h'.repeat(120)}`;+const CREDENTIAL = `test-local-credential-${'a'.repeat(21)}`; // the CLI's shape: 43 base64url charactersconst machine = { id:'rig', name:'GPU rig', transport:'harness', machineId:'machine-123' };diff --git a/store/agents/autonomous-grid/test/wake.test.mjs b/store/agents/autonomous-grid/test/wake.test.mjsindex 8958886e9..d1d4632a0 100644--- a/store/agents/autonomous-grid/test/wake.test.mjs+++ b/store/agents/autonomous-grid/test/wake.test.mjs@@ -64,7 +64,8 @@ async function listen(t, base) {}/** A viewer on a workspace looking at [grid], asleep, a fake `grid` it reads with, and a fake bridge. */-// Too long a path to hold a socket: the fake bridge here is on TCP.+// Too long a path to hold a socket, and a home too long as well: the fake bridge here is on TCP.+process.env.HOME = `/${'h'.repeat(120)}`;const NO_SOCKET = join(tmpdir(), 'grid-wake-'.padEnd(120, 'x'));async function setup(t, respond, { grid = 'test-grid', verbs = verbsFor(grid, 'asleep'), bridgeUrl, giveUpMs = 5000, intervalMs = 50 } = {}) {const dir = await mkdtemp(join(tmpdir(), 'grid-wake-')), log = join(dir, 'calls.log');diff --git a/store/agents/harness-monitor/lib/localDaemon.mjs b/store/agents/harness-monitor/lib/localDaemon.mjsindex dc4cdf86d..b7a10e28d 100644--- a/store/agents/harness-monitor/lib/localDaemon.mjs+++ b/store/agents/harness-monitor/lib/localDaemon.mjs@@ -23,11 +23,17 @@ export function daemonDataDir(env = process.env) {return env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')}-/** The daemon's socket for `port`, or null where it can have none: Windows, or a path too long. */+/**+ * The daemon's socket for `port`: in its data folder, or where that path is too long for a socket, in a 0700 folder under the home folder+ * named by the folder's hash (the CLI's `socketPathIn`). Null where it can have none: Windows, or a home too long as well.+ */export function daemonSocketPath(port, env = process.env, platform = process.platform) {if (platform === 'win32') return null- const path = join(daemonDataDir(env), `daemon-${port}.sock`)- return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null+ const folder = daemonDataDir(env), name = `daemon-${port}.sock`, beside = join(folder, name)+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH_BYTES) return beside+ const hash = createHash('sha256').update(folder).digest('hex').slice(0, 16)+ const short = join(env.HOME || homedir(), '.harness', 's', hash, name)+ return Buffer.byteLength(short) <= MAX_SOCKET_PATH_BYTES ? short : null}/** Whether `path` is the daemon's: a socket of this account's, owner only, in a real folder nobody else can write to. */diff --git a/store/agents/harness-monitor/test/credential.test.mjs b/store/agents/harness-monitor/test/credential.test.mjsindex bf0330cb4..0f2f372a7 100644--- a/store/agents/harness-monitor/test/credential.test.mjs+++ b/store/agents/harness-monitor/test/credential.test.mjs@@ -7,6 +7,9 @@ import { join } from 'node:path'import { test } from 'node:test'import { closeBridges, listAgents, localCredentialHeaders } from '../lib/bridge.mjs'+// A folder too long for a socket has one under the home folder: only a home too long as well is left on the port.+process.env.HOME = `/${'h'.repeat(120)}`+const CREDENTIAL = `test-local-credential-${'a'.repeat(21)}` // the CLI's shape: 43 base64url characters/** A data folder as the CLI leaves it, too long to hold a socket: the one case on TCP, with the credential: 0700, holding a 0600 `hook-credential` (or none). */diff --git a/store/agents/machine-monitor/lib/localDaemon.mjs b/store/agents/machine-monitor/lib/localDaemon.mjsindex dc4cdf86d..b7a10e28d 100644--- a/store/agents/machine-monitor/lib/localDaemon.mjs+++ b/store/agents/machine-monitor/lib/localDaemon.mjs@@ -23,11 +23,17 @@ export function daemonDataDir(env = process.env) {return env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')}-/** The daemon's socket for `port`, or null where it can have none: Windows, or a path too long. */+/**+ * The daemon's socket for `port`: in its data folder, or where that path is too long for a socket, in a 0700 folder under the home folder+ * named by the folder's hash (the CLI's `socketPathIn`). Null where it can have none: Windows, or a home too long as well.+ */export function daemonSocketPath(port, env = process.env, platform = process.platform) {if (platform === 'win32') return null- const path = join(daemonDataDir(env), `daemon-${port}.sock`)- return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null+ const folder = daemonDataDir(env), name = `daemon-${port}.sock`, beside = join(folder, name)+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH_BYTES) return beside+ const hash = createHash('sha256').update(folder).digest('hex').slice(0, 16)+ const short = join(env.HOME || homedir(), '.harness', 's', hash, name)+ return Buffer.byteLength(short) <= MAX_SOCKET_PATH_BYTES ? short : null}/** Whether `path` is the daemon's: a socket of this account's, owner only, in a real folder nobody else can write to. */diff --git a/store/agents/machine-monitor/test/credential.test.mjs b/store/agents/machine-monitor/test/credential.test.mjsindex 1e2079851..560bf346c 100644--- a/store/agents/machine-monitor/test/credential.test.mjs+++ b/store/agents/machine-monitor/test/credential.test.mjs@@ -7,6 +7,9 @@ import { join } from 'node:path';import test from 'node:test';import { closeSessions, listHarnesses, listMachines, localCredentialHeaders } from '../lib/daemon.mjs';+// A folder too long for a socket has one under the home folder: only a home too long as well is left on the port.+process.env.HOME = `/${'h'.repeat(120)}`+const CREDENTIAL = `test-local-credential-${'a'.repeat(21)}`; // the CLI's shape: 43 base64url characters/** A data folder as the CLI leaves it, too long to hold a socket: the one case on TCP, with the credential: 0700, holding a 0600 `hook-credential` (or none). */diff --git a/store/agents/memories/lib/localDaemon.mjs b/store/agents/memories/lib/localDaemon.mjsindex dc4cdf86d..b7a10e28d 100644--- a/store/agents/memories/lib/localDaemon.mjs+++ b/store/agents/memories/lib/localDaemon.mjs@@ -23,11 +23,17 @@ export function daemonDataDir(env = process.env) {return env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')}-/** The daemon's socket for `port`, or null where it can have none: Windows, or a path too long. */+/**+ * The daemon's socket for `port`: in its data folder, or where that path is too long for a socket, in a 0700 folder under the home folder+ * named by the folder's hash (the CLI's `socketPathIn`). Null where it can have none: Windows, or a home too long as well.+ */export function daemonSocketPath(port, env = process.env, platform = process.platform) {if (platform === 'win32') return null- const path = join(daemonDataDir(env), `daemon-${port}.sock`)- return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null+ const folder = daemonDataDir(env), name = `daemon-${port}.sock`, beside = join(folder, name)+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH_BYTES) return beside+ const hash = createHash('sha256').update(folder).digest('hex').slice(0, 16)+ const short = join(env.HOME || homedir(), '.harness', 's', hash, name)+ return Buffer.byteLength(short) <= MAX_SOCKET_PATH_BYTES ? short : null}/** Whether `path` is the daemon's: a socket of this account's, owner only, in a real folder nobody else can write to. */diff --git a/store/agents/memories/test/credential.test.mjs b/store/agents/memories/test/credential.test.mjsindex 054e6507c..27b49192d 100644--- a/store/agents/memories/test/credential.test.mjs+++ b/store/agents/memories/test/credential.test.mjs@@ -7,6 +7,9 @@ import { join } from 'node:path'import { test } from 'node:test'import { closeBridges, listAgents, localCredentialHeaders } from '../lib/bridge.mjs'+// A folder too long for a socket has one under the home folder: only a home too long as well is left on the port.+process.env.HOME = `/${'h'.repeat(120)}`+const CREDENTIAL = `test-local-credential-${'a'.repeat(21)}` // the CLI's shape: 43 base64url characters/** A data folder as the CLI leaves it, too long to hold a socket: the one case on TCP, with the credential: 0700, holding a 0600 `hook-credential` (or none). */diff --git a/store/tools/README.md b/store/tools/README.mdindex 21445f135..0ed598037 100644--- a/store/tools/README.md+++ b/store/tools/README.md@@ -29,8 +29,8 @@ Sources and visual-review notes are in [the asset guide](../../.github/assets/stDaemon-level checks over the same loopback WebSocket the desktop uses (`ws://127.0.0.1:18473/api/local-ws`).They need a running daemon with the harness installed on this machine, and `cli/node_modules` (for `ws`).Run them as the OS user Harness runs as: they reach the daemon over its 0600 socket in `ADAPTER_DATA_DIR`-(default `~/.harness/cli/data`), `local-daemon.mjs`, and nothing goes to its TCP port, which any account can hold. Only where a-socket cannot be (Windows, or a folder too long for one) do they use the port, with `hook-credential` as `X-Harness-Local`+(default `~/.harness/cli/data`, or `~/.harness/s/<hash>` for a folder too long for a socket), `local-daemon.mjs`, and nothing goes to its TCP port, which any account can hold. Only where a+socket cannot be (Windows, or a home too long as well) do they use the port, with `hook-credential` as `X-Harness-Local`(`local-credential.mjs`).```shdiff --git a/store/tools/local-credential.test.mjs b/store/tools/local-credential.test.mjsindex bbdcfd7a2..f9eefa910 100644--- a/store/tools/local-credential.test.mjs+++ b/store/tools/local-credential.test.mjs@@ -10,6 +10,9 @@ import { removeTempFolders, tempFolder } from './test-folders.mjs'after(removeTempFolders)+// A folder too long for a socket has one under the home folder: only a home too long as well is left on the port.+process.env.HOME = `/${'h'.repeat(120)}`+const CREDENTIAL = `test-local-credential-${'a'.repeat(21)}` // the CLI's shape: 43 base64url characters/** A data folder as the CLI leaves it: 0700, holding a 0600 `hook-credential` (or none). */@@ -44,7 +47,7 @@ test('where a socket can be, a check opens it and shows nothing, and only if itconst short = tempFolder('tools-')writeFileSync(join(short, 'hook-credential'), `${CREDENTIAL}\n`, { mode: 0o600 })chmodSync(short, 0o700)- const env = { ADAPTER_DATA_DIR: short }, path = join(short, 'daemon-18473.sock')+ const env = { ADAPTER_DATA_DIR: short, HOME: '/h' }, path = join(short, 'daemon-18473.sock')assert.deepEqual(localCredentialHeaders(env), {})assert.throws(() => daemonBridge(18473, env), /missing or not private/, 'no socket: the daemon is down, and the port is not tried')const server = createServer()diff --git a/store/tools/local-daemon.mjs b/store/tools/local-daemon.mjsindex dc4cdf86d..b7a10e28d 100644--- a/store/tools/local-daemon.mjs+++ b/store/tools/local-daemon.mjs@@ -23,11 +23,17 @@ export function daemonDataDir(env = process.env) {return env.ADAPTER_DATA_DIR || join(homedir(), '.harness', 'cli', 'data')}-/** The daemon's socket for `port`, or null where it can have none: Windows, or a path too long. */+/**+ * The daemon's socket for `port`: in its data folder, or where that path is too long for a socket, in a 0700 folder under the home folder+ * named by the folder's hash (the CLI's `socketPathIn`). Null where it can have none: Windows, or a home too long as well.+ */export function daemonSocketPath(port, env = process.env, platform = process.platform) {if (platform === 'win32') return null- const path = join(daemonDataDir(env), `daemon-${port}.sock`)- return Buffer.byteLength(path) <= MAX_SOCKET_PATH_BYTES ? path : null+ const folder = daemonDataDir(env), name = `daemon-${port}.sock`, beside = join(folder, name)+ if (Buffer.byteLength(beside) <= MAX_SOCKET_PATH_BYTES) return beside+ const hash = createHash('sha256').update(folder).digest('hex').slice(0, 16)+ const short = join(env.HOME || homedir(), '.harness', 's', hash, name)+ return Buffer.byteLength(short) <= MAX_SOCKET_PATH_BYTES ? short : null}/** Whether `path` is the daemon's: a socket of this account's, owner only, in a real folder nobody else can write to. */diff --git a/store/tools/local-daemon.test.mjs b/store/tools/local-daemon.test.mjsindex fd6e03883..ff41d8d53 100644--- a/store/tools/local-daemon.test.mjs+++ b/store/tools/local-daemon.test.mjs@@ -183,8 +183,11 @@ test('fetch: a request and its body over the socket; the timeout reads as a timeawait assert.rejects(daemonFetch(`${base}/api/x`, { env: { ADAPTER_DATA_DIR: dir } }), /not private/)})-test('no socket on Windows or for a path too long; there the port is the only way', () => {+test('a long folder has a socket under the home folder; Windows, and a home too long as well, have none', () => {+ const long = `/${'x'.repeat(100)}`assert.equal(daemonSocketPath(PORT, { ADAPTER_DATA_DIR: '/d' }, 'win32'), null)- assert.equal(daemonSocketPath(PORT, { ADAPTER_DATA_DIR: `/${'x'.repeat(100)}` }, 'linux'), null)assert.equal(daemonSocketPath(PORT, { ADAPTER_DATA_DIR: '/d' }, 'linux'), `/d/daemon-${PORT}.sock`)+ const hash = createHash('sha256').update(long).digest('hex').slice(0, 16)+ assert.equal(daemonSocketPath(PORT, { ADAPTER_DATA_DIR: long, HOME: '/h' }, 'linux'), `/h/.harness/s/${hash}/daemon-${PORT}.sock`)+ assert.equal(daemonSocketPath(PORT, { ADAPTER_DATA_DIR: long, HOME: `/${'h'.repeat(100)}` }, 'linux'), null)})diff --git a/store/tools/port-holder.test.mjs b/store/tools/port-holder.test.mjsindex 8013fe343..7e1b37d62 100644--- a/store/tools/port-holder.test.mjs+++ b/store/tools/port-holder.test.mjs@@ -114,6 +114,33 @@ for (const [name, run] of Object.entries(clients)) {})}+for (const [name, run] of Object.entries(clients)) {+ test(`${name}: a data folder too long for a socket uses its short one, and a holder of the port hears nothing`, async () => {+ const home = tempFolder('hh-'), dir = join(tempFolder('hl-'), 'd'.repeat(100))+ mkdirSync(dir, { mode: 0o700 })+ writeFileSync(join(dir, 'hook-credential'), `${CREDENTIAL}\n`, { mode: 0o600 })+ const hold = await holder()+ const folder = join(home, '.harness', 's', createHash('sha256').update(dir).digest('hex').slice(0, 16))+ mkdirSync(folder, { recursive: true, mode: 0o700 })+ const daemon = await daemonOn(folder, hold.port)+ // A kept session from an earlier test would answer instead.+ closeBridges(); closeMemories(); closeSessions()+ await run({ ...envFor(dir, hold.port), HOME: home }).catch(() => null)+ assert.equal(hold.heard.length, 0, 'nothing reaches the port')+ assert.ok(daemon.got.length > 0, 'the daemon was reached over its short socket')+ assert.ok(daemon.got.every(g => !g.headers?.['x-harness-local']), 'and shown no credential')+ })++ test(`${name}: a long folder with its short socket gone says the daemon is down, and the port is not tried`, async () => {+ const home = tempFolder('hh-'), dir = join(tempFolder('hl-'), 'd'.repeat(100))+ mkdirSync(dir, { mode: 0o700 })+ writeFileSync(join(dir, 'hook-credential'), `${CREDENTIAL}\n`, { mode: 0o600 })+ const hold = await holder()+ await run({ ...envFor(dir, hold.port), HOME: home }).catch(() => null)+ assert.equal(hold.heard.length, 0)+ })+}+test('a socket that is not private is not used, and nothing else is', async () => {const dir = dataDir(), hold = await holder(), daemon = await daemonOn(dir, hold.port)chmodSync(join(dir, `daemon-${hold.port}.sock`), 0o666)