Skip to content

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.

Add account-scoped harness sharing and encrypted observer foundations

Deeb277f1d98fd5
diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma
index f0b69c229..20d833d35 100644
--- a/backend/prisma/schema.prisma
+++ b/backend/prisma/schema.prisma
@@ -555,3 +555,26 @@ model HarnessReview {
@@index([harnessId])
@@map("harness_reviews")
}
+
+/// Discovery metadata for one account-bound, view-only invitation. Content remains on the owner
+/// daemon, which independently authorizes every observer against its durable local grant list.
+model HarnessShare {
+ id String @id @map("_id")
+ ownerId String
+ machineId String
+ agentId String
+ recipientEmail String
+ autonomousEnv String
+ name String
+ engine String?
+ ownerPublicKey String
+ expiresAt DateTime
+ revokedAt DateTime?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@unique([machineId, agentId, recipientEmail])
+ @@index([recipientEmail, autonomousEnv, expiresAt])
+ @@index([ownerId, machineId])
+ @@map("harness_shares")
+}
diff --git a/backend/src/lib/bus.ts b/backend/src/lib/bus.ts
index ee1eb9995..7060777cf 100644
--- a/backend/src/lib/bus.ts
+++ b/backend/src/lib/bus.ts
@@ -210,6 +210,14 @@ export function subscribeDown(machineId: string, cb: (msg: DownBusMsg) => void):
return addSub(downChannel(machineId), cb as Cb)
}
+/** A grant change invalidates observer sockets across backend instances. No content on this channel. */
+export function subscribeShareChanged(id: string, cb: () => void): Promise<() => void> {
+ return addSub(`harness-share:${id}`, cb)
+}
+export function publishShareChanged(id: string): Promise<number> {
+ return safePublish(`harness-share:${id}`, '{}')
+}
+
export function publishUp(machineId: string, msg: UpBusMsg): Promise<number> {
const type = (msg.frame as { type?: unknown } | undefined)?.type
if (typeof type === 'string' && STATUS_TYPES.has(type)) void safePublish(statusChannel(machineId), JSON.stringify(msg.frame))
diff --git a/backend/src/lib/observerWs.ts b/backend/src/lib/observerWs.ts
new file mode 100644
index 000000000..2321cd284
--- /dev/null
+++ b/backend/src/lib/observerWs.ts
@@ -0,0 +1,89 @@
+import { randomUUID } from 'node:crypto'
+import type { IncomingMessage } from 'node:http'
+import type { Duplex } from 'node:stream'
+import { WebSocket, type RawData } from 'ws'
+import { createWss, WS_LIMITS } from './wsServer.js'
+import { authenticateAccessToken, type AuthUser } from './ssoAuth.js'
+import { parseAutonomousEnvironment } from './autonomousEnvironment.js'
+import { extractKey } from '../utils/crypto.js'
+import { recipientShare } from '../routes/harnessShares.js'
+import { publishDown, subscribeUp, subscribeShareChanged } from './bus.js'
+import { guardedSendJson } from './wsSend.js'
+import { trackSocketLiveness } from './hub.js'
+import { createOrderedInbox } from './orderedInbox.js'
+
+const wss = createWss(WS_LIMITS.web, { echoFirstProtocol: true })
+
+export function handleObserverUpgrade(req: IncomingMessage, socket: Duplex, head: Buffer): void {
+ void (async () => {
+ const token = extractKey(req)
+ const url = new URL(req.url ?? '/', 'http://localhost')
+ const id = url.searchParams.get('share') ?? ''
+ if (!token || !/^[a-f0-9-]{36}$/.test(id)) { socket.destroy(); return }
+ const user = await authenticateAccessToken(token, parseAutonomousEnvironment(url.searchParams.get('autonomousEnv')))
+ const share = await recipientShare(id, user)
+ if (socket.destroyed) return
+ wss.handleUpgrade(req, socket, head, ws => {
+ if (!share) { ws.close(4403, 'Sharing ended or invitation expired'); return }
+ void attachObserver(ws, user, share).catch(() => ws.close(1013, 'Sharing temporarily unavailable'))
+ })
+ })().catch(() => { if (!socket.destroyed) socket.destroy() })
+}
+
+/** Separate from the machine hub: no group key, machine inventory, P2P, or generic RPC route. */
+export async function attachObserver(ws: WebSocket, user: AuthUser, share: NonNullable<Awaited<ReturnType<typeof recipientShare>>>): Promise<void> {
+ const connId = `observer:${randomUUID()}`
+ const send = (frame: unknown) => guardedSendJson(ws, frame, 'must')
+ const disposers: Array<() => void> = [trackSocketLiveness(ws)]
+ let closed = false
+ let opened = false
+ const down = (type: string, payload: unknown) => publishDown(share.machineId, { connId, frame: { type, payload } })
+ const close = () => {
+ if (closed) return
+ closed = true
+ for (const dispose of disposers.splice(0)) dispose()
+ void down('observer_close', {}).catch(() => {})
+ }
+ ws.once('close', close)
+ const check = async () => {
+ try {
+ if (!await recipientShare(share.id, user)) ws.close(4403, 'Sharing ended or invitation expired')
+ } catch { ws.close(1013, 'Sharing temporarily unavailable') }
+ }
+ const timer = setInterval(() => { void check() }, 5000)
+ timer.unref()
+ disposers.push(() => clearInterval(timer))
+ const keep = (dispose: () => void) => { if (closed) dispose(); else disposers.push(dispose) }
+ keep(await subscribeShareChanged(share.id, () => { void check() }))
+ keep(await subscribeUp(share.machineId, message => {
+ if (closed) return
+ const frame = message.frame
+ if (frame.type === 'node_status' && (frame.payload as { online?: boolean })?.online === false) {
+ ws.close(1012, 'Owner is offline'); return
+ }
+ if (message.targetConnId !== connId) return
+ if (['observer_welcome', 'observer_frame', 'observer_closed'].includes(String(frame.type))) send(frame)
+ }))
+ if (closed) return
+ await check()
+ if (ws.readyState !== WebSocket.OPEN) return
+ send({ type: 'observer_connected' })
+ // Each message is bounded before decoding; encrypted content is interpreted only on the owner daemon.
+ let windowStart = Date.now(), count = 0
+ const inbox = createOrderedInbox<{ raw: RawData; binary: boolean }>(async ({ raw, binary }) => {
+ if (closed) return
+ if (Date.now() - windowStart >= 1000) { windowStart = Date.now(); count = 0 }
+ if (binary || (Array.isArray(raw) ? raw.reduce((n, b) => n + b.length, 0) : raw.byteLength) > 64 * 1024 || ++count > 120) { ws.close(1008, 'Invalid observer message'); return }
+ let frame: { type?: string; payload?: Record<string, unknown> }
+ try { frame = JSON.parse(raw.toString()) } catch { ws.close(1008, 'Invalid observer message'); return }
+ if (!opened && frame.type === 'observer_hello' && typeof frame.payload?.ephemeral === 'string'
+ && /^[A-Za-z0-9+/]{43}=$/.test(frame.payload.ephemeral)) {
+ opened = true
+ await down('observer_open', { shareId: share.id, email: user.email.trim().toLowerCase(),
+ ephemeral: frame.payload.ephemeral }).catch(() => ws.close(1013, 'Owner unavailable'))
+ } else if (opened && frame.type === 'observer_frame' && frame.payload?.__e2e) {
+ await down('observer_frame', frame.payload).catch(() => ws.close(1013, 'Owner unavailable'))
+ } else ws.close(1008, 'Observer connections are view only')
+ }, () => ws.close(1013, 'Sharing temporarily unavailable'), () => ws.close(1008, 'Too many observer messages'))
+ ws.on('message', (raw, binary) => inbox.enqueue({ raw, binary }))
+}
diff --git a/backend/src/routes/harnessShares.ts b/backend/src/routes/harnessShares.ts
new file mode 100644
index 000000000..8fdb547a0
--- /dev/null
+++ b/backend/src/routes/harnessShares.ts
@@ -0,0 +1,99 @@
+import type { FastifyInstance } from 'fastify'
+import { z } from 'zod'
+import { prisma, machineAlive } from '../lib/prisma.js'
+import { getAgentPresenceMany, publishShareChanged } from '../lib/bus.js'
+import { machineBillingAllowsDataPlane } from '../lib/billingState.js'
+import { validateBody, validateParams } from '../middlewares/validation.js'
+import { sendError, sendSuccess } from '../utils/response.js'
+import type { AuthUser } from '../lib/ssoAuth.js'
+
+const params = z.object({ id: z.string().uuid() })
+const body = z.object({
+ machineId: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/),
+ agentId: z.string().min(1).max(160),
+ recipientEmail: z.string().trim().toLowerCase().email().max(254),
+ name: z.string().trim().min(1).max(160),
+ engine: z.string().max(64).nullable(),
+ ownerPublicKey: z.string().regex(/^[A-Za-z0-9+/]{43}=$/),
+ expiresAt: z.string().datetime().refine(value => {
+ const delta = Date.parse(value) - Date.now()
+ return delta > 0 && delta <= 91 * 24 * 60 * 60_000
+ }, 'Choose an expiry within 90 days.'),
+}).strict()
+
+/** Used again at socket admission and throughout a live connection. Never disclose another grant. */
+export async function recipientShare(id: string, user: AuthUser) {
+ const share = await prisma.harnessShare.findFirst({ where: {
+ id, recipientEmail: user.email.trim().toLowerCase(), autonomousEnv: user.autonomousEnv,
+ revokedAt: null, expiresAt: { gt: new Date() },
+ } })
+ if (!share) return null
+ const machine = await prisma.machine.findFirst({ where: {
+ machineId: share.machineId, userId: share.ownerId, autonomousEnv: user.autonomousEnv, ...machineAlive,
+ } })
+ return machine && machineBillingAllowsDataPlane(machine) ? share : null
+}
+
+export async function harnessShareRoutes(app: FastifyInstance): Promise<void> {
+ app.get('/api/harness-shares', async (req, reply) => {
+ const shares = await prisma.harnessShare.findMany({ where: {
+ recipientEmail: req.user!.email.trim().toLowerCase(), autonomousEnv: req.user!.autonomousEnv,
+ revokedAt: null, expiresAt: { gt: new Date() },
+ }, orderBy: { createdAt: 'asc' }, take: 1000 })
+ const machines = await prisma.machine.findMany({ where: {
+ machineId: { in: [...new Set(shares.map(s => s.machineId))] },
+ autonomousEnv: req.user!.autonomousEnv, ...machineAlive,
+ } })
+ const allowed = machines.filter(machineBillingAllowsDataPlane)
+ const owners = await prisma.user.findMany({ where: { id: { in: [...new Set(allowed.map(m => m.userId))] } },
+ select: { id: true, name: true, email: true } })
+ const presence = await getAgentPresenceMany(allowed.map(m => m.machineId))
+ sendSuccess(reply, { machines: allowed.flatMap(machine => {
+ const grants = shares.filter(s => s.machineId === machine.machineId && s.ownerId === machine.userId)
+ if (grants.length === 0) return []
+ const owner = owners.find(o => o.id === machine.userId)
+ return [{ machineId: machine.machineId, name: machine.name, authMode: 'remote',
+ status: presence.get(machine.machineId) ? 'running' : 'offline',
+ shared: true, ownerName: owner?.name || owner?.email || 'Harness user',
+ shares: grants.map(s => ({ id: s.id, agentId: s.agentId, name: s.name, engine: s.engine,
+ ownerPublicKey: s.ownerPublicKey, expiresAt: s.expiresAt.toISOString() })) }]
+ }) })
+ })
+
+ app.put<{ Params: z.infer<typeof params>; Body: z.infer<typeof body> }>(
+ '/api/harness-shares/:id', { preHandler: [validateParams(params), validateBody(body)] },
+ async (req, reply) => {
+ const input = req.body
+ const machine = await prisma.machine.findFirst({ where: {
+ machineId: input.machineId, userId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv, ...machineAlive,
+ } })
+ if (!machine || !machineBillingAllowsDataPlane(machine)) {
+ return sendError(reply, 'This machine is not available to share.', 'FORBIDDEN', 403)
+ }
+ if (input.recipientEmail === req.user!.email.trim().toLowerCase()) {
+ return sendError(reply, 'You already own this harness.', 'SELF_INVITE', 400)
+ }
+ const existing = await prisma.harnessShare.findUnique({ where: { id: req.params.id } })
+ if (existing && (existing.ownerId !== req.user!.sub || existing.machineId !== input.machineId
+ || existing.agentId !== input.agentId || existing.recipientEmail !== input.recipientEmail)) {
+ return sendError(reply, 'This invitation cannot be changed.', 'FORBIDDEN', 403)
+ }
+ const data = { ...input, expiresAt: new Date(input.expiresAt), revokedAt: null,
+ ownerId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv }
+ await prisma.harnessShare.upsert({ where: { id: req.params.id },
+ create: { id: req.params.id, ...data }, update: data })
+ await publishShareChanged(req.params.id)
+ sendSuccess(reply, { id: req.params.id })
+ },
+ )
+
+ app.delete<{ Params: z.infer<typeof params> }>('/api/harness-shares/:id',
+ { preHandler: [validateParams(params)] }, async (req, reply) => {
+ const changed = await prisma.harnessShare.updateMany({ where: {
+ id: req.params.id, ownerId: req.user!.sub, autonomousEnv: req.user!.autonomousEnv,
+ }, data: { revokedAt: new Date() } })
+ if (!changed.count) return sendError(reply, 'Invitation not found.', 'NOT_FOUND', 404)
+ await publishShareChanged(req.params.id)
+ sendSuccess(reply, { removed: true })
+ })
+}
diff --git a/backend/src/server.ts b/backend/src/server.ts
index 917074d44..e1f21dbf2 100644
--- a/backend/src/server.ts
+++ b/backend/src/server.ts
@@ -9,6 +9,8 @@ import { errorHandler } from './middlewares/errorHandler.js'
import { registerAuthMiddleware } from './middlewares/authMiddleware.js'
import { cursorRoutes } from './routes/cursor.js'
import { voiceRoutes } from './routes/voice.js'
+import { harnessShareRoutes } from './routes/harnessShares.js'
+import { handleObserverUpgrade } from './lib/observerWs.js'
import { deviceAuthRoutes } from './routes/deviceAuth.js'
import { healthRoutes, authRoutes, userRoutes, machineRoutes, planRoutes, gridRoutes, deviceRoutes, mobileRoutes, appRoutes, analyticsRoutes, agentRouteRoutes, storeRoutes } from './routes/index.js'
import { startSubdomainProxy, startMeshProxy } from './lib/subdomainProxy.js'
@@ -76,6 +78,10 @@ const app = Fastify({
// `ws` resets the timeout to 0 once it completes the upgrade, so this only ever fires pre-upgrade.
if (socket instanceof net.Socket) socket.setTimeout(UPGRADE_HANDSHAKE_TIMEOUT_MS, () => socket.destroy())
const path = (req.url ?? '').split('?')[0]
+ if (path === '/api/observer-ws') {
+ handleObserverUpgrade(req, socket, head)
+ return
+ }
// Inverted-transport hub endpoints (terminated here, not proxied):
// /api/web-ws — web clients (replaces the old proxied /proxy/api/ws)
// /api/manager-ws — managers dial in and multiplex all their agents
@@ -151,6 +157,7 @@ async function start(): Promise<void> {
await app.register(voiceRoutes)
await app.register(deviceAuthRoutes) // device-authorization grant: how the desktop app gets a machine key
await app.register(storeRoutes) // the Harness Store's ratings and reviews; the catalogue is the CLI's registry
+ await app.register(harnessShareRoutes)
// Dedicated public subdomain app-proxy on its own port (Host-header routed → tunnelled to the node app).
const appProxyServer = startSubdomainProxy()
diff --git a/cli/src/lib/terminalBackend.ts b/cli/src/lib/terminalBackend.ts
index 56614c0d8..11273bdb2 100644
--- a/cli/src/lib/terminalBackend.ts
+++ b/cli/src/lib/terminalBackend.ts
@@ -40,6 +40,7 @@ export interface TerminalBackend<Ref extends TerminalRuntimeRef = TerminalRuntim
expected: TerminalProcessExpectation,
size: TerminalStreamSize,
sink: TerminalStreamSink,
+ readOnly?: boolean,
): Promise<TerminalReadResult<TerminalStreamHandle<Ref>>>
/** Restart's two primitives. Optional per backend — only tmux (a real multiplexer pane) supports an
diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.ts
index e3e787c52..7a5684706 100644
--- a/cli/src/lib/terminalBackendCoordinator.ts
+++ b/cli/src/lib/terminalBackendCoordinator.ts
@@ -189,6 +189,7 @@ export class TerminalBackendCoordinator {
session: RegisteredSession,
size: TerminalStreamSize,
sink: TerminalStreamSink,
+ readOnly?: boolean,
): Promise<TerminalReadResult<TerminalStreamHandle>> {
// `active` describes whether the engine process was discovered, not whether the retained
// terminal runtime is still viewable. A dormant agent can legitimately be waiting at setup,
@@ -202,7 +203,7 @@ export class TerminalBackendCoordinator {
const result = await backend.openStream(runtime, {
engine: session.engine,
processIdentity: session.processIdentity ?? undefined,
- }, size, sink)
+ }, size, sink, readOnly)
if (result.state === 'succeeded') return result as TerminalReadResult<TerminalStreamHandle>
reason = result.reason
}
diff --git a/cli/src/lib/terminalStreamManager.ts b/cli/src/lib/terminalStreamManager.ts
index a965ef6ba..55c16a63a 100644
--- a/cli/src/lib/terminalStreamManager.ts
+++ b/cli/src/lib/terminalStreamManager.ts
@@ -98,6 +98,8 @@ interface ActiveStream {
}
export interface TerminalStreamManagerDeps {
+ /** An independent observer manager never acquires the owner control lease. */
+ readOnly?: boolean
terminals: TerminalBackendCoordinator
resolveAgent: (agentId: string) => RegisteredSession | undefined
sendTarget: (connId: string, type: string, payload: FramePayload) => boolean
@@ -167,6 +169,10 @@ export class TerminalStreamManager {
}
async handleFrame(connId: string, type: string, payload: FramePayload): Promise<boolean> {
+ if (this.deps.readOnly && !['terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack', 'terminal_resync', 'terminal_close'].includes(type)) {
+ this.sendError(connId, 'VIEW_ONLY', { requestId: payload.requestId })
+ return true
+ }
switch (type) {
case 'terminal_capabilities':
this.capabilities(connId, payload.requestId)
@@ -216,6 +222,7 @@ export class TerminalStreamManager {
}
async handleBinary(connId: string, frame: TerminalBinaryClear): Promise<void> {
+ if (this.deps.readOnly) return
if (frame.kind !== TerminalBinaryKind.input && frame.kind !== TerminalBinaryKind.paste
&& frame.kind !== TerminalBinaryKind.imagePaste && frame.kind !== TerminalBinaryKind.pasteFile) return
const state = this.streams.get(frame.streamId)
@@ -238,26 +245,26 @@ export class TerminalStreamManager {
backend: 'tmux',
available: this.deps.streamingAvailable,
features: {
- rawInput: true,
- resize: true,
- mouse: true,
+ rawInput: !this.deps.readOnly,
+ resize: !this.deps.readOnly,
+ mouse: !this.deps.readOnly,
keyframe: true,
sync: true,
compression: ['none', 'zlib'],
// A client old enough to predate `terminal_paste` must keep sending a direct terminal paste
// through `terminal_input` — checked here rather than assumed, so it degrades instead of
// silently going nowhere against a CLI that doesn't recognize the newer frame type.
- pasteRaw: true,
+ pasteRaw: !this.deps.readOnly,
// A client old enough to predate `TerminalBinaryKind.imagePaste` must keep forwarding a bare
// Ctrl+V and hoping the engine's own clipboard read finds something local — see
// `pasteImage()` for the frame this unlocks.
- imagePaste: true,
+ imagePaste: !this.deps.readOnly,
// A client old enough to predate `TerminalBinaryKind.pasteFile` has no way to hand a
// dropped non-image file to a REMOTE pane at all (a local pane needs no capability — it
// pastes the file's own path directly, never touching the wire) — see `pasteFile()`.
- pasteFile: true,
+ pasteFile: !this.deps.readOnly,
// Bounded media reads through the already encrypted agent_read_file RPC.
- mediaPreview: true,
+ mediaPreview: !this.deps.readOnly,
},
engines: terminalEngineCapabilities(this.deps.streamingAvailable),
})
@@ -311,7 +318,7 @@ export class TerminalStreamManager {
await this.withLeaseLock(reservedPlacement, async () => {
// A terminal is single-controller. A later client explicitly wins the lease and the incumbent
// receives a targeted close notification; it must not be broadcast to other clients.
- await this.closeStreamsForTakeover(session.agentId, reservedPlacement, connId)
+ if (!this.deps.readOnly) await this.closeStreamsForTakeover(session.agentId, reservedPlacement, connId)
// Only THIS connection's stream for THIS terminal, not every stream it holds.
//
// It used to be closeConnection(connId), i.e. "opening a terminal ends every other terminal
@@ -322,8 +329,8 @@ export class TerminalStreamManager {
// looked alive, but its session never reached `controlling`, so every keystroke into it was
// dropped in silence.
await this.closeOwnStreamsFor(connId, session.agentId, reservedPlacement)
- this.controllerByAgent.set(session.agentId, connId)
- this.controllerByPlacement.set(reservedPlacement, connId)
+ if (!this.deps.readOnly) this.controllerByAgent.set(session.agentId, connId)
+ if (!this.deps.readOnly) this.controllerByPlacement.set(reservedPlacement, connId)
const streamId = randomUUID()
const buffered: Buffer[] = []
let state: ActiveStream | null = null
@@ -337,7 +344,7 @@ export class TerminalStreamManager {
onClose: (reason) => {
if (state) void this.closeStream(state, reason, true)
},
- })
+ }, this.deps.readOnly)
} catch {
if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
@@ -353,7 +360,7 @@ export class TerminalStreamManager {
const placementKey = terminalPlacementKey(opened.value.runtime)
const actualController = this.controllerByPlacement.get(placementKey)
- if (actualController && actualController !== connId) {
+ if (!this.deps.readOnly && actualController && actualController !== connId) {
if (this.controllerByAgent.get(session.agentId) === connId) this.controllerByAgent.delete(session.agentId)
if (this.controllerByPlacement.get(reservedPlacement) === connId) this.controllerByPlacement.delete(reservedPlacement)
await opened.value.close().catch(() => { /* best effort */ })
@@ -363,7 +370,7 @@ export class TerminalStreamManager {
if (reservedPlacement !== placementKey && this.controllerByPlacement.get(reservedPlacement) === connId) {
this.controllerByPlacement.delete(reservedPlacement)
}
- this.controllerByPlacement.set(placementKey, connId)
+ if (!this.deps.readOnly) this.controllerByPlacement.set(placementKey, connId)
const requestedCompression = Array.isArray(payload.compression) ? payload.compression : []
// Never compress for the loopback desktop, whatever it asks for: the bytes cross 127.0.0.1,
@@ -415,6 +422,7 @@ export class TerminalStreamManager {
agentId: session.agentId,
engineId: session.engine,
backend: 'tmux',
+ readOnly: this.deps.readOnly === true,
})) {
await this.closeStream(state, 'backend disconnected', false)
return
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 2565e856d..84776adb7 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -385,8 +385,9 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
expected: TerminalProcessExpectation,
size: TerminalStreamSize,
sink: TerminalStreamSink,
+ readOnly?: boolean,
): Promise<TerminalReadResult<TerminalStreamHandle<TmuxRuntimeRef>>> {
void expected
- return TmuxControlStream.open(runtime.paneId, size, sink)
+ return TmuxControlStream.open(runtime.paneId, size, sink, readOnly)
}
}
diff --git a/cli/src/lib/tmuxStream.ts b/cli/src/lib/tmuxStream.ts
index 677b3e6ac..9abb037c4 100644
--- a/cli/src/lib/tmuxStream.ts
+++ b/cli/src/lib/tmuxStream.ts
@@ -435,6 +435,7 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
paneId: string,
child: ChildProcessWithoutNullStreams,
private readonly sink: TerminalStreamSink,
+ private readonly readOnly = false,
) {
this.runtime = { backend: 'tmux', paneId }
this.child = child
@@ -462,7 +463,7 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
child.once('close', (code) => this.notifyClose(this.closed ? 'closed' : `tmux control client exited (${code ?? 'signal'})`))
}
- static async open(paneId: string, size: TerminalStreamSize, sink: TerminalStreamSink): Promise<TerminalReadResult<TmuxControlStream>> {
+ static async open(paneId: string, size: TerminalStreamSize, sink: TerminalStreamSink, readOnly = false): Promise<TerminalReadResult<TmuxControlStream>> {
const original = await paneMeta(paneId)
if (!original) return { state: 'failed', reason: 'tmux pane metadata is unavailable' }
if (original.windowPanes !== 1) return { state: 'failed', reason: 'TERMINAL_MULTI_PANE_UNSUPPORTED' }
@@ -475,8 +476,8 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
child.once('error', () => { if (!settled) { settled = true; resolve(false) } })
})
if (!spawned) return { state: 'failed', reason: 'tmux control client could not start' }
- const stream = new TmuxControlStream(paneId, child, sink)
- const resized = await stream.resize(size)
+ const stream = new TmuxControlStream(paneId, child, sink, readOnly)
+ const resized = readOnly ? TERMINAL_ACTION_SUCCEEDED : await stream.resize(size)
if (resized.state !== 'succeeded') {
await stream.close()
return { state: 'failed', reason: resized.reason }
@@ -663,6 +664,7 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
* `await` slipped in ahead of them would let a later keystroke overtake an earlier one.
*/
async writeRaw(bytes: Uint8Array): Promise<TerminalActionResult> {
+ if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
if (this.closed) return terminalActionNotStarted('terminal stream is closed')
if (bytes.length === 0) return TERMINAL_ACTION_SUCCEEDED
// scroll() below leaves the pane in copy-mode, which captures all keyboard input for its own
@@ -697,6 +699,7 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
* program's own paste-detector once split across multiple `send-keys` commands).
*/
async pasteRaw(text: string): Promise<TerminalActionResult> {
+ if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
if (this.closed) return terminalActionNotStarted('terminal stream is closed')
if (text.length === 0) return TERMINAL_ACTION_SUCCEEDED
const pasted = await pasteRawIntoTmux(this.runtime.paneId, text)
@@ -711,6 +714,7 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
* own prompt as literal characters instead of scrolling) — copy-mode works regardless, since it
* never depends on the program in the pane understanding anything about the bytes at all. */
async scroll(direction: 'up' | 'down', lines: number): Promise<TerminalActionResult> {
+ if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
if (this.closed) return terminalActionNotStarted('terminal stream is closed')
if (lines <= 0) return TERMINAL_ACTION_SUCCEEDED
// Idempotent — safe even if already in copy-mode from a previous scroll.
@@ -726,6 +730,7 @@ export class TmuxControlStream implements TerminalStreamHandle<TmuxRuntimeRef> {
}
async resize(requested: TerminalStreamSize): Promise<TerminalActionResult> {
+ if (this.readOnly) return terminalActionNotStarted('VIEW_ONLY')
return this.serializeOperation(async () => {
if (this.closed) return terminalActionNotStarted('terminal stream is closed')
const metadata = await this.runControlCommand(
diff --git a/cli/src/sharing/crypto.spec.ts b/cli/src/sharing/crypto.spec.ts
new file mode 100644
index 000000000..dac569c5d
--- /dev/null
+++ b/cli/src/sharing/crypto.spec.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest'
+import { b64e, newEphemeral, newIdentity, wrapPayload } from '../lib/e2ee/core.js'
+import { observerContext, ObserverCipher, ownerHandshake, recipientHandshake } from './crypto.js'
+
+function pair(machine = 'machine', share = 'share') {
+ const identity = newIdentity(), ephemeral = newEphemeral()
+ const owner = ownerHandshake(identity, machine, share, b64e(ephemeral.pub))
+ const recipient = recipientHandshake(ephemeral, machine, share, b64e(identity.pub), owner.welcome)
+ return { identity, ephemeral, owner, recipient }
+}
+describe('isolated observer encryption', () => {
+ it('authenticates the owner and encrypts each direction without a machine group key', () => {
+ const p = pair(), input = { type: 'terminal_open', payload: { agentId: 'agent' } }
+ const encrypted = p.recipient.seal(input)
+ expect(JSON.stringify(encrypted)).not.toContain('agent')
+ expect(p.owner.cipher.open(encrypted)).toEqual(input)
+ expect(p.recipient.open(p.owner.cipher.seal({ type: 'terminal_output', text: 'hello' }))).toEqual({ type: 'terminal_output', text: 'hello' })
+ })
+ it('rejects replay, reflection, other recipients, changed ciphertext and grant substitution', () => {
+ const p = pair(), other = pair(), packet = p.recipient.seal({ type: 'terminal_open' })
+ expect(p.recipient.open(packet)).toBeNull()
+ expect(other.owner.cipher.open(packet)).toBeNull()
+ const bad = structuredClone(packet); bad.__e2e.ct = b64e(new Uint8Array(32))
+ expect(p.owner.cipher.open(bad)).toBeNull()
+ expect(p.owner.cipher.open(packet)).toEqual({ type: 'terminal_open' })
+ expect(p.owner.cipher.open(packet)).toBeNull()
+ expect(() => recipientHandshake(p.ephemeral, 'machine', 'other-share', b64e(p.identity.pub), p.owner.welcome)).toThrow()
+ expect(() => recipientHandshake(p.ephemeral, 'machine', 'share', b64e(newIdentity().pub), p.owner.welcome)).toThrow()
+ })
+ it('rejects malformed handshake keys and envelopes', () => {
+ const p = pair()
+ expect(() => ownerHandshake(p.identity, 'm', 's', 'bad')).toThrow()
+ expect(() => ownerHandshake(p.identity, 'm', 's', b64e(new Uint8Array(32)))).toThrow()
+ expect(() => recipientHandshake(p.ephemeral, 'm', 's', 'bad', { ephemeral: 'bad' })).toThrow()
+ for (const value of [null, {}, { __e2e: {} }, { __e2e: { v: 2 } },
+ { __e2e: { v: 1, k: 'g' } }, { __e2e: { v: 1, k: 'p', n: -1 } },
+ { __e2e: { v: 1, k: 'p', n: 0.5 } }, { __e2e: { v: 1, k: 'p', n: 0, ct: 4 } },
+ { __e2e: { v: 1, k: 'p', n: 0, ct: 'x'.repeat(3 * 1024 * 1024 + 1) } },
+ { __e2e: { v: 1, k: 'p', n: 0, ct: 'invalid' } }]) expect(p.owner.cipher.open(value)).toBeNull()
+ })
+ it('rejects decrypted values that are not frames and contains malformed getters', () => {
+ const key = new Uint8Array(32), context = observerContext('m', 's')
+ const cipher = new ObserverCipher(key, key, context)
+ for (const value of [null, false, 'text', []]) expect(cipher.open(wrapPayload(key, 'p', 0, 'observer_frame', context, value))).toBeNull()
+ expect(cipher.open({ get __e2e() { throw new Error('malformed') } })).toBeNull()
+ })
+})
diff --git a/cli/src/sharing/crypto.ts b/cli/src/sharing/crypto.ts
new file mode 100644
index 000000000..942883797
--- /dev/null
+++ b/cli/src/sharing/crypto.ts
@@ -0,0 +1,50 @@
+import {
+ b64d, b64e, newEphemeral, sessionKeys, welcomeSig, welcomeVerify,
+ wrapPayload, unwrapPayload, type Ephemeral, type Identity, type WrappedPayload,
+} from '../lib/e2ee/core.js'
+
+/** Domain separation also binds the invitation: ciphertext cannot move between grants or directions. */
+export function observerContext(machineId: string, shareId: string): string {
+ return `harness-observer-v1:${machineId}:${shareId}`
+}
+export class ObserverCipher {
+ private tx = 0
+ private rx = -1
+ constructor(private readonly sendKey: Uint8Array, private readonly receiveKey: Uint8Array,
+ private readonly context: string) {}
+ seal(frame: unknown): WrappedPayload {
+ return wrapPayload(this.sendKey, 'p', this.tx++, 'observer_frame', this.context, frame)
+ }
+ open(value: unknown): Record<string, unknown> | null {
+ try {
+ const e = (value as WrappedPayload)?.__e2e
+ if (!e || e.v !== 1 || e.k !== 'p' || !Number.isSafeInteger(e.n) || e.n <= this.rx
+ || typeof e.ct !== 'string' || e.ct.length > 3 * 1024 * 1024) return null
+ const frame = unwrapPayload(this.receiveKey, e, 'observer_frame', this.context)
+ if (!frame || typeof frame !== 'object' || Array.isArray(frame)) return null
+ this.rx = e.n
+ return frame as Record<string, unknown>
+ } catch { return null }
+ }
+}
+
+export function ownerHandshake(identity: Identity, 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)) } }
+}
+
+export function recipientHandshake(ephemeral: Ephemeral, machineId: string, shareId: string,
+ ownerPublicKey: string, welcome: Record<string, unknown>): ObserverCipher {
+ const publicKey = b64d(String(welcome.ephemeral))
+ const context = observerContext(machineId, shareId)
+ if (publicKey.length !== 32 || !welcomeVerify(b64d(ownerPublicKey), context, ephemeral.pub,
+ publicKey, b64d(String(welcome.signature)))) throw new Error('The shared harness identity could not be verified.')
+ const keys = sessionKeys(ephemeral.priv, publicKey, context, ephemeral.pub, publicKey)
+ return new ObserverCipher(keys.c2s, keys.s2c, context)
+}
diff --git a/cli/src/sharing/grants.spec.ts b/cli/src/sharing/grants.spec.ts
new file mode 100644
index 000000000..e7bb95089
--- /dev/null
+++ b/cli/src/sharing/grants.spec.ts
@@ -0,0 +1,55 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { HarnessGrantStore, inviteSchema } from './grants.js'
+
+const roots: string[] = []
+afterEach(() => { for (const dir of roots.splice(0)) rmSync(dir, { recursive: true, force: true }) })
+function fixture() {
+ const root = mkdtempSync(join(tmpdir(), 'harness-share-grants-')); roots.push(root)
+ const path = join(root, 'permissions.json')
+ let now = Date.now()
+ const store = new HarnessGrantStore(path, () => now)
+ const input = { machineId: 'machine', agentId: 'agent', recipientEmail: '[email protected]',
+ name: 'CAD prototype', engine: 'codex', ownerPublicKey: 'public', expiresAt: new Date(now + 1000).toISOString() }
+ return { store, path, input, advance: () => { now += 1001 } }
+}
+describe('durable harness sharing permissions', () => {
+ it('normalizes emails and constrains invitation batches and expiry', () => {
+ expect(inviteSchema.parse({ emails: [' [email protected] '] })).toEqual({ emails: ['[email protected]'], days: 30 })
+ for (const invalid of [{ emails: [] }, { emails: ['bad'] }, { emails: ['[email protected]'], days: 365 },
+ { emails: Array(21).fill('[email protected]') }]) expect(inviteSchema.safeParse(invalid).success).toBe(false)
+ })
+ it('persists private grants and admits only the matching recipient, machine and live grant', () => {
+ const f = fixture(); expect(f.store.all()).toEqual([])
+ const grant = f.store.invite(f.input)
+ expect(statSync(f.path).mode & 0o777).toBe(0o600)
+ expect(new HarnessGrantStore(f.path).list('machine', 'agent')).toEqual([grant])
+ expect(f.store.active(grant.id, '[email protected]', 'machine')).toEqual(grant)
+ expect(f.store.active(grant.id, '[email protected]', 'machine')).toBeNull()
+ expect(f.store.active(grant.id, '[email protected]', 'another-machine')).toBeNull()
+ expect(f.store.active('missing', '[email protected]', 'machine')).toBeNull()
+ expect(f.store.list('machine', 'another-agent')).toEqual([])
+ f.advance(); expect(f.store.active(grant.id, '[email protected]', 'machine')).toBeNull()
+ })
+ it('renews idempotently, isolates permissions, and durably revokes before sync', () => {
+ const f = fixture(), ken = f.store.invite(f.input)
+ const diego = f.store.invite({ ...f.input, recipientEmail: '[email protected]' })
+ f.store.synced(ken.id); expect(f.store.all().find(g => g.id === ken.id)?.pending).toBe(false)
+ const renewed = f.store.invite({ ...f.input, name: 'Renamed' })
+ expect(renewed.id).toBe(ken.id); expect(f.store.all()).toHaveLength(2)
+ expect(f.store.revoke(ken.id, 'another-machine', 'agent')).toBe(false)
+ expect(f.store.revoke(ken.id, 'machine', 'another-agent')).toBe(false)
+ expect(f.store.revoke(ken.id, 'machine', 'agent')).toBe(true)
+ expect(f.store.active(ken.id, ken.recipientEmail, 'machine')).toBeNull()
+ expect(new HarnessGrantStore(f.path).list('machine', 'agent')).toEqual([diego])
+ expect(JSON.parse(readFileSync(f.path, 'utf8')).find((g: { id: string }) => g.id === ken.id)).toMatchObject({ revoked: true, pending: true })
+ const copy = f.store.all(); copy[0].name = 'tampered'
+ expect(f.store.all()[0].name).not.toBe('tampered')
+ })
+ it('fails closed on corrupt state instead of silently forgetting permissions', () => {
+ const f = fixture(); writeFileSync(f.path, '{broken')
+ expect(() => new HarnessGrantStore(f.path)).toThrow('permissions file could not be read')
+ })
+})
diff --git a/cli/src/sharing/grants.ts b/cli/src/sharing/grants.ts
new file mode 100644
index 000000000..a96e96e06
--- /dev/null
+++ b/cli/src/sharing/grants.ts
@@ -0,0 +1,61 @@
+import { randomUUID } from 'node:crypto'
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { dirname } from 'node:path'
+import { z } from 'zod'
+
+export const emailSchema = z.string().trim().toLowerCase().email().max(254)
+export const inviteSchema = z.object({
+ emails: z.array(emailSchema).min(1).max(20),
+ days: z.union([z.literal(7), z.literal(30), z.literal(90)]).default(30),
+})
+const grantSchema = z.object({
+ id: z.string().uuid(), machineId: z.string().min(1), agentId: z.string().min(1),
+ recipientEmail: emailSchema, name: z.string(), engine: z.string().nullable(),
+ ownerPublicKey: z.string(), expiresAt: z.string().datetime(), createdAt: z.string().datetime(),
+ revoked: z.boolean().default(false), pending: z.boolean().default(false),
+})
+export type HarnessGrant = z.infer<typeof grantSchema>
+
+/** Durable owner-side authority. Revocation is saved before it can close observers or call a relay. */
+export class HarnessGrantStore {
+ private grants: HarnessGrant[]
+ constructor(private readonly path: string, private readonly now = () => Date.now()) {
+ try { this.grants = z.array(grantSchema).parse(JSON.parse(readFileSync(path, 'utf8'))) }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw new Error('The harness sharing permissions file could not be read.')
+ this.grants = []
+ }
+ }
+ private save(next: HarnessGrant[]): void {
+ mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 })
+ const temp = `${this.path}.${randomUUID()}.tmp`
+ writeFileSync(temp, JSON.stringify(next), { mode: 0o600, flag: 'wx' })
+ renameSync(temp, this.path)
+ this.grants = next
+ }
+ all(): HarnessGrant[] { return this.grants.map(g => ({ ...g })) }
+ active(id: string, email: string, machineId: string): HarnessGrant | null {
+ const grant = this.grants.find(g => g.id === id && g.machineId === machineId
+ && g.recipientEmail === email && !g.revoked && Date.parse(g.expiresAt) > this.now())
+ return grant ? { ...grant } : null
+ }
+ list(machineId: string, agentId: string): HarnessGrant[] {
+ return this.all().filter(g => g.machineId === machineId && g.agentId === agentId && !g.revoked)
+ }
+ invite(input: Omit<HarnessGrant, 'id' | 'createdAt' | 'pending' | 'revoked'>): HarnessGrant {
+ const previous = this.grants.find(g => g.machineId === input.machineId && g.agentId === input.agentId
+ && g.recipientEmail === input.recipientEmail)
+ const grant = grantSchema.parse({ ...input, id: previous?.id ?? randomUUID(),
+ createdAt: previous?.createdAt ?? new Date(this.now()).toISOString(), pending: true, revoked: false })
+ this.save([...this.grants.filter(g => g.id !== grant.id), grant])
+ return { ...grant }
+ }
+ synced(id: string): void {
+ this.save(this.grants.map(g => g.id === id ? { ...g, pending: false } : g))
+ }
+ revoke(id: string, machineId: string, agentId: string): boolean {
+ const found = this.grants.some(g => g.id === id && g.machineId === machineId && g.agentId === agentId)
+ if (found) this.save(this.grants.map(g => g.id === id ? { ...g, revoked: true, pending: true } : g))
+ return found
+ }
+}
diff --git a/cli/src/sharing/owner.ts b/cli/src/sharing/owner.ts
new file mode 100644
index 000000000..c76828ec8
--- /dev/null
+++ b/cli/src/sharing/owner.ts
@@ -0,0 +1,167 @@
+import type { Identity } from '../lib/e2ee/core.js'
+import { b64e } from '../lib/e2ee/core.js'
+import { projectDisplayName, 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 { HarnessGrantStore, inviteSchema, type HarnessGrant } from './grants.js'
+import { ownerHandshake, type ObserverCipher } from './crypto.js'
+
+type Payload = Record<string, unknown>
+interface Observer { grant: HarnessGrant; cipher: ObserverCipher }
+export interface ShareOwnerDeps {
+ machineId: () => string
+ identity: Identity
+ grants: HarnessGrantStore
+ terminals: TerminalBackendCoordinator
+ resolveAgent: (id: string) => RegisteredSession | undefined
+ send: (connId: string, type: string, payload: Payload) => boolean
+ publish: (method: 'PUT' | 'DELETE', path: string, body?: unknown) => Promise<{ status: number; body: unknown }>
+ watchViewer?: (agentId: string, send: (payload: Payload) => void) => (() => void)
+ now?: () => number
+}
+
+/** This is the complete observer dispatch surface. It never calls the ordinary daemon RPC switch. */
+export class HarnessShareOwner {
+ private readonly observers = new Map<string, Observer>()
+ private readonly viewers = new Map<string, () => void>()
+ private readonly streams: TerminalStreamManager
+ private readonly timer: ReturnType<typeof setInterval>
+ private readonly now: () => number
+ private syncing: Promise<void> | null = null
+ private 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,
+ resolveAgent: deps.resolveAgent, streamingAvailable: true,
+ sendTarget: (id, type, payload) => this.send(id, { type, payload }),
+ sendBinaryTarget: (id, frame) => {
+ const bytes = encodeTerminalLocal(frame)
+ return bytes !== null && this.send(id, { type: 'observer_binary',
+ payload: { bytes: Buffer.from(bytes).toString('base64') } })
+ },
+ })
+ let ticks = 0
+ this.timer = setInterval(() => {
+ for (const [id, observer] of this.observers) {
+ if (!this.authorized(observer)) this.close(id, 'Sharing ended or invitation expired')
+ }
+ if (++ticks % 30 === 0) void this.sync()
+ }, 1000)
+ this.timer.unref()
+ }
+ private authorized(observer: Observer): boolean {
+ return !!this.deps.grants.active(observer.grant.id, observer.grant.recipientEmail, this.deps.machineId())
+ && !!this.deps.resolveAgent(observer.grant.agentId)
+ }
+ private send(connId: string, frame: Payload): boolean {
+ const observer = this.observers.get(connId)
+ if (!observer || !this.authorized(observer)) return false
+ return this.deps.send(connId, 'observer_frame', observer.cipher.seal(frame) as unknown as Payload)
+ }
+ close(connId: string, reason = 'Observation ended'): void {
+ if (!this.observers.delete(connId)) return
+ this.viewers.get(connId)?.()
+ this.viewers.delete(connId)
+ void this.streams.closeConnection(connId)
+ this.deps.send(connId, 'observer_closed', { reason })
+ }
+ closeAll(): void { for (const id of this.observers.keys()) this.close(id, 'Owner disconnected') }
+ async stop(): Promise<void> { clearInterval(this.timer); this.closeAll(); await this.streams.stop() }
+
+ async receive(connId: string, type: string, payload: Payload): Promise<void> {
+ if (!connId.startsWith('observer:')) return
+ if (type === 'observer_close') { this.close(connId); return }
+ if (type === 'observer_open') {
+ if (this.observers.has(connId)) { this.close(connId, 'Invalid observer handshake'); return }
+ const grant = this.deps.grants.active(String(payload.shareId), String(payload.email), this.deps.machineId())
+ if (!grant || !this.deps.resolveAgent(grant.agentId) || this.observers.size >= 100) {
+ 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))
+ this.observers.set(connId, { grant, cipher })
+ if (!this.deps.send(connId, 'observer_welcome', welcome)) this.close(connId)
+ } catch { this.deps.send(connId, 'observer_closed', { reason: 'Invalid observer handshake' }) }
+ return
+ }
+ const observer = this.observers.get(connId)
+ if (!observer) return
+ if (!this.authorized(observer)) { this.close(connId, 'Sharing ended or invitation expired'); return }
+ const frame = type === 'observer_frame' ? observer.cipher.open(payload) : null
+ if (!frame || typeof frame.type !== 'string' || !frame.payload || typeof frame.payload !== 'object') {
+ this.close(connId, 'Invalid observer message'); return
+ }
+ const p = frame.payload as Payload
+ const allowed = ['terminal_capabilities', 'terminal_open', 'terminal_alive', 'terminal_ack',
+ 'terminal_resync', 'terminal_close', 'observer_viewer']
+ if (!allowed.includes(frame.type) || (p.agentId !== undefined && p.agentId !== observer.grant.agentId)
+ || (frame.type === 'terminal_open' && p.agentId !== observer.grant.agentId)) {
+ this.send(connId, { type: 'terminal_error', payload: { requestId: p.requestId, code: 'VIEW_ONLY' } })
+ return
+ }
+ if (frame.type === 'observer_viewer') {
+ if (!this.viewers.has(connId) && this.deps.watchViewer) {
+ this.viewers.set(connId, this.deps.watchViewer(observer.grant.agentId,
+ data => { this.send(connId, { type: 'observer_viewer', payload: data }) }))
+ }
+ return
+ }
+ await this.streams.handleFrame(connId, frame.type, p)
+ }
+
+ /** Owner controls are serialized so a delayed publish cannot undo a subsequent removal. */
+ manage(type: string, payload: Payload): Promise<Payload> {
+ const work = this.mutation.then(() => this.manageOne(type, payload))
+ this.mutation = work.catch(() => {})
+ return work
+ }
+ private async manageOne(type: string, payload: Payload): Promise<Payload> {
+ const agentId = typeof payload.agentId === 'string' ? payload.agentId : ''
+ const session = this.deps.resolveAgent(agentId)
+ if (!session) return { error: 'HARNESS_NOT_FOUND', detail: 'This harness is no longer available.' }
+ const machineId = this.deps.machineId()
+ if (type === 'harness_share_invite') {
+ const parsed = inviteSchema.safeParse(payload)
+ if (!parsed.success) return { error: 'INVALID_INVITATION', detail: 'Enter valid email addresses and choose an expiry.' }
+ 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),
+ expiresAt: new Date(this.now() + parsed.data.days * 86400_000).toISOString() })
+ }
+ await this.sync()
+ } else if (type === 'harness_share_remove') {
+ if (typeof payload.id !== 'string' || !this.deps.grants.revoke(payload.id, machineId, agentId)) {
+ return { error: 'INVITATION_NOT_FOUND', detail: 'This invitation is no longer available.' }
+ }
+ for (const [id, observer] of this.observers) if (observer.grant.id === payload.id) this.close(id, 'Access removed')
+ await this.sync()
+ } else if (type !== 'harness_share_list') return { error: 'UNSUPPORTED' }
+ return { shares: this.deps.grants.list(machineId, agentId).map(grant => ({
+ id: grant.id, email: grant.recipientEmail, expiresAt: grant.expiresAt,
+ expired: Date.parse(grant.expiresAt) <= this.now(), pending: grant.pending,
+ watching: [...this.observers.values()].filter(o => o.grant.id === grant.id).length,
+ })) }
+ }
+ sync(): Promise<void> {
+ if (this.syncing) return this.syncing
+ const run = async () => {
+ for (const grant of this.deps.grants.all().filter(g => g.pending && g.machineId === this.deps.machineId())) {
+ try {
+ const result = await this.deps.publish(grant.revoked ? 'DELETE' : 'PUT', `/api/harness-shares/${grant.id}`,
+ grant.revoked ? undefined : { machineId: grant.machineId, agentId: grant.agentId,
+ recipientEmail: grant.recipientEmail, name: grant.name, engine: grant.engine,
+ ownerPublicKey: grant.ownerPublicKey, expiresAt: grant.expiresAt })
+ if (result.status >= 200 && result.status < 300 || grant.revoked && result.status === 404) {
+ // A revoke may have happened while this network request was in flight.
+ const current = this.deps.grants.all().find(g => g.id === grant.id)
+ if (current?.revoked === grant.revoked && current.expiresAt === grant.expiresAt) this.deps.grants.synced(grant.id)
+ }
+ } catch { /* Persisted pending change is retried, including after daemon restart. */ }
+ }
+ }
+ this.syncing = run().finally(() => { this.syncing = null })
+ return this.syncing
+ }
+}
diff --git a/docs/plans/2026-09-17-002-share-harness-plan.md b/docs/plans/2026-09-17-002-share-harness-plan.md
new file mode 100644
index 000000000..2c5f71b80
--- /dev/null
+++ b/docs/plans/2026-09-17-002-share-harness-plan.md
@@ -0,0 +1,35 @@
+# Share a harness
+
+Status: implementation in `codex/share-harness`.
+
+## Experience
+
+The agent pane offers **Share harness**. Its owner enters one or more email addresses and grants
+**Can view** access. The dialog lists recipients, expiry, and active observers and supports removal.
+Invitations are account-bound and appear in the recipient's app, including after first sign-in.
+
+Machines has **Your machines** and **Shared with you** sections. Shared machines carry an owner label
+and a distinct icon. Their submenus contain only harnesses shared with the signed-in recipient.
+Opening one shows a live terminal and viewer with a persistent **View only** indicator. Disconnects
+preserve the pane and recover automatically. Revocation immediately ends access.
+
+## Boundaries
+
+- Authorization belongs to a recipient and a specific agent on a machine. New agents never inherit it.
+- An observer cannot acquire a terminal control lease, resize the owner's terminal, send input,
+ answer questions or approvals, read arbitrary files, enumerate the machine, or mutate its viewer.
+- Observer traffic uses a separate, account-authenticated relay and per-connection encryption.
+ Observers never receive a machine's group key or its full-trust pairing credentials.
+- The owner daemon keeps its own durable grant allow-list. Backend metadata alone cannot grant access.
+- Live viewer images are rendered on the owner's machine. The observer gets pixels, never a proxy
+ to a local viewer's APIs. Renderers use a separate browser profile without the owner's credentials.
+- Publishing results and collaborative input are separate future work.
+
+## Verification
+
+Cover invite normalization and validation, owner/recipient authorization, duplicate and pending
+invitations, discovery filtering, simultaneous observers, encryption and replay rejection, denied
+input/resize/file access, immediate revocation, expiry, reconnect, offline state, terminal fidelity,
+viewer updates, and existing owner controls. Measure coverage of the new feature modules and report
+the actual numbers. Exercise real sockets and a disposable tmux session as well as desktop widgets;
+keep test identities, daemons and runtime data isolated from the user's running sessions.