Import packages/plugin/src/index.ts
This commit is contained in:
parent
e261f11f39
commit
06a6eadd78
|
|
@ -0,0 +1,650 @@
|
|||
import * as DshConnection from '@deepseek-ai/dsh-client-connection'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
// Type-only: pulls the `ctx.settings` Context merge and the rc.1 forms type.
|
||||
import type { SettingsForms } from '@deepseek-ai/dsh-settings'
|
||||
import { ClientModeRuntime, type HostConnectionHandle } from './client-runtime.js'
|
||||
import {
|
||||
Config,
|
||||
entryConfigSchema,
|
||||
resolveConfig,
|
||||
type Config as ConfigShape,
|
||||
type ConfigInput,
|
||||
type EntryConfig,
|
||||
type ResolvedConfig,
|
||||
} from './config.js'
|
||||
import { PluginControlRuntime, type PluginSettingsBinding } from './control-runtime.js'
|
||||
import type { HostWebServerLike } from './control-route.js'
|
||||
import {
|
||||
IdentityStore,
|
||||
prepareDefaultIdentityDirectory,
|
||||
resetDefaultIdentityRoles,
|
||||
serverStorageDirectory,
|
||||
} from './identity-store.js'
|
||||
import { SafeLogger } from './logging.js'
|
||||
import { safeStartupError } from './safe-error.js'
|
||||
import { HostPluginRuntime } from './service.js'
|
||||
import type { ScheduleCreateService } from './harness-remote-bridge.js'
|
||||
import { ClientServerApi } from './server-api.js'
|
||||
import { ServerCredentialStore } from './server-credentials.js'
|
||||
import type { TypertGatewayLike } from './typert-gateway-contract.js'
|
||||
import { subprocessTerminalSpawner, type HostSubprocessLike } from './codex-workspace-bridge.js'
|
||||
import { TypertGatewaySwitch } from './typert-gateway-switch.js'
|
||||
import type { FileViewerHostServiceLike } from './file-viewer-bridge.js'
|
||||
import { createPluginRouteDispatcher, type PluginRouteConnectionLike } from './plugin-route-dispatcher.js'
|
||||
import { installRemoteDiscoveryTools } from './remote-tools.js'
|
||||
import { editableConfig } from './control-runtime.js'
|
||||
import { setLiteModeEnabled } from './lite-mode.js'
|
||||
import { runHmrSafe, type HmrContextLike } from './hmr-safe-settings.js'
|
||||
import { PluginUpdateChecker } from './update-check.js'
|
||||
import { assertRemoteEventSource } from './tui-event-source.js'
|
||||
import {
|
||||
createOwnerPeerFactory,
|
||||
ownerPeerConstructor,
|
||||
type OwnerPeerLike,
|
||||
type OwnerPeerServiceLike,
|
||||
} from './owner-peer.js'
|
||||
|
||||
declare module '@deepseek-ai/cordis' {
|
||||
interface Context {
|
||||
dshRemote: HostPluginRuntime
|
||||
dshRemoteClient: ClientModeRuntime
|
||||
typertGateway: TypertGatewayLike
|
||||
}
|
||||
}
|
||||
|
||||
export const name = 'ds-harness-remote-fast'
|
||||
export { Config }
|
||||
|
||||
// The unscoped dsh-remote package belongs to another publisher. A bare name
|
||||
// cannot establish ownership of a legacy local alias, so leave it unchanged.
|
||||
const legacyLoaderModuleNames = new Set(['@dsh-remote/plugin'])
|
||||
// Settings-registry generation (≤0.1.6). The branded `SettingsNamespace` type
|
||||
// was removed with the registry in rc.1, so the literals stay plain strings.
|
||||
const pluginSettingsNamespace = 'ds-harness-remote'
|
||||
|
||||
/** Fallback entry id when the Loader cannot locate this plugin's entry. */
|
||||
const DEFAULT_ENTRY_ID = 'ds-harness-remote'
|
||||
/** Root include entry id prefixing every profile row's Loader path id. */
|
||||
const INCLUDE_ENTRY_PREFIX = 'include:'
|
||||
|
||||
/**
|
||||
* ≤0.1.6 settings registry seam (removed by DSH 0.1.7-rc.1, DSH-0.1.7-RC1-04).
|
||||
* Kept structural so the plugin can still activate on the registry generation
|
||||
* while `ctx.settings` types only describe the rc.1 `SettingsForms` face.
|
||||
*/
|
||||
interface LegacySettingsScopeLike {
|
||||
get(): ConfigInput
|
||||
replace(section: Config): Promise<unknown>
|
||||
}
|
||||
|
||||
interface LegacySettingsProviderLike {
|
||||
register(ns: string, schema: unknown, options: {
|
||||
base?: ConfigInput
|
||||
applies?: 'live' | 'restart'
|
||||
validate?: (value: ConfigInput) => void
|
||||
}): LegacySettingsScopeLike
|
||||
}
|
||||
|
||||
/** Union of the two settings service generations this plugin must activate on. */
|
||||
type SettingsServiceLike = SettingsForms | LegacySettingsProviderLike
|
||||
|
||||
interface LoaderEntryLike {
|
||||
id: string
|
||||
options: {
|
||||
id: string
|
||||
name?: string
|
||||
disabled?: boolean | null
|
||||
}
|
||||
}
|
||||
|
||||
interface LoaderLike {
|
||||
entries(): Iterable<LoaderEntryLike>
|
||||
locate?(fiber?: unknown): string | undefined
|
||||
update(id: string, options: { disabled?: boolean | null }): unknown
|
||||
}
|
||||
|
||||
interface DshWebServerPortLike {
|
||||
port?: number
|
||||
}
|
||||
|
||||
|
||||
export function apply(ctx: Context, entry: EntryConfig | ConfigShape | undefined = undefined): void {
|
||||
const readConfig = (): ConfigInput => readEntryConfig(entry)
|
||||
const entryId = locateEntryId(ctx)
|
||||
// rc.1 (DSH-0.1.7-RC1-04): the settings-namespace registry is gone. The
|
||||
// plugin declares its editable fields as the entry's volatile Cordis Config
|
||||
// (config.ts) and only records its page policy here (`auto: false` — the
|
||||
// plugin ships its own card); values persist in the active profile's
|
||||
// `cordis.patch.yml` under this entry id.
|
||||
//
|
||||
// Only the rc.1 `SettingsForms` face has `configure`. On the ≤0.1.6 registry
|
||||
// generation `register` owns the page policy (see `activate`), so feature
|
||||
// detection keeps the retired call from throwing during activation.
|
||||
ctx.inject(['settings'], (settingsContext) => {
|
||||
const settings = settingsContext.settings
|
||||
if (isLegacySettingsProvider(settings)) return
|
||||
settingsContext.effect(() => settings.configure({ auto: false }, ctx.fiber))
|
||||
})
|
||||
// The default entry uses the browser/Desktop Host connection service.
|
||||
// The separate dsh-TUI entry starts through applyTuiHost.
|
||||
const activateWhenCarrierReady = async (runtimeContext: Context): Promise<void> => {
|
||||
const gateway = runtimeContext.get('typertGateway') as TypertGatewayLike
|
||||
const connection = runtimeContext.get('connection') as HostConnectionHandle | undefined
|
||||
const webServer = runtimeContext.get('webServer') as HostWebServerLike | undefined
|
||||
let disposePendingControl: (() => Promise<void>) | undefined
|
||||
const installPendingControl = async (): Promise<void> => {
|
||||
if (connection === undefined || disposePendingControl !== undefined) return
|
||||
let identityDirectory = new IdentityStore().directory
|
||||
let storageError: unknown
|
||||
try {
|
||||
identityDirectory = await prepareDefaultIdentityDirectory()
|
||||
} catch (error) {
|
||||
storageError = error
|
||||
}
|
||||
disposePendingControl = runtimeContext.effect(() => {
|
||||
const control = new PluginControlRuntime(
|
||||
resolveConfig(readConfig()),
|
||||
identityDirectory,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
)
|
||||
if (storageError !== undefined) {
|
||||
control.setStartupFailure(storageError, { storageAvailable: false })
|
||||
}
|
||||
return control.register(connection, webServer)
|
||||
}, 'ds-harness-remote pending control')
|
||||
}
|
||||
const startActiveRuntime = async (activeContext: Context): Promise<void> => {
|
||||
await disposePendingControl?.()
|
||||
disposePendingControl = undefined
|
||||
await activate(activeContext, readConfig, entryId)
|
||||
}
|
||||
if (new TypertGatewaySwitch(gateway).supportsCarrier()) {
|
||||
return startActiveRuntime(runtimeContext)
|
||||
}
|
||||
await installPendingControl()
|
||||
}
|
||||
|
||||
ctx.inject(['settings', 'connection', 'typertGateway'], activateWhenCarrierReady)
|
||||
}
|
||||
|
||||
/** Start the shared Host runtime from the separate dsh-TUI package. */
|
||||
export function applyTuiHost(
|
||||
ctx: Context,
|
||||
entry: EntryConfig | ConfigShape | undefined,
|
||||
): void {
|
||||
const readConfig = (): ConfigInput => readEntryConfig(entry)
|
||||
const entryId = locateEntryId(ctx)
|
||||
ctx.inject(['settings', 'typertGateway'], async runtimeContext => {
|
||||
const gateway = runtimeContext.get('typertGateway') as TypertGatewayLike
|
||||
if (!new TypertGatewaySwitch(gateway).supportsCarrier()) {
|
||||
throw new Error('dsh-TUI Remote requires the official Typert Gateway carrier.')
|
||||
}
|
||||
await activate(runtimeContext, readConfig, entryId, true)
|
||||
})
|
||||
}
|
||||
|
||||
async function activate(
|
||||
ctx: Context,
|
||||
readConfig: () => ConfigInput,
|
||||
entryId: string,
|
||||
requireRemoteEvents = false,
|
||||
): Promise<void> {
|
||||
const settings = ctx.get('settings') as SettingsServiceLike | undefined
|
||||
const settingsBinding = await createSettingsBinding(ctx, settings, readConfig, entryId)
|
||||
const connection = ctx.get('connection') as HostConnectionHandle | undefined
|
||||
const webServer = ctx.get('webServer') as HostWebServerLike | undefined
|
||||
// Reads resolve through the binding so the ≤0.1.6 scope's user layer (not the
|
||||
// raw composition seed) is honored; the rc.1 binding reads the live Config.
|
||||
const config: ResolvedConfig = resolveConfig(settingsBinding?.get() ?? readConfig())
|
||||
let defaultIdentityDirectory = new IdentityStore().directory
|
||||
let initialStorageError: unknown
|
||||
try {
|
||||
defaultIdentityDirectory = await prepareDefaultIdentityDirectory()
|
||||
} catch (error) {
|
||||
initialStorageError = error
|
||||
}
|
||||
if (!config.enabled) {
|
||||
if (connection !== undefined) {
|
||||
const controlRuntime = new PluginControlRuntime(
|
||||
config,
|
||||
defaultIdentityDirectory,
|
||||
settingsBinding,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
true,
|
||||
)
|
||||
if (initialStorageError !== undefined) {
|
||||
controlRuntime.setStartupFailure(initialStorageError, { storageAvailable: false })
|
||||
}
|
||||
ctx.effect(() => controlRuntime.register(connection, webServer), 'ds-harness-remote disabled control')
|
||||
}
|
||||
return
|
||||
}
|
||||
// Mirrors SafeLogger output to the process stdout/stderr as well as the DSH
|
||||
// logger: the web process stdout is captured by the Desktop shell into
|
||||
// desktop.log, so remote RPC/transport diagnostics stay greppable there.
|
||||
const logger = new SafeLogger({
|
||||
debug: message => { ctx.logger.debug(message); console.debug(message) },
|
||||
info: message => { ctx.logger.info(message); console.info(message) },
|
||||
warn: message => { ctx.logger.warn(message); console.warn(message) },
|
||||
error: message => { ctx.logger.error(message); console.error(message) },
|
||||
}, () => resolveConfig(settingsBinding?.get() ?? readConfig()).logLevel)
|
||||
// Startup and daily npm dist-tags lookup backing the client update notice.
|
||||
// Lives for the whole activation so Server switches keep its snapshot.
|
||||
const updateChecker = new PluginUpdateChecker(logger)
|
||||
// The official Typert gateway (`typertGateway` from dsh-api-gateway) is the
|
||||
// dispatch path behind `/api/commands/*` on the host. It is an explicit
|
||||
// activation dependency so a peer bridge never silently omits commands.
|
||||
const nativeTypertGateway = ctx.get('typertGateway') as TypertGatewayLike
|
||||
// Only the authenticated ConnectionController callback creates per-connection
|
||||
// owner peers. Never share a browser Peer or accept a principal from the tunnel.
|
||||
const connectionExports = DshConnection as Record<string, unknown>
|
||||
// Harness 0.2.2 dereferences `peer.signal` for forwarded Remote events. Prefer
|
||||
// the official Peer export, but fall back to the Connection Host service when a
|
||||
// build's module shape no longer exposes it, so a local carrier never opens
|
||||
// peerless.
|
||||
const connectionService = ctx.get('connection', false) as OwnerPeerServiceLike | undefined
|
||||
const createOwnerPeer = createOwnerPeerFactory(
|
||||
ctx,
|
||||
ownerPeerConstructor(connectionExports),
|
||||
connectionService,
|
||||
)
|
||||
const hostConnectionPeer = createOwnerPeer()
|
||||
let fallbackPeer: OwnerPeerLike | undefined = hostConnectionPeer
|
||||
// The fallback Peer pairs with the Host connection service when that service
|
||||
// minted it; dispose it with the plugin even when no Remote client connects.
|
||||
ctx.effect(() => () => {
|
||||
const peer = fallbackPeer
|
||||
fallbackPeer = undefined
|
||||
return peer?.dispose?.()
|
||||
}, 'ds-harness-remote fallback owner peer')
|
||||
const hostGateway = new TypertGatewaySwitch(nativeTypertGateway, () => fallbackPeer)
|
||||
const localTypertGateway = hostGateway.local()
|
||||
localTypertGateway.createPeer = () => {
|
||||
const peer = createOwnerPeer()
|
||||
if (peer === undefined) return localTypertGateway
|
||||
return {
|
||||
...hostGateway.local(peer),
|
||||
dispose: async () => {
|
||||
await peer.dispose?.()
|
||||
},
|
||||
}
|
||||
}
|
||||
if (requireRemoteEvents) await assertRemoteEventSource(localTypertGateway)
|
||||
// The Host `subprocess` service owns PTY allocation, containment, and process
|
||||
// termination for remote terminals. Profiles without it fall back to the plain
|
||||
// pipe spawner inside the bridge.
|
||||
const subprocess = ctx.get('subprocess', false) as HostSubprocessLike | undefined
|
||||
// The official reminder service is optional in a Host composition; when it is
|
||||
// absent the bridge reports FEATURE_NOT_SUPPORTED instead of inventing one.
|
||||
// The reminder service is a sibling bundle service; resolve it from the root
|
||||
// when this plugin's own context cannot see it. Absent service = explicit
|
||||
// FEATURE_NOT_SUPPORTED from the bridge, never a fabricated one.
|
||||
const schedule = (ctx.get('schedule', false)
|
||||
?? (ctx.root === undefined ? undefined : ctx.root.get('schedule', false))) as ScheduleCreateService | undefined
|
||||
|
||||
const createRuntimes = (config: ResolvedConfig) => {
|
||||
const hostIdentities = new IdentityStore({
|
||||
directory: config.serverUrl === undefined
|
||||
? defaultIdentityDirectory
|
||||
: serverStorageDirectory(defaultIdentityDirectory, config.serverUrl, 'host'),
|
||||
role: 'host',
|
||||
})
|
||||
const runtime = new HostPluginRuntime(
|
||||
config,
|
||||
hostIdentities,
|
||||
logger,
|
||||
localTypertGateway,
|
||||
() => ctx.get('fileViewerHost') as FileViewerHostServiceLike | undefined,
|
||||
subprocess === undefined ? undefined : subprocessTerminalSpawner(subprocess),
|
||||
peer => createPluginRouteDispatcher(
|
||||
() => ctx.get('connection') as PluginRouteConnectionLike | undefined,
|
||||
() => (ctx.get('webServer') as DshWebServerPortLike | undefined)?.port,
|
||||
peer,
|
||||
),
|
||||
schedule,
|
||||
)
|
||||
|
||||
let clientRuntime: ClientModeRuntime | undefined
|
||||
if (config.serverUrl !== undefined && connection !== undefined) {
|
||||
const clientIdentities = new IdentityStore({
|
||||
directory: serverStorageDirectory(defaultIdentityDirectory, config.serverUrl, 'client'),
|
||||
role: 'client',
|
||||
})
|
||||
clientRuntime = new ClientModeRuntime(
|
||||
config,
|
||||
clientIdentities,
|
||||
new ClientServerApi(config.serverUrl, new ServerCredentialStore(clientIdentities.directory), fetch, config.httpServerAllowlist),
|
||||
nativeTypertGateway,
|
||||
logger,
|
||||
runtime,
|
||||
)
|
||||
}
|
||||
|
||||
return { runtime, clientRuntime }
|
||||
}
|
||||
let runtime: HostPluginRuntime | undefined
|
||||
let clientRuntime: ClientModeRuntime | undefined
|
||||
let hostServiceProvided = false
|
||||
let clientServiceProvided = false
|
||||
let clientActive = false
|
||||
if (initialStorageError === undefined) {
|
||||
;({ runtime, clientRuntime } = createRuntimes(config))
|
||||
}
|
||||
let closed = false
|
||||
let startup: Promise<void> | undefined
|
||||
let replacement: Promise<{ client: ClientModeRuntime | undefined; host: HostPluginRuntime }> | undefined
|
||||
const syncOptionalService = (
|
||||
serviceName: 'dshRemote' | 'dshRemoteClient',
|
||||
value: HostPluginRuntime | ClientModeRuntime,
|
||||
owned: boolean,
|
||||
) => {
|
||||
try {
|
||||
if (serviceName === 'dshRemote') {
|
||||
if (owned) ctx.dshRemote = value as HostPluginRuntime
|
||||
else ctx.provide('dshRemote', value as HostPluginRuntime)
|
||||
} else if (owned) {
|
||||
ctx.dshRemoteClient = value as ClientModeRuntime
|
||||
} else {
|
||||
ctx.provide('dshRemoteClient', value as ClientModeRuntime)
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
logger.warn('failed to provide remote service', {
|
||||
service: serviceName,
|
||||
code: 'SERVICE_PROVIDE_CONFLICT',
|
||||
})
|
||||
return false
|
||||
}
|
||||
}
|
||||
const replaceServer = (next: ResolvedConfig) => {
|
||||
const previousReplacement = replacement
|
||||
const operation = async () => {
|
||||
await startup?.catch(() => undefined)
|
||||
await previousReplacement?.catch(() => undefined)
|
||||
if (closed) throw new Error('Remote plugin is closed')
|
||||
clientActive = false
|
||||
// Stop both authorities before loading identities scoped to another Server.
|
||||
const shutdown = await Promise.allSettled([clientRuntime?.close(), runtime?.close()])
|
||||
const failure = shutdown.find(result => result.status === 'rejected')
|
||||
if (failure?.status === 'rejected') throw failure.reason
|
||||
if (closed) throw new Error('Remote plugin is closed')
|
||||
defaultIdentityDirectory = await prepareDefaultIdentityDirectory()
|
||||
controlRuntime?.setIdentityDirectory(defaultIdentityDirectory)
|
||||
const fresh = createRuntimes(next)
|
||||
try {
|
||||
await fresh.runtime.start()
|
||||
await fresh.clientRuntime?.start()
|
||||
if (closed) throw new Error('Remote plugin is closed')
|
||||
} catch (error) {
|
||||
await Promise.allSettled([fresh.clientRuntime?.close(), fresh.runtime.close()])
|
||||
throw error
|
||||
}
|
||||
runtime = fresh.runtime
|
||||
clientRuntime = fresh.clientRuntime
|
||||
clientActive = clientRuntime !== undefined
|
||||
controlRuntime?.clearStartupFailure()
|
||||
hostServiceProvided = syncOptionalService('dshRemote', runtime, hostServiceProvided)
|
||||
if (clientRuntime !== undefined) {
|
||||
clientServiceProvided = syncOptionalService('dshRemoteClient', clientRuntime, clientServiceProvided)
|
||||
}
|
||||
if (connection !== undefined) updateChecker.start()
|
||||
return { client: clientRuntime, host: runtime }
|
||||
}
|
||||
replacement = operation()
|
||||
return replacement
|
||||
}
|
||||
|
||||
const controlRuntime = connection === undefined
|
||||
? undefined
|
||||
: new PluginControlRuntime(
|
||||
config,
|
||||
defaultIdentityDirectory,
|
||||
settingsBinding,
|
||||
clientRuntime,
|
||||
runtime,
|
||||
replaceServer,
|
||||
updateChecker,
|
||||
true,
|
||||
)
|
||||
if (initialStorageError !== undefined) {
|
||||
controlRuntime?.setStartupFailure(initialStorageError, { storageAvailable: false })
|
||||
}
|
||||
|
||||
if (runtime !== undefined) {
|
||||
hostServiceProvided = syncOptionalService('dshRemote', runtime, hostServiceProvided)
|
||||
}
|
||||
if (clientRuntime !== undefined) {
|
||||
clientServiceProvided = syncOptionalService('dshRemoteClient', clientRuntime, clientServiceProvided)
|
||||
}
|
||||
await disableLegacyLoaderEntries(ctx, logger)
|
||||
await ctx.effect(async () => {
|
||||
const disposeControl = controlRuntime?.register(connection!, webServer)
|
||||
if (initialStorageError !== undefined) {
|
||||
logger.error('Remote plugin startup failed', safeStartupError(initialStorageError))
|
||||
} else {
|
||||
try {
|
||||
startup = (async () => {
|
||||
await runtime!.start()
|
||||
if (clientRuntime !== undefined) {
|
||||
await clientRuntime.start()
|
||||
clientActive = true
|
||||
} else {
|
||||
logger.warn('client remote mode is unavailable', {
|
||||
serverConfigured: config.serverUrl !== undefined,
|
||||
remoteGatewayAvailable: localTypertGateway.supportsCarrier,
|
||||
connectionAvailable: connection !== undefined,
|
||||
})
|
||||
}
|
||||
})()
|
||||
await startup
|
||||
// Only the browser/Desktop connection surfaces the update notice, so a
|
||||
// Host composition without it skips the registry calls.
|
||||
if (connection !== undefined) updateChecker.start()
|
||||
} catch (error) {
|
||||
clientActive = false
|
||||
logger.error('Remote plugin startup failed', safeStartupError(error))
|
||||
controlRuntime?.setStartupFailure(error)
|
||||
await Promise.allSettled([clientRuntime?.close(), runtime?.close()])
|
||||
}
|
||||
}
|
||||
return async () => {
|
||||
closed = true
|
||||
clientActive = false
|
||||
updateChecker.stop()
|
||||
await replacement?.catch(() => undefined)
|
||||
await disposeControl?.()
|
||||
await clientRuntime?.close()
|
||||
await runtime?.close()
|
||||
}
|
||||
}, 'ds-harness-remote lifecycle')
|
||||
if (config.remoteTools?.enabled) {
|
||||
installRemoteDiscoveryTools(ctx, () => closed || !clientActive ? undefined : clientRuntime, settingsBinding === undefined ? undefined : {
|
||||
fastMode: () => resolveConfig(readConfig()).liteMode === true,
|
||||
setFastMode: async (enabled: boolean) => {
|
||||
const current = editableConfig(resolveConfig(readConfig()))
|
||||
await settingsBinding.replace({ ...current, liteMode: enabled })
|
||||
setLiteModeEnabled(enabled)
|
||||
return enabled
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the plugin entry's config. The Loader passes the resolved
|
||||
* {@link EntryConfig} (a live `Volatile` reference); a direct `ctx.plugin()`
|
||||
* caller passes the plain composition object instead.
|
||||
*/
|
||||
function readEntryConfig(entry: EntryConfig | ConfigShape | undefined): ConfigInput {
|
||||
if (entry === undefined) return {}
|
||||
return isEntryConfig(entry) ? entry.get() : entry
|
||||
}
|
||||
|
||||
/** Whether a config value is the Loader's live volatile reference. */
|
||||
function isEntryConfig(value: EntryConfig | ConfigShape): value is EntryConfig {
|
||||
return typeof (value as { get?: unknown }).get === 'function'
|
||||
}
|
||||
|
||||
/** Entry id whose live Config backs this plugin instance's settings writes. */
|
||||
function locateEntryId(ctx: Context): string {
|
||||
const loader = ctx.get('loader') as LoaderLike | undefined
|
||||
// `Entry.id` is the tree path (`include:<row>` for a direct profile row, or
|
||||
// `<include>:<group>:<row>` under a group), while `ctx.settings` and
|
||||
// configEditor address an entry by its own `options.id` (DSH-0.1.7-RC1-04).
|
||||
// Resolve the located path back through the Loader so a bundle-include mount
|
||||
// and a plain insert row both derive the same configurable id.
|
||||
const located = loader?.locate?.(ctx.fiber)
|
||||
if (located === undefined) return DEFAULT_ENTRY_ID
|
||||
if (typeof loader?.entries === 'function') {
|
||||
for (const entry of loader.entries()) {
|
||||
if (entry.id === located) return entry.options.id
|
||||
}
|
||||
}
|
||||
// Fallback for a tree whose entries are not enumerable: the root include's
|
||||
// path component is the only prefix a direct profile row carries.
|
||||
return located.startsWith(INCLUDE_ENTRY_PREFIX) ? located.slice(INCLUDE_ENTRY_PREFIX.length) : located
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the live read/write face for this instance's settings.
|
||||
*
|
||||
* DSH 0.1.7-rc.1 (DSH-0.1.7-RC1-04) replaced the namespace registry with
|
||||
* profile-owned `SettingsForms`: reads come from the entry's live volatile
|
||||
* Config and writes go to `settings.replace(entryId, section)`. The ≤0.1.6
|
||||
* registry generation still exposes `register(ns, Config, …)`, whose scope is
|
||||
* the read/write pair. Feature detection keeps both generations on one binding
|
||||
* seam so `PluginControlRuntime` never branches on the host version.
|
||||
*/
|
||||
async function createSettingsBinding(
|
||||
ctx: Context,
|
||||
settings: SettingsServiceLike | undefined,
|
||||
readConfig: () => ConfigInput,
|
||||
entryId: string,
|
||||
): Promise<PluginSettingsBinding | undefined> {
|
||||
if (settings === undefined) return undefined
|
||||
const hmr = ctx.get('hmr', false) as HmrContextLike | undefined
|
||||
if (!isLegacySettingsProvider(settings)) {
|
||||
return {
|
||||
get: readConfig,
|
||||
replace: section => runHmrSafe<void>(async () => { await settings.replace(entryId, section) }, hmr),
|
||||
}
|
||||
}
|
||||
// `Config` is the volatile variant of the entry schema (the DSH 0.1.7-rc.1+
|
||||
// live entry reference). A registry that still exposes `register()` calls the
|
||||
// schema directly — `schema(mergeLayers(base, user))` — and a volatile schema
|
||||
// resolves to a `{ get }` accessor instead of a plain Config, so the `validate`
|
||||
// step below rejects activation on every host that has this registry
|
||||
// (observed on DSH 0.2.1-rc.3 with `unrecognized key: "get"`).
|
||||
//
|
||||
// That registry also returns `mergeLayers(base, user)` unchanged while no
|
||||
// section is stored (`user === undefined`), so the entry Config never reaches
|
||||
// the schema on a fresh install: `serverUrl`, `loopback.ports` and `acp` all
|
||||
// disappear. Resolve it inside the registered schema instead of merging on
|
||||
// every read, so a stored section — including an explicit reset — keeps the
|
||||
// registry's own precedence.
|
||||
const base = readConfig()
|
||||
const resolveRegistration = (input?: unknown) =>
|
||||
entryConfigSchema((input === undefined ? base : input) as Parameters<typeof entryConfigSchema>[0])
|
||||
const scope = settings.register(pluginSettingsNamespace, resolveRegistration, {
|
||||
base,
|
||||
applies: 'restart',
|
||||
validate: value => { resolveConfig(value) },
|
||||
})
|
||||
return {
|
||||
get: () => scope.get(),
|
||||
replace: section => runHmrSafe<void>(async () => { await scope.replace(section) }, hmr),
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the settings service is the ≤0.1.6 registry generation. */
|
||||
function isLegacySettingsProvider(value: unknown): value is LegacySettingsProviderLike {
|
||||
return typeof value === 'object' && value !== null
|
||||
&& typeof (value as { register?: unknown }).register === 'function'
|
||||
}
|
||||
|
||||
async function disableLegacyLoaderEntries(ctx: Context, logger: SafeLogger): Promise<void> {
|
||||
const loader = ctx.get('loader') as LoaderLike | undefined
|
||||
if (!isLoaderLike(loader)) return
|
||||
|
||||
const currentEntryId = loader.locate?.(ctx.fiber)
|
||||
for (const entry of loader.entries()) {
|
||||
const moduleName = entry.options.name
|
||||
if (moduleName === undefined || !legacyLoaderModuleNames.has(moduleName)) continue
|
||||
if (entry.id === currentEntryId || entry.options.disabled === true) continue
|
||||
|
||||
try {
|
||||
await loader.update(entry.id, { disabled: true })
|
||||
logger.warn('disabled legacy loader entry', { entryId: entry.id, moduleName })
|
||||
} catch {
|
||||
logger.warn('failed to disable legacy loader entry', {
|
||||
entryId: entry.id,
|
||||
moduleName,
|
||||
code: 'LOADER_UPDATE_FAILED',
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isLoaderLike(value: unknown): value is LoaderLike {
|
||||
return typeof value === 'object' && value !== null
|
||||
&& typeof (value as { entries?: unknown }).entries === 'function'
|
||||
&& typeof (value as { update?: unknown }).update === 'function'
|
||||
}
|
||||
|
||||
export type { ResolvedConfig } from './config.js'
|
||||
export { resolveConfig } from './config.js'
|
||||
export { ConnectionController, ConnectionRejectedError } from './connection-controller.js'
|
||||
export type { PeerConnectionContext, RpcRouterFactory } from './connection-controller.js'
|
||||
export {
|
||||
fingerprint,
|
||||
IdentityInvalidError,
|
||||
IdentityStore,
|
||||
prepareDefaultIdentityDirectory,
|
||||
resetDefaultIdentityRoles,
|
||||
} from './identity-store.js'
|
||||
export { serverStorageDirectory } from './identity-store.js'
|
||||
export type { HostIdentity, IdentityErrorCode, RemoteDeviceRole, ResetIdentityOptions, TrustedPeer } from './identity-store.js'
|
||||
export { ClientServerApi, HostServerApi, ServerApiError } from './server-api.js'
|
||||
export { HostServerConnection } from './server-connection.js'
|
||||
export type { WebSocketFactory } from './server-connection.js'
|
||||
export { ServerCredentialStore, ServerCredentialsInvalidError } from './server-credentials.js'
|
||||
export type { ServerCredentials } from './server-credentials.js'
|
||||
export { HOST_CAPABILITIES, RpcError, RpcRouter } from './rpc-router.js'
|
||||
export { HostPluginRuntime } from './service.js'
|
||||
export { ClientModeError, ClientModeRuntime } from './client-runtime.js'
|
||||
export { PluginControlRuntime } from './control-runtime.js'
|
||||
export { ClientSecureTransport } from './client-secure-transport.js'
|
||||
export { HARNESS_REMOTE_ALLOWLIST, HarnessRemoteBridge } from './harness-remote-bridge.js'
|
||||
export { RemoteTypertGateway } from './remote-typert-gateway.js'
|
||||
export { RemoteFileViewerBridge } from './file-viewer-bridge.js'
|
||||
export { CodexRemoteDomain } from './codex/domain.js'
|
||||
export { CodexPeerBridge } from './codex/peer-bridge.js'
|
||||
export { CodexAppServerClient, CodexAppServerError } from './codex/app-server.js'
|
||||
export { CODEX_APP_ALLOWLIST } from './codex/method-policy.js'
|
||||
export { AcpRemoteGateway } from './acp/gateway.js'
|
||||
export { AcpPeerBridge } from './acp/peer-bridge.js'
|
||||
export { CursorAcpClient, CursorAcpError } from './acp/adapters/cursor-process.js'
|
||||
export { ACP_METHOD_ALLOWLIST } from './acp/method-policy.js'
|
||||
export { createRemoteFileContentProvider } from './remote-file-content-provider.js'
|
||||
export { TypertGatewaySwitch } from './typert-gateway-switch.js'
|
||||
export { runCli } from './cli.js'
|
||||
export type { RemoteCliDependencies } from './cli.js'
|
||||
export type {
|
||||
LocalTypertGateway,
|
||||
RemoteTypertGatewayTarget,
|
||||
TypertGatewayLike,
|
||||
TypertGatewayRequest,
|
||||
TypertGatewayWireStreamLike,
|
||||
TypertRpcResult,
|
||||
} from './typert-gateway-contract.js'
|
||||
export type { AuthenticatedPeerChannel } from './types.js'
|
||||
export { AcpGateway } from './acp.js'
|
||||
export type { AcpBackendAdapter } from './acp.js'
|
||||
Loading…
Reference in New Issue