docs: document the OpenCode client migration surfaces (OM-179)

Adds JSDoc comments to the functions this branch adds or changes, so the touched-code docstring coverage clears the review threshold. Comments only; no code, formatting or import changes.
This commit is contained in:
Chris Scott committed 2026-11-05 16:32:43 -05:00
1 parent 64e87ba1ea
commit 6297403a41
41 files changed
+691

No files matched your search

+51
View File
@@ -1134,6 +1134,11 @@ Fork a session, optionally before a specific message. Omit \`beforeMessageId\` t
`
}
/**
* Builds the canonical Assistant `opencode.json` document: the assistant agent as default agent, its
* allowed permissions, and a `primary` agent entry. The result is schema-validated, and an invalid
* result throws rather than returning a config OpenCode would reject.
*/
export function buildAssistantOpenCodeConfig(): OpenCodeConfigInfo {
const permission = buildAssistantAgentPermission()
const config: OpenCodeConfigInfo = {
@@ -1158,6 +1163,12 @@ export function buildAssistantOpenCodeConfig(): OpenCodeConfigInfo {
return config
}
/**
* Creates or repairs the Assistant workspace for `repo`: writes AGENTS.md, the assistant OpenCode
* config, the bundled skills and the default agent file, updating the config under a file lock and
* preserving customized content unless the matching `overwrite*` option is set. Returns the
* resulting status, including warnings for instruction updates it declined to apply.
*/
export async function ensureAssistantMode(
repo: Repo,
options?: AssistantModeInitRequest,
@@ -1352,6 +1363,10 @@ export async function ensureAssistantMode(
}
}
/**
* Parses JSONC config text into a config object, returning `undefined` when the text is malformed or
* its root is not an object.
*/
function parseAssistantOpenCodeConfig(rawContent: string): Record<string, unknown> | undefined {
try {
const parsed = parseJsonc(rawContent)
@@ -1377,12 +1392,21 @@ function resolveV1EntityPath(v2Path: readonly string[]): string[] {
const ASSISTANT_V1_AGENT_PATH = resolveV1EntityPath(['agents'])
const ASSISTANT_V1_PERMISSION_PATH = resolveV1EntityPath(['permissions'])
/**
* Reports whether the config still carries v1 keys, which mark a file that has not been converted to
* the v2 shape yet.
*/
function hasAssistantV1OpenCodeConfig(config: Record<string, unknown>): boolean {
if (readConfigValueAtPath(config, ASSISTANT_V1_PERMISSION_PATH) !== undefined) return true
const v1Agents = readConfigValueAtPath(config, ASSISTANT_V1_AGENT_PATH)
return isRecord(v1Agents) && isRecord(v1Agents[ASSISTANT_DEFAULT_AGENT_NAME])
}
/**
* Reports whether an existing Assistant config lacks what `ensureAssistantMode` requires: the
* assistant as default agent, an enabled agent entry with a valid mode, and no generated persona left
* inline.
*/
function assistantOpenCodeConfigNeedsRepair(config: OpenCodeConfigInfo): boolean {
if (config.default_agent !== ASSISTANT_DEFAULT_AGENT_NAME) return true
const agents = config.agents
@@ -1399,6 +1423,7 @@ function assistantOpenCodeConfigHasGeneratedAgentPersona(config: OpenCodeConfigI
return normalizeAssistantAgent(config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]) !== undefined
}
/** Returns the agent's `mode` when it is `primary` or `all`, otherwise falling back to `primary`. */
function resolveValidAssistantMode(agent: unknown): 'primary' | 'all' {
const mode = (agent as { mode?: unknown } | undefined)?.mode
return mode === 'primary' || mode === 'all' ? mode : 'primary'
@@ -1412,6 +1437,10 @@ function normalizeAssistantAgent(agent: unknown): OpenCodeAgentConfig | undefine
return { mode: resolveValidAssistantMode(agent) }
}
/**
* Rewrites the assistant agent entry to a mode-only value, dropping a generated `system` prompt so it
* comes from the agent markdown file rather than opaque config text.
*/
function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCodeConfigInfo {
const existingAssistantAgent = config.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
@@ -1426,6 +1455,10 @@ function stripGeneratedAssistantAgentPersona(config: OpenCodeConfigInfo): OpenCo
}
}
/**
* Merges an existing Assistant config over a freshly generated one, keeping user settings and extra
* agents while forcing the assistant as default agent and re-enabling its entry.
*/
function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeConfigInfo {
const generated = buildAssistantOpenCodeConfig()
const existingAssistantAgent = existing?.agents?.[ASSISTANT_DEFAULT_AGENT_NAME]
@@ -1448,6 +1481,11 @@ function mergeAssistantOpenCodeConfig(existing?: OpenCodeConfigInfo): OpenCodeCo
}
}
/**
* Lists the v1 paths to delete after a conversion: the assistant agent entry, widened to the whole v1
* `agents` container when that container held nothing else, plus `permissions` when a v2 counterpart
* has just been written.
*/
function buildAssistantV1ConfigRemovalPaths(
config: Record<string, unknown>,
convertedPermissions: unknown,
@@ -1466,6 +1504,10 @@ function buildAssistantV1ConfigRemovalPaths(
return paths
}
/**
* Picks the assistant agent written back to the converted file, preferring OpenCode's converted entry,
* then the agent passed in, then a mode derived from the v1 definition.
*/
function resolveConvertedAssistantAgent(
agent: OpenCodeAgentConfig | undefined,
v1Agent: unknown,
@@ -1473,6 +1515,10 @@ function resolveConvertedAssistantAgent(
return normalizeAssistantAgent(agent) ?? agent ?? { mode: resolveValidAssistantMode(v1Agent) }
}
/**
* Puts the raw `{env:…}` and `{file:…}` references from the original file back into the converted
* assistant agent, returning the agent unchanged when no restored entry can be read.
*/
function restoreAssistantAgentReferences(
agent: OpenCodeAgentConfig,
resolved: OpenCodeConfigInfo,
@@ -1503,6 +1549,11 @@ export async function convertAssistantOpenCodeConfigToV2(api: OpenCodeApi): Prom
}
}
/**
* Converts one Assistant `opencode.json` in place when it still holds v1 keys, writing OpenCode's
* converted agent and permissions while preserving comments. Returns `false` without writing when the
* file is absent, already v2, unreadable by OpenCode, or the rewritten text fails validation.
*/
async function convertAssistantOpenCodeConfigFile(
api: OpenCodeApi,
assistantDir: string,
@@ -101,6 +101,11 @@ function requiresOpenCodeReload(previous: OpenCodeConfigFile | null, next: OpenC
return listChangedTopLevelKeys(previous?.content ?? {}, next.content).length > 0
}
/**
* Replaces substituted values in a merge patch with the `{env:…}` or `{file:…}` references held by
* the raw config, reading the resolved config from the OpenCode server. Returns the patch unchanged
* when it does not name any config entity.
*/
async function keepOpenCodeConfigReferences(
patch: Record<string, unknown>,
snapshot: OpenCodeConfigSnapshot,
@@ -111,6 +116,11 @@ async function keepOpenCodeConfigReferences(
return restoreOpenCodeConfigReferences(patch, resolved as Record<string, unknown>, snapshot.content)
}
/**
* Applies config content or a merge patch under the shared config file lock, saving the previous
* valid config as last-known-good and restoring it if that save fails. OpenCode is reloaded only when
* top-level keys changed, and a failed reload is reported as `restart_pending`.
*/
export async function applyOpenCodeConfigUpdate(
input: ApplyOpenCodeConfigOptions,
): Promise<ApplyOpenCodeConfigResult> {
@@ -30,6 +30,11 @@ export async function readOpenCodeConfigDocuments(
return infoByPath
}
/**
* Merges the OpenCode config documents the server reports for the workspace, keeping only the given
* managed sources. Documents OpenCode did not load are skipped, so the result reflects only values
* the server actually resolved.
*/
export async function readManagedOpenCodeConfig(
api: OpenCodeApi,
sources: ReadonlyArray<ManagedConfigSource>,
@@ -212,6 +212,11 @@ interface ReadOpenCodeConfigPathOptions {
nullAncestorCountsAsFound?: boolean
}
/**
* Resolves a JSON path against parsed config content, walking objects by key and arrays by index.
* Returns whether the path exists plus its value; an absent path yields `found: false`, and
* `nullAncestorCountsAsFound` treats a null intermediate value as terminal instead of missing.
*/
function readOpenCodeConfigPath(
content: Record<string, unknown>,
jsonPath: JSONPath,
@@ -283,6 +288,11 @@ interface MergeOpenCodeConfigValuesOptions {
deleteNullValues?: boolean
}
/**
* Deep-merges `source` into `target` and returns a new object, recursing into plain-object values.
* With `deleteNullValues`, a null source value removes the key and nested nulls are stripped from
* replaced values.
*/
export function mergeOpenCodeConfigValues(
target: Record<string, unknown>,
source: Record<string, unknown>,
@@ -316,11 +326,19 @@ export function withOpenCodeConfigLock<T>(fn: () => Promise<T>): Promise<T> {
return withFileLock(getOpenCodeConfigDirectory(), fn)
}
/**
* Validates parsed config content against the OpenCode config schema and throws
* OpenCodeConfigValidationError carrying the reported issues when it fails.
*/
function assertValidOpenCodeConfig(value: unknown): void {
const result = validateOpenCodeConfig(value)
if (!result.success) throw new OpenCodeConfigValidationError(result.issues)
}
/**
* Parses JSONC config text and validates it against the OpenCode config schema, returning the parsed
* object (empty when parsing fails) with `isValid` and any validation issues instead of throwing.
*/
export function parseOpenCodeConfigContent(rawContent: string): OpenCodeConfigParseResult {
let parsed: unknown
try {
@@ -418,6 +436,11 @@ export async function readOpenCodeConfigSnapshot(): Promise<OpenCodeConfigSnapsh
}
}
/**
* Projects an internal snapshot, which tracks validation per source, onto the API response shape.
* Per-source validation issues are flattened into one list that is omitted when empty, and the file is
* valid only when every source is valid.
*/
function toOpenCodeConfigFile(snapshot: OpenCodeConfigSnapshot): OpenCodeConfigFile {
const validationIssues = snapshot.sources.flatMap((source) => source.validationIssues ?? [])
return {
@@ -458,6 +481,11 @@ export async function writeOpenCodeConfigFile(
return toOpenCodeConfigFile(await readOpenCodeConfigSnapshot())
}
/**
* Computes the JSON-path operations that turn `current` into `next`, recursing into plain objects on
* both sides. Merge mode treats `null` as a deletion and strips null members from merged values,
* replace mode additionally removes keys absent from `next`.
*/
function collectOpenCodeConfigPathOperations(
next: Record<string, unknown>,
current: Record<string, unknown>,
@@ -495,6 +523,11 @@ function collectOpenCodeConfigPathOperations(
return operations
}
/**
* Returns the v1 entity paths a v2 merge patch removes, since OpenCode still reads v1 containers.
* Container-wide removals carry no `container`, while named removals record their v1 container so
* it can be pruned once left empty.
*/
function collectOpenCodeConfigV1EntityRemovals(
patch: Record<string, unknown>,
): OpenCodeConfigV1EntityRemoval[] {
@@ -515,6 +548,10 @@ function collectOpenCodeConfigV1EntityRemovals(
return removals
}
/**
* Returns the offset of the first comma in `rawContent` between `start` and `end`, skipping line
* and block comments, or -1 when none exists or a comment runs past `end`.
*/
function findOpenCodeConfigSeparatorComma(rawContent: string, start: number, end: number): number {
let index = start
while (index < end) {
@@ -536,6 +573,10 @@ function findOpenCodeConfigSeparatorComma(rawContent: string, start: number, end
return -1
}
/**
* Returns the offset just past the line break that follows `offset`, ignoring intervening spaces
* and tabs, or null when the line has more content after them.
*/
function findOpenCodeConfigLineEnd(rawContent: string, offset: number): number | null {
let index = offset
while (index < rawContent.length && (rawContent[index] === ' ' || rawContent[index] === '\t')) {
@@ -546,6 +587,12 @@ function findOpenCodeConfigLineEnd(rawContent: string, offset: number): number |
return null
}
/**
* Builds JSONC text edits that delete the property at `jsonPath` while leaving surrounding comments
* intact. Returns null when the node, its container, or a required separator comma cannot be
* located; a comment between the property and the next member makes the property and the comma be
* removed by separate edits so the comment survives.
*/
function buildOpenCodeConfigCommentPreservingRemovalEdits(
rawContent: string,
jsonPath: JSONPath,
@@ -603,6 +650,10 @@ export function removeOpenCodeConfigProperty(rawContent: string, jsonPath: JSONP
return applyEdits(rawContent, edits)
}
/**
* Returns the distinct containers named by `removals` that remain empty objects in the updated raw
* config text, so they can be pruned. Yields nothing when the parsed root is not an object.
*/
function collectEmptyOpenCodeConfigContainers(
rawContent: string,
removals: OpenCodeConfigV1EntityRemoval[],
@@ -642,6 +693,10 @@ export function applyOpenCodeConfigEdits(
return text
}
/**
* Throws OpenCodeConfigShadowedRemovalError when a planned removal targets a path the target source
* does not define but another config source does, listing the shadowed paths and their sources.
*/
function assertNoShadowedOpenCodeConfigRemovals(
operations: OpenCodeConfigPathOperation[],
targetSource: OpenCodeConfigSourceFile | undefined,
@@ -668,6 +723,11 @@ function assertNoShadowedOpenCodeConfigRemovals(
}
}
/**
* Writes new config text, or applies object content/patch, to the requested source or the preferred
* writable one. Enforces `expectedRevision`, rejects redacted values and invalid sibling sources,
* preserves JSONC comments and formatting, and returns the refreshed config snapshot.
*/
export async function updateOpenCodeConfigFile(
content: Record<string, unknown> | string,
options: UpdateOpenCodeConfigOptions = {},
@@ -874,6 +934,12 @@ async function applyOpenCodeConfigSourceFileStates(
}
}
/**
* Restores the config source files from a serialized snapshot: sources present in the snapshot are
* written, sources absent from it but currently on disk are removed, and the legacy config.json source
* is folded afterwards. All writes roll back together on failure, and the refreshed file view is
* returned, or null when no sources remain.
*/
export async function restoreOpenCodeConfigSnapshot(snapshot: string): Promise<OpenCodeConfigFile | null> {
const desired = parseOpenCodeConfigSnapshot(snapshot)
const current = await readOpenCodeConfigSnapshot()
@@ -906,6 +972,11 @@ async function archiveLegacyConfigJsonSource(rawContent: string): Promise<string
return archivePath
}
/**
* Migrates a legacy `config.json` into the lowest-precedence config source, archiving the original
* first and deleting it only after a successful merge. Returns false when the legacy file is missing
* or cannot be folded.
*/
export async function foldLegacyConfigJsonSource(): Promise<boolean> {
const legacyPath = getOpenCodeConfigSourcePath(LEGACY_OPENCODE_CONFIG_SOURCE_NAME)
@@ -53,6 +53,10 @@ function isSecretKey(key: string): boolean {
return SECRET_KEYS.has(normalizeSecretKey(key))
}
/**
* Reports whether a config path points at a map of user-chosen names (`providers`, `agents`,
* `commands`, `mcp.servers`), so its keys are treated as names rather than secret keys.
*/
function keysAreNames(path: string[]): boolean {
const [head] = path
if (head === 'providers') {
@@ -81,6 +85,10 @@ function redactOpaqueValue(value: unknown, path: string[], redactedPaths: string
)
}
/**
* Recursively copies a config value with secret-named strings and the contents of `headers` and
* `environment` replaced by the redaction placeholder, appending each redacted path to `redactedPaths`.
*/
function redactValue(value: unknown, path: string[], redactedPaths: string[]): unknown {
if (Array.isArray(value)) {
return value.map((item, index) => redactValue(item, [...path, String(index)], redactedPaths))
@@ -44,10 +44,15 @@ export function readConfigValueAtPath(value: unknown, path: readonly string[]):
return current
}
/** Whether `path` begins with every segment of `prefix`, used to match field-alias prefixes. */
function startsWithPath(path: readonly string[], prefix: readonly string[]): boolean {
return prefix.length <= path.length && prefix.every((segment, index) => path[index] === segment)
}
/**
* Finds the raw `{env:…}` or `{file:…}` reference stored for `path` in any candidate entity,
* also checking each alias-mapped path. Returns undefined when no candidate holds a reference there.
*/
function readRawReference(candidates: readonly RawEntityCandidate[], path: readonly string[]): string | undefined {
for (const candidate of candidates) {
const paths = [
@@ -64,6 +69,11 @@ function readRawReference(candidates: readonly RawEntityCandidate[], path: reado
return undefined
}
/**
* Walks a patch value and swaps each string that still equals its resolved counterpart for the raw
* config reference at the same path. Returns a new value; edited strings and strings without a
* stored reference are kept as given.
*/
function restoreEntityReferences(
next: unknown,
path: readonly string[],
@@ -85,6 +95,10 @@ function restoreEntityReferences(
return next
}
/**
* Returns the single entity name the patch removes but the resolved container still contains, or
* undefined when the patch removes zero or several names.
*/
function findRenameSource(
patchContainer: Record<string, unknown>,
resolvedContainer: Record<string, unknown>,
@@ -95,6 +109,11 @@ function findRenameSource(
return removed.length === 1 ? removed[0] : undefined
}
/**
* Restores references for every named entity in a patch container, resolving the source entity from
* the resolved container or from a single rename within the same patch. Returns the patch container
* unchanged when the resolved container is not an object.
*/
function restoreContainerReferences(
mapping: OpenCodeConfigV1EntityPath,
patchContainer: Record<string, unknown>,
@@ -126,6 +145,10 @@ function restoreContainerReferences(
)
}
/**
* Returns a copy of `target` with `value` written at `path`, creating intermediate plain objects
* where they are missing. An empty path returns `target` itself.
*/
function setValueAtPath(target: Record<string, unknown>, path: readonly string[], value: unknown): Record<string, unknown> {
const [head, ...rest] = path
if (head === undefined) return target
@@ -105,6 +105,11 @@ export function applySessionActivity(busySessions: Set<string>, event: V2Event):
}
}
/**
* Returns a builder that stamps each replayed permission, form or session-status event with the
* current time and a monotonically increasing `${idPrefix}${count}` id, so replayed events stay
* ordered and distinct from live ones.
*/
export function createReplayEventBuilder(idPrefix: string): ReplayEventBuilder {
let count = 0
return (...args) => {
@@ -52,6 +52,9 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption
let delayTimer: ReturnType<typeof setTimeout> | null = null
let resolveDelay: (() => void) | null = null
/**
* Clears the watchdog and aborts the in-flight attempt so its stream iterator ends.
*/
const stopAttempt = (): void => {
const attempt = currentAttempt
currentAttempt = null
@@ -63,6 +66,10 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption
attempt.controller.abort()
}
/**
* Cancels a pending reconnect wait and resolves it at once, letting the loop observe that it has
* been closed or superseded.
*/
const stopDelay = (): void => {
if (delayTimer) {
clearTimeout(delayTimer)
@@ -82,6 +89,11 @@ export function subscribeOpenCodeEvents(options: OpenCodeEventSubscriptionOption
}, delayMs)
})
/**
* Runs the reconnect loop for one loop token, opening a fresh attempt per iteration, aborting it
* when the stall watchdog fires, and waiting a doubling backoff before retrying. Returns once the
* subscription is closed or `token` is superseded by a newer loop.
*/
const run = async (token: number): Promise<void> => {
while (!closed && token === loopToken) {
const attempt: SubscriptionAttempt = { controller: new AbortController(), watchdog: null }
@@ -1037,6 +1037,10 @@ class OpenCodeServerManager {
return this.sandboxEnforced
}
/**
* Sets the lifecycle gate and, when it transitions from closed to open, notifies the registered
* listeners that the proxy is now serving requests. Listener failures are logged, not propagated.
*/
setLifecycleInitialized(initialized: boolean): void {
const opened = initialized && !this.lifecycleInitialized
this.lifecycleInitialized = initialized
+4
View File
@@ -64,6 +64,10 @@ export class FetchOpenCodeClient implements OpenCodeClient {
return this.fetchFn(input, { ...init, headers })
}
/**
* Proxies a raw request to the OpenCode server, dropping the `/api/opencode` prefix and applying the
* directory header and basic auth. Upstream failures become a `502` JSON response instead of a throw.
*/
async forwardRaw(request: Request): Promise<Response> {
const url = new URL(request.url)
const path = url.pathname.replace(/^\/api\/opencode/, '') + url.search
@@ -155,6 +155,10 @@ export class RemoteServerEventHub {
return false
}
/**
* Delivers already-built replay events to one client through the aggregator, which drops them unless
* the client still subscribes to that server and directory.
*/
private emitReplayEventsToClient(
clientId: string,
serverId: string,
@@ -181,6 +185,11 @@ export class RemoteServerEventHub {
}
}
/**
* Replaces the server's event subscription with a fresh one, recording a stream error instead when the
* registry cannot provide a connection. Does nothing until the hub has started, so stale callbacks from
* the prior subscription are ignored rather than applied.
*/
private connectServer(serverId: string): void {
if (!this.started) return
this.closeStream(serverId)
@@ -210,6 +219,10 @@ export class RemoteServerEventHub {
logger.info(`Remote event stream connecting: ${serverId}`)
}
/**
* Marks the server's stream connected, announces it to the aggregator, and starts version probing
* and session status replay. A callback from a superseded subscription is ignored.
*/
private handleOpen(serverId: string, subscription: OpenCodeEventSubscription): void {
const stream = this.streams.get(serverId)
if (!stream || stream.subscription !== subscription) return
@@ -223,6 +236,10 @@ export class RemoteServerEventHub {
void this.replaySessionStatuses(serverId, subscription)
}
/**
* Records a disconnect on the server's stream and clears its connected flag, leaving the
* subscription itself to keep reconnecting.
*/
private handleStreamError(serverId: string, error: unknown): void {
const stream = this.streams.get(serverId)
if (!stream) return
@@ -232,6 +249,10 @@ export class RemoteServerEventHub {
logger.warn(`Remote event stream error for ${serverId}: ${stream.error}`)
}
/**
* Routes one upstream event to the aggregator while maintaining the hub's per-stream bookkeeping:
* busy-session activity, subagent session ids, and the directory the event resolves to.
*/
private handleMessage(serverId: string, event: V2Event): void {
const stream = this.streams.get(serverId)
if (!stream) return
@@ -249,6 +270,11 @@ export class RemoteServerEventHub {
this.aggregator.deliverRemoteEnvelope(serverId, resolvedDirectory ?? null, event)
}
/**
* Keeps streams aligned with the server registry: deleted, unreadable, or disabled servers have their
* stream forgotten, while added and updated servers get their cached version state cleared and are
* reconnected.
*/
private handleRegistryChange(change: OpenCodeServerChange): void {
if (!this.started) return
@@ -280,6 +306,10 @@ export class RemoteServerEventHub {
this.connectServer(change.serverId)
}
/**
* Reports whether the subscription still owns the server's live stream, so async work started under
* it does not act on a stream that has since been replaced or disconnected.
*/
private isStreamCurrent(
serverId: string,
stream: RemoteServerStream,
@@ -288,6 +318,11 @@ export class RemoteServerEventHub {
return this.streams.get(serverId) === stream && stream.subscription === subscription && stream.connected
}
/**
* Re-emits idle and busy status events for the server's active sessions after a reconnect, so
* clients that missed updates while disconnected resync. Stops quietly at any await once the stream
* is no longer current.
*/
private async replaySessionStatuses(serverId: string, subscription: OpenCodeEventSubscription): Promise<void> {
const stream = this.streams.get(serverId)
if (!stream || !this.isStreamCurrent(serverId, stream, subscription)) return
@@ -336,6 +371,11 @@ export class RemoteServerEventHub {
}
}
/**
* Looks up the working directory of active sessions the stream has not mapped yet, caching each result
* in `sessionDirectories`. Sessions are fetched concurrently and left unresolved when their lookup
* fails, so replay proceeds with whatever directories are known.
*/
private async resolveActiveSessionDirectories(
api: OpenCodeApi,
serverId: string,
@@ -356,6 +396,11 @@ export class RemoteServerEventHub {
}))
}
/**
* Probes the server's OpenCode version, skipping when a probe is already pending or the version is
* known. Results are applied only when the probe token still matches the current stream, and a failed
* probe reopens the request flag so a later reconnect can retry it.
*/
private async refreshVersion(serverId: string): Promise<void> {
const stream = this.streams.get(serverId)
if (!stream || stream.versionRequested) return
@@ -382,6 +427,10 @@ export class RemoteServerEventHub {
current.versionRequested = false
}
/**
* Returns the server's stream bookkeeping record, creating an empty one on first use so callers can
* record state before a subscription exists.
*/
private ensureStream(serverId: string): RemoteServerStream {
const existing = this.streams.get(serverId)
if (existing) return existing
@@ -407,6 +456,9 @@ export class RemoteServerEventHub {
stream.error = error
}
/**
* Closes the stream's subscription and clears the handle, keeping the stream entry itself.
*/
private closeSubscription(stream: RemoteServerStream): void {
if (!stream.subscription) return
stream.subscription.close()
+97
View File
@@ -99,12 +99,20 @@ class SSEAggregator {
this.broadcastResync()
}
/**
* Forces the upstream event subscription to reconnect, used after credentials change. No-op while the
* aggregator is not started.
*/
reconnect(): void {
if (!this.started) return
logger.info('SSE forcing upstream reconnect (auth changed)')
this.subscription?.reconnect()
}
/**
* Returns the process-wide aggregator, creating it on first call. All events and client registrations
* flow through this single instance.
*/
static getInstance(): SSEAggregator {
if (!SSEAggregator.instance) {
SSEAggregator.instance = new SSEAggregator()
@@ -112,6 +120,10 @@ class SSEAggregator {
return SSEAggregator.instance
}
/**
* Subscribes to local OpenCode events once per process, wiring the open, event, and disconnect handlers.
* Without a registered OpenCode client it logs a warning and stays stopped.
*/
start(): void {
if (this.started) return
const client = this.openCodeClient
@@ -253,6 +265,10 @@ class SSEAggregator {
}
}
/**
* Runs the remote replay handler for one server directory, catching and logging failures so that a
* directory that cannot replay does not reject the caller.
*/
private async replayRemoteDirectory(
clientId: string,
serverId: string,
@@ -266,6 +282,10 @@ class SSEAggregator {
}
}
/**
* Replays pending permission and form events for each of the client's directories, settling every
* directory independently so one failed lookup does not block the rest.
*/
private async replayPendingActionsForClient(clientId: string, directories: string[]): Promise<void> {
const client = this.openCodeClient
if (!client) return
@@ -292,6 +312,10 @@ class SSEAggregator {
this.emitReplayEventsToClient(clientId, directory, events.forms)
}
/**
* Writes replayed events to a client only while it is still registered and subscribed to the directory;
* delivery stops at the first write error, leaving the remaining events unsent.
*/
private emitReplayEventsToClient(clientId: string, directory: string, events: V2Event[]): void {
if (events.length === 0) return
@@ -310,6 +334,11 @@ class SSEAggregator {
logger.info(`replay: sent ${events.length} pending action(s) for ${directory} to client ${clientId}`)
}
/**
* Re-emits idle and busy status events for sessions the aggregator already tracks, so clients recover
* transitions missed while disconnected. Busy sessions with an unknown directory are resolved through
* the API and skipped when that lookup fails.
*/
private async replaySessionStatusesForTrackedDirectories(): Promise<void> {
const client = this.openCodeClient
if (!client) return
@@ -348,6 +377,10 @@ class SSEAggregator {
}
}
/**
* Collects every session currently active or scheduled, keyed by session id, and records the owning
* directory for each so a later replay can address it.
*/
private getTrackedSessions(): Map<string, string> {
const tracked = new Map<string, string>()
this.activeSessions.forEach((sessionIDs, directory) => {
@@ -360,6 +393,10 @@ class SSEAggregator {
return tracked
}
/**
* Resolves a session's directory through the API and caches it for later event routing, returning
* `null` and logging a warning when the lookup fails.
*/
private async resolveSessionDirectory(client: Pick<OpenCodeClient, 'api'>, sessionID: string): Promise<string | null> {
try {
const session = await client.api.session.get({ sessionID })
@@ -371,6 +408,11 @@ class SSEAggregator {
}
}
/**
* Handles a (re)connected upstream stream: broadcasts a resync, or defers it as pending while the resync
* gate is closed, and replays tracked session statuses only on a reconnection rather than the first
* connect.
*/
private handleUpstreamOpen(wasConnectedBefore: boolean): void {
logger.info('SSE global stream connected')
this.upstreamConnected = true
@@ -386,6 +428,10 @@ class SSEAggregator {
}
}
/**
* Announces a fresh upstream connection to the connected-listeners and to clients subscribed to the
* local OpenCode server, isolating any listener that throws.
*/
private notifyUpstreamConnected(): void {
this.upstreamConnectedListeners.forEach(listener => {
try { listener() } catch { /* ignore listener errors */ }
@@ -417,12 +463,20 @@ class SSEAggregator {
return () => { this.serverConnectedListeners.delete(listener) }
}
/**
* Fans an event out to every server-event listener, isolating each listener so a throwing one cannot
* block the others or the dispatch caller.
*/
notifyServerEvent(serverId: string, directory: string | null, event: SSEEvent): void {
this.serverEventListeners.forEach(listener => {
try { listener(serverId, directory, event) } catch { /* ignore listener errors */ }
})
}
/**
* Notifies server-connected listeners that a server's stream is available, swallowing per-listener
* errors so one failure does not interrupt the notification of the rest.
*/
notifyServerConnected(serverId: string): void {
this.serverConnectedListeners.forEach(listener => {
try { listener(serverId) } catch { /* ignore listener errors */ }
@@ -433,6 +487,11 @@ class SSEAggregator {
this.remoteSubagentResolver = resolver
}
/**
* Dispatches one local upstream event: directory-scoped events go to that directory's subscribers,
* catalog updates go to every client, and events without a resolvable directory go to all listeners
* unscoped.
*/
private handleUpstreamEvent(event: V2Event): void {
const { directory, resolvedDirectory } = routeOpenCodeEvent(event, this.sessionDirectories)
@@ -454,6 +513,10 @@ class SSEAggregator {
this.writeEnvelopeToClients(this.clients.keys(), null, event)
}
/**
* Delivers an event to listeners and to the clients subscribed to its directory, writing no client
* frames when no client watches that directory.
*/
private deliverEvent(directory: string, event: SSEEvent): void {
this.notifyEvent(directory, event)
@@ -473,6 +536,10 @@ class SSEAggregator {
this.notifyListeners(directory, event)
}
/**
* Fans an event out to local listeners with its directory scope and reports it as a local-server event,
* swallowing individual listener failures.
*/
private notifyListeners(directory: string | null, event: SSEEvent): void {
this.eventListeners.forEach(listener => {
try { listener(directory, event) } catch { /* ignore listener errors */ }
@@ -495,6 +562,10 @@ class SSEAggregator {
}
}
/**
* Writes one already-encoded frame to a client, logging the labeled error instead of propagating a
* failure so one broken connection cannot interrupt a broadcast.
*/
private writeFrame(client: SSEClient, frame: Uint8Array, errorLabel: string): void {
try {
client.writeFrame(frame)
@@ -511,6 +582,10 @@ class SSEAggregator {
this.writeEnvelopeToClients(this.clients.keys(), directory, event, serverId)
}
/**
* Sends a remote server event to a single client, but only when that client is subscribed to the
* server and directory the event belongs to.
*/
deliverRemoteEnvelopeToClient(clientId: string, serverId: string, directory: string, event: SSEEvent): void {
if (!this.hasClientDirectory(clientId, buildServerDirectoryKey(serverId, directory))) return
const client = this.clients.get(clientId)
@@ -530,6 +605,10 @@ class SSEAggregator {
}
}
/**
* Collects the IDs of clients subscribed to at least one directory of the given server, each client
* listed once regardless of how many of its directories match.
*/
private clientIdsForServer(serverId: string): string[] {
const clientIds: string[] = []
for (const client of this.clients.values()) {
@@ -543,6 +622,11 @@ class SSEAggregator {
return clientIds
}
/**
* Updates active-session and subagent bookkeeping from local events before any listener sees them, so
* status queries reflect the event being dispatched: status and execution events move sessions between
* active and idle, deleted sessions are dropped, and sessions with a parent are marked as subagents.
*/
private handleEvent(directory: string, event: SSEEvent): void {
switch (event.type) {
case 'session.status': {
@@ -612,6 +696,10 @@ class SSEAggregator {
logger.info(`Session active: ${sessionID} in ${directory} (${sessions.size} active)`)
}
/**
* Drops a session from the active set of its directory, forgetting the directory once it has no
* active sessions left.
*/
private markSessionIdle(directory: string, sessionID: string): void {
const sessions = this.activeSessions.get(directory)
if (sessions) {
@@ -633,6 +721,11 @@ class SSEAggregator {
return this.clients.size
}
/**
* Records whether a client is in the foreground and which session and server it is viewing, clearing
* both view fields when it is not visible and defaulting the server to the local one. Returns false
* when the client is unknown, leaving stored visibility untouched.
*/
setClientVisibility(
id: string,
visible: boolean,
@@ -675,6 +768,10 @@ class SSEAggregator {
return new Set(this.getScheduledSessions().map(ref => ref.sessionID))
}
/**
* Reads scheduled session references from the resolver installed by the scheduler, yielding an empty
* list when no resolver is set.
*/
private getScheduledSessions(): ScheduledSessionRef[] {
return this.scheduledSessionsResolver?.() ?? []
}