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
Add domain-specific harness support to the CLI
deeea33286bcc7a
diff --git a/cli/build-bundle.mjs b/cli/build-bundle.mjsindex 515a83370..257c213d4 100644--- a/cli/build-bundle.mjs+++ b/cli/build-bundle.mjs@@ -11,11 +11,15 @@*/import * as esbuild from 'esbuild'import { readFileSync, copyFileSync, rmSync } from 'fs'+import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'const version =process.env.ADAPTER_VERSION ||JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version+// The bundled DSH registry (dsh/registry/**/*.json at the repo root) — see src/dsh/registry.ts.+const dshRegistry = JSON.stringify(readDshRegistry(new URL('../dsh/registry', import.meta.url)))+// Start clean so no stale per-file `dist/*.js` / sourcemaps leak into the release artifact.rmSync('dist', { recursive: true, force: true })@@ -27,7 +31,7 @@ await esbuild.build({format: 'esm',target: 'node20',external: ['bufferutil', 'utf-8-validate'],- define: { __ADAPTER_VERSION__: JSON.stringify(version) },+ define: { __ADAPTER_VERSION__: JSON.stringify(version), __DSH_REGISTRY__: JSON.stringify(dshRegistry) },// The copyright line is MIT's one condition — it has to travel with the copy the user actually// receives, and the published bundle IS that copy (upload-cli.sh ships `cli.js` and `notify.mjs`,// nothing else). `legalComments: 'eof'` below appends the dependencies' own notices; this is ours.diff --git a/cli/build.mjs b/cli/build.mjsindex 5a82525d9..e27067890 100644--- a/cli/build.mjs+++ b/cli/build.mjs@@ -1,10 +1,13 @@import * as esbuild from 'esbuild'import { readdirSync, statSync, readFileSync } from 'fs'import { join } from 'path'+import { readDshRegistry } from './scripts/lib/dshRegistry.mjs'// Bake the version in so `node dist/cli.js version` works in the dev/per-file build too (parity with// build-bundle.mjs). The bundle build overrides this from ADAPTER_VERSION at release time.const version = JSON.parse(readFileSync('package.json', 'utf8')).version+// The bundled DSH registry (dsh/registry/**/*.json at the repo root) — see src/dsh/registry.ts.+const dshRegistry = JSON.stringify(readDshRegistry(join('..', 'dsh', 'registry')))function getAllTsFiles(dir, fileList = []) {const files = readdirSync(dir)@@ -33,7 +36,7 @@ try {target: 'node20',sourcemap: true,outExtension: { '.js': '.js' },- define: { __ADAPTER_VERSION__: JSON.stringify(version) },+ define: { __ADAPTER_VERSION__: JSON.stringify(version), __DSH_REGISTRY__: JSON.stringify(dshRegistry) },logLevel: 'info',})diff --git a/cli/scripts/lib/dshRegistry.mjs b/cli/scripts/lib/dshRegistry.mjsnew file mode 100644index 000000000..478f1d88b--- /dev/null+++ b/cli/scripts/lib/dshRegistry.mjs@@ -0,0 +1,26 @@+// Read `dsh/registry/<owner>/<name>.json` for the build's `__DSH_REGISTRY__` define. Mirrors+// `readRegistryDir` in src/dsh/registry.ts (the runtime dev fallback); kept in plain ESM so both+// build scripts can import it without a TypeScript step.+import { readdirSync, readFileSync, statSync } from 'fs'+import { join } from 'path'+import { fileURLToPath } from 'url'++export function readDshRegistry(dir) {+ const root = dir instanceof URL ? fileURLToPath(dir) : dir+ const out = []+ let owners+ try { owners = readdirSync(root) } catch { return out }+ for (const owner of owners) {+ const ownerDir = join(root, owner)+ let files+ try {+ if (!statSync(ownerDir).isDirectory()) continue+ files = readdirSync(ownerDir)+ } catch { continue }+ for (const file of files) {+ if (!file.endsWith('.json')) continue+ out.push(JSON.parse(readFileSync(join(ownerDir, file), 'utf8')))+ }+ }+ return out+}diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 1572205fc..d04e04ce5 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -34,7 +34,11 @@ import { AgentCreationReceipts, AgentCreationReceiptError, creationFingerprint,import { engineInstallRecipe } from './lib/engineInstall.js'import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from './lib/projectFolder.js'import { projectPreview } from './lib/projectPreview.js'-import { agentFrame, type AgentFrame } from './lib/agentFrame.js'+import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'+import { installedDsh, listInstalledDsh } from './dsh/installed.js'+import { DSH_ID_RE, dshTier } from './dsh/manifest.js'+import { bundledDshRegistry } from './dsh/registry.js'+import type { DshInstallProgress } from './dsh/install.js'import { routeVoiceTask } from './lib/voiceRouter.js'import { tailFile } from './lib/sessions.js'import { messagesToEvents, windowRawLines, subagentStatsFromRawLines, type SessionEvent } from './lib/normalize.js'@@ -332,8 +336,15 @@ export class BackendSocket {grid: GridLaunchOverride | null/** A Codex CODEX_HOME folder to launch this agent against instead of `~/.codex`; codex only. */codexHome: string | null+ /** The domain-specific harness to create this agent as (installed here, base engine = `engine`). */+ dsh: string | null}) =>Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null+ /** Called on `dsh_install` — cli.ts clones/sets up/doctors the harness and reports each phase. */+ onDshInstall: ((input: { id?: string; url?: string; ref?: string }, progress: (p: DshInstallProgress) => void) =>+ Promise<{ ok: true; id: string } | { ok: false; error: string; detail: string }>) | null = null+ /** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */+ dshFrameProvider: ((session: RegisteredSession) => AgentDshContext | null) | null = nullprivate readonly agentCreations = new AgentCreationReceipts(join(env.ADAPTER_DATA_DIR, 'agent-creations'))/** Injectable for queue-isolation tests; production uses the machine-local probe. */engineProbeProvider: typeof probeEngines = probeEngines@@ -1453,6 +1464,57 @@ export class BackendSocket {return}+ case 'dsh_list': {+ // Which domain-specific harnesses this machine has, plus what the bundled registry offers —+ // answered here, on the machine in question, for the same reason `engines_probe` is.+ const installed = listInstalledDsh()+ const seen = new Set<string>()+ const rows: Record<string, unknown>[] = []+ for (const entry of installed) {+ seen.add(entry.id)+ rows.push({+ id: entry.id,+ name: entry.manifest.name,+ description: entry.manifest.description ?? null,+ engine: entry.manifest.engine,+ installed: true,+ viewer: !!entry.manifest.viewer,+ tier: dshTier(entry.manifest),+ verified: bundledDshRegistry().some((known) => known.id === entry.id && known.verified === true),+ })+ }+ for (const entry of bundledDshRegistry()) {+ if (seen.has(entry.id)) continue+ rows.push({+ id: entry.id,+ name: entry.name,+ description: entry.description ?? null,+ engine: entry.engine,+ installed: false,+ viewer: (entry.tier ?? 0) >= 2,+ tier: entry.tier ?? 0,+ verified: entry.verified === true,+ })+ }+ reply(type, requestId, { dsh: rows })+ return+ }++ case 'dsh_install': {+ // Clone, set up and doctor a harness on THIS machine. Long — minutes, for a toolchain — so+ // it is detached from the ordered RPC chain like `engines_probe`, and progress travels as+ // `dsh_install_status` pushes the app renders in the create dialog.+ if (!this.onDshInstall) { reply(type, requestId, { error: 'UNSUPPORTED_ON_REMOTE' }); return }+ const id = typeof payload.id === 'string' && DSH_ID_RE.test(payload.id) ? payload.id : undefined+ const url = typeof payload.url === 'string' && payload.url.length <= 2048 && !/[\x00-\x1f\x7f]/.test(payload.url) ? payload.url : undefined+ const ref = typeof payload.ref === 'string' && payload.ref.length <= 200 ? payload.ref : undefined+ if (!id && !url) { reply(type, requestId, { error: 'INVALID_DSH', detail: 'dsh_install needs an id or a url' }); return }+ void this.onDshInstall({ id, url, ref }, (p) => this.send({ type: 'dsh_install_status', payload: { ...p, id: p.id ?? id ?? null } }))+ .then((result) => reply(type, requestId, result.ok ? { ok: true, id: result.id } : { error: result.error, detail: result.detail }))+ .catch((error) => reply(type, requestId, { error: 'INTERNAL', detail: error instanceof Error ? error.message : String(error) }))+ return+ }+case 'engines_probe': {// Which engines this machine has, asked BEFORE a create rather than discovered by one// failing. Answered here — on the machine in question — because a Mac and the Docker rig@@ -1619,12 +1681,29 @@ export class BackendSocket {reply(type, requestId, { error: 'INVALID_CODEX_HOME', detail: 'codexHome is only valid for codex, without a grid' })return}+ // A DSH is refused, never approximated: an agent created as its plain base engine would look+ // like it worked and have none of the skills the user picked the tile for.+ let dsh: string | null = null+ if (payload.dsh !== undefined && payload.dsh !== null) {+ if (typeof payload.dsh !== 'string' || !DSH_ID_RE.test(payload.dsh)) {+ reply(type, requestId, { error: 'INVALID_DSH', detail: 'dsh must be an owner/name id' }); return+ }+ const installed = installedDsh(payload.dsh)+ if (!installed) {+ reply(type, requestId, { error: 'INVALID_DSH', detail: `${payload.dsh} is not installed on this machine` }); return+ }+ if (installed.manifest.engine !== engine) {+ reply(type, requestId, { error: 'INVALID_DSH', detail: `${payload.dsh} runs on ${installed.manifest.engine}, not ${engine}` }); return+ }+ dsh = installed.id+ }const input = {engine,cwd: typeof cwd === 'string' ? cwd : '',bypassPermission: payload.bypassPermission === true,grid: grid.state === 'ok' ? grid.override : null,codexHome,+ dsh,}if (creationId !== undefined) {// Reserve before spawning. A transport retry carries the SAME creationId; a deliberate@@ -1906,6 +1985,7 @@ export class BackendSocket {return agentFrame(s, {selectedModel: this.runtimeProfileProvider?.(s) ?? null,terminalAvailable: registry.terminalAvailable(s.agentId),+ dsh: this.dshFrameProvider?.(s) ?? null,})}}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex ecd4d42fc..c9c4bcac9 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -71,6 +71,16 @@ import { createAndRegisterPane } from './lib/createAgentPane.js'import { restoreAgents } from './lib/restoreAgents.js'import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'import { buildHarnessSessionLabel } from './lib/harnessSessionLabel.js'+import { installedDsh } from './dsh/installed.js'+import { dshVerdictPath } from './dsh/manifest.js'+import { registryEntry } from './dsh/registry.js'+import { installDsh, resolveInstallSource } from './dsh/install.js'+import { materializeWorkspace } from './dsh/materialize.js'+import { dshLaunch } from './dsh/launch.js'+import { DshViewerManager } from './dsh/viewer.js'+import { DshVerdictWatcher, type DshVerdict } from './dsh/verdict.js'+import { dshCommand, dshUsage } from './dsh/command.js'+import type { AgentDshContext } from './lib/agentFrame.js'import { basename } from 'node:path'import {bypassPermissionActive,@@ -304,6 +314,8 @@ Grid (the fleet of AI engines the \`grid\` CLI serves — needs \`grid\` on PATHthis box is serving BEFORE deleting anything. Flags go straight to it:--force signs out over a serve child it could not confirm stopped+${dshUsage()}+Browser end-to-end encryption:harness browser-link print a reusable 7-day setup link for browsersharness autonomous-device <command> pair/status/list/revoke an Autonomous device@@ -966,8 +978,24 @@ async function logout(): Promise<void> {process.exit(0)}+/** The pane's session environment: the grid's or the profile's, with the DSH's layered on top. */+function mergedLaunchEnv(+ base: Record<string, string> | undefined,+ dsh: Record<string, string> | undefined,+): Record<string, string> | undefined {+ if (!base && !dsh) return undefined+ return { ...(base ?? {}), ...(dsh ?? {}) }+}++/** Set by runForeground once the DSH companions exist; a frame projected before that carries none. */+let dshFrameContextRef: ((s: RegisteredSession) => AgentDshContext | null) | null = null+function projectFrame(s: RegisteredSession, selectedModel: string | null): Promise<AgentFrame> {- return agentFrame(s, { selectedModel, terminalAvailable: registry.terminalAvailable(s.agentId) })+ return agentFrame(s, {+ selectedModel,+ terminalAvailable: registry.terminalAvailable(s.agentId),+ dsh: dshFrameContextRef?.(s) ?? null,+ })}function primaryTerminalLabel(session: RegisteredSession): string {@@ -1327,6 +1355,70 @@ async function runForeground(session: AuthSession): Promise<void> {announceRename(s, opts)}+ // ── Domain-specific harness companions ──────────────────────────────────────────────────────────+ // A DSH agent has two things beside its pane that the daemon owns for as long as the agent exists:+ // its viewer server (a URL the desktop shows in a pane next to the terminal) and a watch on the+ // verdict file its scripts write. Both are keyed on the agent, attached wherever an agent with a+ // `dsh` comes into being (create, restore, discovery) and detached where it is forgotten.+ const dshFrames = new Map<string, { viewerUrl: string | null; verdict: DshVerdict | null }>()+ const dshFrameFor = (agentId: string): { viewerUrl: string | null; verdict: DshVerdict | null } => {+ let state = dshFrames.get(agentId)+ if (!state) { state = { viewerUrl: null, verdict: null }; dshFrames.set(agentId, state) }+ return state+ }+ const dshFrameContext = (s: RegisteredSession): AgentDshContext | null => {+ if (!s.dsh) return null+ const state = dshFrames.get(s.agentId)+ return {+ name: installedDsh(s.dsh)?.manifest.name ?? registryEntry(s.dsh)?.name ?? null,+ viewerUrl: state?.viewerUrl ?? null,+ verdict: state?.verdict ?? null,+ }+ }+ dshFrameContextRef = dshFrameContext+ const dshViewers = new DshViewerManager({+ onUrl: (agentId, url) => {+ dshFrameFor(agentId).viewerUrl = url+ const session = registry.byAgent(agentId)+ if (session) syncSession(session)+ },+ log: (line) => console.log(line),+ })+ const dshVerdicts = new DshVerdictWatcher({+ onChange: (agentId, verdict) => {+ dshFrameFor(agentId).verdict = verdict+ // The verdict's artifact is what the viewer should show, when it names one.+ dshViewers.setVerdictArtifact(agentId, verdict?.artifact ?? null)+ const session = registry.byAgent(agentId)+ if (session) syncSession(session)+ },+ log: (line) => console.log(line),+ })+ const dshWarned = new Set<string>()+ /** Idempotent: safe to call on every observation of the agent. */+ const attachDsh = (s: RegisteredSession): void => {+ if (!s.dsh || !s.cwd) return+ const installed = installedDsh(s.dsh)+ if (!installed) {+ if (!dshWarned.has(s.dsh)) {+ dshWarned.add(s.dsh)+ console.warn(`[dsh] ${s.dsh} is not installed on this machine · agent ${sid(s.agentId)} runs as plain ${s.engine} (no viewer, no verdict)`)+ }+ return+ }+ dshVerdicts.watch(s.agentId, join(s.cwd, dshVerdictPath(installed.manifest)))+ if (installed.manifest.viewer) {+ void dshViewers.start(s.agentId, installed, s.cwd).catch((error) => {+ console.warn(`[dsh] ${s.dsh} viewer failed to start · ${error instanceof Error ? error.message : error}`)+ })+ }+ }+ const detachDsh = (agentId: string): void => {+ dshVerdicts.unwatch(agentId)+ void dshViewers.stop(agentId)+ dshFrames.delete(agentId)+ }+const syncTerminalTitles = async (): Promise<void> => {const titles = await terminals.titles()if (titles.size === 0) return@@ -2003,6 +2095,23 @@ async function runForeground(session: AuthSession): Promise<void> {return session ? runtimeProfiles.modelsForSession(session) : Promise.resolve([])}backend.runtimeProfileProvider = (session) => runtimeProfiles.selectedModel(session)+ backend.dshFrameProvider = dshFrameContext+ backend.onDshInstall = async ({ id, url, ref }, progress) => {+ const resolved = id ? resolveInstallSource(id) : url ? { source: url, ref } : null+ if (!resolved) return { ok: false, error: 'INVALID_DSH', detail: `${id ?? url} is not a known harness` }+ const result = await installDsh({+ source: resolved.source,+ ref: ref ?? resolved.ref,+ onProgress: progress,+ onLine: (line) => console.log(`[dsh] install · ${line}`),+ })+ if (!result.ok) {+ console.warn(`[dsh] install of ${id ?? url} failed · ${result.error} · ${result.detail}`)+ return { ok: false, error: result.error, detail: result.detail }+ }+ console.log(`[dsh] installed ${result.installed.id} at ${result.installed.dir}`)+ return { ok: true, id: result.installed.id }+ }backend.onAgentRename = (session, name) => { void terminals.setTitle(session, name) }backend.onRuntimeProfileUpdate = (sessionId, selectedModel) => runtimeController.setProfile(sessionId, selectedModel)runtimeProfiles.onChanged = (sessionId) => {@@ -2187,6 +2296,7 @@ async function runForeground(session: AuthSession): Promise<void> {void watcher.removeSession(sessionId)stopHeartbeat(sessionId)input.forget(doomed?.agentId ?? sessionId)+ if (!opts.keepAgent) detachDsh(announceId)mirror.forget(sessionId) // aborts any in-flight recap + clears busy; KEEPS the persisted summaryif (opts.keepAgent) returnbackend.send({ type: 'agent_deleted', payload: { agentId: announceId } }) // web tab@@ -2428,8 +2538,10 @@ async function runForeground(session: AuthSession): Promise<void> {gateway: observed.gateway,grid: observed.grid,codexHome: observed.codexHome,+ dsh: observed.dsh,})if (!opened) return+ if (opened.entry.dsh) attachDsh(opened.entry)if (opened.evicted) {console.log(`[discovery] ${observed.primaryRuntimeKey} replaced ${sid(opened.evicted.agentId)}`)// ⚠️ THE REGISTRY ALREADY DROPPED IT; NOBODY HAD TOLD THE CLIENTS. That@@ -2468,6 +2580,11 @@ async function runForeground(session: AuthSession): Promise<void> {// under learns it from the process, before the hook path validates a transcript against it.// Fill-only — a profile the row already knows is never re-derived.if (observed.codexHome && !current.codexHome) registry.setCodexHome(current.agentId, observed.codexHome)+ // And the DSH: a row minted by discovery (or written before the field existed) learns it from+ // the process's own `HARNESS_DSH`, and gets its viewer and verdict watch from here on.+ if (observed.dsh && !current.dsh) registry.setDsh(current.agentId, observed.dsh)+ const withDsh = registry.byAgent(current.agentId)+ if (withDsh?.dsh) attachDsh(withDsh)if (wasLaunching) registry.setLaunch(current.agentId, { state: 'ready' })await bindObservedAgent(observed)if (wasDormant || wasLaunching) {@@ -3384,9 +3501,19 @@ async function runForeground(session: AuthSession): Promise<void> {writeGridConfigDir,tmuxSupportsSessionEnv,installCodexHooks: (codexHome) => { if (!env.DISABLE_HOOK_INSTALL) installCodexHooks(hookPort, codexHome) },+ dshLaunch: (id, workspace) => {+ const installed = installedDsh(id)+ if (!installed) {+ console.warn(`[dsh] ${id} is not installed on this machine · relaunching as its plain base engine`)+ return null+ }+ return dshLaunch(installed, workspace)+ },}+ // Whatever the source (the row itself, or a grid override the desktop just sent), the agent's DSH+ // and workspace come from the row: a retarget must not silently drop the harness the agent is.const relaunchOverrides = (session: RegisteredSession, source: LaunchSource = session): Promise<LaunchOverridesResult> =>- buildLaunchOverrides(launchOverridesDeps, session.engine, source, session.agentId)+ buildLaunchOverrides(launchOverridesDeps, session.engine, { dsh: session.dsh ?? null, cwd: session.cwd, ...source }, session.agentId)watcher.start()await cursorDiscovery.start()@@ -3453,6 +3580,9 @@ async function runForeground(session: AuthSession): Promise<void> {+ (registry.rebootedSinceLastRun ? ' · after reboot' : ''))}}+ // Every DSH agent the registry kept gets its viewer and verdict watch back — restored or not, an+ // agent whose pane is still up is still that harness.+ for (const session of registry.list()) if (session.dsh) attachDsh(session)await agentReconciler.start(env.TERMINAL_RECONCILE_INTERVAL_MS ?? env.TMUX_REAP_INTERVAL_MS)for (const task of await loadCursorPendingTasks(env.ADAPTER_DATA_DIR)) {onCursorTaskStart(task.sessionId, task.toolUseId, task.input)@@ -3585,13 +3715,43 @@ async function runForeground(session: AuthSession): Promise<void> {* pass can miss it — retry `triggerHint` a few times with backoff before giving up.*/- backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid, codexHome }) => {+ backend.onCreateAgent = async ({ engine, cwd, bypassPermission, grid, codexHome, dsh }) => {if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }try {if (!statSync(cwd).isDirectory()) return { ok: false, error: 'CWD_NOT_FOUND' }} catch {return { ok: false, error: 'CWD_NOT_FOUND' }}+ // A domain-specific harness: put its files into the workspace first (template, AGENTS.md, skill+ // links) and take its env/argv for the launch. Refused, never approximated, when it is not here.+ let dshEnv: Record<string, string> | undefined+ let dshArgs: string[] = []+ if (dsh) {+ const installed = installedDsh(dsh)+ if (!installed) return { ok: false, error: 'INVALID_DSH', detail: `${dsh} is not installed on this machine` }+ if (installed.manifest.engine !== engine) {+ return { ok: false, error: 'INVALID_DSH', detail: `${dsh} runs on ${installed.manifest.engine}, not ${engine}` }+ }+ if (!(await tmuxSupportsSessionEnv())) {+ const detail = `this machine's tmux is older than ${TMUX_SESSION_ENV_MIN.major}.${TMUX_SESSION_ENV_MIN.minor}, `+ + `which is the first version that can give a new session its own environment — so ${installed.manifest.name} `+ + `could not tell ${engine} which harness it is. Upgrade tmux.`+ console.warn(`[agent] create ${dsh} refused · ${detail}`)+ return { ok: false, error: 'TMUX_TOO_OLD_FOR_DSH', detail }+ }+ try {+ const materialized = await materializeWorkspace(installed, cwd)+ for (const warning of materialized.warnings) console.warn(`[dsh] ${dsh} materialize · ${warning}`)+ console.log(`[dsh] ${dsh} materialized ${cwd} · created ${materialized.created.length} · kept ${materialized.kept.length}`)+ } catch (error) {+ const detail = `could not prepare the workspace for ${dsh} · ${error instanceof Error ? error.message : error}`+ console.warn(`[agent] create ${dsh} refused · ${detail}`)+ return { ok: false, error: 'DSH_MATERIALIZE_FAILED', detail }+ }+ const launch = dshLaunch(installed, cwd)+ dshEnv = launch.env+ dshArgs = launch.args+ }// Harness-created sessions are easy to distinguish from a user's organic tmux sessions while// retaining the engine and a collision-resistant creation suffix for diagnostics. Computed// before the grid block because a file-configured engine keys its config directory on it.@@ -3651,7 +3811,8 @@ async function runForeground(session: AuthSession): Promise<void> {// only `invalid x-api-key`. Nothing is cleared when no grid is in play: an agent on its own login// is supposed to use exactly these variables.const clearEnv = gridLaunch ? gridConflictingEnvToClear(gridLaunch) : undefined- const launchOptions = { bypassPermission, extraArgs: gridLaunch?.args, installIfMissing, clearEnv, cwd }+ const extraArgs = [...(gridLaunch?.args ?? []), ...dshArgs]+ const launchOptions = { bypassPermission, extraArgs: extraArgs.length ? extraArgs : undefined, installIfMissing, clearEnv, cwd }const command = buildEngineCommandArgv(engine, launchOptions)const argv = buildEngineLaunchArgv(engine, launchOptions)// A tmux route is enough to stream its screen. Register it before looking for a process so both@@ -3671,15 +3832,17 @@ async function runForeground(session: AuthSession): Promise<void> {cwd,sessionLabel: label,argv,- env: gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined),+ env: mergedLaunchEnv(gridLaunch?.env ?? (codexHome ? { CODEX_HOME: codexHome } : undefined), dshEnv),grid: grid ? { baseUrl: grid.baseUrl, model: grid.model ?? null } : null,gridLaunch: grid ?? null,codexHome,+ dsh,bypassPermission,})if (!result.ok) return { ok: false, error: result.error, detail: result.detail }const { spawned, pending } = resultannounceSession(pending)+ if (pending.dsh) attachDsh(pending)const watchCreatedPane = async (): Promise<void> => {const budgetMs = 10 * 60_000@@ -4103,6 +4266,9 @@ async function runForeground(session: AuthSession): Promise<void> {hookServer.close()shutdownSummaryPool()shutdownVoiceRouter()+ // The new daemon starts its own viewers for the agents it restores; ours must not hold the ports.+ await dshViewers.stopAll()+ await dshVerdicts.stop()autonomousDeviceDirect?.stop()await backend.stop() // graceful WS close → releases the Redis machine-owner claimawait new Promise((r) => setTimeout(r, 1000)) // grace before the same-machine reclaim@@ -4242,6 +4408,8 @@ async function runForeground(session: AuthSession): Promise<void> {hookServer.close()shutdownSummaryPool()shutdownVoiceRouter()+ await dshViewers.stopAll()+ await dshVerdicts.stop()autonomousDeviceDirect?.stop()await backend.stop()try { if (readPid() === process.pid) rmSync(PID_FILE, { force: true }) } catch { /* ignore */ }@@ -5407,6 +5575,11 @@ switch (cmd) {else if (args[0] === 'logout') gridLogoutCommand(withoutFirst(rest, 'logout')).catch(onError)else { console.error(`Unknown command: grid ${args[0] ?? ''}`); usage(1) }break+ case 'dsh':+ dshCommand(args[0], args[0] === undefined ? rest : withoutFirst(rest, args[0]))+ .then((code) => { process.exitCode = code })+ .catch(onError)+ breakcase 'machines':if (!args[0]) machinesListCommand(flags.includes('--json')).catch(onError)else if (args[0] === 'list') machinesListCommand(flags.includes('--json')).catch(onError)diff --git a/cli/src/config/env.ts b/cli/src/config/env.tsindex c27605748..0401e55d0 100644--- a/cli/src/config/env.ts+++ b/cli/src/config/env.ts@@ -234,6 +234,9 @@ const envSchema = z.object({// `app-*.log`/`cli-*.log`, so one directory holds everything a bug report needs. Not the data dir:// `harness.log` there is the daemon's console, and `harness reset` wipes it.HARNESS_LOGS_DIR: z.string().default(join(adapterRootDir, 'logs')),+ // Where domain-specific harnesses are installed (`harness dsh install`): one directory per+ // `<owner>/<name>` plus `installed.json`. Product-root state like the SSO session, not daemon data.+ DSH_DIR: z.string().default(join(adapterRootDir, 'dsh')),// This computer's stable id, minted once and never regenerated (see computerIdFile above). Pin it// explicitly on a box with no durable home — a container or CI job that gets a fresh ~/.harness on// every boot would otherwise look like a NEW computer each time and collect a machine per start.diff --git a/cli/src/dsh/artifacts.spec.ts b/cli/src/dsh/artifacts.spec.tsnew file mode 100644index 000000000..32deedbed--- /dev/null+++ b/cli/src/dsh/artifacts.spec.ts@@ -0,0 +1,51 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { isCandidateArtifact, newestArtifact } from './artifacts.js'+import { bundledDshRegistry, resetBundledDshRegistry } from './registry.js'+import { resolveInstallSource } from './install.js'++describe('newestArtifact', () => {+ let workspace: string+ beforeEach(() => { workspace = mkdtempSync(join(tmpdir(), 'dsh-art-')) })+ afterEach(() => rmSync(workspace, { recursive: true, force: true }))++ const touch = (rel: string, at: number): void => {+ const path = join(workspace, rel)+ mkdirSync(join(path, '..'), { recursive: true })+ writeFileSync(path, 'x')+ utimesSync(path, at, at)+ }++ it('picks the most recently modified file with a wanted extension, skipping generated trees', () => {+ touch('models/old.step', 1_000)+ touch('models/new.STEP', 3_000)+ touch('notes.txt', 9_000)+ touch('node_modules/lib/newest.step', 9_000)+ touch('__cadgen__/cache.step', 9_000)+ touch('.hidden/x.step', 9_000)+ expect(newestArtifact(workspace, ['.step', '.stl'])?.path).toBe('models/new.STEP')+ expect(newestArtifact(workspace, ['.glb'])).toBeNull()+ expect(newestArtifact(workspace, [])).toBeNull()+ })+})++describe('isCandidateArtifact', () => {+ it('matches by extension and refuses ignored directories', () => {+ expect(isCandidateArtifact('/ws/models/a.step', ['.step'])).toBe(true)+ expect(isCandidateArtifact('/ws/a.txt', ['.step'])).toBe(false)+ expect(isCandidateArtifact('/ws/node_modules/a.step', ['.step'])).toBe(false)+ })+})++describe('bundledDshRegistry', () => {+ it('reads the registry off the source tree in dev, with Circuit and Workshop present', () => {+ resetBundledDshRegistry()+ const ids = bundledDshRegistry().map((entry) => entry.id)+ expect(ids).toEqual(expect.arrayContaining(['autonomous/circuit', 'autonomous/workshop']))+ expect(resolveInstallSource('autonomous/circuit')).toMatchObject({ source: 'https://github.com/autonomous-ai/autonomous-circuit', id: 'autonomous/circuit' })+ expect(resolveInstallSource('https://example.com/x.git')).toEqual({ source: 'https://example.com/x.git' })+ expect(resolveInstallSource('bad\nsource')).toBeNull()+ })+})diff --git a/cli/src/dsh/artifacts.ts b/cli/src/dsh/artifacts.tsnew file mode 100644index 000000000..663b1a9fd--- /dev/null+++ b/cli/src/dsh/artifacts.ts@@ -0,0 +1,72 @@+/**+ * The newest artifact under a workspace, by extension — what the viewer shows when the verdict+ * names nothing (a STEP written by `gen` between two verifications, for instance).+ *+ * A bounded walk: generated and vendored trees are skipped by name, depth is capped, and the count+ * is capped, so a workspace that is also a large repo costs a few milliseconds, not a scan of+ * `node_modules`.+ */+import { readdirSync, statSync } from 'node:fs'+import { join, relative } from 'node:path'++export const ARTIFACT_IGNORED_DIRS: ReadonlySet<string> = new Set([+ 'node_modules', '.git', '.venv', 'venv', '__pycache__', '__cadgen__', '.circuit', '.harness',+ '.claude', '.agents', '.codex', 'dist', 'build', '.cache', 'inputs', 'blocks',+])+const MAX_DEPTH = 6+const MAX_FILES = 20_000++export function isArtifactDirIgnored(name: string): boolean {+ return ARTIFACT_IGNORED_DIRS.has(name)+}++export interface ArtifactHit {+ /** Workspace-relative, forward slashes. */+ path: string+ mtimeMs: number+}++export function newestArtifact(workspace: string, extensions: readonly string[]): ArtifactHit | null {+ if (!extensions.length) return null+ const wanted = new Set(extensions.map((ext) => ext.toLowerCase()))+ let best: ArtifactHit | null = null+ let seen = 0+ const walk = (dir: string, depth: number): void => {+ if (depth > MAX_DEPTH || seen > MAX_FILES) return+ let names: string[]+ try {+ names = readdirSync(dir)+ } catch {+ return+ }+ for (const name of names) {+ if (seen++ > MAX_FILES) return+ const path = join(dir, name)+ let st: ReturnType<typeof statSync>+ try {+ st = statSync(path)+ } catch {+ continue+ }+ if (st.isDirectory()) {+ if (!isArtifactDirIgnored(name) && !name.startsWith('.')) walk(path, depth + 1)+ continue+ }+ if (!st.isFile()) continue+ const dot = name.lastIndexOf('.')+ if (dot < 0 || !wanted.has(name.slice(dot).toLowerCase())) continue+ if (!best || st.mtimeMs > best.mtimeMs) {+ best = { path: relative(workspace, path).split('\\').join('/'), mtimeMs: st.mtimeMs }+ }+ }+ }+ walk(workspace, 0)+ return best+}++/** True when `path` (relative or absolute) ends with one of `extensions` and is not under an ignored directory. */+export function isCandidateArtifact(path: string, extensions: readonly string[]): boolean {+ const lower = path.toLowerCase()+ if (!extensions.some((ext) => lower.endsWith(ext.toLowerCase()))) return false+ return !path.split(/[\\/]/).slice(0, -1).some((segment) => isArtifactDirIgnored(segment))+}diff --git a/cli/src/dsh/command.ts b/cli/src/dsh/command.tsnew file mode 100644index 000000000..1d03ab6c8--- /dev/null+++ b/cli/src/dsh/command.ts@@ -0,0 +1,87 @@+/**+ * `harness dsh …` — the terminal face of domain-specific harnesses, for a server with no desktop+ * and for the development loop (`--link` a checkout, iterate, no re-clone).+ */+import { listDshState, installedDsh } from './installed.js'+import { dshTier } from './manifest.js'+import { bundledDshRegistry } from './registry.js'+import { installDsh, removeDsh, resolveInstallSource, runDshDoctor } from './install.js'++export function dshUsage(): string {+ return `Domain-specific harnesses (a DSH turns Harness into a product for one domain — see dsh/README.md):+ harness dsh list what is installed on this computer, and what the registry offers+ harness dsh install <id|url|path> [--ref <ref>] [--link]+ install by registry id (autonomous/circuit), git URL, or local path;+ --link symlinks a local checkout instead of cloning it+ harness dsh doctor <id> re-run the harness's own readiness check+ harness dsh remove <id> uninstall (a --link install removes only the link)`+}++function flagValue(argv: readonly string[], flag: string): string | undefined {+ const at = argv.indexOf(flag)+ return at >= 0 ? argv[at + 1] : undefined+}++/** `verb` is the word after `dsh`; `rest` is everything after THAT, flags included. */+export async function dshCommand(verb: string | undefined, rest: readonly string[]): Promise<number> {+ const args = rest.filter((arg) => !arg.startsWith('-'))+ switch (verb) {+ case 'list': {+ const { installed, broken } = listDshState()+ const registry = bundledDshRegistry()+ const seen = new Set<string>()+ const rows: string[] = []+ for (const dsh of installed) {+ seen.add(dsh.id)+ rows.push(` ${dsh.id.padEnd(28)} ${dsh.manifest.name.padEnd(12)} on ${dsh.manifest.engine.padEnd(8)} tier ${dshTier(dsh.manifest)} installed${dsh.linked ? ' (linked)' : ''} · ${dsh.dir}`)+ }+ for (const row of broken) {+ seen.add(row.id)+ rows.push(` ${row.id.padEnd(28)} ${'?'.padEnd(12)} ${''.padEnd(11)} ${''.padEnd(6)} BROKEN · ${row.error}`)+ }+ for (const entry of registry) {+ if (seen.has(entry.id)) continue+ rows.push(` ${entry.id.padEnd(28)} ${entry.name.padEnd(12)} on ${entry.engine.padEnd(8)} tier ${entry.tier ?? '?'} available · ${entry.repo}`)+ }+ console.log(rows.length ? rows.join('\n') : ' (nothing installed, registry empty)')+ return 0+ }+ case 'install': {+ const target = args[0]+ if (!target) { console.error(dshUsage()); return 1 }+ const resolved = resolveInstallSource(target)+ if (!resolved) { console.error(`harness dsh install: ${target} is not an id, URL or path`); return 1 }+ const link = rest.includes('--link')+ const ref = flagValue(rest, '--ref') ?? resolved.ref+ const result = await installDsh({+ source: resolved.source,+ ref: link ? undefined : ref,+ link,+ onProgress: (p) => console.log(`[dsh] ${p.id ?? target} · ${p.phase}${p.detail ? ` · ${p.detail}` : ''}`),+ onLine: (line) => console.log(` ${line}`),+ })+ if (!result.ok) { console.error(`harness dsh install failed · ${result.error} · ${result.detail}`); return 1 }+ console.log(`Installed ${result.installed.id} (${result.installed.manifest.name}, runs on ${result.installed.manifest.engine}) at ${result.installed.dir}`)+ return 0+ }+ case 'doctor': {+ const id = args[0]+ const dsh = id ? installedDsh(id) : undefined+ if (!dsh) { console.error(`harness dsh doctor: ${id ?? '<id>'} is not installed`); return 1 }+ const doctor = await runDshDoctor(dsh, (line) => console.log(` ${line}`))+ console.log(doctor.ok ? `${dsh.id} is ready` : `${dsh.id} is not ready`)+ return doctor.ok ? 0 : 1+ }+ case 'remove': {+ const id = args[0]+ if (!id) { console.error(dshUsage()); return 1 }+ const result = removeDsh(id)+ if (!result.ok) { console.error(`harness dsh remove failed · ${result.error} · ${result.detail}`); return 1 }+ console.log(`Removed ${id}`)+ return 0+ }+ default:+ console.error(dshUsage())+ return verb === undefined || verb === 'help' ? 0 : 1+ }+}diff --git a/cli/src/dsh/install.ts b/cli/src/dsh/install.tsnew file mode 100644index 000000000..e2d743d5a--- /dev/null+++ b/cli/src/dsh/install.ts@@ -0,0 +1,222 @@+/**+ * `harness dsh install`: clone (or link) a DSH repo under `~/.harness/dsh/<owner>/<name>`, run its+ * setup once, run its doctor, and record it in the index. The same function backs the desktop's+ * "Harness will install Circuit on this machine before starting" — the phases it reports are the+ * `dsh_install_status` frames the app shows.+ *+ * The clone lands in a temporary directory first, because the install path is derived from the+ * manifest's own id — which we cannot know until the clone exists. A manifest that fails to parse+ * leaves nothing behind.+ */+import { execFile } from 'node:child_process'+import { existsSync, lstatSync, mkdirSync, realpathSync, renameSync, rmSync, symlinkSync } from 'node:fs'+import { randomUUID } from 'node:crypto'+import { dirname, isAbsolute, join, resolve } from 'node:path'+import { promisify } from 'node:util'+import {+ dshInstallDir, dshRootDir, installedDsh, readInstalledIndex, removeInstalledRecord, resolveInstalled,+ upsertInstalledRecord, isBrokenDsh, type InstalledDsh, type InstalledDshRecord,+} from './installed.js'+import { readDshManifest, type DshManifest } from './manifest.js'+import { registryEntry } from './registry.js'+import { runDshCommand } from './shell.js'++const execFileAsync = promisify(execFile)++export type DshInstallPhase = 'clone' | 'setup' | 'doctor' | 'done' | 'failed'++export interface DshInstallProgress {+ /** Known once the manifest has been read; null while cloning by URL. */+ id: string | null+ phase: DshInstallPhase+ detail?: string+}++export interface DshInstallOptions {+ /** A git URL, or a local path (cloned unless `link`). */+ source: string+ ref?: string+ /** Symlink a local checkout instead of cloning it — the development loop. */+ link?: boolean+ onProgress?: (progress: DshInstallProgress) => void+ /** Setup/doctor output, line by line. */+ onLine?: (line: string) => void+ setupTimeoutMs?: number+}++export interface DshDoctorResult {+ ok: boolean+ lines: string[]+}++export type DshInstallResult =+ | { ok: true; installed: InstalledDsh; doctor: DshDoctorResult; setupLines: string[] }+ | { ok: false; error: string; detail: string }++/** A registry id (`autonomous/circuit`) resolves to its repo and ref; anything else is a source. */+export function resolveInstallSource(idOrSource: string): { source: string; ref?: string; id?: string } | null {+ const entry = registryEntry(idOrSource)+ if (entry) return { source: entry.repo, ref: entry.ref, id: entry.id }+ if (!idOrSource || /[\x00-\x1f\x7f]/.test(idOrSource)) return null+ return { source: idOrSource }+}++async function gitHead(dir: string): Promise<string | null> {+ try {+ const { stdout } = await execFileAsync('git', ['-C', dir, 'rev-parse', 'HEAD'], { timeout: 10_000 })+ return stdout.trim() || null+ } catch {+ return null+ }+}++function linkInstall(source: string): { ok: true; realDir: string; manifest: DshManifest } | { ok: false; error: string; detail: string } {+ if (!isAbsolute(source)) return { ok: false, error: 'INVALID_SOURCE', detail: '--link needs an absolute path to a checkout' }+ let realDir: string+ try {+ realDir = realpathSync(source)+ } catch {+ return { ok: false, error: 'SOURCE_NOT_FOUND', detail: `${source} does not exist` }+ }+ const manifest = readDshManifest(realDir)+ if (!manifest.ok) return { ok: false, error: 'INVALID_MANIFEST', detail: manifest.error }+ return { ok: true, realDir, manifest: manifest.manifest }+}++async function cloneInstall(+ source: string,+ ref: string | undefined,+ onLine: ((line: string) => void) | undefined,+): Promise<{ ok: true; tmpDir: string; manifest: DshManifest; commit: string | null } | { ok: false; error: string; detail: string }> {+ const root = dshRootDir()+ mkdirSync(root, { recursive: true, mode: 0o700 })+ const tmpDir = join(root, `.tmp-${randomUUID()}`)+ const args = ['clone', '--depth', '1', ...(ref ? ['--branch', ref] : []), '--', source, tmpDir]+ try {+ const { stderr } = await execFileAsync('git', args, { timeout: 10 * 60_000, maxBuffer: 8 * 1024 * 1024 })+ for (const line of stderr.split('\n')) if (line.trim()) onLine?.(line)+ } catch (error) {+ rmSync(tmpDir, { recursive: true, force: true })+ const detail = error instanceof Error ? error.message : String(error)+ return { ok: false, error: 'CLONE_FAILED', detail: detail.slice(0, 2000) }+ }+ const manifest = readDshManifest(tmpDir)+ if (!manifest.ok) {+ rmSync(tmpDir, { recursive: true, force: true })+ return { ok: false, error: 'INVALID_MANIFEST', detail: manifest.error }+ }+ return { ok: true, tmpDir, manifest: manifest.manifest, commit: await gitHead(tmpDir) }+}++/** Put the clone (or the link) at its final path, replacing whatever an earlier install left there. */+function placeAt(id: string, from: { tmpDir: string } | { linkTo: string }): string {+ const dir = dshInstallDir(id)+ mkdirSync(dirname(dir), { recursive: true, mode: 0o700 })+ let existing: ReturnType<typeof lstatSync> | null = null+ try { existing = lstatSync(dir) } catch { existing = null }+ if (existing) rmSync(dir, { recursive: true, force: true })+ if ('tmpDir' in from) renameSync(from.tmpDir, dir)+ else symlinkSync(from.linkTo, dir)+ return dir+}++export async function runDshDoctor(installed: InstalledDsh, onLine?: (line: string) => void): Promise<DshDoctorResult> {+ const doctor = installed.manifest.toolchain?.doctor+ if (!doctor) return { ok: true, lines: [] }+ const result = await runDshCommand(doctor, {+ cwd: installed.realDir,+ env: { HARNESS_DSH: installed.id, HARNESS_DSH_DIR: installed.realDir },+ onLine,+ timeoutMs: 60_000,+ })+ return { ok: result.code === 0 && !result.timedOut, lines: result.lines }+}++export async function installDsh(opts: DshInstallOptions): Promise<DshInstallResult> {+ const progress = (p: DshInstallProgress): void => opts.onProgress?.(p)+ let manifest: DshManifest+ let dir: string+ let commit: string | null = null+ let realDir: string++ progress({ id: null, phase: 'clone', detail: opts.link ? `linking ${opts.source}` : `cloning ${opts.source}` })+ if (opts.link) {+ const linked = linkInstall(opts.source)+ if (!linked.ok) { progress({ id: null, phase: 'failed', detail: linked.detail }); return linked }+ manifest = linked.manifest+ realDir = linked.realDir+ dir = placeAt(manifest.id, { linkTo: realDir })+ commit = await gitHead(realDir)+ } else {+ const cloned = await cloneInstall(opts.source, opts.ref, opts.onLine)+ if (!cloned.ok) { progress({ id: null, phase: 'failed', detail: cloned.detail }); return cloned }+ manifest = cloned.manifest+ commit = cloned.commit+ dir = placeAt(manifest.id, { tmpDir: cloned.tmpDir })+ realDir = realpathSync(dir)+ }++ const record: InstalledDshRecord = {+ id: manifest.id,+ dir,+ source: opts.link ? resolve(opts.source) : opts.source,+ ref: opts.ref ?? null,+ commit,+ linked: opts.link === true,+ installedAt: Date.now(),+ }+ const resolved = resolveInstalled(record)+ if (isBrokenDsh(resolved)) {+ progress({ id: manifest.id, phase: 'failed', detail: resolved.error })+ return { ok: false, error: 'INVALID_MANIFEST', detail: resolved.error }+ }++ const setupLines: string[] = []+ if (manifest.toolchain?.setup) {+ progress({ id: manifest.id, phase: 'setup', detail: manifest.toolchain.setup })+ const setup = await runDshCommand(manifest.toolchain.setup, {+ cwd: realDir,+ env: { HARNESS_DSH: manifest.id, HARNESS_DSH_DIR: realDir },+ onLine: (line) => { setupLines.push(line); opts.onLine?.(line) },+ timeoutMs: opts.setupTimeoutMs ?? 30 * 60_000,+ })+ if (setup.code !== 0 || setup.timedOut) {+ const detail = setup.timedOut+ ? 'setup timed out'+ : `setup exited ${setup.code ?? setup.signal} · ${setup.lines.slice(-5).join(' · ')}`.slice(0, 2000)+ progress({ id: manifest.id, phase: 'failed', detail })+ return { ok: false, error: 'SETUP_FAILED', detail }+ }+ }++ progress({ id: manifest.id, phase: 'doctor' })+ const doctor = await runDshDoctor(resolved, opts.onLine)+ // Recorded even when the doctor complains: the user can fix the machine and run the doctor again+ // without re-cloning. The desktop reads the doctor's answer, not the index, before a create.+ upsertInstalledRecord(record)+ if (!doctor.ok) {+ const detail = `doctor failed · ${doctor.lines.filter((line) => line.startsWith('miss')).join(' · ') || doctor.lines.slice(-3).join(' · ')}`.slice(0, 2000)+ progress({ id: manifest.id, phase: 'failed', detail })+ return { ok: false, error: 'DOCTOR_FAILED', detail }+ }+ progress({ id: manifest.id, phase: 'done' })+ return { ok: true, installed: resolved, doctor, setupLines }+}++export function removeDsh(id: string): { ok: true } | { ok: false; error: string; detail: string } {+ const record = readInstalledIndex().find((row) => row.id === id)+ if (!record) return { ok: false, error: 'NOT_INSTALLED', detail: `${id} is not installed` }+ try {+ // A linked install is a symlink: remove the link, never the checkout it points at.+ let isLink = false+ try { isLink = lstatSync(record.dir).isSymbolicLink() } catch { isLink = false }+ if (isLink) rmSync(record.dir, { force: true })+ else if (existsSync(record.dir)) rmSync(record.dir, { recursive: true, force: true })+ } catch (error) {+ return { ok: false, error: 'REMOVE_FAILED', detail: error instanceof Error ? error.message : String(error) }+ }+ removeInstalledRecord(id)+ return { ok: true }+}++export { installedDsh }diff --git a/cli/src/dsh/installed.ts b/cli/src/dsh/installed.tsnew file mode 100644index 000000000..08b8ebcf3--- /dev/null+++ b/cli/src/dsh/installed.ts@@ -0,0 +1,152 @@+/**+ * What is installed on THIS machine: `~/.harness/dsh/installed.json` plus one directory (or, for a+ * `--link` install, one symlink) per DSH under `~/.harness/dsh/<owner>/<name>`.+ *+ * The index is the source of truth for "installed"; a directory without an index row is ignored,+ * and a row whose manifest no longer parses is reported broken rather than silently dropped, so a+ * DSH that breaks on update is visible in `harness dsh list` instead of vanishing from the picker.+ */+import { existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'+import { join } from 'node:path'+import { env } from '../config/env.js'+import { DSH_ID_RE, readDshManifest, type DshManifest } from './manifest.js'++export interface InstalledDshRecord {+ id: string+ /** `<root>/<owner>/<name>`, whether a clone or a symlink. */+ dir: string+ /** The git URL or local path it came from. */+ source: string+ ref: string | null+ commit: string | null+ /** True when `dir` is a symlink to a checkout — the development loop. */+ linked: boolean+ installedAt: number+}++export interface InstalledDsh extends InstalledDshRecord {+ manifest: DshManifest+ /** `dir` with symlinks resolved — where the files really are. */+ realDir: string+}++export interface BrokenDsh extends InstalledDshRecord {+ error: string+}++const INDEX_FILE = 'installed.json'++export function dshRootDir(): string {+ return env.DSH_DIR+}++export function dshInstallDir(id: string): string {+ return join(dshRootDir(), ...id.split('/'))+}++function indexPath(): string {+ return join(dshRootDir(), INDEX_FILE)+}++function validRecord(value: unknown): value is InstalledDshRecord {+ if (!value || typeof value !== 'object') return false+ const row = value as Partial<InstalledDshRecord>+ return typeof row.id === 'string' && DSH_ID_RE.test(row.id)+ && typeof row.dir === 'string' && row.dir.length > 0+ && typeof row.source === 'string'+ && (row.ref === null || typeof row.ref === 'string')+ && (row.commit === null || typeof row.commit === 'string')+ && typeof row.linked === 'boolean'+ && typeof row.installedAt === 'number'+}++export function readInstalledIndex(): InstalledDshRecord[] {+ let text: string+ try {+ text = readFileSync(indexPath(), 'utf8')+ } catch {+ return []+ }+ try {+ const parsed = JSON.parse(text) as unknown+ return Array.isArray(parsed) ? parsed.filter(validRecord) : []+ } catch {+ return []+ }+}++export function writeInstalledIndex(records: readonly InstalledDshRecord[]): void {+ mkdirSync(dshRootDir(), { recursive: true, mode: 0o700 })+ writeFileSync(indexPath(), JSON.stringify(records, null, 2) + '\n', { mode: 0o600 })+}++export function upsertInstalledRecord(record: InstalledDshRecord): void {+ const others = readInstalledIndex().filter((row) => row.id !== record.id)+ writeInstalledIndex([...others, record].sort((a, b) => a.id.localeCompare(b.id)))+ invalidateInstalledDsh()+}++export function removeInstalledRecord(id: string): boolean {+ const before = readInstalledIndex()+ const after = before.filter((row) => row.id !== id)+ if (after.length === before.length) return false+ writeInstalledIndex(after)+ invalidateInstalledDsh()+ return true+}++/** Load one record's manifest, or say why it is broken. */+export function resolveInstalled(record: InstalledDshRecord): InstalledDsh | BrokenDsh {+ if (!existsSync(record.dir)) return { ...record, error: `${record.dir} is missing` }+ let realDir: string+ try {+ realDir = realpathSync(record.dir)+ } catch (error) {+ return { ...record, error: `${record.dir} cannot be resolved (${error instanceof Error ? error.message : String(error)})` }+ }+ const manifest = readDshManifest(realDir)+ if (!manifest.ok) return { ...record, error: manifest.error }+ if (manifest.manifest.id !== record.id) {+ return { ...record, error: `manifest id ${manifest.manifest.id} does not match the installed id ${record.id}` }+ }+ return { ...record, manifest: manifest.manifest, realDir }+}++export function isBrokenDsh(value: InstalledDsh | BrokenDsh): value is BrokenDsh {+ return 'error' in value+}++// The daemon asks "is this agent's DSH installed" on every frame it projects, which is every+// announce of every agent. A short cache keeps that off the disk; installs and removals clear it.+const CACHE_TTL_MS = 2_000+let cache: { at: number; installed: InstalledDsh[]; broken: BrokenDsh[] } | null = null++function stateNow(): { installed: InstalledDsh[]; broken: BrokenDsh[] } {+ if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache+ const installed: InstalledDsh[] = []+ const broken: BrokenDsh[] = []+ for (const entry of readInstalledIndex().map(resolveInstalled)) {+ if (isBrokenDsh(entry)) broken.push(entry)+ else installed.push(entry)+ }+ cache = { at: Date.now(), installed, broken }+ return cache+}++/** Forget the cached index — after an install, a removal, or in a spec that rewrites the directory. */+export function invalidateInstalledDsh(): void {+ cache = null+}++/** Every installed DSH whose manifest loads. Broken ones are returned separately by `listDshState`. */+export function listInstalledDsh(): InstalledDsh[] {+ return stateNow().installed+}++export function listDshState(): { installed: InstalledDsh[]; broken: BrokenDsh[] } {+ return stateNow()+}++export function installedDsh(id: string): InstalledDsh | undefined {+ return stateNow().installed.find((entry) => entry.id === id)+}diff --git a/cli/src/dsh/launch.spec.ts b/cli/src/dsh/launch.spec.tsnew file mode 100644index 000000000..ebe7777c9--- /dev/null+++ b/cli/src/dsh/launch.spec.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from 'vitest'+import type { InstalledDsh } from './installed.js'+import { dshLaunch } from './launch.js'+import { buildLaunchOverrides, type LaunchOverridesDeps } from '../lib/launchOverrides.js'+import { dshFromEnv } from './probe.js'++const installed: InstalledDsh = {+ id: 'autonomous/circuit', dir: '/home/u/.harness/dsh/autonomous/circuit', realDir: '/src/circuit',+ source: '', ref: null, commit: null, linked: true, installedAt: 0,+ manifest: {+ spec: 1, id: 'autonomous/circuit', name: 'Circuit', engine: 'claude',+ agent: {+ env: { CIRCUIT_TOOLCHAIN: '${dsh}/toolchain', CIRCUIT_SKILLS_DIR: '${workspace}/.claude/skills', HARNESS_DSH: 'spoofed' },+ args: ['--add-dir', '${workspace}/inputs'],+ },+ },+}++describe('dshLaunch', () => {+ it('sets the three HARNESS_ variables, expands the manifest env, and refuses a manifest that renames itself', () => {+ const launch = dshLaunch(installed, '/ws')+ expect(launch.env).toEqual({+ HARNESS_DSH: 'autonomous/circuit',+ HARNESS_DSH_DIR: '/src/circuit',+ HARNESS_WORKSPACE: '/ws',+ CIRCUIT_TOOLCHAIN: '/src/circuit/toolchain',+ CIRCUIT_SKILLS_DIR: '/ws/.claude/skills',+ })+ expect(launch.args).toEqual(['--add-dir', '/ws/inputs'])+ // What discovery reads back is exactly what was set.+ expect(dshFromEnv(launch.env)).toBe('autonomous/circuit')+ })+})++describe('buildLaunchOverrides with a DSH', () => {+ const deps: LaunchOverridesDeps = {+ configDirFor: () => undefined,+ writeGridConfigDir: async () => '/cfg',+ tmuxSupportsSessionEnv: async () => true,+ installCodexHooks: () => undefined,+ dshLaunch: (id, workspace) => (id === installed.id ? dshLaunch(installed, workspace) : null),+ }++ it('layers the DSH env and argv over a plain relaunch', async () => {+ const built = await buildLaunchOverrides(deps, 'claude', { dsh: 'autonomous/circuit', cwd: '/ws' }, 'agent-1')+ expect(built.ok).toBe(true)+ if (!built.ok) return+ expect(built.overrides.env.HARNESS_DSH).toBe('autonomous/circuit')+ expect(built.overrides.env.CIRCUIT_TOOLCHAIN).toBe('/src/circuit/toolchain')+ expect(built.overrides.extraArgs).toEqual(['--add-dir', '/ws/inputs'])+ })++ it('layers it over a Codex profile too, keeping CODEX_HOME', async () => {+ const built = await buildLaunchOverrides(deps, 'codex', { dsh: 'autonomous/circuit', cwd: '/ws', codexHome: '/home/u/.codex-work' }, 'agent-1')+ expect(built.ok && built.overrides.env).toMatchObject({ CODEX_HOME: '/home/u/.codex-work', HARNESS_DSH: 'autonomous/circuit' })+ })++ it('falls back to the plain engine when the DSH is no longer installed here', async () => {+ const built = await buildLaunchOverrides(deps, 'claude', { dsh: 'gone/away', cwd: '/ws' }, 'agent-1')+ expect(built.ok && built.overrides).toEqual({ env: {}, extraArgs: [], clearEnv: [] })+ })++ it('does nothing without a workspace to expand into', async () => {+ const built = await buildLaunchOverrides(deps, 'claude', { dsh: 'autonomous/circuit', cwd: null }, 'agent-1')+ expect(built.ok && built.overrides.env).toEqual({})+ })+})++describe('dshFromEnv', () => {+ it('accepts only a well-formed id', () => {+ expect(dshFromEnv({ HARNESS_DSH: 'autonomous/workshop' })).toBe('autonomous/workshop')+ expect(dshFromEnv({ HARNESS_DSH: 'not an id' })).toBeNull()+ expect(dshFromEnv({})).toBeNull()+ })+})diff --git a/cli/src/dsh/launch.ts b/cli/src/dsh/launch.tsnew file mode 100644index 000000000..c5e436aa1--- /dev/null+++ b/cli/src/dsh/launch.ts@@ -0,0 +1,30 @@+/**+ * What a DSH adds to its base engine's launch: the three `HARNESS_*` variables every DSH script can+ * rely on, the manifest's own env with `${dsh}`/`${workspace}` expanded, and its extra argv.+ *+ * Applied on create AND on every relaunch (`launchOverrides.ts`), so an agent restored after a reboot+ * or restarted in place is still the DSH it was created as — and still discoverable as one, since+ * `HARNESS_DSH` is what `probe.ts` reads off the live process.+ */+import type { InstalledDsh } from './installed.js'+import { expandDshValue } from './manifest.js'++export interface DshLaunch {+ env: Record<string, string>+ args: string[]+}++export function dshLaunch(dsh: InstalledDsh, workspace: string): DshLaunch {+ const vars = { dsh: dsh.realDir, workspace }+ const env: Record<string, string> = {+ HARNESS_DSH: dsh.id,+ HARNESS_DSH_DIR: dsh.realDir,+ HARNESS_WORKSPACE: workspace,+ }+ for (const [key, value] of Object.entries(dsh.manifest.agent?.env ?? {})) {+ if (key.startsWith('HARNESS_')) continue // ours; a manifest cannot rename itself+ env[key] = expandDshValue(value, vars)+ }+ const args = (dsh.manifest.agent?.args ?? []).map((arg) => expandDshValue(arg, vars))+ return { env, args }+}diff --git a/cli/src/dsh/manifest.spec.ts b/cli/src/dsh/manifest.spec.tsnew file mode 100644index 000000000..dc68aed26--- /dev/null+++ b/cli/src/dsh/manifest.spec.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'+import { dshSkillsDirFor, dshTier, dshVerdictPath, expandDshValue, parseDshManifest, readDshManifest } from './manifest.js'++const STARTER = fileURLToPath(new URL('../../../dsh/starter-dsh', import.meta.url))++describe('parseDshManifest', () => {+ it('accepts the starter fixture, which is also what the JSON Schema accepts', () => {+ const result = parseDshManifest(readFileSync(`${STARTER}/harness.json`, 'utf8'))+ expect(result.ok).toBe(true)+ if (!result.ok) return+ expect(result.manifest.id).toBe('autonomous/starter')+ expect(result.manifest.engine).toBe('claude')+ expect(dshTier(result.manifest)).toBe(0)+ expect(dshVerdictPath(result.manifest)).toBe('.harness/verdict.json')+ })++ it('reads it off a directory too', () => {+ expect(readDshManifest(STARTER).ok).toBe(true)+ expect(readDshManifest('/nonexistent/dir').ok).toBe(false)+ })++ const base = { spec: 1, id: 'acme/thing', name: 'Thing', engine: 'codex' }++ it('refuses paths that leave the harness', () => {+ for (const bad of ['../outside', '/abs/path', 'a/../../b']) {+ const result = parseDshManifest(JSON.stringify({ ...base, workspace: { template: bad } }))+ expect(result.ok, bad).toBe(false)+ }+ expect(parseDshManifest(JSON.stringify({ ...base, agent: { skills: ['skills', 'more/skills'] } })).ok).toBe(true)+ })++ it('refuses an unknown spec, a bad id, an unknown engine and unknown keys', () => {+ expect(parseDshManifest(JSON.stringify({ ...base, spec: 2 })).ok).toBe(false)+ expect(parseDshManifest(JSON.stringify({ ...base, id: 'NoSlash' })).ok).toBe(false)+ expect(parseDshManifest(JSON.stringify({ ...base, id: 'Acme/Thing' })).ok).toBe(false)+ expect(parseDshManifest(JSON.stringify({ ...base, engine: 'gpt' })).ok).toBe(false)+ expect(parseDshManifest(JSON.stringify({ ...base, extra: true })).ok).toBe(false)+ expect(parseDshManifest('not json').ok).toBe(false)+ })++ it('tiers by what ships', () => {+ const verdictOnly = parseDshManifest(JSON.stringify({ ...base, verdict: '.harness/verdict.json' }))+ const withViewer = parseDshManifest(JSON.stringify({ ...base, viewer: { command: 'x', url: 'http://127.0.0.1:${port}/' } }))+ expect(verdictOnly.ok && dshTier(verdictOnly.manifest)).toBe(1)+ expect(withViewer.ok && dshTier(withViewer.manifest)).toBe(2)+ })++ it('requires env keys to look like environment variables', () => {+ expect(parseDshManifest(JSON.stringify({ ...base, agent: { env: { 'lower-case': 'x' } } })).ok).toBe(false)+ expect(parseDshManifest(JSON.stringify({ ...base, agent: { env: { CIRCUIT_TOOLCHAIN: '${dsh}/toolchain' } } })).ok).toBe(true)+ })+})++describe('expandDshValue', () => {+ it('expands the three variables and leaves anything else alone', () => {+ const vars = { dsh: '/i/dsh', workspace: '/w', home: '/h' }+ expect(expandDshValue('${dsh}/toolchain:${workspace}/.claude:${home}', vars)).toBe('/i/dsh/toolchain:/w/.claude:/h')+ expect(expandDshValue('$HOME and ${other}', vars)).toBe('$HOME and ${other}')+ })+})++describe('dshSkillsDirFor', () => {+ it('puts Claude skills where Claude Code reads project skills, everyone else under .agents', () => {+ expect(dshSkillsDirFor('claude')).toBe('.claude/skills')+ expect(dshSkillsDirFor('codex')).toBe('.agents/skills')+ expect(dshSkillsDirFor('cursor')).toBe('.agents/skills')+ })+})diff --git a/cli/src/dsh/manifest.ts b/cli/src/dsh/manifest.tsnew file mode 100644index 000000000..e4237c677--- /dev/null+++ b/cli/src/dsh/manifest.ts@@ -0,0 +1,124 @@+/**+ * `harness.json` — the one file Harness reads about a domain-specific harness.+ *+ * Spec 1, frozen: see `dsh/spec/README.md` and `dsh/spec/schema/harness.schema.json` at the repo+ * root. The zod schema here is the runtime twin of that JSON Schema; the two must agree, and the+ * fixture under `dsh/starter-dsh/` is parsed by both in the spec.+ *+ * Every path in the manifest is relative to the DSH's install directory and must stay inside it —+ * a manifest is untrusted input (it arrives with a `git clone`), so `..` and absolute paths are+ * refused at parse time rather than discovered at copy time.+ */+import { readFileSync } from 'node:fs'+import { homedir } from 'node:os'+import { isAbsolute } from 'node:path'+import { z } from 'zod'+import { ENGINES } from '../engines/types.js'++export const DSH_ID_RE = /^[a-z0-9][a-z0-9-]{0,63}\/[a-z0-9][a-z0-9-]{0,63}$/+export const DSH_MANIFEST_FILE = 'harness.json'+export const DEFAULT_VERDICT_PATH = '.harness/verdict.json'++function insideHarness(path: string): boolean {+ if (isAbsolute(path)) return false+ return !path.split(/[\\/]/).some((segment) => segment === '..')+}++const relativePath = z.string().min(1).max(512).refine(insideHarness, {+ message: 'must be a relative path inside the harness (no leading / and no ..)',+})+const command = z.string().min(1).max(4096)++export const DshManifestSchema = z.strictObject({+ spec: z.literal(1),+ id: z.string().regex(DSH_ID_RE, 'id must be owner/name in lowercase letters, digits and dashes'),+ name: z.string().min(1).max(40),+ description: z.string().max(300).optional(),+ engine: z.enum(ENGINES),+ workspace: z.strictObject({+ template: relativePath.optional(),+ marker: relativePath.optional(),+ init: command.optional(),+ }).optional(),+ agent: z.strictObject({+ instructions: relativePath.optional(),+ skills: z.array(relativePath).max(32).optional(),+ env: z.record(z.string().regex(/^[A-Z_][A-Z0-9_]*$/, 'env keys are UPPER_SNAKE'), z.string().max(4096)).optional(),+ args: z.array(z.string().max(4096)).max(64).optional(),+ }).optional(),+ toolchain: z.strictObject({+ setup: command.optional(),+ doctor: command.optional(),+ }).optional(),+ viewer: z.strictObject({+ command,+ url: z.string().min(1).max(2048),+ artifactExtensions: z.array(z.string().regex(/^\.[A-Za-z0-9]+$/)).max(32).optional(),+ }).optional(),+ verdict: relativePath.optional(),+})++export type DshManifest = z.infer<typeof DshManifestSchema>++export type ManifestResult =+ | { ok: true; manifest: DshManifest }+ | { ok: false; error: string }++export function parseDshManifest(text: string): ManifestResult {+ let value: unknown+ try {+ value = JSON.parse(text)+ } catch (error) {+ return { ok: false, error: `harness.json is not JSON: ${error instanceof Error ? error.message : String(error)}` }+ }+ const parsed = DshManifestSchema.safeParse(value)+ if (parsed.success) return { ok: true, manifest: parsed.data }+ const issues = parsed.error.issues+ .slice(0, 5)+ .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)+ .join('; ')+ return { ok: false, error: `harness.json is not a spec-1 manifest: ${issues}` }+}++/** The manifest at `<dir>/harness.json`, or why there is none. */+export function readDshManifest(dir: string): ManifestResult {+ let text: string+ try {+ text = readFileSync(`${dir}/${DSH_MANIFEST_FILE}`, 'utf8')+ } catch (error) {+ return { ok: false, error: `no ${DSH_MANIFEST_FILE} in ${dir} (${error instanceof Error ? error.message : String(error)})` }+ }+ return parseDshManifest(text)+}++/** The variables a manifest value may name. `${dsh}` is the install directory. */+export interface DshVars {+ dsh: string+ workspace: string+ home?: string+}++/** Expand `${dsh}`, `${workspace}` and `${home}`; anything else is left exactly as written. */+export function expandDshValue(value: string, vars: DshVars): string {+ const home = vars.home ?? homedir()+ return value.replace(/\$\{(dsh|workspace|home)\}/g, (_, name: string) => (+ name === 'dsh' ? vars.dsh : name === 'workspace' ? vars.workspace : home+ ))+}++/** Which tier the manifest declares, by what it ships — the desktop shows this on the tile. */+export function dshTier(manifest: DshManifest): 0 | 1 | 2 {+ if (manifest.viewer) return 2+ if (manifest.verdict) return 1+ return 0+}++/** The workspace-relative path of the verdict file, defaulted. */+export function dshVerdictPath(manifest: DshManifest): string {+ return manifest.verdict ?? DEFAULT_VERDICT_PATH+}++/** Where a base engine looks for project-level skills. */+export function dshSkillsDirFor(engine: DshManifest['engine']): string {+ return engine === 'claude' ? '.claude/skills' : '.agents/skills'+}diff --git a/cli/src/dsh/materialize.spec.ts b/cli/src/dsh/materialize.spec.tsnew file mode 100644index 000000000..943f8bce4--- /dev/null+++ b/cli/src/dsh/materialize.spec.ts@@ -0,0 +1,96 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { existsSync, lstatSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import type { InstalledDsh } from './installed.js'+import { readDshManifest } from './manifest.js'+import { dshMarkerLine, materializeWorkspace, skillDirsIn } from './materialize.js'++const STARTER = realpathSync(fileURLToPath(new URL('../../../dsh/starter-dsh', import.meta.url)))++function starter(engine: 'claude' | 'codex' = 'claude'): InstalledDsh {+ const manifest = readDshManifest(STARTER)+ if (!manifest.ok) throw new Error(manifest.error)+ return {+ id: manifest.manifest.id,+ dir: STARTER,+ realDir: STARTER,+ source: STARTER,+ ref: null,+ commit: null,+ linked: true,+ installedAt: 0,+ manifest: { ...manifest.manifest, engine },+ }+}++describe('materializeWorkspace', () => {+ let workspace: string+ beforeEach(() => { workspace = mkdtempSync(join(tmpdir(), 'dsh-ws-')) })+ afterEach(() => rmSync(workspace, { recursive: true, force: true }))++ it('fills an empty workspace: template, AGENTS.md, CLAUDE.md import, skill link, .harness', async () => {+ const result = await materializeWorkspace(starter(), workspace)+ expect(result.warnings).toEqual([])+ expect(readFileSync(join(workspace, 'NOTES.md'), 'utf8')).toContain('# Notes')+ const agents = readFileSync(join(workspace, 'AGENTS.md'), 'utf8')+ expect(agents.startsWith(dshMarkerLine('autonomous/starter'))).toBe(true)+ expect(agents).toContain('Starter harness')+ expect(readFileSync(join(workspace, 'CLAUDE.md'), 'utf8').trim()).toBe('@AGENTS.md')+ const link = join(workspace, '.claude', 'skills', 'hello')+ expect(lstatSync(link).isSymbolicLink()).toBe(true)+ expect(readlinkSync(link)).toBe(join(STARTER, 'skills', 'hello'))+ expect(existsSync(join(link, 'SKILL.md'))).toBe(true)+ expect(existsSync(join(workspace, '.harness'))).toBe(true)+ expect(result.created).toContain('AGENTS.md')+ })++ it('is idempotent: a second run keeps everything and appends nothing', async () => {+ await materializeWorkspace(starter(), workspace)+ const before = readFileSync(join(workspace, 'AGENTS.md'), 'utf8')+ const again = await materializeWorkspace(starter(), workspace)+ expect(readFileSync(join(workspace, 'AGENTS.md'), 'utf8')).toBe(before)+ expect(again.created).toEqual([])+ expect(again.kept).toEqual(expect.arrayContaining(['NOTES.md', 'AGENTS.md', 'CLAUDE.md', '.claude/skills/hello']))+ })++ it("appends under a marker to the user's own AGENTS.md and CLAUDE.md, once", async () => {+ writeFileSync(join(workspace, 'NOTES.md'), 'mine\n') // marker present → no template copy+ writeFileSync(join(workspace, 'AGENTS.md'), '# Repo rules\n\nBe kind.\n')+ writeFileSync(join(workspace, 'CLAUDE.md'), '# Claude\n')+ await materializeWorkspace(starter(), workspace)+ await materializeWorkspace(starter(), workspace)+ const agents = readFileSync(join(workspace, 'AGENTS.md'), 'utf8')+ expect(agents.startsWith('# Repo rules')).toBe(true)+ expect(agents.split(dshMarkerLine('autonomous/starter')).length).toBe(2)+ const claude = readFileSync(join(workspace, 'CLAUDE.md'), 'utf8')+ expect(claude.startsWith('# Claude')).toBe(true)+ expect(claude.split('@AGENTS.md').length).toBe(2)+ expect(readFileSync(join(workspace, 'NOTES.md'), 'utf8')).toBe('mine\n')+ })++ it('links Codex skills under .agents and writes no CLAUDE.md', async () => {+ await materializeWorkspace(starter('codex'), workspace)+ expect(lstatSync(join(workspace, '.agents', 'skills', 'hello')).isSymbolicLink()).toBe(true)+ expect(existsSync(join(workspace, 'CLAUDE.md'))).toBe(false)+ expect(existsSync(join(workspace, '.claude'))).toBe(false)+ })++ it('leaves a real directory in the skills folder alone and says so', async () => {+ const { mkdirSync } = await import('node:fs')+ mkdirSync(join(workspace, '.claude', 'skills', 'hello'), { recursive: true })+ const result = await materializeWorkspace(starter(), workspace)+ expect(lstatSync(join(workspace, '.claude', 'skills', 'hello')).isSymbolicLink()).toBe(false)+ expect(result.warnings.some((w) => w.includes('hello'))).toBe(true)+ })+})++describe('skillDirsIn', () => {+ it('lists SKILL.md-bearing subdirectories, or the directory itself when it is one skill', () => {+ expect(skillDirsIn(join(STARTER, 'skills'))).toEqual([join(STARTER, 'skills', 'hello')])+ expect(skillDirsIn(join(STARTER, 'skills', 'hello'))).toEqual([join(STARTER, 'skills', 'hello')])+ expect(skillDirsIn(join(STARTER, 'template'))).toEqual([])+ expect(skillDirsIn('/nonexistent')).toEqual([])+ })+})diff --git a/cli/src/dsh/materialize.ts b/cli/src/dsh/materialize.tsnew file mode 100644index 000000000..9f87ae387--- /dev/null+++ b/cli/src/dsh/materialize.ts@@ -0,0 +1,163 @@+/**+ * Put a DSH into a workspace, idempotently, before its engine is launched there — the four steps of+ * the contract (`dsh/spec/README.md` § Materialization):+ *+ * 1. an EMPTY workspace (no marker) gets the template, then the init command runs;+ * 2. `AGENTS.md` is copied in, or the DSH's text is appended under a marker line; a `claude` base+ * also gets a `CLAUDE.md` that imports it, because that is the file Claude Code reads;+ * 3. each skill directory is symlinked into the engine's project-skills folder, so a DSH update+ * is live in every workspace without a second copy;+ * 4. `.harness/` exists, so the verdict watcher has a directory to watch before the first verdict.+ *+ * Nothing here touches the user's own files beyond those: an existing AGENTS.md keeps its content,+ * an existing skill link that points elsewhere is left alone and reported.+ */+import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'+import { basename, join, relative } from 'node:path'+import type { InstalledDsh } from './installed.js'+import { dshSkillsDirFor } from './manifest.js'+import { runDshCommand } from './shell.js'++export interface MaterializeResult {+ /** Files and links this call created. */+ created: string[]+ /** Things already in place, left untouched. */+ kept: string[]+ /** Things that could not be done, with why; never fatal. */+ warnings: string[]+ /** Output of the init command, when it ran. */+ initLines: string[]+}++export const AGENTS_FILE = 'AGENTS.md'+export const CLAUDE_FILE = 'CLAUDE.md'+export const CLAUDE_IMPORT_LINE = '@AGENTS.md'++export function dshMarkerLine(id: string): string {+ return `<!-- harness:dsh ${id} -->`+}++/** Subdirectories of `dir` that carry a SKILL.md, or `dir` itself when it is a single skill. */+export function skillDirsIn(dir: string): string[] {+ if (existsSync(join(dir, 'SKILL.md'))) return [dir]+ let entries: string[]+ try {+ entries = readdirSync(dir)+ } catch {+ return []+ }+ return entries+ .map((name) => join(dir, name))+ .filter((path) => {+ try { return statSync(path).isDirectory() && existsSync(join(path, 'SKILL.md')) } catch { return false }+ })+ .sort()+}++function ensureDir(path: string): void {+ mkdirSync(path, { recursive: true })+}++function copyTemplate(templateDir: string, workspace: string, result: MaterializeResult): void {+ if (!existsSync(templateDir)) {+ result.warnings.push(`template ${templateDir} is missing`)+ return+ }+ // Never overwrite: a workspace with no marker may still have files the user put there.+ cpSync(templateDir, workspace, { recursive: true, force: false, errorOnExist: false })+ result.created.push(`template → ${workspace}`)+}++function writeInstructions(dsh: InstalledDsh, workspace: string, result: MaterializeResult): void {+ const source = dsh.manifest.agent?.instructions+ if (!source) return+ const sourcePath = join(dsh.realDir, source)+ let text: string+ try {+ text = readFileSync(sourcePath, 'utf8')+ } catch {+ result.warnings.push(`instructions ${sourcePath} could not be read`)+ return+ }+ const marker = dshMarkerLine(dsh.id)+ const target = join(workspace, AGENTS_FILE)+ const body = `${marker}\n${text.trim()}\n`+ if (!existsSync(target)) {+ writeFileSync(target, body)+ result.created.push(AGENTS_FILE)+ } else {+ const existing = readFileSync(target, 'utf8')+ if (existing.includes(marker)) {+ result.kept.push(AGENTS_FILE)+ } else {+ writeFileSync(target, `${existing.replace(/\s*$/, '')}\n\n${body}`)+ result.created.push(`${AGENTS_FILE} (appended)`)+ }+ }+ if (dsh.manifest.engine === 'claude') {+ const claude = join(workspace, CLAUDE_FILE)+ if (!existsSync(claude)) {+ writeFileSync(claude, `${CLAUDE_IMPORT_LINE}\n`)+ result.created.push(CLAUDE_FILE)+ } else {+ const existing = readFileSync(claude, 'utf8')+ if (existing.split('\n').some((line) => line.trim() === CLAUDE_IMPORT_LINE)) {+ result.kept.push(CLAUDE_FILE)+ } else {+ writeFileSync(claude, `${existing.replace(/\s*$/, '')}\n\n${CLAUDE_IMPORT_LINE}\n`)+ result.created.push(`${CLAUDE_FILE} (import added)`)+ }+ }+ }+}++function linkSkills(dsh: InstalledDsh, workspace: string, result: MaterializeResult): void {+ const roots = dsh.manifest.agent?.skills ?? []+ if (!roots.length) return+ const skillsDir = join(workspace, dshSkillsDirFor(dsh.manifest.engine))+ ensureDir(skillsDir)+ for (const root of roots) {+ const dirs = skillDirsIn(join(dsh.realDir, root))+ if (!dirs.length) result.warnings.push(`no SKILL.md under ${root}`)+ for (const dir of dirs) {+ const link = join(skillsDir, basename(dir))+ let existing: ReturnType<typeof lstatSync> | null = null+ try { existing = lstatSync(link) } catch { existing = null }+ if (existing?.isSymbolicLink()) {+ if (readlinkSync(link) === dir) { result.kept.push(relative(workspace, link)); continue }+ // Ours from an earlier install path (a relink, a moved checkout): repoint it.+ rmSync(link)+ } else if (existing) {+ result.warnings.push(`${relative(workspace, link)} exists and is not a link; left alone`)+ continue+ }+ symlinkSync(dir, link)+ result.created.push(relative(workspace, link))+ }+ }+}++export async function materializeWorkspace(dsh: InstalledDsh, workspace: string): Promise<MaterializeResult> {+ const result: MaterializeResult = { created: [], kept: [], warnings: [], initLines: [] }+ const ws = dsh.manifest.workspace+ const marker = ws?.marker ? join(workspace, ws.marker) : null+ const fresh = marker ? !existsSync(marker) : false+ if (fresh && ws?.template) copyTemplate(join(dsh.realDir, ws.template), workspace, result)+ if (fresh && ws?.init) {+ const init = await runDshCommand(ws.init, {+ cwd: workspace,+ env: { HARNESS_DSH: dsh.id, HARNESS_DSH_DIR: dsh.realDir, HARNESS_WORKSPACE: workspace },+ onLine: (line) => result.initLines.push(line),+ timeoutMs: 5 * 60_000,+ })+ if (init.code !== 0 || init.timedOut) {+ result.warnings.push(`init exited ${init.timedOut ? 'by timeout' : init.code ?? init.signal}`)+ }+ } else if (marker && !fresh) {+ result.kept.push(ws!.marker!)+ }+ writeInstructions(dsh, workspace, result)+ linkSkills(dsh, workspace, result)+ ensureDir(join(workspace, '.harness'))+ return result+}diff --git a/cli/src/dsh/probe.ts b/cli/src/dsh/probe.tsnew file mode 100644index 000000000..d617ed103--- /dev/null+++ b/cli/src/dsh/probe.ts@@ -0,0 +1,25 @@+/**+ * Which DSH a live engine process belongs to, read off its environment — the same cached read+ * `probeCodexHome` uses, one `ps` per process for its whole life.+ *+ * Three answers, the same contract as the other probes: an id when the process carries+ * `HARNESS_DSH`, `null` when it does not (a plain engine), and `undefined` when the process could+ * not be read — which must never overwrite what the registry already knows.+ */+import { readProcessEnv } from '../lib/processEnv.js'+import type { ProcessIdentity } from '../lib/registry.js'+import { DSH_ID_RE } from './manifest.js'++export const DSH_ENV_VAR = 'HARNESS_DSH'++/** Pure half, for specs and for callers that already hold the environment. */+export function dshFromEnv(processEnv: Record<string, string>): string | null {+ const id = processEnv[DSH_ENV_VAR]+ return typeof id === 'string' && DSH_ID_RE.test(id) ? id : null+}++export async function probeDsh(identity: ProcessIdentity): Promise<string | null | undefined> {+ const processEnv = await readProcessEnv(identity)+ if (!processEnv) return undefined+ return dshFromEnv(processEnv)+}diff --git a/cli/src/dsh/registry.ts b/cli/src/dsh/registry.tsnew file mode 100644index 000000000..c10c98450--- /dev/null+++ b/cli/src/dsh/registry.ts@@ -0,0 +1,97 @@+/**+ * The bundled registry: `dsh/registry/<owner>/<name>.json` at the repo root, baked into the CLI at+ * build time the same way the version is (`__DSH_REGISTRY__`, an esbuild `define` in both+ * `build.mjs` and `build-bundle.mjs`). Under `tsx`/vitest there is no define, so the files are read+ * off the source tree — the dev loop sees the same entries the release does.+ *+ * A registry entry is how the desktop can offer "Install Circuit" for a DSH this machine does not+ * have yet: it names the repo and the ref to clone. Nothing here runs code.+ */+import { readdirSync, readFileSync, statSync } from 'node:fs'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { z } from 'zod'+import { ENGINES } from '../engines/types.js'+import { DSH_ID_RE } from './manifest.js'++declare const __DSH_REGISTRY__: string | undefined++export const DshRegistryEntrySchema = z.strictObject({+ id: z.string().regex(DSH_ID_RE),+ name: z.string().min(1).max(40),+ description: z.string().max(300).optional(),+ repo: z.string().min(1).max(2048),+ ref: z.string().min(1).max(200).optional(),+ engine: z.enum(ENGINES),+ tier: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional(),+ verified: z.boolean().optional(),+})++export type DshRegistryEntry = z.infer<typeof DshRegistryEntrySchema>++function parseEntries(values: unknown[]): DshRegistryEntry[] {+ const entries: DshRegistryEntry[] = []+ for (const value of values) {+ const parsed = DshRegistryEntrySchema.safeParse(value)+ if (parsed.success) entries.push(parsed.data)+ }+ return entries.sort((a, b) => a.id.localeCompare(b.id))+}++/** Read `dsh/registry/**\/*.json` from a checkout; used by the build and by the dev fallback. */+export function readRegistryDir(dir: string): unknown[] {+ const out: unknown[] = []+ let owners: string[]+ try {+ owners = readdirSync(dir)+ } catch {+ return out+ }+ for (const owner of owners) {+ const ownerDir = join(dir, owner)+ let files: string[]+ try {+ if (!statSync(ownerDir).isDirectory()) continue+ files = readdirSync(ownerDir)+ } catch {+ continue+ }+ for (const file of files) {+ if (!file.endsWith('.json')) continue+ try {+ out.push(JSON.parse(readFileSync(join(ownerDir, file), 'utf8')))+ } catch {+ // A malformed entry is a registry bug, not a runtime one; the conformance check catches it.+ }+ }+ }+ return out+}++let cached: DshRegistryEntry[] | null = null++export function bundledDshRegistry(): DshRegistryEntry[] {+ if (cached) return cached+ if (typeof __DSH_REGISTRY__ !== 'undefined') {+ try {+ cached = parseEntries(JSON.parse(__DSH_REGISTRY__) as unknown[])+ return cached+ } catch {+ cached = []+ return cached+ }+ }+ // src/dsh/registry.ts → ../../../dsh/registry (the same relative walk from dist/dsh/registry.js).+ const dir = fileURLToPath(new URL('../../../dsh/registry', import.meta.url))+ cached = parseEntries(readRegistryDir(dir))+ return cached+}++export function registryEntry(id: string): DshRegistryEntry | undefined {+ return bundledDshRegistry().find((entry) => entry.id === id)+}++/** Test seam. */+export function resetBundledDshRegistry(): void {+ cached = null+}diff --git a/cli/src/dsh/shell.ts b/cli/src/dsh/shell.tsnew file mode 100644index 000000000..82d32f634--- /dev/null+++ b/cli/src/dsh/shell.ts@@ -0,0 +1,121 @@+/**+ * Run a DSH's own commands — setup, doctor, workspace init, the viewer — the way the user's terminal+ * would: through their interactive shell, so `uv`, `npm`, `node` and `kicad-cli` resolve from the+ * PATH their rc files build, not from the detached daemon's. This is the same reasoning (and the+ * same shell selection) `engineLaunch.ts` uses to exec an engine in a pane.+ */+import { spawn, type ChildProcess } from 'node:child_process'+import { interactiveEngineShell } from '../lib/engineLaunch.js'++export interface DshCommandOptions {+ cwd: string+ env?: Record<string, string>+ /** Each line of combined stdout+stderr, as it arrives. */+ onLine?: (line: string) => void+ timeoutMs?: number+}++export interface DshCommandResult {+ code: number | null+ signal: NodeJS.Signals | null+ lines: string[]+ timedOut: boolean+}++/**+ * What the shell itself says about being interactive without a terminal — not the DSH's output.+ * `zsh -lic` with no tty cannot enable the line editor, and an rc file that sets `zle` makes zsh+ * complain once per option; the engine never sees this because its pane HAS a tty. Dropped so a+ * doctor's lines, which the desktop shows verbatim, are the doctor's.+ */+export function isShellNoise(line: string): boolean {+ return /can't change option: zle$/.test(line) || /^\(eval\):\d+: can't change option: zle$/.test(line)+}++/** `[path, ...args]` that runs `script` through the user's shell, or `/bin/sh -c` when none is known. */+export function dshShellArgv(script: string): { path: string; args: string[] } {+ const shell = interactiveEngineShell()+ if (shell) return { path: shell.path, args: [...shell.args, script] }+ return { path: '/bin/sh', args: ['-c', script] }+}++export function spawnDshCommand(script: string, opts: { cwd: string; env?: Record<string, string> }): ChildProcess {+ const { path, args } = dshShellArgv(script)+ return spawn(path, args, {+ cwd: opts.cwd,+ env: { ...process.env, ...(opts.env ?? {}) },+ stdio: ['ignore', 'pipe', 'pipe'],+ // Its own process group, so stopping it stops what it started (`sh -c node …`).+ detached: true,+ })+}++/** Run to completion, collecting output lines. Never rejects: a spawn failure is a non-zero exit. */+export function runDshCommand(script: string, opts: DshCommandOptions): Promise<DshCommandResult> {+ return new Promise((resolve) => {+ const lines: string[] = []+ let timedOut = false+ let settled = false+ let child: ChildProcess+ try {+ child = spawnDshCommand(script, { cwd: opts.cwd, env: opts.env })+ } catch (error) {+ const line = `could not start: ${error instanceof Error ? error.message : String(error)}`+ opts.onLine?.(line)+ resolve({ code: 127, signal: null, lines: [line], timedOut: false })+ return+ }+ const feed = (chunk: Buffer, carry: { rest: string }): void => {+ carry.rest += chunk.toString('utf8')+ let at: number+ while ((at = carry.rest.indexOf('\n')) >= 0) {+ const line = carry.rest.slice(0, at).replace(/\r$/, '')+ carry.rest = carry.rest.slice(at + 1)+ if (isShellNoise(line)) continue+ lines.push(line)+ opts.onLine?.(line)+ }+ }+ const out = { rest: '' }+ const err = { rest: '' }+ child.stdout?.on('data', (chunk: Buffer) => feed(chunk, out))+ child.stderr?.on('data', (chunk: Buffer) => feed(chunk, err))+ const finish = (code: number | null, signal: NodeJS.Signals | null): void => {+ if (settled) return+ settled = true+ if (timer) clearTimeout(timer)+ for (const carry of [out, err]) {+ if (carry.rest) { lines.push(carry.rest); opts.onLine?.(carry.rest) }+ }+ resolve({ code, signal, lines, timedOut })+ }+ const timer = opts.timeoutMs+ ? setTimeout(() => {+ timedOut = true+ killProcessGroup(child)+ }, opts.timeoutMs)+ : null+ timer?.unref?.()+ child.on('error', (error) => {+ const line = `could not start: ${error.message}`+ lines.push(line)+ opts.onLine?.(line)+ finish(127, null)+ })+ child.on('exit', (code, signal) => finish(code, signal))+ })+}++/** SIGTERM the child's whole group, then SIGKILL what is left a moment later. */+export function killProcessGroup(child: ChildProcess, graceMs = 3_000): void {+ const pid = child.pid+ if (!pid) return+ const signalGroup = (signal: NodeJS.Signals): void => {+ try { process.kill(-pid, signal) } catch { /* already gone */ }+ try { process.kill(pid, signal) } catch { /* already gone */ }+ }+ signalGroup('SIGTERM')+ const timer = setTimeout(() => signalGroup('SIGKILL'), graceMs)+ timer.unref?.()+ child.once('exit', () => clearTimeout(timer))+}diff --git a/cli/src/dsh/verdict.spec.ts b/cli/src/dsh/verdict.spec.tsnew file mode 100644index 000000000..f21634fa8--- /dev/null+++ b/cli/src/dsh/verdict.spec.ts@@ -0,0 +1,85 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { mkdtempSync, rmSync, writeFileSync, mkdirSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { DshVerdictWatcher, parseVerdict, type DshVerdict } from './verdict.js'++describe('parseVerdict', () => {+ it('reduces a spec-1 verdict to the wire shape', () => {+ const verdict = parseVerdict(JSON.stringify({+ spec: 1,+ ready: false,+ summary: ' 2 errors, 1 warning ',+ findings: [+ { severity: 'error', kind: 'a', message: 'x' },+ { severity: 'error', kind: 'b', message: 'y', ref: 'U3.pin7' },+ { severity: 'warning', message: 'z' },+ { severity: 'info', message: 'fyi' },+ null,+ ],+ artifact: 'boards/main.board.json',+ updatedAt: '2026-09-14T20:00:00Z',+ extra: 'ignored',+ }))+ expect(verdict).toEqual<DshVerdict>({+ ready: false,+ summary: '2 errors, 1 warning',+ errors: 2,+ warnings: 1,+ artifact: 'boards/main.board.json',+ updatedAt: '2026-09-14T20:00:00Z',+ })+ })++ it('refuses what is not a verdict, and scrubs an artifact that leaves the workspace', () => {+ expect(parseVerdict('nope')).toBeNull()+ expect(parseVerdict('[]')).toBeNull()+ expect(parseVerdict(JSON.stringify({ spec: 2, ready: true }))).toBeNull()+ expect(parseVerdict(JSON.stringify({ spec: 1, ready: 'yes' }))).toBeNull()+ expect(parseVerdict(JSON.stringify({ spec: 1, ready: true, artifact: '../x.step' }))?.artifact).toBeNull()+ expect(parseVerdict(JSON.stringify({ spec: 1, ready: true, artifact: '/abs.step' }))?.artifact).toBeNull()+ expect(parseVerdict(JSON.stringify({ spec: 1, ready: true, updatedAt: 'yesterday' }))?.updatedAt).toBeNull()+ })+})++describe('DshVerdictWatcher', () => {+ let workspace: string+ let watcher: DshVerdictWatcher | null = null+ beforeEach(() => { workspace = mkdtempSync(join(tmpdir(), 'dsh-verdict-')) })+ afterEach(async () => {+ await watcher?.stop()+ watcher = null+ rmSync(workspace, { recursive: true, force: true })+ })++ it('publishes the existing verdict at watch time and each change after it', async () => {+ const file = join(workspace, '.harness', 'verdict.json')+ mkdirSync(join(workspace, '.harness'), { recursive: true })+ writeFileSync(file, JSON.stringify({ spec: 1, ready: false, summary: 'first' }))+ const seen: Array<DshVerdict | null> = []+ let resolveNext: (() => void) | null = null+ watcher = new DshVerdictWatcher({ onChange: (_agentId, verdict) => { seen.push(verdict); resolveNext?.() } })+ watcher.watch('agent-1', file)+ expect(seen).toHaveLength(1)+ expect(seen[0]?.summary).toBe('first')+ expect(watcher.current('agent-1')?.summary).toBe('first')++ const next = new Promise<void>((resolve) => { resolveNext = resolve })+ // Give chokidar a moment to be ready before the write it must notice.+ await new Promise((resolve) => setTimeout(resolve, 300))+ writeFileSync(file, JSON.stringify({ spec: 1, ready: true, summary: 'second' }))+ await Promise.race([next, new Promise((resolve) => setTimeout(resolve, 4_000))])+ expect(seen.at(-1)?.summary).toBe('second')+ expect(seen.at(-1)?.ready).toBe(true)+ }, 10_000)++ it('creates the directory it watches, so a first verdict lands in a watched place', () => {+ const file = join(workspace, 'nested', '.harness', 'verdict.json')+ watcher = new DshVerdictWatcher({ onChange: () => undefined })+ watcher.watch('agent-2', file)+ const { existsSync } = require('node:fs') as typeof import('node:fs')+ expect(existsSync(join(workspace, 'nested', '.harness'))).toBe(true)+ expect(watcher.current('agent-2')).toBeNull()+ watcher.unwatch('agent-2')+ })+})diff --git a/cli/src/dsh/verdict.ts b/cli/src/dsh/verdict.tsnew file mode 100644index 000000000..1d488e129--- /dev/null+++ b/cli/src/dsh/verdict.ts@@ -0,0 +1,155 @@+/**+ * `.harness/verdict.json` — the one file a DSH's own scripts write and Harness reads back.+ *+ * Spec 1 (`dsh/spec/schema/verdict.schema.json`): `ready` is the one machine fact, `findings` carry+ * a closed severity and an open kind, `artifact` names the primary thing to view. The daemon reduces+ * it to what the pane header needs (ready, a summary, two counts) and hands `artifact` to the viewer.+ *+ * Watched per agent through the `.harness` directory rather than the file, because a writer that+ * truncates-then-writes, or renames into place, looks different to the two watch strategies and the+ * directory sees both.+ */+import chokidar, { type FSWatcher } from 'chokidar'+import { existsSync, mkdirSync, readFileSync } from 'node:fs'+import { basename, dirname } from 'node:path'++export interface DshVerdict {+ ready: boolean+ summary: string | null+ errors: number+ warnings: number+ artifact: string | null+ updatedAt: string | null+}++function cleanRelative(value: unknown): string | null {+ if (typeof value !== 'string' || !value || value.length > 1024) return null+ if (value.startsWith('/') || value.split(/[\\/]/).some((segment) => segment === '..')) return null+ return value+}++/** Reduce a verdict file to the wire shape; null when it is not a spec-1 verdict. */+export function parseVerdict(text: string): DshVerdict | null {+ let value: unknown+ try {+ value = JSON.parse(text)+ } catch {+ return null+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null+ const raw = value as Record<string, unknown>+ if (raw.spec !== 1 || typeof raw.ready !== 'boolean') return null+ let errors = 0+ let warnings = 0+ if (Array.isArray(raw.findings)) {+ for (const finding of raw.findings) {+ const severity = (finding as { severity?: unknown } | null)?.severity+ if (severity === 'error') errors+++ else if (severity === 'warning') warnings+++ }+ }+ const summary = typeof raw.summary === 'string' && raw.summary.trim()+ ? raw.summary.trim().slice(0, 200)+ : null+ const updatedAt = typeof raw.updatedAt === 'string' && !Number.isNaN(Date.parse(raw.updatedAt))+ ? raw.updatedAt+ : null+ return { ready: raw.ready, summary, errors, warnings, artifact: cleanRelative(raw.artifact), updatedAt }+}++export function readVerdictFile(file: string): DshVerdict | null {+ try {+ return parseVerdict(readFileSync(file, 'utf8'))+ } catch {+ return null+ }+}++const DEBOUNCE_MS = 150++interface Watched {+ file: string+ watcher: FSWatcher+ timer: NodeJS.Timeout | null+ last: string | null+}++export interface DshVerdictWatcherDeps {+ /** The verdict changed (or went away → null). */+ onChange: (agentId: string, verdict: DshVerdict | null) => void+ log?: (line: string) => void+}++export class DshVerdictWatcher {+ private readonly watched = new Map<string, Watched>()++ constructor(private readonly deps: DshVerdictWatcherDeps) {}++ /** Idempotent: watching the same file again is a no-op; a different file replaces the watch. */+ watch(agentId: string, file: string): void {+ const current = this.watched.get(agentId)+ if (current?.file === file) return+ if (current) this.unwatch(agentId)+ const dir = dirname(file)+ try {+ mkdirSync(dir, { recursive: true })+ } catch (error) {+ this.deps.log?.(`[dsh] verdict dir ${dir} could not be created · ${error instanceof Error ? error.message : error}`)+ return+ }+ const name = basename(file)+ const watcher = chokidar.watch(dir, { ignoreInitial: true, depth: 0, persistent: true })+ const entry: Watched = { file, watcher, timer: null, last: null }+ const schedule = (): void => {+ if (entry.timer) clearTimeout(entry.timer)+ entry.timer = setTimeout(() => {+ entry.timer = null+ this.publish(agentId, entry)+ }, DEBOUNCE_MS)+ entry.timer.unref?.()+ }+ const relevant = (path: string): boolean => basename(path) === name+ watcher+ .on('add', (path: string) => { if (relevant(path)) schedule() })+ .on('change', (path: string) => { if (relevant(path)) schedule() })+ .on('unlink', (path: string) => { if (relevant(path)) schedule() })+ .on('error', (error: unknown) => this.deps.log?.(`[dsh] verdict watch error · ${error instanceof Error ? error.message : error}`))+ this.watched.set(agentId, entry)+ // What is already there counts: a restored agent's last verdict is still its verdict.+ if (existsSync(file)) this.publish(agentId, entry)+ }++ private publish(agentId: string, entry: Watched): void {+ let text: string | null+ try {+ text = readFileSync(entry.file, 'utf8')+ } catch {+ text = null+ }+ if (text === entry.last) return+ entry.last = text+ this.deps.onChange(agentId, text === null ? null : parseVerdict(text))+ }++ current(agentId: string): DshVerdict | null {+ const entry = this.watched.get(agentId)+ return entry?.last ? parseVerdict(entry.last) : null+ }++ unwatch(agentId: string): void {+ const entry = this.watched.get(agentId)+ if (!entry) return+ this.watched.delete(agentId)+ if (entry.timer) clearTimeout(entry.timer)+ void entry.watcher.close()+ }++ async stop(): Promise<void> {+ const entries = [...this.watched.values()]+ this.watched.clear()+ await Promise.all(entries.map((entry) => {+ if (entry.timer) clearTimeout(entry.timer)+ return entry.watcher.close()+ }))+ }+}diff --git a/cli/src/dsh/viewer.spec.ts b/cli/src/dsh/viewer.spec.tsnew file mode 100644index 000000000..71d0b2abe--- /dev/null+++ b/cli/src/dsh/viewer.spec.ts@@ -0,0 +1,122 @@+import { afterEach, describe, expect, it } from 'vitest'+import { EventEmitter } from 'node:events'+import type { ChildProcess } from 'node:child_process'+import type { InstalledDsh } from './installed.js'+import { DshViewerManager, buildViewerUrl } from './viewer.js'++function fakeChild(): ChildProcess & { exitWith: (code: number) => void } {+ const child = new EventEmitter() as ChildProcess & { exitWith: (code: number) => void }+ Object.assign(child, {+ // No pid: killProcessGroup returns early instead of signalling a real process group.+ pid: undefined,+ stdout: new EventEmitter(),+ stderr: new EventEmitter(),+ exitWith: (code: number) => child.emit('exit', code, null),+ })+ return child+}++function dsh(viewer: NonNullable<InstalledDsh['manifest']['viewer']>): InstalledDsh {+ return {+ id: 'acme/thing', dir: '/i/acme/thing', realDir: '/i/acme/thing', source: '', ref: null, commit: null,+ linked: false, installedAt: 0,+ manifest: { spec: 1, id: 'acme/thing', name: 'Thing', engine: 'claude', viewer },+ }+}++describe('buildViewerUrl', () => {+ it('fills the port and url-encodes the artifact per segment', () => {+ expect(buildViewerUrl('http://127.0.0.1:${port}/?file=${artifact}', 4790, 'models/my part.step'))+ .toBe('http://127.0.0.1:4790/?file=models/my%20part.step')+ expect(buildViewerUrl('http://127.0.0.1:${port}/', 4790, null)).toBe('http://127.0.0.1:4790/')+ expect(buildViewerUrl('http://127.0.0.1:${port}/?file=${artifact}', 1, null)).toBe('http://127.0.0.1:1/?file=')+ })+})++describe('DshViewerManager', () => {+ let manager: DshViewerManager | null = null+ afterEach(async () => { await manager?.stopAll(); manager = null })++ function setup(opts: { portUp?: boolean; now?: () => number } = {}) {+ const spawned: Array<{ child: ReturnType<typeof fakeChild>; env: Record<string, string>; cwd: string }> = []+ const urls: Array<string | null> = []+ manager = new DshViewerManager({+ onUrl: (_agentId, url) => urls.push(url),+ freePort: async () => 4790 + spawned.length,+ waitForPort: async () => opts.portUp ?? true,+ spawn: ((_script: string, o: { cwd: string; env?: Record<string, string> }) => {+ const child = fakeChild()+ spawned.push({ child, env: o.env ?? {}, cwd: o.cwd })+ return child+ }) as typeof import('./shell.js').spawnDshCommand,+ now: opts.now,+ })+ return { spawned, urls }+ }++ it('publishes a URL once the port answers, with the env the contract promises', async () => {+ const { spawned, urls } = setup()+ await manager!.start('a1', dsh({ command: 'toolchain/viewer.sh', url: 'http://127.0.0.1:${port}/' }), '/ws')+ expect(spawned).toHaveLength(1)+ expect(spawned[0].cwd).toBe('/i/acme/thing')+ expect(spawned[0].env).toMatchObject({+ HARNESS_DSH: 'acme/thing', HARNESS_DSH_DIR: '/i/acme/thing', HARNESS_WORKSPACE: '/ws', HARNESS_VIEWER_PORT: '4790',+ })+ expect(urls).toEqual(['http://127.0.0.1:4790/'])+ expect(manager!.url('a1')).toBe('http://127.0.0.1:4790/')+ })++ it('is idempotent for the same agent, DSH and workspace', async () => {+ const { spawned } = setup()+ const d = dsh({ command: 'v', url: 'http://127.0.0.1:${port}/' })+ await manager!.start('a1', d, '/ws')+ await manager!.start('a1', d, '/ws')+ expect(spawned).toHaveLength(1)+ })++ it('republishes when the verdict names an artifact, and only when the URL changes', async () => {+ const { urls } = setup()+ await manager!.start('a1', dsh({ command: 'v', url: 'http://127.0.0.1:${port}/?file=${artifact}' }), '/ws')+ manager!.setVerdictArtifact('a1', 'models/a.step')+ manager!.setVerdictArtifact('a1', 'models/a.step')+ manager!.setVerdictArtifact('a1', null)+ expect(urls).toEqual([+ 'http://127.0.0.1:4790/?file=',+ 'http://127.0.0.1:4790/?file=models/a.step',+ 'http://127.0.0.1:4790/?file=',+ ])+ })++ it('publishes null when the port never answers, and stops the child', async () => {+ const { urls } = setup({ portUp: false })+ await manager!.start('a1', dsh({ command: 'v', url: 'http://127.0.0.1:${port}/' }), '/ws')+ expect(urls).toEqual([])+ expect(manager!.url('a1')).toBeNull()+ })++ it('restarts a viewer that exits, then gives up after four exits in a minute', async () => {+ let clock = 0+ const { spawned, urls } = setup({ now: () => clock })+ await manager!.start('a1', dsh({ command: 'v', url: 'http://127.0.0.1:${port}/' }), '/ws')+ expect(urls).toEqual(['http://127.0.0.1:4790/'])+ spawned[0].child.exitWith(1)+ expect(urls.at(-1)).toBeNull()+ // The restart is scheduled with a real timer (1s); the fourth exit inside the window gives up.+ for (let i = 0; i < 3; i++) {+ await new Promise((resolve) => setTimeout(resolve, 1_100 * 2 ** i))+ expect(spawned).toHaveLength(i + 2)+ clock += 1_000+ spawned[i + 1].child.exitWith(1)+ }+ await new Promise((resolve) => setTimeout(resolve, 200))+ expect(spawned).toHaveLength(4)+ }, 15_000)++ it('stops publish null and forgets the agent', async () => {+ const { urls } = setup()+ await manager!.start('a1', dsh({ command: 'v', url: 'http://127.0.0.1:${port}/' }), '/ws')+ await manager!.stop('a1')+ expect(urls.at(-1)).toBeNull()+ expect(manager!.url('a1')).toBeNull()+ })+})diff --git a/cli/src/dsh/viewer.ts b/cli/src/dsh/viewer.tsnew file mode 100644index 000000000..7eddc30e9--- /dev/null+++ b/cli/src/dsh/viewer.ts@@ -0,0 +1,255 @@+/**+ * One viewer server per DSH agent, owned by the daemon the way a terminal stream is: started when+ * the agent is, torn down with it, restarted a bounded number of times if it dies.+ *+ * The daemon picks a free loopback port and hands it to the manifest's `viewer.command` as+ * `HARNESS_VIEWER_PORT`, then waits for something to listen there before it publishes a URL — a+ * pane that navigates to a port nobody serves yet renders a connection error and never recovers.+ *+ * The URL is a template: `${port}` and `${artifact}`. The artifact is the verdict's `artifact` when+ * it names one, else the newest file under the workspace with one of `viewer.artifactExtensions`+ * (rescanned when such a file changes). Either change republishes the URL, which is how the 3D pane+ * follows the newest STEP without the DSH knowing Harness exists.+ */+import chokidar, { type FSWatcher } from 'chokidar'+import type { ChildProcess } from 'node:child_process'+import { createServer, connect } from 'node:net'+import { isCandidateArtifact, isArtifactDirIgnored, newestArtifact } from './artifacts.js'+import type { InstalledDsh } from './installed.js'+import { killProcessGroup, spawnDshCommand } from './shell.js'++export interface DshViewerDeps {+ /** The URL clients should show for this agent's viewer, or null when there is none right now. */+ onUrl: (agentId: string, url: string | null) => void+ log?: (line: string) => void+ /** Test seams. */+ freePort?: () => Promise<number>+ waitForPort?: (port: number, timeoutMs: number) => Promise<boolean>+ spawn?: typeof spawnDshCommand+ now?: () => number+}++interface ViewerState {+ agentId: string+ dsh: InstalledDsh+ workspace: string+ port: number | null+ child: ChildProcess | null+ url: string | null+ verdictArtifact: string | null+ scannedArtifact: string | null+ watcher: FSWatcher | null+ rescanTimer: NodeJS.Timeout | null+ stopping: boolean+ /** Exit timestamps inside the restart window — three in a minute and we give up. */+ exits: number[]+ generation: number+}++const PORT_TIMEOUT_MS = 60_000+const RESTART_WINDOW_MS = 60_000+const RESTART_LIMIT = 3+const RESCAN_DEBOUNCE_MS = 300+const LOG_LINE_LIMIT = 40++export async function freeLoopbackPort(): Promise<number> {+ return new Promise((resolve, reject) => {+ const server = createServer()+ server.unref()+ server.on('error', reject)+ server.listen(0, '127.0.0.1', () => {+ const address = server.address()+ const port = typeof address === 'object' && address ? address.port : 0+ server.close(() => (port ? resolve(port) : reject(new Error('no port'))))+ })+ })+}++export function waitForLoopbackPort(port: number, timeoutMs: number): Promise<boolean> {+ const deadline = Date.now() + timeoutMs+ return new Promise((resolve) => {+ const attempt = (): void => {+ const socket = connect({ port, host: '127.0.0.1' })+ socket.setTimeout(1_000)+ const done = (ok: boolean): void => {+ socket.destroy()+ if (ok) { resolve(true); return }+ if (Date.now() >= deadline) { resolve(false); return }+ const timer = setTimeout(attempt, 250)+ timer.unref?.()+ }+ socket.once('connect', () => done(true))+ socket.once('error', () => done(false))+ socket.once('timeout', () => done(false))+ }+ attempt()+ })+}++/** The template with its two variables filled; the artifact is url-encoded per path segment. */+export function buildViewerUrl(template: string, port: number, artifact: string | null): string {+ const encoded = artifact ? artifact.split('/').map(encodeURIComponent).join('/') : ''+ return template.replace(/\$\{port\}/g, String(port)).replace(/\$\{artifact\}/g, encoded)+}++export class DshViewerManager {+ private readonly states = new Map<string, ViewerState>()++ constructor(private readonly deps: DshViewerDeps) {}++ private log(line: string): void {+ this.deps.log?.(line)+ }++ url(agentId: string): string | null {+ return this.states.get(agentId)?.url ?? null+ }++ /** Idempotent: the same agent, DSH and workspace keep their running viewer. */+ async start(agentId: string, dsh: InstalledDsh, workspace: string): Promise<void> {+ const viewer = dsh.manifest.viewer+ if (!viewer) return+ const current = this.states.get(agentId)+ if (current && current.dsh.realDir === dsh.realDir && current.workspace === workspace && !current.stopping) return+ if (current) await this.stop(agentId)+ const state: ViewerState = {+ agentId, dsh, workspace, port: null, child: null, url: null,+ verdictArtifact: null, scannedArtifact: null, watcher: null, rescanTimer: null,+ stopping: false, exits: [], generation: 0,+ }+ this.states.set(agentId, state)+ if (viewer.artifactExtensions?.length) {+ state.scannedArtifact = newestArtifact(workspace, viewer.artifactExtensions)?.path ?? null+ this.watchArtifacts(state, viewer.artifactExtensions)+ }+ await this.launch(state)+ }++ /** The verdict named (or stopped naming) an artifact. */+ setVerdictArtifact(agentId: string, artifact: string | null): void {+ const state = this.states.get(agentId)+ if (!state || state.verdictArtifact === artifact) return+ state.verdictArtifact = artifact+ this.publish(state)+ }++ private effectiveArtifact(state: ViewerState): string | null {+ return state.verdictArtifact ?? state.scannedArtifact+ }++ private publish(state: ViewerState): void {+ const viewer = state.dsh.manifest.viewer+ const url = viewer && state.port !== null && state.child+ ? buildViewerUrl(viewer.url, state.port, this.effectiveArtifact(state))+ : null+ if (url === state.url) return+ state.url = url+ this.deps.onUrl(state.agentId, url)+ }++ private watchArtifacts(state: ViewerState, extensions: readonly string[]): void {+ const watcher = chokidar.watch(state.workspace, {+ ignoreInitial: true,+ persistent: true,+ depth: 6,+ ignored: (path: string) => path !== state.workspace+ && path.slice(state.workspace.length).split(/[\\/]/).some((segment) => segment && (isArtifactDirIgnored(segment) || segment.startsWith('.'))),+ })+ const bump = (path: string): void => {+ if (!isCandidateArtifact(path, extensions)) return+ if (state.rescanTimer) clearTimeout(state.rescanTimer)+ state.rescanTimer = setTimeout(() => {+ state.rescanTimer = null+ const next = newestArtifact(state.workspace, extensions)?.path ?? null+ if (next === state.scannedArtifact) return+ state.scannedArtifact = next+ this.publish(state)+ }, RESCAN_DEBOUNCE_MS)+ state.rescanTimer.unref?.()+ }+ watcher.on('add', bump).on('change', bump).on('unlink', bump)+ .on('error', (error: unknown) => this.log(`[dsh] artifact watch error · ${error instanceof Error ? error.message : error}`))+ state.watcher = watcher+ }++ private async launch(state: ViewerState): Promise<void> {+ const viewer = state.dsh.manifest.viewer!+ const generation = ++state.generation+ let port: number+ try {+ port = await (this.deps.freePort ?? freeLoopbackPort)()+ } catch (error) {+ this.log(`[dsh] ${state.dsh.id} viewer: no free port · ${error instanceof Error ? error.message : error}`)+ return+ }+ if (state.stopping || state.generation !== generation) return+ state.port = port+ const child = (this.deps.spawn ?? spawnDshCommand)(viewer.command, {+ cwd: state.dsh.realDir,+ env: {+ HARNESS_DSH: state.dsh.id,+ HARNESS_DSH_DIR: state.dsh.realDir,+ HARNESS_WORKSPACE: state.workspace,+ HARNESS_VIEWER_PORT: String(port),+ },+ })+ state.child = child+ let logged = 0+ const onData = (chunk: Buffer): void => {+ for (const line of chunk.toString('utf8').split('\n')) {+ if (!line.trim()) continue+ if (logged++ < LOG_LINE_LIMIT) this.log(`[dsh] ${state.dsh.id} viewer · ${line}`)+ }+ }+ child.stdout?.on('data', onData)+ child.stderr?.on('data', onData)+ child.on('error', (error) => this.log(`[dsh] ${state.dsh.id} viewer could not start · ${error.message}`))+ child.on('exit', (code, signal) => {+ if (state.child !== child) return+ state.child = null+ state.port = null+ this.publish(state)+ if (state.stopping) return+ const now = (this.deps.now ?? Date.now)()+ state.exits = [...state.exits.filter((at) => now - at < RESTART_WINDOW_MS), now]+ if (state.exits.length > RESTART_LIMIT) {+ this.log(`[dsh] ${state.dsh.id} viewer exited ${code ?? signal} ${RESTART_LIMIT + 1} times in a minute · giving up`)+ return+ }+ const delay = 1_000 * 2 ** (state.exits.length - 1)+ this.log(`[dsh] ${state.dsh.id} viewer exited ${code ?? signal} · restarting in ${delay}ms`)+ const timer = setTimeout(() => { void this.launch(state) }, delay)+ timer.unref?.()+ })+ const up = await (this.deps.waitForPort ?? waitForLoopbackPort)(port, PORT_TIMEOUT_MS)+ if (state.child !== child || state.stopping) return+ if (!up) {+ this.log(`[dsh] ${state.dsh.id} viewer did not listen on ${port} within ${PORT_TIMEOUT_MS / 1000}s`)+ killProcessGroup(child)+ return+ }+ this.log(`[dsh] ${state.dsh.id} viewer up on 127.0.0.1:${port} for ${state.workspace}`)+ this.publish(state)+ }++ async stop(agentId: string): Promise<void> {+ const state = this.states.get(agentId)+ if (!state) return+ state.stopping = true+ this.states.delete(agentId)+ if (state.rescanTimer) clearTimeout(state.rescanTimer)+ if (state.watcher) await state.watcher.close().catch(() => undefined)+ const child = state.child+ state.child = null+ state.port = null+ if (child) killProcessGroup(child)+ if (state.url !== null) {+ state.url = null+ this.deps.onUrl(agentId, null)+ }+ }++ async stopAll(): Promise<void> {+ await Promise.all([...this.states.keys()].map((agentId) => this.stop(agentId)))+ }+}diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex fd409e35c..8e2e6f12f 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -22,6 +22,7 @@ import { stat } from 'node:fs/promises'import { agentProject, type AgentProject } from './agentProject.js'import type { GridAssignment } from './gridAssignment.js'import { projectDisplayName, type RegisteredSession } from './registry.js'+import type { DshVerdict } from '../dsh/verdict.js'/*** One agent as it travels to every client.@@ -45,6 +46,21 @@ export type AgentFrame = {grid: GridAssignment | nullcodexHome: string | nullproject: AgentProject | null+ /** The domain-specific harness this agent was created as, or null for a plain engine. */+ dsh: string | null+ /** Its display name from the installed manifest; null when unknown here (not installed, plain engine). */+ dshName: string | null+ /** Where this agent's viewer is being served right now, or null when it has none up. */+ viewerUrl: string | null+ /** The DSH's last verdict for this workspace, reduced for the pane header; null when none yet. */+ verdict: DshVerdict | null+}++/** What the daemon knows about an agent's DSH — looked up by the caller, never here. */+export interface AgentDshContext {+ name: string | null+ viewerUrl: string | null+ verdict: DshVerdict | null}/** What the caller knows and this module deliberately does not look up for itself. */@@ -53,6 +69,8 @@ export interface AgentFrameContext {selectedModel: string | null/** `registry.terminalAvailable(agentId)` — the caller already holds the registry. */terminalAvailable: boolean+ /** The DSH companions' state for this agent; absent when the caller has none to give. */+ dsh?: AgentDshContext | null}/**@@ -64,7 +82,7 @@ export interface AgentFrameContext {*/export async function agentFrame(s: RegisteredSession,- { selectedModel, terminalAvailable }: AgentFrameContext,+ { selectedModel, terminalAvailable, dsh }: AgentFrameContext,): Promise<AgentFrame> {const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : nullreturn {@@ -90,5 +108,11 @@ export async function agentFrame(// `grid: null` is above.codexHome: s.codexHome ?? null,project: await agentProject(s.cwd),+ // All four are real answers when null, for the reason the module doc gives: a frame that omits+ // them would erase a viewer URL or a verdict an earlier frame had reported.+ dsh: s.dsh ?? null,+ dshName: dsh?.name ?? null,+ viewerUrl: dsh?.viewerUrl ?? null,+ verdict: dsh?.verdict ?? null,}}diff --git a/cli/src/lib/createAgentPane.ts b/cli/src/lib/createAgentPane.tsindex 9d63830cc..cf7551fa0 100644--- a/cli/src/lib/createAgentPane.ts+++ b/cli/src/lib/createAgentPane.ts@@ -31,6 +31,7 @@ export interface CreateAgentPaneDeps {grid?: { baseUrl: string; model: string | null } | nullgridLaunch?: GridLaunchOverride | nullcodexHome?: string | null+ dsh?: string | nullbypassPermission?: boolean}) => RegisteredSession | null }engine: AgentEngine@@ -45,6 +46,8 @@ export interface CreateAgentPaneDeps {gridLaunch?: GridLaunchOverride | null/** The CODEX_HOME folder this agent was launched against, if the caller chose one; codex only. */codexHome?: string | null+ /** The domain-specific harness this agent is created as, if any. */+ dsh?: string | nullmaxAttempts?: number}@@ -78,6 +81,7 @@ export async function createAndRegisterPane(deps: CreateAgentPaneDeps): Promise<grid: deps.grid,gridLaunch: deps.gridLaunch,codexHome: deps.codexHome,+ dsh: deps.dsh,bypassPermission: deps.bypassPermission,})if (pending) return { ok: true, spawned, pending }diff --git a/cli/src/lib/launchOverrides.ts b/cli/src/lib/launchOverrides.tsindex e9544e6a6..f6827842c 100644--- a/cli/src/lib/launchOverrides.ts+++ b/cli/src/lib/launchOverrides.ts@@ -21,6 +21,7 @@ import {type GridLaunchOverride,} from './gridLaunch.js'import { TMUX_SESSION_ENV_MIN } from './tmuxVersion.js'+import type { DshLaunch } from '../dsh/launch.js'export interface LaunchOverrides {/** Layered over the pane's inherited environment. The grid key lives here, and only here. */@@ -47,12 +48,19 @@ export interface LaunchOverridesDeps {/** Install the daemon's hooks into a non-default Codex profile. The caller decides whether hook* installation is enabled at all. */installCodexHooks: (codexHome: string) => void+ /** What a DSH adds to the launch (its env and argv), or null when it is not installed here any+ * more — in which case the agent relaunches as its plain base engine and says so in the log. */+ dshLaunch?: (dsh: string, workspace: string) => DshLaunch | null}/** Where the agent should come back: the registry row, or an override the desktop just sent. */export interface LaunchSource {gridLaunch?: GridLaunchOverride | nullcodexHome?: string | null+ /** The DSH the agent was created as; its env rides on every relaunch (`HARNESS_DSH` included). */+ dsh?: string | null+ /** The workspace, for the DSH's `${workspace}` — the registry row's `cwd`. */+ cwd?: string | null}/** Fresh each time: callers hand `env` to tmux and may extend it, and a shared object would carry@@ -98,6 +106,28 @@ export async function buildLaunchOverrides(engine: AgentEngine,source: LaunchSource,configKey: string,+): Promise<LaunchOverridesResult> {+ const base = await buildBaseLaunchOverrides(deps, engine, source, configKey)+ if (!base.ok || !source.dsh || !source.cwd) return base+ const dsh = deps.dshLaunch?.(source.dsh, source.cwd) ?? null+ if (!dsh) return base+ // The DSH's variables layer over the grid's or the profile's; `HARNESS_*` are the daemon's own and+ // a manifest cannot set them (see `dshLaunch`), so nothing here can shadow a grid credential.+ return {+ ok: true,+ overrides: {+ env: { ...base.overrides.env, ...dsh.env },+ extraArgs: [...base.overrides.extraArgs, ...dsh.args],+ clearEnv: base.overrides.clearEnv,+ },+ }+}++async function buildBaseLaunchOverrides(+ deps: LaunchOverridesDeps,+ engine: AgentEngine,+ source: LaunchSource,+ configKey: string,): Promise<LaunchOverridesResult> {const valid = await validateLaunchOverrides(deps, engine, source)if (!valid.ok) return validdiff --git a/cli/src/lib/registry.ts b/cli/src/lib/registry.tsindex 307f8e9c8..6e5417165 100644--- a/cli/src/lib/registry.ts+++ b/cli/src/lib/registry.ts@@ -13,6 +13,7 @@* Module singleton (like the ws `clients` set) — imported by routes + reaper.*/+import { DSH_ID_RE } from '../dsh/manifest.js'import {closeSync,constants,@@ -118,6 +119,14 @@ export interface RegisteredSession {* to a different grid.*/codexHome?: string | null+ /**+ * The domain-specific harness this agent was created as (`autonomous/circuit`), or null for a plain+ * engine. NOT a second engine: `engine` stays the base (`claude`, `codex`, …) and every normalizer,+ * probe and install path keys on that. Chosen at creation, carried forward, and re-read off the+ * live process's `HARNESS_DSH` by discovery so a pane the daemon did not create (or had to mint+ * again after a restart) is still labelled. Fill-only, like `codexHome`. See `src/dsh/`.+ */+ dsh?: string | null/*** Whether the engine was launched with its permission prompts bypassed (`--dangerously-skip-permissions`* and friends, `BYPASS_PERMISSION_FLAGS`). Recorded at launch because it is otherwise only readable@@ -187,6 +196,11 @@ const PANE_RE = /^%\d+$/const GROK_SESSION_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iconst AGENT_ENGINES: ReadonlySet<string> = new Set(ENGINES)+/** A persisted DSH id, or null for anything that is not one (older rows have no field at all). */+function normalizedDshId(value: unknown): string | null {+ return typeof value === 'string' && DSH_ID_RE.test(value) ? value : null+}+function normalizedAgentEngine(value: unknown): AgentEngine {return typeof value === 'string' && AGENT_ENGINES.has(value)? value as AgentEngine@@ -751,6 +765,7 @@ class Registry {gateway: raw.gateway === 'ori' ? 'ori' : null,grid: normalizedGridAssignment(raw.grid),codexHome: typeof rawCodexHome === 'string' && rawCodexHome ? rawCodexHome : null,+ dsh: normalizedDshId((raw as { dsh?: unknown }).dsh),...(rawGridLaunch !== undefined ? { gridLaunch: rawGridLaunch } : {}),...(raw.bypassPermission === true ? { bypassPermission: true } : {}),transcriptPath,@@ -845,6 +860,8 @@ class Registry {/** Codex only: the CODEX_HOME the process was launched under, read off its environment. Fills a* row that does not know its profile yet; never overwrites one that does (see `codexHome`). */codexHome?: string | null+ /** The DSH read off the process's `HARNESS_DSH`, if any. Fill-only, like `codexHome`. */+ dsh?: string | null}):{entry: RegisteredSession@@ -896,6 +913,7 @@ class Registry {if (input.gateway !== undefined) existing.gateway = input.gatewayif (input.grid !== undefined) existing.grid = input.gridif (input.codexHome && !existing.codexHome) existing.codexHome = input.codexHome+ if (input.dsh && !existing.dsh) existing.dsh = input.dshexisting.updatedAt = Date.now()this.index(existing)this.terminalAvailableAgents.add(existing.agentId)@@ -937,6 +955,7 @@ class Registry {// A discovered grid agent has no credential the daemon ever saw: it can be observed, not relaunched.gridLaunch: null,codexHome: input.codexHome ?? null,+ dsh: input.dsh ?? null,transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,cwd: input.cwd ?? null,@@ -968,6 +987,7 @@ class Registry {grid?: GridAssignment | nullgridLaunch?: GridLaunchOverride | nullcodexHome?: string | null+ dsh?: string | nullbypassPermission?: boolean}): RegisteredSession | null {if (this.writeBlocked) return null@@ -989,6 +1009,7 @@ class Registry {grid: input.grid ?? null,gridLaunch: input.gridLaunch ?? null,codexHome: input.codexHome ?? null,+ dsh: input.dsh ?? null,...(input.bypassPermission ? { bypassPermission: true } : {}),transcriptPath: null,projectDir: basename(input.cwd ?? '') || agentId,@@ -1167,6 +1188,7 @@ class Registry {// re-reads off the live process on every discovery) — a hook-triggered bind must carry it// forward or the very first SessionStart hook would silently wipe the agent's chosen profile.codexHome: existing?.codexHome ?? null,+ dsh: existing?.dsh ?? null,...(existing?.bypassPermission ? { bypassPermission: true } : {}),processIdentity: validProcessIdentity(input.processIdentity) ? input.processIdentity : existing?.processIdentity ?? null,registeredAt: existing?.registeredAt ?? now,@@ -1353,6 +1375,17 @@ class Registry {return true}+ /** Fill in the DSH a row did not know (discovery read `HARNESS_DSH` off the live process). Never+ * replaces one it already has — the harness is chosen once, at creation. */+ setDsh(agentId: string, dsh: string): boolean {+ const session = this.agents.get(agentId)+ if (!session || session.dsh || !DSH_ID_RE.test(dsh)) return false+ session.dsh = dsh+ session.updatedAt = Date.now()+ this.save()+ return true+ }+/** Record the launch an agent was last put onto a grid with (`agent_create` / `agent_retarget`), or* null once it was moved back to the engine's own login. */setGridLaunch(agentId: string, gridLaunch: GridLaunchOverride | null): boolean {diff --git a/cli/src/lib/terminalAgentDiscovery.ts b/cli/src/lib/terminalAgentDiscovery.tsindex e223c1a19..c8433784a 100644--- a/cli/src/lib/terminalAgentDiscovery.ts+++ b/cli/src/lib/terminalAgentDiscovery.ts@@ -8,6 +8,7 @@ import {import { probeGatewayRuntime } from './gatewayRuntime.js'import { probeGridAssignment, type GridAssignment } from './gridAssignment.js'import { probeCodexHome } from './codexHomeProbe.js'+import { probeDsh } from '../dsh/probe.js'import type { TerminalBackend } from './terminalBackend.js'import {ambiguousAgentProcess,@@ -58,6 +59,12 @@ export interface DiscoveredTerminalAgent {* process, and the registry keeps what it already knows. See `codexHomeProbe.ts`.*/codexHome?: string | null+ /**+ * The domain-specific harness this process was launched as, read off its `HARNESS_DSH`. null = a+ * plain engine; undefined = the probe could not read the process, and the registry keeps what it+ * already knows. See `src/dsh/probe.ts`.+ */+ dsh?: string | null}export interface TerminalTargetProbe {@@ -254,6 +261,8 @@ export async function probeTerminalAgents(agent.grid = await probeGridAssignment(agent.processIdentity, agent.engine, agent.args)// And, for Codex, the profile it runs under — a fact about the process the row cannot otherwise learn.agent.codexHome = await probeCodexHome(agent.processIdentity, agent.engine)+ // And the DSH it was created as — same read, so a pane the daemon did not create is labelled too.+ agent.dsh = await probeDsh(agent.processIdentity)}))return { processTableAvailable: true, targets, ...discovered }}