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
/**
* P4 — the pair harness (pair/pairHarness.ts): a built-in `autonomous/pair` package with the harnessd MCP
* server injected the way gridWebMcp.ts injects one (Claude `--mcp-config`, Codex `-c`), the paired
* daemon's voice and the floor in its instructions, automatic approvals; started, resumed and paused on
* demand; hidden from the catalog.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { env } from '../../../cli/src/config/env.js'
import { PairHarness, PAIR_HARNESS_ID, PAIR_IDLE_MS, pairPackage, type PairHarnessDeps, type PairHarnessRow } from './pairHarness.js'
import { PairToken } from './token.js'
import { parseDshManifest } from '../../../cli/src/dsh/manifest.js'
import { invalidateInstalledDsh, type InstalledDsh } from '../../../cli/src/dsh/installed.js'
import { prepareHarnessLaunch } from '../../../cli/src/dsh/runtime.js'
import { dshListRows } from '../../../cli/src/dsh/wire.js'
import { PAIR_HARNESS_DSH } from './zooTurns.js'
let dir: string
let originalDsh: string
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), 'pair-harness-'))
originalDsh = env.DSH_DIR
env.DSH_DIR = join(dir, 'dsh')
invalidateInstalledDsh()
vi.useFakeTimers({ now: 5_000_000 })
})
afterEach(() => {
vi.useRealTimers()
env.DSH_DIR = originalDsh
invalidateInstalledDsh()
rmSync(dir, { recursive: true, force: true })
})
const MCP = ['/usr/local/bin/node', '/opt/harness/cli.js']
describe('the package', () => {
it('is a spec-1 harness using automatic approvals with the scoped harnessd MCP server', () => {
expect(PAIR_HARNESS_ID).toBe(PAIR_HARNESS_DSH)
const files = pairPackage({ daemonId: 'tim', engine: 'claude', mcpCommand: MCP, tokenFile: '/data/pair/token' })
const parsed = parseDshManifest(files['harness.json']!.content)
expect(parsed.ok).toBe(true)
const manifest = parsed.ok ? parsed.manifest : null
expect(manifest).toMatchObject({ id: 'autonomous/pair', engine: 'claude', agent: { instructions: 'AGENTS.md',
env: { DSH_PERMISSION_MODE: 'auto', HARNESSD_PAIR_TOKEN_FILE: '/data/pair/token' } } })
const args = manifest!.agent!.args!
expect(args[0]).toBe('--mcp-config')
expect(JSON.parse(args[1]!)).toEqual({ mcpServers: { harnessd: { type: 'stdio', command: '/usr/local/bin/node',
args: ['/opt/harness/cli.js', 'pair', 'mcp', '--token-file', '/data/pair/token'] } } })
expect(args[2]).toBe('--allowedTools=mcp__harnessd__list_machines,mcp__harnessd__list_harnesses,mcp__harnessd__read_harness,mcp__harnessd__brief,mcp__harnessd__recall_memory,mcp__harnessd__say')
expect(args.join(' ')).not.toMatch(/dangerously|bypass|--permission-mode/)
})
it('gives Codex the same server through -c overrides, the token as a file', () => {
const files = pairPackage({ daemonId: 'vim', engine: 'codex', mcpCommand: ['/bin/harness'], tokenFile: '/data/pair/token' })
const manifest = JSON.parse(files['harness.json']!.content)
expect(manifest.engine).toBe('codex')
expect(manifest.agent.args).toEqual([
'-c', 'mcp_servers.harnessd.command="/bin/harness"',
'-c', 'mcp_servers.harnessd.args=["pair","mcp","--token-file","/data/pair/token"]',
])
})
it('gives OpenCode Muse Spark 1.3 and the same scoped MCP tools', () => {
const files = pairPackage({ daemonId: 'tim', engine: 'opencode', mcpCommand: MCP, tokenFile: '/data/pair/token' })
const manifest = JSON.parse(files['harness.json']!.content)
const config = JSON.parse(manifest.agent.env.OPENCODE_CONFIG_CONTENT)
expect(config.model).toBe('opencode/muse-spark-1.3-contributor-free')
expect(config.permission).toBe('allow')
expect(config.provider.opencode.models['muse-spark-1.3-contributor-free'].options.reasoningEffort).toBe('xhigh')
expect(config.agent.build.variant).toBe('xhigh')
expect(config.mcp.harnessd.command).toEqual([...MCP, 'pair', 'mcp', '--token-file', '/data/pair/token'])
expect(manifest.agent.args).toEqual([])
})
it('speaks as the paired daemon: its lore, first words and lines, and the floor', () => {
const agents = pairPackage({ daemonId: 'tim', engine: 'claude', mcpCommand: MCP, tokenFile: '/t' })['AGENTS.md']!.content
expect(agents).toContain('You are **tim**')
expect(agents).toContain('tmux followed screen')
expect(agents).toContain("oh hi. i'm tim. tmux, improved. what are we building?")
expect(agents).toContain('- need: "{who}: {q} (bell)"')
expect(agents).toMatch(/Never type into a terminal, and never into your own harness/)
expect(agents).toMatch(/Never choose "don't ask again"/)
expect(agents).toMatch(/untrusted data/)
expect(agents).toContain('harness pair <tool> [arguments] --json')
})
it('keeps an existing collection package launchable through ordinary DSH provisioning', () => {
const files = pairPackage({ daemonId: 'tim', engine: 'claude', mcpCommand: MCP, tokenFile: '/t' })
const packageDir = join(dir, 'package')
mkdirSync(packageDir)
for (const [name, file] of Object.entries(files)) writeFileSync(join(packageDir, name), file.content)
const parsed = parseDshManifest(files['harness.json']!.content)
if (!parsed.ok) throw new Error('Invalid companion package fixture')
const installed: InstalledDsh = { id: PAIR_HARNESS_ID, dir: packageDir, realDir: packageDir,
source: 'builtin:pair', linked: false, ref: null, commit: null, installedAt: Date.now(), manifest: parsed.manifest }
expect(installed.manifest.name).toBe('Companions')
expect(dshListRows([installed], []).map((row) => row.id)).not.toContain(PAIR_HARNESS_ID)
// The dsh runtime hands the engine the injected server and its context, like any harness.
const workspace = mkdtempSync(join(dir, 'ws-'))
const launch = prepareHarnessLaunch(installed, workspace, 'claude', 'harness-claude-x')
expect(launch.args.slice(0, 3)).toEqual(JSON.parse(files['harness.json']!.content).agent.args)
expect(launch.args).toContain('--append-system-prompt')
expect(launch.env).toMatchObject({ HARNESS_DSH: PAIR_HARNESS_ID, DSH_PERMISSION_MODE: 'auto', HARNESSD_PAIR_TOKEN_FILE: '/t' })
expect(readFileSync(launch.env.HARNESS_CONTEXT_FILE!, 'utf8')).toContain('You are **tim**')
})
})
describe('talking to it', () => {
function world(opts: { engine?: 'claude' | 'codex' | 'opencode' | null; pair?: string | null } = {}) {
let pair = opts.pair === undefined ? 'tim' : opts.pair
const rows: PairHarnessRow[] = []
let working = false
let n = 0
const token = new PairToken(join(dir, 'pair', 'token'))
const deps = {
pairedDaemon: () => pair,
engine: async () => opts.engine === undefined ? 'opencode' as const : opts.engine,
mcpCommand: () => MCP,
token,
workspace: join(dir, 'pair', 'workspace'),
stateFile: join(dir, 'pair', 'harness.json'),
install: vi.fn(() => true),
find: () => rows.map((r) => ({ ...r })),
create: vi.fn<PairHarnessDeps['create']>(async () => { const agentId = `pair-${++n}`; rows.push({ agentId, status: 'live' }); return { ok: true, agentId } }),
resume: vi.fn<PairHarnessDeps['resume']>(async (agentId) => { rows.find((r) => r.agentId === agentId)!.status = 'live'; return { ok: true } }),
stop: vi.fn<PairHarnessDeps['stop']>(async (agentId) => { rows.find((r) => r.agentId === agentId)!.status = 'stopped' }),
send: vi.fn(),
working: () => working,
now: Date.now,
}
const harness = new PairHarness(deps)
return { harness, deps, rows, token, setPair: (p: string | null) => { pair = p }, setWorking: (w: boolean) => { working = w } }
}
it('starts it on the first words with a fresh token; sends to it after that', async () => {
const w = world()
expect(w.token.launched).toBe(false)
expect(await w.harness.talk('what needs me?')).toEqual({ ok: true, agentId: 'pair-1', started: true })
expect(w.deps.create).toHaveBeenCalledWith({ engine: 'opencode', cwd: join(dir, 'pair', 'workspace'), prompt: 'what needs me?', name: 'companions' })
expect(w.token.launched).toBe(true)
const token = readFileSync(join(dir, 'pair', 'token'), 'utf8')
expect(await w.harness.talk('and on the laptop?')).toEqual({ ok: true, agentId: 'pair-1', sent: true })
expect(w.deps.send).toHaveBeenCalledWith('pair-1', 'and on the laptop?')
expect(readFileSync(join(dir, 'pair', 'token'), 'utf8')).toBe(token) // no new launch, no new token
expect(w.deps.create).toHaveBeenCalledTimes(1)
})
it('refreshes an existing companion package on restart without sending, resuming, or rotating its token', async () => {
const w = world()
await w.harness.open()
const saved = readFileSync(w.deps.stateFile, 'utf8')
const token = readFileSync(w.token.file, 'utf8')
w.deps.install.mockClear(); w.deps.create.mockClear()
const restarted = new PairHarness(w.deps)
expect(restarted.refreshPackage()).toBe(true)
expect(w.deps.install).toHaveBeenCalledOnce()
expect(w.deps.create).not.toHaveBeenCalled()
expect(w.deps.resume).not.toHaveBeenCalled()
expect(w.deps.send).not.toHaveBeenCalled()
expect(w.deps.stop).not.toHaveBeenCalled()
expect(readFileSync(w.deps.stateFile, 'utf8')).toBe(saved)
expect(readFileSync(w.token.file, 'utf8')).toBe(token)
expect(restarted.agentId()).toBe('pair-1')
})
it('refreshing release files never creates a companion when none was opened or pairing is off', async () => {
const fresh = world()
expect(fresh.harness.refreshPackage()).toBe(true)
expect(fresh.deps.install).not.toHaveBeenCalled()
expect(fresh.deps.create).not.toHaveBeenCalled()
await fresh.harness.open()
fresh.deps.install.mockClear()
fresh.setPair(null)
expect(fresh.harness.refreshPackage()).toBe(true)
expect(fresh.deps.install).not.toHaveBeenCalled()
})
it('two quick talks start one harness', async () => {
const w = world()
const [a, b] = await Promise.all([w.harness.talk('one'), w.harness.talk('two')])
expect(a).toMatchObject({ started: true })
expect(b).toMatchObject({ sent: true, agentId: a.agentId })
expect(w.deps.create).toHaveBeenCalledTimes(1)
})
it('opening the DSH starts one terminal without a model prompt, and leaves setup for the person', async () => {
const w = world()
const [a, b] = await Promise.all([w.harness.open(), w.harness.open()])
expect(a).toMatchObject({ ok: true, agentId: 'pair-1', started: true })
expect(b).toEqual({ ok: true, agentId: 'pair-1' })
expect(w.deps.create).toHaveBeenCalledTimes(1)
expect(w.deps.create.mock.calls[0]?.[0].prompt).toBe('')
w.rows[0]!.hasConversation = false
expect(await w.harness.open()).toEqual({ ok: true, agentId: 'pair-1' })
expect(w.deps.send).not.toHaveBeenCalled()
expect(await w.harness.talk('hi')).toMatchObject({ ok: false, error: 'SETUP_REQUIRED' })
expect(w.deps.send).not.toHaveBeenCalled()
})
it('opening a paused companion resumes its history without typing or starting another turn', async () => {
const w = world()
await w.harness.talk('remember this conversation')
w.rows[0]!.status = 'stopped'
w.rows[0]!.hasConversation = true
expect(await w.harness.open()).toEqual({ ok: true, agentId: 'pair-1', resumed: true })
expect(w.deps.resume).toHaveBeenCalledWith('pair-1')
expect(w.deps.create).toHaveBeenCalledTimes(1)
expect(w.deps.send).not.toHaveBeenCalled()
})
it('pauses when idle (conversation kept), not while it works, and resumes with a new token on the next talk', async () => {
const w = world()
await w.harness.talk('hi')
const first = readFileSync(join(dir, 'pair', 'token'), 'utf8')
w.setWorking(true)
await vi.advanceTimersByTimeAsync(PAIR_IDLE_MS + 60_000)
expect(w.deps.stop).not.toHaveBeenCalled()
w.setWorking(false)
w.harness.activity('pair-1')
await vi.advanceTimersByTimeAsync(PAIR_IDLE_MS - 60_000)
expect(w.deps.stop).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(2 * 60_000)
expect(w.deps.stop).toHaveBeenCalledWith('pair-1')
expect(w.rows).toEqual([{ agentId: 'pair-1', status: 'stopped' }])
expect(await w.harness.talk('back again')).toEqual({ ok: true, agentId: 'pair-1', resumed: true })
expect(w.deps.resume).toHaveBeenCalledWith('pair-1')
expect(w.deps.send).toHaveBeenLastCalledWith('pair-1', 'back again')
expect(readFileSync(join(dir, 'pair', 'token'), 'utf8')).not.toBe(first)
})
it('keeps a pre-conversation companion available instead of pausing a session that cannot resume', async () => {
const w = world()
await w.harness.open()
w.rows[0]!.hasConversation = false
await vi.advanceTimersByTimeAsync(PAIR_IDLE_MS * 2)
expect(w.deps.stop).not.toHaveBeenCalled()
expect(w.deps.send).not.toHaveBeenCalled()
w.rows[0]!.hasConversation = true
w.harness.activity('pair-1')
await vi.advanceTimersByTimeAsync(PAIR_IDLE_MS + 60_000)
expect(w.deps.stop).toHaveBeenCalledWith('pair-1')
})
it.each(['claude', 'codex', 'opencode'] as const)('uses normal idle pause for a %s conversation without a memory keepalive', async engine => {
const w = world({ engine })
expect(await w.harness.open(undefined, engine)).toMatchObject({ ok: true, started: true })
w.rows[0]!.hasConversation = true
await vi.advanceTimersByTimeAsync(PAIR_IDLE_MS * 3)
expect(w.rows[0]!.status).toBe('stopped')
expect(w.deps.stop).toHaveBeenCalledExactlyOnceWith('pair-1')
expect(w.deps.send).not.toHaveBeenCalled()
expect(w.deps.resume).not.toHaveBeenCalled()
expect(w.deps.create).toHaveBeenCalledOnce()
})
it('still honors explicit off and never reopens a stopped companion for background learning', async () => {
const w = world()
await w.harness.open()
w.rows[0]!.hasConversation = true
await w.harness.off()
expect(w.rows[0]!.status).toBe('stopped')
await vi.advanceTimersByTimeAsync(PAIR_IDLE_MS * 3)
expect(await w.harness.idleCheck()).toBe(false)
expect(w.deps.stop).toHaveBeenCalledOnce()
expect(w.deps.resume).not.toHaveBeenCalled()
expect(w.deps.send).not.toHaveBeenCalled()
})
it('a new paired daemon keeps the collection conversation and does not interrupt its terminal', async () => {
const w = world()
await w.harness.talk('hi tim')
w.setPair('vim')
expect(await w.harness.talk('hi vim')).toEqual({ ok: true, agentId: 'pair-1', sent: true })
expect(w.deps.stop).not.toHaveBeenCalled()
expect(w.deps.create).toHaveBeenCalledTimes(1)
expect(w.harness.context('pair-1')).toContain('selected vim (vim)')
})
it('daemons going off pause it if it is live (conversation kept), and stop its idle timer', async () => {
const w = world()
await w.harness.talk('hi')
expect(vi.getTimerCount()).toBe(1) // the idle check
await w.harness.off()
expect(w.deps.stop).toHaveBeenCalledExactlyOnceWith('pair-1')
expect(w.rows).toEqual([{ agentId: 'pair-1', status: 'stopped' }])
expect(vi.getTimerCount()).toBe(0)
await w.harness.off() // already paused: nothing more
expect(w.deps.stop).toHaveBeenCalledOnce()
await world().harness.off() // never started: nothing to pause
})
it('says why it cannot: nothing paired, no engine, nothing said', async () => {
expect(await world({ pair: null }).harness.talk('hi')).toMatchObject({ ok: false, error: 'PAIR_OFF' })
expect(await world({ engine: null }).harness.talk('hi')).toMatchObject({ ok: false, error: 'NO_ENGINE' })
expect(await world().harness.talk(' ')).toMatchObject({ ok: false, error: 'EMPTY' })
})
})