AI-native design editor. Open-source Figma alternative.
fix(harness): start Pi sessions with MCP tools under Node (#897)
Danila Poyarkov19d01f083566
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fbd2665c5..1813cf2c4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -80,6 +80,7 @@### Fixed+- Start Pi chats with OpenPencil's MCP tools when the Harness companion runs on Node 22.15 or later; the companion now installs the dependency Pi's MCP adapter needs and loads its TypeScript sources. A reopened Pi session starts fresh instead of failing to resume its in-memory sandbox, and npm output from Pi no longer mixes into the companion's protocol.- Import HTML and CSS with the right shadow and border colors. A shadow whose color follows its lengths, as CSS usually writes it, and a `border` with a color function such as `rgb(226, 232, 240)` came in black. Every layer of a `box-shadow` list now imports, `inset` ones as inner shadows, and lengths in `%`, `em`, or `vh` are no longer read as pixels.- Accept a CSS `box-shadow` list in design JSX's `shadow` prop: the color may come first, a fourth length sets the spread, several layers add several shadows, and `inset` makes an inner shadow. A color before the lengths or a spread made the shadow black.- Read `repeat()` and `minmax()` in design JSX grid tracks, such as `columns="repeat(7, 1fr)"`, which collapsed the grid to near-zero columns. A track the grid cannot express sizes to its content instead of to 0.diff --git a/bun.lock b/bun.lockindex 91cf4b0f5..a657d4baa 100644--- a/bun.lock+++ b/bun.lock@@ -349,6 +349,7 @@"@ai-sdk/harness": "1.0.138","@ai-sdk/harness-pi": "1.0.140","@ai-sdk/sandbox-just-bash": "1.0.138",+ "@earendil-works/pi-tui": "0.85.1",},"devDependencies": {"@types/bun": "^1.3.14",diff --git a/packages/harness/AGENTS.md b/packages/harness/AGENTS.mdindex c7871195f..e7125ee5a 100644--- a/packages/harness/AGENTS.md+++ b/packages/harness/AGENTS.md@@ -5,4 +5,5 @@ Optional Node companion for HarnessAgent sessions. Tauri launches the separately- Keep the package backend-neutral.- Persist only opaque, non-secret resume state. Pi's in-memory `just-bash` cannot recover across process restarts.- Expose the bounded JSONL host protocol; changes to it must keep the desktop launcher and `desktop/capabilities/**` in sync (`desktop/AGENTS.md`).+- stdout carries only protocol messages: write them through the writer `reserveProtocolOutput()` returns, and let other output, including npm runs Pi starts, go to stderr (`tests/output.test.ts`).- `bun run test:tools` runs this package's tests together with the repo tooling suites.diff --git a/packages/harness/README.md b/packages/harness/README.mdindex b24e6cea3..8b5006653 100644--- a/packages/harness/README.md+++ b/packages/harness/README.md@@ -11,8 +11,8 @@ The first backend uses AI SDK `HarnessAgent`, Pi, and local `just-bash`. Pi runs- JSONL stdio sidecar transport.- Pi + `just-bash` backend.-The package is installed as an optional companion CLI for the desktop application. It is not bundled into every Tauri build; install `@open-pencil/harness` globally to make the `openpencil-harness` command available. Credentials are supplied to the companion process at runtime and are never written to resume-state storage.+The package is installed as an optional companion CLI for the desktop application. It is not bundled into every Tauri build; install `@open-pencil/harness` globally to make the `openpencil-harness` command available. It runs on Node 22.15 or later, or Bun: Pi's MCP adapter publishes TypeScript sources, which the companion strips through Node's module hooks. Credentials are supplied to the companion process at runtime and are never written to resume-state storage.## Local sandbox limitation-`just-bash` is process-local and in-memory. Multi-turn sessions work while the sidecar remains alive, but its sandbox cannot be reattached after a process restart. Persisted opaque state establishes the session contract; durable restart recovery requires a persistent sandbox provider in a later integration.+`just-bash` is process-local and in-memory. Multi-turn sessions work while the sidecar remains alive, but its sandbox cannot be reattached after a process restart. A backend that reports `sessionResume: 'live-process'`, as Pi does, therefore starts a stopped session fresh and drops its saved state. Durable restart recovery requires a persistent sandbox provider in a later integration.diff --git a/packages/harness/package.json b/packages/harness/package.jsonindex c005594e6..e26a77243 100644--- a/packages/harness/package.json+++ b/packages/harness/package.json@@ -35,7 +35,8 @@"dependencies": {"@ai-sdk/harness": "1.0.138","@ai-sdk/harness-pi": "1.0.140",- "@ai-sdk/sandbox-just-bash": "1.0.138"+ "@ai-sdk/sandbox-just-bash": "1.0.138",+ "@earendil-works/pi-tui": "0.85.1"},"devDependencies": {"@types/bun": "^1.3.14",diff --git a/packages/harness/src/output.ts b/packages/harness/src/output.tsnew file mode 100644index 000000000..2cc0853bb--- /dev/null+++ b/packages/harness/src/output.ts@@ -0,0 +1,15 @@+/**+ * stdout carries the JSONL protocol. Pi and its dependencies also write there: npm runs that+ * prepare a person's Pi packages inherit stdout, and libraries log with `console.log`. Keep+ * npm quiet on success and send every other stdout write to stderr, as Pi's own RPC mode does.+ * Returns the writer that reaches the real stdout.+ */+export function reserveProtocolOutput(): typeof process.stdout.write {+ process.env.npm_config_loglevel = 'silent'+ process.env.npm_config_audit = 'false'+ process.env.npm_config_fund = 'false'+ const writeProtocol = process.stdout.write.bind(process.stdout)+ const writeDiagnostics = process.stderr.write.bind(process.stderr)+ process.stdout.write = writeDiagnostics+ return writeProtocol+}diff --git a/packages/harness/src/service.ts b/packages/harness/src/service.tsindex da60cafcb..036ca6ec4 100644--- a/packages/harness/src/service.ts+++ b/packages/harness/src/service.ts@@ -29,10 +29,7 @@ export class HarnessSessionService {throw new Error(`Harness session already active: ${sessionId}`)const backend = this.backends.get(configuration.adapter)if (!backend) throw new Error(`Harness adapter is unavailable: ${configuration.adapter}`)- const resumeState = await this.store.load(sessionId)- if (resumeState && resumeState.harnessId !== backend.id) {- throw new Error(`Harness state belongs to ${resumeState.harnessId}, not ${backend.id}`)- }+ const resumeState = await this.loadResumeState(sessionId, backend)const session = await backend.createSession({sessionId,resumeState,@@ -75,6 +72,21 @@ export class HarnessSessionService {this.sessions.delete(sessionId)}+ /**+ * A backend that resumes only within its live process (Pi's in-memory just-bash sandbox)+ * cannot use saved state, and passing it makes every later session with that ID fail.+ */+ private async loadResumeState(sessionId: string, backend: HarnessBackend) {+ const resumeState = await this.store.load(sessionId)+ // State another backend saved stays for that backend to resume.+ if (resumeState && resumeState.harnessId !== backend.id) {+ throw new Error(`Harness state belongs to ${resumeState.harnessId}, not ${backend.id}`)+ }+ if (backend.capabilities.sessionResume === 'persistent') return resumeState+ await this.store.remove(sessionId)+ return undefined+ }+async destroySession(sessionId: string): Promise<void> {const session = this.requireSession(sessionId)await session.destroy()diff --git a/packages/harness/src/stdio.ts b/packages/harness/src/stdio.tsindex 5c4258b69..0299e1b9e 100644--- a/packages/harness/src/stdio.ts+++ b/packages/harness/src/stdio.ts@@ -6,10 +6,15 @@ import { createInterface } from 'node:readline'import { PiHarnessBackend } from '#harness/backends/pi'import type { PiHarnessBackendOptions } from '#harness/backends/pi'+import { reserveProtocolOutput } from '#harness/output'import type { HarnessRequest, HarnessSidecarMessage } from '#harness/protocol'import { parseHarnessRequest } from '#harness/protocol'import { HarnessSessionService } from '#harness/service'import { FileResumeStateStore } from '#harness/session-store'+import { loadTypeScriptDependencies } from '#harness/typescript-dependencies'++const writeProtocol = reserveProtocolOutput()+loadTypeScriptDependencies()const stateRoot =process.env.OPENPENCIL_HARNESS_STATE_DIR ?? join(homedir(), '.open-pencil', 'harness-sessions')@@ -25,7 +30,7 @@ const service = new HarnessSessionService()async function emit(message: HarnessSidecarMessage): Promise<void> {- if (process.stdout.write(`${JSON.stringify(message)}\n`)) return+ if (writeProtocol(`${JSON.stringify(message)}\n`)) returnawait new Promise<void>((resolve) => {process.stdout.once('drain', resolve)})diff --git a/packages/harness/src/typescript-dependencies.ts b/packages/harness/src/typescript-dependencies.tsnew file mode 100644index 000000000..983ffbe3d--- /dev/null+++ b/packages/harness/src/typescript-dependencies.ts@@ -0,0 +1,34 @@+import { readFileSync } from 'node:fs'+import { fileURLToPath } from 'node:url'++/**+ * `@ai-sdk/harness-pi` imports `pi-mcp-adapter`, which publishes TypeScript sources, and Node+ * refuses to strip types under `node_modules`. Strip them for TypeScript dependencies only, so+ * Pi sessions with MCP servers start under Node; Bun runs TypeScript itself.+ */+export function loadTypeScriptDependencies(): void {+ if (process.versions.bun) return+ // Read at runtime so Node versions without these APIs still start the companion.+ const { registerHooks, stripTypeScriptTypes } = process.getBuiltinModule('node:module')+ if (typeof registerHooks !== 'function' || typeof stripTypeScriptTypes !== 'function') return+ registerHooks({+ load(url, context, nextLoad) {+ if (!url.startsWith('file:') || !url.endsWith('.ts') || !url.includes('/node_modules/')) {+ return nextLoad(url, context)+ }+ const source = readFileSync(fileURLToPath(url), 'utf8')+ // The first call announces the experimental API on stderr, which reads as a problem in hosts.+ const emitWarning = process.emitWarning.bind(process)+ process.emitWarning = () => undefined+ try {+ return {+ format: 'module',+ source: stripTypeScriptTypes(source, { mode: 'transform' }),+ shortCircuit: true+ }+ } finally {+ process.emitWarning = emitWarning+ }+ }+ })+}diff --git a/packages/harness/tests/dependencies.test.ts b/packages/harness/tests/dependencies.test.tsnew file mode 100644index 000000000..6bc881b50--- /dev/null+++ b/packages/harness/tests/dependencies.test.ts@@ -0,0 +1,30 @@+import { describe, expect, test } from 'bun:test'+import { join } from 'node:path'++import harnessPackage from '../package.json'++function piTuiRange(manifest: unknown): string | undefined {+ if (typeof manifest !== 'object' || manifest === null || !('dependencies' in manifest)) {+ return undefined+ }+ const dependencies = manifest.dependencies+ if (typeof dependencies !== 'object' || dependencies === null) return undefined+ const range: unknown = Reflect.get(dependencies, '@earendil-works/pi-tui')+ return typeof range === 'string' ? range : undefined+}++describe('Pi dependencies', () => {+ test('pins pi-tui to the version pi-coding-agent uses', async () => {+ // pi-mcp-adapter imports pi-tui but declares it as an optional peer, and pi-coding-agent nests+ // its own copy, so the companion depends on pi-tui directly+ // (https://github.com/nicobailon/pi-mcp-adapter/issues/805). Upgrading @ai-sdk/harness-pi+ // moves pi-coding-agent; move this pin with it, or npm installs a second, mismatched pi-tui.+ const harnessPi = Bun.resolveSync('@ai-sdk/harness-pi', join(import.meta.dir, '..'))+ const agentManifest = Bun.resolveSync('@earendil-works/pi-coding-agent/package.json', harnessPi)+ const manifest: unknown = await Bun.file(agentManifest).json()+ const required = piTuiRange(manifest)+ const pinned = harnessPackage.dependencies['@earendil-works/pi-tui']+ expect(required).toBeString()+ expect(Bun.semver.satisfies(pinned, required ?? '')).toBe(true)+ })+})diff --git a/packages/harness/tests/output.test.ts b/packages/harness/tests/output.test.tsnew file mode 100644index 000000000..3ff0a381b--- /dev/null+++ b/packages/harness/tests/output.test.ts@@ -0,0 +1,34 @@+import { describe, expect, test } from 'bun:test'+import { spawnSync } from 'node:child_process'+import { join } from 'node:path'++const output = join(import.meta.dir, '../src/output.ts')+// The companion runs under Node, whose console writes through process.stdout.+const nodeRunsTypeScript =+ spawnSync('node', ['-e', 'process.exit(process.features.typescript ? 0 : 1)']).status === 0++describe('reserveProtocolOutput', () => {+ test.skipIf(!nodeRunsTypeScript)(+ 'keeps stdout for protocol messages and quiets npm runs its children start',+ () => {+ const script = `+ import { spawnSync } from 'node:child_process'+ const { reserveProtocolOutput } = await import(${JSON.stringify(output)})+ const writeProtocol = reserveProtocolOutput()+ console.log('library noise')+ process.stdout.write('more noise\\n')+ writeProtocol('{"type":"response"}\\n')+ const child = spawnSync(process.execPath, ['-p', 'process.env.npm_config_loglevel + " " + process.env.npm_config_audit'], { encoding: 'utf8' })+ writeProtocol(JSON.stringify({ npm: child.stdout.trim() }) + '\\n')+ `+ const result = spawnSync('node', ['--input-type=module', '-e', script], { encoding: 'utf8' })+ const lines = result.stdout.trim().split('\n')+ expect(lines.map((line) => JSON.parse(line))).toEqual([+ { type: 'response' },+ { npm: 'silent false' }+ ])+ expect(result.stderr).toContain('library noise')+ expect(result.stderr).toContain('more noise')+ }+ )+})diff --git a/packages/harness/tests/service.test.ts b/packages/harness/tests/service.test.tsindex 5ed94b0db..158381026 100644--- a/packages/harness/tests/service.test.ts+++ b/packages/harness/tests/service.test.ts@@ -64,15 +64,19 @@ class FakeSession implements BackendSession {class FakeBackend implements HarnessBackend {readonly id = 'pi' as const- readonly capabilities = {- adapter: 'pi',- sandboxes: ['just-bash'],- structuredOutput: false,- sessionResume: 'live-process',- turnContinuation: true- } as const+ readonly capabilitiessessions: FakeSession[] = []+ constructor(sessionResume: 'live-process' | 'persistent' = 'live-process') {+ this.capabilities = {+ adapter: 'pi',+ sandboxes: ['just-bash'],+ structuredOutput: false,+ sessionResume,+ turnContinuation: true+ } as const+ }+async createSession(options: {sessionId: stringresumeState?: HarnessResumeState@@ -100,7 +104,7 @@ describe('HarnessSessionService', () => {})test('streams turns and resumes from opaque persisted state', async () => {- const backend = new FakeBackend()+ const backend = new FakeBackend('persistent')const store = new MemoryStore()const service = new HarnessSessionService(new Map([[backend.id, backend]]), store)@@ -118,7 +122,7 @@ describe('HarnessSessionService', () => {})test('destroys a session and removes resumability', async () => {- const backend = new FakeBackend()+ const backend = new FakeBackend('persistent')const store = new MemoryStore()const service = new HarnessSessionService(new Map([[backend.id, backend]]), store)await service.createSession('session-1', configuration)@@ -138,9 +142,41 @@ describe('HarnessSessionService', () => {specificationVersion: 'harness-v1',data: {}})- const service = new HarnessSessionService(new Map([['pi', new FakeBackend()]]), store)+ const service = new HarnessSessionService(+ new Map([['pi', new FakeBackend('persistent')]]),+ store+ )+ await expect(service.createSession('session-1', configuration)).rejects.toThrow(+ 'belongs to other'+ )+ })++ test('starts a live-process backend fresh and drops state saved by an earlier session', async () => {+ const backend = new FakeBackend('live-process')+ const store = new MemoryStore()+ const service = new HarnessSessionService(new Map([[backend.id, backend]]), store)+ await service.createSession('session-1', configuration)+ await service.stopSession('session-1')++ expect(await service.createSession('session-1', configuration)).toEqual({ isResume: false })+ expect(store.states.has('session-1')).toBeFalse()+ })++ test("rejects another backend's state without deleting it for a live-process backend", async () => {+ const store = new MemoryStore()+ store.states.set('session-1', {+ type: 'resume-session',+ harnessId: 'other',+ specificationVersion: 'harness-v1',+ data: {}+ })+ const service = new HarnessSessionService(+ new Map([['pi', new FakeBackend('live-process')]]),+ store+ )await expect(service.createSession('session-1', configuration)).rejects.toThrow('belongs to other')+ expect(store.states.has('session-1')).toBeTrue()})})diff --git a/packages/harness/tests/typescript-dependencies.test.ts b/packages/harness/tests/typescript-dependencies.test.tsnew file mode 100644index 000000000..2b82d17e3--- /dev/null+++ b/packages/harness/tests/typescript-dependencies.test.ts@@ -0,0 +1,49 @@+import { describe, expect, test } from 'bun:test'+import { spawnSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++const hook = join(import.meta.dir, '../src/typescript-dependencies.ts')+// The hook needs Node's module hooks and type stripping, which older Node versions lack.+const nodeSupportsHook =+ spawnSync('node', [+ '-e',+ "const m = require('node:module'); process.exit(typeof m.registerHooks === 'function' && typeof m.stripTypeScriptTypes === 'function' && process.features.typescript ? 0 : 1)"+ ]).status === 0++function importUnderNode(register: boolean) {+ const root = mkdtempSync(join(tmpdir(), 'openpencil-harness-ts-'))+ try {+ const dependency = join(root, 'node_modules', 'typed-dependency')+ mkdirSync(dependency, { recursive: true })+ writeFileSync(join(dependency, 'package.json'), '{"type":"module","exports":"./index.ts"}')+ writeFileSync(join(dependency, 'index.ts'), 'export const value: number = 42\n')+ const script = [+ register+ ? `const { loadTypeScriptDependencies } = await import(${JSON.stringify(hook)})`+ : '',+ register ? 'loadTypeScriptDependencies()' : '',+ "const { value } = await import('typed-dependency')",+ 'console.log(value)'+ ].join('\n')+ return spawnSync('node', ['--no-warnings', '--input-type=module', '-e', script], {+ cwd: root,+ encoding: 'utf8'+ })+ } finally {+ rmSync(root, { recursive: true, force: true })+ }+}++describe('loadTypeScriptDependencies', () => {+ test.skipIf(!nodeSupportsHook)(+ 'lets Node import a dependency that publishes TypeScript sources',+ () => {+ expect(importUnderNode(false).status).not.toBe(0)+ const result = importUnderNode(true)+ expect(result.stderr).toBe('')+ expect(result.stdout.trim()).toBe('42')+ }+ )+})diff --git a/src/app/ai/harness/process.ts b/src/app/ai/harness/process.tsindex 60ed6945f..b569811e1 100644--- a/src/app/ai/harness/process.ts+++ b/src/app/ai/harness/process.ts@@ -88,7 +88,8 @@ export async function spawnHarnessProcess(options: {})command.stderr.on('data', (raw: Uint8Array | number[] | string) => {const text = typeof raw === 'string' ? raw : decoder.decode(new Uint8Array(raw))- console.error('[Harness]', text)+ // Diagnostics only: the companion reports failures as protocol errors.+ console.warn('[Harness]', text)})command.on('close', () => {controller?.close()