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
Share is an experiment: a process of its own, started only once it is on, holding no credential (#933)
Dee6d79aa30f8df
diff --git a/cli/e2e/experiments.e2e.ts b/cli/e2e/experiments.e2e.tsindex bc771ff23..7c3bb5e67 100644--- a/cli/e2e/experiments.e2e.ts+++ b/cli/e2e/experiments.e2e.ts@@ -9,8 +9,11 @@import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { b64e, newEphemeral } from '../src/lib/e2ee/core.js'+import { recipientHandshake } from '../src/sharing/crypto.js'import { LocalClient, type Frame } from './harness/client.js'import { IsolatedDaemon, until } from './harness/daemon.js'+import { FakeBackend, type FakeMachine } from './harness/fakeBackend.js'/** The orchestrator's process the master runs now: the last one it said it started, read from its log. */const orchestratorPid = (d: IsolatedDaemon): number | null => {@@ -41,10 +44,21 @@ async function turn(client: LocalClient, agentId: string, content: string): Prom}const projects = (client: LocalClient) => client.request('orchestrator', { action: 'list' }, 40_000)const teamsStarts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service teams started/g)].length+const sharingStarts = (d: IsolatedDaemon) => [...d.log().matchAll(/\[harnessd\] service sharing started/g)].length+/** Share publishes its links through the account and reaches its observers through the relay: signed in, to the fake. */+const SHARER: FakeMachine = { machineId: 'd4'.repeat(16), computerId: 'e2e-computer-0000-0000-00000000000d', name: 'sharer', token: 'e2e-token-sharer' }+const signIn = (d: IsolatedDaemon) => writeFileSync(join(d.root, 'auth', 'session.json'), JSON.stringify({+ version: 1, accessToken: SHARER.token, autonomousEnv: 'prod', computerId: SHARER.computerId,+ machineId: SHARER.machineId, expiresAt: Date.now() + 30 * 24 * 3600_000, updatedAt: Date.now(), signInEpoch: 'e2e',+}), { mode: 0o600 })describe('the experiments, each in a process started only when it is on', () => {let daemon: IsolatedDaemon | undefined- afterEach(async () => { await daemon?.close(); daemon = undefined })+ let backend: FakeBackend | undefined+ afterEach(async () => {+ await daemon?.close(); daemon = undefined+ await backend?.close(); backend = undefined+ })const fresh = async (env: Record<string, string> = {}, before?: (d: IsolatedDaemon) => void) => {const d = await IsolatedDaemon.create({ env: {HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',@@ -182,4 +196,54 @@ describe('the experiments, each in a process started only when it is on', () =>await until('the teams to start for their saved state', () => d.log().includes('[services] collaboration connected') || null, 30_000, 200)expect(teamsStarts(d)).toBe(1)})+ const sharer = async (before?: (d: IsolatedDaemon) => void) => {+ const relay = await FakeBackend.start()+ backend = relay+ relay.addMachine(SHARER)+ const d = await fresh({ BACKEND_WS_URL: relay.wsUrl, WEB_URL: relay.httpUrl, ADAPTER_COMPUTER_ID: SHARER.computerId }, (daemon) => { signIn(daemon); before?.(daemon) })+ return { d, relay }+ }++ it('Share: off, it has no process; a link starts it, and the link\'s observer is welcomed under its key and watches the terminal, sealed', async () => {+ const { d, relay } = await sharer()+ // Signed in, the daemon serves as the account's machine.+ const client = await LocalClient.connect(d, { machineId: SHARER.machineId })+ const agent = await create(d, client, 'shared')+ await until('the services to connect', () => d.log().includes('[services] search connected') || null, 30_000, 200)+ await until('the relay', () => relay.nodeUp(SHARER.machineId) || null, 30_000, 200)+ expect(sharingStarts(d), 'an experiment no one asked for').toBe(0)+ const linked = await client.request('harness_share_link', { agentId: agent.id, visibility: 'public' }, 40_000)+ expect(linked.error, JSON.stringify(linked)).toBeUndefined()+ expect(sharingStarts(d)).toBe(1)+ const link = linked.link as { id: string; url: string; error: string | null }+ expect(link.error).toBeNull()+ expect(relay.seen).toContain(`PUT /api/harness-links/${link.id}`)+ // An observer of the link, through the relay: its welcome is signed by the key the link names.+ const observer = 'observer:e2e-ken'+ const ephemeral = newEphemeral()+ relay.injectDown(SHARER.machineId, observer, { type: 'observer_open', payload: { linkId: link.id, ephemeral: b64e(ephemeral.pub), authorId: 'e2e-ken', authorName: 'Ken' } })+ const welcome = await until('the observer\'s welcome', () => relay.targeted.get(observer)?.find((frame) => frame.type === 'observer_welcome') ?? null, 30_000, 100)+ const key = new URLSearchParams(new URL(link.url).hash.slice(1)).get('key')!+ const cipher = recipientHandshake(ephemeral, SHARER.machineId, link.id, key, welcome.payload as Record<string, unknown>)+ relay.injectDown(SHARER.machineId, observer, { type: 'observer_frame', payload: cipher.seal({ type: 'terminal_open', payload: { protocolVersion: 3, agentId: agent.id, cols: 80, rows: 24, requestId: 'e2e-open' } }) as never })+ // Each sealed frame opens once, in order.+ const shown: Array<Record<string, any>> = []+ const read = () => {+ const frames = (relay.targeted.get(observer) ?? []).filter((frame) => frame.type === 'observer_frame')+ for (const frame of frames.slice(shown.length)) shown.push(cipher.open(frame.payload) ?? { type: 'unopened' })+ return shown+ }+ const ready = await until('the terminal, read-only', () => read().find((frame) => frame.type === 'terminal_ready') ?? null, 30_000, 100)+ expect(ready.payload).toMatchObject({ requestId: 'e2e-open', agentId: agent.id, readOnly: true })+ await until('its bytes', () => read().some((frame) => frame.type === 'observer_binary') || null, 30_000, 100)+ expect(shown.map((frame) => frame.type)).not.toContain('unopened')+ expect(d.coresStarted()).toBe(1)+ client.close()+ })++ it('a saved link turns Share on as the daemon starts', async () => {+ const { d } = await sharer((daemon) => writeFileSync(join(daemon.dataDir, 'harness-collaboration.json'), JSON.stringify({ links: [], comments: [] }), { mode: 0o600 }))+ await until('Share to start for its saved links', () => d.log().includes('[services] sharing connected') || null, 30_000, 200)+ expect(sharingStarts(d)).toBe(1)+ })})diff --git a/cli/e2e/harness/fakeBackend.ts b/cli/e2e/harness/fakeBackend.tsindex 20d4d625f..352cbcad8 100644--- a/cli/e2e/harness/fakeBackend.ts+++ b/cli/e2e/harness/fakeBackend.ts@@ -21,6 +21,10 @@** Like the real relay it is blind: the machines seal everything between them end to end, and a frame* for a machine whose node is not connected is simply never answered, as the real hub's would not be.+ * - `PUT`/`DELETE /api/harness-links/:id` and `/api/harness-shares/:id`: Share publishing a link or an+ * invitation, answered 200; what a node sends to one of Share's observers (`observer:` connections) is+ * kept in `targeted`, so a test can open what Share sealed for it.+ ** Everything else is answered 404. Requests are recorded in `seen`, so a test can say what was asked.** And it can misbehave, as a relay under stress does: every socket dropped at once, down for a while,@@ -81,6 +85,8 @@ export class FakeBackend {readonly webReceived = new Map<string, Frame[]>()/** What each device socket (a daemon's lane to its other machines) sent towards a machine, as sent. */readonly deviceSent: Frame[] = []+ /** What a node sent to a connection that is neither a device's nor a web client's (Share's observers), by id. */+ readonly targeted = new Map<string, Frame[]>()private constructor(private readonly server: Server, readonly port: number) {}@@ -100,6 +106,11 @@ export class FakeBackend {res.end(json({ success: true, data: { machines: backend.rows() } }))return}+ if ((req.method === 'PUT' || req.method === 'DELETE') && /^\/api\/harness-(links|shares)\/[^/?]+$/.test(req.url?.split('?')[0] ?? '')) {+ req.resume()+ res.end(json({ success: true, data: {} }))+ return+ }res.statusCode = 404res.end(json({ success: false, error: { code: 'NOT_FOUND', message: 'not on the fake backend' } }))})@@ -280,6 +291,7 @@ export class FakeBackend {if (owner?.machineId === machineId) this.sendDevice(owner.device, tagged)const web = [...this.webClients].find((client) => client.connId === envelope.targetConnId && client.machineId === machineId)if (web) this.toWeb(web, envelope.frame)+ if (!owner && !web) this.targeted.set(envelope.targetConnId, [...(this.targeted.get(envelope.targetConnId) ?? []), envelope.frame])return}if (envelope.commanderEligible) for (const device of this.devices) this.sendDevice(device, tagged)diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 24cedd533..c6b908dc7 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -239,7 +239,13 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {// the core reads a pane with as it writes a team's turn, now lib/teamWriteHold.ts, and what the core keeps of// the teams' process (core/teamsLink.ts: which deliveries may be written, the scopes' own questions) and of// the account's notices (core/experiments.ts).-const CORE_CLOSURE_BUDGET = 88_180+//+// Then at 87,476 in 387, from 88,083 in 392: Share is an experiment, in a process of its own started only+// once on (services/sharingProcess.ts), holding no credential: the owner, its stores, its crypto and the+// identity store it signed with leave. Its welcomes are signed by the gateway (gateway/observerKey.ts), and+// its observers' terminals are read by the core's read-only stream manager (core/terminalWatch.ts), which+// stays with what the core keeps of Share (core/sharingLink.ts).+const CORE_CLOSURE_BUDGET = 87_570/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */const EDGE: RegExp[] = [@@ -310,22 +316,15 @@ const CORE_MAY_REACH: Record<string, string> = {'lib/autonomous-device/storeContract.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway','lib/autonomous-device/storeRuntime.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway','lib/autonomous-device/stream.ts': 'step 10: the Wi-Fi device, into the devices process over the gateway',- 'lib/e2ee/core.ts': 'step 8: Share seals its own frames with it',+ 'lib/e2ee/core.ts': 'with lib/e2ee/machinePeers.ts (step 9)','lib/e2ee/machinePeers.ts': 'step 9: the fleet reads which machines are linked (their public keys, no credential), beside the dial',- 'lib/e2ee/passwordPake.ts': 'with lib/e2ee/store.ts',- 'lib/e2ee/store.ts': 'step 8: this machine\'s identity, for Share\'s owner','lib/sessionSearch/sessionTurns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads','lib/sessionSearch/transcript.ts': 'the readers of other engines\' sessions keep this helper: it moves beside them, out of search\'s folder','lib/sessionSearch/turns.ts': 'the handoff (lib/agentHandoff.ts), in the edge host once CoreApi gives it the stopped agents, recaps and discovery it reads','services/fleet.ts': 'step 9: the fleet, beside the dial','services/fleetRouter.ts': 'step 9: the fleet, beside the dial','services/shell.ts': 'shell setup and launch receipts, in the edge host; only the argv launch stays in the core (#893)',- 'sharing/collaboration.ts': 'step 8: the experimental host',- 'sharing/crypto.ts': 'step 8: the experimental host',- 'sharing/grants.ts': 'step 8: the experimental host',- 'sharing/owner.ts': 'step 8: the experimental host',- 'sharing/protocol.ts': 'step 8: the experimental host',- 'sharing/viewer.ts': 'step 8: the experimental host',+ 'sharing/viewer.ts': 'the windows\' interactive viewers capture with it (lib/interactiveViewer.ts): headless Chrome belongs with the viewers\' process (plan, "Sharing")',}describe('the daemon\'s shape', () => {diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 68635e328..7118f4b3a 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -1,10 +1,8 @@import type { PurgeAgentService } from './lib/purgeAgentService.js'-import { TEAMS_REQUESTS, type Asker, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'+import { SHARE_REQUESTS, TEAMS_REQUESTS, type Asker, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'import { ServiceUnavailableError } from './core/serviceHost.js'import type { ActivityFrame } from './lib/turnActivity.js'import { MonitorCompletions } from './lib/harnessMonitor.js'-import type { HarnessShareOwner } from './sharing/owner.js'-import { SHARE_REQUEST_TYPES } from './sharing/protocol.js'import { deviceRelayOverGateway, type DeviceRelayOverGateway } from './lib/autonomous-device/overGateway.js'import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/autonomous-device/service.js'/**@@ -52,6 +50,8 @@ export { isLocalClientId, type DownTransport }const MAX_REQUESTS_BEFORE_READY = 256/** The teams' requests, which the frame log leaves out: they carry what agents ask each other. */const TEAM_REQUESTS: ReadonlySet<string> = new Set(TEAMS_REQUESTS)+/** Share's requests, which the frame log leaves out as well: they carry who a harness is shared with. */+const SHARE_REQUEST_TYPES: ReadonlySet<string> = new Set(SHARE_REQUESTS)export type Frame = Record<string, unknown>@@ -167,8 +167,10 @@ export class BackendSocket {Promise<{ ok: true; session: RegisteredSession } | { ok: false; error: string; detail?: string }>) | null = null/** Called on `remote_terminal_handoff` — cli.ts names the agent whose tile is that tmux pane, or null. */onTerminalHandoff: ((tmuxPane: string) => string | null) | null = null+ /** Share's observers, as the relay hands their frames over and drops them all with the link (services/sharing.ts,+ * through its port). Null answers none, as a daemon without Share did. */+ observers: { receive(connId: string, type: string, payload: Record<string, unknown>): Promise<void> | void; closeAll(): void } | null = null/** What the daemon knows about an agent's DSH companions (viewer URL, verdict); null when nothing. */- harnessSharing: HarnessShareOwner | null = nullactivityFrameProvider: ((session: RegisteredSession) => ActivityFrame | null) | null = nulldshFrameProvider: ((session: RegisteredSession) => AgentDshContext | null) | null = nullviewerTargetProvider: ((agentId: string) => string | null) | null = null@@ -354,7 +356,7 @@ export class BackendSocket {false,)},- observer: async (connId, type, payload) => { await this.harnessSharing?.receive(connId, type, payload) },+ observer: async (connId, type, payload) => { await this.observers?.receive(connId, type, payload) },toLocal: (connId, frame) => {if (connId) { this.sendLocalTo(connId, frame); return }for (const [id, sink] of this.localClients) if (!sink.sendFrame(frame)) void this.unregisterLocalClient(id)@@ -364,7 +366,7 @@ export class BackendSocket {this.onStatus(connected)},linkDown: () => {- this.harnessSharing?.closeAll()+ this.observers?.closeAll()this.viewerForwarder.closeAll()this.interactiveViewers.closeAll(); this.ownerCommands.closeAll()void this.terminalStreams?.closeConnectionsWhere(@@ -468,7 +470,6 @@ export class BackendSocket {this.interactiveViewers.closeAll(); this.ownerCommands.closeAll()await this.terminalStreams?.stop()await this.gatewayPort?.stop()- await this.harnessSharing?.stop()}/** What the gateway does with a frame of the core's, guarded: a throw there (sealing one, say) costs@@ -815,12 +816,6 @@ export class BackendSocket {&& ['agent_close', 'agent_delete', 'agent_resume', 'agent_restart', 'agent_retarget', 'agent_update'].includes(type)) {reply(type, (frame.payload as { requestId?: unknown }).requestId, { error: 'DELETE_IN_PROGRESS' }); return}- if (SHARE_REQUEST_TYPES.has(type)) {- const p = (frame.payload ?? {}) as Record<string, unknown>- const result = await this.harnessSharing?.manage(type, p).catch(() => ({ error: 'SHARING_UNAVAILABLE', detail: 'Sharing is temporarily unavailable. Try again.' }))- reply(type, p.requestId, result ?? { error: 'UNSUPPORTED' })- return- }const payload = (frame.payload ?? {}) as Record<string, unknown>const requestId = payload.requestIdconst answer = (result: Record<string, unknown>): void => reply(type, requestId, result)diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex 43816f90a..ca673c502 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -46,7 +46,9 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGEkeystrokes, and how it asks it the rest. `agentQueries.ts`: what a service in its own process may ask of the agents;`accountQueries.ts`: of the account (a token, and the fleet's lane's sealing), so it holds no credential.`experimentQueries.ts`: what an experiment acts on the core through; `experiments.ts`: which are on as the- core starts; `orchestratorLink.ts`: what the core keeps of the orchestrator in its own process.+ core starts; `orchestratorLink.ts`: what the core keeps of the orchestrator in its own process;+ `sharingLink.ts`: Share's observers' frames to its process; `terminalWatch.ts`: a read-only view of the+ agents' terminals, which Share shows its observers.`gatewayLink.ts`: the relay and its E2EE in their own process (src/gateway/), as the core sees them:the link's state and the remote clients it reads in line, the frames it hands over in the clear, awindow's sessions to another machine or a shared harness, and the fleet's lane's sealingdiff --git a/cli/src/core/api.spec.ts b/cli/src/core/api.spec.tsindex 9aa922762..3ba586387 100644--- a/cli/src/core/api.spec.ts+++ b/cli/src/core/api.spec.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from 'vitest'import { projectDisplayName, type RegisteredSession } from '../lib/registry.js'-import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, TEAMS_FALLBACKS, type CoreApiDeps } from './api.js'+import { ACCOUNT_BACKEND_OFF, AGENT_ACTIONS_OFF, createCoreApi, DAEMON_UNKNOWN, DELIVERIES_OFF, emptyPorts, FLEET_FALLBACKS, LANE_OFF, LONG_ANSWERS, MODELS_OFF, MODELS_REQUESTS, MONITOR_OFF, OBSERVER_KEY_OFF, ORCHESTRATOR_FALLBACKS, resolveAgent, SHARING_FALLBACKS, TEAMS_FALLBACKS, TERMINALS_OFF, type CoreApiDeps } from './api.js'import { FAIL } from './serviceHost.js'const row = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/work/app' }) as RegisteredSession@@ -62,14 +62,16 @@ describe('the core API services stand on', () => {create: vi.fn(async () => ({ ok: true as const, agentId: 'made' })),dsh: vi.fn(() => null),windows: vi.fn(),- daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1' },+ daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1', autonomousEnv: 'prod' },+ observerKey: OBSERVER_KEY_OFF,+ observer: vi.fn(() => true),turns: { send: vi.fn(), stop: vi.fn(), recent: vi.fn(() => []), asks: vi.fn(() => []), deliver: vi.fn(), cancelDelivery: vi.fn(() => true), onDelivery: vi.fn(() => () => {}) },questions: { answer: vi.fn(), answerReviewed: vi.fn(async () => true) },}const core = createCoreApi(deps)expect(core.dataDir).toBe('/data')expect(await core.terminals.open({ argv: ['/bin/zsh'], cwd: '/work' })).toEqual({ ok: false, error: 'SERVICE_UNAVAILABLE' })- const terminals = { open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })) }+ const terminals = { open: vi.fn(async () => ({ ok: true as const, agentId: 'shell' })), watch: TERMINALS_OFF.watch }expect(createCoreApi({ ...deps, terminals }).terminals).toBe(terminals)expect(core.agents.all().map((s) => s.agentId)).toEqual(['live', 'stopped'])expect(core.agents.live().map((s) => s.agentId)).toEqual(['live'])@@ -96,6 +98,8 @@ describe('the core API services stand on', () => {expect(core.account.machineName).toBe(deps.machineName)expect(core.account.backend).toBe(deps.backend)expect(core.account.onNotice).toBe(deps.onNotice)+ expect(core.account.observerKey).toBe(deps.observerKey)+ expect(core.clients.observer).toBe(deps.observer)// What a device or another machine asks of an agent here: the core's own handlers, as they are.expect(core.agents.runtimeProfile).toBe(deps.runtimeProfile)expect(core.agents.setRuntime).toBe(deps.setRuntime)@@ -131,7 +135,7 @@ describe('the core API services stand on', () => {})it('starts with every port empty: a service fills its own when it starts', () => {- expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null, orchestrator: null })+ expect(emptyPorts()).toEqual({ search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null, orchestrator: null, sharing: null })expect(emptyPorts()).not.toBe(emptyPorts())})@@ -167,6 +171,15 @@ describe('the core API services stand on', () => {expect(ACCOUNT_BACKEND_OFF.onNotice(() => {})()).toBeUndefined()})+ it('watches no terminal and signs nothing for a service without the core\'s terminals or key', async () => {+ await expect(TERMINALS_OFF.watch.frame('observer:x', 'terminal_open', {})).resolves.toBeUndefined()+ await expect(TERMINALS_OFF.watch.close('observer:x')).resolves.toBeUndefined()+ expect(TERMINALS_OFF.watch.onOutput(() => {})()).toBeUndefined()+ await expect(OBSERVER_KEY_OFF.publicKey()).rejects.toThrow('no E2EE identity')+ await expect(OBSERVER_KEY_OFF.signWelcome('m', 's', 'p', 'e')).rejects.toThrow('no E2EE identity')+ expect(SHARING_FALLBACKS).toEqual({ observer: undefined, linkDown: undefined, stop: undefined })+ })+it('answers no role and reads no frame while the orchestrator is off', () => {expect(ORCHESTRATOR_FALLBACKS).toEqual({ roleOf: null, frame: undefined, stop: undefined })})diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 5ef46ec3c..548dd5b66 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -44,10 +44,27 @@ export interface TerminalOpen {cwd: string}export type TerminalOpenResult = { ok: true; agentId: string } | { ok: false; error: string; detail?: string }-export interface TerminalsPort { open(request: TerminalOpen): Promise<TerminalOpenResult> }-/** A service without the core's launch call must refuse, never launch outside the core. */+/** What a viewer is shown of a terminal it watches: a frame, or a terminal's bytes (base64 of the local binary+ * frame, lib/terminalBinary.ts). */+export type TerminalWatchOutput = { type: string; payload: Record<string, unknown> } | { binary: string }+/**+ * A read-only view of agents' terminals for a feature's own viewers (Share's observers, core/terminalWatch.ts):+ * each viewer's terminal frames in (`terminal_open`, `terminal_ack`, …), what it is shown out. Nothing a+ * viewer sends ever reaches a pane.+ */+export interface TerminalWatch {+ frame(viewer: string, type: string, payload: Record<string, unknown>): Promise<void>+ close(viewer: string): Promise<void>+ onOutput(listener: (viewer: string, output: TerminalWatchOutput) => void): () => void+}+export interface TerminalsPort {+ open(request: TerminalOpen): Promise<TerminalOpenResult>+ watch: TerminalWatch+}+/** A service without the core's launch call must refuse, never launch outside the core; it watches nothing. */export const TERMINALS_OFF: TerminalsPort = {open: async () => ({ ok: false, error: 'SERVICE_UNAVAILABLE' }),+ watch: { frame: async () => {}, close: async () => {}, onOutput: () => () => {} },}export interface CoreApi {@@ -137,6 +154,8 @@ export interface CoreApi {/** The fleet's lane to the owner's other machines, sealed by the gateway with this machine's E2EE* identity, which no service holds (`LaneSeal`). */lane: LaneSeal+ /** This machine's E2EE identity as Share's owner signs with it, held by the gateway (`ObserverKey`). */+ observerKey: ObserverKey/** The account's private grid as the backend named it (`machine_meta`), or as grid's set-up just* confirmed it; null before either. Working it out when neither has said is the models service's* (`lib/gridDerive.ts`). */@@ -164,6 +183,9 @@ export interface CoreApi {/** A frame for every window on this computer, as an experiment tells them it changed* (`orchestrator_changed`, `team_changed`); never sent off this computer. */windows(frame: { type: string; payload: Record<string, unknown> }): void+ /** A frame for one of Share's observers, sealed by Share itself, to the relay through the gateway; false+ * when it could not be handed over. */+ observer(connId: string, type: string, payload: Record<string, unknown>): boolean}/** How an agent's shell reaches this daemon: the command that runs this harness's CLI, the port the daemon* serves and the machine it serves as. An experiment writes them into the prompts of the agents it runs@@ -188,6 +210,23 @@ export interface DaemonAddress {command: stringport: numbermachineId(): string+ /** The account's environment (`prod`, `staging`, …), as the links a feature makes name it. */+ autonomousEnv: string+}++/**+ * This machine's E2EE identity as Share's owner uses it (sharing/crypto.ts `OwnerKey`): its public half, and+ * the signature on a welcome to one observer of one share. The private half is the gateway's alone; a Share in+ * a process of its own asks for each welcome and holds no credential. Base64 throughout.+ */+export interface ObserverKey {+ publicKey(): Promise<string>+ signWelcome(machineId: string, shareId: string, peer: string, ephemeral: string): Promise<string>+}+/** A process with no key of the core's: it signs nothing. */+export const OBSERVER_KEY_OFF: ObserverKey = {+ publicKey: () => Promise.reject(new Error('no key: this process holds no E2EE identity')),+ signWelcome: () => Promise.reject(new Error('no key: this process holds no E2EE identity')),}/** A service in its own process that acts on no agent: it creates none and reads no harness's frame. */@@ -196,14 +235,15 @@ export const AGENT_ACTIONS_OFF: Pick<CoreApi['agents'], 'create' | 'dsh'> = {dsh: () => null,}-/** The account as a service that reads no backend and hears no notice has it. */-export const ACCOUNT_BACKEND_OFF: Pick<CoreApi['account'], 'backend' | 'onNotice'> = {+/** The account as a service that reads no backend, hears no notice and signs nothing has it. */+export const ACCOUNT_BACKEND_OFF: Pick<CoreApi['account'], 'backend' | 'onNotice' | 'observerKey'> = {backend: async () => ({ status: 503, body: { error: 'SERVICE_UNAVAILABLE' } }),onNotice: () => () => {},+ observerKey: OBSERVER_KEY_OFF,}/** Where a service that was never told runs this daemon from: the installed CLI, on no port it knows. */-export const DAEMON_UNKNOWN: DaemonAddress = { command: 'harness', port: 0, machineId: () => '' }+export const DAEMON_UNKNOWN: DaemonAddress = { command: 'harness', port: 0, machineId: () => '', autonomousEnv: 'prod' }/** What became of a delivered turn (`turns.deliver`), as the core's input says it: `queued`, written* (`delivered`), its turn `started`, `rejected` with why, or `unknown`. `sessionId` is the agent it was@@ -308,6 +348,12 @@ export const LONG_ANSWERS: Readonly<Record<string, Readonly<Record<string, numbe/** The orchestrator (services/orchestrator.ts): its projects, for the apps and for the agents it runs. */export const ORCHESTRATOR_REQUESTS = ['orchestrator'] as const+/** Share (services/sharing.ts): an owner's shares of a harness, their links and their comments. */+export const SHARE_REQUESTS = [+ 'harness_share_list', 'harness_share_invite', 'harness_share_remove', 'harness_share_link',+ 'harness_share_comments', 'harness_share_comment_post', 'harness_share_comment_remove',+] as const+/** Tab collaboration and teams (services/collaboration.ts): the teams' own requests, from the apps, from `harness team`* in an agent's shell and from the other machines' teams. */export const TEAMS_REQUESTS = ['team', 'team_delivery'] as const@@ -330,8 +376,22 @@ export const EXPERIMENTS: Readonly<Record<string, { requests: readonly string[];// Tab collaboration and teams, beside the prompt scopes in the teams' process (harnessd/services.ts). Its// ledgers and mailboxes: a team was made here, or another machine's team delivered to an agent here.collaboration: { requests: TEAMS_REQUESTS, state: ['teams'] },+ // Its invitations and links: a harness was shared from here.+ sharing: { requests: SHARE_REQUESTS, state: ['harness-shares.json', 'harness-collaboration.json'] },+}++/** The core's calls into Share: an observer's frame as the relay handed it over, the relay gone (every observer+ * with it), and stopping it. */+export interface SharingPort {+ observer(connId: string, type: string, payload: Record<string, unknown>): Promise<void> | void+ linkDown(): void+ stop(): Promise<void> | void}+/** What the core gets when Share fails: an observer's frame goes unanswered, as it would to a daemon without+ * Share, and a shutdown goes on. */+export const SHARING_FALLBACKS: PortFallbacks<SharingPort> = { observer: undefined, linkDown: undefined, stop: undefined }+/** What an agent is to the orchestrator's projects: a specialist (`worker`), or a project's Director, and* whether work is still out under it. */export type OrchestratorRole = { role: 'worker' } | { role: 'director'; busy: boolean }@@ -803,6 +863,8 @@ export interface GatewayOps {reachable(machineIds: string[] | null): void/** The fleet's lane's sessions (`core.account.lane`). */lane: LaneSeal+ /** Share's owner's signature on a welcome, with this machine's identity (`core.account.observerKey`). */+ observerKey: ObserverKey}/** A window on this computer working on another of the owner's machines, through the relay: what the@@ -842,10 +904,11 @@ export interface CorePorts {fleet: FleetPort | nullmonitor: MonitorPort | nullorchestrator: OrchestratorPort | null+ sharing: SharingPort | null}export function emptyPorts(): CorePorts {- return { search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null, orchestrator: null }+ return { search: null, viewers: null, models: null, workspaces: null, teams: null, fleet: null, monitor: null, orchestrator: null, sharing: null }}export interface CoreApiDeps {@@ -865,6 +928,8 @@ export interface CoreApiDeps {mintGridName: CoreApi['account']['mintGridName']accessToken: CoreApi['account']['accessToken']lane: CoreApi['account']['lane']+ observerKey: CoreApi['account']['observerKey']+ observer: CoreApi['clients']['observer']privateGridName: CoreApi['account']['privateGridName']machineName: CoreApi['account']['machineName']backend: CoreApi['account']['backend']@@ -882,7 +947,7 @@ export interface CoreApiDeps {export function createCoreApi({dataDir, registry, stoppedAgents, databaseHistory, externalSessions, openSessions, syncSession, runtimeModels, viewerChanged,- gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, privateGridName, machineName, backend, onNotice,+ gridNamed, gridModelsChanged, dshInstallStatus, mintGridName, accessToken, lane, observerKey, observer, privateGridName, machineName, backend, onNotice,runtimeProfile, setRuntime, fork, create, dsh, windows, daemon, turns, questions, terminals = TERMINALS_OFF,}: CoreApiDeps): CoreApi {return {@@ -908,8 +973,8 @@ export function createCoreApi({questions,transcripts: { databaseHistory },external: { sessions: externalSessions, open: openSessions },- account: { mintGridName, accessToken, lane, privateGridName, machineName, backend, onNotice },- clients: { viewerChanged, gridNamed, gridModelsChanged, dshInstallStatus, windows },+ account: { mintGridName, accessToken, lane, observerKey, privateGridName, machineName, backend, onNotice },+ clients: { viewerChanged, gridNamed, gridModelsChanged, dshInstallStatus, windows, observer },daemon,}}diff --git a/cli/src/core/experimentQueries.spec.ts b/cli/src/core/experimentQueries.spec.tsindex 9030cc1b3..06142b648 100644--- a/cli/src/core/experimentQueries.spec.ts+++ b/cli/src/core/experimentQueries.spec.ts@@ -54,8 +54,8 @@ describe('what an experiment in its own process may ask of the core', () => {})it('says how an agent\'s shell reaches this daemon', async () => {- const core = fakeCore({ daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: () => 'machine-7' } })- expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'daemon', {})).toEqual({ command: `'node' 'cli.js'`, port: 18473, machineId: 'machine-7' })+ const core = fakeCore({ daemon: { command: `'node' 'cli.js'`, port: 18473, machineId: () => 'machine-7', autonomousEnv: 'staging' } })+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'daemon', {})).toEqual({ command: `'node' 'cli.js'`, port: 18473, machineId: 'machine-7', autonomousEnv: 'staging' })})it('reads and writes the account\'s backend under /api/, signed in by the core, and nothing else', async () => {@@ -70,6 +70,30 @@ describe('what an experiment in its own process may ask of the core', () => {expect(backend).toHaveBeenCalledOnce()})+ it('has Share\'s welcomes signed by the key the gateway holds, and says why it could not', async () => {+ const publicKey = vi.fn(async () => 'cHVi')+ const signWelcome = vi.fn(async () => 'c2ln')+ const core = fakeCore({ account: { observerKey: { publicKey, signWelcome } } })+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'observer_key', { op: 'public' })).toEqual({ key: 'cHVi' })+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'observer_key', { op: 'sign', machineId: 'm', shareId: 's', peer: 'p', ephemeral: 'e' })).toEqual({ key: 'c2ln' })+ expect(signWelcome).toHaveBeenCalledWith('m', 's', 'p', 'e')+ signWelcome.mockRejectedValueOnce(new Error('not a welcome to an observer'))+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'observer_key', {})).toEqual({ error: 'not a welcome to an observer' })+ publicKey.mockRejectedValueOnce('odd')+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'observer_key', { op: 'public' })).toEqual({ error: 'odd' })+ })++ it('sends Share\'s sealed frame to one of its observers, and nothing that is not one', async () => {+ const observer = vi.fn(() => true)+ const core = fakeCore({ clients: { observer } })+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'observer_send', { connId: 'observer:ken', type: 'observer_frame', payload: { __e2e: {} } })).toEqual({ sent: true })+ expect(observer).toHaveBeenCalledWith('observer:ken', 'observer_frame', { __e2e: {} })+ for (const bad of [{ connId: 'remote-1', type: 'observer_frame', payload: {} }, { connId: 'observer:ken', type: 'agents_list', payload: {} }, { connId: 'observer:ken', type: 'observer_frame' }]) {+ expect(await answerExperimentQuery(core, experiments, 'orchestrator', 'observer_send', bad)).toEqual({ error: 'INVALID_FRAME' })+ }+ expect(observer).toHaveBeenCalledOnce()+ })+it('answers none of these for a process that is not an experiment, and leaves other queries to whoever answers them', async () => {const core = fakeCore()expect(await answerExperimentQuery(core, experiments, 'gateway', 'create', {})).toEqual({ error: 'NOT_AN_EXPERIMENT' })diff --git a/cli/src/core/experimentQueries.ts b/cli/src/core/experimentQueries.tsindex bae77f73a..6da4ddaae 100644--- a/cli/src/core/experimentQueries.ts+++ b/cli/src/core/experimentQueries.ts@@ -10,7 +10,10 @@* - `windows`: a change notice for every window on this computer (`orchestrator_changed`);* - `daemon`: how an agent's shell reaches this daemon, for the prompts the experiment writes;* - `backend`: a read or write of the account's backend under `/api/`, signed in by the core, which holds the- * sign-in (Tab collaboration's tab channels).+ * sign-in (Tab collaboration's tab channels);+ * - `observer_key`: this machine's public key, or its signature on a welcome to one observer of one share, by+ * the gateway, which holds the identity (Share's owner);+ * - `observer_send`: a frame Share sealed for one of its observers, to the relay through the gateway.* The core answers them only for the experiments (core/api.ts `EXPERIMENTS`): creating an agent or* telling the windows something is no other process's to ask. The process's side is* services/processCoreApi.ts.@@ -21,7 +24,7 @@ import type { AgentCreateRequest, CoreApi } from './api.js'type Payload = Record<string, unknown>type Core = Pick<CoreApi, 'agents' | 'turns' | 'clients' | 'daemon' | 'account'>-const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'windows', 'daemon', 'backend'])+const QUERIES: ReadonlySet<string> = new Set(['shown', 'create', 'stop_turn', 'windows', 'daemon', 'backend', 'observer_key', 'observer_send'])const METHODS: ReadonlySet<string> = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])const text = (value: unknown): string => (typeof value === 'string' ? value : '')@@ -66,8 +69,20 @@ export async function answerExperimentQuery(core: Core, experiments: ReadonlySetif (!METHODS.has(method) || !path.startsWith('/api/')) return { error: 'INVALID_REQUEST' }return { ...await core.account.backend(method, path, payload.body) }}+ case 'observer_key':+ try {+ if (payload.op === 'public') return { key: await core.account.observerKey.publicKey() }+ return { key: await core.account.observerKey.signWelcome(text(payload.machineId), text(payload.shareId), text(payload.peer), text(payload.ephemeral)) }+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error) }+ }+ case 'observer_send': {+ const connId = text(payload.connId), type = text(payload.type)+ if (!connId.startsWith('observer:') || !type.startsWith('observer_') || !payload.payload || typeof payload.payload !== 'object') return { error: 'INVALID_FRAME' }+ return { sent: core.clients.observer(connId, type, payload.payload as Payload) }+ }default:- return { command: core.daemon.command, port: core.daemon.port, machineId: core.daemon.machineId() }+ return { command: core.daemon.command, port: core.daemon.port, machineId: core.daemon.machineId(), autonomousEnv: core.daemon.autonomousEnv }}}diff --git a/cli/src/core/gatewayLink.spec.ts b/cli/src/core/gatewayLink.spec.tsindex b74cd8f47..5b949ceed 100644--- a/cli/src/core/gatewayLink.spec.ts+++ b/cli/src/core/gatewayLink.spec.ts@@ -251,6 +251,21 @@ describe('the gateway in its own process, as the core sees it', () => {expect(await link.ops.wifi({ op: 'revoke', id: 'x' })).toMatchObject({ refused: { code: 'UNAVAILABLE' } })})+ it('asks the gateway for Share\'s owner\'s key, and says none is held while it cannot answer', async () => {+ let answer: Record<string, unknown> = { key: 'cHVi' }+ const { link, call } = setup({ call: async () => answer })+ expect(await link.ops.observerKey.publicKey()).toBe('cHVi')+ expect(call).toHaveBeenLastCalledWith(GATEWAY_CALLS.observerKey, { op: 'public' }, LANE_WAIT_MS)+ expect(await link.ops.observerKey.signWelcome('m', 's', 'cA==', 'ZQ==')).toBe('cHVi')+ expect(call).toHaveBeenLastCalledWith(GATEWAY_CALLS.observerKey, { op: 'sign', machineId: 'm', shareId: 's', peer: 'cA==', ephemeral: 'ZQ==' }, LANE_WAIT_MS)+ answer = { error: 'not a welcome to an observer' }+ await expect(link.ops.observerKey.signWelcome('m', 's', 'x', 'y')).rejects.toThrow('not a welcome to an observer')+ for (const error of ['SERVICE_UNAVAILABLE', 'SERVICE_FAILED', undefined]) {+ answer = error ? { error } : {}+ await expect(link.ops.observerKey.publicKey()).rejects.toThrow(/not running/)+ }+ })+it('carries the fleet\'s lane to the gateway\'s sessions, every step a call in order, and never a frame back unsealed', async () => {let answer: Record<string, unknown> = {}const { link, call } = setup({ call: async () => answer })diff --git a/cli/src/core/gatewayLink.ts b/cli/src/core/gatewayLink.tsindex 6a7bb934b..cd2855c4e 100644--- a/cli/src/core/gatewayLink.ts+++ b/cli/src/core/gatewayLink.ts@@ -171,6 +171,14 @@ export function createGatewayLink(deps: GatewayLinkDeps) {drop: (machineId) => { void lane('drop', { machineId }) },}+ /** Share's owner's key, held by the gateway (gateway/observerKey.ts): each a call; none while it is away. */+ const ownerKey = async (payload: Record<string, unknown>): Promise<string> => {+ const answer = await deps.call(GATEWAY_CALLS.observerKey, payload, LANE_WAIT_MS)+ if (typeof answer.key === 'string') return answer.key+ // Its process down, or its gateway not started yet: no key to sign with.+ throw new Error(typeof answer.error === 'string' && !answer.error.startsWith('SERVICE_') ? answer.error : 'the gateway holds no key just now: it is not running')+ }+const ops: GatewayOps = {status: async (): Promise<GatewayStatus> => {const answer = await deps.call(GATEWAY_CALLS.status, {}, 2_000)@@ -211,6 +219,10 @@ export function createGatewayLink(deps: GatewayLinkDeps) {account: (next) => { send('account', { account: next }) },reachable: (machineIds) => { reachable = machineIds; send('reachable', { machineIds }) },lane: laneOps,+ observerKey: {+ publicKey: () => ownerKey({ op: 'public' }),+ signWelcome: (machineId, shareId, peer, ephemeral) => ownerKey({ op: 'sign', machineId, shareId, peer, ephemeral }),+ },}/** A window's session through the gateway: to another of the owner's machines, or to a harness shareddiff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex b4de95b3d..a8a3d5664 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -11,10 +11,6 @@*/import { ensureBundledCoreHarnesses } from '../dsh/builtins.js'import { createDeviceStore, deviceStoreAgents } from '../lib/autonomous-device/storeRuntime.js'-import { HarnessShareOwner } from '../sharing/owner.js'-import { HarnessGrantStore } from '../sharing/grants.js'-import { HarnessCollaborationStore } from '../sharing/collaboration.js'-import { SharedViewerPool } from '../sharing/viewer.js'import { runningDevicePart, startDevicePart } from '../lib/autonomous-device/parts.js'import { readFileSync, writeFileSync, openSync, existsSync, rmSync, statSync } from 'fs'import { join } from 'path'@@ -128,7 +124,7 @@ import { createAgentUpdate } from './agents/update.js'import { createEngineHooks, installEngineHooks } from './engines/hooks.js'import { createCursorTaskHooks } from './engines/cursorTasks.js'import { databaseHistory } from './transcripts/databaseHistory.js'-import { createCoreApi, emptyPorts, EXPERIMENTS, FLEET_FALLBACKS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'+import { createCoreApi, emptyPorts, EXPERIMENTS, FLEET_FALLBACKS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type TeamsPort } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { startStalls } from './stall.js'import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'@@ -139,6 +135,8 @@ import { createStoreLink } from './storeLink.js'import { createModelsLink } from './modelsLink.js'import { answerAgentQuery } from './agentQueries.js'import { createDeliveries } from './deliveries.js'+import { createTerminalWatch } from './terminalWatch.js'+import { createSharingLink } from './sharingLink.js'import { createExperimentHooks, wakeExperiments } from './experiments.js'import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'import { createOrchestratorLink } from './orchestratorLink.js'@@ -162,7 +160,6 @@ import { WindowVisit } from '../cable/windowVisit.js'import { WindowForm } from '../cable/windowForm.js'import { TERMINAL_BINARY_VERSION } from '../lib/terminalBinary.js'import { setVoiceRouterDeviceConnected, setVoiceRouterSessions, shutdownVoiceRouter } from '../lib/voiceRouter.js'-import { E2eeStore } from '../lib/e2ee/store.js'import { isLoopbackRequest, loopbackHosts } from '../lib/loopbackRequest.js'import { startSelfUpdater, restore as restoreUpdate, DOWNLOAD_LIMITS, type Poller } from '../lib/selfUpdate.js'import { managedNodePath } from '../lib/nodeRuntime.js'@@ -626,6 +623,9 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The core's side of the boundary its services stand on, and the ports it reaches them through (core/api.ts).// Delivered turns (core/deliveries.ts): text a feature writes into an agent under a delivery id of its// own, and what becomes of each, told back to whoever made it, in this process or in its own.+ // A read-only view of agents' terminals for an experiment's viewers, told to its process (core/terminalWatch.ts).+ const terminalWatch = createTerminalWatch({ terminals, resolve: (id) => registry.resolve(id), watchers: new Set(Object.keys(EXPERIMENTS)),+ tell: (service, viewer, output) => serviceLinksRef?.notify(service, { type: 'service_event', payload: { kind: 'watch', viewer, output } }) ?? false })const deliveries = createDeliveries({submit: (agentId, text, deliveryId) => backendRef?.onMessage?.(agentId, text, deliveryId),cancel: (deliveryId) => backendRef?.onCancelOrchestratorMessage?.(deliveryId) ?? false,@@ -634,7 +634,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {deliverers: new Set(Object.keys(EXPERIMENTS)),})const coreApi = createCoreApi({- terminals: createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }),+ // Agents' terminals: a literal-argv launch, and a read-only view for Share's observers (core/terminalWatch.ts).+ terminals: { ...createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder: (cwd) => !!backendRef?.purgeAgentService?.blocksFolder(cwd) }), watch: terminalWatch.watch },dataDir: env.ADAPTER_DATA_DIR,registry,stoppedAgents,@@ -678,7 +679,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {create: (request) => createForExperiment(backendRef?.onCreateAgent ?? null, request),dsh: (session) => backendRef?.dshFrameProvider?.(session) ?? null,windows: (frame) => backendRef?.sendLocal(frame),- daemon: { command: daemonCommand(), port: env.PORT, machineId: () => backendRef?.machineId ?? '' },+ daemon: { command: daemonCommand(), port: env.PORT, machineId: () => backendRef?.machineId ?? '', autonomousEnv: session?.autonomousEnv ?? env.AUTONOMOUS_ENV },+ // Share: its observers' frames to the relay, and its welcomes signed by the gateway, which holds the identity.+ observer: (connId, type, payload) => backendRef?.sendObserver(connId, type, payload) ?? false,+ observerKey: { publicKey: () => gatewayOps.observerKey.publicKey(), signWelcome: (...args) => gatewayOps.observerKey.signWelcome(...args) },// The same path the window's `agent_fork` takes.fork: async (agentId) => {if (!backendRef?.onForkAgent) return { ok: false, error: 'UNSUPPORTED' }@@ -1127,6 +1131,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {want: (service) => experimentHooks.want(service),answer: async (service, query, payload) => deliveries.answer(service, query, payload)?? await answerExperimentQuery(coreApi, experiments, service, query, payload)+ ?? await terminalWatch.answer(service, query, payload)?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)?? (service === 'viewers' ? viewersLink.answer(query, payload): service === 'workspaces' ? workspacesLink.answer(query, payload)@@ -1141,7 +1146,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (service === 'gateway') gatewayLink?.connected()if (service === 'teams') teamsLink.on()},- disconnected: (service) => { if (service === 'gateway') gatewayLink?.disconnected() },+ disconnected: (service) => {+ if (service === 'gateway') gatewayLink?.disconnected()+ void terminalWatch.gone(service)+ },})serviceLinksRef = serviceLinks// A request a service declared goes to it: in its own process, or in this one (core/serviceHost.ts).@@ -1172,6 +1180,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (outOfProcess.has('orchestrator')) ports.orchestrator = orchestratorLink.portelse serviceHost.start('orchestrator', inline!.startOrchestrator, coreApi, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS)backend.onFrameSent = (frame) => ports.orchestrator?.frame(frame)+ // Share (services/sharing.ts): in this process, or in its own once it is on (core/sharingLink.ts). Its+ // observers' frames reach it as the relay hands them over.+ if (outOfProcess.has('sharing')) ports.sharing = createSharingLink({ call: (type, payload) => serviceLinks.call('sharing', type, payload), notify: (frame) => serviceLinks.notify('sharing', frame) })+ else serviceHost.start('sharing', inline!.startSharing, coreApi, SHARING_FALLBACKS, SHARE_REQUESTS)+ backend.observers = { receive: (connId, type, payload) => ports.sharing?.observer(connId, type, payload), closeAll: () => ports.sharing?.linkDown() }// Tab collaboration and teams (services/collaboration.ts): in their own process, or in this one behind the// service host's guard (a fault there costs no message its write), the prompt scopes the service's own.if (teamsOut) ports.teams = teamsLink.scopes@@ -1430,27 +1443,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {return result}- // Built HERE rather than beside the cable stack that also uses it (further down), because the hook- // server starts long before that point and agent restore can sit between the two. A cache bound late- // is a cache that is still null exactly when a cold boot during an outage needs it most.- const sharingIdentity = new E2eeStore()- sharingIdentity.init()- const sharedViewers = new SharedViewerPool((agentId) => {- const agent = registry.resolve(agentId)- return agent ? backend.dshFrameProvider?.(agent)?.viewerUrl ?? null : null- })- backend.harnessSharing = new HarnessShareOwner({- machineId: () => backend.machineId,- identity: sharingIdentity.getIdentity(),- grants: new HarnessGrantStore(join(env.ADAPTER_DATA_DIR, 'harness-shares.json')),- collaboration: new HarnessCollaborationStore(join(env.ADAPTER_DATA_DIR, 'harness-collaboration.json')),- autonomousEnv,- terminals, resolveAgent: (id) => registry.resolve(id),- send: (id, type, payload) => backend.sendObserver(id, type, payload),- publish: (method, path, body) => proxyBackend(method, path, body),- watchViewer: (id, send) => sharedViewers.watch(id, send),- })-/*** The machine list a signed-out daemon answers with: this computer, alone.*@@ -2445,7 +2437,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The FIXED hook port, released before the successor binds it (no fallback → EADDRINUSE otherwise).// Process-owned agents stay in the persisted registry and are revalidated by its first discovery passes.['the hook connections', () => (hookServer as unknown as { closeAllConnections?: () => void }).closeAllConnections?.()],- ['the shared viewers', () => sharedViewers.stop()],+ ['Share', () => ports.sharing?.stop()],['the local websocket', () => localWsServer.close()], ['the hook server', () => hookServer.close()],['the local socket', () => localSocket?.close()], ['Codex activity', () => codexActivity.close()],['the voice router', () => shutdownVoiceRouter()],@@ -2483,7 +2475,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {normalizers.stopPollers()await cursorDiscovery.stop()await watcher.stop()- sharedViewers.stop()+ await ports.sharing?.stop()// The data folder's socket first: a successor waiting for this core to leave (lib/localSocket.ts) can// start as soon as it is gone, whatever the clients below take to close.await localSocket?.close()diff --git a/cli/src/core/sharingLink.spec.ts b/cli/src/core/sharingLink.spec.tsnew file mode 100644index 000000000..0a2ffe5ea--- /dev/null+++ b/cli/src/core/sharingLink.spec.ts@@ -0,0 +1,15 @@+import { describe, expect, it, vi } from 'vitest'+import { createSharingLink } from './sharingLink.js'++describe('Share in its own process, as the core sees it', () => {+ it('hands it each observer\'s frame as a call, which wakes it while it is off, and the relay gone as a notice', async () => {+ const call = vi.fn(async () => ({}))+ const notify = vi.fn(() => true)+ const port = createSharingLink({ call, notify })+ await port.observer('observer:ken', 'observer_open', { shareId: 's' })+ expect(call).toHaveBeenCalledWith('observer', { connId: 'observer:ken', type: 'observer_open', payload: { shareId: 's' } })+ port.linkDown()+ expect(notify).toHaveBeenCalledWith({ type: 'service_event', payload: { kind: 'linkDown' } })+ expect(port.stop()).toBeUndefined()+ })+})diff --git a/cli/src/core/sharingLink.ts b/cli/src/core/sharingLink.tsnew file mode 100644index 000000000..2b7821e8c--- /dev/null+++ b/cli/src/core/sharingLink.ts@@ -0,0 +1,25 @@+/**+ * Share in its own process, as the core sees it (an experiment, step 8; the process's side is+ * services/sharingProcess.ts). The core tells it two things, both from the relay: an observer's frame, which+ * asks for Share's process if it is off (an observer of a share saved here), and the relay's link gone, with+ * every observer on it. Nothing is held for it while it is down: an observer whose frame finds no Share is+ * answered by its own timeout, as one whose owner went offline.+ */+import type { SharingPort } from './api.js'+import type { ServiceFrame } from './serviceLinks.js'++export interface SharingLinkDeps {+ /** Ask Share's process (core/serviceLinks.ts `call`, for `sharing`): it asks the master for it while it is off. */+ call(type: string, payload: Record<string, unknown>): Promise<Record<string, unknown>>+ /** Tell Share's process something (core/serviceLinks.ts `notify`, for `sharing`). */+ notify(frame: ServiceFrame): boolean+}++export function createSharingLink(deps: SharingLinkDeps): SharingPort {+ return {+ observer: async (connId, type, payload) => { await deps.call('observer', { connId, type, payload }) },+ linkDown: () => { deps.notify({ type: 'service_event', payload: { kind: 'linkDown' } }) },+ // Its process is the master's to stop.+ stop: () => {},+ }+}diff --git a/cli/src/core/terminalWatch.spec.ts b/cli/src/core/terminalWatch.spec.tsnew file mode 100644index 000000000..14849d663--- /dev/null+++ b/cli/src/core/terminalWatch.spec.ts@@ -0,0 +1,118 @@+import { describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../lib/registry.js'+import type { TerminalStreamSink } from '../lib/terminalTypes.js'+import type { TerminalStreamManager } from '../lib/terminalStreamManager.js'+import { createTerminalWatch, KEPT_VIEWERS, type TerminalWatchDeps } from './terminalWatch.js'++type Manager = ConstructorParameters<typeof TerminalStreamManager>[0]++/** A stream manager the spec drives: it records what it was handed and how it was built. */+function manager() {+ const built: Manager[] = []+ const handled: Array<[string, string, Record<string, unknown>]> = []+ const closed: string[] = []+ const stop = vi.fn(async () => {})+ const make = (deps: Manager) => {+ built.push(deps)+ return {+ handleFrame: vi.fn(async (viewer: string, type: string, payload: Record<string, unknown>) => { handled.push([viewer, type, payload]); return true }),+ closeConnection: vi.fn(async (viewer: string) => { closed.push(viewer) }),+ stop,+ }+ }+ return { built, handled, closed, stop, make }+}++const setup = (over: Partial<TerminalWatchDeps> = {}) => {+ const m = manager()+ const tell = vi.fn(() => true)+ const agent = { agentId: 'agent-1' } as RegisteredSession+ const watch = createTerminalWatch({+ terminals: { openStream: vi.fn() } as never,+ resolve: (id) => (id === 'agent-1' ? agent : undefined),+ tell,+ watchers: new Set(['sharing']),+ manager: m.make as never,+ ...over,+ })+ return { watch, tell, m, agent }+}++describe('a read-only view of agents\' terminals', () => {+ it('builds no stream manager until its first viewer, and a read-only one then', async () => {+ const { watch, m, agent } = setup()+ expect(m.built).toHaveLength(0)+ await watch.watch.close('observer:none')+ await watch.stop()+ await watch.watch.frame('observer:ken', 'terminal_open', { agentId: 'agent-1' })+ expect(m.built).toHaveLength(1)+ expect(m.built[0]).toMatchObject({ readOnly: true, streamingAvailable: true })+ expect(m.built[0].resolveAgent('agent-1')).toBe(agent)+ expect(m.handled).toEqual([['observer:ken', 'terminal_open', { agentId: 'agent-1' }]])+ await watch.watch.frame('observer:ken', 'terminal_ack', {})+ expect(m.built).toHaveLength(1)+ await watch.stop()+ expect(m.stop).toHaveBeenCalledOnce()+ })++ it('shows a viewer in this process what it is shown, frames and bytes, through each listener until it stops', async () => {+ const { watch, m } = setup()+ const shown: unknown[] = []+ const stop = watch.watch.onOutput((viewer, output) => shown.push([viewer, output]))+ watch.watch.onOutput(() => { throw new Error('one listener failing') })+ await watch.watch.frame('observer:ken', 'terminal_open', {})+ const deps = m.built[0]+ expect(deps.sendTarget('observer:ken', 'terminal_opened', { streamId: 's' })).toBe(true)+ // A terminal's output bytes (kind 2), as the stream manager hands them over.+ expect(deps.sendBinaryTarget('observer:ken', { kind: 2, streamId: '00000000-0000-4000-8000-000000000001', seq: 1, bytes: new Uint8Array([104, 105]), compressed: false } as never)).toBe(true)+ expect(shown[0]).toEqual(['observer:ken', { type: 'terminal_opened', payload: { streamId: 's' } }])+ expect(shown[1]).toEqual(['observer:ken', { binary: expect.any(String) }])+ // A frame the local encoding cannot carry is not sent.+ expect(deps.sendBinaryTarget('observer:ken', { kind: 2, streamId: '00000000-0000-4000-8000-000000000001', seq: -1, bytes: new Uint8Array(), compressed: false } as never)).toBe(false)+ stop()+ })++ it('tells a process\'s viewer what it is shown, and nothing to a viewer no one has', async () => {+ const { watch, tell, m } = setup()+ expect(await watch.answer('sharing', 'watch_frame', { viewer: 'observer:ken', type: 'terminal_open', payload: { agentId: 'agent-1' } })).toEqual({})+ expect(m.handled).toEqual([['observer:ken', 'terminal_open', { agentId: 'agent-1' }]])+ await watch.answer('sharing', 'watch_frame', { viewer: 'observer:ken', type: 'terminal_ack' })+ expect(m.handled[1]).toEqual(['observer:ken', 'terminal_ack', {}])+ const deps = m.built[0]+ expect(deps.sendTarget('observer:ken', 'terminal_opened', {})).toBe(true)+ expect(tell).toHaveBeenCalledWith('sharing', 'observer:ken', { type: 'terminal_opened', payload: {} })+ // No listener and no process: shown to no one.+ expect(deps.sendTarget('observer:nobody', 'terminal_opened', {})).toBe(false)+ expect(await watch.answer('sharing', 'watch_close', { viewer: 'observer:ken' })).toEqual({})+ expect(m.closed).toEqual(['observer:ken'])+ expect(deps.sendTarget('observer:ken', 'terminal_opened', {})).toBe(false)+ })++ it('takes a viewer\'s terminal frames from a watcher alone, and nothing that is not one', async () => {+ const { watch, m } = setup()+ expect(await watch.answer('gateway', 'watch_frame', { viewer: 'v', type: 'terminal_open' })).toEqual({ error: 'NOT_A_WATCHER' })+ expect(await watch.answer('sharing', 'watch_frame', { type: 'terminal_open' })).toEqual({ error: 'INVALID_VIEWER' })+ expect(await watch.answer('sharing', 'watch_frame', { viewer: 'v', type: 'message' })).toEqual({ error: 'INVALID_FRAME' })+ expect(await watch.answer('sharing', 'live', {})).toBeNull()+ expect(m.handled).toEqual([])+ })++ it('stops showing a process\'s viewers when it goes, and remembers the owners of the last viewers only', async () => {+ const { watch, m, tell } = setup({ watchers: new Set(['sharing', 'other']) })+ await watch.answer('sharing', 'watch_frame', { viewer: 'v1', type: 'terminal_open' })+ await watch.answer('other', 'watch_frame', { viewer: 'v2', type: 'terminal_open' })+ await watch.gone('sharing')+ expect(m.closed).toEqual(['v1'])+ for (let i = 0; i < KEPT_VIEWERS; i++) await watch.answer('sharing', 'watch_frame', { viewer: `x${i}`, type: 'terminal_ack' })+ m.built[0].sendTarget('v2', 'terminal_opened', {})+ expect(tell).not.toHaveBeenCalledWith('other', 'v2', expect.anything())+ })++ it('builds the real stream manager when given none', async () => {+ const watch = createTerminalWatch({ terminals: { openStream: vi.fn() } as never, resolve: () => undefined, tell: () => true, watchers: new Set(['sharing']) })+ const sink: TerminalStreamSink[] = []+ await watch.watch.frame('observer:ken', 'terminal_capabilities', {})+ await watch.stop()+ expect(sink).toEqual([])+ })+})diff --git a/cli/src/core/terminalWatch.ts b/cli/src/core/terminalWatch.tsnew file mode 100644index 000000000..d0097b728--- /dev/null+++ b/cli/src/core/terminalWatch.ts@@ -0,0 +1,105 @@+/**+ * A read-only view of agents' terminals for a feature's own viewers (`core.terminals.watch`): Share's+ * observers. The plan's "read-only terminal subscription" (docs/design/2026-10-06-core-boundary-next.md,+ * "Sharing"): Share used to read panes through a stream manager of its own over the core's terminals; now the+ * core runs that manager, read-only, and a feature in its own process hands it each viewer's terminal frames+ * and hears back what each viewer is shown. A viewer can only watch: the manager is read-only, and refuses+ * input before any reaches a pane, as Share's own did.+ *+ * What a viewer is shown goes to whoever asked for it: a listener in the core's process (`onOutput`), or the+ * process that sent the viewer's frames (`tell`). A terminal's bytes go as `binary`, base64 of the local+ * binary frame (lib/terminalBinary.ts `encodeTerminalLocal`), as Share already carried them to its observers.+ */+import type { RegisteredSession } from '../lib/registry.js'+import type { TerminalBackendCoordinator } from '../lib/terminalBackendCoordinator.js'+import { encodeTerminalLocal } from '../lib/terminalBinary.js'+import { TerminalStreamManager } from '../lib/terminalStreamManager.js'+import type { TerminalWatch, TerminalWatchOutput } from './api.js'++type Payload = Record<string, unknown>++/** The most viewers whose process is remembered; past it the oldest is forgotten. Share takes 100 at most. */+export const KEPT_VIEWERS = 1_000++export interface TerminalWatchDeps {+ terminals: Pick<TerminalBackendCoordinator, 'openStream'>+ resolve: (agentId: string) => RegisteredSession | undefined+ /** Tell a process what its viewer is shown; false when it could not be told (the stream then closes). */+ tell: (service: string, viewer: string, output: TerminalWatchOutput) => boolean+ /** The processes that may watch: a viewer is only ever an experiment's. */+ watchers: ReadonlySet<string>+ /** Swapped in tests for a manager they can drive. */+ manager?: (deps: ConstructorParameters<typeof TerminalStreamManager>[0]) => Pick<TerminalStreamManager, 'handleFrame' | 'closeConnection' | 'stop'>+}++const text = (value: unknown): string => (typeof value === 'string' ? value : '')++export function createTerminalWatch(deps: TerminalWatchDeps) {+ const listeners = new Set<(viewer: string, output: TerminalWatchOutput) => void>()+ /** Which process each viewer is a process's, oldest first. */+ const owners = new Map<string, string>()+ const show = (viewer: string, output: TerminalWatchOutput): boolean => {+ const owner = owners.get(viewer)+ if (owner) return deps.tell(owner, viewer, output)+ let shown = false+ for (const listener of listeners) {+ try { listener(viewer, output); shown = true } catch { /* that listener's viewer misses the frame */ }+ }+ return shown+ }+ let manager: Pick<TerminalStreamManager, 'handleFrame' | 'closeConnection' | 'stop'> | null = null+ /** Built at the first viewer: a daemon no one shares costs no stream manager. */+ const streams = () => manager ??= (deps.manager ?? ((d) => new TerminalStreamManager(d)))({+ readOnly: true,+ terminals: deps.terminals as TerminalBackendCoordinator,+ resolveAgent: deps.resolve,+ streamingAvailable: true,+ sendTarget: (viewer, type, payload) => show(viewer, { type, payload }),+ sendBinaryTarget: (viewer, frame) => {+ const bytes = encodeTerminalLocal(frame)+ return bytes !== null && show(viewer, { binary: Buffer.from(bytes).toString('base64') })+ },+ })++ const watch: TerminalWatch = {+ frame: async (viewer, type, payload) => { await streams().handleFrame(viewer, type, payload) },+ close: async (viewer) => {+ await manager?.closeConnection(viewer)+ owners.delete(viewer)+ },+ onOutput: (listener) => {+ listeners.add(listener)+ return () => { listeners.delete(listener) }+ },+ }++ return {+ /** The watch of the core's own `CoreApi`, for a feature in this process. */+ watch,++ /** A process's viewer's frame (`watch_frame`) or its end (`watch_close`): null for any other query. */+ async answer(service: string, query: string, payload: Payload): Promise<Payload | null> {+ if (query !== 'watch_frame' && query !== 'watch_close') return null+ if (!deps.watchers.has(service)) return { error: 'NOT_A_WATCHER' }+ const viewer = text(payload.viewer)+ if (!viewer) return { error: 'INVALID_VIEWER' }+ if (query === 'watch_close') { await watch.close(viewer); return {} }+ const type = text(payload.type)+ if (!type.startsWith('terminal_')) return { error: 'INVALID_FRAME' }+ owners.delete(viewer)+ owners.set(viewer, service)+ if (owners.size > KEPT_VIEWERS) owners.delete(owners.keys().next().value!)+ await watch.frame(viewer, type, payload.payload && typeof payload.payload === 'object' ? payload.payload as Payload : {})+ return {}+ },++ /** A process went: every viewer it had stops being shown anything. */+ async gone(service: string): Promise<void> {+ for (const [viewer, owner] of [...owners]) if (owner === service) await watch.close(viewer)+ },++ async stop(): Promise<void> { await manager?.stop() },+ }+}++export type TerminalWatchLink = ReturnType<typeof createTerminalWatch>diff --git a/cli/src/core/terminals/open.ts b/cli/src/core/terminals/open.tsindex 0d15ba53f..1c0b10b66 100644--- a/cli/src/core/terminals/open.ts+++ b/cli/src/core/terminals/open.ts@@ -12,7 +12,7 @@ export interface TerminalOpenerDeps {blocksFolder(cwd: string): boolean}-export function createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder }: TerminalOpenerDeps): TerminalsPort {+export function createTerminalOpener({ tmuxBackend, registry, announceSession, blocksFolder }: TerminalOpenerDeps): Pick<TerminalsPort, 'open'> {return { open: async ({ argv, cwd }) => {if (!tmuxBackend) return { ok: false, error: 'TMUX_UNAVAILABLE' }if (blocksFolder(cwd)) return { ok: false, error: 'WORKTREE_BUSY' }diff --git a/cli/src/gateway/gatewayProcess.spec.ts b/cli/src/gateway/gatewayProcess.spec.tsindex ee9110fb9..098ae63e6 100644--- a/cli/src/gateway/gatewayProcess.spec.ts+++ b/cli/src/gateway/gatewayProcess.spec.ts@@ -38,6 +38,10 @@ function stubGateway() {rekey: vi.fn(async () => {}), seal: vi.fn(async (_m: string, frame: Record<string, unknown>) => ({ frame: { ...frame, sealed: true } })),open: vi.fn(async () => ({ unreadable: true as const })), drop: vi.fn(),},+ observerKey: {+ publicKey: vi.fn(async () => 'cHVi'),+ signWelcome: vi.fn(async (_m: string, shareId: string) => { if (shareId === 'bad') throw new Error('not a welcome to an observer'); return 'c2ln' }),+ },} satisfies GatewayOpsconst sessions: Array<{ send: ReturnType<typeof vi.fn>; sendBinary: ReturnType<typeof vi.fn>; detach: ReturnType<typeof vi.fn> }> = []const windowRelay = {@@ -283,6 +287,19 @@ describe('the gateway\'s process, spoken to by the core', () => {expect(await lane.seal('m2', { type: 'message' })).toEqual({ lost: true })})+ it('signs Share\'s welcomes with the identity it holds, and none while it is not running', async () => {+ const w = wire()+ const key = w.link.ops.observerKey+ await expect(key.publicKey()).rejects.toThrow(/not running/)+ w.connect()+ expect(await key.publicKey()).toBe('cHVi')+ expect(await key.signWelcome('m', 'share-1', 'cA==', 'ZQ==')).toBe('c2ln')+ expect(w.gateways[0].ops.observerKey.signWelcome).toHaveBeenCalledWith('m', 'share-1', 'cA==', 'ZQ==')+ await expect(key.signWelcome('m', 'bad', 'cA==', 'ZQ==')).rejects.toThrow('not a welcome to an observer')+ w.gateways[0].ops.observerKey.publicKey.mockRejectedValueOnce('odd')+ await expect(key.publicKey()).rejects.toThrow('odd')+ })+it('opens a window\'s session on another machine, carries it both ways, and fails it as the pool did', async () => {const w = wire()w.connect()diff --git a/cli/src/gateway/gatewayProcess.ts b/cli/src/gateway/gatewayProcess.tsindex 4cc3019f2..c34855d3f 100644--- a/cli/src/gateway/gatewayProcess.ts+++ b/cli/src/gateway/gatewayProcess.ts@@ -242,6 +242,16 @@ export function runGatewayService(options: GatewayServiceOptions): ServiceProcesdefault: return { error: 'UNKNOWN_OP' }}},+ // Share's owner's key (gateway/observerKey.ts): its public half, or a welcome signed.+ [GATEWAY_CALLS.observerKey]: async (p: Payload): Promise<Payload> => {+ const key = ops().observerKey+ try {+ if (p.op === 'public') return { key: await key.publicKey() }+ return { key: await key.signWelcome(text(p.machineId), text(p.shareId), text(p.peer), text(p.ephemeral)) }+ } catch (error) {+ return { error: error instanceof Error ? error.message : String(error) }+ }+ },}return (options.run ?? runServiceProcess)({diff --git a/cli/src/gateway/observerKey.spec.ts b/cli/src/gateway/observerKey.spec.tsnew file mode 100644index 000000000..f99a99465--- /dev/null+++ b/cli/src/gateway/observerKey.spec.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest'+import { b64e, newEphemeral, newIdentity } from '../lib/e2ee/core.js'+import { recipientHandshake, signedOwnerHandshake } from '../sharing/crypto.js'+import { b64d } from '../lib/e2ee/core.js'+import { observerKey } from './observerKey.js'++describe('Share\'s owner\'s key, held by the gateway', () => {+ it('says its public half and signs a welcome the observer verifies, holding the private half to itself', async () => {+ const identity = newIdentity()+ const key = observerKey(() => identity)+ expect(await key.publicKey()).toBe(b64e(identity.pub))+ const ephemeral = newEphemeral()+ // The owner's side, as Share in its own process runs it: the signature asked of the gateway.+ const { welcome } = await signedOwnerHandshake({+ publicKey: async () => b64d(await key.publicKey()),+ signWelcome: async (machineId, shareId, peer, ours) => b64d(await key.signWelcome(machineId, shareId, b64e(peer), b64e(ours))),+ }, 'machine', 'share-1', b64e(ephemeral.pub))+ expect(() => recipientHandshake(ephemeral, 'machine', 'share-1', b64e(identity.pub), welcome)).not.toThrow()+ // Bound to its share: another share's observer refuses it.+ expect(() => recipientHandshake(ephemeral, 'machine', 'share-2', b64e(identity.pub), welcome)).toThrow()+ })++ it('signs nothing that is not a welcome to an observer', async () => {+ const key = observerKey(() => newIdentity())+ const key32 = b64e(new Uint8Array(32))+ for (const [machineId, shareId, peer, ours] of [['', 's', key32, key32], ['m', '', key32, key32], ['m', 's', b64e(new Uint8Array(3)), key32], ['m', 's', key32, b64e(new Uint8Array(64))]]) {+ await expect(key.signWelcome(machineId, shareId, peer, ours)).rejects.toThrow('not a welcome')+ }+ })+})diff --git a/cli/src/gateway/observerKey.ts b/cli/src/gateway/observerKey.tsnew file mode 100644index 000000000..0837cf5a4--- /dev/null+++ b/cli/src/gateway/observerKey.ts@@ -0,0 +1,21 @@+/**+ * Share's owner's key, held here with this machine's E2EE identity (`core.account.observerKey`): its public+ * half, and the signature on a welcome to one observer of one share, with the context Share's handshake binds+ * to that share (sharing/crypto.ts `observerContext`). Share, in a process of its own, holds no credential and+ * asks the gateway for each welcome, as the fleet's lane asks it to seal (gateway/lane.ts).+ */+import type { ObserverKey } from '../core/api.js'+import { b64d, b64e, welcomeSig, type Identity } from '../lib/e2ee/core.js'+import { observerContext } from '../sharing/crypto.js'++export function observerKey(identity: () => Identity): ObserverKey {+ return {+ publicKey: async () => b64e(identity().pub),+ signWelcome: async (machineId, shareId, peer, ephemeral) => {+ const theirs = b64d(peer), ours = b64d(ephemeral)+ // A welcome is two X25519 keys; anything else is not one, and is not signed.+ if (!machineId || !shareId || theirs.length !== 32 || ours.length !== 32) throw new Error('not a welcome to an observer')+ return b64e(welcomeSig(identity().priv, observerContext(machineId, shareId), theirs, ours))+ },+ }+}diff --git a/cli/src/gateway/start.ts b/cli/src/gateway/start.tsindex be2264b2d..b30e15051 100644--- a/cli/src/gateway/start.ts+++ b/cli/src/gateway/start.ts@@ -34,6 +34,7 @@ import { RemoteRelayPool } from '../lib/remoteRelay.js'import { HarnessShareRelay, type SharedMachineReference } from '../sharing/relay.js'import { RelayGateway } from './gateway.js'import { LaneSessions } from './lane.js'+import { observerKey } from './observerKey.js'import { shareWindows } from './share.js'/** What the gateway needs of the core, in whichever process it runs. */@@ -128,6 +129,8 @@ export function startGateway(host: GatewayHost): StartedGateway {const relayPeers = new MachinePeerStore()// The fleet's lane's sessions, sealed with the same identity (gateway/lane.ts).const lane = new LaneSessions(() => relayIdentityStore.getIdentity())+ // Share's owner's welcomes, signed with the same identity (gateway/observerKey.ts).+ const ownerKey = observerKey(() => relayIdentityStore.getIdentity())// The trust group and the device key log are built below; the pool's callbacks reach them through these.let groupSyncer: GroupSyncer | null = nulllet devLogSyncer: DeviceLogSyncer | null = null@@ -421,6 +424,7 @@ export function startGateway(host: GatewayHost): StartedGateway {},reachable: (machineIds) => { reachable = machineIds ? new Set(machineIds) : null },lane,+ observerKey: ownerKey,}return {diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex b14f49264..d89d2b412 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -343,6 +343,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// beside them the teams, their mailbox and the tab channels (services/collaborationProcess.ts), each on its// own link to the core. Started only once it is on (core/api.ts `EXPERIMENTS`).teams: { services: ['teams', 'collaboration'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },+ // Share, an experiment (services/sharingProcess.ts): its invitations, its observers' sessions and their+ // ciphers; the headless Chrome it captures a shared viewer in is a process of its own, outside this budget.+ sharing: { services: ['sharing'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true },// The relay and its E2EE (gateway/gatewayProcess.ts): the backend link, every remote client's session,// the terminals' WebRTC channels and their queues. Network, crypto and pure-JS WebRTC, the attack surface,// where a fault costs the remote clients and nothing else (docs/design/2026-10-06-core-boundary-next.md).diff --git a/cli/src/lib/gatewayWire.ts b/cli/src/lib/gatewayWire.tsindex 62fd7b004..e88b6ce83 100644--- a/cli/src/lib/gatewayWire.ts+++ b/cli/src/lib/gatewayWire.ts@@ -61,4 +61,5 @@ export const GATEWAY_CALLS = {devicesRebaseline: 'gateway_devices_rebaseline',wifi: 'gateway_wifi',lane: 'gateway_lane',+ observerKey: 'gateway_observer_key',} as constdiff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 469068a08..f0bea8545 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -34,6 +34,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['store', async () => (await import('./services/storeProcess.js')).runStoreService],['teams', async () => (await import('./services/teamsProcess.js')).runTeamsService],['collaboration', async () => (await import('./services/collaborationProcess.js')).runCollaborationService],+ ['sharing', async () => (await import('./services/sharingProcess.js')).runSharingService],['orchestrator', async () => (await import('./services/orchestratorProcess.js')).runOrchestratorService],['gateway', async () => (await import('./gateway/gatewayProcess.js')).runGatewayService],['models', async () => (await import('./services/modelsProcess.js')).runModelsService],diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.mdindex a41fa9fb7..5adc9e0de 100644--- a/cli/src/services/AGENTS.md+++ b/cli/src/services/AGENTS.md@@ -122,7 +122,7 @@ way back).## Experiments-An experiment (the orchestrator, Tab collaboration; Share next) is a service that costs nothing until it is+An experiment (the orchestrator, Tab collaboration, Share) is a service that costs nothing until it ison: its own process, which the master starts only when the core asks for it (`want`), when one of itsrequests arrives or, as the core starts, when its saved state is in the data folder. Off, nothing of it runs oris loaded anywhere; one failing costs its own process and nothing else. `e2e/experiments.e2e.ts` proves it:@@ -135,7 +135,10 @@ To add one:`src/services/orchestratorProcess.ts`). Its `CoreApi` in its process is `processCoreApi` with `ask`, whichgives it what an experiment acts on the core through (`src/core/experimentQueries.ts`): the agents as theapps are shown them, creating an agent, stopping a turn, delivering turns (`services/turnsLink.ts`), a- change notice for the windows (`<name>_changed`) and how an agent's shell reaches this daemon.+ change notice for the windows (`<name>_changed`) and how an agent's shell reaches this daemon; Share+ also reads the backend as the account (`core.account.backend`) and has its welcomes signed by the gateway+ (`core.account.observerKey`), so it holds no credential, and watches terminals read-only+ (`core.terminals.watch`, `services/watchLink.ts`).2. Its entry in `EXPERIMENTS` (`src/core/api.ts`): its requests and its saved state.3. Its process in `SERVICE_HOSTS` (`src/harnessd/services.ts`) with `onDemand: true`, and its runner in`SERVICE_RUNNERS` (`src/serviceProcess.ts`).diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex 062682ffe..0489ee559 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -7,6 +7,7 @@ import { startMonitor } from './monitor.js'import { startOrchestrator } from './orchestrator.js'import { startProjects } from './projects.js'import { startSearch } from './search.js'+import { startSharing } from './sharing.js'import { startStore } from './store.js'import { startUsage } from './usage.js'import { startViewers } from './viewers.js'@@ -14,6 +15,6 @@ import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startStore, startTeamsInCore, startUsage, startViewers, startWorkspaces })+ expect({ ...inline }).toEqual({ startGateway, startModels, startMonitor, startOrchestrator, startProjects, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex e680e9021..051e1abba 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -19,6 +19,7 @@ export { startMonitor } from './monitor.js'export { startOrchestrator } from './orchestrator.js'export { startProjects } from './projects.js'export { startSearch } from './search.js'+export { startSharing } from './sharing.js'export { startStore } from './store.js'export { startUsage } from './usage.js'export { startViewers } from './viewers.js'diff --git a/cli/src/services/modelsProcess.spec.ts b/cli/src/services/modelsProcess.spec.tsindex 3a40bd731..a42da13ee 100644--- a/cli/src/services/modelsProcess.spec.ts+++ b/cli/src/services/modelsProcess.spec.ts@@ -247,6 +247,7 @@ describe('the core API models runs on in its own process', () => {api.clients.viewerChanged('a1')api.clients.dshInstallStatus({})api.clients.windows({ type: 'orchestrator_changed', payload: {} })+ expect(api.clients.observer('observer:x', 'observer_frame', {})).toBe(false)expect(ask).not.toHaveBeenCalled()})})diff --git a/cli/src/services/modelsProcess.ts b/cli/src/services/modelsProcess.tsindex 448765cda..deb71ba3a 100644--- a/cli/src/services/modelsProcess.ts+++ b/cli/src/services/modelsProcess.ts@@ -110,7 +110,7 @@ export function modelsCoreApi(dataDir: string, ask: (query: string, payload?: PagridNamed: (name) => told('gridNamed', { name }),gridModelsChanged: () => told('gridModelsChanged'),dshInstallStatus: () => {},- windows: () => {},+ windows: () => {}, observer: () => false,},daemon: DAEMON_UNKNOWN,}diff --git a/cli/src/services/processCoreApi.spec.ts b/cli/src/services/processCoreApi.spec.tsindex 235e3ca39..1241fa591 100644--- a/cli/src/services/processCoreApi.spec.ts+++ b/cli/src/services/processCoreApi.spec.ts@@ -96,7 +96,7 @@ describe('the core API a light service runs on in its own process', () => {const shown = { ...agent('a1'), displayName: 'Planner', terminalAvailable: true, dshContext: { viewerUrl: 'http://127.0.0.1:1/', viewerName: 'CAD' } } as unknown as ShownAgentconst api = processCoreApi('/data', 'orchestrator', {live: () => [shown, agent('a2')], ask, deliveries: turnsLink(ask),- daemon: () => ({ command: `'node' 'cli.js'`, port: 18473, machineId: () => 'm' }),+ daemon: () => ({ command: `'node' 'cli.js'`, port: 18473, machineId: () => 'm', autonomousEnv: 'staging' }),})const request = { engine: 'claude' as const, cwd: '/w', dsh: null, prompt: 'p', name: 'n', bypassPermission: false }expect(await api.agents.create(request)).toEqual({ ok: true, agentId: 'made' })@@ -127,9 +127,41 @@ describe('the core API a light service runs on in its own process', () => {expect(api.daemon.machineId()).toBe('m')})+ it('has Share\'s welcomes signed and its observers\' frames sent through the core, and watches through the link it is given', async () => {+ const answers: Record<string, Record<string, unknown> | Error> = { observer_key: { key: 'a2V5' }, observer_send: { sent: true } }+ const ask = vi.fn(async (query: string) => {+ const answer = answers[query]+ if (answer instanceof Error) throw answer+ return answer+ })+ const watch = { frame: vi.fn(async () => {}), close: vi.fn(async () => {}), onOutput: vi.fn(() => () => {}) }+ const api = processCoreApi('/data', 'sharing', { ask, watch, daemon: () => ({ command: 'x', port: 1, machineId: () => 'm', autonomousEnv: 'staging' }) })+ expect(await api.account.observerKey.publicKey()).toBe('a2V5')+ expect(await api.account.observerKey.signWelcome('m', 's', 'cA==', 'ZQ==')).toBe('a2V5')+ expect(ask).toHaveBeenCalledWith('observer_key', { op: 'public' })+ expect(ask).toHaveBeenCalledWith('observer_key', { op: 'sign', machineId: 'm', shareId: 's', peer: 'cA==', ephemeral: 'ZQ==' })+ answers.observer_key = { error: 'not a welcome to an observer' }+ await expect(api.account.observerKey.signWelcome('m', 's', 'x', 'y')).rejects.toThrow('not a welcome to an observer')+ answers.observer_key = {}+ await expect(api.account.observerKey.publicKey()).rejects.toThrow('did not answer')+ expect(api.clients.observer('observer:k', 'observer_frame', { a: 1 })).toBe(true)+ answers.observer_send = new Error('the link went')+ expect(api.clients.observer('observer:k', 'observer_frame', {})).toBe(true)+ await new Promise((settle) => setTimeout(settle, 0))+ expect(ask).toHaveBeenCalledWith('observer_send', { connId: 'observer:k', type: 'observer_frame', payload: { a: 1 } })+ expect(api.terminals.watch).toBe(watch)+ expect(api.daemon.autonomousEnv).toBe('staging')+ // Without the core to ask, it signs nothing and sends nothing.+ const alone = processCoreApi('/data', 'sharing')+ expect(alone.clients.observer('observer:k', 'observer_frame', {})).toBe(false)+ await expect(alone.account.observerKey.publicKey()).rejects.toThrow('no E2EE identity')+ expect(alone.daemon.autonomousEnv).toBe('prod')+ })+it('reads the daemon\'s address out of the core\'s answer, and nothing out of anything else', () => {const address = daemonIn({ command: 'harness', port: 18473, machineId: 'm' })!- expect(address).toMatchObject({ command: 'harness', port: 18473 })+ expect(address).toMatchObject({ command: 'harness', port: 18473, autonomousEnv: 'prod' })+ expect(daemonIn({ command: 'harness', port: 18473, machineId: 'm', autonomousEnv: 'staging' })!.autonomousEnv).toBe('staging')expect(address.machineId()).toBe('m')expect(daemonIn({ command: 'harness', port: '18473', machineId: 'm' })).toBeNull()expect(daemonIn({ command: 'harness', port: 18473 })).toBeNull()diff --git a/cli/src/services/processCoreApi.ts b/cli/src/services/processCoreApi.tsindex a0ca90b11..6390b9fc7 100644--- a/cli/src/services/processCoreApi.ts+++ b/cli/src/services/processCoreApi.ts@@ -8,11 +8,12 @@* credential is refused: a service holds none (services/AGENTS.md).** An experiment acts on the core as well (core/experimentQueries.ts): it creates agents, stops a turn,- * delivers turns (services/turnsLink.ts), reads and writes the account's backend and tells the windows it- * changed, each asked of the core over its link (`ask`). The agents it reads come as the apps are shown them (`service_query shown`): each with its+ * delivers turns (services/turnsLink.ts), reads and writes the account's backend, tells the windows it+ * changed and Share's observers what they are shown, and has Share's welcomes signed with this machine's key,+ * each asked of the core over its link (`ask`). The agents it reads come as the apps are shown them (`service_query shown`): each with its* name, whether its terminal is there and its harness's viewer.*/-import { DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, resolveAgent, TERMINALS_OFF, type CoreApi, type DaemonAddress } from '../core/api.js'+import { DAEMON_UNKNOWN, DELIVERIES_OFF, LANE_OFF, OBSERVER_KEY_OFF, resolveAgent, TERMINALS_OFF, type CoreApi, type DaemonAddress, type TerminalWatch } from '../core/api.js'import type { AgentDshContext } from '../lib/agentFrame.js'import type { RegisteredSession } from '../lib/registry.js'import type { turnsLink } from './turnsLink.js'@@ -35,6 +36,8 @@ export interface AgentsView {daemon?: () => DaemonAddress | null/** The account's notices the core tells it (`service_event` kind `notice`), for whoever listens. */onNotice?: CoreApi['account']['onNotice']+ /** The core's read-only view of terminals, for its own viewers (services/watchLink.ts). */+ watch?: TerminalWatch}/** Whether what the core sent is an agent. */@@ -50,7 +53,13 @@ export function agentsIn(answer: Record<string, unknown> | null | undefined): Reexport function daemonIn(answer: Payload | null | undefined): DaemonAddress | null {if (typeof answer?.command !== 'string' || typeof answer.port !== 'number' || typeof answer.machineId !== 'string') return nullconst machineId = answer.machineId- return { command: answer.command, port: answer.port, machineId: () => machineId }+ return { command: answer.command, port: answer.port, machineId: () => machineId, autonomousEnv: typeof answer.autonomousEnv === 'string' ? answer.autonomousEnv : DAEMON_UNKNOWN.autonomousEnv }+}++/** The key the core answered with, or a refusal a caller can read. */+function keyAnswer(answer: Payload): string {+ if (typeof answer.key === 'string') return answer.key+ throw new Error(typeof answer.error === 'string' ? answer.error : 'the gateway did not answer for this machine\'s key')}export function processCoreApi(dataDir: string, service: string, view: AgentsView = {}): CoreApi {@@ -61,7 +70,7 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsViedataDir,// Terminals are launched by the core alone (the shell service, #893): a service in its own process// is refused, never handed a way to start a process outside the core.- terminals: TERMINALS_OFF,+ terminals: { open: TERMINALS_OFF.open, watch: view.watch ?? TERMINALS_OFF.watch },agents: {// The stopped agents are never sent to these services: none of them reads one.all: live,@@ -101,6 +110,11 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsViemintGridName: async () => null,accessToken: () => Promise.reject(new Error(`${service} holds no credential`)),lane: LANE_OFF,+ // Share's owner signs a welcome with this machine's identity, which the gateway holds: asked each time.+ observerKey: ask ? {+ publicKey: async () => keyAnswer(await ask('observer_key', { op: 'public' })),+ signWelcome: async (machineId, shareId, peer, ephemeral) => keyAnswer(await ask('observer_key', { op: 'sign', machineId, shareId, peer, ephemeral })),+ } : OBSERVER_KEY_OFF,privateGridName: async () => null,machineName: () => null,backend: async (method, path, body) => {@@ -115,11 +129,19 @@ export function processCoreApi(dataDir: string, service: string, view: AgentsVieclients: {viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {},windows: (frame) => { void ask?.('windows', { frame }).catch(() => {}) },+ // Handed to the core in order; whether the relay took it is the core's to know, and a lost observer's+ // close follows.+ observer: (connId, type, payload) => {+ if (!ask) return false+ void ask('observer_send', { connId, type, payload }).catch(() => {})+ return true+ },},daemon: {get command() { return daemon().command },get port() { return daemon().port },machineId: () => daemon().machineId(),+ get autonomousEnv() { return daemon().autonomousEnv },},}}diff --git a/cli/src/services/searchProcess.spec.ts b/cli/src/services/searchProcess.spec.tsindex aed1fa095..43051daf3 100644--- a/cli/src/services/searchProcess.spec.ts+++ b/cli/src/services/searchProcess.spec.ts@@ -143,6 +143,7 @@ describe('search in its own process', () => {api.clients.gridModelsChanged()api.clients.dshInstallStatus({ phase: 'clone' })api.clients.windows({ type: 'orchestrator_changed', payload: {} })+ expect(api.clients.observer('observer:x', 'observer_frame', {})).toBe(false)})it('runs as a real service process, over the conversations this machine has, by default', () => {diff --git a/cli/src/services/searchProcess.ts b/cli/src/services/searchProcess.tsindex 51ad451ab..bbcfd6044 100644--- a/cli/src/services/searchProcess.ts+++ b/cli/src/services/searchProcess.ts@@ -73,7 +73,7 @@ export function searchCoreApi(machineName: () => null,...ACCOUNT_BACKEND_OFF,},- clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },+ clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false },daemon: DAEMON_UNKNOWN,}}diff --git a/cli/src/services/sharing.spec.ts b/cli/src/services/sharing.spec.tsnew file mode 100644index 000000000..9b326d8b5--- /dev/null+++ b/cli/src/services/sharing.spec.ts@@ -0,0 +1,111 @@+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { emptyPorts, type TerminalWatchOutput } from '../core/api.js'+import { b64d, b64e, newEphemeral, newIdentity, welcomeSig } from '../lib/e2ee/core.js'+import type { RegisteredSession } from '../lib/registry.js'+import { observerContext, recipientHandshake } from '../sharing/crypto.js'+import { fakeCore } from '../testing/fakeCore.js'+import { SHARE_REQUESTS, startSharing, viewerPage, watchStreams } from './sharing.js'++const identity = newIdentity()+const agent = { agentId: 'agent', sessionId: 's', engine: 'codex', active: true } as unknown as RegisteredSession++describe('Share, as a service', () => {+ let dataDir: string+ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'sharing-service-')) })+ afterEach(() => rmSync(dataDir, { recursive: true, force: true }))++ const start = (over: Parameters<typeof fakeCore>[0] = {}) => {+ const outputs: Array<(viewer: string, output: TerminalWatchOutput) => void> = []+ const watch = { frame: vi.fn(async () => {}), close: vi.fn(async () => {}), onOutput: vi.fn((listener: (viewer: string, output: TerminalWatchOutput) => void) => { outputs.push(listener); return () => {} }) }+ const sent: Array<{ connId: string; type: string; payload: any }> = []+ const viewers = { watch: vi.fn((_id: string, send: (frame: Record<string, unknown>) => void) => { send({ state: 'live' }); return vi.fn() }), stop: vi.fn() }+ const core = fakeCore({+ dataDir,+ terminals: { watch },+ agents: {+ resolve: (id: string) => { if (id === 'explode') throw new Error('the registry could not be read'); return id === 'agent' ? agent : undefined },+ dsh: () => ({ viewerUrl: 'http://127.0.0.1:7/' } as never),+ },+ account: {+ observerKey: {+ publicKey: async () => b64e(identity.pub),+ signWelcome: async (machineId, shareId, peer, ephemeral) => b64e(welcomeSig(identity.priv, observerContext(machineId, shareId), b64d(peer), b64d(ephemeral))),+ },+ backend: vi.fn(async () => ({ status: 200, body: {} })),+ },+ clients: { observer: vi.fn((connId: string, type: string, payload: Record<string, unknown>) => { sent.push({ connId, type, payload }); return true }) },+ daemon: { command: 'harness', port: 1, machineId: () => 'machine', autonomousEnv: 'staging' },+ })+ const ports = emptyPorts()+ const requests = startSharing(core, ports, { viewers })+ return { core, ports, port: ports.sharing!, requests, watch, outputs, sent, viewers }+ }++ it('answers its requests, as the socket did, and says Share is unavailable when one fails outright', async () => {+ const { requests, core } = start()+ expect(Object.keys(requests)).toEqual([...SHARE_REQUESTS])+ const asker = { local: true, owner: true }+ const linked = await requests.harness_share_link({ agentId: 'agent', visibility: 'public' }, asker) as { link: { url: string } }+ // The link names the owner's key the gateway holds, and the account's environment.+ expect(linked.link.url).toContain(`key=${encodeURIComponent(b64e(identity.pub))}`)+ expect(linked.link.url).toContain('env=staging')+ expect(core.account.backend).toHaveBeenCalledWith('PUT', expect.stringMatching(/^\/api\/harness-links\//), expect.objectContaining({ visibility: 'public' }))+ vi.mocked(core.account.backend).mockRejectedValueOnce(new Error('offline'))+ expect(await requests.harness_share_list({ agentId: 'nobody' }, asker)).toMatchObject({ error: 'HARNESS_NOT_FOUND' })+ expect(await requests.harness_share_list({ agentId: 'explode' }, asker)).toEqual({ error: 'SHARING_UNAVAILABLE', detail: 'Sharing is temporarily unavailable. Try again.' })+ })++ it('welcomes an observer with a signature the gateway made, and seals what the core\'s streams show it', async () => {+ const { requests, port, watch, outputs, sent, viewers } = start()+ const linked = await requests.harness_share_link({ agentId: 'agent', visibility: 'public' }, { local: true, owner: true }) as { link: { id: string } }+ const ephemeral = newEphemeral()+ await port.observer('observer:ken', 'observer_open', { linkId: linked.link.id, ephemeral: b64e(ephemeral.pub), authorId: 'u1', authorName: 'Ken' })+ const welcome = sent.find((frame) => frame.type === 'observer_welcome')!+ const cipher = recipientHandshake(ephemeral, 'machine', linked.link.id, b64e(identity.pub), welcome.payload)+ await port.observer('observer:ken', 'observer_frame', cipher.seal({ type: 'terminal_open', payload: { agentId: 'agent', requestId: 'r1' } }) as never)+ expect(watch.frame).toHaveBeenCalledWith('observer:ken', 'terminal_open', { agentId: 'agent', requestId: 'r1' })+ for (const listener of outputs) {+ listener('observer:ken', { type: 'terminal_opened', payload: { streamId: 's' } })+ listener('observer:ken', { binary: 'aGk=' })+ }+ const shown = sent.filter((frame) => frame.type === 'observer_frame').map((frame) => cipher.open(frame.payload))+ expect(shown).toEqual([{ type: 'terminal_opened', payload: { streamId: 's' } }, { type: 'observer_binary', payload: { bytes: 'aGk=' } }])+ // Its viewer, captured where Share runs, from the agent's viewer the core shows.+ await port.observer('observer:ken', 'observer_frame', cipher.seal({ type: 'observer_viewer', payload: {} }) as never)+ expect(viewers.watch).toHaveBeenCalledWith('agent', expect.any(Function))+ port.linkDown()+ expect(watch.close).toHaveBeenCalledWith('observer:ken')+ await port.stop()+ expect(viewers.stop).toHaveBeenCalledOnce()+ })++ it('reads its viewers\' pages from the core\'s agents, and starts a pool of its own when given none', async () => {+ const core = fakeCore({ dataDir, agents: { resolve: (id: string) => (id === 'agent' ? agent : undefined), dsh: (session) => (session === agent ? { viewerUrl: 'http://127.0.0.1:7/' } as never : null) } })+ const page = viewerPage(core)+ expect(page('agent')).toBe('http://127.0.0.1:7/')+ expect(page('nobody')).toBeNull()+ const ports = emptyPorts()+ startSharing(core, ports)+ await ports.sharing!.stop()+ expect(viewerPage(fakeCore({ agents: { resolve: () => agent, dsh: () => null } }))('agent')).toBeNull()+ })++ it('hands the owner the core\'s streams: frames to the core, what each viewer is shown back to it', async () => {+ const outputs: Array<(viewer: string, output: TerminalWatchOutput) => void> = []+ const stopHearing = vi.fn()+ const watch = { frame: vi.fn(async () => {}), close: vi.fn(async () => {}), onOutput: vi.fn((listener: (viewer: string, output: TerminalWatchOutput) => void) => { outputs.push(listener); return stopHearing }) }+ const sendTarget = vi.fn(() => true)+ const streams = watchStreams(watch, { sendTarget })+ expect(await streams.handleFrame('v', 'terminal_ack', {})).toBe(true)+ await streams.closeConnection('v')+ expect(watch.close).toHaveBeenCalledWith('v')+ outputs[0]('v', { binary: 'aGk=' })+ outputs[0]('v', { type: 'terminal_closed', payload: {} })+ expect(sendTarget.mock.calls).toEqual([['v', 'observer_binary', { bytes: 'aGk=' }], ['v', 'terminal_closed', {}]])+ await streams.stop()+ expect(stopHearing).toHaveBeenCalledOnce()+ })+})diff --git a/cli/src/services/sharing.ts b/cli/src/services/sharing.tsnew file mode 100644index 000000000..b4a6b7b5c--- /dev/null+++ b/cli/src/services/sharing.ts@@ -0,0 +1,81 @@+/**+ * Share, an experiment: an owner shares a harness with people by email or by link, and they watch its+ * terminal read-only, its viewer, and comment (sharing/owner.ts). Moved out of the core as it was (step 8 of+ * docs/design/2026-10-06-core-boundary-next.md, move only): built on every daemon before, with a 1 s timer and+ * a 30 s publish; now only once it is on (its invitations or links are saved here, or the app asks), in the+ * core's process (`HARNESSD_SERVICES=none`) or in its own (services/sharingProcess.ts).+ *+ * What the core gave it, it gets from the core's API:+ * - its welcomes signed with this machine's identity, which the gateway holds (`core.account.observerKey`):+ * Share holds no credential;+ * - its observers' terminals, read-only, by the core's stream manager (`core.terminals.watch`), what each is+ * shown sealed here and sent on through the gateway (`core.clients.observer`);+ * - its invitations and links published through the account (`core.account.backend`);+ * - the agents it shares, and their viewers, which it captures in headless Chrome itself (sharing/viewer.ts).+ * The observers' frames reach it through its port, as the relay hands them over.+ */+import { join } from 'node:path'+import type { CoreApi, CorePorts, ServiceRequests, TerminalWatch } from '../core/api.js'+import { SHARE_REQUESTS } from '../core/api.js'+import { b64d, b64e } from '../lib/e2ee/core.js'+import { HarnessCollaborationStore } from '../sharing/collaboration.js'+import { HarnessGrantStore } from '../sharing/grants.js'+import { HarnessShareOwner, type ObserverStreams } from '../sharing/owner.js'+import { SharedViewerPool } from '../sharing/viewer.js'++/** The requests Share answers, declared in core/api.ts for the core to route. */+export { SHARE_REQUESTS } from '../core/api.js'++export interface SharingOptions {+ /** The pool that captures a shared viewer; swapped in tests for one that starts no browser. */+ viewers?: Pick<SharedViewerPool, 'watch' | 'stop'>+}++/** The core's read-only streams, as the owner's own stream manager was: frames in, what each observer is shown out. */+export function watchStreams(watch: TerminalWatch, targets: { sendTarget(id: string, type: string, payload: Record<string, unknown>): boolean }): ObserverStreams {+ const stopHearing = watch.onOutput((viewer, output) => {+ if ('binary' in output) targets.sendTarget(viewer, 'observer_binary', { bytes: output.binary })+ else targets.sendTarget(viewer, output.type, output.payload)+ })+ return {+ handleFrame: async (viewer, type, payload) => { await watch.frame(viewer, type, payload); return true },+ closeConnection: (viewer) => watch.close(viewer),+ stop: async () => { stopHearing() },+ }+}++/** The page of an agent's viewer, which Share captures for its observers, as the core shows its agents. */+export const viewerPage = (core: Pick<CoreApi, 'agents'>) => (agentId: string): string | null => {+ const agent = core.agents.resolve(agentId)+ return agent ? core.agents.dsh(agent)?.viewerUrl ?? null : null+}++export function startSharing(core: CoreApi, ports: CorePorts, options: SharingOptions = {}): ServiceRequests {+ const viewers = options.viewers ?? new SharedViewerPool(viewerPage(core))+ const owner = new HarnessShareOwner({+ machineId: () => core.daemon.machineId(),+ key: {+ publicKey: async () => b64d(await core.account.observerKey.publicKey()),+ signWelcome: async (machineId, shareId, peer, ephemeral) => b64d(await core.account.observerKey.signWelcome(machineId, shareId, b64e(peer), b64e(ephemeral))),+ },+ grants: new HarnessGrantStore(join(core.dataDir, 'harness-shares.json')),+ collaboration: new HarnessCollaborationStore(join(core.dataDir, 'harness-collaboration.json')),+ // Read as each link is made: in Share's own process the core says it once connected, after this starts.+ get autonomousEnv() { return core.daemon.autonomousEnv },+ resolveAgent: (id) => core.agents.resolve(id),+ send: (id, type, payload) => core.clients.observer(id, type, payload),+ publish: (method, path, body) => core.account.backend(method, path, body),+ watchViewer: (id, send) => viewers.watch(id, send),+ streams: (targets) => watchStreams(core.terminals.watch, targets),+ })+ ports.sharing = {+ observer: (connId, type, payload) => owner.receive(connId, type, payload),+ linkDown: () => owner.closeAll(),+ stop: async () => {+ await owner.stop()+ viewers.stop()+ },+ }+ return Object.fromEntries(SHARE_REQUESTS.map((type) => [type, (payload: Record<string, unknown>) =>+ owner.manage(type, payload).catch(() => ({ error: 'SHARING_UNAVAILABLE', detail: 'Sharing is temporarily unavailable. Try again.' }))]))+}diff --git a/cli/src/services/sharingProcess.spec.ts b/cli/src/services/sharingProcess.spec.tsnew file mode 100644index 000000000..2172b53a6--- /dev/null+++ b/cli/src/services/sharingProcess.spec.ts@@ -0,0 +1,144 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { CoreApi, CorePorts, SharingPort } from '../core/api.js'+import type { RegisteredSession } from '../lib/registry.js'+import type { CoreConnection, ServiceProcessOptions } from './process.js'+import { AGENTS_FRESH_MS, runSharingService } from './sharingProcess.js'++// The real default reaches a real socket: never in a test.+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))++const OWNER = { local: true, owner: true }+const flush = async () => { for (let i = 0; i < 5; i++) await new Promise((settle) => setTimeout(settle, 0)) }+const agent = (agentId: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: '/w' }) as unknown as RegisteredSession++describe('Share in its own process', () => {+ afterEach(() => vi.clearAllMocks())++ const setup = () => {+ let options: ServiceProcessOptions | null = null+ let api: CoreApi | null = null+ let clock = 10_000+ const ports: SharingPort[] = []+ const order: string[] = []+ const stop = vi.fn()+ const service = runSharingService({+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ now: () => clock,+ run: (given) => { options = given; return { stop } },+ start: (core: CoreApi, given: CorePorts) => {+ api = core+ const port: SharingPort = {+ observer: vi.fn(async (connId: string, type: string) => {+ order.push(`${connId} ${type} start`)+ await flush()+ order.push(`${connId} ${type} end`)+ if (type === 'observer_boom') throw new Error('an unreadable frame')+ if (type === 'observer_odd') throw 'odd'+ }),+ linkDown: vi.fn(),+ stop: vi.fn(async () => {}),+ }+ ports.push(port)+ given.sharing = port+ return { harness_share_list: async (payload) => ({ listed: payload.agentId, env: core.daemon.autonomousEnv, agents: core.agents.live().map((a) => a.agentId) }) }+ },+ })+ return { options: options!, api: () => api!, ports, order, service, stop, tick: (ms: number) => { clock += ms } }+ }+ const core = (answers: Record<string, unknown> = {}) => {+ const asked: Array<[string, Record<string, unknown> | undefined]> = []+ const query = vi.fn(async (name: string, payload?: Record<string, unknown>) => {+ asked.push([name, payload])+ const answer = answers[name]+ if (answer instanceof Error) throw answer+ return (answer ?? {}) as Record<string, unknown>+ })+ return { connection: { query } satisfies CoreConnection, asked, query }+ }++ it('answers its requests on the agents and the daemon as the core shows them as each starts', async () => {+ const { options } = setup()+ expect(options).toMatchObject({ name: 'sharing', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ options.onConnected!(core({ shown: { agents: [agent('a1')] }, daemon: { command: 'x', port: 1, machineId: 'm', autonomousEnv: 'staging' } }).connection)+ expect(await options.requests.harness_share_list!({ agentId: 'a1' }, OWNER)).toEqual({ listed: 'a1', env: 'staging', agents: ['a1'] })+ // A new core that cannot say leaves what the last one said.+ options.onConnected!(core({ shown: new Error('gone'), daemon: new Error('gone') }).connection)+ expect(await options.requests.harness_share_list!({ agentId: 'a1' }, OWNER)).toEqual({ listed: 'a1', env: 'staging', agents: ['a1'] })+ })++ it('takes each observer\'s frames one at a time, in order, and another observer\'s beside them', async () => {+ const { options, order, ports } = setup()+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'm' } }).connection)+ const first = options.requests.observer!({ connId: 'observer:ken', type: 'observer_open', payload: { shareId: 's' } }, OWNER)+ const second = options.requests.observer!({ connId: 'observer:ken', type: 'observer_close' }, OWNER)+ const other = options.requests.observer!({ connId: 'observer:ann', type: 'observer_open' }, OWNER)+ expect(await Promise.all([first, second, other])).toEqual([{}, {}, {}])+ const ken = order.filter((line) => line.startsWith('observer:ken'))+ expect(ken).toEqual(['observer:ken observer_open start', 'observer:ken observer_open end', 'observer:ken observer_close start', 'observer:ken observer_close end'])+ expect(ports[0].observer).toHaveBeenCalledWith('observer:ken', 'observer_open', { shareId: 's' })+ expect(ports[0].observer).toHaveBeenCalledWith('observer:ken', 'observer_close', {})+ expect(await options.requests.observer!({ type: 'observer_open' }, OWNER)).toEqual({ error: 'INVALID_FRAME' })+ })++ it('says why an observer\'s frame failed, and goes on with the next', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ try {+ const { options } = setup()+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'm' } }).connection)+ expect(await options.requests.observer!({ connId: 'observer:ken', type: 'observer_boom' }, OWNER)).toEqual({})+ expect(await options.requests.observer!({ connId: 'observer:ken', type: 'observer_odd' }, OWNER)).toEqual({})+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('an unreadable frame'))+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('odd'))+ } finally {+ warn.mockRestore()+ }+ })++ it('hands the core\'s watch and the relay gone to Share; anything else is not its', async () => {+ const { options, api, ports } = setup()+ const shown = vi.fn()+ api().terminals.watch.onOutput(shown)+ options.onEvent!({ kind: 'watch', viewer: 'observer:ken', output: { binary: 'aGk=' } })+ options.onEvent!({ kind: 'linkDown' })+ options.onEvent!({ kind: 'other' })+ expect(shown).toHaveBeenCalledWith('observer:ken', { binary: 'aGk=' })+ expect(ports[0].linkDown).toHaveBeenCalledOnce()+ })++ it('reads the agents again for its timers once they are a second old, once at a time', async () => {+ const { options, api, tick } = setup()+ const link = core({ shown: { agents: [agent('a1')] } })+ options.onConnected!(link.connection)+ await flush()+ const reads = () => link.asked.filter(([name]) => name === 'shown').length+ const before = reads()+ expect(api().agents.live().map((a) => a.agentId)).toEqual(['a1'])+ expect(reads()).toBe(before)+ tick(AGENTS_FRESH_MS + 1)+ api().agents.live()+ api().agents.live()+ expect(reads()).toBe(before + 1)+ })++ it('starts Share again under the machine a new core serves as, and stops what it runs with the process', async () => {+ const { options, ports, service, stop } = setup()+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'computer' } }).connection)+ await flush()+ options.onConnected!(core({ daemon: { command: 'x', port: 1, machineId: 'account-machine' } }).connection)+ await flush()+ expect(ports).toHaveLength(2)+ expect(ports[0].stop).toHaveBeenCalledOnce()+ options.onDisconnected!()+ expect(await options.requests.harness_share_list!({ agentId: 'a1' }, OWNER)).toMatchObject({ listed: 'a1' })+ await service.stop()+ expect(ports[1].stop).toHaveBeenCalledOnce()+ expect(stop).toHaveBeenCalledOnce()+ })++ it('runs the real Share and process when given neither', async () => {+ const { runServiceProcess } = await import('./process.js')+ const process = runSharingService({ dataDir: '/data-that-is-not-there', socketPath: '/s', machineId: 'm', token: 't' })+ expect(vi.mocked(runServiceProcess).mock.calls.at(-1)![0].requests.harness_share_list).toBeTypeOf('function')+ await process.stop()+ })+})diff --git a/cli/src/services/sharingProcess.ts b/cli/src/services/sharingProcess.tsnew file mode 100644index 000000000..431850e3a--- /dev/null+++ b/cli/src/services/sharingProcess.ts@@ -0,0 +1,129 @@+/**+ * Share in its own process (`harness __service sharing`), an experiment: started only once it is on (core/api.ts+ * `EXPERIMENTS`): its invitations or links are saved here, or the app or an observer asks. The same service as+ * in the core's process (services/sharing.ts), on the core's API as a process reaches it+ * (services/processCoreApi.ts), and holding no credential: each welcome it gives an observer is signed by the+ * gateway (`observer_key`).+ * - An observer's frames come as the relay handed them over (`observer`, the core's call), taken one at a time+ * for each observer, in the order they came: a close that follows an open waits for the open's welcome.+ * - What an observer is shown of a terminal is the core's read-only stream manager's (`watch_frame`, and the+ * core's `watch` events back, services/watchLink.ts); sealed here, it goes to the relay through the core.+ * - The agents it reads as the apps are shown them: asked as each request starts, and whenever its timers read+ * them and they are a second old, since an observer's access is checked every second.+ * - A new core under another machine (a sign-in since) starts Share again: its saved shares are that machine's.+ */+import { emptyPorts, SHARE_REQUESTS, type DaemonAddress, type ServiceRequests, type SharingPort } from '../core/api.js'+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { agentsIn, daemonIn, processCoreApi, type ShownAgent } from './processCoreApi.js'+import { startSharing } from './sharing.js'+import { watchLink } from './watchLink.js'++type Payload = Record<string, unknown>++/** How old the agents it read may be before a timer's next look asks again. */+export const AGENTS_FRESH_MS = 1_000++export interface SharingServiceOptions {+ dataDir: string+ socketPath: string+ machineId: string+ token: string+ /** Swapped in tests for one that does not touch the real socket or process. */+ run?: typeof runServiceProcess+ /** Swapped in tests for a Share that keeps nothing on disk and starts no browser. */+ start?: typeof startSharing+ now?: () => number+}++export function runSharingService(options: SharingServiceOptions): ServiceProcess {+ const now = options.now ?? Date.now+ let core: CoreConnection | null = null+ let live: ShownAgent[] = []+ let readAt = -Infinity+ let daemon: DaemonAddress | null = null+ let askedOn: CoreConnection | null = null+ let reading: Promise<void> | null = null+ const ask = (query: string, payload: Payload): Promise<Payload> =>+ core ? core.query(query, payload) : Promise.reject(new Error('not connected to the core'))+ const readAgents = (): Promise<void> => reading ??= ask('shown', {}).then((answer) => {+ live = (agentsIn(answer) as ShownAgent[] | null) ?? live+ readAt = now()+ }, () => {}).finally(() => { reading = null })+ /** The agents now, and how this daemon is run, asked once per connection; a core that cannot say leaves the last. */+ const ready = async (): Promise<void> => {+ await readAgents()+ if (daemon && askedOn === core) return+ const on = core+ daemon = daemonIn(await ask('daemon', {}).catch(() => null)) ?? daemon+ askedOn = on+ }+ const watch = watchLink(ask)+ const api = processCoreApi(options.dataDir, 'sharing', {+ live: () => { if (now() - readAt > AGENTS_FRESH_MS) void readAgents(); return live },+ ask, daemon: () => daemon, watch: watch.watch,+ })++ const build = () => {+ const ports = emptyPorts()+ const requests = (options.start ?? startSharing)(api, ports)+ return { requests, port: ports.sharing! }+ }+ let built: { requests: ServiceRequests; port: SharingPort } = build()+ let builtFor: string | null = null+ /** Share, for the machine this daemon serves as now; the one under another machine stops. */+ const current = () => {+ const machine = daemon?.machineId() ?? null+ if (machine !== null && builtFor !== null && builtFor !== machine) {+ void built.port.stop()+ built = build()+ }+ if (machine !== null) builtFor = machine+ return built+ }+ /** Each observer's frames, one at a time, in the order the relay handed them over. */+ const inLine = new Map<string, Promise<void>>()+ const observer = (connId: string, type: string, payload: Payload): Promise<void> => {+ const turn = (inLine.get(connId) ?? Promise.resolve())+ .then(() => ready())+ .then(() => current().port.observer(connId, type, payload))+ .catch((error: unknown) => console.warn(`[service sharing] an observer's frame failed · ${error instanceof Error ? error.message : String(error)}`))+ .finally(() => { if (inLine.get(connId) === turn) inLine.delete(connId) })+ inLine.set(connId, turn)+ return turn+ }++ const requests: ServiceRequests = Object.fromEntries(SHARE_REQUESTS.map((type) => [type, async (payload: Payload, asker: { local: boolean; owner: boolean }) => {+ await ready()+ return current().requests[type](payload, asker)+ }]))+ const service = (options.run ?? runServiceProcess)({+ name: 'sharing',+ socketPath: options.socketPath,+ machineId: options.machineId,+ token: options.token,+ requests: {+ ...requests,+ // The core's own call, for an observer's frame as the relay handed it over.+ observer: async (payload) => {+ if (typeof payload.connId !== 'string' || typeof payload.type !== 'string') return { error: 'INVALID_FRAME' }+ await observer(payload.connId, payload.type, payload.payload && typeof payload.payload === 'object' ? payload.payload as Payload : {})+ return {}+ },+ },+ onEvent: (payload) => {+ if (watch.heard(payload)) return+ if (payload.kind === 'linkDown') built.port.linkDown()+ },+ onConnected: (connection) => {+ core = connection+ void ready().then(() => { current() })+ },+ onDisconnected: () => { core = null },+ })+ return {+ stop: async () => {+ await built.port.stop()+ await service.stop()+ },+ }+}diff --git a/cli/src/services/viewersProcess.spec.ts b/cli/src/services/viewersProcess.spec.tsindex eeea57566..97c29286b 100644--- a/cli/src/services/viewersProcess.spec.ts+++ b/cli/src/services/viewersProcess.spec.ts@@ -238,6 +238,7 @@ describe('the viewers in their own process', () => {api.clients.gridModelsChanged()api.clients.dshInstallStatus({ phase: 'clone' })api.clients.windows({ type: 'orchestrator_changed', payload: {} })+ expect(api.clients.observer('observer:x', 'observer_frame', {})).toBe(false)})it('runs as a real service by default: its viewers, on its own link to the core', async () => {diff --git a/cli/src/services/viewersProcess.ts b/cli/src/services/viewersProcess.tsindex d9091ab82..917e94500 100644--- a/cli/src/services/viewersProcess.ts+++ b/cli/src/services/viewersProcess.ts@@ -79,7 +79,7 @@ export function viewersCoreApi(dataDir: string, sessions: ReadonlyMap<string, RemachineName: () => null,...ACCOUNT_BACKEND_OFF,},- clients: { viewerChanged: tell, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },+ clients: { viewerChanged: tell, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false },daemon: DAEMON_UNKNOWN,}}diff --git a/cli/src/services/watchLink.spec.ts b/cli/src/services/watchLink.spec.tsnew file mode 100644index 000000000..07abd578f--- /dev/null+++ b/cli/src/services/watchLink.spec.ts@@ -0,0 +1,40 @@+import { describe, expect, it, vi } from 'vitest'+import { watchIn, watchLink } from './watchLink.js'++describe('the core\'s read-only view of terminals, from a service in its own process', () => {+ it('asks the core for each viewer\'s frames and its end, in order, and a frame the core could not take is lost quietly', async () => {+ const query = vi.fn(async () => ({}))+ const { watch } = watchLink(query)+ await watch.frame('observer:ken', 'terminal_open', { agentId: 'a1' })+ await watch.close('observer:ken')+ expect(query.mock.calls).toEqual([+ ['watch_frame', { viewer: 'observer:ken', type: 'terminal_open', payload: { agentId: 'a1' } }],+ ['watch_close', { viewer: 'observer:ken' }],+ ])+ const gone = watchLink(async () => { throw new Error('the link went') })+ await expect(gone.watch.frame('v', 'terminal_ack', {})).resolves.toBeUndefined()+ await expect(gone.watch.close('v')).resolves.toBeUndefined()+ })++ it('hands what the core says a viewer is shown to each listener, until it stops listening', () => {+ const link = watchLink(async () => ({}))+ const heard = vi.fn()+ const stop = link.watch.onOutput(heard)+ link.watch.onOutput(() => { throw new Error('one listener failing') })+ expect(link.heard({ kind: 'watch', viewer: 'v', output: { type: 'terminal_opened', payload: { streamId: 's' } } })).toBe(true)+ expect(link.heard({ kind: 'watch', viewer: 'v', output: { binary: 'aGk=' } })).toBe(true)+ stop()+ link.heard({ kind: 'watch', viewer: 'v', output: { binary: 'aGk=' } })+ expect(heard.mock.calls).toEqual([['v', { type: 'terminal_opened', payload: { streamId: 's' } }], ['v', { binary: 'aGk=' }]])+ })++ it('takes nothing else for what a viewer is shown', () => {+ expect(watchLink(async () => ({})).heard({ kind: 'delivery' })).toBe(false)+ for (const payload of [+ { kind: 'watch', output: { binary: 'x' } },+ { kind: 'watch', viewer: 'v' },+ { kind: 'watch', viewer: 'v', output: { type: 'x' } },+ { kind: 'watch', viewer: 'v', output: { payload: {} } },+ ]) expect(watchIn(payload)).toBeNull()+ })+})diff --git a/cli/src/services/watchLink.ts b/cli/src/services/watchLink.tsnew file mode 100644index 000000000..44db37ec9--- /dev/null+++ b/cli/src/services/watchLink.ts@@ -0,0 +1,46 @@+/**+ * The core's read-only view of terminals, as a service in its own process reaches it (core/terminalWatch.ts is+ * the core's side): each viewer's terminal frames asked of the core over the link, in order, and what each+ * viewer is shown told back (`service_event` kind `watch`), handed to whoever listens here.+ */+import type { TerminalWatch, TerminalWatchOutput } from '../core/api.js'++type Payload = Record<string, unknown>++/** What the core said a viewer is shown, or null when it is not that. */+export function watchIn(payload: Payload): { viewer: string; output: TerminalWatchOutput } | null {+ if (payload.kind !== 'watch' || typeof payload.viewer !== 'string' || !payload.output || typeof payload.output !== 'object') return null+ const output = payload.output as Payload+ if (typeof output.binary === 'string') return { viewer: payload.viewer, output: { binary: output.binary } }+ if (typeof output.type === 'string' && output.payload && typeof output.payload === 'object') {+ return { viewer: payload.viewer, output: { type: output.type, payload: output.payload as Payload } }+ }+ return null+}++/** `query` asks the core (`CoreConnection.query`, services/process.ts); it rejects when the link goes. */+export function watchLink(query: (query: string, payload: Payload) => Promise<Payload>) {+ const listeners = new Set<(viewer: string, output: TerminalWatchOutput) => void>()+ const watch: TerminalWatch = {+ // A frame the core could not take (the link went) is a viewer's frame lost: its stream closes as the+ // relay's does, and the viewer opens it again.+ frame: async (viewer, type, payload) => { await query('watch_frame', { viewer, type, payload }).catch(() => {}) },+ close: async (viewer) => { await query('watch_close', { viewer }).catch(() => {}) },+ onOutput: (listener) => {+ listeners.add(listener)+ return () => { listeners.delete(listener) }+ },+ }+ return {+ watch,+ /** What the core told this service: true when it was a viewer's output, now heard here. */+ heard(payload: Payload): boolean {+ const shown = watchIn(payload)+ if (!shown) return false+ for (const listener of listeners) {+ try { listener(shown.viewer, shown.output) } catch { /* that listener's viewer misses the frame */ }+ }+ return true+ },+ }+}diff --git a/cli/src/services/workspacesProcess.spec.ts b/cli/src/services/workspacesProcess.spec.tsindex 19c2cc4d1..c2498338a 100644--- a/cli/src/services/workspacesProcess.spec.ts+++ b/cli/src/services/workspacesProcess.spec.ts@@ -182,6 +182,7 @@ describe('workspaces in their own process', () => {api.clients.gridNamed('grid')api.clients.dshInstallStatus({ phase: 'clone' })api.clients.windows({ type: 'orchestrator_changed', payload: {} })+ expect(api.clients.observer('observer:x', 'observer_frame', {})).toBe(false)})it('runs as a real service process, with the real workspaces, by default', () => {diff --git a/cli/src/services/workspacesProcess.ts b/cli/src/services/workspacesProcess.tsindex 86ae50856..8da78d7d6 100644--- a/cli/src/services/workspacesProcess.ts+++ b/cli/src/services/workspacesProcess.ts@@ -81,7 +81,7 @@ export function workspacesCoreApi(machineName: () => null,...ACCOUNT_BACKEND_OFF,},- clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {} },+ clients: { viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {}, windows: () => {}, observer: () => false },daemon: DAEMON_UNKNOWN,}}diff --git a/cli/src/sharing/crypto.ts b/cli/src/sharing/crypto.tsindex 942883797..c23fc5400 100644--- a/cli/src/sharing/crypto.ts+++ b/cli/src/sharing/crypto.ts@@ -29,14 +29,37 @@ export class ObserverCipher {}export function ownerHandshake(identity: Identity, machineId: string, shareId: string, peer: string) {+ const { publicKey, ephemeral, context, cipher } = handshakeKeys(machineId, shareId, peer)+ return { cipher,+ welcome: { ephemeral: b64e(ephemeral.pub),+ signature: b64e(welcomeSig(identity.priv, context, publicKey, ephemeral.pub)) } }+}++/**+ * The owner's key where its private half is another process's: the gateway's, which holds this machine's+ * E2EE identity, when Share runs in a process of its own and holds no credential (services/sharing.ts).+ * It signs a welcome for one observer of one share, and nothing else.+ */+export interface OwnerKey {+ publicKey(): Promise<Uint8Array>+ signWelcome(machineId: string, shareId: string, peer: Uint8Array, ephemeral: Uint8Array): Promise<Uint8Array>+}++/** The same handshake, its welcome signed by the owner's key wherever that is held. */+export async function signedOwnerHandshake(key: OwnerKey, machineId: string, shareId: string, peer: string) {+ const { publicKey, ephemeral, cipher } = handshakeKeys(machineId, shareId, peer)+ return { cipher,+ welcome: { ephemeral: b64e(ephemeral.pub),+ signature: b64e(await key.signWelcome(machineId, shareId, publicKey, ephemeral.pub)) } }+}++function handshakeKeys(machineId: string, shareId: string, peer: string) {const publicKey = b64d(peer)if (publicKey.length !== 32) throw new Error('Invalid observer key')const ephemeral = newEphemeral()const context = observerContext(machineId, shareId)const keys = sessionKeys(ephemeral.priv, publicKey, context, publicKey, ephemeral.pub)- return { cipher: new ObserverCipher(keys.s2c, keys.c2s, context),- welcome: { ephemeral: b64e(ephemeral.pub),- signature: b64e(welcomeSig(identity.priv, context, publicKey, ephemeral.pub)) } }+ return { publicKey, ephemeral, context, cipher: new ObserverCipher(keys.s2c, keys.c2s, context) }}export function recipientHandshake(ephemeral: Ephemeral, machineId: string, shareId: string,diff --git a/cli/src/sharing/owner.ts b/cli/src/sharing/owner.tsindex 41c9e3d72..f67ece00f 100644--- a/cli/src/sharing/owner.ts+++ b/cli/src/sharing/owner.ts@@ -5,19 +5,27 @@ import type { TerminalBackendCoordinator } from '../lib/terminalBackendCoordinatimport { encodeTerminalLocal } from '../lib/terminalBinary.js'import { TerminalStreamManager } from '../lib/terminalStreamManager.js'import { HarnessGrantStore, inviteSchema, type HarnessGrant } from './grants.js'-import { ownerHandshake, type ObserverCipher } from './crypto.js'+import { ownerHandshake, signedOwnerHandshake, type ObserverCipher, type OwnerKey } from './crypto.js'import { HarnessCollaborationStore, linkVisibility, type CommentAuthor } from './collaboration.js'type Payload = Record<string, unknown>interface Observer { grant: HarnessGrant; cipher: ObserverCipher; linkId?: string; author: CommentAuthor | null }+/** What reads an observer's terminal: the owner's own read-only stream manager, or the core's (`streams`). */+export type ObserverStreams = Pick<TerminalStreamManager, 'handleFrame' | 'closeConnection' | 'stop'>+export interface ShareOwnerDeps {machineId: () => string- identity: Identity+ /** This machine's E2EE identity, which the owner signs its welcome with, or the key where it is held+ * (`key`): a Share in a process of its own holds no credential. One of the two. */+ identity?: Identity+ key?: OwnerKeygrants: HarnessGrantStorecollaboration?: HarnessCollaborationStorewebOrigin?: stringautonomousEnv?: string- terminals: TerminalBackendCoordinator+ /** The terminals the owner's own read-only stream manager reads; or the core reads them (`streams`). */+ terminals?: TerminalBackendCoordinator+ streams?: (targets: { sendTarget(id: string, type: string, payload: Payload): boolean }) => ObserverStreamsresolveAgent: (id: string) => RegisteredSession | undefinedsend: (connId: string, type: string, payload: Payload) => booleanpublish: (method: 'PUT' | 'DELETE', path: string, body?: unknown) => Promise<{ status: number; body: unknown }>@@ -29,14 +37,14 @@ export interface ShareOwnerDeps {export class HarnessShareOwner {private readonly observers = new Map<string, Observer>()private readonly viewers = new Map<string, () => void>()- private readonly streams: TerminalStreamManager+ private readonly streams: ObserverStreamsprivate readonly timer: ReturnType<typeof setInterval>private readonly now: () => numberprivate syncing: Promise<void> | null = nullprivate mutation: Promise<unknown> = Promise.resolve()constructor(private readonly deps: ShareOwnerDeps) {this.now = deps.now ?? (() => Date.now())- this.streams = new TerminalStreamManager({ readOnly: true, terminals: deps.terminals,+ this.streams = deps.streams?.({ sendTarget: (id, type, payload) => this.send(id, { type, payload }) }) ?? new TerminalStreamManager({ readOnly: true, terminals: deps.terminals!,resolveAgent: deps.resolveAgent, streamingAvailable: true,sendTarget: (id, type, payload) => this.send(id, { type, payload }),sendBinaryTarget: (id, frame) => {@@ -106,7 +114,9 @@ export class HarnessShareOwner {this.deps.send(connId, 'observer_closed', { reason: 'Sharing ended or invitation expired' }); return}try {- const { cipher, welcome } = ownerHandshake(this.deps.identity, grant.machineId, grant.id, String(payload.ephemeral))+ const { cipher, welcome } = this.deps.key+ ? await signedOwnerHandshake(this.deps.key, grant.machineId, grant.id, String(payload.ephemeral))+ : ownerHandshake(this.deps.identity!, grant.machineId, grant.id, String(payload.ephemeral))this.observers.set(connId, { grant, cipher, author, ...(link ? { linkId: link.id } : {}) })if (!this.deps.send(connId, 'observer_welcome', welcome)) this.close(connId)} catch { this.deps.send(connId, 'observer_closed', { reason: 'Invalid observer handshake' }) }@@ -165,7 +175,7 @@ export class HarnessShareOwner {if (!this.deps.collaboration) return { error: 'UNSUPPORTED' }if (!visibility.success) return { error: 'INVALID_VISIBILITY', detail: 'Choose Public or Private.' }this.deps.collaboration.set({ machineId, agentId, visibility: visibility.data,- name: projectDisplayName(session), engine: session.engine, ownerPublicKey: b64e(this.deps.identity.pub) })+ name: projectDisplayName(session), engine: session.engine, ownerPublicKey: await this.ownerPublicKey() })if (visibility.data === 'off') {for (const grant of this.deps.grants.list(machineId, agentId)) this.deps.grants.revoke(grant.id, machineId, agentId)}@@ -178,7 +188,7 @@ export class HarnessShareOwner {for (const email of new Set(parsed.data.emails)) {this.deps.grants.invite({ machineId, agentId, recipientEmail: email,name: projectDisplayName(session), engine: session.engine,- ownerPublicKey: b64e(this.deps.identity.pub),+ ownerPublicKey: await this.ownerPublicKey(),expiresAt: new Date(this.now() + parsed.data.days * 86400_000).toISOString() })}await this.syncing@@ -208,6 +218,9 @@ export class HarnessShareOwner {watching: [...this.observers.values()].filter(o => o.grant.agentId === agentId && o.grant.recipientEmail === grant.recipientEmail).length,})) }}+ private async ownerPublicKey(): Promise<string> {+ return b64e(this.deps.key ? await this.deps.key.publicKey() : this.deps.identity!.pub)+ }private comments(action: string, agentId: string, author: CommentAuthor | null, payload: Payload): Payload {const store = this.deps.collaborationif (!store) return { error: 'UNSUPPORTED', detail: 'Update Harness on the owner machine to use comments.' }diff --git a/cli/src/sharing/seams.spec.ts b/cli/src/sharing/seams.spec.tsnew file mode 100644index 000000000..d88b4e6d9--- /dev/null+++ b/cli/src/sharing/seams.spec.ts@@ -0,0 +1,68 @@+/**+ * Share in a process of its own (services/sharing.ts): the owner signs with a key it does not hold, and the+ * core reads the observers' terminals. The same owner, the same handshake and the same frames as with the+ * identity and the stream manager in its hands (owner.spec.ts).+ */+import { mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { b64e, newEphemeral, newIdentity, welcomeSig } from '../lib/e2ee/core.js'+import type { RegisteredSession } from '../lib/registry.js'+import { observerContext, recipientHandshake, signedOwnerHandshake, type OwnerKey } from './crypto.js'+import { HarnessGrantStore } from './grants.js'+import { HarnessShareOwner } from './owner.js'++const identity = newIdentity()+/** The owner's key as the gateway holds it: the identity's private half never leaves it. */+const key: OwnerKey = {+ publicKey: async () => identity.pub,+ signWelcome: async (machineId, shareId, peer, ephemeral) => welcomeSig(identity.priv, observerContext(machineId, shareId), peer, ephemeral),+}++describe('Share with its key and its terminals held elsewhere', () => {+ let root: string+ beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'share-seams-')) })+ afterEach(() => rmSync(root, { recursive: true, force: true }))++ it('signs a welcome the observer verifies against the owner\'s published key', async () => {+ const ephemeral = newEphemeral()+ const { cipher, welcome } = await signedOwnerHandshake(key, 'machine', 'share-1', b64e(ephemeral.pub))+ const theirs = recipientHandshake(ephemeral, 'machine', 'share-1', b64e(identity.pub), welcome)+ expect(theirs.open(cipher.seal({ type: 'hello', payload: {} }))).toEqual({ type: 'hello', payload: {} })+ await expect(signedOwnerHandshake(key, 'machine', 'share-1', b64e(new Uint8Array(3)))).rejects.toThrow('Invalid observer key')+ })++ it('invites under the key\'s public half, welcomes with its signature, and hands terminal frames to the streams it was given', async () => {+ const store = new HarnessGrantStore(join(root, 'grants.json'))+ const frames: Array<{ id: string; type: string; payload: any }> = []+ let targets: { sendTarget(id: string, type: string, payload: Record<string, unknown>): boolean } | null = null+ const streams = { handleFrame: vi.fn(async () => true), closeConnection: vi.fn(async () => {}), stop: vi.fn(async () => {}) }+ const agent = { agentId: 'agent', sessionId: 's', engine: 'codex', active: true } as unknown as RegisteredSession+ const owner = new HarnessShareOwner({+ machineId: () => 'machine', key, grants: store, resolveAgent: (id) => (id === 'agent' ? agent : undefined),+ send: (id, type, payload) => { frames.push({ id, type, payload }); return true },+ publish: async () => ({ status: 200, body: {} }),+ streams: (given) => { targets = given; return streams as never },+ })+ try {+ await owner.manage('harness_share_invite', { agentId: 'agent', emails: ['[email protected]'] })+ const grant = store.list('machine', 'agent')[0]+ expect(grant.ownerPublicKey).toBe(b64e(identity.pub))+ const ephemeral = newEphemeral()+ await owner.receive('observer:ken', 'observer_open', { shareId: grant.id, email: '[email protected]', ephemeral: b64e(ephemeral.pub) })+ const welcome = frames.find((f) => f.type === 'observer_welcome')!+ const cipher = recipientHandshake(ephemeral, 'machine', grant.id, b64e(identity.pub), welcome.payload)+ await owner.receive('observer:ken', 'observer_frame', cipher.seal({ type: 'terminal_open', payload: { agentId: 'agent', requestId: 'r1' } }) as never)+ expect(streams.handleFrame).toHaveBeenCalledWith('observer:ken', 'terminal_open', { agentId: 'agent', requestId: 'r1' })+ // What the core's streams have for the observer is sealed to it, as the owner's own were.+ expect(targets!.sendTarget('observer:ken', 'terminal_frame', { bytes: 'x' })).toBe(true)+ expect(cipher.open(frames.at(-1)!.payload)).toEqual({ type: 'terminal_frame', payload: { bytes: 'x' } })+ owner.close('observer:ken')+ expect(streams.closeConnection).toHaveBeenCalledWith('observer:ken')+ } finally {+ await owner.stop()+ }+ expect(streams.stop).toHaveBeenCalledOnce()+ })+})diff --git a/cli/src/testing/fakeCore.ts b/cli/src/testing/fakeCore.tsindex 18033f4cc..1d86041e5 100644--- a/cli/src/testing/fakeCore.ts+++ b/cli/src/testing/fakeCore.ts@@ -11,7 +11,11 @@ type Overrides = { [K in keyof CoreApi]?: CoreApi[K] extends object ? Partial<Coexport function fakeCore(over: Overrides = {}): CoreApi {return {dataDir: over.dataDir ?? '/data',- terminals: { open: vi.fn(TERMINALS_OFF.open), ...over.terminals },+ terminals: {+ open: vi.fn(TERMINALS_OFF.open),+ watch: { frame: vi.fn(async () => {}), close: vi.fn(async () => {}), onOutput: vi.fn(() => () => {}) },+ ...over.terminals,+ },agents: {all: vi.fn(() => []),live: vi.fn(() => []),@@ -55,10 +59,11 @@ export function fakeCore(over: Overrides = {}): CoreApi {privateGridName: vi.fn(async () => null),machineName: vi.fn(() => null),backend: vi.fn(async () => ({ status: 200, body: {} })),+ observerKey: { publicKey: vi.fn(async () => 'cHVi'), signWelcome: vi.fn(async () => 'c2ln') },onNotice: vi.fn(() => () => {}),...over.account,},- clients: { viewerChanged: vi.fn(), gridNamed: vi.fn(), gridModelsChanged: vi.fn(), dshInstallStatus: vi.fn(), windows: vi.fn(), ...over.clients },- daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1', ...over.daemon },+ clients: { viewerChanged: vi.fn(), gridNamed: vi.fn(), gridModelsChanged: vi.fn(), dshInstallStatus: vi.fn(), windows: vi.fn(), observer: vi.fn(() => true), ...over.clients },+ daemon: { command: 'harness', port: 18473, machineId: () => 'machine-1', autonomousEnv: 'prod', ...over.daemon },}}diff --git a/cli/src/testing/teamFixture.ts b/cli/src/testing/teamFixture.tsindex ed4c844a5..d79cd87eb 100644--- a/cli/src/testing/teamFixture.ts+++ b/cli/src/testing/teamFixture.ts@@ -69,8 +69,9 @@ export function attachTeams<T extends BackendSocket>(socket: T): T & TeamFixtureclients: {viewerChanged: () => {}, gridNamed: () => {}, gridModelsChanged: () => {}, dshInstallStatus: () => {},windows: (frame) => socket.sendLocal(frame),+ observer: () => false,},- daemon: { command: 'harness', port: env.PORT, machineId: () => socket.machineId },+ daemon: { command: 'harness', port: env.PORT, machineId: () => socket.machineId, autonomousEnv: 'prod' },})/** Built at its first use, from what the spec set by then. */const collaboration = (): Teams => teams ??= startCollaboration(core(), {