diff --git a/apps/mobile/src/connection/runtime.ts b/apps/mobile/src/connection/runtime.ts index 57b02cf03051f..fb90ade275ee2 100644 --- a/apps/mobile/src/connection/runtime.ts +++ b/apps/mobile/src/connection/runtime.ts @@ -5,6 +5,7 @@ import { BoundedThreadSnapshotLoader, ThreadHistoryController, } from "@t3tools/client-runtime/state/threads"; +import { SOCKET_RPC_CODEC_SCHEMA_BINARY } from "@t3tools/shared/socketFrameParts"; import { Platform } from "react-native"; import * as Layer from "effect/Layer"; import { Atom } from "effect/reactivity"; @@ -12,6 +13,7 @@ import { Atom } from "effect/reactivity"; import type { FoundationHotModule } from "../lib/foundation-fast-refresh"; import { hotSwappableAtomRuntime } from "../lib/hot-swappable-atom-runtime"; import * as Runtime from "../lib/runtime"; +import * as NativeWebSocket from "../native/nativeWebSocket"; import { appAtomRegistry } from "../state/atom-registry"; import * as BackgroundActivity from "./background-activity"; import * as ConnectionPlatform from "./platform"; @@ -46,6 +48,10 @@ const layerProvidedClientConnection = layerSnapshotLoader.pipe( providerCatalogsOnDemand: true, providerCatalogDigests: true, providerStatusDeltas: true, + // Android stays on JSON: RN's WebSocketModule.kt base64-encodes binary frames over the bridge. + ...(NativeWebSocket.supportsNativeBinaryWebSocket + ? { rpcCodec: SOCKET_RPC_CODEC_SCHEMA_BINARY } + : {}), // Halves idle pings. The timeout is checked on ping ticks, after an unanswered ping // and 15 s with no frame: within 25 s of the last frame (20 s at the 5 s default), // and a host stalled for 10 s can lose the socket (15 s at the default). diff --git a/apps/mobile/src/native/nativeWebSocket.ios.ts b/apps/mobile/src/native/nativeWebSocket.ios.ts index 9cea3c4197daf..669d9f04d605f 100644 --- a/apps/mobile/src/native/nativeWebSocket.ios.ts +++ b/apps/mobile/src/native/nativeWebSocket.ios.ts @@ -188,6 +188,8 @@ function layerFromModule(native: NativeModule): Layer.Layer("T3WebSocket"); +export const supportsNativeBinaryWebSocket = native !== null; + // A dev client built before this module shipped still has SocketRocket. export const layer: Layer.Layer = native === null ? Socket.layerWebSocketConstructorGlobal : layerFromModule(native); diff --git a/apps/mobile/src/native/nativeWebSocket.ts b/apps/mobile/src/native/nativeWebSocket.ts index 00c40e5a9e885..9c036f08210a4 100644 --- a/apps/mobile/src/native/nativeWebSocket.ts +++ b/apps/mobile/src/native/nativeWebSocket.ts @@ -1,3 +1,5 @@ import * as Socket from "effect/socket/Socket"; +export const supportsNativeBinaryWebSocket = false; + export const layer = Socket.layerWebSocketConstructorGlobal; diff --git a/apps/server/src/environment/ServerEnvironment.test.ts b/apps/server/src/environment/ServerEnvironment.test.ts index 682518d242d47..c893b6d62348b 100644 --- a/apps/server/src/environment/ServerEnvironment.test.ts +++ b/apps/server/src/environment/ServerEnvironment.test.ts @@ -327,6 +327,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("ServerEnvironmen expect(second.capabilities.serverResolvedCommandContext).toBe(true); expect(second.capabilities.projectProviderInstanceOverrides).toBe(true); expect(second.capabilities.wsAckWindow).toBe(4); + expect(second.capabilities.wsRpcCodecs).toEqual(["json", "schema-binary"]); expect(second.capabilities.agentActivityPublishing).toBe(false); }), ); diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 6d5ff51ac0602..4359bb82a3b7c 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -5,7 +5,11 @@ import { type ExecutionEnvironmentDescriptor, } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; -import { MAX_SOCKET_ACK_WINDOW } from "@t3tools/shared/socketFrameParts"; +import { + MAX_SOCKET_ACK_WINDOW, + SOCKET_RPC_CODEC_JSON, + SOCKET_RPC_CODEC_SCHEMA_BINARY, +} from "@t3tools/shared/socketFrameParts"; import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Deferred from "effect/Deferred"; @@ -315,6 +319,7 @@ export const make = Effect.gen(function* () { htmlPreviewTheme: true, agentFeedback: true, wsAckWindow: MAX_SOCKET_ACK_WINDOW, + wsRpcCodecs: [SOCKET_RPC_CODEC_JSON, SOCKET_RPC_CODEC_SCHEMA_BINARY], }, }; diff --git a/apps/server/src/socketHeartbeat.test.ts b/apps/server/src/socketHeartbeat.test.ts index 7b13d979e27db..c09fe9463f8ba 100644 --- a/apps/server/src/socketHeartbeat.test.ts +++ b/apps/server/src/socketHeartbeat.test.ts @@ -1,4 +1,5 @@ import { assert, describe, it } from "@effect/vitest"; +import { SCHEMA_BINARY_PONG_FRAME } from "@t3tools/shared/socketFrameParts"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Scope from "effect/Scope"; @@ -65,4 +66,33 @@ describe("withSocketHeartbeat", () => { yield* Scope.close(scope, Exit.void); }), ); + + it.effect("writes binary Pong heartbeat frames when configured for SchemaBinary sockets", () => + Effect.gen(function* () { + const written: Array = []; + const socket = withSocketHeartbeat( + Socket.make({ + reader: Effect.never, + writer: Effect.succeed({ + write: (chunk) => Effect.sync(() => void written.push(chunk)), + writeAll: (chunks) => Effect.sync(() => void written.push(...chunks)), + }), + }), + { frame: SCHEMA_BINARY_PONG_FRAME }, + ); + const scope = yield* Scope.make(); + const writer = yield* Scope.provide(socket.writer, scope); + + const outbound = new Uint8Array([1, 2, 3]); + yield* TestClock.adjust("15 seconds"); + yield* writer.write(outbound); + yield* TestClock.adjust("15 seconds"); + assert.deepStrictEqual(written, [outbound]); + + yield* TestClock.adjust("5 seconds"); + assert.deepStrictEqual(written, [outbound, SCHEMA_BINARY_PONG_FRAME]); + + yield* Scope.close(scope, Exit.void); + }), + ); }); diff --git a/apps/server/src/socketHeartbeat.ts b/apps/server/src/socketHeartbeat.ts index 185c85480fa63..a5b01e67068c6 100644 --- a/apps/server/src/socketHeartbeat.ts +++ b/apps/server/src/socketHeartbeat.ts @@ -12,8 +12,16 @@ export const SOCKET_HEARTBEAT_FRAME = '{"_tag":"Pong"}'; const SOCKET_HEARTBEAT_INTERVAL_NANOS = Duration.toNanosUnsafe(SOCKET_HEARTBEAT_INTERVAL); +export interface SocketHeartbeatOptions { + readonly frame?: string | Uint8Array; +} + /** Server side: writes a heartbeat frame after an idle interval for as long as the writer is open. */ -export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket { +export function withSocketHeartbeat( + socket: Socket.Socket, + options?: SocketHeartbeatOptions, +): Socket.Socket { + const frame = options?.frame ?? SOCKET_HEARTBEAT_FRAME; return Socket.make({ reader: socket.reader, writer: Effect.gen(function* () { @@ -35,7 +43,7 @@ export function withSocketHeartbeat(socket: Socket.Socket): Socket.Socket { } // Stamp before writing so an ignored write failure still sleeps a full interval. markWrite(); - yield* writer.write(SOCKET_HEARTBEAT_FRAME).pipe(Effect.ignore); + yield* writer.write(frame).pipe(Effect.ignore); } }); diff --git a/apps/server/src/terminal/OutputProtocol.test.ts b/apps/server/src/terminal/OutputProtocol.test.ts index 19846af2ec70a..fb9899bb5948e 100644 --- a/apps/server/src/terminal/OutputProtocol.test.ts +++ b/apps/server/src/terminal/OutputProtocol.test.ts @@ -5,10 +5,12 @@ import { TerminalAttachStreamEvent as TerminalAttachStreamEventSchema, WS_METHODS, } from "@t3tools/contracts"; +import { layerSocketSchemaBinary } from "@t3tools/shared/socketFrameParts"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { Rpc, RpcGroup, RpcMessage, RpcSerialization, RpcServer } from "effect/rpc"; @@ -262,6 +264,81 @@ describe("terminal output window", () => { assert.equal((yield* Queue.take(responses))._tag, "Exit"); }).pipe(Effect.provide(RpcSerialization.layerJson)), ); + + it.effect( + "enforces byte-window backpressure on terminalAttach under SchemaBinary Uint8Array chunks", + () => + Effect.gen(function* () { + const tag = WS_METHODS.terminalAttach; + const group = RpcGroup.make( + Rpc.make(tag, { success: TerminalAttachStreamEventSchema, stream: true }), + ); + const serialization = yield* RpcSerialization.RpcSerialization; + const encodeVoid = Schema.encodeEffect(serialization.codecFor(Schema.Void)); + const decodeChunk = Schema.decodeUnknownEffect( + serialization.codecFor(Schema.NonEmptyArray(TerminalAttachStreamEventSchema)), + ); + const output = yield* Queue.unbounded(); + const responses = yield* Queue.unbounded(); + const receive = yield* Deferred.make[0]>(); + const protocol = yield* RpcServer.Protocol.make((write) => + Effect.gen(function* () { + yield* Deferred.succeed(receive, write); + return { + disconnects: yield* Queue.unbounded(), + send: (_clientId, response) => Queue.offer(responses, response), + end: () => Effect.void, + clientIds: Effect.succeed(new Set([0])), + initialMessage: Effect.succeedNone, + supportsAck: true, + supportsTransferables: false, + supportsSpanPropagation: false, + supportsNotifications: true, + codecFor: serialization.codecFor, + }; + }), + ); + yield* RpcServer.make(group).pipe( + Effect.provide(group.toLayerHandler(tag, () => Stream.fromQueue(output))), + Effect.provideService(RpcServer.Protocol, withOutputWindow(protocol, { ackWindow: 4 })), + Effect.forkScoped, + ); + const write = yield* Deferred.await(receive); + yield* write(0, { + _tag: "Request", + id: "1", + tag, + payload: yield* encodeVoid(undefined), + headers: [], + }); + + const large = eventWith("data", "x".repeat(64 * 1024)); + yield* Queue.offer(output, large); + yield* TestClock.adjust(0); + const first = yield* Queue.take(responses); + assert.equal(first._tag, "Chunk"); + if (first._tag === "Chunk") { + assert.instanceOf(first.values, Uint8Array); + assert.deepEqual(yield* decodeChunk(first.values), [large]); + } + + const next = eventWith("data", "after-large"); + yield* Queue.offer(output, next); + yield* TestClock.adjust(0); + assert.equal(yield* Queue.size(responses), 0); + + yield* write(0, { _tag: "Ack", requestId: "1" }); + const resumed = yield* Queue.take(responses); + assert.equal(resumed._tag, "Chunk"); + if (resumed._tag === "Chunk") { + assert.instanceOf(resumed.values, Uint8Array); + assert.deepEqual(yield* decodeChunk(resumed.values), [next]); + } + + yield* write(0, { _tag: "Interrupt", requestId: "1" }); + assert.equal((yield* Queue.take(responses))._tag, "Exit"); + }).pipe(Effect.provide(layerSocketSchemaBinary)), + ); }); const output = (data: string): TerminalAttachStreamEvent => ({ diff --git a/apps/server/src/terminal/OutputProtocol.ts b/apps/server/src/terminal/OutputProtocol.ts index 23c912e771014..abd6fbed01017 100644 --- a/apps/server/src/terminal/OutputProtocol.ts +++ b/apps/server/src/terminal/OutputProtocol.ts @@ -57,13 +57,17 @@ const queuedSize = (event: TerminalEvent | TerminalAttachStreamEvent) => byteLengthOf(event.snapshot.label) : 0); -// Byte-windowed streams carry TerminalAttachStreamEvent, whose encoded form is the -// event itself, so charge it like the output queue does instead of serializing twice. -const chunkSize = (values: ReadonlyArray) => - values.reduce( - (total, value) => total + queuedSize(value as TerminalAttachStreamEvent), - EVENT_OVERHEAD, - ); +// Byte-windowed streams carry TerminalAttachStreamEvent (array on JSON, Uint8Array on binary), +// so charge the already-encoded size instead of re-serializing. +const chunkSize = (values: unknown) => + values instanceof Uint8Array + ? EVENT_OVERHEAD + values.byteLength + : Array.isArray(values) + ? values.reduce( + (total, value) => total + queuedSize(value as TerminalAttachStreamEvent), + EVENT_OVERHEAD, + ) + : EVENT_OVERHEAD; interface Window { readonly bytes: boolean; diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 274afacedee68..c3a7115c7d579 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -1,8 +1,9 @@ import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer"; -import { WebSocket } from "@effect/platform-node/NodeWS"; +import { layerWebSocketConstructor, WebSocket } from "@effect/platform-node/NodeWS"; // @effect-diagnostics-next-line nodeBuiltinImport:off -- Bind an isolated WebSocket negotiation fixture. import * as NodeHttp from "node:http"; +import * as NodeZlib from "node:zlib"; import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; @@ -12,6 +13,8 @@ import { AuthOrchestrationOperateScope, AuthOrchestrationReadScope, AuthProvidersManageScope, + CommandId, + DEFAULT_SERVER_SETTINGS, type ManagedPolicySummary, type WorkflowRun, type WorkflowStep, @@ -20,11 +23,13 @@ import { AuthTerminalOperateScope, ORCHESTRATION_PROTOCOL_VERSION, ORCHESTRATION_PROTOCOL_QUERY_PARAM, + ORCHESTRATION_V2_WS_METHODS, EnvironmentId, EventId, GitManagerError, VcsProcessSpawnError, MessageId, + NodeId, mcpClientScopes, ProjectId, ThreadId, @@ -41,14 +46,25 @@ import { type AuthAccessStreamEvent, type OrchestrationV2AppThread, type OrchestrationV2DomainEvent, + OrchestrationV2ShellStreamItem, type OrchestrationV2StoredEvent, + type OrchestrationV2ThreadProjection, type OrchestrationV2ThreadShell, + OrchestrationV2ThreadStreamItem, + type OrchestrationV2TurnItem, type OrchestrationProjectShell, type ServerConfig, - type ServerConfigStreamEvent, + ServerConfigStreamEvent, type ServerProvider, } from "@t3tools/contracts"; -import { SOCKET_FRAME_PARTS_QUERY_PARAM } from "@t3tools/shared/socketFrameParts"; +import { + joinSocketFrameParts, + layerSocketSchemaBinary, + SCHEMA_BINARY_PING_FRAME, + SOCKET_FRAME_PARTS_QUERY_PARAM, + SOCKET_RPC_CODEC_QUERY_PARAM, + SOCKET_RPC_CODEC_SCHEMA_BINARY, +} from "@t3tools/shared/socketFrameParts"; import * as Deferred from "effect/Deferred"; import type { ProviderInstance } from "@t3tools/provider-core/server/driver"; import * as DateTime from "effect/DateTime"; @@ -61,6 +77,8 @@ import * as Layer from "effect/Layer"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; import * as Queue from "effect/Queue"; +import * as Schema from "effect/Schema"; +import * as Socket from "effect/socket/Socket"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; import { Headers, HttpRouter, HttpServer } from "effect/http"; @@ -69,7 +87,15 @@ import * as FetchHttpClient from "effect/http/FetchHttpClient"; import * as VcsProcess from "./vcs/VcsProcess.ts"; import * as ProviderInstallationGate from "./provider/ProviderInstallationGate.ts"; import * as Ws from "./ws.ts"; -import { RpcGroup, RpcMessage, RpcServer } from "effect/rpc"; +import { + Rpc, + RpcClient, + RpcGroup, + RpcMessage, + RpcSchema, + RpcSerialization, + RpcServer, +} from "effect/rpc"; import * as RpcTest from "effect/rpc/RpcTest"; import * as SqlClient from "effect/sql/SqlClient"; import * as Statement from "effect/sql/Statement"; @@ -3420,3 +3446,910 @@ it.effect("a session that can only read sees a workflow run but cannot steer it" assert.deepEqual(calls, []); }).pipe(Effect.provide(layerWorkflowRpcTest), Effect.scoped), ); + +it.effect("compiles every WsRpcGroup schema under layerSocketSchemaBinary", () => + Effect.gen(function* () { + const serialization = yield* RpcSerialization.RpcSerialization; + assert.isAbove(WsRpcGroup.requests.size, 100); + for (const rpc of WsRpcGroup.requests.values()) { + serialization.codecFor(rpc.payloadSchema); + serialization.codecFor(Rpc.exitSchema(rpc)); + if (RpcSchema.isStreamSchema(rpc.successSchema)) { + serialization.codecFor(Schema.NonEmptyArray(rpc.successSchema.success)); + } + } + serialization.codecFor(Schema.Defect()); + serialization.codecFor(Schema.Exit(Schema.Never, Schema.Never, Schema.Defect())); + }).pipe(Effect.provide(layerSocketSchemaBinary)), +); + +it.live( + "serves WsRpcGroup streams, commands, defects, split frames, and heartbeats over schema-binary", + () => + Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const keybindings = yield* Keybindings.Keybindings; + yield* settings.updateSettings({ speechAcceleration: "gpu:cuda:0" }); + yield* keybindings.upsertKeybindingRule({ + key: "mod+alt+b", + command: "script.build.run", + }); + + const nowIso = "2026-11-01T12:00:00.000Z"; + const nowUtc = DateTime.makeUnsafe(nowIso); + const instanceId = ProviderInstanceId.make("codex"); + const projectId = ProjectId.make("project:binary"); + const threadId = ThreadId.make("thread:binary"); + const runId = RunId.make("run:binary-1"); + const nodeId = NodeId.make("node:binary-1"); + const messageId = MessageId.make("message:binary-1"); + const itemId = TurnItemId.make("item:binary-1"); + const liveItemId = TurnItemId.make("item:binary-live"); + const largeText = "binary-payload-".repeat(15_000); + + const provider: ServerProvider = { + instanceId, + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: "1.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: nowIso, + models: [ + { + slug: "gpt-5", + name: "GPT-5", + isCustom: false, + capabilities: null, + }, + ], + slashCommands: [{ name: "review" }], + skills: [], + }; + const projectShell: OrchestrationProjectShell = { + id: projectId, + title: "Binary Test Project", + workspaceRoot: "/tmp/binary-project", + defaultModelSelection: null, + scripts: [], + createdAt: nowIso, + updatedAt: nowIso, + }; + const threadShell: OrchestrationV2ThreadShell = { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId, + title: "Binary thread", + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + activeProviderThreadId: null, + latestRunId: runId, + activeRunId: null, + status: "completed", + pendingRuntimeRequest: null, + latestVisibleMessage: { + id: messageId, + role: "assistant", + text: "Summary", + updatedAt: nowUtc, + }, + latestUserMessageAt: nowUtc, + hasActionableProposedPlan: false, + pendingBackgroundTasks: [], + providerInstanceHistory: [instanceId], + itemCount: 1, + visibleItemCount: 1, + createdAt: nowUtc, + updatedAt: nowUtc, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, + }; + const appThread: OrchestrationV2AppThread = { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId, + title: "Binary thread", + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: nowUtc, + updatedAt: nowUtc, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: nowUtc, + deletedAt: null, + }; + const largeAssistantItem: OrchestrationV2TurnItem = { + id: itemId, + threadId, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed", + title: null, + startedAt: nowUtc, + completedAt: nowUtc, + updatedAt: nowUtc, + type: "assistant_message", + messageId, + text: largeText, + streaming: false, + }; + const largeProjection: OrchestrationV2ThreadProjection = { + thread: appThread, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: [largeAssistantItem], + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: [ + { + position: 0, + visibility: "local", + sourceThreadId: threadId, + sourceItemId: itemId, + item: largeAssistantItem, + }, + ], + updatedAt: nowUtc, + }; + const liveTurnItem: OrchestrationV2TurnItem = { + ...largeAssistantItem, + id: liveItemId, + ordinal: 1, + text: "live delta complete", + }; + + const liveThreadEvents = yield* Queue.unbounded(); + const enrichmentChanges = + yield* PubSub.unbounded(); + + const services = Layer.mergeAll( + layerUnusedConfigRpcServices, + Layer.mock(ServerBrowser.ServerBrowser)({ + profileReporter: Effect.succeed(() => Effect.void), + }), + Layer.mock(EnvironmentAuth.EnvironmentAuth)({ + authenticateWebSocketUpgrade: () => + Effect.succeed({ + sessionId: AuthSessionId.make("binary-test"), + subject: "one-time-token", + method: "bearer-access-token", + scopes: [AuthOrchestrationReadScope, AuthOrchestrationOperateScope], + }), + getDescriptor: () => + Effect.succeed({ + policy: "loopback-browser", + bootstrapMethods: [], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "binary-test-session", + }), + }), + Layer.mock(SessionStore.SessionStore)({ + cookieName: "binary-test", + legacyCookieName: undefined, + markConnected: () => Effect.void, + markDisconnected: () => Effect.void, + awaitInvalidation: () => Effect.never, + }), + Layer.mock(AnalyticsService.AnalyticsService)({ + recordOwners: () => Effect.void, + record: () => Effect.succeed(true), + }), + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({ + scratchRoot: Effect.succeedNone, + namedProjectsRoot: process.cwd(), + }), + Layer.mock(ThreadWorkspaceService.ThreadWorkspaceService)({}), + Layer.mock(ProviderRegistry.ProviderRegistry)({ + getProviders: Effect.succeed([provider]), + streamChanges: Stream.never, + }), + Layer.mock(UsageLimitSources.UsageLimitSources)({ streamChanges: Stream.make([]) }), + Layer.mock(ExternalLauncher.ExternalLauncher)({ + resolveAvailableEditors: () => Effect.succeed(["file-manager"]), + resolveFileManagerRevealKind: () => Effect.succeed("file-explorer"), + }), + Layer.mock(RemoteOpenTargets.RemoteOpenTargets)({ + resolveTargets: () => Effect.succeed([]), + }), + Layer.mock(DirectEndpoints.DirectEndpoints)({ + resolveAvailable: () => Effect.succeed([]), + resolve: () => Effect.succeed([]), + }), + Layer.mock(ServerEnvironment.ServerEnvironment)({ + getDescriptor: Effect.succeed({ + environmentId: EnvironmentId.make("binary-test"), + label: "Binary test", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.0.0", + capabilities: { + repositoryIdentity: false, + wsRpcCodecs: ["json", SOCKET_RPC_CODEC_SCHEMA_BINARY], + }, + }), + }), + Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({ + enqueueCommand: (effect) => effect, + }), + Layer.mock(OrchestrationEventStore.OrchestrationEventStore)({ + latestApplicationSequence: Effect.succeed(7), + streamProjectedApplicationEvents: () => Stream.never, + }), + Layer.mock(ProjectStore.ProjectStoreV2)({ + listShells: () => Effect.succeed([projectShell]), + }), + Layer.mock(ProjectService.ProjectService)({ + getShell: () => Effect.succeedNone, + }), + Layer.mock(ProjectEnrichment.ProjectEnrichmentService)({ + subscribeChanges: PubSub.subscribe(enrichmentChanges), + getAvailable: () => + Effect.succeed({ + repositoryIdentity: null, + faviconPath: null, + repositoryIdentityResolved: true, + }), + }), + Layer.mock(ThreadManagement.ThreadManagementService)({ + listActiveShellIndex: () => Effect.succeed([]), + readShellSnapshot: () => + Effect.succeed( + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 7, + threads: [threadShell], + archivedThreads: [], + }), + ), + ensureLegacyTranscript: () => Effect.void, + getThreadSnapshotWindow: () => + Effect.succeed({ + schemaVersion: 1, + snapshotSequence: 7, + projection: largeProjection, + }), + streamStoredEventsFrom: () => Stream.fromQueue(liveThreadEvents), + dispatch: (command) => + command.commandId === CommandId.make("cmd-reject") + ? Effect.fail( + new Orchestrator.OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + }), + ) + : Effect.succeed({ sequence: 42, storedEvents: [] }), + }), + Layer.mock(Workflows.Workflows)({ + get: () => Effect.die("boom"), + }), + Layer.mock(VcsProcess.VcsProcess)({ + run: (input) => + Effect.fail( + new VcsProcessSpawnError({ + operation: input.operation, + command: input.command, + cwd: input.cwd, + cause: "No VCS commands in binary WS fixture", + }), + ), + }), + ProviderInstallationGate.layer, + FetchHttpClient.layer, + ); + + const serverContext = yield* Layer.build( + HttpRouter.serve(Ws.layer, { disableListenLog: true }).pipe( + Layer.provideMerge( + NodeHttpServer.layer(NodeHttp.createServer, { + host: "127.0.0.1", + port: 0, + websocket: { perMessageDeflate: true }, + }), + ), + Layer.provide(services), + ), + ); + const server = Context.get(serverContext, HttpServer.HttpServer); + const origin = HttpServer.formatAddress(server.address).replace(/^http/, "ws"); + const binaryUrl = `${origin}/ws?${ORCHESTRATION_PROTOCOL_QUERY_PARAM}=${ORCHESTRATION_PROTOCOL_VERSION}&${SOCKET_FRAME_PARTS_QUERY_PARAM}=1&${SOCKET_RPC_CODEC_QUERY_PARAM}=${SOCKET_RPC_CODEC_SCHEMA_BINARY}`; + + const rawInboundFrames: Array = []; + const observedSocket = yield* Socket.makeWebSocket(binaryUrl, { + headers: { origin: "t3code://app" }, + }).pipe( + Effect.provide(layerWebSocketConstructor), + Effect.map((baseSocket) => + joinSocketFrameParts( + Socket.make({ + reader: Effect.map(baseSocket.reader, (reader) => ({ + ...reader, + pull: Effect.tap(reader.pull, (batch) => + Effect.sync(() => { + for (const frame of batch) { + rawInboundFrames.push(frame instanceof Uint8Array ? frame.slice() : frame); + } + }), + ), + })), + writer: baseSocket.writer, + }), + ), + ), + ); + const clientProtocol = yield* Layer.build( + RpcClient.layerProtocolSocket({ retryTransientErrors: false }).pipe( + Layer.provide( + Layer.mergeAll(Layer.succeed(Socket.Socket, observedSocket), layerSocketSchemaBinary), + ), + ), + ); + const client = yield* RpcClient.make(WsRpcGroup, { disableTracing: true }).pipe( + Effect.provide(clientProtocol), + ); + + const configQueue = yield* client[WS_METHODS.subscribeServerConfig]({}, { asQueue: true }); + const initialConfig = yield* Queue.take(configQueue); + assert.equal(initialConfig.type, "snapshot"); + if (initialConfig.type !== "snapshot") return yield* Effect.die("Missing config snapshot"); + assert.equal(initialConfig.config.settings.speechAcceleration, "gpu:cuda:0"); + assert.isTrue( + initialConfig.config.keybindings.some((rule) => rule.command === "terminal.toggle"), + ); + assert.isTrue( + initialConfig.config.keybindings.some((rule) => rule.command === "script.build.run"), + ); + assert.equal(initialConfig.config.providers[0]?.instanceId, instanceId); + + yield* settings.updateSettings({ defaultAutoPull: true }); + let liveConfig = yield* Queue.take(configQueue); + while (liveConfig.type === "snapshot") { + liveConfig = yield* Queue.take(configQueue); + } + assert.equal(liveConfig.type, "settingsUpdated"); + if (liveConfig.type === "settingsUpdated") { + assert.isTrue(liveConfig.payload.settings.defaultAutoPull); + } + + const [shellItem] = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({}).pipe( + Stream.take(1), + Stream.runCollect, + ); + assert.equal(shellItem?.kind, "snapshot"); + if (shellItem?.kind === "snapshot") { + assert.deepEqual( + shellItem.snapshot.projects.map((project) => project.id), + [projectId], + ); + assert.equal(shellItem.snapshot.threads[0]?.id, threadId); + assert.deepEqual(shellItem.snapshot.threads[0]?.createdAt, nowUtc); + } + + const threadQueue = yield* client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]( + { + threadId, + acceptBoundedSnapshot: true, + acceptCompactIds: true, + }, + { asQueue: true }, + ); + const threadSnapshot = yield* Queue.take(threadQueue); + assert.equal(threadSnapshot.kind, "snapshot"); + if (threadSnapshot.kind !== "snapshot") return yield* Effect.die("Missing thread snapshot"); + assert.isUndefined(threadSnapshot.idTable); + assert.deepEqual(threadSnapshot.projection.thread.createdAt, nowUtc); + const decodedItem = threadSnapshot.projection.visibleTurnItems[0]?.item; + assert.equal(decodedItem?.type, "assistant_message"); + if (decodedItem?.type === "assistant_message") { + assert.equal(decodedItem.text, largeText); + } + assert.isTrue(rawInboundFrames.every((frame) => frame instanceof Uint8Array)); + assert.isTrue( + rawInboundFrames.some( + (frame) => + frame instanceof Uint8Array && + frame.byteLength >= 2 && + frame[0] === 0x00 && + frame[1] === 0x01, + ), + ); + assert.isTrue( + rawInboundFrames.some( + (frame) => + frame instanceof Uint8Array && + frame.byteLength >= 2 && + frame[0] === 0x00 && + frame[1] === 0x02, + ), + ); + + yield* Queue.offer(liveThreadEvents, { + sequence: 8, + commandId: null, + event: { + id: EventId.make("evt:binary-live"), + threadId, + occurredAt: nowUtc, + type: "turn-item.updated", + payload: liveTurnItem, + }, + }); + const liveThreadItem = yield* Queue.take(threadQueue); + assert.equal(liveThreadItem.kind, "event"); + if (liveThreadItem.kind === "event") { + assert.equal(liveThreadItem.sequence, 8); + assert.equal(liveThreadItem.event.type, "turn-item.updated"); + if ( + liveThreadItem.event.type === "turn-item.updated" && + liveThreadItem.event.payload.type === "assistant_message" + ) { + assert.equal(liveThreadItem.event.payload.text, "live delta complete"); + } + } + + const dispatchOk = yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]({ + type: "thread.pin", + commandId: CommandId.make("cmd-ok"), + threadId, + }); + assert.deepEqual(dispatchOk, { sequence: 42 }); + + const dispatchError = yield* client[ORCHESTRATION_V2_WS_METHODS.dispatchCommand]({ + type: "thread.pin", + commandId: CommandId.make("cmd-reject"), + threadId, + }).pipe(Effect.flip); + assert.equal(dispatchError._tag, "OrchestrationV2DispatchCommandError"); + + const defectExit = yield* Effect.exit( + client[WS_METHODS.workflowsGet]({ runId: "run-defect" }), + ); + assert.isTrue(Exit.isFailure(defectExit)); + if (Exit.isFailure(defectExit)) { + assert.isTrue(Cause.hasDies(defectExit.cause)); + } + const probeAfterDefect = yield* client[WS_METHODS.serverProbe]({}); + assert.isString(probeAfterDefect.serverTime); + + const roundTripRawPing = (url: string, payload: string | Uint8Array) => + Effect.acquireUseRelease( + Effect.sync(() => new WebSocket(url, { origin: "t3code://app" })), + (socket) => + Effect.promise( + () => + new Promise<{ readonly data: Buffer; readonly isBinary: boolean }>( + (resolve, reject) => { + socket.once("error", reject); + socket.once("open", () => { + socket.once("message", (data, isBinary) => { + const buffer = Buffer.isBuffer(data) + ? data + : Array.isArray(data) + ? Buffer.concat(data) + : Buffer.from(data); + resolve({ data: buffer, isBinary }); + }); + socket.send(payload); + }); + }, + ), + ), + (socket) => Effect.sync(() => socket.terminate()), + ); + + const binarySerialization = yield* RpcSerialization.RpcSerialization.pipe( + Effect.provide(layerSocketSchemaBinary), + ); + const binaryPong = yield* roundTripRawPing(binaryUrl, SCHEMA_BINARY_PING_FRAME); + assert.isTrue(binaryPong.isBinary); + assert.deepEqual( + binarySerialization + .makeUnsafe() + .decode( + new Uint8Array( + binaryPong.data.buffer, + binaryPong.data.byteOffset, + binaryPong.data.byteLength, + ), + ), + [{ _tag: "Pong" }], + ); + + const legacyJsonUrl = `${origin}/ws?${ORCHESTRATION_PROTOCOL_QUERY_PARAM}=${ORCHESTRATION_PROTOCOL_VERSION}`; + const legacyPong = yield* roundTripRawPing(legacyJsonUrl, '{"_tag":"Ping"}'); + assert.isFalse(legacyPong.isBinary); + assert.equal(legacyPong.data.toString("utf8"), '{"_tag":"Pong"}'); + + const unknownCodecPong = yield* roundTripRawPing( + `${legacyJsonUrl}&${SOCKET_RPC_CODEC_QUERY_PARAM}=unknown`, + '{"_tag":"Ping"}', + ); + assert.isFalse(unknownCodecPong.isBinary); + assert.equal(unknownCodecPong.data.toString("utf8"), '{"_tag":"Pong"}'); + }).pipe(Effect.scoped, Effect.provide(Layer.fresh(layerConfigSources))), +); + +it.effect( + "reduces raw and deflated wire bytes over JSON for realistic config, shell, and thread chunks", + () => + Effect.gen(function* () { + const jsonSerialization = yield* RpcSerialization.RpcSerialization.pipe( + Effect.provide(RpcSerialization.layerJson), + ); + const binarySerialization = yield* RpcSerialization.RpcSerialization.pipe( + Effect.provide(layerSocketSchemaBinary), + ); + + const measureChunkSavings = (schema: Schema.Codec, item: A) => + Effect.gen(function* () { + const chunkSchema = Schema.NonEmptyArray(schema); + const jsonCodec = jsonSerialization.codecFor(chunkSchema); + const encodeJsonValues = Schema.encodeUnknownEffect(jsonCodec); + const jsonValues = yield* encodeJsonValues([item]); + const jsonWire = jsonSerialization + .makeUnsafe() + .encode({ _tag: "Chunk", requestId: 1, values: jsonValues }); + if (typeof jsonWire !== "string") { + return yield* Effect.die("Expected JSON chunk frame to encode as a string."); + } + const jsonBytes = Buffer.from(jsonWire, "utf8"); + + const binaryCodec = binarySerialization.codecFor(chunkSchema); + const encodeBinaryValues = Schema.encodeUnknownEffect(binaryCodec); + const decodeBinaryValues = Schema.decodeUnknownEffect(binaryCodec); + const binaryValues = yield* encodeBinaryValues([item]); + const binaryParser = binarySerialization.makeUnsafe(); + const encodedBinaryWire = binaryParser.encode({ + _tag: "Chunk", + requestId: 1, + values: binaryValues instanceof Uint8Array ? binaryValues.slice() : binaryValues, + }); + if (!(encodedBinaryWire instanceof Uint8Array)) { + return yield* Effect.die("Expected SchemaBinary chunk frame to encode as Uint8Array."); + } + const binaryWire = encodedBinaryWire.slice(); + + const decodedEnvelopes = binaryParser.decode(binaryWire); + assert.equal(decodedEnvelopes.length, 1); + const envelope = decodedEnvelopes[0] as { + readonly _tag: string; + readonly requestId: string | number; + readonly values: unknown; + }; + assert.equal(envelope._tag, "Chunk"); + assert.equal(envelope.requestId, 1); + const decodedItems = yield* decodeBinaryValues(envelope.values); + assert.deepEqual(decodedItems, [item]); + + return { + jsonRaw: jsonBytes.byteLength, + binaryRaw: binaryWire.byteLength, + jsonDeflated: NodeZlib.deflateRawSync(jsonBytes).byteLength, + binaryDeflated: NodeZlib.deflateRawSync(binaryWire).byteLength, + }; + }); + + const baseMs = DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-01T12:00:00.000Z")); + const utcAt = (offsetSeconds: number) => DateTime.makeUnsafe(baseMs + offsetSeconds * 1000); + const isoAt = (offsetSeconds: number) => DateTime.formatIso(utcAt(offsetSeconds)); + const instanceId = ProviderInstanceId.make("codex"); + const projectIds = Array.from({ length: 4 }, (_, index) => + ProjectId.make(`project:bench-${index}`), + ); + const threadId = ThreadId.make("thread:bench-primary"); + + const configEvent: ServerConfigStreamEvent = { + version: 1, + type: "snapshot", + config: { + environment: { + environmentId: EnvironmentId.make("env:bench"), + label: "Workstation", + platform: { os: "linux", arch: "x64", machine: "desktop" }, + serverVersion: "1.4.0", + capabilities: { + repositoryIdentity: true, + wsRpcCodecs: ["json", SOCKET_RPC_CODEC_SCHEMA_BINARY], + }, + }, + auth: { + policy: "loopback-browser", + bootstrapMethods: [], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3-session", + }, + cwd: "/workspace/t3code", + keybindingsConfigPath: "/home/dev/.t3/keybindings.json", + keybindings: Array.from({ length: 24 }, (_, index) => ({ + command: index % 4 === 0 ? (`script.task-${index}.run` as const) : "terminal.toggle", + shortcut: { + key: String.fromCharCode(97 + (index % 26)), + metaKey: index % 2 === 0, + ctrlKey: index % 3 === 0, + shiftKey: index % 5 === 0, + altKey: false, + modKey: true, + }, + })), + issues: [], + providers: (["codex", "claudeAgent", "cursor"] as const).map((driver, providerIndex) => ({ + instanceId: ProviderInstanceId.make(driver), + driver: ProviderDriverKind.make(driver), + enabled: true, + installed: true, + version: `2.${providerIndex}.1`, + status: "ready" as const, + auth: { status: "authenticated" as const }, + checkedAt: isoAt(providerIndex * 10), + models: Array.from({ length: 12 }, (_, modelIndex) => ({ + slug: `${driver}-model-${modelIndex}`, + name: `${driver} Model ${modelIndex}`, + isCustom: modelIndex === 11, + isDefault: modelIndex === 0, + capabilities: null, + })), + slashCommands: Array.from({ length: 15 }, (_, cmdIndex) => ({ + name: `cmd-${providerIndex}-${cmdIndex}`, + description: `Run workflow action ${cmdIndex} for ${driver}`, + })), + skills: Array.from({ length: 10 }, (_, skillIndex) => ({ + name: `skill-${providerIndex}-${skillIndex}`, + description: `Specialized engineering workflow ${skillIndex}`, + path: `/workspace/.agents/skills/skill-${providerIndex}-${skillIndex}/SKILL.md`, + enabled: skillIndex % 3 !== 0, + })), + })), + availableEditors: ["cursor", "vscode", "file-manager"], + observability: { + logsDirectoryPath: "/home/dev/.t3/logs", + localTracingEnabled: false, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + otlpLogsEnabled: false, + }, + settings: { + ...DEFAULT_SERVER_SETTINGS, + speechAcceleration: "gpu:cuda:0", + }, + }, + }; + + const shellEvent: OrchestrationV2ShellStreamItem = { + kind: "snapshot", + snapshot: { + schemaVersion: 1, + snapshotSequence: 240, + projects: projectIds.map((id, index) => ({ + id, + title: `Repository ${index}`, + workspaceRoot: `/workspace/repo-${index}`, + defaultModelSelection: { instanceId, model: "gpt-5" }, + scripts: [], + createdAt: isoAt(index), + updatedAt: isoAt(index + 50), + })), + threads: Array.from({ length: 40 }, (_, index) => { + const id = ThreadId.make(`thread:shell-${index}`); + const createdAt = utcAt(index * 17); + const updatedAt = utcAt(index * 17 + 120); + return { + createdBy: "user", + creationSource: "web", + id, + projectId: projectIds[index % projectIds.length]!, + title: `Implement feature #${100 + index} on module-${index % 7}`, + providerInstanceId: instanceId, + modelSelection: { + instanceId, + model: index % 2 === 0 ? "gpt-5" : "gpt-5-mini", + ...(index === 0 ? { options: [{ id: "reasoningEffort", value: "high" }] } : {}), + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: `feat/change-${index}`, + worktreePath: index % 3 === 0 ? `/workspace/worktrees/wt-${index}` : null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: id }, + forkedFrom: null, + activeProviderThreadId: ProviderThreadId.make(`prov-thread-${index}`), + latestRunId: RunId.make(`run:shell-${index}`), + activeRunId: null, + status: index % 5 === 0 ? "running" : "completed", + pendingRuntimeRequest: null, + latestVisibleMessage: { + id: MessageId.make(`msg:shell-${index}`), + role: "assistant", + text: `Completed step ${index} across files/mod-${index}.ts`, + updatedAt, + }, + latestUserMessageAt: createdAt, + hasActionableProposedPlan: index % 9 === 0, + pendingBackgroundTasks: [], + providerInstanceHistory: [instanceId], + itemCount: 12 + index, + visibleItemCount: 8 + (index % 10), + createdAt, + updatedAt, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, + }; + }), + archivedThreads: [], + }, + }; + + const runs = Array.from({ length: 10 }, (_, index) => ({ + id: RunId.make(`run:bench-${index}`), + threadId, + ordinal: index + 1, + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "gpt-5" }, + providerThreadId: ProviderThreadId.make("prov-thread-bench"), + userMessageId: MessageId.make(`msg:user-${index}`), + rootNodeId: NodeId.make(`node:root-${index}`), + activeAttemptId: null, + status: "completed" as const, + requestedAt: utcAt(index * 60), + startedAt: utcAt(index * 60 + 1), + completedAt: utcAt(index * 60 + 45), + checkpointId: null, + contextHandoffId: null, + })); + const messages = Array.from({ length: 20 }, (_, index) => ({ + createdBy: (index % 2 === 0 ? "user" : "agent") as "user" | "agent", + creationSource: (index % 2 === 0 ? "web" : "provider") as "web" | "provider", + id: MessageId.make(`msg:bench-${index}`), + threadId, + runId: runs[index % runs.length]!.id, + nodeId: NodeId.make(`node:msg-${index}`), + role: (index % 2 === 0 ? "user" : "assistant") as "user" | "assistant", + text: `Turn ${index} discussion covering module-${index % 6} serialization metrics and validation.`, + attachments: [], + streaming: false, + createdAt: utcAt(index * 30), + updatedAt: utcAt(index * 30 + 5), + })); + const turnItems: Array = Array.from({ length: 60 }, (_, index) => { + const startedAt = utcAt(index * 11); + const completedAt = utcAt(index * 11 + 4); + const base = { + id: TurnItemId.make(`item:bench-${index}`), + threadId, + runId: runs[index % runs.length]!.id, + nodeId: NodeId.make(`node:item-${index}`), + providerThreadId: ProviderThreadId.make("prov-thread-bench"), + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: index, + status: "completed" as const, + title: `Step ${index}`, + startedAt, + completedAt, + updatedAt: completedAt, + }; + return index % 2 === 0 + ? { + ...base, + type: "assistant_message", + messageId: messages[index % messages.length]!.id, + text: `Updated module-${index % 12}.ts with schema codec check #${index}.`, + streaming: false, + } + : { + ...base, + type: "command_execution", + input: `vp test run packages/shared/src/case-${index}.test.ts`, + output: `PASS case-${index}.test.ts (${12 + index}ms)`, + exitCode: 0, + }; + }); + const threadEvent: OrchestrationV2ThreadStreamItem = { + kind: "snapshot", + snapshotSequence: 512, + projection: { + thread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: projectIds[0]!, + title: "Benchmark thread", + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: "feat/ws-binary", + worktreePath: "/workspace/worktrees/ws-binary", + activeProviderThreadId: ProviderThreadId.make("prov-thread-bench"), + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: utcAt(0), + updatedAt: utcAt(900), + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: utcAt(890), + deletedAt: null, + }, + runs, + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages, + plans: [], + turnItems, + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: turnItems.map((item, position) => ({ + position, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: item.id, + item, + })), + updatedAt: utcAt(900), + }, + historyCursor: null, + hasMoreHistory: false, + latestLocalTurnOrdinal: 59, + }; + + const configMetrics = yield* measureChunkSavings(ServerConfigStreamEvent, configEvent); + const shellMetrics = yield* measureChunkSavings(OrchestrationV2ShellStreamItem, shellEvent); + const threadMetrics = yield* measureChunkSavings( + OrchestrationV2ThreadStreamItem, + threadEvent, + ); + + for (const metrics of [configMetrics, shellMetrics, threadMetrics]) { + assert.isBelow(metrics.binaryRaw, metrics.jsonRaw * 0.65); + } + assert.isBelow(threadMetrics.binaryDeflated, threadMetrics.jsonDeflated); + // Single-shot deflate without context takeover pays one-time evolution field IDs on wide structs. + assert.isBelow(configMetrics.binaryDeflated, configMetrics.jsonDeflated * 1.05); + assert.isBelow(shellMetrics.binaryDeflated, shellMetrics.jsonDeflated * 1.05); + assert.isBelow( + configMetrics.binaryDeflated + shellMetrics.binaryDeflated + threadMetrics.binaryDeflated, + configMetrics.jsonDeflated + shellMetrics.jsonDeflated + threadMetrics.jsonDeflated, + ); + }), +); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 82d163b13e4d9..7ceeeb1a4662e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -300,9 +300,16 @@ import * as SourceControlRateLimit from "@t3tools/source-control-core/server/Sou import { isNetworkPath } from "@t3tools/shared/path"; import * as RelayClient from "@t3tools/shared/relayClient"; import { + layerSocketSchemaBinary, parseSocketAckWindow, + parseSocketRpcCodec, + SCHEMA_BINARY_PONG_FRAME, SOCKET_ACK_WINDOW_QUERY_PARAM, SOCKET_FRAME_PARTS_QUERY_PARAM, + SOCKET_RPC_CODEC_JSON, + SOCKET_RPC_CODEC_QUERY_PARAM, + SOCKET_RPC_CODEC_SCHEMA_BINARY, + type SocketRpcCodec, splitLargeSocketFrames, } from "@t3tools/shared/socketFrameParts"; import { isTelemetryIdHash } from "@t3tools/shared/telemetryId"; @@ -1492,6 +1499,7 @@ export const layerWsRpc = ( serverBrowser: ServerBrowser.ServerBrowser["Service"], reportProfiles: ServerBrowser.ProfileReporter, settingsClient: ServerSettings.SettingsClient, + rpcCodec: SocketRpcCodec = SOCKET_RPC_CODEC_JSON, ) => Layer.effectContext( Effect.gen(function* () { @@ -2447,7 +2455,13 @@ export const layerWsRpc = ( Stream.unwrap( Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe( Effect.andThen(threadViewers.view(input.threadId)), - Effect.andThen(subscribeOrchestrationV2Thread(input)), + Effect.andThen( + subscribeOrchestrationV2Thread( + rpcCodec === SOCKET_RPC_CODEC_SCHEMA_BINARY + ? { ...input, acceptCompactIds: false } + : input, + ), + ), ), ), [ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: (input) => @@ -4052,6 +4066,10 @@ export const layer = Layer.unwrap( const ackWindow = parseSocketAckWindow( url.value.searchParams.get(SOCKET_ACK_WINDOW_QUERY_PARAM), ); + const rpcCodec = parseSocketRpcCodec( + url.value.searchParams.get(SOCKET_RPC_CODEC_QUERY_PARAM), + ); + const isBinaryRpcCodec = rpcCodec === SOCKET_RPC_CODEC_SCHEMA_BINARY; const rpcWebSocketHttpEffect = yield* Effect.gen(function* () { const { protocol, httpEffect } = yield* RpcServer.makeProtocolWithHttpEffectWebsocket; yield* RpcServer.make(ServerWsRpcGroup, WS_RPC_SERVER_OPTIONS).pipe( @@ -4087,8 +4105,11 @@ export const layer = Layer.unwrap( serverBrowser, reportProfiles, readSettingsClient(url.value), + rpcCodec, ).pipe( - Layer.provideMerge(RpcSerialization.layerJson), + Layer.provideMerge( + isBinaryRpcCodec ? layerSocketSchemaBinary : RpcSerialization.layerJson, + ), // Handler-context reporters see only request defects, not server-wide defects. Layer.provide(DefectReporter.layer), Layer.provide(AcpRegistrySessions.layer), @@ -4146,7 +4167,10 @@ export const layer = Layer.unwrap( Object.create(request, { upgrade: { value: Effect.map(request.upgrade, (socket) => - withSocketHeartbeat(splitFrames ? splitLargeSocketFrames(socket) : socket), + withSocketHeartbeat( + splitFrames ? splitLargeSocketFrames(socket) : socket, + isBinaryRpcCodec ? { frame: SCHEMA_BINARY_PONG_FRAME } : undefined, + ), ), }, }), diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.ts index beff1fe7c2a55..7225104676969 100644 --- a/apps/web/src/connection/runtime.ts +++ b/apps/web/src/connection/runtime.ts @@ -5,6 +5,7 @@ import { ThreadHistoryController, } from "@t3tools/client-runtime/state/threads"; import { PullRequestDiffLoader } from "@t3tools/client-runtime/state/pull-requests"; +import { SOCKET_RPC_CODEC_SCHEMA_BINARY } from "@t3tools/shared/socketFrameParts"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import { Atom } from "effect/reactivity"; @@ -39,6 +40,7 @@ const layerProvidedClientConnection = layerSnapshotLoader.pipe( usageLimitSources: true, hostPressure: true, usageLimitsCommand: true, + rpcCodec: SOCKET_RPC_CODEC_SCHEMA_BINARY, }), ), Layer.provideMerge( diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 6b0c778667ce2..143c2f2f8640b 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -6,11 +6,22 @@ import { ServerConfigStreamEvent, type ServerConfigStreamEvent as ServerConfigStreamEventType, ServerProvider, + TerminalAttachStreamEvent, WS_METHODS, + WsRpcGroup, UsageLimitSourceId, CALM_HOST_PRESSURE, } from "@t3tools/contracts"; -import { DEFAULT_SOCKET_ACK_WINDOW, splitSocketFrame } from "@t3tools/shared/socketFrameParts"; +import { + DEFAULT_SOCKET_ACK_WINDOW, + layerSocketSchemaBinary, + SCHEMA_BINARY_PING_FRAME, + SCHEMA_BINARY_PONG_FRAME, + SOCKET_RPC_CODEC_JSON, + SOCKET_RPC_CODEC_SCHEMA_BINARY, + splitBinarySocketFrame, + splitSocketFrame, +} from "@t3tools/shared/socketFrameParts"; import { describe, expect, it } from "@effect/vitest"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; @@ -22,6 +33,8 @@ import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; +import * as Rpc from "effect/rpc/Rpc"; +import * as RpcSerialization from "effect/rpc/RpcSerialization"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; @@ -59,6 +72,7 @@ class TestWebSocket { readyState = TestWebSocket.CONNECTING; readonly sent: string[] = []; + readonly sentFrames: Array = []; readonly url: string; readonly sentChanges: Queue.Queue; private readonly listeners = new Map>(); @@ -78,8 +92,14 @@ class TestWebSocket { this.listeners.get(type)?.delete(listener); } - send(data: string) { - this.sent.push(data); + send(data: string | Uint8Array) { + if (typeof data === "string") { + this.sent.push(data); + this.sentFrames.push(data); + } else { + // Copy out of SchemaBinary's pooled output buffer before later sends overwrite it. + this.sentFrames.push(data.slice()); + } Queue.offerUnsafe(this.sentChanges, undefined); } @@ -96,7 +116,7 @@ class TestWebSocket { this.emit("open", { type: "open" }); } - serverMessage(data: string) { + serverMessage(data: string | Uint8Array) { this.emit("message", { data, type: "message" }); } @@ -1638,4 +1658,209 @@ describe("RpcSessionFactory", () => { yield* Fiber.interrupt(streamFiber); }), ); + + it.effect( + "negotiates schema-binary only when opted in and advertised, handling binary split frames, heartbeats, and terminal byte-window Acks", + () => + Effect.gen(function* () { + const serialization = yield* RpcSerialization.RpcSerialization; + const parser = serialization.makeUnsafe(); + const encodeConfigChunk = Schema.encodeEffect( + serialization.codecFor(Schema.NonEmptyArray(ServerConfigStreamEvent)), + ); + const encodeTerminalChunk = Schema.encodeEffect( + serialization.codecFor(Schema.NonEmptyArray(TerminalAttachStreamEvent)), + ); + const probeRpc = WsRpcGroup.requests.get(WS_METHODS.serverProbe)!; + const encodeProbeExit = Schema.encodeUnknownEffect( + serialization.codecFor(Rpc.exitSchema(probeRpc)), + ); + const copyIfBytes = (value: unknown) => + value instanceof Uint8Array ? value.slice() : value; + const encodeBinaryEnvelope = (message: unknown): Uint8Array => { + const encoded = parser.encode(message); + if (!(encoded instanceof Uint8Array)) { + throw new Error("Expected binary SchemaBinary envelope"); + } + return encoded.slice(); + }; + const decodeBinarySent = (socket: TestWebSocket) => + socket.sentFrames.flatMap((frame) => + frame instanceof Uint8Array ? serialization.makeUnsafe().decode(frame) : [], + ); + const awaitBinaryRequest = Effect.fn("TestRpcSessionFactory.awaitBinaryRequest")(function* ( + socket: TestWebSocket, + index = 0, + ) { + for (;;) { + const request = decodeBinarySent(socket).filter(isRpcRequest)[index]; + if (request) return request; + yield* Queue.take(socket.sentChanges); + } + }); + + const binaryDescriptor = { + ...SERVER_CONFIG.environment, + capabilities: { + ...SERVER_CONFIG.environment.capabilities, + wsAckWindow: 4, + wsRpcCodecs: [SOCKET_RPC_CODEC_JSON, SOCKET_RPC_CODEC_SCHEMA_BINARY], + }, + }; + const binaryConfig: ServerConfigType = { + ...SERVER_CONFIG, + environment: binaryDescriptor, + // Large enough to trigger splitBinarySocketFrame across multiple binary parts. + cwd: "/" + "é€😀x".repeat(40 * 1024), + }; + const { factory, sockets } = yield* makeFactory({ + rpcCodec: SOCKET_RPC_CODEC_SCHEMA_BINARY, + }); + const session = yield* factory.connect({ ...PREPARED, descriptor: binaryDescriptor }); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + + expect(socket.url).toBe( + `${PREPARED.socketUrl}&frameParts=1&ackWindow=${DEFAULT_SOCKET_ACK_WINDOW}&rpcCodec=${SOCKET_RPC_CODEC_SCHEMA_BINARY}`, + ); + socket.open(); + const configRequest = yield* awaitBinaryRequest(socket, 0); + expect(configRequest.tag).toBe(WS_METHODS.subscribeServerConfig); + expect(socket.sent).toHaveLength(0); + expect(socket.sentFrames[0]).toBeInstanceOf(Uint8Array); + + const snapshotFrame = encodeBinaryEnvelope({ + _tag: "Chunk", + requestId: configRequest.id, + values: copyIfBytes( + yield* encodeConfigChunk([{ version: 1, type: "snapshot", config: binaryConfig }]), + ), + }); + const binaryParts = splitBinarySocketFrame(snapshotFrame); + expect(binaryParts.length).toBeGreaterThan(1); + for (const part of binaryParts) { + socket.serverMessage(part); + } + yield* Fiber.join(readyFiber); + expect(yield* session.initialConfig).toEqual(binaryConfig); + + const beforeInbound = yield* session.inboundFrames; + const probeFiber = yield* Effect.forkChild(session.probe); + const probeRequest = yield* awaitBinaryRequest(socket, 1); + expect(probeRequest.tag).toBe(WS_METHODS.serverProbe); + expect(yield* session.awaitingReply).toBe(true); + socket.serverMessage(SCHEMA_BINARY_PONG_FRAME); + expect(yield* session.inboundFrames).toBe(beforeInbound + 1); + expect(yield* session.awaitingReply).toBe(false); + socket.serverMessage( + encodeBinaryEnvelope({ + _tag: "Exit", + requestId: probeRequest.id, + exit: copyIfBytes(yield* encodeProbeExit(Exit.succeed({}))), + }), + ); + yield* Fiber.join(probeFiber); + + // Idle ping uses SCHEMA_BINARY_PING_FRAME instead of JSON text. + const framesBeforePing = socket.sentFrames.length; + yield* TestClock.adjust("5 seconds"); + expect(socket.sentFrames.slice(framesBeforePing)).toEqual([SCHEMA_BINARY_PING_FRAME]); + socket.serverMessage(SCHEMA_BINARY_PONG_FRAME); + + // Byte-windowed terminalAttach flushes an Ack once binary chunk bytes cross 32 KiB. + const receivedTerminal = yield* Queue.unbounded(); + const terminalFiber = yield* session.client[WS_METHODS.terminalAttach]({ + threadId: "thread-1", + terminalId: "default", + }).pipe( + Stream.runForEach((event) => Queue.offer(receivedTerminal, event)), + Effect.forkChild, + ); + const terminalRequest = yield* awaitBinaryRequest(socket, 2); + const sentBinaryAcks = () => + decodeBinarySent(socket) + .filter(isRpcAck) + .filter((ack) => String(ack.requestId) === String(terminalRequest.id)); + + socket.serverMessage( + encodeBinaryEnvelope({ + _tag: "Chunk", + requestId: terminalRequest.id, + values: copyIfBytes( + yield* encodeTerminalChunk([ + { + type: "output", + threadId: "thread-1", + terminalId: "default", + data: "hello", + }, + ]), + ), + }), + ); + yield* Queue.take(receivedTerminal); + yield* TestClock.adjust(0); + expect(sentBinaryAcks()).toHaveLength(0); + + socket.serverMessage( + encodeBinaryEnvelope({ + _tag: "Chunk", + requestId: terminalRequest.id, + values: copyIfBytes( + yield* encodeTerminalChunk([ + { + type: "output", + threadId: "thread-1", + terminalId: "default", + data: "x".repeat(40 * 1024), + }, + ]), + ), + }), + ); + yield* Queue.take(receivedTerminal); + yield* TestClock.adjust(0); + expect(sentBinaryAcks()).toHaveLength(1); + yield* Fiber.interrupt(terminalFiber); + }).pipe(Effect.provide(layerSocketSchemaBinary), Effect.scoped), + ); + + it.effect.each([ + { + name: "legacy server without descriptor", + options: { rpcCodec: SOCKET_RPC_CODEC_SCHEMA_BINARY } satisfies RpcSession.RpcSessionOptions, + descriptor: undefined, + }, + { + name: "legacy server without wsRpcCodecs capability", + options: { rpcCodec: SOCKET_RPC_CODEC_SCHEMA_BINARY } satisfies RpcSession.RpcSessionOptions, + descriptor: SERVER_CONFIG.environment, + }, + { + name: "client that omits rpcCodec (Android guardrail)", + options: {} satisfies RpcSession.RpcSessionOptions, + descriptor: { + ...SERVER_CONFIG.environment, + capabilities: { + ...SERVER_CONFIG.environment.capabilities, + wsRpcCodecs: [SOCKET_RPC_CODEC_JSON, SOCKET_RPC_CODEC_SCHEMA_BINARY], + }, + }, + }, + ])("falls back to JSON for $name", ({ options, descriptor }) => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(options); + const session = yield* factory.connect( + descriptor === undefined ? PREPARED : { ...PREPARED, descriptor }, + ); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + + expect(new URL(socket.url).searchParams.get("rpcCodec")).toBeNull(); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + expect(socket.sent.length).toBeGreaterThan(0); + }).pipe(Effect.scoped), + ); }); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index db082fe57cde9..1aac06e8e225c 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -9,9 +9,15 @@ import { import { DEFAULT_SOCKET_ACK_WINDOW, joinSocketFrameParts, + layerSocketSchemaBinary, + SCHEMA_BINARY_PING_FRAME, SOCKET_ACK_BYTE_FLUSH_THRESHOLD, SOCKET_ACK_WINDOW_QUERY_PARAM, SOCKET_FRAME_PARTS_QUERY_PARAM, + SOCKET_RPC_CODEC_JSON, + SOCKET_RPC_CODEC_QUERY_PARAM, + SOCKET_RPC_CODEC_SCHEMA_BINARY, + type SocketRpcCodec, utf8ByteLength, } from "@t3tools/shared/socketFrameParts"; import * as Cause from "effect/Cause"; @@ -101,7 +107,13 @@ function estimateTerminalEventBytes(event: unknown): number { return bytes; } -function estimateTerminalChunkBytes(values: ReadonlyArray): number { +function estimateTerminalChunkBytes(values: unknown): number { + if (values instanceof Uint8Array) { + return TERMINAL_EVENT_OVERHEAD + values.byteLength; + } + if (!Array.isArray(values)) { + return TERMINAL_EVENT_OVERHEAD; + } let total = TERMINAL_EVENT_OVERHEAD; for (const value of values) { total += estimateTerminalEventBytes(value); @@ -115,9 +127,11 @@ function withIdleOnlyClientPings( options: { readonly pingInterval: Duration.Duration; readonly pingTimeout: Duration.Duration; + readonly pingFrame?: string | Uint8Array; readonly onPingTimeout: () => void; }, ): Socket.Socket { + const pingFrame = options.pingFrame ?? CLIENT_PING_FRAME; const intervalMillis = Duration.toMillis(options.pingInterval); const timeoutMillis = Duration.toMillis(options.pingTimeout); if (!Number.isFinite(intervalMillis) || intervalMillis <= 0 || !Number.isFinite(timeoutMillis)) { @@ -159,7 +173,7 @@ function withIdleOnlyClientPings( const nextPingAt = (lastPingSentNanos ?? firstPingSentNanos) + intervalNanos; if (now >= nextPingAt) { lastPingSentNanos = now; - yield* writer.write(CLIENT_PING_FRAME).pipe(Effect.ignore); + yield* writer.write(pingFrame).pipe(Effect.ignore); continue; } yield* Effect.sleep(Duration.nanos(minBigInt(timeoutAt, nextPingAt) - now)); @@ -173,7 +187,7 @@ function withIdleOnlyClientPings( } firstPingSentNanos = now; lastPingSentNanos = now; - yield* writer.write(CLIENT_PING_FRAME).pipe(Effect.ignore); + yield* writer.write(pingFrame).pipe(Effect.ignore); } }); @@ -221,6 +235,7 @@ export interface RpcSessionOptions { readonly providerCatalogsOnDemand?: boolean; readonly providerCatalogDigests?: boolean; readonly providerStatusDeltas?: boolean; + readonly rpcCodec?: SocketRpcCodec; readonly pingInterval?: Duration.Input; readonly onInitialConfig?: () => void; } @@ -413,9 +428,19 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( }); return socket; }; + const effectiveRpcCodec: SocketRpcCodec = + options.rpcCodec === SOCKET_RPC_CODEC_SCHEMA_BINARY && + connection.descriptor?.capabilities.wsRpcCodecs?.includes(SOCKET_RPC_CODEC_SCHEMA_BINARY) === + true + ? SOCKET_RPC_CODEC_SCHEMA_BINARY + : SOCKET_RPC_CODEC_JSON; + const isBinaryRpcCodec = effectiveRpcCodec === SOCKET_RPC_CODEC_SCHEMA_BINARY; const socketUrl = new URL(connection.socketUrl); socketUrl.searchParams.set(SOCKET_FRAME_PARTS_QUERY_PARAM, "1"); socketUrl.searchParams.set(SOCKET_ACK_WINDOW_QUERY_PARAM, String(DEFAULT_SOCKET_ACK_WINDOW)); + if (isBinaryRpcCodec) { + socketUrl.searchParams.set(SOCKET_RPC_CODEC_QUERY_PARAM, SOCKET_RPC_CODEC_SCHEMA_BINARY); + } const layerSocket = Layer.effect( Socket.Socket, Effect.gen(function* () { @@ -424,6 +449,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( return withIdleOnlyClientPings(socket, clock, { pingInterval, pingTimeout: PING_TIMEOUT_DURATION, + pingFrame: isBinaryRpcCodec ? SCHEMA_BINARY_PING_FRAME : CLIENT_PING_FRAME, onPingTimeout: () => { pingTimedOut = true; }, @@ -540,7 +566,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( Layer.provide( Layer.mergeAll( layerSocket, - RpcSerialization.layerJson, + isBinaryRpcCodec ? layerSocketSchemaBinary : RpcSerialization.layerJson, Layer.succeed(RpcClient.ConnectionHooks, hooks), ), ), diff --git a/packages/contracts/src/baseSchemas.ts b/packages/contracts/src/baseSchemas.ts index efa0081bbeb78..947fc99d5172e 100644 --- a/packages/contracts/src/baseSchemas.ts +++ b/packages/contracts/src/baseSchemas.ts @@ -4,6 +4,12 @@ import * as Schema from "effect/Schema"; import * as SchemaGetter from "effect/SchemaGetter"; import * as SchemaTransformation from "effect/SchemaTransformation"; +/** Annotation carrying the inner AST for SchemaBinary to bypass JSON-only wrappers. */ +export const SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION = "t3/socket/binaryUnwrappedAst"; +/** Annotation carrying the element AST of a ForwardCompatibleArray for binary wire widening. */ +export const SOCKET_BINARY_FORWARD_COMPATIBLE_ARRAY_ANNOTATION = + "t3/socket/binaryForwardCompatibleArray"; + // Hermes copies the string on every `trim()`, even when nothing changes. // Returning the original keeps repeated IDs shared after decode. const trim = (value: string) => { @@ -147,35 +153,37 @@ export const ForwardCompatibleArray = (element: Elem Schema.Union([element, UnknownArrayElement]).pipe( Schema.catchEncoding(() => Effect.succeedSome(undefined)), ), - ).pipe( - Schema.decodeTo( - Schema.Array( - Schema.UndefinedOr(Schema.toType(element)).pipe( - Schema.catchEncoding(() => Effect.succeedSome(undefined)), - ), - ).check( - // Schema.is/make must reject holes; abort before later array checks. - Schema.makeFilter( - (values) => { - // Every index, not `every`, which skips the holes of a sparse array. - for (let index = 0; index < values.length; index++) { - if (values[index] === undefined) return false; - } - return true; - }, - { expected: "an array without holes" }, - true, + ) + .annotate({ [SOCKET_BINARY_FORWARD_COMPATIBLE_ARRAY_ANNOTATION]: element.ast }) + .pipe( + Schema.decodeTo( + Schema.Array( + Schema.UndefinedOr(Schema.toType(element)).pipe( + Schema.catchEncoding(() => Effect.succeedSome(undefined)), + ), + ).check( + // Schema.is/make must reject holes; abort before later array checks. + Schema.makeFilter( + (values) => { + // Every index, not `every`, which skips the holes of a sparse array. + for (let index = 0; index < values.length; index++) { + if (values[index] === undefined) return false; + } + return true; + }, + { expected: "an array without holes" }, + true, + ), ), + SchemaTransformation.transform< + ReadonlyArray, + ReadonlyArray + >({ + decode: (values) => values.filter((value) => value !== undefined), + encode: (values) => values.filter((value) => value !== undefined), + }), ), - SchemaTransformation.transform< - ReadonlyArray, - ReadonlyArray - >({ - decode: (values) => values.filter((value) => value !== undefined), - encode: (values) => values.filter((value) => value !== undefined), - }), - ), - ) as unknown as ForwardCompatibleArray; + ) as unknown as ForwardCompatibleArray; export type ForwardCompatibleArray = Schema.Codec< ReadonlyArray, ReadonlyArray, @@ -253,22 +261,45 @@ export const ForwardCompatibleUnionArray = < >( members: Members, tag: Tag, -) => - Schema.Array(ForwardCompatibleUnion(members, tag)).pipe( +) => { + const knownUnion = Schema.Union(members); + // Optional struct key absorbs SchemaBinary ABSENT on unknown future variants while keeping broken known variants failing. + const binaryEntry = Schema.Struct({ + item: Schema.optionalKey(knownUnion), + }); + const binaryArray = Schema.Array(binaryEntry).pipe( Schema.decodeTo( - Schema.Array(Schema.toType(Schema.Union(members))), + Schema.Array(Schema.toType(knownUnion)), SchemaTransformation.transform< ReadonlyArray, - ReadonlyArray> + ReadonlyArray<{ readonly item?: Members[number]["Type"] }> >({ - decode: (values) => - values.filter((value) => !isUnknownUnionMember(value)) as ReadonlyArray< - Members[number]["Type"] - >, - encode: (values) => values, + decode: (entries) => + entries.flatMap((entry) => + entry.item === undefined ? [] : [entry.item as Members[number]["Type"]], + ), + encode: (values) => values.map((item) => ({ item })), }), ), ); + return Schema.Array(ForwardCompatibleUnion(members, tag)) + .pipe( + Schema.decodeTo( + Schema.Array(Schema.toType(knownUnion)), + SchemaTransformation.transform< + ReadonlyArray, + ReadonlyArray> + >({ + decode: (values) => + values.filter((value) => !isUnknownUnionMember(value)) as ReadonlyArray< + Members[number]["Type"] + >, + encode: (values) => values, + }), + ), + ) + .annotate({ [SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION]: binaryArray.ast }); +}; const knownTags = ( members: ReadonlyArray, diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index fcbcdfe02da30..23996d153f003 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -237,6 +237,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ issueTrackerAccounts: Schema.optionalKey(Schema.Boolean), /** Max stream chunks a single WebSocket Ack releases when `?ackWindow=` is set. */ wsAckWindow: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))), + /** WebSocket RPC wire codecs accepted via `?rpcCodec=`; absent means JSON only. */ + wsRpcCodecs: Schema.optionalKey(Schema.Array(Schema.String)), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 855afb74013a5..e9abff1954417 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -129,10 +129,13 @@ export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([ Schema.Literal(".run"), ]); -export const KeybindingCommand = Schema.Union([ +const KeybindingCommandTarget = Schema.Union([ Schema.Literals(STATIC_KEYBINDING_COMMANDS), SCRIPT_RUN_COMMAND_PATTERN, ]); + +// Encode as a single string leaf so SchemaBinary sees one string branch instead of colliding literals + pattern. +export const KeybindingCommand = Schema.String.pipe(Schema.decodeTo(KeybindingCommandTarget)); export type KeybindingCommand = typeof KeybindingCommand.Type; export const KeybindingValue = TrimmedString.check( diff --git a/packages/contracts/src/modelSelection.ts b/packages/contracts/src/modelSelection.ts index de133ea59a1e2..57f8b56e64a11 100644 --- a/packages/contracts/src/modelSelection.ts +++ b/packages/contracts/src/modelSelection.ts @@ -2,8 +2,8 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as SchemaTransformation from "effect/SchemaTransformation"; -import { TrimmedNonEmptyString } from "./baseSchemas.ts"; -import { ProviderOptionSelections } from "./model.ts"; +import { SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ProviderOptionSelection, ProviderOptionSelections } from "./model.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; const ModelSelectionWire = Schema.Struct({ @@ -12,13 +12,20 @@ const ModelSelectionWire = Schema.Struct({ options: Schema.optionalKey(ProviderOptionSelections), }); +// Binary peers emit canonical `{ instanceId, model, options? }`, avoiding `Schema.Unknown` JSON fallbacks. +const ModelSelectionBinaryWire = Schema.Struct({ + instanceId: Schema.String, + model: Schema.String, + options: Schema.optionalKey(Schema.Array(ProviderOptionSelection)), +}); + const ModelSelectionSource = Schema.Struct({ provider: Schema.optional(Schema.Unknown), instanceId: Schema.optional(Schema.Unknown), model: Schema.Unknown, // Keep decoding array or object forms; advertised MCP JSON Schema uses the object map. options: Schema.optional(Schema.NullOr(ProviderOptionSelections)), -}); +}).annotate({ [SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION]: ModelSelectionBinaryWire.ast }); export const ModelSelection = ModelSelectionSource.pipe( Schema.decodeTo( diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 68f90a24532f6..5435bd4cf2b9e 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -5,6 +5,7 @@ import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; import * as SchemaAST from "effect/SchemaAST"; import * as SchemaGetter from "effect/SchemaGetter"; +import * as SchemaIssue from "effect/SchemaIssue"; import * as SchemaTransformation from "effect/SchemaTransformation"; import { @@ -27,10 +28,13 @@ import { MessageId, EnvironmentId, NodeId, + ForwardCompatibleNullable, ForwardCompatibleUnion, ForwardCompatibleUnionArray, hasUnknownUnionTag, isUnknownUnionMember, + SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION, + UnknownUnionMember, NonNegativeInt, PlanId, PositiveInt, @@ -534,9 +538,7 @@ export type OrchestrationV2ThreadOpens = typeof OrchestrationV2ThreadOpens.Type; // Open stats only rank search results, so a value this build cannot read (an // older or newer shape) becomes null instead of failing the whole thread. -const LenientThreadOpens = Schema.NullOr(OrchestrationV2ThreadOpens).pipe( - Schema.catchDecoding(() => Effect.succeedSome(null)), -); +const LenientThreadOpens = ForwardCompatibleNullable(OrchestrationV2ThreadOpens); const OrchestrationV2LastTitleRegeneration = Schema.Struct({ ...ThreadTitleRegenerationOutcome.fields, @@ -1274,7 +1276,7 @@ const PendingBackgroundTaskFields = { awaited: Schema.optional(Schema.Literal(true)), }; -export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback( +const OrchestrationV2PendingBackgroundTaskUnion = kindUnionWithFallback( [ Schema.Struct({ ...PendingBackgroundTaskFields, @@ -1295,6 +1297,30 @@ export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback( kind: "background_task", }), ); + +// Flat binary wire struct skips unknown fields and lets kindUnionWithFallback handle future kinds. +const OrchestrationV2PendingBackgroundTaskBinaryWire = Schema.Struct({ + command: Schema.optional(Schema.String), + itemId: Schema.optional(Schema.String), + sourceThreadId: Schema.optional(Schema.String), + taskId: Schema.String, + description: Schema.optional(Schema.String), + parentTaskId: Schema.optional(Schema.String), + nativeItemId: Schema.optional(Schema.String), + runId: Schema.optional(Schema.String), + awaited: Schema.optional(Schema.Boolean), + kind: Schema.optional(Schema.String), + providerInstanceId: Schema.optional(Schema.String), + childThreadId: Schema.optional(Schema.String), +}); + +export const OrchestrationV2PendingBackgroundTask = Schema.toEncoded( + OrchestrationV2PendingBackgroundTaskUnion, +) + .annotate({ + [SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION]: OrchestrationV2PendingBackgroundTaskBinaryWire.ast, + }) + .pipe(Schema.decodeTo(OrchestrationV2PendingBackgroundTaskUnion)); export type OrchestrationV2PendingBackgroundTask = typeof OrchestrationV2PendingBackgroundTask.Type; export const OrchestrationV2ProviderThreadNativeMetadata = Schema.Struct({ @@ -1549,7 +1575,7 @@ const MonitorPullRequestStamp = Schema.Struct({ }); /** Encode legacy background_command/background_task shapes first so older clients accept command/subagent sources. */ -export const OrchestrationV2NotificationSource = kindUnionWithFallback( +const OrchestrationV2NotificationSourceUnion = kindUnionWithFallback( [ Schema.Struct({ kind: Schema.Literal("delegated_task"), @@ -1589,6 +1615,24 @@ export const OrchestrationV2NotificationSource = kindUnionWithFallback( (kind) => Schema.Struct({ kind }), () => ({ kind: "background_task" }), ); + +// Flat binary wire struct skips unknown fields and lets kindUnionWithFallback handle future kinds. +const OrchestrationV2NotificationSourceBinaryWire = Schema.Struct({ + kind: Schema.optional(Schema.String), + work: Schema.optional(Schema.String), + taskIds: Schema.optional(Schema.Array(Schema.String)), + childThreadId: Schema.optional(Schema.String), + pullRequest: Schema.optional(Schema.toEncoded(MonitorPullRequestStamp)), + otherPullRequests: Schema.optional(Schema.Array(Schema.toEncoded(MonitorPullRequestStamp))), +}); + +export const OrchestrationV2NotificationSource = Schema.toEncoded( + OrchestrationV2NotificationSourceUnion, +) + .annotate({ + [SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION]: OrchestrationV2NotificationSourceBinaryWire.ast, + }) + .pipe(Schema.decodeTo(OrchestrationV2NotificationSourceUnion)); export type OrchestrationV2NotificationSource = typeof OrchestrationV2NotificationSource.Type; export const OrchestrationV2Notification = Schema.Struct({ @@ -2287,6 +2331,40 @@ export const OrchestrationV2ProjectedTurnItem = Schema.Struct({ }); export type OrchestrationV2ProjectedTurnItem = typeof OrchestrationV2ProjectedTurnItem.Type; +// Optional `item` absorbs SchemaBinary ABSENT on unknown future turn items without failing the array. +const OrchestrationV2ProjectedTurnItemBinary = OrchestrationV2ProjectedTurnItem.mapFields( + (fields) => ({ + ...fields, + item: Schema.optionalKey(fields.item), + }), +); + +const OrchestrationV2ProjectedTurnItemBinaryArray = Schema.Array( + OrchestrationV2ProjectedTurnItemBinary, +).pipe( + Schema.decodeTo( + Schema.Array(Schema.toType(OrchestrationV2ProjectedTurnItem)), + SchemaTransformation.transform< + ReadonlyArray, + ReadonlyArray + >({ + decode: (rows) => + rows.filter((row): row is OrchestrationV2ProjectedTurnItem => row.item !== undefined), + encode: (rows) => rows, + }), + ), +); + +const OrchestrationV2ProjectedTurnItems = projectedTurnItemArray( + OrchestrationV2ProjectedTurnItem, + OrchestrationV2ProjectedTurnItem.mapFields((fields) => ({ + ...fields, + item: ForwardCompatibleUnion(OrchestrationV2TurnItem.members, "type"), + })), +).annotate({ + [SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION]: OrchestrationV2ProjectedTurnItemBinaryArray.ast, +}); + const OrchestrationV2EventBase = Schema.Struct({ id: EventId, threadId: ThreadId, @@ -2298,42 +2376,39 @@ const OrchestrationV2EventBase = Schema.Struct({ occurredAt: Schema.DateTimeUtc, }); -export const OrchestrationV2DomainEvent = Schema.Union([ +const threadUpdatedEventMember = (type: Type) => Schema.Struct({ ...OrchestrationV2EventBase.fields, - type: Schema.Literal("thread.created"), - payload: OrchestrationV2AppThread, - }), - Schema.Struct({ - ...OrchestrationV2EventBase.fields, - type: Schema.Literals([ - "thread.archived", - "thread.unarchived", - "thread.deleted", - "thread.settled", - "thread.unsettled", - "thread.snoozed", - "thread.unsnoozed", - "thread.pinned", - "thread.auto-settle-set", - "thread.unpinned", - "thread.pin-reordered", - "thread.active-reordered", - "thread.tags-updated", - "thread.tool-overrides-updated", - "thread.visited", - "thread.marked-unread", - "thread.metadata-updated", - "thread.pull-request-synced", - "thread.issue-synced", - "thread.runtime-mode-updated", - "thread.interaction-mode-updated", - "thread.model-selection-updated", - "thread.provider-switched", - "thread.guest-share-updated", - ]), + type: Schema.Literal(type), payload: OrchestrationV2AppThread, - }), + }); + +const OrchestrationV2DomainEventMembersBeforeTurnItem = [ + threadUpdatedEventMember("thread.created"), + threadUpdatedEventMember("thread.archived"), + threadUpdatedEventMember("thread.unarchived"), + threadUpdatedEventMember("thread.deleted"), + threadUpdatedEventMember("thread.settled"), + threadUpdatedEventMember("thread.unsettled"), + threadUpdatedEventMember("thread.snoozed"), + threadUpdatedEventMember("thread.unsnoozed"), + threadUpdatedEventMember("thread.pinned"), + threadUpdatedEventMember("thread.auto-settle-set"), + threadUpdatedEventMember("thread.unpinned"), + threadUpdatedEventMember("thread.pin-reordered"), + threadUpdatedEventMember("thread.active-reordered"), + threadUpdatedEventMember("thread.tags-updated"), + threadUpdatedEventMember("thread.tool-overrides-updated"), + threadUpdatedEventMember("thread.visited"), + threadUpdatedEventMember("thread.marked-unread"), + threadUpdatedEventMember("thread.metadata-updated"), + threadUpdatedEventMember("thread.pull-request-synced"), + threadUpdatedEventMember("thread.issue-synced"), + threadUpdatedEventMember("thread.runtime-mode-updated"), + threadUpdatedEventMember("thread.interaction-mode-updated"), + threadUpdatedEventMember("thread.model-selection-updated"), + threadUpdatedEventMember("thread.provider-switched"), + threadUpdatedEventMember("thread.guest-share-updated"), Schema.Struct({ ...OrchestrationV2EventBase.fields, type: Schema.Literal("thread.pull-request-link-updated"), @@ -2386,7 +2461,12 @@ export const OrchestrationV2DomainEvent = Schema.Union([ }), Schema.Struct({ ...OrchestrationV2EventBase.fields, - type: Schema.Literals(["provider-session.attached", "provider-session.updated"]), + type: Schema.Literal("provider-session.attached"), + payload: OrchestrationV2ProviderSession, + }), + Schema.Struct({ + ...OrchestrationV2EventBase.fields, + type: Schema.Literal("provider-session.updated"), payload: OrchestrationV2ProviderSession, }), Schema.Struct({ @@ -2414,11 +2494,15 @@ export const OrchestrationV2DomainEvent = Schema.Union([ type: Schema.Literal("message.updated"), payload: OrchestrationV2ConversationMessage, }), - Schema.Struct({ - ...OrchestrationV2EventBase.fields, - type: Schema.Literal("turn-item.updated"), - payload: OrchestrationV2TurnItem, - }), +] as const; + +const OrchestrationV2TurnItemUpdatedEvent = Schema.Struct({ + ...OrchestrationV2EventBase.fields, + type: Schema.Literal("turn-item.updated"), + payload: OrchestrationV2TurnItem, +}); + +const OrchestrationV2DomainEventMembersAfterTurnItem = [ Schema.Struct({ ...OrchestrationV2EventBase.fields, type: Schema.Literal("plan.updated"), @@ -2454,6 +2538,12 @@ export const OrchestrationV2DomainEvent = Schema.Union([ type: Schema.Literal("context-transfer.updated"), payload: OrchestrationV2ContextTransfer, }), +] as const; + +export const OrchestrationV2DomainEvent = Schema.Union([ + ...OrchestrationV2DomainEventMembersBeforeTurnItem, + OrchestrationV2TurnItemUpdatedEvent, + ...OrchestrationV2DomainEventMembersAfterTurnItem, ]); export type OrchestrationV2DomainEvent = typeof OrchestrationV2DomainEvent.Type; @@ -2474,13 +2564,7 @@ export const OrchestrationV2ThreadProjection = Schema.Struct({ checkpoints: Schema.Array(OrchestrationV2Checkpoint), contextHandoffs: Schema.Array(OrchestrationV2ContextHandoff), contextTransfers: Schema.Array(OrchestrationV2ContextTransfer), - visibleTurnItems: projectedTurnItemArray( - OrchestrationV2ProjectedTurnItem, - OrchestrationV2ProjectedTurnItem.mapFields((fields) => ({ - ...fields, - item: ForwardCompatibleUnion(OrchestrationV2TurnItem.members, "type"), - })), - ), + visibleTurnItems: OrchestrationV2ProjectedTurnItems, updatedAt: Schema.DateTimeUtc, }); export type OrchestrationV2ThreadProjection = typeof OrchestrationV2ThreadProjection.Type; @@ -4576,13 +4660,7 @@ export type OrchestrationV2ThreadBoundedSnapshot = typeof OrchestrationV2ThreadB export const OrchestrationV2ThreadHistoryPage = withRecordIdTable( Schema.Struct({ snapshotSequence: NonNegativeInt, - items: projectedTurnItemArray( - OrchestrationV2ProjectedTurnItem, - OrchestrationV2ProjectedTurnItem.mapFields((fields) => ({ - ...fields, - item: ForwardCompatibleUnion(OrchestrationV2TurnItem.members, "type"), - })), - ), + items: OrchestrationV2ProjectedTurnItems, nextCursor: Schema.NullOr(TrimmedNonEmptyString), hasMoreHistory: Schema.Boolean, /** Records of the page's subagent items, which a bounded snapshot can omit. */ @@ -4596,10 +4674,7 @@ export const OrchestrationV2ThreadHistoryPage = withRecordIdTable( export type OrchestrationV2ThreadHistoryPage = typeof OrchestrationV2ThreadHistoryPage.Type; const knownDomainEventTypes: ReadonlySet = new Set( - OrchestrationV2DomainEvent.members.flatMap((member) => { - const type = member.fields.type; - return "literals" in type ? type.literals : [type.literal]; - }), + OrchestrationV2DomainEvent.members.map((member) => member.fields.type.literal), ); export function isKnownOrchestrationV2EventType(type: string): boolean { @@ -4607,38 +4682,152 @@ export function isKnownOrchestrationV2EventType(type: string): boolean { } // Skip unknown event or turn-item types while advancing the resume cursor. -const OrchestrationV2UnknownThreadStreamEvent = Schema.Struct({ - kind: Schema.Literal("event"), - sequence: NonNegativeInt, - event: Schema.Struct({ - type: Schema.String, - payload: Schema.optional(Schema.Unknown), - }).check( +const OrchestrationV2UnknownDomainEvent = Schema.Struct({ + type: Schema.String, + payload: Schema.optional(Schema.Unknown), +}) + .check( Schema.makeFilter( (event) => !knownDomainEventTypes.has(event.type) || (event.type === "turn-item.updated" && isUnknownTurnItem(event.payload)) || "A known event type must decode in full.", ), - ), -}).pipe( + ) + .pipe( + Schema.decodeTo(Schema.instanceOf(UnknownUnionMember<"type">), { + decode: SchemaGetter.transform((event) => new UnknownUnionMember("type", event.type)), + encode: SchemaGetter.forbidden(() => "Servers never send unknown thread events."), + }), + ); + +// Single `kind: "event"` wire branch avoids a sentinel collision in SchemaBinary. +const OrchestrationV2ThreadStreamEventWire = Schema.Struct({ + kind: Schema.Literal("event"), + sequence: NonNegativeInt, + event: Schema.Union([...OrchestrationV2DomainEvent.members, OrchestrationV2UnknownDomainEvent]), +}); + +const OrchestrationV2ThreadStreamEventDecoded = Schema.Union([ + Schema.Struct({ + kind: Schema.Literal("event"), + sequence: NonNegativeInt, + event: OrchestrationV2DomainEvent, + }), + Schema.Struct({ + kind: Schema.Literal("unknown-event"), + sequence: NonNegativeInt, + eventType: Schema.String, + }), +]); + +const OrchestrationV2TurnItemUpdatedBinaryEvent = OrchestrationV2TurnItemUpdatedEvent.mapFields( + (fields) => ({ + ...fields, + payload: Schema.optionalKey(fields.payload), + }), +); + +const OrchestrationV2DomainEventBinary = Schema.Union([ + ...OrchestrationV2DomainEventMembersBeforeTurnItem, + OrchestrationV2TurnItemUpdatedBinaryEvent, + ...OrchestrationV2DomainEventMembersAfterTurnItem, +]); + +// Optional `event` and `turn-item.updated.payload` absorb SchemaBinary ABSENT on future variants. +const OrchestrationV2ThreadStreamEventBinaryWire = Schema.Struct({ + kind: Schema.Literal("event"), + sequence: NonNegativeInt, + event: Schema.optionalKey(OrchestrationV2DomainEventBinary), +}); + +const OrchestrationV2ThreadStreamEventBinary = OrchestrationV2ThreadStreamEventBinaryWire.pipe( Schema.decodeTo( - Schema.Struct({ - kind: Schema.Literal("unknown-event"), - sequence: NonNegativeInt, - eventType: Schema.String, + Schema.toType(OrchestrationV2ThreadStreamEventDecoded), + SchemaTransformation.transformEffect< + typeof OrchestrationV2ThreadStreamEventDecoded.Type, + typeof OrchestrationV2ThreadStreamEventBinaryWire.Type + >({ + decode: (item) => { + if (item.event === undefined) { + return Effect.succeed({ + kind: "unknown-event" as const, + sequence: item.sequence, + eventType: "unknown", + }); + } + if (item.event.type === "turn-item.updated" && item.event.payload === undefined) { + return Effect.succeed({ + kind: "unknown-event" as const, + sequence: item.sequence, + eventType: "turn-item.updated", + }); + } + return Effect.succeed({ + kind: "event" as const, + sequence: item.sequence, + event: item.event as OrchestrationV2DomainEvent, + }); + }, + encode: (item, options) => + item.kind === "unknown-event" + ? Effect.fail( + new SchemaIssue.Forbidden( + { message: "Servers never send unknown thread events." }, + item, + options, + ), + ) + : Effect.succeed({ + kind: "event" as const, + sequence: item.sequence, + event: item.event, + }), }), - { - decode: SchemaGetter.transform((item) => ({ - kind: "unknown-event" as const, - sequence: item.sequence, - eventType: item.event.type, - })), - encode: SchemaGetter.forbidden(() => "Servers never send unknown thread events."), - }, ), ); +const OrchestrationV2ThreadStreamEvent = OrchestrationV2ThreadStreamEventWire.pipe( + Schema.decodeTo( + Schema.toType(OrchestrationV2ThreadStreamEventDecoded), + SchemaTransformation.transformEffect< + typeof OrchestrationV2ThreadStreamEventDecoded.Type, + typeof OrchestrationV2ThreadStreamEventWire.Type + >({ + decode: (item) => + Effect.succeed( + isUnknownUnionMember(item.event) + ? { + kind: "unknown-event" as const, + sequence: item.sequence, + eventType: item.event.value, + } + : { + kind: "event" as const, + sequence: item.sequence, + event: item.event, + }, + ), + encode: (item, options) => + item.kind === "unknown-event" + ? Effect.fail( + new SchemaIssue.Forbidden( + { message: "Servers never send unknown thread events." }, + item, + options, + ), + ) + : Effect.succeed({ + kind: "event" as const, + sequence: item.sequence, + event: item.event, + }), + }), + ), +).annotate({ + [SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION]: OrchestrationV2ThreadStreamEventBinary.ast, +}); + export const OrchestrationV2ThreadStreamItem = withRecordIdTable( Schema.Union([ Schema.Struct({ @@ -4654,12 +4843,7 @@ export const OrchestrationV2ThreadStreamItem = withRecordIdTable( turnItemsOmitLocalVisible: Schema.optionalKey(Schema.Literal(true)), idTable: IdTableMarker, }), - Schema.Struct({ - kind: Schema.Literal("event"), - sequence: NonNegativeInt, - event: OrchestrationV2DomainEvent, - }), - OrchestrationV2UnknownThreadStreamEvent, + OrchestrationV2ThreadStreamEvent, ]), (item) => (item.kind === "snapshot" ? "projection" : undefined), ); diff --git a/packages/contracts/src/orchestrationV2IdTable.ts b/packages/contracts/src/orchestrationV2IdTable.ts index 3d4205be76ac5..85555f3e07750 100644 --- a/packages/contracts/src/orchestrationV2IdTable.ts +++ b/packages/contracts/src/orchestrationV2IdTable.ts @@ -1,6 +1,8 @@ import * as Schema from "effect/Schema"; import * as SchemaGetter from "effect/SchemaGetter"; +import { SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION } from "./baseSchemas.ts"; + /** * Opt-in wire form: on each record (top-level array element, top-level object, or `item`), values * under `id`, `*Id`, and `*Ids` index the response's `ids` table. Both peers must apply this exact @@ -121,5 +123,6 @@ export const withRecordIdTable = ( return { ...rest, [key]: internRecordIds(target, ids), ids }; }), }), + Schema.annotate({ [SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION]: schema.ast }), ); }; diff --git a/packages/contracts/src/providerUsageLimits.ts b/packages/contracts/src/providerUsageLimits.ts index bf31e218d0f78..a6ac36b2aa9d4 100644 --- a/packages/contracts/src/providerUsageLimits.ts +++ b/packages/contracts/src/providerUsageLimits.ts @@ -134,13 +134,25 @@ export const UsageLimitSourceConsumeResetCreditInput = Schema.Struct({ export type UsageLimitSourceConsumeResetCreditInput = typeof UsageLimitSourceConsumeResetCreditInput.Type; -export const ProviderConsumeResetCreditInput = Schema.Union([ +const ProviderConsumeResetCreditInputTarget = Schema.Union([ Schema.Struct({ instanceId: ProviderInstanceId, creditId: Schema.optional(TrimmedNonEmptyString), }), UsageLimitSourceConsumeResetCreditInput, ]); + +// Single wire struct avoids an untagged struct-struct union in SchemaBinary while keeping JSON identical. +const ProviderConsumeResetCreditInputWire = Schema.Struct({ + instanceId: Schema.optionalKey(Schema.String), + sourceId: Schema.optionalKey(Schema.String), + accountId: Schema.optionalKey(Schema.String), + creditId: Schema.optional(Schema.String), +}); + +export const ProviderConsumeResetCreditInput = ProviderConsumeResetCreditInputWire.pipe( + Schema.decodeTo(ProviderConsumeResetCreditInputTarget), +); export type ProviderConsumeResetCreditInput = typeof ProviderConsumeResetCreditInput.Type; export class UsageLimitSourceError extends Schema.TaggedError()( diff --git a/packages/contracts/src/scheduledTask.ts b/packages/contracts/src/scheduledTask.ts index 7fb686afb3f09..62e62b6f78875 100644 --- a/packages/contracts/src/scheduledTask.ts +++ b/packages/contracts/src/scheduledTask.ts @@ -363,7 +363,7 @@ export const ScheduledTaskWebhookDeliverySummary = Schema.Struct({ contentType: Schema.NullOr(Schema.String), bodyBytes: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), // Any string, so an outcome added later doesn't break a client's whole list. - outcome: Schema.Union([ScheduledTaskWebhookDeliveryOutcome, Schema.String]), + outcome: Schema.String, signatureVerified: Schema.Boolean, pendingWindow: Schema.optional(Schema.Boolean), missingFields: Schema.Array(Schema.String), diff --git a/packages/contracts/src/secretRequest.ts b/packages/contracts/src/secretRequest.ts index 699f85992d8ab..bd4036f2c91d0 100644 --- a/packages/contracts/src/secretRequest.ts +++ b/packages/contracts/src/secretRequest.ts @@ -14,17 +14,29 @@ export function secretRequestPageUrl(value: string): URL | null { } } +const SecretRequestSaveAnswer = Schema.Struct({ + type: Schema.Literal("save"), + secret: Schema.optionalKey(Schema.String), + values: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)), +}).pipe( + Schema.decodeTo( + Schema.Union([ + Schema.Struct({ type: Schema.Literal("save"), secret: TrimmedNonEmptyString }), + /** A request with `fields`: one value per field name. */ + Schema.Struct({ + type: Schema.Literal("save"), + values: Schema.Record(Schema.String, TrimmedNonEmptyString), + }), + ]), + ), +); + /** Server stores the value under a one-use SecretRef; the thread learns only status. */ export const SecretRequestAnswerInput = Schema.Struct({ threadId: ThreadId, turnItemId: TurnItemId, answer: Schema.Union([ - Schema.Struct({ type: Schema.Literal("save"), secret: TrimmedNonEmptyString }), - /** A request with `fields`: one value per field name. */ - Schema.Struct({ - type: Schema.Literal("save"), - values: Schema.Record(Schema.String, TrimmedNonEmptyString), - }), + SecretRequestSaveAnswer, Schema.Struct({ type: Schema.Literal("decline") }), /** Read once through a configured secret provider; only servers advertising `secretRequestReferences` accept it. */ Schema.Struct({ type: Schema.Literal("reference"), reference: SecretReference }), diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index afeccb00b3da2..45d856fba18a2 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -410,7 +410,12 @@ export const VoiceTranscriptionDestination = Schema.Union([ Schema.Struct({ kind: Schema.Literal("cloud"), environmentId: EnvironmentId, - provider: Schema.Literals(["openai", "xai"]), + provider: Schema.Literal("openai"), + }), + Schema.Struct({ + kind: Schema.Literal("cloud"), + environmentId: EnvironmentId, + provider: Schema.Literal("xai"), }), Schema.Struct({ kind: Schema.Literal("cloud"), diff --git a/packages/contracts/src/speech.ts b/packages/contracts/src/speech.ts index b9359f21595b3..a1f7f5d62e231 100644 --- a/packages/contracts/src/speech.ts +++ b/packages/contracts/src/speech.ts @@ -98,11 +98,13 @@ export const SpeechCustomWords = Schema.Array( ); export type SpeechCustomWords = typeof SpeechCustomWords.Type; -export const SpeechAcceleration = Schema.Union([ +const SpeechAccelerationTarget = Schema.Union([ Schema.Literal("auto"), Schema.Literal("cpu"), Schema.String.check(Schema.isPattern(/^gpu:.+/), Schema.isMaxLength(500)), ]); + +export const SpeechAcceleration = Schema.String.pipe(Schema.decodeTo(SpeechAccelerationTarget)); export type SpeechAcceleration = typeof SpeechAcceleration.Type; export const SpeechModelUnloadTimeout = Schema.Literals([ diff --git a/packages/shared/src/socketFrameParts.test.ts b/packages/shared/src/socketFrameParts.test.ts index 04f63516d6b44..2b7a74447dada 100644 --- a/packages/shared/src/socketFrameParts.test.ts +++ b/packages/shared/src/socketFrameParts.test.ts @@ -1,13 +1,55 @@ +import { + DEFAULT_SERVER_SETTINGS, + EditorId, + EnvironmentId, + EventId, + ForwardCompatibleArray, + ForwardCompatibleUnionArray, + KeybindingShortcut, + KeybindingWhenNode, + MessageId, + NodeId, + NonNegativeInt, + OrchestrationV2Notification, + OrchestrationV2ProjectedTurnItem, + OrchestrationV2ThreadHistoryPage, + OrchestrationV2ThreadProjection, + OrchestrationV2ThreadShell, + OrchestrationV2ThreadStreamItem, + OrchestrationV2TurnItem, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ProviderThreadId, + RunId, + SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION, + ServerConfig, + ServerConfigIssue, + ThreadId, + TurnItemId, +} from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import type * as Arr from "effect/Array"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as RpcSerialization from "effect/rpc/RpcSerialization"; +import * as Schema from "effect/Schema"; +import * as SchemaTransformation from "effect/SchemaTransformation"; import * as Socket from "effect/socket/Socket"; import { joinSocketFrameParts, + layerSocketSchemaBinary, MAX_SOCKET_ACK_WINDOW, parseSocketAckWindow, + parseSocketRpcCodec, + SCHEMA_BINARY_PING_FRAME, + SCHEMA_BINARY_PONG_FRAME, SOCKET_FRAME_PART_BYTES, + SOCKET_RPC_CODEC_JSON, + SOCKET_RPC_CODEC_SCHEMA_BINARY, + splitBinarySocketFrame, splitLargeSocketFrames, splitSocketFrame, utf8ByteLength, @@ -134,4 +176,820 @@ describe("socketFrameParts", () => { expect(utf8ByteLength(sample)).toBe(encoder.encode(sample).length); } }); + + it("parses rpcCodec query values with safe JSON fallback", () => { + expect(parseSocketRpcCodec(null)).toBe(SOCKET_RPC_CODEC_JSON); + expect(parseSocketRpcCodec(undefined)).toBe(SOCKET_RPC_CODEC_JSON); + expect(parseSocketRpcCodec("")).toBe(SOCKET_RPC_CODEC_JSON); + expect(parseSocketRpcCodec("json")).toBe(SOCKET_RPC_CODEC_JSON); + expect(parseSocketRpcCodec("SCHEMA-BINARY")).toBe(SOCKET_RPC_CODEC_JSON); + expect(parseSocketRpcCodec("unknown")).toBe(SOCKET_RPC_CODEC_JSON); + expect(parseSocketRpcCodec("schema-binary")).toBe(SOCKET_RPC_CODEC_SCHEMA_BINARY); + }); + + it.effect("encodes SchemaBinary Ping and Pong control frames with nonzero leading bytes", () => + Effect.gen(function* () { + const serialization = yield* RpcSerialization.RpcSerialization; + const parser = serialization.makeUnsafe(); + expect(SCHEMA_BINARY_PING_FRAME[0]).toBeGreaterThan(0); + expect(SCHEMA_BINARY_PONG_FRAME[0]).toBeGreaterThan(0); + expect(parser.decode(SCHEMA_BINARY_PING_FRAME)).toEqual([{ _tag: "Ping" }]); + expect(parser.decode(SCHEMA_BINARY_PONG_FRAME)).toEqual([{ _tag: "Pong" }]); + }).pipe(Effect.provide(layerSocketSchemaBinary)), + ); + + it.effect( + "splits and reassembles large binary frames cleanly across interior magic bytes and interleaved heartbeats", + () => + Effect.gen(function* () { + const small = new Uint8Array([0x05, 0x00, 0x01, 0x02]); + expect(splitBinarySocketFrame(small, 16)).toEqual([small]); + + // Leading byte >= 1 mirrors real SchemaBinary frames; interior bytes include 0x00/0x01/0x02. + const large = new Uint8Array(64); + large[0] = 0x40; + for (let index = 1; index < large.length; index++) { + large[index] = index % 4; + } + const parts = splitBinarySocketFrame(large, 20); + expect(parts.length).toBeGreaterThan(2); + for (const part of parts) { + expect(part.byteLength).toBeLessThanOrEqual(20); + expect(part[0]).toBe(0x00); + } + for (const part of parts.slice(0, -1)) { + expect(part[1]).toBe(0x01); + } + expect(parts.at(-1)?.[1]).toBe(0x02); + + const interleaved: Arr.NonEmptyReadonlyArray = [ + parts[0], + SCHEMA_BINARY_PONG_FRAME, + ...parts.slice(1), + ]; + const { socket, written } = makeChunkSocket([[small], interleaved]); + + const writerSocket = splitLargeSocketFrames(socket, 20); + const writer = yield* writerSocket.writer; + yield* writer.write(small); + yield* writer.write(large); + expect(written).toEqual([small, ...parts]); + + const readerSocket = joinSocketFrameParts(socket); + const reader = yield* readerSocket.reader; + expect(yield* reader.pull).toEqual([small]); + const batch = yield* reader.pull; + expect(batch.slice(0, -1)).toEqual( + Array.from({ length: parts.length }, () => SCHEMA_BINARY_PONG_FRAME), + ); + expect(batch.at(-1)).toEqual(large); + }).pipe(Effect.scoped), + ); +}); + +describe("layerSocketSchemaBinary forward-compatibility under version skew", () => { + const binaryTranscode = ( + futureSchema: Schema.Codec, + currentSchema: Schema.Codec, + value: FutureA, + ) => + Effect.gen(function* () { + const serialization = yield* RpcSerialization.RpcSerialization; + const futureCodec = serialization.codecFor(futureSchema); + const currentCodec = serialization.codecFor(currentSchema); + const encodeFuture = Schema.encodeUnknownEffect(futureCodec); + const decodeCurrent = Schema.decodeUnknownEffect(currentCodec); + const encoded = yield* encodeFuture(value); + const bytes = encoded instanceof Uint8Array ? encoded.slice() : encoded; + return yield* decodeCurrent(bytes); + }); + + const jsonTranscode = ( + futureSchema: Schema.Codec, + currentSchema: Schema.Codec, + value: FutureA, + ) => + Effect.gen(function* () { + const encodeFuture = Schema.encodeUnknownEffect(Schema.toCodecJson(futureSchema)); + const decodeCurrent = Schema.decodeUnknownEffect(Schema.toCodecJson(currentSchema)); + const wire = yield* encodeFuture(value); + return yield* decodeCurrent(wire); + }); + + const now = DateTime.makeUnsafe("2026-11-01T12:00:00.000Z"); + const nowIso = DateTime.formatIso(now); + const threadId = ThreadId.make("thread:skew-1"); + const projectId = ProjectId.make("project:skew-1"); + const instanceId = ProviderInstanceId.make("codex"); + const runId = RunId.make("run:skew-1"); + const nodeId = NodeId.make("node:skew-1"); + const messageId = MessageId.make("msg:skew-1"); + const providerThreadId = ProviderThreadId.make("prov-thread:skew-1"); + + const makeBaseShell = (): OrchestrationV2ThreadShell => ({ + createdBy: "user", + creationSource: "web", + id: threadId, + projectId, + title: "Skew thread", + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: providerThreadId, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + latestRunId: runId, + activeRunId: null, + status: "idle", + pendingRuntimeRequest: null, + latestVisibleMessage: null, + latestUserMessageAt: null, + hasActionableProposedPlan: false, + pendingBackgroundTasks: [], + providerInstanceHistory: [instanceId], + itemCount: 0, + visibleItemCount: 0, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + deletedAt: null, + }); + + const makeTurnItemBase = (id: string, ordinal: number) => ({ + id: TurnItemId.make(id), + threadId, + runId, + nodeId, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed" as const, + title: null, + startedAt: null, + completedAt: null, + updatedAt: now, + }); + + const turnItemBaseFields = { + id: TurnItemId, + threadId: ThreadId, + runId: Schema.NullOr(RunId), + nodeId: Schema.NullOr(NodeId), + providerThreadId: Schema.NullOr(ProviderThreadId), + providerTurnId: Schema.NullOr(Schema.String), + nativeItemRef: Schema.NullOr(Schema.Unknown), + parentItemId: Schema.NullOr(TurnItemId), + ordinal: NonNegativeInt, + status: Schema.Literals(["pending", "in_progress", "completed", "failed", "cancelled"]), + title: Schema.NullOr(Schema.String), + startedAt: Schema.NullOr(Schema.DateTimeUtc), + completedAt: Schema.NullOr(Schema.DateTimeUtc), + updatedAt: Schema.DateTimeUtc, + }; + + it.effect( + "preserves full AST context (optionality, mutability, annotations, defaults) across binary AST unwrapping", + () => + Effect.gen(function* () { + const Inner = Schema.Struct({ value: Schema.String }); + const Wrapped = Schema.String.pipe( + Schema.decodeTo( + Inner, + SchemaTransformation.transform({ + decode: (value) => ({ value }), + encode: ({ value }) => value, + }), + ), + Schema.annotate({ [SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION]: Inner.ast }), + ); + const Container = Schema.Struct({ + entry: Wrapped.pipe( + Schema.optionalKey, + Schema.mutableKey, + Schema.annotateKey({ description: "Optional unwrapped entry" }), + Schema.withConstructorDefault(Effect.succeed({ value: "default" })), + ), + }); + expect(yield* binaryTranscode(Container, Container, {})).toEqual({}); + expect(yield* binaryTranscode(Container, Container, { entry: { value: "ok" } })).toEqual({ + entry: { value: "ok" }, + }); + }).pipe(Effect.provide(layerSocketSchemaBinary)), + ); + + it.effect( + "drops unknown future EditorId, ServerConfigIssue, KeybindingCommand, and KeybindingWhenNode entries identically to JSON", + () => + Effect.gen(function* () { + const FutureEditorId = Schema.Union([EditorId, Schema.Literal("future-editor")]); + const FutureServerConfigIssue = Schema.Union([ + ...ServerConfigIssue.members, + Schema.Struct({ + kind: Schema.Literal("keybindings.future-issue"), + message: Schema.String, + severity: Schema.Number, + }), + ]); + const FutureWhenNode = Schema.Union([ + ...KeybindingWhenNode.members, + Schema.Struct({ + type: Schema.Literal("xor"), + left: KeybindingWhenNode, + right: KeybindingWhenNode, + }), + ]); + const FutureKeybindingRule = Schema.Struct({ + command: Schema.String, + shortcut: KeybindingShortcut, + whenAst: Schema.optional(FutureWhenNode), + }); + const FutureServerConfig = ServerConfig.mapFields((fields) => ({ + ...fields, + availableEditors: ForwardCompatibleArray(FutureEditorId), + issues: ForwardCompatibleArray(FutureServerConfigIssue), + keybindings: ForwardCompatibleArray(FutureKeybindingRule), + })); + + const shortcut = { + key: "k", + metaKey: false, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: true, + }; + const futureConfig: typeof FutureServerConfig.Type = { + environment: { + environmentId: EnvironmentId.make("env:skew"), + label: "Future Server", + platform: { os: "linux", arch: "x64", machine: "desktop" }, + serverVersion: "2.0.0", + capabilities: { + repositoryIdentity: true, + wsRpcCodecs: ["json", SOCKET_RPC_CODEC_SCHEMA_BINARY], + }, + }, + auth: { + policy: "loopback-browser", + bootstrapMethods: [], + sessionMethods: ["browser-session-cookie"], + sessionCookieName: "t3-session", + }, + cwd: "/workspace/t3code", + keybindingsConfigPath: "/home/dev/.t3/keybindings.json", + keybindings: [ + { + command: "terminal.toggle", + shortcut, + whenAst: { type: "identifier", name: "editorFocus" }, + }, + { + command: "future.command", + shortcut, + }, + { + command: "sidebar.toggle", + shortcut, + whenAst: { + type: "xor", + left: { type: "identifier", name: "a" }, + right: { type: "identifier", name: "b" }, + }, + }, + ], + issues: [ + { kind: "keybindings.malformed-config", message: "bad syntax" }, + { kind: "keybindings.future-issue", message: "new warning", severity: 2 }, + ], + providers: [ + { + instanceId, + driver: ProviderDriverKind.make("codex"), + enabled: true, + installed: true, + version: "2.0.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: nowIso, + models: [], + slashCommands: [], + skills: [], + }, + ], + availableEditors: ["cursor", "future-editor", "vscode"], + observability: { + logsDirectoryPath: "/home/dev/.t3/logs", + localTracingEnabled: false, + otlpTracesEnabled: false, + otlpMetricsEnabled: false, + otlpLogsEnabled: false, + }, + settings: DEFAULT_SERVER_SETTINGS, + }; + + const binaryDecoded = yield* binaryTranscode( + FutureServerConfig, + ServerConfig, + futureConfig, + ); + const jsonDecoded = yield* jsonTranscode(FutureServerConfig, ServerConfig, futureConfig); + + expect(binaryDecoded.availableEditors).toEqual(["cursor", "vscode"]); + expect(binaryDecoded.issues).toEqual([ + { kind: "keybindings.malformed-config", message: "bad syntax" }, + ]); + // Unknown command AND unknown optional whenAst rule must both be dropped (never made unconditional). + expect(binaryDecoded.keybindings).toEqual([ + { + command: "terminal.toggle", + shortcut, + whenAst: { type: "identifier", name: "editorFocus" }, + }, + ]); + expect(binaryDecoded).toEqual(jsonDecoded); + }).pipe(Effect.provide(layerSocketSchemaBinary)), + ); + + it.effect( + "skips unknown future OrchestrationV2TurnItem variants across turnItems, visibleTurnItems, and history pages while rejecting malformed known variants", + () => + Effect.gen(function* () { + const FutureWidgetTurnItem = Schema.Struct({ + ...turnItemBaseFields, + type: Schema.Literal("future_widget"), + widgetLabel: Schema.String, + }); + const FutureTurnItem = Schema.Union([ + ...OrchestrationV2TurnItem.members, + FutureWidgetTurnItem, + ]); + const FutureProjectedTurnItem = OrchestrationV2ProjectedTurnItem.mapFields((fields) => ({ + ...fields, + item: FutureTurnItem, + })); + const FutureThreadProjection = OrchestrationV2ThreadProjection.mapFields((fields) => ({ + ...fields, + turnItems: ForwardCompatibleUnionArray(FutureTurnItem.members, "type"), + visibleTurnItems: Schema.Array(FutureProjectedTurnItem), + })); + const FutureHistoryPage = Schema.Struct({ + snapshotSequence: NonNegativeInt, + items: Schema.Array(FutureProjectedTurnItem), + nextCursor: Schema.NullOr(Schema.String), + hasMoreHistory: Schema.Boolean, + }); + + const knownAssistant: OrchestrationV2TurnItem = { + ...makeTurnItemBase("item:assistant", 0), + type: "assistant_message", + messageId, + text: "hello", + streaming: false, + }; + const futureWidget: typeof FutureWidgetTurnItem.Type = { + ...makeTurnItemBase("item:widget", 1), + type: "future_widget", + widgetLabel: "Live chart", + }; + const knownCommand: OrchestrationV2TurnItem = { + ...makeTurnItemBase("item:cmd", 2), + type: "command_execution", + input: "echo hi", + }; + const futureItems: ReadonlyArray = [ + knownAssistant, + futureWidget, + knownCommand, + ]; + const futureProjected = futureItems.map((item, position) => ({ + position, + visibility: "local" as const, + sourceThreadId: threadId, + sourceItemId: item.id, + item, + })); + const futureProjection: typeof FutureThreadProjection.Type = { + thread: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId, + title: "Skew thread", + providerInstanceId: instanceId, + modelSelection: { instanceId, model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: providerThreadId, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: now, + deletedAt: null, + }, + runs: [], + attempts: [], + nodes: [], + subagents: [], + providerSessions: [], + providerThreads: [], + providerTurns: [], + runtimeRequests: [], + messages: [], + plans: [], + turnItems: futureItems, + checkpointScopes: [], + checkpoints: [], + contextHandoffs: [], + contextTransfers: [], + visibleTurnItems: futureProjected, + updatedAt: now, + }; + + const binaryProjection = yield* binaryTranscode( + FutureThreadProjection, + OrchestrationV2ThreadProjection, + futureProjection, + ); + const jsonProjection = yield* jsonTranscode( + FutureThreadProjection, + OrchestrationV2ThreadProjection, + futureProjection, + ); + expect(binaryProjection.turnItems.map((item) => item.type)).toEqual([ + "assistant_message", + "command_execution", + ]); + expect(binaryProjection.visibleTurnItems.map((row) => row.item.type)).toEqual([ + "assistant_message", + "command_execution", + ]); + expect(binaryProjection).toEqual(jsonProjection); + + const futurePage: typeof FutureHistoryPage.Type = { + snapshotSequence: 5, + items: futureProjected, + nextCursor: null, + hasMoreHistory: false, + }; + const binaryPage = yield* binaryTranscode( + FutureHistoryPage, + OrchestrationV2ThreadHistoryPage, + futurePage, + ); + expect(binaryPage.items.map((row) => row.item.type)).toEqual([ + "assistant_message", + "command_execution", + ]); + + // Malformed known variant (assistant_message missing required `text`) must still fail. + const BrokenAssistant = Schema.Struct({ + ...turnItemBaseFields, + type: Schema.Literal("assistant_message"), + messageId: MessageId, + streaming: Schema.Boolean, + }); + const BrokenTurnItems = ForwardCompatibleUnionArray( + [BrokenAssistant, FutureWidgetTurnItem], + "type", + ); + const BrokenProjection = OrchestrationV2ThreadProjection.mapFields((fields) => ({ + ...fields, + turnItems: BrokenTurnItems, + visibleTurnItems: Schema.Array( + OrchestrationV2ProjectedTurnItem.mapFields((rowFields) => ({ + ...rowFields, + item: Schema.Union([BrokenAssistant, FutureWidgetTurnItem]), + })), + ), + })); + const brokenItem: typeof BrokenAssistant.Type = { + ...makeTurnItemBase("item:broken", 0), + type: "assistant_message", + messageId, + streaming: false, + }; + const brokenExit = yield* Effect.exit( + binaryTranscode(BrokenProjection, OrchestrationV2ThreadProjection, { + ...futureProjection, + turnItems: [brokenItem], + visibleTurnItems: [], + }), + ); + expect(Exit.isFailure(brokenExit)).toBe(true); + + const brokenVisibleExit = yield* Effect.exit( + binaryTranscode(BrokenProjection, OrchestrationV2ThreadProjection, { + ...futureProjection, + turnItems: [], + visibleTurnItems: [ + { + position: 0, + visibility: "local", + sourceThreadId: threadId, + sourceItemId: brokenItem.id, + item: brokenItem, + }, + ], + }), + ); + expect(Exit.isFailure(brokenVisibleExit)).toBe(true); + }).pipe(Effect.provide(layerSocketSchemaBinary)), + ); + + it.effect( + "decodes unknown future OrchestrationV2DomainEvent and turn-item.updated turn items to unknown-event while rejecting malformed known events", + () => + Effect.gen(function* () { + const FutureWidgetTurnItem = Schema.Struct({ + ...turnItemBaseFields, + type: Schema.Literal("future_widget"), + widgetLabel: Schema.String, + }); + const FutureTurnItem = Schema.Union([ + ...OrchestrationV2TurnItem.members, + FutureWidgetTurnItem, + ]); + const eventBaseFields = { + id: EventId, + threadId: ThreadId, + occurredAt: Schema.DateTimeUtc, + }; + const FutureCustomEvent = Schema.Struct({ + ...eventBaseFields, + type: Schema.Literal("future.event"), + payload: Schema.Struct({ flag: Schema.Boolean }), + }); + const FutureTurnItemUpdatedEvent = Schema.Struct({ + ...eventBaseFields, + type: Schema.Literal("turn-item.updated"), + payload: FutureTurnItem, + }); + const FutureStreamItem = Schema.Union([ + Schema.Struct({ kind: Schema.Literal("synchronized") }), + Schema.Struct({ + kind: Schema.Literal("event"), + sequence: NonNegativeInt, + event: Schema.Union([FutureCustomEvent, FutureTurnItemUpdatedEvent]), + }), + ]); + + const unknownDomainDecoded = yield* binaryTranscode( + FutureStreamItem, + OrchestrationV2ThreadStreamItem, + { + kind: "event", + sequence: 10, + event: { + id: EventId.make("evt:future-1"), + threadId, + occurredAt: now, + type: "future.event", + payload: { flag: true }, + }, + }, + ); + expect(unknownDomainDecoded).toEqual({ + kind: "unknown-event", + sequence: 10, + eventType: "unknown", + }); + + const unknownTurnItemDecoded = yield* binaryTranscode( + FutureStreamItem, + OrchestrationV2ThreadStreamItem, + { + kind: "event", + sequence: 11, + event: { + id: EventId.make("evt:future-2"), + threadId, + occurredAt: now, + type: "turn-item.updated", + payload: { + ...makeTurnItemBase("item:widget-stream", 0), + type: "future_widget", + widgetLabel: "Chart", + }, + }, + }, + ); + expect(unknownTurnItemDecoded).toEqual({ + kind: "unknown-event", + sequence: 11, + eventType: "turn-item.updated", + }); + + const knownTurnItemDecoded = yield* binaryTranscode( + FutureStreamItem, + OrchestrationV2ThreadStreamItem, + { + kind: "event", + sequence: 12, + event: { + id: EventId.make("evt:known-1"), + threadId, + occurredAt: now, + type: "turn-item.updated", + payload: { + ...makeTurnItemBase("item:known-stream", 1), + type: "assistant_message", + messageId, + text: "streamed", + streaming: false, + }, + }, + }, + ); + expect(knownTurnItemDecoded.kind).toBe("event"); + if (knownTurnItemDecoded.kind === "event") { + expect(knownTurnItemDecoded.sequence).toBe(12); + expect(knownTurnItemDecoded.event.type).toBe("turn-item.updated"); + } + + // Malformed known event (turn-item.updated carrying assistant_message missing `text`) must still fail. + const BrokenAssistant = Schema.Struct({ + ...turnItemBaseFields, + type: Schema.Literal("assistant_message"), + messageId: MessageId, + streaming: Schema.Boolean, + }); + const BrokenStreamItem = Schema.Union([ + Schema.Struct({ kind: Schema.Literal("synchronized") }), + Schema.Struct({ + kind: Schema.Literal("event"), + sequence: NonNegativeInt, + event: Schema.Union([ + FutureCustomEvent, + Schema.Struct({ + ...eventBaseFields, + type: Schema.Literal("turn-item.updated"), + payload: Schema.Union([BrokenAssistant, FutureWidgetTurnItem]), + }), + ]), + }), + ]); + const brokenExit = yield* Effect.exit( + binaryTranscode(BrokenStreamItem, OrchestrationV2ThreadStreamItem, { + kind: "event", + sequence: 13, + event: { + id: EventId.make("evt:broken"), + threadId, + occurredAt: now, + type: "turn-item.updated", + payload: { + ...makeTurnItemBase("item:broken-stream", 2), + type: "assistant_message", + messageId, + streaming: false, + }, + }, + }), + ); + expect(Exit.isFailure(brokenExit)).toBe(true); + }).pipe(Effect.provide(layerSocketSchemaBinary)), + ); + + it.effect( + "degrades unknown OrchestrationV2PendingBackgroundTask, OrchestrationV2NotificationSource, and evolved opens identically to JSON while rejecting malformed known values", + () => + Effect.gen(function* () { + const FuturePendingTaskWire = Schema.Struct({ + taskId: Schema.String, + description: Schema.optional(Schema.String), + parentTaskId: Schema.optional(Schema.String), + kind: Schema.optional(Schema.String), + childThreadId: Schema.optional(Schema.String), + schedule: Schema.optional(Schema.String), + }); + const FutureThreadShell = OrchestrationV2ThreadShell.mapFields((fields) => ({ + ...fields, + pendingBackgroundTasks: Schema.optional(Schema.Array(FuturePendingTaskWire)), + opens: Schema.optional(Schema.Unknown), + })); + + const futureShell = { + ...makeBaseShell(), + pendingBackgroundTasks: [ + { + taskId: "bg-future", + description: "Nightly", + parentTaskId: "parent-1", + kind: "workflow", + schedule: "0 3 * * *", + }, + { + taskId: "bg-sub", + kind: "subagent", + childThreadId: "thread:child", + }, + ], + opens: { version: 2, rank: "hot", openedAt: "2026-11-01" }, + }; + + const binaryShell = yield* binaryTranscode( + FutureThreadShell, + OrchestrationV2ThreadShell, + futureShell, + ); + const jsonShell = yield* jsonTranscode( + FutureThreadShell, + OrchestrationV2ThreadShell, + futureShell, + ); + expect(binaryShell.pendingBackgroundTasks).toEqual([ + { + taskId: "bg-future", + description: "Nightly", + parentTaskId: "parent-1", + kind: "background_task", + }, + { + taskId: "bg-sub", + kind: "subagent", + childThreadId: "thread:child", + }, + ]); + expect(binaryShell.opens).toBeNull(); + expect(binaryShell).toEqual(jsonShell); + + const validOpens = { openedAt: 1, score: 2, picks: [{ query: "ws", at: 1 }] }; + const binaryShellWithOpens = yield* binaryTranscode( + OrchestrationV2ThreadShell, + OrchestrationV2ThreadShell, + { ...makeBaseShell(), opens: validOpens }, + ); + expect(binaryShellWithOpens.opens).toEqual(validOpens); + + const brokenTaskExit = yield* Effect.exit( + binaryTranscode(FutureThreadShell, OrchestrationV2ThreadShell, { + ...makeBaseShell(), + pendingBackgroundTasks: [{ taskId: "", kind: "command" }], + }), + ); + expect(Exit.isFailure(brokenTaskExit)).toBe(true); + + const FutureNotificationSourceWire = Schema.Struct({ + kind: Schema.optional(Schema.String), + work: Schema.optional(Schema.String), + taskIds: Schema.optional(Schema.Array(Schema.String)), + childThreadId: Schema.optional(Schema.String), + workflowId: Schema.optional(Schema.String), + }); + const FutureNotification = OrchestrationV2Notification.mapFields((fields) => ({ + ...fields, + source: FutureNotificationSourceWire, + })); + const futureNotification = { + source: { kind: "workflow", workflowId: "wf-1" }, + outcome: "completed" as const, + summary: "Workflow finished", + }; + const binaryNotification = yield* binaryTranscode( + FutureNotification, + OrchestrationV2Notification, + futureNotification, + ); + const jsonNotification = yield* jsonTranscode( + FutureNotification, + OrchestrationV2Notification, + futureNotification, + ); + expect(binaryNotification.source).toEqual({ kind: "background_task" }); + expect(binaryNotification).toEqual(jsonNotification); + + const knownNotification = yield* binaryTranscode( + FutureNotification, + OrchestrationV2Notification, + { + source: { kind: "delegated_task", taskIds: [nodeId] }, + outcome: "completed", + summary: "Delegated task finished", + }, + ); + expect(knownNotification.source).toEqual({ kind: "delegated_task", taskIds: [nodeId] }); + + const brokenNotificationExit = yield* Effect.exit( + binaryTranscode(FutureNotification, OrchestrationV2Notification, { + source: { kind: "delegated_task" }, + outcome: "completed", + summary: "Broken delegated task", + }), + ); + expect(Exit.isFailure(brokenNotificationExit)).toBe(true); + }).pipe(Effect.provide(layerSocketSchemaBinary)), + ); }); diff --git a/packages/shared/src/socketFrameParts.ts b/packages/shared/src/socketFrameParts.ts index d79e7daa2ba49..3bebf8370ac89 100644 --- a/packages/shared/src/socketFrameParts.ts +++ b/packages/shared/src/socketFrameParts.ts @@ -1,14 +1,31 @@ +import { + SOCKET_BINARY_FORWARD_COMPATIBLE_ARRAY_ANNOTATION, + SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION, +} from "@t3tools/contracts"; import * as Arr from "effect/Array"; import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SchemaAST from "effect/SchemaAST"; +import * as SchemaTransformation from "effect/SchemaTransformation"; +import * as SchemaBinary from "effect/encoding/SchemaBinary"; +import * as RpcMessage from "effect/rpc/RpcMessage"; +import * as RpcSerialization from "effect/rpc/RpcSerialization"; import * as Socket from "effect/socket/Socket"; // Old clients omit these; old servers ignore them. export const SOCKET_FRAME_PARTS_QUERY_PARAM = "frameParts"; export const SOCKET_ACK_WINDOW_QUERY_PARAM = "ackWindow"; +export const SOCKET_RPC_CODEC_QUERY_PARAM = "rpcCodec"; +export const SOCKET_RPC_CODEC_JSON = "json"; +export const SOCKET_RPC_CODEC_SCHEMA_BINARY = "schema-binary"; +export type SocketRpcCodec = typeof SOCKET_RPC_CODEC_JSON | typeof SOCKET_RPC_CODEC_SCHEMA_BINARY; export const DEFAULT_SOCKET_ACK_WINDOW = 4; export const MAX_SOCKET_ACK_WINDOW = 4; // Half of the server's 64 KiB byte-windowed stream cap so large terminal chunks flush immediately. export const SOCKET_ACK_BYTE_FLUSH_THRESHOLD = 32 * 1024; +// Generous ceiling above Effect's 16 MiB default for large thread snapshots and file diffs. +const SOCKET_SCHEMA_BINARY_MAX_FRAME_SIZE = 128 * 1024 * 1024; // JSON snapshots compress ~4-6x under permessage-deflate, so 192 KiB raw UTF-8 stays around // 32-48 KiB on the wire (under the 15s liveness timeout even on slow links) and well below @@ -21,6 +38,688 @@ export function parseSocketAckWindow(value: string | null | undefined): number { return Math.max(1, Math.min(parsed, MAX_SOCKET_ACK_WINDOW)); } +export function parseSocketRpcCodec(value: string | null | undefined): SocketRpcCodec { + return value === SOCKET_RPC_CODEC_SCHEMA_BINARY + ? SOCKET_RPC_CODEC_SCHEMA_BINARY + : SOCKET_RPC_CODEC_JSON; +} + +const schemaBinaryEnvelopeEncoder = SchemaBinary.encoder(RpcMessage.EncodedSchema, { + fingerprint: true, +}); + +// Copy out of SchemaBinary's shared output arena so cached control frames own their buffers. +export const SCHEMA_BINARY_PING_FRAME: Uint8Array = schemaBinaryEnvelopeEncoder + .encode(RpcMessage.constPing) + .slice(); + +export const SCHEMA_BINARY_PONG_FRAME: Uint8Array = schemaBinaryEnvelopeEncoder + .encode(RpcMessage.constPong) + .slice(); + +function mapEncoding( + encoding: SchemaAST.Encoding | undefined, + walk: (ast: SchemaAST.AST) => SchemaAST.AST, +): SchemaAST.Encoding | undefined { + if (encoding === undefined) return undefined; + const mapped = SchemaAST.mapOrSame(encoding, (link) => { + const to = walk(link.to); + return to === link.to ? link : new SchemaAST.Link(to, link.transformation); + }); + return mapped === encoding ? encoding : (mapped as SchemaAST.Encoding); +} + +const UNKNOWN_BINARY_VARIANT = Symbol.for("t3/socket/unknownBinaryVariant"); + +function preserveAstContext( + walked: SchemaAST.AST, + context: SchemaAST.Context | undefined, +): SchemaAST.AST { + if (context === undefined) return walked; + let schema: Schema.Top = Schema.make(walked); + if (context.isOptional && schema.ast.context?.isOptional !== true) { + schema = Schema.optionalKey(schema); + } + if (context.isMutable && schema.ast.context?.isMutable !== true) { + schema = Schema.mutableKey(schema); + } + if (context.annotations !== undefined && schema.ast.context?.annotations === undefined) { + schema = schema.pipe(Schema.annotateKey(context.annotations)); + } + if ( + context.constructorDefault !== undefined && + schema.ast.context?.constructorDefault === undefined + ) { + schema = (schema as Schema.Top & { readonly "~type.constructor.default": "no-default" }).pipe( + Schema.withConstructorDefault(context.constructorDefault), + ); + } + return schema.ast; +} + +function stripArrayAnnotationAndContext(ast: SchemaAST.Arrays, key: string): SchemaAST.Arrays { + const annotations = + ast.annotations !== undefined && key in ast.annotations + ? Object.fromEntries(Object.entries(ast.annotations).filter(([entryKey]) => entryKey !== key)) + : ast.annotations; + return new SchemaAST.Arrays( + ast.isMutable, + ast.elements, + ast.rest, + annotations !== undefined && Object.keys(annotations).length === 0 ? undefined : annotations, + ast.checks, + ast.encoding, + undefined, + ast.encodingChecks, + ); +} + +function resolveSuspend(ast: SchemaAST.AST): SchemaAST.AST { + const seen = new Set(); + let cur = ast; + while (SchemaAST.isSuspend(cur) && !seen.has(cur)) { + seen.add(cur); + cur = cur.thunk(); + } + return cur; +} + +function collectObjectSentinelKeys(ast: SchemaAST.Objects): ReadonlySet { + const keys = new Set(); + for (const ps of ast.propertySignatures) { + if ( + !SchemaAST.isOptional(ps.type) && + (SchemaAST.isLiteral(ps.type) || SchemaAST.isUniqueSymbol(ps.type)) + ) { + keys.add(ps.name); + } + } + return keys; +} + +function collectArraySentinelIndices(ast: SchemaAST.Arrays): ReadonlySet { + const indices = new Set(); + for (let i = 0; i < ast.elements.length; i++) { + const element = ast.elements[i]!; + if ( + !SchemaAST.isOptional(element) && + (SchemaAST.isLiteral(element) || SchemaAST.isUniqueSymbol(element)) + ) { + indices.add(i); + } + } + return indices; +} + +function flattenUnionMembers(ast: SchemaAST.Union): ReadonlyArray { + const out: Array = []; + const seen = new Set(); + const visit = (member: SchemaAST.AST): void => { + const resolved = resolveSuspend(member); + if (seen.has(resolved)) return; + seen.add(resolved); + if (SchemaAST.isNever(resolved)) return; + if (SchemaAST.isUnion(resolved)) { + for (const inner of resolved.types) visit(inner); + return; + } + if (SchemaAST.isEnum(resolved)) { + for (const [, value] of resolved.enums) { + out.push(new SchemaAST.Literal(value)); + } + return; + } + out.push(resolved); + }; + for (const member of ast.types) visit(member); + return out; +} + +function widenedPrimitiveKind(ast: SchemaAST.AST): string | undefined { + switch (ast._tag) { + case "String": + case "TemplateLiteral": + return "String"; + case "Number": + return "Number"; + case "Boolean": + return "Boolean"; + case "BigInt": + return "BigInt"; + case "Symbol": + case "UniqueSymbol": + return "Symbol"; + case "Null": + return "Null"; + case "Undefined": + case "Void": + return "Undefined"; + case "Unknown": + case "Any": + case "ObjectKeyword": + return "Unknown"; + case "Literal": + switch (typeof ast.literal) { + case "string": + return "String"; + case "number": + return "Number"; + case "boolean": + return "Boolean"; + case "bigint": + return "BigInt"; + default: + return undefined; + } + default: + return undefined; + } +} + +function needsAbsenceWrapper(ast: SchemaAST.AST): boolean { + const resolved = resolveSuspend(ast); + if (!SchemaAST.isUnion(resolved)) return false; + const members = flattenUnionMembers(resolved); + let nonNullishBranches = 0; + const seenPrimitiveKinds = new Set(); + for (const member of members) { + if (SchemaAST.isObjects(member) && collectObjectSentinelKeys(member).size > 0) return true; + if (SchemaAST.isArrays(member) && collectArraySentinelIndices(member).size > 0) return true; + const prim = widenedPrimitiveKind(member); + if (prim === "Null" || prim === "Undefined") continue; + if (prim !== undefined) { + if (seenPrimitiveKinds.has(prim)) continue; + seenPrimitiveKinds.add(prim); + } + nonNullishBranches++; + } + return nonNullishBranches >= 2; +} + +function unionIncludesUndefined(ast: SchemaAST.AST): boolean { + const resolved = resolveSuspend(ast); + if (SchemaAST.isUndefined(resolved) || SchemaAST.isVoid(resolved)) return true; + if (!SchemaAST.isUnion(resolved)) return false; + return flattenUnionMembers(resolved).some( + (member) => SchemaAST.isUndefined(member) || SchemaAST.isVoid(member), + ); +} + +function stripUndefinedFromUnion(ast: SchemaAST.AST): SchemaAST.AST { + if (!SchemaAST.isUnion(ast)) return ast; + const remaining = ast.types.filter( + (member) => !SchemaAST.isUndefined(member) && !SchemaAST.isVoid(member), + ); + if (remaining.length === 0) return SchemaAST.never; + if (remaining.length === 1) return remaining[0]!; + return new SchemaAST.Union(remaining); +} + +function wrapUnionValueBox(widenedAst: SchemaAST.AST): SchemaAST.AST { + const box = Schema.Struct({ v: Schema.optionalKey(Schema.make(widenedAst)) }); + return box.pipe( + Schema.decodeTo( + Schema.Unknown, + SchemaTransformation.transform({ + decode: (raw) => (Object.hasOwn(raw, "v") ? raw.v : UNKNOWN_BINARY_VARIANT), + encode: (value) => ({ v: value }), + }), + ), + ).ast; +} + +function wrapOptionalUnionField( + originalAst: SchemaAST.AST, + widenedAst: SchemaAST.AST, +): SchemaAST.AST { + const hasUndefined = unionIncludesUndefined(originalAst); + const nonUndefined = stripUndefinedFromUnion(widenedAst); + if (!hasUndefined) return wrapUnionValueBox(nonUndefined); + const box = Schema.Struct({ v: Schema.optionalKey(Schema.make(nonUndefined)) }); + return Schema.Union([box, Schema.Undefined]).pipe( + Schema.decodeTo( + Schema.Unknown, + SchemaTransformation.transform({ + decode: (raw) => + raw === undefined ? undefined : Object.hasOwn(raw, "v") ? raw.v : UNKNOWN_BINARY_VARIANT, + encode: (value) => (value === undefined ? undefined : { v: value }), + }), + ), + ).ast; +} + +function widenIndexParameter(parameter: SchemaAST.AST): SchemaAST.AST { + if (SchemaAST.isSymbol(parameter) || SchemaAST.isUniqueSymbol(parameter)) { + return SchemaAST.symbol; + } + if (SchemaAST.isUnion(parameter)) { + const members = flattenUnionMembers(parameter); + const hasSymbol = members.some( + (member) => SchemaAST.isSymbol(member) || SchemaAST.isUniqueSymbol(member), + ); + const hasString = members.some( + (member) => !SchemaAST.isSymbol(member) && !SchemaAST.isUniqueSymbol(member), + ); + if (hasSymbol && hasString) return new SchemaAST.Union([SchemaAST.string, SchemaAST.symbol]); + if (hasSymbol) return SchemaAST.symbol; + } + return SchemaAST.string; +} + +function cloneSentinelLeaf(ast: SchemaAST.AST): SchemaAST.AST { + if (SchemaAST.isLiteral(ast)) return new SchemaAST.Literal(ast.literal); + if (SchemaAST.isUniqueSymbol(ast)) return new SchemaAST.UniqueSymbol(ast.symbol); + return ast; +} + +// Widens an encoded ForwardCompatibleArray element AST so SchemaBinary never throws on new +// literals, unknown union variants, or evolved fields before the element Schema drops the entry. +function widenForForwardCompatibleBinary(root: SchemaAST.AST): SchemaAST.AST { + const memo = new Map(); + + const widenObjects = ( + ast: SchemaAST.Objects, + sentinelKeys?: ReadonlySet, + ): SchemaAST.Objects => { + const propertySignatures = ast.propertySignatures.map((ps) => { + if (sentinelKeys?.has(ps.name)) { + return new SchemaAST.PropertySignature(ps.name, cloneSentinelLeaf(ps.type)); + } + const wasOptional = SchemaAST.isOptional(ps.type); + const widened = widen(ps.type); + const wrapped = + wasOptional && needsAbsenceWrapper(ps.type) + ? wrapOptionalUnionField(ps.type, widened) + : widened; + return new SchemaAST.PropertySignature( + ps.name, + Schema.optionalKey(Schema.make(wrapped)).ast, + ); + }); + const indexSignatures = ast.indexSignatures.map((is) => { + const widenedValue = widen(is.type); + const value = needsAbsenceWrapper(is.type) ? wrapUnionValueBox(widenedValue) : widenedValue; + return new SchemaAST.IndexSignature(widenIndexParameter(is.parameter), value); + }); + return new SchemaAST.Objects(propertySignatures, indexSignatures); + }; + + const widenArrays = ( + ast: SchemaAST.Arrays, + sentinelIndices?: ReadonlySet, + ): SchemaAST.AST => { + if (sentinelIndices !== undefined && sentinelIndices.size > 0) { + const elements = ast.elements.map((element, index) => { + if (sentinelIndices.has(index)) return cloneSentinelLeaf(element); + const widened = widen(element); + const wrapped = needsAbsenceWrapper(element) ? wrapUnionValueBox(widened) : widened; + return SchemaAST.isOptional(element) + ? Schema.optionalKey(Schema.make(wrapped)).ast + : wrapped; + }); + const rest = ast.rest.map((slot) => + needsAbsenceWrapper(slot) ? wrapUnionValueBox(widen(slot)) : widen(slot), + ); + return new SchemaAST.Arrays(false, elements, rest); + } + if (ast.elements.length === 0 && ast.rest.length === 1) { + const slot = ast.rest[0]!; + const widenedSlot = widen(slot); + if (!needsAbsenceWrapper(slot)) { + return new SchemaAST.Arrays(false, [], [widenedSlot]); + } + const box = Schema.Struct({ v: Schema.optionalKey(Schema.make(widenedSlot)) }); + return Schema.Array(box).pipe( + Schema.decodeTo( + Schema.Array(Schema.Unknown), + SchemaTransformation.transform< + ReadonlyArray, + ReadonlyArray<{ readonly v?: unknown }> + >({ + decode: (entries) => + entries.map((entry) => + Object.hasOwn(entry, "v") ? entry.v : UNKNOWN_BINARY_VARIANT, + ), + encode: (values) => values.map((v) => ({ v })), + }), + ), + ).ast; + } + const elements = ast.elements.map((element) => { + const widened = widen(element); + const wrapped = needsAbsenceWrapper(element) ? wrapUnionValueBox(widened) : widened; + return SchemaAST.isOptional(element) + ? Schema.optionalKey(Schema.make(wrapped)).ast + : wrapped; + }); + const rest = ast.rest.map((slot) => + needsAbsenceWrapper(slot) ? wrapUnionValueBox(widen(slot)) : widen(slot), + ); + return new SchemaAST.Arrays(false, elements, rest); + }; + + const widen = (ast: SchemaAST.AST): SchemaAST.AST => { + const cached = memo.get(ast); + if (cached !== undefined) return cached; + let next: SchemaAST.AST; + switch (ast._tag) { + case "String": + case "TemplateLiteral": + next = SchemaAST.string; + break; + case "Number": + next = SchemaAST.number; + break; + case "Boolean": + next = SchemaAST.boolean; + break; + case "BigInt": + next = SchemaAST.bigInt; + break; + case "Symbol": + case "UniqueSymbol": + next = SchemaAST.symbol; + break; + case "Null": + next = SchemaAST.null; + break; + case "Undefined": + case "Void": + next = SchemaAST.undefined; + break; + case "Never": + next = SchemaAST.never; + break; + case "Unknown": + case "Any": + case "ObjectKeyword": + next = SchemaAST.unknown; + break; + case "Literal": + switch (typeof ast.literal) { + case "string": + next = SchemaAST.string; + break; + case "number": + next = SchemaAST.number; + break; + case "boolean": + next = SchemaAST.boolean; + break; + case "bigint": + next = SchemaAST.bigInt; + break; + } + break; + case "Enum": { + let hasString = false; + let hasNumber = false; + for (const [, value] of ast.enums) { + if (typeof value === "string") hasString = true; + else hasNumber = true; + } + next = + hasString && hasNumber + ? new SchemaAST.Union([SchemaAST.string, SchemaAST.number]) + : hasString + ? SchemaAST.string + : hasNumber + ? SchemaAST.number + : SchemaAST.never; + break; + } + case "Suspend": { + next = new SchemaAST.Suspend(() => widen(ast.thunk())); + memo.set(ast, next); + return next; + } + case "Objects": + next = widenObjects(ast); + break; + case "Arrays": + next = widenArrays(ast); + break; + case "Union": { + const members = flattenUnionMembers(ast); + const out: Array = []; + const seenPrimitives = new Set(); + for (const member of members) { + if (SchemaAST.isObjects(member)) { + const sentinels = collectObjectSentinelKeys(member); + if (sentinels.size > 0) { + out.push(widenObjects(member, sentinels)); + continue; + } + } + if (SchemaAST.isArrays(member)) { + const sentinels = collectArraySentinelIndices(member); + if (sentinels.size > 0) { + out.push(widenArrays(member, sentinels)); + continue; + } + } + const widened = widen(member); + const prim = widenedPrimitiveKind(widened); + if (prim !== undefined) { + if (seenPrimitives.has(prim)) continue; + seenPrimitives.add(prim); + } + out.push(widened); + } + next = + out.length === 0 + ? SchemaAST.never + : out.length === 1 + ? out[0]! + : new SchemaAST.Union(out); + break; + } + case "Declaration": { + const typeParameters = SchemaAST.mapOrSame(ast.typeParameters, widen); + next = + typeParameters === ast.typeParameters && + ast.checks === undefined && + ast.encodingChecks === undefined + ? ast + : new SchemaAST.Declaration( + typeParameters, + ast.run, + ast.annotations, + undefined, + undefined, + undefined, + undefined, + ast.encodingRun, + ); + break; + } + } + memo.set(ast, next); + return next; + }; + + return widen(root); +} + +function buildForwardCompatibleBinaryArraySource(walkedElementAst: SchemaAST.AST): SchemaAST.AST { + const encodedElement = SchemaAST.toEncoded(walkedElementAst); + return widenForForwardCompatibleBinary(new SchemaAST.Arrays(false, [], [encodedElement])); +} + +function unwrapBinaryAst(root: SchemaAST.AST): SchemaAST.AST { + const memo = new Map(); + const walk = (ast: SchemaAST.AST): SchemaAST.AST => { + const cached = memo.get(ast); + if (cached !== undefined) return cached; + const unwrapped = SchemaAST.resolveAt(SOCKET_BINARY_UNWRAPPED_AST_ANNOTATION)( + ast, + ); + if (unwrapped !== undefined && SchemaAST.isAST(unwrapped)) { + const walked = walk(unwrapped); + const preserved = preserveAstContext(walked, ast.context); + memo.set(ast, preserved); + return preserved; + } + if (SchemaAST.isArrays(ast)) { + const fcElement = ast.annotations?.[SOCKET_BINARY_FORWARD_COMPATIBLE_ARRAY_ANNOTATION]; + if (fcElement !== undefined && SchemaAST.isAST(fcElement)) { + const walkedElement = walk(fcElement); + const binarySource = buildForwardCompatibleBinaryArraySource(walkedElement); + // `toEncoded(ForwardCompatibleArray)` strips the element middleware; swap directly to pure wire AST. + const isEncodedView = ast.rest.length === 1 && ast.rest[0]?.encoding === undefined; + const next = isEncodedView + ? preserveAstContext(SchemaAST.toEncoded(binarySource), ast.context) + : preserveAstContext( + SchemaAST.decodeTo( + binarySource, + walk( + stripArrayAnnotationAndContext( + ast, + SOCKET_BINARY_FORWARD_COMPATIBLE_ARRAY_ANNOTATION, + ), + ), + SchemaTransformation.passthrough(), + ), + ast.context, + ); + memo.set(ast, next); + return next; + } + } + // Register first so cyclic Suspend nodes terminate cleanly. + memo.set(ast, ast); + let next: SchemaAST.AST = ast; + switch (ast._tag) { + case "Arrays": { + const elements = SchemaAST.mapOrSame(ast.elements, walk); + const rest = SchemaAST.mapOrSame(ast.rest, walk); + const encoding = mapEncoding(ast.encoding, walk); + if (elements !== ast.elements || rest !== ast.rest || encoding !== ast.encoding) { + next = new SchemaAST.Arrays( + ast.isMutable, + elements, + rest, + ast.annotations, + ast.checks, + encoding, + ast.context, + ast.encodingChecks, + ); + } + break; + } + case "Objects": { + const propertySignatures = SchemaAST.mapOrSame(ast.propertySignatures, (ps) => { + const type = walk(ps.type); + return type === ps.type ? ps : new SchemaAST.PropertySignature(ps.name, type); + }); + const indexSignatures = SchemaAST.mapOrSame(ast.indexSignatures, (is) => { + const type = walk(is.type); + return type === is.type ? is : new SchemaAST.IndexSignature(is.parameter, type); + }); + const encoding = mapEncoding(ast.encoding, walk); + if ( + propertySignatures !== ast.propertySignatures || + indexSignatures !== ast.indexSignatures || + encoding !== ast.encoding + ) { + next = new SchemaAST.Objects( + propertySignatures, + indexSignatures, + ast.annotations, + ast.checks, + encoding, + ast.context, + ast.encodingChecks, + ); + } + break; + } + case "Union": { + const types = SchemaAST.mapOrSame(ast.types, walk); + const encoding = mapEncoding(ast.encoding, walk); + if (types !== ast.types || encoding !== ast.encoding) { + next = new SchemaAST.Union( + types, + ast.options, + ast.annotations, + ast.checks, + encoding, + ast.context, + ast.encodingChecks, + ); + } + break; + } + case "Declaration": { + const typeParameters = SchemaAST.mapOrSame(ast.typeParameters, walk); + const encoding = mapEncoding(ast.encoding, walk); + if (typeParameters !== ast.typeParameters || encoding !== ast.encoding) { + next = new SchemaAST.Declaration( + typeParameters, + ast.run, + ast.annotations, + ast.checks, + encoding, + ast.context, + ast.encodingChecks, + ast.encodingRun, + ); + } + break; + } + case "Suspend": { + const inner = ast.thunk(); + const walked = walk(inner); + const encoding = mapEncoding(ast.encoding, walk); + if (walked !== inner || encoding !== ast.encoding) { + next = new SchemaAST.Suspend( + () => walk(ast.thunk()), + ast.annotations, + ast.checks, + encoding, + ast.context, + ); + } + break; + } + default: + break; + } + memo.set(ast, next); + return next; + }; + return walk(root); +} + +const unwrappedSchemaCache = new WeakMap(); + +function unwrapBinarySchema(schema: S): S { + const cached = unwrappedSchemaCache.get(schema); + if (cached !== undefined) return cached as S; + const unwrappedAst = unwrapBinaryAst(schema.ast); + const result = + unwrappedAst === schema.ast ? schema : (Schema.make(unwrappedAst) as S); + unwrappedSchemaCache.set(schema, result); + return result; +} + +export const layerSocketSchemaBinary: Layer.Layer = Layer.effect( + RpcSerialization.RpcSerialization, + Effect.map(RpcSerialization.RpcSerialization, (base) => + RpcSerialization.RpcSerialization.of({ + ...base, + codecFor: (schema: S) => base.codecFor(unwrapBinarySchema(schema)), + }), + ), +).pipe( + Layer.provide( + RpcSerialization.layerSchemaBinary({ + maxFrameSize: SOCKET_SCHEMA_BINARY_MAX_FRAME_SIZE, + }), + ), +); + function isSurrogatePairAt(text: string, index: number, code: number): boolean { if (code < 0xd800 || code > 0xdbff || index + 1 >= text.length) return false; const next = text.charCodeAt(index + 1); @@ -41,6 +740,13 @@ export function utf8ByteLength(text: string): number { // No JSON message starts with a record separator. It marks every part but the last. const PART_PREFIX = "\u001e"; +// Every valid SchemaBinary frame starts with a nonzero varint frame length, so a leading +// 0x00 byte marks split binary parts with zero overhead on unsplit frames. +const BINARY_PART_MAGIC = 0x00; +const BINARY_PART_CONTINUE = 0x01; +const BINARY_PART_FINAL = 0x02; +const BINARY_PART_HEADER_BYTES = 2; + // The RPC client only counts frames that decode to messages as liveness, and // ignores pongs, so each held-back part reads to it as one. const PART_RECEIVED_FRAME = '{"_tag":"Pong"}'; @@ -70,20 +776,49 @@ export function splitSocketFrame( return Arr.append(parts, frame.slice(start)); } -/** Server side: sends string frames longer than one part as consecutive parts. */ +export function splitBinarySocketFrame( + frame: Uint8Array, + partBytes = SOCKET_FRAME_PART_BYTES, +): Arr.NonEmptyReadonlyArray { + if (frame.byteLength <= partBytes) return [frame]; + const payloadBytes = Math.max(1, partBytes - BINARY_PART_HEADER_BYTES); + const parts: Array = []; + let offset = 0; + while (offset + payloadBytes < frame.byteLength) { + const slice = frame.subarray(offset, offset + payloadBytes); + const part = new Uint8Array(BINARY_PART_HEADER_BYTES + slice.byteLength); + part[0] = BINARY_PART_MAGIC; + part[1] = BINARY_PART_CONTINUE; + part.set(slice, BINARY_PART_HEADER_BYTES); + parts.push(part); + offset += payloadBytes; + } + const tail = frame.subarray(offset); + const finalPart = new Uint8Array(BINARY_PART_HEADER_BYTES + tail.byteLength); + finalPart[0] = BINARY_PART_MAGIC; + finalPart[1] = BINARY_PART_FINAL; + finalPart.set(tail, BINARY_PART_HEADER_BYTES); + return Arr.append(parts, finalPart); +} + +/** Server side: sends frames longer than one part as consecutive parts. */ export function splitLargeSocketFrames( socket: Socket.Socket, partBytes = SOCKET_FRAME_PART_BYTES, ): Socket.Socket { const split = (chunk: string | Uint8Array): Arr.NonEmptyReadonlyArray => - typeof chunk === "string" ? splitSocketFrame(chunk, partBytes) : [chunk]; + typeof chunk === "string" + ? splitSocketFrame(chunk, partBytes) + : splitBinarySocketFrame(chunk, partBytes); return Socket.make({ reader: socket.reader, writer: Effect.map(socket.writer, (writer) => ({ write: (chunk) => typeof chunk === "string" ? writer.writeAll(splitSocketFrame(chunk, partBytes)) - : writer.write(chunk), + : chunk instanceof Uint8Array + ? writer.writeAll(splitBinarySocketFrame(chunk, partBytes)) + : writer.write(chunk), writeAll: (chunks) => writer.writeAll(Arr.flatMap(chunks, split)), })), }); @@ -94,16 +829,39 @@ export function joinSocketFrameParts(socket: Socket.Socket): Socket.Socket { return Socket.make({ reader: Effect.map(socket.reader, (reader) => { let pending = ""; - const join = (frame: string | Uint8Array) => { - if (typeof frame !== "string") return frame; - if (frame.startsWith(PART_PREFIX)) { - pending += frame.slice(PART_PREFIX.length); - return PART_RECEIVED_FRAME; + let pendingBinaryParts: Array = []; + const join = (frame: string | Uint8Array): string | Uint8Array => { + if (typeof frame === "string") { + if (frame.startsWith(PART_PREFIX)) { + pending += frame.slice(PART_PREFIX.length); + return PART_RECEIVED_FRAME; + } + if (pending === "") return frame; + const whole = pending + frame; + pending = ""; + return whole; + } + if (frame.byteLength >= BINARY_PART_HEADER_BYTES && frame[0] === BINARY_PART_MAGIC) { + const kind = frame[1]; + if (kind === BINARY_PART_CONTINUE) { + pendingBinaryParts.push(frame.subarray(BINARY_PART_HEADER_BYTES)); + return SCHEMA_BINARY_PONG_FRAME; + } + if (kind === BINARY_PART_FINAL && pendingBinaryParts.length > 0) { + pendingBinaryParts.push(frame.subarray(BINARY_PART_HEADER_BYTES)); + let totalBytes = 0; + for (const part of pendingBinaryParts) totalBytes += part.byteLength; + const whole = new Uint8Array(totalBytes); + let offset = 0; + for (const part of pendingBinaryParts) { + whole.set(part, offset); + offset += part.byteLength; + } + pendingBinaryParts = []; + return whole; + } } - if (pending === "") return frame; - const whole = pending + frame; - pending = ""; - return whole; + return frame; }; return { upgrade: reader.upgrade,