Import packages/plugin/src/service.ts

This commit is contained in:
QQ 2026-11-17 08:48:45 +08:00
parent 9c89ae899f
commit 60927632df
1 changed files with 100 additions and 10 deletions

View File

@ -1,10 +1,11 @@
import { LanUploadHost } from './lan-upload.js'
import { HostPairing } from './host-pairing.js'
import type { HostPairingView } from './pairing-contract.js'
import { WorkspaceUploadHost } from './workspace-upload.js'
import { workspaceUploadRootResolver } from './workspace-upload-authority.js'
import { LoopbackHost } from './loopback-host.js'
import { TerminalPolicy } from './terminal-policy.js'
import { createEvent, type RemoteWorkspaceTypeDescription } from '@dsh-remote/protocol'
import { createEvent, REMOTE_SESSION_EVENTS_CAPABILITY, type RemoteWorkspaceTypeDescription } from '@dsh-remote/protocol'
import { setLiteModeEnabled } from './lite-mode.js'
import { setForceRelayEnabled } from './relay-preference.js'
import { ConnectionController } from './connection-controller.js'
@ -12,6 +13,7 @@ import type { ResolvedConfig } from './config.js'
import type { HostIdentity, IdentityStore } from './identity-store.js'
import {
harnessSessionGeneration,
isLiveSessionEventsHarnessVersion,
readHarnessDistributionVersion,
} from './harness-version.js'
import type { SafeLogger } from './logging.js'
@ -28,7 +30,8 @@ import {
} from './server-api.js'
import { HostServerConnection } from './server-connection.js'
import { ServerCredentialStore } from './server-credentials.js'
import { HarnessRemoteBridge, type ScheduleCreateService } from './harness-remote-bridge.js'
import { dispatchCommandForHost, HarnessRemoteBridge, type ScheduleCreateService } from './harness-remote-bridge.js'
import { readCompactionConfirmation, RemoteCompactionOperations } from './remote-compaction-operations.js'
import type { PluginRouteDispatcher } from './plugin-route-bridge.js'
import { PluginRouteBridge } from './plugin-route-bridge.js'
import type { LocalTypertGateway } from './typert-gateway-contract.js'
@ -81,6 +84,11 @@ export class HostPluginRuntime {
private readonly codex: CodexRemoteDomain
private readonly acp: AcpRemoteGateway
private readonly codexWorkspaceState = new CodexWorkspaceState(key => TerminalPolicy.releaseOwner(this.terminalOwners, key))
/**
* Host-wide async compaction registry. It deliberately lives on the runtime,
* not on a connection: disconnecting a client must not abort a compaction.
*/
private readonly compactionOperations: RemoteCompactionOperations
private localCodexPeer?: CodexPeerBridge
private localCodexPublish: PublishCodexFrame = async () => undefined
private localAcpPeer?: AcpPeerBridge
@ -105,8 +113,44 @@ export class HostPluginRuntime {
this.loopbackPorts = [...config.loopback.ports]
this.codex = new CodexRemoteDomain(config.codex, logger)
this.acp = new AcpRemoteGateway(config.acp ?? { enabled: false, backends: [] }, logger, undefined, undefined, () => this.terminalEnabled, this.terminalSpawner)
// Each operation runs on its own owner Peer minted from the Host gateway,
// so its lifetime is independent of the client connection that submitted it.
this.compactionOperations = new RemoteCompactionOperations(async (sessionId, signal) => {
const gateway = this.localGateway?.createPeer?.() ?? this.localGateway
if (gateway === undefined) throw new RpcError('HARNESS_UNAVAILABLE', 'The Host Harness gateway is unavailable.')
try {
return await dispatchCommandForHost(
gateway,
{ args: { agentId: sessionId, line: '/compact' } },
signal,
this.harnessVersion,
)
} finally {
await gateway.dispose?.()
}
}, {
logger,
// `commands/execute` stops waiting on abort while the compaction handler
// keeps running, so lifecycle confirmation comes from the Session log.
confirm: async (sessionId, acceptedAt, commandId) => {
const gateway = this.localGateway?.createPeer?.() ?? this.localGateway
if (gateway === undefined) return { kind: 'unknown' }
try {
const result = await gateway.dispatch('session/events', {
args: { request: { address: { kind: 'session', sessionId }, maxMessages: 128 } },
}, AbortSignal.timeout(5_000))
return readCompactionConfirmation(result, acceptedAt, commandId)
} catch {
return { kind: 'unknown' }
} finally {
await gateway.dispose?.()
}
},
})
this.connections = new ConnectionController(this.identities, (context, send) => {
const peerGateway = this.localGateway?.createPeer?.() ?? this.localGateway
const uploadDispatcher = this.pluginRoutes?.(peerGateway?.peer)
const uploadBridge = uploadDispatcher === undefined ? undefined : new PluginRouteBridge(uploadDispatcher, this.logger)
const harnessRemote = peerGateway?.supportsCarrier === true
? new HarnessRemoteBridge(
peerGateway,
@ -127,6 +171,7 @@ export class HostPluginRuntime {
sessionId => this.acp.resolveUploadWorkspace(context.connectionId, sessionId),
),
this.schedule,
uploadBridge === undefined ? undefined : body => uploadBridge.call({ route: 'api/session/uploadFileBinary', body }, true),
)
: undefined
const fileViewer = new RemoteFileViewerBridge(
@ -146,6 +191,16 @@ export class HostPluginRuntime {
// plugin is activated.
const dispatcher = this.pluginRoutes?.(peerGateway?.peer)
const pluginRoute = dispatcher === undefined ? undefined : new PluginRouteBridge(dispatcher, this.logger)
const workspaceUpload = new WorkspaceUploadHost(workspaceUploadRootResolver(
peerGateway,
() => harnessSessionGeneration(this.harnessVersion) === 'v3',
threadId => this.codex.resolveThreadWorkspace(context.connectionId, threadId),
sessionId => this.acp.resolveUploadWorkspace(context.connectionId, sessionId),
), undefined, context.transportMode)
const lanUpload = context.peerIdentityKey && context.transportMode ? new LanUploadHost(workspaceUpload, {
connectionId: context.connectionId, peerIdentityKey: context.peerIdentityKey,
identity: () => this.currentIdentity(), mode: context.transportMode,
}) : undefined
return new RpcRouter(
undefined,
this.logger,
@ -158,12 +213,13 @@ export class HostPluginRuntime {
this.createLoopbackHost(),
() => this.hostWorkspaceTypes(),
pluginRoute,
new WorkspaceUploadHost(workspaceUploadRootResolver(
peerGateway,
() => harnessSessionGeneration(this.harnessVersion) === 'v3',
threadId => this.codex.resolveThreadWorkspace(context.connectionId, threadId),
sessionId => this.acp.resolveUploadWorkspace(context.connectionId, sessionId),
), undefined, context.transportMode),
workspaceUpload,
{
operations: this.compactionOperations,
owner: { deviceId: context.peerDeviceId, connectionId: context.connectionId },
},
lanUpload,
context.createTransportUpgradeHost?.(send),
)
}, this.logger)
if (config.serverUrl !== undefined) {
@ -470,6 +526,7 @@ export class HostPluginRuntime {
this.pairing?.close()
this.serverApi?.close()
await this.serverConnection?.stop()
this.compactionOperations.closeAll()
await this.connections.close()
await this.localCodexPeer?.closeAll()
this.localCodexPeer = undefined
@ -554,11 +611,22 @@ export class HostPluginRuntime {
if (gateway?.supportsCarrier !== true) return capabilities
let result: Awaited<ReturnType<LocalTypertGateway['dispatch']>>
try {
result = await gateway.dispatch('session/list', { args: { _request: {} } }, AbortSignal.timeout(5_000))
// The Gateway resolves the endpoint before rejecting unknown arguments, and
// rejects them before invoking the Session handler. Never enumerate persisted
// sessions during capability discovery: cold history can take minutes to read.
result = await gateway.dispatch('session/list', { args: { __remoteCapabilityProbe: true } }, AbortSignal.timeout(5_000))
} catch {
throw new RpcError('CONNECTION_FAILED', 'Cannot verify the Host Session API.', undefined, true)
}
if (result.ok) return capabilities
if (!result.ok && result.error.code === 'gateway/arguments-invalid') {
if (isLiveSessionEventsHarnessVersion(this.harnessVersion) && await this.probeLiveSessionEvents(gateway)) {
capabilities.push(REMOTE_SESSION_EVENTS_CAPABILITY)
}
return capabilities
}
if (result.ok) {
throw new RpcError('CONNECTION_FAILED', 'The Host Gateway did not reject the Session API probe.', undefined, true)
}
if (result.error.code === 'gateway/service-unavailable') {
throw new RpcError('CONNECTION_FAILED', 'The Host Session API is not ready.', undefined, true)
}
@ -572,6 +640,28 @@ export class HostPluginRuntime {
return capabilities.filter(value => !value.startsWith('harness.remote.') && value !== 'harness.terminal.v1')
}
private async probeLiveSessionEvents(gateway: LocalTypertGateway): Promise<boolean> {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 2_000)
let iterator: AsyncIterator<unknown> | undefined
try {
const stream = await gateway.open('$events', { args: {} }, controller.signal)
iterator = stream[Symbol.asyncIterator]()
const first = await iterator.next()
return !first.done
&& typeof first.value === 'object'
&& first.value !== null
&& !Array.isArray(first.value)
&& (first.value as { type?: unknown }).type === 'ready'
} catch {
return false
} finally {
clearTimeout(timeout)
controller.abort()
await iterator?.return?.().catch(() => undefined)
}
}
private hostWorkspaceTypes(): RemoteWorkspaceTypeDescription[] {
const types: RemoteWorkspaceTypeDescription[] = []
if (this.codex.isAvailable()) {