@anureo/host 0.0.0-stage → 0.3.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -2
- package/package.json +50 -4
- package/schema/v1/hx.schema.json +3422 -0
- package/src/catalog-store.ts +45 -0
- package/src/catalog-worker.ts +14 -0
- package/src/catalog.ts +179 -0
- package/src/compat.ts +7 -0
- package/src/errors.ts +24 -0
- package/src/host.ts +1229 -0
- package/src/index.ts +16 -0
- package/src/interaction-capture.ts +37 -0
- package/src/legacy-protocol/generated/types.ts +244 -0
- package/src/legacy-protocol/index.ts +37 -0
- package/src/native-subagent.ts +19 -0
- package/src/persistent-secrets.ts +34 -0
- package/src/protocol.ts +68 -0
- package/src/queue.ts +12 -0
- package/src/rpc.ts +43 -0
- package/src/scoped-host.ts +39 -0
- package/src/sqlite-bun.ts +12 -0
- package/src/sqlite-driver.ts +14 -0
- package/src/sqlite-node.ts +38 -0
- package/src/store.ts +408 -0
- package/src/subagents.ts +115 -0
- package/src/swarm-client.ts +113 -0
- package/src/swarm-workflows.ts +50 -0
- package/src/workspaces.ts +36 -0
- package/src/ws-bun-listener.ts +44 -0
- package/src/ws-connection.ts +127 -0
- package/src/ws-listener.ts +87 -0
- package/src/ws.ts +12 -0
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { createClient, HarnessSdkError, sdkError, type Client, type HarnessAdapter, type Session, type SessionEventSink } from '@anureo/sdk'
|
|
2
|
+
import { createSwarmAdapter, type SwarmModelCatalog, type SwarmWorkflowOptions } from '@anureo/adapter-swarm'
|
|
3
|
+
import { attachInteractionCapture, clientInteractionCapture, type InteractionCapture } from './interaction-capture'
|
|
4
|
+
|
|
5
|
+
/** A Host session owns the composed client and every isolated backend client. */
|
|
6
|
+
export async function createOwnedSwarmClient(backend: Client, modelCatalog?: SwarmModelCatalog, workflows?: SwarmWorkflowOptions, createBackend?: () => Client | Promise<Client>): Promise<Client> {
|
|
7
|
+
let swarm: HarnessAdapter | undefined
|
|
8
|
+
let closing: Promise<void> | undefined
|
|
9
|
+
let sink: SessionEventSink | undefined
|
|
10
|
+
let activeTurnId: string | undefined
|
|
11
|
+
const capture = clientInteractionCapture(backend)
|
|
12
|
+
const owned = new Set<Client>([backend])
|
|
13
|
+
let mainAllocated = false
|
|
14
|
+
const routes = new Map<string, { capture: InteractionCapture; nativeId: string }>()
|
|
15
|
+
const routedCapture: InteractionCapture = {
|
|
16
|
+
requests: { get: id => {
|
|
17
|
+
const route = routes.get(id), request = route?.capture.requests.get(route.nativeId)
|
|
18
|
+
return request ? { ...request, interactionId: id } : undefined
|
|
19
|
+
} },
|
|
20
|
+
pending: {
|
|
21
|
+
get: id => { const route = routes.get(id); return route?.capture.pending.get(route.nativeId) },
|
|
22
|
+
delete: id => { const route = routes.get(id); return route?.capture.pending.delete(route.nativeId) ?? false },
|
|
23
|
+
},
|
|
24
|
+
}
|
|
25
|
+
const observation = new AbortController()
|
|
26
|
+
const observers = new Set<Promise<void>>()
|
|
27
|
+
const observe = (session: Session, owner: Client) => {
|
|
28
|
+
const memberCapture = clientInteractionCapture(owner)
|
|
29
|
+
if (!memberCapture) return session
|
|
30
|
+
const events = session.events({ signal: observation.signal })
|
|
31
|
+
const forwarded = new Set<string>()
|
|
32
|
+
const reading = (async () => {
|
|
33
|
+
for await (const event of events) {
|
|
34
|
+
if (!sink) continue
|
|
35
|
+
if (event.type === 'interaction/requested' && activeTurnId) {
|
|
36
|
+
forwarded.add(event.payload.interactionId)
|
|
37
|
+
const interactionId = JSON.stringify([session.id, event.payload.interactionId])
|
|
38
|
+
routes.set(interactionId, { capture: memberCapture, nativeId: event.payload.interactionId })
|
|
39
|
+
// Interaction payloads refer to the outer turn; the capture retains native/private data.
|
|
40
|
+
await sink.emit({ type: event.type, payload: { ...event.payload, interactionId, turnId: activeTurnId, itemId: undefined } }, { turnId: activeTurnId })
|
|
41
|
+
} else if (event.type === 'interaction/resolved' && forwarded.delete(event.payload.interactionId)) {
|
|
42
|
+
const interactionId = JSON.stringify([session.id, event.payload.interactionId])
|
|
43
|
+
await sink.emit({ type: event.type, payload: { ...event.payload, interactionId } }, { turnId: activeTurnId })
|
|
44
|
+
routes.delete(interactionId)
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
})().catch(cause => {
|
|
48
|
+
if (sdkError(cause).code === 'OBSERVATION_CLOSED') return
|
|
49
|
+
// Failure may dispose the adapter, which drains this reader; never await that cycle here.
|
|
50
|
+
if (!closing && !observation.signal.aborted) void sink?.fail(cause).catch(() => {})
|
|
51
|
+
}).finally(async () => {
|
|
52
|
+
for (const id of forwarded) routes.delete(JSON.stringify([session.id, id]))
|
|
53
|
+
if (owner !== backend) {
|
|
54
|
+
try { await owner.dispose(); owned.delete(owner) }
|
|
55
|
+
catch (cause) { if (!closing) void sink?.fail(cause).catch(() => {}) }
|
|
56
|
+
}
|
|
57
|
+
})
|
|
58
|
+
observers.add(reading)
|
|
59
|
+
void reading.finally(() => observers.delete(reading)).catch(() => {})
|
|
60
|
+
return session
|
|
61
|
+
}
|
|
62
|
+
// Observe public session streams while leaving SDK execution and interaction settlement intact.
|
|
63
|
+
const sessions: Client['sessions'] = { ...backend.sessions, create: async (...args) => {
|
|
64
|
+
// Native interaction IDs are unique only within one adapter/client instance.
|
|
65
|
+
const owner = !capture || !mainAllocated ? backend : await createBackend!()
|
|
66
|
+
mainAllocated = true
|
|
67
|
+
if (closing) { await owner.dispose(); throw new HarnessSdkError('SESSION_CLOSED') }
|
|
68
|
+
owned.add(owner)
|
|
69
|
+
try { return observe(await owner.sessions.create(...args), owner) }
|
|
70
|
+
catch (cause) {
|
|
71
|
+
if (owner !== backend) {
|
|
72
|
+
try { await owner.dispose(); owned.delete(owner) }
|
|
73
|
+
catch (cleanup) { throw new AggregateError([cause, cleanup], 'Swarm member initialization failed') }
|
|
74
|
+
}
|
|
75
|
+
throw cause
|
|
76
|
+
}
|
|
77
|
+
} }
|
|
78
|
+
const borrowed = new Proxy(backend, { get: (target, key, receiver) => key === 'sessions' ? sessions : Reflect.get(target, key, receiver) })
|
|
79
|
+
const dispose = () => closing ??= (async () => {
|
|
80
|
+
const errors: unknown[] = []
|
|
81
|
+
try { await swarm?.dispose() } catch (cause) { errors.push(cause) }
|
|
82
|
+
for (const owner of owned) try { await owner.dispose() } catch (cause) { errors.push(cause) }
|
|
83
|
+
observation.abort()
|
|
84
|
+
await Promise.allSettled(observers)
|
|
85
|
+
if (errors.length) throw new AggregateError(errors, 'Swarm client cleanup failed')
|
|
86
|
+
})()
|
|
87
|
+
try {
|
|
88
|
+
if (capture && !createBackend) throw new Error('Captured Swarm sessions require an isolated backend factory')
|
|
89
|
+
swarm = createSwarmAdapter({ backend: borrowed, modelCatalog, workflows })
|
|
90
|
+
const client = await createClient({
|
|
91
|
+
adapter: { ...swarm, dispose, openSession: async (params, target) => {
|
|
92
|
+
sink = target
|
|
93
|
+
const emit: SessionEventSink['emit'] = async (event, scope) => {
|
|
94
|
+
if (event.type === 'turn/started') activeTurnId = event.payload.turnId
|
|
95
|
+
await target.emit(event, scope)
|
|
96
|
+
if (event.type === 'turn/completed') activeTurnId = undefined
|
|
97
|
+
}
|
|
98
|
+
const routed = new Proxy(target, { get: (original, key) => {
|
|
99
|
+
if (key === 'emit') return emit
|
|
100
|
+
const value = Reflect.get(original, key, original)
|
|
101
|
+
return typeof value === 'function' ? value.bind(original) : value
|
|
102
|
+
} })
|
|
103
|
+
return swarm!.openSession(params, routed)
|
|
104
|
+
} },
|
|
105
|
+
// The Host keeps the selected runtime identity; executionMode records composition.
|
|
106
|
+
identity: backend.identity,
|
|
107
|
+
})
|
|
108
|
+
return capture ? await attachInteractionCapture(client, routedCapture) : client
|
|
109
|
+
} catch (cause) {
|
|
110
|
+
try { await dispose() } catch (cleanup) { throw new AggregateError([cause, cleanup], 'Swarm initialization failed') }
|
|
111
|
+
throw cause
|
|
112
|
+
}
|
|
113
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
// Discovers swarm workflow registrations from a session workspace, mirroring the
|
|
2
|
+
// upstream CLI's project-scope `.anureo/workflows/` convention.
|
|
3
|
+
import { readdir } from 'node:fs/promises'
|
|
4
|
+
import { createRequire } from 'node:module'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { pathToFileURL } from 'node:url'
|
|
7
|
+
import { parseSwarmWorkflowRegistration, type SwarmWorkflowOptions, type SwarmWorkflowRegistration } from '@anureo/adapter-swarm'
|
|
8
|
+
|
|
9
|
+
const EXTENSIONS = ['.ts', '.js', '.mjs'] as const
|
|
10
|
+
const require = createRequire(import.meta.url)
|
|
11
|
+
|
|
12
|
+
/** Load workflow files from `<cwd>/.anureo/workflows/`; missing directory yields an empty list. */
|
|
13
|
+
export async function discoverSwarmWorkflows(cwd: string): Promise<SwarmWorkflowRegistration[]> {
|
|
14
|
+
const directory = join(cwd, '.anureo', 'workflows')
|
|
15
|
+
let files: string[]
|
|
16
|
+
try {
|
|
17
|
+
files = (await readdir(directory)).filter(name => EXTENSIONS.some(extension => name.endsWith(extension))).sort()
|
|
18
|
+
} catch { return [] }
|
|
19
|
+
const found = new Map<string, SwarmWorkflowRegistration>()
|
|
20
|
+
for (const name of files) {
|
|
21
|
+
const sourceFile = join(directory, name)
|
|
22
|
+
let module: Record<string, unknown>
|
|
23
|
+
try {
|
|
24
|
+
// The Host runs on Bun, whose require.cache also owns imported ES modules.
|
|
25
|
+
// Query-string versions alone do not invalidate Bun's file module cache.
|
|
26
|
+
delete require.cache[sourceFile]
|
|
27
|
+
module = await import(pathToFileURL(sourceFile).href) as Record<string, unknown>
|
|
28
|
+
} catch (cause) {
|
|
29
|
+
throw new Error(`cannot load swarm workflow ${sourceFile}: ${(cause as Error).message}`)
|
|
30
|
+
}
|
|
31
|
+
const candidate = module.workflow ?? module.default
|
|
32
|
+
if (candidate === undefined) continue
|
|
33
|
+
// The adapter rejects unknown registration fields, so the parsed registration is passed through as-is.
|
|
34
|
+
const registration = parseSwarmWorkflowRegistration(candidate)
|
|
35
|
+
found.set(registration.id, registration)
|
|
36
|
+
}
|
|
37
|
+
return [...found.values()]
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Journal directory for run manifests and step journals; kept under the workspace .anureo tree. */
|
|
41
|
+
export function swarmWorkflowJournalDirectory(cwd: string): string {
|
|
42
|
+
return join(cwd, '.anureo', 'workflow-runs')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Workflow adapter options for a workspace, or undefined when the workspace registers none. */
|
|
46
|
+
export async function swarmWorkflowOptions(cwd: string): Promise<SwarmWorkflowOptions | undefined> {
|
|
47
|
+
const registrations = await discoverSwarmWorkflows(cwd)
|
|
48
|
+
if (registrations.length === 0) return undefined
|
|
49
|
+
return { registrations, journalDirectory: swarmWorkflowJournalDirectory(cwd) }
|
|
50
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { HostError } from './errors'
|
|
2
|
+
|
|
3
|
+
/** Product workspace allocation. Requests deliberately contain no paths or commands. */
|
|
4
|
+
export type WorkspaceRequest = { kind: 'project' } | { kind: 'worktree'; name?: string; baseRef?: string; worktreeId?: string }
|
|
5
|
+
export type WorkspacePrincipal = { userId: string; mode: 'on' | 'off'; isAdmin?: boolean; service?: boolean }
|
|
6
|
+
export type WorkspaceContext = { principal: WorkspacePrincipal; projectId: string; sessionId: string }
|
|
7
|
+
/** cwd is an internal server value. Only the remaining fields are public metadata. */
|
|
8
|
+
export type WorkspaceBinding = { kind: 'project' | 'worktree'; cwd: string; worktreeId?: string; name?: string; branch?: string }
|
|
9
|
+
export type WorkspaceAllocation = { binding: WorkspaceBinding; created: boolean; rollback(): Promise<void> }
|
|
10
|
+
/** Constructed by Host after inspecting or disposing its independently owned runtime. */
|
|
11
|
+
export type WorkspaceStopEvidence = { stopped: true; source: 'native-inspect' | 'owned-runtime-disposed'; bindingGeneration: number }
|
|
12
|
+
export type WorkspaceIntegration = { result: 'merged' | 'noop' | 'conflict' | 'patch'; conflictFiles?: string[]; patchPath?: string }
|
|
13
|
+
export interface WorkspacePort {
|
|
14
|
+
allocate(context: WorkspaceContext & { request?: WorkspaceRequest }): Promise<WorkspaceAllocation>
|
|
15
|
+
get(context: WorkspaceContext): Promise<WorkspaceBinding>
|
|
16
|
+
integrate(context: WorkspaceContext & { worktreeId: string; mode: 'merge' | 'patch'; message?: string; force?: boolean; evidence: WorkspaceStopEvidence }): Promise<WorkspaceIntegration>
|
|
17
|
+
discard(context: WorkspaceContext & { worktreeId: string; force?: boolean; evidence: WorkspaceStopEvidence }): Promise<WorkspaceBinding>
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type WorkspaceExecutionState = {
|
|
21
|
+
status: string; activeTurnId?: string; pendingInteractions?: boolean; pendingQueue?: boolean
|
|
22
|
+
unknownOperation?: boolean; activeGoal?: boolean; managed?: boolean; executedTurns?: boolean
|
|
23
|
+
}
|
|
24
|
+
/** Call under the Host's session mutation lock, before reserving destructive work. */
|
|
25
|
+
export function assertWorkspaceMutable(state: WorkspaceExecutionState): void {
|
|
26
|
+
if (state.managed) throw new HostError('MANAGED_SESSION_IMMUTABLE')
|
|
27
|
+
if (state.status === 'recoveryRequired' || state.unknownOperation) throw new HostError('RECOVERY_REQUIRED')
|
|
28
|
+
if (['running', 'opening'].includes(state.status) || state.activeTurnId || state.pendingInteractions || state.pendingQueue || state.activeGoal) throw new HostError('SESSION_BUSY')
|
|
29
|
+
// 产品规则(2026-11):Harness 仅可在会话开始前选择;已执行过 turn 的会话锁定。
|
|
30
|
+
// 放在忙碌判定之后:运行中/排队等瞬时状态优先报 SESSION_BUSY,空闲的已开始会话才报 HARNESS_LOCKED。
|
|
31
|
+
if (state.executedTurns) throw new HostError('HARNESS_LOCKED', 'Harness selection is locked once a session has executed turns')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function assertWorkspaceStopEvidence(evidence: WorkspaceStopEvidence | undefined): void {
|
|
35
|
+
if (!evidence || evidence.stopped !== true || !['native-inspect', 'owned-runtime-disposed'].includes(evidence.source) || !Number.isSafeInteger(evidence.bindingGeneration) || evidence.bindingGeneration < 0) throw new HostError('RESULT_UNKNOWN', 'Native execution stop has not been verified', false, true)
|
|
36
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { createHostWebSocket, type HostWebSocketConnection } from './ws-connection'
|
|
2
|
+
import type { HostWebSocketListenerOptions } from './ws-listener'
|
|
3
|
+
|
|
4
|
+
export function listenBunHostWebSocket<Actor>(options: HostWebSocketListenerOptions<Actor>) {
|
|
5
|
+
const transport = createHostWebSocket(options)
|
|
6
|
+
const pathname = options.path ?? '/rpc'
|
|
7
|
+
const maxBufferedBytes = options.maxBufferedBytes ?? 16 * 1024 * 1024
|
|
8
|
+
if (!Number.isSafeInteger(maxBufferedBytes) || maxBufferedBytes < 1) throw new RangeError('maxBufferedBytes must be a positive integer')
|
|
9
|
+
type SocketData = { principal: () => Actor | null; connection?: HostWebSocketConnection }
|
|
10
|
+
const server = Bun.serve<SocketData>({
|
|
11
|
+
hostname: options.hostname ?? '127.0.0.1',
|
|
12
|
+
port: options.port ?? 0,
|
|
13
|
+
async fetch(request, server) {
|
|
14
|
+
if (new URL(request.url).pathname !== pathname) return new Response(null, { status: 404 })
|
|
15
|
+
if (request.headers.get('upgrade')?.toLowerCase() !== 'websocket') return new Response(null, { status: 426 })
|
|
16
|
+
const principal = await options.authenticate(request)
|
|
17
|
+
if (!principal || !principal()) return new Response(null, { status: 401 })
|
|
18
|
+
if (server.upgrade(request, { data: { principal } })) return
|
|
19
|
+
return new Response(null, { status: 400 })
|
|
20
|
+
},
|
|
21
|
+
websocket: {
|
|
22
|
+
maxPayloadLength: options.maxMessageBytes ?? 1024 * 1024,
|
|
23
|
+
backpressureLimit: maxBufferedBytes,
|
|
24
|
+
closeOnBackpressureLimit: true,
|
|
25
|
+
open(socket) {
|
|
26
|
+
socket.data.connection = transport.attach({
|
|
27
|
+
send: text => socket.send(text) > 0,
|
|
28
|
+
close: (code, reason) => socket.close(code, reason),
|
|
29
|
+
}, socket.data.principal)
|
|
30
|
+
},
|
|
31
|
+
message(socket, message) {
|
|
32
|
+
if (typeof message === 'string') void socket.data.connection?.receive(message)
|
|
33
|
+
else socket.close(1003, 'Text messages required')
|
|
34
|
+
},
|
|
35
|
+
close(socket) {
|
|
36
|
+
socket.data.connection?.disconnect()
|
|
37
|
+
},
|
|
38
|
+
},
|
|
39
|
+
})
|
|
40
|
+
return {
|
|
41
|
+
address: { address: server.hostname, port: server.port },
|
|
42
|
+
async close() { await server.stop(true) },
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { decodeRequest, rpcError, type HostConnection, type HostDispatcher, type RpcNotification, type RpcRequest, type RpcResponse } from './rpc'
|
|
3
|
+
|
|
4
|
+
export interface WebSocketPort {
|
|
5
|
+
/** Return false when the socket cannot accept the frame within its send budget. */
|
|
6
|
+
send(text: string, kind: 'response' | 'notification'): boolean | void
|
|
7
|
+
close(code: number, reason: string): void
|
|
8
|
+
onNotification?(notification: RpcNotification): void
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface HostWebSocketOptions<Actor> {
|
|
12
|
+
dispatcher: HostDispatcher<Actor>
|
|
13
|
+
maxMessageBytes?: number
|
|
14
|
+
maxInFlight?: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export interface HostWebSocketConnection {
|
|
18
|
+
readonly id: string
|
|
19
|
+
receive(text: string): Promise<void>
|
|
20
|
+
dispatch(request: RpcRequest): Promise<{ response: RpcResponse; sent: boolean } | undefined>
|
|
21
|
+
/** Call when the underlying connection closes or is removed from the host. */
|
|
22
|
+
disconnect(): void
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface HostWebSocket<Actor> {
|
|
26
|
+
attach(socket: WebSocketPort, principal: () => Actor | null, id?: string): HostWebSocketConnection
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function positiveLimit(value: number, name: string): number {
|
|
30
|
+
if (!Number.isSafeInteger(value) || value < 1) throw new RangeError(`${name} must be a positive integer`)
|
|
31
|
+
return value
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Attach a Host to an application-owned WebSocket without taking over routing or HTTP upgrade. */
|
|
35
|
+
export function createHostWebSocket<Actor>(options: HostWebSocketOptions<Actor>): HostWebSocket<Actor> {
|
|
36
|
+
const { dispatcher } = options
|
|
37
|
+
const maxMessageBytes = positiveLimit(options.maxMessageBytes ?? 1024 * 1024, 'maxMessageBytes')
|
|
38
|
+
const maxInFlight = positiveLimit(options.maxInFlight ?? 64, 'maxInFlight')
|
|
39
|
+
const active = new Set<string>()
|
|
40
|
+
|
|
41
|
+
return {
|
|
42
|
+
attach(socket: WebSocketPort, principal: () => Actor | null, id: string = randomUUID()): HostWebSocketConnection {
|
|
43
|
+
if (active.has(id)) throw new Error('Host connection id is already attached')
|
|
44
|
+
active.add(id)
|
|
45
|
+
let disconnected = false
|
|
46
|
+
let pending = 0
|
|
47
|
+
|
|
48
|
+
function disconnect() {
|
|
49
|
+
if (disconnected) return
|
|
50
|
+
disconnected = true
|
|
51
|
+
dispatcher.disconnect(id)
|
|
52
|
+
if (!pending) active.delete(id)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function close(code: number, reason: string) {
|
|
56
|
+
if (disconnected) return
|
|
57
|
+
disconnect()
|
|
58
|
+
socket.close(code, reason)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function send(message: unknown, kind: 'response' | 'notification' = 'response'): boolean {
|
|
62
|
+
if (disconnected) return false
|
|
63
|
+
try {
|
|
64
|
+
if (socket.send(JSON.stringify(message), kind) !== false) return true
|
|
65
|
+
} catch (error) {
|
|
66
|
+
close(1011, 'Send failed')
|
|
67
|
+
if (kind === 'notification') throw error
|
|
68
|
+
return false
|
|
69
|
+
}
|
|
70
|
+
close(1013, 'Send buffer full')
|
|
71
|
+
if (kind === 'notification') throw new Error('Host WebSocket send buffer full')
|
|
72
|
+
return false
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const connection: HostConnection<Actor> = {
|
|
76
|
+
id,
|
|
77
|
+
principal: () => disconnected ? null : principal(),
|
|
78
|
+
send(notification) {
|
|
79
|
+
if (disconnected) return
|
|
80
|
+
socket.onNotification?.(notification)
|
|
81
|
+
send(notification, 'notification')
|
|
82
|
+
},
|
|
83
|
+
close: () => close(1011, 'Host closed connection'),
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function dispatch(request: RpcRequest) {
|
|
87
|
+
if (disconnected) return
|
|
88
|
+
if (pending >= maxInFlight) {
|
|
89
|
+
const response = rpcError(request.id, -32000, 'Too many in-flight requests')
|
|
90
|
+
return { response, sent: send(response) }
|
|
91
|
+
}
|
|
92
|
+
pending++
|
|
93
|
+
try {
|
|
94
|
+
let response: RpcResponse
|
|
95
|
+
try { response = await dispatcher.handle(connection, request) }
|
|
96
|
+
catch { response = rpcError(request.id, -32603, 'Internal error') }
|
|
97
|
+
return { response, sent: send(response) }
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
pending--
|
|
101
|
+
if (disconnected && !pending) {
|
|
102
|
+
// A request that was already authorized can finish after the socket closes.
|
|
103
|
+
// Release any subscriptions it registered late before allowing id reuse.
|
|
104
|
+
dispatcher.disconnect(id)
|
|
105
|
+
active.delete(id)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
id,
|
|
112
|
+
async receive(text) {
|
|
113
|
+
if (disconnected) return
|
|
114
|
+
if (Buffer.byteLength(text) > maxMessageBytes) {
|
|
115
|
+
close(1009, 'Message too large')
|
|
116
|
+
return
|
|
117
|
+
}
|
|
118
|
+
const message = decodeRequest(text)
|
|
119
|
+
if ('jsonrpc' in message) send(message)
|
|
120
|
+
else await dispatch(message)
|
|
121
|
+
},
|
|
122
|
+
dispatch,
|
|
123
|
+
disconnect,
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
}
|
|
127
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { createServer } from 'node:http'
|
|
2
|
+
import type { Duplex } from 'node:stream'
|
|
3
|
+
import { WebSocket, WebSocketServer } from 'ws'
|
|
4
|
+
import { createHostWebSocket, type HostWebSocketOptions } from './ws-connection'
|
|
5
|
+
|
|
6
|
+
export interface HostWebSocketListenerOptions<Actor> extends HostWebSocketOptions<Actor> {
|
|
7
|
+
authenticate(request: Request): (() => Actor | null) | null | Promise<(() => Actor | null) | null>
|
|
8
|
+
hostname?: string
|
|
9
|
+
port?: number
|
|
10
|
+
path?: string
|
|
11
|
+
maxBufferedBytes?: number
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function rejectUpgrade(socket: Duplex, status: number, reason: string) {
|
|
15
|
+
socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** Start an application-owned listener. Closing it releases sockets without closing the Host. */
|
|
19
|
+
export async function listenNodeHostWebSocket<Actor>(options: HostWebSocketListenerOptions<Actor>) {
|
|
20
|
+
const transport = createHostWebSocket(options)
|
|
21
|
+
const pathname = options.path ?? '/rpc'
|
|
22
|
+
const maxBufferedBytes = options.maxBufferedBytes ?? 16 * 1024 * 1024
|
|
23
|
+
if (!Number.isSafeInteger(maxBufferedBytes) || maxBufferedBytes < 1) throw new RangeError('maxBufferedBytes must be a positive integer')
|
|
24
|
+
const websocket = new WebSocketServer({ noServer: true, maxPayload: options.maxMessageBytes ?? 1024 * 1024 })
|
|
25
|
+
const server = createServer((_request, response) => response.writeHead(404).end())
|
|
26
|
+
const upgrades = new Set<Duplex>()
|
|
27
|
+
let closing: Promise<void> | undefined
|
|
28
|
+
|
|
29
|
+
server.on('upgrade', (request, socket, head) => {
|
|
30
|
+
if (request.url?.split('?', 1)[0] !== pathname) {
|
|
31
|
+
rejectUpgrade(socket, 404, 'Not Found')
|
|
32
|
+
return
|
|
33
|
+
}
|
|
34
|
+
upgrades.add(socket)
|
|
35
|
+
const onError = () => socket.destroy()
|
|
36
|
+
socket.on('error', onError)
|
|
37
|
+
void Promise.resolve().then(() => options.authenticate(new Request(`http://localhost${request.url}`, { headers: request.headers as HeadersInit }))).then(principal => {
|
|
38
|
+
if (socket.destroyed) return
|
|
39
|
+
if (!principal || !principal()) {
|
|
40
|
+
rejectUpgrade(socket, 401, 'Unauthorized')
|
|
41
|
+
return
|
|
42
|
+
}
|
|
43
|
+
websocket.handleUpgrade(request, socket, head, peer => {
|
|
44
|
+
const connection = transport.attach({
|
|
45
|
+
send(text) {
|
|
46
|
+
if (peer.readyState !== WebSocket.OPEN || peer.bufferedAmount + Buffer.byteLength(text) > maxBufferedBytes) return false
|
|
47
|
+
peer.send(text, error => { if (error) peer.terminate() })
|
|
48
|
+
},
|
|
49
|
+
close(code, reason) { peer.close(code, reason) },
|
|
50
|
+
}, principal)
|
|
51
|
+
peer.on('message', (data, binary) => {
|
|
52
|
+
if (binary) peer.close(1003, 'Text messages required')
|
|
53
|
+
else void connection.receive(data.toString())
|
|
54
|
+
})
|
|
55
|
+
peer.once('close', () => connection.disconnect())
|
|
56
|
+
peer.on('error', () => peer.terminate())
|
|
57
|
+
})
|
|
58
|
+
}).catch(() => {
|
|
59
|
+
if (!socket.destroyed) rejectUpgrade(socket, 500, 'Internal Server Error')
|
|
60
|
+
}).finally(() => {
|
|
61
|
+
upgrades.delete(socket)
|
|
62
|
+
socket.off('error', onError)
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
await new Promise<void>((resolve, reject) => {
|
|
67
|
+
server.once('error', reject)
|
|
68
|
+
server.listen(options.port ?? 0, options.hostname ?? '127.0.0.1', () => {
|
|
69
|
+
server.off('error', reject)
|
|
70
|
+
resolve()
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
const address = server.address()
|
|
74
|
+
if (!address || typeof address === 'string') throw new Error('Expected a TCP address')
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
address,
|
|
78
|
+
close(): Promise<void> {
|
|
79
|
+
return closing ??= new Promise((resolve, reject) => {
|
|
80
|
+
for (const socket of upgrades) socket.destroy()
|
|
81
|
+
for (const peer of websocket.clients) peer.terminate()
|
|
82
|
+
websocket.close()
|
|
83
|
+
server.close(error => error ? reject(error) : resolve())
|
|
84
|
+
})
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
package/src/ws.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export { createHostWebSocket, type HostWebSocket, type HostWebSocketConnection, type HostWebSocketOptions, type WebSocketPort } from './ws-connection'
|
|
2
|
+
import type { HostWebSocketListenerOptions } from './ws-listener'
|
|
3
|
+
export type { HostWebSocketListenerOptions } from './ws-listener'
|
|
4
|
+
|
|
5
|
+
export async function listenHostWebSocket<Actor>(options: HostWebSocketListenerOptions<Actor>) {
|
|
6
|
+
if (typeof Bun !== 'undefined') {
|
|
7
|
+
const { listenBunHostWebSocket } = await import('./ws-bun-listener')
|
|
8
|
+
return listenBunHostWebSocket(options)
|
|
9
|
+
}
|
|
10
|
+
const { listenNodeHostWebSocket } = await import('./ws-listener')
|
|
11
|
+
return listenNodeHostWebSocket(options)
|
|
12
|
+
}
|