From bb39425cca739635af44951a4ad4ff756ae171cf Mon Sep 17 00:00:00 2001 From: QQ Date: Sat, 14 Nov 2026 14:57:21 +0800 Subject: [PATCH] Import packages/plugin/src/remote-typert-gateway.ts --- packages/plugin/src/remote-typert-gateway.ts | 792 +++++++++++++++++++ 1 file changed, 792 insertions(+) create mode 100644 packages/plugin/src/remote-typert-gateway.ts diff --git a/packages/plugin/src/remote-typert-gateway.ts b/packages/plugin/src/remote-typert-gateway.ts new file mode 100644 index 0000000..022741f --- /dev/null +++ b/packages/plugin/src/remote-typert-gateway.ts @@ -0,0 +1,792 @@ +import { RemoteClientError, type RemoteClientCore } from '@dsh-remote/client-core' +import { + HARNESS_API_TRANSFER_CHUNK_BYTES, + MAX_HARNESS_API_TRANSFER_BYTES, + type EventPayload, + type HarnessApiTransferCommitResult, + type HarnessApiTransferReadResult, + type HarnessRemoteFrameData, + type HarnessRemoteStreamClosedData, +} from '@dsh-remote/protocol' +import { uuidV7 } from './ids.js' +import { + canonicalUnaryHistoryKey, + extractSessionIdFromGatewayPayload, + isSessionMutationEndpoint, + RemoteSessionHistoryCache, +} from './session-history-cache.js' +import { + normalizeAssistantMessageStreamValue, + normalizeLegacySessionGatewayValue, + type SessionFormatCompatibility, +} from './session-format-compat.js' +import type { + RemoteTypertGatewayTarget, + TypertGatewayRequest, + TypertRpcResult, +} from './typert-gateway-contract.js' + +const DIRECT_REMOTE_CALL_BYTES = 2 * 1024 * 1024 +const WELCOME_NOTICE_NAMESPACE = 'ui-settings-general' +const WELCOME_NOTICE_FIELD = 'welcomeNoticeVersion' +const WELCOME_NOTICE_VERSION = '2026-08-13.1' + +/** Client-side alpha Gateway carrier over the authenticated Remote channel. */ +export class RemoteTypertGateway implements RemoteTypertGatewayTarget { + private frameTransfers?: boolean + constructor( + private readonly client: RemoteClientCore, + private readonly compatibility?: SessionFormatCompatibility, + private readonly harnessVersion?: string, + // Native snapshot consumers treat wire errors as terminal. Their local + // carrier is reset by subscribeRemoteRecovery only after reauthentication. + private readonly deferStreamDisconnect = false, + private readonly historyCache: RemoteSessionHistoryCache = new RemoteSessionHistoryCache(), + ) {} + + async invoke(request: TypertGatewayRequest): Promise { + const result = await this.dispatch( + `${request.namespace}/${request.method}`, + { args: request.args }, + request.signal ?? new AbortController().signal, + ) + if (result.ok) return result.value + throw remoteFailure(result.error) + } + + async dispatch( + endpoint: string, + payload: unknown, + signal: AbortSignal, + ): Promise { + if (endpoint === 'workspace/delete') { + this.historyCache.clear() + } else if (isSessionMutationEndpoint(endpoint)) { + const mutatedSessionId = extractSessionIdFromGatewayPayload(payload) + if (mutatedSessionId !== undefined) this.historyCache.invalidateSession(mutatedSessionId) + } + if (endpoint === 'session/page' || endpoint === 'session/history' || endpoint === 'session/projections') { + const sessionId = extractSessionIdFromGatewayPayload(payload) + if (sessionId !== undefined) { + const key = canonicalUnaryHistoryKey(endpoint, payload) + const cached = this.historyCache.getUnary(this.client, sessionId, key) + ?? (endpoint === 'session/page' ? this.historyCache.slicePageFromSnapshot(this.client, sessionId, payload) : undefined) + if (cached !== undefined) return { ok: true, value: cached } + return await this.historyCache.runSingleFlightUnary( + this.client, + sessionId, + key, + signal, + async sharedSignal => { + const readEpoch = this.historyCache.beginReadEpoch() + try { + const result = await this.dispatchRemote(endpoint, payload, sharedSignal) + if (result.ok) { + this.historyCache.setUnary(this.client, sessionId, key, result.value, readEpoch) + } + return result + } catch (error) { + if (!sharedSignal.aborted && !(isRecord(error) && error.isDSHRemoteError === true)) { + const fallback = this.historyCache.getFallbackUnary(sessionId, endpoint, key, payload) + if (fallback !== undefined) return { ok: true, value: fallback } + } + throw error + } + }, + ) + } + } + const result = await this.dispatchRemote(endpoint, payload, signal) + if (isSessionMutationEndpoint(endpoint)) { + const mutatedSessionId = extractSessionIdFromGatewayPayload(payload) + if (mutatedSessionId !== undefined) this.historyCache.invalidateSession(mutatedSessionId) + } + return result + } + + private async dispatchRemote( + endpoint: string, + payload: unknown, + signal: AbortSignal, + ): Promise { + // The Remote Gateway contract requires a single plain-object `args` field. + // Keep the payload unchanged here: converting it to positional arrays makes + // current Hosts reject even empty calls such as `llm/listProviders`. + const request = { endpoint, payload } + const encoded = new TextEncoder().encode(JSON.stringify(request)) + let response: unknown + if (encoded.byteLength > DIRECT_REMOTE_CALL_BYTES) { + response = await this.callTransferred(encoded, signal) + } else { + try { + response = await this.client.rpc('harness.remote.call', request, signal) + } catch (error) { + if (!hasErrorCode(error, 'RESPONSE_TOO_LARGE')) throw error + response = await this.callTransferred(encoded, signal) + } + } + const result = normalizeThemeSettingsResult(endpoint, parseRpcResult(response)) + const settingsResult = this.normalizeLegacyWelcomeSettings(endpoint, payload, result) + if (settingsResult !== undefined) return settingsResult + if (result.ok) { + const value = this.compatibility === 'legacy-to-v3' + ? normalizeLegacySessionGatewayValue(endpoint, result.value) + : normalizeAssistantMessageStreamValue(endpoint, result.value) + return { ...result, value: normalizeProjectionResult(endpoint, normalizeWorkspaceBinaryResult(endpoint, value)) } + } + return result + } + + private legacyWelcomeAcknowledged = false + private settingsDescribeValue?: Record + + /** DSH <=0.1.6 cannot persist the 0.1.7 welcome acknowledgement remotely. */ + private normalizeLegacyWelcomeSettings(endpoint: string, payload: unknown, result: TypertRpcResult): TypertRpcResult | undefined { + if (!isLegacyRemoteHost(this.harnessVersion)) return undefined + if (endpoint === 'settings/describe' && result.ok && isRecord(result.value)) { + this.settingsDescribeValue = result.value + return this.legacyWelcomeAcknowledged ? { ...result, value: patchWelcomeDescribe(result.value) } : undefined + } + if (endpoint !== 'settings/mutate' || !isRecord(payload) || !isRecord(payload.args)) return undefined + const args = payload.args + if (args.ns !== WELCOME_NOTICE_NAMESPACE || !isWelcomeNoticeOperation(args.ops)) return undefined + // Older Hosts reject the 0.1.7 onboarding field before returning a usable + // settings snapshot. Treat the acknowledgement as client-local in that + // case; a later describe is patched when one becomes available. + const value = patchWelcomeDescribe(this.settingsDescribeValue ?? { namespaces: [] }) + this.legacyWelcomeAcknowledged = true + return { ok: true, value } + } + + async open(endpoint: string, payload: unknown, signal: AbortSignal): Promise> { + signal.throwIfAborted() + if (endpoint === 'session/follow') { + const sessionId = extractSessionIdFromGatewayPayload(payload) + const cached = sessionId === undefined + ? undefined + : this.historyCache.getFollowSnapshot(this.client, sessionId) + if (cached !== undefined && cached.sameClient && sessionId !== undefined) { + return this.iterateWithCachedSnapshot(sessionId, cached.snapshot, cached.cursor, endpoint, payload, signal) + } + try { + return await this.openRaw(endpoint, payload, signal, sessionId, cached?.snapshot) + } catch (error) { + if (cached !== undefined && !signal.aborted && !(isRecord(error) && error.isDSHRemoteError === true)) { + return this.iterateFallbackSnapshot(cached.snapshot, signal) + } + throw error + } + } + return this.openRaw(endpoint, payload, signal) + } + + private async openRaw( + endpoint: string, + payload: unknown, + signal: AbortSignal, + sessionId?: string, + fallbackSnapshot?: Record, + ): Promise> { + signal.throwIfAborted() + const streamId = uuidV7() + const queue = new AsyncValueQueue() + const lifetime = new AbortController() + const transferSignal = AbortSignal.any([signal, lifetime.signal]) + let disconnected = false + const unsubscribe = this.client.onEvent(event => routeStreamEvent(event, streamId, queue)) + const unsubscribeClose = this.client.onClose(() => { + disconnected = true + lifetime.abort() + queue.fail(new RemoteClientError('TRANSPORT_CLOSED', 'The remote Harness stream transport closed.')) + }) + const onAbort = () => { + lifetime.abort() + queue.close() + unsubscribe() + unsubscribeClose() + void this.client.rpc('harness.remote.stream.close', { streamId }, undefined, { timeoutMs: 5000 }).catch(() => undefined) + } + signal.addEventListener('abort', onAbort, { once: true }) + try { + if (this.frameTransfers === undefined) { + const description = await this.client.rpc('harness.transport.describe', {}, signal) + this.frameTransfers = isRecord(description) && Array.isArray(description.capabilities) + && description.capabilities.includes('harness.remote.stream.transfer.v1') + } + signal.throwIfAborted() + await this.client.rpc('harness.remote.stream.open', { + streamId, endpoint, payload, ...(this.frameTransfers ? { transferFrames: true } : {}), + }, signal) + } catch (error) { + signal.removeEventListener('abort', onAbort) + unsubscribe() + unsubscribeClose() + lifetime.abort() + void this.client.rpc('harness.remote.stream.close', { streamId }).catch(() => undefined) + await this.deferDisconnect(error, disconnected, signal) + throw error + } + return this.iterate( + streamId, + endpoint, + queue, + unsubscribe, + unsubscribeClose, + signal, + onAbort, + lifetime, + transferSignal, + () => disconnected, + sessionId, + fallbackSnapshot, + ) + } + + private async *iterateWithCachedSnapshot( + sessionId: string, + cachedSnapshot: Record, + initialCursor: number, + endpoint: string, + payload: unknown, + signal: AbortSignal, + ): AsyncGenerator { + const upstreamController = new AbortController() + const onAbort = () => upstreamController.abort() + signal.addEventListener('abort', onAbort, { once: true }) + const upstreamPromise = this.openRaw(endpoint, payload, upstreamController.signal, sessionId) + void upstreamPromise.catch(() => undefined) + let upstreamIterator: AsyncIterator | undefined + let lastCursor = initialCursor + let assistantRevision = 0 + let resyncRequired = false + const backfillRange = async (fromExclusive: number, toInclusive: number): Promise & { event: Record & { seq: number } }> | undefined> => { + const missingCount = toInclusive - fromExclusive + if (missingCount <= 0) return [] + if (missingCount > 200) return undefined + const backfilled = await this.dispatchRemote( + 'session/page', + { + args: { + request: { + address: { kind: 'session', sessionId }, + throughSeq: toInclusive, + maxMessages: missingCount, + }, + }, + }, + upstreamController.signal, + ).catch(() => undefined) + if (!backfilled?.ok || !isRecord(backfilled.value) || !Array.isArray(backfilled.value.records)) { + return undefined + } + const records = backfilled.value.records.filter( + (record): record is Record & { event: Record & { seq: number } } => + isRecord(record) && isRecord(record.event) && typeof record.event.seq === 'number' + && record.event.seq > fromExclusive && record.event.seq <= toInclusive, + ) + if (records.length !== missingCount) return undefined + for (let index = 0; index < records.length; index += 1) { + if (records[index]!.event.seq !== fromExclusive + index + 1) return undefined + } + return records + } + try { + signal.throwIfAborted() + yield cachedSnapshot + const upstream = await upstreamPromise + upstreamIterator = upstream[Symbol.asyncIterator]() + while (true) { + const next = await upstreamIterator.next() + if (next.done) break + const item = next.value + if (isRecord(item) && item.type === 'snapshot') { + const upstreamCursor = typeof item.cursor === 'number' ? item.cursor : lastCursor + if (upstreamCursor < lastCursor) { + this.historyCache.recordFollowSnapshot(this.client, sessionId, item) + resyncRequired = true + throw new RemoteClientError('TRANSPORT_CLOSED', 'Remote session history cursor was reset; reopen to resync.') + } + if (Array.isArray(item.records)) { + const newerRecords = item.records.filter( + (record): record is Record & { event: Record & { seq: number } } => + isRecord(record) && isRecord(record.event) && typeof record.event.seq === 'number' && record.event.seq > lastCursor, + ) + for (const record of newerRecords) { + if (record.event.seq <= lastCursor) continue + if (record.event.seq > lastCursor + 1) { + const recovered = await backfillRange(lastCursor, record.event.seq - 1) + if (recovered === undefined) { + this.historyCache.recordFollowSnapshot(this.client, sessionId, item) + resyncRequired = true + throw new RemoteClientError('TRANSPORT_CLOSED', 'Remote session history gap requires resync.') + } + this.historyCache.prependBackfilledRecords(this.client, sessionId, recovered) + for (const missing of recovered) { + lastCursor = missing.event.seq + yield missing + } + } + lastCursor = record.event.seq + yield record + } + } + if (upstreamCursor > lastCursor) { + const recovered = await backfillRange(lastCursor, upstreamCursor) + if (recovered === undefined) { + this.historyCache.recordFollowSnapshot(this.client, sessionId, item) + resyncRequired = true + throw new RemoteClientError('TRANSPORT_CLOSED', 'Remote session history cursor gap requires resync.') + } + this.historyCache.prependBackfilledRecords(this.client, sessionId, recovered) + for (const missing of recovered) { + lastCursor = missing.event.seq + yield missing + } + } + if (isRecord(item.projections) && isRecord(item.projections.values)) { + const cachedProjections = isRecord(cachedSnapshot.projections) && isRecord(cachedSnapshot.projections.values) + ? cachedSnapshot.projections.values + : undefined + const asOfSeq = typeof item.projections.asOfSeq === 'number' ? item.projections.asOfSeq : lastCursor + for (const [key, value] of Object.entries(item.projections.values)) { + if (cachedProjections === undefined || JSON.stringify(cachedProjections[key]) !== JSON.stringify(value)) { + yield { type: 'projection', key, seq: asOfSeq, value } + } + } + } + if (isRecord(item.assistantStream)) { + const cachedAssistant = isRecord(cachedSnapshot.assistantStream) ? cachedSnapshot.assistantStream : undefined + const hasActiveStream = item.assistantStream.active === true + || item.assistantStream.message != null + || (Array.isArray(item.assistantStream.entries) && item.assistantStream.entries.length > 0) + const cachedHadActiveStream = cachedAssistant !== undefined && ( + cachedAssistant.active === true + || cachedAssistant.message != null + || (Array.isArray(cachedAssistant.entries) && cachedAssistant.entries.length > 0) + ) + if (hasActiveStream || cachedHadActiveStream) { + yield { + type: 'assistant-stream', + frame: { + ...item.assistantStream, + revision: ++assistantRevision, + }, + } + } + } + continue + } + if (isRecord(item) && item.type === 'event' && isRecord(item.event) && typeof item.event.seq === 'number') { + if (item.event.seq <= lastCursor) continue + if (item.event.seq > lastCursor + 1) { + const recovered = await backfillRange(lastCursor, item.event.seq - 1) + if (recovered === undefined) { + this.historyCache.invalidateSession(sessionId) + resyncRequired = true + throw new RemoteClientError('TRANSPORT_CLOSED', 'Remote session live event gap requires resync.') + } + this.historyCache.prependBackfilledRecords(this.client, sessionId, [...recovered, item]) + for (const missing of recovered) { + lastCursor = missing.event.seq + yield missing + } + } + lastCursor = item.event.seq + yield item + continue + } + if (isRecord(item) && item.type === 'assistant-stream' && isRecord(item.frame)) { + yield { + ...item, + frame: { + ...item.frame, + revision: ++assistantRevision, + }, + } + continue + } + yield item + } + } catch (error) { + if (signal.aborted) return + if (resyncRequired || (isRecord(error) && error.isDSHRemoteError === true)) throw error + if (this.deferStreamDisconnect) { + await new Promise(resolve => signal.addEventListener('abort', () => resolve(), { once: true })) + return + } + throw error + } finally { + signal.removeEventListener('abort', onAbort) + upstreamController.abort() + await upstreamIterator?.return?.().catch(() => undefined) + } + } + + private async *iterateFallbackSnapshot( + snapshot: Record, + signal: AbortSignal, + ): AsyncGenerator { + signal.throwIfAborted() + yield snapshot + if (this.deferStreamDisconnect && !signal.aborted) { + await new Promise(resolve => signal.addEventListener('abort', () => resolve(), { once: true })) + } + } + + private async *iterate( + streamId: string, + endpoint: string, + queue: AsyncValueQueue, + unsubscribe: () => void, + unsubscribeClose: () => void, + signal: AbortSignal, + onAbort: () => void, + lifetime: AbortController, + transferSignal: AbortSignal, + disconnected: () => boolean, + sessionId?: string, + fallbackSnapshot?: Record, + ): AsyncGenerator { + let resolvedSessionId = sessionId ?? '' + try { + for await (const item of queue) { + let frame = item as HarnessRemoteFrameData + if (frame.transfer !== undefined) { + if (!this.frameTransfers || Object.hasOwn(frame, 'value')) throw new Error('Unnegotiated or ambiguous Harness Remote stream transfer') + const descriptor = frame.transfer + try { + const decoded = await this.readTransferred(descriptor, transferSignal) + if (!isRecord(decoded) || decoded.streamId !== streamId || decoded.hasValue !== true || Object.hasOwn(decoded, 'transfer')) { + throw new Error('Invalid Harness Remote transferred stream frame') + } + frame = decoded as unknown as HarnessRemoteFrameData + } finally { + if (typeof descriptor.transferId === 'string') { + await this.client.rpc('harness.remote.transfer.close', { transferId: descriptor.transferId }, undefined, { timeoutMs: 5000 }).catch(() => undefined) + } + } + } + transferSignal.throwIfAborted() + const value = frame.value + const normalized = this.compatibility === 'legacy-to-v3' + ? normalizeLegacySessionGatewayValue(endpoint, value) + : normalizeAssistantMessageStreamValue(endpoint, value) + if (endpoint === 'session/follow' && isRecord(normalized)) { + if (normalized.type === 'snapshot') { + if (resolvedSessionId.length === 0 && isRecord(normalized.header) && typeof normalized.header.id === 'string') { + resolvedSessionId = normalized.header.id + } + this.historyCache.recordFollowSnapshot(this.client, resolvedSessionId, normalized) + } else { + this.historyCache.recordFollowFrame(this.client, resolvedSessionId, normalized) + } + } + yield normalized + } + } catch (error) { + void fallbackSnapshot + await this.deferDisconnect(error, disconnected(), signal) + throw error + } finally { + lifetime.abort() + signal.removeEventListener('abort', onAbort) + unsubscribe() + unsubscribeClose() + queue.close() + await this.client.rpc('harness.remote.stream.close', { streamId }).catch(() => undefined) + } + } + + private async deferDisconnect(error: unknown, disconnected: boolean, signal: AbortSignal): Promise { + if (!this.deferStreamDisconnect || !disconnected || signal.aborted) return + // Host business/permission failures remain terminal, even if a transport + // close races them. Only the actual onClose path may defer a failure; + // queue overflow uses TRANSPORT_CLOSED too but must not hang forever. + if (isRecord(error) && error.isDSHRemoteError === true) return + // Keep the native consumer alive until its carrier is replaced (or the + // page/selection is disposed). Do not reopen streams or replay RPCs here. + await new Promise(resolve => signal.addEventListener('abort', () => resolve(), { once: true })) + } + + private async callTransferred(encoded: Uint8Array, signal: AbortSignal): Promise { + if (encoded.byteLength > MAX_HARNESS_API_TRANSFER_BYTES) { + throw new Error('The Harness Remote request exceeds the transfer limit.') + } + const transferId = uuidV7() + const totalChunks = Math.ceil(encoded.byteLength / HARNESS_API_TRANSFER_CHUNK_BYTES) + let opened = false + try { + await this.client.rpc('harness.remote.transfer.open', { + transferId, + totalBytes: encoded.byteLength, + totalChunks, + }, signal) + opened = true + for (let index = 0; index < totalChunks; index += 1) { + const start = index * HARNESS_API_TRANSFER_CHUNK_BYTES + const chunk = encoded.subarray(start, Math.min(start + HARNESS_API_TRANSFER_CHUNK_BYTES, encoded.byteLength)) + await this.client.rpc('harness.remote.transfer.chunk', { + transferId, + index, + data: bytesToBase64(chunk), + }, signal) + } + const committed = await this.client.rpc( + 'harness.remote.transfer.commit', + { transferId }, + signal, + ) + if (committed.kind === 'inline') return committed.response + if (committed.transferId !== transferId) { + throw new Error('The remote Host returned an invalid Harness Remote transfer descriptor.') + } + return await this.readTransferred(committed, signal) + } finally { + if (opened) await this.client.rpc('harness.remote.transfer.close', { transferId }).catch(() => undefined) + } + } + + private async readTransferred(committed: Extract, signal: AbortSignal): Promise { + if (committed.kind !== 'chunked' || typeof committed.transferId !== 'string' + || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(committed.transferId) + || !Number.isSafeInteger(committed.totalBytes) || committed.totalBytes <= 0 + || committed.totalBytes > MAX_HARNESS_API_TRANSFER_BYTES + || committed.totalChunks !== Math.ceil(committed.totalBytes / HARNESS_API_TRANSFER_CHUNK_BYTES)) { + throw new Error('The remote Host returned an invalid Harness Remote transfer descriptor.') + } + signal.throwIfAborted() + const { transferId } = committed + const responseBytes = new Uint8Array(committed.totalBytes) + let offset = 0 + for (let index = 0; index < committed.totalChunks; index += 1) { + const result = await this.client.rpc( + 'harness.remote.transfer.read', + { transferId, index }, + signal, + ) + if (result.transferId !== transferId || result.index !== index) { + throw new Error('The remote Host returned an out-of-order Harness Remote transfer chunk.') + } + const chunk = base64ToBytes(result.data) + const expectedBytes = Math.min(HARNESS_API_TRANSFER_CHUNK_BYTES, committed.totalBytes - offset) + if (chunk.byteLength !== expectedBytes) { + throw new Error('The remote Host returned an invalid Harness Remote transfer chunk.') + } + responseBytes.set(chunk, offset) + offset += chunk.byteLength + } + return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(responseBytes)) as unknown + } +} + +class AsyncValueQueue implements AsyncIterable { + private readonly values: Array<{ value: unknown; bytes: number }> = [] + private bytes = 0 + private readonly waiters: Array<(result: IteratorResult) => void> = [] + private closed = false + private error?: Error + + push(value: unknown): void { + if (this.closed) return + const waiter = this.waiters.shift() + if (waiter !== undefined) { waiter({ done: false, value }); return } + const bytes = new TextEncoder().encode(JSON.stringify(value) ?? '').byteLength + if (this.values.length >= 256 || this.bytes + bytes > 4 * 1024 * 1024) { + this.values.length = 0; this.bytes = 0 + this.fail(new RemoteClientError('TRANSPORT_CLOSED', 'Remote stream consumer is too slow; reconnect to recover.')) + return + } + this.bytes += bytes + this.values.push({ value, bytes }) + } + + close(): void { + if (this.closed) return + this.closed = true + for (const waiter of this.waiters.splice(0)) waiter({ done: true, value: undefined }) + } + + fail(error: Error): void { + if (this.closed) return + this.error = error + this.close() + } + + async *[Symbol.asyncIterator](): AsyncIterator { + while (true) { + if (this.values.length > 0) { + const entry = this.values.shift()! + this.bytes -= entry.bytes + yield entry.value + continue + } + if (this.closed) { + if (this.error !== undefined) throw this.error + return + } + const next = await new Promise>(resolve => this.waiters.push(resolve)) + if (next.done) { + if (this.error !== undefined) throw this.error + return + } + yield next.value + } + } +} + +function routeStreamEvent(event: EventPayload, streamId: string, queue: AsyncValueQueue): void { + if (event.event === 'harness.remote.frame') { + const data = event.data as Partial + if (data.streamId === streamId && data.hasValue === true) queue.push(data) + return + } + if (event.event !== 'harness.remote.stream.closed') return + const data = event.data as Partial + if (data.streamId !== streamId) return + if (data.reason === 'failed') { + const failure = data.failure + queue.fail(remoteFailure({ + code: typeof failure?.code === 'string' ? failure.code : 'internal', + message: typeof failure?.message === 'string' ? failure.message : 'The remote Harness stream failed.', + details: isRecord(failure?.details) ? failure.details : {}, + })) + } else { + queue.close() + } +} + +function parseRpcResult(value: unknown): TypertRpcResult { + if (!isRecord(value)) throw new Error('The remote Host returned an invalid Gateway result.') + if (value.ok === true) return Object.hasOwn(value, 'value') ? { ok: true, value: value.value } : { ok: true } + if (value.ok !== false || !isRecord(value.error) + || typeof value.error.code !== 'string' + || typeof value.error.message !== 'string' + || !isRecord(value.error.details)) { + throw new Error('The remote Host returned an invalid Gateway failure.') + } + return { + ok: false, + error: { code: value.error.code, message: value.error.message, details: value.error.details }, + } +} + +function remoteFailure(failure: { code: string; message: string; details: Record }): Error { + // v0.1.2-alpha.2+ identifies RemoteError values structurally across bundles and + // realms. Keep this carrier dependency-free so the same build still runs on + // older Harness releases, while preserving current stream failures at the local mux. + return Object.assign(new Error(failure.message), { + isDSHRemoteError: true as const, + code: failure.code, + details: failure.details, + }) +} + +function bytesToBase64(bytes: Uint8Array): string { + let binary = '' + for (let offset = 0; offset < bytes.byteLength; offset += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(offset, Math.min(offset + 0x8000, bytes.byteLength))) + } + return btoa(binary) +} + +function base64ToBytes(value: string): Uint8Array { + let binary: string + try { + binary = atob(value) + } catch { + throw new Error('The remote Host returned malformed Harness Remote transfer data.') + } + const bytes = new Uint8Array(binary.length) + for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index) + if (bytesToBase64(bytes) !== value) throw new Error('The remote Host returned non-canonical Harness Remote transfer data.') + return bytes +} + +/** Restore binary fields after the JSON-only Remote carrier. */ +function normalizeWorkspaceBinaryResult(endpoint: string, value: unknown): unknown { + if (endpoint !== 'workspaceFiles/readBytes' && endpoint !== 'officeToPdf/render') return value + if (!isRecord(value) || typeof value.data !== 'string') return value + return { ...value, data: base64ToBytes(value.data) } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function hasErrorCode(error: unknown, code: string): boolean { + return error instanceof Error && 'code' in error && error.code === code +} + +function isLegacyRemoteHost(version: string | undefined): boolean { + if (version === undefined) return false + const match = /^(?:dsh-)?v?(\d+)\.(\d+)\.(\d+)(?:-|$)/u.exec(version.trim()) + if (match === null) return false + return Number(match[1]) === 0 && Number(match[2]) === 1 && Number(match[3]) < 7 +} + +function isWelcomeNoticeOperation(value: unknown): boolean { + return Array.isArray(value) && value.some(operation => ( + isRecord(operation) + && operation.op === 'set' + && Array.isArray(operation.path) + && operation.path.length === 1 + && operation.path[0] === WELCOME_NOTICE_FIELD + && operation.value === WELCOME_NOTICE_VERSION + )) +} + +function patchWelcomeDescribe(value: Record): Record { + if (!Array.isArray(value.namespaces)) return value + const namespaces = value.namespaces.map(namespace => { + if (!isRecord(namespace) || namespace.ns !== WELCOME_NOTICE_NAMESPACE) return namespace + const current = isRecord(namespace.value) ? namespace.value : {} + return { ...namespace, value: { ...current, [WELCOME_NOTICE_FIELD]: WELCOME_NOTICE_VERSION } } + }) + return { ...value, namespaces } +} + +/** Older Hosts return the exact projection cut without RC.1's discriminator. */ +function normalizeProjectionResult(endpoint: string, value: unknown): unknown { + if (endpoint !== 'session/projections' || !isRecord(value) || value.kind !== undefined) return value + return Number.isSafeInteger(value.asOfSeq) && isRecord(value.values) ? { ...value, kind: 'sequenced' } : value +} + +/** + * RC.1's ThemeRuntime reads the new font fields before providing `theme`. + * A 0.2.0 Host's valid theme section lacks them and otherwise crashes web boot. + * Supply only absent display defaults in the received view; keep the Host's + * schema, revision, write results and persisted settings authoritative. + */ +function normalizeThemeSettingsResult(endpoint: string, result: TypertRpcResult): TypertRpcResult { + if (!result.ok || !isRecord(result.value)) return result + const value = result.value + if (endpoint === 'settings/describe' && Array.isArray(value.namespaces)) { + const original = value.namespaces + const namespaces = original.map(normalizeThemeNamespace) + return namespaces.some((row, index) => row !== original[index]) + ? { ...result, value: { ...value, namespaces } } + : result + } + if (['settings/update', 'settings/replace', 'settings/mutate'].includes(endpoint) && value.ok === true) { + const namespace = normalizeThemeNamespace(value.value) + if (namespace !== value.value) return { ...result, value: { ...value, value: namespace } } + } + return result +} + +function normalizeThemeNamespace(namespace: unknown): unknown { + if (!isRecord(namespace) || namespace.ns !== 'ui-theme' || !isRecord(namespace.value)) return namespace + const section = namespace.value + const defaults: Record = { + codeFontSize: 11, + terminalFontSize: 13, + textFontFamily: '', + codeFontFamily: '', + terminalFontFamily: '', + } + const missing = Object.entries(defaults).filter(([field]) => section[field] === undefined) + return missing.length === 0 ? namespace : { + ...namespace, + value: { ...section, ...Object.fromEntries(missing) }, + } +}