@hediet/linkrpc-cli 0.0.3-next.20261024.1 → 0.0.3-next.20261025.2
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 +1 -1
- package/dist/chunks/{cli-CXAAnZDA.js → cli-BZ-4lHyj.js} +46 -18
- package/dist/chunks/{cli-CXAAnZDA.js.map → cli-BZ-4lHyj.js.map} +1 -1
- package/dist/chunks/{runApprovalUi-BdPp7WNP.js → runApprovalUi-DTSdmhod.js} +3 -3
- package/dist/chunks/{runApprovalUi-BdPp7WNP.js.map → runApprovalUi-DTSdmhod.js.map} +1 -1
- package/dist/chunks/{runComplete-M-eKaNkI.js → runComplete-1DjMsU_0.js} +66 -39
- package/dist/chunks/runComplete-1DjMsU_0.js.map +1 -0
- package/dist/chunks/{runUi-Deeox_Ef.js → runUi-C8VfjCWT.js} +4 -4
- package/dist/chunks/{runUi-Deeox_Ef.js.map → runUi-C8VfjCWT.js.map} +1 -1
- package/dist/chunks/{scroll-CYhlBDSN.js → scroll-UHQjKgoj.js} +2 -2
- package/dist/chunks/{scroll-CYhlBDSN.js.map → scroll-UHQjKgoj.js.map} +1 -1
- package/dist/chunks/{src-yrqRWXzG.js → src-DPg65Jd1.js} +2 -2
- package/dist/chunks/{src-yrqRWXzG.js.map → src-DPg65Jd1.js.map} +1 -1
- package/dist/hub.js +1 -1
- package/dist/index.js +1 -1
- package/dist/linkrpc.js +1 -1
- package/dist/rpc.js +1 -1
- package/package.json +5 -5
- package/dist/chunks/runComplete-M-eKaNkI.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-CXAAnZDA.js","names":["fetchSchema","fetchSchema","fetchSchema","traceMessageTransport","fetchSchema","toJsonValue","participantLabel","createInterface","fetchSchema","_untilSignalled","nonNegativeInteger","positiveInteger","positiveInteger","connectEndpoint"],"sources":["../../src/commands/serviceConsoleInput.ts","../../src/commands/consoleSession.ts","../../src/commands/services.ts","../../src/views/types.ts","../../src/views/discovery.ts","../../src/commands/consoleAttach.ts","../../src/output.ts","../../src/commands/caps.ts","../../src/suggest.ts","../../src/schemaLookup.ts","../../src/commands/call.ts","../../src/commands/batch.ts","../../src/commands/connectionBrokerProcess.ts","../../src/commands/checkCompat.ts","../../src/commands/codegen.ts","../../src/commands/contract.ts","../../src/completions/shellScripts.ts","../../src/commands/completions.ts","../../src/commands/defaults.ts","../../src/commands/hash.ts","../../src/commands/internalComplete.ts","../../src/commands/displayForest.ts","../../src/commands/jsonPatch.ts","../../src/commands/stateJsonl.ts","../../src/commands/ls.ts","../../src/commands/topology.ts","../../src/commands/ping.ts","../../src/commands/participantWatch.ts","../../src/commands/schema.ts","../../src/commands/serve.ts","../../src/commands/connectAs.ts","../../src/commands/connectAsTransports.ts","../../src/commands/mcpForward.ts","../../src/commands/jsonRpcStdio.ts","../../src/commands/jsonRpcExport.ts","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/logging.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/debugLocation.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/debugName.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/baseObservable.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/commonFacade/deps.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/disposables.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/derivedImpl.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/derived.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/reactions/createEffectImpl.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/reactions/createEffect.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/base.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/transaction.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/observableValue.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/observableFromEvent.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/utils/utils.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/consoleObservableLogger.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/debugGetDependencyGraph.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/index.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/utils/promise.js","../../src/approvalPresentation.ts","../../src/commands/approval.ts","../../src/commands/identity.ts","../../src/engine/runHub.ts","../../src/methodHelp.ts","../../src/paramFlags.ts","../../src/ui/terminalText.ts","../../src/infra/graph/graphFrame.ts","../../src/infra/graph/inspectGraphTerminal.ts","../../src/infra/graph/inspectGraphTiming.ts","../../src/infra/graph/inspectGraphModel.ts","../../src/infra/graph/inspectGraphView.ts","../../src/infra/graph/inspectGraph.ts","../../src/views/commands.ts","../../src/views/CommandLegend.tsx","../../src/views/ViewFrame.tsx","../../src/views/runViewTui.tsx","../../src/infra/graph/session.tsx","../../src/infra/graph/contribution.ts","../../src/infra/logging/model.ts","../../src/infra/logging/session.tsx","../../src/infra/logging/contribution.ts","../../src/infra/topology/diagram.ts","../../src/infra/topology/model.ts","../../src/infra/topology/session.tsx","../../src/infra/topology/contribution.ts","../../src/views/registry.ts","../../src/commands/view.ts","../../src/cli.ts"],"sourcesContent":["import { createInterface, type Interface, type Key } from 'node:readline';\nimport type { Readable, Writable } from 'node:stream';\n\ntype ConsoleInput = Readable & {\n readonly isTTY?: boolean;\n readonly isRaw?: boolean;\n setRawMode?(mode: boolean): unknown;\n unref?(): unknown;\n};\n\nexport class ServiceConsoleInput {\n private readonly _readline: Interface | undefined;\n private readonly _wasRaw: boolean;\n\n constructor(\n private readonly _input: ConsoleInput,\n output: Writable,\n private readonly _send: (data: string) => void,\n private readonly _interrupt: () => void,\n private readonly _close: () => void,\n ) {\n this._wasRaw = _input.isRaw ?? false;\n if (_input.isTTY) {\n this._readline = createInterface({ input: _input, output, terminal: true, prompt: '', historySize: 0 });\n this._readline.on('line', this._onLine);\n this._readline.on('SIGINT', _interrupt);\n this._readline.on('close', _close);\n _input.on('keypress', this._onKeypress);\n } else {\n _input.on('data', this._onData);\n _input.resume();\n }\n }\n\n dispose(): void {\n if (this._readline) {\n this._readline.removeListener('line', this._onLine);\n this._readline.removeListener('SIGINT', this._interrupt);\n this._readline.removeListener('close', this._close);\n this._readline.close();\n this._input.removeListener('keypress', this._onKeypress);\n this._input.setRawMode?.(this._wasRaw);\n } else {\n this._input.removeListener('data', this._onData);\n }\n this._input.pause();\n // Readline can already have paused stdin during EOF; release any remaining native read handle.\n this._input.unref?.();\n }\n\n private readonly _onLine = (line: string): void => { this._send(line + '\\n'); };\n private readonly _onKeypress = (_text: string | undefined, key: Key): void => {\n if (key.sequence === '\\x1d') this._close();\n };\n private readonly _onData = (data: Buffer): void => {\n if (data.includes(29)) this._close();\n else this._send(data.toString('utf8'));\n };\n}\n","import {\n decodeConsoleData,\n encodeConsoleData,\n type ConsoleClientMessage,\n type ConsoleExit,\n type ConsoleMode,\n type ConsoleServerMessage,\n type ConsoleSignal,\n type ConsoleSize,\n} from '@hediet/linkrpc-infra/console';\nimport { ServiceConsoleInput } from './serviceConsoleInput';\n\n/** An in-flight console attach call: typed streaming calls and adapted raw calls both satisfy it. */\nexport interface ConsoleCall extends PromiseLike<{ readonly exit: ConsoleExit | null }> {\n send(message: ConsoleClientMessage): unknown;\n cancel(): unknown;\n}\n\nexport interface ConsoleSessionOptions {\n /** Forward local input, resizes, and interrupts. */\n readonly interactive: boolean;\n /** Closing the session stops the process (foreground ownership). */\n readonly owner: boolean;\n /** Close after replay, for one-shot log output. */\n readonly untilLive?: boolean;\n readonly reattachCommand?: string;\n /** Detaches a TTY attachment; defaults to {@link DEFAULT_DETACH_KEYS}. */\n readonly detachKeys?: DetachKeys;\n /** Aborting closes the session locally. */\n readonly signal?: AbortSignal;\n}\n\nexport interface ConsoleSessionResult {\n readonly exit: ConsoleExit | null;\n /** The session was closed by this side (detach, ownership release, or abort) rather than by the console. */\n readonly closedLocally: boolean;\n}\n\n/**\n * Drive a `linkrpc.console` attachment (or a stream embedding its protocol):\n * render output, and configure local input from the console's mode. TTY\n * consoles get raw keystrokes, so detaching uses a key sequence (see\n * {@link DetachKeys}); pipe consoles get local line editing, and Ctrl+D on an\n * empty line detaches.\n */\nexport async function runConsoleSession<TExtra extends { readonly t: string }>(\n start: (onMessage: (message: ConsoleServerMessage | TExtra) => void) => ConsoleCall,\n options: ConsoleSessionOptions,\n onExtra?: (message: TExtra) => void,\n): Promise<ConsoleSessionResult> {\n const session = new ConsoleSession(options, onExtra);\n return session.run(start);\n}\n\n/** Local terminal size, sent so that TTY consoles match this terminal. */\nexport function localTerminalSize(): ConsoleSize | undefined {\n const { columns, rows } = process.stdout;\n return process.stdout.isTTY && columns > 0 && rows > 0 ? { cols: columns, rows } : undefined;\n}\n\n/**\n * A detach key sequence in Docker's `--detach-keys` syntax: comma-separated\n * keys, each a single character or `ctrl-<key>` with `<key>` in `a`-`z`, `@`,\n * `[`, `\\`, `]`, `^`, or `_`. For example `ctrl-b,d` or `ctrl-p,ctrl-q`.\n */\nexport class DetachKeys {\n private constructor(readonly spec: string, readonly bytes: Uint8Array) {}\n\n static parse(spec: string): DetachKeys {\n const bytes = spec.split(',').map(part => {\n const key = part.trim();\n const ctrl = /^ctrl-(.)$/i.exec(key);\n if (ctrl) {\n const index = '@abcdefghijklmnopqrstuvwxyz[\\\\]^_'.indexOf(ctrl[1]!.toLowerCase());\n if (index >= 0) return index;\n } else if (key.length === 1 && key.charCodeAt(0) >= 0x20 && key.charCodeAt(0) < 0x7f) {\n return key.charCodeAt(0);\n }\n throw new Error(`Invalid detach key \"${key}\" in \"${spec}\": use a character or ctrl-<a-z, @, [, \\\\, ], ^, _>, separated by commas`);\n });\n if (bytes.length === 0) throw new Error('The detach key sequence is empty');\n return new DetachKeys(spec, Uint8Array.from(bytes));\n }\n\n /** Human-readable form, e.g. `Ctrl+B, then d`. */\n get label(): string {\n return [...this.bytes].map(byte => byte < 0x20 ? `Ctrl+${String.fromCharCode(byte + 0x40)}` : String.fromCharCode(byte)).join(', then ');\n }\n}\n\n/** Ctrl+B, then d (tmux's binding): unlike Docker's Ctrl+P, Ctrl+Q, it reaches programs in VS Code's terminal. */\nexport const DEFAULT_DETACH_KEYS = DetachKeys.parse('ctrl-b,d');\n\n/**\n * Recognizes a detach sequence in raw keyboard input. Bytes of a partial match\n * are held back, and forwarded unchanged when the sequence does not complete.\n */\nexport class DetachKeyFilter {\n private _matched = 0;\n\n constructor(private readonly _keys: DetachKeys = DEFAULT_DETACH_KEYS) {}\n\n push(chunk: Uint8Array): { readonly forward: Uint8Array; readonly detach: boolean } {\n const sequence = this._keys.bytes;\n const forward: number[] = [];\n for (const byte of chunk) {\n // Keep the longest suffix of the pending keys that still starts the sequence.\n const pending = [...sequence.subarray(0, this._matched), byte];\n let start = 0;\n while (start < pending.length && !pending.slice(start).every((value, index) => value === sequence[index])) start++;\n forward.push(...pending.slice(0, start));\n this._matched = pending.length - start;\n if (this._matched === sequence.length) {\n this._matched = 0;\n return { forward: Uint8Array.from(forward), detach: true };\n }\n }\n return { forward: Uint8Array.from(forward), detach: false };\n }\n}\n\nconst ALTERNATE_SCREEN = /\\x1b\\[\\?(?:1049|1047|47)([hl])/g;\n/** Undo terminal modes a program may have enabled: mouse, bracketed paste, focus, win32-input, hidden cursor. */\nconst TERMINAL_RESET = '\\x1b[0m\\x1b[?25h\\x1b[?1000l\\x1b[?1002l\\x1b[?1003l\\x1b[?1006l\\x1b[?2004l\\x1b[?1004l\\x1b[?9001l';\n\nclass ConsoleSession<TExtra extends { readonly t: string }> {\n private _call: ConsoleCall | undefined;\n private readonly _detachKeys: DetachKeys;\n private _mode: ConsoleMode | undefined;\n private _signals: readonly ConsoleSignal[] = [];\n private _input: { dispose(): void } | undefined;\n private _raw = false;\n private _alternateScreen = false;\n private _closedLocally = false;\n\n constructor(\n private readonly _options: ConsoleSessionOptions,\n private readonly _onExtra: ((message: TExtra) => void) | undefined,\n ) {\n this._detachKeys = _options.detachKeys ?? DEFAULT_DETACH_KEYS;\n }\n\n async run(start: (onMessage: (message: ConsoleServerMessage | TExtra) => void) => ConsoleCall): Promise<ConsoleSessionResult> {\n const onSignal = () => this._interrupt();\n const onTerminate = () => this.close();\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onTerminate);\n this._options.signal?.addEventListener('abort', onTerminate);\n try {\n this._call = start(message => this._onMessage(message));\n if (this._closedLocally || this._options.signal?.aborted) this.close();\n let exit: ConsoleExit | null = null;\n try {\n exit = (await this._call).exit;\n } catch (error) {\n if (!this._closedLocally) throw error;\n }\n return { exit, closedLocally: this._closedLocally };\n } finally {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onTerminate);\n this._options.signal?.removeEventListener('abort', onTerminate);\n this._input?.dispose();\n if (this._raw) {\n process.stdout.write(TERMINAL_RESET + (this._alternateScreen ? '\\x1b[?1049l' : '') + '\\r\\n');\n }\n if (this._closedLocally && this._options.interactive && !this._options.owner && this._options.reattachCommand) {\n process.stderr.write(`Detached. Reattach: ${this._options.reattachCommand}\\n`);\n }\n }\n }\n\n close(): void {\n this._closedLocally = true;\n try { void Promise.resolve(this._call?.cancel()).catch(() => {}); } catch { /* already settled */ }\n }\n\n private _onMessage(message: ConsoleServerMessage | TExtra): void {\n const console = message as ConsoleServerMessage;\n switch (console.t) {\n case 'console':\n this._mode = console.mode;\n this._signals = console.signals;\n this._startInput();\n return;\n case 'screen': {\n const screen = decodeConsoleData(console.data);\n if (screen.length > 0 && process.stdout.isTTY) process.stdout.write('\\x1b[H\\x1b[2J');\n this._write(process.stdout, screen);\n return;\n }\n case 'output':\n this._write(console.stream === 'stderr' ? process.stderr : process.stdout, decodeConsoleData(console.data));\n return;\n case 'notice':\n process.stderr.write(this._mode === 'tty' ? `\\r\\n[console] ${console.text}\\r\\n` : `${console.text}\\n`);\n return;\n case 'live':\n if (this._options.untilLive) this.close();\n return;\n case 'started':\n case 'exit':\n case 'resized':\n return;\n }\n this._onExtra?.(message as TExtra);\n }\n\n private _write(stream: NodeJS.WriteStream, data: Uint8Array): void {\n if (this._mode === 'tty') {\n for (const match of new TextDecoder().decode(data).matchAll(ALTERNATE_SCREEN)) this._alternateScreen = match[1] === 'h';\n }\n stream.write(data);\n }\n\n private _startInput(): void {\n if (!this._options.interactive || this._input) return;\n const owner = this._options.owner;\n const reattach = this._options.reattachCommand;\n if (this._mode === 'tty') {\n process.stderr.write(owner\n ? `Foreground (TTY). Keys go to the program; ${this._detachKeys.label} stops and removes the service.\\n`\n : `Attached (TTY). Keys go to the program; ${this._detachKeys.label} detaches.\\n`);\n } else {\n const interrupt = owner ? 'Ctrl+C or ' : this._signals.includes('SIGINT') ? 'Ctrl+C interrupts; ' : '';\n process.stderr.write(owner\n ? `Foreground (pipe console). ${interrupt}Ctrl+D on an empty line stops and removes the service.\\n`\n : `Attached (pipe console). ${interrupt}Ctrl+D on an empty line detaches.\\n`);\n }\n if (reattach) process.stderr.write(`${owner ? 'Attach from another terminal while running' : 'Reattach'}: ${reattach}\\n`);\n this._input = this._mode === 'tty' ? this._startTerminalInput() : this._startLineInput();\n }\n\n private _startTerminalInput(): { dispose(): void } {\n const stdin = process.stdin;\n const filter = stdin.isTTY ? new DetachKeyFilter(this._detachKeys) : undefined;\n const wasRaw = stdin.isRaw;\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n this._raw = true;\n }\n const onData = (chunk: Buffer) => {\n const { forward, detach } = filter ? filter.push(chunk) : { forward: chunk, detach: false };\n if (forward.length > 0) this._send({ t: 'input', data: encodeConsoleData(forward) });\n if (detach) this.close();\n };\n const onResize = () => {\n const size = localTerminalSize();\n if (size) this._send({ t: 'resize', ...size });\n };\n stdin.on('data', onData);\n stdin.resume();\n process.stdout.on('resize', onResize);\n return {\n dispose: () => {\n stdin.removeListener('data', onData);\n process.stdout.removeListener('resize', onResize);\n if (stdin.isTTY) stdin.setRawMode(wasRaw);\n stdin.pause();\n stdin.unref?.();\n },\n };\n }\n\n private _startLineInput(): { dispose(): void } {\n return new ServiceConsoleInput(\n process.stdin, process.stderr,\n data => this._send({ t: 'input', data: encodeConsoleData(new TextEncoder().encode(data)) }),\n () => this._interrupt(),\n () => this.close(),\n );\n }\n\n private _interrupt(): void {\n if (this._options.owner || !this._options.interactive) {\n this.close();\n } else if (this._mode === 'tty') {\n this._send({ t: 'input', data: encodeConsoleData(Uint8Array.of(0x03)) });\n } else if (this._signals.includes('SIGINT')) {\n this._send({ t: 'signal', signal: 'SIGINT' });\n } else {\n process.stderr.write('Interrupting is not supported for pipe processes on this host; run with -t for a terminal. Ctrl+D on an empty line detaches.\\n');\n }\n }\n\n private _send(message: ConsoleClientMessage): void {\n try { void Promise.resolve(this._call?.send(message)).catch(() => {}); } catch { /* the call ended */ }\n }\n}\n","import { Command, Option } from 'commander';\nimport { directoryInterface, ErrorCode, RpcError, type InterfaceClient, type LinkRpcConnection } from '@hediet/linkrpc';\nimport { connectToHub } from '@hediet/linkrpc/node';\nimport type { ConsoleServerMessage } from '@hediet/linkrpc-infra/console';\nimport { managedEndpointsInterface, HubHome, readEndpointDiscovery, type EndpointStatus, type RunEvent } from '@hediet/linkrpc-hub-daemon/client';\nimport type { ContextReference, ContextValues } from '../contexts';\nimport { localTerminalSize, runConsoleSession, type DetachKeys } from './consoleSession';\n\nexport type EndpointClient = InterfaceClient<typeof managedEndpointsInterface>;\nexport interface ServicesHost {\n namespace(): string;\n attachCommand(id: string): string;\n /** The configured TTY detach sequence, if not the default. */\n detachKeys(): DetachKeys | undefined;\n restart(): Promise<void>;\n use<T>(startLocal: boolean, action: (client: EndpointClient, context: ManagementContext) => Promise<T>): Promise<T>;\n}\n\nexport interface ManagementContext {\n /** The selected manager is the local daemon, so local paths are meaningful. */\n readonly local: boolean;\n}\n\nfunction withDetachKeys(host: ServicesHost): { detachKeys?: DetachKeys } {\n const detachKeys = host.detachKeys();\n return detachKeys ? { detachKeys } : {};\n}\n\nexport function serviceAttachCommand(options: {\n context: string; namespace: string; id: string; overrides: ContextValues; useEnv: boolean;\n}, platform: NodeJS.Platform = process.platform): string {\n const args = ['hub', 'services', 'attach', '--id', options.id,\n '--context', options.context, '--namespace', options.namespace, options.useEnv ? '--use-env' : '--no-use-env'];\n for (const key of Object.keys(options.overrides) as (keyof ContextValues)[]) {\n if (key === 'namespace') continue;\n const value = options.overrides[key];\n if (value === undefined) continue;\n const flag = '--' + key.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());\n if (key === 'endpointCmdEnv' && typeof value === 'object') {\n for (const name of Object.keys(value)) args.push(flag, `${name}=<same value>`);\n } else if (typeof value === 'boolean') {\n if (value) args.push(flag);\n else if (key === 'sign') args.push('--no-sign');\n } else if (typeof value === 'string' || typeof value === 'number') {\n args.push(flag, key === 'endpointToken' ? '<same endpoint token>' : String(value).replace(/([?&]token=)[^&]+/g, '$1<same token>'));\n }\n }\n return args.map(arg => /^[A-Za-z0-9_./:-]+$/.test(arg) ? arg\n : \"'\" + arg.replace(/'/g, platform === 'win32' ? \"''\" : \"'\\\\''\") + \"'\").join(' ');\n}\n\nconst requiredInterfaces = [\n { id: managedEndpointsInterface.info.id, hash: managedEndpointsInterface.schemaHash },\n];\n\nexport async function checkDaemonInterfaces(connection: LinkRpcConnection, serviceId?: string): Promise<void> {\n const recovery = serviceId === undefined\n ? 'Run `hub services restart` to stop the local daemon via RPC and start this CLI\\'s bundled daemon.'\n : 'Update/restart the daemon on its execution host. To replace the default local daemon, run `hub --context :empty --no-use-env services restart`.';\n for (const required of requiredInterfaces) {\n let cursor: string | undefined;\n let supported = false;\n const hashes = new Set<string>();\n try {\n do {\n const page = await connection.get(directoryInterface, { serviceId }).list({\n interfaceId: required.id, serviceId: serviceId ?? '', cursor,\n });\n for (const item of page.items) {\n if (item.interfaceId !== required.id || item.serviceId !== (serviceId ?? '')) continue;\n hashes.add(item.interfaceHash);\n supported ||= item.interfaceHash === required.hash;\n }\n if (page.truncated) throw new Error('Daemon interface discovery was truncated; compatibility could not be checked.');\n cursor = page.nextCursor;\n } while (!supported && cursor !== undefined);\n } catch (error) {\n if (!(error instanceof RpcError) || error.code !== ErrorCode.methodNotFound) throw error;\n throw new Error(`The selected daemon cannot report its interfaces. ${recovery}`, { cause: error });\n }\n if (!supported) {\n throw new Error(`The selected daemon does not support required interface ${required.id}@${required.hash} (reported: ${[...hashes].join(', ') || 'missing'}). ${recovery}`);\n }\n }\n}\n\nexport function contextNamespace(reference: ContextReference): string {\n switch (reference.kind) {\n case 'path': return process.platform === 'win32' ? reference.path.toLowerCase() : reference.path;\n case 'id': return `id:${reference.id}`;\n case 'root': return ':root';\n case 'empty': throw new Error('The :empty context has no namespace. Pass --namespace <name>, or select another context with --context <selector>.');\n }\n}\n\nexport async function useLocalManagement<T>(start: boolean, action: (client: EndpointClient, context: ManagementContext) => Promise<T>): Promise<T> {\n const home = HubHome.resolve();\n if (start) {\n const { startDaemon, nodeDaemonLaunch } = await import('@hediet/linkrpc-hub-daemon');\n const result = await startDaemon({ home, launch: nodeDaemonLaunch(home) });\n if (result === 'started') process.stderr.write('linkrpc: local daemon started.\\n');\n }\n const discovery = readEndpointDiscovery(home.managementFile);\n if (!discovery) throw new Error('No endpoint configured through flags, environment, or context, and the local Hub daemon is not running.');\n const handle = await connectToHub({ endpoint: discovery.endpoint, token: discovery.token ?? '' });\n try {\n await checkDaemonInterfaces(handle.connection);\n return await action(handle.connection.get(managedEndpointsInterface), { local: true });\n }\n finally { handle.close(); }\n}\n\nexport async function restartLocalDaemon(): Promise<void> {\n const { startDaemon, stopDaemon, nodeDaemonLaunch } = await import('@hediet/linkrpc-hub-daemon');\n const home = HubHome.resolve();\n process.stderr.write('Restarting the local Hub daemon: clients will disconnect and managed workloads will stop. OS autostart settings are unchanged.\\n');\n await stopDaemon(home);\n await startDaemon({ home, launch: nodeDaemonLaunch(home) });\n await useLocalManagement(false, async () => {});\n process.stderr.write('The bundled daemon is running and supports the required interfaces.\\n');\n}\n\nexport function registerServices(program: Command, host: ServicesHost): void {\n const createEndpoint = async (id: string, action: (client: EndpointClient, context: ManagementContext) => Promise<void>) => {\n try { await host.use(true, action); }\n catch (error) {\n if (error instanceof RpcError && error.message === `Endpoint \"${id}\" already exists in ${host.namespace()}`) {\n throw new RpcError(\n `${error.message}\\nAttach to it: ${host.attachCommand(id)}\\nOr replace it: rerun this command with --force`,\n error.code, error.data, error.origin, error.hasData,\n );\n }\n throw error;\n }\n };\n const services = program.command('services').description('Manage context-scoped endpoints through the selected daemon.')\n .option('--namespace <name>', 'managed endpoint namespace (defaults to selected context)');\n services.command('restart')\n .description('Stop the local daemon via RPC and start the bundled daemon; does not change OS autostart.')\n .action(() => host.restart());\n const addressed = (command: Command) => command.option('--id <id>', 'endpoint name in this context', 'main');\n const policy = (command: Command) => command.option('--persistent', 'retain definition across stop and daemon restart')\n .addOption(new Option('--restart <policy>', 'restart process or reconnect after failure').choices(['never', 'on-failure', 'always']).default('never'))\n .option('--force', 'stop and replace an existing endpoint with the same ID, even one owned by another terminal');\n policy(addressed(services.command('run <command...>').description('Start a process on the daemon; arguments follow --.')))\n .option('--detach', 'return after readiness')\n .addOption(new Option('--foreground', 'stop and remove the service when this CLI disconnects').conflicts(['detach', 'persistent']))\n .option('-t, --tty', 'run in a pseudoterminal; keys go to the program and Ctrl+P, Ctrl+Q detaches')\n .option('-x, --no-rpc', 'run a plain stdio process without an RPC connection; ready on spawn')\n .option('--cwd <directory>', 'working directory on the execution host')\n .option('--env <key=value...>', 'explicit child environment')\n .addOption(new Option('--readiness <mode>', 'wait for Hub connection or process spawn (default: connected, or spawned with --no-rpc)').choices(['connected', 'spawned']))\n .action(async (command: string[], options: {\n id: string; persistent?: boolean; restart: 'never' | 'on-failure' | 'always'; force?: boolean;\n detach?: boolean; foreground?: boolean; tty?: boolean; rpc: boolean; cwd?: string; env?: string[]; readiness?: 'connected' | 'spawned';\n }) => {\n if (!options.rpc && options.readiness === 'connected') throw new Error('--no-rpc cannot use --readiness connected; plain processes are ready on spawn.');\n const namespace = host.namespace();\n const env: Record<string, string> = {};\n for (const value of options.env ?? []) {\n const index = value.indexOf('=');\n if (index <= 0) throw new Error('--env requires KEY=value');\n env[value.slice(0, index)] = value.slice(index + 1);\n }\n await createEndpoint(options.id, async (client, context) => {\n const info = await client.info({});\n const cwd = options.cwd ?? (context.local ? process.cwd() : undefined);\n if (!cwd) throw new Error('Remote execution requires --cwd with a path on the execution host.');\n process.stderr.write(`Execution host: ${info.hostname}\\nNamespace: ${namespace}\\nEndpoint: ${options.id}\\nCommand: ${JSON.stringify(command)}\\nWorking directory: ${cwd}\\n`);\n const tty = options.tty === true;\n const size = tty ? localTerminalSize() : undefined;\n const detach = new AbortController();\n let status: EndpointStatus | undefined;\n let timedOut = false;\n const timeout = options.detach ? setTimeout(() => { timedOut = true; detach.abort(); }, 30_000) : undefined;\n try {\n const result = await runConsoleSession<Exclude<RunEvent, ConsoleServerMessage>>(onMessage => client.run({\n definition: {\n namespace, id: options.id, persistent: options.persistent ?? false, restart: options.restart,\n source: { kind: 'process', command, cwd, env, rpc: options.rpc, tty, readiness: options.readiness ?? (options.rpc ? 'connected' : 'spawned') },\n },\n owner: options.foreground === true,\n replace: options.force === true,\n console: { interactive: !options.detach, ...(size ? { size } : {}) },\n }, { onMessage }), {\n interactive: !options.detach,\n owner: options.foreground === true,\n reattachCommand: host.attachCommand(options.id),\n ...withDetachKeys(host),\n signal: detach.signal,\n }, event => {\n status = event.status;\n if (options.detach && status.runtime.state === 'running') detach.abort();\n });\n if (options.detach) {\n if (timedOut) throw new Error('Endpoint did not become ready within 30 seconds. It remains daemon-owned; use services list or logs to inspect it.');\n if (status?.runtime.state !== 'running') throw new Error(status?.runtime.error ?? 'Endpoint exited before readiness');\n print(status);\n } else if (!result.closedLocally && result.exit?.code) {\n process.exitCode = result.exit.code;\n } else if (!result.closedLocally && status?.runtime.state === 'failed' && !result.exit) {\n throw new Error(status.runtime.error ?? 'Endpoint failed');\n }\n } finally {\n clearTimeout(timeout);\n }\n });\n });\n policy(addressed(services.command('connect').description('Connect an existing LinkRPC endpoint; never owns its external process.')))\n .requiredOption('--target-endpoint <uri>', 'endpoint resolved on the daemon machine')\n .action(async (options: { id: string; targetEndpoint: string; persistent?: boolean; restart: 'never' | 'on-failure' | 'always'; force?: boolean }) => {\n const namespace = host.namespace();\n await createEndpoint(options.id, async client => {\n const info = await client.info({});\n process.stderr.write(`Execution host: ${info.hostname}\\nNamespace: ${namespace}\\nEndpoint: ${options.id}\\n`);\n const status = await client.create({\n namespace, id: options.id, persistent: options.persistent ?? false, restart: options.restart, replace: options.force === true,\n source: { kind: 'connection', endpoint: options.targetEndpoint },\n });\n print(await waitUntilReady(client, status));\n });\n });\n services.command('list').option('--all-contexts', 'include every namespace visible to this caller')\n .action(async (options: { allContexts?: boolean }) => {\n const namespace = options.allContexts ? undefined : host.namespace();\n await host.use(false, async client => print(await client.list({ namespace })));\n });\n for (const operation of ['start', 'stop', 'remove'] as const) {\n addressed(services.command(operation)).action(async (options: { id: string }) => {\n const namespace = host.namespace();\n await host.use(operation === 'start', async client => {\n if (operation === 'start') print(await waitUntilReady(client, await client.start({ namespace, id: options.id })));\n else print(await client[operation]({ namespace, id: options.id }));\n });\n });\n }\n addressed(services.command('configure'))\n .option('--persistent', 'retain this endpoint')\n .option('--no-persistent', 'remove it when stopped')\n .addOption(new Option('--restart <policy>').choices(['never', 'on-failure', 'always']))\n .action(async (options: { id: string; persistent?: boolean; restart?: 'never' | 'on-failure' | 'always' }, command: Command) => {\n const namespace = host.namespace();\n await host.use(false, async client => print(await client.configure({\n namespace, id: options.id, restart: options.restart,\n persistent: command.getOptionValueSource('persistent') === 'cli' ? options.persistent : undefined,\n })));\n });\n for (const operation of ['attach', 'logs'] as const) {\n const subcommand = addressed(services.command(operation));\n if (operation === 'attach') subcommand.option('--read-only', 'observe without sending input');\n else subcommand.option('--follow', 'follow new output');\n subcommand.action(async (options: { id: string; follow?: boolean; readOnly?: boolean }) => {\n const namespace = host.namespace();\n await host.use(false, async client => {\n const status = (await client.list({ namespace })).find(value => value.id === options.id);\n if (!status) throw new Error(`Endpoint \"${options.id}\" not found in ${namespace}`);\n if (!status.console) throw new Error(`Endpoint \"${options.id}\" is a connection and has no console`);\n const interactive = operation === 'attach' && options.readOnly !== true;\n const size = interactive ? localTerminalSize() : undefined;\n // The management interface's `consoles` template instance, addressed by endpoint, like `hub attach`.\n const result = await runConsoleSession(onMessage => client.consoles.attach({\n params: { namespace, id: options.id }, interactive, ...(size ? { size } : {}),\n }, { onMessage }), {\n interactive,\n owner: false,\n untilLive: operation === 'logs' && !options.follow,\n reattachCommand: host.attachCommand(options.id),\n ...withDetachKeys(host),\n });\n if (operation === 'attach' && !result.closedLocally && result.exit?.code) process.exitCode = result.exit.code;\n });\n });\n }\n}\n\n/** Wait until an endpoint runs; fail if it stops, fails, or is removed first. */\nasync function waitUntilReady(client: EndpointClient, initial: EndpointStatus): Promise<EndpointStatus> {\n if (initial.runtime.state === 'running') return initial;\n let current = initial;\n let outcome: 'ready' | 'finished' | 'removed' | 'timeout' | undefined;\n const call = client.watch({ namespace: initial.namespace, id: initial.id }, {\n onMessage: event => {\n if (event.t === 'removed') outcome = 'removed';\n else {\n current = event.status;\n if (current.runtime.state === 'running') outcome = 'ready';\n else if (['failed', 'stopped', 'disabled'].includes(current.runtime.state)) outcome = 'finished';\n }\n if (outcome) void call.cancel().catch(() => {});\n },\n });\n const timeout = setTimeout(() => { outcome ??= 'timeout'; void call.cancel().catch(() => {}); }, 30_000);\n try {\n await call;\n } catch (error) {\n if (!outcome) throw error;\n } finally {\n clearTimeout(timeout);\n }\n switch (outcome) {\n case 'ready': return current;\n case 'timeout': throw new Error('Endpoint did not become ready within 30 seconds. It remains daemon-owned; use services list or logs to inspect it.');\n default: throw new Error(current.runtime.error ?? 'Endpoint exited before readiness');\n }\n}\n\nfunction print(value: unknown): void { process.stdout.write(JSON.stringify(value, null, 2) + '\\n'); }\n","import type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport type { LinkRpcInterfaceSchema } from \"@hediet/linkrpc\";\nimport type { Command } from \"commander\";\nimport type React from \"react\";\nimport type { IObservable } from \"@vscode/observables\";\n\nexport type InterfaceCondition =\n | { readonly interfaceId: string }\n | { readonly tag: string };\n\nexport type ViewCondition =\n | { readonly kind: \"interface\"; readonly interface: InterfaceCondition }\n | { readonly kind: \"service\"; readonly implements: InterfaceCondition };\n\nexport interface ViewInterface {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash?: string;\n readonly tags?: readonly string[];\n readonly discoveredFrom: string;\n readonly isDefault?: boolean;\n}\n\n/** The schema hash is deliberately not part of identity: opening resolves it again. */\nexport interface ViewTarget {\n readonly id: string;\n readonly kind: \"interface\" | \"service\";\n readonly serviceId: string;\n readonly interfaceId?: string;\n readonly discoveredFrom: string;\n readonly interfaces: readonly ViewInterface[];\n /** Sibling advertisements on the same service, for optional companion protocols. */\n readonly serviceInterfaces?: readonly ViewInterface[];\n}\n\nexport interface ResolvedViewInterface extends ViewInterface {\n readonly schema: LinkRpcInterfaceSchema;\n}\n\nexport interface ViewOpenContext {\n readonly channel: CliChannel;\n readonly target: ViewTarget;\n readonly interfaces: readonly ResolvedViewInterface[];\n}\n\nexport interface ViewKeyEvent {\n readonly input: string;\n readonly name?: string;\n readonly ctrl?: boolean;\n readonly meta?: boolean;\n readonly shift?: boolean;\n}\n\n/** Named terminal keys (up, return, pageup, …) or a literal character. */\nexport interface ViewKeybinding {\n readonly key: string;\n readonly ctrl?: boolean;\n readonly meta?: boolean;\n readonly shift?: boolean;\n}\n\nexport interface ViewCommand {\n readonly id: string;\n readonly title: string;\n readonly keybindings: readonly ViewKeybinding[];\n readonly enabled?: boolean;\n /** Human-readable context, e.g. \"Graph\" or \"Editing parameters\". */\n readonly context?: string;\n execute(): void;\n}\n\nexport interface ViewSession {\n readonly element: React.ReactElement;\n /** Publish a new command list whenever availability, titles or context change. */\n readonly commands: IObservable<readonly ViewCommand[]>;\n /** Optional compact-legend limit; a view can expose full help as a command. */\n readonly maxLegendRows?: number;\n readonly capturesInput?: boolean;\n captureState?(): unknown;\n restoreState?(state: unknown): void;\n setViewport?(rows: number, columns?: number): void;\n /** Called only while capturesInput is true, after declarative commands. */\n handleTextInput?(event: ViewKeyEvent): boolean;\n dispose(): void;\n disposeAsync?(): Promise<void>;\n}\n\n/** Compiled-in contributions; matching is discovery, never authorization. */\nexport interface ViewContribution {\n readonly id: string;\n readonly title: string;\n readonly modes: readonly (\"cli\" | \"tui\")[];\n readonly conditions: readonly ViewCondition[];\n configureCommand(command: Command): void;\n open(context: ViewOpenContext, options: Readonly<Record<string, unknown>>): Promise<string>;\n createSession(context: ViewOpenContext): ViewSession;\n}\n\nexport function formatCondition(condition: ViewCondition): string {\n const match = condition.kind === \"interface\" ? condition.interface : condition.implements;\n const predicate = \"tag\" in match ? `tag(${match.tag})` : `id(${match.interfaceId})`;\n return condition.kind === \"interface\" ? `interface:${predicate}` : `service:implements(${predicate})`;\n}\n\nexport function matchesInterface(value: ViewInterface, condition: InterfaceCondition): boolean {\n return \"tag\" in condition\n ? value.tags?.includes(condition.tag) === true\n : value.interfaceId === condition.interfaceId;\n}\n\nexport function matchesTarget(target: ViewTarget, view: Pick<ViewContribution, \"conditions\">): boolean {\n return view.conditions.some(condition => condition.kind === target.kind\n && target.interfaces.some(value => matchesInterface(value,\n condition.kind === \"interface\" ? condition.interface : condition.implements)));\n}\n\nexport function targetId(kind: ViewTarget[\"kind\"], listing: ViewInterface): string {\n return `${kind}:${encodeURIComponent(listing.serviceId)}:${encodeURIComponent(listing.discoveredFrom)}`\n + (kind === \"interface\" ? `:${encodeURIComponent(listing.interfaceId)}:${listing.isDefault ? \"default\" : \"qualified\"}` : \"\");\n}\n\nexport function interfaceTarget(listing: ViewInterface): ViewTarget {\n return {\n id: targetId(\"interface\", listing), kind: \"interface\", serviceId: listing.serviceId,\n interfaceId: listing.interfaceId, discoveredFrom: listing.discoveredFrom, interfaces: [listing],\n };\n}\n","import { fetchDefaults, fetchSchema, type CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { HubDirectoryExplorer } from \"@hediet/linkrpc/hub/common\";\nimport { interfaceTarget, matchesInterface, matchesTarget, targetId, type ViewContribution, type ViewInterface, type ViewOpenContext, type ViewTarget } from \"./types\";\n\nexport interface ViewDiscoveryOptions {\n readonly maxDepth?: number;\n readonly timeoutMs?: number;\n}\n\nexport interface ViewSelectionOptions extends ViewDiscoveryOptions {\n readonly target?: string;\n readonly interface?: string;\n readonly service?: string;\n}\n\nexport async function discoverViewTargets(channel: CliChannel, view: ViewContribution, options: ViewDiscoveryOptions = {}) {\n const explorer = new HubDirectoryExplorer(channel, options);\n const warnings: string[] = [];\n try {\n await explorer.explore();\n const snapshot = explorer.graphSnapshot.result;\n warnings.push(...snapshot.inaccessible.map(item => `${item.serviceId || \"<root>\"}: ${item.reason}`));\n const listings: ViewInterface[] = [...snapshot.listings];\n try {\n const defaults = await deadline(fetchDefaults(channel), options.timeoutMs ?? 5_000);\n if (defaults.interfaceId !== undefined) {\n const existing = listings.find(item => item.serviceId === \"\" && item.interfaceId === defaults.interfaceId);\n listings.unshift({\n serviceId: \"\", interfaceId: defaults.interfaceId, hash: defaults.hash ?? existing?.hash,\n discoveredFrom: \"\", isDefault: true, tags: existing?.tags,\n });\n }\n } catch (error) {\n warnings.push(`Default service: ${message(error)}`);\n }\n // Absent tags mean no advertised labels. Discovery never scans schemas;\n // opening separately validates the selected implementation's contract.\n const interfacesById = new Map<string, ViewTarget>();\n for (const listing of listings) {\n const target = interfaceTarget(listing);\n const previous = interfacesById.get(target.id);\n interfacesById.set(target.id, previous === undefined ? target\n : { ...previous, interfaces: [...previous.interfaces, listing] });\n }\n const targets: ViewTarget[] = [...interfacesById.values()];\n const services = new Map<string, ViewInterface[]>();\n for (const listing of listings) {\n const id = targetId(\"service\", listing);\n const values = services.get(id) ?? [];\n // Prefer default routing for the main interface of the root service.\n if (!values.some(value => value.interfaceId === listing.interfaceId && value.hash === listing.hash)) values.push(listing);\n services.set(id, values);\n }\n for (const [id, interfaces] of services) {\n const first = interfaces[0]!;\n targets.push({ id, kind: \"service\", serviceId: first.serviceId, discoveredFrom: first.discoveredFrom, interfaces });\n }\n return { targets: targets.filter(target => matchesTarget(target, view))\n .map(target => ({ ...target, serviceInterfaces: listings.filter(listing =>\n listing.serviceId === target.serviceId && listing.discoveredFrom === target.discoveredFrom) }))\n .sort((a, b) => a.id.localeCompare(b.id)), warnings };\n } finally {\n explorer.dispose();\n }\n}\n\nexport async function resolveViewTarget(channel: CliChannel, view: ViewContribution, id: string, options: ViewDiscoveryOptions = {}): Promise<ViewOpenContext> {\n const { targets } = await discoverViewTargets(channel, view, options);\n const target = targets.find(value => value.id === id);\n if (!target) throw new Error(`Unknown or unavailable ${view.id} target \"${id}\". Run view targets ${view.id} again.`);\n return loadViewTarget(channel, target, options.timeoutMs, view);\n}\n\n/** Selection and opening share a connection, including spawned ephemeral endpoints. */\nexport async function resolveViewSelection(channel: CliChannel, view: ViewContribution, options: ViewSelectionOptions): Promise<ViewOpenContext> {\n if (options.target !== undefined) {\n const context = await resolveViewTarget(channel, view, options.target, options);\n if (options.service !== undefined && context.target.serviceId !== options.service) {\n throw new Error(\"--target does not match --service\");\n }\n if (options.interface !== undefined && !context.target.interfaces.some(value => value.interfaceId === options.interface)) {\n throw new Error(\"--target does not match --interface\");\n }\n return context;\n }\n if (options.interface === undefined && options.service === undefined) {\n throw new Error(\"Specify --target, or an exact --interface / --service selector\");\n }\n const discovery = await discoverViewTargets(channel, view, options);\n const candidates = discovery.targets.filter(target =>\n target.kind === (options.interface === undefined ? \"service\" : \"interface\")\n && (options.interface === undefined || target.interfaceId === options.interface)\n && (options.service === undefined || target.serviceId === options.service));\n // Defaults can also appear as qualified directory entries. They represent\n // the same implementation, not an ambiguity between two endpoint routes.\n const matches = candidates.filter(target => target.kind !== \"interface\"\n || target.interfaces.some(value => value.isDefault)\n || !candidates.some(other => other.serviceId === target.serviceId\n && other.discoveredFrom === target.discoveredFrom\n && other.interfaceId === target.interfaceId\n && other.interfaces.every(value => target.interfaces.some(candidate => candidate.hash === value.hash))\n && target.interfaces.every(value => other.interfaces.some(candidate => candidate.hash === value.hash))\n && other.interfaces.some(value => value.isDefault)));\n if (matches.length !== 1) {\n const detail = matches.length === 0 ? \"No matching target\" : `Target selection is ambiguous (${matches.length} targets)`;\n throw new Error(`${detail}; use --service to narrow the selection or --target from view targets ${view.id}`);\n }\n return loadViewTarget(channel, matches[0]!, options.timeoutMs, view);\n}\n\nexport async function loadViewTarget(channel: CliChannel, target: ViewTarget, timeoutMs = 5_000, view?: ViewContribution): Promise<ViewOpenContext> {\n const candidates = view === undefined || target.kind === \"interface\" ? target.interfaces\n : target.interfaces.filter(listing => view.conditions.some(condition =>\n condition.kind === \"service\" && matchesInterface(listing, condition.implements)));\n for (const listing of candidates) {\n if (candidates.some(other => other.interfaceId === listing.interfaceId && other.hash !== listing.hash)) {\n throw new Error(`Target \"${target.id}\" is ambiguous: interface \"${listing.interfaceId}\" advertises multiple schema hashes`);\n }\n }\n return {\n channel, target,\n interfaces: await Promise.all(candidates.map(async listing => {\n // Use the freshly advertised hash, not a hash embedded in a saved\n // target ID. Different services can implement different revisions.\n const schema = await deadline(fetchSchema(channel, listing.interfaceId, listing.hash, listing.discoveredFrom || undefined), timeoutMs);\n if (schema.id !== listing.interfaceId || (listing.hash !== undefined && schema.hash !== listing.hash)) {\n throw new Error(`Schema for \"${listing.interfaceId}\" does not match its current directory advertisement; rediscover the target`);\n }\n return { ...listing, hash: schema.hash, schema };\n })),\n };\n}\n\nasync function deadline<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([promise, new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`Reflection timed out after ${timeoutMs}ms`)), timeoutMs);\n })]);\n } finally { clearTimeout(timer); }\n}\n\nfunction message(error: unknown): string { return error instanceof Error ? error.message : String(error); }\n","import {\n createSchemaToZod,\n interfaceTemplateMemberName,\n interfaceTemplatesEqual,\n INTERFACE_TEMPLATES_EXTENSION,\n validateInterfaceTemplates,\n type InterfaceTemplateArgument,\n type InterfaceTemplatesMetadata,\n type JsonValue,\n} from '@hediet/linkrpc';\nimport type { CliChannel } from '@hediet/linkrpc-client-internal';\nimport {\n CONSOLE_INTERFACE_TAG,\n consoleAttachResultSchema,\n consoleServerMessageSchema,\n ConsoleTemplate,\n type ConsoleAttachParams,\n type ConsoleServerMessage,\n} from '@hediet/linkrpc-infra/console';\nimport { unknown } from 'zod/mini';\nimport { discoverViewTargets, loadViewTarget, resolveViewSelection } from '../views/discovery';\nimport type { ResolvedViewInterface, ViewContribution } from '../views/types';\nimport { localTerminalSize, runConsoleSession, type ConsoleCall, type DetachKeys } from './consoleSession';\n\n/** One instance of the `linkrpc.console.v1` template, found through reflection. */\nexport interface ConsoleTarget {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly instance: string;\n readonly infoMethod: string;\n readonly attachMethod: string;\n readonly params: InterfaceTemplateArgument;\n}\n\nexport interface AttachConsoleOptions {\n readonly serviceId: string;\n readonly interfaceId?: string;\n readonly instance?: string;\n /** JSON params of the selected instance; defaults to `{}`. */\n readonly params?: string;\n readonly readOnly?: boolean;\n readonly detachKeys?: DetachKeys;\n readonly reattachCommand: string;\n}\n\nconst consoleTemplate = ConsoleTemplate({ params: unknown() }).template;\n\n/** Discovery-only view: the generic `attach` command reuses directory and reflection resolution. */\nexport const consoleDiscovery: ViewContribution = {\n id: 'console', title: 'Console', modes: ['cli'],\n conditions: [\n { kind: 'interface', interface: { tag: CONSOLE_INTERFACE_TAG } },\n { kind: 'service', implements: { tag: CONSOLE_INTERFACE_TAG } },\n ],\n configureCommand() {},\n open() { throw new Error('Use the attach command'); },\n createSession() { throw new Error('Consoles have no TUI view'); },\n};\n\n/** Console template instances in reflected schemas; tags are only discovery hints. */\nexport function consoleTargets(interfaces: readonly ResolvedViewInterface[]): ConsoleTarget[] {\n return interfaces.flatMap(listing => {\n const metadata = listing.schema[INTERFACE_TEMPLATES_EXTENSION] as InterfaceTemplatesMetadata | undefined;\n if (metadata === undefined) return [];\n validateInterfaceTemplates(listing.schema);\n return metadata.instances.flatMap(instance => {\n const template = metadata.templates[instance.template];\n if (template?.id !== consoleTemplate.id) return [];\n if (!interfaceTemplatesEqual(template, consoleTemplate)) {\n throw new Error(`${listing.interfaceId} uses an unsupported revision of the ${consoleTemplate.id} template`);\n }\n const method = (member: string) => {\n const name = interfaceTemplateMemberName(instance, member);\n if (listing.isDefault) return name;\n return listing.serviceId === '' ? `${listing.interfaceId}::${name}` : `${listing.serviceId}::${listing.interfaceId}::${name}`;\n };\n const params = instance.arguments.params;\n if (params === undefined) throw new Error(`Console instance \"${instance.name}\" is missing its params argument`);\n return [{\n serviceId: listing.serviceId, interfaceId: listing.interfaceId, instance: instance.name,\n infoMethod: method('info'), attachMethod: method('attach'), params,\n }];\n });\n });\n}\n\n/** List console targets without attaching: discovery uses directory tags, then reflection resolves instances. */\nexport async function listConsoleTargets(channel: CliChannel): Promise<string> {\n const discovery = await discoverViewTargets(channel, consoleDiscovery);\n const rows: string[] = [];\n for (const target of discovery.targets.filter(value => value.kind === 'service')) {\n const context = await loadViewTarget(channel, target, undefined, consoleDiscovery);\n for (const console of consoleTargets(context.interfaces)) {\n rows.push(`${console.serviceId || '<root>'} ${console.interfaceId} ${console.instance} ${JSON.stringify(console.params.schema)}`);\n }\n }\n return [\n rows.length === 0 ? 'No services offer linkrpc.console.' : 'SERVICE INTERFACE INSTANCE PARAMS',\n ...rows,\n ...discovery.warnings.map(warning => `warning: ${warning}`),\n ].join('\\n');\n}\n\n/** Attach to any service implementing the console template, selected by service, interface, and instance. */\nexport async function attachConsole(channel: CliChannel, options: AttachConsoleOptions): Promise<void> {\n const context = await resolveViewSelection(channel, consoleDiscovery, {\n service: options.serviceId, ...(options.interfaceId === undefined ? {} : { interface: options.interfaceId }),\n });\n const candidates = consoleTargets(context.interfaces)\n .filter(target => options.instance === undefined || target.instance === options.instance);\n if (candidates.length !== 1) {\n const names = consoleTargets(context.interfaces).map(target => `${target.interfaceId}#${target.instance}`).join(', ');\n throw new Error(candidates.length === 0\n ? `No console instance matches on \"${options.serviceId}\"${names ? ` (available: ${names})` : ''}`\n : `Several consoles are available (${names}); select one with --instance or --interface`);\n }\n const target = candidates[0]!;\n let params: unknown;\n try { params = JSON.parse(options.params ?? '{}'); }\n catch { throw new Error('--params must be valid JSON'); }\n const validation = createSchemaToZod(target.params.components?.schemas ?? {}).toZod(target.params.schema).safeParse(params);\n if (!validation.success) {\n throw new Error(`--params does not match the params of console \"${target.instance}\" `\n + `(${JSON.stringify(target.params.schema)}): ${validation.error.message}`);\n }\n const interactive = options.readOnly !== true;\n const size = interactive ? localTerminalSize() : undefined;\n const result = await runConsoleSession(onMessage => rawConsoleCall(channel, target.attachMethod, {\n params: params as JsonValue, interactive, ...(size ? { size } : {}),\n }, onMessage), {\n interactive, owner: false, reattachCommand: options.reattachCommand,\n ...(options.detachKeys ? { detachKeys: options.detachKeys } : {}),\n });\n if (!result.closedLocally && result.exit?.code) process.exitCode = result.exit.code;\n}\n\n/** Call a reflected attach method on the raw channel, validating every stream message against the protocol. */\nfunction rawConsoleCall(\n channel: Pick<CliChannel, 'sendRequestWithStream'>,\n method: string,\n params: ConsoleAttachParams & { readonly params: JsonValue },\n onMessage: (message: ConsoleServerMessage) => void,\n): ConsoleCall {\n const call = channel.sendRequestWithStream(method, params as JsonValue, {\n onStreamMessage: payload => {\n const message = consoleServerMessageSchema.safeParse(payload);\n onMessage(message.success ? message.data : { t: 'notice', text: `Ignored an invalid console message: ${message.error.message}` });\n },\n });\n const result = call.result.then(value => consoleAttachResultSchema.parse(value));\n void result.finally(() => call.dispose?.()).catch(() => {});\n return {\n then: (onFulfilled, onRejected) => result.then(onFulfilled, onRejected),\n send: message => call.send(message as JsonValue),\n cancel: () => call.cancel('detached'),\n };\n}\n","import { readFileSync } from \"node:fs\";\n\n/**\n * Read params either from a `--params <json>` argument (treated as inline\n * JSON) or `--params -` (read from stdin). `undefined` if neither was given.\n */\nexport function readParamsArg(value: string | undefined): unknown {\n if (value === undefined) return undefined;\n const text = value === \"-\" ? readFileSync(0, \"utf8\") : value;\n const trimmed = text.trim();\n if (trimmed.length === 0) return undefined;\n try {\n return JSON.parse(trimmed);\n } catch (e) {\n throw new Error(`--params: invalid JSON (${(e as Error).message})`);\n }\n}\n\nexport function formatJson(v: unknown): string {\n if (v === undefined) return \"undefined\";\n return JSON.stringify(v, null, 2);\n}\n\n/** Stringify a value for one-line tabular output. */\nexport function oneLine(v: unknown): string {\n if (v === undefined) return \"\";\n if (typeof v === \"string\") return v;\n return JSON.stringify(v);\n}\n","import { isAssignable, matchParams, schemaToZod, type LinkRpcInterfaceSchema, type LinkRpcJsonSchema, type ParamMatcher } from '@hediet/linkrpc';\nimport { findCoveringCapabilities, type HubAccessDuration, type HubAccessPermission } from '@hediet/linkrpc/hub/common';\nimport { fetchDefaults, findMethodInSchema, type CliChannel, type SigningSession } from '@hediet/linkrpc-client-internal';\nimport { z } from 'zod';\nimport type { MethodRefWithOptHash } from '../methodRef';\nimport { parseParamOverride } from '../paramParsing';\nimport { formatJson } from '../output';\n\nconst matcherSchema = z.union([\n z.strictObject({ exact: z.json() }),\n z.strictObject({ enum: z.array(z.json()).min(1) }),\n z.strictObject({ prefix: z.string() }),\n z.strictObject({ subsetOf: z.array(z.string()) }),\n z.strictObject({ any: z.literal(true) }),\n]);\n\nexport interface RequestCallCapabilityOptions {\n readonly allowParams?: readonly string[];\n readonly duration?: HubAccessDuration;\n}\n\nexport async function requestCallCapability(\n channel: CliChannel,\n session: SigningSession,\n ref: MethodRefWithOptHash,\n params: unknown,\n schema: LinkRpcInterfaceSchema,\n opts: RequestCallCapabilityOptions,\n): Promise<string> {\n const method = findMethodInSchema(schema, ref.methodName);\n if (method === undefined) throw new Error(`Unknown method ${ref.getMethodOnWire()}.`);\n const matchers = createParamMatchers(params, opts.allowParams ?? [], method.params, schema.components?.schemas);\n const defaults = ref.interfaceId === undefined ? await fetchDefaults(channel) : undefined;\n const permission: HubAccessPermission = {\n target: {\n serviceId: { exact: ref.serviceId ?? defaults?.serviceId ?? '' },\n interfaceId: { exact: ref.interfaceId ?? schema.id },\n members: [{ exact: ref.methodName }],\n ...(ref.hash !== undefined ? { interfaceHash: ref.hash } : {}),\n },\n canInvoke: true,\n params: matchers,\n };\n const coverageOptions = { audience: session.principal.id, freshnessMarginMs: 2000 };\n const cached = findCoveringCapabilities(session.listGrants(), [permission], coverageOptions);\n if (cached !== undefined) {\n return formatJson({ status: 'granted', reused: true, capabilities: cached });\n }\n const result = await session.requestAccess({\n consumer: { name: 'linkrpc-cli', purpose: `Invoke ${ref.getMethodOnWire()}.` },\n permissions: [permission],\n duration: opts.duration ?? 'persistent',\n });\n if (result.status !== 'granted') {\n const reason = 'reason' in result ? result.reason : undefined;\n throw new Error(`Capability request ${result.status}${reason ? `: ${reason}` : '.'}`);\n }\n if (findCoveringCapabilities(session.listGrants(), [permission], coverageOptions) === undefined) {\n throw new Error('The granted capabilities do not cover the requested durable scope.');\n }\n return formatJson({ ...result, reused: false });\n}\n\nexport function createParamMatchers(\n params: unknown,\n allowParams: readonly string[],\n schema: LinkRpcJsonSchema,\n components: Record<string, LinkRpcJsonSchema> = {},\n): Record<string, ParamMatcher> {\n if (params !== undefined && (params === null || typeof params !== 'object' || Array.isArray(params))) {\n throw new Error('Capability requests require object parameters.');\n }\n const actual: Record<string, unknown> = params === undefined ? {} : Object.fromEntries(Object.entries(params));\n const matchers: Record<string, ParamMatcher> = Object.fromEntries(\n Object.entries(actual).map(([key, value]) => [key, { exact: value }]),\n );\n const seen = new Set<string>();\n for (const raw of allowParams) {\n const { path, value } = parseParamOverride(raw);\n if (path.length !== 1) throw new Error('--cap:allow-param only supports top-level parameter names.');\n const key = path[0];\n if (seen.has(key)) throw new Error(`Duplicate --cap:allow-param for ${key}.`);\n seen.add(key);\n const parsed = matcherSchema.safeParse(value);\n if (!parsed.success) throw new Error(`Invalid --cap:allow-param ${key}: ${parsed.error.message}`);\n matchers[key] = parsed.data;\n }\n const properties = Object.fromEntries(\n Object.entries(matchers).map(([key, matcher]) => [key, matcherToSchema(matcher)]),\n );\n if (!isAssignable({\n type: 'object', properties, required: Object.keys(properties), additionalProperties: false,\n }, schema, { schemas: components })) {\n throw new Error('--cap:allow-param scope does not match the method parameter schema.');\n }\n const validator = schemaToZod(schema, components);\n const samples = [actual];\n for (const [key, matcher] of Object.entries(matchers)) {\n const values = 'exact' in matcher ? [matcher.exact] : 'enum' in matcher ? matcher.enum\n : 'subsetOf' in matcher ? [[], ...matcher.subsetOf.map(value => [value])] : [];\n for (const value of values) samples.push({ ...actual, [key]: value });\n }\n for (const sample of samples) {\n const validated = validator.safeParse(sample);\n if (!validated.success) throw new Error(`Capability parameter schema validation failed: ${validated.error.message}`);\n }\n const matched = matchParams(matchers, actual);\n if (!matched.ok) throw new Error(`Parameters do not match --cap:allow-param: ${matched.reason}`);\n return matchers;\n}\n\nfunction matcherToSchema(matcher: ParamMatcher): LinkRpcJsonSchema {\n if ('any' in matcher) return true;\n if ('prefix' in matcher) return { type: 'string' };\n if ('subsetOf' in matcher) {\n return { type: 'array', items: { enum: matcher.subsetOf } };\n }\n if ('enum' in matcher) return { enum: z.array(z.json()).parse(matcher.enum) };\n return { const: z.json().parse(matcher.exact) };\n}\n\nexport function listCaps(session: SigningSession, json: boolean): string {\n const capabilities = session.listGrants();\n return json ? formatJson({ principal: session.principal.id, capabilities })\n : `principal: ${session.principal.id}\\n${capabilities.length === 0 ? 'No stored capabilities.' : formatJson(capabilities)}`;\n}\n","/**\n * \"Did you mean…\" suggestions for failed `hub call` / `hub notify` invocations.\n *\n * Drives off a static snapshot of the hub (`HubSnapshot`) so the formatter is\n * pure-functional and exhaustively testable with literal strings. A snapshot\n * is built by walking the bus once (`HubSnapshot.load`) on the error path.\n *\n * The matrix is resolved left-to-right (serviceId, interfaceId, method): the\n * first token that doesn't resolve dictates the suggestion scope, and we never\n * propose replacements for positions to its left.\n */\nimport { MethodRefWithOptHash } from './methodRef';\nimport {\n fetchSchema,\n walkHub,\n type CliChannel,\n} from '@hediet/linkrpc-client-internal';\n\n// ---------------------------------------------------------------------------\n// HubSnapshot\n// ---------------------------------------------------------------------------\n\nexport interface SnapshotEntry {\n /** Empty string = root. */\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly methods: readonly string[];\n}\n\nconst _SYSTEM_PREFIX = 'hubrpc.';\n\nfunction _isSystemInterface(id: string): boolean {\n return id.startsWith(_SYSTEM_PREFIX);\n}\n\nfunction _isUserInterface(id: string): boolean {\n return !_isSystemInterface(id);\n}\n\n/**\n * Indexed view of the bus's directory + per-interface methods. Constructed\n * directly from a list of entries (tests) or by walking a live channel\n * (`HubSnapshot.load`). Read-only after construction.\n */\nexport class HubSnapshot {\n private readonly _byService = new Map<string, Map<string, SnapshotEntry>>();\n private readonly _byInterface = new Map<string, string[]>();\n private readonly _byMethodName = new Map<string, { serviceId: string; interfaceId: string; }[]>();\n\n constructor(public readonly entries: readonly SnapshotEntry[]) {\n for (const e of entries) {\n let byIface = this._byService.get(e.serviceId);\n if (!byIface) {\n byIface = new Map();\n this._byService.set(e.serviceId, byIface);\n }\n byIface.set(e.interfaceId, e);\n\n const hosts = this._byInterface.get(e.interfaceId) ?? [];\n if (!hosts.includes(e.serviceId)) hosts.push(e.serviceId);\n this._byInterface.set(e.interfaceId, hosts);\n\n for (const m of e.methods) {\n const locs = this._byMethodName.get(m) ?? [];\n locs.push({ serviceId: e.serviceId, interfaceId: e.interfaceId });\n this._byMethodName.set(m, locs);\n }\n }\n }\n\n /** All serviceIds present on the bus, in encounter order (\"\" = root). */\n services(): readonly string[] {\n return [...this._byService.keys()];\n }\n\n /** All distinct interface ids (system + user), in encounter order. */\n interfaces(): readonly string[] {\n return [...this._byInterface.keys()];\n }\n\n interfacesOnService(serviceId: string): readonly string[] {\n const m = this._byService.get(serviceId);\n return m ? [...m.keys()] : [];\n }\n\n servicesHostingInterface(interfaceId: string): readonly string[] {\n return this._byInterface.get(interfaceId) ?? [];\n }\n\n methodsOn(serviceId: string, interfaceId: string): readonly string[] {\n return this._byService.get(serviceId)?.get(interfaceId)?.methods ?? [];\n }\n\n locationsOfMethod(name: string): readonly { serviceId: string; interfaceId: string; }[] {\n return this._byMethodName.get(name) ?? [];\n }\n\n /**\n * Walk the live bus once and fetch the schema for every (service, interface)\n * pair in parallel. Failures on individual schema fetches are absorbed —\n * the affected entry just ends up with `methods: []`, so it still\n * participates in service/interface-level suggestions.\n */\n static async load(channel: CliChannel): Promise<HubSnapshot> {\n const listings = await walkHub(channel);\n const entries = await Promise.all(listings.map(async (l): Promise<SnapshotEntry> => {\n try {\n const schema = await fetchSchema(\n channel,\n l.interfaceId,\n l.hash,\n l.serviceId || undefined,\n );\n return {\n serviceId: l.serviceId,\n interfaceId: l.interfaceId,\n hash: l.hash,\n methods: Object.keys(schema.methods),\n };\n } catch {\n return {\n serviceId: l.serviceId,\n interfaceId: l.interfaceId,\n hash: l.hash,\n methods: [],\n };\n }\n }));\n return new HubSnapshot(entries);\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatSuggestion (entry point)\n// ---------------------------------------------------------------------------\n\nexport interface SuggestionInput {\n readonly ref: MethodRefWithOptHash;\n readonly snapshot: HubSnapshot;\n /** Verb embedded in copy-paste lines (`hub call` vs `hub notify`). */\n readonly verb: 'call' | 'notify';\n /** CLI binary name; defaults to `hub`. */\n readonly tool?: string;\n}\n\ninterface _Ctx {\n ref: MethodRefWithOptHash;\n snapshot: HubSnapshot;\n verb: 'call' | 'notify';\n tool: string;\n}\n\n/**\n * Compose a multi-line \"Did you mean…\" message tailored to the failed ref.\n * The returned string has no trailing newline and no `linkrpc:` prefix (the\n * outer error path adds those).\n */\nexport function formatSuggestion(input: SuggestionInput): string {\n const ctx: _Ctx = {\n ref: input.ref,\n snapshot: input.snapshot,\n verb: input.verb,\n tool: input.tool ?? 'hub',\n };\n if (ctx.ref.serviceId !== undefined && ctx.ref.interfaceId !== undefined) {\n return _suggestForm3(ctx);\n }\n if (ctx.ref.interfaceId !== undefined) {\n return _suggestForm2(ctx);\n }\n return _suggestForm1(ctx);\n}\n\nfunction _qualify(ctx: _Ctx, s: string, i: string, m: string): string {\n return `${ctx.tool} ${ctx.verb} ${s}::${i}::${m}`;\n}\n\n// ---------------------------------------------------------------------------\n// Form 1: `<method>` (bare token, no preset)\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm1(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const token = ref.methodName;\n\n // A1: token is itself a serviceId\n if (token !== '' && snapshot.services().includes(token)) {\n const samples = _sampleCallsForService(ctx, token, 3);\n const lines = [`\"${token}\" is a serviceId, not a method.`];\n lines.push(' See its interfaces:');\n lines.push(` ${ctx.tool} ls --service ${token}`);\n if (samples.length > 0) {\n lines.push(' Or call one:');\n for (const s of samples) lines.push(` ${s}`);\n }\n return lines.join('\\n');\n }\n\n // A2: token is an interfaceId\n if (snapshot.interfaces().includes(token) && _isUserInterface(token)) {\n const hosts = snapshot.servicesHostingInterface(token).filter((s) => s !== '');\n const samples = _sampleCallsForInterface(ctx, token, 3);\n const lines = [\n `\"${token}\" is an interface, not a method. It's hosted on services: ${hosts.join(', ')}.`,\n ];\n if (samples.length > 0) {\n lines.push(' Try a call:');\n for (const s of samples) lines.push(` ${s}`);\n }\n return lines.join('\\n');\n }\n\n // A3/A4: token is exactly a method name on one or more interfaces\n const locs = snapshot\n .locationsOfMethod(token)\n .filter((l) => _isUserInterface(l.interfaceId));\n if (locs.length > 0) {\n const lines = [`\"${token}\" is not callable without an interface (no preset is set).`];\n lines.push(' Did you mean:');\n for (const l of locs.slice(0, 5)) {\n lines.push(` ${_qualify(ctx, l.serviceId, l.interfaceId, token)}`);\n }\n return lines.join('\\n');\n }\n\n // A5/A6/A7: fuzzy fallback\n return _suggestForm1Fuzzy(ctx);\n}\n\nfunction _suggestForm1Fuzzy(ctx: _Ctx): string {\n const { snapshot } = ctx;\n const token = ctx.ref.methodName;\n\n const methodHits = _rankAllMethods(snapshot, token, 3);\n const ifaceHits = _rankAllInterfaces(snapshot, token, 3);\n const svcHits = _rankServices(snapshot, token, 3);\n\n const lines = [`\"${token}\" matches no known service, interface, or method.`];\n if (methodHits.length > 0) {\n lines.push(' Closest methods:');\n for (const h of methodHits) {\n lines.push(` ${_qualify(ctx, h.serviceId, h.interfaceId, h.name)}`);\n }\n }\n if (ifaceHits.length > 0) {\n lines.push(' Closest interfaces:');\n for (const id of ifaceHits) {\n const sampleSvc = snapshot\n .servicesHostingInterface(id)\n .find((s) => s !== '') ?? snapshot.servicesHostingInterface(id)[0];\n lines.push(` ${id} (try ${ctx.tool} ${ctx.verb} ${sampleSvc ?? ''}::${id}::<method>)`);\n }\n }\n if (svcHits.length > 0) {\n lines.push(' Closest services:');\n for (const s of svcHits) {\n lines.push(` ${s} (try ${ctx.tool} ls --service ${s})`);\n }\n }\n if (methodHits.length === 0 && ifaceHits.length === 0 && svcHits.length === 0) {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Form 2: `<interface>::<method>`\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm2(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const iface = ref.interfaceId!;\n const method = ref.methodName;\n const hostsOfIface = snapshot.servicesHostingInterface(iface);\n\n if (hostsOfIface.length === 0) {\n // Interface unknown.\n // B3: first token is actually a serviceId\n if (iface !== '' && snapshot.services().includes(iface)) {\n // B3a: the second token is an exact method name on that service\n // (e.g. `azure-cli::runCommand` → fully-qualified suggestion).\n const locs = snapshot\n .locationsOfMethod(method)\n .filter((l) => l.serviceId === iface && _isUserInterface(l.interfaceId));\n if (locs.length > 0) {\n const lines = [\n `Interface \"${method}\" not found on service \"${iface}\", `\n + `but \"${method}\" is a method name there.`,\n ];\n lines.push(' Did you mean:');\n for (const l of locs.slice(0, 3)) {\n lines.push(` ${_qualify(ctx, l.serviceId, l.interfaceId, method)}`);\n }\n return lines.join('\\n');\n }\n\n // B3b: prefix or full enumeration — list interfaces on the service.\n // Typing `vscode::vscode.` is navigation, not a typo; show what's\n // available rather than guessing methods.\n return _formatInterfaceListOnService(ctx, iface, method);\n }\n\n // B2: fuzzy interfaces, boost ones where `method` exists\n const candidates = _rankInterfacesWithMethodBoost(snapshot, iface, method, 3);\n const lines = [`Interface \"${iface}\" not found.`];\n if (candidates.length > 0) {\n lines.push(' Did you mean:');\n for (const c of candidates) {\n lines.push(` ${_qualify(ctx, c.serviceId, c.interfaceId, c.methodToTry)}`);\n }\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n }\n\n // Interface valid on >=1 service. Method missing on all of them.\n // B1/B4: fuzzy methods across hosts\n const fuzzy = _rankMethodsOnInterface(snapshot, iface, method, 3);\n if (fuzzy.length > 0) {\n const where = hostsOfIface.length === 1 ? ` (service: ${hostsOfIface[0]})` : '';\n const lines = [`Method \"${method}\" not found on interface \"${iface}\"${where}.`];\n lines.push(' Did you mean:');\n for (const f of fuzzy) {\n lines.push(` ${_qualify(ctx, f.serviceId, iface, f.methodName)}`);\n }\n return lines.join('\\n');\n }\n\n // B5: enumerate everything available under this interface\n const lines = [`Method \"${method}\" not found on interface \"${iface}\".`];\n lines.push(' Available methods:');\n let count = 0;\n for (const s of hostsOfIface) {\n for (const m of snapshot.methodsOn(s, iface)) {\n if (count >= 12) break;\n lines.push(` ${_qualify(ctx, s, iface, m)}`);\n count++;\n }\n if (count >= 12) break;\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Form 3: `<svc>::<iface>::<method>`\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm3(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const svc = ref.serviceId!;\n const iface = ref.interfaceId!;\n const method = ref.methodName;\n\n // C4/C7: service unknown\n if (!snapshot.services().includes(svc)) {\n const hits = _rankServices(snapshot, svc, 3, (cand) => {\n const ifaces = snapshot.interfacesOnService(cand);\n if (ifaces.includes(iface) && snapshot.methodsOn(cand, iface).includes(method)) {\n return 200;\n }\n if (ifaces.includes(iface)) return 100;\n return 0;\n });\n const lines = [`Service \"${svc}\" not found.`];\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n const ifacesOnH = snapshot.interfacesOnService(h);\n if (ifacesOnH.includes(iface) && snapshot.methodsOn(h, iface).includes(method)) {\n lines.push(` ${_qualify(ctx, h, iface, method)}`);\n } else {\n lines.push(` ${h} (try ${ctx.tool} ls --service ${h})`);\n }\n }\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n }\n\n // Service valid; check interface.\n const ifacesOnSvc = snapshot.interfacesOnService(svc);\n if (!ifacesOnSvc.includes(iface)) {\n // C2a: navigation-style input — `iface` is a prefix of one or more\n // interfaces on this service (e.g. `vscode::vscode.::login`). List the\n // matches, using `method` as the sample call when it exists on a\n // match, else the first method of each.\n const prefixMatches = _prefixMatchesOnService(snapshot, svc, iface);\n if (prefixMatches.length > 0) {\n const lines = [\n `Interface \"${iface}\" not found on service \"${svc}\". `\n + `Interfaces starting with \"${iface}\":`,\n ];\n for (const id of prefixMatches.slice(0, 10)) {\n const sampleMethod = snapshot.methodsOn(svc, id).includes(method)\n ? method\n : (snapshot.methodsOn(svc, id)[0] ?? '<method>');\n lines.push(` ${_qualify(ctx, svc, id, sampleMethod)}`);\n }\n const otherHosts = snapshot\n .servicesHostingInterface(iface)\n .filter((s) => s !== svc && s !== '');\n if (otherHosts.length > 0) {\n lines.push(` Note: \"${iface}\" also exists on service \"${otherHosts[0]}\".`);\n }\n return lines.join('\\n');\n }\n\n // C2/C3\n const lines = [`Interface \"${iface}\" not found on service \"${svc}\".`];\n\n // C2: fuzzy interfaces on THIS service, boost those hosting `method`\n const hits = _rankInterfacesOnService(snapshot, svc, iface, method, 3);\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n const methodOk = snapshot.methodsOn(svc, h).includes(method);\n lines.push(` ${_qualify(ctx, svc, h, methodOk ? method : '<method>')}`);\n }\n }\n\n // C3: footnote — interface exists on another service?\n const otherHosts = snapshot\n .servicesHostingInterface(iface)\n .filter((s) => s !== svc && s !== '');\n const userIfacesOnSvc = ifacesOnSvc.filter(_isUserInterface);\n if (otherHosts.length > 0) {\n if (hits.length === 0 && userIfacesOnSvc.length > 0) {\n lines.push(` Interfaces on \"${svc}\": ${userIfacesOnSvc.join(', ')}`);\n }\n const otherSvc = otherHosts[0];\n const sampleMethod = snapshot.methodsOn(otherSvc, iface).includes(method)\n ? method\n : (snapshot.methodsOn(otherSvc, iface)[0] ?? '<method>');\n lines.push(` Note: \"${iface}\" exists on service \"${otherSvc}\". Did you mean:`);\n lines.push(` ${_qualify(ctx, otherSvc, iface, sampleMethod)}`);\n } else if (hits.length === 0) {\n if (userIfacesOnSvc.length > 0) {\n lines.push(` Interfaces on \"${svc}\": ${userIfacesOnSvc.join(', ')}`);\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls --service ${svc}\\``);\n }\n }\n return lines.join('\\n');\n }\n\n // C1: svc + iface valid; method missing\n const methods = snapshot.methodsOn(svc, iface);\n const hits = _rankNames(methods, method, 3);\n const lines = [`Method \"${method}\" not found on ${svc}::${iface}.`];\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n lines.push(` ${_qualify(ctx, svc, iface, h)}`);\n }\n } else if (methods.length > 0) {\n lines.push(' Available methods:');\n for (const m of methods.slice(0, 12)) {\n lines.push(` ${_qualify(ctx, svc, iface, m)}`);\n }\n } else {\n lines.push(` Tip: this interface has no methods declared.`);\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Ranking / fuzzy primitives\n// ---------------------------------------------------------------------------\n\nfunction _threshold(s: string): number {\n return Math.max(1, Math.ceil(s.length / 3));\n}\n\n/** Levenshtein distance between two short strings. O(m*n) time, O(n) space. */\nfunction _lev(a: string, b: string): number {\n const m = a.length, n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n const dp = new Array<number>(n + 1);\n for (let j = 0; j <= n; j++) dp[j] = j;\n for (let i = 1; i <= m; i++) {\n let prev = dp[0];\n dp[0] = i;\n for (let j = 1; j <= n; j++) {\n const tmp = dp[j];\n dp[j] = a[i - 1] === b[j - 1] ? prev : Math.min(prev, dp[j], dp[j - 1]) + 1;\n prev = tmp;\n }\n }\n return dp[n];\n}\n\ninterface _Ranked<T> { item: T; dist: number; boost: number; }\n\nfunction _rank<T>(\n items: readonly T[],\n key: (t: T) => string,\n query: string,\n limit: number,\n boost?: (t: T) => number,\n): T[] {\n const lower = query.toLowerCase();\n const thr = _threshold(query);\n const ranked: _Ranked<T>[] = [];\n for (const it of items) {\n const k = key(it);\n const d = _lev(k.toLowerCase(), lower);\n if (d > thr) continue;\n ranked.push({ item: it, dist: d, boost: boost ? boost(it) : 0 });\n }\n ranked.sort((a, b) =>\n (a.dist - b.dist)\n || (b.boost - a.boost)\n || key(a.item).localeCompare(key(b.item))\n );\n return ranked.slice(0, limit).map((r) => r.item);\n}\n\nfunction _rankNames(\n names: readonly string[],\n query: string,\n limit: number,\n boost?: (n: string) => number,\n): string[] {\n return _rank(names, (n) => n, query, limit, boost);\n}\n\nfunction _rankServices(\n snapshot: HubSnapshot,\n query: string,\n limit: number,\n boost?: (s: string) => number,\n): string[] {\n return _rankNames(snapshot.services().filter((s) => s !== ''), query, limit, boost);\n}\n\nfunction _rankAllInterfaces(snapshot: HubSnapshot, query: string, limit: number): string[] {\n return _rankNames(snapshot.interfaces().filter(_isUserInterface), query, limit);\n}\n\nfunction _rankAllMethods(\n snapshot: HubSnapshot,\n query: string,\n limit: number,\n): readonly { name: string; serviceId: string; interfaceId: string; }[] {\n const all: { name: string; serviceId: string; interfaceId: string; }[] = [];\n for (const e of snapshot.entries) {\n if (!_isUserInterface(e.interfaceId)) continue;\n for (const m of e.methods) {\n all.push({ name: m, serviceId: e.serviceId, interfaceId: e.interfaceId });\n }\n }\n return _rank(all, (x) => x.name, query, limit);\n}\n\nfunction _rankMethodsOnInterface(\n snapshot: HubSnapshot,\n interfaceId: string,\n query: string,\n limit: number,\n): readonly { methodName: string; serviceId: string; }[] {\n const all: { methodName: string; serviceId: string; }[] = [];\n for (const s of snapshot.servicesHostingInterface(interfaceId)) {\n for (const m of snapshot.methodsOn(s, interfaceId)) {\n all.push({ methodName: m, serviceId: s });\n }\n }\n return _rank(all, (x) => x.methodName, query, limit);\n}\n\nfunction _rankInterfacesWithMethodBoost(\n snapshot: HubSnapshot,\n query: string,\n methodName: string,\n limit: number,\n): readonly { interfaceId: string; serviceId: string; methodToTry: string; }[] {\n const ifaces = snapshot.interfaces().filter(_isUserInterface);\n const ranked = _rankNames(ifaces, query, limit, (id) => {\n for (const s of snapshot.servicesHostingInterface(id)) {\n if (snapshot.methodsOn(s, id).includes(methodName)) return 100;\n }\n return 0;\n });\n return ranked.map((id) => {\n const hosts = snapshot.servicesHostingInterface(id);\n const withMethod = hosts.find(\n (s) => s !== '' && snapshot.methodsOn(s, id).includes(methodName),\n );\n const fallback = hosts.find((s) => s !== '') ?? hosts[0] ?? '';\n const svc = withMethod ?? fallback;\n const m = snapshot.methodsOn(svc, id).includes(methodName)\n ? methodName\n : (snapshot.methodsOn(svc, id)[0] ?? '<method>');\n return { interfaceId: id, serviceId: svc, methodToTry: m };\n });\n}\n\nfunction _rankInterfacesOnService(\n snapshot: HubSnapshot,\n serviceId: string,\n query: string,\n methodName: string,\n limit: number,\n): string[] {\n const ifaces = snapshot.interfacesOnService(serviceId).filter(_isUserInterface);\n return _rankNames(ifaces, query, limit, (id) =>\n snapshot.methodsOn(serviceId, id).includes(methodName) ? 100 : 0\n );\n}\n\n// ---------------------------------------------------------------------------\n// Sample call generators\n// ---------------------------------------------------------------------------\n\n/**\n * Interface ids on `serviceId` whose name starts with `prefix`\n * (case-insensitive). System interfaces (`linkrpc.*`) are excluded — they're\n * noise for navigation. Returns `[]` for an empty `prefix` so the caller can\n * distinguish \"no prefix typed\" from \"prefix had matches\".\n */\nfunction _prefixMatchesOnService(\n snapshot: HubSnapshot,\n serviceId: string,\n prefix: string,\n): string[] {\n if (prefix === '') return [];\n const lower = prefix.toLowerCase();\n return snapshot\n .interfacesOnService(serviceId)\n .filter((id) => _isUserInterface(id) && id.toLowerCase().startsWith(lower));\n}\n\n/**\n * Render an interface-list response for `serviceId`. When `prefix` is a real\n * prefix of one or more interfaces, only those are shown; otherwise all user\n * interfaces on the service are listed. Sample method per row defaults to the\n * first declared method.\n */\nfunction _formatInterfaceListOnService(\n ctx: _Ctx,\n serviceId: string,\n prefix: string,\n): string {\n const allUserIfaces = ctx.snapshot\n .interfacesOnService(serviceId)\n .filter(_isUserInterface);\n const prefixMatches = _prefixMatchesOnService(ctx.snapshot, serviceId, prefix);\n const matches = prefixMatches.length > 0 ? prefixMatches : allUserIfaces;\n\n const header = prefixMatches.length > 0\n ? `Interfaces on \"${serviceId}\" starting with \"${prefix}\":`\n : (prefix !== ''\n ? `Interface \"${prefix}\" not found on service \"${serviceId}\". `\n + `Interfaces on \"${serviceId}\":`\n : `Interfaces on \"${serviceId}\":`);\n\n const lines = [header];\n if (matches.length === 0) {\n lines.push(` Tip: run \\`${ctx.tool} ls --service ${serviceId}\\``);\n return lines.join('\\n');\n }\n for (const id of matches.slice(0, 10)) {\n const sampleMethod = ctx.snapshot.methodsOn(serviceId, id)[0] ?? '<method>';\n lines.push(` ${_qualify(ctx, serviceId, id, sampleMethod)}`);\n }\n return lines.join('\\n');\n}\n\nfunction _sampleCallsForService(ctx: _Ctx, serviceId: string, limit: number): string[] {\n const { snapshot } = ctx;\n const out: string[] = [];\n for (const iface of snapshot.interfacesOnService(serviceId)) {\n if (!_isUserInterface(iface)) continue;\n for (const m of snapshot.methodsOn(serviceId, iface)) {\n out.push(_qualify(ctx, serviceId, iface, m));\n if (out.length >= limit) return out;\n }\n }\n return out;\n}\n\nfunction _sampleCallsForInterface(ctx: _Ctx, interfaceId: string, limit: number): string[] {\n const { snapshot } = ctx;\n const out: string[] = [];\n for (const s of snapshot.servicesHostingInterface(interfaceId)) {\n if (s === '') continue;\n for (const m of snapshot.methodsOn(s, interfaceId)) {\n out.push(_qualify(ctx, s, interfaceId, m));\n if (out.length >= limit) return out;\n }\n }\n return out;\n}\n","import type { LinkRpcInterfaceSchema } from '@hediet/linkrpc';\nimport {\n type CliChannel,\n fetchDefaults,\n fetchSchema,\n} from '@hediet/linkrpc-client-internal';\nimport type { MethodRefWithOptHash } from './methodRef';\n\n/**\n * Fetch the schema addressed by a method reference. Form-1 references use the\n * connection preset for lookup, but remain bare when sent on the wire.\n */\nexport async function fetchSchemaForMethodRef(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n): Promise<LinkRpcInterfaceSchema | undefined> {\n if (ref.interfaceId !== undefined) {\n return fetchSchema(channel, ref.interfaceId, ref.hash, ref.serviceId);\n }\n\n const defaults = await fetchDefaults(channel);\n if (defaults.interfaceId === undefined) {\n return undefined;\n }\n return fetchSchema(\n channel,\n defaults.interfaceId,\n ref.hash ?? defaults.hash,\n defaults.serviceId,\n );\n}\n","import { ErrorCode, type JsonValue, RpcError } from '@hediet/linkrpc';\nimport { MethodRefWithOptHash } from '../methodRef';\nimport { formatJson, readParamsArg } from '../output';\nimport { mergeParams } from '../paramParsing';\nimport { type CliChannel, type SigningSession, findMethodInSchema } from '@hediet/linkrpc-client-internal';\nimport { requestCallCapability, type RequestCallCapabilityOptions } from './caps';\nimport { formatSuggestion, HubSnapshot } from '../suggest';\nimport {\n describeObjectParams,\n describeSchema,\n explainValidation,\n validateValueAgainstSchema,\n} from '../validation';\nimport type { LinkRpcInterfaceSchema as SvcInterfaceSchema, MethodSchema } from '@hediet/linkrpc';\nimport { fetchSchemaForMethodRef } from '../schemaLookup';\n\nexport interface CallCommandOptions extends RequestCallCapabilityOptions {\n /** Full `[svc::][iface::]method[@hash]` reference. */\n readonly methodRef: string;\n /** Raw `--params <json>` value, or \"-\" for stdin. */\n readonly paramsArg?: string;\n readonly paramOverrides?: readonly string[];\n /** Skip schema-based validation. Default: validate. */\n readonly noValidate?: boolean;\n /** Schema lookup policy. `noValidate` takes precedence when set. */\n readonly validation?: 'auto' | 'required' | 'off';\n readonly json?: boolean;\n readonly requestCap?: boolean;\n readonly capabilityOnly?: boolean;\n readonly signingSession?: SigningSession;\n /**\n * Invoked for every server→client stream message (`$stream::send`) that\n * arrives while the call is in flight. Defaults to writing each chunk to\n * stderr (one line each) so streamed progress shows live without\n * polluting the stdout result. Pass a custom sink in tests.\n */\n readonly onStreamChunk?: (payload: JsonValue) => void;\n}\n\nexport async function callCommand(channel: CliChannel, opts: CallCommandOptions): Promise<string> {\n const ref = MethodRefWithOptHash.parseMethodRef(opts.methodRef);\n const baseParams = readParamsArg(opts.paramsArg);\n const params = mergeParams({ base: baseParams, overrides: opts.paramOverrides });\n\n const requestCap = opts.requestCap === true || opts.capabilityOnly === true;\n if (!requestCap && opts.allowParams !== undefined) {\n throw new Error('--cap:allow-param requires --cap:request.');\n }\n if (requestCap && (opts.noValidate || opts.validation === 'off')) {\n throw new Error('Capability requests require schema validation; remove --no-validate/--validation off.');\n }\n if (requestCap && opts.signingSession === undefined) {\n throw new Error('Capability requests require a signed LinkRPC connection.');\n }\n const onStreamChunk = opts.onStreamChunk ?? writeChunkToStderr;\n try {\n const validation = requestCap ? 'required' : opts.noValidate ? 'off' : (opts.validation ?? 'required');\n const schema = validation === 'off' ? undefined : await validateParams(channel, ref, params, 'call', validation);\n if (requestCap) {\n if (schema === undefined || opts.signingSession === undefined) {\n throw new Error('Capability requests require a method schema and signing session.');\n }\n const result = await requestCallCapability(channel, opts.signingSession, ref, params, schema, opts);\n if (opts.capabilityOnly) return result;\n }\n // Always use the streaming send path: it behaves identically to a plain\n // request when no stream messages arrive, and surfaces them live when\n // the method does stream (e.g. an interactive `login` device-code\n // prompt). The final result is the request's response.\n const call = channel.sendRequestWithStream(ref.getMethodOnWire(), params as never, {\n onStreamMessage: onStreamChunk,\n ...(opts.signingSession !== undefined && ref.hash !== undefined ? { interfaceHash: ref.hash } : {}),\n });\n const result = await call.result;\n return opts.json !== false ? formatJson(result) : String(result);\n } catch (e) {\n if (e instanceof RpcError && e.code === ErrorCode.methodNotFound) {\n await _failWithSuggestion(channel, ref, 'call');\n }\n if (e instanceof RpcError) throw formatRpcError(e);\n throw e;\n }\n}\n\n/**\n * Default stream sink: one line per chunk on stderr. Strings pass through\n * verbatim; structured payloads are JSON-encoded. stderr (not stdout) keeps\n * `call … | jq` clean while still showing live progress.\n */\nfunction writeChunkToStderr(payload: JsonValue): void {\n const text = typeof payload === 'string' ? payload : JSON.stringify(payload);\n process.stderr.write(text + '\\n');\n}\n\nexport interface NotifyCommandOptions extends CallCommandOptions { }\n\nexport async function notifyCommand(channel: CliChannel, opts: NotifyCommandOptions): Promise<string> {\n const ref = MethodRefWithOptHash.parseMethodRef(opts.methodRef);\n const baseParams = readParamsArg(opts.paramsArg);\n const params = mergeParams({ base: baseParams, overrides: opts.paramOverrides });\n const validation = opts.noValidate ? 'off' : (opts.validation ?? 'required');\n if (validation !== 'off') await validateParams(channel, ref, params, 'notify', validation);\n await channel.sendNotification(ref.getMethodOnWire(), params as never);\n return '(notification sent)';\n}\n\nasync function validateParams(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n params: unknown,\n verb: 'call' | 'notify',\n validation: 'auto' | 'required',\n): Promise<SvcInterfaceSchema | undefined> {\n let schema: SvcInterfaceSchema | undefined;\n try {\n schema = await fetchSchemaForMethodRef(channel, ref);\n } catch (e) {\n // Server side says the interface (or its host route) is unknown.\n // ErrorCode.methodNotFound covers both \"no such interface\" and \"no\n // such route\" — in either case the bus-wide suggestion is what the\n // user wants. Any other RpcError (e.g. permission) is propagated.\n if (e instanceof RpcError && e.code === ErrorCode.methodNotFound) {\n if (validation === 'auto') return;\n await _failWithSuggestion(channel, ref, verb);\n }\n throw e;\n }\n if (schema === undefined) {\n if (validation === 'auto') return;\n return _failWithSuggestion(channel, ref, verb);\n }\n const method = findMethodInSchema(schema, ref.methodName);\n if (!method) {\n return _failWithSuggestion(channel, ref, verb);\n }\n if (verb === 'call' && method.result === undefined) {\n throw new Error(\n `${ref.getMethodOnWire()} is a notification member; use \\`notify\\` instead of \\`call\\`.`,\n );\n }\n if (verb === 'notify' && method.result !== undefined) {\n throw new Error(\n `${ref.getMethodOnWire()} is a request member; use \\`call\\` instead of \\`notify\\`.`,\n );\n }\n const paramsSchema = method.params;\n const reason = validateValueAgainstSchema(params, paramsSchema, schema.components?.schemas ?? {});\n if (reason !== undefined) {\n throw new Error(_formatParamValidationError(ref, schema, method, params, reason));\n }\n return schema;\n}\n\nfunction _formatParamValidationError(\n ref: MethodRefWithOptHash,\n schema: SvcInterfaceSchema,\n method: MethodSchema,\n params: unknown,\n fallback: string,\n): string {\n const components = schema.components?.schemas ?? {};\n const paramsSchema = method.params;\n const lines: string[] = [];\n lines.push(`Param validation failed for ${ref.getMethodOnWire()}:`);\n const issues = explainValidation(params, paramsSchema, components);\n if (issues.length > 0) {\n for (const i of issues) {\n const where = i.path === '' ? '(root)' : i.path;\n lines.push(` ${where}: ${i.reason}`);\n }\n } else {\n lines.push(` ${fallback}`);\n }\n if (paramsSchema !== undefined) {\n const table = describeObjectParams(paramsSchema, components);\n if (table !== undefined) {\n lines.push('Expected params:');\n lines.push(table);\n } else {\n lines.push(`Expected: ${describeSchema(paramsSchema, components)}`);\n }\n }\n return lines.join('\\n');\n}\n\n/**\n * Walk the bus once, build a snapshot, and throw an Error whose message is a\n * focused \"did you mean…\" block tailored to `ref`. Always throws — return\n * type is `Promise<never>`. Snapshot load failures fall back to an empty\n * snapshot so we still produce *some* output.\n */\nasync function _failWithSuggestion(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n verb: 'call' | 'notify',\n): Promise<never> {\n let snapshot: HubSnapshot;\n try {\n snapshot = await HubSnapshot.load(channel);\n } catch {\n snapshot = new HubSnapshot([]);\n }\n throw new Error(formatSuggestion({ ref, snapshot, verb }));\n}\n\nfunction formatRpcError(e: RpcError): Error {\n if (e.code === ErrorCode.permissionRequired) {\n return new Error(_formatPermissionRequired(e));\n }\n const dataStr = e.data === undefined ? '' : ` ${JSON.stringify(e.data)}`;\n return new Error(`RPC error ${e.code}: ${e.message}${dataStr}`);\n}\n\nfunction _formatPermissionRequired(e: RpcError): string {\n return [\n `Permission required: ${e.message}`,\n ' No usable capability authorizes this call.',\n ' Retry with --cap:request to request access before calling.',\n ' Use --cap:allow-param with --cap:request to request a broader parameter scope,',\n ' or use `linkrpc hub caps request <methodRef>` to acquire and store access separately.',\n ].join('\\n');\n}\n","import type { JsonValue } from \"@hediet/linkrpc\";\nimport type { CallCommandOptions, NotifyCommandOptions } from \"./call\";\n\nexport interface BatchOperation {\n readonly kind: \"call\" | \"notify\";\n readonly methodRef: string;\n readonly paramsArg?: string;\n readonly paramOverrides: readonly string[];\n readonly noValidate: boolean;\n}\n\nexport interface BatchPlan {\n readonly operations: readonly BatchOperation[];\n readonly continueOnError: boolean;\n}\n\nexport interface BatchExecutor {\n readonly call: (options: CallCommandOptions) => Promise<string>;\n readonly notify: (options: NotifyCommandOptions) => Promise<string>;\n}\n\nexport type BatchResult =\n | {\n readonly index: number;\n readonly kind: BatchOperation[\"kind\"];\n readonly method: string;\n readonly ok: true;\n readonly result?: JsonValue;\n }\n | {\n readonly index: number;\n readonly kind: BatchOperation[\"kind\"];\n readonly method: string;\n readonly ok: false;\n readonly error: string;\n };\n\nexport interface ExecuteBatchOptions {\n readonly validation?: 'auto' | 'required' | 'off';\n readonly onStreamChunk?: (event: {\n readonly index: number;\n readonly method: string;\n readonly payload: JsonValue;\n }) => void;\n}\n\nexport function parseBatchArgs(args: readonly string[]): BatchPlan {\n const operations: MutableBatchOperation[] = [];\n let current: MutableBatchOperation | undefined;\n let continueOnError = false;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n switch (arg) {\n case \"--call\":\n case \"--notify\": {\n const methodRef = readOptionValue(args, ++i, arg, \"method\");\n current = {\n kind: arg === \"--call\" ? \"call\" : \"notify\",\n methodRef,\n paramOverrides: [],\n noValidate: false,\n };\n operations.push(current);\n break;\n }\n case \"--params\": {\n requireOperation(current, arg);\n if (current.paramsArg !== undefined) {\n throw new Error(\"--params may be specified only once per batch operation\");\n }\n current.paramsArg = readOptionValue(args, ++i, arg);\n break;\n }\n case \"--param\": {\n requireOperation(current, arg);\n current.paramOverrides.push(readOptionValue(args, ++i, arg));\n break;\n }\n case \"--no-validate\":\n requireOperation(current, arg);\n current.noValidate = true;\n break;\n case \"--continue-on-error\":\n continueOnError = true;\n break;\n default:\n if (arg.startsWith(\"-\")) {\n throw new Error(`Unknown batch option: ${arg}`);\n }\n throw new Error(`Unexpected batch argument: ${arg}`);\n }\n }\n\n if (operations.length === 0) {\n throw new Error(\"Batch requires at least one --call or --notify operation\");\n }\n\n return { operations, continueOnError };\n}\n\nexport async function executeBatch(\n plan: BatchPlan,\n executor: BatchExecutor,\n options: ExecuteBatchOptions = {},\n): Promise<BatchResult[]> {\n const results: BatchResult[] = [];\n\n for (let index = 0; index < plan.operations.length; index++) {\n const operation = plan.operations[index];\n const commandOptions: CallCommandOptions = {\n methodRef: operation.methodRef,\n paramsArg: operation.paramsArg,\n paramOverrides: operation.paramOverrides,\n noValidate: operation.noValidate,\n validation: options.validation,\n json: true,\n onStreamChunk: (payload) => options.onStreamChunk?.({\n index,\n method: operation.methodRef,\n payload,\n }),\n };\n\n try {\n if (operation.kind === \"notify\") {\n await executor.notify(commandOptions);\n results.push(toSuccessResult(index, operation));\n } else {\n const output = await executor.call(commandOptions);\n const result: JsonValue = JSON.parse(output);\n results.push(toSuccessResult(index, operation, result));\n }\n } catch (error) {\n if (!plan.continueOnError) {\n throw error;\n }\n results.push({\n index,\n kind: operation.kind,\n method: operation.methodRef,\n ok: false,\n error: getErrorMessage(error),\n });\n }\n }\n\n return results;\n}\n\ninterface MutableBatchOperation {\n kind: BatchOperation[\"kind\"];\n methodRef: string;\n paramsArg?: string;\n paramOverrides: string[];\n noValidate: boolean;\n}\n\nfunction readOptionValue(\n args: readonly string[],\n index: number,\n option: string,\n valueName = \"value\",\n): string {\n const value = args[index];\n if (value === undefined || value.startsWith(\"--\")) {\n throw new Error(`${option} requires a ${valueName}`);\n }\n return value;\n}\n\nfunction requireOperation(\n operation: MutableBatchOperation | undefined,\n option: string,\n): asserts operation is MutableBatchOperation {\n if (operation === undefined) {\n throw new Error(`${option} must follow --call or --notify`);\n }\n}\n\nfunction toSuccessResult(\n index: number,\n operation: BatchOperation,\n result?: JsonValue,\n): BatchResult {\n return {\n index,\n kind: operation.kind,\n method: operation.methodRef,\n ok: true,\n ...(result === undefined ? {} : { result }),\n };\n}\n\nfunction getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { spawn } from \"node:child_process\";\nimport {\n formatEndpointUri,\n traceMessageTransport,\n type ResolvedEndpoint,\n} from \"@hediet/linkrpc/node\";\nimport { SocketServer } from \"@hediet/linkrpc-hub/hub/server/node\";\nimport {\n connect,\n connectViaTransport,\n} from \"@hediet/linkrpc-client-internal\";\nimport type { StaticHubSchema } from \"../staticHubSchema\";\nimport type { ConnectionLimit } from \"../duration\";\nimport { ConnectionBroker, type BrokerStopReason } from \"./connectionBroker\";\n\nexport interface RunConnectionBrokerOptions {\n readonly remote: ResolvedEndpoint;\n readonly timeoutMs: ConnectionLimit;\n readonly ttlMs: ConnectionLimit;\n readonly notificationLimit?: number;\n readonly staticHubSchema?: StaticHubSchema;\n}\n\nexport interface RunningConnectionBroker {\n readonly endpoint: string;\n readonly stopped: Promise<BrokerStopReason>;\n dispose(): void;\n}\n\nexport async function runConnectionBroker(\n options: RunConnectionBrokerOptions,\n): Promise<RunningConnectionBroker> {\n const startedAt = Date.now();\n let broker: ConnectionBroker | undefined;\n const remote = await connect(options.remote, {\n trace: () => broker?.recordActivity(),\n });\n const token = randomUUID();\n const server = await SocketServer.start({\n isTokenAccepted: async (candidate) => candidate === token,\n });\n const mode = options.remote.kind === \"ws-no-init\" ? \"raw\" : \"linkrpc\";\n\n try {\n broker = new ConnectionBroker(remote, {\n id: randomUUID(),\n remoteEndpoint: formatRemoteEndpointForStatus(options.remote),\n mode,\n startedAt,\n timeoutMs: options.timeoutMs,\n ttlMs: options.ttlMs,\n ...(options.notificationLimit === undefined\n ? {}\n : { notificationLimit: options.notificationLimit }),\n ...(options.staticHubSchema === undefined\n ? {}\n : { staticHubSchema: options.staticHubSchema }),\n onStop: () => server.dispose(),\n });\n server.setConnectionHandler((transport) => {\n broker!.recordActivity();\n const traced = traceMessageTransport(transport, () => broker!.recordActivity());\n const local = connectViaTransport(traced);\n try {\n broker!.attach(local);\n } catch {\n local.close();\n return;\n }\n\n transport.onDidClose(() => broker!.detach(local));\n });\n } catch (error) {\n server.dispose();\n remote.close();\n throw error;\n }\n\n const endpoint = formatEndpointUri({\n kind: \"socket\",\n path: server.endpoint,\n token,\n brokerMode: mode,\n }, { revealToken: true });\n return {\n endpoint,\n stopped: broker.stopped,\n dispose: () => broker!.dispose(),\n };\n}\n\nfunction formatRemoteEndpointForStatus(endpoint: ResolvedEndpoint): string {\n if (endpoint.kind === \"ws-no-init\") {\n const url = new URL(endpoint.url);\n for (const key of [...url.searchParams.keys()]) {\n url.searchParams.set(key, \"***\");\n }\n return url.toString().replace(/^ws:/i, \"ws-no-init:\");\n }\n if (endpoint.kind === \"cmd-env\" || endpoint.kind === \"cmd-stdio\") {\n return `${endpoint.kind}:<redacted>`;\n }\n return formatEndpointUri(endpoint);\n}\n\nexport interface SpawnConnectionBrokerOptions {\n readonly remote: ResolvedEndpoint;\n readonly timeoutMs: ConnectionLimit;\n readonly ttlMs: ConnectionLimit;\n readonly notificationLimit?: number;\n readonly readyTimeoutMs?: number;\n readonly schemaSource?: string;\n}\n\nexport async function spawnConnectionBroker(\n options: SpawnConnectionBrokerOptions,\n): Promise<string> {\n const cliPath = process.argv[1];\n if (cliPath === undefined) {\n throw new Error(\"cannot locate the linkrpc CLI entry point\");\n }\n const args = [\n ...process.execArgv,\n cliPath,\n \"_connection-broker\",\n \"--remote-endpoint\",\n formatEndpointUri(options.remote, { revealToken: true }),\n \"--timeout-ms\",\n String(options.timeoutMs),\n \"--ttl-ms\",\n String(options.ttlMs),\n ];\n if (options.notificationLimit !== undefined) {\n args.push(\"--notification-limit\", String(options.notificationLimit));\n }\n if (options.schemaSource !== undefined) {\n args.push(\"--schema\", options.schemaSource);\n }\n\n const child = spawn(process.execPath, args, {\n detached: true,\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n const stdout = child.stdout;\n if (stdout === null) {\n child.kill();\n throw new Error(\"connection broker child exposes no stdout\");\n }\n\n try {\n const endpoint = await readReadyEndpoint(\n child,\n stdout,\n options.readyTimeoutMs ?? 60_000,\n );\n stdout.destroy();\n child.unref();\n return endpoint;\n } catch (error) {\n child.kill();\n throw error;\n }\n}\n\nfunction readReadyEndpoint(\n child: ReturnType<typeof spawn>,\n stdout: NodeJS.ReadableStream,\n timeoutMs: number,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let buffer = \"\";\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(\"connection broker did not become ready before the timeout\"));\n }, timeoutMs);\n const onData = (chunk: Buffer | string) => {\n buffer += chunk.toString();\n const newline = buffer.indexOf(\"\\n\");\n if (newline < 0) return;\n const endpoint = buffer.slice(0, newline).trim();\n cleanup();\n try {\n if (endpoint.startsWith(\"{\")) {\n const response: unknown = JSON.parse(endpoint);\n if (\n typeof response === \"object\"\n && response !== null\n && \"error\" in response\n && typeof response.error === \"string\"\n ) {\n throw new Error(`connection broker failed to start: ${response.error}`);\n }\n throw new Error(\"connection broker returned an invalid startup response\");\n }\n const parsed = new URL(endpoint);\n if (parsed.protocol !== \"unix:\" && parsed.protocol !== \"npipe:\") {\n throw new Error(`unexpected broker endpoint '${endpoint}'`);\n }\n resolve(endpoint);\n } catch (error) {\n reject(error);\n }\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onExit = (code: number | null) => {\n cleanup();\n reject(new Error(`connection broker exited before becoming ready (code ${code ?? \"unknown\"})`));\n };\n const cleanup = () => {\n clearTimeout(timer);\n stdout.removeListener(\"data\", onData);\n child.removeListener(\"error\", onError);\n child.removeListener(\"close\", onExit);\n };\n stdout.on(\"data\", onData);\n child.once(\"error\", onError);\n child.once(\"close\", onExit);\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport {\n isAssignable,\n type LinkRpcInterfaceSchema as SvcInterfaceSchema,\n type LinkRpcJsonSchema as SvcJsonSchema,\n} from \"@hediet/linkrpc\";\nimport { type CliChannel, fetchSchema } from \"@hediet/linkrpc-client-internal\";\n\nexport interface CheckCompatOptions {\n readonly interfaceId: string;\n /** Path to a local SvcInterfaceSchema JSON file. */\n readonly localPath: string;\n}\n\nexport type CompatVerdict =\n | { kind: \"identical\"; hash: string }\n | { kind: \"compatible-subset\"; localHash: string; remoteHash: string; details: string }\n | { kind: \"incompatible\"; localHash: string; remoteHash: string; details: string };\n\nexport async function checkCompatCommand(channel: CliChannel, opts: CheckCompatOptions): Promise<CompatVerdict> {\n const local = JSON.parse(readFileSync(opts.localPath, \"utf8\")) as SvcInterfaceSchema;\n const remote = await fetchSchema(channel, opts.interfaceId, undefined);\n return diffSchemas(local, remote);\n}\n\nexport function diffSchemas(\n local: SvcInterfaceSchema,\n remote: SvcInterfaceSchema,\n): CompatVerdict {\n if (local.hash === remote.hash) return { kind: \"identical\", hash: local.hash };\n\n const localComponents = local.components?.schemas ?? {};\n const remoteComponents = remote.components?.schemas ?? {};\n const issues: string[] = [];\n\n // Direction: a client speaking `local` calls a server speaking `remote`.\n // For that to work, local params must be assignable to remote params\n // (server accepts what client sends) and remote result must be assignable\n // to local result (client accepts what server returns).\n for (const [name, lm] of Object.entries(local.methods)) {\n const rm = remote.methods[name];\n if (!rm) {\n issues.push(`method \"${name}\" missing on remote`);\n continue;\n }\n if (!safeAssignable(lm.params, rm.params, mergeComponents(localComponents, remoteComponents))) {\n issues.push(`method \"${name}\": params not assignable (local → remote)`);\n }\n if (lm.result && rm.result) {\n if (!safeAssignable(rm.result, lm.result, mergeComponents(localComponents, remoteComponents))) {\n issues.push(`method \"${name}\": result not assignable (remote → local)`);\n }\n } else if (lm.result && !rm.result) {\n issues.push(`method \"${name}\": local expects a result, remote is notification-only`);\n }\n }\n\n if (issues.length === 0) {\n return {\n kind: \"compatible-subset\",\n localHash: local.hash,\n remoteHash: remote.hash,\n details: \"all local methods are structurally assignable against remote\",\n };\n }\n return {\n kind: \"incompatible\",\n localHash: local.hash,\n remoteHash: remote.hash,\n details: issues.join(\"; \"),\n };\n}\n\nfunction safeAssignable(\n a: SvcJsonSchema,\n b: SvcJsonSchema,\n components: Record<string, SvcJsonSchema>,\n): boolean {\n try { return isAssignable(a, b, components); } catch { return false; }\n}\n\nfunction mergeComponents(\n a: Record<string, SvcJsonSchema>,\n b: Record<string, SvcJsonSchema>,\n): Record<string, SvcJsonSchema> {\n return { ...a, ...b };\n}\n\nexport function formatVerdict(v: CompatVerdict): string {\n switch (v.kind) {\n case \"identical\":\n return `identical (${v.hash})`;\n case \"compatible-subset\":\n return `compatible-subset\\n local: ${v.localHash}\\n remote: ${v.remoteHash}\\n ${v.details}`;\n case \"incompatible\":\n return `incompatible\\n local: ${v.localHash}\\n remote: ${v.remoteHash}\\n ${v.details}`;\n }\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { generateTsContract, generateTsInterface, type GenerateContractOptions } from '@hediet/linkrpc';\nimport { loadStaticHubSchema } from '../staticHubSchema';\n\nexport interface CodegenCommandOptions {\n readonly input: string;\n readonly interfaceId?: string;\n readonly name?: string;\n readonly output: string;\n readonly preserveWireSchema?: boolean;\n readonly check?: boolean;\n readonly names?: string;\n}\n\nexport async function codegenCommand(options: CodegenCommandOptions): Promise<void> {\n if (/^https?:\\/\\//i.test(options.input)) {\n throw new Error('codegen --input must be a local offline bundle');\n }\n if (options.name !== undefined && !/^[$A-Z_a-z][$\\w]*$/.test(options.name)) {\n throw new Error(`codegen --name must be a valid TypeScript identifier, got '${options.name}'`);\n }\n\n const bundle = await loadStaticHubSchema(options.input);\n let generated: string;\n if (options.interfaceId === undefined) {\n if (options.name !== undefined) throw new Error('codegen --name requires --interface');\n let naming: GenerateContractOptions = {};\n if (options.names !== undefined) {\n const raw = JSON.parse(await readFile(options.names, 'utf8'));\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)\n || Object.keys(raw).some((key) => key !== 'interfaceNames' && key !== 'bindingNames')) {\n throw new Error('codegen --names must contain only interfaceNames and bindingNames maps');\n }\n for (const map of Object.values(raw)) {\n if (map === null || typeof map !== 'object' || Array.isArray(map)\n || Object.values(map).some((name) => typeof name !== 'string')) {\n throw new Error('codegen --names values must be string maps');\n }\n }\n naming = raw;\n }\n generated = generateTsContract(bundle, naming);\n } else {\n if (options.name === undefined) throw new Error('codegen --interface requires --name');\n if (options.names !== undefined) throw new Error('codegen --names is only supported for whole contracts');\n const matches = bundle.interfaceSchemas.filter((schema) => schema.id === options.interfaceId);\n if (matches.length === 0) {\n throw new Error(\n `Interface '${options.interfaceId}' was not found in bundle '${options.input}'`,\n );\n }\n if (matches.length > 1) {\n throw new Error(\n `Interface '${options.interfaceId}' is ambiguous in bundle '${options.input}' `\n + `(${matches.length} schema versions)`,\n );\n }\n\n generated = generateTsInterface(matches[0]!, {\n exportName: options.name,\n preserveWireSchema: options.preserveWireSchema === true,\n });\n }\n if (options.check === true) {\n let current: string;\n try {\n current = await readFile(options.output, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Generated output is missing: ${options.output}`);\n }\n throw error;\n }\n if (current !== generated) {\n throw new Error(`Generated output is stale: ${options.output}`);\n }\n return;\n }\n\n await mkdir(dirname(options.output), { recursive: true });\n await writeFile(options.output, generated, 'utf8');\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { exportStaticHubSchema, type ExportStaticHubSchemaOptions } from '@hediet/linkrpc';\nimport type { CliChannel } from '@hediet/linkrpc-client-internal';\n\nexport async function exportContractCommand(\n channel: CliChannel,\n options: ExportStaticHubSchemaOptions & { output: string },\n): Promise<void> {\n const document = await exportStaticHubSchema(channel, options);\n const text = `${JSON.stringify(document, null, 2)}\\n`;\n if (options.output === '-') {\n process.stdout.write(text);\n } else {\n await mkdir(dirname(options.output), { recursive: true });\n await writeFile(options.output, text, 'utf8');\n }\n}\n","/**\n * Emit shell-completion scripts. Currently PowerShell only; the entry point\n * is structured so adding bash / zsh later just plugs in another renderer.\n *\n * The scripts shell out to `hub _complete --line <line> --point <cursor>`,\n * which prints one candidate per line in the format `text\\ttooltip`. PS\n * turns each line into a `CompletionResult`.\n */\n\nexport type SupportedShell = 'powershell';\n\nconst SUPPORTED: ReadonlySet<SupportedShell> = new Set(['powershell']);\n\nexport function isSupportedShell(name: string): name is SupportedShell {\n return SUPPORTED.has(name as SupportedShell);\n}\n\nexport function emitCompletionScript(shell: SupportedShell): string {\n if (shell === 'powershell') return POWERSHELL_SCRIPT;\n throw new Error(`unsupported shell: ${shell}`);\n}\n\n/**\n * The PowerShell registration script. Self-contained — `Invoke-Expression`\n * of this string registers a native completer for `hub`, `linkrpc`, and `rpc`.\n *\n * Notes:\n * - `$commandAst.Extent.Text` is the entire pipeline element text (the\n * part PS treats as one command); `$cursorPosition` is absolute, so we\n * subtract `$commandAst.Extent.StartOffset` to get a position relative\n * to the line we're handing to the CLI.\n * - We invoke whichever binary the user is actually typing\n * (`$commandAst.CommandElements[0]`) so a local `hub.exe` and a global\n * one both work transparently.\n * - All errors are silently swallowed — a broken completer must never\n * break the user's prompt.\n */\nconst POWERSHELL_SCRIPT = `\n# linkrpc completion for PowerShell — auto-generated by \\`hub completions powershell\\`.\n# Install once with: hub completions powershell | Out-String | Invoke-Expression\n# Persist with: hub completions powershell >> $PROFILE\nRegister-ArgumentCompleter -Native -CommandName hub,linkrpc,rpc -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n\n try {\n $line = $commandAst.Extent.Text\n $point = $cursorPosition - $commandAst.Extent.StartOffset\n if ($point -lt 0) { $point = 0 }\n if ($point -gt $line.Length) { $point = $line.Length }\n\n $binElement = $commandAst.CommandElements[0]\n $bin = if ($binElement.Value) { $binElement.Value } else { $binElement.Extent.Text }\n\n # The completer must never write to the user's prompt. Redirect stderr.\n $raw = & $bin _complete --line $line --point $point 2>$null\n if (-not $raw) { return }\n\n foreach ($entry in ($raw -split \"\\`r?\\`n\")) {\n if (-not $entry) { continue }\n $parts = $entry -split \"\\`t\", 2\n $text = $parts[0]\n $tooltip = if ($parts.Length -ge 2 -and $parts[1]) { $parts[1] } else { $text }\n [System.Management.Automation.CompletionResult]::new(\n $text,\n $text,\n [System.Management.Automation.CompletionResultType]::ParameterValue,\n $tooltip\n )\n }\n } catch {\n # Silent: a broken completer must not break the prompt.\n }\n}\n`.trimStart();\n","/**\n * `hub completions <shell>` — print the shell-completion registration script\n * for the requested shell.\n *\n * No connection required. Currently supports `powershell` only.\n */\nimport { emitCompletionScript, isSupportedShell } from '../completions/shellScripts';\n\nexport interface CompletionsCommandOptions {\n readonly shell: string;\n}\n\nexport function completionsCommand(opts: CompletionsCommandOptions): string {\n if (!isSupportedShell(opts.shell)) {\n throw new Error(\n `unsupported shell \"${opts.shell}\". Supported: powershell.`,\n );\n }\n return emitCompletionScript(opts.shell);\n}\n","import { type CliChannel, fetchDefaults } from \"@hediet/linkrpc-client-internal\";\nimport { formatJson } from \"../output\";\n\nexport interface DefaultsCommandOptions {\n readonly json?: boolean;\n}\n\nexport async function defaultsCommand(channel: CliChannel, opts: DefaultsCommandOptions = {}): Promise<string> {\n const d = await fetchDefaults(channel);\n if (opts.json) return formatJson(d);\n if (!d.interfaceId && !d.serviceId) return \"(no preset)\";\n const lines: string[] = [];\n if (d.serviceId) lines.push(`service: ${d.serviceId}`);\n lines.push(`interface: ${d.interfaceId ?? \"(none)\"}`);\n if (d.hash) lines.push(`hash: ${d.hash}`);\n return lines.join(\"\\n\");\n}\n","import { readFileSync } from \"node:fs\";\nimport { computeInterfaceHash, type LinkRpcInterfaceSchema as SvcInterfaceSchema } from \"@hediet/linkrpc\";\n\nexport interface HashCommandOptions {\n readonly schemaPath: string;\n}\n\nexport function hashCommand(opts: HashCommandOptions): string {\n const text = readFileSync(opts.schemaPath, \"utf8\");\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (e) {\n throw new Error(`${opts.schemaPath}: invalid JSON (${(e as Error).message})`);\n }\n if (!isInterfaceSchema(parsed)) {\n throw new Error(`${opts.schemaPath}: not a SvcInterfaceSchema (missing id / methods)`);\n }\n return computeInterfaceHash(parsed);\n}\n\nfunction isInterfaceSchema(v: unknown): v is SvcInterfaceSchema {\n if (!v || typeof v !== \"object\") return false;\n const o = v as Record<string, unknown>;\n return typeof o.id === \"string\"\n && typeof o.methods === \"object\"\n && o.methods !== null\n && !Array.isArray(o.methods);\n}\n","/**\n * `hub _complete --line <line> --point <cursor>` — internal completion\n * resolver invoked by the shell scripts emitted by `hub completions`.\n *\n * Reads the line + cursor, optionally connects to whatever endpoint the line\n * already names (via `--endpoint*` flags or `LINKRPC_ENDPOINT`), and prints\n * one candidate per line as `text\\ttooltip`. Empty output on any error —\n * the completer that invokes us must never disturb the user's prompt.\n *\n * The actual resolution lives in `../completions/runComplete.ts`; this command\n * just formats the structured result for stdout.\n */\nimport { type Completion } from '../completions/complete';\nimport { completeForLine, type CompleteForLineOptions } from '../completions/runComplete';\nimport { type DirectorySource } from '../completions/directorySource';\n\nexport interface InternalCompleteOptions {\n readonly line: string;\n readonly point: number;\n /** Override the directory source (tests). */\n readonly directoryOverride?: DirectorySource;\n /** Suppress the connect attempt entirely (tests). */\n readonly skipConnect?: boolean;\n}\n\n/**\n * Compute completions and return them as a `\\n`-joined `text\\ttooltip` string\n * ready for stdout. Returns `''` when there are no candidates so callers can\n * unconditionally write the result.\n */\nexport async function internalCompleteCommand(opts: InternalCompleteOptions): Promise<string> {\n const runOpts: CompleteForLineOptions = {\n line: opts.line,\n point: opts.point,\n ...(opts.directoryOverride !== undefined ? { directoryOverride: opts.directoryOverride } : {}),\n ...(opts.skipConnect !== undefined ? { skipConnect: opts.skipConnect } : {}),\n };\n const result = await completeForLine(runOpts);\n return _formatCandidates(result.candidates);\n}\n\nfunction _formatCandidates(candidates: readonly Completion[]): string {\n return candidates\n .map((c) => (c.tooltip ? `${c.text}\\t${c.tooltip}` : c.text))\n .join('\\n');\n}\n","export interface DisplayForestNode<TNode, TEdge> {\n readonly node: TNode;\n readonly parentEdge?: TEdge;\n readonly children: readonly DisplayForestNode<TNode, TEdge>[];\n}\n\nexport interface DisplayForest<TNode, TEdge> {\n readonly roots: readonly DisplayForestNode<TNode, TEdge>[];\n readonly crossEdges: readonly TEdge[];\n}\n\nexport interface DisplayGraph<TNode, TEdge> {\n readonly nodes: readonly TNode[];\n readonly edges: readonly TEdge[];\n readonly rootIds: readonly string[];\n nodeId(node: TNode): string;\n edgeKey(edge: TEdge): string;\n edgeEndpoints(edge: TEdge): readonly [string, string];\n readonly directed?: boolean;\n}\n\n/**\n * Projects a graph into a deterministic shortest-path forest. Every node is\n * rendered once; non-tree edges remain available as explicit cross-links.\n */\nexport function createDisplayForest<TNode, TEdge>(\n graph: DisplayGraph<TNode, TEdge>,\n): DisplayForest<TNode, TEdge> {\n const nodes = new Map(graph.nodes.map((node) => [graph.nodeId(node), node]));\n const edges = [...graph.edges].sort((a, b) => graph.edgeKey(a).localeCompare(graph.edgeKey(b)));\n const adjacency = new Map<string, Array<{ edge: TEdge; next: string }>>();\n for (const edge of edges) {\n const [from, to] = graph.edgeEndpoints(edge);\n if (nodes.has(from) && nodes.has(to)) {\n addAdjacent(adjacency, from, edge, to);\n if (graph.directed !== true) addAdjacent(adjacency, to, edge, from);\n }\n }\n for (const entries of adjacency.values()) {\n entries.sort((a, b) =>\n a.next.localeCompare(b.next)\n || graph.edgeKey(a.edge).localeCompare(graph.edgeKey(b.edge)));\n }\n\n const parent = new Map<string, { parentId: string; edge: TEdge }>();\n const visited = new Set<string>();\n const roots: string[] = [];\n const walk = (rootId: string): void => {\n if (visited.has(rootId) || !nodes.has(rootId)) return;\n roots.push(rootId);\n visited.add(rootId);\n const queue = [rootId];\n for (let index = 0; index < queue.length; index++) {\n const current = queue[index];\n for (const entry of adjacency.get(current) ?? []) {\n if (visited.has(entry.next)) continue;\n visited.add(entry.next);\n parent.set(entry.next, { parentId: current, edge: entry.edge });\n queue.push(entry.next);\n }\n }\n };\n\n for (const rootId of [...new Set(graph.rootIds)].sort()) walk(rootId);\n for (const nodeId of [...nodes.keys()].sort()) walk(nodeId);\n\n const children = new Map<string, string[]>();\n for (const [nodeId, value] of parent) {\n const entries = children.get(value.parentId) ?? [];\n entries.push(nodeId);\n children.set(value.parentId, entries);\n }\n for (const entries of children.values()) entries.sort();\n\n const build = (nodeId: string): DisplayForestNode<TNode, TEdge> => ({\n node: nodes.get(nodeId)!,\n ...(parent.get(nodeId) !== undefined ? { parentEdge: parent.get(nodeId)!.edge } : {}),\n children: (children.get(nodeId) ?? []).map(build),\n });\n const treeEdgeKeys = new Set([...parent.values()].map((value) => graph.edgeKey(value.edge)));\n return {\n roots: roots.map(build),\n crossEdges: edges.filter((edge) => !treeEdgeKeys.has(graph.edgeKey(edge))),\n };\n}\n\nfunction addAdjacent<TEdge>(\n adjacency: Map<string, Array<{ edge: TEdge; next: string }>>,\n from: string,\n edge: TEdge,\n next: string,\n): void {\n const entries = adjacency.get(from) ?? [];\n entries.push({ edge, next });\n adjacency.set(from, entries);\n}\n","export type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport type JsonPatchOperation =\n | { readonly op: \"add\" | \"replace\"; readonly path: string; readonly value: JsonValue }\n | { readonly op: \"remove\"; readonly path: string };\n\nexport function createJsonPatch(\n before: JsonValue,\n after: JsonValue,\n path = \"\",\n): JsonPatchOperation[] {\n if (Object.is(before, after)) {\n return [];\n }\n if (isJsonObject(before) && isJsonObject(after)) {\n const operations: JsonPatchOperation[] = [];\n const beforeKeys = Object.keys(before).sort();\n const afterKeys = Object.keys(after).sort();\n const afterKeySet = new Set(afterKeys);\n for (const key of beforeKeys) {\n if (!afterKeySet.has(key)) {\n operations.push({ op: \"remove\", path: appendPath(path, key) });\n }\n }\n const beforeKeySet = new Set(beforeKeys);\n for (const key of afterKeys) {\n const childPath = appendPath(path, key);\n if (!beforeKeySet.has(key)) {\n operations.push({ op: \"add\", path: childPath, value: after[key] });\n } else {\n operations.push(...createJsonPatch(before[key], after[key], childPath));\n }\n }\n return operations;\n }\n return [{ op: \"replace\", path, value: after }];\n}\n\nexport function applyJsonPatch(\n value: JsonValue,\n operations: readonly JsonPatchOperation[],\n): JsonValue {\n let result = structuredClone(value);\n for (const operation of operations) {\n if (operation.path === \"\") {\n if (operation.op === \"remove\") {\n throw new Error(\"Cannot remove the JSON document root\");\n }\n result = structuredClone(operation.value);\n continue;\n }\n const segments = operation.path\n .slice(1)\n .split(\"/\")\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"));\n let target = result;\n for (const segment of segments.slice(0, -1)) {\n if (typeof target !== \"object\" || target === null || Array.isArray(target)) {\n throw new Error(`JSON patch path does not address an object: ${operation.path}`);\n }\n target = target[segment];\n }\n if (typeof target !== \"object\" || target === null || Array.isArray(target)) {\n throw new Error(`JSON patch path does not address an object: ${operation.path}`);\n }\n const key = segments.at(-1)!;\n if (operation.op === \"remove\") {\n delete target[key];\n } else {\n target[key] = structuredClone(operation.value);\n }\n }\n return result;\n}\n\nfunction appendPath(path: string, key: string): string {\n return `${path}/${key.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`;\n}\n\nfunction isJsonObject(value: JsonValue): value is { [key: string]: JsonValue } {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import {\n createJsonPatch,\n type JsonPatchOperation,\n type JsonValue,\n} from \"./jsonPatch\";\n\nexport type StateJsonlLine =\n | {\n readonly type: \"snapshot\";\n readonly revision: number;\n readonly value: JsonValue;\n }\n | {\n readonly type: \"patch\";\n readonly revision: number;\n readonly patch: readonly JsonPatchOperation[];\n };\n\n/**\n * Serializes changing state as one initial value followed by atomic RFC 6902\n * patches. Await {@link whenIdle} before closing the destination.\n */\nexport class StateJsonlWriter {\n private _current: JsonValue | undefined;\n private _queue = Promise.resolve();\n\n public constructor(\n private readonly _emitLine: (line: string) => void | Promise<void>,\n ) {}\n\n public write(value: unknown, revision: number): void {\n const next = toJsonValue(value);\n this._queue = this._queue.then(async () => {\n if (this._current === undefined) {\n const line: StateJsonlLine = { type: \"snapshot\", revision, value: next };\n this._current = next;\n await this._emitLine(JSON.stringify(line));\n return;\n }\n const patch = createJsonPatch(this._current, next);\n this._current = next;\n if (patch.length === 0) return;\n const line: StateJsonlLine = { type: \"patch\", revision, patch };\n await this._emitLine(JSON.stringify(line));\n });\n }\n\n public async whenIdle(): Promise<void> {\n await this._queue;\n }\n}\n\nexport function toJsonValue(value: unknown): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n","import { mkdir, open, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { ErrorCode, type LinkRpcInterfaceSchema } from \"@hediet/linkrpc\";\nimport {\n DEFAULT_WALK_DEPTH,\n HubDirectoryExplorer,\n fetchSchema,\n type DiscoveredListing,\n type HubDirectoryGraphEvent,\n type HubDirectoryGraphSnapshot,\n type HubDirectoryNodeReport,\n type HubDirectoryGraphTarget,\n type InaccessibleDirectory,\n type ServiceListing,\n type WalkHubOptions,\n} from \"@hediet/linkrpc/hub/common\";\nimport type { CliChannel, SigningSession } from \"@hediet/linkrpc-client-internal\";\nimport { formatJson } from \"../output\";\nimport { createDisplayForest, type DisplayForestNode } from \"./displayForest\";\nimport { createJsonPatch, type JsonValue } from \"./jsonPatch\";\nimport { StateJsonlWriter } from \"./stateJsonl\";\n\nexport type LsFormat = \"pretty\" | \"json\" | \"jsonl\";\n\nexport interface LsOptions {\n readonly requestDirectoryAccess?: (serviceId: string) => Promise<boolean>;\n readonly log?: (message: string) => void;\n readonly interfaceId?: string;\n readonly interfacePrefix?: string;\n readonly serviceId?: string;\n readonly servicePrefix?: string;\n readonly search?: string;\n readonly json?: boolean;\n readonly format?: LsFormat;\n readonly withMembers?: boolean;\n /** Write a complete topology and schema fixture instead of rendering the listing. */\n readonly dumpPath?: string;\n /** Write one RFC 6902 operation per line as exploration progresses. `-` writes to stdout. */\n readonly dumpPatchesPath?: string;\n /** Emit an initial value and subsequent RFC 6902 patches as a patch-log JSONL stream. */\n readonly stream?: boolean;\n /** Keep the explorer watches active until `stop` resolves. Implies `stream`. */\n readonly watch?: boolean;\n /** Destination for stdout-oriented streaming modes. */\n readonly emitLine?: (line: string) => void | Promise<void>;\n /** Destination for a complete repainting terminal frame. */\n readonly emitFrame?: (frame: string) => void | Promise<void>;\n /** Receives each reconstructable state before it is rendered or serialized. */\n readonly onState?: (state: LsState) => void;\n /** Resolves when a watched stream should stop. */\n readonly stop?: Promise<void>;\n /**\n * When listing the whole bus, how many `hubrpc.directory` follow-ups\n * to perform. Defaults to 5. Ignored when `serviceId` is set (then we\n * just list that one service).\n */\n readonly maxDepth?: number;\n /** Hard deadline for each directory request. Defaults to 5 seconds. */\n readonly timeoutMs?: number;\n}\n\nexport interface LsState {\n readonly kind: \"directory\";\n readonly revision: number;\n readonly complete: boolean;\n readonly root: HubDirectoryNodeReport;\n readonly directories: readonly HubDirectoryNodeReport[];\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n}\n\n/**\n * Recursive bus walk: list the connection's directory, then for each\n * `hubrpc.directory` entry it surfaces on a service we haven't queried\n * yet, recurse. Bounded by `maxDepth`. Duplicates (same\n * `serviceId+interfaceId+hash`) are dropped.\n */\nexport async function lsCommand(channel: CliChannel, opts: LsOptions = {}): Promise<string> {\n validateLsOptions(opts);\n const legacyOutput = opts.format === undefined;\n if (opts.dumpPath !== undefined) {\n const dump = await createHubDump(channel, opts);\n const dumpPath = path.resolve(opts.dumpPath);\n await mkdir(path.dirname(dumpPath), { recursive: true });\n await writeFile(dumpPath, `${formatJson(dump)}\\n`, \"utf8\");\n return dumpSummary(\"Wrote\", dumpPath, dump);\n }\n if (opts.dumpPatchesPath !== undefined) {\n return runStreamingLs(channel, opts);\n }\n if (legacyOutput && (opts.stream === true || opts.watch === true)) {\n return runStreamingLs(channel, opts);\n }\n const format = resolveLsFormat(opts);\n if (opts.format !== undefined || opts.watch === true) {\n return runStateLs(channel, opts, format);\n }\n\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n await explorer.explore();\n const state = createLsState(explorer.graphSnapshot, opts);\n explorer.dispose();\n const all = state.listings;\n const output = opts.withMembers\n ? await addMembers(createSchemaFetcher(channel, opts), all, (listing) => listing.discoveredFrom)\n : all;\n if (format === \"json\") {\n for (const item of state.inaccessible) opts.log?.(`Inaccessible directory ${item.serviceId || \"(root)\"}: ${item.reason}`);\n return formatJson(legacyOutput ? output : state);\n }\n return [\n renderTree(output, opts.interfaceId),\n ...state.inaccessible.map(item => `! Inaccessible directory ${item.serviceId || \"(root)\"}: ${item.reason}`),\n ].join(\"\\n\");\n}\n\nexport async function requestDirectoryAccess(\n session: Pick<SigningSession, \"requestAccess\">,\n serviceId: string,\n options: Pick<LsOptions, \"watch\" | \"withMembers\" | \"dumpPath\" | \"dumpPatchesPath\">,\n): Promise<boolean> {\n const result = await session.requestAccess({\n consumer: { name: \"linkrpc-cli\", purpose: `Discover interfaces in ${serviceId}.` },\n permissions: [{\n target: {\n serviceId: { exact: serviceId },\n interfaceId: { exact: \"hubrpc.directory\" },\n members: [\n { exact: \"list\" },\n ...(options.watch ? [{ exact: \"watch\" }] : []),\n ],\n },\n canInvoke: true,\n }, ...(options.withMembers || options.dumpPath !== undefined || options.dumpPatchesPath !== undefined ? [{\n target: {\n serviceId: { exact: serviceId },\n interfaceId: { exact: \"hubrpc.schemas\" },\n members: [{ exact: \"get\" }],\n },\n canInvoke: true,\n }] : [])],\n duration: \"shortLived\",\n });\n if (result.status !== \"granted\") {\n throw new Error(`Directory access ${result.status}${\"reason\" in result && result.reason ? `: ${result.reason}` : \"\"}`);\n }\n return true;\n}\n\nfunction validateLsOptions(opts: LsOptions): void {\n validateSearchExpression(opts.search, \"ls\");\n if (opts.format !== undefined && opts.withMembers === true) {\n throw new Error(\"--format cannot be combined with --with-members\");\n }\n if (opts.dumpPath !== undefined) {\n if (\n opts.interfaceId !== undefined\n || opts.interfacePrefix !== undefined\n || opts.serviceId !== undefined\n || opts.servicePrefix !== undefined\n || opts.search !== undefined\n || opts.json === true\n || opts.format !== undefined\n || opts.withMembers === true\n || opts.stream === true\n || opts.watch === true\n || opts.dumpPatchesPath !== undefined\n ) {\n throw new Error(\n \"--dump cannot be combined with filters, --with-members, --json, --format, \"\n + \"--stream, --watch, or --dump-patches\",\n );\n }\n\n }\n if (opts.dumpPatchesPath !== undefined && (\n opts.interfaceId !== undefined\n || opts.interfacePrefix !== undefined\n || opts.serviceId !== undefined\n || opts.servicePrefix !== undefined\n || opts.search !== undefined\n || opts.json === true\n || opts.format !== undefined\n || opts.withMembers === true\n || opts.stream === true\n )) {\n throw new Error(\n \"--dump-patches cannot be combined with filters, --with-members, --json, \"\n + \"--format, or --stream\",\n );\n }\n if (\n opts.format === undefined\n && (opts.stream === true || opts.watch === true)\n && opts.withMembers === true\n ) {\n throw new Error(\"--stream/--watch already emit JSON and cannot include schema members\");\n }\n if (opts.format === \"jsonl\" && opts.dumpPatchesPath === undefined) {\n if (opts.emitLine === undefined) {\n throw new Error(\"JSONL ls output requires an output sink\");\n }\n }\n if (\n opts.watch === true\n && opts.format === \"pretty\"\n && opts.emitFrame === undefined\n ) {\n throw new Error(\"pretty ls watch requires a frame output sink\");\n }\n if (opts.watch === true && opts.stop === undefined) {\n throw new Error(\"--watch requires a stop signal\");\n }\n}\n\nfunction validateSearchExpression(search: string | undefined, command: string): void {\n if (search === undefined) return;\n try {\n new RegExp(search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid ${command} search regexp: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n\nfunction explorerOptions(opts: LsOptions): WalkHubOptions {\n return {\n unlockGatedDirectory: opts.requestDirectoryAccess,\n log: opts.log,\n maxDepth: opts.serviceId === undefined\n ? opts.maxDepth ?? DEFAULT_WALK_DEPTH\n : 0,\n ...(opts.interfaceId !== undefined ? { interfaceId: opts.interfaceId } : {}),\n ...(opts.interfacePrefix !== undefined\n ? { interfaceIdPrefix: opts.interfacePrefix }\n : {}),\n ...(opts.serviceId !== undefined\n ? { rootTarget: opts.serviceId, serviceId: opts.serviceId }\n : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n };\n}\n\nfunction resolveLsFormat(opts: LsOptions): LsFormat {\n if (opts.format !== undefined) return opts.format;\n if (opts.stream === true) return \"jsonl\";\n if (opts.json === true) return \"json\";\n return \"pretty\";\n}\n\nasync function runStateLs(\n channel: CliChannel,\n opts: LsOptions,\n format: LsFormat,\n): Promise<string> {\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n const writer = format === \"jsonl\" ? new StateJsonlWriter(opts.emitLine!) : undefined;\n let state = createLsState(explorer.graphSnapshot, opts);\n let outputQueue = Promise.resolve();\n const emitState = (snapshot: HubDirectoryGraphSnapshot): void => {\n state = createLsState(snapshot, opts);\n opts.onState?.(state);\n if (writer !== undefined) {\n writer.write(state, state.revision);\n } else if (opts.watch === true && format === \"pretty\") {\n const frame = renderLsState(state, opts);\n outputQueue = outputQueue.then(() => opts.emitFrame!(frame));\n }\n };\n const unsubscribe = explorer.subscribe((event) => emitState(event.snapshot));\n let stopWatch: (() => void) | undefined;\n try {\n if (opts.watch === true) {\n stopWatch = await explorer.watch(() => {});\n await opts.stop;\n stopWatch();\n stopWatch = undefined;\n await explorer.whenIdle();\n emitState(explorer.graphSnapshot);\n } else {\n await explorer.explore();\n emitState(explorer.graphSnapshot);\n }\n await outputQueue;\n await writer?.whenIdle();\n if (format === \"json\") return formatJson(state);\n if (format === \"pretty\") return opts.watch === true ? \"\" : renderLsState(state, opts);\n return \"\";\n } finally {\n stopWatch?.();\n unsubscribe();\n explorer.dispose();\n await outputQueue;\n await writer?.whenIdle();\n }\n}\n\nexport function createLsState(\n snapshot: HubDirectoryGraphSnapshot,\n opts: Pick<\n LsOptions,\n \"interfaceId\" | \"interfacePrefix\" | \"serviceId\" | \"servicePrefix\" | \"search\"\n > = {},\n): LsState {\n const matches = createListingFilter(opts);\n const mapNode = (node: HubDirectoryNodeReport): HubDirectoryNodeReport => ({\n ...node,\n nativeListings: node.nativeListings.filter(matches),\n });\n return {\n kind: \"directory\",\n revision: snapshot.revision,\n complete: snapshot.complete,\n root: mapNode(snapshot.root),\n directories: snapshot.directories.map(mapNode),\n listings: snapshot.result.listings.filter(matches),\n inaccessible: snapshot.result.inaccessible,\n };\n}\n\nfunction createListingFilter(\n opts: Pick<\n LsOptions,\n \"interfaceId\" | \"interfacePrefix\" | \"serviceId\" | \"servicePrefix\" | \"search\"\n >,\n): (listing: ServiceListing) => boolean {\n let search: RegExp | undefined;\n if (opts.search !== undefined) {\n try {\n search = new RegExp(opts.search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid ls search regexp: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return (listing) =>\n (opts.interfaceId === undefined || listing.interfaceId === opts.interfaceId)\n && (opts.interfacePrefix === undefined\n || listing.interfaceId.startsWith(opts.interfacePrefix))\n && (opts.serviceId === undefined || listing.serviceId === opts.serviceId)\n && (opts.servicePrefix === undefined\n || listing.serviceId.startsWith(opts.servicePrefix))\n && (search === undefined || search.test(JSON.stringify(listing)));\n}\n\nfunction renderLsState(state: LsState, opts: Pick<LsOptions, \"interfaceId\">): string {\n const status = state.complete ? \"complete\" : \"loading\";\n const nodes = [state.root, ...state.directories];\n const edges: DirectoryDisplayEdge[] = [];\n for (const node of nodes) {\n for (const parent of node.parents) {\n edges.push({\n from: directoryTargetKey(parent.target),\n to: directoryTargetKey(node.target),\n scopes: parent.scopes.map((scope) =>\n \"exact\" in scope ? `=${scope.exact}` : `${scope.prefix}*`),\n });\n }\n }\n const forest = createDisplayForest({\n nodes,\n edges,\n rootIds: [directoryTargetKey(state.root.target)],\n nodeId: (node) => directoryTargetKey(node.target),\n edgeKey: (edge) => `${edge.from}\\0${edge.to}\\0${edge.scopes.join(\"\\0\")}`,\n edgeEndpoints: (edge) => [edge.from, edge.to],\n directed: true,\n });\n const body: string[] = [];\n for (const root of forest.roots) renderDirectoryNode(root, body, \"\");\n if (forest.crossEdges.length > 0) {\n body.push(\"\", \"Additional referrals\");\n for (const edge of forest.crossEdges) {\n body.push(` ${edge.from} → ${edge.to}${formatScopes(edge.scopes)}`);\n }\n }\n if (state.inaccessible.length > 0) {\n body.push(\"\", \"Inaccessible\");\n for (const item of state.inaccessible) {\n body.push(` ${item.serviceId}: ${item.reason}`);\n }\n }\n return [\n `LinkRPC directory (${status}, revision ${state.revision})`,\n \"\",\n ...(body.length > 0 ? body : [\"(empty)\"]),\n ].join(\"\\n\");\n}\n\ninterface DirectoryDisplayEdge {\n readonly from: string;\n readonly to: string;\n readonly scopes: readonly string[];\n}\n\nfunction renderDirectoryNode(\n item: DisplayForestNode<HubDirectoryNodeReport, DirectoryDisplayEdge>,\n lines: string[],\n prefix: string,\n): void {\n const watch = item.node.watching ? \", watching\" : \"\";\n lines.push(\n `${prefix}${directoryTargetLabel(item.node.target)} [${item.node.state}${watch}]`\n + (item.parentEdge === undefined ? \"\" : formatScopes(item.parentEdge.scopes)),\n );\n for (const listing of item.node.nativeListings) {\n const service = listing.serviceId === \"\" ? \"(root)\" : listing.serviceId;\n lines.push(`${prefix} ${service} → ${listing.interfaceId} @ ${listing.hash}`);\n }\n if (item.node.inaccessibleReason !== undefined) {\n lines.push(`${prefix} ! ${item.node.inaccessibleReason}`);\n }\n for (let index = 0; index < item.children.length; index++) {\n const child = item.children[index];\n const last = index === item.children.length - 1;\n const childPrefix = prefix + (last ? \" \" : \"│ \");\n const childLines: string[] = [];\n renderDirectoryNode(child, childLines, childPrefix);\n childLines[0] = `${prefix}${last ? \"└─ \" : \"├─ \"}${childLines[0].slice(childPrefix.length)}`;\n lines.push(...childLines);\n }\n}\n\nfunction directoryTargetKey(target: HubDirectoryGraphTarget): string {\n return target.kind === \"root\"\n ? `root:${target.serviceId ?? \"\"}`\n : `service:${target.serviceId}`;\n}\n\nfunction directoryTargetLabel(target: HubDirectoryGraphTarget): string {\n if (target.kind === \"addressed\") return target.serviceId;\n return target.serviceId === undefined || target.serviceId === \"\"\n ? \"(connection root)\"\n : `(root listing for ${target.serviceId})`;\n}\n\nfunction formatScopes(scopes: readonly string[]): string {\n return scopes.length === 0 ? \"\" : ` via ${scopes.join(\", \")}`;\n}\n\ninterface LsMember {\n readonly name: string;\n readonly kind: \"request\" | \"notification\";\n}\n\ninterface LsListing extends ServiceListing {\n readonly members?: readonly LsMember[];\n}\n\nfunction createSchemaFetcher(channel: CliChannel, opts: Pick<LsOptions, \"requestDirectoryAccess\">) {\n const approvals = new Map<string, Promise<boolean>>();\n return async (interfaceId: string, hash: string, target: string | undefined) => {\n try {\n return await fetchSchema(channel, interfaceId, hash, target);\n } catch (error) {\n if (typeof error !== \"object\" || error === null || !(\"code\" in error)\n || error.code !== ErrorCode.permissionRequired || !target || !opts.requestDirectoryAccess) {\n throw error;\n }\n let approval = approvals.get(target);\n if (!approval) {\n approval = opts.requestDirectoryAccess(target);\n approvals.set(target, approval);\n }\n if (!await approval) throw error;\n return fetchSchema(channel, interfaceId, hash, target);\n }\n };\n}\n\nasync function addMembers<T extends ServiceListing>(\n getSchema: ReturnType<typeof createSchemaFetcher>,\n listings: readonly T[],\n getTarget: (listing: T) => string | undefined,\n): Promise<LsListing[]> {\n const cache = new Map<string, Promise<readonly LsMember[]>>();\n return Promise.all(listings.map(async (listing) => {\n const target = getTarget(listing);\n const cacheKey = `${target ?? \"\"}\\0${listing.interfaceId}\\0${listing.hash}`;\n let members = cache.get(cacheKey);\n if (members === undefined) {\n members = getSchema(\n listing.interfaceId,\n listing.hash,\n target === \"\" ? undefined : target,\n ).then((schema) =>\n Object.entries(schema.methods)\n .map(([name, method]): LsMember => ({\n name,\n kind: method.result === undefined ? \"notification\" : \"request\",\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n );\n cache.set(cacheKey, members);\n }\n return { ...listing, members: await members };\n }));\n}\n\nexport interface HubDumpSchemaError {\n readonly interfaceIds: readonly string[];\n readonly attempts: readonly {\n readonly reportedBy: string;\n readonly interfaceId: string;\n readonly error: string;\n }[];\n}\n\nexport interface HubDump {\n readonly format: \"linkrpc-hub-dump\";\n readonly version: 2;\n readonly revision: number;\n readonly complete: boolean;\n readonly schemasComplete: boolean;\n readonly root: HubDirectoryNodeReport;\n readonly directories: Readonly<Record<string, HubDirectoryNodeReport>>;\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n /** Complete reflected interface schemas, deduplicated by interface hash. */\n readonly schemas: Readonly<Record<string, LinkRpcInterfaceSchema>>;\n /** Hashes advertised by a directory but not retrievable from any reporter. */\n readonly schemaErrors: Readonly<Record<string, HubDumpSchemaError>>;\n}\n\nexport function createInitialHubDump(): HubDump {\n return {\n format: \"linkrpc-hub-dump\",\n version: 2,\n revision: 0,\n complete: false,\n schemasComplete: false,\n root: {\n target: { kind: \"root\" },\n state: \"unexplored\",\n effectiveScopes: [{ prefix: \"\" }],\n depth: 0,\n parents: [],\n nativeListings: [],\n watching: false,\n },\n directories: {},\n listings: [],\n inaccessible: [],\n schemas: {},\n schemaErrors: {},\n };\n}\n\nexport async function createHubDump(\n channel: CliChannel,\n opts: Pick<LsOptions, \"maxDepth\" | \"timeoutMs\" | \"requestDirectoryAccess\" | \"log\"> = {},\n): Promise<HubDump> {\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n await explorer.explore();\n const cache = await fetchDumpSchemas(createSchemaFetcher(channel, opts), explorer.graphSnapshot);\n const dump = buildHubDump(explorer.graphSnapshot, cache, true);\n explorer.dispose();\n return dump;\n}\n\ninterface SchemaCandidate {\n readonly reportedBy: string;\n readonly target: string | undefined;\n readonly interfaceId: string;\n}\n\ninterface DumpSchemaCache {\n readonly schemas: Map<string, LinkRpcInterfaceSchema>;\n readonly errors: Map<string, HubDumpSchemaError>;\n}\n\nasync function fetchDumpSchemas(\n getSchema: ReturnType<typeof createSchemaFetcher>,\n snapshot: HubDirectoryGraphSnapshot,\n cache: DumpSchemaCache = { schemas: new Map(), errors: new Map() },\n): Promise<DumpSchemaCache> {\n const candidatesByHash = collectSchemaCandidates(snapshot);\n for (const [hash, candidates] of candidatesByHash) {\n if (cache.schemas.has(hash)) continue;\n cache.errors.delete(hash);\n const attempts: { reportedBy: string; interfaceId: string; error: string; }[] = [];\n for (const candidate of candidates) {\n try {\n const schema = await getSchema(\n candidate.interfaceId,\n hash,\n candidate.target,\n );\n cache.schemas.set(hash, schema);\n break;\n } catch (error) {\n attempts.push({\n reportedBy: candidate.reportedBy,\n interfaceId: candidate.interfaceId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (!cache.schemas.has(hash)) {\n cache.errors.set(hash, {\n interfaceIds: [...new Set(candidates.map((candidate) => candidate.interfaceId))],\n attempts,\n });\n }\n }\n return cache;\n}\n\nfunction buildHubDump(\n snapshot: HubDirectoryGraphSnapshot,\n cache: DumpSchemaCache,\n schemasComplete: boolean,\n): HubDump {\n const directories = Object.fromEntries(snapshot.directories.map((directory) => [\n directory.target.kind === \"addressed\" ? directory.target.serviceId : \"\",\n directory,\n ]));\n const activeHashes = new Set(collectSchemaCandidates(snapshot).keys());\n for (const hash of [...cache.schemas.keys()]) {\n if (!activeHashes.has(hash)) cache.schemas.delete(hash);\n }\n for (const hash of [...cache.errors.keys()]) {\n if (!activeHashes.has(hash)) cache.errors.delete(hash);\n }\n return {\n format: \"linkrpc-hub-dump\",\n version: 2,\n revision: snapshot.revision,\n complete: snapshot.complete,\n schemasComplete,\n root: snapshot.root,\n directories,\n listings: snapshot.result.listings,\n inaccessible: snapshot.result.inaccessible,\n schemas: Object.fromEntries(cache.schemas),\n schemaErrors: Object.fromEntries(cache.errors),\n };\n}\n\nfunction collectSchemaCandidates(\n snapshot: HubDirectoryGraphSnapshot,\n): Map<string, SchemaCandidate[]> {\n const result = new Map<string, SchemaCandidate[]>();\n for (const report of [snapshot.root, ...snapshot.directories]) {\n const target = report.target.serviceId;\n const reportedBy = target ?? \"\";\n for (const listing of report.nativeListings) {\n const candidates = result.get(listing.hash) ?? [];\n if (!candidates.some((candidate) =>\n candidate.reportedBy === reportedBy\n && candidate.interfaceId === listing.interfaceId\n )) {\n candidates.push({ reportedBy, target, interfaceId: listing.interfaceId });\n result.set(listing.hash, candidates);\n }\n }\n }\n return result;\n}\n\nasync function runStreamingLs(channel: CliChannel, opts: LsOptions): Promise<string> {\n const getSchema = createSchemaFetcher(channel, opts);\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n const patchMode = opts.dumpPatchesPath !== undefined;\n const patchPath = patchMode && opts.dumpPatchesPath !== \"-\"\n ? path.resolve(opts.dumpPatchesPath)\n : undefined;\n if (patchPath !== undefined) await mkdir(path.dirname(patchPath), { recursive: true });\n const file = patchPath !== undefined ? await open(patchPath, \"w\") : undefined;\n const writeLine = file !== undefined\n ? async (line: string) => { await file.write(`${line}\\n`); }\n : opts.emitLine;\n if (writeLine === undefined) {\n explorer.dispose();\n throw new Error(\"--dump-patches - requires an output sink\");\n }\n\n let currentDump = createInitialHubDump();\n let previousListings: readonly DiscoveredListing[] = [];\n let previousStreamValue: LsStreamEvent | undefined;\n const schemaCache: DumpSchemaCache = { schemas: new Map(), errors: new Map() };\n let queue = Promise.resolve();\n const unsubscribe = explorer.subscribe((event) => {\n queue = queue.then(async () => {\n if (patchMode) {\n if (event.type === \"settled\") {\n await fetchDumpSchemas(getSchema, event.snapshot, schemaCache);\n }\n const schemasComplete = event.snapshot.complete\n && [...collectSchemaCandidates(event.snapshot).keys()].every((hash) =>\n schemaCache.schemas.has(hash) || schemaCache.errors.has(hash));\n const next = buildHubDump(event.snapshot, schemaCache, schemasComplete);\n for (const operation of createJsonPatch(\n toJsonValue(currentDump),\n toJsonValue(next),\n )) {\n await writeLine(JSON.stringify(operation));\n }\n currentDump = next;\n } else {\n const nextStreamValue = createLsStreamEvent(event, previousListings);\n await writeLine(JSON.stringify(createPatchLogLine(event, previousStreamValue, nextStreamValue)));\n previousListings = event.snapshot.result.listings;\n previousStreamValue = nextStreamValue;\n }\n });\n });\n\n let stopWatch: (() => void) | undefined;\n try {\n if (opts.watch === true) {\n stopWatch = await explorer.watch(() => {});\n } else {\n await explorer.explore();\n }\n await queue;\n if (opts.watch === true) {\n await opts.stop;\n stopWatch();\n stopWatch = undefined;\n await explorer.whenIdle();\n await queue;\n }\n } finally {\n stopWatch?.();\n unsubscribe();\n explorer.dispose();\n try {\n await queue;\n } finally {\n await file?.close();\n }\n }\n\n if (patchPath !== undefined) {\n return dumpSummary(\"Wrote patches to\", patchPath, currentDump);\n }\n return \"\";\n}\n\ninterface LsStreamEvent {\n readonly type: HubDirectoryGraphEvent[\"type\"];\n readonly reason?: string;\n readonly revision: number;\n readonly complete: boolean;\n readonly target?: HubDirectoryNodeReport[\"target\"];\n readonly state?: HubDirectoryNodeReport[\"state\"];\n readonly added: readonly DiscoveredListing[];\n readonly removed: readonly DiscoveredListing[];\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n}\n\ntype LsPatchLogLine =\n | {\n readonly message: string;\n readonly time: number;\n readonly value: LsStreamEvent;\n }\n | {\n readonly message: string;\n readonly time: number;\n readonly patch: ReturnType<typeof createJsonPatch>;\n };\n\nfunction createPatchLogLine(\n event: HubDirectoryGraphEvent,\n previous: LsStreamEvent | undefined,\n next: LsStreamEvent,\n): LsPatchLogLine {\n const metadata = {\n message: describeLsStreamEvent(event),\n time: Date.now(),\n };\n if (previous === undefined) {\n return { ...metadata, value: next };\n }\n return {\n ...metadata,\n patch: createJsonPatch(toJsonValue(previous), toJsonValue(next)),\n };\n}\n\nfunction describeLsStreamEvent(event: HubDirectoryGraphEvent): string {\n if (event.type === \"settled\") return \"Directory exploration settled\";\n const subject = event.type === \"snapshot\"\n ? \"Directory snapshot\"\n : event.type === \"node-added\"\n ? \"Directory node added\"\n : event.type === \"node-updated\"\n ? \"Directory node updated\"\n : \"Directory node removed\";\n return `${subject}: ${event.reason}`;\n}\n\nfunction createLsStreamEvent(\n event: HubDirectoryGraphEvent,\n previousListings: readonly DiscoveredListing[],\n): LsStreamEvent {\n const current = event.snapshot.result.listings;\n const previousByKey = new Map(previousListings.map((listing) => [listingKey(listing), listing]));\n const currentByKey = new Map(current.map((listing) => [listingKey(listing), listing]));\n const node = \"node\" in event ? event.node : undefined;\n return {\n type: event.type,\n ...(\"reason\" in event ? { reason: event.reason } : {}),\n revision: event.snapshot.revision,\n complete: event.snapshot.complete,\n ...(node !== undefined ? { target: node.target, state: node.state } : {}),\n added: current.filter((listing) => !previousByKey.has(listingKey(listing))),\n removed: previousListings.filter((listing) => !currentByKey.has(listingKey(listing))),\n listings: current,\n inaccessible: event.snapshot.result.inaccessible,\n };\n}\n\nfunction listingKey(listing: ServiceListing): string {\n return `${listing.serviceId}\\0${listing.interfaceId}\\0${listing.hash}`;\n}\n\nfunction toJsonValue(value: unknown): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n\nfunction dumpSummary(prefix: string, destination: string, dump: HubDump): string {\n return `${prefix} ${destination} (${Object.keys(dump.directories).length + 1} directories, `\n + `${Object.keys(dump.schemas).length} schemas)`;\n}\n\nfunction renderTree(\n listings: readonly LsListing[],\n interfaceFilter: string | undefined,\n): string {\n if (listings.length === 0) {\n return interfaceFilter\n ? `(no interfaces matching \"${interfaceFilter}\")`\n : \"(no services)\";\n }\n\n const byService = new Map<string, LsListing[]>();\n for (const l of listings) {\n const bucket = byService.get(l.serviceId) ?? [];\n bucket.push(l);\n byService.set(l.serviceId, bucket);\n }\n const serviceIds = [...byService.keys()].sort((a, b) => {\n // Root first, then lexical.\n if (a === b) return 0;\n if (a === \"\") return -1;\n if (b === \"\") return 1;\n return a < b ? -1 : 1;\n });\n\n const lines: string[] = [];\n for (const sid of serviceIds) {\n lines.push(sid === \"\" ? \"(root)\" : sid);\n const ifaces = (byService.get(sid) ?? [])\n .slice()\n .sort((a, b) => (a.interfaceId < b.interfaceId ? -1 : a.interfaceId > b.interfaceId ? 1 : 0));\n for (let i = 0; i < ifaces.length; i++) {\n const isLast = i === ifaces.length - 1;\n const branch = isLast ? \"└── \" : \"├── \";\n const path = ifaces[i].path ? ` [${ifaces[i].path}]` : \"\";\n lines.push(`${branch}${ifaces[i].interfaceId} @ ${ifaces[i].hash}${path}`);\n const members = ifaces[i].members ?? [];\n for (let j = 0; j < members.length; j++) {\n const memberPrefix = isLast ? \" \" : \"│ \";\n const memberBranch = j === members.length - 1 ? \"└── \" : \"├── \";\n lines.push(\n `${memberPrefix}${memberBranch}${members[j].kind.padEnd(12)} ${members[j].name}`,\n );\n }\n }\n }\n return lines.join(\"\\n\");\n}\n","import { LinkRpcConnection } from \"@hediet/linkrpc\";\nimport type {\n NetworkTopologyGraph,\n SourcedTopologyLink,\n SourcedTopologyNode,\n TopologyNetworkSnapshot,\n} from \"@hediet/linkrpc-infra/inspection\";\nimport { TopologyNetworkClient } from \"@hediet/linkrpc-infra/inspection\";\nimport type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { formatJson } from \"../output\";\nimport { createDisplayForest, type DisplayForestNode } from \"./displayForest\";\nimport { StateJsonlWriter } from \"./stateJsonl\";\n\nexport type TopologyFormat = \"pretty\" | \"json\" | \"jsonl\";\n\nexport interface TopologyCommandOptions {\n readonly sources?: readonly string[];\n readonly maxDepth?: number;\n readonly timeoutMs?: number;\n readonly watch?: boolean;\n readonly format?: TopologyFormat;\n readonly nodeId?: string;\n readonly serviceId?: string;\n readonly kind?: \"hub\" | \"endpoint\";\n readonly search?: string;\n readonly emitLine?: (line: string) => void | Promise<void>;\n readonly emitFrame?: (frame: string) => void | Promise<void>;\n readonly onState?: (state: TopologyNetworkSnapshot) => void;\n readonly stop?: Promise<void>;\n}\n\nexport async function topologyCommand(\n channel: CliChannel,\n options: TopologyCommandOptions = {},\n): Promise<string> {\n const format = options.format ?? \"pretty\";\n compileTopologySearch(options.search);\n if (format === \"jsonl\" && options.emitLine === undefined) {\n throw new Error(\"JSONL topology output requires an output sink\");\n }\n if (options.watch === true && options.stop === undefined) {\n throw new Error(\"topology watch requires a stop signal\");\n }\n if (options.watch === true && format === \"pretty\" && options.emitFrame === undefined) {\n throw new Error(\"pretty topology watch requires a frame output sink\");\n }\n\n const connection = new LinkRpcConnection(channel);\n const client = new TopologyNetworkClient(connection);\n const writer = format === \"jsonl\" ? new StateJsonlWriter(options.emitLine!) : undefined;\n let latest: TopologyNetworkSnapshot | undefined;\n let outputQueue = Promise.resolve();\n const consume = (snapshot: TopologyNetworkSnapshot): void => {\n latest = filterTopologySnapshot(snapshot, options);\n options.onState?.(latest);\n if (writer !== undefined) {\n writer.write(latest, latest.revision);\n } else if (options.watch === true && format === \"pretty\") {\n const frame = renderTopology(latest);\n outputQueue = outputQueue.then(() => options.emitFrame!(frame));\n }\n };\n const sourceOptions = {\n ...(options.sources !== undefined ? { sourceServiceIds: options.sources } : {}),\n ...(options.maxDepth !== undefined ? { maxDepth: options.maxDepth } : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n };\n\n if (options.watch === true) {\n const watch = client.watch(sourceOptions);\n const unsubscribe = watch.subscribe(consume);\n try {\n await options.stop;\n } finally {\n await watch.cancel(\"topology CLI stopped\");\n unsubscribe();\n }\n } else {\n latest = await client.query(sourceOptions, { onSnapshot: consume });\n latest = filterTopologySnapshot(latest, options);\n }\n\n await outputQueue;\n await writer?.whenIdle();\n const snapshot = latest ?? filterTopologySnapshot(\n await client.query(sourceOptions),\n options,\n );\n if (format === \"json\") return formatJson(snapshot);\n if (format === \"pretty\") return options.watch === true ? \"\" : renderTopology(snapshot);\n return \"\";\n}\n\nexport function filterTopologySnapshot(\n snapshot: TopologyNetworkSnapshot,\n options: Pick<TopologyCommandOptions, \"nodeId\" | \"serviceId\" | \"kind\" | \"search\">,\n): TopologyNetworkSnapshot {\n const hasFilter = options.nodeId !== undefined\n || options.serviceId !== undefined\n || options.kind !== undefined\n || options.search !== undefined;\n if (!hasFilter) return snapshot;\n const search = compileTopologySearch(options.search);\n const graph = snapshot.graph;\n const routesByNode = new Map<string, NetworkTopologyGraph[\"routes\"]>();\n for (const route of graph.routes) {\n const routes = routesByNode.get(route.nodeId) ?? [];\n routesByNode.set(route.nodeId, [...routes, route]);\n }\n const matchingNodeIds = new Set(graph.nodes\n .filter((node) => {\n const routes = routesByNode.get(node.nodeId) ?? [];\n return (options.nodeId === undefined || node.nodeId === options.nodeId)\n && (options.kind === undefined || node.kind === options.kind)\n && (options.serviceId === undefined\n || routes.some((route) => route.serviceId === options.serviceId))\n && (search === undefined || search.test(JSON.stringify({\n node,\n routes,\n })));\n })\n .map((node) => node.nodeId));\n const nodes = graph.nodes.filter((node) => matchingNodeIds.has(node.nodeId));\n const nodeIds = new Set(nodes.map((node) => node.nodeId));\n return {\n ...snapshot,\n graph: {\n ...graph,\n nodes,\n links: graph.links.filter((link) =>\n nodeIds.has(link.from.nodeId) && nodeIds.has(link.to.nodeId)),\n routes: graph.routes.filter((route) =>\n nodeIds.has(route.nodeId)\n && (options.serviceId === undefined || route.serviceId === options.serviceId)),\n },\n };\n}\n\nfunction compileTopologySearch(search: string | undefined): RegExp | undefined {\n if (search === undefined) return undefined;\n try {\n return new RegExp(search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid topology search regexp: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n\nexport function renderTopology(snapshot: TopologyNetworkSnapshot): string {\n const sourceLines = snapshot.sources.map((source) => {\n const marker = source.state === \"ready\" ? \"✓\" : source.state === \"loading\" ? \"…\" : \"!\";\n return ` ${marker} ${source.serviceId}${source.error ? ` — ${source.error}` : \"\"}`;\n });\n const forest = createDisplayForest({\n nodes: snapshot.graph.nodes,\n edges: snapshot.graph.links,\n rootIds: snapshot.graph.sources.map((source) => source.entryNodeId),\n nodeId: (node) => node.nodeId,\n edgeKey: topologyLinkKey,\n edgeEndpoints: (link) => [link.from.nodeId, link.to.nodeId],\n });\n const routeMap = new Map<string, NetworkTopologyGraph[\"routes\"]>();\n for (const route of snapshot.graph.routes) {\n const routes = routeMap.get(route.nodeId) ?? [];\n routeMap.set(route.nodeId, [...routes, route]);\n }\n const treeLines: string[] = [];\n for (const root of forest.roots) renderTopologyNode(root, routeMap, treeLines, \"\");\n if (forest.crossEdges.length > 0) {\n treeLines.push(\"\", \"Additional links\");\n for (const link of forest.crossEdges) {\n treeLines.push(` ${formatEndpoint(link.from)} ↔ ${formatEndpoint(link.to)}`);\n }\n }\n const status = snapshot.complete ? \"complete\" : \"loading\";\n return [\n `LinkRPC topology (${status}, revision ${snapshot.revision})`,\n \"\",\n \"Sources\",\n ...(sourceLines.length > 0 ? sourceLines : [\" (none)\"]),\n \"\",\n \"Network\",\n ...(treeLines.length > 0 ? treeLines : [\" (empty)\"]),\n ].join(\"\\n\");\n}\n\nfunction renderTopologyNode(\n item: DisplayForestNode<SourcedTopologyNode, SourcedTopologyLink>,\n routes: ReadonlyMap<string, NetworkTopologyGraph[\"routes\"]>,\n lines: string[],\n prefix: string,\n): void {\n const label = participantLabel(item.node);\n lines.push(`${prefix}${label} [${item.node.kind ?? \"unknown\"}]`);\n for (const route of routes.get(item.node.nodeId) ?? []) {\n lines.push(`${prefix} ${route.match.padEnd(6)} ${route.serviceId} → ${route.portId}`);\n }\n for (let index = 0; index < item.children.length; index++) {\n const child = item.children[index];\n const last = index === item.children.length - 1;\n const branch = last ? \"└─ \" : \"├─ \";\n const childPrefix = prefix + (last ? \" \" : \"│ \");\n const childLines: string[] = [];\n renderTopologyNode(child, routes, childLines, childPrefix);\n childLines[0] = `${prefix}${branch}${childLines[0].slice(childPrefix.length)}`;\n lines.push(...childLines);\n }\n}\n\nfunction participantLabel(node: SourcedTopologyNode): string {\n for (const source of node.descriptors ?? []) {\n if (source.descriptor.label !== undefined) return source.descriptor.label;\n }\n return node.label ?? node.nodeId;\n}\n\nfunction topologyLinkKey(link: SourcedTopologyLink): string {\n const endpoints = [formatEndpoint(link.from), formatEndpoint(link.to)].sort();\n return `${endpoints[0]}\\0${endpoints[1]}`;\n}\n\nfunction formatEndpoint(endpoint: { readonly nodeId: string; readonly portId: string }): string {\n return `${endpoint.nodeId}:${endpoint.portId}`;\n}\n","import type { CliChannel } from \"@hediet/linkrpc-client-internal\";\n\nexport async function pingCommand(channel: CliChannel): Promise<string> {\n const start = performance.now();\n await channel.sendRequest(\"hubrpc.defaults::get\", {});\n const latencyMs = performance.now() - start;\n return `pong ${latencyMs.toFixed(1)}ms`;\n}\n","import { createInterface } from 'node:readline/promises';\nimport { stdin as input, stdout as output } from 'node:process';\nimport {\n LinkRpcConnection,\n type TopologyGraph,\n type TrafficEvent,\n type TrafficTransitEvent,\n} from '@hediet/linkrpc';\nimport {\n HubDirectoryExplorer,\n} from '@hediet/linkrpc/hub/common';\nimport type {\n ParticipantDescriptorSource,\n RouteClaim,\n} from '@hediet/linkrpc';\nimport {\n formatFlowSummary,\n TrafficFlowAggregator,\n} from '@hediet/linkrpc-hub';\nimport { TopologyClient, TrafficClient } from '@hediet/linkrpc-infra/inspection';\nimport type { CliChannel } from '@hediet/linkrpc-client-internal';\nimport { formatJson } from '../output';\n\nexport interface ParticipantWatchOptions {\n readonly search?: string;\n readonly nodeId?: string;\n readonly format?: 'pretty' | 'plain' | 'jsonl';\n readonly methodPrefix?: string;\n readonly payloadBytes?: number;\n readonly resume?: string | true;\n readonly stop: Promise<void>;\n readonly emit?: (line: string) => void;\n}\n\nexport interface ParticipantSummary {\n readonly nodeId: string;\n readonly descriptors: readonly ParticipantDescriptorSource[];\n readonly routeClaims: readonly RouteClaim[];\n readonly serviceIds: readonly string[];\n readonly sourceServices: readonly string[];\n}\n\ninterface InspectionSource {\n readonly serviceId: string;\n readonly graph: TopologyGraph;\n}\n\nconst TOPOLOGY_INTERFACE = 'hubrpc.topology';\n\nexport async function topologyParticipantsCommand(\n channel: CliChannel,\n search?: string,\n): Promise<string> {\n const participants = await discoverParticipants(channel);\n const filtered = filterParticipants(participants, search);\n return formatJson(filtered);\n}\n\nexport async function trafficWatchCommand(\n channel: CliChannel,\n options: ParticipantWatchOptions,\n): Promise<void> {\n const emit = options.emit ?? ((line: string) => process.stdout.write(line + '\\n'));\n const connection = new LinkRpcConnection(channel);\n const sources = await discoverTopologySources(channel, connection);\n let participants = summarizeParticipants(sources);\n let search = options.search;\n let nodeId = options.nodeId;\n let methodPrefix = options.methodPrefix;\n let payloadBytes = options.payloadBytes;\n let format = options.format;\n\n if (options.resume !== undefined) {\n const resumed = await readResume(options.resume);\n search ??= resumed.search;\n nodeId ??= resumed.nodeId;\n methodPrefix ??= resumed.methodPrefix;\n payloadBytes ??= resumed.payloadBytes;\n format ??= resumed.format;\n }\n\n let selected = selectParticipant(filterParticipants(participants, search), nodeId);\n if (selected === undefined && options.nodeId === undefined && search !== undefined) {\n selected = selectParticipant(filterParticipants(participants, search), undefined);\n }\n if (selected === undefined && process.stdin.isTTY && process.stdout.isTTY) {\n const prompted = await promptForParticipant(participants, search);\n selected = prompted?.participant;\n search = prompted?.search ?? search;\n }\n if (selected === undefined) {\n throw new Error(\n 'No participant matched. Use --search <regexp> or --node <nodeId>; '\n + 'interactive selection requires a TTY.',\n );\n }\n\n const serviceId = serviceForParticipant(sources, selected.nodeId);\n if (serviceId === undefined) {\n throw new Error(`Participant ${selected.nodeId} has no addressable service route.`);\n }\n\n await writeResume(options.resume, {\n search,\n nodeId: selected.nodeId,\n methodPrefix,\n format,\n payloadBytes,\n });\n\n format ??= process.stdout.isTTY ? 'pretty' : 'plain';\n const session = {\n type: 'session',\n version: 1,\n nodeId: selected.nodeId,\n serviceId,\n search,\n format,\n methodPrefix,\n payloadBytes,\n };\n if (format === 'jsonl') emit(JSON.stringify(session));\n else emit(`Watching participant ${selected.nodeId} via ${serviceId}`);\n\n let aggregator: TrafficFlowAggregator | undefined;\n if (format === 'pretty') {\n aggregator = new TrafficFlowAggregator({\n onFlow: (flow) => emit(formatFlowSummary(flow)),\n });\n }\n\n const traffic = new TrafficClient(connection, serviceId);\n const callbacks = {\n onTransit: (event: TrafficTransitEvent) => {\n if (aggregator !== undefined) {\n aggregator.add(event);\n } else if (format === 'jsonl') {\n emit(JSON.stringify({ type: 'transit', event }));\n } else {\n emit(formatTransit(event));\n }\n },\n onOverflow: (event: Extract<TrafficEvent, { type: 'overflow' }>) => {\n emit(format === 'jsonl'\n ? JSON.stringify({ type: 'overflow', event })\n : `traffic overflow: dropped ${event.dropped} events`);\n },\n onError: (error: unknown) => {\n emit(`traffic watch failed: ${error instanceof Error ? error.message : String(error)}`);\n },\n };\n const watch = payloadBytes === undefined\n ? traffic.watch(\n { methodPrefix },\n callbacks,\n )\n : traffic.watchWithPayloads(\n { methodPrefix, maxPayloadBytes: payloadBytes },\n callbacks,\n );\n\n try {\n await Promise.race([watch.done, options.stop]);\n } finally {\n await watch.cancel('cli-watch-ended');\n aggregator?.flush();\n aggregator?.dispose();\n if (format === 'jsonl') {\n emit(JSON.stringify({ type: 'end', reason: 'stopped' }));\n }\n }\n}\n\nasync function discoverTopologySources(\n channel: CliChannel,\n connection: LinkRpcConnection,\n): Promise<readonly InspectionSource[]> {\n const explorer = new HubDirectoryExplorer(channel, { maxDepth: 5 });\n const result = await explorer.explore();\n const serviceIds = unique(\n result.listings\n .filter((listing) => listing.interfaceId === TOPOLOGY_INTERFACE)\n .map((listing) => listing.serviceId),\n );\n const sources: InspectionSource[] = [];\n for (const serviceId of serviceIds) {\n const graph = await new TopologyClient(connection, serviceId).getGraph();\n sources.push({ serviceId, graph });\n }\n explorer.dispose();\n return sources;\n}\n\nasync function discoverParticipants(channel: CliChannel): Promise<readonly ParticipantSummary[]> {\n return summarizeParticipants(await discoverTopologySources(channel, new LinkRpcConnection(channel)));\n}\n\nfunction summarizeParticipants(sources: readonly InspectionSource[]): ParticipantSummary[] {\n const byNode = new Map<string, {\n descriptors: unknown[];\n routeClaims: unknown[];\n serviceIds: Set<string>;\n sourceServices: Set<string>;\n }>();\n for (const source of sources) {\n for (const node of source.graph.nodes) {\n const current = byNode.get(node.nodeId) ?? {\n descriptors: [],\n routeClaims: [],\n serviceIds: new Set<string>(),\n sourceServices: new Set<string>(),\n };\n current.descriptors.push(...(node.descriptors ?? []));\n byNode.set(node.nodeId, current);\n current.sourceServices.add(source.serviceId);\n }\n for (const route of source.graph.routes) {\n const current = byNode.get(route.nodeId) ?? {\n descriptors: [],\n routeClaims: [],\n serviceIds: new Set<string>(),\n sourceServices: new Set<string>(),\n };\n current.routeClaims.push(route);\n current.serviceIds.add(route.serviceId);\n byNode.set(route.nodeId, current);\n }\n }\n return [...byNode].map(([nodeId, value]) => ({\n nodeId,\n descriptors: value.descriptors,\n routeClaims: value.routeClaims,\n serviceIds: [...value.serviceIds].sort(),\n sourceServices: [...value.sourceServices].sort(),\n }));\n}\n\nfunction filterParticipants(\n participants: readonly ParticipantSummary[],\n search: string | undefined,\n): ParticipantSummary[] {\n if (search === undefined || search.length === 0) return [...participants];\n let expression: RegExp;\n try {\n expression = new RegExp(search, 'i');\n } catch (error) {\n throw new Error(`Invalid participant search regexp: ${error instanceof Error ? error.message : String(error)}`);\n }\n return participants.filter((participant) => expression.test(JSON.stringify(participant)));\n}\n\nfunction selectParticipant(\n participants: readonly ParticipantSummary[],\n nodeId: string | undefined,\n): ParticipantSummary | undefined {\n if (nodeId !== undefined) {\n return participants.find((participant) => participant.nodeId === nodeId);\n }\n return participants.length === 1 ? participants[0] : undefined;\n}\n\nasync function promptForParticipant(\n participants: readonly ParticipantSummary[],\n search: string | undefined,\n): Promise<{ participant: ParticipantSummary; search: string } | undefined> {\n const readline = createInterface({ input, output });\n try {\n const query = search ?? await readline.question('Search participants (regexp): ');\n const matches = filterParticipants(participants, query);\n if (matches.length === 0) return undefined;\n for (let i = 0; i < matches.length; i++) {\n output.write(`${i + 1}. ${participantLabel(matches[i])}\\n`);\n }\n const answer = await readline.question('Select participant: ');\n const index = Number.parseInt(answer, 10) - 1;\n return Number.isInteger(index) && index >= 0 && matches[index] !== undefined\n ? { participant: matches[index], search: query }\n : undefined;\n } finally {\n readline.close();\n }\n}\n\nfunction participantLabel(participant: ParticipantSummary): string {\n const labels = participant.descriptors\n .flatMap((value) => {\n if (typeof value !== 'object' || value === null) return [];\n const descriptor = (value as { descriptor?: { label?: unknown } }).descriptor;\n return typeof descriptor?.label === 'string' ? [descriptor.label] : [];\n });\n return `${labels[0] ?? participant.nodeId} (${participant.serviceIds.join(', ') || 'no routes'})`;\n}\n\nfunction serviceForParticipant(\n sources: readonly InspectionSource[],\n nodeId: string,\n): string | undefined {\n for (const source of sources) {\n const route = source.graph.routes.find((candidate) => candidate.nodeId === nodeId);\n if (route !== undefined) return route.serviceId;\n if (source.graph.entryNodeId === nodeId) return source.serviceId;\n }\n return undefined;\n}\n\nfunction formatTransit(event: TrafficTransitEvent): string {\n const direction = event.in !== undefined && event.out !== undefined\n ? 'forward'\n : event.in !== undefined ? 'in' : 'out';\n return `${event.ts} ${direction} ${event.kind} ${event.method ?? '(unknown)'}`;\n}\n\ninterface ResumeState {\n readonly search?: string;\n readonly nodeId?: string;\n readonly methodPrefix?: string;\n readonly format?: 'pretty' | 'plain' | 'jsonl';\n readonly payloadBytes?: number;\n}\n\nasync function readResume(value: string | true): Promise<ResumeState> {\n const { readFile } = await import('node:fs/promises');\n const path = value === true ? '.linkrpc-watch.json' : value;\n try {\n return JSON.parse(await readFile(path, 'utf8')) as ResumeState;\n } catch (error) {\n throw new Error(`Cannot resume from ${path}: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nasync function writeResume(value: string | true | undefined, state: ResumeState): Promise<void> {\n if (value === undefined) return;\n const { writeFile } = await import('node:fs/promises');\n const path = value === true ? '.linkrpc-watch.json' : value;\n await writeFile(path, `${JSON.stringify(state, null, 2)}\\n`, 'utf8');\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n","import type { MethodSchema, LinkRpcInterfaceSchema as SvcInterfaceSchema } from \"@hediet/linkrpc\";\nimport { type CliChannel, fetchSchema, findMethodInSchema } from \"@hediet/linkrpc-client-internal\";\nimport { formatJson } from \"../output\";\n\nexport interface SchemaCommandOptions {\n readonly interfaceId: string;\n readonly hash?: string;\n readonly method?: string;\n readonly json?: boolean;\n /**\n * Route the schema request to a specific service (form-3). Needed when\n * the interface lives behind a hub participant — the CLI's default\n * (form-2) target is the hub itself.\n */\n readonly serviceId?: string;\n}\n\nexport async function schemaCommand(channel: CliChannel, opts: SchemaCommandOptions): Promise<string> {\n const schema = await fetchSchema(channel, opts.interfaceId, opts.hash, opts.serviceId);\n if (opts.method !== undefined) {\n const m = findMethodInSchema(schema, opts.method);\n if (!m) throw new Error(`Method \"${opts.method}\" not found in ${schema.id}@${schema.hash}`);\n if (opts.json) return formatJson(m);\n return renderMethod(m);\n }\n if (opts.json) return formatJson(schema);\n return renderSchema(schema);\n}\n\nfunction renderSchema(schema: SvcInterfaceSchema): string {\n const lines: string[] = [];\n lines.push(`${schema.id}@${schema.hash}`);\n if (schema.description) lines.push(` ${schema.description}`);\n lines.push(\"\");\n for (const [name, method] of Object.entries(schema.methods)) {\n lines.push(renderMethod(name, method));\n lines.push(\"\");\n }\n return lines.join(\"\\n\").trimEnd();\n}\n\nfunction renderMethod(name: string, m: MethodSchema): string {\n const kind = m.result === undefined ? \"notify\" : \"request\";\n const lines: string[] = [];\n lines.push(` ${kind} ${name}`);\n if (m.summary) lines.push(` ${m.summary}`);\n if (m.description) lines.push(` ${m.description}`);\n lines.push(` params: ${shortSchema(m.params)}`);\n if (m.result) {\n lines.push(` result: ${shortSchema(m.result)}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction shortSchema(s: unknown): string {\n const str = JSON.stringify(s);\n if (str.length <= 120) return str;\n return str.slice(0, 117) + \"...\";\n}\n","/**\n * `linkrpc serve <config>` — run a hub from a declarative `HubConfig` file and\n * block until interrupted. Thin CLI face over the shared `@hediet/linkrpc-hub`\n * engine, so one config format drives the CLI hub, the server hub, and the\n * VS Code extension.\n */\nimport { loadHubConfig, printHubConfigSchema } from '@hediet/linkrpc-hub/config-file';\n\nexport { loadHubConfig, printHubConfigSchema };\n\nexport interface ServeOptions {\n /** Path to the JSON config file. */\n readonly configPath: string;\n /** Forward this process's stdin to the single cmd endpoint, if any. */\n readonly cmdInteractive?: boolean;\n /** Log every JSON-RPC message routed through the hub to stderr. */\n readonly logMessages?: boolean;\n}\n\n/** Run a hub from `configPath` and resolve only when interrupted (SIGINT/SIGTERM). */\nexport async function serveCommand(opts: ServeOptions): Promise<void> {\n const { serveHub } = await import('@hediet/linkrpc-hub/serve');\n await serveHub({\n configPath: opts.configPath,\n cmdInteractive: opts.cmdInteractive,\n logMessages: opts.logMessages,\n log: (line) => process.stderr.write(`linkrpc: ${line}\\n`),\n });\n}\n","import { connectTransports, type IMessageTransport } from '@hediet/linkrpc';\n\n/**\n * A live transport plus the seams to observe and tear down its underlying\n * resource. `IMessageTransport` itself exposes no close event, so `onClose`\n * bridges the raw socket / child-process lifecycle (mirrors how the docker\n * provenance proxy drives its splice teardown).\n */\nexport interface TransportHandle {\n readonly transport: IMessageTransport;\n /** Register a callback fired when the underlying resource closes. */\n onClose(cb: () => void): void;\n /** Tear down the transport and its underlying resource. */\n dispose(): void;\n}\n\nexport interface ConnectAsDeps {\n /**\n * Mint a single-use `hubrpc::initialize` token bound to the target's slot\n * (identity + granted namespace), via a `connectionTokenBinder` service.\n */\n mintToken(): Promise<string>;\n /**\n * Open the **hub-facing** transport, presenting `token` in its initialize\n * handshake so the hub's `{ token: \"bound\" }` handler redeems it — binding\n * this connection to the slot's identity + granted namespace.\n */\n openHubTransport(token: string): Promise<TransportHandle>;\n /**\n * Open the **target-facing** transport. Either a dial (ws / socket / uri /\n * cmd-stdio) or an accept-one (cmd-env: spawn the child and take the\n * connection it dials back).\n */\n openTargetTransport(): Promise<TransportHandle>;\n /**\n * Optional tap wrapping the target-facing transport so every spliced\n * message is logged. Tapping one edge captures the full bidirectional flow\n * (each message crosses it exactly once), so this is applied to a single\n * side to avoid double-logging.\n */\n tapTarget?(transport: IMessageTransport): IMessageTransport;\n /** Human-readable status sink. */\n log?(line: string): void;\n /** Resolves to stop the proxy (e.g. on SIGINT). */\n stop?: Promise<void>;\n}\n\n/**\n * Run a **connect-as** proxy until either side closes (or {@link\n * ConnectAsDeps.stop} resolves).\n *\n * Mints a bound token for a slot, opens the target-facing transport and the\n * hub-facing transport (which redeems the token → this connection *is* the slot\n * on the hub), and splices them message-for-message. The target thereby joins\n * the hub as a first-class participant with the slot's managed identity +\n * granted namespace, without running a local hub and without the target needing\n * to perform the hub handshake itself.\n *\n * Because all traffic crosses the CLI's splice point, {@link\n * ConnectAsDeps.tapTarget} yields complete `--log-messages` observability.\n */\nexport async function connectAs(deps: ConnectAsDeps): Promise<void> {\n const token = await deps.mintToken();\n\n const target = await deps.openTargetTransport();\n let hub: TransportHandle;\n try {\n hub = await deps.openHubTransport(token);\n } catch (e) {\n target.dispose();\n throw e;\n }\n\n const targetTransport = deps.tapTarget\n ? deps.tapTarget(target.transport)\n : target.transport;\n const pipe = connectTransports(targetTransport, hub.transport);\n\n deps.log?.('connect-as: bridged target ⟷ hub');\n\n await new Promise<void>((resolve) => {\n let done = false;\n const teardown = (): void => {\n if (done) return;\n done = true;\n pipe.dispose();\n try { target.dispose(); } catch { /* best effort */ }\n try { hub.dispose(); } catch { /* best effort */ }\n resolve();\n };\n target.onClose(teardown);\n hub.onClose(teardown);\n void deps.stop?.then(teardown);\n });\n\n deps.log?.('connect-as: closed');\n}\n","import {\n connectNdjson,\n type EndpointCommand,\n openWebSocket,\n runInitializeHandshake,\n WebSocketTransport,\n} from '@hediet/linkrpc/node';\nimport { SocketServer, type NodeSocketTransport } from '@hediet/linkrpc-hub/hub/server/node';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as net from 'node:net';\nimport type { ResolvedEndpoint } from '@hediet/linkrpc-client-internal';\nimport type { TransportHandle } from './connectAs';\n\n/** A ws / socket endpoint the CLI can dial (the only dial-able hub-facing kinds). */\nexport type DialEndpoint = Extract<ResolvedEndpoint, { kind: 'ws' | 'socket'; }>;\n\n/**\n * Dial a ws / socket endpoint as a client, presenting `token` in the\n * `hubrpc::initialize` handshake. Used for the hub-facing side (with the minted\n * bound token) and for ws / socket / uri targets (with the target's own token).\n */\nexport async function openDialTransport(spec: DialEndpoint, token: string): Promise<TransportHandle> {\n if (spec.kind === 'ws') {\n const ws = await openWebSocket(spec.url);\n const closeWs = (): void => { try { ws.close(); } catch { /* ignore */ } };\n const transport = new WebSocketTransport(ws, closeWs);\n try {\n await runInitializeHandshake(transport, { kind: 'client', token });\n } catch (err) {\n transport.dispose();\n closeWs();\n throw err;\n }\n return {\n transport,\n onClose: (cb) => ws.addEventListener('close', () => cb()),\n dispose: () => { transport.dispose(); closeWs(); },\n };\n }\n const socket = net.createConnection(spec.path);\n const { transport } = await connectNdjson({\n input: socket,\n output: socket,\n onClose: () => socket.destroy(),\n initialize: { kind: 'client', token },\n });\n return {\n transport,\n onClose: (cb) => socket.on('close', cb),\n dispose: () => socket.destroy(),\n };\n}\n\n/** Forward a child stream's lines to `log`, prefixed with `label`. */\nfunction _pipeLines(\n stream: NodeJS.ReadableStream | null,\n label: string,\n log: (line: string) => void,\n): void {\n if (!stream) return;\n stream.setEncoding('utf8');\n stream.on('data', (chunk: string) => {\n for (const line of chunk.split(/\\r?\\n/)) {\n if (line.length > 0) log(`[${label}] ${line}`);\n }\n });\n}\n\n/** Spawn a `cmd-stdio` target and talk linkrpc over its stdin/stdout. */\nexport async function openStdioTransport(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n cwd: string | undefined,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n const child = spawnCommand(command, {\n stdio: ['pipe', 'pipe', 'pipe'],\n ...(env !== undefined ? { env: { ...process.env, ...env } } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n });\n if (!child.stdin || !child.stdout) {\n throw new Error('connect-as: cmd-stdio child exposes no stdio');\n }\n // stdout carries the linkrpc protocol; only stderr can be logged.\n if (log) _pipeLines(child.stderr, 'target', log);\n const { transport } = await connectNdjson({\n input: child.stdout,\n output: child.stdin,\n onClose: () => { if (!child.killed) child.kill(); },\n });\n return {\n transport,\n onClose: (cb) => child.once('exit', cb),\n dispose: () => { transport.dispose(); if (!child.killed) child.kill(); },\n };\n}\n\n/**\n * Spawn a `cmd-env` target against a private socket the CLI listens on, and\n * take the single connection it dials back. This is the sole role-inverted\n * case: the target dials the CLI, so we accept rather than dial. No hub /\n * acceptor is needed — just the raw post-handshake transport to splice.\n */\nexport async function openAcceptOneTransport(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n cwd: string | undefined,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n const socketPath = SocketServer.allocSocketPath();\n const token = randomBytes(16).toString('hex');\n const server = await SocketServer.start({ endpoint: socketPath });\n\n const accepted = new Promise<NodeSocketTransport>((resolve) => {\n server.setConnectionHandler((t) => resolve(t));\n });\n const child = spawnCommand(command, {\n stdio: ['ignore', 'pipe', 'pipe'],\n env: { ...process.env, ...env, LINKRPC_ENDPOINT: socketPath, LINKRPC_TOKEN: token },\n ...(cwd !== undefined ? { cwd } : {}),\n });\n // The child talks to the CLI over the socket, so both its stdout and stderr\n // are free to surface (crucial for diagnosing a child that exits before\n // dialing back).\n if (log) {\n _pipeLines(child.stdout, 'target', log);\n _pipeLines(child.stderr, 'target', log);\n }\n\n let exited = false;\n child.once('exit', () => { exited = true; });\n\n const transport = await Promise.race([\n accepted,\n new Promise<never>((_resolve, reject) => {\n child.once('exit', (code) =>\n reject(new Error(`connect-as: cmd-env child exited (code ${code ?? '?'}) before connecting`)),\n );\n }),\n ]).catch((err: unknown) => {\n server.dispose();\n _unlink(socketPath);\n if (!child.killed) child.kill();\n throw err;\n });\n\n const dispose = (): void => {\n transport.dispose();\n server.dispose();\n _unlink(socketPath);\n if (!exited && !child.killed) child.kill();\n };\n return {\n transport,\n onClose: (cb) => { transport.onDidClose(cb); child.once('exit', cb); },\n dispose,\n };\n}\n\n/** Open the target-facing transport for any resolved endpoint kind. */\nexport function openTargetTransport(\n endpoint: ResolvedEndpoint,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n switch (endpoint.kind) {\n case 'cmd-env':\n return openAcceptOneTransport(endpoint.command, endpoint.env, endpoint.cwd, log);\n case 'cmd-stdio':\n return openStdioTransport(endpoint.command, endpoint.env, endpoint.cwd, log);\n case 'ws':\n case 'socket':\n return openDialTransport(endpoint, endpoint.token ?? '');\n }\n}\n\nfunction _unlink(socketPath: string): void {\n if (process.platform === 'win32') return;\n try { fs.unlinkSync(socketPath); } catch { /* ignore */ }\n}\n","import { LinkRpcConnection } from '@hediet/linkrpc';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { type EndpointCommand } from '@hediet/linkrpc/node';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport * as readline from 'node:readline';\nimport type { CliConnection } from '@hediet/linkrpc-client-internal';\nimport { mcpForwardInterface } from '../mcpForward.interface';\n\n/**\n * Front door for claiming a serviceId within the connection's granted\n * namespace — interface-form `hubGrantedServiceId::register`. Same claim the\n * `tunnel` command uses.\n */\nconst CLAIM_METHOD = `${hubGrantedServiceIdInterface.info.id}::register`;\n\n/** Read-only connection facts — `hubGrantedServiceId::get`. */\nconst INFO_METHOD = `${hubGrantedServiceIdInterface.info.id}::get`;\n\nexport interface McpForwardOptions {\n /**\n * Prefix to claim on the hub; the MCP server is reached as\n * `<serviceId>::vscode.mcp-forward::connect`. When omitted, the connection's\n * granted serviceId namespace (`hubGrantedServiceId::get`) is claimed as-is.\n */\n readonly serviceId?: string;\n /** Live, signed connection to the hub we claim `serviceId` on and serve from. */\n readonly local: CliConnection;\n /** The MCP server child to spawn (one fresh child per `connect` leg). */\n readonly command: EndpointCommand;\n /** Extra env merged on top of `process.env` for the spawned child. */\n readonly env?: Readonly<Record<string, string>>;\n /** Resolves to stop the forwarder (e.g. on SIGINT). Defaults to first SIGINT/SIGTERM. */\n readonly stop?: Promise<void>;\n /** Sink for human-readable status lines (defaults to stderr). */\n readonly log?: (line: string) => void;\n}\n\n/**\n * Run a transparent MCP forwarder until stopped.\n *\n * Serves {@link mcpForwardInterface} under `serviceId` on the hub: each inbound\n * `connect` request spawns a fresh MCP server child and shuttles raw JSON-RPC\n * frames between the child's stdio (newline-delimited JSON, the MCP stdio\n * transport framing) and the request's duplex stream. The forwarder never\n * parses MCP semantics — it only splits/joins NDJSON lines so each line becomes\n * one opaque `frame`. {@link LinkRpcConnection.enableReflection} is enabled so\n * the hub's directory can discover the service.\n *\n * Resolves when {@link McpForwardOptions.stop} resolves (or on SIGINT/SIGTERM).\n */\nexport async function mcpForwardCommand(opts: McpForwardOptions): Promise<void> {\n const log = opts.log ?? ((line) => process.stderr.write(line + '\\n'));\n\n // Default the prefix to the connection's granted serviceId namespace, so a\n // forwarder run without an explicit `--serviceId` claims exactly what it is\n // already entitled to.\n const serviceId = opts.serviceId ?? await _resolveGrantedServiceId(opts.local);\n\n // A typed connection that SERVES the forward interface over the hub link.\n // Constructing it binds the inbound handler, so do this BEFORE claiming so\n // no `connect` can race in between the claim landing and the handler being\n // installed.\n const conn = new LinkRpcConnection(opts.local.rpcChannel);\n conn.register(\n mcpForwardInterface,\n {\n connect: (_params, _ctx, stream) => _runLeg(opts.command, opts.env, stream, log),\n },\n { serviceId },\n );\n // Advertise reflection (directory + schemas) under the same serviceId so the\n // hub's referral-only directory fan-out can discover and surface this leg.\n conn.enableReflection({ serviceId });\n\n // Claim the prefix via the granted-namespace front door. The local\n // connection's signing layer signs this where the hub requires it.\n await opts.local.channel.sendRequest(CLAIM_METHOD, { serviceId });\n log(`mcp-forward: claimed '${serviceId}' — forwarding MCP stdio to ${_describe(opts.command)}`);\n\n await (opts.stop ?? _untilSignalled());\n log('mcp-forward: stopping');\n}\n\n/**\n * Resolve the connection's granted serviceId namespace\n * (`hubGrantedServiceId::get`) to use as the default forward prefix. Throws if\n * the namespace is empty (\"claim nothing freely\") — the caller must then pass an\n * explicit `--serviceId`.\n */\nasync function _resolveGrantedServiceId(local: CliConnection): Promise<string> {\n const info = await local.channel.sendRequest(INFO_METHOD, {}) as {\n grantedServiceIdNamespace?: string;\n } | null | undefined;\n const granted = info?.grantedServiceIdNamespace ?? '';\n if (granted.length === 0) {\n throw new Error(\n 'mcp-forward: this connection has no granted serviceId namespace to claim; '\n + 'pass an explicit --serviceId.',\n );\n }\n return granted;\n}\n\n/**\n * One MCP session leg: spawn the child, bridge stdio<->stream, and resolve when\n * the child exits or the caller cancels (killing the child).\n */\nfunction _runLeg(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n stream: { send(p: { frame: unknown; }): void; onMessage(l: (p: { frame: unknown; }) => void): void; readonly signal: AbortSignal; },\n log: (line: string) => void,\n): Promise<{ serverInfo?: { name: string; version: string; }; }> {\n return new Promise((resolve) => {\n const child = spawnCommand(command, {\n stdio: ['pipe', 'pipe', 'inherit'],\n ...(env !== undefined ? { env: { ...process.env, ...env } } : {}),\n });\n if (!child.stdin || !child.stdout) {\n log('mcp-forward: child exposes no stdio');\n if (!child.killed) child.kill();\n resolve({});\n return;\n }\n\n let settled = false;\n const rl = readline.createInterface({ input: child.stdout });\n const finish = (): void => {\n if (settled) return;\n settled = true;\n rl.close();\n if (!child.killed) child.kill();\n resolve({});\n };\n\n // child stdout (NDJSON) → stream: each line becomes one opaque frame.\n rl.on('line', (line) => {\n const trimmed = line.trim();\n if (trimmed.length === 0) return;\n let frame: unknown;\n try {\n frame = JSON.parse(trimmed);\n } catch {\n // MCP stdio servers must emit JSON-only on stdout; skip stray\n // non-JSON lines defensively instead of corrupting the stream.\n return;\n }\n if (stream.signal.aborted) return;\n stream.send({ frame });\n });\n\n // stream → child stdin: re-serialize each frame as one NDJSON line.\n stream.onMessage(({ frame }) => {\n if (!child.stdin || child.stdin.destroyed) return;\n child.stdin.write(JSON.stringify(frame) + '\\n');\n });\n\n // Caller cancelled / disconnected → kill the child and settle.\n if (stream.signal.aborted) {\n finish();\n return;\n }\n stream.signal.addEventListener('abort', finish, { once: true });\n\n // Child exited → settle so the consumer drops its client.\n child.on('exit', finish);\n child.on('error', (err) => {\n log(`mcp-forward: child error: ${String(err)}`);\n finish();\n });\n });\n}\n\n/** Resolve on the next `SIGINT` / `SIGTERM`. */\nfunction _untilSignalled(): Promise<void> {\n return new Promise<void>((resolve) => {\n const done = (): void => {\n process.removeListener('SIGINT', done);\n process.removeListener('SIGTERM', done);\n resolve();\n };\n process.once('SIGINT', done);\n process.once('SIGTERM', done);\n });\n}\n\n/** One-line description of the spawned command for logs. */\nfunction _describe(command: EndpointCommand): string {\n return 'argv' in command ? command.argv.join(' ') : command.command;\n}\n","import { LinkRpcConnection, type JsonValue } from '@hediet/linkrpc';\nimport {\n connectJsonRpcTransports,\n connectRawJsonRpcTransport,\n createNdjsonJsonRpcTransport,\n jsonRpcConnectionInterface,\n} from '@hediet/linkrpc-infra/json-rpc';\nimport type { CliConnection } from '@hediet/linkrpc-client-internal';\n\nexport interface JsonRpcStdioOptions {\n readonly local: CliConnection;\n readonly serviceId: string;\n readonly params?: JsonValue;\n readonly input?: NodeJS.ReadableStream;\n readonly output?: NodeJS.WritableStream;\n}\n\n/** Expose a remote `jsonRpcConnection` service as an NDJSON stdio endpoint. */\nexport async function jsonRpcStdioCommand(options: JsonRpcStdioOptions): Promise<void> {\n const connection = new LinkRpcConnection(options.local.rpcChannel);\n const client = connection.service(options.serviceId).get(jsonRpcConnectionInterface);\n const remote = await connectRawJsonRpcTransport(client, options.params);\n const stdio = createNdjsonJsonRpcTransport({\n input: options.input ?? process.stdin,\n output: options.output ?? process.stdout,\n });\n const bridge = connectJsonRpcTransports(remote, stdio);\n\n await new Promise<void>((resolve) => {\n let settled = false;\n const finish = (): void => {\n if (settled) return;\n settled = true;\n resolve();\n };\n remote.onClose(finish);\n stdio.onClose(finish);\n });\n bridge.dispose();\n remote.close('closed');\n stdio.close('closed');\n}\n","import { LinkRpcConnection } from '@hediet/linkrpc';\nimport { connectRawJsonRpcTransport, jsonRpcConnectionInterface } from '@hediet/linkrpc-infra/json-rpc';\nimport {\n startJsonRpcWebSocketExport,\n type JsonRpcExportRoute,\n type JsonRpcWebSocketExport,\n} from '@hediet/linkrpc-infra/json-rpc/node';\nimport type { CliConnection } from '@hediet/linkrpc-client-internal';\n\n/** Preserve option order so a missing path cannot shift subsequent service mappings. */\nexport class JsonRpcExportRoutes {\n private readonly _routes: JsonRpcExportRoute[] = [];\n private _pendingService: string | undefined;\n\n public serviceId(value: string): void {\n if (this._pendingService !== undefined) throw new Error('Each --serviceId must be followed by --path.');\n this._pendingService = value;\n }\n\n public path(value: string): void {\n if (this._pendingService === undefined) throw new Error('--path must follow --serviceId.');\n this._routes.push({ serviceId: this._pendingService, path: value.startsWith('/') ? value : `/${value}` });\n this._pendingService = undefined;\n }\n\n public getRoutes(): readonly JsonRpcExportRoute[] {\n if (this._pendingService !== undefined) throw new Error('Each --serviceId must be followed by --path.');\n return this._routes;\n }\n}\n\nexport async function jsonRpcExportCommand(options: {\n readonly local: Pick<CliConnection, 'rpcChannel'>;\n readonly targetEndpoint: string;\n readonly token?: string;\n readonly tokenQueryParameters?: readonly string[];\n readonly routes: readonly JsonRpcExportRoute[];\n readonly onError: (error: Error) => void;\n}): Promise<JsonRpcWebSocketExport> {\n const connection = new LinkRpcConnection(options.local.rpcChannel);\n return startJsonRpcWebSocketExport({\n ...options,\n openTransport: (serviceId, signal) => connectRawJsonRpcTransport(\n connection.service(serviceId).get(jsonRpcConnectionInterface),\n undefined,\n signal,\n ),\n });\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet globalObservableLogger;\nfunction addLogger(logger) {\n if (!globalObservableLogger) {\n globalObservableLogger = logger;\n }\n else if (globalObservableLogger instanceof ComposedLogger) {\n globalObservableLogger.loggers.push(logger);\n }\n else {\n globalObservableLogger = new ComposedLogger([globalObservableLogger, logger]);\n }\n}\nfunction getLogger() {\n return globalObservableLogger;\n}\nlet globalObservableLoggerFn = undefined;\nfunction setLogObservableFn(fn) {\n globalObservableLoggerFn = fn;\n}\nfunction logObservable(obs) {\n if (globalObservableLoggerFn) {\n globalObservableLoggerFn(obs);\n }\n}\nclass ComposedLogger {\n constructor(loggers) {\n this.loggers = loggers;\n }\n handleObservableCreated(observable, location) {\n for (const logger of this.loggers) {\n logger.handleObservableCreated(observable, location);\n }\n }\n handleOnListenerCountChanged(observable, newCount) {\n for (const logger of this.loggers) {\n logger.handleOnListenerCountChanged(observable, newCount);\n }\n }\n handleObservableUpdated(observable, info) {\n for (const logger of this.loggers) {\n logger.handleObservableUpdated(observable, info);\n }\n }\n handleAutorunCreated(autorun, location) {\n for (const logger of this.loggers) {\n logger.handleAutorunCreated(autorun, location);\n }\n }\n handleAutorunDisposed(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunDisposed(autorun);\n }\n }\n handleAutorunDependencyChanged(autorun, observable, change) {\n for (const logger of this.loggers) {\n logger.handleAutorunDependencyChanged(autorun, observable, change);\n }\n }\n handleAutorunStarted(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunStarted(autorun);\n }\n }\n handleAutorunFinished(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunFinished(autorun);\n }\n }\n handleDerivedDependencyChanged(derived, observable, change) {\n for (const logger of this.loggers) {\n logger.handleDerivedDependencyChanged(derived, observable, change);\n }\n }\n handleDerivedCleared(observable) {\n for (const logger of this.loggers) {\n logger.handleDerivedCleared(observable);\n }\n }\n handleBeginTransaction(transaction) {\n for (const logger of this.loggers) {\n logger.handleBeginTransaction(transaction);\n }\n }\n handleEndTransaction(transaction) {\n for (const logger of this.loggers) {\n logger.handleEndTransaction(transaction);\n }\n }\n}\n\nexport { addLogger, getLogger, logObservable, setLogObservableFn };\n//# sourceMappingURL=logging.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar DebugLocation;\n(function (DebugLocation) {\n let enabled = false;\n function enable() {\n enabled = true;\n }\n DebugLocation.enable = enable;\n function ofCaller() {\n return ofNthCaller(1);\n }\n DebugLocation.ofCaller = ofCaller;\n function ofNthCaller(n) {\n if (!enabled) {\n return undefined;\n }\n const Err = Error; // For the monaco editor checks, which don't have the nodejs types.\n const l = Err.stackTraceLimit;\n Err.stackTraceLimit = 3;\n const stack = new Error().stack;\n Err.stackTraceLimit = l;\n return DebugLocationImpl.fromStack(stack, n + 1);\n }\n DebugLocation.ofNthCaller = ofNthCaller;\n})(DebugLocation || (DebugLocation = {}));\nclass DebugLocationImpl {\n static fromStack(stack, parentIdx) {\n const lines = stack.split('\\n');\n const location = parseLine(lines[parentIdx + 1]);\n if (location) {\n return new DebugLocationImpl(location.fileName, location.line, location.column, location.id);\n }\n else {\n return undefined;\n }\n }\n constructor(fileName, line, column, id) {\n this.fileName = fileName;\n this.line = line;\n this.column = column;\n this.id = id;\n }\n}\nfunction parseLine(stackLine) {\n if (!stackLine) {\n return undefined;\n }\n const match = stackLine.match(/\\((.*):(\\d+):(\\d+)\\)/);\n if (match) {\n return {\n fileName: match[1],\n line: parseInt(match[2]),\n column: parseInt(match[3]),\n id: stackLine,\n };\n }\n const match2 = stackLine.match(/at ([^\\(\\)]*):(\\d+):(\\d+)/);\n if (match2) {\n return {\n fileName: match2[1],\n line: parseInt(match2[2]),\n column: parseInt(match2[3]),\n id: stackLine,\n };\n }\n return undefined;\n}\n\nexport { DebugLocation };\n//# sourceMappingURL=debugLocation.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nclass DebugNameData {\n constructor(owner, debugNameSource, referenceFn) {\n this.owner = owner;\n this.debugNameSource = debugNameSource;\n this.referenceFn = referenceFn;\n }\n getDebugName(target) {\n return getDebugName(target, this);\n }\n}\nconst countPerName = new Map();\nconst cachedDebugName = new WeakMap();\nfunction getDebugName(target, data) {\n const cached = cachedDebugName.get(target);\n if (cached) {\n return cached;\n }\n const dbgName = computeDebugName(target, data);\n if (dbgName) {\n let count = countPerName.get(dbgName) ?? 0;\n count++;\n countPerName.set(dbgName, count);\n const result = count === 1 ? dbgName : `${dbgName}#${count}`;\n cachedDebugName.set(target, result);\n return result;\n }\n return undefined;\n}\nfunction computeDebugName(self, data) {\n const cached = cachedDebugName.get(self);\n if (cached) {\n return cached;\n }\n const ownerStr = data.owner ? formatOwner(data.owner) + `.` : '';\n let result;\n const debugNameSource = data.debugNameSource;\n if (debugNameSource !== undefined) {\n if (typeof debugNameSource === 'function') {\n result = debugNameSource();\n if (result !== undefined) {\n return ownerStr + result;\n }\n }\n else {\n return ownerStr + debugNameSource;\n }\n }\n const referenceFn = data.referenceFn;\n if (referenceFn !== undefined) {\n result = getFunctionName(referenceFn);\n if (result !== undefined) {\n return ownerStr + result;\n }\n }\n if (data.owner !== undefined) {\n const key = findKey(data.owner, self);\n if (key !== undefined) {\n return ownerStr + key;\n }\n }\n return undefined;\n}\nfunction findKey(obj, value) {\n for (const key in obj) {\n if (obj[key] === value) {\n return key;\n }\n }\n return undefined;\n}\nconst countPerClassName = new Map();\nconst ownerId = new WeakMap();\nfunction formatOwner(owner) {\n const id = ownerId.get(owner);\n if (id) {\n return id;\n }\n const className = getClassName(owner) ?? 'Object';\n let count = countPerClassName.get(className) ?? 0;\n count++;\n countPerClassName.set(className, count);\n const result = count === 1 ? className : `${className}#${count}`;\n ownerId.set(owner, result);\n return result;\n}\nfunction getClassName(obj) {\n const ctor = obj.constructor;\n if (ctor) {\n if (ctor.name === 'Object') {\n return undefined;\n }\n return ctor.name;\n }\n return undefined;\n}\nfunction getFunctionName(fn) {\n const fnSrc = fn.toString();\n // Pattern: /** @description ... */\n const regexp = /\\/\\*\\*\\s*@description\\s*([^*]*)\\*\\//;\n const match = regexp.exec(fnSrc);\n const result = match ? match[1] : undefined;\n return result?.trim();\n}\n\nexport { DebugNameData, getClassName, getDebugName, getFunctionName };\n//# sourceMappingURL=debugName.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { DebugLocation } from '../debugLocation.js';\nimport { getFunctionName } from '../debugName.js';\nimport { logObservable, getLogger } from '../logging/logging.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet _derived;\n/**\n * @internal\n * This is to allow splitting files.\n*/\nfunction _setDerivedOpts(derived) {\n _derived = derived;\n}\nlet _recomputeInitiallyAndOnChange;\nfunction _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange) {\n _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange;\n}\nlet _keepObserved;\nfunction _setKeepObserved(keepObserved) {\n _keepObserved = keepObserved;\n}\nlet _debugGetDependencyGraph;\nfunction _setDebugGetDependencyGraph(debugGetDependencyGraph) {\n _debugGetDependencyGraph = debugGetDependencyGraph;\n}\nclass ConvenientObservable {\n get TChange() { return null; }\n reportChanges() {\n this.get();\n }\n /** @sealed */\n read(reader) {\n if (reader) {\n return reader.readObservable(this);\n }\n else {\n return this.get();\n }\n }\n map(fnOrOwner, fnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n const owner = fnOrUndefined === undefined ? undefined : fnOrOwner;\n const fn = fnOrUndefined === undefined ? fnOrOwner : fnOrUndefined;\n return _derived({\n owner,\n debugName: () => {\n const name = getFunctionName(fn);\n if (name !== undefined) {\n return name;\n }\n // regexp to match `x => x.y` or `x => x?.y` where x and y can be arbitrary identifiers (uses backref):\n const regexp = /^\\s*\\(?\\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\\s*\\)?\\s*=>\\s*\\1(?:\\??)\\.([a-zA-Z_$][a-zA-Z_$0-9]*)\\s*$/;\n const match = regexp.exec(fn.toString());\n if (match) {\n return `${this.debugName}.${match[2]}`;\n }\n if (!owner) {\n return `${this.debugName} (mapped)`;\n }\n return undefined;\n },\n debugReferenceFn: fn,\n }, (reader) => fn(this.read(reader), reader), debugLocation);\n }\n /**\n * @sealed\n * Converts an observable of an observable value into a direct observable of the value.\n */\n flatten() {\n return _derived({\n owner: undefined,\n debugName: () => `${this.debugName} (flattened)`,\n }, (reader) => this.read(reader).read(reader));\n }\n recomputeInitiallyAndOnChange(store, handleValue) {\n store.add(_recomputeInitiallyAndOnChange(this, handleValue));\n return this;\n }\n /**\n * Ensures that this observable is observed. This keeps the cache alive.\n * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get).\n * Use `recomputeInitiallyAndOnChange` for eager evaluation.\n */\n keepObserved(store) {\n store.add(_keepObserved(this));\n return this;\n }\n get debugValue() {\n return this.get();\n }\n debugGetDependencyGraph() {\n return _debugGetDependencyGraph(this);\n }\n}\nclass BaseObservable extends ConvenientObservable {\n constructor(debugLocation) {\n super();\n this._observers = new Set();\n getLogger()?.handleObservableCreated(this, debugLocation);\n }\n addObserver(observer) {\n const len = this._observers.size;\n this._observers.add(observer);\n if (len === 0) {\n this.onFirstObserverAdded();\n }\n if (len !== this._observers.size) {\n getLogger()?.handleOnListenerCountChanged(this, this._observers.size);\n }\n }\n removeObserver(observer) {\n const deleted = this._observers.delete(observer);\n if (deleted && this._observers.size === 0) {\n this.onLastObserverRemoved();\n }\n if (deleted) {\n getLogger()?.handleOnListenerCountChanged(this, this._observers.size);\n }\n }\n onFirstObserverAdded() { }\n onLastObserverRemoved() { }\n log() {\n const hadLogger = !!getLogger();\n logObservable(this);\n if (!hadLogger) {\n getLogger()?.handleObservableCreated(this, DebugLocation.ofCaller());\n }\n return this;\n }\n debugGetObservers() {\n return this._observers;\n }\n}\n\nexport { BaseObservable, ConvenientObservable, _setDebugGetDependencyGraph, _setDerivedOpts, _setKeepObserved, _setRecomputeInitiallyAndOnChange };\n//# sourceMappingURL=baseObservable.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction toDisposable(fn) {\n return {\n dispose: fn\n };\n}\nclass BugIndicatingError extends Error {\n constructor(message) {\n super(message || 'An unexpected bug occurred.');\n Object.setPrototypeOf(this, BugIndicatingError.prototype);\n // Because we know for sure only buggy code throws this,\n // we definitely want to break here and fix the bug.\n // eslint-disable-next-line no-debugger\n // debugger;\n }\n}\nfunction onBugIndicatingError(error) {\n // debugger;\n throw error;\n}\nfunction onUnexpectedError(error) {\n console.error('Unexpected error:', error);\n}\n/**\n * Compares two items for equality using strict equality.\n*/\nconst strictEquals = (a, b) => a === b;\n\nexport { BugIndicatingError, onBugIndicatingError, onUnexpectedError, strictEquals, toDisposable };\n//# sourceMappingURL=deps.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nclass DisposableStore {\n constructor() {\n this.disposables = [];\n this._isDisposed = false;\n }\n get isDisposed() { return this._isDisposed; }\n dispose() {\n this.clear();\n this._isDisposed = true;\n }\n add(disposable) {\n if (disposable) {\n this.disposables.push(disposable);\n }\n return disposable;\n }\n remove(disposable) {\n if (!disposable) {\n return disposable;\n }\n const index = this.disposables.indexOf(disposable);\n if (index !== -1) {\n this.disposables.splice(index, 1);\n }\n return disposable;\n }\n clear() {\n for (const disposable of this.disposables) {\n disposable.dispose();\n }\n this.disposables = [];\n }\n leakItems() {\n this.disposables = [];\n }\n}\nclass Disposable {\n constructor() {\n this._store = new DisposableStore();\n }\n dispose() {\n this._store.dispose();\n }\n _register(t) {\n this._store.add(t);\n return t;\n }\n _registerOrDispose(t) {\n if (t) {\n if (this._store.isDisposed) {\n t.dispose();\n }\n else {\n this._store.add(t);\n }\n }\n return t;\n }\n}\n\nexport { Disposable, DisposableStore };\n//# sourceMappingURL=disposables.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { BaseObservable } from './baseObservable.js';\nimport { BugIndicatingError, onBugIndicatingError } from '../commonFacade/deps.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction derivedStateToString(state) {\n switch (state) {\n case 0 /* DerivedState.initial */: return 'initial';\n case 1 /* DerivedState.dependenciesMightHaveChanged */: return 'dependenciesMightHaveChanged';\n case 2 /* DerivedState.stale */: return 'stale';\n case 3 /* DerivedState.upToDate */: return 'upToDate';\n default: return '<unknown>';\n }\n}\nclass Derived extends BaseObservable {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? '(anonymous)';\n }\n constructor(_debugNameData, _computeFn, _changeTracker, _handleLastObserverRemoved = undefined, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this._computeFn = _computeFn;\n this._changeTracker = _changeTracker;\n this._handleLastObserverRemoved = _handleLastObserverRemoved;\n this._equalityComparator = _equalityComparator;\n this._state = 0 /* DerivedState.initial */;\n this._value = undefined;\n this._updateCount = 0;\n this._dependencies = new Set();\n this._dependenciesToBeRemoved = new Set();\n this._changeSummary = undefined;\n this._isUpdating = false;\n this._isComputing = false;\n this._didReportChange = false;\n this._isInBeforeUpdate = false;\n this._isReaderValid = false;\n this._store = undefined;\n this._delayedStore = undefined;\n this._removedObserverToCallEndUpdateOn = null;\n this._changeSummary = this._changeTracker?.createChangeSummary(undefined);\n }\n onLastObserverRemoved() {\n /**\n * We are not tracking changes anymore, thus we have to assume\n * that our cache is invalid.\n */\n this._state = 0 /* DerivedState.initial */;\n this._value = undefined;\n getLogger()?.handleDerivedCleared(this);\n for (const d of this._dependencies) {\n d.removeObserver(this);\n }\n this._dependencies.clear();\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n if (this._delayedStore !== undefined) {\n this._delayedStore.dispose();\n this._delayedStore = undefined;\n }\n this._handleLastObserverRemoved?.();\n }\n get() {\n const checkEnabled = false; // TODO set to true\n if (this._isComputing && checkEnabled) {\n // investigate why this fails in the diff editor!\n throw new BugIndicatingError('Cyclic deriveds are not supported yet!');\n }\n if (this._observers.size === 0) {\n let result;\n // Without observers, we don't know when to clean up stuff.\n // Thus, we don't cache anything to prevent memory leaks.\n try {\n this._isReaderValid = true;\n let changeSummary = undefined;\n if (this._changeTracker) {\n changeSummary = this._changeTracker.createChangeSummary(undefined);\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n }\n result = this._computeFn(this, changeSummary);\n }\n finally {\n this._isReaderValid = false;\n }\n // Clear new dependencies\n this.onLastObserverRemoved();\n return result;\n }\n else {\n do {\n // We might not get a notification for a dependency that changed while it is updating,\n // thus we also have to ask all our depedencies if they changed in this case.\n if (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */) {\n for (const d of this._dependencies) {\n /** might call {@link handleChange} indirectly, which could make us stale */\n d.reportChanges();\n if (this._state === 2 /* DerivedState.stale */) {\n // The other dependencies will refresh on demand, so early break\n break;\n }\n }\n }\n // We called report changes of all dependencies.\n // If we are still not stale, we can assume to be up to date again.\n if (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */) {\n this._state = 3 /* DerivedState.upToDate */;\n }\n if (this._state !== 3 /* DerivedState.upToDate */) {\n this._recompute();\n }\n // In case recomputation changed one of our dependencies, we need to recompute again.\n } while (this._state !== 3 /* DerivedState.upToDate */);\n return this._value;\n }\n }\n _recompute() {\n let didChange = false;\n this._isComputing = true;\n this._didReportChange = false;\n const emptySet = this._dependenciesToBeRemoved;\n this._dependenciesToBeRemoved = this._dependencies;\n this._dependencies = emptySet;\n try {\n const changeSummary = this._changeSummary;\n this._isReaderValid = true;\n if (this._changeTracker) {\n this._isInBeforeUpdate = true;\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n this._isInBeforeUpdate = false;\n this._changeSummary = this._changeTracker?.createChangeSummary(changeSummary);\n }\n const hadValue = this._state !== 0 /* DerivedState.initial */;\n const oldValue = this._value;\n this._state = 3 /* DerivedState.upToDate */;\n const delayedStore = this._delayedStore;\n if (delayedStore !== undefined) {\n this._delayedStore = undefined;\n }\n try {\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n /** might call {@link handleChange} indirectly, which could invalidate us */\n this._value = this._computeFn(this, changeSummary);\n }\n finally {\n this._isReaderValid = false;\n // We don't want our observed observables to think that they are (not even temporarily) not being observed.\n // Thus, we only unsubscribe from observables that are definitely not read anymore.\n for (const o of this._dependenciesToBeRemoved) {\n o.removeObserver(this);\n }\n this._dependenciesToBeRemoved.clear();\n if (delayedStore !== undefined) {\n delayedStore.dispose();\n }\n }\n didChange = this._didReportChange || (hadValue && !(this._equalityComparator(oldValue, this._value)));\n getLogger()?.handleObservableUpdated(this, {\n oldValue,\n newValue: this._value,\n change: undefined,\n didChange,\n hadValue,\n });\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n this._isComputing = false;\n if (!this._didReportChange && didChange) {\n for (const r of this._observers) {\n r.handleChange(this, undefined);\n }\n }\n else {\n this._didReportChange = false;\n }\n }\n toString() {\n return `LazyDerived<${this.debugName}>`;\n }\n // IObserver Implementation\n beginUpdate(_observable) {\n if (this._isUpdating) {\n throw new BugIndicatingError('Cyclic deriveds are not supported yet!');\n }\n this._updateCount++;\n this._isUpdating = true;\n try {\n const propagateBeginUpdate = this._updateCount === 1;\n if (this._state === 3 /* DerivedState.upToDate */) {\n this._state = 1 /* DerivedState.dependenciesMightHaveChanged */;\n // If we propagate begin update, that will already signal a possible change.\n if (!propagateBeginUpdate) {\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n if (propagateBeginUpdate) {\n for (const r of this._observers) {\n r.beginUpdate(this); // This signals a possible change\n }\n }\n }\n finally {\n this._isUpdating = false;\n }\n }\n endUpdate(_observable) {\n this._updateCount--;\n if (this._updateCount === 0) {\n // End update could change the observer list.\n const observers = [...this._observers];\n for (const r of observers) {\n r.endUpdate(this);\n }\n if (this._removedObserverToCallEndUpdateOn) {\n const observers = [...this._removedObserverToCallEndUpdateOn];\n this._removedObserverToCallEndUpdateOn = null;\n for (const r of observers) {\n r.endUpdate(this);\n }\n }\n }\n }\n handlePossibleChange(observable) {\n // In all other states, observers already know that we might have changed.\n if (this._state === 3 /* DerivedState.upToDate */ && this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable)) {\n this._state = 1 /* DerivedState.dependenciesMightHaveChanged */;\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n handleChange(observable, change) {\n if (this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable) || this._isInBeforeUpdate) {\n getLogger()?.handleDerivedDependencyChanged(this, observable, change);\n let shouldReact = false;\n try {\n shouldReact = this._changeTracker ? this._changeTracker.handleChange({\n changedObservable: observable,\n change,\n didChange: (o) => o === observable,\n }, this._changeSummary) : true;\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n const wasUpToDate = this._state === 3 /* DerivedState.upToDate */;\n if (shouldReact && (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */ || wasUpToDate)) {\n this._state = 2 /* DerivedState.stale */;\n if (wasUpToDate) {\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n }\n }\n // IReader Implementation\n _ensureReaderValid() {\n if (!this._isReaderValid) {\n throw new BugIndicatingError('The reader object cannot be used outside its compute function!');\n }\n }\n readObservable(observable) {\n this._ensureReaderValid();\n // Subscribe before getting the value to enable caching\n observable.addObserver(this);\n /** This might call {@link handleChange} indirectly, which could invalidate us */\n const value = observable.get();\n // Which is why we only add the observable to the dependencies now.\n this._dependencies.add(observable);\n this._dependenciesToBeRemoved.delete(observable);\n return value;\n }\n reportChange(change) {\n this._ensureReaderValid();\n this._didReportChange = true;\n // TODO add logging\n for (const r of this._observers) {\n r.handleChange(this, change);\n }\n }\n get store() {\n this._ensureReaderValid();\n if (this._store === undefined) {\n this._store = new DisposableStore();\n }\n return this._store;\n }\n get delayedStore() {\n this._ensureReaderValid();\n if (this._delayedStore === undefined) {\n this._delayedStore = new DisposableStore();\n }\n return this._delayedStore;\n }\n addObserver(observer) {\n const shouldCallBeginUpdate = !this._observers.has(observer) && this._updateCount > 0;\n super.addObserver(observer);\n if (shouldCallBeginUpdate) {\n if (this._removedObserverToCallEndUpdateOn && this._removedObserverToCallEndUpdateOn.has(observer)) {\n this._removedObserverToCallEndUpdateOn.delete(observer);\n }\n else {\n observer.beginUpdate(this);\n }\n }\n }\n removeObserver(observer) {\n if (this._observers.has(observer) && this._updateCount > 0) {\n if (!this._removedObserverToCallEndUpdateOn) {\n this._removedObserverToCallEndUpdateOn = new Set();\n }\n this._removedObserverToCallEndUpdateOn.add(observer);\n }\n super.removeObserver(observer);\n }\n debugGetState() {\n return {\n state: this._state,\n stateStr: derivedStateToString(this._state),\n updateCount: this._updateCount,\n isComputing: this._isComputing,\n dependencies: this._dependencies,\n value: this._value,\n };\n }\n debugSetValue(newValue) {\n this._value = newValue;\n }\n debugRecompute() {\n if (!this._isComputing) {\n this._recompute();\n }\n else {\n this._state = 2 /* DerivedState.stale */;\n }\n }\n setValue(newValue, tx, change) {\n this._value = newValue;\n const observers = this._observers;\n tx.updateObserver(this, this);\n for (const d of observers) {\n d.handleChange(this, change);\n }\n }\n}\nclass DerivedWithSetter extends Derived {\n constructor(debugNameData, computeFn, changeTracker, handleLastObserverRemoved = undefined, equalityComparator, set, debugLocation) {\n super(debugNameData, computeFn, changeTracker, handleLastObserverRemoved, equalityComparator, debugLocation);\n this.set = set;\n }\n}\n\nexport { Derived, DerivedWithSetter };\n//# sourceMappingURL=derivedImpl.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugLocation } from '../debugLocation.js';\nimport { DebugNameData } from '../debugName.js';\nimport { _setDerivedOpts } from './baseObservable.js';\nimport { Derived, DerivedWithSetter } from './derivedImpl.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction derived(computeFnOrOwner, computeFn, debugLocation = DebugLocation.ofCaller()) {\n if (computeFn !== undefined) {\n return new Derived(new DebugNameData(computeFnOrOwner, undefined, computeFn), computeFn, undefined, undefined, strictEquals, debugLocation);\n }\n return new Derived(new DebugNameData(undefined, undefined, computeFnOrOwner), computeFnOrOwner, undefined, undefined, strictEquals, debugLocation);\n}\nfunction derivedWithSetter(owner, computeFn, setter, debugLocation = DebugLocation.ofCaller()) {\n return new DerivedWithSetter(new DebugNameData(owner, undefined, computeFn), computeFn, undefined, undefined, strictEquals, setter, debugLocation);\n}\nfunction derivedOpts(options, computeFn, debugLocation = DebugLocation.ofCaller()) {\n return new Derived(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn), computeFn, undefined, options.onLastObserverRemoved, options.equalsFn ?? strictEquals, debugLocation);\n}\n_setDerivedOpts(derivedOpts);\n/**\n * Represents an observable that is derived from other observables.\n * The value is only recomputed when absolutely needed.\n *\n * {@link computeFn} should start with a JS Doc using `@description` to name the derived.\n *\n * Use `createEmptyChangeSummary` to create a \"change summary\" that can collect the changes.\n * Use `handleChange` to add a reported change to the change summary.\n * The compute function is given the last change summary.\n * The change summary is discarded after the compute function was called.\n *\n * @see derived\n */\nfunction derivedHandleChanges(options, computeFn, debugLocation = DebugLocation.ofCaller()) {\n return new Derived(new DebugNameData(options.owner, options.debugName, undefined), computeFn, options.changeTracker, undefined, options.equalityComparer ?? strictEquals, debugLocation);\n}\nfunction derivedWithStore(computeFnOrOwner, computeFnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n let computeFn;\n let owner;\n if (computeFnOrUndefined === undefined) {\n computeFn = computeFnOrOwner;\n owner = undefined;\n }\n else {\n owner = computeFnOrOwner;\n computeFn = computeFnOrUndefined;\n }\n // Intentionally re-assigned in case an inactive observable is re-used later\n // eslint-disable-next-line local/code-no-potentially-unsafe-disposables\n let store = new DisposableStore();\n return new Derived(new DebugNameData(owner, undefined, computeFn), r => {\n if (store.isDisposed) {\n store = new DisposableStore();\n }\n else {\n store.clear();\n }\n return computeFn(r, store);\n }, undefined, () => store.dispose(), strictEquals, debugLocation);\n}\nfunction derivedDisposable(computeFnOrOwner, computeFnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n let computeFn;\n let owner;\n if (computeFnOrUndefined === undefined) {\n computeFn = computeFnOrOwner;\n owner = undefined;\n }\n else {\n owner = computeFnOrOwner;\n computeFn = computeFnOrUndefined;\n }\n let store = undefined;\n return new Derived(new DebugNameData(owner, undefined, computeFn), r => {\n if (!store) {\n store = new DisposableStore();\n }\n else {\n store.clear();\n }\n const result = computeFn(r);\n if (result) {\n store.add(result);\n }\n return result;\n }, undefined, () => {\n if (store) {\n store.dispose();\n store = undefined;\n }\n }, strictEquals, debugLocation);\n}\n\nexport { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter, derivedWithStore };\n//# sourceMappingURL=derived.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onBugIndicatingError, BugIndicatingError } from '../commonFacade/deps.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction autorunStateToString(state) {\n switch (state) {\n case 1 /* AutorunState.dependenciesMightHaveChanged */: return 'dependenciesMightHaveChanged';\n case 2 /* AutorunState.stale */: return 'stale';\n case 3 /* AutorunState.upToDate */: return 'upToDate';\n default: return '<unknown>';\n }\n}\nclass AutorunObserver {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? '(anonymous)';\n }\n constructor(_debugNameData, _runFn, _changeTracker, debugLocation) {\n this._debugNameData = _debugNameData;\n this._runFn = _runFn;\n this._changeTracker = _changeTracker;\n this._state = 2 /* AutorunState.stale */;\n this._updateCount = 0;\n this._disposed = false;\n this._dependencies = new Set();\n this._dependenciesToBeRemoved = new Set();\n this._isRunning = false;\n this._store = undefined;\n this._delayedStore = undefined;\n this._changeSummary = this._changeTracker?.createChangeSummary(undefined);\n getLogger()?.handleAutorunCreated(this, debugLocation);\n this._run();\n }\n dispose() {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n for (const o of this._dependencies) {\n o.removeObserver(this); // Warning: external call!\n }\n this._dependencies.clear();\n if (this._store !== undefined) {\n this._store.dispose();\n }\n if (this._delayedStore !== undefined) {\n this._delayedStore.dispose();\n }\n getLogger()?.handleAutorunDisposed(this);\n }\n _run() {\n const emptySet = this._dependenciesToBeRemoved;\n this._dependenciesToBeRemoved = this._dependencies;\n this._dependencies = emptySet;\n this._state = 3 /* AutorunState.upToDate */;\n try {\n if (!this._disposed) {\n getLogger()?.handleAutorunStarted(this);\n const changeSummary = this._changeSummary;\n const delayedStore = this._delayedStore;\n if (delayedStore !== undefined) {\n this._delayedStore = undefined;\n }\n try {\n this._isRunning = true;\n if (this._changeTracker) {\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n this._changeSummary = this._changeTracker.createChangeSummary(changeSummary); // Warning: external call!\n }\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n this._runFn(this, changeSummary); // Warning: external call!\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n finally {\n this._isRunning = false;\n if (delayedStore !== undefined) {\n delayedStore.dispose();\n }\n }\n }\n }\n finally {\n if (!this._disposed) {\n getLogger()?.handleAutorunFinished(this);\n }\n // We don't want our observed observables to think that they are (not even temporarily) not being observed.\n // Thus, we only unsubscribe from observables that are definitely not read anymore.\n for (const o of this._dependenciesToBeRemoved) {\n o.removeObserver(this); // Warning: external call!\n }\n this._dependenciesToBeRemoved.clear();\n }\n }\n toString() {\n return `Autorun<${this.debugName}>`;\n }\n // IObserver implementation\n beginUpdate(_observable) {\n if (this._state === 3 /* AutorunState.upToDate */) {\n this._state = 1 /* AutorunState.dependenciesMightHaveChanged */;\n }\n this._updateCount++;\n }\n endUpdate(_observable) {\n try {\n if (this._updateCount === 1) {\n do {\n if (this._state === 1 /* AutorunState.dependenciesMightHaveChanged */) {\n this._state = 3 /* AutorunState.upToDate */;\n for (const d of this._dependencies) {\n d.reportChanges(); // Warning: external call!\n if (this._state === 2 /* AutorunState.stale */) {\n // The other dependencies will refresh on demand\n break;\n }\n }\n }\n if (this._state !== 3 /* AutorunState.upToDate */) {\n this._run(); // Warning: indirect external call!\n }\n } while (this._state !== 3 /* AutorunState.upToDate */);\n }\n }\n finally {\n this._updateCount--;\n }\n }\n handlePossibleChange(observable) {\n if (this._state === 3 /* AutorunState.upToDate */ && this._isDependency(observable)) {\n this._state = 1 /* AutorunState.dependenciesMightHaveChanged */;\n }\n }\n handleChange(observable, change) {\n if (this._isDependency(observable)) {\n getLogger()?.handleAutorunDependencyChanged(this, observable, change);\n try {\n // Warning: external call!\n const shouldReact = this._changeTracker ? this._changeTracker.handleChange({\n changedObservable: observable,\n change,\n didChange: (o) => o === observable,\n }, this._changeSummary) : true;\n if (shouldReact) {\n this._state = 2 /* AutorunState.stale */;\n }\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n }\n }\n _isDependency(observable) {\n return this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable);\n }\n // IReader implementation\n _ensureNoRunning() {\n if (!this._isRunning) {\n throw new BugIndicatingError('The reader object cannot be used outside its compute function!');\n }\n }\n readObservable(observable) {\n this._ensureNoRunning();\n // In case the run action disposes the autorun\n if (this._disposed) {\n return observable.get(); // warning: external call!\n }\n observable.addObserver(this); // warning: external call!\n const value = observable.get(); // warning: external call!\n this._dependencies.add(observable);\n this._dependenciesToBeRemoved.delete(observable);\n return value;\n }\n get store() {\n this._ensureNoRunning();\n if (this._disposed) {\n throw new BugIndicatingError('Cannot access store after dispose');\n }\n if (this._store === undefined) {\n this._store = new DisposableStore();\n }\n return this._store;\n }\n get delayedStore() {\n this._ensureNoRunning();\n if (this._disposed) {\n throw new BugIndicatingError('Cannot access store after dispose');\n }\n if (this._delayedStore === undefined) {\n this._delayedStore = new DisposableStore();\n }\n return this._delayedStore;\n }\n debugGetState() {\n return {\n isRunning: this._isRunning,\n updateCount: this._updateCount,\n dependencies: this._dependencies,\n state: this._state,\n stateStr: autorunStateToString(this._state),\n };\n }\n debugRerun() {\n if (!this._isRunning) {\n this._run();\n }\n else {\n this._state = 2 /* AutorunState.stale */;\n }\n }\n}\n\nexport { AutorunObserver };\n//# sourceMappingURL=createEffectImpl.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { toDisposable } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { AutorunObserver } from './createEffectImpl.js';\nimport { DebugLocation } from '../debugLocation.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the effect.\n */\nfunction createEffect(fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(undefined, undefined, fn), fn, undefined, debugLocation);\n}\n/**\n * @deprecated Use {@link createEffect} instead.\n */\nconst autorun = createEffect;\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the autorun.\n */\nfunction createEffectOpts(options, fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, undefined, debugLocation);\n}\n/**\n * @deprecated Use {@link createEffectOpts} instead.\n */\nconst autorunOpts = createEffectOpts;\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the autorun.\n *\n * Use `changeTracker.createChangeSummary` to create a \"change summary\" that can collect the changes.\n * Use `changeTracker.handleChange` to add a reported change to the change summary.\n * The run function is given the last change summary.\n * The change summary is discarded after the run function was called.\n *\n * @see autorun\n */\nfunction autorunHandleChanges(options, fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, options.changeTracker, debugLocation);\n}\n/**\n * @see autorunHandleChanges (but with a disposable store that is cleared before the next run or on dispose)\n */\nfunction autorunWithStoreHandleChanges(options, fn) {\n const store = new DisposableStore();\n const disposable = autorunHandleChanges({\n owner: options.owner,\n debugName: options.debugName,\n debugReferenceFn: options.debugReferenceFn ?? fn,\n changeTracker: options.changeTracker,\n }, (reader, changeSummary) => {\n store.clear();\n fn(reader, changeSummary, store);\n });\n return toDisposable(() => {\n disposable.dispose();\n store.dispose();\n });\n}\n/**\n * @see autorun (but with a disposable store that is cleared before the next run or on dispose)\n *\n * @deprecated Use `autorun(reader => { reader.store.add(...) })` instead!\n */\nfunction autorunWithStore(fn) {\n const store = new DisposableStore();\n const disposable = createEffectOpts({\n owner: undefined,\n debugName: undefined,\n debugReferenceFn: fn,\n }, reader => {\n store.clear();\n fn(reader, store);\n });\n return toDisposable(() => {\n disposable.dispose();\n store.dispose();\n });\n}\nfunction autorunDelta(observable, handler) {\n let _lastValue;\n return createEffectOpts({ debugReferenceFn: handler }, (reader) => {\n const newValue = observable.read(reader);\n const lastValue = _lastValue;\n _lastValue = newValue;\n handler({ lastValue, newValue });\n });\n}\nfunction autorunIterableDelta(getValue, handler, getUniqueIdentifier = v => v) {\n const lastValues = new Map();\n return createEffectOpts({ debugReferenceFn: getValue }, (reader) => {\n const newValues = new Map();\n const removedValues = new Map(lastValues);\n for (const value of getValue(reader)) {\n const id = getUniqueIdentifier(value);\n if (lastValues.has(id)) {\n removedValues.delete(id);\n }\n else {\n newValues.set(id, value);\n lastValues.set(id, value);\n }\n }\n for (const id of removedValues.keys()) {\n lastValues.delete(id);\n }\n if (newValues.size || removedValues.size) {\n handler({ addedValues: [...newValues.values()], removedValues: [...removedValues.values()] });\n }\n });\n}\n/**\n * An autorun with a `dispose()` method on its `reader` which cancels the autorun.\n * It it safe to call `dispose()` synchronously.\n */\nfunction autorunSelfDisposable(fn, debugLocation = DebugLocation.ofCaller()) {\n let ar;\n let disposed = false;\n // eslint-disable-next-line prefer-const\n ar = createEffect(reader => {\n fn({\n delayedStore: reader.delayedStore,\n store: reader.store,\n readObservable: reader.readObservable.bind(reader),\n dispose: () => {\n ar?.dispose();\n disposed = true;\n }\n });\n }, debugLocation);\n if (disposed) {\n ar.dispose();\n }\n return ar;\n}\n\nexport { autorun, autorunDelta, autorunHandleChanges, autorunIterableDelta, autorunOpts, autorunSelfDisposable, autorunWithStore, autorunWithStoreHandleChanges, createEffect, createEffectOpts };\n//# sourceMappingURL=createEffect.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onUnexpectedError } from './commonFacade/deps.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * This function is used to indicate that the caller recovered from an error that indicates a bug.\n*/\nfunction handleBugIndicatingErrorRecovery(message) {\n const err = new Error('BugIndicatingErrorRecovery: ' + message);\n onUnexpectedError(err);\n console.error('recovered from an error that indicates a bug', err);\n}\n\nexport { handleBugIndicatingErrorRecovery };\n//# sourceMappingURL=base.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { handleBugIndicatingErrorRecovery } from './base.js';\nimport { getFunctionName } from './debugName.js';\nimport { getLogger } from './logging/logging.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * Starts a transaction in which many observables can be changed at once.\n * {@link fn} should start with a JS Doc using `@description` to give the transaction a debug name.\n * Reaction run on demand or when the transaction ends.\n */\nfunction transaction(fn, getDebugName) {\n const tx = new TransactionImpl(fn, getDebugName);\n try {\n fn(tx);\n }\n finally {\n tx.finish();\n }\n}\nlet _globalTransaction = undefined;\nfunction globalTransaction(fn) {\n if (_globalTransaction) {\n fn(_globalTransaction);\n }\n else {\n const tx = new TransactionImpl(fn, undefined);\n _globalTransaction = tx;\n try {\n fn(tx);\n }\n finally {\n tx.finish(); // During finish, more actions might be added to the transaction.\n // Which is why we only clear the global transaction after finish.\n _globalTransaction = undefined;\n }\n }\n}\n/** @deprecated */\nasync function asyncTransaction(fn, getDebugName) {\n const tx = new TransactionImpl(fn, getDebugName);\n try {\n await fn(tx);\n }\n finally {\n tx.finish();\n }\n}\n/**\n * Allows to chain transactions.\n */\nfunction subtransaction(tx, fn, getDebugName) {\n if (!tx) {\n transaction(fn, getDebugName);\n }\n else {\n fn(tx);\n }\n}\nclass TransactionImpl {\n constructor(_fn, _getDebugName) {\n this._fn = _fn;\n this._getDebugName = _getDebugName;\n this._updatingObservers = [];\n getLogger()?.handleBeginTransaction(this);\n }\n getDebugName() {\n if (this._getDebugName) {\n return this._getDebugName();\n }\n return getFunctionName(this._fn);\n }\n updateObserver(observer, observable) {\n if (!this._updatingObservers) {\n // This happens when a transaction is used in a callback or async function.\n // If an async transaction is used, make sure the promise awaits all users of the transaction (e.g. no race).\n handleBugIndicatingErrorRecovery('Transaction already finished!');\n // Error recovery\n transaction(tx => {\n tx.updateObserver(observer, observable);\n });\n return;\n }\n // When this gets called while finish is active, they will still get considered\n this._updatingObservers.push({ observer, observable });\n observer.beginUpdate(observable);\n }\n finish() {\n const updatingObservers = this._updatingObservers;\n if (!updatingObservers) {\n handleBugIndicatingErrorRecovery('transaction.finish() has already been called!');\n return;\n }\n for (let i = 0; i < updatingObservers.length; i++) {\n const { observer, observable } = updatingObservers[i];\n observer.endUpdate(observable);\n }\n // Prevent anyone from updating observers from now on.\n this._updatingObservers = null;\n getLogger()?.handleEndTransaction(this);\n }\n debugGetUpdatingObservers() {\n return this._updatingObservers;\n }\n}\n\nexport { TransactionImpl, asyncTransaction, globalTransaction, subtransaction, transaction };\n//# sourceMappingURL=transaction.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { TransactionImpl } from '../transaction.js';\nimport { BaseObservable } from './baseObservable.js';\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DebugLocation } from '../debugLocation.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableValue(nameOrOwner, initialValue, debugLocation = DebugLocation.ofCaller()) {\n let debugNameData;\n if (typeof nameOrOwner === 'string') {\n debugNameData = new DebugNameData(undefined, nameOrOwner, undefined);\n }\n else {\n debugNameData = new DebugNameData(nameOrOwner, undefined, undefined);\n }\n return new ObservableValue(debugNameData, initialValue, strictEquals, debugLocation);\n}\nclass ObservableValue extends BaseObservable {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? 'ObservableValue';\n }\n constructor(_debugNameData, initialValue, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this._equalityComparator = _equalityComparator;\n this._value = initialValue;\n getLogger()?.handleObservableUpdated(this, { hadValue: false, newValue: initialValue, change: undefined, didChange: true, oldValue: undefined });\n }\n get() {\n return this._value;\n }\n set(value, tx, change) {\n if (change === undefined && this._equalityComparator(this._value, value)) {\n return;\n }\n let _tx;\n if (!tx) {\n tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`);\n }\n try {\n const oldValue = this._value;\n this._setValue(value);\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue: value, change, didChange: true, hadValue: true });\n for (const observer of this._observers) {\n tx.updateObserver(observer, this);\n observer.handleChange(this, change);\n }\n }\n finally {\n if (_tx) {\n _tx.finish();\n }\n }\n }\n toString() {\n return `${this.debugName}: ${this._value}`;\n }\n _setValue(newValue) {\n this._value = newValue;\n }\n debugGetState() {\n return {\n value: this._value,\n };\n }\n debugSetValue(value) {\n this._value = value;\n }\n}\n/**\n * A disposable observable. When disposed, its value is also disposed.\n * When a new value is set, the previous value is disposed.\n */\nfunction disposableObservableValue(nameOrOwner, initialValue, debugLocation = DebugLocation.ofCaller()) {\n let debugNameData;\n if (typeof nameOrOwner === 'string') {\n debugNameData = new DebugNameData(undefined, nameOrOwner, undefined);\n }\n else {\n debugNameData = new DebugNameData(nameOrOwner, undefined, undefined);\n }\n return new DisposableObservableValue(debugNameData, initialValue, strictEquals, debugLocation);\n}\nclass DisposableObservableValue extends ObservableValue {\n _setValue(newValue) {\n if (this._value === newValue) {\n return;\n }\n if (this._value) {\n this._value.dispose();\n }\n this._value = newValue;\n }\n dispose() {\n this._value?.dispose();\n }\n}\n\nexport { DisposableObservableValue, ObservableValue, disposableObservableValue, observableValue };\n//# sourceMappingURL=observableValue.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { subtransaction } from '../transaction.js';\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { getLogger } from '../logging/logging.js';\nimport { BaseObservable } from './baseObservable.js';\nimport { DebugLocation } from '../debugLocation.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableFromEvent(...args) {\n let owner;\n let event;\n let getValue;\n let debugLocation;\n if (args.length === 2) {\n [event, getValue] = args;\n }\n else {\n [owner, event, getValue, debugLocation] = args;\n }\n return new FromEventObservable(new DebugNameData(owner, undefined, getValue), event, getValue, () => FromEventObservable.globalTransaction, strictEquals, debugLocation ?? DebugLocation.ofCaller());\n}\nfunction observableFromEventOpts(options, event, getValue, debugLocation = DebugLocation.ofCaller()) {\n return new FromEventObservable(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? getValue), event, getValue, () => FromEventObservable.globalTransaction, options.equalsFn ?? strictEquals, debugLocation);\n}\nclass FromEventObservable extends BaseObservable {\n constructor(_debugNameData, event, _getValue, _getTransaction, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this.event = event;\n this._getValue = _getValue;\n this._getTransaction = _getTransaction;\n this._equalityComparator = _equalityComparator;\n this._hasValue = false;\n this.handleEvent = (args) => {\n const newValue = this._getValue(args);\n const oldValue = this._value;\n const didChange = !this._hasValue || !(this._equalityComparator(oldValue, newValue));\n let didRunTransaction = false;\n if (didChange) {\n this._value = newValue;\n if (this._hasValue) {\n didRunTransaction = true;\n subtransaction(this._getTransaction(), (tx) => {\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue, change: undefined, didChange, hadValue: this._hasValue });\n for (const o of this._observers) {\n tx.updateObserver(o, this);\n o.handleChange(this, undefined);\n }\n }, () => {\n const name = this.getDebugName();\n return 'Event fired' + (name ? `: ${name}` : '');\n });\n }\n this._hasValue = true;\n }\n if (!didRunTransaction) {\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue, change: undefined, didChange, hadValue: this._hasValue });\n }\n };\n }\n getDebugName() {\n return this._debugNameData.getDebugName(this);\n }\n get debugName() {\n const name = this.getDebugName();\n return 'From Event' + (name ? `: ${name}` : '');\n }\n onFirstObserverAdded() {\n this._subscription = this.event(this.handleEvent);\n }\n onLastObserverRemoved() {\n this._subscription.dispose();\n this._subscription = undefined;\n this._hasValue = false;\n this._value = undefined;\n }\n get() {\n if (this._subscription) {\n if (!this._hasValue) {\n this.handleEvent(undefined);\n }\n return this._value;\n }\n else {\n // no cache, as there are no subscribers to keep it updated\n const value = this._getValue(undefined);\n return value;\n }\n }\n debugSetValue(value) {\n this._value = value;\n }\n debugGetState() {\n return { value: this._value, hasValue: this._hasValue };\n }\n}\n(function (observableFromEvent) {\n observableFromEvent.Observer = FromEventObservable;\n function batchEventsGlobally(tx, fn) {\n let didSet = false;\n if (FromEventObservable.globalTransaction === undefined) {\n FromEventObservable.globalTransaction = tx;\n didSet = true;\n }\n try {\n fn();\n }\n finally {\n if (didSet) {\n FromEventObservable.globalTransaction = undefined;\n }\n }\n }\n observableFromEvent.batchEventsGlobally = batchEventsGlobally;\n})(observableFromEvent || (observableFromEvent = {}));\n\nexport { FromEventObservable, observableFromEvent, observableFromEventOpts };\n//# sourceMappingURL=observableFromEvent.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createEffect } from '../reactions/createEffect.js';\nimport { transaction } from '../transaction.js';\nimport { observableValue } from '../observables/observableValue.js';\nimport { toDisposable } from '../commonFacade/deps.js';\nimport { derivedOpts, derived } from '../observables/derived.js';\nimport { observableFromEvent } from '../observables/observableFromEvent.js';\nimport { observableSignal } from '../observables/observableSignal.js';\nimport { _setKeepObserved, _setRecomputeInitiallyAndOnChange } from '../observables/baseObservable.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableFromPromise(promise) {\n const observable = observableValue('promiseValue', {});\n promise.then((value) => {\n observable.set({ value }, undefined);\n });\n return observable;\n}\nfunction signalFromObservable(owner, observable) {\n return derivedOpts({\n owner,\n equalsFn: () => false,\n }, reader => {\n observable.read(reader);\n });\n}\n/**\n * @deprecated Use `debouncedObservable` instead.\n */\nfunction debouncedObservableDeprecated(observable, debounceMs, disposableStore) {\n const debouncedObservable = observableValue('debounced', undefined);\n let timeout = undefined;\n disposableStore.add(createEffect(reader => {\n /** @description debounce */\n const value = observable.read(reader);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n transaction(tx => {\n debouncedObservable.set(value, tx);\n });\n }, debounceMs);\n }));\n return debouncedObservable;\n}\n/**\n * Creates an observable that debounces the input observable.\n */\nfunction debouncedObservable(observable, debounceMs) {\n let hasValue = false;\n let lastValue;\n let timeout = undefined;\n return observableFromEvent(cb => {\n const d = createEffect(reader => {\n const value = observable.read(reader);\n if (!hasValue) {\n hasValue = true;\n lastValue = value;\n }\n else {\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n lastValue = value;\n cb();\n }, debounceMs);\n }\n });\n return {\n dispose() {\n d.dispose();\n hasValue = false;\n lastValue = undefined;\n },\n };\n }, () => {\n if (hasValue) {\n return lastValue;\n }\n else {\n return observable.get();\n }\n });\n}\nfunction wasEventTriggeredRecently(event, timeoutMs, disposableStore) {\n const observable = observableValue('triggeredRecently', false);\n let timeout = undefined;\n disposableStore.add(event(() => {\n observable.set(true, undefined);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n observable.set(false, undefined);\n }, timeoutMs);\n }));\n return observable;\n}\n/**\n * This makes sure the observable is being observed and keeps its cache alive.\n */\nfunction keepObserved(observable) {\n const o = new KeepAliveObserver(false, undefined);\n observable.addObserver(o);\n return toDisposable(() => {\n observable.removeObserver(o);\n });\n}\n_setKeepObserved(keepObserved);\n/**\n * This converts the given observable into an autorun.\n */\nfunction recomputeInitiallyAndOnChange(observable, handleValue) {\n const o = new KeepAliveObserver(true, handleValue);\n observable.addObserver(o);\n try {\n o.beginUpdate(observable);\n }\n finally {\n o.endUpdate(observable);\n }\n return toDisposable(() => {\n observable.removeObserver(o);\n });\n}\n_setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange);\nclass KeepAliveObserver {\n constructor(_forceRecompute, _handleValue) {\n this._forceRecompute = _forceRecompute;\n this._handleValue = _handleValue;\n this._counter = 0;\n }\n beginUpdate(observable) {\n this._counter++;\n }\n endUpdate(observable) {\n if (this._counter === 1 && this._forceRecompute) {\n if (this._handleValue) {\n this._handleValue(observable.get());\n }\n else {\n observable.reportChanges();\n }\n }\n this._counter--;\n }\n handlePossibleChange(observable) {\n // NO OP\n }\n handleChange(observable, change) {\n // NO OP\n }\n}\nfunction derivedObservableWithCache(owner, computeFn) {\n let lastValue = undefined;\n const observable = derivedOpts({ owner, debugReferenceFn: computeFn }, reader => {\n lastValue = computeFn(reader, lastValue);\n return lastValue;\n });\n return observable;\n}\nfunction derivedObservableWithWritableCache(owner, computeFn) {\n let lastValue = undefined;\n const onChange = observableSignal('derivedObservableWithWritableCache');\n const observable = derived(owner, reader => {\n onChange.read(reader);\n lastValue = computeFn(reader, lastValue);\n return lastValue;\n });\n return Object.assign(observable, {\n clearCache: (tx) => {\n lastValue = undefined;\n onChange.trigger(tx);\n },\n setCache: (newValue, tx) => {\n lastValue = newValue;\n onChange.trigger(tx);\n }\n });\n}\n/**\n * When the items array changes, referential equal items are not mapped again.\n */\nfunction mapObservableArrayCached(owner, items, map, keySelector) {\n let m = new ArrayMap(map, keySelector);\n const self = derivedOpts({\n debugReferenceFn: map,\n owner,\n onLastObserverRemoved: () => {\n m.dispose();\n m = new ArrayMap(map);\n }\n }, (reader) => {\n m.setItems(items.read(reader));\n return m.getItems();\n });\n return self;\n}\nclass ArrayMap {\n constructor(_map, _keySelector) {\n this._map = _map;\n this._keySelector = _keySelector;\n this._cache = new Map();\n this._items = [];\n }\n dispose() {\n this._cache.forEach(entry => entry.store.dispose());\n this._cache.clear();\n }\n setItems(items) {\n const newItems = [];\n const itemsToRemove = new Set(this._cache.keys());\n for (const item of items) {\n const key = this._keySelector ? this._keySelector(item) : item;\n let entry = this._cache.get(key);\n if (!entry) {\n const store = new DisposableStore();\n const out = this._map(item, store);\n entry = { out, store };\n this._cache.set(key, entry);\n }\n else {\n itemsToRemove.delete(key);\n }\n newItems.push(entry.out);\n }\n for (const item of itemsToRemove) {\n const entry = this._cache.get(item);\n entry.store.dispose();\n this._cache.delete(item);\n }\n this._items = newItems;\n }\n getItems() {\n return this._items;\n }\n}\n\nexport { KeepAliveObserver, debouncedObservable, debouncedObservableDeprecated, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, mapObservableArrayCached, observableFromPromise, recomputeInitiallyAndOnChange, signalFromObservable, wasEventTriggeredRecently };\n//# sourceMappingURL=utils.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { addLogger } from './logging.js';\nimport { getClassName } from '../debugName.js';\nimport { Derived } from '../observables/derivedImpl.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet consoleObservableLogger;\nfunction logObservableToConsole(obs) {\n if (!consoleObservableLogger) {\n consoleObservableLogger = new ConsoleObservableLogger();\n addLogger(consoleObservableLogger);\n }\n consoleObservableLogger.addFilteredObj(obs);\n}\nclass ConsoleObservableLogger {\n constructor() {\n this.indentation = 0;\n this.changedObservablesSets = new WeakMap();\n }\n addFilteredObj(obj) {\n if (!this._filteredObjects) {\n this._filteredObjects = new Set();\n }\n this._filteredObjects.add(obj);\n }\n _isIncluded(obj) {\n return this._filteredObjects?.has(obj) ?? true;\n }\n textToConsoleArgs(text) {\n return consoleTextToArgs([\n normalText(repeat('| ', this.indentation)),\n text,\n ]);\n }\n formatInfo(info) {\n if (!info.hadValue) {\n return [\n normalText(` `),\n styled(formatValue(info.newValue, 60), {\n color: 'green',\n }),\n normalText(` (initial)`),\n ];\n }\n return info.didChange\n ? [\n normalText(` `),\n styled(formatValue(info.oldValue, 70), {\n color: 'red',\n strikeThrough: true,\n }),\n normalText(` `),\n styled(formatValue(info.newValue, 60), {\n color: 'green',\n }),\n ]\n : [normalText(` (unchanged)`)];\n }\n handleObservableCreated(observable) {\n if (observable instanceof Derived) {\n const derived = observable;\n this.changedObservablesSets.set(derived, new Set());\n }\n }\n handleOnListenerCountChanged(observable, newCount) {\n }\n handleObservableUpdated(observable, info) {\n if (!this._isIncluded(observable)) {\n return;\n }\n if (observable instanceof Derived) {\n this._handleDerivedRecomputed(observable, info);\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('observable value changed'),\n styled(observable.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n ]));\n }\n formatChanges(changes) {\n if (changes.size === 0) {\n return undefined;\n }\n return styled(' (changed deps: ' +\n [...changes].map((o) => o.debugName).join(', ') +\n ')', { color: 'gray' });\n }\n handleDerivedDependencyChanged(derived, observable, change) {\n if (!this._isIncluded(derived)) {\n return;\n }\n this.changedObservablesSets.get(derived)?.add(observable);\n }\n _handleDerivedRecomputed(derived, info) {\n if (!this._isIncluded(derived)) {\n return;\n }\n const changedObservables = this.changedObservablesSets.get(derived);\n if (!changedObservables) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('derived recomputed'),\n styled(derived.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n this.formatChanges(changedObservables),\n { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] }\n ]));\n changedObservables.clear();\n }\n handleDerivedCleared(derived) {\n if (!this._isIncluded(derived)) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('derived cleared'),\n styled(derived.debugName, { color: 'BlueViolet' }),\n ]));\n }\n handleFromEventObservableTriggered(observable, info) {\n if (!this._isIncluded(observable)) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('observable from event triggered'),\n styled(observable.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n { data: [{ fn: observable._getValue }] }\n ]));\n }\n handleAutorunCreated(autorun) {\n if (!this._isIncluded(autorun)) {\n return;\n }\n this.changedObservablesSets.set(autorun, new Set());\n }\n handleAutorunDisposed(autorun) {\n }\n handleAutorunDependencyChanged(autorun, observable, change) {\n if (!this._isIncluded(autorun)) {\n return;\n }\n this.changedObservablesSets.get(autorun).add(observable);\n }\n handleAutorunStarted(autorun) {\n const changedObservables = this.changedObservablesSets.get(autorun);\n if (!changedObservables) {\n return;\n }\n if (this._isIncluded(autorun)) {\n console.log(...this.textToConsoleArgs([\n formatKind('autorun'),\n styled(autorun.debugName, { color: 'BlueViolet' }),\n this.formatChanges(changedObservables),\n { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] }\n ]));\n }\n changedObservables.clear();\n this.indentation++;\n }\n handleAutorunFinished(autorun) {\n this.indentation--;\n }\n handleBeginTransaction(transaction) {\n let transactionName = transaction.getDebugName();\n if (transactionName === undefined) {\n transactionName = '';\n }\n if (this._isIncluded(transaction)) {\n console.log(...this.textToConsoleArgs([\n formatKind('transaction'),\n styled(transactionName, { color: 'BlueViolet' }),\n { data: [{ fn: transaction._fn }] }\n ]));\n }\n this.indentation++;\n }\n handleEndTransaction() {\n this.indentation--;\n }\n}\nfunction consoleTextToArgs(text) {\n const styles = new Array();\n const data = [];\n let firstArg = '';\n function process(t) {\n if ('length' in t) {\n for (const item of t) {\n if (item) {\n process(item);\n }\n }\n }\n else if ('text' in t) {\n firstArg += `%c${t.text}`;\n styles.push(t.style);\n if (t.data) {\n data.push(...t.data);\n }\n }\n else if ('data' in t) {\n data.push(...t.data);\n }\n }\n process(text);\n const result = [firstArg, ...styles];\n result.push(...data);\n return result;\n}\nfunction normalText(text) {\n return styled(text, { color: 'black' });\n}\nfunction formatKind(kind) {\n return styled(padStr(`${kind}: `, 10), { color: 'black', bold: true });\n}\nfunction styled(text, options = {\n color: 'black',\n}) {\n function objToCss(styleObj) {\n return Object.entries(styleObj).reduce((styleString, [propName, propValue]) => {\n return `${styleString}${propName}:${propValue};`;\n }, '');\n }\n const style = {\n color: options.color,\n };\n if (options.strikeThrough) {\n style['text-decoration'] = 'line-through';\n }\n if (options.bold) {\n style['font-weight'] = 'bold';\n }\n return {\n text,\n style: objToCss(style),\n };\n}\nfunction formatValue(value, availableLen) {\n try {\n return formatValueUnsafe(value, availableLen);\n }\n catch {\n // Value could not be formatted (e.g., a Proxy that throws on coercion)\n return '[[???]]';\n }\n}\nfunction formatValueUnsafe(value, availableLen) {\n switch (typeof value) {\n case 'number':\n return '' + value;\n case 'string':\n if (value.length + 2 <= availableLen) {\n return `\"${value}\"`;\n }\n return `\"${value.substr(0, availableLen - 7)}\"+...`;\n case 'boolean':\n return value ? 'true' : 'false';\n case 'undefined':\n return 'undefined';\n case 'object':\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return formatArray(value, availableLen);\n }\n return formatObject(value, availableLen);\n case 'symbol':\n return value.toString();\n case 'function':\n return `[[Function${value.name ? ' ' + value.name : ''}]]`;\n default:\n return '' + value;\n }\n}\nfunction formatArray(value, availableLen) {\n let result = '[ ';\n let first = true;\n for (const val of value) {\n if (!first) {\n result += ', ';\n }\n if (result.length - 5 > availableLen) {\n result += '...';\n break;\n }\n first = false;\n result += `${formatValue(val, availableLen - result.length)}`;\n }\n result += ' ]';\n return result;\n}\nfunction formatObject(value, availableLen) {\n // Avoid drilling into Proxies - wrap operations that could trigger traps\n try {\n if (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) {\n const val = value.toString();\n if (val.length <= availableLen) {\n return val;\n }\n return val.substring(0, availableLen - 3) + '...';\n }\n }\n catch {\n // toString triggered a Proxy trap or threw - bail out\n return '[[Object]]';\n }\n const className = getClassName(value);\n let result = className ? className + '(' : '{ ';\n let first = true;\n let entries;\n try {\n entries = Object.entries(value);\n }\n catch {\n // Object.entries triggered a Proxy trap - bail out\n return className ? `${className}(...)` : '[[Object]]';\n }\n for (const [key, val] of entries) {\n if (!first) {\n result += ', ';\n }\n if (result.length - 5 > availableLen) {\n result += '...';\n break;\n }\n first = false;\n result += `${key}: ${formatValue(val, availableLen - result.length)}`;\n }\n result += className ? ')' : ' }';\n return result;\n}\nfunction repeat(str, count) {\n let result = '';\n for (let i = 1; i <= count; i++) {\n result += str;\n }\n return result;\n}\nfunction padStr(str, length) {\n while (str.length < length) {\n str += ' ';\n }\n return str;\n}\n\nexport { ConsoleObservableLogger, formatValue, logObservableToConsole };\n//# sourceMappingURL=consoleObservableLogger.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Derived } from '../observables/derivedImpl.js';\nimport { FromEventObservable } from '../observables/observableFromEvent.js';\nimport { ObservableValue } from '../observables/observableValue.js';\nimport { AutorunObserver } from '../reactions/createEffectImpl.js';\nimport { formatValue } from './consoleObservableLogger.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction debugGetDependencyGraph(obs, options) {\n const debugNamePostProcessor = options?.debugNamePostProcessor ?? ((str) => str);\n const info = Info.from(obs, debugNamePostProcessor);\n if (!info) {\n return '';\n }\n const alreadyListed = new Set();\n return formatObservableInfo(info, 0, alreadyListed).trim();\n}\nfunction formatObservableInfo(info, indentLevel, alreadyListed) {\n const indent = '\\t\\t'.repeat(indentLevel);\n const lines = [];\n const isAlreadyListed = alreadyListed.has(info.sourceObj);\n if (isAlreadyListed) {\n lines.push(`${indent}* ${info.type} ${info.name} (already listed)`);\n return lines.join('\\n');\n }\n alreadyListed.add(info.sourceObj);\n lines.push(`${indent}* ${info.type} ${info.name}:`);\n lines.push(`${indent} value: ${formatValue(info.value, 50)}`);\n lines.push(`${indent} state: ${info.state}`);\n if (info.dependencies.length > 0) {\n lines.push(`${indent} dependencies:`);\n for (const dep of info.dependencies) {\n lines.push(formatObservableInfo(dep, indentLevel + 1, alreadyListed));\n }\n }\n return lines.join('\\n');\n}\nclass Info {\n static from(obs, debugNamePostProcessor) {\n if (obs instanceof AutorunObserver) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'autorun', undefined, state.stateStr, Array.from(state.dependencies).map(dep => Info.from(dep, debugNamePostProcessor) || Info.unknown(dep)));\n }\n else if (obs instanceof Derived) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'derived', state.value, state.stateStr, Array.from(state.dependencies).map(dep => Info.from(dep, debugNamePostProcessor) || Info.unknown(dep)));\n }\n else if (obs instanceof ObservableValue) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'observableValue', state.value, 'upToDate', []);\n }\n else if (obs instanceof FromEventObservable) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'fromEvent', state.value, state.hasValue ? 'upToDate' : 'initial', []);\n }\n return undefined;\n }\n static unknown(obs) {\n return new Info(obs, '(unknown)', 'unknown', undefined, 'unknown', []);\n }\n constructor(sourceObj, name, type, value, state, dependencies) {\n this.sourceObj = sourceObj;\n this.name = name;\n this.type = type;\n this.value = value;\n this.state = state;\n this.dependencies = dependencies;\n }\n}\n\nexport { debugGetDependencyGraph };\n//# sourceMappingURL=debugGetDependencyGraph.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { setLogObservableFn } from './logging/logging.js';\nimport { _setDebugGetDependencyGraph } from './observables/baseObservable.js';\nexport { DebugLocation } from './debugLocation.js';\nexport { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter, derivedWithStore } from './observables/derived.js';\nexport { debouncedObservable, debouncedObservableDeprecated, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, mapObservableArrayCached, observableFromPromise, recomputeInitiallyAndOnChange, signalFromObservable, wasEventTriggeredRecently } from './utils/utils.js';\nexport { observableFromEvent, observableFromEventOpts } from './observables/observableFromEvent.js';\nimport { logObservableToConsole } from './logging/consoleObservableLogger.js';\nimport { debugGetDependencyGraph } from './logging/debugGetDependencyGraph.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n// This is a facade for the observable implementation. Only import from here!\n_setDebugGetDependencyGraph(debugGetDependencyGraph);\nsetLogObservableFn(logObservableToConsole);\n//# sourceMappingURL=index.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { transaction } from '../transaction.js';\nimport { derived } from '../observables/derived.js';\nimport { observableValue } from '../observables/observableValue.js';\n\nclass ObservableLazy {\n /**\n * The cached value.\n * Does not force a computation of the value.\n */\n get cachedValue() { return this._value; }\n constructor(_computeValue) {\n this._computeValue = _computeValue;\n this._value = observableValue(this, undefined);\n }\n /**\n * Returns the cached value.\n * Computes the value if the value has not been cached yet.\n */\n getValue() {\n let v = this._value.get();\n if (!v) {\n v = this._computeValue();\n this._value.set(v, undefined);\n }\n return v;\n }\n}\n/**\n * A promise whose state is observable.\n */\nclass ObservablePromise {\n static fromFn(fn) {\n return new ObservablePromise(fn());\n }\n constructor(promise) {\n this._value = observableValue(this, undefined);\n /**\n * The current state of the promise.\n * Is `undefined` if the promise didn't resolve yet.\n */\n this.promiseResult = this._value;\n this.resolvedValue = derived(this, reader => {\n const result = this.promiseResult.read(reader);\n if (!result) {\n return undefined;\n }\n return result.getDataOrThrow();\n });\n this.promise = promise.then(value => {\n transaction(tx => {\n /** @description onPromiseResolved */\n this._value.set(new PromiseResult(value, undefined), tx);\n });\n return value;\n }, error => {\n transaction(tx => {\n /** @description onPromiseRejected */\n this._value.set(new PromiseResult(undefined, error), tx);\n });\n throw error;\n });\n }\n}\nclass PromiseResult {\n constructor(\n /**\n * The value of the resolved promise.\n * Undefined if the promise rejected.\n */\n data, \n /**\n * The error in case of a rejected promise.\n * Undefined if the promise resolved.\n */\n error) {\n this.data = data;\n this.error = error;\n }\n /**\n * Returns the value if the promise resolved, otherwise throws the error.\n */\n getDataOrThrow() {\n if (this.error) {\n throw this.error;\n }\n return this.data;\n }\n}\n/**\n * A lazy promise whose state is observable.\n */\nclass ObservableLazyPromise {\n constructor(_computePromise) {\n this._computePromise = _computePromise;\n this._lazyValue = new ObservableLazy(() => new ObservablePromise(this._computePromise()));\n /**\n * Does not enforce evaluation of the promise compute function.\n * Is undefined if the promise has not been computed yet.\n */\n this.cachedPromiseResult = derived(this, reader => this._lazyValue.cachedValue.read(reader)?.promiseResult.read(reader));\n }\n getPromise() {\n return this._lazyValue.getValue().promise;\n }\n}\n\nexport { ObservableLazy, ObservableLazyPromise, ObservablePromise, PromiseResult };\n//# sourceMappingURL=promise.js.map\n","import { jcsCanonicalize, type Pattern, type Permission } from '@hediet/linkrpc';\nimport type { HubAccessManifestRequest } from '@hediet/linkrpc/hub/common';\nimport type { AccessDirectPermission } from '@hediet/linkrpc-infra/approval';\n\nexport interface ApprovalPresentationLine {\n readonly label?: string;\n readonly text: string;\n readonly tone?: 'normal' | 'muted' | 'warning';\n}\n\nexport interface ApprovalPresentationRequest {\n readonly id: string;\n readonly request: HubAccessManifestRequest;\n readonly sourceServiceId?: string;\n}\n\nexport interface PreparedApprovalPresentation {\n readonly pending: ApprovalPresentationRequest;\n readonly permissions: readonly Permission[];\n readonly resolvedSlot?: {\n readonly serviceId: string;\n readonly satisfiedInterfaces: readonly string[];\n };\n}\n\nexport interface ApprovalPresentation {\n readonly heading: string;\n readonly details: readonly ApprovalPresentationLine[];\n}\n\nexport function createApprovalPresentation(\n item: ApprovalPresentationRequest,\n prepared?: PreparedApprovalPresentation,\n): ApprovalPresentation {\n const request = item.request;\n const details: ApprovalPresentationLine[] = [\n { label: 'Consumer', text: request.consumer.name },\n { label: 'Principal', text: request.consumer.principal, tone: 'muted' },\n ...(request.consumer.origin !== undefined\n ? [{ label: 'Origin', text: request.consumer.origin } satisfies ApprovalPresentationLine]\n : []),\n ...(request.consumer.purpose !== undefined\n ? [{ label: 'Purpose', text: request.consumer.purpose } satisfies ApprovalPresentationLine]\n : []),\n ...(request.reason !== undefined\n ? [{ label: 'Reason', text: request.reason } satisfies ApprovalPresentationLine]\n : []),\n ...(item.sourceServiceId === undefined\n ? []\n : [{\n label: 'Manifest source',\n text: item.sourceServiceId.length === 0 ? '<root>' : item.sourceServiceId,\n } satisfies ApprovalPresentationLine]),\n {\n label: 'Duration',\n text: request.duration ?? 'unspecified',\n tone: durationTone(request.duration),\n },\n { label: 'Request ID', text: item.id, tone: 'muted' },\n ...(prepared?.resolvedSlot === undefined\n ? []\n : [\n {\n label: 'Resolved service',\n text: prepared.resolvedSlot.serviceId,\n tone: 'warning',\n } satisfies ApprovalPresentationLine,\n {\n label: 'Satisfied interfaces',\n text: prepared.resolvedSlot.satisfiedInterfaces.join(', '),\n } satisfies ApprovalPresentationLine,\n ]),\n {\n text: prepared !== undefined\n ? 'Exact authority to be signed'\n : request.kind === 'direct' ? 'Requested authority' : 'Required service shape',\n tone: 'muted',\n },\n ];\n\n const reviewedPermissions = prepared?.pending.request.kind === 'direct'\n ? prepared.pending.request.permissions\n : undefined;\n details.push(...(\n prepared === undefined\n ? authorityLines(request)\n : permissionLines(prepared.permissions, reviewedPermissions)\n ));\n return {\n heading: `${item.id} ${request.kind} ${request.consumer.name}`,\n details,\n };\n}\n\nexport function approvalDetailLines(\n item: ApprovalPresentationRequest,\n prepared?: PreparedApprovalPresentation,\n): readonly ApprovalPresentationLine[] {\n return createApprovalPresentation(item, prepared).details;\n}\n\nfunction authorityLines(\n request: HubAccessManifestRequest,\n): readonly ApprovalPresentationLine[] {\n if (request.kind === 'direct') {\n return permissionLines(request.permissions);\n }\n return [\n ...request.interfaces.map((item) => ({\n text: `• interface ${item.id}${item.required === false ? ' (optional)' : ''}`,\n } satisfies ApprovalPresentationLine)),\n ...request.members.map((item) => ({\n text: `• member ${item.interfaceId}::${patternText(item.member)}`\n + `${item.required === false ? ' (optional)' : ''}`,\n } satisfies ApprovalPresentationLine)),\n ];\n}\n\nfunction permissionLines(\n permissions: readonly Permission[],\n reviewedPermissions?: readonly AccessDirectPermission[],\n): readonly ApprovalPresentationLine[] {\n return permissions.flatMap((permission, index) => {\n const service = patternText(permission.target.serviceId);\n const iface = patternText(permission.target.interfaceId);\n const members = permission.target.members.map(patternText).join(', ');\n const actions = [\n ...(permission.canInvoke === true ? ['invoke'] : []),\n ...(permission.canDelegate === true ? ['delegate'] : []),\n ].join(' + ') || 'none';\n const callIntent = reviewedPermissions?.[index]?.callIntent;\n return [\n {\n text: `• ${service}::${iface} {${members}}`,\n tone: [\n permission.target.serviceId,\n permission.target.interfaceId,\n ...permission.target.members,\n ].some(isBroadPattern)\n ? 'warning' as const\n : 'normal' as const,\n },\n {\n label: ` Actions ${index + 1}`,\n text: actions,\n tone: permission.canDelegate ? 'warning' : 'normal',\n } satisfies ApprovalPresentationLine,\n ...(permission.target.interfaceHash === undefined\n ? []\n : [{\n label: ' Interface hash',\n text: permission.target.interfaceHash,\n } satisfies ApprovalPresentationLine]),\n ...(permission.params === undefined\n ? [{\n label: ' Parameters',\n text: 'any',\n tone: 'warning',\n } satisfies ApprovalPresentationLine]\n : [{\n label: ' Parameters',\n text: jcsCanonicalize(permission.params),\n } satisfies ApprovalPresentationLine]),\n ...(permission.callBind === undefined\n ? []\n : [{\n label: ' Exact-call binding',\n text: jcsCanonicalize(permission.callBind),\n } satisfies ApprovalPresentationLine]),\n ...(callIntent === undefined\n ? []\n : [\n ...(callIntent.summary === undefined\n ? []\n : [{\n label: ' Call summary',\n text: callIntent.summary,\n } satisfies ApprovalPresentationLine]),\n {\n label: ' Call method',\n text: callIntent.method,\n } satisfies ApprovalPresentationLine,\n {\n label: ' Call parameters',\n text: callIntent.params === undefined\n ? '{}'\n : jcsCanonicalize(callIntent.params),\n } satisfies ApprovalPresentationLine,\n ...(callIntent.interfaceHash === undefined\n ? []\n : [{\n label: ' Call interface hash',\n text: callIntent.interfaceHash,\n } satisfies ApprovalPresentationLine]),\n ]),\n ];\n });\n}\n\nfunction patternText(pattern: Pattern | undefined): string {\n if (pattern === undefined) return 'any';\n if ('exact' in pattern) return `exact(${JSON.stringify(pattern.exact)})`;\n if ('prefix' in pattern) return `prefix(${JSON.stringify(pattern.prefix)})`;\n return 'any';\n}\n\nfunction isBroadPattern(pattern: Pattern | undefined): boolean {\n return pattern === undefined || 'prefix' in pattern;\n}\n\nfunction durationTone(\n duration: string | undefined,\n): ApprovalPresentationLine['tone'] {\n return duration === 'persistent' || duration === undefined ? 'warning' : 'normal';\n}\n","import {\n ApprovalClient,\n createHubApprovalClient,\n type ApprovalSnapshot,\n type ApprovalDecisionOutcome,\n type PendingApprovalRequest,\n type ConsentPrompt,\n} from '@hediet/linkrpc-infra/approval';\nimport { createTerminalConsentPrompt } from '@hediet/linkrpc-hub';\nimport { autorun } from '@vscode/observables';\nimport { createApprovalPresentation } from '../approvalPresentation';\nimport { formatJson } from '../output';\n\nexport interface ApprovalSubscription {\n dispose(): void;\n}\n\n/** Terminal prompt and callback adapter for the CLI's approval UI. */\nexport class ApprovalCommandClient extends ApprovalClient {\n public watch(listener: (snapshot: ApprovalSnapshot) => void): ApprovalSubscription {\n return autorun((reader) => listener(this.snapshot.read(reader)));\n }\n\n public override runInteractive(\n signal: AbortSignal,\n prompt: ConsentPrompt = createTerminalConsentPrompt(),\n ): Promise<void> {\n return super.runInteractive(signal, prompt);\n }\n}\n\nexport function createHubApprovalCommandClient(\n ...args: Parameters<typeof createHubApprovalClient>\n): ApprovalCommandClient {\n const client = createHubApprovalClient(...args);\n const runInteractive = client.runInteractive.bind(client);\n return Object.assign(client, {\n watch: (listener: (snapshot: ApprovalSnapshot) => void): ApprovalSubscription =>\n autorun((reader) => listener(client.snapshot.read(reader))),\n runInteractive: (\n signal: AbortSignal,\n prompt: ConsentPrompt = createTerminalConsentPrompt(),\n ): Promise<void> => runInteractive(signal, prompt),\n });\n}\n\nexport function formatApprovalRequests(\n requests: readonly PendingApprovalRequest[],\n principalId: string,\n json = false,\n): string {\n if (json) {\n return formatJson({\n version: 1,\n principal: principalId,\n requests: requests.map(({ id, request }) => ({ id, request })),\n });\n }\n if (requests.length === 0) {\n return `No pending approval requests for ${principalId}.`;\n }\n const lines: string[] = [];\n for (const request of requests) {\n const presentation = createApprovalPresentation(request);\n lines.push(presentation.heading);\n for (const detail of presentation.details) {\n lines.push(` ${detail.label === undefined ? '' : `${detail.label}: `}${detail.text}`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function formatApprovalDecision(\n action: 'approved' | 'denied',\n id: string,\n principalId: string,\n json = false,\n outcome: ApprovalDecisionOutcome = 'applied',\n): string {\n if (json) {\n return formatJson({\n version: 1,\n action,\n id,\n principal: principalId,\n ...(outcome === 'still-pending' ? { requestStillPending: true } : {}),\n });\n }\n return outcome === 'applied'\n ? `${action === 'approved' ? 'Approved' : 'Denied'} ${id}.`\n : `${action === 'approved' ? 'Approval' : 'Denial'} decision accepted for ${id}, `\n + 'but a matching request is still pending; the consumer may have retried.';\n}\n","import type { PrincipalSource, SigningSession } from '@hediet/linkrpc-client-internal';\nimport { formatPrincipalSource } from '@hediet/linkrpc-client-internal';\nimport { formatJson } from '../output';\n\nexport interface CliIdentity {\n readonly principal: string;\n readonly source: PrincipalSource;\n}\n\nexport function cliIdentity(session: SigningSession): CliIdentity {\n return {\n principal: session.principal.id,\n source: session.principalSource,\n };\n}\n\nexport function formatCliIdentity(identity: CliIdentity, json = false): string {\n if (json) {\n return formatJson({\n version: 1,\n principal: identity.principal,\n source: identity.source,\n });\n }\n return [\n formatPrincipalSource(identity.source, identity.principal),\n `principal: ${identity.principal}`,\n ].join('\\n');\n}\n","/**\n * The hub engine now lives in `@hediet/linkrpc-hub` (shared by the CLI, the\n * standalone `linkrpc-hub` server, and the VS Code extension). This module\n * re-exports it for the CLI's existing `./engine/runHub` import sites.\n */\nimport type {\n ListenerInfo,\n RunHubOptions,\n RunningHub,\n} from '@hediet/linkrpc-hub/engine/runHub';\n\nexport type { ListenerInfo, RunHubOptions, RunningHub };\n\nexport async function runHub(options: RunHubOptions): Promise<RunningHub> {\n const engine = await import('@hediet/linkrpc-hub/engine/runHub');\n return engine.runHub(options);\n}\n","/**\n * Render the dynamic \"Method parameters\" block appended to `hub call --help`\n * and `hub notify --help`. Pure: takes a `MethodSchema` (already fetched by\n * the caller) plus the live interface schema for ref resolution, and returns\n * the formatted block. The caller concatenates it after commander's\n * static help text.\n *\n * Param names show up as `--p:<name>`; the type / required-ness / one-line\n * description is derived from the params object's `properties` map.\n *\n * If the method's params schema isn't a plain object schema (e.g. a\n * union, or a top-level array), we render a coarse fallback instead of\n * pretending each branch is its own `--p:` flag.\n */\nimport type {\n MethodSchema,\n LinkRpcInterfaceSchema as SvcInterfaceSchema,\n LinkRpcJsonSchema as SvcJsonSchema,\n} from '@hediet/linkrpc';\n\nexport interface RenderedParamHelp {\n /** Multi-line block, or empty when the method takes no params. */\n readonly text: string;\n /**\n * Param names suitable for completion. Empty when the params descriptor\n * isn't a plain object (no `--p:<name>` flag-name to suggest).\n */\n readonly paramNames: readonly string[];\n}\n\nexport function renderMethodParamHelp(\n method: MethodSchema,\n schema: SvcInterfaceSchema,\n): RenderedParamHelp {\n const resolved = _resolve(method.params, schema.components?.schemas ?? {});\n if (!_isObjectSchema(resolved)) {\n return {\n text:\n `Method parameters (${schema.id}@${schema.hash}):\\n`\n + ` (params is not a plain object — pass with --params <json>)\\n`,\n paramNames: [],\n };\n }\n\n const props = resolved.properties ?? {};\n const required = new Set<string>(resolved.required ?? []);\n const names = Object.keys(props);\n if (names.length === 0) {\n return {\n text:\n `Method parameters (${schema.id}@${schema.hash}):\\n`\n + ` (no parameters)\\n`,\n paramNames: [],\n };\n }\n\n const rows: string[][] = [];\n for (const name of names) {\n const propSchema = _resolve(props[name], schema.components?.schemas ?? {});\n const flag = `--p:${name} <${_typeLabel(propSchema)}>`;\n const reqMark = required.has(name) ? 'required' : 'optional';\n const desc = _oneLineDescription(propSchema);\n rows.push([flag, reqMark, desc]);\n }\n\n const flagCol = Math.max(...rows.map((r) => r[0].length));\n const reqCol = Math.max(...rows.map((r) => r[1].length));\n\n const lines = [`Method parameters (${schema.id}@${schema.hash}):`];\n for (const [flag, req, desc] of rows) {\n const padded = ` ${flag.padEnd(flagCol)} ${req.padEnd(reqCol)}${desc ? ' ' + desc : ''}`;\n lines.push(padded.trimEnd());\n }\n return { text: lines.join('\\n') + '\\n', paramNames: names };\n}\n\nfunction _isObjectSchema(\n s: SvcJsonSchema,\n): s is Extract<SvcJsonSchema, { type: 'object' }> {\n return typeof s === 'object' && s !== null && (s as { type?: string }).type === 'object';\n}\n\nfunction _resolve(\n s: SvcJsonSchema,\n components: Record<string, SvcJsonSchema>,\n): SvcJsonSchema {\n if (typeof s === 'object' && s !== null && '$ref' in s) {\n const ref = (s as { $ref: string }).$ref;\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n if (m) {\n const target = components[m[1]];\n if (target !== undefined) return target;\n }\n }\n return s;\n}\n\nfunction _typeLabel(s: SvcJsonSchema): string {\n if (s === true) return 'any';\n if (s === false) return 'never';\n const obj = s as unknown as Record<string, unknown>;\n\n if (typeof obj.type === 'string') {\n if (obj.type === 'array') {\n const items = obj.items as SvcJsonSchema | undefined;\n if (items !== undefined) return `${_typeLabel(items)}[]`;\n return 'array';\n }\n const fmt = obj.format !== undefined ? `:${obj.format}` : '';\n return `${obj.type as string}${fmt}`;\n }\n if (Array.isArray(obj.enum)) {\n return `enum(${obj.enum.map((v) => JSON.stringify(v)).join('|')})`;\n }\n if ('const' in obj) {\n return JSON.stringify(obj.const);\n }\n if (Array.isArray(obj.oneOf) || Array.isArray(obj.anyOf)) {\n return 'union';\n }\n if ('$ref' in obj) {\n const ref = obj.$ref as string;\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n return m ? m[1] : 'ref';\n }\n return 'value';\n}\n\nfunction _oneLineDescription(propSchema: SvcJsonSchema): string {\n const obj = propSchema as unknown as Record<string, unknown>;\n const raw = (obj.description as string | undefined) ?? (obj.title as string | undefined) ?? '';\n if (!raw) return '';\n const firstLine = raw.split(/\\r?\\n/, 1)[0];\n return firstLine.length > 80 ? firstLine.slice(0, 77) + '…' : firstLine;\n}\n","/**\n * Pre-processor for `--p:<name>[=<value>]` shortcuts on the CLI. Rewrites\n * them to commander-friendly `--param <name>=<value>` pairs *before*\n * commander sees the argv, so we don't have to teach commander about them\n * (which is awkward given they're dynamic per-method).\n *\n * Forms accepted:\n * --p:to=a@b.c single token, kept verbatim → `--param to=a@b.c`\n * --p:to a@b.c two tokens, joined → `--param to=a@b.c`\n * --p:dryRun boolean shortcut (no value) → `--param dryRun=true`\n *\n * Nested keys keep working through the existing `mergeParams` dot-path\n * support: `--p:user.name=alice` → `--param user.name=alice`.\n *\n * Anything past a literal `--` token is left alone (POSIX end-of-options).\n * Tokens that look like the start of the next flag (e.g. `--p:dryRun\n * --verbose`) are treated as the \"no value\" form so `--verbose` keeps its\n * intended role.\n */\n\nconst FLAG_PREFIX = '--p:';\n\n/**\n * Transform `argv`, expanding every `--p:<name>` token to `--param key=value`.\n * Non-matching tokens pass through unchanged. Returns a new array; never\n * mutates the input.\n */\nexport function rewriteParamShortcuts(argv: readonly string[]): string[] {\n return rewriteCapabilityShortcuts(expandParamShortcuts(argv));\n}\n\nfunction expandParamShortcuts(argv: readonly string[]): string[] {\n const out: string[] = [];\n let stopExpanding = false;\n\n for (let i = 0; i < argv.length; i++) {\n const tok = argv[i];\n\n if (!stopExpanding && tok === '--') {\n stopExpanding = true;\n out.push(tok);\n continue;\n }\n if (stopExpanding || !tok.startsWith(FLAG_PREFIX)) {\n out.push(tok);\n continue;\n }\n\n const rest = tok.slice(FLAG_PREFIX.length);\n if (rest.length === 0) {\n // Bare `--p:` is meaningless; leave it for commander to error on.\n out.push(tok);\n continue;\n }\n\n const eq = rest.indexOf('=');\n if (eq >= 0) {\n const name = rest.slice(0, eq);\n const value = rest.slice(eq + 1);\n if (name.length === 0) {\n out.push(tok); // malformed `--p:=value`; let commander complain\n continue;\n }\n out.push('--param', `${name}=${value}`);\n continue;\n }\n\n // `--p:name` with no inline value. Use the next token unless it looks\n // like another flag (then assume boolean shortcut).\n const name = rest;\n const peek = argv[i + 1];\n if (peek === undefined || peek.startsWith('-')) {\n out.push('--param', `${name}=true`);\n continue;\n }\n out.push('--param', `${name}=${peek}`);\n i += 1;\n }\n return out;\n}\n\nconst CAPABILITY_SHORTCUTS = new Map([\n ['--cap:allow-prefix', 'prefix'],\n ['--cap:allow-any', 'any'],\n ['--cap:allow-enum', 'enum'],\n ['--cap:allow-subset', 'subsetOf'],\n]);\n\nfunction rewriteCapabilityShortcuts(argv: readonly string[]): string[] {\n const out: string[] = [];\n const constrained = new Set<string>();\n const assigned = new Set<string>();\n let precedingParam: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i];\n if (token === '--') {\n out.push(...argv.slice(i));\n break;\n }\n const eq = token.indexOf('=');\n const flag = eq < 0 ? token : token.slice(0, eq);\n const matcher = CAPABILITY_SHORTCUTS.get(flag);\n if (matcher !== undefined) {\n if (precedingParam === undefined) {\n throw new Error(`${flag} must immediately follow a --param or --p:<name> assignment.`);\n }\n if (precedingParam.includes('.')) throw new Error(`${flag} only supports top-level parameter names.`);\n if (constrained.has(precedingParam)) throw new Error(`Duplicate --cap:allow-param for ${precedingParam}.`);\n let value: unknown = true;\n if (matcher === 'any') {\n if (eq >= 0) throw new Error('--cap:allow-any takes no value.');\n } else {\n const raw = eq >= 0 ? token.slice(eq + 1) : argv[++i];\n if (raw === undefined || (eq < 0 && raw.startsWith('--'))) {\n throw new Error(`${flag} requires a value.`);\n }\n if (matcher === 'prefix') {\n value = raw;\n } else {\n try { value = JSON.parse(raw); }\n catch { throw new Error(`${flag} requires a JSON array.`); }\n if (!Array.isArray(value)\n || (matcher === 'enum' && value.length === 0)\n || (matcher === 'subsetOf' && !value.every(item => typeof item === 'string'))) {\n throw new Error(`${flag} requires ${matcher === 'enum' ? 'a non-empty JSON array' : 'a JSON string array'}.`);\n }\n }\n }\n constrained.add(precedingParam);\n out.push('--cap:allow-param', `${precedingParam}=${JSON.stringify({ [matcher]: value })}`);\n continue;\n }\n if (flag === '--param' || flag === '--cap:allow-param') {\n const values: string[] = [];\n if (eq >= 0) {\n values.push(token.slice(eq + 1));\n out.push(token);\n } else {\n out.push(token);\n while (argv[i + 1] !== undefined && !argv[i + 1].startsWith('-')) {\n const value = argv[++i];\n values.push(value);\n out.push(value);\n }\n }\n precedingParam = undefined;\n for (const value of values) {\n const assignment = value.indexOf('=');\n if (assignment <= 0) continue;\n const key = value.slice(0, assignment);\n if (constrained.has(key) && (flag === '--cap:allow-param' || assigned.has(key))) {\n throw new Error(flag === '--param'\n ? `Cannot reassign parameter ${key} after an explicit capability constraint.`\n : `Duplicate --cap:allow-param for ${key}.`);\n }\n if (flag === '--cap:allow-param') constrained.add(key);\n else {\n assigned.add(key);\n precedingParam = key;\n }\n }\n continue;\n }\n precedingParam = undefined;\n out.push(token);\n }\n return out;\n}\n","export function safeTerminalText(text: string): string {\n let result = '';\n for (const character of text) {\n result += /^[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]$/u.test(character)\n ? `\\\\u{${character.codePointAt(0)!.toString(16).padStart(4, '0')}}`\n : character;\n }\n return result;\n}\n","import { safeTerminalText } from \"../../ui/terminalText\";\nimport type { GraphTreeLine } from \"./inspectGraphModel\";\nimport type { GraphExplorerModel } from \"./inspectGraphView\";\n\nexport interface GraphFrameOptions {\n readonly title: string;\n readonly params: string;\n readonly version?: number;\n readonly columns: number;\n readonly rows: number;\n readonly scrollTop: number;\n readonly revealSelection?: boolean;\n readonly showObjectIds?: boolean;\n readonly status?: string;\n readonly error?: boolean;\n readonly phase?: string;\n}\n\nexport interface GraphFrameRow {\n readonly text: string;\n readonly style: \"header\" | \"muted\" | \"reference\" | \"value\" | \"selected\" | \"error\";\n readonly key?: string;\n}\n\nexport const graphChromeRows = 6;\n\n/** Presentation only: no terminal ownership, input handling or mutable model state. */\nexport function createGraphFrame(model: GraphExplorerModel | undefined, options: GraphFrameOptions): {\n readonly rows: readonly GraphFrameRow[];\n readonly scrollTop: number;\n} {\n const capacity = Math.max(0, options.rows - graphChromeRows);\n const lines = model?.lines ?? [];\n const selected = model?.selectedIndex ?? 0;\n const scrollTop = clampGraphScroll(lines.length, selected, options.scrollTop, capacity, options.revealSelection !== false);\n const separator = \" \" + \"─\".repeat(Math.max(0, options.columns - 2));\n const rows: GraphFrameRow[] = [\n { text: ` GRAPH EXPLORER ${options.phase ?? (options.version === undefined ? \"CONNECTING\" : `LIVE v${options.version}`)}`, style: \"header\" },\n { text: ` ${options.title} ${options.params}`, style: \"muted\" },\n { text: separator, style: \"muted\" },\n ];\n const labels = formatGraphTreeRows(lines, options.showObjectIds === true);\n for (let offset = 0; offset < capacity; offset++) {\n const index = scrollTop + offset;\n const line = lines[index];\n rows.push({\n text: line ? \" \" + labels[index] : \"\",\n key: line?.key,\n style: line && index === selected ? \"selected\" : line?.ref ? \"reference\" : \"value\",\n });\n }\n rows.push(\n { text: separator, style: \"muted\" },\n { text: ` ${options.status ?? (model ? model.selectedKey : \"Waiting for first root…\")}`, style: options.error ? \"error\" : \"muted\" },\n { text: ` ${lines.length === 0 ? 0 : selected + 1}/${lines.length} ${model?.cachedObjects ?? 0} cached objects`\n + ` IDs:${options.showObjectIds ? \"on\" : \"off\"}`, style: \"reference\" },\n );\n return { rows: rows.slice(0, Math.max(0, options.rows)), scrollTop };\n}\n\nexport function clampGraphScroll(count: number, selected: number, top: number, capacity: number, reveal = true): number {\n return Math.max(0, Math.min(\n !reveal || capacity === 0 ? top : selected < top ? selected\n : selected >= top + capacity ? selected - capacity + 1 : top,\n Math.max(0, count - capacity),\n ));\n}\n\n/** Relative labels and branches are computed before slicing, so scrolled rows retain ancestry. */\nexport function formatGraphTreeRows(lines: readonly GraphTreeLine[], showObjectIds: boolean): readonly string[] {\n const ancestors: GraphTreeLine[] = [];\n const ancestorIndices: number[] = [];\n const nextSiblings = new Map<number, number>();\n const hasSibling: boolean[] = [];\n for (let index = lines.length - 1; index >= 0; index--) {\n const depth = lines[index]!.depth;\n hasSibling[index] = nextSiblings.has(depth);\n for (const deeper of nextSiblings.keys()) if (deeper > depth) nextSiblings.delete(deeper);\n nextSiblings.set(depth, index);\n }\n return lines.map((line, index) => {\n ancestors.length = line.depth;\n ancestorIndices.length = line.depth;\n const parent = ancestors[line.depth - 1];\n const label = line.key === \"$\" ? \"root\" : line.key.slice((parent?.key ?? \"$\").length).replace(/^\\./, \"\");\n ancestors[line.depth] = line;\n ancestorIndices[line.depth] = index;\n const marker = line.targetKey !== undefined ? \"↪\" : line.expandable ? line.expanded && line.loaded ? \"▾\" : \"▸\" : \" \";\n const content = line.ref === undefined ? line.text.slice(line.key.length).replace(/^ = /, \" \")\n : ` ${line.ref.kind}${showObjectIds ? `:${line.ref.id}` : \"\"}`\n + (line.summary === undefined ? \"\" : ` ${line.summary}`)\n + (line.description === undefined ? \"\" : ` — ${line.description}`)\n + (line.loaded ? \"\" : \" [fetch on expand]\")\n + (line.targetKey === undefined ? \"\" : ` [link to ${line.targetKey}]`);\n const branch = line.depth === 0 ? \"\" : ancestorIndices.slice(1, line.depth)\n .map(ancestor => hasSibling[ancestor] ? \"│ \" : \" \").join(\"\")\n + (hasSibling[index] ? \"├─ \" : \"└─ \");\n return `${branch}${marker} ${label}${content}`;\n });\n}\n\nexport function anchorGraphScrollTop(previous: readonly GraphTreeLine[], next: readonly GraphTreeLine[], scrollTop: number): number {\n const indices = new Map(next.map((line, index) => [line.key, index]));\n for (let distance = 0; distance < previous.length; distance++) {\n for (const index of distance === 0 ? [scrollTop] : [scrollTop + distance, scrollTop - distance]) {\n const line = previous[index];\n const position = line === undefined ? undefined : indices.get(line.key);\n if (position !== undefined) return position;\n }\n }\n return scrollTop;\n}\n\nconst segments = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\nfunction cellWidth(text: string): number {\n const code = text.codePointAt(0)!;\n if (/^\\p{Mark}+$/u.test(text)) return 0;\n if (/[\\p{Extended_Pictographic}\\p{Regional_Indicator}]/u.test(text)) return 2;\n return code >= 0x1100 && (code <= 0x115f || code === 0x2329 || code === 0x232a\n || code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f\n || code >= 0xac00 && code <= 0xd7a3 || code >= 0xf900 && code <= 0xfaff\n || code >= 0xfe10 && code <= 0xfe19 || code >= 0xfe30 && code <= 0xfe6f\n || code >= 0xff00 && code <= 0xff60 || code >= 0xffe0 && code <= 0xffe6\n || code >= 0x20000 && code <= 0x3fffd) ? 2 : 1;\n}\n\n/** Sanitize first, then clip/pad by terminal cells so Ink never wraps a frame row. */\nexport function graphFrameText(text: string, columns: number, pad = false): string {\n const width = Math.max(0, columns);\n const characters = [...segments.segment(safeTerminalText(text))].map(value => value.segment);\n let result = \"\", used = 0;\n const total = characters.reduce((sum, value) => sum + cellWidth(value), 0);\n const clipped = total > width;\n for (const character of characters) {\n const size = cellWidth(character);\n if (used + size > width - (clipped ? 1 : 0)) break;\n used += size;\n result += character;\n }\n if (clipped && width > 0) { result += \"…\"; used++; }\n return result + (pad ? \" \".repeat(Math.max(0, width - used)) : \"\");\n}\n","import { emitKeypressEvents, type Key } from \"node:readline\";\nimport { stdin, stdout } from \"node:process\";\nimport { autorun, observableValue } from \"@vscode/observables\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\nimport type { GraphTreeLine } from \"./inspectGraphModel\";\nimport type { GraphExplorerModel } from \"./inspectGraphView\";\nimport type { GraphTimings } from \"./inspectGraphTiming\";\nimport { anchorGraphScrollTop, formatGraphTreeRows } from \"./graphFrame\";\nexport { anchorGraphScrollTop } from \"./graphFrame\";\n\nexport class GraphTerminal {\n private readonly _view = observableValue<{ model: GraphExplorerModel; version: number } | undefined>(this, undefined);\n private readonly _busy = observableValue(this, false);\n private readonly _updating = observableValue(this, false);\n private readonly _error = observableValue<string | undefined>(this, undefined);\n private readonly _revision = observableValue(this, 0);\n private readonly _scrollTop = observableValue(this, 0);\n private readonly _showObjectIds = observableValue(this, false);\n private _renderedLines: readonly GraphTreeLine[] = [];\n private _renderedModel: GraphExplorerModel | undefined;\n private _revealSelection = true;\n private readonly _raw = stdin.isRaw;\n private readonly _wasFlowing = stdin.readableFlowing === true;\n private readonly _rendering: { dispose(): void };\n private _action: Promise<void> = Promise.resolve();\n private _disposed = false;\n private readonly _resolve: () => void;\n private readonly _reject: (error: unknown) => void;\n public readonly result: Promise<void>;\n\n public constructor(\n private readonly _title: string,\n private readonly _params: string,\n private readonly _repaint: (text: string) => void = text => { stdout.write(text); },\n private readonly _timings?: GraphTimings,\n ) {\n let resolve!: () => void;\n let reject!: (error: unknown) => void;\n this.result = new Promise<void>((res, rej) => { resolve = res; reject = rej; });\n this._resolve = resolve;\n this._reject = reject;\n stdout.write(\"\\x1b[?1049h\\x1b[?25l\\x1b[?7l\");\n emitKeypressEvents(stdin);\n stdin.setRawMode(true);\n stdin.resume();\n stdin.on(\"keypress\", this._onKey);\n stdout.on(\"resize\", this._invalidate);\n this._rendering = autorun(reader => {\n const view = this._view.read(reader);\n const busy = this._busy.read(reader);\n const updating = this._updating.read(reader);\n const error = this._error.read(reader);\n const showObjectIds = this._showObjectIds.read(reader);\n this._revision.read(reader);\n const model = view?.model;\n const lines = model?.lines ?? [];\n const scrollTop = model !== this._renderedModel\n ? anchorGraphScrollTop(this._renderedLines, lines, this._scrollTop.get())\n : this._scrollTop.get();\n const render = () => renderGraphScreen(model, {\n title: this._title,\n params: this._params,\n version: view?.version,\n columns: stdout.columns || 80,\n rows: stdout.rows || 24,\n scrollTop,\n revealSelection: this._revealSelection,\n showObjectIds,\n status: error ?? (updating ? \"Refreshing root...\" : busy ? \"Loading object...\" : undefined),\n error: error !== undefined,\n });\n const frame = this._timings?.measureSync(\"screen\", render, { version: view?.version ?? 0 }) ?? render();\n this._scrollTop.set(frame.scrollTop, undefined);\n this._renderedLines = lines;\n this._renderedModel = model;\n this._repaint(frame.text);\n });\n }\n\n public async beginUpdate(): Promise<void> {\n this._updating.set(true, undefined);\n await this._action;\n }\n\n public async finishUpdate(model: GraphExplorerModel, version: number, signal?: AbortSignal): Promise<void> {\n while (!this._disposed) {\n await this._action;\n signal?.throwIfAborted();\n const source = this._view.get()?.model;\n const paths = source?.expandedPaths;\n await model.restoreExpanded(signal, source);\n signal?.throwIfAborted();\n if (this._busy.get() || source?.expandedPaths !== paths) continue;\n if (source !== undefined) {\n const selected = source.selectedKey;\n model.select(Math.max(0, model.lines.findIndex(line => line.key === selected)));\n }\n this.update(model, version);\n return;\n }\n }\n\n public update(model: GraphExplorerModel, version: number): void {\n if (this._disposed) return;\n this._revealSelection = this._view.get() === undefined;\n this._view.set({ model, version }, undefined);\n this._updating.set(false, undefined);\n }\n\n public dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._rendering.dispose();\n stdin.off(\"keypress\", this._onKey);\n stdout.off(\"resize\", this._invalidate);\n stdin.setRawMode(this._raw ?? false);\n if (!this._wasFlowing) stdin.pause();\n stdout.write(\"\\x1b[0m\\x1b[?7h\\x1b[?25h\\x1b[?1049l\");\n this._resolve();\n }\n\n private readonly _invalidate = (): void => {\n this._revision.set(this._revision.get() + 1, undefined);\n };\n\n private readonly _onKey = (text: string, key: Key): void => {\n if (text === \"q\" || key.name === \"escape\" || (key.ctrl && key.name === \"c\")) {\n this.dispose();\n return;\n }\n if (this._disposed) return;\n if (text === \"i\" && !key.ctrl && !key.meta) {\n this._showObjectIds.set(!this._showObjectIds.get(), undefined);\n return;\n }\n const expands = key.name === \"right\" || key.name === \"return\" || text === \"l\" || text === \" \";\n if (this._busy.get() && expands) return;\n const action = this._handleKey(text, key).catch(error => {\n this._reject(error);\n this.dispose();\n });\n if (expands) this._action = action;\n };\n\n private async _handleKey(text: string, key: Key): Promise<void> {\n const model = this._view.get()?.model;\n if (model === undefined) return;\n this._revealSelection = true;\n this._error.set(undefined, undefined);\n const page = Math.max(1, (stdout.rows || 24) - 7);\n if (key.name === \"down\" || text === \"j\") model.move(1);\n else if (key.name === \"up\" || text === \"k\") model.move(-1);\n else if (key.name === \"pagedown\") model.move(page);\n else if (key.name === \"pageup\") model.move(-page);\n else if (key.name === \"home\" || text === \"g\") model.select(0);\n else if (key.name === \"end\" || text === \"G\") model.select(model.lines.length - 1);\n else if (key.name === \"left\" || text === \"h\") model.collapseSelected();\n else if (key.name === \"right\" || key.name === \"return\" || text === \"l\" || text === \" \") {\n this._busy.set(true, undefined);\n try {\n await model.expandSelected();\n } catch (error) {\n this._error.set(error instanceof Error ? error.message : String(error), undefined);\n } finally {\n this._busy.set(false, undefined);\n }\n }\n this._invalidate();\n }\n}\n\nexport interface GraphScreenOptions {\n readonly title: string;\n readonly params: string;\n readonly version?: number;\n readonly columns: number;\n readonly rows: number;\n readonly scrollTop: number;\n readonly revealSelection?: boolean;\n readonly showObjectIds?: boolean;\n readonly status?: string;\n readonly error?: boolean;\n}\n\nexport function renderGraphScreen(\n model: GraphExplorerModel | undefined,\n options: GraphScreenOptions,\n): { readonly text: string; readonly scrollTop: number } {\n const width = Math.max(1, options.columns - 1);\n const height = Math.max(1, options.rows);\n const capacity = Math.max(1, height - 7);\n const lines = model?.lines ?? [];\n const selected = model?.selectedIndex ?? 0;\n const scrollTop = Math.max(0, Math.min(\n options.revealSelection === false ? options.scrollTop\n : selected < options.scrollTop ? selected\n : selected >= options.scrollTop + capacity ? selected - capacity + 1 : options.scrollTop,\n Math.max(0, lines.length - capacity),\n ));\n const frame: string[] = [];\n const row = (text: string, style = \"\\x1b[37m\"): void => {\n frame.push(`${style}${clip(text, width)}\\x1b[K\\x1b[0m`);\n };\n row(` GRAPH EXPLORER ${options.version === undefined ? \"CONNECTING\" : `LIVE v${options.version}`}`, \"\\x1b[1;36m\");\n row(` ${options.title} ${options.params}`, \"\\x1b[90m\");\n row(\" \" + \"\\u2500\".repeat(Math.max(0, width - 2)), \"\\x1b[90m\");\n const labels = formatGraphTreeRows(lines, options.showObjectIds === true);\n for (let offset = 0; offset < capacity; offset++) {\n const index = scrollTop + offset;\n row(index < lines.length ? \" \" + labels[index] : \"\",\n index === selected && lines.length > 0 ? \"\\x1b[1;30;46m\"\n : lines[index]?.ref === undefined ? \"\\x1b[37m\" : \"\\x1b[36m\");\n }\n row(\" \" + \"\\u2500\".repeat(Math.max(0, width - 2)), \"\\x1b[90m\");\n row(` ${options.status ?? (model === undefined ? \"Waiting for first root...\" : model.selectedKey)}`,\n options.error ? \"\\x1b[31m\" : \"\\x1b[90m\");\n row(` ${lines.length === 0 ? 0 : selected + 1}/${lines.length} ${model?.cachedObjects ?? 0} cached objects`\n + ` \\u2191\\u2193 move \\u2192/Enter open \\u2190 close i IDs:${options.showObjectIds ? \"on\" : \"off\"} q quit`, \"\\x1b[36m\");\n return {\n text: frame.slice(0, height).map((line, index) => `\\x1b[${index + 1};1H${line}`).join(\"\") + \"\\x1b[J\",\n scrollTop,\n };\n}\n\nfunction clip(text: string, width: number): string {\n const characters = [...safeTerminalText(text)];\n return characters.length <= width ? characters.join(\"\")\n : characters.slice(0, Math.max(0, width - 1)).join(\"\") + \"\\u2026\";\n}\n","export interface GraphTiming {\n readonly phase: string;\n readonly wallMs: number;\n readonly cpuUserMs: number;\n readonly cpuSystemMs: number;\n readonly ok: boolean;\n readonly detail: Readonly<Record<string, number>>;\n}\n\nexport class GraphTimings {\n public constructor(private readonly _emit: (timing: GraphTiming) => void) {}\n\n public measureSync<T>(phase: string, operation: () => T, detail: GraphTiming[\"detail\"] = {}): T {\n const finish = this._start(phase, detail);\n let ok = false;\n try {\n const result = operation();\n ok = true;\n return result;\n } finally {\n finish(ok);\n }\n }\n\n public async measureAsync<T>(phase: string, operation: () => Promise<T>, detail: GraphTiming[\"detail\"] = {}): Promise<T> {\n const finish = this._start(phase, detail);\n let ok = false;\n try {\n const result = await operation();\n ok = true;\n return result;\n } finally {\n finish(ok);\n }\n }\n\n private _start(phase: string, detail: GraphTiming[\"detail\"]): (ok: boolean) => void {\n const start = performance.now();\n const cpu = process.cpuUsage();\n return ok => {\n const elapsedCpu = process.cpuUsage(cpu);\n this._emit({\n phase,\n wallMs: performance.now() - start,\n cpuUserMs: elapsedCpu.user / 1000,\n cpuSystemMs: elapsedCpu.system / 1000,\n ok,\n detail,\n });\n };\n }\n}\n","import type {\n JsonValue,\n} from \"@hediet/linkrpc\";\nimport type {\n GraphBatchRequest as LinkRpcGraphBatchRequest,\n GraphBatchResult as LinkRpcGraphBatchResult,\n GraphHave as LinkRpcGraphHave,\n GraphNeed as LinkRpcGraphNeed,\n GraphObject as LinkRpcGraphObject,\n GraphRef,\n GraphLimits,\n MissingGraphObject,\n} from \"@hediet/linkrpc-infra/graph\";\nimport { evaluateGraphPresentation, isGraphRef, standardGraphRuntimeOptions, type GraphPresentation } from \"@hediet/linkrpc-infra/graph\";\nimport type { GraphTimings } from \"./inspectGraphTiming\";\n\nexport type GraphBatchRequest = LinkRpcGraphBatchRequest<GraphRef>;\nexport type GraphBatchResult = LinkRpcGraphBatchResult<GraphRef, JsonValue>;\nexport type GraphHave = LinkRpcGraphHave<GraphRef>;\nexport type GraphNeed = LinkRpcGraphNeed<GraphRef>;\nexport type GraphObject = LinkRpcGraphObject<GraphRef, JsonValue>;\nexport type { GraphRef };\n\nexport type GraphBatchFetch = (\n request: GraphBatchRequest,\n signal: AbortSignal,\n) => Promise<unknown>;\n\nexport interface GraphFetchOptions {\n readonly timings?: GraphTimings;\n readonly signal?: AbortSignal;\n readonly maxObjects?: number;\n readonly maxBytes?: number;\n readonly maxRounds?: number;\n readonly timeoutMs?: number;\n}\n\nexport class GraphObjectCache {\n private readonly _objects = new Map<string, GraphObject>();\n\n public get size(): number {\n return this._objects.size;\n }\n\n public get(ref: GraphRef): GraphObject | undefined {\n return this._objects.get(graphRefKey(ref));\n }\n\n public has(ref: GraphRef): boolean {\n return this._objects.has(graphRefKey(ref));\n }\n\n public put(objects: readonly GraphObject[]): void {\n for (const object of objects) {\n const key = graphRefKey(object.ref);\n const previous = this._objects.get(key);\n if (previous !== undefined && !jsonEqual(previous.value, object.value)) {\n throw new Error(`Graph server returned conflicting values for ${formatGraphRef(object.ref)}`);\n }\n this._objects.set(key, object);\n }\n }\n\n public have(): readonly GraphHave[] {\n return [...this._objects.values()]\n .map(({ ref }) => ({ ref, coverage: \"object\" as const }))\n .sort((a, b) => graphRefKey(a.ref).localeCompare(graphRefKey(b.ref)));\n }\n}\n\nexport class GraphLoader {\n private readonly _limits: GraphLimits;\n private readonly _maxRounds: number;\n private readonly _timeoutMs: number;\n private readonly _signal: AbortSignal | undefined;\n private readonly _timings: GraphTimings | undefined;\n\n public constructor(\n private readonly _fetch: GraphBatchFetch,\n public readonly cache = new GraphObjectCache(),\n options: GraphFetchOptions = {},\n ) {\n this._signal = options.signal;\n this._timings = options.timings;\n this._limits = {\n maxObjects: options.maxObjects ?? 256,\n maxBytes: options.maxBytes ?? 1_048_576,\n };\n this._maxRounds = options.maxRounds ?? 32;\n this._timeoutMs = options.timeoutMs ?? 5_000;\n if (!Number.isInteger(this._limits.maxObjects) || this._limits.maxObjects <= 0) {\n throw new Error(\"maxObjects must be a positive integer\");\n }\n if (!Number.isInteger(this._limits.maxBytes) || this._limits.maxBytes <= 0) {\n throw new Error(\"maxBytes must be a positive integer\");\n }\n if (!Number.isInteger(this._maxRounds) || this._maxRounds <= 0) {\n throw new Error(\"maxRounds must be a positive integer\");\n }\n if (!Number.isInteger(this._timeoutMs) || this._timeoutMs <= 0) {\n throw new Error(\"timeoutMs must be a positive integer\");\n }\n }\n\n public async load(needs: readonly GraphNeed[]): Promise<void> {\n const normalizedNeeds = normalizeNeeds(needs);\n const objectOnly = normalizedNeeds.every(need => need.paths.every(path => path === \"/\"));\n for (let round = 0; ; round++) {\n this._signal?.throwIfAborted();\n const pendingNeeds = objectOnly\n ? normalizedNeeds.filter(need => !this.cache.has(need.ref))\n : normalizedNeeds;\n if (pendingNeeds.length === 0) return;\n if (round >= this._maxRounds) {\n throw new Error(\n `Graph fetch did not converge after ${this._maxRounds} rounds; `\n + `${normalizedNeeds.length} need(s) remain`,\n );\n }\n const before = this.cache.size;\n const fetch = () => withTimeout(\n (signal) => this._fetch({\n needs: pendingNeeds,\n // Object-only reads cannot encounter cached descendants.\n have: objectOnly ? [] : this.cache.have(),\n limits: this._limits,\n }, signal),\n this._timeoutMs,\n \"graph batch fetch\",\n this._signal,\n );\n const raw = await (this._timings?.measureAsync(\"fetch\", fetch, { needs: pendingNeeds.length, round }) ?? fetch());\n const processResult = () => {\n const result = parseGraphBatchResult(raw);\n assertNoMissing(result.missing);\n this.cache.put(result.objects);\n return result;\n };\n const result = this._timings?.measureSync(\"cache\", processResult) ?? processResult();\n if (result.complete) return;\n if (this.cache.size === before) {\n throw new Error(\n \"Graph server returned an incomplete batch without progress\",\n );\n }\n }\n }\n}\n\nexport interface GraphTreeLine {\n readonly key: string;\n readonly depth: number;\n readonly text: string;\n readonly ref?: GraphRef;\n readonly expandable: boolean;\n readonly expanded?: boolean;\n readonly loaded?: boolean;\n readonly targetKey?: string;\n readonly summary?: string;\n readonly description?: string;\n readonly presentationPending?: readonly GraphRef[];\n readonly selector?: string;\n}\n\nexport function createGraphTree(\n root: GraphRef,\n cache: GraphObjectCache,\n expanded: ReadonlySet<string>,\n maxDepth = Number.POSITIVE_INFINITY,\n presentation?: GraphPresentation,\n): readonly GraphTreeLine[] {\n const lines: GraphTreeLine[] = [];\n const firstPaths = new Map<string, string>();\n appendRef(root, \"$\", 0, new Set(), lines, firstPaths, cache, expanded, maxDepth, []);\n if (presentation === undefined) return lines;\n return lines.map(line => {\n if (line.ref === undefined || !Object.hasOwn(presentation.rules, line.ref.kind)) return line;\n const result = evaluateGraphPresentation(line.ref, presentation, ref => cache.get(ref));\n return { ...line, summary: result.label, description: result.secondary, presentationPending: result.pending };\n });\n}\n\nexport function graphRefsInValue(value: JsonValue): readonly GraphRef[] {\n const refs = new Map<string, GraphRef>();\n visitValue(value, (ref) => refs.set(graphRefKey(ref), ref));\n return [...refs.values()];\n}\n\nexport const graphRefKey = standardGraphRuntimeOptions.refKey;\n\nexport function formatGraphRef(ref: GraphRef): string {\n return `${ref.kind}:${ref.id}`;\n}\n\nexport function parseGraphRef(value: unknown, location = \"graph ref\"): GraphRef {\n if (!isGraphRef(value)) throw new Error(`${location} must contain exactly string kind and id fields`);\n return value;\n}\n\nexport function parseGraphBatchResult(value: unknown): GraphBatchResult {\n const record = asRecord(value, \"graph batch result\");\n if (!Array.isArray(record.objects)) {\n throw new Error(\"graph batch result.objects must be an array\");\n }\n if (!Array.isArray(record.missing)) {\n throw new Error(\"graph batch result.missing must be an array\");\n }\n if (typeof record.complete !== \"boolean\") {\n throw new Error(\"graph batch result.complete must be a boolean\");\n }\n const objects = record.objects.map((item, index): GraphObject => {\n const object = asRecord(item, `graph batch result.objects[${index}]`);\n if (!Object.hasOwn(object, \"value\")) {\n throw new Error(`graph batch result.objects[${index}].value is required`);\n }\n assertJsonValue(object.value, `graph batch result.objects[${index}].value`);\n return {\n ref: parseGraphRef(object.ref, `graph batch result.objects[${index}].ref`),\n value: object.value,\n };\n });\n const missing = record.missing.map((item, index) =>\n parseMissing(item, `graph batch result.missing[${index}]`));\n return { objects, missing, complete: record.complete };\n}\n\nfunction parseGraphNeed(value: unknown, location: string): GraphNeed {\n const record = asRecord(value, location);\n if (!Array.isArray(record.paths)) {\n throw new Error(`${location}.paths must be an array`);\n }\n const paths = record.paths.map((path, pathIndex) => {\n if (typeof path !== \"string\" || !path.startsWith(\"/\")) {\n throw new Error(`${location}.paths[${pathIndex}] must be a JSON pointer string`);\n }\n return path;\n });\n return { ref: parseGraphRef(record.ref, `${location}.ref`), paths };\n}\n\nfunction normalizeNeeds(needs: readonly GraphNeed[]): readonly GraphNeed[] {\n const result = new Map<string, { ref: GraphRef; paths: Set<string> }>();\n for (const need of needs) {\n const key = graphRefKey(need.ref);\n let entry = result.get(key);\n if (entry === undefined) {\n entry = { ref: need.ref, paths: new Set() };\n result.set(key, entry);\n }\n for (const path of need.paths) entry.paths.add(path);\n }\n return [...result.values()].map(({ ref, paths }) => ({ ref, paths: [...paths] }));\n}\n\nfunction parseMissing(value: unknown, location: string): MissingGraphObject<GraphRef> {\n const record = asRecord(value, location);\n const reasons = new Set([\"missing\", \"expired\", \"forbidden\", \"oversized\"]);\n if (typeof record.reason !== \"string\" || !reasons.has(record.reason)) {\n throw new Error(`${location}.reason is unsupported`);\n }\n if (record.detail !== undefined && typeof record.detail !== \"string\") {\n throw new Error(`${location}.detail must be a string when present`);\n }\n return {\n ref: parseGraphRef(record.ref, `${location}.ref`),\n reason: record.reason as MissingGraphObject<GraphRef>[\"reason\"],\n ...(record.detail === undefined ? {} : { detail: record.detail }),\n };\n}\n\nfunction assertNoMissing(missing: readonly MissingGraphObject<GraphRef>[]): void {\n if (missing.length === 0) return;\n const details = missing.map((item) =>\n `${formatGraphRef(item.ref)}: ${item.reason}${item.detail === undefined ? \"\" : ` (${item.detail})`}`);\n throw new Error(`Graph references unavailable:\\n${details.map((line) => ` ${line}`).join(\"\\n\")}`);\n}\n\nfunction appendRef(\n ref: GraphRef,\n path: string,\n depth: number,\n ancestors: ReadonlySet<string>,\n lines: GraphTreeLine[],\n firstPaths: Map<string, string>,\n cache: GraphObjectCache,\n expanded: ReadonlySet<string>,\n maxDepth: number,\n selector: readonly string[] | undefined,\n): void {\n const refKey = graphRefKey(ref);\n const priorPath = firstPaths.get(refKey);\n const cycle = ancestors.has(refKey);\n const object = cache.get(ref);\n const marker = cycle\n ? ` ↩ cycle to ${priorPath ?? formatGraphRef(ref)}`\n : priorPath !== undefined ? ` ↗ shared with ${priorPath}` : \"\";\n lines.push({\n key: path,\n depth,\n text: `${path} → ${formatGraphRef(ref)}${object === undefined ? \" [not loaded]\" : marker}`,\n ref,\n ...(selector === undefined ? {} : { selector: selector.length === 0 ? \"/\" : `/${selector.join(\"/\")}` }),\n expandable: !cycle && priorPath === undefined && depth < maxDepth,\n expanded: expanded.has(refKey),\n loaded: object !== undefined,\n targetKey: cycle || priorPath !== undefined ? priorPath : undefined,\n summary: object?.value !== null && typeof object?.value === \"object\" && !Array.isArray(object.value)\n ? typeof object.value.title === \"string\" ? object.value.title\n : typeof object.value.name === \"string\" ? object.value.name : undefined\n : undefined,\n });\n if (object === undefined || cycle || priorPath !== undefined || depth >= maxDepth) return;\n firstPaths.set(refKey, path);\n if (!expanded.has(refKey)) return;\n const nextAncestors = new Set(ancestors);\n nextAncestors.add(refKey);\n appendValue(object.value, path, depth + 1, nextAncestors, lines, firstPaths, cache, expanded, maxDepth, selector);\n}\n\nfunction appendValue(\n value: JsonValue,\n path: string,\n depth: number,\n ancestors: ReadonlySet<string>,\n lines: GraphTreeLine[],\n firstPaths: Map<string, string>,\n cache: GraphObjectCache,\n expanded: ReadonlySet<string>,\n maxDepth: number,\n selector: readonly string[] | undefined,\n): void {\n if (isGraphRef(value)) {\n appendRef(value, path, depth, ancestors, lines, firstPaths, cache, expanded, maxDepth,\n selector === undefined ? undefined : [...selector, \"@\"]);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) lines.push({ key: path, depth, text: `${path} = []`, expandable: false });\n value.forEach((item, index) =>\n appendValue(item, `${path}[${index}]`, depth, ancestors, lines, firstPaths, cache, expanded, maxDepth,\n selector === undefined ? undefined : [...selector, String(index)]));\n return;\n }\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value);\n if (entries.length === 0) lines.push({ key: path, depth, text: `${path} = {}`, expandable: false });\n for (const [name, child] of entries) {\n if (child !== undefined) {\n appendValue(child, propertyPath(path, name), depth, ancestors, lines, firstPaths, cache, expanded, maxDepth,\n selector === undefined || name === \"*\" || name === \"**\" || name === \"@\"\n ? undefined : [...selector, name.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")]);\n }\n }\n return;\n }\n lines.push({ key: path, depth, text: `${path} = ${JSON.stringify(value)}`, expandable: false });\n}\n\nfunction visitValue(value: JsonValue, visitor: (ref: GraphRef) => void): void {\n if (isGraphRef(value)) {\n visitor(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) visitValue(item, visitor);\n return;\n }\n if (value !== null && typeof value === \"object\") {\n for (const child of Object.values(value)) {\n if (child !== undefined) visitValue(child, visitor);\n }\n }\n}\n\nfunction propertyPath(parent: string, name: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(name)\n ? `${parent}.${name}`\n : `${parent}[${JSON.stringify(name)}]`;\n}\n\nexport async function withTimeout<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n timeoutMs: number,\n label: string,\n signal?: AbortSignal,\n): Promise<T> {\n signal?.throwIfAborted();\n const controller = new AbortController();\n let timer: NodeJS.Timeout | undefined;\n let onAbort!: () => void;\n const timeout = new Promise<never>((_resolve, reject) => {\n onAbort = () => {\n controller.abort(signal?.reason);\n reject(controller.signal.reason);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n timer = setTimeout(() => {\n const error = new Error(`${label} timed out after ${timeoutMs}ms`);\n controller.abort(error);\n reject(error);\n }, timeoutMs);\n });\n try {\n return await Promise.race([operation(controller.signal), timeout]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction asRecord(value: unknown, location: string): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${location} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction assertJsonValue(value: unknown, location: string): asserts value is JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n if (typeof value === \"number\" && Number.isFinite(value)) return;\n if (Array.isArray(value)) {\n value.forEach((item, index) => assertJsonValue(item, `${location}[${index}]`));\n return;\n }\n if (typeof value === \"object\") {\n for (const [key, child] of Object.entries(value)) {\n assertJsonValue(child, `${location}.${key}`);\n }\n return;\n }\n throw new Error(`${location} must be a JSON value`);\n}\n\nfunction jsonEqual(a: JsonValue, b: JsonValue): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n","import type { JsonValue } from \"@hediet/linkrpc\";\nimport { isGraphRef, type GraphPresentation } from \"@hediet/linkrpc-infra/graph\";\nimport { observableValue } from \"@vscode/observables\";\nimport {\n GraphLoader,\n createGraphTree,\n formatGraphRef,\n graphRefKey,\n graphRefsInValue,\n type GraphRef,\n type GraphTreeLine,\n} from \"./inspectGraphModel\";\nimport type { GraphTimings } from \"./inspectGraphTiming\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\n\nexport interface GraphViewOptions {\n readonly depth?: number;\n}\n\nexport class GraphExplorerModel {\n private readonly _expanded = observableValue<ReadonlySet<string>>(this, new Set());\n private readonly _expandedPaths = observableValue<ReadonlySet<string>>(this, new Set([\"$\"]));\n private readonly _selectedKey = observableValue(this, \"$\");\n private _cachedTree: {\n readonly size: number;\n readonly expanded: ReadonlySet<string>;\n readonly lines: readonly GraphTreeLine[];\n } | undefined;\n\n public constructor(\n public readonly root: GraphRef,\n private readonly _loader: GraphLoader,\n private readonly _maxDepth = Number.POSITIVE_INFINITY,\n state?: {\n readonly selectedKey?: string;\n readonly expanded?: ReadonlySet<string>;\n readonly expandedPaths?: ReadonlySet<string>;\n },\n private readonly _timings?: GraphTimings,\n private readonly _presentation?: GraphPresentation,\n ) {\n const expanded = new Set(state?.expanded);\n if (state?.expandedPaths === undefined || state.expandedPaths.has(\"$\")) expanded.add(graphRefKey(root));\n else expanded.delete(graphRefKey(root));\n this._expanded.set(expanded, undefined);\n this._expandedPaths.set(new Set(state?.expandedPaths ?? [\"$\"]), undefined);\n this._selectedKey.set(state?.selectedKey ?? \"$\", undefined);\n }\n\n public get lines(): readonly GraphTreeLine[] {\n const size = this._loader.cache.size;\n const expanded = this._expanded.get();\n if (this._cachedTree?.size !== size || this._cachedTree.expanded !== expanded) {\n const build = () => createGraphTree(this.root, this._loader.cache, expanded, this._maxDepth, this._presentation);\n this._cachedTree = { size, expanded, lines: this._timings?.measureSync(\"tree\", build) ?? build() };\n }\n return this._cachedTree.lines;\n }\n\n public get selectedIndex(): number {\n const exact = this.lines.findIndex((line) => line.key === this._selectedKey.get());\n return exact === -1 ? 0 : exact;\n }\n\n public get selectedKey(): string {\n return this.lines[this.selectedIndex]?.key ?? \"$\";\n }\n\n public get expandedKeys(): ReadonlySet<string> {\n return this._expanded.get();\n }\n\n public get expandedPaths(): ReadonlySet<string> {\n return this._expandedPaths.get();\n }\n\n public get cachedObjects(): number {\n return this._loader.cache.size;\n }\n\n public async prefetchExpanded(root: GraphRef): Promise<void> {\n const paths = this.lines.flatMap(line =>\n line.expandable && line.expanded && line.selector !== undefined ? [line.selector] : []);\n if (paths.length > 0) await this._loader.load([{ ref: root, paths }]);\n }\n\n public async restoreExpanded(signal?: AbortSignal, source?: GraphExplorerModel): Promise<void> {\n let paths: ReadonlySet<string>;\n do {\n paths = source?.expandedPaths ?? this.expandedPaths;\n if (source !== undefined) {\n this._expanded.set(new Set(source.expandedKeys), undefined);\n this._expandedPaths.set(paths, undefined);\n }\n const pending = new Set(paths);\n while (pending.size > 0) {\n signal?.throwIfAborted();\n const available = this.lines.filter(line => pending.has(line.key) && line.ref !== undefined && line.expandable);\n if (available.length === 0) break;\n const needs = available.flatMap(line => line.ref !== undefined && !this._loader.cache.has(line.ref)\n ? [{ ref: line.ref, paths: [\"/\"] }] : []);\n if (needs.length > 0) await this._loader.load(needs);\n signal?.throwIfAborted();\n const expanded = new Set(this._expanded.get());\n for (const line of available) {\n pending.delete(line.key);\n if (line.ref !== undefined) expanded.add(graphRefKey(line.ref));\n }\n this._expanded.set(expanded, undefined);\n if (source !== undefined && source.expandedPaths !== paths) break;\n }\n await this._loadVisibleObjects();\n signal?.throwIfAborted();\n } while (source !== undefined && source.expandedPaths !== paths);\n if (source !== undefined) this._selectedKey.set(source.selectedKey, undefined);\n }\n\n private async _loadVisibleObjects(): Promise<void> {\n // Fetch the displayed references, not their descendants. Collapsed rows\n // can then show titles without recursively opening the graph.\n const needs = this.lines.flatMap(line => line.ref !== undefined\n ? [{ ref: line.ref, paths: [\"/\"] }] : []);\n await this._loader.load(needs);\n await this.loadPresentation();\n }\n\n public async loadPresentation(): Promise<void> {\n // The evaluator stops at the first unresolved candidate. Re-evaluate after\n // each bounded object-only batch, never fetching a graph closure for labels.\n for (let round = 0; round < 32; round++) {\n const refs = this.lines.flatMap(line => line.presentationPending ?? []);\n if (refs.length === 0) return;\n const before = this._loader.cache.size;\n await this._loader.load(refs.map(ref => ({ ref, paths: [\"/\"] })));\n if (this._loader.cache.size === before) return;\n }\n }\n\n public select(index: number): void {\n const line = this.lines[index];\n if (line === undefined) throw new Error(`No graph line ${index + 1}`);\n this._selectedKey.set(line.key, undefined);\n }\n\n public move(delta: number): void {\n const lines = this.lines;\n if (lines.length === 0) return;\n const index = Math.max(0, Math.min(lines.length - 1, this.selectedIndex + delta));\n this._selectedKey.set(lines[index].key, undefined);\n }\n\n public async expandSelected(): Promise<void> {\n const line = this.lines[this.selectedIndex];\n if (line?.targetKey !== undefined) {\n this._selectedKey.set(line.targetKey, undefined);\n return;\n }\n if (line?.ref === undefined || !line.expandable) return;\n if (line.expanded && (this.lines[this.selectedIndex + 1]?.depth ?? -1) > line.depth) {\n this.move(1);\n return;\n }\n await this._expand(line);\n }\n\n private async _expand(line: GraphTreeLine): Promise<void> {\n if (line.ref === undefined) return;\n if (!this._loader.cache.has(line.ref)) {\n await this._loader.load([{ ref: line.ref, paths: [\"/\"] }]);\n }\n const key = graphRefKey(line.ref);\n const canonical = this.lines.find(item => item.ref !== undefined\n && graphRefKey(item.ref) === key && item.expandable)?.key ?? line.key;\n this._expanded.set(new Set([...this._expanded.get(), key]), undefined);\n this._expandedPaths.set(new Set([...this._expandedPaths.get(), canonical]), undefined);\n if (this._selectedKey.get() === line.key) this._selectedKey.set(canonical, undefined);\n await this._loadVisibleObjects();\n }\n\n public collapseSelected(): void {\n const lines = this.lines;\n const line = lines[this.selectedIndex];\n if (line?.ref !== undefined && line.expandable && line.expanded) {\n const refKey = graphRefKey(line.ref);\n const aliases = new Set(lines.filter(item => item.ref !== undefined\n && graphRefKey(item.ref) === refKey).map(item => item.key));\n this._expanded.set(new Set([...this._expanded.get()].filter(key => key !== refKey)), undefined);\n this._expandedPaths.set(new Set([...this._expandedPaths.get()].filter(path => !aliases.has(path))), undefined);\n return;\n }\n for (let index = this.selectedIndex - 1; index >= 0; index--) {\n if (lines[index].depth < (line?.depth ?? 0)) {\n this.select(index);\n return;\n }\n }\n }\n}\n\nexport async function loadGraphDepth(\n root: GraphRef,\n loader: GraphLoader,\n depth: number,\n): Promise<void> {\n if (!Number.isInteger(depth) || depth < 0) {\n throw new Error(\"depth must be a non-negative integer\");\n }\n let frontier = [root];\n const visited = new Set<string>();\n for (let level = 0; level <= depth && frontier.length > 0; level++) {\n const needs = frontier\n .filter((ref) => !loader.cache.has(ref))\n .map((ref) => ({ ref, paths: [\"/\"] }));\n if (needs.length > 0) await loader.load(needs);\n if (level === depth) break;\n const next = new Map<string, GraphRef>();\n for (const ref of frontier) {\n const key = graphRefKey(ref);\n if (visited.has(key)) continue;\n visited.add(key);\n const object = loader.cache.get(ref);\n if (object === undefined) {\n throw new Error(`Graph object ${formatGraphRef(ref)} is missing or expired`);\n }\n for (const child of graphRefsInValue(object.value)) {\n if (!visited.has(graphRefKey(child))) next.set(graphRefKey(child), child);\n }\n }\n frontier = [...next.values()];\n }\n}\n\nexport function renderGraphTree(\n model: GraphExplorerModel,\n options: { readonly selected?: boolean } = {},\n): string {\n const selectedIndex = model.selectedIndex;\n return model.lines.map((line, index) => {\n const cursor = options.selected === true\n ? (index === selectedIndex ? \"> \" : \" \")\n : \"\";\n const presentation = [line.summary, line.description].filter(value => value !== undefined).join(\" — \");\n return `${cursor}${\" \".repeat(line.depth)}${line.text}${presentation ? ` ${safeTerminalText(presentation)}` : \"\"}`;\n }).join(\"\\n\");\n}\n\nexport function renderGraphJson(root: GraphRef, loader: GraphLoader): string {\n return JSON.stringify(materializeGraphValue(root, loader, new Set()), null, 2);\n}\n\nfunction materializeGraphValue(\n ref: GraphRef,\n loader: GraphLoader,\n ancestors: ReadonlySet<string>,\n): JsonValue {\n const key = graphRefKey(ref);\n if (ancestors.has(key)) return { $ref: formatGraphRef(ref), $cycle: true };\n const object = loader.cache.get(ref);\n if (object === undefined) return { $ref: formatGraphRef(ref), $missing: true };\n const nextAncestors = new Set(ancestors);\n nextAncestors.add(key);\n return replaceRefs(object.value, loader, nextAncestors);\n}\n\nfunction replaceRefs(\n value: JsonValue,\n loader: GraphLoader,\n ancestors: ReadonlySet<string>,\n): JsonValue {\n if (isGraphRef(value)) return materializeGraphValue(value, loader, ancestors);\n if (Array.isArray(value)) return value.map((item) => replaceRefs(item, loader, ancestors));\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).flatMap(([key, child]) =>\n child === undefined ? [] : [[key, replaceRefs(child, loader, ancestors)]]),\n );\n }\n return value;\n}\n","import { stdout } from \"node:process\";\nimport {\n createSchemaToZod,\n interfaceTemplateMemberName,\n INTERFACE_TEMPLATES_EXTENSION,\n type JsonValue,\n type LinkRpcInterfaceSchema,\n type InterfaceTemplateArgument,\n type InterfaceTemplatesMetadata,\n} from \"@hediet/linkrpc\";\nimport {\n IMMUTABLE_GRAPH_INTERFACE_ID,\n ROOT_WATCH_INTERFACE_ID,\n validateGraphInterfaceSchema,\n graphPresentationSchema,\n} from \"@hediet/linkrpc-infra/graph\";\nimport type { DiscoveredListing } from \"@hediet/linkrpc/hub/common\";\nimport type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { GraphTerminal } from \"./inspectGraphTerminal\";\nimport { GraphTimings, type GraphTiming } from \"./inspectGraphTiming\";\nimport {\n GraphLoader,\n GraphObjectCache,\n graphRefKey,\n parseGraphRef,\n withTimeout,\n type GraphBatchFetch,\n type GraphRef,\n} from \"./inspectGraphModel\";\nimport {\n GraphExplorerModel,\n loadGraphDepth,\n renderGraphJson,\n renderGraphTree,\n} from \"./inspectGraphView\";\n\nexport interface GraphTarget {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly graphInterfaceId: string;\n readonly root: string;\n readonly watchMethod: string;\n readonly batchMethod: string;\n readonly paramsArgument: InterfaceTemplateArgument;\n readonly refArgument: InterfaceTemplateArgument;\n readonly valueArgument: InterfaceTemplateArgument;\n readonly presentationMethod?: string;\n}\n\nexport interface InspectGraphOptions {\n readonly targets: readonly GraphTarget[];\n readonly onModel?: (model: GraphExplorerModel, version: number) => void | Promise<void>;\n readonly onUpdating?: () => void | Promise<void>;\n readonly logTiming?: boolean;\n readonly onTiming?: (timing: GraphTiming) => void;\n readonly serviceId?: string;\n readonly interfaceId?: string;\n readonly root?: string;\n readonly params?: unknown;\n readonly depth?: number;\n readonly path?: string;\n readonly watch?: boolean;\n readonly json?: boolean;\n readonly maxObjects?: number;\n readonly maxBytes?: number;\n readonly maxRounds?: number;\n readonly timeoutMs?: number;\n readonly interactive?: boolean;\n readonly stop?: Promise<void>;\n readonly emit?: (text: string) => void;\n readonly repaint?: (text: string) => void;\n}\n\nexport interface GraphDiscovery {\n readonly targets: readonly GraphTarget[];\n readonly warnings: readonly string[];\n}\n\ninterface GraphRootDescriptor {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly root: string;\n readonly watchMethod: string;\n readonly paramsArgument: InterfaceTemplateArgument;\n readonly refArgument: InterfaceTemplateArgument;\n}\n\ninterface GraphStoreDescriptor {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly batchMethod: string;\n readonly refArgument: InterfaceTemplateArgument;\n readonly valueArgument: InterfaceTemplateArgument;\n}\n\nexport function graphDescriptorsFromSchema(\n listing: DiscoveredListing,\n schema: LinkRpcInterfaceSchema,\n): {\n readonly roots: readonly GraphRootDescriptor[];\n readonly stores: readonly GraphStoreDescriptor[];\n} {\n const metadata = schema[INTERFACE_TEMPLATES_EXTENSION] as InterfaceTemplatesMetadata | undefined;\n if (metadata === undefined) return { roots: [], stores: [] };\n validateGraphInterfaceSchema(schema);\n const graphInstances = metadata.instances.filter((instance) =>\n metadata.templates[instance.template]?.id === IMMUTABLE_GRAPH_INTERFACE_ID);\n const rootInstances = metadata.instances.filter((instance) =>\n metadata.templates[instance.template]?.id === ROOT_WATCH_INTERFACE_ID);\n return {\n roots: rootInstances.map((root) => ({\n serviceId: listing.serviceId,\n interfaceId: listing.interfaceId,\n hash: listing.hash,\n root: root.name,\n watchMethod: wireMethod(listing.serviceId, listing.interfaceId, interfaceTemplateMemberName(root, 'watch')),\n paramsArgument: requiredArgument(root.arguments, \"params\", root.name),\n refArgument: requiredArgument(root.arguments, \"ref\", root.name),\n })),\n stores: graphInstances.map((graph) => ({\n serviceId: listing.serviceId,\n interfaceId: listing.interfaceId,\n hash: listing.hash,\n batchMethod: wireMethod(listing.serviceId, listing.interfaceId, interfaceTemplateMemberName(graph, 'batchObjGet')),\n refArgument: requiredArgument(graph.arguments, \"ref\", graph.name),\n valueArgument: requiredArgument(graph.arguments, \"value\", graph.name),\n })),\n };\n}\n\nexport async function inspectGraphCommand(\n channel: CliChannel,\n options: InspectGraphOptions,\n): Promise<string> {\n const discovery: GraphDiscovery = { targets: options.targets, warnings: [] };\n const target = selectGraphTarget(discovery.targets, options);\n if (target === undefined) {\n return renderGraphTargetList(discovery);\n }\n const params = validateSchemaValue(options.params === undefined ? {} : options.params, target.paramsArgument, \"root params\");\n const refValidator = schemaValidator(target.refArgument);\n const valueValidator = schemaValidator(target.valueArgument);\n const timings = options.onTiming !== undefined || options.logTiming\n ? new GraphTimings(options.onTiming ?? (timing => {\n process.stderr.write(`linkrpc: timing ${JSON.stringify(timing)}\\n`);\n }))\n : undefined;\n const fetch: GraphBatchFetch = async (request, signal) => {\n const call = channel.sendRequestWithStream(target.batchMethod, {\n needs: request.needs.map(({ ref, paths }) => ({ ref, paths: [...paths] })),\n have: request.have.map(item => ({ ...item })),\n limits: { ...request.limits },\n });\n const cancel = (): void => {\n call.cancel(\"graph batch cancelled\");\n call.dispose?.();\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n const result = await call.result;\n validateBatchPayload(result, refValidator, valueValidator);\n return result;\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n call.dispose?.();\n }\n };\n const cancellation = new AbortController();\n const loader = new GraphLoader(fetch, new GraphObjectCache(), { ...options, timings, signal: cancellation.signal });\n const emit = options.emit ?? ((text) => stdout.write(`${text}\\n`));\n const interactive = options.interactive === true;\n const navigable = interactive || options.onModel !== undefined;\n let firstOutput = \"\";\n let currentModel: GraphExplorerModel | undefined;\n const terminal = interactive\n ? new GraphTerminal(`${target.serviceId || \"local\"} / ${target.interfaceId} / ${target.root}`, JSON.stringify(params), options.repaint, timings)\n : undefined;\n const stopRequested = terminal !== undefined\n ? options.stop === undefined ? terminal.result : Promise.race([terminal.result, options.stop])\n : options.stop;\n const stop = stopRequested?.then(() => { cancellation.abort(); });\n try {\n await watchRoots(channel, target, params as JsonValue, stop, options.timeoutMs ?? 5_000, async ({ version, ref }, call) => {\n const refresh = async () => {\n await terminal?.beginUpdate();\n await options.onUpdating?.();\n cancellation.signal.throwIfAborted();\n validateWith(refValidator, ref, \"root watch ref\");\n if (options.path !== undefined) {\n await loader.load([{ ref, paths: [normalizeGraphPath(options.path)] }]);\n } else {\n if (navigable && currentModel !== undefined) await currentModel.prefetchExpanded(ref);\n await loadGraphDepth(ref, loader, options.depth ?? (navigable ? 0 : 2));\n }\n const presentation = options.json || target.presentationMethod === undefined ? undefined\n : await withTimeout(async signal => {\n const call = channel.sendRequestWithStream(target.presentationMethod!, {});\n const cancel = () => { call.cancel(\"graph presentation cancelled\"); call.dispose?.(); };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try { return graphPresentationSchema.parse(await call.result); }\n finally { signal.removeEventListener(\"abort\", cancel); call.dispose?.(); }\n }, options.timeoutMs ?? 5_000, \"graph presentation\", cancellation.signal);\n const model = new GraphExplorerModel(ref, loader, navigable ? undefined : options.depth, navigable\n ? currentModel === undefined ? undefined : {\n selectedKey: currentModel.selectedKey,\n expanded: currentModel.expandedKeys,\n expandedPaths: currentModel.expandedPaths,\n }\n : { expanded: new Set(loader.cache.have().map((item) => graphRefKey(item.ref))) }, timings, presentation);\n await model.loadPresentation();\n cancellation.signal.throwIfAborted();\n if (options.onModel !== undefined) {\n await options.onModel(model, version);\n } else if (terminal !== undefined) {\n const restore = () => terminal.finishUpdate(model, version, cancellation.signal);\n await (timings?.measureAsync(\"restore\", restore, { version }) ?? restore());\n } else {\n const render = () => options.json === true\n ? renderGraphJson(ref, loader)\n : renderGraphTree(model);\n const rendered = timings?.measureSync(\"output\", render, { version }) ?? render();\n if (options.watch === true) emit(options.json === true ? JSON.stringify(JSON.parse(rendered)) : rendered);\n else firstOutput = rendered;\n }\n await call.send({ accept: version });\n currentModel = model;\n return interactive || options.watch === true;\n };\n return timings?.measureAsync(\"refresh\", refresh, { version }) ?? refresh();\n });\n } catch (error) {\n if (!cancellation.signal.aborted) throw error;\n } finally {\n cancellation.abort();\n terminal?.dispose();\n }\n for (const warning of discovery.warnings) {\n process.stderr.write(`linkrpc: ${warning}\\n`);\n }\n return firstOutput;\n}\n\nexport function selectGraphTarget(\n targets: readonly GraphTarget[],\n options: Pick<InspectGraphOptions, \"serviceId\" | \"interfaceId\" | \"root\">,\n): GraphTarget | undefined {\n if (\n options.serviceId === undefined\n && options.interfaceId === undefined\n && options.root === undefined\n ) {\n return undefined;\n }\n const matches = targets.filter((target) =>\n (options.serviceId === undefined || target.serviceId === options.serviceId)\n && (options.interfaceId === undefined || target.interfaceId === options.interfaceId)\n && (options.root === undefined || target.root === options.root));\n if (matches.length === 0) {\n if (options.serviceId !== undefined || options.interfaceId !== undefined || options.root !== undefined) {\n throw new Error(\"No graph root matches the requested service, interface, and root selectors\");\n }\n return undefined;\n }\n if (matches.length > 1) {\n throw new Error(\n `Graph selection is ambiguous (${matches.length} roots); specify --service, --interface, and --root`,\n );\n }\n return matches[0];\n}\n\nexport function renderGraphTargetList(discovery: GraphDiscovery): string {\n if (discovery.targets.length === 0) {\n const suffix = discovery.warnings.length === 0\n ? \"\"\n : `\\n${discovery.warnings.map((warning) => `warning: ${warning}`).join(\"\\n\")}`;\n return `No graph-capable reflected interface templates found.${suffix}`;\n }\n return [\n \"Available graph roots:\",\n ...discovery.targets.map((target) =>\n ` ${target.serviceId || \"<root>\"}::${target.interfaceId} root=${target.root} `\n + `objects=${target.graphInterfaceId}`),\n ...discovery.warnings.map((warning) => `warning: ${warning}`),\n ].join(\"\\n\");\n}\n\ninterface RootOffer {\n readonly version: number;\n readonly ref: GraphRef;\n}\n\nexport async function watchRoots(\n channel: Pick<CliChannel, \"sendRequestWithStream\">,\n target: GraphTarget,\n params: JsonValue,\n stop: Promise<void> | undefined,\n timeoutMs: number,\n onOffer: (\n offer: RootOffer,\n call: ReturnType<CliChannel[\"sendRequestWithStream\"]>,\n ) => Promise<boolean>,\n): Promise<void> {\n let queue = Promise.resolve(true);\n let received = false;\n let resolveFirst!: () => void;\n let rejectFirst!: (error: unknown) => void;\n const first = new Promise<void>((resolve, reject) => {\n resolveFirst = resolve;\n rejectFirst = reject;\n });\n let fail!: (error: unknown) => void;\n const failed = new Promise<never>((_resolve, reject) => { fail = reject; });\n const timer = setTimeout(() => {\n if (!received) fail(new Error(`Graph root watch produced no root within ${timeoutMs}ms`));\n }, timeoutMs);\n let call!: ReturnType<CliChannel[\"sendRequestWithStream\"]>;\n call = channel.sendRequestWithStream(target.watchMethod, params, {\n onStreamMessage: (payload) => {\n queue = queue.then(async (keepWatching) => {\n if (!keepWatching) return false;\n const offer = parseRootOffer(payload);\n received = true;\n const keep = await onOffer(offer, call);\n resolveFirst();\n return keep;\n }).catch((error: unknown) => {\n rejectFirst(error);\n fail(error);\n return false;\n });\n },\n });\n const stopped = stop?.then(() => \"stop\" as const);\n try {\n const outcome = await Promise.race([\n first.then(() => \"first\" as const),\n call.result.then(() => \"result\" as const),\n failed,\n ...(stopped === undefined ? [] : [stopped]),\n ]);\n if (outcome === \"result\" && !received) {\n throw new Error(\"Graph root watch ended before offering a root\");\n }\n if (outcome === \"first\" && await queue) {\n await Promise.race([call.result, failed, ...(stopped === undefined ? [] : [stopped])]);\n }\n await queue;\n } finally {\n clearTimeout(timer);\n call.cancel(\"graph explorer finished\");\n call.dispose?.();\n }\n}\n\nfunction validateBatchPayload(\n value: JsonValue,\n refValidator: ReturnType<typeof schemaValidator>,\n valueValidator: ReturnType<typeof schemaValidator>,\n): void {\n if (value === null || Array.isArray(value) || typeof value !== \"object\") {\n throw new Error(\"graph batch result must be an object\");\n }\n if (!Array.isArray(value.objects)) return;\n value.objects.forEach((object, index) => {\n if (object === null || Array.isArray(object) || typeof object !== \"object\") return;\n validateWith(refValidator, object.ref, `graph batch objects[${index}].ref`);\n validateWith(valueValidator, object.value, `graph batch objects[${index}].value`);\n });\n}\n\nfunction schemaValidator(argument: InterfaceTemplateArgument) {\n return createSchemaToZod(argument.components?.schemas ?? {}).toZod(argument.schema);\n}\n\nfunction validateSchemaValue(\n value: unknown,\n argument: InterfaceTemplateArgument,\n location: string,\n): unknown {\n const validator = schemaValidator(argument);\n validateWith(validator, value, location);\n return value;\n}\n\nfunction validateWith(\n validator: ReturnType<typeof schemaValidator>,\n value: unknown,\n location: string,\n): void {\n const result = validator.safeParse(value);\n if (!result.success) {\n throw new Error(`${location} does not match its reflected schema: ${result.error.message}`);\n }\n}\n\nfunction parseRootOffer(value: JsonValue): RootOffer {\n if (value === null || Array.isArray(value) || typeof value !== \"object\") {\n throw new Error(\"root watch event must be an object\");\n }\n if (typeof value.version !== \"number\" || !Number.isSafeInteger(value.version)) {\n throw new Error(\"root watch event.version must be a safe integer\");\n }\n return { version: value.version, ref: parseGraphRef(value.ref, \"root watch event.ref\") };\n}\n\nfunction requiredArgument(\n args: Readonly<Record<string, InterfaceTemplateArgument>>,\n name: string,\n instance: string,\n): InterfaceTemplateArgument {\n const argument = args[name];\n if (argument === undefined) {\n throw new Error(`Graph template instance \"${instance}\" is missing schema argument \"${name}\"`);\n }\n return argument;\n}\n\nfunction wireMethod(serviceId: string, interfaceId: string, member: string): string {\n return serviceId.length === 0\n ? `${interfaceId}::${member}`\n : `${serviceId}::${interfaceId}::${member}`;\n}\n\nfunction normalizeGraphPath(path: string): string {\n if (path === \"/\") return path;\n if (!path.startsWith(\"/\")) throw new Error(\"--path must be a JSON pointer beginning with '/'\");\n return path;\n}\n","import type { ViewCommand, ViewKeybinding, ViewKeyEvent, ViewSession } from \"./types\";\n\nexport interface ViewHostActions {\n readonly quit: () => void;\n readonly nextTab?: () => void;\n readonly toggleScope?: () => void;\n readonly back?: () => void;\n}\n\nexport function matchesKey(binding: ViewKeybinding, event: ViewKeyEvent): boolean {\n return (binding.key.length === 1 && !binding.ctrl && !binding.meta ? event.input === binding.key\n : event.name === binding.key || event.input === binding.key)\n && !!binding.ctrl === !!event.ctrl && !!binding.meta === !!event.meta\n // Terminals often infer shift for uppercase letters. The literal already encodes it.\n && (binding.shift === undefined && binding.key.length === 1 || !!binding.shift === !!event.shift);\n}\n\n/** Host bindings take precedence; capture only releases ordinary keys, never Ctrl+C. */\nexport function hostCommands(actions: ViewHostActions, capturesInput = false): readonly ViewCommand[] {\n return [\n { id: \"host.quit\", title: \"Quit\", keybindings: [{ key: \"c\", ctrl: true }, ...capturesInput ? [] : [{ key: \"q\" }]], execute: actions.quit },\n ...capturesInput ? [] : [\n ...actions.nextTab ? [{ id: \"host.nextTab\", title: \"Next view\", keybindings: [{ key: \"tab\" }], execute: actions.nextTab }] : [],\n ...actions.toggleScope ? [{ id: \"host.scope\", title: \"Switch scope\", keybindings: [{ key: \"v\" }], execute: actions.toggleScope }] : [],\n ...actions.back ? [{ id: \"host.back\", title: \"Services\", keybindings: [{ key: \"escape\" }], execute: actions.back }] : [],\n ],\n ];\n}\n\nexport function availableViewCommands(\n commands: readonly ViewCommand[], reserved: readonly ViewCommand[] = [],\n): readonly ViewCommand[] {\n const claimed = reserved.filter(command => command.enabled !== false).flatMap(command => command.keybindings);\n const result: ViewCommand[] = [];\n for (const command of commands) {\n if (command.enabled === false) continue;\n const keybindings = command.keybindings.filter(binding => !claimed.some(key =>\n key.key === binding.key && !!key.ctrl === !!binding.ctrl && !!key.meta === !!binding.meta\n && (key.key.length === 1 && (key.shift === undefined || binding.shift === undefined)\n || !!key.shift === !!binding.shift)));\n claimed.push(...keybindings);\n if (keybindings.length > 0) result.push({ ...command, keybindings });\n }\n return result;\n}\n\nfunction dispatch(commands: readonly ViewCommand[], event: ViewKeyEvent): boolean {\n const command = commands.find(command => command.enabled !== false\n && command.keybindings.some(binding => matchesKey(binding, event)));\n if (!command) return false;\n command.execute();\n return true;\n}\n\nexport function dispatchViewKey(session: ViewSession, event: ViewKeyEvent): boolean {\n if (dispatch(session.commands.get(), event)) return true;\n return session.capturesInput === true && session.handleTextInput?.(event) === true;\n}\n\n/** A true result means consumed: callers must not dispatch the event a second time. */\nexport function dispatchHostKey(session: ViewSession | undefined, event: ViewKeyEvent, actions: ViewHostActions): boolean {\n if (dispatch(hostCommands(actions, session?.capturesInput), event)) return true;\n return session ? dispatchViewKey(session, event) : false;\n}\n\nexport function formatKeybinding(binding: ViewKeybinding): string {\n const labels: Record<string, string> = {\n up: \"↑\", down: \"↓\", left: \"←\", right: \"→\", return: \"Enter\", escape: \"Esc\",\n pageup: \"PgUp\", pagedown: \"PgDn\", home: \"Home\", end: \"End\", tab: \"Tab\",\n backspace: \"Backspace\", delete: \"Delete\", \" \": \"Space\",\n };\n return `${binding.ctrl ? \"Ctrl+\" : \"\"}${binding.meta ? \"Alt+\" : \"\"}${binding.shift ? \"Shift+\" : \"\"}${labels[binding.key] ?? binding.key}`;\n}\n\nexport function formatCommandLegend(commands: readonly ViewCommand[]): string {\n return availableViewCommands(commands).map(command =>\n `${command.keybindings.map(formatKeybinding).join(\"/\")}: ${command.title}`).join(\" · \");\n}\n","import React from \"react\";\nimport { Box, Text } from \"ink\";\nimport { autorun } from \"@vscode/observables\";\nimport type { ViewSession } from \"./types\";\nimport { availableViewCommands, formatCommandLegend, hostCommands, type ViewHostActions } from \"./commands\";\nimport { safeTerminalText } from \"../ui/terminalText\";\n\nconst noop = () => {};\n\n/** The legend and keyboard dispatcher use the same availability and reservation policy. */\nexport class CommandLegend extends React.Component<{\n readonly session: ViewSession;\n readonly tabbed?: boolean;\n readonly active?: boolean;\n readonly columns?: number;\n readonly maxRows?: number;\n}, { revision: number }> {\n state = { revision: 0 };\n private subscription: { dispose(): void } | undefined;\n componentDidMount(): void { this.subscribe(); }\n componentDidUpdate(previous: Readonly<{ session: ViewSession; tabbed?: boolean; active?: boolean }>): void {\n if (previous.session !== this.props.session) this.subscribe();\n }\n private subscribe(): void {\n this.subscription?.dispose();\n this.subscription = autorun(reader => {\n this.props.session.commands.read(reader);\n this.setState(previous => ({ revision: previous.revision + 1 }));\n });\n }\n componentWillUnmount(): void { this.subscription?.dispose(); }\n render(): React.ReactNode {\n const { session, tabbed, active = true, columns = 80, maxRows } = this.props;\n const lines = viewLegendLines(session, { tabbed, active, columns, maxRows });\n return <Box flexDirection=\"column\" flexShrink={0} height={lines.length}>\n {lines.map((line, index) => <Text key={index} dimColor wrap=\"truncate-end\">{line}</Text>)}\n </Box>;\n }\n}\n\nexport function viewLegendLines(session: ViewSession, options: {\n readonly tabbed?: boolean; readonly active?: boolean; readonly columns: number; readonly maxRows?: number;\n}): readonly string[] {\n const { tabbed, active = true, columns, maxRows = Infinity } = options;\n const actions: ViewHostActions = tabbed\n ? { quit: noop, nextTab: noop, toggleScope: noop, back: noop } : { quit: noop };\n const host = hostCommands(actions, active && session.capturesInput);\n const commands = [...host, ...active ? availableViewCommands(session.commands.get(), host) : []];\n const words = safeTerminalText(formatCommandLegend(commands)).split(\" \");\n const lines: string[] = [];\n let line = \"\";\n for (const word of words) {\n if (line && [...`${line} ${word}`].length > columns) { lines.push(line); line = \"\"; }\n line += (line ? \" \" : \"\") + word;\n }\n if (line) lines.push(line);\n const visible = lines.slice(0, Math.max(1, maxRows));\n if (lines.length > visible.length && visible.length > 0) {\n visible[visible.length - 1] = [...visible[visible.length - 1]!].slice(0, Math.max(0, columns - 2)).join(\"\").trimEnd() + \" …\";\n }\n return visible;\n}\n","import React from \"react\";\nimport { Box, measureElement, type DOMElement } from \"ink\";\nimport { autorun, observableValue } from \"@vscode/observables\";\nimport type { ViewSession } from \"./types\";\nimport { CommandLegend, viewLegendLines } from \"./CommandLegend\";\n\n/** Gives content exactly the rows left after the command-driven legend. */\nexport class ViewFrame extends React.Component<{\n readonly session: ViewSession;\n readonly rows: number;\n readonly columns?: number;\n readonly maxColumns?: number;\n readonly tabbed?: boolean;\n readonly active?: boolean;\n}, { revision: number }> {\n state = { revision: 0 };\n private subscription: { dispose(): void } | undefined;\n private readonly measuredColumns = observableValue(this, 1);\n private readonly root = React.createRef<DOMElement>();\n private mounted = false;\n private appliedViewport: { readonly session: ViewSession; readonly rows: number; readonly columns: number } | undefined;\n componentDidMount(): void { this.mounted = true; this.subscribe(); this.layout(); }\n componentDidUpdate(previous: Readonly<ViewFrame[\"props\"]>): void {\n if (previous.session !== this.props.session) this.subscribe();\n this.layout();\n }\n componentWillUnmount(): void { this.mounted = false; this.subscription?.dispose(); }\n private subscribe(): void {\n this.subscription?.dispose();\n this.subscription = autorun(reader => {\n this.props.session.commands.read(reader);\n this.measuredColumns.read(reader);\n this.setState(previous => ({ revision: previous.revision + 1 }));\n });\n }\n private get columns(): number {\n return Math.min(this.props.columns ?? this.measuredColumns.get(), this.props.maxColumns ?? Infinity);\n }\n private get legendRows(): number {\n return viewLegendLines(this.props.session, { ...this.props, columns: this.columns,\n maxRows: Math.min(this.props.session.maxLegendRows ?? Infinity,\n this.props.tabbed ? Math.min(2, Math.max(1, this.props.rows - 7)) : Math.max(1, this.props.rows - 7)) }).length;\n }\n private layout(): void {\n const rows = Math.max(1, this.props.rows - this.legendRows);\n const columns = this.columns;\n const previous = this.appliedViewport;\n if (previous?.session !== this.props.session || previous.rows !== rows || previous.columns !== columns) {\n this.props.session.setViewport?.(rows, columns);\n this.appliedViewport = { session: this.props.session, rows, columns };\n this.setState(value => ({ revision: value.revision + 1 }));\n }\n // Yoga dimensions become final after the commit, not during render/mount.\n queueMicrotask(() => {\n if (!this.mounted || this.props.columns !== undefined || !this.root.current) return;\n const width = Math.max(1, Math.floor(measureElement(this.root.current).width));\n if (width !== this.measuredColumns.get()) this.measuredColumns.set(width, undefined);\n });\n }\n render(): React.ReactNode {\n const { session, rows, tabbed, active } = this.props;\n const columns = this.columns;\n const legendRows = this.legendRows;\n const contentRows = Math.max(1, rows - legendRows);\n const ready = this.appliedViewport?.session === session\n && this.appliedViewport.rows === contentRows && this.appliedViewport.columns === columns;\n return <Box ref={this.root} flexDirection=\"column\" width={this.props.columns ?? \"100%\"} minWidth={0}\n height={rows} flexShrink={0} overflow=\"hidden\">\n <Box flexDirection=\"column\" height={contentRows} flexShrink={0} overflow=\"hidden\">\n {/* Ink 5 uses the innermost clip, so a stale oversized child can escape its parent's clip. */}\n <Box display={ready ? \"flex\" : \"none\"} flexDirection=\"column\" height={contentRows} width={columns}>\n {session.element}\n </Box>\n </Box>\n <CommandLegend session={session} columns={columns} maxRows={legendRows} tabbed={tabbed} active={active} />\n </Box>;\n }\n}\n","import React from \"react\";\nimport { render } from \"ink\";\nimport { emitKeypressEvents, type Key } from \"node:readline\";\nimport { stdin, stdout } from \"node:process\";\nimport type { ViewSession } from \"./types\";\nimport { dispatchHostKey } from \"./commands\";\nimport { ViewFrame } from \"./ViewFrame\";\n\n/** Runs any contributed view and drains its I/O before returning connection ownership. */\nexport async function runViewTui(session: ViewSession): Promise<void> {\n let instance: ReturnType<typeof render> | undefined;\n let ownsInput = false;\n const raw = stdin.isRaw;\n const flowing = stdin.readableFlowing === true;\n const onKey = (input: string, key: Key) =>\n dispatchHostKey(session, { ...key, input }, { quit: () => instance?.unmount() });\n const element = () => <ViewFrame session={session} rows={stdout.rows || 24} columns={stdout.columns || 80} />;\n const onResize = () => {\n instance?.rerender(element());\n };\n const onStop = () => instance?.unmount();\n try {\n if (!stdin.isTTY || !stdout.isTTY) throw new Error(\"--tui requires an interactive terminal; omit --tui for a snapshot\");\n onResize();\n instance = render(element(), { stdin, stdout, exitOnCtrlC: false });\n emitKeypressEvents(stdin);\n stdin.setRawMode(true);\n ownsInput = true;\n stdin.resume();\n stdin.on(\"keypress\", onKey);\n stdout.on(\"resize\", onResize);\n process.once(\"SIGINT\", onStop);\n process.once(\"SIGTERM\", onStop);\n await instance.waitUntilExit();\n } finally {\n session.dispose();\n stdin.off(\"keypress\", onKey);\n stdout.off(\"resize\", onResize);\n process.off(\"SIGINT\", onStop);\n process.off(\"SIGTERM\", onStop);\n if (ownsInput) {\n stdin.setRawMode(raw ?? false);\n if (!flowing) stdin.pause();\n }\n instance?.unmount();\n await session.disposeAsync?.();\n }\n}\n","import React from \"react\";\nimport { Box, Text } from \"ink\";\nimport { autorun, derived, observableValue } from \"@vscode/observables\";\nimport { stdout } from \"node:process\";\nimport type { ViewCommand, ViewKeyEvent, ViewOpenContext, ViewSession } from \"../../views/types\";\nimport { runViewTui } from \"../../views/runViewTui\";\nimport { inspectGraphCommand, type GraphTarget } from \"./inspectGraph\";\nimport type { GraphExplorerModel } from \"./inspectGraphView\";\nimport { anchorGraphScrollTop, clampGraphScroll, createGraphFrame, graphChromeRows, graphFrameText, type GraphFrameRow } from \"./graphFrame\";\n\ninterface State {\n readonly cursor: number;\n readonly params: string;\n readonly editing: boolean;\n readonly active: boolean;\n readonly model?: GraphExplorerModel;\n readonly version?: number;\n readonly error?: string;\n readonly revision: number;\n readonly viewportRows?: number;\n readonly showObjectIds?: boolean;\n readonly viewportColumns?: number;\n readonly scrollTop?: number;\n readonly busy?: boolean;\n readonly refreshing?: boolean;\n}\n\n/** A tab owns one watch. Disposing invalidates callbacks before cancelling I/O. */\nexport class GraphSession implements ViewSession {\n readonly state = observableValue<State>(this, { cursor: 0, params: \"{}\", editing: false, active: false, revision: 0 });\n readonly element = <GraphPanel session={this} />;\n private generation = 0;\n private stop: (() => void) | undefined;\n private disposed = false;\n private action = Promise.resolve();\n private readonly pending = new Set<Promise<void>>();\n private started = false;\n\n constructor(\n private readonly context: ViewOpenContext,\n readonly roots: readonly GraphTarget[],\n private options: Readonly<Record<string, unknown>> = {},\n ) {}\n get capturesInput(): boolean { return this.state.get().editing; }\n setViewport(rows: number, columns = this.state.get().viewportColumns ?? stdout.columns ?? 80): void {\n const state = this.state.get();\n if (state.viewportRows !== rows || state.viewportColumns !== columns) this.update({\n viewportRows: rows, viewportColumns: columns,\n scrollTop: clampGraphScroll(state.model?.lines.length ?? this.roots.length, state.model?.selectedIndex ?? state.cursor,\n state.scrollTop ?? 0, Math.max(0, rows - graphChromeRows), false),\n });\n }\n captureState(): unknown {\n const state = this.state.get();\n return { root: this.roots[state.cursor]?.root, interfaceId: this.roots[state.cursor]?.interfaceId,\n params: state.params, started: this.started, showObjectIds: state.showObjectIds };\n }\n restoreState(value: unknown): void {\n const state = value as { root?: string; interfaceId?: string; params?: string; started?: boolean; showObjectIds?: boolean } | undefined;\n if (!state) return;\n const cursor = this.roots.findIndex(root => root.root === state.root && root.interfaceId === state.interfaceId);\n if (cursor < 0) return;\n this.update({ cursor, params: state.params ?? \"{}\", showObjectIds: state.showObjectIds });\n if (state.started) this.start(this.options);\n }\n\n readonly commands = derived(this, (reader): readonly ViewCommand[] => {\n const state = this.state.read(reader);\n const graph = state.active || state.model !== undefined;\n if (this.disposed) return [];\n const command = (id: string, title: string, keys: readonly string[], execute: () => void, enabled = true): ViewCommand => ({\n id: `graph.${id}`, title, keybindings: keys.map(key => ({ key })), enabled, execute,\n context: state.editing ? \"Editing parameters\" : graph ? \"Graph\" : \"Roots\",\n });\n if (state.editing) return [\n command(\"finishParams\", \"Finish parameters\", [\"return\", \"escape\"], () => this.update({ editing: false })),\n command(\"deleteParam\", \"Delete character\", [\"backspace\", \"delete\"],\n () => this.update({ params: this.state.get().params.slice(0, -1) }), state.params.length > 0),\n ];\n const model = state.model;\n const index = graph ? model?.selectedIndex ?? 0 : state.cursor;\n const count = graph ? model?.lines.length ?? 0 : this.roots.length;\n const move = (delta: number) => {\n if (!graph) this.selectRoot(Math.max(0, Math.min(this.roots.length - 1, this.state.get().cursor + delta)));\n else this.enqueue(model => model.move(delta));\n };\n const select = (last: boolean) => {\n if (!graph) this.selectRoot(last ? this.roots.length - 1 : 0);\n else this.enqueue(model => model.select(last ? model.lines.length - 1 : 0));\n };\n const page = Math.max(1, (state.viewportRows ?? 24) - graphChromeRows);\n const selected = model?.lines[model.selectedIndex];\n return [\n command(\"up\", \"Previous\", [\"up\", \"k\"], () => move(-1), index > 0),\n command(\"down\", \"Next\", [\"down\", \"j\"], () => move(1), index + 1 < count),\n command(\"pageUp\", \"Page up\", [\"pageup\"], () => move(-page), index > 0),\n command(\"pageDown\", \"Page down\", [\"pagedown\"], () => move(page), index + 1 < count),\n command(\"first\", \"First\", [\"home\", \"g\"], () => select(false), index > 0),\n command(\"last\", \"Last\", [\"end\", \"G\"], () => select(true), index + 1 < count),\n ...graph ? [\n command(\"collapse\", \"Collapse / parent\", [\"left\", \"h\", \"backspace\"],\n () => this.enqueue(model => model.collapseSelected()), !!selected && (selected.expanded || selected.depth > 0)),\n command(\"expand\", \"Expand / follow\", [\"right\", \"return\", \"l\", \" \"],\n () => this.enqueue(model => model.expandSelected()), !state.busy && !!selected && (selected.expandable || selected.targetKey !== undefined)),\n command(\"ids\", state.showObjectIds ? \"Hide object IDs\" : \"Show object IDs\", [\"i\"],\n () => this.update({ showObjectIds: !this.state.get().showObjectIds }), !!model),\n command(\"roots\", \"Roots\", [\"r\"], () => {\n this.started = false; this.cancel(); this.update({ active: false, model: undefined, error: undefined, scrollTop: 0, version: undefined });\n }),\n ] : [\n command(\"attach\", \"Open root\", [\"return\"], () => this.start(this.options), count > 0),\n ],\n command(\"params\", \"Edit parameters\", [\"p\"], () => {\n this.started = false; this.cancel(); this.update({ editing: true, active: false, model: undefined, version: undefined, scrollTop: 0 });\n }, this.roots.length > 0),\n ];\n });\n\n private selectRoot(cursor: number): void {\n const state = this.state.get();\n this.update({ cursor, scrollTop: clampGraphScroll(this.roots.length, cursor, state.scrollTop ?? 0,\n Math.max(0, (state.viewportRows ?? 24) - graphChromeRows)) });\n }\n\n handleTextInput(event: ViewKeyEvent): boolean {\n if (this.disposed || !this.capturesInput) return false;\n if (event.ctrl || event.meta || !event.input || /[\\x00-\\x1f\\x7f]/.test(event.input)) return false;\n this.update({ params: this.state.get().params + event.input });\n return true;\n }\n\n private enqueue(execute: (model: GraphExplorerModel) => void | Promise<void>): void {\n const state = this.state.get();\n const model = state.model;\n if (!model) return;\n const generation = this.generation;\n this.action = this.action.then(async () => {\n if (this.disposed || generation !== this.generation) return;\n this.update({ busy: true, error: undefined });\n await execute(model);\n if (!this.disposed && generation === this.generation) this.update({\n busy: false, scrollTop: clampGraphScroll(model.lines.length, model.selectedIndex, this.state.get().scrollTop ?? 0,\n Math.max(0, (this.state.get().viewportRows ?? 24) - graphChromeRows)),\n });\n }).catch(error => {\n if (!this.disposed && generation === this.generation) this.update({ busy: false, error: String(error) });\n });\n }\n\n start(options: Readonly<Record<string, unknown>> = this.options): void {\n if (this.disposed) return;\n this.options = options;\n this.cancel();\n const generation = this.generation;\n const state = this.state.get();\n const root = this.roots[state.cursor];\n if (!root) { this.update({ error: \"No compatible graph roots\" }); return; }\n let params: unknown;\n try { params = JSON.parse(state.params); }\n catch { this.update({ error: \"Root parameters must be valid JSON\" }); return; }\n const stop = new Promise<void>(resolve => { this.stop = resolve; });\n this.started = true;\n this.update({ active: true, model: undefined, error: undefined, version: undefined, scrollTop: 0, busy: false, refreshing: false });\n const completion = inspectGraphCommand(this.context.channel, {\n targets: [root], root: root.root, params, stop, watch: true, depth: 0, interactive: false,\n maxObjects: options.maxObjects as number | undefined,\n maxBytes: options.maxBytes as number | undefined,\n maxRounds: options.maxRounds as number | undefined,\n timeoutMs: options.timeoutMs as number | undefined,\n logTiming: options.logTiming === true,\n onUpdating: async () => {\n if (this.disposed || generation !== this.generation) return;\n this.update({ refreshing: true });\n await this.action;\n },\n onModel: async (model, version) => {\n while (!this.disposed && generation === this.generation) {\n const action = this.action;\n await action;\n if (this.disposed || generation !== this.generation) return;\n await model.restoreExpanded(undefined, this.state.get().model);\n if (action !== this.action) continue;\n if (!this.disposed && generation === this.generation) {\n const previous = this.state.get();\n const top = previous.model ? anchorGraphScrollTop(previous.model.lines, model.lines, previous.scrollTop ?? 0) : 0;\n this.update({ model, version, refreshing: false,\n scrollTop: clampGraphScroll(model.lines.length, model.selectedIndex, top,\n Math.max(0, (previous.viewportRows ?? 24) - graphChromeRows), false) });\n }\n return;\n }\n },\n }).then(() => {\n if (!this.disposed && generation === this.generation) this.update({ active: false, refreshing: false });\n }, error => {\n if (!this.disposed && generation === this.generation) this.update({ active: false, refreshing: false, error: String(error) });\n });\n this.pending.add(completion);\n void completion.then(() => this.pending.delete(completion), () => this.pending.delete(completion));\n }\n\n update(value: Partial<State>): void {\n if (this.disposed) return;\n const previous = this.state.get();\n this.state.set({ ...previous, ...value, revision: previous.revision + 1 }, undefined);\n }\n private cancel(): void { this.generation++; this.stop?.(); this.stop = undefined; }\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.cancel();\n this.state.set({ ...this.state.get(), revision: this.state.get().revision + 1 }, undefined);\n }\n async disposeAsync(): Promise<void> {\n this.dispose();\n await Promise.allSettled([...this.pending, this.action]);\n }\n}\n\nexport class GraphPanel extends React.Component<{ readonly session: GraphSession }, { revision: number }> {\n state = { revision: 0 };\n private subscription: { dispose(): void } | undefined;\n componentDidMount(): void {\n this.subscription = autorun(reader => {\n const value = this.props.session.state.read(reader);\n this.setState({ revision: value.revision });\n });\n }\n componentWillUnmount(): void { this.subscription?.dispose(); }\n render(): React.ReactNode {\n const session = this.props.session;\n const state = session.state.get();\n const model = state.model;\n const height = Math.max(1, state.viewportRows ?? stdout.rows ?? 24);\n const width = Math.max(1, state.viewportColumns ?? stdout.columns ?? 80);\n const root = session.roots[state.cursor];\n const graph = state.active || model !== undefined;\n const status = state.error ?? (state.refreshing ? \"Refreshing root…\"\n : state.busy ? \"Loading object…\" : undefined);\n const frame = createGraphFrame(model, {\n title: root ? `${root.serviceId || \"local\"} / ${root.interfaceId} / ${root.root}` : \"No compatible roots\",\n params: `params: ${state.params}${state.editing ? \"█\" : \"\"}`,\n rows: height, columns: width, scrollTop: state.scrollTop ?? 0,\n revealSelection: false, version: state.version, showObjectIds: state.showObjectIds, status,\n error: state.error !== undefined,\n phase: !graph ? state.editing ? \"EDIT PARAMETERS\" : \"SELECT ROOT\"\n : !state.active ? `STOPPED${state.version === undefined ? \"\" : ` v${state.version}`}` : undefined,\n });\n let rows: readonly GraphFrameRow[] = frame.rows;\n if (!graph) {\n const capacity = Math.max(0, height - graphChromeRows);\n const top = state.scrollTop ?? 0;\n rows = ([\n ...rows.slice(0, 3),\n ...Array.from({ length: capacity }, (_, offset): GraphFrameRow => {\n const item = session.roots[top + offset];\n return { text: item ? ` ${item.serviceId || \"local\"} / ${item.interfaceId} / ${item.root}` : \"\",\n style: item && top + offset === state.cursor ? \"selected\" : \"value\" };\n }),\n { text: ` ${\"─\".repeat(Math.max(0, width - 2))}`, style: \"muted\" },\n { text: state.error ?? ` schema: ${JSON.stringify(root?.paramsArgument.schema ?? {})}`, style: state.error ? \"error\" : \"muted\" },\n { text: ` ${root ? state.cursor + 1 : 0}/${session.roots.length} roots`, style: \"reference\" },\n ] satisfies readonly GraphFrameRow[]).slice(0, height);\n }\n return <Box flexDirection=\"column\" width={width} height={height} flexShrink={0} overflow=\"hidden\">\n {rows.map((row, index) => <Text key={index} wrap=\"truncate-end\"\n bold={row.style === \"header\" || row.style === \"selected\"}\n dimColor={row.style === \"muted\"}\n color={row.style === \"selected\" ? \"black\" : row.style === \"error\" ? \"red\"\n : row.style === \"header\" || row.style === \"reference\" ? \"cyan\" : \"white\"}\n backgroundColor={row.style === \"selected\" ? \"cyan\" : undefined}>\n {graphFrameText(row.text, width, row.style === \"selected\") || \" \"}\n </Text>)}\n </Box>;\n }\n}\n\nexport async function runGraphTui(context: ViewOpenContext, roots: readonly GraphTarget[], options: Readonly<Record<string, unknown>>): Promise<void> {\n const session = new GraphSession(context, roots, options);\n const cursor = roots.findIndex(root => (options.root === undefined || root.root === options.root)\n && (options.interface === undefined || root.interfaceId === options.interface));\n if (cursor < 0) throw new Error(\"No matching graph root\");\n session.update({ cursor, params: String(options.params ?? \"{}\") });\n const running = runViewTui(session);\n if (roots.length === 1 || options.root !== undefined) session.start(options);\n await running;\n}\n","import { interfaceTemplateArgumentsEquivalent } from \"@hediet/linkrpc\";\nimport { GRAPH_INTERFACE_TAG, graphPresentationInterface } from \"@hediet/linkrpc-infra/graph\";\nimport type { ViewContribution, ViewOpenContext } from \"../../views/types\";\nimport { graphDescriptorsFromSchema, inspectGraphCommand, type GraphTarget } from \"./inspectGraph\";\nimport { GraphSession, runGraphTui } from \"./session\";\n\nexport function resolveGraphRoots(context: ViewOpenContext): GraphTarget[] {\n return context.interfaces.flatMap(listing => {\n const presentation = (context.target.serviceInterfaces ?? context.target.interfaces).find(candidate =>\n candidate.serviceId === listing.serviceId && candidate.interfaceId === graphPresentationInterface.info.id\n && candidate.hash === graphPresentationInterface.toSchema().hash);\n const { roots, stores } = graphDescriptorsFromSchema({ ...listing, hash: listing.hash ?? \"\" }, listing.schema);\n return roots.map(root => {\n const compatible = stores.filter(store => interfaceTemplateArgumentsEquivalent(store.refArgument, root.refArgument));\n if (compatible.length !== 1) throw new Error(`Root \"${root.root}\" requires exactly one compatible object store`);\n const store = compatible[0]!;\n const route = (method: string) => listing.isDefault ? method.slice(method.lastIndexOf(\"::\") + 2) : method;\n return {\n ...root, graphInterfaceId: store.interfaceId, watchMethod: route(root.watchMethod),\n batchMethod: route(store.batchMethod), valueArgument: store.valueArgument,\n ...(presentation === undefined ? {} : {\n presentationMethod: presentation.isDefault ? \"get\"\n : [presentation.serviceId, presentation.interfaceId, \"get\"].filter(Boolean).join(\"::\"),\n }),\n };\n });\n });\n}\n\nexport const graphView: ViewContribution = {\n id: \"graph\", title: \"Graph\", modes: [\"cli\", \"tui\"],\n conditions: [\n { kind: \"interface\", interface: { tag: GRAPH_INTERFACE_TAG } },\n { kind: \"service\", implements: { tag: GRAPH_INTERFACE_TAG } },\n ],\n configureCommand(command) {\n command\n .option(\"--mode <mode>\", \"roots, snapshot, or watch (watch --json emits one snapshot per JSONL line)\", \"snapshot\")\n .option(\"--root <name>\", \"root instance name (required if ambiguous)\")\n .option(\"--params <json>\", \"root parameters as JSON\", \"{}\")\n .option(\"--depth <number>\", \"snapshot traversal depth\", nonNegativeInteger)\n .option(\"--path <pointer>\", \"graph JSON pointer selector\")\n .option(\"--max-objects <number>\", \"maximum objects per batch\", positiveInteger)\n .option(\"--max-bytes <number>\", \"maximum bytes per batch\", positiveInteger)\n .option(\"--max-rounds <number>\", \"maximum batch rounds\", positiveInteger)\n .option(\"--log-timing\", \"write graph timing diagnostics to stderr\");\n },\n async open(context, options) {\n const mode = options.mode ?? \"snapshot\";\n if (![\"roots\", \"snapshot\", \"watch\"].includes(String(mode))) throw new Error(\"--mode must be roots, snapshot, or watch\");\n const roots = resolveGraphRoots(context);\n if (roots.length === 0) throw new Error(\"Selected target has no compatible graph roots; advertised tags are not a contract\");\n const selected = roots.filter(root => (options.root === undefined || root.root === options.root)\n && (options.interface === undefined || root.interfaceId === options.interface));\n if (options.tui === true) {\n if (options.json === true || mode !== \"snapshot\") throw new Error(\"--tui cannot be combined with --json or --mode roots/watch\");\n if (options.path !== undefined || options.depth !== undefined) throw new Error(\"--tui loads on demand; --path and --depth apply to snapshots/watch\");\n if (selected.length === 0) throw new Error(\"No matching graph root. Use --mode roots.\");\n if (options.root !== undefined && selected.length > 1) throw new Error(\"Graph root is ambiguous; specify --interface\");\n await runGraphTui(context, selected, options);\n return \"\";\n }\n if (mode === \"roots\") {\n const rows = selected.map(root => ({ interfaceId: root.interfaceId, root: root.root, params: root.paramsArgument }));\n return options.json ? JSON.stringify(rows, null, 2) : rows.map(row => `${row.interfaceId} ${row.root} ${JSON.stringify(row.params.schema)}`).join(\"\\n\");\n }\n if (selected.length !== 1) throw new Error(selected.length === 0\n ? \"No matching graph root. Use --mode roots.\"\n : \"Graph root is ambiguous. Use --mode roots, then --root and optionally --interface.\");\n let params: unknown;\n try { params = JSON.parse(String(options.params ?? \"{}\")); }\n catch { throw new Error(\"--params must be valid JSON\"); }\n let stop!: () => void;\n const stopped = options.stop as Promise<void> | undefined ?? new Promise<void>(resolve => { stop = resolve; });\n const onStop = () => stop?.();\n process.once(\"SIGINT\", onStop);\n process.once(\"SIGTERM\", onStop);\n try {\n return await inspectGraphCommand(context.channel, {\n targets: selected, root: selected[0]!.root, params,\n depth: options.depth as number | undefined, path: options.path as string | undefined,\n watch: mode === \"watch\", json: options.json === true, interactive: false, stop: stopped,\n maxObjects: options.maxObjects as number | undefined,\n maxBytes: options.maxBytes as number | undefined,\n maxRounds: options.maxRounds as number | undefined,\n timeoutMs: options.timeoutMs as number | undefined,\n logTiming: options.logTiming === true,\n emit: options.emit as ((text: string) => void) | undefined,\n });\n } finally {\n process.off(\"SIGINT\", onStop);\n process.off(\"SIGTERM\", onStop);\n }\n },\n createSession(context) { return new GraphSession(context, resolveGraphRoots(context)); },\n};\n\nfunction nonNegativeInteger(value: string): number {\n const number = Number(value);\n if (!Number.isSafeInteger(number) || number < 0) throw new Error(\"Expected a non-negative integer\");\n return number;\n}\nfunction positiveInteger(value: string): number {\n const number = nonNegativeInteger(value);\n if (number === 0) throw new Error(\"Expected a positive integer\");\n return number;\n}\n","import type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { computeInterfaceHash, type JsonValue } from \"@hediet/linkrpc\";\nimport { parse } from \"zod/mini\";\nimport {\n applyJsonDocumentEdits, loggingInterface, logDocumentSchema, logStreamEventSchema,\n type LogDocument, type LogEntry, type LogLevel,\n} from \"@hediet/linkrpc-infra\";\nimport type { ResolvedViewInterface, ViewOpenContext } from \"../../views/types\";\n\nexport const levels = [\"trace\", \"debug\", \"info\", \"warn\", \"error\"] as const;\nexport interface LoggingTarget {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly route: (member: string) => string;\n}\nexport interface LogFrame {\n readonly revision: number;\n readonly document: LogDocument;\n readonly entries: readonly LogEntry[];\n readonly hidden: number;\n}\nexport interface LogOptions {\n readonly level: LogLevel;\n readonly tail: number;\n readonly maxBytes: number;\n readonly timeoutMs: number;\n}\n\nexport function resolveLoggingTargets(context: ViewOpenContext): LoggingTarget[] {\n const selected = context.interfaces.filter(listing =>\n listing.interfaceId === \"linkrpc.logging\" || listing.tags?.includes(\"linkrpc.logging\"));\n return selected.map(listing => {\n validateLoggingSchema(listing);\n return {\n serviceId: listing.serviceId, interfaceId: listing.interfaceId, hash: listing.schema.hash,\n route: member => listing.isDefault ? member\n : [listing.serviceId, listing.interfaceId, member].filter(Boolean).join(\"::\"),\n };\n });\n}\n\nfunction validateLoggingSchema(listing: ResolvedViewInterface): void {\n const canonical = loggingInterface.toSchema();\n if (listing.interfaceId !== canonical.id\n || listing.schema.id !== canonical.id\n || computeInterfaceHash({ ...canonical, methods: listing.schema.methods,\n components: listing.schema.components }) !== canonical.hash) {\n throw new Error(`Interface ${listing.interfaceId} does not implement the canonical logging contract (tags are discovery hints)`);\n }\n}\n\nexport function logOptions(options: Readonly<Record<string, unknown>>): LogOptions {\n const level = String(options.level ?? \"trace\") as LogLevel;\n if (![...levels, \"off\"].includes(level)) throw new Error(\"--level must be trace, debug, info, warn, error, or off\");\n const tail = options.tail ?? 200;\n const maxBytes = options.maxBytes ?? 2_000_000;\n const timeoutMs = options.timeoutMs ?? 5_000;\n if (!Number.isSafeInteger(tail) || Number(tail) < 1 || Number(tail) > 10_000) throw new Error(\"--tail must be an integer from 1 to 10000\");\n if (!Number.isSafeInteger(maxBytes) || Number(maxBytes) < 1024 || Number(maxBytes) > 50_000_000) throw new Error(\"--max-bytes must be an integer from 1024 to 50000000\");\n if (!Number.isSafeInteger(timeoutMs) || Number(timeoutMs) < 1) throw new Error(\"--timeout-ms must be a positive integer\");\n return { level, tail: Number(tail), maxBytes: Number(maxBytes), timeoutMs: Number(timeoutMs) };\n}\n\nfunction flatten(entries: readonly LogEntry[], result: LogEntry[] = [], depth = 0): LogEntry[] {\n if (depth > 32) throw new Error(\"Log entry nesting exceeds 32 levels\");\n for (const entry of entries) {\n result.push(entry);\n if (entry.entries) flatten(entry.entries, result, depth + 1);\n }\n return result;\n}\n\nexport function frame(revision: number, document: LogDocument, options: LogOptions): LogFrame {\n const filtered = flatten(document.entries).filter(entry =>\n options.level !== \"off\" && levels.indexOf(entry.level) >= levels.indexOf(options.level as typeof levels[number]));\n return {\n revision, document, entries: filtered.slice(-options.tail),\n hidden: filtered.length - Math.min(filtered.length, options.tail),\n };\n}\n\nfunction checkedDocument(value: unknown, maxBytes: number): LogDocument {\n checkedSize(value, maxBytes);\n return parse(logDocumentSchema, value);\n}\n\nfunction checkedSize(value: unknown, maxBytes: number): void {\n if (Buffer.byteLength(JSON.stringify(value) ?? \"\", \"utf8\") > maxBytes) {\n throw new Error(`Logging payload exceeds --max-bytes (${maxBytes}); stream stopped to bound memory`);\n }\n}\n\nexport async function readLogSnapshot(channel: CliChannel, target: LoggingTarget, options: LogOptions): Promise<LogFrame> {\n const value = await withDeadline(\n channel.sendRequest(target.route(\"getLogSnapshot\"), {}, { interfaceHash: target.hash }), options.timeoutMs);\n const result = value as { revision?: unknown; document?: unknown };\n if (!Number.isSafeInteger(result?.revision) || Number(result.revision) < 0) throw new Error(\"Invalid logging snapshot revision\");\n return frame(Number(result.revision), checkedDocument(result.document, options.maxBytes), options);\n}\n\nexport async function watchLog(\n channel: CliChannel, target: LoggingTarget, options: LogOptions,\n emit: (value: LogFrame) => void, stop: Promise<void>,\n): Promise<void> {\n let revision: number | undefined;\n let document: LogDocument | undefined;\n let pending = 0;\n let queue = Promise.resolve();\n let fail!: (error: unknown) => void;\n const failure = new Promise<never>((_, reject) => { fail = reject; });\n const call = channel.sendRequestWithStream(target.route(\"watchLog\"), {}, {\n interfaceHash: target.hash,\n onStreamMessage: payload => {\n if (++pending > 128) { fail(new Error(\"Logging stream backlog exceeded 128 events; stopping slow consumer\")); return; }\n queue = queue.then(async () => {\n try {\n checkedSize(payload, options.maxBytes);\n const event = logStreamEventSchema.parse(payload);\n if (event.type === \"snapshot\") {\n revision = event.revision;\n document = checkedDocument(event.document, options.maxBytes);\n } else {\n if (revision === undefined || event.revision !== revision + 1) {\n const latest = await readLogSnapshot(channel, target, options);\n revision = latest.revision;\n document = latest.document;\n emit(latest);\n if (event.revision <= revision) return;\n if (event.revision !== revision + 1) throw new Error(`Logging revision gap after resync: ${revision} -> ${event.revision}`);\n }\n // A validated wire document is JSON data, but its domain\n // interface has no index signature required by JsonValue.\n const jsonDocument: JsonValue = JSON.parse(JSON.stringify(document));\n document = checkedDocument(applyJsonDocumentEdits(jsonDocument, event.edits), options.maxBytes);\n revision = event.revision;\n }\n emit(frame(revision, document, options));\n } finally { pending--; }\n }).catch(fail);\n },\n });\n const timer = setTimeout(() => {\n if (revision === undefined) fail(new Error(`Logging watch produced no snapshot within ${options.timeoutMs}ms`));\n }, options.timeoutMs);\n try {\n const outcome = await Promise.race([call.result.then(() => \"ended\" as const), stop.then(() => \"stop\" as const), failure]);\n await Promise.race([queue, failure]);\n if (outcome === \"ended\" && revision === undefined) throw new Error(\"Logging watch ended without a snapshot\");\n } finally {\n clearTimeout(timer);\n call.cancel(\"logging view closed\");\n call.dispose?.();\n void call.result.catch(() => {});\n }\n}\n\nasync function withDeadline<T>(promise: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([promise, new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`Logging snapshot timed out after ${ms}ms`)), ms);\n })]);\n } finally { clearTimeout(timer); }\n}\n","import React from \"react\";\nimport { Box, Text } from \"ink\";\nimport { autorun, derived, observableValue } from \"@vscode/observables\";\nimport type { ViewCommand, ViewOpenContext, ViewSession } from \"../../views/types\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\nimport { levels, watchLog, type LoggingTarget, type LogFrame, type LogOptions } from \"./model\";\nimport type { LogEntry } from \"@hediet/linkrpc-infra\";\n\ninterface State {\n readonly revision: number;\n readonly frame?: LogFrame;\n readonly cursor: number;\n readonly paused: boolean;\n readonly follow: boolean;\n readonly level: LogOptions[\"level\"];\n readonly cleared: readonly LogEntry[];\n readonly rows: number;\n readonly error?: string;\n}\n\nexport class LoggingSession implements ViewSession {\n readonly state = observableValue<State>(this, {\n revision: 0, cursor: 0, paused: false, follow: true, level: \"trace\", cleared: [], rows: 24,\n });\n readonly element = <LoggingPanel session={this} />;\n private stop!: () => void;\n private completion: Promise<void> | undefined;\n private disposed = false;\n private generation = 0;\n private latest?: LogFrame;\n constructor(private readonly context: ViewOpenContext, readonly target: LoggingTarget, private readonly options: LogOptions) {\n this.update({ level: options.level });\n this.start();\n }\n private update(patch: Partial<State>): void {\n if (this.disposed) return;\n const state = this.state.get();\n this.state.set({ ...state, ...patch, revision: state.revision + 1 }, undefined);\n }\n private start(): void {\n const generation = ++this.generation;\n const stop = new Promise<void>(resolve => { this.stop = resolve; });\n this.completion = watchLog(this.context.channel, this.target, { ...this.options, level: \"trace\" }, value => {\n if (this.disposed || generation !== this.generation) return;\n this.latest = value;\n const state = this.state.get();\n if (state.paused) return;\n this.showLatest();\n }, stop).then(() => {\n if (!this.disposed && generation === this.generation) this.update({ error: \"Logging watch ended\" });\n }, error => {\n if (!this.disposed && generation === this.generation) this.update({ error: String(error) });\n });\n }\n private showLatest(): void {\n if (!this.latest) return;\n const state = this.state.get();\n const cleared = state.frame && this.latest.revision < state.frame.revision\n ? [] : retainedCleared(state.cleared, this.latest.entries);\n const entries = visibleEntries({ ...state, frame: this.latest, cleared });\n this.update({ frame: this.latest, cleared, cursor: state.follow\n ? Math.max(0, entries.length - 1) : Math.min(state.cursor, Math.max(0, entries.length - 1)) });\n }\n get displayedEntries(): readonly LogEntry[] { return visibleEntries(this.state.get()); }\n setViewport(rows: number): void { if (this.state.get().rows !== rows) this.update({ rows }); }\n captureState(): unknown {\n const { level, follow, paused } = this.state.get();\n return { level, follow, paused };\n }\n restoreState(value: unknown): void {\n const state = value as Partial<Pick<State, \"level\" | \"follow\" | \"paused\">> | undefined;\n if (state) this.update({\n level: [...levels, \"off\"].includes(state.level as typeof levels[number]) ? state.level : this.state.get().level,\n follow: state.follow === false ? false : true, paused: state.paused === true,\n });\n }\n readonly commands = derived(this, (reader): readonly ViewCommand[] => {\n const state = this.state.read(reader);\n if (this.disposed) return [];\n const entries = visibleEntries(state);\n const command = (id: string, title: string, key: string, execute: () => void, enabled = true): ViewCommand =>\n ({ id: `logging.${id}`, title, context: \"Logging\", keybindings: [{ key }], execute, enabled });\n const move = (delta: number) => this.update({\n cursor: Math.max(0, Math.min(entries.length - 1, this.state.get().cursor + delta)),\n follow: false,\n });\n return [\n command(\"up\", \"Previous entry\", \"up\", () => move(-1), state.cursor > 0),\n command(\"down\", \"Next entry\", \"down\", () => move(1), state.cursor + 1 < entries.length),\n command(\"pageUp\", \"Page up\", \"pageup\", () => move(-Math.max(1, state.rows - 4)), state.cursor > 0),\n command(\"pageDown\", \"Page down\", \"pagedown\", () => move(Math.max(1, state.rows - 4)), state.cursor + 1 < entries.length),\n command(\"follow\", state.follow ? \"Stop following\" : \"Follow latest\", \"f\",\n () => this.update({ follow: !state.follow, cursor: state.follow ? state.cursor : Math.max(0, entries.length - 1) })),\n command(\"pause\", state.paused ? \"Resume updates\" : \"Pause updates\", \"p\", () => {\n this.update({ paused: !state.paused });\n if (state.paused) this.showLatest();\n }),\n command(\"clear\", \"Clear displayed entries (local)\", \"c\",\n () => this.update({ cleared: state.frame?.entries ?? [], cursor: 0 })),\n command(\"filter\", `Minimum level: ${state.level}`, \"l\", () => {\n const list = [...levels, \"off\"] as const;\n this.update({ level: list[(list.indexOf(state.level) + 1) % list.length]!, cursor: 0 });\n }),\n ];\n });\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.generation++;\n this.stop?.();\n this.state.set({ ...this.state.get(), revision: this.state.get().revision + 1 }, undefined);\n }\n async disposeAsync(): Promise<void> { this.dispose(); await this.completion; }\n}\n\nfunction visibleEntries(state: State): readonly LogEntry[] {\n return state.frame?.entries.slice(state.cleared.length).filter(entry =>\n state.level !== \"off\" && levels.indexOf(entry.level) >= levels.indexOf(state.level as typeof levels[number])) ?? [];\n}\n\nfunction retainedCleared(previous: readonly LogEntry[], current: readonly LogEntry[]): readonly LogEntry[] {\n if (previous.length === 0 || current.length === 0) return [];\n const oldKeys = previous.map(entry => JSON.stringify(entry));\n const newKeys = current.map(entry => JSON.stringify(entry));\n // The wire format has no entry identity. Ambiguous duplicate values must\n // reappear rather than accidentally hiding a newly appended identical log.\n if (new Set(oldKeys).size !== oldKeys.length || new Set(newKeys).size !== newKeys.length) return [];\n for (let count = Math.min(previous.length, current.length); count > 0; count--) {\n if (oldKeys.slice(-count).every((key, index) => key === newKeys[index])) return current.slice(0, count);\n }\n return [];\n}\n\nexport class LoggingPanel extends React.Component<{ readonly session: LoggingSession }, { revision: number }> {\n state = { revision: 0 };\n private subscription?: { dispose(): void };\n componentDidMount(): void {\n this.subscription = autorun(reader => this.setState({ revision: this.props.session.state.read(reader).revision }));\n }\n componentWillUnmount(): void { this.subscription?.dispose(); }\n render(): React.ReactNode {\n const state = this.props.session.state.get();\n const entries = this.props.session.displayedEntries;\n const rows = Math.max(1, state.rows - 4);\n const start = Math.max(0, Math.min(state.cursor, entries.length - 1) - rows + 1);\n return <Box flexDirection=\"column\" flexGrow={1} overflow=\"hidden\">\n <Text bold>Logging {safeTerminalText(this.props.session.target.serviceId || \"<root>\")} revision {state.frame?.revision ?? \"…\"}</Text>\n <Text dimColor>level {state.level} · {state.paused ? \"paused\" : \"live\"} · {state.follow ? \"follow\" : \"manual\"} · {state.frame?.hidden ?? 0} earlier hidden · clear is local</Text>\n {state.error && <Text color=\"red\">{safeTerminalText(state.error)}</Text>}\n {entries.slice(start, start + rows).map((entry, index) =>\n <Text key={`${start + index}:${entry.timestamp}`} color={start + index === state.cursor ? \"cyan\" : undefined} wrap=\"truncate-end\">\n {start + index === state.cursor ? \"› \" : \" \"}\n {safeTerminalText(`${entry.timestamp} ${entry.level.toUpperCase()} ${entry.message}`\n + (entry.attributes ? ` ${JSON.stringify(entry.attributes)}` : \"\")\n + (entry.error ? ` ${entry.error.name ?? \"Error\"}: ${entry.error.message}${entry.error.stack ? ` ${entry.error.stack}` : \"\"}` : \"\"))}\n </Text>)}\n </Box>;\n }\n}\n","import { runViewTui } from \"../../views/runViewTui\";\nimport type { ViewContribution } from \"../../views/types\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\nimport { LoggingSession } from \"./session\";\nimport { logOptions, readLogSnapshot, resolveLoggingTargets, watchLog, type LogFrame } from \"./model\";\n\nexport function formatLogFrame(value: LogFrame, json: boolean): string {\n if (json) return JSON.stringify({\n revision: value.revision, service: value.document.service,\n startedAt: value.document.startedAt, state: value.document.state,\n entries: value.entries, hidden: value.hidden,\n });\n const lines = value.entries.map(entry => {\n const details = entry.attributes ? ` ${JSON.stringify(entry.attributes)}` : \"\";\n const error = entry.error ? ` ${entry.error.name ?? \"Error\"}: ${entry.error.message}${entry.error.stack ? ` ${entry.error.stack}` : \"\"}` : \"\";\n return safeTerminalText(`${entry.timestamp} ${entry.level.toUpperCase()} ${entry.message}${details}${error}`);\n });\n return [`${safeTerminalText(value.document.service)} revision=${value.revision} (${value.hidden} earlier matching entries hidden)`, ...lines].join(\"\\n\");\n}\n\nexport const loggingView: ViewContribution = {\n id: \"logging\", title: \"Logging\", modes: [\"cli\", \"tui\"],\n conditions: [\n { kind: \"interface\", interface: { interfaceId: \"linkrpc.logging\" } },\n { kind: \"service\", implements: { interfaceId: \"linkrpc.logging\" } },\n { kind: \"interface\", interface: { tag: \"linkrpc.logging\" } },\n { kind: \"service\", implements: { tag: \"linkrpc.logging\" } },\n ],\n configureCommand(command) {\n command\n .option(\"--mode <mode>\", \"snapshot (read-only) or watch (one frame per revision)\", \"snapshot\")\n .option(\"--level <level>\", \"client-side minimum level: trace, debug, info, warn, error, off\", \"trace\")\n .option(\"--tail <count>\", \"maximum displayed matching entries\", positiveInteger, 200)\n .option(\"--max-bytes <bytes>\", \"maximum in-memory log document size\", positiveInteger, 2_000_000);\n },\n async open(context, options) {\n const targets = resolveLoggingTargets(context).filter(target =>\n options.interface === undefined || target.interfaceId === options.interface);\n if (targets.length !== 1) throw new Error(targets.length\n ? \"Multiple logging interfaces in this service; use --interface or an interface --target\"\n : \"Selected target has no canonical logging interface\");\n const target = targets[0]!;\n const config = logOptions(options);\n const mode = options.mode ?? \"snapshot\";\n if (mode !== \"snapshot\" && mode !== \"watch\") throw new Error(\"--mode must be snapshot or watch\");\n if (options.tui === true) {\n if (options.json === true || mode !== \"snapshot\") throw new Error(\"--tui cannot be combined with --json or --mode watch\");\n const session = new LoggingSession(context, target, config);\n await runViewTui(session);\n return \"\";\n }\n if (mode === \"snapshot\") return formatLogFrame(await readLogSnapshot(context.channel, target, config), options.json === true);\n let release!: () => void;\n const stop = options.stop as Promise<void> | undefined ?? new Promise<void>(resolve => { release = resolve; });\n const onStop = () => release?.();\n const emit = options.emit as ((text: string) => void) | undefined ?? (text => process.stdout.write(`${text}\\n`));\n process.once(\"SIGINT\", onStop);\n process.once(\"SIGTERM\", onStop);\n try {\n await watchLog(context.channel, target, config, value => emit(formatLogFrame(value, options.json === true)), stop);\n return \"\";\n } finally {\n process.off(\"SIGINT\", onStop);\n process.off(\"SIGTERM\", onStop);\n }\n },\n createSession(context) {\n const targets = resolveLoggingTargets(context);\n if (targets.length !== 1) throw new Error(\"Logging service is ambiguous; select an interface target\");\n return new LoggingSession(context, targets[0]!, logOptions({}));\n },\n};\n\nfunction positiveInteger(text: string): number {\n const value = Number(text);\n if (!Number.isSafeInteger(value) || value < 1) throw new Error(\"Expected a positive integer\");\n return value;\n}\n","import { renderMermaidASCII } from \"beautiful-mermaid\";\nimport type { TopologyGraph } from \"@hediet/linkrpc/inspection\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\n\nexport interface TopologyDocument {\n readonly lines: readonly string[];\n readonly mermaid: string;\n readonly warnings: readonly string[];\n}\n\n/** JSON-compatible escaping also neutralizes terminal C1 and bidi controls. */\nexport function topologyJson(value: unknown, indent?: number): string {\n return JSON.stringify(value, null, indent).replace(/[\\u007f-\\u009f\\p{Cf}\\p{Zl}\\p{Zp}]/gu,\n character => character.split(\"\").map(unit => `\\\\u${unit.charCodeAt(0).toString(16).padStart(4, \"0\")}`).join(\"\"));\n}\n\nfunction boxHint(label: string): string {\n const text = label.replace(/[^a-zA-Z0-9 ._-]/gu, \"_\");\n return text.length > 26 ? `${text.slice(0, 23)}...` : text;\n}\n\n/** Only generated IDs and a bounded, allowlisted label alphabet enter Mermaid syntax. */\nexport function topologyDocument(graph: TopologyGraph): TopologyDocument {\n const identifiers = new Map<string, number>();\n const warnings: string[] = [];\n for (const node of graph.nodes) {\n if (identifiers.has(node.nodeId)) throw new Error(`Duplicate topology node ID: ${safeTerminalText(JSON.stringify(node.nodeId))}`);\n identifiers.set(node.nodeId, identifiers.size);\n }\n const declared = identifiers.size;\n const include = (nodeId: string) => {\n if (!identifiers.has(nodeId)) {\n identifiers.set(nodeId, identifiers.size);\n warnings.push(`Unlisted node referenced by the result: ${topologyJson(nodeId)}`);\n }\n };\n include(graph.entryNodeId);\n for (const link of graph.links) { include(link.from.nodeId); include(link.to.nodeId); }\n for (const route of graph.routes) include(route.nodeId);\n const key = (id: string) => `N${identifiers.get(id)! + 1}`;\n const definitions = [...identifiers].map(([id, index]) =>\n `n${index}[\"${key(id)}${index >= declared ? \" unlisted\" : \"\"}${id === graph.entryNodeId ? \" entry\" : \"\"}`\n + (index < declared ? ` - ${boxHint(graph.nodes[index]!.label ?? id)}` : \"\") + '\"]');\n const pairs = new Set<string>();\n for (const link of graph.links) {\n const from = identifiers.get(link.from.nodeId)!, to = identifiers.get(link.to.nodeId)!;\n pairs.add(`n${Math.min(from, to)} --- n${Math.max(from, to)}`);\n }\n const mermaid = [\"graph LR\", ...definitions, ...pairs].join(\"\\n\");\n let diagram: string;\n if (identifiers.size > 200 || pairs.size > 400) {\n diagram = \"Diagram omitted: layout exceeds 200 nodes or 400 distinct connections. Complete records follow.\";\n } else {\n try {\n diagram = identifiers.size === 0 ? \"(empty topology)\" : renderMermaidASCII(mermaid, {\n useAscii: false, colorMode: \"none\", paddingX: 3, paddingY: 2, boxBorderPadding: 0,\n });\n } catch (error) {\n diagram = `Diagram unavailable: ${String(error)}. Complete records follow.`;\n }\n }\n const lines = [\n `TOPOLOGY — observer ${topologyJson(graph.observerServiceId)}; entry ${key(graph.entryNodeId)}`,\n \"One service's observed graph. Lines are connections, not RPC direction.\",\n \"Parallel links share a diagram line; LINKS below preserves every endpoint and transport record.\",\n \"Box labels are abbreviated ASCII-safe hints; NODES preserves complete Unicode labels.\",\n \"\",\n ...diagram.split(\"\\n\").map(line => line.trimEnd()),\n \"\",\n `NODES (${graph.nodes.length}) — complete records, including ports and descriptors`,\n ...graph.nodes.map(node => `${key(node.nodeId)} ${topologyJson(node)}`),\n ...[...identifiers].filter(([, index]) => index >= declared).map(([id]) => `${key(id)} unlisted node ${topologyJson(id)}`),\n \"\",\n `LINKS (${graph.links.length}) — from/to are transport endpoint roles, not RPC arrows`,\n ...graph.links.map((link, index) => `L${index + 1} ${key(link.from.nodeId)} -- ${key(link.to.nodeId)} ${topologyJson(link)}`),\n \"\",\n `ROUTES (${graph.routes.length}) — claims from this result only`,\n ...graph.routes.map((route, index) => `R${index + 1} ${key(route.nodeId)} ${topologyJson(route)}`),\n ...warnings.length ? [\"\", \"WARNINGS\", ...warnings] : [],\n ].map(safeTerminalText);\n return { lines, mermaid, warnings };\n}\n","import { parse } from \"zod/mini\";\nimport { computeInterfaceHash, LinkRpcConnection, type IRequestSender, type JsonValue, type RawStreamingCall, type StreamSendOpts } from \"@hediet/linkrpc\";\nimport { topologyInterface, zTopologyGraph, type TopologyGraph } from \"@hediet/linkrpc/inspection\";\nimport { TopologyClient, type TopologyWatch } from \"@hediet/linkrpc-infra/inspection\";\nimport type { ViewOpenContext } from \"../../views/types\";\n\nexport interface TopologyTarget {\n readonly serviceId: string;\n readonly hash: string;\n readonly isDefault: boolean;\n}\n\nexport function resolveTopologyTarget(context: ViewOpenContext): TopologyTarget {\n const candidates = context.interfaces.filter(value => value.interfaceId === topologyInterface.info.id);\n if (candidates.length !== 1) throw new Error(\"Select exactly one canonical hubrpc.topology interface\");\n const listing = candidates[0]!;\n const canonical = topologyInterface.toSchema();\n if (listing.schema.id !== canonical.id\n || computeInterfaceHash(listing.schema) !== listing.schema.hash\n || computeInterfaceHash({\n ...canonical, methods: listing.schema.methods, components: listing.schema.components,\n }) !== canonical.hash) {\n throw new Error(\"Selected hubrpc.topology schema does not match the canonical inspection contract\");\n }\n return { serviceId: listing.serviceId, hash: listing.schema.hash, isDefault: listing.isDefault === true };\n}\n\nexport function topologyTimeout(options: Readonly<Record<string, unknown>>): number {\n const timeout = Number(options.timeoutMs ?? 5_000);\n if (!Number.isSafeInteger(timeout) || timeout < 1) throw new Error(\"--timeout-ms must be a positive integer\");\n return timeout;\n}\n\n/**\n * A send-only, non-owning connection adapter. Typed inspection clients still validate\n * the canonical contract; this adapter supplies the selected default/qualified route.\n */\nexport class TopologyReader {\n readonly client: TopologyClient;\n private readonly calls = new Set<RawStreamingCall>();\n private readonly pending = new Set<Promise<JsonValue>>();\n private disposed = false;\n\n constructor(context: ViewOpenContext, readonly target: TopologyTarget, timeoutMs: number) {\n const start = (method: string, params: JsonValue | undefined, options?: StreamSendOpts): RawStreamingCall => {\n if (this.disposed) throw new Error(\"Topology view is closed\");\n const member = method.split(\"::\").at(-1)!;\n if (member !== \"getGraph\" && member !== \"watchGraph\") throw new Error(`Unexpected topology member: ${member}`);\n const route = target.isDefault ? member : [target.serviceId, topologyInterface.info.id, member].filter(Boolean).join(\"::\");\n const raw = context.channel.sendRequestWithStream(route, params, { ...options, interfaceHash: target.hash });\n let rejectLocal!: (error: unknown) => void;\n const result = Promise.race([raw.result, new Promise<never>((_, reject) => { rejectLocal = reject; })]);\n const call: RawStreamingCall = {\n result,\n send: value => raw.send(value),\n ping: () => raw.ping(),\n cancel: reason => raw.cancel(reason),\n dispose: reason => {\n try { raw.dispose?.(reason); }\n finally { rejectLocal(new Error(reason ?? \"Topology request disposed\")); }\n },\n };\n this.calls.add(call);\n this.pending.add(result);\n const finish = () => { this.calls.delete(call); this.pending.delete(result); };\n void result.then(finish, finish);\n return call;\n };\n const sender: IRequestSender = {\n sendRequest: (method, params, options) => start(method, params, options).result,\n sendRequestWithStream: start,\n sendNotification: async () => { throw new Error(\"Topology has no notification members\"); },\n close() {},\n };\n this.client = new TopologyClient(new LinkRpcConnection(sender), target.serviceId, timeoutMs);\n }\n\n async snapshot(): Promise<TopologyGraph> { return parse(zTopologyGraph, await this.client.getGraph()); }\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n for (const call of this.calls) {\n try { call.cancel(\"topology view closed\"); } catch { /* The underlying connection may already be closed. */ }\n finally { call.dispose?.(\"topology view closed\"); }\n }\n }\n async waitForIdle(): Promise<void> { await Promise.allSettled([...this.pending]); }\n}\n\nexport class TopologyObservation {\n private readonly reader: TopologyReader;\n private readonly watch: TopologyWatch;\n private readonly requests = new Set<Promise<void>>();\n private stopping = false;\n private cancellation: Promise<void> | undefined;\n readonly done: Promise<void>;\n readonly ready: Promise<TopologyGraph>;\n\n constructor(\n context: ViewOpenContext, target: TopologyTarget, timeoutMs: number,\n private readonly callbacks: { onGraph(graph: TopologyGraph): void; onError(error: unknown): void; onEnd(): void },\n ) {\n this.reader = new TopologyReader(context, target, timeoutMs);\n this.watch = this.reader.client.watch({\n onGraph: graph => this.accept(graph),\n onError: error => { if (!this.stopping) callbacks.onError(error); },\n });\n this.ready = this.watch.ready;\n void this.ready.catch(() => {});\n this.done = this.watch.done.then(\n () => { if (!this.stopping) callbacks.onEnd(); },\n error => { if (!this.stopping) { callbacks.onError(error); callbacks.onEnd(); } },\n );\n }\n private accept(graph: TopologyGraph): void {\n if (!this.stopping) this.callbacks.onGraph(parse(zTopologyGraph, graph));\n }\n refresh(): Promise<void> {\n if (this.stopping) return Promise.resolve();\n const request = this.reader.snapshot().then(graph => this.accept(graph)).catch(error => {\n if (!this.stopping) this.callbacks.onError(error);\n });\n this.requests.add(request);\n void request.then(() => this.requests.delete(request), () => this.requests.delete(request));\n return request;\n }\n dispose(): void {\n if (this.stopping) return;\n this.stopping = true;\n this.cancellation = this.watch.cancel(\"topology view closed\");\n void this.cancellation.catch(() => {});\n this.reader.dispose();\n }\n async disposeAsync(): Promise<void> {\n this.dispose();\n await Promise.allSettled([this.ready, this.done, this.cancellation, ...this.requests]);\n await this.reader.waitForIdle();\n }\n}\n\nexport async function readTopology(context: ViewOpenContext, target: TopologyTarget, timeoutMs: number): Promise<TopologyGraph> {\n const reader = new TopologyReader(context, target, timeoutMs);\n try { return await reader.snapshot(); }\n finally { reader.dispose(); await reader.waitForIdle(); }\n}\n\nexport async function watchTopology(\n context: ViewOpenContext, target: TopologyTarget, timeoutMs: number,\n onGraph: (graph: TopologyGraph) => void, stop: Promise<void>,\n): Promise<void> {\n let fail!: (error: unknown) => void;\n const failure = new Promise<never>((_, reject) => { fail = reject; });\n const observation = new TopologyObservation(context, target, timeoutMs, {\n onGraph,\n onError: fail,\n onEnd: () => fail(new Error(\"Topology invalidation watch ended\")),\n });\n try { await Promise.race([stop, failure]); }\n finally { await observation.disposeAsync(); }\n}\n","import React from \"react\";\nimport { Box, Text } from \"ink\";\nimport { autorun, derived, observableValue } from \"@vscode/observables\";\nimport type { ViewCommand, ViewOpenContext, ViewSession } from \"../../views/types\";\nimport { formatCommandLegend } from \"../../views/commands\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\nimport { topologyDocument } from \"./diagram\";\nimport { TopologyObservation, type TopologyTarget } from \"./model\";\n\ninterface State {\n readonly lines: readonly string[];\n readonly rows: number;\n readonly columns: number;\n readonly top: number;\n readonly left: number;\n readonly snapshots: number;\n readonly nodes: number;\n readonly links: number;\n readonly help: boolean;\n readonly helpTop: number;\n readonly refreshing: boolean;\n readonly ended: boolean;\n readonly error?: string;\n readonly disposed: boolean;\n}\n\nexport class TopologySession implements ViewSession {\n readonly element = <TopologyPanel session={this} />;\n readonly maxLegendRows = 2;\n readonly state = observableValue<State>(this, {\n lines: [], rows: 24, columns: 80, top: 0, left: 0, snapshots: 0, nodes: 0, links: 0,\n help: false, helpTop: 0, refreshing: false, ended: false, disposed: false,\n });\n private readonly observation: TopologyObservation;\n constructor(context: ViewOpenContext, readonly target: TopologyTarget, timeoutMs: number) {\n this.observation = new TopologyObservation(context, target, timeoutMs, {\n onGraph: graph => {\n const document = topologyDocument(graph);\n this.update({ lines: document.lines, snapshots: this.state.get().snapshots + 1,\n nodes: graph.nodes.length, links: graph.links.length, error: undefined });\n },\n onError: error => this.update({ error: String(error) }),\n onEnd: () => this.update({ ended: true, error: this.state.get().error ?? \"Topology invalidation watch ended\" }),\n });\n }\n private update(patch: Partial<State>): void {\n const state = this.state.get();\n if (!state.disposed) this.state.set({ ...state, ...patch }, undefined);\n }\n setViewport(rows: number, columns = this.state.get().columns): void {\n const state = this.state.get();\n if (state.rows !== rows || state.columns !== columns) this.update({ rows, columns });\n }\n captureState(): unknown { const { top, left } = this.state.get(); return { top, left }; }\n restoreState(value: unknown): void {\n const state = value as { top?: number; left?: number } | undefined;\n if (state) this.update({ top: Math.max(0, Number(state.top) || 0), left: Math.max(0, Number(state.left) || 0) });\n }\n readonly commands = derived(this, (reader): readonly ViewCommand[] => {\n const state = this.state.read(reader);\n if (state.disposed) return [];\n const lines = this.content(state);\n const page = Math.max(1, state.rows - 2);\n const maxTop = Math.max(0, lines.length - page);\n const maxLeft = Math.max(0, lines.reduce((length, line) => Math.max(length, [...line].length), 0) - 1);\n const top = Math.min(state.help ? state.helpTop : state.top, maxTop);\n const left = state.help ? 0 : Math.min(state.left, maxLeft);\n const move = (vertical: number, horizontal = 0) => {\n const next = Math.max(0, Math.min(maxTop, top + vertical));\n this.update(state.help ? { helpTop: next } : { top: next, left: Math.max(0, Math.min(maxLeft, left + horizontal)) });\n };\n const command = (id: string, title: string, keys: readonly string[], execute: () => void, enabled = true): ViewCommand => ({\n id: `topology.${id}`, title, context: state.help ? \"Topology commands\" : \"Topology\",\n keybindings: keys.map(key => ({ key })), execute, enabled,\n });\n return [\n command(\"help\", state.help ? \"Close commands\" : \"Show commands\", [\"?\"], () => this.update({ help: !state.help, helpTop: 0 })),\n command(\"refresh\", \"Refresh snapshot\", [\"r\"], () => {\n this.update({ refreshing: true });\n void this.observation.refresh().finally(() => this.update({ refreshing: false }));\n }, !state.refreshing),\n command(\"up\", \"Scroll up\", [\"up\", \"k\"], () => move(-1), top > 0),\n command(\"down\", \"Scroll down\", [\"down\", \"j\"], () => move(1), top < maxTop),\n command(\"pageUp\", \"Page up\", [\"pageup\"], () => move(-page), top > 0),\n command(\"pageDown\", \"Page down\", [\"pagedown\"], () => move(page), top < maxTop),\n command(\"first\", \"First line\", [\"home\", \"g\"], () => move(-maxTop), top > 0),\n command(\"last\", \"Last line\", [\"end\", \"G\"], () => move(maxTop), top < maxTop),\n command(\"left\", \"Scroll left\", [\"left\", \"h\"], () => move(0, -8), !state.help && left > 0),\n command(\"right\", \"Scroll right\", [\"right\", \"l\"], () => move(0, 8), !state.help && left < maxLeft),\n command(\"pageLeft\", \"Page left\", [\"[\"], () => move(0, -state.columns), !state.help && left > 0),\n command(\"pageRight\", \"Page right\", [\"]\"], () => move(0, state.columns), !state.help && left < maxLeft),\n ];\n });\n\n private content(state: State): readonly string[] {\n // A fixed count breaks the dependency cycle between help scrolling and the\n // command list; actual help text is generated from that list in render().\n if (state.help) return Array.from({ length: 13 }, () => \"\");\n return state.lines.length ? state.lines : [state.error ? `Fetch/watch failed: ${state.error}` : \"Loading topology…\"];\n }\n displayLines(): readonly string[] {\n const state = this.state.get();\n if (!state.help) return this.content(state);\n return [\"TOPOLOGY COMMANDS (unavailable commands are marked)\", ...this.commands.get().map(command =>\n formatCommandLegend([{ ...command, enabled: true }]) + (command.enabled === false ? \" [unavailable]\" : \"\"))];\n }\n dispose(): void {\n if (this.state.get().disposed) return;\n this.state.set({ ...this.state.get(), disposed: true }, undefined);\n this.observation.dispose();\n }\n async disposeAsync(): Promise<void> { this.dispose(); await this.observation.disposeAsync(); }\n}\n\nexport class TopologyPanel extends React.Component<{ readonly session: TopologySession }, { revision: number }> {\n state = { revision: 0 };\n private subscription: { dispose(): void } | undefined;\n componentDidMount(): void {\n this.subscription = autorun(reader => {\n this.props.session.state.read(reader);\n this.setState(value => ({ revision: value.revision + 1 }));\n });\n }\n componentWillUnmount(): void { this.subscription?.dispose(); }\n render(): React.ReactNode {\n const { session } = this.props;\n const state = session.state.get();\n const lines = session.displayLines();\n const capacity = Math.max(1, state.rows - 2);\n const top = Math.min(state.help ? state.helpTop : state.top, Math.max(0, lines.length - capacity));\n const maxLeft = Math.max(0, lines.reduce((length, line) => Math.max(length, [...line].length), 0) - 1);\n const left = state.help ? 0 : Math.min(state.left, maxLeft);\n const status = state.error ? `ERROR: ${state.error}` : state.refreshing ? \"Refreshing…\"\n : `Lines ${top + 1}–${Math.min(lines.length, top + capacity)}/${lines.length} · character ${left + 1} · ${state.nodes} nodes / ${state.links} links`;\n return <Box flexDirection=\"column\" width={state.columns} height={state.rows} flexShrink={0} overflow=\"hidden\">\n {state.rows > 1 && <Box height={1} flexShrink={0} overflow=\"hidden\">\n <Text bold color={state.error ? \"red\" : \"cyan\"} wrap=\"truncate-end\">\n {safeTerminalText(`TOPOLOGY ${state.ended ? \"STOPPED\" : \"LIVE\"} — ${session.target.serviceId || \"<root>\"} · snapshot ${state.snapshots}`)}\n </Text>\n </Box>}\n {Array.from({ length: capacity }, (_, offset) => <Box key={offset} height={1} flexShrink={0} overflow=\"hidden\">\n <Text wrap=\"truncate-end\">{[...safeTerminalText(lines[top + offset] ?? \"\")].slice(left).join(\"\") || \" \"}</Text>\n </Box>)}\n {state.rows > 2 && <Box height={1} flexShrink={0} overflow=\"hidden\">\n <Text dimColor={!state.error} color={state.error ? \"red\" : undefined} wrap=\"truncate-end\">{safeTerminalText(status)}</Text>\n </Box>}\n </Box>;\n }\n}\n","import type { ViewContribution } from \"../../views/types\";\nimport { topologyInterface } from \"@hediet/linkrpc/inspection\";\nimport { runViewTui } from \"../../views/runViewTui\";\nimport { topologyDocument, topologyJson } from \"./diagram\";\nimport { readTopology, resolveTopologyTarget, topologyTimeout, watchTopology } from \"./model\";\nimport { TopologySession } from \"./session\";\n\nexport const topologyView: ViewContribution = {\n id: \"topology\", title: \"Topology\", modes: [\"cli\", \"tui\"],\n conditions: [\n { kind: \"interface\", interface: { interfaceId: topologyInterface.info.id } },\n { kind: \"service\", implements: { interfaceId: topologyInterface.info.id } },\n ],\n configureCommand(command) {\n command.option(\"--mode <mode>\", \"snapshot or watch (watch --json emits complete snapshots as JSONL)\", \"snapshot\");\n },\n async open(context, options) {\n const target = resolveTopologyTarget(context);\n const timeoutMs = topologyTimeout(options);\n const mode = options.mode ?? \"snapshot\";\n if (mode !== \"snapshot\" && mode !== \"watch\") throw new Error(\"--mode must be snapshot or watch\");\n if (options.interface !== undefined && options.interface !== topologyInterface.info.id) throw new Error(\"Topology requires hubrpc.topology\");\n if (options.tui === true) {\n if (options.json === true || mode !== \"snapshot\") throw new Error(\"--tui cannot be combined with --json or --mode watch\");\n await runViewTui(new TopologySession(context, target, timeoutMs));\n return \"\";\n }\n if (mode === \"snapshot\") {\n const graph = await readTopology(context, target, timeoutMs);\n return options.json ? topologyJson(graph, 2) : topologyDocument(graph).lines.join(\"\\n\");\n }\n let release!: () => void;\n const stop = options.stop as Promise<void> | undefined ?? new Promise<void>(resolve => { release = resolve; });\n const onStop = () => release?.();\n const emit = options.emit as ((text: string) => void) | undefined ?? (text => process.stdout.write(`${text}\\n`));\n process.once(\"SIGINT\", onStop);\n process.once(\"SIGTERM\", onStop);\n try {\n await watchTopology(context, target, timeoutMs,\n graph => emit(options.json ? topologyJson(graph) : topologyDocument(graph).lines.join(\"\\n\")), stop);\n return \"\";\n } finally {\n process.off(\"SIGINT\", onStop);\n process.off(\"SIGTERM\", onStop);\n }\n },\n createSession(context) { return new TopologySession(context, resolveTopologyTarget(context), topologyTimeout({})); },\n};\n","import { graphView } from \"../infra/graph/contribution\";\nimport { loggingView } from \"../infra/logging/contribution\";\nimport { topologyView } from \"../infra/topology/contribution\";\nimport type { ViewContribution } from \"./types\";\n\nexport const views: readonly ViewContribution[] = [graphView, loggingView, topologyView];\n\nexport function getView(id: string): ViewContribution {\n const view = views.find(value => value.id === id);\n if (!view) throw new Error(`Unknown view \"${id}\". Run view list.`);\n return view;\n}\n","import type { Command } from \"commander\";\nimport type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { discoverViewTargets, resolveViewSelection } from \"../views/discovery\";\nimport { getView, views } from \"../views/registry\";\nimport { formatCondition } from \"../views/types\";\n\nexport function viewList(json = false): string {\n const rows = views.map(view => ({\n id: view.id, title: view.title, modes: view.modes,\n conditions: view.conditions.map(formatCondition),\n }));\n return json ? JSON.stringify(rows, null, 2)\n : [\"VIEW MODES TARGET CONDITIONS\", ...rows.map(row => `${row.id} ${row.modes.join(\",\")} ${row.conditions.join(\" | \")}`)].join(\"\\n\");\n}\n\nexport function registerViewCommands(\n program: Command,\n withChannel: (action: (channel: CliChannel) => Promise<void>) => Promise<void>,\n emit: (text: string) => void = text => { if (text) process.stdout.write(`${text}\\n`); },\n): void {\n const command = program.command(\"view\").description(\"Discover and open compiled-in interface and service views\");\n command.command(\"list\").description(\"List views, modes, and target conditions without connecting\")\n .option(\"--json\", \"JSON output\")\n .action(options => { emit(viewList(options.json)); });\n command.command(\"targets <view>\").description(\"List matching stable targets (no graph watches or object loads)\")\n .option(\"--json\", \"JSON output\")\n .option(\"--max-depth <number>\", \"directory recursion bound\", nonNegativeInteger)\n .option(\"--timeout-ms <number>\", \"reflection deadline in milliseconds\", positiveInteger)\n .action(async (id: string, options) => {\n const view = getView(id);\n await withChannel(async channel => {\n const discovery = await discoverViewTargets(channel, view, options);\n emit(options.json ? JSON.stringify(discovery, null, 2)\n : [\"TARGET KIND SERVICE INTERFACE\",\n ...discovery.targets.map(target => `${target.id} ${target.kind} ${target.serviceId || \"<root>\"} ${target.interfaceId ?? \"*\"}`),\n ...discovery.warnings.map(warning => `warning: ${warning}`)].join(\"\\n\"));\n });\n });\n const open = command.command(\"open\").description(\"Open a view; default is noninteractive, --tui is explicit\");\n for (const view of views) {\n const child = open.command(view.id).description(view.title)\n .option(\"--target <id>\", \"stable ID from view targets (otherwise resolve exact selectors on this connection)\")\n .option(\"--interface <id>\", \"exact interface ID; must uniquely resolve without --target\")\n .option(\"--service <id>\", \"exact service route; narrows --interface or selects a service target\")\n .option(\"--json\", \"JSON snapshot / JSONL watch output\")\n .option(\"--tui\", \"interactive terminal renderer\")\n .option(\"--max-depth <number>\", \"directory recursion bound\", nonNegativeInteger)\n .option(\"--timeout-ms <number>\", \"reflection and graph call deadline\", positiveInteger);\n view.configureCommand(child);\n child.action(async options => {\n if (options.target === undefined && options.interface === undefined && options.service === undefined) {\n throw new Error(\"Specify --target, or an exact --interface / --service selector\");\n }\n await withChannel(async channel => {\n const context = await resolveViewSelection(channel, view, options);\n emit(await view.open(context, options));\n });\n });\n }\n}\n\nfunction nonNegativeInteger(value: string): number {\n const result = Number(value);\n if (!Number.isSafeInteger(result) || result < 0) throw new Error(\"Expected a non-negative integer\");\n return result;\n}\nfunction positiveInteger(value: string): number {\n const result = nonNegativeInteger(value);\n if (result === 0) throw new Error(\"Expected a positive integer\");\n return result;\n}\n","import { Command, InvalidArgumentError, Option } from 'commander';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { managedEndpointsInterface } from '@hediet/linkrpc-hub-daemon/client';\nimport { resolveLocalEndpoint } from './localEndpoint';\nimport { checkDaemonInterfaces, contextNamespace, registerServices, restartLocalDaemon, serviceAttachCommand, useLocalManagement } from './commands/services';\nimport { DetachKeys } from './commands/consoleSession';\nimport { attachConsole, listConsoleTargets } from './commands/consoleAttach';\nimport { bootstrapApprovalCapability } from '@hediet/linkrpc-infra/approval';\nimport { LinkRpcConnection, type JsonValue } from '@hediet/linkrpc';\nimport { connectNdjson, formatEndpointUri, isHubEndpoint, parseEndpointUri } from '@hediet/linkrpc/node';\nimport { connectionTokenBinderInterface } from '@hediet/linkrpc-hub/hub/server/connection-token-binder';\nimport { tapTransport } from '@hediet/linkrpc-hub/hub/server/transit';\nimport { callCommand, notifyCommand } from './commands/call';\nimport { listCaps } from './commands/caps';\nimport { executeBatch, parseBatchArgs } from './commands/batch';\nimport {\n disconnectBroker,\n getBrokerStatus,\n stopConnectionBroker,\n readBrokerNotifications,\n} from './commands/connectionBrokerClient';\nimport {\n runConnectionBroker,\n spawnConnectionBroker,\n} from './commands/connectionBrokerProcess';\nimport { parseDuration, parseConnectionLimit, parseConnectionLimitMilliseconds, type ConnectionLimit } from './duration';\nimport { checkCompatCommand, formatVerdict } from './commands/checkCompat';\nimport { codegenCommand } from './commands/codegen';\nimport { exportContractCommand } from './commands/contract';\nimport { completionsCommand } from './commands/completions';\nimport { defaultsCommand } from './commands/defaults';\nimport { hashCommand } from './commands/hash';\nimport { internalCompleteCommand } from './commands/internalComplete';\nimport { lsCommand, requestDirectoryAccess } from './commands/ls';\nimport { topologyCommand, type TopologyFormat } from './commands/topology';\nimport { pingCommand } from './commands/ping';\nimport {\n topologyParticipantsCommand,\n trafficWatchCommand,\n} from './commands/participantWatch';\nimport { schemaCommand } from './commands/schema';\nimport { loadHubConfig, printHubConfigSchema, serveCommand } from './commands/serve';\nimport { proxyCommand, tunnelCommand } from './commands/tunnel';\nimport { connectAs } from './commands/connectAs';\nimport { openDialTransport, openTargetTransport, type DialEndpoint } from './commands/connectAsTransports';\nimport { mcpForwardCommand } from './commands/mcpForward';\nimport { jsonRpcStdioCommand } from './commands/jsonRpcStdio';\nimport { jsonRpcExportCommand, JsonRpcExportRoutes } from './commands/jsonRpcExport';\nimport { validateJsonRpcExport } from '@hediet/linkrpc-infra/json-rpc/node';\nimport {\n createHubApprovalCommandClient,\n formatApprovalDecision,\n formatApprovalRequests,\n type ApprovalCommandClient,\n} from './commands/approval';\nimport { cliIdentity, formatCliIdentity } from './commands/identity';\nimport {\n connect as connectEndpoint,\n connectViaRootOverlay,\n connectViaTransport,\n type CliConnection,\n type ConnectLogOptions,\n} from '@hediet/linkrpc-client-internal';\nimport { type HubConfig } from '@hediet/linkrpc-client-internal';\nimport { runHub, type RunningHub } from './engine/runHub';\nimport {\n type ResolvedEndpoint,\n resolveTargetEndpoint,\n resolvedEndpointToConfig,\n} from '@hediet/linkrpc-client-internal';\nimport {\n type SigningSession,\n setupSigning,\n requestReflectionAccess,\n requestTopologyAccess,\n} from '@hediet/linkrpc-client-internal';\nimport { logoutCliIdentity } from '@hediet/linkrpc-client-internal';\nimport { MethodRefWithOptHash } from './methodRef';\nimport { renderMethodParamHelp } from './methodHelp';\nimport { rewriteParamShortcuts } from './paramFlags';\nimport { formatPrincipalSource, parsePrincipalSpec, type PrincipalSpec } from '@hediet/linkrpc-client-internal';\nimport { findMethodInSchema } from '@hediet/linkrpc-client-internal';\nimport { fetchSchemaForMethodRef } from './schemaLookup';\nimport {\n loadStaticHubSchema,\n resolveStaticHubSchemaSource,\n} from './staticHubSchema';\nimport {\n ContextStore,\n type ContextReference,\n type ContextValues,\n type SelectedContext,\n type StoredContext,\n type ValidationMode,\n formatContextReference,\n} from './contexts';\nimport {\n type CliProfile,\n type ResolvedInvocationContext,\n resolveInvocationContext,\n resolveInvocationEndpoint,\n validationDefault,\n resolveSigning,\n} from './invocationContext';\nimport { resolveCliInvocation } from './cliInvocation';\nimport { withStaticHubReflection } from './commands/staticHubReflection';\nimport { registerViewCommands } from './commands/view';\n\nexport async function main(\n rawArgv: readonly string[],\n executableName: 'linkrpc' | 'rpc' | 'hub' = 'linkrpc',\n): Promise<void> {\n const cliInvocation = resolveCliInvocation(rawArgv, executableName);\n const profile = cliInvocation.profile;\n const program = new Command();\n program.configureHelp({ showGlobalOptions: true });\n program\n .name(cliInvocation.programName)\n .description(\n profile === 'hub'\n ? 'CLI / TUI for LinkRPC hubs. Shared RPC commands use hub initialization, signing, '\n + 'capability negotiation, and required schema validation by default.'\n : 'CLI / TUI for JSON-RPC and LinkRPC endpoints. Shared commands use the RPC profile '\n + 'with automatic schema validation and no endpoint environment override by default.',\n )\n .option(\n '--endpoint <uri>',\n 'endpoint URI (linkrpc:local, unix:/path?token=…, npipe://./pipe/…, ws[s]://host?token=…, ' +\n 'ws-no-init://host?…, ' +\n 'cmd:?command=… or cmd-stdio:?command=…)',\n )\n .option('--endpoint-cmd <command>', 'spawn a server, connect via an injected env socket')\n .option('--endpoint-cmd-stdio <command>', 'spawn a child and talk over its stdio')\n .option(\n '--endpoint-cmd-env <key=value>',\n 'env var for the --endpoint-cmd / --endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option(\n '--endpoint-token <token>',\n 'fill the exact token=% placeholder in --endpoint (or a context endpoint)',\n )\n .option(\n '--endpoint-cmd-cwd <dir>',\n 'working directory for the --endpoint-cmd / --endpoint-cmd-stdio child',\n )\n .option(\n '--context <selector>',\n 'use an exact folder, id:<name>, :root, or :empty context; otherwise look up from cwd',\n )\n .option(\n '--context-set',\n 'persist context-capable overrides supplied on this command to the active context',\n )\n .option(\n '--new-context <selector>',\n 'create a new context from the effective command values; fails if it already exists',\n )\n .option('--schema <path-or-url>', 'static schema catalog used for discovery and validation')\n .option('--daemon-service <id>', 'daemon management service ID on the selected Hub')\n .option('--detach-keys <keys>', \"TTY console detach sequence in Docker syntax, e.g. 'ctrl-b,d' (default) or 'ctrl-p,ctrl-q'\")\n .option(\n '--validation <mode>',\n 'schema validation mode: auto, required, or off',\n parseValidationMode,\n )\n .option('--use-env', 'allow LINKRPC_* / legacy HUBRPC_* endpoint variables to override context')\n .option('--no-use-env', 'ignore LINKRPC_* / legacy HUBRPC_* endpoint variables')\n .option('--sign', 'enable Hub signing and stored capabilities (Hub profile default)')\n .option('--no-sign', 'disable Hub signing and stored capabilities (RPC profile default)')\n .option(\n '--provision-identity',\n 'with --endpoint-cmd: provision & reuse a persistent identity (slot derived from cwd + command)',\n )\n .option(\n '--provision-identity-slot <slot>',\n 'with --endpoint-cmd: provision & reuse a persistent identity under this explicit slot id',\n )\n .option(\n '--principal <spec>',\n 'identity to sign calls with: \"managed\" (default, falls back to user:hubrpc-cli), ' +\n '\"user:<id>\" (per-user data dir), or \"file:<path>\"',\n (v) => {\n try {\n parsePrincipalSpec(v);\n } catch (e) {\n throw new InvalidArgumentError((e as Error).message);\n }\n return v;\n },\n )\n .option(\n '--log-messages',\n profile === 'hub'\n ? 'log every JSON-RPC message to stderr, one coalesced flow per line (like the ' +\n 'VS Code \"linkrpc Flows\" channel). For `serve` / `-c, --config` this is the ' +\n 'in-process hub\\'s routed traffic; for a direct `--endpoint` connection it taps ' +\n 'the client transport. Ignored by `ui`.'\n : 'log every JSON-RPC message on a direct endpoint connection to stderr, one ' +\n 'coalesced flow per line (like the VS Code \"linkrpc Flows\" channel). Ignored by `ui`.',\n )\n .option(\n '--log-transport',\n 'log every raw JSON-RPC message sent and received to stderr, including transport initialization; '\n + 'may expose tokens and other sensitive payloads',\n )\n .showHelpAfterError();\n if (profile === 'hub') {\n program.option(\n '-c, --config <file>',\n 'run an in-process hub from this declarative config file and target it (see `serve --print-schema`)',\n );\n }\n /** Parse the effective context/flag principal once the pre-action hook has resolved it. */\n const getPrincipalSpec = (): PrincipalSpec =>\n parsePrincipalSpec(g_invocation?.values.principal);\n\n // Resolved once per command after inherited options, context defaults, and\n // the profile-specific environment policy have been merged.\n let endpoint: ResolvedEndpoint | undefined;\n let pendingContextSet:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n readonly values: ContextValues;\n }\n | undefined;\n let pendingNewContext:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n readonly values: ContextValues;\n }\n | undefined;\n let preparedNewContext:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n }\n | undefined;\n /** Create a context from the effective values, then make it the selected context of this invocation. */\n const createAndSelectContext = async (reference: Exclude<ContextReference, { readonly kind: 'empty'; }>) => {\n if (g_contextStore === undefined || g_invocation === undefined) throw new Error('context resolver is unavailable');\n await createContextFromInvocation(g_contextStore, reference, g_invocation.values);\n const useEnvironment = explicitOption<boolean>(program, 'useEnv');\n g_invocation = await resolveInvocationContext({\n profile, store: g_contextStore, selector: formatContextReference(reference),\n cliOverrides: g_invocation.cliOverrides, ...(useEnvironment !== undefined ? { useEnvironment } : {}),\n });\n };\n program.hook('preAction', async (_thisCommand, actionCommand) => {\n const commandPath = getCommandPath(actionCommand);\n const store = new ContextStore();\n const cliOverrides = collectContextOverrides(program, actionCommand);\n const selector = explicitOption<string>(program, 'context');\n const useEnvironment = explicitOption<boolean>(program, 'useEnv');\n g_contextStore = store;\n g_invocation = await resolveInvocationContext({\n profile,\n store,\n ...(selector !== undefined ? { selector } : {}),\n cliOverrides,\n ...(useEnvironment !== undefined ? { useEnvironment } : {}),\n });\n if (profile === 'rpc' && g_invocation.values.config !== undefined) {\n throw new Error('--config is only available in the hub profile');\n }\n\n if (program.opts().contextSet === true) {\n if (program.opts().newContext !== undefined) {\n throw new Error('--context-set cannot be combined with --new-context');\n }\n if (Object.keys(cliOverrides).length === 0) {\n throw new Error('--context-set requires at least one context-capable override');\n }\n assertExplicitRootMutation(g_invocation.selected);\n if (g_invocation.selected.context === undefined) {\n throw new Error('No context exists to update. Use --new-context . to create one.');\n }\n pendingContextSet = {\n store,\n reference: mutableReference(g_invocation.selected.reference),\n values: cliOverrides,\n };\n }\n\n if (program.opts().newContext !== undefined) {\n const reference = mutableReference(\n await store.resolveReference(program.opts().newContext as string),\n );\n await store.assertCanCreate(reference);\n preparedNewContext = { store, reference };\n }\n if (preparedNewContext !== undefined && commandPath !== 'connection create') {\n pendingNewContext = {\n store,\n reference: preparedNewContext.reference,\n values: g_invocation.values,\n };\n }\n if (commandPath.startsWith('services ') && preparedNewContext !== undefined) {\n await createContextFromInvocation(preparedNewContext.store, preparedNewContext.reference, g_invocation.values);\n pendingNewContext = undefined;\n }\n if ((commandPath === 'context' || commandPath === 'context show') && preparedNewContext !== undefined) {\n // Create first, so that the command shows the new context rather than the one it was derived from.\n await createAndSelectContext(preparedNewContext.reference);\n pendingNewContext = undefined;\n }\n\n endpoint = commandUsesEndpoint(commandPath) || hasEndpointOverrides(cliOverrides)\n ? resolveInvocationEndpoint(g_invocation, actionCommand.name() === 'tunnel')\n : undefined;\n g_hubConfigPath = g_invocation.values.config;\n // Message logging goes to stderr, which would corrupt the full-screen\n // TUI — so it applies to every command except `ui`.\n g_logMessages = program.opts().logMessages === true\n && actionCommand.name() !== 'ui';\n g_logTransport = program.opts().logTransport === true\n && actionCommand.name() !== 'ui';\n });\n program.hook('postAction', async () => {\n if (pendingContextSet !== undefined) {\n await pendingContextSet.store.set(\n pendingContextSet.reference,\n pendingContextSet.values,\n );\n process.stderr.write(\n `linkrpc: updated context ${formatContextReference(pendingContextSet.reference)}.\\n`,\n );\n pendingContextSet = undefined;\n }\n if (pendingNewContext !== undefined) {\n await createContextFromInvocation(\n pendingNewContext.store,\n pendingNewContext.reference,\n pendingNewContext.values,\n );\n pendingNewContext = undefined;\n }\n });\n\n if (profile === 'hub') registerServices(program, {\n detachKeys,\n attachCommand: id => {\n if (!g_invocation) throw new Error('Context resolver is unavailable');\n const reference = preparedNewContext?.reference ?? g_invocation.selected.reference;\n return serviceAttachCommand({\n context: formatContextReference(reference),\n namespace: g_invocation.values.namespace ?? contextNamespace(reference),\n id, overrides: g_invocation.cliOverrides, useEnv: g_invocation.environmentApplied,\n });\n },\n restart: async () => {\n if (endpoint !== undefined || g_hubConfigPath !== undefined || g_invocation?.values.daemonService !== undefined) {\n throw new Error('services restart only replaces the default local daemon, not a selected Hub endpoint or routed daemon. Run `hub --context :empty --no-use-env services restart` to explicitly choose the local daemon.');\n }\n await restartLocalDaemon();\n },\n namespace: () => {\n if (!g_invocation) throw new Error('Context resolver is unavailable');\n return g_invocation.values.namespace ?? contextNamespace(preparedNewContext?.reference ?? g_invocation.selected.reference);\n },\n use: async (startLocal, action) => {\n if (endpoint === undefined && g_hubConfigPath === undefined) {\n return useLocalManagement(startLocal, action);\n }\n let result: Awaited<ReturnType<typeof action>> | undefined;\n await withChannel(endpoint, getPrincipalSpec(), async channel => {\n const connection = new LinkRpcConnection(channel);\n const serviceId = g_invocation?.values.daemonService\n ?? `${(await connection.get(hubGrantedServiceIdInterface).getHubServiceId({})).hubServiceId}/daemon`;\n await checkDaemonInterfaces(connection, serviceId);\n result = await action(connection.get(managedEndpointsInterface, { serviceId }), { local: false });\n }, { requestReflectionAccess: false, autoNegotiatePerCall: true });\n return result!;\n },\n });\n\n program\n .command('attach [serviceId]')\n .description(\n 'Attach to a console of any service implementing the `linkrpc.console.v1` interface template '\n + '(found through the `linkrpc.console` directory tag). Without a service, list available consoles. '\n + 'Pipe consoles: Ctrl+D on an empty line detaches. TTY consoles: keys go to the program; the detach '\n + 'keys (default Ctrl+B, then d) detach.',\n )\n .option('--params <json>', \"params of the console template instance, e.g. '{\\\"namespace\\\":\\\"…\\\",\\\"id\\\":\\\"main\\\"}'\", '{}')\n .option('--interface <id>', 'interface containing the console instance')\n .option('--instance <name>', 'console template instance name, when an interface has several')\n .option('--read-only', 'observe output without sending input')\n .action(async (serviceId: string | undefined, opts: { params: string; interface?: string; instance?: string; readOnly?: boolean }) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n if (serviceId === undefined) {\n process.stdout.write(`${await listConsoleTargets(channel)}\\n`);\n return;\n }\n await attachConsole(channel, {\n serviceId, params: opts.params, readOnly: opts.readOnly,\n ...(opts.interface === undefined ? {} : { interfaceId: opts.interface }),\n ...(opts.instance === undefined ? {} : { instance: opts.instance }),\n detachKeys: detachKeys(),\n reattachCommand: [cliInvocation.programName, 'attach', serviceId,\n ...(opts.params === '{}' ? [] : ['--params', `'${opts.params}'`]),\n ...(opts.instance === undefined ? [] : ['--instance', opts.instance])].join(' '),\n });\n }, { autoNegotiatePerCall: true });\n });\n\n program\n .command('ls')\n .description(\n 'List services and interfaces. Walks the bus recursively, following `hubrpc.directory` references.',\n )\n .option('--interface <id>', 'filter by interfaceId')\n .option('--interface-prefix <prefix>', 'filter by interfaceId prefix')\n .option('--service <id>', 'list a single service (no recursion)')\n .option('--service-prefix <prefix>', 'filter by serviceId prefix')\n .option('--search <regexp>', 'case-insensitive regexp over listings')\n .option('--depth <n>', 'max recursion depth (default 5)', (v) => Number.parseInt(v, 10))\n .option('--with-members', 'include request and notification members from interface schemas')\n .option('--json', 'legacy flat listing JSON; use --format json for graph state')\n .option('--format <format>', 'pretty, json, or jsonl')\n .option('--dump <file>', 'write topology and all schemas to one JSON fixture file')\n .option(\n '--dump-patches <file>',\n 'write progressive RFC 6902 operations as JSON Lines; use - for stdout',\n )\n .option('--stream', 'legacy patch-log JSONL; use --format jsonl for reconstructable graph state')\n .option('--watch', 'continue observing directory changes until interrupted')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel, session) => {\n const format = resolveGraphFormat(opts.format, {\n json: opts.json === true,\n stream: opts.stream === true,\n watch: opts.watch === true,\n });\n const legacyOutput = opts.format === undefined && opts.watch !== true;\n const out = await lsCommand(channel, {\n requestDirectoryAccess: session === undefined ? undefined : serviceId =>\n requestDirectoryAccess(session, serviceId, {\n watch: opts.watch,\n withMembers: opts.withMembers,\n dumpPath: opts.dump,\n dumpPatchesPath: opts.dumpPatches,\n }),\n log: message => { process.stderr.write(`linkrpc: ${message}\\n`); },\n interfaceId: opts.interface,\n interfacePrefix: opts.interfacePrefix,\n serviceId: opts.service,\n servicePrefix: opts.servicePrefix,\n search: opts.search,\n withMembers: !!opts.withMembers,\n json: !!opts.json,\n format: legacyOutput ? undefined : format,\n dumpPath: opts.dump,\n dumpPatchesPath: opts.dumpPatches,\n stream: !!opts.stream,\n watch: !!opts.watch,\n emitLine: (line) => { process.stdout.write(line + '\\n'); },\n emitFrame: (frame) => { repaintTerminal(frame); },\n stop: opts.watch ? _untilSignalled() : undefined,\n maxDepth: typeof opts.depth === 'number' && !Number.isNaN(opts.depth) ?\n opts.depth :\n undefined,\n });\n if (out.length > 0) process.stdout.write(out + '\\n');\n }, { requestReflectionAccess: false, autoNegotiatePerCall: false });\n });\n\n if (profile === 'hub') {\n const topology = program\n .command('topology')\n .description('Inspect and optionally watch the merged transport topology.')\n .option(\n '--source <serviceId>',\n 'topology provider serviceId; repeat for multiple fixed sources',\n collectOption,\n )\n .option('--depth <n>', 'directory discovery depth (default 5)', (v) => Number.parseInt(v, 10))\n .option('--node <nodeId>', 'filter by exact node id')\n .option('--service <serviceId>', 'filter route claims by exact service id')\n .option('--kind <kind>', 'filter nodes by hub or endpoint')\n .option('--search <regexp>', 'case-insensitive regexp over node metadata and routes')\n .option('--format <format>', 'pretty, json, or jsonl')\n .option('--json', 'alias for --format json')\n .option('--stream', 'alias for --format jsonl')\n .option('--watch', 'continue observing directory and topology changes')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const format = resolveGraphFormat(opts.format, {\n json: opts.json === true,\n stream: opts.stream === true,\n watch: opts.watch === true,\n });\n const kind = opts.kind === undefined ? undefined : String(opts.kind);\n if (kind !== undefined && kind !== 'hub' && kind !== 'endpoint') {\n throw new InvalidArgumentError(\"--kind must be 'hub' or 'endpoint'\");\n }\n const out = await topologyCommand(channel, {\n sources: opts.source,\n maxDepth: typeof opts.depth === 'number' && !Number.isNaN(opts.depth)\n ? opts.depth\n : undefined,\n nodeId: opts.node,\n serviceId: opts.service,\n kind,\n search: opts.search,\n format,\n watch: opts.watch === true,\n emitLine: (line) => { process.stdout.write(line + '\\n'); },\n emitFrame: (frame) => { repaintTerminal(frame); },\n stop: opts.watch ? _untilSignalled() : undefined,\n });\n if (out.length > 0) process.stdout.write(out + '\\n');\n }, {\n requestReflectionAccess: false,\n requestTopologyAccess: { sourceServiceIds: opts.source },\n });\n });\n\n topology\n .command('participants')\n .description('List participant nodes; --search accepts a case-insensitive regexp.')\n .option('--search <regexp>', 'full-text regexp over participant metadata and routes')\n .option('--json', 'raw JSON output')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await topologyParticipantsCommand(channel, opts.search);\n process.stdout.write(opts.json ? out + '\\n' : out + '\\n');\n }, {\n requestReflectionAccess: false,\n requestTopologyAccess: {},\n });\n });\n\n program\n .command('traffic')\n .description('Observe participant traffic.')\n .command('watch')\n .description('Watch node-wide traffic for a selected participant.')\n .option('--search <regexp>', 'participant metadata search regexp')\n .option('--node <nodeId>', 'select an exact topology node id')\n .option('--method <prefix>', 'only methods beginning with this prefix')\n .option('--payloads <bytes>', 'include payloads up to this many bytes', (v) => Number.parseInt(v, 10))\n .option('--format <format>', 'pretty, plain, or jsonl')\n .option('--resume [file]', 'restore the previous participant/filter selection')\n .action(async (opts) => {\n const format = opts.format as 'pretty' | 'plain' | 'jsonl';\n if (!['pretty', 'plain', 'jsonl'].includes(format)) {\n throw new InvalidArgumentError('--format must be pretty, plain, or jsonl');\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n await trafficWatchCommand(channel, {\n search: opts.search,\n nodeId: opts.node,\n methodPrefix: opts.method,\n payloadBytes: opts.payloads,\n format,\n resume: opts.resume,\n stop: _untilSignalled(),\n });\n }, { requestReflectionAccess: true });\n });\n }\n\n program\n .command('defaults')\n .description('Print the preset service / interface for form-1 calls.')\n .option('--json', 'raw JSON output')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await defaultsCommand(channel, { json: !!opts.json });\n process.stdout.write(out + '\\n');\n });\n });\n\n program\n .command('codegen')\n .description('Generate reusable TypeScript interfaces and bindings from an offline contract.')\n .requiredOption('--input <bundle>', 'local static hub schema bundle')\n .option('--interface <id>', 'generate only this interface (requires --name)')\n .option('--name <name>', 'single-interface exported TypeScript const name')\n .option('--names <file>', 'whole-contract JSON interfaceNames/bindingNames overrides')\n .requiredOption('--output <file>', 'generated TypeScript output file')\n .option(\n '--preserve-wire-schema',\n 'freeze the canonical input schema verbatim in the generated definition',\n )\n .option('--check', 'fail if the output is missing or stale without overwriting it')\n .action(async (opts) => {\n await codegenCommand({\n input: opts.input,\n interfaceId: opts.interface,\n name: opts.name,\n output: opts.output,\n preserveWireSchema: opts.preserveWireSchema === true,\n check: opts.check === true,\n names: opts.names,\n });\n });\n\n program.command('contract')\n .description('Export reusable static interface and binding contracts.')\n .command('export')\n .requiredOption('--output <file>', 'contract JSON destination, or - for stdout')\n .option('--service <id>', 'reflection scope (defaults to the endpoint root)')\n .option('--max-depth <depth>', 'maximum directory referral depth', (value) => {\n if (!/^\\d+$/.test(value)) throw new InvalidArgumentError('depth must be a non-negative integer');\n return Number(value);\n })\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n await exportContractCommand(channel, {\n output: opts.output,\n serviceId: opts.service,\n maxDepth: opts.maxDepth,\n });\n }, { requestReflectionAccess: true });\n });\n\n const schema = program\n .command('schema')\n .description('Inspect, hash, and compare LinkRPC interface schemas.');\n\n schema\n .command('show <interfaceRef>')\n .description('Print an interface schema. `<interfaceRef>` is `id[@hash]`.')\n .option('--method <name>', 'show only this method')\n .option('--service <id>', 'route the lookup to this service (form-3); needed behind a hub')\n .option('--json', 'raw JSON output')\n .action(async (interfaceRef: string, opts) => {\n const { id, hash } = parseInterfaceRef(interfaceRef);\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await schemaCommand(channel, {\n interfaceId: id,\n hash,\n method: opts.method,\n serviceId: opts.service,\n json: !!opts.json,\n });\n process.stdout.write(out + '\\n');\n });\n });\n\n schema\n .command('hash <schema>')\n .description('Compute the hash of a local LinkRpcInterfaceSchema JSON file.')\n .action((schemaPath: string) => {\n const out = hashCommand({ schemaPath });\n process.stdout.write(out + '\\n');\n });\n\n schema\n .command('check-compat <interfaceId> <local>')\n .description('Compare a local schema against the live interface schema.')\n .action(async (interfaceId: string, local: string) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const verdict = await checkCompatCommand(channel, { interfaceId, localPath: local });\n process.stdout.write(formatVerdict(verdict) + '\\n');\n if (verdict.kind === 'incompatible') process.exitCode = 1;\n });\n });\n\n /**\n * Render `commander`'s static help for the given command, then (if a\n * methodRef is provided and an endpoint is reachable) fetch the live\n * schema and append a \"Method parameters\" block describing the\n * supported `--p:<name>` shortcuts.\n *\n * Best-effort: schema fetch failures degrade to static help with an\n * inline note instead of erroring out.\n */\n const _printCallHelp = async (cmd: Command, methodRef: string): Promise<void> => {\n process.stdout.write(cmd.helpInformation());\n if (methodRef.length === 0) {\n process.stdout.write(\n '\\n(Pass a methodRef to see method-specific --p:<name> flags, e.g.\\n'\n + ' hub call acme.email::send --help)\\n',\n );\n return;\n }\n if (endpoint === undefined) {\n process.stdout.write(\n '\\n(No endpoint configured: pass --endpoint / --endpoint-cmd or set LINKRPC_ENDPOINT\\n'\n + 'to see method-specific --p:<name> flags here.)\\n',\n );\n return;\n }\n let ref: MethodRefWithOptHash;\n try {\n ref = MethodRefWithOptHash.parseMethodRef(methodRef);\n } catch (e) {\n process.stdout.write(`\\n(Could not parse method reference: ${(e as Error).message})\\n`);\n return;\n }\n try {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const schema = await fetchSchemaForMethodRef(channel, ref);\n if (schema === undefined) {\n process.stdout.write(\n '\\n(Bare-method refs (form 1) need a preset interface to look up the schema.)\\n',\n );\n return;\n }\n const method = findMethodInSchema(schema, ref.methodName);\n if (method === undefined) {\n process.stdout.write(\n `\\n(Method \"${ref.methodName}\" not found on interface ${schema.id}@${schema.hash}.)\\n`,\n );\n return;\n }\n const rendered = renderMethodParamHelp(method, schema);\n if (rendered.text.length > 0) {\n process.stdout.write('\\n' + rendered.text);\n }\n }, { requestReflectionAccess: false, autoNegotiatePerCall: false });\n } catch (e) {\n process.stdout.write(`\\n(Could not fetch method schema: ${(e as Error).message})\\n`);\n }\n };\n\n const call = program.command('call [methodRef]');\n const caps = profile === 'hub'\n ? program.command('caps').description('List stored capabilities or request access for a call.')\n : undefined;\n caps?.command('list')\n .description('List capabilities stored for the selected principal (including expired grants).')\n .option('--json', 'machine-readable JSON output')\n .action(async (opts: { json?: boolean }) => {\n await withResolvedSigning(endpoint, getPrincipalSpec(), async (_conn, session) => {\n process.stdout.write(listCaps(session, opts.json === true) + '\\n');\n });\n });\n const capsRequest = caps?.command('request [methodRef]')\n .description('Request and store a capability without invoking the method.');\n\n const addCapabilityOptions = (cmd: Command): Command => cmd\n .option('--cap:allow-param <kv...>', 'top-level key=matcher JSON (exact, enum, prefix, subsetOf, any)')\n .option('--cap:allow-prefix <prefix>', 'allow a string prefix for the immediately preceding parameter')\n .option('--cap:allow-any', 'allow any JSON value for the immediately preceding parameter')\n .option('--cap:allow-enum <json>', 'allow one value from a JSON array for the preceding parameter')\n .option('--cap:allow-subset <json>', 'allow an array of items from a JSON string array for the preceding parameter')\n .addOption(new Option('--cap:duration <duration>', 'requested grant lifetime')\n .choices(['shortLived', 'longLived', 'persistent']).default('persistent'));\n\n const configureCall = (cmd: Command, capabilityOnly: boolean): void => {\n cmd\n .description(\n (capabilityOnly ? 'Request a capability without executing a call. ' : 'Invoke a request. ')\n + '`<methodRef>` is `[svc::][iface::]method[@hash]`. '\n + 'Use `--p:<name> <value>` (or `--p:<name>=<value>`) as a shortcut for '\n + '`--param <name>=<value>`. Run `hub call <methodRef> --help` to see the '\n + 'method-specific `--p:` flags derived from the live schema.',\n )\n .option('--params <json>', 'inline params JSON, or \"-\" to read stdin')\n .option('--param <kv...>', 'param override, key=value (JSON or string)')\n .option('--no-validate', 'skip schema-based param validation')\n // Disable commander's built-in --help so we can intercept it and\n // append the dynamic \"Method parameters\" block.\n .helpOption(false)\n .option('-h, --help', 'show help (includes method params when reachable)')\n .action(async (methodRef: string | undefined, opts, cmd: Command) => {\n if (opts.help) {\n await _printCallHelp(cmd, methodRef ?? '');\n return;\n }\n if (methodRef === undefined) {\n process.stderr.write(\"linkrpc: missing required argument 'methodRef'.\\n\");\n process.stderr.write(cmd.helpInformation());\n process.exit(2);\n }\n const requestCap = opts['cap:request'] === true;\n const allowParams = opts['cap:allowParam'];\n if (!capabilityOnly && allowParams !== undefined && !requestCap) {\n throw new Error('--cap:allow-param requires --cap:request.');\n }\n if (!capabilityOnly && cmd.getOptionValueSource('cap:duration') === 'cli' && !requestCap) {\n throw new Error('--cap:duration requires --cap:request.');\n }\n resolveSigning(profile, g_invocation?.values ?? {}, capabilityOnly || requestCap);\n const validation = opts.validate === false ? 'off' : effectiveValidation(profile);\n if ((capabilityOnly || requestCap) && validation === 'off') {\n throw new Error('Capability requests require schema validation; remove --no-validate/--validation off.');\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel, session) => {\n const out = await callCommand(channel, {\n methodRef,\n paramsArg: opts.params,\n paramOverrides: opts.param,\n validation,\n allowParams,\n requestCap,\n capabilityOnly,\n signingSession: session,\n duration: opts['cap:duration'],\n });\n process.stdout.write(out + '\\n');\n }, {\n requestReflectionAccess: (capabilityOnly || requestCap)\n && validation !== 'off',\n requireSigning: capabilityOnly || requestCap,\n autoNegotiatePerCall: false,\n });\n });\n addCapabilityOptions(cmd);\n };\n configureCall(call, false);\n call.option('--cap:request', 'ensure a stored capability covers the requested scope before calling');\n if (capsRequest !== undefined) configureCall(capsRequest, true);\n\n program\n .command('notify [methodRef]')\n .description(\n 'Fire a notification (no response). Same `--p:<name>` shortcuts as `call`.',\n )\n .option('--params <json>', 'inline params JSON, or \"-\" to read stdin')\n .option('--param <kv...>', 'param override, key=value')\n .option('--no-validate', 'skip schema-based param validation')\n .helpOption(false)\n .option('-h, --help', 'show help (includes method params when reachable)')\n .action(async (methodRef: string | undefined, opts, cmd: Command) => {\n if (opts.help) {\n await _printCallHelp(cmd, methodRef ?? '');\n return;\n }\n if (methodRef === undefined) {\n process.stderr.write(\"linkrpc: missing required argument 'methodRef'.\\n\");\n process.stderr.write(cmd.helpInformation());\n process.exit(2);\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const validation = opts.validate === false\n ? 'off'\n : effectiveValidation(profile);\n const out = await notifyCommand(channel, {\n methodRef,\n paramsArg: opts.params,\n paramOverrides: opts.param,\n validation,\n });\n process.stdout.write(out + '\\n');\n }, { requestReflectionAccess: effectiveValidation(profile) !== 'off' });\n });\n\n program\n .command('batch [batchArgs...]')\n .description(\n 'Run sequential calls and notifications on one connection. Start each operation with '\n + '`--call <method>` or `--notify <method>`; following `--params`, `--param`, and '\n + '`--no-validate` flags apply to that operation.',\n )\n .allowUnknownOption()\n .addHelpText('after', `\nBatch options:\n --call <method> start a request operation\n --notify <method> start a notification operation\n --params <json> set inline JSON params for the preceding operation\n --param <key=value> add a param override to the preceding operation (repeatable)\n --no-validate skip validation for the preceding operation\n --continue-on-error record an error and continue with later operations\n`)\n .action(async (batchArgs: string[]) => {\n const plan = parseBatchArgs(batchArgs);\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const results = await executeBatch(plan, {\n call: (options) => callCommand(channel, options),\n notify: (options) => notifyCommand(channel, options),\n }, {\n validation: effectiveValidation(profile),\n onStreamChunk: ({ index, method, payload }) => {\n const text = typeof payload === 'string'\n ? payload\n : JSON.stringify(payload);\n process.stderr.write(`[${index + 1} ${method}] ${text}\\n`);\n },\n });\n process.stdout.write(JSON.stringify(results, undefined, 2) + '\\n');\n }, {\n requestReflectionAccess: effectiveValidation(profile) !== 'off'\n && plan.operations.some((operation) => !operation.noValidate),\n });\n });\n\n const connection = program\n .command('connection')\n .description('Create, inspect, consume, and destroy persistent RPC connections.');\n\n connection\n .command('create')\n .description('Create a detached persistent connection and print its local endpoint.')\n .option('--timeout <duration>', 'transport inactivity limit (duration or inf; omitted: inf)')\n .option('--ttl <duration>', 'hard lifetime limit (duration or inf; omitted: inf)')\n .option(\n '--notification-limit <count>',\n 'maximum buffered incoming notifications',\n (value) => parsePositiveInteger(value, '--notification-limit'),\n )\n .action(async (opts: {\n timeout?: string;\n ttl?: string;\n notificationLimit?: number;\n }) => {\n if (opts.timeout === undefined && opts.ttl === undefined) {\n throw new Error('connection create requires an explicit --timeout or --ttl (use inf for unlimited)');\n }\n if (g_hubConfigPath !== undefined) {\n throw new Error('connection create does not support --config; use an endpoint URI or command endpoint');\n }\n const schemaSource = g_invocation?.values.schema === undefined\n ? undefined\n : resolveStaticHubSchemaSource(g_invocation.values.schema);\n if (schemaSource !== undefined) {\n await loadStaticHubSchema(schemaSource);\n }\n const timeout = opts.timeout ?? 'inf';\n const ttl = opts.ttl ?? 'inf';\n const notificationLimit = opts.notificationLimit\n ?? g_invocation?.values.notificationLimit\n ?? 1_000;\n const brokerEndpoint = await spawnConnectionBroker({\n remote: needEndpoint(endpoint),\n timeoutMs: parseConnectionLimit(timeout),\n ttlMs: parseConnectionLimit(ttl),\n notificationLimit,\n schemaSource,\n });\n if (preparedNewContext !== undefined) {\n if (g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n try {\n await createConnectionContext(\n preparedNewContext.store,\n preparedNewContext.reference,\n g_invocation.values,\n brokerEndpoint,\n );\n } catch (error) {\n try {\n await stopConnectionBroker(brokerEndpoint);\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n 'failed to create the context and stop the new connection broker',\n );\n }\n throw error;\n }\n }\n process.stdout.write(brokerEndpoint + '\\n');\n });\n\n connection\n .command('status')\n .description('Read status from the connection broker at the configured endpoint.')\n .action(async () => {\n await withRawConnection(endpoint, async (channel) => {\n process.stdout.write(JSON.stringify(await getBrokerStatus(channel), undefined, 2) + '\\n');\n });\n });\n\n connection\n .command('destroy')\n .description('Stop the connection broker at the configured endpoint.')\n .action(async () => {\n await withRawConnection(endpoint, async (channel) => {\n await disconnectBroker(channel);\n });\n });\n\n connection\n .command('notifications')\n .description(\n 'Read server notifications buffered by the persistent connection; --follow emits JSON Lines.',\n )\n .option('--after <sequence>', 'read notifications after this sequence', (value) =>\n parseNonNegativeInteger(value, '--after'), 0)\n .option('--wait <duration>', 'wait for a notification before returning')\n .option('--follow', 'continue waiting and print notifications as JSON lines')\n .action(async (opts: { after: number; wait?: string; follow?: boolean; }) => {\n const waitMs = opts.wait === undefined\n ? (opts.follow ? 25_000 : 0)\n : Math.min(parseDuration(opts.wait), 30_000);\n await withRawConnection(endpoint, async (channel) => {\n let after = opts.after;\n do {\n const batch = await readBrokerNotifications(channel, { after, waitMs });\n if (opts.follow) {\n for (const notification of batch.notifications) {\n process.stdout.write(JSON.stringify(notification) + '\\n');\n }\n } else {\n process.stdout.write(JSON.stringify(batch, undefined, 2) + '\\n');\n }\n after = batch.next;\n } while (opts.follow);\n });\n });\n\n const context = program\n .command('context')\n .description('Show how the active context resolves, or explicitly modify shared context defaults.')\n .action(() => {\n printSelectedContext(true);\n });\n\n context\n .command('show')\n .description('Show only the selected context and its stored defaults.')\n .action(() => {\n printSelectedContext(false);\n });\n\n context\n .command('create <selector>')\n .description('Create a context (a folder, id:<name>) from the effective values, including flags on this command; same as hub context --new-context <selector>.')\n .action(async (selector: string) => {\n if (g_contextStore === undefined) throw new Error('context store is unavailable');\n if (preparedNewContext !== undefined) throw new Error('Use either context create <selector> or --new-context, not both');\n const reference = mutableReference(await g_contextStore.resolveReference(selector));\n await g_contextStore.assertCanCreate(reference);\n await createAndSelectContext(reference);\n printSelectedContext(false);\n });\n\n context\n .command('list')\n .description('List every path and named context in the global store, and the root context, which always exists.')\n .action(async () => {\n if (g_contextStore === undefined) throw new Error('context store is unavailable');\n const references = (await g_contextStore.list()).map(item => formatContextReference(item.reference));\n if (!references.includes(':root')) references.push(':root');\n for (const reference of references.sort()) process.stdout.write(`${reference}\\n`);\n });\n\n context\n .command('set')\n .description(\n 'Set explicit context-capable flags on an existing context, or create one with --new-context.',\n )\n .option('--unset <key...>', 'remove one or more stored context values')\n .action(async (opts: { unset?: string[] }) => {\n if (g_contextStore === undefined || g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n if (preparedNewContext !== undefined) {\n if ((opts.unset?.length ?? 0) > 0) throw new Error('--unset cannot be used with --new-context');\n return;\n }\n assertExplicitRootMutation(g_invocation.selected);\n if (g_invocation.selected.context === undefined) {\n throw new Error('No context exists to update. Use hub context set --new-context . with your desired flags.');\n }\n const target = mutableReference(g_invocation.selected.reference);\n const overrides = g_invocation.cliOverrides;\n const unset = (opts.unset ?? []).map(parseContextValueKey);\n if (Object.keys(overrides).length === 0 && unset.length === 0) {\n throw new Error('context set requires at least one context-capable flag or --unset');\n }\n let result = Object.keys(overrides).length === 0\n ? g_invocation.selected.context\n : await g_contextStore.set(target, overrides);\n if (unset.length > 0) {\n result = await g_contextStore.unset(target, unset);\n }\n process.stdout.write(`Updated context ${formatContextReference(target)}.\\n`);\n if (result !== undefined) printContextValues(result.values, false);\n });\n\n context\n .command('remove')\n .description('Stop any owned connection and remove the selected context; removing :root resets it to no defaults.')\n .action(async () => {\n if (g_contextStore === undefined || g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n const reference = g_invocation.selected.reference;\n if (\n reference.kind === 'empty'\n || (reference.kind === 'root' && explicitOption<string>(program, 'context') === undefined)\n ) {\n throw new Error('select the context to remove explicitly with --context');\n }\n const removed = await g_contextStore.remove(reference);\n if (!removed) throw new Error(`context ${formatContextReference(reference)} does not exist`);\n process.stdout.write(reference.kind === 'root'\n ? 'Reset context :root to no stored defaults (the root context always exists).\\n'\n : `Removed context ${formatContextReference(reference)}.\\n`);\n });\n\n program\n .command('_connection-broker')\n .description('(internal) Run a persistent connection broker.')\n .requiredOption('--remote-endpoint <uri>')\n .requiredOption('--timeout-ms <milliseconds-or-inf>', '', parseConnectionLimitMilliseconds)\n .requiredOption('--ttl-ms <milliseconds-or-inf>', '', parseConnectionLimitMilliseconds)\n .option('--notification-limit <count>', '', (value) =>\n parsePositiveInteger(value, '--notification-limit'), 1_000)\n .option('--schema <path-or-url>')\n .action(async (opts: {\n remoteEndpoint: string;\n timeoutMs: ConnectionLimit;\n ttlMs: ConnectionLimit;\n notificationLimit: number;\n schema?: string;\n }) => {\n const running = await runConnectionBroker({\n remote: parseEndpointUri(opts.remoteEndpoint),\n timeoutMs: opts.timeoutMs,\n ttlMs: opts.ttlMs,\n notificationLimit: opts.notificationLimit,\n ...(opts.schema === undefined\n ? {}\n : { staticHubSchema: await loadStaticHubSchema(opts.schema) }),\n });\n process.stdout.write(running.endpoint + '\\n');\n await running.stopped;\n });\n\n program\n .command('ping')\n .description('One reflection round-trip; prints latency.')\n .action(async () => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await pingCommand(channel);\n process.stdout.write(out + '\\n');\n });\n });\n if (profile === 'hub') {\n const exportRoutes = new JsonRpcExportRoutes();\n program\n .command('json-rpc-export')\n .description('Export Hub JSON-RPC services through one authenticated raw WebSocket listener.')\n .requiredOption('--target-endpoint <uri>', 'Listener URI, e.g. listen:ws://127.0.0.1:8123')\n .option('--target-token <token>', 'Local client authentication token (or put token in target URI)')\n .option('--target-token-query-param <name>', 'Accepted token query parameter (repeatable; replaces defaults tkn and token)', collectOption)\n .option('--serviceId <id>', 'Begin a route; follow each occurrence with --path', value => {\n exportRoutes.serviceId(value);\n return value;\n })\n .option('--path <path>', 'Path for the preceding service ID; repeat pairs for multiple routes', value => {\n exportRoutes.path(value);\n return value;\n })\n .action(async (opts: { targetEndpoint: string; targetToken?: string; targetTokenQueryParam?: readonly string[] }) => {\n const options = {\n targetEndpoint: opts.targetEndpoint,\n token: opts.targetToken,\n tokenQueryParameters: opts.targetTokenQueryParam,\n routes: exportRoutes.getRoutes(),\n };\n validateJsonRpcExport(options);\n const localEp = needEndpoint(endpoint);\n const local = await connectEndpoint(localEp, wireLog('hub'));\n try {\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n const server = await jsonRpcExportCommand({\n ...options,\n local,\n onError: error => process.stderr.write(`linkrpc: ${error.message}\\n`),\n });\n try {\n process.stderr.write(`linkrpc: JSON-RPC export listening at ${server.endpoint}\\n`);\n await _untilSignalled();\n } finally {\n await server.close();\n }\n } finally {\n local.close();\n }\n });\n program\n .command('json-rpc-stdio <serviceId>')\n .description(\n 'Expose <serviceId>::jsonRpcConnection::connectRaw as a newline-delimited '\n + \"JSON-RPC endpoint on this process's stdin/stdout.\",\n )\n .option('--params <json>', 'JSON value passed to the remote transport factory')\n .action(async (serviceId: string, opts: { params?: string; }) => {\n const localEp = needEndpoint(endpoint);\n let params: JsonValue | undefined;\n if (opts.params !== undefined) {\n try {\n params = JSON.parse(opts.params) as JsonValue;\n } catch (error) {\n throw new InvalidArgumentError(\n `invalid --params JSON: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n const local = await connectEndpoint(localEp, wireLog('hub'));\n try {\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n await jsonRpcStdioCommand({\n local,\n serviceId,\n ...(params === undefined ? {} : { params }),\n });\n } finally {\n local.close();\n }\n });\n\n program\n .command('serve [config]')\n .description(\n 'Run a hub from a declarative config file and block until interrupted. '\n + 'The same config format drives the CLI hub, the server hub, and the VS Code extension.',\n )\n .option('--print-schema', 'print the config JSON Schema and exit')\n .option('--cmd-interactive', 'forward stdin to the single cmd endpoint (errors if more than one)')\n .action(async (config: string | undefined, opts: { printSchema?: boolean; cmdInteractive?: boolean; }) => {\n if (opts.printSchema) {\n process.stdout.write(printHubConfigSchema() + '\\n');\n return;\n }\n if (config === undefined) {\n process.stderr.write('linkrpc: serve requires a <config> file (or --print-schema).\\n');\n process.exit(2);\n }\n await serveCommand({\n configPath: config,\n cmdInteractive: opts.cmdInteractive,\n logMessages: g_logMessages,\n });\n });\n\n addTargetEndpointOptions(program\n .command('tunnel <serviceId>')\n .description(\n 'Claim <serviceId> on the source hub (--endpoint*) and forward every request it ' +\n 'routes here to a target endpoint over a second connection. The target endpoint ' +\n 'is set via --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio; ' +\n 'when it is --target-endpoint-cmd, the spawned child sees ' +\n \"`hubGrantedServiceId::get().grantedServiceIdNamespace` = <serviceId> from its local hub, \" +\n 'and global --provision-identity[-slot] applies to it. With `-c, --config`, the ' +\n 'source hub is instead appended to the config as an endpoint claiming <serviceId>, ' +\n 'and the in-process hub serves it (the config provides the target). Runs until Ctrl-C.',\n ))\n .option(\n '--bidi',\n 'also forward every request/notification the target endpoint emits back to the ' +\n 'source hub, exposing the hub to the endpoint (forwards everything, unsigned)',\n )\n .action(async (serviceId: string, cmdOpts: TargetEndpointCliOptions & {\n bidi?: boolean;\n }) => {\n const localEp = needEndpoint(endpoint);\n\n // Config mode: append the source hub to the loaded config as an\n // endpoint claiming <serviceId>, then run that in-process hub. The\n // config itself provides the target that serves the service id, so\n // the manual two-connection forward path is not used.\n if (g_hubConfigPath !== undefined) {\n const baseConfig = loadHubConfig(g_hubConfigPath);\n const claimEndpoint = resolvedEndpointToConfig(localEp, {\n claimServiceIds: [serviceId],\n });\n const config: HubConfig = {\n ...baseConfig,\n // The in-process hub serves <serviceId> and claims it on the\n // source, so it must mount its own services under <serviceId>\n // (not the default 'hub') for the claim and routing to line up.\n hubServiceId: serviceId,\n endpoints: [...baseConfig.endpoints, claimEndpoint],\n };\n const running = await runHub({ config, logMessages: g_logMessages });\n process.stderr.write(\n `linkrpc: tunnel: claimed '${serviceId}' on source via config hub. Ctrl-C to stop.\\n`,\n );\n await new Promise<void>((resolve) => {\n const stop = (): void => {\n running.dispose();\n resolve();\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n });\n return;\n }\n\n const globalOpts = program.opts();\n const targetEp = resolveTargetEndpointOrExit(cmdOpts, globalOpts, 'tunnel');\n const local = await connectEndpoint(localEp, wireLog('source'));\n const remote = await connectTargetEndpoint(targetEp, serviceId);\n try {\n // Sign the claim where the source hub requires it (managed\n // identity with local-keypair fallback). The remote side is\n // left unsigned so requests forward verbatim.\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n // Stop when either side goes away, and exit non-zero so a\n // supervisor (e.g. the hub daemon) restarts the tunnel: a\n // claim without a live target would only time out calls.\n const lost = Promise.race([\n local.closed.then(() => 'source'),\n remote.closed.then(() => 'target'),\n ]).then((side) => {\n process.stderr.write(`linkrpc: tunnel: the ${side} connection closed\\n`);\n process.exitCode = 1;\n });\n await tunnelCommand({ serviceId, local, remote, bidi: cmdOpts.bidi, stop: Promise.race([lost, _untilSignalled()]) });\n } finally {\n remote.close();\n local.close();\n }\n });\n\n addTargetEndpointOptions(program\n .command('proxy')\n .description(\n 'Connect a participant to the hub (--endpoint*) through this process. The participant is ' +\n \"this process's stdin/stdout (--stdio) or a target endpoint (--target-endpoint*). By \" +\n 'default the proxy does not sign anything: calls the participant makes are forwarded to ' +\n 'the hub as they are (unsigned, or with the signature the participant attached). ' +\n '--sign-as re-signs them with an identity of this machine, --no-outbound drops them, and ' +\n '--claim makes the hub route a service id to the participant. ' +\n 'Runs until the participant disconnects or Ctrl-C.',\n ))\n .option('--stdio', \"use this process's stdin/stdout as the participant\")\n .option(\n '--sign-as [principal]',\n 'sign every call the participant makes as <principal> (\"managed\", \"user:<id>\" or ' +\n '\"file:<path>\"; default: --principal, i.e. the managed Hub identity falling back to ' +\n 'user:hubrpc-cli) and request capabilities for those calls, prompting for approval ' +\n 'when needed. This lends the participant that identity; use it for participants that ' +\n 'cannot sign but must call services behind forwardChecking',\n )\n .option(\n '--claim <serviceId>',\n 'register <serviceId> on the hub (this registration is signed as --principal) and ' +\n \"forward requests for it to the participant unchanged, keeping callers' signatures\",\n )\n .option('--no-outbound', 'drop calls the participant makes instead of forwarding them to the hub')\n .action(async (cmdOpts: TargetEndpointCliOptions & {\n stdio?: boolean;\n signAs?: string | true;\n claim?: string;\n outbound: boolean;\n }) => {\n const localEp = needEndpoint(endpoint);\n if (cmdOpts.stdio === hasTargetEndpoint(cmdOpts)) {\n process.stderr.write('linkrpc: proxy requires exactly one of --stdio or --target-endpoint*.\\n');\n process.exit(2);\n }\n if (g_invocation?.cliOverrides.sign === true) {\n process.stderr.write('linkrpc: proxy does not use --sign; pass --sign-as [principal] to sign participant calls.\\n');\n process.exit(2);\n }\n if (cmdOpts.signAs !== undefined && !cmdOpts.outbound) {\n process.stderr.write('linkrpc: proxy --sign-as has no effect with --no-outbound.\\n');\n process.exit(2);\n }\n const targetEp = cmdOpts.stdio\n ? undefined\n : resolveTargetEndpointOrExit(cmdOpts, program.opts(), 'proxy');\n const hub = await connectEndpoint(localEp, wireLog('hub'));\n // The proxy signs only what was asked for: participant calls with --sign-as,\n // and its own --claim registration.\n if (cmdOpts.signAs !== undefined || cmdOpts.claim !== undefined) {\n const principal = typeof cmdOpts.signAs === 'string'\n ? parsePrincipalSpec(cmdOpts.signAs)\n : getPrincipalSpec();\n reportIdentity(await setupSigning(hub.channel, hub.signing, principal, {\n negotiateHubCaps: isHubEndpoint(localEp),\n }));\n }\n // Connect the participant last: proxyCommand installs its forwarders\n // synchronously, before any message the participant sent is dispatched.\n const participant = targetEp === undefined\n ? await connectStdioParticipant()\n : await connectTargetEndpoint(targetEp, cmdOpts.claim ?? '').then((connection) => ({ connection, closed: connection.closed }));\n try {\n await proxyCommand({\n hub,\n participant: participant.connection,\n outbound: !cmdOpts.outbound ? 'none' : cmdOpts.signAs !== undefined ? 'signed' : 'verbatim',\n ...(cmdOpts.claim !== undefined ? { claimServiceId: cmdOpts.claim } : {}),\n ...(participant.closed !== undefined ? { stop: participant.closed } : {}),\n });\n } finally {\n participant.connection.close();\n hub.close();\n }\n });\n\n program\n .command('connect-as <binderServiceId> <slot>')\n .description(\n 'Mint a single-use identity token for <slot> from the <binderServiceId> ' +\n '(a service implementing connectionTokenBinder, typically the hub service id), ' +\n 'then splice a target endpoint onto the hub as a first-class participant with that ' +\n 'slot\\'s managed identity and a granted serviceId namespace (--granted-service-id, ' +\n 'defaulting to <slot>). No local hub is started: the CLI ' +\n 'proxies the connection (target ⟷ CLI ⟷ hub), so it works with every target kind and ' +\n '--log-messages taps the full flow. The hub-facing bound-token listener is ' +\n '--hub-endpoint (defaults to --endpoint when that is a ws/socket). Runs until Ctrl-C.',\n )\n .option(\n '--hub-endpoint <uri>',\n 'ws/socket bound-token listener to splice the target onto (default: --endpoint)',\n )\n .option('--target-endpoint <uri>', 'target endpoint URI (unix:/…, ws[s]://…)')\n .option('--target-endpoint-cmd <command>', 'spawn the target as a server; it dials the CLI back')\n .option('--target-endpoint-cmd-stdio <command>', 'spawn the target and talk linkrpc over its stdio')\n .option(\n '--target-endpoint-cmd-env <key=value>',\n 'env var for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option('--target-endpoint-token <token>', 'token overriding the target URI token')\n .option(\n '--target-endpoint-cmd-cwd <dir>',\n 'working directory for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child',\n )\n .option(\n '--granted-service-id <serviceId>',\n 'serviceId namespace to grant the target (default: <slot>)',\n )\n .action(async (binderServiceId: string, slot: string, cmdOpts: {\n hubEndpoint?: string;\n targetEndpoint?: string;\n targetEndpointCmd?: string;\n targetEndpointCmdStdio?: string;\n targetEndpointCmdEnv?: Record<string, string>;\n targetEndpointToken?: string;\n targetEndpointCmdCwd?: string;\n grantedServiceId?: string;\n }) => {\n const localEp = needEndpoint(endpoint);\n\n // Resolve the hub-facing (bound-token) listener the target is spliced\n // onto. Defaults to --endpoint when that is itself a dial-able ws/socket.\n let hubEp: DialEndpoint;\n try {\n hubEp = _resolveDialEndpoint(cmdOpts.hubEndpoint, localEp);\n } catch (e) {\n process.stderr.write(`linkrpc: ${(e as Error).message}\\n`);\n process.exit(2);\n }\n\n const targetRes = resolveTargetEndpoint({\n targetEndpoint: cmdOpts.targetEndpoint,\n targetEndpointCmd: cmdOpts.targetEndpointCmd,\n targetEndpointCmdStdio: cmdOpts.targetEndpointCmdStdio,\n targetEndpointCmdEnv: cmdOpts.targetEndpointCmdEnv,\n targetEndpointToken: cmdOpts.targetEndpointToken,\n targetEndpointCmdCwd: cmdOpts.targetEndpointCmdCwd,\n });\n if (targetRes.error) {\n process.stderr.write(`linkrpc: ${targetRes.error}\\n`);\n process.exit(2);\n }\n if (!targetRes.endpoint) {\n process.stderr.write(\n 'linkrpc: connect-as requires --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio.\\n',\n );\n process.exit(2);\n }\n const targetEp = targetRes.endpoint;\n\n // Broker connection: sign the mint call where the hub requires it.\n const broker = await connectEndpoint(localEp, wireLog('broker'));\n try {\n const session = await setupSigning(broker.channel, broker.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n\n const brokerConn = new LinkRpcConnection(broker.rpcChannel);\n const binder = brokerConn.service(binderServiceId).get(connectionTokenBinderInterface);\n\n const logLine = (line: string): void => { process.stderr.write(`linkrpc: ${line}\\n`); };\n const serviceIdNamespace = cmdOpts.grantedServiceId ?? slot;\n await connectAs({\n mintToken: async () => {\n const { token } = await binder.bindConnectionToken({\n identitySlot: slot,\n serviceIdNamespace,\n });\n logLine(\n `connect-as: minted token for identity slot '${slot}'` +\n `${serviceIdNamespace !== slot ? `, granted serviceId '${serviceIdNamespace}'` : ''}` +\n ` via ${binderServiceId}`,\n );\n return token;\n },\n openHubTransport: (token) => openDialTransport(hubEp, token),\n openTargetTransport: () => openTargetTransport(targetEp, logLine),\n ...(g_logMessages\n ? {\n tapTarget: (t) => tapTransport(t, {\n log: logLine,\n localLabel: 'cli',\n remoteLabel: 'target',\n }),\n }\n : {}),\n log: logLine,\n stop: _untilSignalled(),\n });\n } finally {\n broker.close();\n }\n });\n\n program\n .command('mcp-forward [mcpCommand...]')\n .description(\n 'Expose an MCP server through the hub (--endpoint*) as a transparent forwarder. ' +\n 'By default it claims this connection\\'s granted serviceId namespace; pass ' +\n '--serviceId to claim a specific prefix. The MCP server command follows `--`, e.g. ' +\n '`linkrpc mcp-forward -- npx -y @modelcontextprotocol/server-everything` or ' +\n '`linkrpc mcp-forward --serviceId my-mcp -- npx -y @modelcontextprotocol/server-everything`. ' +\n 'Each consumer that opens `<serviceId>::vscode.mcp-forward::connect` spawns a fresh child ' +\n 'and gets its MCP stdio bridged raw over the stream. Runs until Ctrl-C.',\n )\n .option(\n '--serviceId <serviceId>',\n 'serviceId prefix to claim (default: the connection\\'s granted serviceId namespace)',\n )\n .option(\n '--env <key=value>',\n 'env var for the spawned MCP server child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .action(async (mcpCommand: string[] | undefined, cmdOpts: {\n serviceId?: string;\n env?: Record<string, string>;\n }) => {\n const localEp = needEndpoint(endpoint);\n if (!mcpCommand || mcpCommand.length === 0) {\n process.stderr.write(\n 'linkrpc: mcp-forward requires an MCP server command after `--`, e.g. ' +\n '`mcp-forward -- npx -y @modelcontextprotocol/server-everything`.\\n',\n );\n process.exit(2);\n }\n const local = await connectEndpoint(localEp, wireLog('hub'));\n try {\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n await mcpForwardCommand({\n ...(cmdOpts.serviceId !== undefined ? { serviceId: cmdOpts.serviceId } : {}),\n local,\n command: { argv: mcpCommand },\n ...(cmdOpts.env !== undefined ? { env: cmdOpts.env } : {}),\n });\n } finally {\n local.close();\n }\n });\n\n program\n .command('identity')\n .description('Inspect the persistent principal used by connected CLI commands.')\n .command('show')\n .description('Print the resolved persistent CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (opts: { json?: boolean; }) => {\n await withResolvedSigning(endpoint, getPrincipalSpec(), async (_conn, session) => {\n const out = formatCliIdentity(cliIdentity(session), opts.json === true);\n process.stdout.write(out + '\\n');\n });\n });\n\n const approval = program\n .command('approval')\n .description('Inspect and decide pending Hub access approval requests.');\n\n approval\n .command('requests')\n .description('List pending requests whose capability audience is this CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (opts: { json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const out = formatApprovalRequests(\n await client.requests(),\n client.principalId,\n opts.json === true,\n );\n process.stdout.write(out + '\\n');\n });\n });\n\n approval\n .command('approve <request-id>')\n .description('Approve one pending request for this CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (requestId: string, opts: { json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const outcome = await client.approve(requestId);\n process.stdout.write(\n formatApprovalDecision(\n 'approved',\n requestId,\n client.principalId,\n opts.json === true,\n outcome,\n ) + '\\n',\n );\n });\n });\n\n approval\n .command('deny <request-id>')\n .description('Deny one pending request for this CLI identity.')\n .option('--reason <text>', 'optional denial reason')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (requestId: string, opts: { reason?: string; json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const outcome = await client.deny(requestId, opts.reason);\n process.stdout.write(\n formatApprovalDecision(\n 'denied',\n requestId,\n client.principalId,\n opts.json === true,\n outcome,\n ) + '\\n',\n );\n });\n });\n\n approval\n .command('ui')\n .description('Watch pending requests and approve or deny them interactively in the terminal.')\n .action(async () => {\n if (\n process.stdin.isTTY !== true\n || process.stdout.isTTY !== true\n || !Number.isInteger(process.stdout.columns)\n || process.stdout.columns <= 0\n || !Number.isInteger(process.stdout.rows)\n || process.stdout.rows <= 0\n ) {\n throw new Error('approval ui requires an interactive terminal with visible output');\n }\n const stop = new AbortController();\n const onSignal = () => stop.abort();\n await withApprovalClient(\n endpoint,\n getPrincipalSpec(),\n async (client) => {\n process.once('SIGINT', onSignal);\n process.once('SIGTERM', onSignal);\n try {\n const { runApprovalUi } = await import('./approval-ui/runApprovalUi');\n await runApprovalUi({ client, signal: stop.signal });\n } finally {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onSignal);\n }\n },\n () => { /* Ink owns the terminal while the approval UI is active. */ },\n );\n });\n }\n\n registerViewCommands(program, action => withChannel(endpoint, getPrincipalSpec(), action));\n\n program\n .command('ui')\n .description('Launch the terminal UI (form-based browser of services + methods).')\n .action(async () => {\n const acquired = await acquireConnection(endpoint);\n const { runUi } = await import('./ui/runUi');\n try {\n await runUi({\n endpoint: acquired.ep, principalSpec: getPrincipalSpec(), profile,\n schema: g_invocation?.values.schema === undefined ? undefined\n : await loadStaticHubSchema(g_invocation.values.schema),\n });\n } finally {\n acquired.running?.dispose();\n }\n });\n\n if (profile === 'hub') {\n program\n .command('logout')\n .description(\n 'Delete the stored CLI identity and cached capabilities. Next call will mint a fresh keypair and prompt for consent again.',\n )\n .action(async () => {\n const removed = await logoutCliIdentity();\n if (removed.length === 0) {\n process.stdout.write('linkrpc: no stored identity found.\\n');\n return;\n }\n for (const f of removed) {\n process.stdout.write(`removed ${f}\\n`);\n }\n });\n }\n\n program\n .command('completions <shell>')\n .description(\n 'Print a shell completion script. Supported: powershell. Install with ' +\n '`hub completions powershell | Out-String | Invoke-Expression` (one-shot) or ' +\n 'append to $PROFILE.',\n )\n .action((shell: string) => {\n try {\n const script = completionsCommand({ shell });\n process.stdout.write(script);\n if (!script.endsWith('\\n')) process.stdout.write('\\n');\n } catch (e) {\n process.stderr.write(`linkrpc: ${(e as Error).message}\\n`);\n process.exit(2);\n }\n });\n\n program\n .command('_complete')\n .description(\n '(internal) Emit completion candidates for a partial command line. ' +\n 'Invoked by the scripts produced by `hub completions`.',\n )\n .option('--line <line>', 'the partial command line, including the binary name')\n .option('--point <n>', 'cursor position (0-indexed) into --line', (v) => Number.parseInt(v, 10))\n .action(async (opts: { line?: string; point?: number; }) => {\n // The completer must NEVER write to stderr or non-zero-exit — that\n // would surface in the user's prompt. Always exit 0 with whatever\n // we managed to compute (possibly nothing). Force-exit at the end\n // so any open socket / setup-signing timer can't keep the process\n // alive past the action — that hangs the user's shell on TAB.\n try {\n const line = opts.line ?? '';\n const point = typeof opts.point === 'number' && !Number.isNaN(opts.point)\n ? opts.point\n : line.length;\n const out = await internalCompleteCommand({ line, point });\n if (out.length > 0) process.stdout.write(out + '\\n');\n } catch {\n // swallow\n }\n // Force-exit: completion is one-shot and must never hang.\n process.exit(0);\n });\n\n if (profile === 'rpc') {\n program\n .command('hub')\n .description('Run the same shared commands with the hub profile and expose hub-only commands.');\n }\n\n await program.parseAsync([\n 'node',\n cliInvocation.programName,\n ...rewriteParamShortcuts(cliInvocation.argv),\n ]);\n}\n\nfunction collectContextOverrides(program: Command, actionCommand: Command): ContextValues {\n const opts = program.opts();\n const result: Record<string, unknown> = {};\n copyExplicit(program, opts, result, 'endpoint');\n copyExplicit(program, opts, result, 'endpointCmd');\n copyExplicit(program, opts, result, 'endpointCmdStdio');\n copyExplicit(program, opts, result, 'endpointCmdEnv');\n copyExplicit(program, opts, result, 'endpointToken');\n copyExplicit(program, opts, result, 'endpointCmdCwd');\n copyExplicit(program, opts, result, 'config');\n copyExplicit(program, opts, result, 'provisionIdentity');\n copyExplicit(program, opts, result, 'provisionIdentitySlot');\n copyExplicit(program, opts, result, 'principal');\n copyExplicit(program, opts, result, 'sign');\n copyExplicit(program, opts, result, 'schema');\n copyExplicit(program, opts, result, 'validation');\n copyExplicit(program, opts, result, 'daemonService');\n copyExplicit(program, opts, result, 'detachKeys');\n for (let command: Command | null = actionCommand; command; command = command.parent) {\n if (command.name() === 'services') copyExplicit(command, command.opts(), result, 'namespace');\n }\n\n if (getCommandPath(actionCommand) === 'connection create') {\n const actionOpts = actionCommand.opts();\n copyExplicit(actionCommand, actionOpts, result, 'timeout', 'connectionTimeout');\n copyExplicit(actionCommand, actionOpts, result, 'ttl', 'connectionTtl');\n copyExplicit(actionCommand, actionOpts, result, 'notificationLimit');\n }\n return result as ContextValues;\n}\n\nfunction copyExplicit(\n command: Command,\n source: Record<string, unknown>,\n target: Record<string, unknown>,\n optionName: string,\n contextName = optionName,\n): void {\n if (command.getOptionValueSource(optionName) === 'cli') {\n target[contextName] = source[optionName];\n }\n}\n\nfunction explicitOption<T>(command: Command, name: string): T | undefined {\n return command.getOptionValueSource(name) === 'cli'\n ? command.opts()[name] as T\n : undefined;\n}\n\nasync function createContextFromInvocation(\n store: ContextStore,\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n values: ContextValues,\n ownedConnection?: StoredContext['ownedConnection'],\n): Promise<void> {\n await store.replace(reference, values, { createOnly: true, ownedConnection });\n process.stderr.write(`linkrpc: created context ${formatContextReference(reference)}.\\n`);\n}\n\nasync function createConnectionContext(\n store: ContextStore,\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n values: ContextValues,\n brokerEndpoint: string,\n): Promise<void> {\n const {\n endpoint: _endpoint,\n endpointCmd: _endpointCmd,\n endpointCmdStdio: _endpointCmdStdio,\n endpointCmdEnv: _endpointCmdEnv,\n endpointToken: _endpointToken,\n endpointCmdCwd: _endpointCmdCwd,\n provisionIdentity: _provisionIdentity,\n provisionIdentitySlot: _provisionIdentitySlot,\n ...rest\n } = values;\n const connectionEndpoint = splitEndpointToken(brokerEndpoint);\n await createContextFromInvocation(store, reference, {\n ...rest,\n ...connectionEndpoint,\n }, { endpoint: brokerEndpoint });\n}\n\nfunction splitEndpointToken(endpoint: string): Pick<ContextValues, 'endpoint' | 'endpointToken'> {\n const parsed = parseEndpointUri(endpoint);\n if ((parsed.kind !== 'socket' && parsed.kind !== 'ws') || parsed.token === undefined) {\n return { endpoint };\n }\n const { token, ...withoutToken } = parsed;\n const separator = formatEndpointUri(withoutToken).includes('?') ? '&' : '?';\n return {\n endpoint: `${formatEndpointUri(withoutToken)}${separator}token=%`,\n endpointToken: token,\n };\n}\n\nfunction mutableReference(\n reference: ContextReference,\n): Exclude<ContextReference, { readonly kind: 'empty'; }> {\n if (reference.kind === 'empty') {\n throw new Error(':empty is immutable and cannot be modified');\n }\n return reference;\n}\n\n/** The root context applies to every folder without a context: change it only when selected explicitly. */\nfunction assertExplicitRootMutation(selected: SelectedContext): void {\n if (selected.selectedBy === 'root') {\n throw new Error('No folder or named context applies here, so the root context is in effect. '\n + 'To change defaults for every such folder, select it explicitly with --context :root; '\n + 'to create a context for this folder, use --new-context .');\n }\n}\n\nfunction printSelectedContext(effective: boolean): void {\n if (g_invocation === undefined) throw new Error('context resolver is unavailable');\n const selected = g_invocation.selected;\n process.stdout.write('Context\\n');\n process.stdout.write(` Reference: ${formatContextReference(selected.reference)}\\n`);\n process.stdout.write(` Selected via: ${contextSelectionDescription(selected.selectedBy)}\\n`);\n if (effective) {\n process.stdout.write(` Profile: ${g_invocation.profile}\\n`);\n const environmentStatus = g_invocation.environmentApplied\n ? Object.keys(g_invocation.environmentValues).length > 0\n ? 'enabled'\n : 'enabled (no variables set)'\n : 'disabled';\n process.stdout.write(\n ` Environment overrides: ${environmentStatus}\\n`,\n );\n }\n\n process.stdout.write('\\nStored defaults\\n');\n printContextValues(selected.context?.values ?? {}, false);\n if (!effective) return;\n\n process.stdout.write('\\nEffective values\\n');\n printContextValues(g_invocation.values, false, (key) => {\n if (hasContextValue(g_invocation?.cliOverrides, key)) return 'command line';\n if (hasContextValue(g_invocation?.environmentValues, key)) return 'environment';\n if (hasContextValue(g_invocation?.contextValues, key)) return 'context';\n return undefined;\n });\n}\n\nfunction contextSelectionDescription(selectedBy: ResolvedInvocationContext['selected']['selectedBy']): string {\n switch (selectedBy) {\n case 'argument': return '--context';\n case 'environment': return 'LINKRPC_CONTEXT (HUBRPC_CONTEXT fallback)';\n case 'cwd': return 'current-directory lookup';\n case 'root': return ':root fallback (no folder context applies)';\n case 'empty': return 'no matching context (:empty)';\n }\n}\n\nfunction hasContextValue(\n values: ContextValues | undefined,\n key: keyof ContextValues,\n): boolean {\n return values !== undefined && values[key] !== undefined;\n}\n\nfunction printContextValues(\n values: ContextValues,\n revealToken: boolean,\n source?: (key: keyof ContextValues) => string | undefined,\n): void {\n const entries = Object.entries(values);\n if (entries.length === 0) {\n process.stdout.write(' (none)\\n');\n return;\n }\n for (const [key, value] of entries) {\n const contextKey = key as keyof ContextValues;\n const rendered = key === 'endpointToken' && !revealToken\n ? '<stored>'\n : key === 'endpoint' && typeof value === 'string' && !revealToken\n ? redactEndpointTokens(value)\n : typeof value === 'string'\n ? value\n : JSON.stringify(value);\n const valueSource = source?.(contextKey);\n process.stdout.write(\n ` --${contextValueFlag(contextKey)} = ${rendered}${valueSource ? ` (${valueSource})` : ''}\\n`,\n );\n }\n\n function redactEndpointTokens(endpoint: string): string {\n return endpoint.replace(/([?&]token=)([^&#]*)/g, (_match, prefix: string, token: string) =>\n `${prefix}${token === '%' ? '%' : '<stored>'}`);\n }\n}\n\nfunction contextValueFlag(key: keyof ContextValues): string {\n const names: Record<keyof ContextValues, string> = {\n daemonService: 'daemon-service',\n detachKeys: 'detach-keys',\n namespace: 'namespace',\n endpoint: 'endpoint',\n endpointCmd: 'endpoint-cmd',\n endpointCmdStdio: 'endpoint-cmd-stdio',\n endpointCmdEnv: 'endpoint-cmd-env',\n endpointToken: 'endpoint-token',\n endpointCmdCwd: 'endpoint-cmd-cwd',\n config: 'config',\n provisionIdentity: 'provision-identity',\n provisionIdentitySlot: 'provision-identity-slot',\n principal: 'principal',\n sign: 'sign',\n schema: 'schema',\n validation: 'validation',\n connectionTimeout: 'connection-timeout',\n connectionTtl: 'connection-ttl',\n notificationLimit: 'notification-limit',\n };\n return names[key];\n}\n\nfunction parseContextValueKey(value: string): keyof ContextValues {\n const entry = (Object.keys({\n daemonService: true,\n detachKeys: true,\n namespace: true,\n endpoint: true,\n endpointCmd: true,\n endpointCmdStdio: true,\n endpointCmdEnv: true,\n endpointToken: true,\n endpointCmdCwd: true,\n config: true,\n provisionIdentity: true,\n provisionIdentitySlot: true,\n principal: true,\n sign: true,\n schema: true,\n validation: true,\n connectionTimeout: true,\n connectionTtl: true,\n notificationLimit: true,\n }) as (keyof ContextValues)[]).find((key) => contextValueFlag(key) === value);\n if (entry === undefined) throw new InvalidArgumentError(`unknown context value \"${value}\"`);\n return entry;\n}\n\nfunction effectiveValidation(profile: CliProfile): ValidationMode {\n return g_invocation?.values.validation ?? validationDefault(profile);\n}\n\n/** The configured TTY detach sequence; validated when used, so invalid stored values fail with a clear message. */\nfunction detachKeys(): DetachKeys | undefined {\n const spec = g_invocation?.values.detachKeys;\n return spec === undefined ? undefined : DetachKeys.parse(spec);\n}\n\nfunction parseValidationMode(value: string): ValidationMode {\n if (value === 'auto' || value === 'required' || value === 'off') return value;\n throw new InvalidArgumentError(\"--validation must be 'auto', 'required', or 'off'\");\n}\n\nfunction getCommandPath(command: Command): string {\n const names: string[] = [];\n for (let cursor: Command | null = command; cursor?.parent !== null; cursor = cursor.parent) {\n names.unshift(cursor.name());\n }\n return names.join(' ');\n}\n\nfunction commandUsesEndpoint(commandPath: string): boolean {\n return !(\n commandPath === 'context'\n || commandPath.startsWith('context ')\n || commandPath === 'codegen'\n || commandPath === 'schema hash'\n || commandPath === 'completions'\n || commandPath === '_complete'\n || commandPath === '_connection-broker'\n || commandPath === 'serve'\n || commandPath === 'logout'\n );\n}\n\nfunction hasEndpointOverrides(values: ContextValues): boolean {\n return values.endpoint !== undefined\n || values.endpointCmd !== undefined\n || values.endpointCmdStdio !== undefined\n || values.endpointCmdEnv !== undefined\n || values.endpointToken !== undefined\n || values.endpointCmdCwd !== undefined\n || values.provisionIdentity !== undefined\n || values.provisionIdentitySlot !== undefined;\n}\n\nasync function withChannel(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (channel: import('@hediet/linkrpc-client-internal').CliChannel, session?: SigningSession) => Promise<void>,\n opts: {\n requestReflectionAccess?: boolean;\n requestTopologyAccess?: { readonly sourceServiceIds?: readonly string[] };\n requireSigning?: boolean;\n autoNegotiatePerCall?: boolean;\n } = {},\n): Promise<void> {\n const sign = resolveSigning(g_invocation?.profile ?? 'rpc', g_invocation?.values ?? {}, opts.requireSigning);\n const acquired = await acquireConnection(endpoint);\n // When `--config` runs an in-process hub, that hub already logs its routed\n // traffic (richer than the client leg) — so only tap the wire for a direct\n // remote connection, to avoid double-logging the control socket.\n const conn = await connectEndpoint(acquired.ep, acquired.running === undefined ? wireLog('hub') : undefined);\n try {\n const schemaSource = g_invocation?.values.schema;\n const channel = schemaSource === undefined\n ? conn.channel\n : withStaticHubReflection(conn.channel, await loadStaticHubSchema(schemaSource));\n if (\n acquired.ep.kind === 'ws-no-init'\n || (acquired.ep.kind === 'socket' && acquired.ep.brokerMode === 'raw')\n ) {\n if (opts.requireSigning || g_invocation?.values.sign === true) {\n throw new Error('Signing requires an initialized LinkRPC endpoint.');\n }\n await fn(channel);\n return;\n }\n if (!sign) {\n await fn(channel);\n return;\n }\n\n const session = await setupSigning(conn.channel, conn.signing, principalSpec, {\n negotiateHubCaps: acquired.running !== undefined || isHubEndpoint(acquired.ep),\n autoNegotiatePerCall: opts.autoNegotiatePerCall,\n });\n reportIdentity(session);\n // Up-front, batched reflection grant across all services. One consent\n // prompt covers `ls` / `schema` / `defaults`; if denied we fall back to\n // per-call auto-cap negotiation installed by `setupSigning`.\n if (\n opts.requestReflectionAccess !== false\n && schemaSource === undefined\n && (acquired.running !== undefined || isHubEndpoint(acquired.ep))\n ) {\n const status = await requestReflectionAccess(session);\n if (status === 'denied') {\n process.stderr.write(\n 'linkrpc: reflection access denied; falling back to per-call negotiation.\\n',\n );\n }\n }\n if (\n opts.requestTopologyAccess !== undefined\n && (acquired.running !== undefined || isHubEndpoint(acquired.ep))\n ) {\n const status = await requestTopologyAccess(session, opts.requestTopologyAccess);\n if (status === 'denied') {\n process.stderr.write(\n 'linkrpc: topology access denied; topology sources may be inaccessible.\\n',\n );\n }\n }\n await fn(channel, session);\n } finally {\n conn.close();\n acquired.running?.dispose();\n }\n}\n\nasync function withResolvedSigning(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (connection: CliConnection, session: SigningSession) => Promise<void>,\n): Promise<void> {\n resolveSigning(g_invocation?.profile ?? 'rpc', g_invocation?.values ?? {}, true);\n const acquired = await acquireConnection(endpoint);\n if (\n acquired.ep.kind === 'ws-no-init'\n || (acquired.ep.kind === 'socket' && acquired.ep.brokerMode === 'raw')\n ) {\n acquired.running?.dispose();\n throw new Error('identity and approval commands require a LinkRPC endpoint');\n }\n const conn = await connectEndpoint(acquired.ep, acquired.running === undefined ? wireLog('hub') : undefined);\n try {\n const session = await setupSigning(conn.channel, conn.signing, principalSpec, {\n negotiateHubCaps: acquired.running !== undefined || isHubEndpoint(acquired.ep),\n autoNegotiatePerCall: false,\n });\n await fn(conn, session);\n } finally {\n conn.close();\n acquired.running?.dispose();\n }\n}\n\nasync function withApprovalClient(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (client: ApprovalCommandClient) => Promise<void>,\n log: (line: string) => void = (line) => process.stderr.write(`linkrpc: ${line}\\n`),\n): Promise<void> {\n await withResolvedSigning(endpoint, principalSpec, async (conn, session) => {\n reportIdentity(session);\n await bootstrapApprovalCapability(session.principal);\n const connection = new LinkRpcConnection(conn.rpcChannel);\n const client = createHubApprovalCommandClient(\n connection,\n session.principal.identity,\n log,\n () => session.principal.capBag.capabilities,\n () => bootstrapApprovalCapability(session.principal, log),\n );\n try {\n await fn(client);\n } finally {\n client.dispose();\n }\n });\n}\n\nasync function withRawConnection(\n endpoint: ResolvedEndpoint | undefined,\n fn: (channel: import('@hediet/linkrpc-client-internal').CliChannel) => Promise<void>,\n): Promise<void> {\n if (g_hubConfigPath !== undefined) {\n throw new Error('connection broker commands do not support --config');\n }\n const conn = await connectEndpoint(needEndpoint(endpoint), wireLog('connection broker'));\n try {\n await fn(conn.channel);\n } finally {\n conn.close();\n }\n}\n\nfunction parsePositiveInteger(value: string, option: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(`${option} must be a positive integer`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string, option: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError(`${option} must be a non-negative integer`);\n }\n return parsed;\n}\n\n/**\n * Module-level config path, set per-command in the `preAction` hook. When set,\n * client commands run an in-process hub from the config and target its private\n * control socket instead of `--endpoint`.\n */\nlet g_hubConfigPath: string | undefined;\nlet g_contextStore: ContextStore | undefined;\nlet g_invocation: ResolvedInvocationContext | undefined;\n\n/**\n * Module-level flag, set per-command in the `preAction` hook. When set, the\n * in-process hub (`-c, --config` or `serve`) logs every routed JSON-RPC\n * message to stderr. Forced off for `ui` (it would corrupt the TUI).\n */\nlet g_logMessages = false;\nlet g_logTransport = false;\n\n/**\n * Build the wire-tap options for a direct {@link connect}, or `undefined` when\n * `--log-messages` is off. Logs every JSON-RPC message crossing the client\n * transport to stderr, rendered like the hub \"Flows\" view — the way to observe\n * a connection that never routes through a local hub.\n */\nfunction wireLog(remoteLabel: string): ConnectLogOptions | undefined {\n if (!g_logMessages && !g_logTransport) return undefined;\n return {\n ...(g_logMessages\n ? { log: (line: string) => process.stderr.write(`linkrpc: ${line}\\n`) }\n : {}),\n ...(g_logTransport\n ? {\n trace: (direction: 'send' | 'receive', message: import('@hediet/linkrpc').JsonRpcMessage) =>\n process.stderr.write(`linkrpc: transport ${direction} ${JSON.stringify(message)}\\n`),\n }\n : {}),\n remoteLabel,\n };\n}\n\n/**\n * Resolve the endpoint a client command should connect to. With `--config`,\n * spins up an in-process hub and returns its control socket (the caller must\n * `running.dispose()` when done); otherwise returns the resolved `--endpoint`.\n */\nasync function acquireConnection(\n endpoint: ResolvedEndpoint | undefined,\n): Promise<{ ep: ResolvedEndpoint; running?: RunningHub; }> {\n if (g_hubConfigPath !== undefined) {\n const config: HubConfig = loadHubConfig(g_hubConfigPath);\n const running = await runHub({ config, logMessages: g_logMessages });\n return {\n ep: { kind: 'socket', path: running.controlEndpoint.path, token: running.controlEndpoint.token },\n running,\n };\n }\n if (endpoint === undefined && g_invocation?.profile === 'hub') {\n // Without a configured endpoint, the hub profile uses the local Hub daemon whenever it runs.\n try {\n return { ep: resolveLocalEndpoint() };\n } catch {\n throw new Error('No endpoint configured through flags, environment, or context, and the local Hub daemon is not running. '\n + 'Pass --endpoint, or start the daemon (any `hub services run` starts it).');\n }\n }\n return { ep: needEndpoint(endpoint) };\n}\n\n/** Print the identity used to sign calls to stderr (keeps stdout clean for JSON output). */\nfunction reportIdentity(session: SigningSession): void {\n process.stderr.write(\n `linkrpc: identity ${formatPrincipalSource(session.principalSource, session.principal.id)\n }\\n`,\n );\n}\n\nfunction needEndpoint(endpoint: ResolvedEndpoint | undefined): ResolvedEndpoint {\n if (!endpoint) {\n process.stderr.write(\n 'linkrpc: this command requires --endpoint / --endpoint-cmd / --endpoint-cmd-stdio ' +\n 'or the LINKRPC_ENDPOINT env var to be set.\\n',\n );\n process.exit(2);\n }\n return endpoint;\n}\n\ninterface TargetEndpointCliOptions {\n readonly targetEndpoint?: string;\n readonly targetEndpointCmd?: string;\n readonly targetEndpointCmdStdio?: string;\n readonly targetEndpointCmdEnv?: Record<string, string>;\n readonly targetEndpointToken?: string;\n readonly targetEndpointCmdCwd?: string;\n}\n\n/** The `--target-endpoint*` options shared by `tunnel` and `proxy`. */\nfunction addTargetEndpointOptions(command: Command): Command {\n return command\n .option(\n '--target-endpoint <uri>',\n 'target endpoint URI (unix:/path?token=…, npipe://./pipe/…, ws[s]://host?token=…, ' +\n 'cmd:?command=… or cmd-stdio:?command=…)',\n )\n .option(\n '--target-endpoint-cmd <command>',\n 'spawn the target as a server, connect via an injected env socket; the child sees ' +\n 'the claimed service id as grantedServiceIdNamespace via hubGrantedServiceId::get',\n )\n .option(\n '--target-endpoint-cmd-stdio <command>',\n 'spawn the target and talk linkrpc over its stdio',\n )\n .option(\n '--target-endpoint-cmd-env <key=value>',\n 'env var for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option(\n '--target-endpoint-token <token>',\n 'token overriding the target URI token (no env fallback for the target)',\n )\n .option(\n '--target-endpoint-cmd-cwd <dir>',\n 'working directory for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child',\n );\n}\n\nfunction hasTargetEndpoint(opts: TargetEndpointCliOptions): boolean {\n return opts.targetEndpoint !== undefined\n || opts.targetEndpointCmd !== undefined\n || opts.targetEndpointCmdStdio !== undefined;\n}\n\nfunction resolveTargetEndpointOrExit(\n opts: TargetEndpointCliOptions,\n globalOpts: Record<string, unknown>,\n commandName: string,\n): ResolvedEndpoint {\n const targetRes = resolveTargetEndpoint({\n ...opts,\n provisionIdentity: globalOpts.provisionIdentity as boolean | undefined,\n provisionIdentitySlot: globalOpts.provisionIdentitySlot as string | undefined,\n });\n if (targetRes.error) {\n process.stderr.write(`linkrpc: ${targetRes.error}\\n`);\n process.exit(2);\n }\n if (!targetRes.endpoint) {\n process.stderr.write(\n `linkrpc: ${commandName} requires --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio.\\n`,\n );\n process.exit(2);\n }\n // Honor the legacy LINKRPC_REMOTE_ENDPOINT_TOKEN env var as a fallback\n // for token-bearing target URIs.\n const targetEp = targetRes.endpoint;\n const remoteTok = process.env.LINKRPC_REMOTE_ENDPOINT_TOKEN;\n return remoteTok !== undefined && (targetEp.kind === 'socket' || targetEp.kind === 'ws')\n && targetEp.token === undefined\n ? { ...targetEp, token: remoteTok }\n : targetEp;\n}\n\n/**\n * Connect straight to a target endpoint — no routing hub. A spawned cmd-env\n * child is fronted with a RootOverlay: its root-form calls (identity::*,\n * hubGrantedServiceId::*, reflection, hubAccess) are served locally while every\n * forwarded request is relayed to the child through the overlay splitter. This\n * keeps --provision-identity working (identity::* is served) without the 'hub'\n * service id / claim-wait dance a full local hub imposes.\n */\nasync function connectTargetEndpoint(target: ResolvedEndpoint, grantedNamespace: string): Promise<CliConnection> {\n if (target.kind !== 'cmd-env') {\n return connectEndpoint(target, wireLog('target'));\n }\n return connectViaRootOverlay({\n command: target.command,\n provisionSlot: target.provisionSlot,\n env: target.env,\n ...(target.cwd !== undefined ? { cwd: target.cwd } : {}),\n grantedNamespace,\n log: wireLog('target'),\n });\n}\n\n/** This process's stdin/stdout as a participant; `closed` resolves when stdin ends. */\nasync function connectStdioParticipant(): Promise<{ connection: CliConnection; closed: Promise<void>; }> {\n let markClosed!: () => void;\n const closed = new Promise<void>((resolve) => { markClosed = resolve; });\n const { transport } = await connectNdjson({\n input: process.stdin,\n output: process.stdout,\n onClose: () => markClosed(),\n });\n return { connection: connectViaTransport(transport), closed };\n}\n\n/**\n * Resolve the ws/socket bound-token listener `connect-as` splices the target\n * onto: an explicit `--hub-endpoint <uri>`, else the fallback endpoint when it\n * is itself a dial-able ws/socket. Throws otherwise (cmd endpoints aren't\n * dial-able bound listeners).\n */\nfunction _resolveDialEndpoint(\n hubEndpoint: string | undefined,\n fallback: ResolvedEndpoint,\n): DialEndpoint {\n if (hubEndpoint !== undefined) {\n const spec = parseEndpointUri(hubEndpoint);\n if (spec.kind !== 'ws' && spec.kind !== 'socket') {\n throw new Error(`--hub-endpoint must be a ws/socket URI, got '${spec.kind}'`);\n }\n return spec;\n }\n if (fallback.kind === 'ws' || fallback.kind === 'socket') {\n return fallback;\n }\n throw new Error(\n 'connect-as requires --hub-endpoint <ws/socket uri> (the bound-token listener); ' +\n `--endpoint resolved to '${fallback.kind}', which is not a dial-able bound listener`,\n );\n}\n\n/** Resolve on the next `SIGINT` / `SIGTERM`. */\nfunction _untilSignalled(): Promise<void> {\n return new Promise<void>((resolve) => {\n const done = (): void => {\n process.removeListener('SIGINT', done);\n process.removeListener('SIGTERM', done);\n resolve();\n };\n process.once('SIGINT', done);\n process.once('SIGTERM', done);\n });\n}\n\nfunction resolveGraphFormat(\n rawFormat: unknown,\n aliases: { readonly json: boolean; readonly stream: boolean; readonly watch: boolean },\n): TopologyFormat {\n if (aliases.json && aliases.stream) {\n throw new InvalidArgumentError('--json and --stream cannot be combined');\n }\n if (rawFormat !== undefined && (aliases.json || aliases.stream)) {\n throw new InvalidArgumentError('--format cannot be combined with --json or --stream');\n }\n if (rawFormat !== undefined\n && rawFormat !== 'pretty'\n && rawFormat !== 'json'\n && rawFormat !== 'jsonl') {\n throw new InvalidArgumentError(\"--format must be 'pretty', 'json', or 'jsonl'\");\n }\n if (aliases.json) return 'json';\n if (aliases.stream) return 'jsonl';\n if (rawFormat !== undefined) return rawFormat;\n return aliases.watch && !process.stdout.isTTY ? 'jsonl' : 'pretty';\n}\n\nfunction collectOption(value: string, previous: readonly string[] | undefined): readonly string[] {\n return [...(previous ?? []), value];\n}\n\nfunction repaintTerminal(frame: string): void {\n process.stdout.write(`\\u001b[2J\\u001b[H${frame}\\n`);\n}\n\nfunction parseInterfaceRef(raw: string): { id: string; hash: string | undefined; } {\n const at = raw.lastIndexOf('@');\n if (at > 0 && !raw.slice(at + 1).includes('::')) {\n return { id: raw.slice(0, at), hash: raw.slice(at + 1) };\n }\n return { id: raw, hash: undefined };\n}\n\nexport function runCli(executableName: 'linkrpc' | 'rpc' | 'hub'): void {\n main(process.argv.slice(2), executableName).catch(async (e: unknown) => {\n const message = formatCliError(e);\n process.stderr.write(`linkrpc: ${message}\\n`);\n if (process.argv[2] === '_connection-broker') {\n await new Promise<void>((resolve, reject) => {\n process.stdout.write(JSON.stringify({ error: message }) + '\\n', error => {\n if (error) reject(error);\n else resolve();\n });\n });\n }\n process.exit(1);\n });\n}\n\nfunction formatCliError(error: unknown): string {\n if (typeof error !== 'object' || error === null) return String(error);\n\n const value = error as {\n readonly code?: unknown;\n readonly message?: unknown;\n readonly data?: unknown;\n };\n const message = typeof value.message === 'string' ? value.message : String(error);\n if (typeof value.code !== 'number' && typeof value.code !== 'string') return message;\n\n const data = value.data === undefined ? '' : ` data=${safeJson(value.data)}`;\n return `[${value.code}] ${message}${data}`;\n}\n\nfunction safeJson(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n"],"x_google_ignoreList":[35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAa,sBAAb,MAAiC;CAKR;CAEA;CACA;CACA;CARrB;CACA;CAEA,YACI,QACA,QACA,OACA,YACA,QACF;EALmB,KAAA,SAAA;EAEA,KAAA,QAAA;EACA,KAAA,aAAA;EACA,KAAA,SAAA;EAEjB,KAAK,UAAU,OAAO,SAAS;EAC/B,IAAI,OAAO,OAAO;GACd,KAAK,YAAY,gBAAgB;IAAE,OAAO;IAAQ;IAAQ,UAAU;IAAM,QAAQ;IAAI,aAAa;GAAE,CAAC;GACtG,KAAK,UAAU,GAAG,QAAQ,KAAK,OAAO;GACtC,KAAK,UAAU,GAAG,UAAU,UAAU;GACtC,KAAK,UAAU,GAAG,SAAS,MAAM;GACjC,OAAO,GAAG,YAAY,KAAK,WAAW;EAC1C,OAAO;GACH,OAAO,GAAG,QAAQ,KAAK,OAAO;GAC9B,OAAO,OAAO;EAClB;CACJ;CAEA,UAAgB;EACZ,IAAI,KAAK,WAAW;GAChB,KAAK,UAAU,eAAe,QAAQ,KAAK,OAAO;GAClD,KAAK,UAAU,eAAe,UAAU,KAAK,UAAU;GACvD,KAAK,UAAU,eAAe,SAAS,KAAK,MAAM;GAClD,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","traceMessageTransport","fetchSchema","toJsonValue","participantLabel","fetchSchema","_untilSignalled","nonNegativeInteger","positiveInteger","positiveInteger","connectEndpoint"],"sources":["../../src/commands/serviceConsoleInput.ts","../../src/commands/consoleSession.ts","../../src/commands/services.ts","../../src/views/types.ts","../../src/views/discovery.ts","../../src/commands/consoleAttach.ts","../../src/output.ts","../../src/commands/caps.ts","../../src/suggest.ts","../../src/schemaLookup.ts","../../src/commands/call.ts","../../src/commands/batch.ts","../../src/commands/connectionBrokerProcess.ts","../../src/commands/checkCompat.ts","../../src/commands/codegen.ts","../../src/commands/contract.ts","../../src/completions/shellScripts.ts","../../src/commands/completions.ts","../../src/commands/defaults.ts","../../src/commands/hash.ts","../../src/commands/internalComplete.ts","../../src/commands/displayForest.ts","../../src/commands/jsonPatch.ts","../../src/commands/stateJsonl.ts","../../src/commands/ls.ts","../../src/commands/topology.ts","../../src/commands/ping.ts","../../src/commands/participantWatch.ts","../../src/commands/schema.ts","../../src/commands/serve.ts","../../src/commands/connectAs.ts","../../src/commands/connectAsTransports.ts","../../src/commands/mcpForward.ts","../../src/commands/jsonRpcStdio.ts","../../src/commands/jsonRpcExport.ts","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/logging.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/debugLocation.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/debugName.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/baseObservable.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/commonFacade/deps.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/disposables.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/derivedImpl.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/derived.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/reactions/createEffectImpl.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/reactions/createEffect.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/base.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/transaction.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/observableValue.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/observables/observableFromEvent.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/utils/utils.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/consoleObservableLogger.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/logging/debugGetDependencyGraph.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/index.js","../../../../node_modules/.pnpm/@vscode+observables@0.1.1-0/node_modules/@vscode/observables/dist/observableInternal/utils/promise.js","../../src/approvalPresentation.ts","../../src/commands/approval.ts","../../src/commands/identity.ts","../../src/engine/runHub.ts","../../src/methodHelp.ts","../../src/paramFlags.ts","../../src/ui/terminalText.ts","../../src/infra/graph/graphFrame.ts","../../src/infra/graph/inspectGraphTerminal.ts","../../src/infra/graph/inspectGraphTiming.ts","../../src/infra/graph/inspectGraphModel.ts","../../src/infra/graph/inspectGraphView.ts","../../src/infra/graph/inspectGraph.ts","../../src/views/commands.ts","../../src/views/CommandLegend.tsx","../../src/views/ViewFrame.tsx","../../src/views/runViewTui.tsx","../../src/infra/graph/session.tsx","../../src/infra/graph/contribution.ts","../../src/infra/logging/model.ts","../../src/infra/logging/session.tsx","../../src/infra/logging/contribution.ts","../../src/infra/topology/diagram.ts","../../src/infra/topology/model.ts","../../src/infra/topology/session.tsx","../../src/infra/topology/contribution.ts","../../src/views/registry.ts","../../src/commands/view.ts","../../src/cli.ts"],"sourcesContent":["import { createInterface, type Interface, type Key } from 'node:readline';\nimport type { Readable, Writable } from 'node:stream';\n\ntype ConsoleInput = Readable & {\n readonly isTTY?: boolean;\n readonly isRaw?: boolean;\n setRawMode?(mode: boolean): unknown;\n unref?(): unknown;\n};\n\nexport class ServiceConsoleInput {\n private readonly _readline: Interface | undefined;\n private readonly _wasRaw: boolean;\n\n constructor(\n private readonly _input: ConsoleInput,\n output: Writable,\n private readonly _send: (data: string) => void,\n private readonly _interrupt: () => void,\n private readonly _close: () => void,\n ) {\n this._wasRaw = _input.isRaw ?? false;\n if (_input.isTTY) {\n this._readline = createInterface({ input: _input, output, terminal: true, prompt: '', historySize: 0 });\n this._readline.on('line', this._onLine);\n this._readline.on('SIGINT', _interrupt);\n this._readline.on('close', _close);\n _input.on('keypress', this._onKeypress);\n } else {\n _input.on('data', this._onData);\n _input.resume();\n }\n }\n\n dispose(): void {\n if (this._readline) {\n this._readline.removeListener('line', this._onLine);\n this._readline.removeListener('SIGINT', this._interrupt);\n this._readline.removeListener('close', this._close);\n this._readline.close();\n this._input.removeListener('keypress', this._onKeypress);\n this._input.setRawMode?.(this._wasRaw);\n } else {\n this._input.removeListener('data', this._onData);\n }\n this._input.pause();\n // Readline can already have paused stdin during EOF; release any remaining native read handle.\n this._input.unref?.();\n }\n\n private readonly _onLine = (line: string): void => { this._send(line + '\\n'); };\n private readonly _onKeypress = (_text: string | undefined, key: Key): void => {\n if (key.sequence === '\\x1d') this._close();\n };\n private readonly _onData = (data: Buffer): void => {\n if (data.includes(29)) this._close();\n else this._send(data.toString('utf8'));\n };\n}\n","import {\n decodeConsoleData,\n encodeConsoleData,\n type ConsoleClientMessage,\n type ConsoleExit,\n type ConsoleMode,\n type ConsoleServerMessage,\n type ConsoleSignal,\n type ConsoleSize,\n} from '@hediet/linkrpc-infra/console';\nimport { ServiceConsoleInput } from './serviceConsoleInput';\n\n/** An in-flight console attach call: typed streaming calls and adapted raw calls both satisfy it. */\nexport interface ConsoleCall extends PromiseLike<{ readonly exit: ConsoleExit | null }> {\n send(message: ConsoleClientMessage): unknown;\n cancel(): unknown;\n}\n\nexport interface ConsoleSessionOptions {\n /** Forward local input, resizes, and interrupts. */\n readonly interactive: boolean;\n /** Closing the session stops the process (foreground ownership). */\n readonly owner: boolean;\n /** Close after replay, for one-shot log output. */\n readonly untilLive?: boolean;\n readonly reattachCommand?: string;\n /** Detaches a TTY attachment; defaults to {@link DEFAULT_DETACH_KEYS}. */\n readonly detachKeys?: DetachKeys;\n /** Aborting closes the session locally. */\n readonly signal?: AbortSignal;\n}\n\nexport interface ConsoleSessionResult {\n readonly exit: ConsoleExit | null;\n /** The session was closed by this side (detach, ownership release, or abort) rather than by the console. */\n readonly closedLocally: boolean;\n}\n\n/**\n * Drive a `linkrpc.console` attachment (or a stream embedding its protocol):\n * render output, and configure local input from the console's mode. TTY\n * consoles get raw keystrokes, so detaching uses a key sequence (see\n * {@link DetachKeys}); pipe consoles get local line editing, and Ctrl+D on an\n * empty line detaches.\n */\nexport async function runConsoleSession<TExtra extends { readonly t: string }>(\n start: (onMessage: (message: ConsoleServerMessage | TExtra) => void) => ConsoleCall,\n options: ConsoleSessionOptions,\n onExtra?: (message: TExtra) => void,\n): Promise<ConsoleSessionResult> {\n const session = new ConsoleSession(options, onExtra);\n return session.run(start);\n}\n\n/** Local terminal size, sent so that TTY consoles match this terminal. */\nexport function localTerminalSize(): ConsoleSize | undefined {\n const { columns, rows } = process.stdout;\n return process.stdout.isTTY && columns > 0 && rows > 0 ? { cols: columns, rows } : undefined;\n}\n\n/**\n * A detach key sequence in Docker's `--detach-keys` syntax: comma-separated\n * keys, each a single character or `ctrl-<key>` with `<key>` in `a`-`z`, `@`,\n * `[`, `\\`, `]`, `^`, or `_`. For example `ctrl-b,d` or `ctrl-p,ctrl-q`.\n */\nexport class DetachKeys {\n private constructor(readonly spec: string, readonly bytes: Uint8Array) {}\n\n static parse(spec: string): DetachKeys {\n const bytes = spec.split(',').map(part => {\n const key = part.trim();\n const ctrl = /^ctrl-(.)$/i.exec(key);\n if (ctrl) {\n const index = '@abcdefghijklmnopqrstuvwxyz[\\\\]^_'.indexOf(ctrl[1]!.toLowerCase());\n if (index >= 0) return index;\n } else if (key.length === 1 && key.charCodeAt(0) >= 0x20 && key.charCodeAt(0) < 0x7f) {\n return key.charCodeAt(0);\n }\n throw new Error(`Invalid detach key \"${key}\" in \"${spec}\": use a character or ctrl-<a-z, @, [, \\\\, ], ^, _>, separated by commas`);\n });\n if (bytes.length === 0) throw new Error('The detach key sequence is empty');\n return new DetachKeys(spec, Uint8Array.from(bytes));\n }\n\n /** Human-readable form, e.g. `Ctrl+B, then d`. */\n get label(): string {\n return [...this.bytes].map(byte => byte < 0x20 ? `Ctrl+${String.fromCharCode(byte + 0x40)}` : String.fromCharCode(byte)).join(', then ');\n }\n}\n\n/** Ctrl+B, then d (tmux's binding): unlike Docker's Ctrl+P, Ctrl+Q, it reaches programs in VS Code's terminal. */\nexport const DEFAULT_DETACH_KEYS = DetachKeys.parse('ctrl-b,d');\n\n/**\n * Recognizes a detach sequence in raw keyboard input. Bytes of a partial match\n * are held back, and forwarded unchanged when the sequence does not complete.\n */\nexport class DetachKeyFilter {\n private _matched = 0;\n\n constructor(private readonly _keys: DetachKeys = DEFAULT_DETACH_KEYS) {}\n\n push(chunk: Uint8Array): { readonly forward: Uint8Array; readonly detach: boolean } {\n const sequence = this._keys.bytes;\n const forward: number[] = [];\n for (const byte of chunk) {\n // Keep the longest suffix of the pending keys that still starts the sequence.\n const pending = [...sequence.subarray(0, this._matched), byte];\n let start = 0;\n while (start < pending.length && !pending.slice(start).every((value, index) => value === sequence[index])) start++;\n forward.push(...pending.slice(0, start));\n this._matched = pending.length - start;\n if (this._matched === sequence.length) {\n this._matched = 0;\n return { forward: Uint8Array.from(forward), detach: true };\n }\n }\n return { forward: Uint8Array.from(forward), detach: false };\n }\n}\n\nconst ALTERNATE_SCREEN = /\\x1b\\[\\?(?:1049|1047|47)([hl])/g;\n/** Undo terminal modes a program may have enabled: mouse, bracketed paste, focus, win32-input, hidden cursor. */\nconst TERMINAL_RESET = '\\x1b[0m\\x1b[?25h\\x1b[?1000l\\x1b[?1002l\\x1b[?1003l\\x1b[?1006l\\x1b[?2004l\\x1b[?1004l\\x1b[?9001l';\n\nclass ConsoleSession<TExtra extends { readonly t: string }> {\n private _call: ConsoleCall | undefined;\n private readonly _detachKeys: DetachKeys;\n private _mode: ConsoleMode | undefined;\n private _signals: readonly ConsoleSignal[] = [];\n private _input: { dispose(): void } | undefined;\n private _raw = false;\n private _alternateScreen = false;\n private _closedLocally = false;\n\n constructor(\n private readonly _options: ConsoleSessionOptions,\n private readonly _onExtra: ((message: TExtra) => void) | undefined,\n ) {\n this._detachKeys = _options.detachKeys ?? DEFAULT_DETACH_KEYS;\n }\n\n async run(start: (onMessage: (message: ConsoleServerMessage | TExtra) => void) => ConsoleCall): Promise<ConsoleSessionResult> {\n const onSignal = () => this._interrupt();\n const onTerminate = () => this.close();\n process.on('SIGINT', onSignal);\n process.on('SIGTERM', onTerminate);\n this._options.signal?.addEventListener('abort', onTerminate);\n try {\n this._call = start(message => this._onMessage(message));\n if (this._closedLocally || this._options.signal?.aborted) this.close();\n let exit: ConsoleExit | null = null;\n try {\n exit = (await this._call).exit;\n } catch (error) {\n if (!this._closedLocally) throw error;\n }\n return { exit, closedLocally: this._closedLocally };\n } finally {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onTerminate);\n this._options.signal?.removeEventListener('abort', onTerminate);\n this._input?.dispose();\n if (this._raw) {\n process.stdout.write(TERMINAL_RESET + (this._alternateScreen ? '\\x1b[?1049l' : '') + '\\r\\n');\n }\n if (this._closedLocally && this._options.interactive && !this._options.owner && this._options.reattachCommand) {\n process.stderr.write(`Detached. Reattach: ${this._options.reattachCommand}\\n`);\n }\n }\n }\n\n close(): void {\n this._closedLocally = true;\n try { void Promise.resolve(this._call?.cancel()).catch(() => {}); } catch { /* already settled */ }\n }\n\n private _onMessage(message: ConsoleServerMessage | TExtra): void {\n const console = message as ConsoleServerMessage;\n switch (console.t) {\n case 'console':\n this._mode = console.mode;\n this._signals = console.signals;\n this._startInput();\n return;\n case 'screen': {\n const screen = decodeConsoleData(console.data);\n if (screen.length > 0 && process.stdout.isTTY) process.stdout.write('\\x1b[H\\x1b[2J');\n this._write(process.stdout, screen);\n return;\n }\n case 'output':\n this._write(console.stream === 'stderr' ? process.stderr : process.stdout, decodeConsoleData(console.data));\n return;\n case 'notice':\n process.stderr.write(this._mode === 'tty' ? `\\r\\n[console] ${console.text}\\r\\n` : `${console.text}\\n`);\n return;\n case 'live':\n if (this._options.untilLive) this.close();\n return;\n case 'started':\n case 'exit':\n case 'resized':\n return;\n }\n this._onExtra?.(message as TExtra);\n }\n\n private _write(stream: NodeJS.WriteStream, data: Uint8Array): void {\n if (this._mode === 'tty') {\n for (const match of new TextDecoder().decode(data).matchAll(ALTERNATE_SCREEN)) this._alternateScreen = match[1] === 'h';\n }\n stream.write(data);\n }\n\n private _startInput(): void {\n if (!this._options.interactive || this._input) return;\n const owner = this._options.owner;\n const reattach = this._options.reattachCommand;\n if (this._mode === 'tty') {\n process.stderr.write(owner\n ? `Foreground (TTY). Keys go to the program; ${this._detachKeys.label} stops and removes the service.\\n`\n : `Attached (TTY). Keys go to the program; ${this._detachKeys.label} detaches.\\n`);\n } else {\n const interrupt = owner ? 'Ctrl+C or ' : this._signals.includes('SIGINT') ? 'Ctrl+C interrupts; ' : '';\n process.stderr.write(owner\n ? `Foreground (pipe console). ${interrupt}Ctrl+D on an empty line stops and removes the service.\\n`\n : `Attached (pipe console). ${interrupt}Ctrl+D on an empty line detaches.\\n`);\n }\n if (reattach) process.stderr.write(`${owner ? 'Attach from another terminal while running' : 'Reattach'}: ${reattach}\\n`);\n this._input = this._mode === 'tty' ? this._startTerminalInput() : this._startLineInput();\n }\n\n private _startTerminalInput(): { dispose(): void } {\n const stdin = process.stdin;\n const filter = stdin.isTTY ? new DetachKeyFilter(this._detachKeys) : undefined;\n const wasRaw = stdin.isRaw;\n if (stdin.isTTY) {\n stdin.setRawMode(true);\n this._raw = true;\n }\n const onData = (chunk: Buffer) => {\n const { forward, detach } = filter ? filter.push(chunk) : { forward: chunk, detach: false };\n if (forward.length > 0) this._send({ t: 'input', data: encodeConsoleData(forward) });\n if (detach) this.close();\n };\n const onResize = () => {\n const size = localTerminalSize();\n if (size) this._send({ t: 'resize', ...size });\n };\n stdin.on('data', onData);\n stdin.resume();\n process.stdout.on('resize', onResize);\n return {\n dispose: () => {\n stdin.removeListener('data', onData);\n process.stdout.removeListener('resize', onResize);\n if (stdin.isTTY) stdin.setRawMode(wasRaw);\n stdin.pause();\n stdin.unref?.();\n },\n };\n }\n\n private _startLineInput(): { dispose(): void } {\n return new ServiceConsoleInput(\n process.stdin, process.stderr,\n data => this._send({ t: 'input', data: encodeConsoleData(new TextEncoder().encode(data)) }),\n () => this._interrupt(),\n () => this.close(),\n );\n }\n\n private _interrupt(): void {\n if (this._options.owner || !this._options.interactive) {\n this.close();\n } else if (this._mode === 'tty') {\n this._send({ t: 'input', data: encodeConsoleData(Uint8Array.of(0x03)) });\n } else if (this._signals.includes('SIGINT')) {\n this._send({ t: 'signal', signal: 'SIGINT' });\n } else {\n process.stderr.write('Interrupting is not supported for pipe processes on this host; run with -t for a terminal. Ctrl+D on an empty line detaches.\\n');\n }\n }\n\n private _send(message: ConsoleClientMessage): void {\n try { void Promise.resolve(this._call?.send(message)).catch(() => {}); } catch { /* the call ended */ }\n }\n}\n","import { Command, Option } from 'commander';\nimport { directoryInterface, ErrorCode, RpcError, type InterfaceClient, type LinkRpcConnection } from '@hediet/linkrpc';\nimport { connectToHub } from '@hediet/linkrpc/node';\nimport type { ConsoleServerMessage } from '@hediet/linkrpc-infra/console';\nimport { managedEndpointsInterface, HubHome, readEndpointDiscovery, type EndpointStatus, type RunEvent } from '@hediet/linkrpc-hub-daemon/client';\nimport type { ContextReference, ContextValues } from '../contexts';\nimport { localTerminalSize, runConsoleSession, type DetachKeys } from './consoleSession';\n\nexport type EndpointClient = InterfaceClient<typeof managedEndpointsInterface>;\nexport interface ServicesHost {\n namespace(): string;\n attachCommand(id: string): string;\n /** The configured TTY detach sequence, if not the default. */\n detachKeys(): DetachKeys | undefined;\n restart(): Promise<void>;\n use<T>(startLocal: boolean, action: (client: EndpointClient, context: ManagementContext) => Promise<T>): Promise<T>;\n}\n\nexport interface ManagementContext {\n /** The selected manager is the local daemon, so local paths are meaningful. */\n readonly local: boolean;\n}\n\nfunction withDetachKeys(host: ServicesHost): { detachKeys?: DetachKeys } {\n const detachKeys = host.detachKeys();\n return detachKeys ? { detachKeys } : {};\n}\n\nexport function serviceAttachCommand(options: {\n context: string; namespace: string; id: string; overrides: ContextValues; useEnv: boolean;\n}, platform: NodeJS.Platform = process.platform): string {\n const args = ['hub', 'services', 'attach', '--id', options.id,\n '--context', options.context, '--namespace', options.namespace, options.useEnv ? '--use-env' : '--no-use-env'];\n for (const key of Object.keys(options.overrides) as (keyof ContextValues)[]) {\n if (key === 'namespace') continue;\n const value = options.overrides[key];\n if (value === undefined) continue;\n const flag = '--' + key.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());\n if (key === 'endpointCmdEnv' && typeof value === 'object') {\n for (const name of Object.keys(value)) args.push(flag, `${name}=<same value>`);\n } else if (typeof value === 'boolean') {\n if (value) args.push(flag);\n else if (key === 'sign') args.push('--no-sign');\n } else if (typeof value === 'string' || typeof value === 'number') {\n args.push(flag, key === 'endpointToken' ? '<same endpoint token>' : String(value).replace(/([?&]token=)[^&]+/g, '$1<same token>'));\n }\n }\n return args.map(arg => /^[A-Za-z0-9_./:-]+$/.test(arg) ? arg\n : \"'\" + arg.replace(/'/g, platform === 'win32' ? \"''\" : \"'\\\\''\") + \"'\").join(' ');\n}\n\nconst requiredInterfaces = [\n { id: managedEndpointsInterface.info.id, hash: managedEndpointsInterface.schemaHash },\n];\n\nexport async function checkDaemonInterfaces(connection: LinkRpcConnection, serviceId?: string): Promise<void> {\n const recovery = serviceId === undefined\n ? 'Run `hub services restart` to stop the local daemon via RPC and start this CLI\\'s bundled daemon.'\n : 'Update/restart the daemon on its execution host. To replace the default local daemon, run `hub --context :empty --no-use-env services restart`.';\n for (const required of requiredInterfaces) {\n let cursor: string | undefined;\n let supported = false;\n const hashes = new Set<string>();\n try {\n do {\n const page = await connection.get(directoryInterface, { serviceId }).list({\n interfaceId: required.id, serviceId: serviceId ?? '', cursor,\n });\n for (const item of page.items) {\n if (item.interfaceId !== required.id || item.serviceId !== (serviceId ?? '')) continue;\n hashes.add(item.interfaceHash);\n supported ||= item.interfaceHash === required.hash;\n }\n if (page.truncated) throw new Error('Daemon interface discovery was truncated; compatibility could not be checked.');\n cursor = page.nextCursor;\n } while (!supported && cursor !== undefined);\n } catch (error) {\n if (!(error instanceof RpcError) || error.code !== ErrorCode.methodNotFound) throw error;\n throw new Error(`The selected daemon cannot report its interfaces. ${recovery}`, { cause: error });\n }\n if (!supported) {\n throw new Error(`The selected daemon does not support required interface ${required.id}@${required.hash} (reported: ${[...hashes].join(', ') || 'missing'}). ${recovery}`);\n }\n }\n}\n\nexport function contextNamespace(reference: ContextReference): string {\n switch (reference.kind) {\n case 'path': return process.platform === 'win32' ? reference.path.toLowerCase() : reference.path;\n case 'id': return `id:${reference.id}`;\n case 'root': return ':root';\n case 'empty': throw new Error('The :empty context has no namespace. Pass --namespace <name>, or select another context with --context <selector>.');\n }\n}\n\nexport async function useLocalManagement<T>(start: boolean, action: (client: EndpointClient, context: ManagementContext) => Promise<T>): Promise<T> {\n const home = HubHome.resolve();\n if (start) {\n const { startDaemon, nodeDaemonLaunch } = await import('@hediet/linkrpc-hub-daemon');\n const result = await startDaemon({ home, launch: nodeDaemonLaunch(home) });\n if (result === 'started') process.stderr.write('linkrpc: local daemon started.\\n');\n }\n const discovery = readEndpointDiscovery(home.managementFile);\n if (!discovery) throw new Error('No endpoint configured through flags, environment, or context, and the local Hub daemon is not running.');\n const handle = await connectToHub({ endpoint: discovery.endpoint, token: discovery.token ?? '' });\n try {\n await checkDaemonInterfaces(handle.connection);\n return await action(handle.connection.get(managedEndpointsInterface), { local: true });\n }\n finally { handle.close(); }\n}\n\nexport async function restartLocalDaemon(): Promise<void> {\n const { startDaemon, stopDaemon, nodeDaemonLaunch } = await import('@hediet/linkrpc-hub-daemon');\n const home = HubHome.resolve();\n process.stderr.write('Restarting the local Hub daemon: clients will disconnect and managed workloads will stop. OS autostart settings are unchanged.\\n');\n await stopDaemon(home);\n await startDaemon({ home, launch: nodeDaemonLaunch(home) });\n await useLocalManagement(false, async () => {});\n process.stderr.write('The bundled daemon is running and supports the required interfaces.\\n');\n}\n\nexport function registerServices(program: Command, host: ServicesHost): void {\n const createEndpoint = async (id: string, action: (client: EndpointClient, context: ManagementContext) => Promise<void>) => {\n try { await host.use(true, action); }\n catch (error) {\n if (error instanceof RpcError && error.message === `Endpoint \"${id}\" already exists in ${host.namespace()}`) {\n throw new RpcError(\n `${error.message}\\nAttach to it: ${host.attachCommand(id)}\\nOr replace it: rerun this command with --force`,\n error.code, error.data, error.origin, error.hasData,\n );\n }\n throw error;\n }\n };\n const services = program.command('services').description('Manage context-scoped endpoints through the selected daemon.')\n .option('--namespace <name>', 'managed endpoint namespace (defaults to selected context)');\n services.command('restart')\n .description('Stop the local daemon via RPC and start the bundled daemon; does not change OS autostart.')\n .action(() => host.restart());\n const addressed = (command: Command) => command.option('--id <id>', 'endpoint name in this context', 'main');\n const policy = (command: Command) => command.option('--persistent', 'retain definition across stop and daemon restart')\n .addOption(new Option('--restart <policy>', 'restart process or reconnect after failure').choices(['never', 'on-failure', 'always']).default('never'))\n .option('--force', 'stop and replace an existing endpoint with the same ID, even one owned by another terminal');\n policy(addressed(services.command('run <command...>').description('Start a process on the daemon; arguments follow --.')))\n .option('--detach', 'return after readiness')\n .addOption(new Option('--foreground', 'stop and remove the service when this CLI disconnects').conflicts(['detach', 'persistent']))\n .option('-t, --tty', 'run in a pseudoterminal; keys go to the program and Ctrl+P, Ctrl+Q detaches')\n .option('-x, --no-rpc', 'run a plain stdio process without an RPC connection; ready on spawn')\n .option('--cwd <directory>', 'working directory on the execution host')\n .option('--env <key=value...>', 'explicit child environment')\n .addOption(new Option('--readiness <mode>', 'wait for Hub connection or process spawn (default: connected, or spawned with --no-rpc)').choices(['connected', 'spawned']))\n .action(async (command: string[], options: {\n id: string; persistent?: boolean; restart: 'never' | 'on-failure' | 'always'; force?: boolean;\n detach?: boolean; foreground?: boolean; tty?: boolean; rpc: boolean; cwd?: string; env?: string[]; readiness?: 'connected' | 'spawned';\n }) => {\n if (!options.rpc && options.readiness === 'connected') throw new Error('--no-rpc cannot use --readiness connected; plain processes are ready on spawn.');\n const namespace = host.namespace();\n const env: Record<string, string> = {};\n for (const value of options.env ?? []) {\n const index = value.indexOf('=');\n if (index <= 0) throw new Error('--env requires KEY=value');\n env[value.slice(0, index)] = value.slice(index + 1);\n }\n await createEndpoint(options.id, async (client, context) => {\n const info = await client.info({});\n const cwd = options.cwd ?? (context.local ? process.cwd() : undefined);\n if (!cwd) throw new Error('Remote execution requires --cwd with a path on the execution host.');\n process.stderr.write(`Execution host: ${info.hostname}\\nNamespace: ${namespace}\\nEndpoint: ${options.id}\\nCommand: ${JSON.stringify(command)}\\nWorking directory: ${cwd}\\n`);\n const tty = options.tty === true;\n const size = tty ? localTerminalSize() : undefined;\n const detach = new AbortController();\n let status: EndpointStatus | undefined;\n let timedOut = false;\n const timeout = options.detach ? setTimeout(() => { timedOut = true; detach.abort(); }, 30_000) : undefined;\n try {\n const result = await runConsoleSession<Exclude<RunEvent, ConsoleServerMessage>>(onMessage => client.run({\n definition: {\n namespace, id: options.id, persistent: options.persistent ?? false, restart: options.restart,\n source: { kind: 'process', command, cwd, env, rpc: options.rpc, tty, readiness: options.readiness ?? (options.rpc ? 'connected' : 'spawned') },\n },\n owner: options.foreground === true,\n replace: options.force === true,\n console: { interactive: !options.detach, ...(size ? { size } : {}) },\n }, { onMessage }), {\n interactive: !options.detach,\n owner: options.foreground === true,\n reattachCommand: host.attachCommand(options.id),\n ...withDetachKeys(host),\n signal: detach.signal,\n }, event => {\n status = event.status;\n if (options.detach && status.runtime.state === 'running') detach.abort();\n });\n if (options.detach) {\n if (timedOut) throw new Error('Endpoint did not become ready within 30 seconds. It remains daemon-owned; use services list or logs to inspect it.');\n if (status?.runtime.state !== 'running') throw new Error(status?.runtime.error ?? 'Endpoint exited before readiness');\n print(status);\n } else if (!result.closedLocally && result.exit?.code) {\n process.exitCode = result.exit.code;\n } else if (!result.closedLocally && status?.runtime.state === 'failed' && !result.exit) {\n throw new Error(status.runtime.error ?? 'Endpoint failed');\n }\n } finally {\n clearTimeout(timeout);\n }\n });\n });\n policy(addressed(services.command('connect').description('Connect an existing LinkRPC endpoint; never owns its external process.')))\n .requiredOption('--target-endpoint <uri>', 'endpoint resolved on the daemon machine')\n .action(async (options: { id: string; targetEndpoint: string; persistent?: boolean; restart: 'never' | 'on-failure' | 'always'; force?: boolean }) => {\n const namespace = host.namespace();\n await createEndpoint(options.id, async client => {\n const info = await client.info({});\n process.stderr.write(`Execution host: ${info.hostname}\\nNamespace: ${namespace}\\nEndpoint: ${options.id}\\n`);\n const status = await client.create({\n namespace, id: options.id, persistent: options.persistent ?? false, restart: options.restart, replace: options.force === true,\n source: { kind: 'connection', endpoint: options.targetEndpoint },\n });\n print(await waitUntilReady(client, status));\n });\n });\n services.command('list').option('--all-contexts', 'include every namespace visible to this caller')\n .action(async (options: { allContexts?: boolean }) => {\n const namespace = options.allContexts ? undefined : host.namespace();\n await host.use(false, async client => print(await client.list({ namespace })));\n });\n for (const operation of ['start', 'stop', 'remove'] as const) {\n addressed(services.command(operation)).action(async (options: { id: string }) => {\n const namespace = host.namespace();\n await host.use(operation === 'start', async client => {\n if (operation === 'start') print(await waitUntilReady(client, await client.start({ namespace, id: options.id })));\n else print(await client[operation]({ namespace, id: options.id }));\n });\n });\n }\n addressed(services.command('configure'))\n .option('--persistent', 'retain this endpoint')\n .option('--no-persistent', 'remove it when stopped')\n .addOption(new Option('--restart <policy>').choices(['never', 'on-failure', 'always']))\n .action(async (options: { id: string; persistent?: boolean; restart?: 'never' | 'on-failure' | 'always' }, command: Command) => {\n const namespace = host.namespace();\n await host.use(false, async client => print(await client.configure({\n namespace, id: options.id, restart: options.restart,\n persistent: command.getOptionValueSource('persistent') === 'cli' ? options.persistent : undefined,\n })));\n });\n for (const operation of ['attach', 'logs'] as const) {\n const subcommand = addressed(services.command(operation));\n if (operation === 'attach') subcommand.option('--read-only', 'observe without sending input');\n else subcommand.option('--follow', 'follow new output');\n subcommand.action(async (options: { id: string; follow?: boolean; readOnly?: boolean }) => {\n const namespace = host.namespace();\n await host.use(false, async client => {\n const status = (await client.list({ namespace })).find(value => value.id === options.id);\n if (!status) throw new Error(`Endpoint \"${options.id}\" not found in ${namespace}`);\n if (!status.console) throw new Error(`Endpoint \"${options.id}\" is a connection and has no console`);\n const interactive = operation === 'attach' && options.readOnly !== true;\n const size = interactive ? localTerminalSize() : undefined;\n // The management interface's `consoles` template instance, addressed by endpoint, like `hub attach`.\n const result = await runConsoleSession(onMessage => client.consoles.attach({\n params: { namespace, id: options.id }, interactive, ...(size ? { size } : {}),\n }, { onMessage }), {\n interactive,\n owner: false,\n untilLive: operation === 'logs' && !options.follow,\n reattachCommand: host.attachCommand(options.id),\n ...withDetachKeys(host),\n });\n if (operation === 'attach' && !result.closedLocally && result.exit?.code) process.exitCode = result.exit.code;\n });\n });\n }\n}\n\n/** Wait until an endpoint runs; fail if it stops, fails, or is removed first. */\nasync function waitUntilReady(client: EndpointClient, initial: EndpointStatus): Promise<EndpointStatus> {\n if (initial.runtime.state === 'running') return initial;\n let current = initial;\n let outcome: 'ready' | 'finished' | 'removed' | 'timeout' | undefined;\n const call = client.watch({ namespace: initial.namespace, id: initial.id }, {\n onMessage: event => {\n if (event.t === 'removed') outcome = 'removed';\n else {\n current = event.status;\n if (current.runtime.state === 'running') outcome = 'ready';\n else if (['failed', 'stopped', 'disabled'].includes(current.runtime.state)) outcome = 'finished';\n }\n if (outcome) void call.cancel().catch(() => {});\n },\n });\n const timeout = setTimeout(() => { outcome ??= 'timeout'; void call.cancel().catch(() => {}); }, 30_000);\n try {\n await call;\n } catch (error) {\n if (!outcome) throw error;\n } finally {\n clearTimeout(timeout);\n }\n switch (outcome) {\n case 'ready': return current;\n case 'timeout': throw new Error('Endpoint did not become ready within 30 seconds. It remains daemon-owned; use services list or logs to inspect it.');\n default: throw new Error(current.runtime.error ?? 'Endpoint exited before readiness');\n }\n}\n\nfunction print(value: unknown): void { process.stdout.write(JSON.stringify(value, null, 2) + '\\n'); }\n","import type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport type { LinkRpcInterfaceSchema } from \"@hediet/linkrpc\";\nimport type { Command } from \"commander\";\nimport type React from \"react\";\nimport type { IObservable } from \"@vscode/observables\";\n\nexport type InterfaceCondition =\n | { readonly interfaceId: string }\n | { readonly tag: string };\n\nexport type ViewCondition =\n | { readonly kind: \"interface\"; readonly interface: InterfaceCondition }\n | { readonly kind: \"service\"; readonly implements: InterfaceCondition };\n\nexport interface ViewInterface {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash?: string;\n readonly tags?: readonly string[];\n readonly discoveredFrom: string;\n readonly isDefault?: boolean;\n}\n\n/** The schema hash is deliberately not part of identity: opening resolves it again. */\nexport interface ViewTarget {\n readonly id: string;\n readonly kind: \"interface\" | \"service\";\n readonly serviceId: string;\n readonly interfaceId?: string;\n readonly discoveredFrom: string;\n readonly interfaces: readonly ViewInterface[];\n /** Sibling advertisements on the same service, for optional companion protocols. */\n readonly serviceInterfaces?: readonly ViewInterface[];\n}\n\nexport interface ResolvedViewInterface extends ViewInterface {\n readonly schema: LinkRpcInterfaceSchema;\n}\n\nexport interface ViewOpenContext {\n readonly channel: CliChannel;\n readonly target: ViewTarget;\n readonly interfaces: readonly ResolvedViewInterface[];\n}\n\nexport interface ViewKeyEvent {\n readonly input: string;\n readonly name?: string;\n readonly ctrl?: boolean;\n readonly meta?: boolean;\n readonly shift?: boolean;\n}\n\n/** Named terminal keys (up, return, pageup, …) or a literal character. */\nexport interface ViewKeybinding {\n readonly key: string;\n readonly ctrl?: boolean;\n readonly meta?: boolean;\n readonly shift?: boolean;\n}\n\nexport interface ViewCommand {\n readonly id: string;\n readonly title: string;\n readonly keybindings: readonly ViewKeybinding[];\n readonly enabled?: boolean;\n /** Human-readable context, e.g. \"Graph\" or \"Editing parameters\". */\n readonly context?: string;\n execute(): void;\n}\n\nexport interface ViewSession {\n readonly element: React.ReactElement;\n /** Publish a new command list whenever availability, titles or context change. */\n readonly commands: IObservable<readonly ViewCommand[]>;\n /** Optional compact-legend limit; a view can expose full help as a command. */\n readonly maxLegendRows?: number;\n readonly capturesInput?: boolean;\n captureState?(): unknown;\n restoreState?(state: unknown): void;\n setViewport?(rows: number, columns?: number): void;\n /** Called only while capturesInput is true, after declarative commands. */\n handleTextInput?(event: ViewKeyEvent): boolean;\n dispose(): void;\n disposeAsync?(): Promise<void>;\n}\n\n/** Compiled-in contributions; matching is discovery, never authorization. */\nexport interface ViewContribution {\n readonly id: string;\n readonly title: string;\n readonly modes: readonly (\"cli\" | \"tui\")[];\n readonly conditions: readonly ViewCondition[];\n configureCommand(command: Command): void;\n open(context: ViewOpenContext, options: Readonly<Record<string, unknown>>): Promise<string>;\n createSession(context: ViewOpenContext): ViewSession;\n}\n\nexport function formatCondition(condition: ViewCondition): string {\n const match = condition.kind === \"interface\" ? condition.interface : condition.implements;\n const predicate = \"tag\" in match ? `tag(${match.tag})` : `id(${match.interfaceId})`;\n return condition.kind === \"interface\" ? `interface:${predicate}` : `service:implements(${predicate})`;\n}\n\nexport function matchesInterface(value: ViewInterface, condition: InterfaceCondition): boolean {\n return \"tag\" in condition\n ? value.tags?.includes(condition.tag) === true\n : value.interfaceId === condition.interfaceId;\n}\n\nexport function matchesTarget(target: ViewTarget, view: Pick<ViewContribution, \"conditions\">): boolean {\n return view.conditions.some(condition => condition.kind === target.kind\n && target.interfaces.some(value => matchesInterface(value,\n condition.kind === \"interface\" ? condition.interface : condition.implements)));\n}\n\nexport function targetId(kind: ViewTarget[\"kind\"], listing: ViewInterface): string {\n return `${kind}:${encodeURIComponent(listing.serviceId)}:${encodeURIComponent(listing.discoveredFrom)}`\n + (kind === \"interface\" ? `:${encodeURIComponent(listing.interfaceId)}:${listing.isDefault ? \"default\" : \"qualified\"}` : \"\");\n}\n\nexport function interfaceTarget(listing: ViewInterface): ViewTarget {\n return {\n id: targetId(\"interface\", listing), kind: \"interface\", serviceId: listing.serviceId,\n interfaceId: listing.interfaceId, discoveredFrom: listing.discoveredFrom, interfaces: [listing],\n };\n}\n","import { fetchDefaults, fetchSchema, type CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { HubDirectoryExplorer } from \"@hediet/linkrpc/hub/common\";\nimport { interfaceTarget, matchesInterface, matchesTarget, targetId, type ViewContribution, type ViewInterface, type ViewOpenContext, type ViewTarget } from \"./types\";\n\nexport interface ViewDiscoveryOptions {\n readonly maxDepth?: number;\n readonly timeoutMs?: number;\n}\n\nexport interface ViewSelectionOptions extends ViewDiscoveryOptions {\n readonly target?: string;\n readonly interface?: string;\n readonly service?: string;\n}\n\nexport async function discoverViewTargets(channel: CliChannel, view: ViewContribution, options: ViewDiscoveryOptions = {}) {\n const explorer = new HubDirectoryExplorer(channel, options);\n const warnings: string[] = [];\n try {\n await explorer.explore();\n const snapshot = explorer.graphSnapshot.result;\n warnings.push(...snapshot.inaccessible.map(item => `${item.serviceId || \"<root>\"}: ${item.reason}`));\n const listings: ViewInterface[] = [...snapshot.listings];\n try {\n const defaults = await deadline(fetchDefaults(channel), options.timeoutMs ?? 5_000);\n if (defaults.interfaceId !== undefined) {\n const existing = listings.find(item => item.serviceId === \"\" && item.interfaceId === defaults.interfaceId);\n listings.unshift({\n serviceId: \"\", interfaceId: defaults.interfaceId, hash: defaults.hash ?? existing?.hash,\n discoveredFrom: \"\", isDefault: true, tags: existing?.tags,\n });\n }\n } catch (error) {\n warnings.push(`Default service: ${message(error)}`);\n }\n // Absent tags mean no advertised labels. Discovery never scans schemas;\n // opening separately validates the selected implementation's contract.\n const interfacesById = new Map<string, ViewTarget>();\n for (const listing of listings) {\n const target = interfaceTarget(listing);\n const previous = interfacesById.get(target.id);\n interfacesById.set(target.id, previous === undefined ? target\n : { ...previous, interfaces: [...previous.interfaces, listing] });\n }\n const targets: ViewTarget[] = [...interfacesById.values()];\n const services = new Map<string, ViewInterface[]>();\n for (const listing of listings) {\n const id = targetId(\"service\", listing);\n const values = services.get(id) ?? [];\n // Prefer default routing for the main interface of the root service.\n if (!values.some(value => value.interfaceId === listing.interfaceId && value.hash === listing.hash)) values.push(listing);\n services.set(id, values);\n }\n for (const [id, interfaces] of services) {\n const first = interfaces[0]!;\n targets.push({ id, kind: \"service\", serviceId: first.serviceId, discoveredFrom: first.discoveredFrom, interfaces });\n }\n return { targets: targets.filter(target => matchesTarget(target, view))\n .map(target => ({ ...target, serviceInterfaces: listings.filter(listing =>\n listing.serviceId === target.serviceId && listing.discoveredFrom === target.discoveredFrom) }))\n .sort((a, b) => a.id.localeCompare(b.id)), warnings };\n } finally {\n explorer.dispose();\n }\n}\n\nexport async function resolveViewTarget(channel: CliChannel, view: ViewContribution, id: string, options: ViewDiscoveryOptions = {}): Promise<ViewOpenContext> {\n const { targets } = await discoverViewTargets(channel, view, options);\n const target = targets.find(value => value.id === id);\n if (!target) throw new Error(`Unknown or unavailable ${view.id} target \"${id}\". Run view targets ${view.id} again.`);\n return loadViewTarget(channel, target, options.timeoutMs, view);\n}\n\n/** Selection and opening share a connection, including spawned ephemeral endpoints. */\nexport async function resolveViewSelection(channel: CliChannel, view: ViewContribution, options: ViewSelectionOptions): Promise<ViewOpenContext> {\n if (options.target !== undefined) {\n const context = await resolveViewTarget(channel, view, options.target, options);\n if (options.service !== undefined && context.target.serviceId !== options.service) {\n throw new Error(\"--target does not match --service\");\n }\n if (options.interface !== undefined && !context.target.interfaces.some(value => value.interfaceId === options.interface)) {\n throw new Error(\"--target does not match --interface\");\n }\n return context;\n }\n if (options.interface === undefined && options.service === undefined) {\n throw new Error(\"Specify --target, or an exact --interface / --service selector\");\n }\n const discovery = await discoverViewTargets(channel, view, options);\n const candidates = discovery.targets.filter(target =>\n target.kind === (options.interface === undefined ? \"service\" : \"interface\")\n && (options.interface === undefined || target.interfaceId === options.interface)\n && (options.service === undefined || target.serviceId === options.service));\n // Defaults can also appear as qualified directory entries. They represent\n // the same implementation, not an ambiguity between two endpoint routes.\n const matches = candidates.filter(target => target.kind !== \"interface\"\n || target.interfaces.some(value => value.isDefault)\n || !candidates.some(other => other.serviceId === target.serviceId\n && other.discoveredFrom === target.discoveredFrom\n && other.interfaceId === target.interfaceId\n && other.interfaces.every(value => target.interfaces.some(candidate => candidate.hash === value.hash))\n && target.interfaces.every(value => other.interfaces.some(candidate => candidate.hash === value.hash))\n && other.interfaces.some(value => value.isDefault)));\n if (matches.length !== 1) {\n const detail = matches.length === 0 ? \"No matching target\" : `Target selection is ambiguous (${matches.length} targets)`;\n throw new Error(`${detail}; use --service to narrow the selection or --target from view targets ${view.id}`);\n }\n return loadViewTarget(channel, matches[0]!, options.timeoutMs, view);\n}\n\nexport async function loadViewTarget(channel: CliChannel, target: ViewTarget, timeoutMs = 5_000, view?: ViewContribution): Promise<ViewOpenContext> {\n const candidates = view === undefined || target.kind === \"interface\" ? target.interfaces\n : target.interfaces.filter(listing => view.conditions.some(condition =>\n condition.kind === \"service\" && matchesInterface(listing, condition.implements)));\n for (const listing of candidates) {\n if (candidates.some(other => other.interfaceId === listing.interfaceId && other.hash !== listing.hash)) {\n throw new Error(`Target \"${target.id}\" is ambiguous: interface \"${listing.interfaceId}\" advertises multiple schema hashes`);\n }\n }\n return {\n channel, target,\n interfaces: await Promise.all(candidates.map(async listing => {\n // Use the freshly advertised hash, not a hash embedded in a saved\n // target ID. Different services can implement different revisions.\n const schema = await deadline(fetchSchema(channel, listing.interfaceId, listing.hash, listing.discoveredFrom || undefined), timeoutMs);\n if (schema.id !== listing.interfaceId || (listing.hash !== undefined && schema.hash !== listing.hash)) {\n throw new Error(`Schema for \"${listing.interfaceId}\" does not match its current directory advertisement; rediscover the target`);\n }\n return { ...listing, hash: schema.hash, schema };\n })),\n };\n}\n\nasync function deadline<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([promise, new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`Reflection timed out after ${timeoutMs}ms`)), timeoutMs);\n })]);\n } finally { clearTimeout(timer); }\n}\n\nfunction message(error: unknown): string { return error instanceof Error ? error.message : String(error); }\n","import {\n createSchemaToZod,\n interfaceTemplateMemberName,\n interfaceTemplatesEqual,\n INTERFACE_TEMPLATES_EXTENSION,\n validateInterfaceTemplates,\n type InterfaceTemplateArgument,\n type InterfaceTemplatesMetadata,\n type JsonValue,\n} from '@hediet/linkrpc';\nimport type { CliChannel } from '@hediet/linkrpc-client-internal';\nimport {\n CONSOLE_INTERFACE_TAG,\n consoleAttachResultSchema,\n consoleServerMessageSchema,\n ConsoleTemplate,\n type ConsoleAttachParams,\n type ConsoleServerMessage,\n} from '@hediet/linkrpc-infra/console';\nimport { unknown } from 'zod/mini';\nimport { discoverViewTargets, loadViewTarget, resolveViewSelection } from '../views/discovery';\nimport type { ResolvedViewInterface, ViewContribution } from '../views/types';\nimport { localTerminalSize, runConsoleSession, type ConsoleCall, type DetachKeys } from './consoleSession';\n\n/** One instance of the `linkrpc.console.v1` template, found through reflection. */\nexport interface ConsoleTarget {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly instance: string;\n readonly infoMethod: string;\n readonly attachMethod: string;\n readonly params: InterfaceTemplateArgument;\n}\n\nexport interface AttachConsoleOptions {\n readonly serviceId: string;\n readonly interfaceId?: string;\n readonly instance?: string;\n /** JSON params of the selected instance; defaults to `{}`. */\n readonly params?: string;\n readonly readOnly?: boolean;\n readonly detachKeys?: DetachKeys;\n readonly reattachCommand: string;\n}\n\nconst consoleTemplate = ConsoleTemplate({ params: unknown() }).template;\n\n/** Discovery-only view: the generic `attach` command reuses directory and reflection resolution. */\nexport const consoleDiscovery: ViewContribution = {\n id: 'console', title: 'Console', modes: ['cli'],\n conditions: [\n { kind: 'interface', interface: { tag: CONSOLE_INTERFACE_TAG } },\n { kind: 'service', implements: { tag: CONSOLE_INTERFACE_TAG } },\n ],\n configureCommand() {},\n open() { throw new Error('Use the attach command'); },\n createSession() { throw new Error('Consoles have no TUI view'); },\n};\n\n/** Console template instances in reflected schemas; tags are only discovery hints. */\nexport function consoleTargets(interfaces: readonly ResolvedViewInterface[]): ConsoleTarget[] {\n return interfaces.flatMap(listing => {\n const metadata = listing.schema[INTERFACE_TEMPLATES_EXTENSION] as InterfaceTemplatesMetadata | undefined;\n if (metadata === undefined) return [];\n validateInterfaceTemplates(listing.schema);\n return metadata.instances.flatMap(instance => {\n const template = metadata.templates[instance.template];\n if (template?.id !== consoleTemplate.id) return [];\n if (!interfaceTemplatesEqual(template, consoleTemplate)) {\n throw new Error(`${listing.interfaceId} uses an unsupported revision of the ${consoleTemplate.id} template`);\n }\n const method = (member: string) => {\n const name = interfaceTemplateMemberName(instance, member);\n if (listing.isDefault) return name;\n return listing.serviceId === '' ? `${listing.interfaceId}::${name}` : `${listing.serviceId}::${listing.interfaceId}::${name}`;\n };\n const params = instance.arguments.params;\n if (params === undefined) throw new Error(`Console instance \"${instance.name}\" is missing its params argument`);\n return [{\n serviceId: listing.serviceId, interfaceId: listing.interfaceId, instance: instance.name,\n infoMethod: method('info'), attachMethod: method('attach'), params,\n }];\n });\n });\n}\n\n/** List console targets without attaching: discovery uses directory tags, then reflection resolves instances. */\nexport async function listConsoleTargets(channel: CliChannel): Promise<string> {\n const discovery = await discoverViewTargets(channel, consoleDiscovery);\n const rows: string[] = [];\n for (const target of discovery.targets.filter(value => value.kind === 'service')) {\n const context = await loadViewTarget(channel, target, undefined, consoleDiscovery);\n for (const console of consoleTargets(context.interfaces)) {\n rows.push(`${console.serviceId || '<root>'} ${console.interfaceId} ${console.instance} ${JSON.stringify(console.params.schema)}`);\n }\n }\n return [\n rows.length === 0 ? 'No services offer linkrpc.console.' : 'SERVICE INTERFACE INSTANCE PARAMS',\n ...rows,\n ...discovery.warnings.map(warning => `warning: ${warning}`),\n ].join('\\n');\n}\n\n/** Attach to any service implementing the console template, selected by service, interface, and instance. */\nexport async function attachConsole(channel: CliChannel, options: AttachConsoleOptions): Promise<void> {\n const context = await resolveViewSelection(channel, consoleDiscovery, {\n service: options.serviceId, ...(options.interfaceId === undefined ? {} : { interface: options.interfaceId }),\n });\n const candidates = consoleTargets(context.interfaces)\n .filter(target => options.instance === undefined || target.instance === options.instance);\n if (candidates.length !== 1) {\n const names = consoleTargets(context.interfaces).map(target => `${target.interfaceId}#${target.instance}`).join(', ');\n throw new Error(candidates.length === 0\n ? `No console instance matches on \"${options.serviceId}\"${names ? ` (available: ${names})` : ''}`\n : `Several consoles are available (${names}); select one with --instance or --interface`);\n }\n const target = candidates[0]!;\n let params: unknown;\n try { params = JSON.parse(options.params ?? '{}'); }\n catch { throw new Error('--params must be valid JSON'); }\n const validation = createSchemaToZod(target.params.components?.schemas ?? {}).toZod(target.params.schema).safeParse(params);\n if (!validation.success) {\n throw new Error(`--params does not match the params of console \"${target.instance}\" `\n + `(${JSON.stringify(target.params.schema)}): ${validation.error.message}`);\n }\n const interactive = options.readOnly !== true;\n const size = interactive ? localTerminalSize() : undefined;\n const result = await runConsoleSession(onMessage => rawConsoleCall(channel, target.attachMethod, {\n params: params as JsonValue, interactive, ...(size ? { size } : {}),\n }, onMessage), {\n interactive, owner: false, reattachCommand: options.reattachCommand,\n ...(options.detachKeys ? { detachKeys: options.detachKeys } : {}),\n });\n if (!result.closedLocally && result.exit?.code) process.exitCode = result.exit.code;\n}\n\n/** Call a reflected attach method on the raw channel, validating every stream message against the protocol. */\nfunction rawConsoleCall(\n channel: Pick<CliChannel, 'sendRequestWithStream'>,\n method: string,\n params: ConsoleAttachParams & { readonly params: JsonValue },\n onMessage: (message: ConsoleServerMessage) => void,\n): ConsoleCall {\n const call = channel.sendRequestWithStream(method, params as JsonValue, {\n onStreamMessage: payload => {\n const message = consoleServerMessageSchema.safeParse(payload);\n onMessage(message.success ? message.data : { t: 'notice', text: `Ignored an invalid console message: ${message.error.message}` });\n },\n });\n const result = call.result.then(value => consoleAttachResultSchema.parse(value));\n void result.finally(() => call.dispose?.()).catch(() => {});\n return {\n then: (onFulfilled, onRejected) => result.then(onFulfilled, onRejected),\n send: message => call.send(message as JsonValue),\n cancel: () => call.cancel('detached'),\n };\n}\n","import { readFileSync } from \"node:fs\";\n\n/**\n * Read params either from a `--params <json>` argument (treated as inline\n * JSON) or `--params -` (read from stdin). `undefined` if neither was given.\n */\nexport function readParamsArg(value: string | undefined): unknown {\n if (value === undefined) return undefined;\n const text = value === \"-\" ? readFileSync(0, \"utf8\") : value;\n const trimmed = text.trim();\n if (trimmed.length === 0) return undefined;\n try {\n return JSON.parse(trimmed);\n } catch (e) {\n throw new Error(`--params: invalid JSON (${(e as Error).message})`);\n }\n}\n\nexport function formatJson(v: unknown): string {\n if (v === undefined) return \"undefined\";\n return JSON.stringify(v, null, 2);\n}\n\n/** Stringify a value for one-line tabular output. */\nexport function oneLine(v: unknown): string {\n if (v === undefined) return \"\";\n if (typeof v === \"string\") return v;\n return JSON.stringify(v);\n}\n","import { isAssignable, matchParams, schemaToZod, type LinkRpcInterfaceSchema, type LinkRpcJsonSchema, type ParamMatcher } from '@hediet/linkrpc';\nimport { findCoveringCapabilities, type HubAccessDuration, type HubAccessPermission } from '@hediet/linkrpc/hub/common';\nimport { fetchDefaults, findMethodInSchema, type CliChannel, type SigningSession } from '@hediet/linkrpc-client-internal';\nimport { z } from 'zod';\nimport type { MethodRefWithOptHash } from '../methodRef';\nimport { parseParamOverride } from '../paramParsing';\nimport { formatJson } from '../output';\n\nconst matcherSchema = z.union([\n z.strictObject({ exact: z.json() }),\n z.strictObject({ enum: z.array(z.json()).min(1) }),\n z.strictObject({ prefix: z.string() }),\n z.strictObject({ subsetOf: z.array(z.string()) }),\n z.strictObject({ any: z.literal(true) }),\n]);\n\nexport interface RequestCallCapabilityOptions {\n readonly allowParams?: readonly string[];\n readonly duration?: HubAccessDuration;\n}\n\nexport async function requestCallCapability(\n channel: CliChannel,\n session: SigningSession,\n ref: MethodRefWithOptHash,\n params: unknown,\n schema: LinkRpcInterfaceSchema,\n opts: RequestCallCapabilityOptions,\n): Promise<string> {\n const method = findMethodInSchema(schema, ref.methodName);\n if (method === undefined) throw new Error(`Unknown method ${ref.getMethodOnWire()}.`);\n const matchers = createParamMatchers(params, opts.allowParams ?? [], method.params, schema.components?.schemas);\n const defaults = ref.interfaceId === undefined ? await fetchDefaults(channel) : undefined;\n const permission: HubAccessPermission = {\n target: {\n serviceId: { exact: ref.serviceId ?? defaults?.serviceId ?? '' },\n interfaceId: { exact: ref.interfaceId ?? schema.id },\n members: [{ exact: ref.methodName }],\n ...(ref.hash !== undefined ? { interfaceHash: ref.hash } : {}),\n },\n canInvoke: true,\n params: matchers,\n };\n const coverageOptions = { audience: session.principal.id, freshnessMarginMs: 2000 };\n const cached = findCoveringCapabilities(session.listGrants(), [permission], coverageOptions);\n if (cached !== undefined) {\n return formatJson({ status: 'granted', reused: true, capabilities: cached });\n }\n const result = await session.requestAccess({\n consumer: { name: 'linkrpc-cli', purpose: `Invoke ${ref.getMethodOnWire()}.` },\n permissions: [permission],\n duration: opts.duration ?? 'persistent',\n });\n if (result.status !== 'granted') {\n const reason = 'reason' in result ? result.reason : undefined;\n throw new Error(`Capability request ${result.status}${reason ? `: ${reason}` : '.'}`);\n }\n if (findCoveringCapabilities(session.listGrants(), [permission], coverageOptions) === undefined) {\n throw new Error('The granted capabilities do not cover the requested durable scope.');\n }\n return formatJson({ ...result, reused: false });\n}\n\nexport function createParamMatchers(\n params: unknown,\n allowParams: readonly string[],\n schema: LinkRpcJsonSchema,\n components: Record<string, LinkRpcJsonSchema> = {},\n): Record<string, ParamMatcher> {\n if (params !== undefined && (params === null || typeof params !== 'object' || Array.isArray(params))) {\n throw new Error('Capability requests require object parameters.');\n }\n const actual: Record<string, unknown> = params === undefined ? {} : Object.fromEntries(Object.entries(params));\n const matchers: Record<string, ParamMatcher> = Object.fromEntries(\n Object.entries(actual).map(([key, value]) => [key, { exact: value }]),\n );\n const seen = new Set<string>();\n for (const raw of allowParams) {\n const { path, value } = parseParamOverride(raw);\n if (path.length !== 1) throw new Error('--cap:allow-param only supports top-level parameter names.');\n const key = path[0];\n if (seen.has(key)) throw new Error(`Duplicate --cap:allow-param for ${key}.`);\n seen.add(key);\n const parsed = matcherSchema.safeParse(value);\n if (!parsed.success) throw new Error(`Invalid --cap:allow-param ${key}: ${parsed.error.message}`);\n matchers[key] = parsed.data;\n }\n const properties = Object.fromEntries(\n Object.entries(matchers).map(([key, matcher]) => [key, matcherToSchema(matcher)]),\n );\n if (!isAssignable({\n type: 'object', properties, required: Object.keys(properties), additionalProperties: false,\n }, schema, { schemas: components })) {\n throw new Error('--cap:allow-param scope does not match the method parameter schema.');\n }\n const validator = schemaToZod(schema, components);\n const samples = [actual];\n for (const [key, matcher] of Object.entries(matchers)) {\n const values = 'exact' in matcher ? [matcher.exact] : 'enum' in matcher ? matcher.enum\n : 'subsetOf' in matcher ? [[], ...matcher.subsetOf.map(value => [value])] : [];\n for (const value of values) samples.push({ ...actual, [key]: value });\n }\n for (const sample of samples) {\n const validated = validator.safeParse(sample);\n if (!validated.success) throw new Error(`Capability parameter schema validation failed: ${validated.error.message}`);\n }\n const matched = matchParams(matchers, actual);\n if (!matched.ok) throw new Error(`Parameters do not match --cap:allow-param: ${matched.reason}`);\n return matchers;\n}\n\nfunction matcherToSchema(matcher: ParamMatcher): LinkRpcJsonSchema {\n if ('any' in matcher) return true;\n if ('prefix' in matcher) return { type: 'string' };\n if ('subsetOf' in matcher) {\n return { type: 'array', items: { enum: matcher.subsetOf } };\n }\n if ('enum' in matcher) return { enum: z.array(z.json()).parse(matcher.enum) };\n return { const: z.json().parse(matcher.exact) };\n}\n\nexport function listCaps(session: SigningSession, json: boolean): string {\n const capabilities = session.listGrants();\n return json ? formatJson({ principal: session.principal.id, capabilities })\n : `principal: ${session.principal.id}\\n${capabilities.length === 0 ? 'No stored capabilities.' : formatJson(capabilities)}`;\n}\n","/**\n * \"Did you mean…\" suggestions for failed `hub call` / `hub notify` invocations.\n *\n * Drives off a static snapshot of the hub (`HubSnapshot`) so the formatter is\n * pure-functional and exhaustively testable with literal strings. A snapshot\n * is built by walking the bus once (`HubSnapshot.load`) on the error path.\n *\n * The matrix is resolved left-to-right (serviceId, interfaceId, method): the\n * first token that doesn't resolve dictates the suggestion scope, and we never\n * propose replacements for positions to its left.\n */\nimport { MethodRefWithOptHash } from './methodRef';\nimport {\n fetchSchema,\n walkHub,\n type CliChannel,\n} from '@hediet/linkrpc-client-internal';\n\n// ---------------------------------------------------------------------------\n// HubSnapshot\n// ---------------------------------------------------------------------------\n\nexport interface SnapshotEntry {\n /** Empty string = root. */\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly methods: readonly string[];\n}\n\nconst _SYSTEM_PREFIX = 'hubrpc.';\n\nfunction _isSystemInterface(id: string): boolean {\n return id.startsWith(_SYSTEM_PREFIX);\n}\n\nfunction _isUserInterface(id: string): boolean {\n return !_isSystemInterface(id);\n}\n\n/**\n * Indexed view of the bus's directory + per-interface methods. Constructed\n * directly from a list of entries (tests) or by walking a live channel\n * (`HubSnapshot.load`). Read-only after construction.\n */\nexport class HubSnapshot {\n private readonly _byService = new Map<string, Map<string, SnapshotEntry>>();\n private readonly _byInterface = new Map<string, string[]>();\n private readonly _byMethodName = new Map<string, { serviceId: string; interfaceId: string; }[]>();\n\n constructor(public readonly entries: readonly SnapshotEntry[]) {\n for (const e of entries) {\n let byIface = this._byService.get(e.serviceId);\n if (!byIface) {\n byIface = new Map();\n this._byService.set(e.serviceId, byIface);\n }\n byIface.set(e.interfaceId, e);\n\n const hosts = this._byInterface.get(e.interfaceId) ?? [];\n if (!hosts.includes(e.serviceId)) hosts.push(e.serviceId);\n this._byInterface.set(e.interfaceId, hosts);\n\n for (const m of e.methods) {\n const locs = this._byMethodName.get(m) ?? [];\n locs.push({ serviceId: e.serviceId, interfaceId: e.interfaceId });\n this._byMethodName.set(m, locs);\n }\n }\n }\n\n /** All serviceIds present on the bus, in encounter order (\"\" = root). */\n services(): readonly string[] {\n return [...this._byService.keys()];\n }\n\n /** All distinct interface ids (system + user), in encounter order. */\n interfaces(): readonly string[] {\n return [...this._byInterface.keys()];\n }\n\n interfacesOnService(serviceId: string): readonly string[] {\n const m = this._byService.get(serviceId);\n return m ? [...m.keys()] : [];\n }\n\n servicesHostingInterface(interfaceId: string): readonly string[] {\n return this._byInterface.get(interfaceId) ?? [];\n }\n\n methodsOn(serviceId: string, interfaceId: string): readonly string[] {\n return this._byService.get(serviceId)?.get(interfaceId)?.methods ?? [];\n }\n\n locationsOfMethod(name: string): readonly { serviceId: string; interfaceId: string; }[] {\n return this._byMethodName.get(name) ?? [];\n }\n\n /**\n * Walk the live bus once and fetch the schema for every (service, interface)\n * pair in parallel. Failures on individual schema fetches are absorbed —\n * the affected entry just ends up with `methods: []`, so it still\n * participates in service/interface-level suggestions.\n */\n static async load(channel: CliChannel): Promise<HubSnapshot> {\n const listings = await walkHub(channel);\n const entries = await Promise.all(listings.map(async (l): Promise<SnapshotEntry> => {\n try {\n const schema = await fetchSchema(\n channel,\n l.interfaceId,\n l.hash,\n l.serviceId || undefined,\n );\n return {\n serviceId: l.serviceId,\n interfaceId: l.interfaceId,\n hash: l.hash,\n methods: Object.keys(schema.methods),\n };\n } catch {\n return {\n serviceId: l.serviceId,\n interfaceId: l.interfaceId,\n hash: l.hash,\n methods: [],\n };\n }\n }));\n return new HubSnapshot(entries);\n }\n}\n\n// ---------------------------------------------------------------------------\n// formatSuggestion (entry point)\n// ---------------------------------------------------------------------------\n\nexport interface SuggestionInput {\n readonly ref: MethodRefWithOptHash;\n readonly snapshot: HubSnapshot;\n /** Verb embedded in copy-paste lines (`hub call` vs `hub notify`). */\n readonly verb: 'call' | 'notify';\n /** CLI binary name; defaults to `hub`. */\n readonly tool?: string;\n}\n\ninterface _Ctx {\n ref: MethodRefWithOptHash;\n snapshot: HubSnapshot;\n verb: 'call' | 'notify';\n tool: string;\n}\n\n/**\n * Compose a multi-line \"Did you mean…\" message tailored to the failed ref.\n * The returned string has no trailing newline and no `linkrpc:` prefix (the\n * outer error path adds those).\n */\nexport function formatSuggestion(input: SuggestionInput): string {\n const ctx: _Ctx = {\n ref: input.ref,\n snapshot: input.snapshot,\n verb: input.verb,\n tool: input.tool ?? 'hub',\n };\n if (ctx.ref.serviceId !== undefined && ctx.ref.interfaceId !== undefined) {\n return _suggestForm3(ctx);\n }\n if (ctx.ref.interfaceId !== undefined) {\n return _suggestForm2(ctx);\n }\n return _suggestForm1(ctx);\n}\n\nfunction _qualify(ctx: _Ctx, s: string, i: string, m: string): string {\n return `${ctx.tool} ${ctx.verb} ${s}::${i}::${m}`;\n}\n\n// ---------------------------------------------------------------------------\n// Form 1: `<method>` (bare token, no preset)\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm1(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const token = ref.methodName;\n\n // A1: token is itself a serviceId\n if (token !== '' && snapshot.services().includes(token)) {\n const samples = _sampleCallsForService(ctx, token, 3);\n const lines = [`\"${token}\" is a serviceId, not a method.`];\n lines.push(' See its interfaces:');\n lines.push(` ${ctx.tool} ls --service ${token}`);\n if (samples.length > 0) {\n lines.push(' Or call one:');\n for (const s of samples) lines.push(` ${s}`);\n }\n return lines.join('\\n');\n }\n\n // A2: token is an interfaceId\n if (snapshot.interfaces().includes(token) && _isUserInterface(token)) {\n const hosts = snapshot.servicesHostingInterface(token).filter((s) => s !== '');\n const samples = _sampleCallsForInterface(ctx, token, 3);\n const lines = [\n `\"${token}\" is an interface, not a method. It's hosted on services: ${hosts.join(', ')}.`,\n ];\n if (samples.length > 0) {\n lines.push(' Try a call:');\n for (const s of samples) lines.push(` ${s}`);\n }\n return lines.join('\\n');\n }\n\n // A3/A4: token is exactly a method name on one or more interfaces\n const locs = snapshot\n .locationsOfMethod(token)\n .filter((l) => _isUserInterface(l.interfaceId));\n if (locs.length > 0) {\n const lines = [`\"${token}\" is not callable without an interface (no preset is set).`];\n lines.push(' Did you mean:');\n for (const l of locs.slice(0, 5)) {\n lines.push(` ${_qualify(ctx, l.serviceId, l.interfaceId, token)}`);\n }\n return lines.join('\\n');\n }\n\n // A5/A6/A7: fuzzy fallback\n return _suggestForm1Fuzzy(ctx);\n}\n\nfunction _suggestForm1Fuzzy(ctx: _Ctx): string {\n const { snapshot } = ctx;\n const token = ctx.ref.methodName;\n\n const methodHits = _rankAllMethods(snapshot, token, 3);\n const ifaceHits = _rankAllInterfaces(snapshot, token, 3);\n const svcHits = _rankServices(snapshot, token, 3);\n\n const lines = [`\"${token}\" matches no known service, interface, or method.`];\n if (methodHits.length > 0) {\n lines.push(' Closest methods:');\n for (const h of methodHits) {\n lines.push(` ${_qualify(ctx, h.serviceId, h.interfaceId, h.name)}`);\n }\n }\n if (ifaceHits.length > 0) {\n lines.push(' Closest interfaces:');\n for (const id of ifaceHits) {\n const sampleSvc = snapshot\n .servicesHostingInterface(id)\n .find((s) => s !== '') ?? snapshot.servicesHostingInterface(id)[0];\n lines.push(` ${id} (try ${ctx.tool} ${ctx.verb} ${sampleSvc ?? ''}::${id}::<method>)`);\n }\n }\n if (svcHits.length > 0) {\n lines.push(' Closest services:');\n for (const s of svcHits) {\n lines.push(` ${s} (try ${ctx.tool} ls --service ${s})`);\n }\n }\n if (methodHits.length === 0 && ifaceHits.length === 0 && svcHits.length === 0) {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Form 2: `<interface>::<method>`\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm2(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const iface = ref.interfaceId!;\n const method = ref.methodName;\n const hostsOfIface = snapshot.servicesHostingInterface(iface);\n\n if (hostsOfIface.length === 0) {\n // Interface unknown.\n // B3: first token is actually a serviceId\n if (iface !== '' && snapshot.services().includes(iface)) {\n // B3a: the second token is an exact method name on that service\n // (e.g. `azure-cli::runCommand` → fully-qualified suggestion).\n const locs = snapshot\n .locationsOfMethod(method)\n .filter((l) => l.serviceId === iface && _isUserInterface(l.interfaceId));\n if (locs.length > 0) {\n const lines = [\n `Interface \"${method}\" not found on service \"${iface}\", `\n + `but \"${method}\" is a method name there.`,\n ];\n lines.push(' Did you mean:');\n for (const l of locs.slice(0, 3)) {\n lines.push(` ${_qualify(ctx, l.serviceId, l.interfaceId, method)}`);\n }\n return lines.join('\\n');\n }\n\n // B3b: prefix or full enumeration — list interfaces on the service.\n // Typing `vscode::vscode.` is navigation, not a typo; show what's\n // available rather than guessing methods.\n return _formatInterfaceListOnService(ctx, iface, method);\n }\n\n // B2: fuzzy interfaces, boost ones where `method` exists\n const candidates = _rankInterfacesWithMethodBoost(snapshot, iface, method, 3);\n const lines = [`Interface \"${iface}\" not found.`];\n if (candidates.length > 0) {\n lines.push(' Did you mean:');\n for (const c of candidates) {\n lines.push(` ${_qualify(ctx, c.serviceId, c.interfaceId, c.methodToTry)}`);\n }\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n }\n\n // Interface valid on >=1 service. Method missing on all of them.\n // B1/B4: fuzzy methods across hosts\n const fuzzy = _rankMethodsOnInterface(snapshot, iface, method, 3);\n if (fuzzy.length > 0) {\n const where = hostsOfIface.length === 1 ? ` (service: ${hostsOfIface[0]})` : '';\n const lines = [`Method \"${method}\" not found on interface \"${iface}\"${where}.`];\n lines.push(' Did you mean:');\n for (const f of fuzzy) {\n lines.push(` ${_qualify(ctx, f.serviceId, iface, f.methodName)}`);\n }\n return lines.join('\\n');\n }\n\n // B5: enumerate everything available under this interface\n const lines = [`Method \"${method}\" not found on interface \"${iface}\".`];\n lines.push(' Available methods:');\n let count = 0;\n for (const s of hostsOfIface) {\n for (const m of snapshot.methodsOn(s, iface)) {\n if (count >= 12) break;\n lines.push(` ${_qualify(ctx, s, iface, m)}`);\n count++;\n }\n if (count >= 12) break;\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Form 3: `<svc>::<iface>::<method>`\n// ---------------------------------------------------------------------------\n\nfunction _suggestForm3(ctx: _Ctx): string {\n const { ref, snapshot } = ctx;\n const svc = ref.serviceId!;\n const iface = ref.interfaceId!;\n const method = ref.methodName;\n\n // C4/C7: service unknown\n if (!snapshot.services().includes(svc)) {\n const hits = _rankServices(snapshot, svc, 3, (cand) => {\n const ifaces = snapshot.interfacesOnService(cand);\n if (ifaces.includes(iface) && snapshot.methodsOn(cand, iface).includes(method)) {\n return 200;\n }\n if (ifaces.includes(iface)) return 100;\n return 0;\n });\n const lines = [`Service \"${svc}\" not found.`];\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n const ifacesOnH = snapshot.interfacesOnService(h);\n if (ifacesOnH.includes(iface) && snapshot.methodsOn(h, iface).includes(method)) {\n lines.push(` ${_qualify(ctx, h, iface, method)}`);\n } else {\n lines.push(` ${h} (try ${ctx.tool} ls --service ${h})`);\n }\n }\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls\\` to see what's available.`);\n }\n return lines.join('\\n');\n }\n\n // Service valid; check interface.\n const ifacesOnSvc = snapshot.interfacesOnService(svc);\n if (!ifacesOnSvc.includes(iface)) {\n // C2a: navigation-style input — `iface` is a prefix of one or more\n // interfaces on this service (e.g. `vscode::vscode.::login`). List the\n // matches, using `method` as the sample call when it exists on a\n // match, else the first method of each.\n const prefixMatches = _prefixMatchesOnService(snapshot, svc, iface);\n if (prefixMatches.length > 0) {\n const lines = [\n `Interface \"${iface}\" not found on service \"${svc}\". `\n + `Interfaces starting with \"${iface}\":`,\n ];\n for (const id of prefixMatches.slice(0, 10)) {\n const sampleMethod = snapshot.methodsOn(svc, id).includes(method)\n ? method\n : (snapshot.methodsOn(svc, id)[0] ?? '<method>');\n lines.push(` ${_qualify(ctx, svc, id, sampleMethod)}`);\n }\n const otherHosts = snapshot\n .servicesHostingInterface(iface)\n .filter((s) => s !== svc && s !== '');\n if (otherHosts.length > 0) {\n lines.push(` Note: \"${iface}\" also exists on service \"${otherHosts[0]}\".`);\n }\n return lines.join('\\n');\n }\n\n // C2/C3\n const lines = [`Interface \"${iface}\" not found on service \"${svc}\".`];\n\n // C2: fuzzy interfaces on THIS service, boost those hosting `method`\n const hits = _rankInterfacesOnService(snapshot, svc, iface, method, 3);\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n const methodOk = snapshot.methodsOn(svc, h).includes(method);\n lines.push(` ${_qualify(ctx, svc, h, methodOk ? method : '<method>')}`);\n }\n }\n\n // C3: footnote — interface exists on another service?\n const otherHosts = snapshot\n .servicesHostingInterface(iface)\n .filter((s) => s !== svc && s !== '');\n const userIfacesOnSvc = ifacesOnSvc.filter(_isUserInterface);\n if (otherHosts.length > 0) {\n if (hits.length === 0 && userIfacesOnSvc.length > 0) {\n lines.push(` Interfaces on \"${svc}\": ${userIfacesOnSvc.join(', ')}`);\n }\n const otherSvc = otherHosts[0];\n const sampleMethod = snapshot.methodsOn(otherSvc, iface).includes(method)\n ? method\n : (snapshot.methodsOn(otherSvc, iface)[0] ?? '<method>');\n lines.push(` Note: \"${iface}\" exists on service \"${otherSvc}\". Did you mean:`);\n lines.push(` ${_qualify(ctx, otherSvc, iface, sampleMethod)}`);\n } else if (hits.length === 0) {\n if (userIfacesOnSvc.length > 0) {\n lines.push(` Interfaces on \"${svc}\": ${userIfacesOnSvc.join(', ')}`);\n } else {\n lines.push(` Tip: run \\`${ctx.tool} ls --service ${svc}\\``);\n }\n }\n return lines.join('\\n');\n }\n\n // C1: svc + iface valid; method missing\n const methods = snapshot.methodsOn(svc, iface);\n const hits = _rankNames(methods, method, 3);\n const lines = [`Method \"${method}\" not found on ${svc}::${iface}.`];\n if (hits.length > 0) {\n lines.push(' Did you mean:');\n for (const h of hits) {\n lines.push(` ${_qualify(ctx, svc, iface, h)}`);\n }\n } else if (methods.length > 0) {\n lines.push(' Available methods:');\n for (const m of methods.slice(0, 12)) {\n lines.push(` ${_qualify(ctx, svc, iface, m)}`);\n }\n } else {\n lines.push(` Tip: this interface has no methods declared.`);\n }\n return lines.join('\\n');\n}\n\n// ---------------------------------------------------------------------------\n// Ranking / fuzzy primitives\n// ---------------------------------------------------------------------------\n\nfunction _threshold(s: string): number {\n return Math.max(1, Math.ceil(s.length / 3));\n}\n\n/** Levenshtein distance between two short strings. O(m*n) time, O(n) space. */\nfunction _lev(a: string, b: string): number {\n const m = a.length, n = b.length;\n if (m === 0) return n;\n if (n === 0) return m;\n const dp = new Array<number>(n + 1);\n for (let j = 0; j <= n; j++) dp[j] = j;\n for (let i = 1; i <= m; i++) {\n let prev = dp[0];\n dp[0] = i;\n for (let j = 1; j <= n; j++) {\n const tmp = dp[j];\n dp[j] = a[i - 1] === b[j - 1] ? prev : Math.min(prev, dp[j], dp[j - 1]) + 1;\n prev = tmp;\n }\n }\n return dp[n];\n}\n\ninterface _Ranked<T> { item: T; dist: number; boost: number; }\n\nfunction _rank<T>(\n items: readonly T[],\n key: (t: T) => string,\n query: string,\n limit: number,\n boost?: (t: T) => number,\n): T[] {\n const lower = query.toLowerCase();\n const thr = _threshold(query);\n const ranked: _Ranked<T>[] = [];\n for (const it of items) {\n const k = key(it);\n const d = _lev(k.toLowerCase(), lower);\n if (d > thr) continue;\n ranked.push({ item: it, dist: d, boost: boost ? boost(it) : 0 });\n }\n ranked.sort((a, b) =>\n (a.dist - b.dist)\n || (b.boost - a.boost)\n || key(a.item).localeCompare(key(b.item))\n );\n return ranked.slice(0, limit).map((r) => r.item);\n}\n\nfunction _rankNames(\n names: readonly string[],\n query: string,\n limit: number,\n boost?: (n: string) => number,\n): string[] {\n return _rank(names, (n) => n, query, limit, boost);\n}\n\nfunction _rankServices(\n snapshot: HubSnapshot,\n query: string,\n limit: number,\n boost?: (s: string) => number,\n): string[] {\n return _rankNames(snapshot.services().filter((s) => s !== ''), query, limit, boost);\n}\n\nfunction _rankAllInterfaces(snapshot: HubSnapshot, query: string, limit: number): string[] {\n return _rankNames(snapshot.interfaces().filter(_isUserInterface), query, limit);\n}\n\nfunction _rankAllMethods(\n snapshot: HubSnapshot,\n query: string,\n limit: number,\n): readonly { name: string; serviceId: string; interfaceId: string; }[] {\n const all: { name: string; serviceId: string; interfaceId: string; }[] = [];\n for (const e of snapshot.entries) {\n if (!_isUserInterface(e.interfaceId)) continue;\n for (const m of e.methods) {\n all.push({ name: m, serviceId: e.serviceId, interfaceId: e.interfaceId });\n }\n }\n return _rank(all, (x) => x.name, query, limit);\n}\n\nfunction _rankMethodsOnInterface(\n snapshot: HubSnapshot,\n interfaceId: string,\n query: string,\n limit: number,\n): readonly { methodName: string; serviceId: string; }[] {\n const all: { methodName: string; serviceId: string; }[] = [];\n for (const s of snapshot.servicesHostingInterface(interfaceId)) {\n for (const m of snapshot.methodsOn(s, interfaceId)) {\n all.push({ methodName: m, serviceId: s });\n }\n }\n return _rank(all, (x) => x.methodName, query, limit);\n}\n\nfunction _rankInterfacesWithMethodBoost(\n snapshot: HubSnapshot,\n query: string,\n methodName: string,\n limit: number,\n): readonly { interfaceId: string; serviceId: string; methodToTry: string; }[] {\n const ifaces = snapshot.interfaces().filter(_isUserInterface);\n const ranked = _rankNames(ifaces, query, limit, (id) => {\n for (const s of snapshot.servicesHostingInterface(id)) {\n if (snapshot.methodsOn(s, id).includes(methodName)) return 100;\n }\n return 0;\n });\n return ranked.map((id) => {\n const hosts = snapshot.servicesHostingInterface(id);\n const withMethod = hosts.find(\n (s) => s !== '' && snapshot.methodsOn(s, id).includes(methodName),\n );\n const fallback = hosts.find((s) => s !== '') ?? hosts[0] ?? '';\n const svc = withMethod ?? fallback;\n const m = snapshot.methodsOn(svc, id).includes(methodName)\n ? methodName\n : (snapshot.methodsOn(svc, id)[0] ?? '<method>');\n return { interfaceId: id, serviceId: svc, methodToTry: m };\n });\n}\n\nfunction _rankInterfacesOnService(\n snapshot: HubSnapshot,\n serviceId: string,\n query: string,\n methodName: string,\n limit: number,\n): string[] {\n const ifaces = snapshot.interfacesOnService(serviceId).filter(_isUserInterface);\n return _rankNames(ifaces, query, limit, (id) =>\n snapshot.methodsOn(serviceId, id).includes(methodName) ? 100 : 0\n );\n}\n\n// ---------------------------------------------------------------------------\n// Sample call generators\n// ---------------------------------------------------------------------------\n\n/**\n * Interface ids on `serviceId` whose name starts with `prefix`\n * (case-insensitive). System interfaces (`linkrpc.*`) are excluded — they're\n * noise for navigation. Returns `[]` for an empty `prefix` so the caller can\n * distinguish \"no prefix typed\" from \"prefix had matches\".\n */\nfunction _prefixMatchesOnService(\n snapshot: HubSnapshot,\n serviceId: string,\n prefix: string,\n): string[] {\n if (prefix === '') return [];\n const lower = prefix.toLowerCase();\n return snapshot\n .interfacesOnService(serviceId)\n .filter((id) => _isUserInterface(id) && id.toLowerCase().startsWith(lower));\n}\n\n/**\n * Render an interface-list response for `serviceId`. When `prefix` is a real\n * prefix of one or more interfaces, only those are shown; otherwise all user\n * interfaces on the service are listed. Sample method per row defaults to the\n * first declared method.\n */\nfunction _formatInterfaceListOnService(\n ctx: _Ctx,\n serviceId: string,\n prefix: string,\n): string {\n const allUserIfaces = ctx.snapshot\n .interfacesOnService(serviceId)\n .filter(_isUserInterface);\n const prefixMatches = _prefixMatchesOnService(ctx.snapshot, serviceId, prefix);\n const matches = prefixMatches.length > 0 ? prefixMatches : allUserIfaces;\n\n const header = prefixMatches.length > 0\n ? `Interfaces on \"${serviceId}\" starting with \"${prefix}\":`\n : (prefix !== ''\n ? `Interface \"${prefix}\" not found on service \"${serviceId}\". `\n + `Interfaces on \"${serviceId}\":`\n : `Interfaces on \"${serviceId}\":`);\n\n const lines = [header];\n if (matches.length === 0) {\n lines.push(` Tip: run \\`${ctx.tool} ls --service ${serviceId}\\``);\n return lines.join('\\n');\n }\n for (const id of matches.slice(0, 10)) {\n const sampleMethod = ctx.snapshot.methodsOn(serviceId, id)[0] ?? '<method>';\n lines.push(` ${_qualify(ctx, serviceId, id, sampleMethod)}`);\n }\n return lines.join('\\n');\n}\n\nfunction _sampleCallsForService(ctx: _Ctx, serviceId: string, limit: number): string[] {\n const { snapshot } = ctx;\n const out: string[] = [];\n for (const iface of snapshot.interfacesOnService(serviceId)) {\n if (!_isUserInterface(iface)) continue;\n for (const m of snapshot.methodsOn(serviceId, iface)) {\n out.push(_qualify(ctx, serviceId, iface, m));\n if (out.length >= limit) return out;\n }\n }\n return out;\n}\n\nfunction _sampleCallsForInterface(ctx: _Ctx, interfaceId: string, limit: number): string[] {\n const { snapshot } = ctx;\n const out: string[] = [];\n for (const s of snapshot.servicesHostingInterface(interfaceId)) {\n if (s === '') continue;\n for (const m of snapshot.methodsOn(s, interfaceId)) {\n out.push(_qualify(ctx, s, interfaceId, m));\n if (out.length >= limit) return out;\n }\n }\n return out;\n}\n","import type { LinkRpcInterfaceSchema } from '@hediet/linkrpc';\nimport {\n type CliChannel,\n fetchDefaults,\n fetchSchema,\n} from '@hediet/linkrpc-client-internal';\nimport type { MethodRefWithOptHash } from './methodRef';\n\n/**\n * Fetch the schema addressed by a method reference. Form-1 references use the\n * connection preset for lookup, but remain bare when sent on the wire.\n */\nexport async function fetchSchemaForMethodRef(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n): Promise<LinkRpcInterfaceSchema | undefined> {\n if (ref.interfaceId !== undefined) {\n return fetchSchema(channel, ref.interfaceId, ref.hash, ref.serviceId);\n }\n\n const defaults = await fetchDefaults(channel);\n if (defaults.interfaceId === undefined) {\n return undefined;\n }\n return fetchSchema(\n channel,\n defaults.interfaceId,\n ref.hash ?? defaults.hash,\n defaults.serviceId,\n );\n}\n","import { ErrorCode, type JsonValue, RpcError } from '@hediet/linkrpc';\nimport { MethodRefWithOptHash } from '../methodRef';\nimport { formatJson, readParamsArg } from '../output';\nimport { mergeParams } from '../paramParsing';\nimport { type CliChannel, type SigningSession, findMethodInSchema } from '@hediet/linkrpc-client-internal';\nimport { requestCallCapability, type RequestCallCapabilityOptions } from './caps';\nimport { formatSuggestion, HubSnapshot } from '../suggest';\nimport {\n describeObjectParams,\n describeSchema,\n explainValidation,\n validateValueAgainstSchema,\n} from '../validation';\nimport type { LinkRpcInterfaceSchema as SvcInterfaceSchema, MethodSchema } from '@hediet/linkrpc';\nimport { fetchSchemaForMethodRef } from '../schemaLookup';\n\nexport interface CallCommandOptions extends RequestCallCapabilityOptions {\n /** Full `[svc::][iface::]method[@hash]` reference. */\n readonly methodRef: string;\n /** Raw `--params <json>` value, or \"-\" for stdin. */\n readonly paramsArg?: string;\n readonly paramOverrides?: readonly string[];\n /** Skip schema-based validation. Default: validate. */\n readonly noValidate?: boolean;\n /** Schema lookup policy. `noValidate` takes precedence when set. */\n readonly validation?: 'auto' | 'required' | 'off';\n readonly json?: boolean;\n readonly requestCap?: boolean;\n readonly capabilityOnly?: boolean;\n readonly signingSession?: SigningSession;\n /**\n * Invoked for every server→client stream message (`$stream::send`) that\n * arrives while the call is in flight. Defaults to writing each chunk to\n * stderr (one line each) so streamed progress shows live without\n * polluting the stdout result. Pass a custom sink in tests.\n */\n readonly onStreamChunk?: (payload: JsonValue) => void;\n}\n\nexport async function callCommand(channel: CliChannel, opts: CallCommandOptions): Promise<string> {\n const ref = MethodRefWithOptHash.parseMethodRef(opts.methodRef);\n const baseParams = readParamsArg(opts.paramsArg);\n const params = mergeParams({ base: baseParams, overrides: opts.paramOverrides });\n\n const requestCap = opts.requestCap === true || opts.capabilityOnly === true;\n if (!requestCap && opts.allowParams !== undefined) {\n throw new Error('--cap:allow-param requires --cap:request.');\n }\n if (requestCap && (opts.noValidate || opts.validation === 'off')) {\n throw new Error('Capability requests require schema validation; remove --no-validate/--validation off.');\n }\n if (requestCap && opts.signingSession === undefined) {\n throw new Error('Capability requests require a signed LinkRPC connection.');\n }\n const onStreamChunk = opts.onStreamChunk ?? writeChunkToStderr;\n try {\n const validation = requestCap ? 'required' : opts.noValidate ? 'off' : (opts.validation ?? 'required');\n const schema = validation === 'off' ? undefined : await validateParams(channel, ref, params, 'call', validation);\n if (requestCap) {\n if (schema === undefined || opts.signingSession === undefined) {\n throw new Error('Capability requests require a method schema and signing session.');\n }\n const result = await requestCallCapability(channel, opts.signingSession, ref, params, schema, opts);\n if (opts.capabilityOnly) return result;\n }\n // Always use the streaming send path: it behaves identically to a plain\n // request when no stream messages arrive, and surfaces them live when\n // the method does stream (e.g. an interactive `login` device-code\n // prompt). The final result is the request's response.\n const call = channel.sendRequestWithStream(ref.getMethodOnWire(), params as never, {\n onStreamMessage: onStreamChunk,\n ...(opts.signingSession !== undefined && ref.hash !== undefined ? { interfaceHash: ref.hash } : {}),\n });\n const result = await call.result;\n return opts.json !== false ? formatJson(result) : String(result);\n } catch (e) {\n if (e instanceof RpcError && e.code === ErrorCode.methodNotFound) {\n await _failWithSuggestion(channel, ref, 'call');\n }\n if (e instanceof RpcError) throw formatRpcError(e);\n throw e;\n }\n}\n\n/**\n * Default stream sink: one line per chunk on stderr. Strings pass through\n * verbatim; structured payloads are JSON-encoded. stderr (not stdout) keeps\n * `call … | jq` clean while still showing live progress.\n */\nfunction writeChunkToStderr(payload: JsonValue): void {\n const text = typeof payload === 'string' ? payload : JSON.stringify(payload);\n process.stderr.write(text + '\\n');\n}\n\nexport interface NotifyCommandOptions extends CallCommandOptions { }\n\nexport async function notifyCommand(channel: CliChannel, opts: NotifyCommandOptions): Promise<string> {\n const ref = MethodRefWithOptHash.parseMethodRef(opts.methodRef);\n const baseParams = readParamsArg(opts.paramsArg);\n const params = mergeParams({ base: baseParams, overrides: opts.paramOverrides });\n const validation = opts.noValidate ? 'off' : (opts.validation ?? 'required');\n if (validation !== 'off') await validateParams(channel, ref, params, 'notify', validation);\n await channel.sendNotification(ref.getMethodOnWire(), params as never);\n return '(notification sent)';\n}\n\nasync function validateParams(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n params: unknown,\n verb: 'call' | 'notify',\n validation: 'auto' | 'required',\n): Promise<SvcInterfaceSchema | undefined> {\n let schema: SvcInterfaceSchema | undefined;\n try {\n schema = await fetchSchemaForMethodRef(channel, ref);\n } catch (e) {\n // Server side says the interface (or its host route) is unknown.\n // ErrorCode.methodNotFound covers both \"no such interface\" and \"no\n // such route\" — in either case the bus-wide suggestion is what the\n // user wants. Any other RpcError (e.g. permission) is propagated.\n if (e instanceof RpcError && e.code === ErrorCode.methodNotFound) {\n if (validation === 'auto') return;\n await _failWithSuggestion(channel, ref, verb);\n }\n throw e;\n }\n if (schema === undefined) {\n if (validation === 'auto') return;\n return _failWithSuggestion(channel, ref, verb);\n }\n const method = findMethodInSchema(schema, ref.methodName);\n if (!method) {\n return _failWithSuggestion(channel, ref, verb);\n }\n if (verb === 'call' && method.result === undefined) {\n throw new Error(\n `${ref.getMethodOnWire()} is a notification member; use \\`notify\\` instead of \\`call\\`.`,\n );\n }\n if (verb === 'notify' && method.result !== undefined) {\n throw new Error(\n `${ref.getMethodOnWire()} is a request member; use \\`call\\` instead of \\`notify\\`.`,\n );\n }\n const paramsSchema = method.params;\n const reason = validateValueAgainstSchema(params, paramsSchema, schema.components?.schemas ?? {});\n if (reason !== undefined) {\n throw new Error(_formatParamValidationError(ref, schema, method, params, reason));\n }\n return schema;\n}\n\nfunction _formatParamValidationError(\n ref: MethodRefWithOptHash,\n schema: SvcInterfaceSchema,\n method: MethodSchema,\n params: unknown,\n fallback: string,\n): string {\n const components = schema.components?.schemas ?? {};\n const paramsSchema = method.params;\n const lines: string[] = [];\n lines.push(`Param validation failed for ${ref.getMethodOnWire()}:`);\n const issues = explainValidation(params, paramsSchema, components);\n if (issues.length > 0) {\n for (const i of issues) {\n const where = i.path === '' ? '(root)' : i.path;\n lines.push(` ${where}: ${i.reason}`);\n }\n } else {\n lines.push(` ${fallback}`);\n }\n if (paramsSchema !== undefined) {\n const table = describeObjectParams(paramsSchema, components);\n if (table !== undefined) {\n lines.push('Expected params:');\n lines.push(table);\n } else {\n lines.push(`Expected: ${describeSchema(paramsSchema, components)}`);\n }\n }\n return lines.join('\\n');\n}\n\n/**\n * Walk the bus once, build a snapshot, and throw an Error whose message is a\n * focused \"did you mean…\" block tailored to `ref`. Always throws — return\n * type is `Promise<never>`. Snapshot load failures fall back to an empty\n * snapshot so we still produce *some* output.\n */\nasync function _failWithSuggestion(\n channel: CliChannel,\n ref: MethodRefWithOptHash,\n verb: 'call' | 'notify',\n): Promise<never> {\n let snapshot: HubSnapshot;\n try {\n snapshot = await HubSnapshot.load(channel);\n } catch {\n snapshot = new HubSnapshot([]);\n }\n throw new Error(formatSuggestion({ ref, snapshot, verb }));\n}\n\nfunction formatRpcError(e: RpcError): Error {\n if (e.code === ErrorCode.permissionRequired) {\n return new Error(_formatPermissionRequired(e));\n }\n const dataStr = e.data === undefined ? '' : ` ${JSON.stringify(e.data)}`;\n return new Error(`RPC error ${e.code}: ${e.message}${dataStr}`);\n}\n\nfunction _formatPermissionRequired(e: RpcError): string {\n return [\n `Permission required: ${e.message}`,\n ' No usable capability authorizes this call.',\n ' Retry with --cap:request to request access before calling.',\n ' Use --cap:allow-param with --cap:request to request a broader parameter scope,',\n ' or use `linkrpc hub caps request <methodRef>` to acquire and store access separately.',\n ].join('\\n');\n}\n","import type { JsonValue } from \"@hediet/linkrpc\";\nimport type { CallCommandOptions, NotifyCommandOptions } from \"./call\";\n\nexport interface BatchOperation {\n readonly kind: \"call\" | \"notify\";\n readonly methodRef: string;\n readonly paramsArg?: string;\n readonly paramOverrides: readonly string[];\n readonly noValidate: boolean;\n}\n\nexport interface BatchPlan {\n readonly operations: readonly BatchOperation[];\n readonly continueOnError: boolean;\n}\n\nexport interface BatchExecutor {\n readonly call: (options: CallCommandOptions) => Promise<string>;\n readonly notify: (options: NotifyCommandOptions) => Promise<string>;\n}\n\nexport type BatchResult =\n | {\n readonly index: number;\n readonly kind: BatchOperation[\"kind\"];\n readonly method: string;\n readonly ok: true;\n readonly result?: JsonValue;\n }\n | {\n readonly index: number;\n readonly kind: BatchOperation[\"kind\"];\n readonly method: string;\n readonly ok: false;\n readonly error: string;\n };\n\nexport interface ExecuteBatchOptions {\n readonly validation?: 'auto' | 'required' | 'off';\n readonly onStreamChunk?: (event: {\n readonly index: number;\n readonly method: string;\n readonly payload: JsonValue;\n }) => void;\n}\n\nexport function parseBatchArgs(args: readonly string[]): BatchPlan {\n const operations: MutableBatchOperation[] = [];\n let current: MutableBatchOperation | undefined;\n let continueOnError = false;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n switch (arg) {\n case \"--call\":\n case \"--notify\": {\n const methodRef = readOptionValue(args, ++i, arg, \"method\");\n current = {\n kind: arg === \"--call\" ? \"call\" : \"notify\",\n methodRef,\n paramOverrides: [],\n noValidate: false,\n };\n operations.push(current);\n break;\n }\n case \"--params\": {\n requireOperation(current, arg);\n if (current.paramsArg !== undefined) {\n throw new Error(\"--params may be specified only once per batch operation\");\n }\n current.paramsArg = readOptionValue(args, ++i, arg);\n break;\n }\n case \"--param\": {\n requireOperation(current, arg);\n current.paramOverrides.push(readOptionValue(args, ++i, arg));\n break;\n }\n case \"--no-validate\":\n requireOperation(current, arg);\n current.noValidate = true;\n break;\n case \"--continue-on-error\":\n continueOnError = true;\n break;\n default:\n if (arg.startsWith(\"-\")) {\n throw new Error(`Unknown batch option: ${arg}`);\n }\n throw new Error(`Unexpected batch argument: ${arg}`);\n }\n }\n\n if (operations.length === 0) {\n throw new Error(\"Batch requires at least one --call or --notify operation\");\n }\n\n return { operations, continueOnError };\n}\n\nexport async function executeBatch(\n plan: BatchPlan,\n executor: BatchExecutor,\n options: ExecuteBatchOptions = {},\n): Promise<BatchResult[]> {\n const results: BatchResult[] = [];\n\n for (let index = 0; index < plan.operations.length; index++) {\n const operation = plan.operations[index];\n const commandOptions: CallCommandOptions = {\n methodRef: operation.methodRef,\n paramsArg: operation.paramsArg,\n paramOverrides: operation.paramOverrides,\n noValidate: operation.noValidate,\n validation: options.validation,\n json: true,\n onStreamChunk: (payload) => options.onStreamChunk?.({\n index,\n method: operation.methodRef,\n payload,\n }),\n };\n\n try {\n if (operation.kind === \"notify\") {\n await executor.notify(commandOptions);\n results.push(toSuccessResult(index, operation));\n } else {\n const output = await executor.call(commandOptions);\n const result: JsonValue = JSON.parse(output);\n results.push(toSuccessResult(index, operation, result));\n }\n } catch (error) {\n if (!plan.continueOnError) {\n throw error;\n }\n results.push({\n index,\n kind: operation.kind,\n method: operation.methodRef,\n ok: false,\n error: getErrorMessage(error),\n });\n }\n }\n\n return results;\n}\n\ninterface MutableBatchOperation {\n kind: BatchOperation[\"kind\"];\n methodRef: string;\n paramsArg?: string;\n paramOverrides: string[];\n noValidate: boolean;\n}\n\nfunction readOptionValue(\n args: readonly string[],\n index: number,\n option: string,\n valueName = \"value\",\n): string {\n const value = args[index];\n if (value === undefined || value.startsWith(\"--\")) {\n throw new Error(`${option} requires a ${valueName}`);\n }\n return value;\n}\n\nfunction requireOperation(\n operation: MutableBatchOperation | undefined,\n option: string,\n): asserts operation is MutableBatchOperation {\n if (operation === undefined) {\n throw new Error(`${option} must follow --call or --notify`);\n }\n}\n\nfunction toSuccessResult(\n index: number,\n operation: BatchOperation,\n result?: JsonValue,\n): BatchResult {\n return {\n index,\n kind: operation.kind,\n method: operation.methodRef,\n ok: true,\n ...(result === undefined ? {} : { result }),\n };\n}\n\nfunction getErrorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import { randomUUID } from \"node:crypto\";\nimport { spawn } from \"node:child_process\";\nimport {\n formatEndpointUri,\n traceMessageTransport,\n type ResolvedEndpoint,\n} from \"@hediet/linkrpc/node\";\nimport { SocketServer } from \"@hediet/linkrpc-hub/hub/server/node\";\nimport {\n connect,\n connectViaTransport,\n} from \"@hediet/linkrpc-client-internal\";\nimport type { StaticHubSchema } from \"../staticHubSchema\";\nimport type { ConnectionLimit } from \"../duration\";\nimport { ConnectionBroker, type BrokerStopReason } from \"./connectionBroker\";\n\nexport interface RunConnectionBrokerOptions {\n readonly remote: ResolvedEndpoint;\n readonly timeoutMs: ConnectionLimit;\n readonly ttlMs: ConnectionLimit;\n readonly notificationLimit?: number;\n readonly staticHubSchema?: StaticHubSchema;\n}\n\nexport interface RunningConnectionBroker {\n readonly endpoint: string;\n readonly stopped: Promise<BrokerStopReason>;\n dispose(): void;\n}\n\nexport async function runConnectionBroker(\n options: RunConnectionBrokerOptions,\n): Promise<RunningConnectionBroker> {\n const startedAt = Date.now();\n let broker: ConnectionBroker | undefined;\n const remote = await connect(options.remote, {\n trace: () => broker?.recordActivity(),\n });\n const token = randomUUID();\n const server = await SocketServer.start({\n isTokenAccepted: async (candidate) => candidate === token,\n });\n const mode = options.remote.kind === \"ws-no-init\" ? \"raw\" : \"linkrpc\";\n\n try {\n broker = new ConnectionBroker(remote, {\n id: randomUUID(),\n remoteEndpoint: formatRemoteEndpointForStatus(options.remote),\n mode,\n startedAt,\n timeoutMs: options.timeoutMs,\n ttlMs: options.ttlMs,\n ...(options.notificationLimit === undefined\n ? {}\n : { notificationLimit: options.notificationLimit }),\n ...(options.staticHubSchema === undefined\n ? {}\n : { staticHubSchema: options.staticHubSchema }),\n onStop: () => server.dispose(),\n });\n server.setConnectionHandler((transport) => {\n broker!.recordActivity();\n const traced = traceMessageTransport(transport, () => broker!.recordActivity());\n const local = connectViaTransport(traced);\n try {\n broker!.attach(local);\n } catch {\n local.close();\n return;\n }\n\n transport.onDidClose(() => broker!.detach(local));\n });\n } catch (error) {\n server.dispose();\n remote.close();\n throw error;\n }\n\n const endpoint = formatEndpointUri({\n kind: \"socket\",\n path: server.endpoint,\n token,\n brokerMode: mode,\n }, { revealToken: true });\n return {\n endpoint,\n stopped: broker.stopped,\n dispose: () => broker!.dispose(),\n };\n}\n\nfunction formatRemoteEndpointForStatus(endpoint: ResolvedEndpoint): string {\n if (endpoint.kind === \"ws-no-init\") {\n const url = new URL(endpoint.url);\n for (const key of [...url.searchParams.keys()]) {\n url.searchParams.set(key, \"***\");\n }\n return url.toString().replace(/^ws:/i, \"ws-no-init:\");\n }\n if (endpoint.kind === \"cmd-env\" || endpoint.kind === \"cmd-stdio\") {\n return `${endpoint.kind}:<redacted>`;\n }\n return formatEndpointUri(endpoint);\n}\n\nexport interface SpawnConnectionBrokerOptions {\n readonly remote: ResolvedEndpoint;\n readonly timeoutMs: ConnectionLimit;\n readonly ttlMs: ConnectionLimit;\n readonly notificationLimit?: number;\n readonly readyTimeoutMs?: number;\n readonly schemaSource?: string;\n}\n\nexport async function spawnConnectionBroker(\n options: SpawnConnectionBrokerOptions,\n): Promise<string> {\n const cliPath = process.argv[1];\n if (cliPath === undefined) {\n throw new Error(\"cannot locate the linkrpc CLI entry point\");\n }\n const args = [\n ...process.execArgv,\n cliPath,\n \"_connection-broker\",\n \"--remote-endpoint\",\n formatEndpointUri(options.remote, { revealToken: true }),\n \"--timeout-ms\",\n String(options.timeoutMs),\n \"--ttl-ms\",\n String(options.ttlMs),\n ];\n if (options.notificationLimit !== undefined) {\n args.push(\"--notification-limit\", String(options.notificationLimit));\n }\n if (options.schemaSource !== undefined) {\n args.push(\"--schema\", options.schemaSource);\n }\n\n const child = spawn(process.execPath, args, {\n detached: true,\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n const stdout = child.stdout;\n if (stdout === null) {\n child.kill();\n throw new Error(\"connection broker child exposes no stdout\");\n }\n\n try {\n const endpoint = await readReadyEndpoint(\n child,\n stdout,\n options.readyTimeoutMs ?? 60_000,\n );\n stdout.destroy();\n child.unref();\n return endpoint;\n } catch (error) {\n child.kill();\n throw error;\n }\n}\n\nfunction readReadyEndpoint(\n child: ReturnType<typeof spawn>,\n stdout: NodeJS.ReadableStream,\n timeoutMs: number,\n): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n let buffer = \"\";\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(\"connection broker did not become ready before the timeout\"));\n }, timeoutMs);\n const onData = (chunk: Buffer | string) => {\n buffer += chunk.toString();\n const newline = buffer.indexOf(\"\\n\");\n if (newline < 0) return;\n const endpoint = buffer.slice(0, newline).trim();\n cleanup();\n try {\n if (endpoint.startsWith(\"{\")) {\n const response: unknown = JSON.parse(endpoint);\n if (\n typeof response === \"object\"\n && response !== null\n && \"error\" in response\n && typeof response.error === \"string\"\n ) {\n throw new Error(`connection broker failed to start: ${response.error}`);\n }\n throw new Error(\"connection broker returned an invalid startup response\");\n }\n const parsed = new URL(endpoint);\n if (parsed.protocol !== \"unix:\" && parsed.protocol !== \"npipe:\") {\n throw new Error(`unexpected broker endpoint '${endpoint}'`);\n }\n resolve(endpoint);\n } catch (error) {\n reject(error);\n }\n };\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n const onExit = (code: number | null) => {\n cleanup();\n reject(new Error(`connection broker exited before becoming ready (code ${code ?? \"unknown\"})`));\n };\n const cleanup = () => {\n clearTimeout(timer);\n stdout.removeListener(\"data\", onData);\n child.removeListener(\"error\", onError);\n child.removeListener(\"close\", onExit);\n };\n stdout.on(\"data\", onData);\n child.once(\"error\", onError);\n child.once(\"close\", onExit);\n });\n}\n","import { readFileSync } from \"node:fs\";\nimport {\n isAssignable,\n type LinkRpcInterfaceSchema as SvcInterfaceSchema,\n type LinkRpcJsonSchema as SvcJsonSchema,\n} from \"@hediet/linkrpc\";\nimport { type CliChannel, fetchSchema } from \"@hediet/linkrpc-client-internal\";\n\nexport interface CheckCompatOptions {\n readonly interfaceId: string;\n /** Path to a local SvcInterfaceSchema JSON file. */\n readonly localPath: string;\n}\n\nexport type CompatVerdict =\n | { kind: \"identical\"; hash: string }\n | { kind: \"compatible-subset\"; localHash: string; remoteHash: string; details: string }\n | { kind: \"incompatible\"; localHash: string; remoteHash: string; details: string };\n\nexport async function checkCompatCommand(channel: CliChannel, opts: CheckCompatOptions): Promise<CompatVerdict> {\n const local = JSON.parse(readFileSync(opts.localPath, \"utf8\")) as SvcInterfaceSchema;\n const remote = await fetchSchema(channel, opts.interfaceId, undefined);\n return diffSchemas(local, remote);\n}\n\nexport function diffSchemas(\n local: SvcInterfaceSchema,\n remote: SvcInterfaceSchema,\n): CompatVerdict {\n if (local.hash === remote.hash) return { kind: \"identical\", hash: local.hash };\n\n const localComponents = local.components?.schemas ?? {};\n const remoteComponents = remote.components?.schemas ?? {};\n const issues: string[] = [];\n\n // Direction: a client speaking `local` calls a server speaking `remote`.\n // For that to work, local params must be assignable to remote params\n // (server accepts what client sends) and remote result must be assignable\n // to local result (client accepts what server returns).\n for (const [name, lm] of Object.entries(local.methods)) {\n const rm = remote.methods[name];\n if (!rm) {\n issues.push(`method \"${name}\" missing on remote`);\n continue;\n }\n if (!safeAssignable(lm.params, rm.params, mergeComponents(localComponents, remoteComponents))) {\n issues.push(`method \"${name}\": params not assignable (local → remote)`);\n }\n if (lm.result && rm.result) {\n if (!safeAssignable(rm.result, lm.result, mergeComponents(localComponents, remoteComponents))) {\n issues.push(`method \"${name}\": result not assignable (remote → local)`);\n }\n } else if (lm.result && !rm.result) {\n issues.push(`method \"${name}\": local expects a result, remote is notification-only`);\n }\n }\n\n if (issues.length === 0) {\n return {\n kind: \"compatible-subset\",\n localHash: local.hash,\n remoteHash: remote.hash,\n details: \"all local methods are structurally assignable against remote\",\n };\n }\n return {\n kind: \"incompatible\",\n localHash: local.hash,\n remoteHash: remote.hash,\n details: issues.join(\"; \"),\n };\n}\n\nfunction safeAssignable(\n a: SvcJsonSchema,\n b: SvcJsonSchema,\n components: Record<string, SvcJsonSchema>,\n): boolean {\n try { return isAssignable(a, b, components); } catch { return false; }\n}\n\nfunction mergeComponents(\n a: Record<string, SvcJsonSchema>,\n b: Record<string, SvcJsonSchema>,\n): Record<string, SvcJsonSchema> {\n return { ...a, ...b };\n}\n\nexport function formatVerdict(v: CompatVerdict): string {\n switch (v.kind) {\n case \"identical\":\n return `identical (${v.hash})`;\n case \"compatible-subset\":\n return `compatible-subset\\n local: ${v.localHash}\\n remote: ${v.remoteHash}\\n ${v.details}`;\n case \"incompatible\":\n return `incompatible\\n local: ${v.localHash}\\n remote: ${v.remoteHash}\\n ${v.details}`;\n }\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { generateTsContract, generateTsInterface, type GenerateContractOptions } from '@hediet/linkrpc';\nimport { loadStaticHubSchema } from '../staticHubSchema';\n\nexport interface CodegenCommandOptions {\n readonly input: string;\n readonly interfaceId?: string;\n readonly name?: string;\n readonly output: string;\n readonly preserveWireSchema?: boolean;\n readonly check?: boolean;\n readonly names?: string;\n}\n\nexport async function codegenCommand(options: CodegenCommandOptions): Promise<void> {\n if (/^https?:\\/\\//i.test(options.input)) {\n throw new Error('codegen --input must be a local offline bundle');\n }\n if (options.name !== undefined && !/^[$A-Z_a-z][$\\w]*$/.test(options.name)) {\n throw new Error(`codegen --name must be a valid TypeScript identifier, got '${options.name}'`);\n }\n\n const bundle = await loadStaticHubSchema(options.input);\n let generated: string;\n if (options.interfaceId === undefined) {\n if (options.name !== undefined) throw new Error('codegen --name requires --interface');\n let naming: GenerateContractOptions = {};\n if (options.names !== undefined) {\n const raw = JSON.parse(await readFile(options.names, 'utf8'));\n if (raw === null || typeof raw !== 'object' || Array.isArray(raw)\n || Object.keys(raw).some((key) => key !== 'interfaceNames' && key !== 'bindingNames')) {\n throw new Error('codegen --names must contain only interfaceNames and bindingNames maps');\n }\n for (const map of Object.values(raw)) {\n if (map === null || typeof map !== 'object' || Array.isArray(map)\n || Object.values(map).some((name) => typeof name !== 'string')) {\n throw new Error('codegen --names values must be string maps');\n }\n }\n naming = raw;\n }\n generated = generateTsContract(bundle, naming);\n } else {\n if (options.name === undefined) throw new Error('codegen --interface requires --name');\n if (options.names !== undefined) throw new Error('codegen --names is only supported for whole contracts');\n const matches = bundle.interfaceSchemas.filter((schema) => schema.id === options.interfaceId);\n if (matches.length === 0) {\n throw new Error(\n `Interface '${options.interfaceId}' was not found in bundle '${options.input}'`,\n );\n }\n if (matches.length > 1) {\n throw new Error(\n `Interface '${options.interfaceId}' is ambiguous in bundle '${options.input}' `\n + `(${matches.length} schema versions)`,\n );\n }\n\n generated = generateTsInterface(matches[0]!, {\n exportName: options.name,\n preserveWireSchema: options.preserveWireSchema === true,\n });\n }\n if (options.check === true) {\n let current: string;\n try {\n current = await readFile(options.output, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`Generated output is missing: ${options.output}`);\n }\n throw error;\n }\n if (current !== generated) {\n throw new Error(`Generated output is stale: ${options.output}`);\n }\n return;\n }\n\n await mkdir(dirname(options.output), { recursive: true });\n await writeFile(options.output, generated, 'utf8');\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { exportStaticHubSchema, type ExportStaticHubSchemaOptions } from '@hediet/linkrpc';\nimport type { CliChannel } from '@hediet/linkrpc-client-internal';\n\nexport async function exportContractCommand(\n channel: CliChannel,\n options: ExportStaticHubSchemaOptions & { output: string },\n): Promise<void> {\n const document = await exportStaticHubSchema(channel, options);\n const text = `${JSON.stringify(document, null, 2)}\\n`;\n if (options.output === '-') {\n process.stdout.write(text);\n } else {\n await mkdir(dirname(options.output), { recursive: true });\n await writeFile(options.output, text, 'utf8');\n }\n}\n","/**\n * Emit shell-completion scripts. Currently PowerShell only; the entry point\n * is structured so adding bash / zsh later just plugs in another renderer.\n *\n * The scripts shell out to `hub _complete --line <line> --point <cursor>`,\n * which prints one candidate per line in the format `text\\ttooltip`. PS\n * turns each line into a `CompletionResult`.\n */\n\nexport type SupportedShell = 'powershell';\n\nconst SUPPORTED: ReadonlySet<SupportedShell> = new Set(['powershell']);\n\nexport function isSupportedShell(name: string): name is SupportedShell {\n return SUPPORTED.has(name as SupportedShell);\n}\n\nexport function emitCompletionScript(shell: SupportedShell): string {\n if (shell === 'powershell') return POWERSHELL_SCRIPT;\n throw new Error(`unsupported shell: ${shell}`);\n}\n\n/**\n * The PowerShell registration script. Self-contained — `Invoke-Expression`\n * of this string registers a native completer for `hub`, `linkrpc`, and `rpc`.\n *\n * Notes:\n * - `$commandAst.Extent.Text` is the entire pipeline element text (the\n * part PS treats as one command); `$cursorPosition` is absolute, so we\n * subtract `$commandAst.Extent.StartOffset` to get a position relative\n * to the line we're handing to the CLI.\n * - We invoke whichever binary the user is actually typing\n * (`$commandAst.CommandElements[0]`) so a local `hub.exe` and a global\n * one both work transparently.\n * - All errors are silently swallowed — a broken completer must never\n * break the user's prompt.\n */\nconst POWERSHELL_SCRIPT = `\n# linkrpc completion for PowerShell — auto-generated by \\`hub completions powershell\\`.\n# Install once with: hub completions powershell | Out-String | Invoke-Expression\n# Persist with: hub completions powershell >> $PROFILE\nRegister-ArgumentCompleter -Native -CommandName hub,linkrpc,rpc -ScriptBlock {\n param($wordToComplete, $commandAst, $cursorPosition)\n\n try {\n $line = $commandAst.Extent.Text\n $point = $cursorPosition - $commandAst.Extent.StartOffset\n if ($point -lt 0) { $point = 0 }\n if ($point -gt $line.Length) { $point = $line.Length }\n\n $binElement = $commandAst.CommandElements[0]\n $bin = if ($binElement.Value) { $binElement.Value } else { $binElement.Extent.Text }\n\n # The completer must never write to the user's prompt. Redirect stderr.\n $raw = & $bin _complete --line $line --point $point 2>$null\n if (-not $raw) { return }\n\n foreach ($entry in ($raw -split \"\\`r?\\`n\")) {\n if (-not $entry) { continue }\n $parts = $entry -split \"\\`t\", 2\n $text = $parts[0]\n $tooltip = if ($parts.Length -ge 2 -and $parts[1]) { $parts[1] } else { $text }\n [System.Management.Automation.CompletionResult]::new(\n $text,\n $text,\n [System.Management.Automation.CompletionResultType]::ParameterValue,\n $tooltip\n )\n }\n } catch {\n # Silent: a broken completer must not break the prompt.\n }\n}\n`.trimStart();\n","/**\n * `hub completions <shell>` — print the shell-completion registration script\n * for the requested shell.\n *\n * No connection required. Currently supports `powershell` only.\n */\nimport { emitCompletionScript, isSupportedShell } from '../completions/shellScripts';\n\nexport interface CompletionsCommandOptions {\n readonly shell: string;\n}\n\nexport function completionsCommand(opts: CompletionsCommandOptions): string {\n if (!isSupportedShell(opts.shell)) {\n throw new Error(\n `unsupported shell \"${opts.shell}\". Supported: powershell.`,\n );\n }\n return emitCompletionScript(opts.shell);\n}\n","import { type CliChannel, fetchDefaults } from \"@hediet/linkrpc-client-internal\";\nimport { formatJson } from \"../output\";\n\nexport interface DefaultsCommandOptions {\n readonly json?: boolean;\n}\n\nexport async function defaultsCommand(channel: CliChannel, opts: DefaultsCommandOptions = {}): Promise<string> {\n const d = await fetchDefaults(channel);\n if (opts.json) return formatJson(d);\n if (!d.interfaceId && !d.serviceId) return \"(no preset)\";\n const lines: string[] = [];\n if (d.serviceId) lines.push(`service: ${d.serviceId}`);\n lines.push(`interface: ${d.interfaceId ?? \"(none)\"}`);\n if (d.hash) lines.push(`hash: ${d.hash}`);\n return lines.join(\"\\n\");\n}\n","import { readFileSync } from \"node:fs\";\nimport { computeInterfaceHash, type LinkRpcInterfaceSchema as SvcInterfaceSchema } from \"@hediet/linkrpc\";\n\nexport interface HashCommandOptions {\n readonly schemaPath: string;\n}\n\nexport function hashCommand(opts: HashCommandOptions): string {\n const text = readFileSync(opts.schemaPath, \"utf8\");\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (e) {\n throw new Error(`${opts.schemaPath}: invalid JSON (${(e as Error).message})`);\n }\n if (!isInterfaceSchema(parsed)) {\n throw new Error(`${opts.schemaPath}: not a SvcInterfaceSchema (missing id / methods)`);\n }\n return computeInterfaceHash(parsed);\n}\n\nfunction isInterfaceSchema(v: unknown): v is SvcInterfaceSchema {\n if (!v || typeof v !== \"object\") return false;\n const o = v as Record<string, unknown>;\n return typeof o.id === \"string\"\n && typeof o.methods === \"object\"\n && o.methods !== null\n && !Array.isArray(o.methods);\n}\n","/**\n * `hub _complete --line <line> --point <cursor>` — internal completion\n * resolver invoked by the shell scripts emitted by `hub completions`.\n *\n * Reads the line + cursor, optionally connects to whatever endpoint the line\n * already names (via `--endpoint*` flags or `LINKRPC_ENDPOINT`), and prints\n * one candidate per line as `text\\ttooltip`. Empty output on any error —\n * the completer that invokes us must never disturb the user's prompt.\n *\n * The actual resolution lives in `../completions/runComplete.ts`; this command\n * just formats the structured result for stdout.\n */\nimport { type Completion } from '../completions/complete';\nimport { completeForLine, type CompleteForLineOptions } from '../completions/runComplete';\nimport { type DirectorySource } from '../completions/directorySource';\n\nexport interface InternalCompleteOptions {\n readonly line: string;\n readonly point: number;\n /** Override the directory source (tests). */\n readonly directoryOverride?: DirectorySource;\n /** Suppress the connect attempt entirely (tests). */\n readonly skipConnect?: boolean;\n}\n\n/**\n * Compute completions and return them as a `\\n`-joined `text\\ttooltip` string\n * ready for stdout. Returns `''` when there are no candidates so callers can\n * unconditionally write the result.\n */\nexport async function internalCompleteCommand(opts: InternalCompleteOptions): Promise<string> {\n const runOpts: CompleteForLineOptions = {\n line: opts.line,\n point: opts.point,\n ...(opts.directoryOverride !== undefined ? { directoryOverride: opts.directoryOverride } : {}),\n ...(opts.skipConnect !== undefined ? { skipConnect: opts.skipConnect } : {}),\n };\n const result = await completeForLine(runOpts);\n return _formatCandidates(result.candidates);\n}\n\nfunction _formatCandidates(candidates: readonly Completion[]): string {\n return candidates\n .map((c) => (c.tooltip ? `${c.text}\\t${c.tooltip}` : c.text))\n .join('\\n');\n}\n","export interface DisplayForestNode<TNode, TEdge> {\n readonly node: TNode;\n readonly parentEdge?: TEdge;\n readonly children: readonly DisplayForestNode<TNode, TEdge>[];\n}\n\nexport interface DisplayForest<TNode, TEdge> {\n readonly roots: readonly DisplayForestNode<TNode, TEdge>[];\n readonly crossEdges: readonly TEdge[];\n}\n\nexport interface DisplayGraph<TNode, TEdge> {\n readonly nodes: readonly TNode[];\n readonly edges: readonly TEdge[];\n readonly rootIds: readonly string[];\n nodeId(node: TNode): string;\n edgeKey(edge: TEdge): string;\n edgeEndpoints(edge: TEdge): readonly [string, string];\n readonly directed?: boolean;\n}\n\n/**\n * Projects a graph into a deterministic shortest-path forest. Every node is\n * rendered once; non-tree edges remain available as explicit cross-links.\n */\nexport function createDisplayForest<TNode, TEdge>(\n graph: DisplayGraph<TNode, TEdge>,\n): DisplayForest<TNode, TEdge> {\n const nodes = new Map(graph.nodes.map((node) => [graph.nodeId(node), node]));\n const edges = [...graph.edges].sort((a, b) => graph.edgeKey(a).localeCompare(graph.edgeKey(b)));\n const adjacency = new Map<string, Array<{ edge: TEdge; next: string }>>();\n for (const edge of edges) {\n const [from, to] = graph.edgeEndpoints(edge);\n if (nodes.has(from) && nodes.has(to)) {\n addAdjacent(adjacency, from, edge, to);\n if (graph.directed !== true) addAdjacent(adjacency, to, edge, from);\n }\n }\n for (const entries of adjacency.values()) {\n entries.sort((a, b) =>\n a.next.localeCompare(b.next)\n || graph.edgeKey(a.edge).localeCompare(graph.edgeKey(b.edge)));\n }\n\n const parent = new Map<string, { parentId: string; edge: TEdge }>();\n const visited = new Set<string>();\n const roots: string[] = [];\n const walk = (rootId: string): void => {\n if (visited.has(rootId) || !nodes.has(rootId)) return;\n roots.push(rootId);\n visited.add(rootId);\n const queue = [rootId];\n for (let index = 0; index < queue.length; index++) {\n const current = queue[index];\n for (const entry of adjacency.get(current) ?? []) {\n if (visited.has(entry.next)) continue;\n visited.add(entry.next);\n parent.set(entry.next, { parentId: current, edge: entry.edge });\n queue.push(entry.next);\n }\n }\n };\n\n for (const rootId of [...new Set(graph.rootIds)].sort()) walk(rootId);\n for (const nodeId of [...nodes.keys()].sort()) walk(nodeId);\n\n const children = new Map<string, string[]>();\n for (const [nodeId, value] of parent) {\n const entries = children.get(value.parentId) ?? [];\n entries.push(nodeId);\n children.set(value.parentId, entries);\n }\n for (const entries of children.values()) entries.sort();\n\n const build = (nodeId: string): DisplayForestNode<TNode, TEdge> => ({\n node: nodes.get(nodeId)!,\n ...(parent.get(nodeId) !== undefined ? { parentEdge: parent.get(nodeId)!.edge } : {}),\n children: (children.get(nodeId) ?? []).map(build),\n });\n const treeEdgeKeys = new Set([...parent.values()].map((value) => graph.edgeKey(value.edge)));\n return {\n roots: roots.map(build),\n crossEdges: edges.filter((edge) => !treeEdgeKeys.has(graph.edgeKey(edge))),\n };\n}\n\nfunction addAdjacent<TEdge>(\n adjacency: Map<string, Array<{ edge: TEdge; next: string }>>,\n from: string,\n edge: TEdge,\n next: string,\n): void {\n const entries = adjacency.get(from) ?? [];\n entries.push({ edge, next });\n adjacency.set(from, entries);\n}\n","export type JsonValue =\n | null\n | boolean\n | number\n | string\n | JsonValue[]\n | { [key: string]: JsonValue };\n\nexport type JsonPatchOperation =\n | { readonly op: \"add\" | \"replace\"; readonly path: string; readonly value: JsonValue }\n | { readonly op: \"remove\"; readonly path: string };\n\nexport function createJsonPatch(\n before: JsonValue,\n after: JsonValue,\n path = \"\",\n): JsonPatchOperation[] {\n if (Object.is(before, after)) {\n return [];\n }\n if (isJsonObject(before) && isJsonObject(after)) {\n const operations: JsonPatchOperation[] = [];\n const beforeKeys = Object.keys(before).sort();\n const afterKeys = Object.keys(after).sort();\n const afterKeySet = new Set(afterKeys);\n for (const key of beforeKeys) {\n if (!afterKeySet.has(key)) {\n operations.push({ op: \"remove\", path: appendPath(path, key) });\n }\n }\n const beforeKeySet = new Set(beforeKeys);\n for (const key of afterKeys) {\n const childPath = appendPath(path, key);\n if (!beforeKeySet.has(key)) {\n operations.push({ op: \"add\", path: childPath, value: after[key] });\n } else {\n operations.push(...createJsonPatch(before[key], after[key], childPath));\n }\n }\n return operations;\n }\n return [{ op: \"replace\", path, value: after }];\n}\n\nexport function applyJsonPatch(\n value: JsonValue,\n operations: readonly JsonPatchOperation[],\n): JsonValue {\n let result = structuredClone(value);\n for (const operation of operations) {\n if (operation.path === \"\") {\n if (operation.op === \"remove\") {\n throw new Error(\"Cannot remove the JSON document root\");\n }\n result = structuredClone(operation.value);\n continue;\n }\n const segments = operation.path\n .slice(1)\n .split(\"/\")\n .map((segment) => segment.replaceAll(\"~1\", \"/\").replaceAll(\"~0\", \"~\"));\n let target = result;\n for (const segment of segments.slice(0, -1)) {\n if (typeof target !== \"object\" || target === null || Array.isArray(target)) {\n throw new Error(`JSON patch path does not address an object: ${operation.path}`);\n }\n target = target[segment];\n }\n if (typeof target !== \"object\" || target === null || Array.isArray(target)) {\n throw new Error(`JSON patch path does not address an object: ${operation.path}`);\n }\n const key = segments.at(-1)!;\n if (operation.op === \"remove\") {\n delete target[key];\n } else {\n target[key] = structuredClone(operation.value);\n }\n }\n return result;\n}\n\nfunction appendPath(path: string, key: string): string {\n return `${path}/${key.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")}`;\n}\n\nfunction isJsonObject(value: JsonValue): value is { [key: string]: JsonValue } {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n","import {\n createJsonPatch,\n type JsonPatchOperation,\n type JsonValue,\n} from \"./jsonPatch\";\n\nexport type StateJsonlLine =\n | {\n readonly type: \"snapshot\";\n readonly revision: number;\n readonly value: JsonValue;\n }\n | {\n readonly type: \"patch\";\n readonly revision: number;\n readonly patch: readonly JsonPatchOperation[];\n };\n\n/**\n * Serializes changing state as one initial value followed by atomic RFC 6902\n * patches. Await {@link whenIdle} before closing the destination.\n */\nexport class StateJsonlWriter {\n private _current: JsonValue | undefined;\n private _queue = Promise.resolve();\n\n public constructor(\n private readonly _emitLine: (line: string) => void | Promise<void>,\n ) {}\n\n public write(value: unknown, revision: number): void {\n const next = toJsonValue(value);\n this._queue = this._queue.then(async () => {\n if (this._current === undefined) {\n const line: StateJsonlLine = { type: \"snapshot\", revision, value: next };\n this._current = next;\n await this._emitLine(JSON.stringify(line));\n return;\n }\n const patch = createJsonPatch(this._current, next);\n this._current = next;\n if (patch.length === 0) return;\n const line: StateJsonlLine = { type: \"patch\", revision, patch };\n await this._emitLine(JSON.stringify(line));\n });\n }\n\n public async whenIdle(): Promise<void> {\n await this._queue;\n }\n}\n\nexport function toJsonValue(value: unknown): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n","import { mkdir, open, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { ErrorCode, type LinkRpcInterfaceSchema } from \"@hediet/linkrpc\";\nimport {\n DEFAULT_WALK_DEPTH,\n HubDirectoryExplorer,\n fetchSchema,\n type DiscoveredListing,\n type HubDirectoryGraphEvent,\n type HubDirectoryGraphSnapshot,\n type HubDirectoryNodeReport,\n type HubDirectoryGraphTarget,\n type InaccessibleDirectory,\n type ServiceListing,\n type WalkHubOptions,\n} from \"@hediet/linkrpc/hub/common\";\nimport type { CliChannel, SigningSession } from \"@hediet/linkrpc-client-internal\";\nimport { formatJson } from \"../output\";\nimport { createDisplayForest, type DisplayForestNode } from \"./displayForest\";\nimport { createJsonPatch, type JsonValue } from \"./jsonPatch\";\nimport { StateJsonlWriter } from \"./stateJsonl\";\n\nexport type LsFormat = \"pretty\" | \"json\" | \"jsonl\";\n\nexport interface LsOptions {\n readonly requestDirectoryAccess?: (serviceId: string) => Promise<boolean>;\n readonly log?: (message: string) => void;\n readonly interfaceId?: string;\n readonly interfacePrefix?: string;\n readonly serviceId?: string;\n readonly servicePrefix?: string;\n readonly search?: string;\n readonly json?: boolean;\n readonly format?: LsFormat;\n readonly withMembers?: boolean;\n /** Write a complete topology and schema fixture instead of rendering the listing. */\n readonly dumpPath?: string;\n /** Write one RFC 6902 operation per line as exploration progresses. `-` writes to stdout. */\n readonly dumpPatchesPath?: string;\n /** Emit an initial value and subsequent RFC 6902 patches as a patch-log JSONL stream. */\n readonly stream?: boolean;\n /** Keep the explorer watches active until `stop` resolves. Implies `stream`. */\n readonly watch?: boolean;\n /** Destination for stdout-oriented streaming modes. */\n readonly emitLine?: (line: string) => void | Promise<void>;\n /** Destination for a complete repainting terminal frame. */\n readonly emitFrame?: (frame: string) => void | Promise<void>;\n /** Receives each reconstructable state before it is rendered or serialized. */\n readonly onState?: (state: LsState) => void;\n /** Resolves when a watched stream should stop. */\n readonly stop?: Promise<void>;\n /**\n * When listing the whole bus, how many `hubrpc.directory` follow-ups\n * to perform. Defaults to 5. Ignored when `serviceId` is set (then we\n * just list that one service).\n */\n readonly maxDepth?: number;\n /** Hard deadline for each directory request. Defaults to 5 seconds. */\n readonly timeoutMs?: number;\n}\n\nexport interface LsState {\n readonly kind: \"directory\";\n readonly revision: number;\n readonly complete: boolean;\n readonly root: HubDirectoryNodeReport;\n readonly directories: readonly HubDirectoryNodeReport[];\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n}\n\n/**\n * Recursive bus walk: list the connection's directory, then for each\n * `hubrpc.directory` entry it surfaces on a service we haven't queried\n * yet, recurse. Bounded by `maxDepth`. Duplicates (same\n * `serviceId+interfaceId+hash`) are dropped.\n */\nexport async function lsCommand(channel: CliChannel, opts: LsOptions = {}): Promise<string> {\n validateLsOptions(opts);\n const legacyOutput = opts.format === undefined;\n if (opts.dumpPath !== undefined) {\n const dump = await createHubDump(channel, opts);\n const dumpPath = path.resolve(opts.dumpPath);\n await mkdir(path.dirname(dumpPath), { recursive: true });\n await writeFile(dumpPath, `${formatJson(dump)}\\n`, \"utf8\");\n return dumpSummary(\"Wrote\", dumpPath, dump);\n }\n if (opts.dumpPatchesPath !== undefined) {\n return runStreamingLs(channel, opts);\n }\n if (legacyOutput && (opts.stream === true || opts.watch === true)) {\n return runStreamingLs(channel, opts);\n }\n const format = resolveLsFormat(opts);\n if (opts.format !== undefined || opts.watch === true) {\n return runStateLs(channel, opts, format);\n }\n\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n await explorer.explore();\n const state = createLsState(explorer.graphSnapshot, opts);\n explorer.dispose();\n const all = state.listings;\n const output = opts.withMembers\n ? await addMembers(createSchemaFetcher(channel, opts), all, (listing) => listing.discoveredFrom)\n : all;\n if (format === \"json\") {\n for (const item of state.inaccessible) opts.log?.(`Inaccessible directory ${item.serviceId || \"(root)\"}: ${item.reason}`);\n return formatJson(legacyOutput ? output : state);\n }\n return [\n renderTree(output, opts.interfaceId),\n ...state.inaccessible.map(item => `! Inaccessible directory ${item.serviceId || \"(root)\"}: ${item.reason}`),\n ].join(\"\\n\");\n}\n\nexport async function requestDirectoryAccess(\n session: Pick<SigningSession, \"requestAccess\">,\n serviceId: string,\n options: Pick<LsOptions, \"watch\" | \"withMembers\" | \"dumpPath\" | \"dumpPatchesPath\">,\n): Promise<boolean> {\n const result = await session.requestAccess({\n consumer: { name: \"linkrpc-cli\", purpose: `Discover interfaces in ${serviceId}.` },\n permissions: [{\n target: {\n serviceId: { exact: serviceId },\n interfaceId: { exact: \"hubrpc.directory\" },\n members: [\n { exact: \"list\" },\n ...(options.watch ? [{ exact: \"watch\" }] : []),\n ],\n },\n canInvoke: true,\n }, ...(options.withMembers || options.dumpPath !== undefined || options.dumpPatchesPath !== undefined ? [{\n target: {\n serviceId: { exact: serviceId },\n interfaceId: { exact: \"hubrpc.schemas\" },\n members: [{ exact: \"get\" }],\n },\n canInvoke: true,\n }] : [])],\n duration: \"shortLived\",\n });\n if (result.status !== \"granted\") {\n throw new Error(`Directory access ${result.status}${\"reason\" in result && result.reason ? `: ${result.reason}` : \"\"}`);\n }\n return true;\n}\n\nfunction validateLsOptions(opts: LsOptions): void {\n validateSearchExpression(opts.search, \"ls\");\n if (opts.format !== undefined && opts.withMembers === true) {\n throw new Error(\"--format cannot be combined with --with-members\");\n }\n if (opts.dumpPath !== undefined) {\n if (\n opts.interfaceId !== undefined\n || opts.interfacePrefix !== undefined\n || opts.serviceId !== undefined\n || opts.servicePrefix !== undefined\n || opts.search !== undefined\n || opts.json === true\n || opts.format !== undefined\n || opts.withMembers === true\n || opts.stream === true\n || opts.watch === true\n || opts.dumpPatchesPath !== undefined\n ) {\n throw new Error(\n \"--dump cannot be combined with filters, --with-members, --json, --format, \"\n + \"--stream, --watch, or --dump-patches\",\n );\n }\n\n }\n if (opts.dumpPatchesPath !== undefined && (\n opts.interfaceId !== undefined\n || opts.interfacePrefix !== undefined\n || opts.serviceId !== undefined\n || opts.servicePrefix !== undefined\n || opts.search !== undefined\n || opts.json === true\n || opts.format !== undefined\n || opts.withMembers === true\n || opts.stream === true\n )) {\n throw new Error(\n \"--dump-patches cannot be combined with filters, --with-members, --json, \"\n + \"--format, or --stream\",\n );\n }\n if (\n opts.format === undefined\n && (opts.stream === true || opts.watch === true)\n && opts.withMembers === true\n ) {\n throw new Error(\"--stream/--watch already emit JSON and cannot include schema members\");\n }\n if (opts.format === \"jsonl\" && opts.dumpPatchesPath === undefined) {\n if (opts.emitLine === undefined) {\n throw new Error(\"JSONL ls output requires an output sink\");\n }\n }\n if (\n opts.watch === true\n && opts.format === \"pretty\"\n && opts.emitFrame === undefined\n ) {\n throw new Error(\"pretty ls watch requires a frame output sink\");\n }\n if (opts.watch === true && opts.stop === undefined) {\n throw new Error(\"--watch requires a stop signal\");\n }\n}\n\nfunction validateSearchExpression(search: string | undefined, command: string): void {\n if (search === undefined) return;\n try {\n new RegExp(search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid ${command} search regexp: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n\nfunction explorerOptions(opts: LsOptions): WalkHubOptions {\n return {\n unlockGatedDirectory: opts.requestDirectoryAccess,\n log: opts.log,\n maxDepth: opts.serviceId === undefined\n ? opts.maxDepth ?? DEFAULT_WALK_DEPTH\n : 0,\n ...(opts.interfaceId !== undefined ? { interfaceId: opts.interfaceId } : {}),\n ...(opts.interfacePrefix !== undefined\n ? { interfaceIdPrefix: opts.interfacePrefix }\n : {}),\n ...(opts.serviceId !== undefined\n ? { rootTarget: opts.serviceId, serviceId: opts.serviceId }\n : {}),\n ...(opts.timeoutMs !== undefined ? { timeoutMs: opts.timeoutMs } : {}),\n };\n}\n\nfunction resolveLsFormat(opts: LsOptions): LsFormat {\n if (opts.format !== undefined) return opts.format;\n if (opts.stream === true) return \"jsonl\";\n if (opts.json === true) return \"json\";\n return \"pretty\";\n}\n\nasync function runStateLs(\n channel: CliChannel,\n opts: LsOptions,\n format: LsFormat,\n): Promise<string> {\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n const writer = format === \"jsonl\" ? new StateJsonlWriter(opts.emitLine!) : undefined;\n let state = createLsState(explorer.graphSnapshot, opts);\n let outputQueue = Promise.resolve();\n const emitState = (snapshot: HubDirectoryGraphSnapshot): void => {\n state = createLsState(snapshot, opts);\n opts.onState?.(state);\n if (writer !== undefined) {\n writer.write(state, state.revision);\n } else if (opts.watch === true && format === \"pretty\") {\n const frame = renderLsState(state, opts);\n outputQueue = outputQueue.then(() => opts.emitFrame!(frame));\n }\n };\n const unsubscribe = explorer.subscribe((event) => emitState(event.snapshot));\n let stopWatch: (() => void) | undefined;\n try {\n if (opts.watch === true) {\n stopWatch = await explorer.watch(() => {});\n await opts.stop;\n stopWatch();\n stopWatch = undefined;\n await explorer.whenIdle();\n emitState(explorer.graphSnapshot);\n } else {\n await explorer.explore();\n emitState(explorer.graphSnapshot);\n }\n await outputQueue;\n await writer?.whenIdle();\n if (format === \"json\") return formatJson(state);\n if (format === \"pretty\") return opts.watch === true ? \"\" : renderLsState(state, opts);\n return \"\";\n } finally {\n stopWatch?.();\n unsubscribe();\n explorer.dispose();\n await outputQueue;\n await writer?.whenIdle();\n }\n}\n\nexport function createLsState(\n snapshot: HubDirectoryGraphSnapshot,\n opts: Pick<\n LsOptions,\n \"interfaceId\" | \"interfacePrefix\" | \"serviceId\" | \"servicePrefix\" | \"search\"\n > = {},\n): LsState {\n const matches = createListingFilter(opts);\n const mapNode = (node: HubDirectoryNodeReport): HubDirectoryNodeReport => ({\n ...node,\n nativeListings: node.nativeListings.filter(matches),\n });\n return {\n kind: \"directory\",\n revision: snapshot.revision,\n complete: snapshot.complete,\n root: mapNode(snapshot.root),\n directories: snapshot.directories.map(mapNode),\n listings: snapshot.result.listings.filter(matches),\n inaccessible: snapshot.result.inaccessible,\n };\n}\n\nfunction createListingFilter(\n opts: Pick<\n LsOptions,\n \"interfaceId\" | \"interfacePrefix\" | \"serviceId\" | \"servicePrefix\" | \"search\"\n >,\n): (listing: ServiceListing) => boolean {\n let search: RegExp | undefined;\n if (opts.search !== undefined) {\n try {\n search = new RegExp(opts.search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid ls search regexp: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n return (listing) =>\n (opts.interfaceId === undefined || listing.interfaceId === opts.interfaceId)\n && (opts.interfacePrefix === undefined\n || listing.interfaceId.startsWith(opts.interfacePrefix))\n && (opts.serviceId === undefined || listing.serviceId === opts.serviceId)\n && (opts.servicePrefix === undefined\n || listing.serviceId.startsWith(opts.servicePrefix))\n && (search === undefined || search.test(JSON.stringify(listing)));\n}\n\nfunction renderLsState(state: LsState, opts: Pick<LsOptions, \"interfaceId\">): string {\n const status = state.complete ? \"complete\" : \"loading\";\n const nodes = [state.root, ...state.directories];\n const edges: DirectoryDisplayEdge[] = [];\n for (const node of nodes) {\n for (const parent of node.parents) {\n edges.push({\n from: directoryTargetKey(parent.target),\n to: directoryTargetKey(node.target),\n scopes: parent.scopes.map((scope) =>\n \"exact\" in scope ? `=${scope.exact}` : `${scope.prefix}*`),\n });\n }\n }\n const forest = createDisplayForest({\n nodes,\n edges,\n rootIds: [directoryTargetKey(state.root.target)],\n nodeId: (node) => directoryTargetKey(node.target),\n edgeKey: (edge) => `${edge.from}\\0${edge.to}\\0${edge.scopes.join(\"\\0\")}`,\n edgeEndpoints: (edge) => [edge.from, edge.to],\n directed: true,\n });\n const body: string[] = [];\n for (const root of forest.roots) renderDirectoryNode(root, body, \"\");\n if (forest.crossEdges.length > 0) {\n body.push(\"\", \"Additional referrals\");\n for (const edge of forest.crossEdges) {\n body.push(` ${edge.from} → ${edge.to}${formatScopes(edge.scopes)}`);\n }\n }\n if (state.inaccessible.length > 0) {\n body.push(\"\", \"Inaccessible\");\n for (const item of state.inaccessible) {\n body.push(` ${item.serviceId}: ${item.reason}`);\n }\n }\n return [\n `LinkRPC directory (${status}, revision ${state.revision})`,\n \"\",\n ...(body.length > 0 ? body : [\"(empty)\"]),\n ].join(\"\\n\");\n}\n\ninterface DirectoryDisplayEdge {\n readonly from: string;\n readonly to: string;\n readonly scopes: readonly string[];\n}\n\nfunction renderDirectoryNode(\n item: DisplayForestNode<HubDirectoryNodeReport, DirectoryDisplayEdge>,\n lines: string[],\n prefix: string,\n): void {\n const watch = item.node.watching ? \", watching\" : \"\";\n lines.push(\n `${prefix}${directoryTargetLabel(item.node.target)} [${item.node.state}${watch}]`\n + (item.parentEdge === undefined ? \"\" : formatScopes(item.parentEdge.scopes)),\n );\n for (const listing of item.node.nativeListings) {\n const service = listing.serviceId === \"\" ? \"(root)\" : listing.serviceId;\n lines.push(`${prefix} ${service} → ${listing.interfaceId} @ ${listing.hash}`);\n }\n if (item.node.inaccessibleReason !== undefined) {\n lines.push(`${prefix} ! ${item.node.inaccessibleReason}`);\n }\n for (let index = 0; index < item.children.length; index++) {\n const child = item.children[index];\n const last = index === item.children.length - 1;\n const childPrefix = prefix + (last ? \" \" : \"│ \");\n const childLines: string[] = [];\n renderDirectoryNode(child, childLines, childPrefix);\n childLines[0] = `${prefix}${last ? \"└─ \" : \"├─ \"}${childLines[0].slice(childPrefix.length)}`;\n lines.push(...childLines);\n }\n}\n\nfunction directoryTargetKey(target: HubDirectoryGraphTarget): string {\n return target.kind === \"root\"\n ? `root:${target.serviceId ?? \"\"}`\n : `service:${target.serviceId}`;\n}\n\nfunction directoryTargetLabel(target: HubDirectoryGraphTarget): string {\n if (target.kind === \"addressed\") return target.serviceId;\n return target.serviceId === undefined || target.serviceId === \"\"\n ? \"(connection root)\"\n : `(root listing for ${target.serviceId})`;\n}\n\nfunction formatScopes(scopes: readonly string[]): string {\n return scopes.length === 0 ? \"\" : ` via ${scopes.join(\", \")}`;\n}\n\ninterface LsMember {\n readonly name: string;\n readonly kind: \"request\" | \"notification\";\n}\n\ninterface LsListing extends ServiceListing {\n readonly members?: readonly LsMember[];\n}\n\nfunction createSchemaFetcher(channel: CliChannel, opts: Pick<LsOptions, \"requestDirectoryAccess\">) {\n const approvals = new Map<string, Promise<boolean>>();\n return async (interfaceId: string, hash: string, target: string | undefined) => {\n try {\n return await fetchSchema(channel, interfaceId, hash, target);\n } catch (error) {\n if (typeof error !== \"object\" || error === null || !(\"code\" in error)\n || error.code !== ErrorCode.permissionRequired || !target || !opts.requestDirectoryAccess) {\n throw error;\n }\n let approval = approvals.get(target);\n if (!approval) {\n approval = opts.requestDirectoryAccess(target);\n approvals.set(target, approval);\n }\n if (!await approval) throw error;\n return fetchSchema(channel, interfaceId, hash, target);\n }\n };\n}\n\nasync function addMembers<T extends ServiceListing>(\n getSchema: ReturnType<typeof createSchemaFetcher>,\n listings: readonly T[],\n getTarget: (listing: T) => string | undefined,\n): Promise<LsListing[]> {\n const cache = new Map<string, Promise<readonly LsMember[]>>();\n return Promise.all(listings.map(async (listing) => {\n const target = getTarget(listing);\n const cacheKey = `${target ?? \"\"}\\0${listing.interfaceId}\\0${listing.hash}`;\n let members = cache.get(cacheKey);\n if (members === undefined) {\n members = getSchema(\n listing.interfaceId,\n listing.hash,\n target === \"\" ? undefined : target,\n ).then((schema) =>\n Object.entries(schema.methods)\n .map(([name, method]): LsMember => ({\n name,\n kind: method.result === undefined ? \"notification\" : \"request\",\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n );\n cache.set(cacheKey, members);\n }\n return { ...listing, members: await members };\n }));\n}\n\nexport interface HubDumpSchemaError {\n readonly interfaceIds: readonly string[];\n readonly attempts: readonly {\n readonly reportedBy: string;\n readonly interfaceId: string;\n readonly error: string;\n }[];\n}\n\nexport interface HubDump {\n readonly format: \"linkrpc-hub-dump\";\n readonly version: 2;\n readonly revision: number;\n readonly complete: boolean;\n readonly schemasComplete: boolean;\n readonly root: HubDirectoryNodeReport;\n readonly directories: Readonly<Record<string, HubDirectoryNodeReport>>;\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n /** Complete reflected interface schemas, deduplicated by interface hash. */\n readonly schemas: Readonly<Record<string, LinkRpcInterfaceSchema>>;\n /** Hashes advertised by a directory but not retrievable from any reporter. */\n readonly schemaErrors: Readonly<Record<string, HubDumpSchemaError>>;\n}\n\nexport function createInitialHubDump(): HubDump {\n return {\n format: \"linkrpc-hub-dump\",\n version: 2,\n revision: 0,\n complete: false,\n schemasComplete: false,\n root: {\n target: { kind: \"root\" },\n state: \"unexplored\",\n effectiveScopes: [{ prefix: \"\" }],\n depth: 0,\n parents: [],\n nativeListings: [],\n watching: false,\n },\n directories: {},\n listings: [],\n inaccessible: [],\n schemas: {},\n schemaErrors: {},\n };\n}\n\nexport async function createHubDump(\n channel: CliChannel,\n opts: Pick<LsOptions, \"maxDepth\" | \"timeoutMs\" | \"requestDirectoryAccess\" | \"log\"> = {},\n): Promise<HubDump> {\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n await explorer.explore();\n const cache = await fetchDumpSchemas(createSchemaFetcher(channel, opts), explorer.graphSnapshot);\n const dump = buildHubDump(explorer.graphSnapshot, cache, true);\n explorer.dispose();\n return dump;\n}\n\ninterface SchemaCandidate {\n readonly reportedBy: string;\n readonly target: string | undefined;\n readonly interfaceId: string;\n}\n\ninterface DumpSchemaCache {\n readonly schemas: Map<string, LinkRpcInterfaceSchema>;\n readonly errors: Map<string, HubDumpSchemaError>;\n}\n\nasync function fetchDumpSchemas(\n getSchema: ReturnType<typeof createSchemaFetcher>,\n snapshot: HubDirectoryGraphSnapshot,\n cache: DumpSchemaCache = { schemas: new Map(), errors: new Map() },\n): Promise<DumpSchemaCache> {\n const candidatesByHash = collectSchemaCandidates(snapshot);\n for (const [hash, candidates] of candidatesByHash) {\n if (cache.schemas.has(hash)) continue;\n cache.errors.delete(hash);\n const attempts: { reportedBy: string; interfaceId: string; error: string; }[] = [];\n for (const candidate of candidates) {\n try {\n const schema = await getSchema(\n candidate.interfaceId,\n hash,\n candidate.target,\n );\n cache.schemas.set(hash, schema);\n break;\n } catch (error) {\n attempts.push({\n reportedBy: candidate.reportedBy,\n interfaceId: candidate.interfaceId,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n if (!cache.schemas.has(hash)) {\n cache.errors.set(hash, {\n interfaceIds: [...new Set(candidates.map((candidate) => candidate.interfaceId))],\n attempts,\n });\n }\n }\n return cache;\n}\n\nfunction buildHubDump(\n snapshot: HubDirectoryGraphSnapshot,\n cache: DumpSchemaCache,\n schemasComplete: boolean,\n): HubDump {\n const directories = Object.fromEntries(snapshot.directories.map((directory) => [\n directory.target.kind === \"addressed\" ? directory.target.serviceId : \"\",\n directory,\n ]));\n const activeHashes = new Set(collectSchemaCandidates(snapshot).keys());\n for (const hash of [...cache.schemas.keys()]) {\n if (!activeHashes.has(hash)) cache.schemas.delete(hash);\n }\n for (const hash of [...cache.errors.keys()]) {\n if (!activeHashes.has(hash)) cache.errors.delete(hash);\n }\n return {\n format: \"linkrpc-hub-dump\",\n version: 2,\n revision: snapshot.revision,\n complete: snapshot.complete,\n schemasComplete,\n root: snapshot.root,\n directories,\n listings: snapshot.result.listings,\n inaccessible: snapshot.result.inaccessible,\n schemas: Object.fromEntries(cache.schemas),\n schemaErrors: Object.fromEntries(cache.errors),\n };\n}\n\nfunction collectSchemaCandidates(\n snapshot: HubDirectoryGraphSnapshot,\n): Map<string, SchemaCandidate[]> {\n const result = new Map<string, SchemaCandidate[]>();\n for (const report of [snapshot.root, ...snapshot.directories]) {\n const target = report.target.serviceId;\n const reportedBy = target ?? \"\";\n for (const listing of report.nativeListings) {\n const candidates = result.get(listing.hash) ?? [];\n if (!candidates.some((candidate) =>\n candidate.reportedBy === reportedBy\n && candidate.interfaceId === listing.interfaceId\n )) {\n candidates.push({ reportedBy, target, interfaceId: listing.interfaceId });\n result.set(listing.hash, candidates);\n }\n }\n }\n return result;\n}\n\nasync function runStreamingLs(channel: CliChannel, opts: LsOptions): Promise<string> {\n const getSchema = createSchemaFetcher(channel, opts);\n const explorer = new HubDirectoryExplorer(channel, explorerOptions(opts));\n const patchMode = opts.dumpPatchesPath !== undefined;\n const patchPath = patchMode && opts.dumpPatchesPath !== \"-\"\n ? path.resolve(opts.dumpPatchesPath)\n : undefined;\n if (patchPath !== undefined) await mkdir(path.dirname(patchPath), { recursive: true });\n const file = patchPath !== undefined ? await open(patchPath, \"w\") : undefined;\n const writeLine = file !== undefined\n ? async (line: string) => { await file.write(`${line}\\n`); }\n : opts.emitLine;\n if (writeLine === undefined) {\n explorer.dispose();\n throw new Error(\"--dump-patches - requires an output sink\");\n }\n\n let currentDump = createInitialHubDump();\n let previousListings: readonly DiscoveredListing[] = [];\n let previousStreamValue: LsStreamEvent | undefined;\n const schemaCache: DumpSchemaCache = { schemas: new Map(), errors: new Map() };\n let queue = Promise.resolve();\n const unsubscribe = explorer.subscribe((event) => {\n queue = queue.then(async () => {\n if (patchMode) {\n if (event.type === \"settled\") {\n await fetchDumpSchemas(getSchema, event.snapshot, schemaCache);\n }\n const schemasComplete = event.snapshot.complete\n && [...collectSchemaCandidates(event.snapshot).keys()].every((hash) =>\n schemaCache.schemas.has(hash) || schemaCache.errors.has(hash));\n const next = buildHubDump(event.snapshot, schemaCache, schemasComplete);\n for (const operation of createJsonPatch(\n toJsonValue(currentDump),\n toJsonValue(next),\n )) {\n await writeLine(JSON.stringify(operation));\n }\n currentDump = next;\n } else {\n const nextStreamValue = createLsStreamEvent(event, previousListings);\n await writeLine(JSON.stringify(createPatchLogLine(event, previousStreamValue, nextStreamValue)));\n previousListings = event.snapshot.result.listings;\n previousStreamValue = nextStreamValue;\n }\n });\n });\n\n let stopWatch: (() => void) | undefined;\n try {\n if (opts.watch === true) {\n stopWatch = await explorer.watch(() => {});\n } else {\n await explorer.explore();\n }\n await queue;\n if (opts.watch === true) {\n await opts.stop;\n stopWatch();\n stopWatch = undefined;\n await explorer.whenIdle();\n await queue;\n }\n } finally {\n stopWatch?.();\n unsubscribe();\n explorer.dispose();\n try {\n await queue;\n } finally {\n await file?.close();\n }\n }\n\n if (patchPath !== undefined) {\n return dumpSummary(\"Wrote patches to\", patchPath, currentDump);\n }\n return \"\";\n}\n\ninterface LsStreamEvent {\n readonly type: HubDirectoryGraphEvent[\"type\"];\n readonly reason?: string;\n readonly revision: number;\n readonly complete: boolean;\n readonly target?: HubDirectoryNodeReport[\"target\"];\n readonly state?: HubDirectoryNodeReport[\"state\"];\n readonly added: readonly DiscoveredListing[];\n readonly removed: readonly DiscoveredListing[];\n readonly listings: readonly DiscoveredListing[];\n readonly inaccessible: readonly InaccessibleDirectory[];\n}\n\ntype LsPatchLogLine =\n | {\n readonly message: string;\n readonly time: number;\n readonly value: LsStreamEvent;\n }\n | {\n readonly message: string;\n readonly time: number;\n readonly patch: ReturnType<typeof createJsonPatch>;\n };\n\nfunction createPatchLogLine(\n event: HubDirectoryGraphEvent,\n previous: LsStreamEvent | undefined,\n next: LsStreamEvent,\n): LsPatchLogLine {\n const metadata = {\n message: describeLsStreamEvent(event),\n time: Date.now(),\n };\n if (previous === undefined) {\n return { ...metadata, value: next };\n }\n return {\n ...metadata,\n patch: createJsonPatch(toJsonValue(previous), toJsonValue(next)),\n };\n}\n\nfunction describeLsStreamEvent(event: HubDirectoryGraphEvent): string {\n if (event.type === \"settled\") return \"Directory exploration settled\";\n const subject = event.type === \"snapshot\"\n ? \"Directory snapshot\"\n : event.type === \"node-added\"\n ? \"Directory node added\"\n : event.type === \"node-updated\"\n ? \"Directory node updated\"\n : \"Directory node removed\";\n return `${subject}: ${event.reason}`;\n}\n\nfunction createLsStreamEvent(\n event: HubDirectoryGraphEvent,\n previousListings: readonly DiscoveredListing[],\n): LsStreamEvent {\n const current = event.snapshot.result.listings;\n const previousByKey = new Map(previousListings.map((listing) => [listingKey(listing), listing]));\n const currentByKey = new Map(current.map((listing) => [listingKey(listing), listing]));\n const node = \"node\" in event ? event.node : undefined;\n return {\n type: event.type,\n ...(\"reason\" in event ? { reason: event.reason } : {}),\n revision: event.snapshot.revision,\n complete: event.snapshot.complete,\n ...(node !== undefined ? { target: node.target, state: node.state } : {}),\n added: current.filter((listing) => !previousByKey.has(listingKey(listing))),\n removed: previousListings.filter((listing) => !currentByKey.has(listingKey(listing))),\n listings: current,\n inaccessible: event.snapshot.result.inaccessible,\n };\n}\n\nfunction listingKey(listing: ServiceListing): string {\n return `${listing.serviceId}\\0${listing.interfaceId}\\0${listing.hash}`;\n}\n\nfunction toJsonValue(value: unknown): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n}\n\nfunction dumpSummary(prefix: string, destination: string, dump: HubDump): string {\n return `${prefix} ${destination} (${Object.keys(dump.directories).length + 1} directories, `\n + `${Object.keys(dump.schemas).length} schemas)`;\n}\n\nfunction renderTree(\n listings: readonly LsListing[],\n interfaceFilter: string | undefined,\n): string {\n if (listings.length === 0) {\n return interfaceFilter\n ? `(no interfaces matching \"${interfaceFilter}\")`\n : \"(no services)\";\n }\n\n const byService = new Map<string, LsListing[]>();\n for (const l of listings) {\n const bucket = byService.get(l.serviceId) ?? [];\n bucket.push(l);\n byService.set(l.serviceId, bucket);\n }\n const serviceIds = [...byService.keys()].sort((a, b) => {\n // Root first, then lexical.\n if (a === b) return 0;\n if (a === \"\") return -1;\n if (b === \"\") return 1;\n return a < b ? -1 : 1;\n });\n\n const lines: string[] = [];\n for (const sid of serviceIds) {\n lines.push(sid === \"\" ? \"(root)\" : sid);\n const ifaces = (byService.get(sid) ?? [])\n .slice()\n .sort((a, b) => (a.interfaceId < b.interfaceId ? -1 : a.interfaceId > b.interfaceId ? 1 : 0));\n for (let i = 0; i < ifaces.length; i++) {\n const isLast = i === ifaces.length - 1;\n const branch = isLast ? \"└── \" : \"├── \";\n const path = ifaces[i].path ? ` [${ifaces[i].path}]` : \"\";\n lines.push(`${branch}${ifaces[i].interfaceId} @ ${ifaces[i].hash}${path}`);\n const members = ifaces[i].members ?? [];\n for (let j = 0; j < members.length; j++) {\n const memberPrefix = isLast ? \" \" : \"│ \";\n const memberBranch = j === members.length - 1 ? \"└── \" : \"├── \";\n lines.push(\n `${memberPrefix}${memberBranch}${members[j].kind.padEnd(12)} ${members[j].name}`,\n );\n }\n }\n }\n return lines.join(\"\\n\");\n}\n","import { LinkRpcConnection } from \"@hediet/linkrpc\";\nimport type {\n NetworkTopologyGraph,\n SourcedTopologyLink,\n SourcedTopologyNode,\n TopologyNetworkSnapshot,\n} from \"@hediet/linkrpc-infra/inspection\";\nimport { TopologyNetworkClient } from \"@hediet/linkrpc-infra/inspection\";\nimport type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { formatJson } from \"../output\";\nimport { createDisplayForest, type DisplayForestNode } from \"./displayForest\";\nimport { StateJsonlWriter } from \"./stateJsonl\";\n\nexport type TopologyFormat = \"pretty\" | \"json\" | \"jsonl\";\n\nexport interface TopologyCommandOptions {\n readonly sources?: readonly string[];\n readonly maxDepth?: number;\n readonly timeoutMs?: number;\n readonly watch?: boolean;\n readonly format?: TopologyFormat;\n readonly nodeId?: string;\n readonly serviceId?: string;\n readonly kind?: \"hub\" | \"endpoint\";\n readonly search?: string;\n readonly emitLine?: (line: string) => void | Promise<void>;\n readonly emitFrame?: (frame: string) => void | Promise<void>;\n readonly onState?: (state: TopologyNetworkSnapshot) => void;\n readonly stop?: Promise<void>;\n}\n\nexport async function topologyCommand(\n channel: CliChannel,\n options: TopologyCommandOptions = {},\n): Promise<string> {\n const format = options.format ?? \"pretty\";\n compileTopologySearch(options.search);\n if (format === \"jsonl\" && options.emitLine === undefined) {\n throw new Error(\"JSONL topology output requires an output sink\");\n }\n if (options.watch === true && options.stop === undefined) {\n throw new Error(\"topology watch requires a stop signal\");\n }\n if (options.watch === true && format === \"pretty\" && options.emitFrame === undefined) {\n throw new Error(\"pretty topology watch requires a frame output sink\");\n }\n\n const connection = new LinkRpcConnection(channel);\n const client = new TopologyNetworkClient(connection);\n const writer = format === \"jsonl\" ? new StateJsonlWriter(options.emitLine!) : undefined;\n let latest: TopologyNetworkSnapshot | undefined;\n let outputQueue = Promise.resolve();\n const consume = (snapshot: TopologyNetworkSnapshot): void => {\n latest = filterTopologySnapshot(snapshot, options);\n options.onState?.(latest);\n if (writer !== undefined) {\n writer.write(latest, latest.revision);\n } else if (options.watch === true && format === \"pretty\") {\n const frame = renderTopology(latest);\n outputQueue = outputQueue.then(() => options.emitFrame!(frame));\n }\n };\n const sourceOptions = {\n ...(options.sources !== undefined ? { sourceServiceIds: options.sources } : {}),\n ...(options.maxDepth !== undefined ? { maxDepth: options.maxDepth } : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n };\n\n if (options.watch === true) {\n const watch = client.watch(sourceOptions);\n const unsubscribe = watch.subscribe(consume);\n try {\n await options.stop;\n } finally {\n await watch.cancel(\"topology CLI stopped\");\n unsubscribe();\n }\n } else {\n latest = await client.query(sourceOptions, { onSnapshot: consume });\n latest = filterTopologySnapshot(latest, options);\n }\n\n await outputQueue;\n await writer?.whenIdle();\n const snapshot = latest ?? filterTopologySnapshot(\n await client.query(sourceOptions),\n options,\n );\n if (format === \"json\") return formatJson(snapshot);\n if (format === \"pretty\") return options.watch === true ? \"\" : renderTopology(snapshot);\n return \"\";\n}\n\nexport function filterTopologySnapshot(\n snapshot: TopologyNetworkSnapshot,\n options: Pick<TopologyCommandOptions, \"nodeId\" | \"serviceId\" | \"kind\" | \"search\">,\n): TopologyNetworkSnapshot {\n const hasFilter = options.nodeId !== undefined\n || options.serviceId !== undefined\n || options.kind !== undefined\n || options.search !== undefined;\n if (!hasFilter) return snapshot;\n const search = compileTopologySearch(options.search);\n const graph = snapshot.graph;\n const routesByNode = new Map<string, NetworkTopologyGraph[\"routes\"]>();\n for (const route of graph.routes) {\n const routes = routesByNode.get(route.nodeId) ?? [];\n routesByNode.set(route.nodeId, [...routes, route]);\n }\n const matchingNodeIds = new Set(graph.nodes\n .filter((node) => {\n const routes = routesByNode.get(node.nodeId) ?? [];\n return (options.nodeId === undefined || node.nodeId === options.nodeId)\n && (options.kind === undefined || node.kind === options.kind)\n && (options.serviceId === undefined\n || routes.some((route) => route.serviceId === options.serviceId))\n && (search === undefined || search.test(JSON.stringify({\n node,\n routes,\n })));\n })\n .map((node) => node.nodeId));\n const nodes = graph.nodes.filter((node) => matchingNodeIds.has(node.nodeId));\n const nodeIds = new Set(nodes.map((node) => node.nodeId));\n return {\n ...snapshot,\n graph: {\n ...graph,\n nodes,\n links: graph.links.filter((link) =>\n nodeIds.has(link.from.nodeId) && nodeIds.has(link.to.nodeId)),\n routes: graph.routes.filter((route) =>\n nodeIds.has(route.nodeId)\n && (options.serviceId === undefined || route.serviceId === options.serviceId)),\n },\n };\n}\n\nfunction compileTopologySearch(search: string | undefined): RegExp | undefined {\n if (search === undefined) return undefined;\n try {\n return new RegExp(search, \"i\");\n } catch (error) {\n throw new Error(\n `Invalid topology search regexp: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n}\n\nexport function renderTopology(snapshot: TopologyNetworkSnapshot): string {\n const sourceLines = snapshot.sources.map((source) => {\n const marker = source.state === \"ready\" ? \"✓\" : source.state === \"loading\" ? \"…\" : \"!\";\n return ` ${marker} ${source.serviceId}${source.error ? ` — ${source.error}` : \"\"}`;\n });\n const forest = createDisplayForest({\n nodes: snapshot.graph.nodes,\n edges: snapshot.graph.links,\n rootIds: snapshot.graph.sources.map((source) => source.entryNodeId),\n nodeId: (node) => node.nodeId,\n edgeKey: topologyLinkKey,\n edgeEndpoints: (link) => [link.from.nodeId, link.to.nodeId],\n });\n const routeMap = new Map<string, NetworkTopologyGraph[\"routes\"]>();\n for (const route of snapshot.graph.routes) {\n const routes = routeMap.get(route.nodeId) ?? [];\n routeMap.set(route.nodeId, [...routes, route]);\n }\n const treeLines: string[] = [];\n for (const root of forest.roots) renderTopologyNode(root, routeMap, treeLines, \"\");\n if (forest.crossEdges.length > 0) {\n treeLines.push(\"\", \"Additional links\");\n for (const link of forest.crossEdges) {\n treeLines.push(` ${formatEndpoint(link.from)} ↔ ${formatEndpoint(link.to)}`);\n }\n }\n const status = snapshot.complete ? \"complete\" : \"loading\";\n return [\n `LinkRPC topology (${status}, revision ${snapshot.revision})`,\n \"\",\n \"Sources\",\n ...(sourceLines.length > 0 ? sourceLines : [\" (none)\"]),\n \"\",\n \"Network\",\n ...(treeLines.length > 0 ? treeLines : [\" (empty)\"]),\n ].join(\"\\n\");\n}\n\nfunction renderTopologyNode(\n item: DisplayForestNode<SourcedTopologyNode, SourcedTopologyLink>,\n routes: ReadonlyMap<string, NetworkTopologyGraph[\"routes\"]>,\n lines: string[],\n prefix: string,\n): void {\n const label = participantLabel(item.node);\n lines.push(`${prefix}${label} [${item.node.kind ?? \"unknown\"}]`);\n for (const route of routes.get(item.node.nodeId) ?? []) {\n lines.push(`${prefix} ${route.match.padEnd(6)} ${route.serviceId} → ${route.portId}`);\n }\n for (let index = 0; index < item.children.length; index++) {\n const child = item.children[index];\n const last = index === item.children.length - 1;\n const branch = last ? \"└─ \" : \"├─ \";\n const childPrefix = prefix + (last ? \" \" : \"│ \");\n const childLines: string[] = [];\n renderTopologyNode(child, routes, childLines, childPrefix);\n childLines[0] = `${prefix}${branch}${childLines[0].slice(childPrefix.length)}`;\n lines.push(...childLines);\n }\n}\n\nfunction participantLabel(node: SourcedTopologyNode): string {\n for (const source of node.descriptors ?? []) {\n if (source.descriptor.label !== undefined) return source.descriptor.label;\n }\n return node.label ?? node.nodeId;\n}\n\nfunction topologyLinkKey(link: SourcedTopologyLink): string {\n const endpoints = [formatEndpoint(link.from), formatEndpoint(link.to)].sort();\n return `${endpoints[0]}\\0${endpoints[1]}`;\n}\n\nfunction formatEndpoint(endpoint: { readonly nodeId: string; readonly portId: string }): string {\n return `${endpoint.nodeId}:${endpoint.portId}`;\n}\n","import type { CliChannel } from \"@hediet/linkrpc-client-internal\";\n\nexport async function pingCommand(channel: CliChannel): Promise<string> {\n const start = performance.now();\n await channel.sendRequest(\"hubrpc.defaults::get\", {});\n const latencyMs = performance.now() - start;\n return `pong ${latencyMs.toFixed(1)}ms`;\n}\n","import { createInterface } from 'node:readline/promises';\nimport { stdin as input, stdout as output } from 'node:process';\nimport {\n LinkRpcConnection,\n type TopologyGraph,\n type TrafficEvent,\n type TrafficTransitEvent,\n} from '@hediet/linkrpc';\nimport {\n HubDirectoryExplorer,\n} from '@hediet/linkrpc/hub/common';\nimport type {\n ParticipantDescriptorSource,\n RouteClaim,\n} from '@hediet/linkrpc';\nimport {\n formatFlowSummary,\n TrafficFlowAggregator,\n} from '@hediet/linkrpc-hub';\nimport { TopologyClient, TrafficClient } from '@hediet/linkrpc-infra/inspection';\nimport type { CliChannel } from '@hediet/linkrpc-client-internal';\nimport { formatJson } from '../output';\n\nexport interface ParticipantWatchOptions {\n readonly search?: string;\n readonly nodeId?: string;\n readonly format?: 'pretty' | 'plain' | 'jsonl';\n readonly methodPrefix?: string;\n readonly payloadBytes?: number;\n readonly resume?: string | true;\n readonly stop: Promise<void>;\n readonly emit?: (line: string) => void;\n}\n\nexport interface ParticipantSummary {\n readonly nodeId: string;\n readonly descriptors: readonly ParticipantDescriptorSource[];\n readonly routeClaims: readonly RouteClaim[];\n readonly serviceIds: readonly string[];\n readonly sourceServices: readonly string[];\n}\n\ninterface InspectionSource {\n readonly serviceId: string;\n readonly graph: TopologyGraph;\n}\n\nconst TOPOLOGY_INTERFACE = 'hubrpc.topology';\n\nexport async function topologyParticipantsCommand(\n channel: CliChannel,\n search?: string,\n): Promise<string> {\n const participants = await discoverParticipants(channel);\n const filtered = filterParticipants(participants, search);\n return formatJson(filtered);\n}\n\nexport async function trafficWatchCommand(\n channel: CliChannel,\n options: ParticipantWatchOptions,\n): Promise<void> {\n const emit = options.emit ?? ((line: string) => process.stdout.write(line + '\\n'));\n const connection = new LinkRpcConnection(channel);\n const sources = await discoverTopologySources(channel, connection);\n let participants = summarizeParticipants(sources);\n let search = options.search;\n let nodeId = options.nodeId;\n let methodPrefix = options.methodPrefix;\n let payloadBytes = options.payloadBytes;\n let format = options.format;\n\n if (options.resume !== undefined) {\n const resumed = await readResume(options.resume);\n search ??= resumed.search;\n nodeId ??= resumed.nodeId;\n methodPrefix ??= resumed.methodPrefix;\n payloadBytes ??= resumed.payloadBytes;\n format ??= resumed.format;\n }\n\n let selected = selectParticipant(filterParticipants(participants, search), nodeId);\n if (selected === undefined && options.nodeId === undefined && search !== undefined) {\n selected = selectParticipant(filterParticipants(participants, search), undefined);\n }\n if (selected === undefined && process.stdin.isTTY && process.stdout.isTTY) {\n const prompted = await promptForParticipant(participants, search);\n selected = prompted?.participant;\n search = prompted?.search ?? search;\n }\n if (selected === undefined) {\n throw new Error(\n 'No participant matched. Use --search <regexp> or --node <nodeId>; '\n + 'interactive selection requires a TTY.',\n );\n }\n\n const serviceId = serviceForParticipant(sources, selected.nodeId);\n if (serviceId === undefined) {\n throw new Error(`Participant ${selected.nodeId} has no addressable service route.`);\n }\n\n await writeResume(options.resume, {\n search,\n nodeId: selected.nodeId,\n methodPrefix,\n format,\n payloadBytes,\n });\n\n format ??= process.stdout.isTTY ? 'pretty' : 'plain';\n const session = {\n type: 'session',\n version: 1,\n nodeId: selected.nodeId,\n serviceId,\n search,\n format,\n methodPrefix,\n payloadBytes,\n };\n if (format === 'jsonl') emit(JSON.stringify(session));\n else emit(`Watching participant ${selected.nodeId} via ${serviceId}`);\n\n let aggregator: TrafficFlowAggregator | undefined;\n if (format === 'pretty') {\n aggregator = new TrafficFlowAggregator({\n onFlow: (flow) => emit(formatFlowSummary(flow)),\n });\n }\n\n const traffic = new TrafficClient(connection, serviceId);\n const callbacks = {\n onTransit: (event: TrafficTransitEvent) => {\n if (aggregator !== undefined) {\n aggregator.add(event);\n } else if (format === 'jsonl') {\n emit(JSON.stringify({ type: 'transit', event }));\n } else {\n emit(formatTransit(event));\n }\n },\n onOverflow: (event: Extract<TrafficEvent, { type: 'overflow' }>) => {\n emit(format === 'jsonl'\n ? JSON.stringify({ type: 'overflow', event })\n : `traffic overflow: dropped ${event.dropped} events`);\n },\n onError: (error: unknown) => {\n emit(`traffic watch failed: ${error instanceof Error ? error.message : String(error)}`);\n },\n };\n const watch = payloadBytes === undefined\n ? traffic.watch(\n { methodPrefix },\n callbacks,\n )\n : traffic.watchWithPayloads(\n { methodPrefix, maxPayloadBytes: payloadBytes },\n callbacks,\n );\n\n try {\n await Promise.race([watch.done, options.stop]);\n } finally {\n await watch.cancel('cli-watch-ended');\n aggregator?.flush();\n aggregator?.dispose();\n if (format === 'jsonl') {\n emit(JSON.stringify({ type: 'end', reason: 'stopped' }));\n }\n }\n}\n\nasync function discoverTopologySources(\n channel: CliChannel,\n connection: LinkRpcConnection,\n): Promise<readonly InspectionSource[]> {\n const explorer = new HubDirectoryExplorer(channel, { maxDepth: 5 });\n const result = await explorer.explore();\n const serviceIds = unique(\n result.listings\n .filter((listing) => listing.interfaceId === TOPOLOGY_INTERFACE)\n .map((listing) => listing.serviceId),\n );\n const sources: InspectionSource[] = [];\n for (const serviceId of serviceIds) {\n const graph = await new TopologyClient(connection, serviceId).getGraph();\n sources.push({ serviceId, graph });\n }\n explorer.dispose();\n return sources;\n}\n\nasync function discoverParticipants(channel: CliChannel): Promise<readonly ParticipantSummary[]> {\n return summarizeParticipants(await discoverTopologySources(channel, new LinkRpcConnection(channel)));\n}\n\nfunction summarizeParticipants(sources: readonly InspectionSource[]): ParticipantSummary[] {\n const byNode = new Map<string, {\n descriptors: unknown[];\n routeClaims: unknown[];\n serviceIds: Set<string>;\n sourceServices: Set<string>;\n }>();\n for (const source of sources) {\n for (const node of source.graph.nodes) {\n const current = byNode.get(node.nodeId) ?? {\n descriptors: [],\n routeClaims: [],\n serviceIds: new Set<string>(),\n sourceServices: new Set<string>(),\n };\n current.descriptors.push(...(node.descriptors ?? []));\n byNode.set(node.nodeId, current);\n current.sourceServices.add(source.serviceId);\n }\n for (const route of source.graph.routes) {\n const current = byNode.get(route.nodeId) ?? {\n descriptors: [],\n routeClaims: [],\n serviceIds: new Set<string>(),\n sourceServices: new Set<string>(),\n };\n current.routeClaims.push(route);\n current.serviceIds.add(route.serviceId);\n byNode.set(route.nodeId, current);\n }\n }\n return [...byNode].map(([nodeId, value]) => ({\n nodeId,\n descriptors: value.descriptors,\n routeClaims: value.routeClaims,\n serviceIds: [...value.serviceIds].sort(),\n sourceServices: [...value.sourceServices].sort(),\n }));\n}\n\nfunction filterParticipants(\n participants: readonly ParticipantSummary[],\n search: string | undefined,\n): ParticipantSummary[] {\n if (search === undefined || search.length === 0) return [...participants];\n let expression: RegExp;\n try {\n expression = new RegExp(search, 'i');\n } catch (error) {\n throw new Error(`Invalid participant search regexp: ${error instanceof Error ? error.message : String(error)}`);\n }\n return participants.filter((participant) => expression.test(JSON.stringify(participant)));\n}\n\nfunction selectParticipant(\n participants: readonly ParticipantSummary[],\n nodeId: string | undefined,\n): ParticipantSummary | undefined {\n if (nodeId !== undefined) {\n return participants.find((participant) => participant.nodeId === nodeId);\n }\n return participants.length === 1 ? participants[0] : undefined;\n}\n\nasync function promptForParticipant(\n participants: readonly ParticipantSummary[],\n search: string | undefined,\n): Promise<{ participant: ParticipantSummary; search: string } | undefined> {\n const readline = createInterface({ input, output });\n try {\n const query = search ?? await readline.question('Search participants (regexp): ');\n const matches = filterParticipants(participants, query);\n if (matches.length === 0) return undefined;\n for (let i = 0; i < matches.length; i++) {\n output.write(`${i + 1}. ${participantLabel(matches[i])}\\n`);\n }\n const answer = await readline.question('Select participant: ');\n const index = Number.parseInt(answer, 10) - 1;\n return Number.isInteger(index) && index >= 0 && matches[index] !== undefined\n ? { participant: matches[index], search: query }\n : undefined;\n } finally {\n readline.close();\n }\n}\n\nfunction participantLabel(participant: ParticipantSummary): string {\n const labels = participant.descriptors\n .flatMap((value) => {\n if (typeof value !== 'object' || value === null) return [];\n const descriptor = (value as { descriptor?: { label?: unknown } }).descriptor;\n return typeof descriptor?.label === 'string' ? [descriptor.label] : [];\n });\n return `${labels[0] ?? participant.nodeId} (${participant.serviceIds.join(', ') || 'no routes'})`;\n}\n\nfunction serviceForParticipant(\n sources: readonly InspectionSource[],\n nodeId: string,\n): string | undefined {\n for (const source of sources) {\n const route = source.graph.routes.find((candidate) => candidate.nodeId === nodeId);\n if (route !== undefined) return route.serviceId;\n if (source.graph.entryNodeId === nodeId) return source.serviceId;\n }\n return undefined;\n}\n\nfunction formatTransit(event: TrafficTransitEvent): string {\n const direction = event.in !== undefined && event.out !== undefined\n ? 'forward'\n : event.in !== undefined ? 'in' : 'out';\n return `${event.ts} ${direction} ${event.kind} ${event.method ?? '(unknown)'}`;\n}\n\ninterface ResumeState {\n readonly search?: string;\n readonly nodeId?: string;\n readonly methodPrefix?: string;\n readonly format?: 'pretty' | 'plain' | 'jsonl';\n readonly payloadBytes?: number;\n}\n\nasync function readResume(value: string | true): Promise<ResumeState> {\n const { readFile } = await import('node:fs/promises');\n const path = value === true ? '.linkrpc-watch.json' : value;\n try {\n return JSON.parse(await readFile(path, 'utf8')) as ResumeState;\n } catch (error) {\n throw new Error(`Cannot resume from ${path}: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n\nasync function writeResume(value: string | true | undefined, state: ResumeState): Promise<void> {\n if (value === undefined) return;\n const { writeFile } = await import('node:fs/promises');\n const path = value === true ? '.linkrpc-watch.json' : value;\n await writeFile(path, `${JSON.stringify(state, null, 2)}\\n`, 'utf8');\n}\n\nfunction unique(values: readonly string[]): string[] {\n return [...new Set(values)];\n}\n","import type { MethodSchema, LinkRpcInterfaceSchema as SvcInterfaceSchema } from \"@hediet/linkrpc\";\nimport { type CliChannel, fetchSchema, findMethodInSchema } from \"@hediet/linkrpc-client-internal\";\nimport { formatJson } from \"../output\";\n\nexport interface SchemaCommandOptions {\n readonly interfaceId: string;\n readonly hash?: string;\n readonly method?: string;\n readonly json?: boolean;\n /**\n * Route the schema request to a specific service (form-3). Needed when\n * the interface lives behind a hub participant — the CLI's default\n * (form-2) target is the hub itself.\n */\n readonly serviceId?: string;\n}\n\nexport async function schemaCommand(channel: CliChannel, opts: SchemaCommandOptions): Promise<string> {\n const schema = await fetchSchema(channel, opts.interfaceId, opts.hash, opts.serviceId);\n if (opts.method !== undefined) {\n const m = findMethodInSchema(schema, opts.method);\n if (!m) throw new Error(`Method \"${opts.method}\" not found in ${schema.id}@${schema.hash}`);\n if (opts.json) return formatJson(m);\n return renderMethod(m);\n }\n if (opts.json) return formatJson(schema);\n return renderSchema(schema);\n}\n\nfunction renderSchema(schema: SvcInterfaceSchema): string {\n const lines: string[] = [];\n lines.push(`${schema.id}@${schema.hash}`);\n if (schema.description) lines.push(` ${schema.description}`);\n lines.push(\"\");\n for (const [name, method] of Object.entries(schema.methods)) {\n lines.push(renderMethod(name, method));\n lines.push(\"\");\n }\n return lines.join(\"\\n\").trimEnd();\n}\n\nfunction renderMethod(name: string, m: MethodSchema): string {\n const kind = m.result === undefined ? \"notify\" : \"request\";\n const lines: string[] = [];\n lines.push(` ${kind} ${name}`);\n if (m.summary) lines.push(` ${m.summary}`);\n if (m.description) lines.push(` ${m.description}`);\n lines.push(` params: ${shortSchema(m.params)}`);\n if (m.result) {\n lines.push(` result: ${shortSchema(m.result)}`);\n }\n return lines.join(\"\\n\");\n}\n\nfunction shortSchema(s: unknown): string {\n const str = JSON.stringify(s);\n if (str.length <= 120) return str;\n return str.slice(0, 117) + \"...\";\n}\n","/**\n * `linkrpc serve <config>` — run a hub from a declarative `HubConfig` file and\n * block until interrupted. Thin CLI face over the shared `@hediet/linkrpc-hub`\n * engine, so one config format drives the CLI hub, the server hub, and the\n * VS Code extension.\n */\nimport { loadHubConfig, printHubConfigSchema } from '@hediet/linkrpc-hub/config-file';\n\nexport { loadHubConfig, printHubConfigSchema };\n\nexport interface ServeOptions {\n /** Path to the JSON config file. */\n readonly configPath: string;\n /** Forward this process's stdin to the single cmd endpoint, if any. */\n readonly cmdInteractive?: boolean;\n /** Log every JSON-RPC message routed through the hub to stderr. */\n readonly logMessages?: boolean;\n}\n\n/** Run a hub from `configPath` and resolve only when interrupted (SIGINT/SIGTERM). */\nexport async function serveCommand(opts: ServeOptions): Promise<void> {\n const { serveHub } = await import('@hediet/linkrpc-hub/serve');\n await serveHub({\n configPath: opts.configPath,\n cmdInteractive: opts.cmdInteractive,\n logMessages: opts.logMessages,\n log: (line) => process.stderr.write(`linkrpc: ${line}\\n`),\n });\n}\n","import { connectTransports, type IMessageTransport } from '@hediet/linkrpc';\n\n/**\n * A live transport plus the seams to observe and tear down its underlying\n * resource. `IMessageTransport` itself exposes no close event, so `onClose`\n * bridges the raw socket / child-process lifecycle (mirrors how the docker\n * provenance proxy drives its splice teardown).\n */\nexport interface TransportHandle {\n readonly transport: IMessageTransport;\n /** Register a callback fired when the underlying resource closes. */\n onClose(cb: () => void): void;\n /** Tear down the transport and its underlying resource. */\n dispose(): void;\n}\n\nexport interface ConnectAsDeps {\n /**\n * Mint a single-use `hubrpc::initialize` token bound to the target's slot\n * (identity + granted namespace), via a `connectionTokenBinder` service.\n */\n mintToken(): Promise<string>;\n /**\n * Open the **hub-facing** transport, presenting `token` in its initialize\n * handshake so the hub's `{ token: \"bound\" }` handler redeems it — binding\n * this connection to the slot's identity + granted namespace.\n */\n openHubTransport(token: string): Promise<TransportHandle>;\n /**\n * Open the **target-facing** transport. Either a dial (ws / socket / uri /\n * cmd-stdio) or an accept-one (cmd-env: spawn the child and take the\n * connection it dials back).\n */\n openTargetTransport(): Promise<TransportHandle>;\n /**\n * Optional tap wrapping the target-facing transport so every spliced\n * message is logged. Tapping one edge captures the full bidirectional flow\n * (each message crosses it exactly once), so this is applied to a single\n * side to avoid double-logging.\n */\n tapTarget?(transport: IMessageTransport): IMessageTransport;\n /** Human-readable status sink. */\n log?(line: string): void;\n /** Resolves to stop the proxy (e.g. on SIGINT). */\n stop?: Promise<void>;\n}\n\n/**\n * Run a **connect-as** proxy until either side closes (or {@link\n * ConnectAsDeps.stop} resolves).\n *\n * Mints a bound token for a slot, opens the target-facing transport and the\n * hub-facing transport (which redeems the token → this connection *is* the slot\n * on the hub), and splices them message-for-message. The target thereby joins\n * the hub as a first-class participant with the slot's managed identity +\n * granted namespace, without running a local hub and without the target needing\n * to perform the hub handshake itself.\n *\n * Because all traffic crosses the CLI's splice point, {@link\n * ConnectAsDeps.tapTarget} yields complete `--log-messages` observability.\n */\nexport async function connectAs(deps: ConnectAsDeps): Promise<void> {\n const token = await deps.mintToken();\n\n const target = await deps.openTargetTransport();\n let hub: TransportHandle;\n try {\n hub = await deps.openHubTransport(token);\n } catch (e) {\n target.dispose();\n throw e;\n }\n\n const targetTransport = deps.tapTarget\n ? deps.tapTarget(target.transport)\n : target.transport;\n const pipe = connectTransports(targetTransport, hub.transport);\n\n deps.log?.('connect-as: bridged target ⟷ hub');\n\n await new Promise<void>((resolve) => {\n let done = false;\n const teardown = (): void => {\n if (done) return;\n done = true;\n pipe.dispose();\n try { target.dispose(); } catch { /* best effort */ }\n try { hub.dispose(); } catch { /* best effort */ }\n resolve();\n };\n target.onClose(teardown);\n hub.onClose(teardown);\n void deps.stop?.then(teardown);\n });\n\n deps.log?.('connect-as: closed');\n}\n","import {\n connectNdjson,\n type EndpointCommand,\n openWebSocket,\n runInitializeHandshake,\n WebSocketTransport,\n} from '@hediet/linkrpc/node';\nimport { SocketServer, type NodeSocketTransport } from '@hediet/linkrpc-hub/hub/server/node';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as net from 'node:net';\nimport type { ResolvedEndpoint } from '@hediet/linkrpc-client-internal';\nimport type { TransportHandle } from './connectAs';\n\n/** A ws / socket endpoint the CLI can dial (the only dial-able hub-facing kinds). */\nexport type DialEndpoint = Extract<ResolvedEndpoint, { kind: 'ws' | 'socket'; }>;\n\n/**\n * Dial a ws / socket endpoint as a client, presenting `token` in the\n * `hubrpc::initialize` handshake. Used for the hub-facing side (with the minted\n * bound token) and for ws / socket / uri targets (with the target's own token).\n */\nexport async function openDialTransport(spec: DialEndpoint, token: string): Promise<TransportHandle> {\n if (spec.kind === 'ws') {\n const ws = await openWebSocket(spec.url);\n const closeWs = (): void => { try { ws.close(); } catch { /* ignore */ } };\n const transport = new WebSocketTransport(ws, closeWs);\n try {\n await runInitializeHandshake(transport, { kind: 'client', token });\n } catch (err) {\n transport.dispose();\n closeWs();\n throw err;\n }\n return {\n transport,\n onClose: (cb) => ws.addEventListener('close', () => cb()),\n dispose: () => { transport.dispose(); closeWs(); },\n };\n }\n const socket = net.createConnection(spec.path);\n const { transport } = await connectNdjson({\n input: socket,\n output: socket,\n onClose: () => socket.destroy(),\n initialize: { kind: 'client', token },\n });\n return {\n transport,\n onClose: (cb) => socket.on('close', cb),\n dispose: () => socket.destroy(),\n };\n}\n\n/** Forward a child stream's lines to `log`, prefixed with `label`. */\nfunction _pipeLines(\n stream: NodeJS.ReadableStream | null,\n label: string,\n log: (line: string) => void,\n): void {\n if (!stream) return;\n stream.setEncoding('utf8');\n stream.on('data', (chunk: string) => {\n for (const line of chunk.split(/\\r?\\n/)) {\n if (line.length > 0) log(`[${label}] ${line}`);\n }\n });\n}\n\n/** Spawn a `cmd-stdio` target and talk linkrpc over its stdin/stdout. */\nexport async function openStdioTransport(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n cwd: string | undefined,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n const child = spawnCommand(command, {\n stdio: ['pipe', 'pipe', 'pipe'],\n ...(env !== undefined ? { env: { ...process.env, ...env } } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n });\n if (!child.stdin || !child.stdout) {\n throw new Error('connect-as: cmd-stdio child exposes no stdio');\n }\n // stdout carries the linkrpc protocol; only stderr can be logged.\n if (log) _pipeLines(child.stderr, 'target', log);\n const { transport } = await connectNdjson({\n input: child.stdout,\n output: child.stdin,\n onClose: () => { if (!child.killed) child.kill(); },\n });\n return {\n transport,\n onClose: (cb) => child.once('exit', cb),\n dispose: () => { transport.dispose(); if (!child.killed) child.kill(); },\n };\n}\n\n/**\n * Spawn a `cmd-env` target against a private socket the CLI listens on, and\n * take the single connection it dials back. This is the sole role-inverted\n * case: the target dials the CLI, so we accept rather than dial. No hub /\n * acceptor is needed — just the raw post-handshake transport to splice.\n */\nexport async function openAcceptOneTransport(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n cwd: string | undefined,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n const socketPath = SocketServer.allocSocketPath();\n const token = randomBytes(16).toString('hex');\n const server = await SocketServer.start({ endpoint: socketPath });\n\n const accepted = new Promise<NodeSocketTransport>((resolve) => {\n server.setConnectionHandler((t) => resolve(t));\n });\n const child = spawnCommand(command, {\n stdio: ['ignore', 'pipe', 'pipe'],\n env: { ...process.env, ...env, LINKRPC_ENDPOINT: socketPath, LINKRPC_TOKEN: token },\n ...(cwd !== undefined ? { cwd } : {}),\n });\n // The child talks to the CLI over the socket, so both its stdout and stderr\n // are free to surface (crucial for diagnosing a child that exits before\n // dialing back).\n if (log) {\n _pipeLines(child.stdout, 'target', log);\n _pipeLines(child.stderr, 'target', log);\n }\n\n let exited = false;\n child.once('exit', () => { exited = true; });\n\n const transport = await Promise.race([\n accepted,\n new Promise<never>((_resolve, reject) => {\n child.once('exit', (code) =>\n reject(new Error(`connect-as: cmd-env child exited (code ${code ?? '?'}) before connecting`)),\n );\n }),\n ]).catch((err: unknown) => {\n server.dispose();\n _unlink(socketPath);\n if (!child.killed) child.kill();\n throw err;\n });\n\n const dispose = (): void => {\n transport.dispose();\n server.dispose();\n _unlink(socketPath);\n if (!exited && !child.killed) child.kill();\n };\n return {\n transport,\n onClose: (cb) => { transport.onDidClose(cb); child.once('exit', cb); },\n dispose,\n };\n}\n\n/** Open the target-facing transport for any resolved endpoint kind. */\nexport function openTargetTransport(\n endpoint: ResolvedEndpoint,\n log?: (line: string) => void,\n): Promise<TransportHandle> {\n switch (endpoint.kind) {\n case 'cmd-env':\n return openAcceptOneTransport(endpoint.command, endpoint.env, endpoint.cwd, log);\n case 'cmd-stdio':\n return openStdioTransport(endpoint.command, endpoint.env, endpoint.cwd, log);\n case 'ws':\n case 'socket':\n return openDialTransport(endpoint, endpoint.token ?? '');\n }\n}\n\nfunction _unlink(socketPath: string): void {\n if (process.platform === 'win32') return;\n try { fs.unlinkSync(socketPath); } catch { /* ignore */ }\n}\n","import { LinkRpcConnection } from '@hediet/linkrpc';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { type EndpointCommand } from '@hediet/linkrpc/node';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport * as readline from 'node:readline';\nimport type { CliConnection } from '@hediet/linkrpc-client-internal';\nimport { mcpForwardInterface } from '../mcpForward.interface';\n\n/**\n * Front door for claiming a serviceId within the connection's granted\n * namespace — interface-form `hubGrantedServiceId::register`. Same claim the\n * `tunnel` command uses.\n */\nconst CLAIM_METHOD = `${hubGrantedServiceIdInterface.info.id}::register`;\n\n/** Read-only connection facts — `hubGrantedServiceId::get`. */\nconst INFO_METHOD = `${hubGrantedServiceIdInterface.info.id}::get`;\n\nexport interface McpForwardOptions {\n /**\n * Prefix to claim on the hub; the MCP server is reached as\n * `<serviceId>::vscode.mcp-forward::connect`. When omitted, the connection's\n * granted serviceId namespace (`hubGrantedServiceId::get`) is claimed as-is.\n */\n readonly serviceId?: string;\n /** Live, signed connection to the hub we claim `serviceId` on and serve from. */\n readonly local: CliConnection;\n /** The MCP server child to spawn (one fresh child per `connect` leg). */\n readonly command: EndpointCommand;\n /** Extra env merged on top of `process.env` for the spawned child. */\n readonly env?: Readonly<Record<string, string>>;\n /** Resolves to stop the forwarder (e.g. on SIGINT). Defaults to first SIGINT/SIGTERM. */\n readonly stop?: Promise<void>;\n /** Sink for human-readable status lines (defaults to stderr). */\n readonly log?: (line: string) => void;\n}\n\n/**\n * Run a transparent MCP forwarder until stopped.\n *\n * Serves {@link mcpForwardInterface} under `serviceId` on the hub: each inbound\n * `connect` request spawns a fresh MCP server child and shuttles raw JSON-RPC\n * frames between the child's stdio (newline-delimited JSON, the MCP stdio\n * transport framing) and the request's duplex stream. The forwarder never\n * parses MCP semantics — it only splits/joins NDJSON lines so each line becomes\n * one opaque `frame`. {@link LinkRpcConnection.enableReflection} is enabled so\n * the hub's directory can discover the service.\n *\n * Resolves when {@link McpForwardOptions.stop} resolves (or on SIGINT/SIGTERM).\n */\nexport async function mcpForwardCommand(opts: McpForwardOptions): Promise<void> {\n const log = opts.log ?? ((line) => process.stderr.write(line + '\\n'));\n\n // Default the prefix to the connection's granted serviceId namespace, so a\n // forwarder run without an explicit `--serviceId` claims exactly what it is\n // already entitled to.\n const serviceId = opts.serviceId ?? await _resolveGrantedServiceId(opts.local);\n\n // A typed connection that SERVES the forward interface over the hub link.\n // Constructing it binds the inbound handler, so do this BEFORE claiming so\n // no `connect` can race in between the claim landing and the handler being\n // installed.\n const conn = new LinkRpcConnection(opts.local.rpcChannel);\n conn.register(\n mcpForwardInterface,\n {\n connect: (_params, _ctx, stream) => _runLeg(opts.command, opts.env, stream, log),\n },\n { serviceId },\n );\n // Advertise reflection (directory + schemas) under the same serviceId so the\n // hub's referral-only directory fan-out can discover and surface this leg.\n conn.enableReflection({ serviceId });\n\n // Claim the prefix via the granted-namespace front door. The local\n // connection's signing layer signs this where the hub requires it.\n await opts.local.channel.sendRequest(CLAIM_METHOD, { serviceId });\n log(`mcp-forward: claimed '${serviceId}' — forwarding MCP stdio to ${_describe(opts.command)}`);\n\n await (opts.stop ?? _untilSignalled());\n log('mcp-forward: stopping');\n}\n\n/**\n * Resolve the connection's granted serviceId namespace\n * (`hubGrantedServiceId::get`) to use as the default forward prefix. Throws if\n * the namespace is empty (\"claim nothing freely\") — the caller must then pass an\n * explicit `--serviceId`.\n */\nasync function _resolveGrantedServiceId(local: CliConnection): Promise<string> {\n const info = await local.channel.sendRequest(INFO_METHOD, {}) as {\n grantedServiceIdNamespace?: string;\n } | null | undefined;\n const granted = info?.grantedServiceIdNamespace ?? '';\n if (granted.length === 0) {\n throw new Error(\n 'mcp-forward: this connection has no granted serviceId namespace to claim; '\n + 'pass an explicit --serviceId.',\n );\n }\n return granted;\n}\n\n/**\n * One MCP session leg: spawn the child, bridge stdio<->stream, and resolve when\n * the child exits or the caller cancels (killing the child).\n */\nfunction _runLeg(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n stream: { send(p: { frame: unknown; }): void; onMessage(l: (p: { frame: unknown; }) => void): void; readonly signal: AbortSignal; },\n log: (line: string) => void,\n): Promise<{ serverInfo?: { name: string; version: string; }; }> {\n return new Promise((resolve) => {\n const child = spawnCommand(command, {\n stdio: ['pipe', 'pipe', 'inherit'],\n ...(env !== undefined ? { env: { ...process.env, ...env } } : {}),\n });\n if (!child.stdin || !child.stdout) {\n log('mcp-forward: child exposes no stdio');\n if (!child.killed) child.kill();\n resolve({});\n return;\n }\n\n let settled = false;\n const rl = readline.createInterface({ input: child.stdout });\n const finish = (): void => {\n if (settled) return;\n settled = true;\n rl.close();\n if (!child.killed) child.kill();\n resolve({});\n };\n\n // child stdout (NDJSON) → stream: each line becomes one opaque frame.\n rl.on('line', (line) => {\n const trimmed = line.trim();\n if (trimmed.length === 0) return;\n let frame: unknown;\n try {\n frame = JSON.parse(trimmed);\n } catch {\n // MCP stdio servers must emit JSON-only on stdout; skip stray\n // non-JSON lines defensively instead of corrupting the stream.\n return;\n }\n if (stream.signal.aborted) return;\n stream.send({ frame });\n });\n\n // stream → child stdin: re-serialize each frame as one NDJSON line.\n stream.onMessage(({ frame }) => {\n if (!child.stdin || child.stdin.destroyed) return;\n child.stdin.write(JSON.stringify(frame) + '\\n');\n });\n\n // Caller cancelled / disconnected → kill the child and settle.\n if (stream.signal.aborted) {\n finish();\n return;\n }\n stream.signal.addEventListener('abort', finish, { once: true });\n\n // Child exited → settle so the consumer drops its client.\n child.on('exit', finish);\n child.on('error', (err) => {\n log(`mcp-forward: child error: ${String(err)}`);\n finish();\n });\n });\n}\n\n/** Resolve on the next `SIGINT` / `SIGTERM`. */\nfunction _untilSignalled(): Promise<void> {\n return new Promise<void>((resolve) => {\n const done = (): void => {\n process.removeListener('SIGINT', done);\n process.removeListener('SIGTERM', done);\n resolve();\n };\n process.once('SIGINT', done);\n process.once('SIGTERM', done);\n });\n}\n\n/** One-line description of the spawned command for logs. */\nfunction _describe(command: EndpointCommand): string {\n return 'argv' in command ? command.argv.join(' ') : command.command;\n}\n","import { LinkRpcConnection, type JsonValue } from '@hediet/linkrpc';\nimport {\n connectJsonRpcTransports,\n connectRawJsonRpcTransport,\n createNdjsonJsonRpcTransport,\n jsonRpcConnectionInterface,\n} from '@hediet/linkrpc-infra/json-rpc';\nimport type { CliConnection } from '@hediet/linkrpc-client-internal';\n\nexport interface JsonRpcStdioOptions {\n readonly local: CliConnection;\n readonly serviceId: string;\n readonly params?: JsonValue;\n readonly input?: NodeJS.ReadableStream;\n readonly output?: NodeJS.WritableStream;\n}\n\n/** Expose a remote `jsonRpcConnection` service as an NDJSON stdio endpoint. */\nexport async function jsonRpcStdioCommand(options: JsonRpcStdioOptions): Promise<void> {\n const connection = new LinkRpcConnection(options.local.rpcChannel);\n const client = connection.service(options.serviceId).get(jsonRpcConnectionInterface);\n const remote = await connectRawJsonRpcTransport(client, options.params);\n const stdio = createNdjsonJsonRpcTransport({\n input: options.input ?? process.stdin,\n output: options.output ?? process.stdout,\n });\n const bridge = connectJsonRpcTransports(remote, stdio);\n\n await new Promise<void>((resolve) => {\n let settled = false;\n const finish = (): void => {\n if (settled) return;\n settled = true;\n resolve();\n };\n remote.onClose(finish);\n stdio.onClose(finish);\n });\n bridge.dispose();\n remote.close('closed');\n stdio.close('closed');\n}\n","import { LinkRpcConnection } from '@hediet/linkrpc';\nimport { connectRawJsonRpcTransport, jsonRpcConnectionInterface } from '@hediet/linkrpc-infra/json-rpc';\nimport {\n startJsonRpcWebSocketExport,\n type JsonRpcExportRoute,\n type JsonRpcWebSocketExport,\n} from '@hediet/linkrpc-infra/json-rpc/node';\nimport type { CliConnection } from '@hediet/linkrpc-client-internal';\n\n/** Preserve option order so a missing path cannot shift subsequent service mappings. */\nexport class JsonRpcExportRoutes {\n private readonly _routes: JsonRpcExportRoute[] = [];\n private _pendingService: string | undefined;\n\n public serviceId(value: string): void {\n if (this._pendingService !== undefined) throw new Error('Each --serviceId must be followed by --path.');\n this._pendingService = value;\n }\n\n public path(value: string): void {\n if (this._pendingService === undefined) throw new Error('--path must follow --serviceId.');\n this._routes.push({ serviceId: this._pendingService, path: value.startsWith('/') ? value : `/${value}` });\n this._pendingService = undefined;\n }\n\n public getRoutes(): readonly JsonRpcExportRoute[] {\n if (this._pendingService !== undefined) throw new Error('Each --serviceId must be followed by --path.');\n return this._routes;\n }\n}\n\nexport async function jsonRpcExportCommand(options: {\n readonly local: Pick<CliConnection, 'rpcChannel'>;\n readonly targetEndpoint: string;\n readonly token?: string;\n readonly tokenQueryParameters?: readonly string[];\n readonly routes: readonly JsonRpcExportRoute[];\n readonly onError: (error: Error) => void;\n}): Promise<JsonRpcWebSocketExport> {\n const connection = new LinkRpcConnection(options.local.rpcChannel);\n return startJsonRpcWebSocketExport({\n ...options,\n openTransport: (serviceId, signal) => connectRawJsonRpcTransport(\n connection.service(serviceId).get(jsonRpcConnectionInterface),\n undefined,\n signal,\n ),\n });\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet globalObservableLogger;\nfunction addLogger(logger) {\n if (!globalObservableLogger) {\n globalObservableLogger = logger;\n }\n else if (globalObservableLogger instanceof ComposedLogger) {\n globalObservableLogger.loggers.push(logger);\n }\n else {\n globalObservableLogger = new ComposedLogger([globalObservableLogger, logger]);\n }\n}\nfunction getLogger() {\n return globalObservableLogger;\n}\nlet globalObservableLoggerFn = undefined;\nfunction setLogObservableFn(fn) {\n globalObservableLoggerFn = fn;\n}\nfunction logObservable(obs) {\n if (globalObservableLoggerFn) {\n globalObservableLoggerFn(obs);\n }\n}\nclass ComposedLogger {\n constructor(loggers) {\n this.loggers = loggers;\n }\n handleObservableCreated(observable, location) {\n for (const logger of this.loggers) {\n logger.handleObservableCreated(observable, location);\n }\n }\n handleOnListenerCountChanged(observable, newCount) {\n for (const logger of this.loggers) {\n logger.handleOnListenerCountChanged(observable, newCount);\n }\n }\n handleObservableUpdated(observable, info) {\n for (const logger of this.loggers) {\n logger.handleObservableUpdated(observable, info);\n }\n }\n handleAutorunCreated(autorun, location) {\n for (const logger of this.loggers) {\n logger.handleAutorunCreated(autorun, location);\n }\n }\n handleAutorunDisposed(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunDisposed(autorun);\n }\n }\n handleAutorunDependencyChanged(autorun, observable, change) {\n for (const logger of this.loggers) {\n logger.handleAutorunDependencyChanged(autorun, observable, change);\n }\n }\n handleAutorunStarted(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunStarted(autorun);\n }\n }\n handleAutorunFinished(autorun) {\n for (const logger of this.loggers) {\n logger.handleAutorunFinished(autorun);\n }\n }\n handleDerivedDependencyChanged(derived, observable, change) {\n for (const logger of this.loggers) {\n logger.handleDerivedDependencyChanged(derived, observable, change);\n }\n }\n handleDerivedCleared(observable) {\n for (const logger of this.loggers) {\n logger.handleDerivedCleared(observable);\n }\n }\n handleBeginTransaction(transaction) {\n for (const logger of this.loggers) {\n logger.handleBeginTransaction(transaction);\n }\n }\n handleEndTransaction(transaction) {\n for (const logger of this.loggers) {\n logger.handleEndTransaction(transaction);\n }\n }\n}\n\nexport { addLogger, getLogger, logObservable, setLogObservableFn };\n//# sourceMappingURL=logging.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nvar DebugLocation;\n(function (DebugLocation) {\n let enabled = false;\n function enable() {\n enabled = true;\n }\n DebugLocation.enable = enable;\n function ofCaller() {\n return ofNthCaller(1);\n }\n DebugLocation.ofCaller = ofCaller;\n function ofNthCaller(n) {\n if (!enabled) {\n return undefined;\n }\n const Err = Error; // For the monaco editor checks, which don't have the nodejs types.\n const l = Err.stackTraceLimit;\n Err.stackTraceLimit = 3;\n const stack = new Error().stack;\n Err.stackTraceLimit = l;\n return DebugLocationImpl.fromStack(stack, n + 1);\n }\n DebugLocation.ofNthCaller = ofNthCaller;\n})(DebugLocation || (DebugLocation = {}));\nclass DebugLocationImpl {\n static fromStack(stack, parentIdx) {\n const lines = stack.split('\\n');\n const location = parseLine(lines[parentIdx + 1]);\n if (location) {\n return new DebugLocationImpl(location.fileName, location.line, location.column, location.id);\n }\n else {\n return undefined;\n }\n }\n constructor(fileName, line, column, id) {\n this.fileName = fileName;\n this.line = line;\n this.column = column;\n this.id = id;\n }\n}\nfunction parseLine(stackLine) {\n if (!stackLine) {\n return undefined;\n }\n const match = stackLine.match(/\\((.*):(\\d+):(\\d+)\\)/);\n if (match) {\n return {\n fileName: match[1],\n line: parseInt(match[2]),\n column: parseInt(match[3]),\n id: stackLine,\n };\n }\n const match2 = stackLine.match(/at ([^\\(\\)]*):(\\d+):(\\d+)/);\n if (match2) {\n return {\n fileName: match2[1],\n line: parseInt(match2[2]),\n column: parseInt(match2[3]),\n id: stackLine,\n };\n }\n return undefined;\n}\n\nexport { DebugLocation };\n//# sourceMappingURL=debugLocation.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nclass DebugNameData {\n constructor(owner, debugNameSource, referenceFn) {\n this.owner = owner;\n this.debugNameSource = debugNameSource;\n this.referenceFn = referenceFn;\n }\n getDebugName(target) {\n return getDebugName(target, this);\n }\n}\nconst countPerName = new Map();\nconst cachedDebugName = new WeakMap();\nfunction getDebugName(target, data) {\n const cached = cachedDebugName.get(target);\n if (cached) {\n return cached;\n }\n const dbgName = computeDebugName(target, data);\n if (dbgName) {\n let count = countPerName.get(dbgName) ?? 0;\n count++;\n countPerName.set(dbgName, count);\n const result = count === 1 ? dbgName : `${dbgName}#${count}`;\n cachedDebugName.set(target, result);\n return result;\n }\n return undefined;\n}\nfunction computeDebugName(self, data) {\n const cached = cachedDebugName.get(self);\n if (cached) {\n return cached;\n }\n const ownerStr = data.owner ? formatOwner(data.owner) + `.` : '';\n let result;\n const debugNameSource = data.debugNameSource;\n if (debugNameSource !== undefined) {\n if (typeof debugNameSource === 'function') {\n result = debugNameSource();\n if (result !== undefined) {\n return ownerStr + result;\n }\n }\n else {\n return ownerStr + debugNameSource;\n }\n }\n const referenceFn = data.referenceFn;\n if (referenceFn !== undefined) {\n result = getFunctionName(referenceFn);\n if (result !== undefined) {\n return ownerStr + result;\n }\n }\n if (data.owner !== undefined) {\n const key = findKey(data.owner, self);\n if (key !== undefined) {\n return ownerStr + key;\n }\n }\n return undefined;\n}\nfunction findKey(obj, value) {\n for (const key in obj) {\n if (obj[key] === value) {\n return key;\n }\n }\n return undefined;\n}\nconst countPerClassName = new Map();\nconst ownerId = new WeakMap();\nfunction formatOwner(owner) {\n const id = ownerId.get(owner);\n if (id) {\n return id;\n }\n const className = getClassName(owner) ?? 'Object';\n let count = countPerClassName.get(className) ?? 0;\n count++;\n countPerClassName.set(className, count);\n const result = count === 1 ? className : `${className}#${count}`;\n ownerId.set(owner, result);\n return result;\n}\nfunction getClassName(obj) {\n const ctor = obj.constructor;\n if (ctor) {\n if (ctor.name === 'Object') {\n return undefined;\n }\n return ctor.name;\n }\n return undefined;\n}\nfunction getFunctionName(fn) {\n const fnSrc = fn.toString();\n // Pattern: /** @description ... */\n const regexp = /\\/\\*\\*\\s*@description\\s*([^*]*)\\*\\//;\n const match = regexp.exec(fnSrc);\n const result = match ? match[1] : undefined;\n return result?.trim();\n}\n\nexport { DebugNameData, getClassName, getDebugName, getFunctionName };\n//# sourceMappingURL=debugName.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { DebugLocation } from '../debugLocation.js';\nimport { getFunctionName } from '../debugName.js';\nimport { logObservable, getLogger } from '../logging/logging.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet _derived;\n/**\n * @internal\n * This is to allow splitting files.\n*/\nfunction _setDerivedOpts(derived) {\n _derived = derived;\n}\nlet _recomputeInitiallyAndOnChange;\nfunction _setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange) {\n _recomputeInitiallyAndOnChange = recomputeInitiallyAndOnChange;\n}\nlet _keepObserved;\nfunction _setKeepObserved(keepObserved) {\n _keepObserved = keepObserved;\n}\nlet _debugGetDependencyGraph;\nfunction _setDebugGetDependencyGraph(debugGetDependencyGraph) {\n _debugGetDependencyGraph = debugGetDependencyGraph;\n}\nclass ConvenientObservable {\n get TChange() { return null; }\n reportChanges() {\n this.get();\n }\n /** @sealed */\n read(reader) {\n if (reader) {\n return reader.readObservable(this);\n }\n else {\n return this.get();\n }\n }\n map(fnOrOwner, fnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n const owner = fnOrUndefined === undefined ? undefined : fnOrOwner;\n const fn = fnOrUndefined === undefined ? fnOrOwner : fnOrUndefined;\n return _derived({\n owner,\n debugName: () => {\n const name = getFunctionName(fn);\n if (name !== undefined) {\n return name;\n }\n // regexp to match `x => x.y` or `x => x?.y` where x and y can be arbitrary identifiers (uses backref):\n const regexp = /^\\s*\\(?\\s*([a-zA-Z_$][a-zA-Z_$0-9]*)\\s*\\)?\\s*=>\\s*\\1(?:\\??)\\.([a-zA-Z_$][a-zA-Z_$0-9]*)\\s*$/;\n const match = regexp.exec(fn.toString());\n if (match) {\n return `${this.debugName}.${match[2]}`;\n }\n if (!owner) {\n return `${this.debugName} (mapped)`;\n }\n return undefined;\n },\n debugReferenceFn: fn,\n }, (reader) => fn(this.read(reader), reader), debugLocation);\n }\n /**\n * @sealed\n * Converts an observable of an observable value into a direct observable of the value.\n */\n flatten() {\n return _derived({\n owner: undefined,\n debugName: () => `${this.debugName} (flattened)`,\n }, (reader) => this.read(reader).read(reader));\n }\n recomputeInitiallyAndOnChange(store, handleValue) {\n store.add(_recomputeInitiallyAndOnChange(this, handleValue));\n return this;\n }\n /**\n * Ensures that this observable is observed. This keeps the cache alive.\n * However, in case of deriveds, it does not force eager evaluation (only when the value is read/get).\n * Use `recomputeInitiallyAndOnChange` for eager evaluation.\n */\n keepObserved(store) {\n store.add(_keepObserved(this));\n return this;\n }\n get debugValue() {\n return this.get();\n }\n debugGetDependencyGraph() {\n return _debugGetDependencyGraph(this);\n }\n}\nclass BaseObservable extends ConvenientObservable {\n constructor(debugLocation) {\n super();\n this._observers = new Set();\n getLogger()?.handleObservableCreated(this, debugLocation);\n }\n addObserver(observer) {\n const len = this._observers.size;\n this._observers.add(observer);\n if (len === 0) {\n this.onFirstObserverAdded();\n }\n if (len !== this._observers.size) {\n getLogger()?.handleOnListenerCountChanged(this, this._observers.size);\n }\n }\n removeObserver(observer) {\n const deleted = this._observers.delete(observer);\n if (deleted && this._observers.size === 0) {\n this.onLastObserverRemoved();\n }\n if (deleted) {\n getLogger()?.handleOnListenerCountChanged(this, this._observers.size);\n }\n }\n onFirstObserverAdded() { }\n onLastObserverRemoved() { }\n log() {\n const hadLogger = !!getLogger();\n logObservable(this);\n if (!hadLogger) {\n getLogger()?.handleObservableCreated(this, DebugLocation.ofCaller());\n }\n return this;\n }\n debugGetObservers() {\n return this._observers;\n }\n}\n\nexport { BaseObservable, ConvenientObservable, _setDebugGetDependencyGraph, _setDerivedOpts, _setKeepObserved, _setRecomputeInitiallyAndOnChange };\n//# sourceMappingURL=baseObservable.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction toDisposable(fn) {\n return {\n dispose: fn\n };\n}\nclass BugIndicatingError extends Error {\n constructor(message) {\n super(message || 'An unexpected bug occurred.');\n Object.setPrototypeOf(this, BugIndicatingError.prototype);\n // Because we know for sure only buggy code throws this,\n // we definitely want to break here and fix the bug.\n // eslint-disable-next-line no-debugger\n // debugger;\n }\n}\nfunction onBugIndicatingError(error) {\n // debugger;\n throw error;\n}\nfunction onUnexpectedError(error) {\n console.error('Unexpected error:', error);\n}\n/**\n * Compares two items for equality using strict equality.\n*/\nconst strictEquals = (a, b) => a === b;\n\nexport { BugIndicatingError, onBugIndicatingError, onUnexpectedError, strictEquals, toDisposable };\n//# sourceMappingURL=deps.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nclass DisposableStore {\n constructor() {\n this.disposables = [];\n this._isDisposed = false;\n }\n get isDisposed() { return this._isDisposed; }\n dispose() {\n this.clear();\n this._isDisposed = true;\n }\n add(disposable) {\n if (disposable) {\n this.disposables.push(disposable);\n }\n return disposable;\n }\n remove(disposable) {\n if (!disposable) {\n return disposable;\n }\n const index = this.disposables.indexOf(disposable);\n if (index !== -1) {\n this.disposables.splice(index, 1);\n }\n return disposable;\n }\n clear() {\n for (const disposable of this.disposables) {\n disposable.dispose();\n }\n this.disposables = [];\n }\n leakItems() {\n this.disposables = [];\n }\n}\nclass Disposable {\n constructor() {\n this._store = new DisposableStore();\n }\n dispose() {\n this._store.dispose();\n }\n _register(t) {\n this._store.add(t);\n return t;\n }\n _registerOrDispose(t) {\n if (t) {\n if (this._store.isDisposed) {\n t.dispose();\n }\n else {\n this._store.add(t);\n }\n }\n return t;\n }\n}\n\nexport { Disposable, DisposableStore };\n//# sourceMappingURL=disposables.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { BaseObservable } from './baseObservable.js';\nimport { BugIndicatingError, onBugIndicatingError } from '../commonFacade/deps.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction derivedStateToString(state) {\n switch (state) {\n case 0 /* DerivedState.initial */: return 'initial';\n case 1 /* DerivedState.dependenciesMightHaveChanged */: return 'dependenciesMightHaveChanged';\n case 2 /* DerivedState.stale */: return 'stale';\n case 3 /* DerivedState.upToDate */: return 'upToDate';\n default: return '<unknown>';\n }\n}\nclass Derived extends BaseObservable {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? '(anonymous)';\n }\n constructor(_debugNameData, _computeFn, _changeTracker, _handleLastObserverRemoved = undefined, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this._computeFn = _computeFn;\n this._changeTracker = _changeTracker;\n this._handleLastObserverRemoved = _handleLastObserverRemoved;\n this._equalityComparator = _equalityComparator;\n this._state = 0 /* DerivedState.initial */;\n this._value = undefined;\n this._updateCount = 0;\n this._dependencies = new Set();\n this._dependenciesToBeRemoved = new Set();\n this._changeSummary = undefined;\n this._isUpdating = false;\n this._isComputing = false;\n this._didReportChange = false;\n this._isInBeforeUpdate = false;\n this._isReaderValid = false;\n this._store = undefined;\n this._delayedStore = undefined;\n this._removedObserverToCallEndUpdateOn = null;\n this._changeSummary = this._changeTracker?.createChangeSummary(undefined);\n }\n onLastObserverRemoved() {\n /**\n * We are not tracking changes anymore, thus we have to assume\n * that our cache is invalid.\n */\n this._state = 0 /* DerivedState.initial */;\n this._value = undefined;\n getLogger()?.handleDerivedCleared(this);\n for (const d of this._dependencies) {\n d.removeObserver(this);\n }\n this._dependencies.clear();\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n if (this._delayedStore !== undefined) {\n this._delayedStore.dispose();\n this._delayedStore = undefined;\n }\n this._handleLastObserverRemoved?.();\n }\n get() {\n const checkEnabled = false; // TODO set to true\n if (this._isComputing && checkEnabled) {\n // investigate why this fails in the diff editor!\n throw new BugIndicatingError('Cyclic deriveds are not supported yet!');\n }\n if (this._observers.size === 0) {\n let result;\n // Without observers, we don't know when to clean up stuff.\n // Thus, we don't cache anything to prevent memory leaks.\n try {\n this._isReaderValid = true;\n let changeSummary = undefined;\n if (this._changeTracker) {\n changeSummary = this._changeTracker.createChangeSummary(undefined);\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n }\n result = this._computeFn(this, changeSummary);\n }\n finally {\n this._isReaderValid = false;\n }\n // Clear new dependencies\n this.onLastObserverRemoved();\n return result;\n }\n else {\n do {\n // We might not get a notification for a dependency that changed while it is updating,\n // thus we also have to ask all our depedencies if they changed in this case.\n if (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */) {\n for (const d of this._dependencies) {\n /** might call {@link handleChange} indirectly, which could make us stale */\n d.reportChanges();\n if (this._state === 2 /* DerivedState.stale */) {\n // The other dependencies will refresh on demand, so early break\n break;\n }\n }\n }\n // We called report changes of all dependencies.\n // If we are still not stale, we can assume to be up to date again.\n if (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */) {\n this._state = 3 /* DerivedState.upToDate */;\n }\n if (this._state !== 3 /* DerivedState.upToDate */) {\n this._recompute();\n }\n // In case recomputation changed one of our dependencies, we need to recompute again.\n } while (this._state !== 3 /* DerivedState.upToDate */);\n return this._value;\n }\n }\n _recompute() {\n let didChange = false;\n this._isComputing = true;\n this._didReportChange = false;\n const emptySet = this._dependenciesToBeRemoved;\n this._dependenciesToBeRemoved = this._dependencies;\n this._dependencies = emptySet;\n try {\n const changeSummary = this._changeSummary;\n this._isReaderValid = true;\n if (this._changeTracker) {\n this._isInBeforeUpdate = true;\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n this._isInBeforeUpdate = false;\n this._changeSummary = this._changeTracker?.createChangeSummary(changeSummary);\n }\n const hadValue = this._state !== 0 /* DerivedState.initial */;\n const oldValue = this._value;\n this._state = 3 /* DerivedState.upToDate */;\n const delayedStore = this._delayedStore;\n if (delayedStore !== undefined) {\n this._delayedStore = undefined;\n }\n try {\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n /** might call {@link handleChange} indirectly, which could invalidate us */\n this._value = this._computeFn(this, changeSummary);\n }\n finally {\n this._isReaderValid = false;\n // We don't want our observed observables to think that they are (not even temporarily) not being observed.\n // Thus, we only unsubscribe from observables that are definitely not read anymore.\n for (const o of this._dependenciesToBeRemoved) {\n o.removeObserver(this);\n }\n this._dependenciesToBeRemoved.clear();\n if (delayedStore !== undefined) {\n delayedStore.dispose();\n }\n }\n didChange = this._didReportChange || (hadValue && !(this._equalityComparator(oldValue, this._value)));\n getLogger()?.handleObservableUpdated(this, {\n oldValue,\n newValue: this._value,\n change: undefined,\n didChange,\n hadValue,\n });\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n this._isComputing = false;\n if (!this._didReportChange && didChange) {\n for (const r of this._observers) {\n r.handleChange(this, undefined);\n }\n }\n else {\n this._didReportChange = false;\n }\n }\n toString() {\n return `LazyDerived<${this.debugName}>`;\n }\n // IObserver Implementation\n beginUpdate(_observable) {\n if (this._isUpdating) {\n throw new BugIndicatingError('Cyclic deriveds are not supported yet!');\n }\n this._updateCount++;\n this._isUpdating = true;\n try {\n const propagateBeginUpdate = this._updateCount === 1;\n if (this._state === 3 /* DerivedState.upToDate */) {\n this._state = 1 /* DerivedState.dependenciesMightHaveChanged */;\n // If we propagate begin update, that will already signal a possible change.\n if (!propagateBeginUpdate) {\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n if (propagateBeginUpdate) {\n for (const r of this._observers) {\n r.beginUpdate(this); // This signals a possible change\n }\n }\n }\n finally {\n this._isUpdating = false;\n }\n }\n endUpdate(_observable) {\n this._updateCount--;\n if (this._updateCount === 0) {\n // End update could change the observer list.\n const observers = [...this._observers];\n for (const r of observers) {\n r.endUpdate(this);\n }\n if (this._removedObserverToCallEndUpdateOn) {\n const observers = [...this._removedObserverToCallEndUpdateOn];\n this._removedObserverToCallEndUpdateOn = null;\n for (const r of observers) {\n r.endUpdate(this);\n }\n }\n }\n }\n handlePossibleChange(observable) {\n // In all other states, observers already know that we might have changed.\n if (this._state === 3 /* DerivedState.upToDate */ && this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable)) {\n this._state = 1 /* DerivedState.dependenciesMightHaveChanged */;\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n handleChange(observable, change) {\n if (this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable) || this._isInBeforeUpdate) {\n getLogger()?.handleDerivedDependencyChanged(this, observable, change);\n let shouldReact = false;\n try {\n shouldReact = this._changeTracker ? this._changeTracker.handleChange({\n changedObservable: observable,\n change,\n didChange: (o) => o === observable,\n }, this._changeSummary) : true;\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n const wasUpToDate = this._state === 3 /* DerivedState.upToDate */;\n if (shouldReact && (this._state === 1 /* DerivedState.dependenciesMightHaveChanged */ || wasUpToDate)) {\n this._state = 2 /* DerivedState.stale */;\n if (wasUpToDate) {\n for (const r of this._observers) {\n r.handlePossibleChange(this);\n }\n }\n }\n }\n }\n // IReader Implementation\n _ensureReaderValid() {\n if (!this._isReaderValid) {\n throw new BugIndicatingError('The reader object cannot be used outside its compute function!');\n }\n }\n readObservable(observable) {\n this._ensureReaderValid();\n // Subscribe before getting the value to enable caching\n observable.addObserver(this);\n /** This might call {@link handleChange} indirectly, which could invalidate us */\n const value = observable.get();\n // Which is why we only add the observable to the dependencies now.\n this._dependencies.add(observable);\n this._dependenciesToBeRemoved.delete(observable);\n return value;\n }\n reportChange(change) {\n this._ensureReaderValid();\n this._didReportChange = true;\n // TODO add logging\n for (const r of this._observers) {\n r.handleChange(this, change);\n }\n }\n get store() {\n this._ensureReaderValid();\n if (this._store === undefined) {\n this._store = new DisposableStore();\n }\n return this._store;\n }\n get delayedStore() {\n this._ensureReaderValid();\n if (this._delayedStore === undefined) {\n this._delayedStore = new DisposableStore();\n }\n return this._delayedStore;\n }\n addObserver(observer) {\n const shouldCallBeginUpdate = !this._observers.has(observer) && this._updateCount > 0;\n super.addObserver(observer);\n if (shouldCallBeginUpdate) {\n if (this._removedObserverToCallEndUpdateOn && this._removedObserverToCallEndUpdateOn.has(observer)) {\n this._removedObserverToCallEndUpdateOn.delete(observer);\n }\n else {\n observer.beginUpdate(this);\n }\n }\n }\n removeObserver(observer) {\n if (this._observers.has(observer) && this._updateCount > 0) {\n if (!this._removedObserverToCallEndUpdateOn) {\n this._removedObserverToCallEndUpdateOn = new Set();\n }\n this._removedObserverToCallEndUpdateOn.add(observer);\n }\n super.removeObserver(observer);\n }\n debugGetState() {\n return {\n state: this._state,\n stateStr: derivedStateToString(this._state),\n updateCount: this._updateCount,\n isComputing: this._isComputing,\n dependencies: this._dependencies,\n value: this._value,\n };\n }\n debugSetValue(newValue) {\n this._value = newValue;\n }\n debugRecompute() {\n if (!this._isComputing) {\n this._recompute();\n }\n else {\n this._state = 2 /* DerivedState.stale */;\n }\n }\n setValue(newValue, tx, change) {\n this._value = newValue;\n const observers = this._observers;\n tx.updateObserver(this, this);\n for (const d of observers) {\n d.handleChange(this, change);\n }\n }\n}\nclass DerivedWithSetter extends Derived {\n constructor(debugNameData, computeFn, changeTracker, handleLastObserverRemoved = undefined, equalityComparator, set, debugLocation) {\n super(debugNameData, computeFn, changeTracker, handleLastObserverRemoved, equalityComparator, debugLocation);\n this.set = set;\n }\n}\n\nexport { Derived, DerivedWithSetter };\n//# sourceMappingURL=derivedImpl.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugLocation } from '../debugLocation.js';\nimport { DebugNameData } from '../debugName.js';\nimport { _setDerivedOpts } from './baseObservable.js';\nimport { Derived, DerivedWithSetter } from './derivedImpl.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction derived(computeFnOrOwner, computeFn, debugLocation = DebugLocation.ofCaller()) {\n if (computeFn !== undefined) {\n return new Derived(new DebugNameData(computeFnOrOwner, undefined, computeFn), computeFn, undefined, undefined, strictEquals, debugLocation);\n }\n return new Derived(new DebugNameData(undefined, undefined, computeFnOrOwner), computeFnOrOwner, undefined, undefined, strictEquals, debugLocation);\n}\nfunction derivedWithSetter(owner, computeFn, setter, debugLocation = DebugLocation.ofCaller()) {\n return new DerivedWithSetter(new DebugNameData(owner, undefined, computeFn), computeFn, undefined, undefined, strictEquals, setter, debugLocation);\n}\nfunction derivedOpts(options, computeFn, debugLocation = DebugLocation.ofCaller()) {\n return new Derived(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn), computeFn, undefined, options.onLastObserverRemoved, options.equalsFn ?? strictEquals, debugLocation);\n}\n_setDerivedOpts(derivedOpts);\n/**\n * Represents an observable that is derived from other observables.\n * The value is only recomputed when absolutely needed.\n *\n * {@link computeFn} should start with a JS Doc using `@description` to name the derived.\n *\n * Use `createEmptyChangeSummary` to create a \"change summary\" that can collect the changes.\n * Use `handleChange` to add a reported change to the change summary.\n * The compute function is given the last change summary.\n * The change summary is discarded after the compute function was called.\n *\n * @see derived\n */\nfunction derivedHandleChanges(options, computeFn, debugLocation = DebugLocation.ofCaller()) {\n return new Derived(new DebugNameData(options.owner, options.debugName, undefined), computeFn, options.changeTracker, undefined, options.equalityComparer ?? strictEquals, debugLocation);\n}\nfunction derivedWithStore(computeFnOrOwner, computeFnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n let computeFn;\n let owner;\n if (computeFnOrUndefined === undefined) {\n computeFn = computeFnOrOwner;\n owner = undefined;\n }\n else {\n owner = computeFnOrOwner;\n computeFn = computeFnOrUndefined;\n }\n // Intentionally re-assigned in case an inactive observable is re-used later\n // eslint-disable-next-line local/code-no-potentially-unsafe-disposables\n let store = new DisposableStore();\n return new Derived(new DebugNameData(owner, undefined, computeFn), r => {\n if (store.isDisposed) {\n store = new DisposableStore();\n }\n else {\n store.clear();\n }\n return computeFn(r, store);\n }, undefined, () => store.dispose(), strictEquals, debugLocation);\n}\nfunction derivedDisposable(computeFnOrOwner, computeFnOrUndefined, debugLocation = DebugLocation.ofCaller()) {\n let computeFn;\n let owner;\n if (computeFnOrUndefined === undefined) {\n computeFn = computeFnOrOwner;\n owner = undefined;\n }\n else {\n owner = computeFnOrOwner;\n computeFn = computeFnOrUndefined;\n }\n let store = undefined;\n return new Derived(new DebugNameData(owner, undefined, computeFn), r => {\n if (!store) {\n store = new DisposableStore();\n }\n else {\n store.clear();\n }\n const result = computeFn(r);\n if (result) {\n store.add(result);\n }\n return result;\n }, undefined, () => {\n if (store) {\n store.dispose();\n store = undefined;\n }\n }, strictEquals, debugLocation);\n}\n\nexport { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter, derivedWithStore };\n//# sourceMappingURL=derived.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onBugIndicatingError, BugIndicatingError } from '../commonFacade/deps.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction autorunStateToString(state) {\n switch (state) {\n case 1 /* AutorunState.dependenciesMightHaveChanged */: return 'dependenciesMightHaveChanged';\n case 2 /* AutorunState.stale */: return 'stale';\n case 3 /* AutorunState.upToDate */: return 'upToDate';\n default: return '<unknown>';\n }\n}\nclass AutorunObserver {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? '(anonymous)';\n }\n constructor(_debugNameData, _runFn, _changeTracker, debugLocation) {\n this._debugNameData = _debugNameData;\n this._runFn = _runFn;\n this._changeTracker = _changeTracker;\n this._state = 2 /* AutorunState.stale */;\n this._updateCount = 0;\n this._disposed = false;\n this._dependencies = new Set();\n this._dependenciesToBeRemoved = new Set();\n this._isRunning = false;\n this._store = undefined;\n this._delayedStore = undefined;\n this._changeSummary = this._changeTracker?.createChangeSummary(undefined);\n getLogger()?.handleAutorunCreated(this, debugLocation);\n this._run();\n }\n dispose() {\n if (this._disposed) {\n return;\n }\n this._disposed = true;\n for (const o of this._dependencies) {\n o.removeObserver(this); // Warning: external call!\n }\n this._dependencies.clear();\n if (this._store !== undefined) {\n this._store.dispose();\n }\n if (this._delayedStore !== undefined) {\n this._delayedStore.dispose();\n }\n getLogger()?.handleAutorunDisposed(this);\n }\n _run() {\n const emptySet = this._dependenciesToBeRemoved;\n this._dependenciesToBeRemoved = this._dependencies;\n this._dependencies = emptySet;\n this._state = 3 /* AutorunState.upToDate */;\n try {\n if (!this._disposed) {\n getLogger()?.handleAutorunStarted(this);\n const changeSummary = this._changeSummary;\n const delayedStore = this._delayedStore;\n if (delayedStore !== undefined) {\n this._delayedStore = undefined;\n }\n try {\n this._isRunning = true;\n if (this._changeTracker) {\n this._changeTracker.beforeUpdate?.(this, changeSummary);\n this._changeSummary = this._changeTracker.createChangeSummary(changeSummary); // Warning: external call!\n }\n if (this._store !== undefined) {\n this._store.dispose();\n this._store = undefined;\n }\n this._runFn(this, changeSummary); // Warning: external call!\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n finally {\n this._isRunning = false;\n if (delayedStore !== undefined) {\n delayedStore.dispose();\n }\n }\n }\n }\n finally {\n if (!this._disposed) {\n getLogger()?.handleAutorunFinished(this);\n }\n // We don't want our observed observables to think that they are (not even temporarily) not being observed.\n // Thus, we only unsubscribe from observables that are definitely not read anymore.\n for (const o of this._dependenciesToBeRemoved) {\n o.removeObserver(this); // Warning: external call!\n }\n this._dependenciesToBeRemoved.clear();\n }\n }\n toString() {\n return `Autorun<${this.debugName}>`;\n }\n // IObserver implementation\n beginUpdate(_observable) {\n if (this._state === 3 /* AutorunState.upToDate */) {\n this._state = 1 /* AutorunState.dependenciesMightHaveChanged */;\n }\n this._updateCount++;\n }\n endUpdate(_observable) {\n try {\n if (this._updateCount === 1) {\n do {\n if (this._state === 1 /* AutorunState.dependenciesMightHaveChanged */) {\n this._state = 3 /* AutorunState.upToDate */;\n for (const d of this._dependencies) {\n d.reportChanges(); // Warning: external call!\n if (this._state === 2 /* AutorunState.stale */) {\n // The other dependencies will refresh on demand\n break;\n }\n }\n }\n if (this._state !== 3 /* AutorunState.upToDate */) {\n this._run(); // Warning: indirect external call!\n }\n } while (this._state !== 3 /* AutorunState.upToDate */);\n }\n }\n finally {\n this._updateCount--;\n }\n }\n handlePossibleChange(observable) {\n if (this._state === 3 /* AutorunState.upToDate */ && this._isDependency(observable)) {\n this._state = 1 /* AutorunState.dependenciesMightHaveChanged */;\n }\n }\n handleChange(observable, change) {\n if (this._isDependency(observable)) {\n getLogger()?.handleAutorunDependencyChanged(this, observable, change);\n try {\n // Warning: external call!\n const shouldReact = this._changeTracker ? this._changeTracker.handleChange({\n changedObservable: observable,\n change,\n didChange: (o) => o === observable,\n }, this._changeSummary) : true;\n if (shouldReact) {\n this._state = 2 /* AutorunState.stale */;\n }\n }\n catch (e) {\n onBugIndicatingError(e);\n }\n }\n }\n _isDependency(observable) {\n return this._dependencies.has(observable) && !this._dependenciesToBeRemoved.has(observable);\n }\n // IReader implementation\n _ensureNoRunning() {\n if (!this._isRunning) {\n throw new BugIndicatingError('The reader object cannot be used outside its compute function!');\n }\n }\n readObservable(observable) {\n this._ensureNoRunning();\n // In case the run action disposes the autorun\n if (this._disposed) {\n return observable.get(); // warning: external call!\n }\n observable.addObserver(this); // warning: external call!\n const value = observable.get(); // warning: external call!\n this._dependencies.add(observable);\n this._dependenciesToBeRemoved.delete(observable);\n return value;\n }\n get store() {\n this._ensureNoRunning();\n if (this._disposed) {\n throw new BugIndicatingError('Cannot access store after dispose');\n }\n if (this._store === undefined) {\n this._store = new DisposableStore();\n }\n return this._store;\n }\n get delayedStore() {\n this._ensureNoRunning();\n if (this._disposed) {\n throw new BugIndicatingError('Cannot access store after dispose');\n }\n if (this._delayedStore === undefined) {\n this._delayedStore = new DisposableStore();\n }\n return this._delayedStore;\n }\n debugGetState() {\n return {\n isRunning: this._isRunning,\n updateCount: this._updateCount,\n dependencies: this._dependencies,\n state: this._state,\n stateStr: autorunStateToString(this._state),\n };\n }\n debugRerun() {\n if (!this._isRunning) {\n this._run();\n }\n else {\n this._state = 2 /* AutorunState.stale */;\n }\n }\n}\n\nexport { AutorunObserver };\n//# sourceMappingURL=createEffectImpl.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { toDisposable } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { AutorunObserver } from './createEffectImpl.js';\nimport { DebugLocation } from '../debugLocation.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the effect.\n */\nfunction createEffect(fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(undefined, undefined, fn), fn, undefined, debugLocation);\n}\n/**\n * @deprecated Use {@link createEffect} instead.\n */\nconst autorun = createEffect;\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the autorun.\n */\nfunction createEffectOpts(options, fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, undefined, debugLocation);\n}\n/**\n * @deprecated Use {@link createEffectOpts} instead.\n */\nconst autorunOpts = createEffectOpts;\n/**\n * Runs immediately and whenever a transaction ends and an observed observable changed.\n * {@link fn} should start with a JS Doc using `@description` to name the autorun.\n *\n * Use `changeTracker.createChangeSummary` to create a \"change summary\" that can collect the changes.\n * Use `changeTracker.handleChange` to add a reported change to the change summary.\n * The run function is given the last change summary.\n * The change summary is discarded after the run function was called.\n *\n * @see autorun\n */\nfunction autorunHandleChanges(options, fn, debugLocation = DebugLocation.ofCaller()) {\n return new AutorunObserver(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? fn), fn, options.changeTracker, debugLocation);\n}\n/**\n * @see autorunHandleChanges (but with a disposable store that is cleared before the next run or on dispose)\n */\nfunction autorunWithStoreHandleChanges(options, fn) {\n const store = new DisposableStore();\n const disposable = autorunHandleChanges({\n owner: options.owner,\n debugName: options.debugName,\n debugReferenceFn: options.debugReferenceFn ?? fn,\n changeTracker: options.changeTracker,\n }, (reader, changeSummary) => {\n store.clear();\n fn(reader, changeSummary, store);\n });\n return toDisposable(() => {\n disposable.dispose();\n store.dispose();\n });\n}\n/**\n * @see autorun (but with a disposable store that is cleared before the next run or on dispose)\n *\n * @deprecated Use `autorun(reader => { reader.store.add(...) })` instead!\n */\nfunction autorunWithStore(fn) {\n const store = new DisposableStore();\n const disposable = createEffectOpts({\n owner: undefined,\n debugName: undefined,\n debugReferenceFn: fn,\n }, reader => {\n store.clear();\n fn(reader, store);\n });\n return toDisposable(() => {\n disposable.dispose();\n store.dispose();\n });\n}\nfunction autorunDelta(observable, handler) {\n let _lastValue;\n return createEffectOpts({ debugReferenceFn: handler }, (reader) => {\n const newValue = observable.read(reader);\n const lastValue = _lastValue;\n _lastValue = newValue;\n handler({ lastValue, newValue });\n });\n}\nfunction autorunIterableDelta(getValue, handler, getUniqueIdentifier = v => v) {\n const lastValues = new Map();\n return createEffectOpts({ debugReferenceFn: getValue }, (reader) => {\n const newValues = new Map();\n const removedValues = new Map(lastValues);\n for (const value of getValue(reader)) {\n const id = getUniqueIdentifier(value);\n if (lastValues.has(id)) {\n removedValues.delete(id);\n }\n else {\n newValues.set(id, value);\n lastValues.set(id, value);\n }\n }\n for (const id of removedValues.keys()) {\n lastValues.delete(id);\n }\n if (newValues.size || removedValues.size) {\n handler({ addedValues: [...newValues.values()], removedValues: [...removedValues.values()] });\n }\n });\n}\n/**\n * An autorun with a `dispose()` method on its `reader` which cancels the autorun.\n * It it safe to call `dispose()` synchronously.\n */\nfunction autorunSelfDisposable(fn, debugLocation = DebugLocation.ofCaller()) {\n let ar;\n let disposed = false;\n // eslint-disable-next-line prefer-const\n ar = createEffect(reader => {\n fn({\n delayedStore: reader.delayedStore,\n store: reader.store,\n readObservable: reader.readObservable.bind(reader),\n dispose: () => {\n ar?.dispose();\n disposed = true;\n }\n });\n }, debugLocation);\n if (disposed) {\n ar.dispose();\n }\n return ar;\n}\n\nexport { autorun, autorunDelta, autorunHandleChanges, autorunIterableDelta, autorunOpts, autorunSelfDisposable, autorunWithStore, autorunWithStoreHandleChanges, createEffect, createEffectOpts };\n//# sourceMappingURL=createEffect.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { onUnexpectedError } from './commonFacade/deps.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * This function is used to indicate that the caller recovered from an error that indicates a bug.\n*/\nfunction handleBugIndicatingErrorRecovery(message) {\n const err = new Error('BugIndicatingErrorRecovery: ' + message);\n onUnexpectedError(err);\n console.error('recovered from an error that indicates a bug', err);\n}\n\nexport { handleBugIndicatingErrorRecovery };\n//# sourceMappingURL=base.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { handleBugIndicatingErrorRecovery } from './base.js';\nimport { getFunctionName } from './debugName.js';\nimport { getLogger } from './logging/logging.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n/**\n * Starts a transaction in which many observables can be changed at once.\n * {@link fn} should start with a JS Doc using `@description` to give the transaction a debug name.\n * Reaction run on demand or when the transaction ends.\n */\nfunction transaction(fn, getDebugName) {\n const tx = new TransactionImpl(fn, getDebugName);\n try {\n fn(tx);\n }\n finally {\n tx.finish();\n }\n}\nlet _globalTransaction = undefined;\nfunction globalTransaction(fn) {\n if (_globalTransaction) {\n fn(_globalTransaction);\n }\n else {\n const tx = new TransactionImpl(fn, undefined);\n _globalTransaction = tx;\n try {\n fn(tx);\n }\n finally {\n tx.finish(); // During finish, more actions might be added to the transaction.\n // Which is why we only clear the global transaction after finish.\n _globalTransaction = undefined;\n }\n }\n}\n/** @deprecated */\nasync function asyncTransaction(fn, getDebugName) {\n const tx = new TransactionImpl(fn, getDebugName);\n try {\n await fn(tx);\n }\n finally {\n tx.finish();\n }\n}\n/**\n * Allows to chain transactions.\n */\nfunction subtransaction(tx, fn, getDebugName) {\n if (!tx) {\n transaction(fn, getDebugName);\n }\n else {\n fn(tx);\n }\n}\nclass TransactionImpl {\n constructor(_fn, _getDebugName) {\n this._fn = _fn;\n this._getDebugName = _getDebugName;\n this._updatingObservers = [];\n getLogger()?.handleBeginTransaction(this);\n }\n getDebugName() {\n if (this._getDebugName) {\n return this._getDebugName();\n }\n return getFunctionName(this._fn);\n }\n updateObserver(observer, observable) {\n if (!this._updatingObservers) {\n // This happens when a transaction is used in a callback or async function.\n // If an async transaction is used, make sure the promise awaits all users of the transaction (e.g. no race).\n handleBugIndicatingErrorRecovery('Transaction already finished!');\n // Error recovery\n transaction(tx => {\n tx.updateObserver(observer, observable);\n });\n return;\n }\n // When this gets called while finish is active, they will still get considered\n this._updatingObservers.push({ observer, observable });\n observer.beginUpdate(observable);\n }\n finish() {\n const updatingObservers = this._updatingObservers;\n if (!updatingObservers) {\n handleBugIndicatingErrorRecovery('transaction.finish() has already been called!');\n return;\n }\n for (let i = 0; i < updatingObservers.length; i++) {\n const { observer, observable } = updatingObservers[i];\n observer.endUpdate(observable);\n }\n // Prevent anyone from updating observers from now on.\n this._updatingObservers = null;\n getLogger()?.handleEndTransaction(this);\n }\n debugGetUpdatingObservers() {\n return this._updatingObservers;\n }\n}\n\nexport { TransactionImpl, asyncTransaction, globalTransaction, subtransaction, transaction };\n//# sourceMappingURL=transaction.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { TransactionImpl } from '../transaction.js';\nimport { BaseObservable } from './baseObservable.js';\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { getLogger } from '../logging/logging.js';\nimport { DebugLocation } from '../debugLocation.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableValue(nameOrOwner, initialValue, debugLocation = DebugLocation.ofCaller()) {\n let debugNameData;\n if (typeof nameOrOwner === 'string') {\n debugNameData = new DebugNameData(undefined, nameOrOwner, undefined);\n }\n else {\n debugNameData = new DebugNameData(nameOrOwner, undefined, undefined);\n }\n return new ObservableValue(debugNameData, initialValue, strictEquals, debugLocation);\n}\nclass ObservableValue extends BaseObservable {\n get debugName() {\n return this._debugNameData.getDebugName(this) ?? 'ObservableValue';\n }\n constructor(_debugNameData, initialValue, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this._equalityComparator = _equalityComparator;\n this._value = initialValue;\n getLogger()?.handleObservableUpdated(this, { hadValue: false, newValue: initialValue, change: undefined, didChange: true, oldValue: undefined });\n }\n get() {\n return this._value;\n }\n set(value, tx, change) {\n if (change === undefined && this._equalityComparator(this._value, value)) {\n return;\n }\n let _tx;\n if (!tx) {\n tx = _tx = new TransactionImpl(() => { }, () => `Setting ${this.debugName}`);\n }\n try {\n const oldValue = this._value;\n this._setValue(value);\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue: value, change, didChange: true, hadValue: true });\n for (const observer of this._observers) {\n tx.updateObserver(observer, this);\n observer.handleChange(this, change);\n }\n }\n finally {\n if (_tx) {\n _tx.finish();\n }\n }\n }\n toString() {\n return `${this.debugName}: ${this._value}`;\n }\n _setValue(newValue) {\n this._value = newValue;\n }\n debugGetState() {\n return {\n value: this._value,\n };\n }\n debugSetValue(value) {\n this._value = value;\n }\n}\n/**\n * A disposable observable. When disposed, its value is also disposed.\n * When a new value is set, the previous value is disposed.\n */\nfunction disposableObservableValue(nameOrOwner, initialValue, debugLocation = DebugLocation.ofCaller()) {\n let debugNameData;\n if (typeof nameOrOwner === 'string') {\n debugNameData = new DebugNameData(undefined, nameOrOwner, undefined);\n }\n else {\n debugNameData = new DebugNameData(nameOrOwner, undefined, undefined);\n }\n return new DisposableObservableValue(debugNameData, initialValue, strictEquals, debugLocation);\n}\nclass DisposableObservableValue extends ObservableValue {\n _setValue(newValue) {\n if (this._value === newValue) {\n return;\n }\n if (this._value) {\n this._value.dispose();\n }\n this._value = newValue;\n }\n dispose() {\n this._value?.dispose();\n }\n}\n\nexport { DisposableObservableValue, ObservableValue, disposableObservableValue, observableValue };\n//# sourceMappingURL=observableValue.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { subtransaction } from '../transaction.js';\nimport { strictEquals } from '../commonFacade/deps.js';\nimport { DebugNameData } from '../debugName.js';\nimport { getLogger } from '../logging/logging.js';\nimport { BaseObservable } from './baseObservable.js';\nimport { DebugLocation } from '../debugLocation.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableFromEvent(...args) {\n let owner;\n let event;\n let getValue;\n let debugLocation;\n if (args.length === 2) {\n [event, getValue] = args;\n }\n else {\n [owner, event, getValue, debugLocation] = args;\n }\n return new FromEventObservable(new DebugNameData(owner, undefined, getValue), event, getValue, () => FromEventObservable.globalTransaction, strictEquals, debugLocation ?? DebugLocation.ofCaller());\n}\nfunction observableFromEventOpts(options, event, getValue, debugLocation = DebugLocation.ofCaller()) {\n return new FromEventObservable(new DebugNameData(options.owner, options.debugName, options.debugReferenceFn ?? getValue), event, getValue, () => FromEventObservable.globalTransaction, options.equalsFn ?? strictEquals, debugLocation);\n}\nclass FromEventObservable extends BaseObservable {\n constructor(_debugNameData, event, _getValue, _getTransaction, _equalityComparator, debugLocation) {\n super(debugLocation);\n this._debugNameData = _debugNameData;\n this.event = event;\n this._getValue = _getValue;\n this._getTransaction = _getTransaction;\n this._equalityComparator = _equalityComparator;\n this._hasValue = false;\n this.handleEvent = (args) => {\n const newValue = this._getValue(args);\n const oldValue = this._value;\n const didChange = !this._hasValue || !(this._equalityComparator(oldValue, newValue));\n let didRunTransaction = false;\n if (didChange) {\n this._value = newValue;\n if (this._hasValue) {\n didRunTransaction = true;\n subtransaction(this._getTransaction(), (tx) => {\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue, change: undefined, didChange, hadValue: this._hasValue });\n for (const o of this._observers) {\n tx.updateObserver(o, this);\n o.handleChange(this, undefined);\n }\n }, () => {\n const name = this.getDebugName();\n return 'Event fired' + (name ? `: ${name}` : '');\n });\n }\n this._hasValue = true;\n }\n if (!didRunTransaction) {\n getLogger()?.handleObservableUpdated(this, { oldValue, newValue, change: undefined, didChange, hadValue: this._hasValue });\n }\n };\n }\n getDebugName() {\n return this._debugNameData.getDebugName(this);\n }\n get debugName() {\n const name = this.getDebugName();\n return 'From Event' + (name ? `: ${name}` : '');\n }\n onFirstObserverAdded() {\n this._subscription = this.event(this.handleEvent);\n }\n onLastObserverRemoved() {\n this._subscription.dispose();\n this._subscription = undefined;\n this._hasValue = false;\n this._value = undefined;\n }\n get() {\n if (this._subscription) {\n if (!this._hasValue) {\n this.handleEvent(undefined);\n }\n return this._value;\n }\n else {\n // no cache, as there are no subscribers to keep it updated\n const value = this._getValue(undefined);\n return value;\n }\n }\n debugSetValue(value) {\n this._value = value;\n }\n debugGetState() {\n return { value: this._value, hasValue: this._hasValue };\n }\n}\n(function (observableFromEvent) {\n observableFromEvent.Observer = FromEventObservable;\n function batchEventsGlobally(tx, fn) {\n let didSet = false;\n if (FromEventObservable.globalTransaction === undefined) {\n FromEventObservable.globalTransaction = tx;\n didSet = true;\n }\n try {\n fn();\n }\n finally {\n if (didSet) {\n FromEventObservable.globalTransaction = undefined;\n }\n }\n }\n observableFromEvent.batchEventsGlobally = batchEventsGlobally;\n})(observableFromEvent || (observableFromEvent = {}));\n\nexport { FromEventObservable, observableFromEvent, observableFromEventOpts };\n//# sourceMappingURL=observableFromEvent.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { createEffect } from '../reactions/createEffect.js';\nimport { transaction } from '../transaction.js';\nimport { observableValue } from '../observables/observableValue.js';\nimport { toDisposable } from '../commonFacade/deps.js';\nimport { derivedOpts, derived } from '../observables/derived.js';\nimport { observableFromEvent } from '../observables/observableFromEvent.js';\nimport { observableSignal } from '../observables/observableSignal.js';\nimport { _setKeepObserved, _setRecomputeInitiallyAndOnChange } from '../observables/baseObservable.js';\nimport { DisposableStore } from '../../disposables.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction observableFromPromise(promise) {\n const observable = observableValue('promiseValue', {});\n promise.then((value) => {\n observable.set({ value }, undefined);\n });\n return observable;\n}\nfunction signalFromObservable(owner, observable) {\n return derivedOpts({\n owner,\n equalsFn: () => false,\n }, reader => {\n observable.read(reader);\n });\n}\n/**\n * @deprecated Use `debouncedObservable` instead.\n */\nfunction debouncedObservableDeprecated(observable, debounceMs, disposableStore) {\n const debouncedObservable = observableValue('debounced', undefined);\n let timeout = undefined;\n disposableStore.add(createEffect(reader => {\n /** @description debounce */\n const value = observable.read(reader);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n transaction(tx => {\n debouncedObservable.set(value, tx);\n });\n }, debounceMs);\n }));\n return debouncedObservable;\n}\n/**\n * Creates an observable that debounces the input observable.\n */\nfunction debouncedObservable(observable, debounceMs) {\n let hasValue = false;\n let lastValue;\n let timeout = undefined;\n return observableFromEvent(cb => {\n const d = createEffect(reader => {\n const value = observable.read(reader);\n if (!hasValue) {\n hasValue = true;\n lastValue = value;\n }\n else {\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n lastValue = value;\n cb();\n }, debounceMs);\n }\n });\n return {\n dispose() {\n d.dispose();\n hasValue = false;\n lastValue = undefined;\n },\n };\n }, () => {\n if (hasValue) {\n return lastValue;\n }\n else {\n return observable.get();\n }\n });\n}\nfunction wasEventTriggeredRecently(event, timeoutMs, disposableStore) {\n const observable = observableValue('triggeredRecently', false);\n let timeout = undefined;\n disposableStore.add(event(() => {\n observable.set(true, undefined);\n if (timeout) {\n clearTimeout(timeout);\n }\n timeout = setTimeout(() => {\n observable.set(false, undefined);\n }, timeoutMs);\n }));\n return observable;\n}\n/**\n * This makes sure the observable is being observed and keeps its cache alive.\n */\nfunction keepObserved(observable) {\n const o = new KeepAliveObserver(false, undefined);\n observable.addObserver(o);\n return toDisposable(() => {\n observable.removeObserver(o);\n });\n}\n_setKeepObserved(keepObserved);\n/**\n * This converts the given observable into an autorun.\n */\nfunction recomputeInitiallyAndOnChange(observable, handleValue) {\n const o = new KeepAliveObserver(true, handleValue);\n observable.addObserver(o);\n try {\n o.beginUpdate(observable);\n }\n finally {\n o.endUpdate(observable);\n }\n return toDisposable(() => {\n observable.removeObserver(o);\n });\n}\n_setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange);\nclass KeepAliveObserver {\n constructor(_forceRecompute, _handleValue) {\n this._forceRecompute = _forceRecompute;\n this._handleValue = _handleValue;\n this._counter = 0;\n }\n beginUpdate(observable) {\n this._counter++;\n }\n endUpdate(observable) {\n if (this._counter === 1 && this._forceRecompute) {\n if (this._handleValue) {\n this._handleValue(observable.get());\n }\n else {\n observable.reportChanges();\n }\n }\n this._counter--;\n }\n handlePossibleChange(observable) {\n // NO OP\n }\n handleChange(observable, change) {\n // NO OP\n }\n}\nfunction derivedObservableWithCache(owner, computeFn) {\n let lastValue = undefined;\n const observable = derivedOpts({ owner, debugReferenceFn: computeFn }, reader => {\n lastValue = computeFn(reader, lastValue);\n return lastValue;\n });\n return observable;\n}\nfunction derivedObservableWithWritableCache(owner, computeFn) {\n let lastValue = undefined;\n const onChange = observableSignal('derivedObservableWithWritableCache');\n const observable = derived(owner, reader => {\n onChange.read(reader);\n lastValue = computeFn(reader, lastValue);\n return lastValue;\n });\n return Object.assign(observable, {\n clearCache: (tx) => {\n lastValue = undefined;\n onChange.trigger(tx);\n },\n setCache: (newValue, tx) => {\n lastValue = newValue;\n onChange.trigger(tx);\n }\n });\n}\n/**\n * When the items array changes, referential equal items are not mapped again.\n */\nfunction mapObservableArrayCached(owner, items, map, keySelector) {\n let m = new ArrayMap(map, keySelector);\n const self = derivedOpts({\n debugReferenceFn: map,\n owner,\n onLastObserverRemoved: () => {\n m.dispose();\n m = new ArrayMap(map);\n }\n }, (reader) => {\n m.setItems(items.read(reader));\n return m.getItems();\n });\n return self;\n}\nclass ArrayMap {\n constructor(_map, _keySelector) {\n this._map = _map;\n this._keySelector = _keySelector;\n this._cache = new Map();\n this._items = [];\n }\n dispose() {\n this._cache.forEach(entry => entry.store.dispose());\n this._cache.clear();\n }\n setItems(items) {\n const newItems = [];\n const itemsToRemove = new Set(this._cache.keys());\n for (const item of items) {\n const key = this._keySelector ? this._keySelector(item) : item;\n let entry = this._cache.get(key);\n if (!entry) {\n const store = new DisposableStore();\n const out = this._map(item, store);\n entry = { out, store };\n this._cache.set(key, entry);\n }\n else {\n itemsToRemove.delete(key);\n }\n newItems.push(entry.out);\n }\n for (const item of itemsToRemove) {\n const entry = this._cache.get(item);\n entry.store.dispose();\n this._cache.delete(item);\n }\n this._items = newItems;\n }\n getItems() {\n return this._items;\n }\n}\n\nexport { KeepAliveObserver, debouncedObservable, debouncedObservableDeprecated, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, mapObservableArrayCached, observableFromPromise, recomputeInitiallyAndOnChange, signalFromObservable, wasEventTriggeredRecently };\n//# sourceMappingURL=utils.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { addLogger } from './logging.js';\nimport { getClassName } from '../debugName.js';\nimport { Derived } from '../observables/derivedImpl.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nlet consoleObservableLogger;\nfunction logObservableToConsole(obs) {\n if (!consoleObservableLogger) {\n consoleObservableLogger = new ConsoleObservableLogger();\n addLogger(consoleObservableLogger);\n }\n consoleObservableLogger.addFilteredObj(obs);\n}\nclass ConsoleObservableLogger {\n constructor() {\n this.indentation = 0;\n this.changedObservablesSets = new WeakMap();\n }\n addFilteredObj(obj) {\n if (!this._filteredObjects) {\n this._filteredObjects = new Set();\n }\n this._filteredObjects.add(obj);\n }\n _isIncluded(obj) {\n return this._filteredObjects?.has(obj) ?? true;\n }\n textToConsoleArgs(text) {\n return consoleTextToArgs([\n normalText(repeat('| ', this.indentation)),\n text,\n ]);\n }\n formatInfo(info) {\n if (!info.hadValue) {\n return [\n normalText(` `),\n styled(formatValue(info.newValue, 60), {\n color: 'green',\n }),\n normalText(` (initial)`),\n ];\n }\n return info.didChange\n ? [\n normalText(` `),\n styled(formatValue(info.oldValue, 70), {\n color: 'red',\n strikeThrough: true,\n }),\n normalText(` `),\n styled(formatValue(info.newValue, 60), {\n color: 'green',\n }),\n ]\n : [normalText(` (unchanged)`)];\n }\n handleObservableCreated(observable) {\n if (observable instanceof Derived) {\n const derived = observable;\n this.changedObservablesSets.set(derived, new Set());\n }\n }\n handleOnListenerCountChanged(observable, newCount) {\n }\n handleObservableUpdated(observable, info) {\n if (!this._isIncluded(observable)) {\n return;\n }\n if (observable instanceof Derived) {\n this._handleDerivedRecomputed(observable, info);\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('observable value changed'),\n styled(observable.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n ]));\n }\n formatChanges(changes) {\n if (changes.size === 0) {\n return undefined;\n }\n return styled(' (changed deps: ' +\n [...changes].map((o) => o.debugName).join(', ') +\n ')', { color: 'gray' });\n }\n handleDerivedDependencyChanged(derived, observable, change) {\n if (!this._isIncluded(derived)) {\n return;\n }\n this.changedObservablesSets.get(derived)?.add(observable);\n }\n _handleDerivedRecomputed(derived, info) {\n if (!this._isIncluded(derived)) {\n return;\n }\n const changedObservables = this.changedObservablesSets.get(derived);\n if (!changedObservables) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('derived recomputed'),\n styled(derived.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n this.formatChanges(changedObservables),\n { data: [{ fn: derived._debugNameData.referenceFn ?? derived._computeFn }] }\n ]));\n changedObservables.clear();\n }\n handleDerivedCleared(derived) {\n if (!this._isIncluded(derived)) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('derived cleared'),\n styled(derived.debugName, { color: 'BlueViolet' }),\n ]));\n }\n handleFromEventObservableTriggered(observable, info) {\n if (!this._isIncluded(observable)) {\n return;\n }\n console.log(...this.textToConsoleArgs([\n formatKind('observable from event triggered'),\n styled(observable.debugName, { color: 'BlueViolet' }),\n ...this.formatInfo(info),\n { data: [{ fn: observable._getValue }] }\n ]));\n }\n handleAutorunCreated(autorun) {\n if (!this._isIncluded(autorun)) {\n return;\n }\n this.changedObservablesSets.set(autorun, new Set());\n }\n handleAutorunDisposed(autorun) {\n }\n handleAutorunDependencyChanged(autorun, observable, change) {\n if (!this._isIncluded(autorun)) {\n return;\n }\n this.changedObservablesSets.get(autorun).add(observable);\n }\n handleAutorunStarted(autorun) {\n const changedObservables = this.changedObservablesSets.get(autorun);\n if (!changedObservables) {\n return;\n }\n if (this._isIncluded(autorun)) {\n console.log(...this.textToConsoleArgs([\n formatKind('autorun'),\n styled(autorun.debugName, { color: 'BlueViolet' }),\n this.formatChanges(changedObservables),\n { data: [{ fn: autorun._debugNameData.referenceFn ?? autorun._runFn }] }\n ]));\n }\n changedObservables.clear();\n this.indentation++;\n }\n handleAutorunFinished(autorun) {\n this.indentation--;\n }\n handleBeginTransaction(transaction) {\n let transactionName = transaction.getDebugName();\n if (transactionName === undefined) {\n transactionName = '';\n }\n if (this._isIncluded(transaction)) {\n console.log(...this.textToConsoleArgs([\n formatKind('transaction'),\n styled(transactionName, { color: 'BlueViolet' }),\n { data: [{ fn: transaction._fn }] }\n ]));\n }\n this.indentation++;\n }\n handleEndTransaction() {\n this.indentation--;\n }\n}\nfunction consoleTextToArgs(text) {\n const styles = new Array();\n const data = [];\n let firstArg = '';\n function process(t) {\n if ('length' in t) {\n for (const item of t) {\n if (item) {\n process(item);\n }\n }\n }\n else if ('text' in t) {\n firstArg += `%c${t.text}`;\n styles.push(t.style);\n if (t.data) {\n data.push(...t.data);\n }\n }\n else if ('data' in t) {\n data.push(...t.data);\n }\n }\n process(text);\n const result = [firstArg, ...styles];\n result.push(...data);\n return result;\n}\nfunction normalText(text) {\n return styled(text, { color: 'black' });\n}\nfunction formatKind(kind) {\n return styled(padStr(`${kind}: `, 10), { color: 'black', bold: true });\n}\nfunction styled(text, options = {\n color: 'black',\n}) {\n function objToCss(styleObj) {\n return Object.entries(styleObj).reduce((styleString, [propName, propValue]) => {\n return `${styleString}${propName}:${propValue};`;\n }, '');\n }\n const style = {\n color: options.color,\n };\n if (options.strikeThrough) {\n style['text-decoration'] = 'line-through';\n }\n if (options.bold) {\n style['font-weight'] = 'bold';\n }\n return {\n text,\n style: objToCss(style),\n };\n}\nfunction formatValue(value, availableLen) {\n try {\n return formatValueUnsafe(value, availableLen);\n }\n catch {\n // Value could not be formatted (e.g., a Proxy that throws on coercion)\n return '[[???]]';\n }\n}\nfunction formatValueUnsafe(value, availableLen) {\n switch (typeof value) {\n case 'number':\n return '' + value;\n case 'string':\n if (value.length + 2 <= availableLen) {\n return `\"${value}\"`;\n }\n return `\"${value.substr(0, availableLen - 7)}\"+...`;\n case 'boolean':\n return value ? 'true' : 'false';\n case 'undefined':\n return 'undefined';\n case 'object':\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return formatArray(value, availableLen);\n }\n return formatObject(value, availableLen);\n case 'symbol':\n return value.toString();\n case 'function':\n return `[[Function${value.name ? ' ' + value.name : ''}]]`;\n default:\n return '' + value;\n }\n}\nfunction formatArray(value, availableLen) {\n let result = '[ ';\n let first = true;\n for (const val of value) {\n if (!first) {\n result += ', ';\n }\n if (result.length - 5 > availableLen) {\n result += '...';\n break;\n }\n first = false;\n result += `${formatValue(val, availableLen - result.length)}`;\n }\n result += ' ]';\n return result;\n}\nfunction formatObject(value, availableLen) {\n // Avoid drilling into Proxies - wrap operations that could trigger traps\n try {\n if (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) {\n const val = value.toString();\n if (val.length <= availableLen) {\n return val;\n }\n return val.substring(0, availableLen - 3) + '...';\n }\n }\n catch {\n // toString triggered a Proxy trap or threw - bail out\n return '[[Object]]';\n }\n const className = getClassName(value);\n let result = className ? className + '(' : '{ ';\n let first = true;\n let entries;\n try {\n entries = Object.entries(value);\n }\n catch {\n // Object.entries triggered a Proxy trap - bail out\n return className ? `${className}(...)` : '[[Object]]';\n }\n for (const [key, val] of entries) {\n if (!first) {\n result += ', ';\n }\n if (result.length - 5 > availableLen) {\n result += '...';\n break;\n }\n first = false;\n result += `${key}: ${formatValue(val, availableLen - result.length)}`;\n }\n result += className ? ')' : ' }';\n return result;\n}\nfunction repeat(str, count) {\n let result = '';\n for (let i = 1; i <= count; i++) {\n result += str;\n }\n return result;\n}\nfunction padStr(str, length) {\n while (str.length < length) {\n str += ' ';\n }\n return str;\n}\n\nexport { ConsoleObservableLogger, formatValue, logObservableToConsole };\n//# sourceMappingURL=consoleObservableLogger.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { Derived } from '../observables/derivedImpl.js';\nimport { FromEventObservable } from '../observables/observableFromEvent.js';\nimport { ObservableValue } from '../observables/observableValue.js';\nimport { AutorunObserver } from '../reactions/createEffectImpl.js';\nimport { formatValue } from './consoleObservableLogger.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nfunction debugGetDependencyGraph(obs, options) {\n const debugNamePostProcessor = options?.debugNamePostProcessor ?? ((str) => str);\n const info = Info.from(obs, debugNamePostProcessor);\n if (!info) {\n return '';\n }\n const alreadyListed = new Set();\n return formatObservableInfo(info, 0, alreadyListed).trim();\n}\nfunction formatObservableInfo(info, indentLevel, alreadyListed) {\n const indent = '\\t\\t'.repeat(indentLevel);\n const lines = [];\n const isAlreadyListed = alreadyListed.has(info.sourceObj);\n if (isAlreadyListed) {\n lines.push(`${indent}* ${info.type} ${info.name} (already listed)`);\n return lines.join('\\n');\n }\n alreadyListed.add(info.sourceObj);\n lines.push(`${indent}* ${info.type} ${info.name}:`);\n lines.push(`${indent} value: ${formatValue(info.value, 50)}`);\n lines.push(`${indent} state: ${info.state}`);\n if (info.dependencies.length > 0) {\n lines.push(`${indent} dependencies:`);\n for (const dep of info.dependencies) {\n lines.push(formatObservableInfo(dep, indentLevel + 1, alreadyListed));\n }\n }\n return lines.join('\\n');\n}\nclass Info {\n static from(obs, debugNamePostProcessor) {\n if (obs instanceof AutorunObserver) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'autorun', undefined, state.stateStr, Array.from(state.dependencies).map(dep => Info.from(dep, debugNamePostProcessor) || Info.unknown(dep)));\n }\n else if (obs instanceof Derived) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'derived', state.value, state.stateStr, Array.from(state.dependencies).map(dep => Info.from(dep, debugNamePostProcessor) || Info.unknown(dep)));\n }\n else if (obs instanceof ObservableValue) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'observableValue', state.value, 'upToDate', []);\n }\n else if (obs instanceof FromEventObservable) {\n const state = obs.debugGetState();\n return new Info(obs, debugNamePostProcessor(obs.debugName), 'fromEvent', state.value, state.hasValue ? 'upToDate' : 'initial', []);\n }\n return undefined;\n }\n static unknown(obs) {\n return new Info(obs, '(unknown)', 'unknown', undefined, 'unknown', []);\n }\n constructor(sourceObj, name, type, value, state, dependencies) {\n this.sourceObj = sourceObj;\n this.name = name;\n this.type = type;\n this.value = value;\n this.state = state;\n this.dependencies = dependencies;\n }\n}\n\nexport { debugGetDependencyGraph };\n//# sourceMappingURL=debugGetDependencyGraph.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { setLogObservableFn } from './logging/logging.js';\nimport { _setDebugGetDependencyGraph } from './observables/baseObservable.js';\nexport { DebugLocation } from './debugLocation.js';\nexport { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter, derivedWithStore } from './observables/derived.js';\nexport { debouncedObservable, debouncedObservableDeprecated, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, mapObservableArrayCached, observableFromPromise, recomputeInitiallyAndOnChange, signalFromObservable, wasEventTriggeredRecently } from './utils/utils.js';\nexport { observableFromEvent, observableFromEventOpts } from './observables/observableFromEvent.js';\nimport { logObservableToConsole } from './logging/consoleObservableLogger.js';\nimport { debugGetDependencyGraph } from './logging/debugGetDependencyGraph.js';\n\n/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n// This is a facade for the observable implementation. Only import from here!\n_setDebugGetDependencyGraph(debugGetDependencyGraph);\nsetLogObservableFn(logObservableToConsole);\n//# sourceMappingURL=index.js.map\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\nimport { transaction } from '../transaction.js';\nimport { derived } from '../observables/derived.js';\nimport { observableValue } from '../observables/observableValue.js';\n\nclass ObservableLazy {\n /**\n * The cached value.\n * Does not force a computation of the value.\n */\n get cachedValue() { return this._value; }\n constructor(_computeValue) {\n this._computeValue = _computeValue;\n this._value = observableValue(this, undefined);\n }\n /**\n * Returns the cached value.\n * Computes the value if the value has not been cached yet.\n */\n getValue() {\n let v = this._value.get();\n if (!v) {\n v = this._computeValue();\n this._value.set(v, undefined);\n }\n return v;\n }\n}\n/**\n * A promise whose state is observable.\n */\nclass ObservablePromise {\n static fromFn(fn) {\n return new ObservablePromise(fn());\n }\n constructor(promise) {\n this._value = observableValue(this, undefined);\n /**\n * The current state of the promise.\n * Is `undefined` if the promise didn't resolve yet.\n */\n this.promiseResult = this._value;\n this.resolvedValue = derived(this, reader => {\n const result = this.promiseResult.read(reader);\n if (!result) {\n return undefined;\n }\n return result.getDataOrThrow();\n });\n this.promise = promise.then(value => {\n transaction(tx => {\n /** @description onPromiseResolved */\n this._value.set(new PromiseResult(value, undefined), tx);\n });\n return value;\n }, error => {\n transaction(tx => {\n /** @description onPromiseRejected */\n this._value.set(new PromiseResult(undefined, error), tx);\n });\n throw error;\n });\n }\n}\nclass PromiseResult {\n constructor(\n /**\n * The value of the resolved promise.\n * Undefined if the promise rejected.\n */\n data, \n /**\n * The error in case of a rejected promise.\n * Undefined if the promise resolved.\n */\n error) {\n this.data = data;\n this.error = error;\n }\n /**\n * Returns the value if the promise resolved, otherwise throws the error.\n */\n getDataOrThrow() {\n if (this.error) {\n throw this.error;\n }\n return this.data;\n }\n}\n/**\n * A lazy promise whose state is observable.\n */\nclass ObservableLazyPromise {\n constructor(_computePromise) {\n this._computePromise = _computePromise;\n this._lazyValue = new ObservableLazy(() => new ObservablePromise(this._computePromise()));\n /**\n * Does not enforce evaluation of the promise compute function.\n * Is undefined if the promise has not been computed yet.\n */\n this.cachedPromiseResult = derived(this, reader => this._lazyValue.cachedValue.read(reader)?.promiseResult.read(reader));\n }\n getPromise() {\n return this._lazyValue.getValue().promise;\n }\n}\n\nexport { ObservableLazy, ObservableLazyPromise, ObservablePromise, PromiseResult };\n//# sourceMappingURL=promise.js.map\n","import { jcsCanonicalize, type Pattern, type Permission } from '@hediet/linkrpc';\nimport type { HubAccessManifestRequest } from '@hediet/linkrpc/hub/common';\nimport type { AccessDirectPermission } from '@hediet/linkrpc-infra/approval';\n\nexport interface ApprovalPresentationLine {\n readonly label?: string;\n readonly text: string;\n readonly tone?: 'normal' | 'muted' | 'warning';\n}\n\nexport interface ApprovalPresentationRequest {\n readonly id: string;\n readonly request: HubAccessManifestRequest;\n readonly sourceServiceId?: string;\n}\n\nexport interface PreparedApprovalPresentation {\n readonly pending: ApprovalPresentationRequest;\n readonly permissions: readonly Permission[];\n readonly resolvedSlot?: {\n readonly serviceId: string;\n readonly satisfiedInterfaces: readonly string[];\n };\n}\n\nexport interface ApprovalPresentation {\n readonly heading: string;\n readonly details: readonly ApprovalPresentationLine[];\n}\n\nexport function createApprovalPresentation(\n item: ApprovalPresentationRequest,\n prepared?: PreparedApprovalPresentation,\n): ApprovalPresentation {\n const request = item.request;\n const details: ApprovalPresentationLine[] = [\n { label: 'Consumer', text: request.consumer.name },\n { label: 'Principal', text: request.consumer.principal, tone: 'muted' },\n ...(request.consumer.origin !== undefined\n ? [{ label: 'Origin', text: request.consumer.origin } satisfies ApprovalPresentationLine]\n : []),\n ...(request.consumer.purpose !== undefined\n ? [{ label: 'Purpose', text: request.consumer.purpose } satisfies ApprovalPresentationLine]\n : []),\n ...(request.reason !== undefined\n ? [{ label: 'Reason', text: request.reason } satisfies ApprovalPresentationLine]\n : []),\n ...(item.sourceServiceId === undefined\n ? []\n : [{\n label: 'Manifest source',\n text: item.sourceServiceId.length === 0 ? '<root>' : item.sourceServiceId,\n } satisfies ApprovalPresentationLine]),\n {\n label: 'Duration',\n text: request.duration ?? 'unspecified',\n tone: durationTone(request.duration),\n },\n { label: 'Request ID', text: item.id, tone: 'muted' },\n ...(prepared?.resolvedSlot === undefined\n ? []\n : [\n {\n label: 'Resolved service',\n text: prepared.resolvedSlot.serviceId,\n tone: 'warning',\n } satisfies ApprovalPresentationLine,\n {\n label: 'Satisfied interfaces',\n text: prepared.resolvedSlot.satisfiedInterfaces.join(', '),\n } satisfies ApprovalPresentationLine,\n ]),\n {\n text: prepared !== undefined\n ? 'Exact authority to be signed'\n : request.kind === 'direct' ? 'Requested authority' : 'Required service shape',\n tone: 'muted',\n },\n ];\n\n const reviewedPermissions = prepared?.pending.request.kind === 'direct'\n ? prepared.pending.request.permissions\n : undefined;\n details.push(...(\n prepared === undefined\n ? authorityLines(request)\n : permissionLines(prepared.permissions, reviewedPermissions)\n ));\n return {\n heading: `${item.id} ${request.kind} ${request.consumer.name}`,\n details,\n };\n}\n\nexport function approvalDetailLines(\n item: ApprovalPresentationRequest,\n prepared?: PreparedApprovalPresentation,\n): readonly ApprovalPresentationLine[] {\n return createApprovalPresentation(item, prepared).details;\n}\n\nfunction authorityLines(\n request: HubAccessManifestRequest,\n): readonly ApprovalPresentationLine[] {\n if (request.kind === 'direct') {\n return permissionLines(request.permissions);\n }\n return [\n ...request.interfaces.map((item) => ({\n text: `• interface ${item.id}${item.required === false ? ' (optional)' : ''}`,\n } satisfies ApprovalPresentationLine)),\n ...request.members.map((item) => ({\n text: `• member ${item.interfaceId}::${patternText(item.member)}`\n + `${item.required === false ? ' (optional)' : ''}`,\n } satisfies ApprovalPresentationLine)),\n ];\n}\n\nfunction permissionLines(\n permissions: readonly Permission[],\n reviewedPermissions?: readonly AccessDirectPermission[],\n): readonly ApprovalPresentationLine[] {\n return permissions.flatMap((permission, index) => {\n const service = patternText(permission.target.serviceId);\n const iface = patternText(permission.target.interfaceId);\n const members = permission.target.members.map(patternText).join(', ');\n const actions = [\n ...(permission.canInvoke === true ? ['invoke'] : []),\n ...(permission.canDelegate === true ? ['delegate'] : []),\n ].join(' + ') || 'none';\n const callIntent = reviewedPermissions?.[index]?.callIntent;\n return [\n {\n text: `• ${service}::${iface} {${members}}`,\n tone: [\n permission.target.serviceId,\n permission.target.interfaceId,\n ...permission.target.members,\n ].some(isBroadPattern)\n ? 'warning' as const\n : 'normal' as const,\n },\n {\n label: ` Actions ${index + 1}`,\n text: actions,\n tone: permission.canDelegate ? 'warning' : 'normal',\n } satisfies ApprovalPresentationLine,\n ...(permission.target.interfaceHash === undefined\n ? []\n : [{\n label: ' Interface hash',\n text: permission.target.interfaceHash,\n } satisfies ApprovalPresentationLine]),\n ...(permission.params === undefined\n ? [{\n label: ' Parameters',\n text: 'any',\n tone: 'warning',\n } satisfies ApprovalPresentationLine]\n : [{\n label: ' Parameters',\n text: jcsCanonicalize(permission.params),\n } satisfies ApprovalPresentationLine]),\n ...(permission.callBind === undefined\n ? []\n : [{\n label: ' Exact-call binding',\n text: jcsCanonicalize(permission.callBind),\n } satisfies ApprovalPresentationLine]),\n ...(callIntent === undefined\n ? []\n : [\n ...(callIntent.summary === undefined\n ? []\n : [{\n label: ' Call summary',\n text: callIntent.summary,\n } satisfies ApprovalPresentationLine]),\n {\n label: ' Call method',\n text: callIntent.method,\n } satisfies ApprovalPresentationLine,\n {\n label: ' Call parameters',\n text: callIntent.params === undefined\n ? '{}'\n : jcsCanonicalize(callIntent.params),\n } satisfies ApprovalPresentationLine,\n ...(callIntent.interfaceHash === undefined\n ? []\n : [{\n label: ' Call interface hash',\n text: callIntent.interfaceHash,\n } satisfies ApprovalPresentationLine]),\n ]),\n ];\n });\n}\n\nfunction patternText(pattern: Pattern | undefined): string {\n if (pattern === undefined) return 'any';\n if ('exact' in pattern) return `exact(${JSON.stringify(pattern.exact)})`;\n if ('prefix' in pattern) return `prefix(${JSON.stringify(pattern.prefix)})`;\n return 'any';\n}\n\nfunction isBroadPattern(pattern: Pattern | undefined): boolean {\n return pattern === undefined || 'prefix' in pattern;\n}\n\nfunction durationTone(\n duration: string | undefined,\n): ApprovalPresentationLine['tone'] {\n return duration === 'persistent' || duration === undefined ? 'warning' : 'normal';\n}\n","import {\n ApprovalClient,\n createHubApprovalClient,\n type ApprovalSnapshot,\n type ApprovalDecisionOutcome,\n type PendingApprovalRequest,\n type ConsentPrompt,\n} from '@hediet/linkrpc-infra/approval';\nimport { createTerminalConsentPrompt } from '@hediet/linkrpc-hub';\nimport { autorun } from '@vscode/observables';\nimport { createApprovalPresentation } from '../approvalPresentation';\nimport { formatJson } from '../output';\n\nexport interface ApprovalSubscription {\n dispose(): void;\n}\n\n/** Terminal prompt and callback adapter for the CLI's approval UI. */\nexport class ApprovalCommandClient extends ApprovalClient {\n public watch(listener: (snapshot: ApprovalSnapshot) => void): ApprovalSubscription {\n return autorun((reader) => listener(this.snapshot.read(reader)));\n }\n\n public override runInteractive(\n signal: AbortSignal,\n prompt: ConsentPrompt = createTerminalConsentPrompt(),\n ): Promise<void> {\n return super.runInteractive(signal, prompt);\n }\n}\n\nexport function createHubApprovalCommandClient(\n ...args: Parameters<typeof createHubApprovalClient>\n): ApprovalCommandClient {\n const client = createHubApprovalClient(...args);\n const runInteractive = client.runInteractive.bind(client);\n return Object.assign(client, {\n watch: (listener: (snapshot: ApprovalSnapshot) => void): ApprovalSubscription =>\n autorun((reader) => listener(client.snapshot.read(reader))),\n runInteractive: (\n signal: AbortSignal,\n prompt: ConsentPrompt = createTerminalConsentPrompt(),\n ): Promise<void> => runInteractive(signal, prompt),\n });\n}\n\nexport function formatApprovalRequests(\n requests: readonly PendingApprovalRequest[],\n principalId: string,\n json = false,\n): string {\n if (json) {\n return formatJson({\n version: 1,\n principal: principalId,\n requests: requests.map(({ id, request }) => ({ id, request })),\n });\n }\n if (requests.length === 0) {\n return `No pending approval requests for ${principalId}.`;\n }\n const lines: string[] = [];\n for (const request of requests) {\n const presentation = createApprovalPresentation(request);\n lines.push(presentation.heading);\n for (const detail of presentation.details) {\n lines.push(` ${detail.label === undefined ? '' : `${detail.label}: `}${detail.text}`);\n }\n }\n return lines.join('\\n');\n}\n\nexport function formatApprovalDecision(\n action: 'approved' | 'denied',\n id: string,\n principalId: string,\n json = false,\n outcome: ApprovalDecisionOutcome = 'applied',\n): string {\n if (json) {\n return formatJson({\n version: 1,\n action,\n id,\n principal: principalId,\n ...(outcome === 'still-pending' ? { requestStillPending: true } : {}),\n });\n }\n return outcome === 'applied'\n ? `${action === 'approved' ? 'Approved' : 'Denied'} ${id}.`\n : `${action === 'approved' ? 'Approval' : 'Denial'} decision accepted for ${id}, `\n + 'but a matching request is still pending; the consumer may have retried.';\n}\n","import type { PrincipalSource, SigningSession } from '@hediet/linkrpc-client-internal';\nimport { formatPrincipalSource } from '@hediet/linkrpc-client-internal';\nimport { formatJson } from '../output';\n\nexport interface CliIdentity {\n readonly principal: string;\n readonly source: PrincipalSource;\n}\n\nexport function cliIdentity(session: SigningSession): CliIdentity {\n return {\n principal: session.principal.id,\n source: session.principalSource,\n };\n}\n\nexport function formatCliIdentity(identity: CliIdentity, json = false): string {\n if (json) {\n return formatJson({\n version: 1,\n principal: identity.principal,\n source: identity.source,\n });\n }\n return [\n formatPrincipalSource(identity.source, identity.principal),\n `principal: ${identity.principal}`,\n ].join('\\n');\n}\n","/**\n * The hub engine now lives in `@hediet/linkrpc-hub` (shared by the CLI, the\n * standalone `linkrpc-hub` server, and the VS Code extension). This module\n * re-exports it for the CLI's existing `./engine/runHub` import sites.\n */\nimport type {\n ListenerInfo,\n RunHubOptions,\n RunningHub,\n} from '@hediet/linkrpc-hub/engine/runHub';\n\nexport type { ListenerInfo, RunHubOptions, RunningHub };\n\nexport async function runHub(options: RunHubOptions): Promise<RunningHub> {\n const engine = await import('@hediet/linkrpc-hub/engine/runHub');\n return engine.runHub(options);\n}\n","/**\n * Render the dynamic \"Method parameters\" block appended to `hub call --help`\n * and `hub notify --help`. Pure: takes a `MethodSchema` (already fetched by\n * the caller) plus the live interface schema for ref resolution, and returns\n * the formatted block. The caller concatenates it after commander's\n * static help text.\n *\n * Param names show up as `--p:<name>`; the type / required-ness / one-line\n * description is derived from the params object's `properties` map.\n *\n * If the method's params schema isn't a plain object schema (e.g. a\n * union, or a top-level array), we render a coarse fallback instead of\n * pretending each branch is its own `--p:` flag.\n */\nimport type {\n MethodSchema,\n LinkRpcInterfaceSchema as SvcInterfaceSchema,\n LinkRpcJsonSchema as SvcJsonSchema,\n} from '@hediet/linkrpc';\n\nexport interface RenderedParamHelp {\n /** Multi-line block, or empty when the method takes no params. */\n readonly text: string;\n /**\n * Param names suitable for completion. Empty when the params descriptor\n * isn't a plain object (no `--p:<name>` flag-name to suggest).\n */\n readonly paramNames: readonly string[];\n}\n\nexport function renderMethodParamHelp(\n method: MethodSchema,\n schema: SvcInterfaceSchema,\n): RenderedParamHelp {\n const resolved = _resolve(method.params, schema.components?.schemas ?? {});\n if (!_isObjectSchema(resolved)) {\n return {\n text:\n `Method parameters (${schema.id}@${schema.hash}):\\n`\n + ` (params is not a plain object — pass with --params <json>)\\n`,\n paramNames: [],\n };\n }\n\n const props = resolved.properties ?? {};\n const required = new Set<string>(resolved.required ?? []);\n const names = Object.keys(props);\n if (names.length === 0) {\n return {\n text:\n `Method parameters (${schema.id}@${schema.hash}):\\n`\n + ` (no parameters)\\n`,\n paramNames: [],\n };\n }\n\n const rows: string[][] = [];\n for (const name of names) {\n const propSchema = _resolve(props[name], schema.components?.schemas ?? {});\n const flag = `--p:${name} <${_typeLabel(propSchema)}>`;\n const reqMark = required.has(name) ? 'required' : 'optional';\n const desc = _oneLineDescription(propSchema);\n rows.push([flag, reqMark, desc]);\n }\n\n const flagCol = Math.max(...rows.map((r) => r[0].length));\n const reqCol = Math.max(...rows.map((r) => r[1].length));\n\n const lines = [`Method parameters (${schema.id}@${schema.hash}):`];\n for (const [flag, req, desc] of rows) {\n const padded = ` ${flag.padEnd(flagCol)} ${req.padEnd(reqCol)}${desc ? ' ' + desc : ''}`;\n lines.push(padded.trimEnd());\n }\n return { text: lines.join('\\n') + '\\n', paramNames: names };\n}\n\nfunction _isObjectSchema(\n s: SvcJsonSchema,\n): s is Extract<SvcJsonSchema, { type: 'object' }> {\n return typeof s === 'object' && s !== null && (s as { type?: string }).type === 'object';\n}\n\nfunction _resolve(\n s: SvcJsonSchema,\n components: Record<string, SvcJsonSchema>,\n): SvcJsonSchema {\n if (typeof s === 'object' && s !== null && '$ref' in s) {\n const ref = (s as { $ref: string }).$ref;\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n if (m) {\n const target = components[m[1]];\n if (target !== undefined) return target;\n }\n }\n return s;\n}\n\nfunction _typeLabel(s: SvcJsonSchema): string {\n if (s === true) return 'any';\n if (s === false) return 'never';\n const obj = s as unknown as Record<string, unknown>;\n\n if (typeof obj.type === 'string') {\n if (obj.type === 'array') {\n const items = obj.items as SvcJsonSchema | undefined;\n if (items !== undefined) return `${_typeLabel(items)}[]`;\n return 'array';\n }\n const fmt = obj.format !== undefined ? `:${obj.format}` : '';\n return `${obj.type as string}${fmt}`;\n }\n if (Array.isArray(obj.enum)) {\n return `enum(${obj.enum.map((v) => JSON.stringify(v)).join('|')})`;\n }\n if ('const' in obj) {\n return JSON.stringify(obj.const);\n }\n if (Array.isArray(obj.oneOf) || Array.isArray(obj.anyOf)) {\n return 'union';\n }\n if ('$ref' in obj) {\n const ref = obj.$ref as string;\n const m = /^#\\/components\\/schemas\\/(.+)$/.exec(ref);\n return m ? m[1] : 'ref';\n }\n return 'value';\n}\n\nfunction _oneLineDescription(propSchema: SvcJsonSchema): string {\n const obj = propSchema as unknown as Record<string, unknown>;\n const raw = (obj.description as string | undefined) ?? (obj.title as string | undefined) ?? '';\n if (!raw) return '';\n const firstLine = raw.split(/\\r?\\n/, 1)[0];\n return firstLine.length > 80 ? firstLine.slice(0, 77) + '…' : firstLine;\n}\n","/**\n * Pre-processor for `--p:<name>[=<value>]` shortcuts on the CLI. Rewrites\n * them to commander-friendly `--param <name>=<value>` pairs *before*\n * commander sees the argv, so we don't have to teach commander about them\n * (which is awkward given they're dynamic per-method).\n *\n * Forms accepted:\n * --p:to=a@b.c single token, kept verbatim → `--param to=a@b.c`\n * --p:to a@b.c two tokens, joined → `--param to=a@b.c`\n * --p:dryRun boolean shortcut (no value) → `--param dryRun=true`\n *\n * Nested keys keep working through the existing `mergeParams` dot-path\n * support: `--p:user.name=alice` → `--param user.name=alice`.\n *\n * Anything past a literal `--` token is left alone (POSIX end-of-options).\n * Tokens that look like the start of the next flag (e.g. `--p:dryRun\n * --verbose`) are treated as the \"no value\" form so `--verbose` keeps its\n * intended role.\n */\n\nconst FLAG_PREFIX = '--p:';\n\n/**\n * Transform `argv`, expanding every `--p:<name>` token to `--param key=value`.\n * Non-matching tokens pass through unchanged. Returns a new array; never\n * mutates the input.\n */\nexport function rewriteParamShortcuts(argv: readonly string[]): string[] {\n return rewriteCapabilityShortcuts(expandParamShortcuts(argv));\n}\n\nfunction expandParamShortcuts(argv: readonly string[]): string[] {\n const out: string[] = [];\n let stopExpanding = false;\n\n for (let i = 0; i < argv.length; i++) {\n const tok = argv[i];\n\n if (!stopExpanding && tok === '--') {\n stopExpanding = true;\n out.push(tok);\n continue;\n }\n if (stopExpanding || !tok.startsWith(FLAG_PREFIX)) {\n out.push(tok);\n continue;\n }\n\n const rest = tok.slice(FLAG_PREFIX.length);\n if (rest.length === 0) {\n // Bare `--p:` is meaningless; leave it for commander to error on.\n out.push(tok);\n continue;\n }\n\n const eq = rest.indexOf('=');\n if (eq >= 0) {\n const name = rest.slice(0, eq);\n const value = rest.slice(eq + 1);\n if (name.length === 0) {\n out.push(tok); // malformed `--p:=value`; let commander complain\n continue;\n }\n out.push('--param', `${name}=${value}`);\n continue;\n }\n\n // `--p:name` with no inline value. Use the next token unless it looks\n // like another flag (then assume boolean shortcut).\n const name = rest;\n const peek = argv[i + 1];\n if (peek === undefined || peek.startsWith('-')) {\n out.push('--param', `${name}=true`);\n continue;\n }\n out.push('--param', `${name}=${peek}`);\n i += 1;\n }\n return out;\n}\n\nconst CAPABILITY_SHORTCUTS = new Map([\n ['--cap:allow-prefix', 'prefix'],\n ['--cap:allow-any', 'any'],\n ['--cap:allow-enum', 'enum'],\n ['--cap:allow-subset', 'subsetOf'],\n]);\n\nfunction rewriteCapabilityShortcuts(argv: readonly string[]): string[] {\n const out: string[] = [];\n const constrained = new Set<string>();\n const assigned = new Set<string>();\n let precedingParam: string | undefined;\n for (let i = 0; i < argv.length; i++) {\n const token = argv[i];\n if (token === '--') {\n out.push(...argv.slice(i));\n break;\n }\n const eq = token.indexOf('=');\n const flag = eq < 0 ? token : token.slice(0, eq);\n const matcher = CAPABILITY_SHORTCUTS.get(flag);\n if (matcher !== undefined) {\n if (precedingParam === undefined) {\n throw new Error(`${flag} must immediately follow a --param or --p:<name> assignment.`);\n }\n if (precedingParam.includes('.')) throw new Error(`${flag} only supports top-level parameter names.`);\n if (constrained.has(precedingParam)) throw new Error(`Duplicate --cap:allow-param for ${precedingParam}.`);\n let value: unknown = true;\n if (matcher === 'any') {\n if (eq >= 0) throw new Error('--cap:allow-any takes no value.');\n } else {\n const raw = eq >= 0 ? token.slice(eq + 1) : argv[++i];\n if (raw === undefined || (eq < 0 && raw.startsWith('--'))) {\n throw new Error(`${flag} requires a value.`);\n }\n if (matcher === 'prefix') {\n value = raw;\n } else {\n try { value = JSON.parse(raw); }\n catch { throw new Error(`${flag} requires a JSON array.`); }\n if (!Array.isArray(value)\n || (matcher === 'enum' && value.length === 0)\n || (matcher === 'subsetOf' && !value.every(item => typeof item === 'string'))) {\n throw new Error(`${flag} requires ${matcher === 'enum' ? 'a non-empty JSON array' : 'a JSON string array'}.`);\n }\n }\n }\n constrained.add(precedingParam);\n out.push('--cap:allow-param', `${precedingParam}=${JSON.stringify({ [matcher]: value })}`);\n continue;\n }\n if (flag === '--param' || flag === '--cap:allow-param') {\n const values: string[] = [];\n if (eq >= 0) {\n values.push(token.slice(eq + 1));\n out.push(token);\n } else {\n out.push(token);\n while (argv[i + 1] !== undefined && !argv[i + 1].startsWith('-')) {\n const value = argv[++i];\n values.push(value);\n out.push(value);\n }\n }\n precedingParam = undefined;\n for (const value of values) {\n const assignment = value.indexOf('=');\n if (assignment <= 0) continue;\n const key = value.slice(0, assignment);\n if (constrained.has(key) && (flag === '--cap:allow-param' || assigned.has(key))) {\n throw new Error(flag === '--param'\n ? `Cannot reassign parameter ${key} after an explicit capability constraint.`\n : `Duplicate --cap:allow-param for ${key}.`);\n }\n if (flag === '--cap:allow-param') constrained.add(key);\n else {\n assigned.add(key);\n precedingParam = key;\n }\n }\n continue;\n }\n precedingParam = undefined;\n out.push(token);\n }\n return out;\n}\n","export function safeTerminalText(text: string): string {\n let result = '';\n for (const character of text) {\n result += /^[\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]$/u.test(character)\n ? `\\\\u{${character.codePointAt(0)!.toString(16).padStart(4, '0')}}`\n : character;\n }\n return result;\n}\n","import { safeTerminalText } from \"../../ui/terminalText\";\nimport type { GraphTreeLine } from \"./inspectGraphModel\";\nimport type { GraphExplorerModel } from \"./inspectGraphView\";\n\nexport interface GraphFrameOptions {\n readonly title: string;\n readonly params: string;\n readonly version?: number;\n readonly columns: number;\n readonly rows: number;\n readonly scrollTop: number;\n readonly revealSelection?: boolean;\n readonly showObjectIds?: boolean;\n readonly status?: string;\n readonly error?: boolean;\n readonly phase?: string;\n}\n\nexport interface GraphFrameRow {\n readonly text: string;\n readonly style: \"header\" | \"muted\" | \"reference\" | \"value\" | \"selected\" | \"error\";\n readonly key?: string;\n}\n\nexport const graphChromeRows = 6;\n\n/** Presentation only: no terminal ownership, input handling or mutable model state. */\nexport function createGraphFrame(model: GraphExplorerModel | undefined, options: GraphFrameOptions): {\n readonly rows: readonly GraphFrameRow[];\n readonly scrollTop: number;\n} {\n const capacity = Math.max(0, options.rows - graphChromeRows);\n const lines = model?.lines ?? [];\n const selected = model?.selectedIndex ?? 0;\n const scrollTop = clampGraphScroll(lines.length, selected, options.scrollTop, capacity, options.revealSelection !== false);\n const separator = \" \" + \"─\".repeat(Math.max(0, options.columns - 2));\n const rows: GraphFrameRow[] = [\n { text: ` GRAPH EXPLORER ${options.phase ?? (options.version === undefined ? \"CONNECTING\" : `LIVE v${options.version}`)}`, style: \"header\" },\n { text: ` ${options.title} ${options.params}`, style: \"muted\" },\n { text: separator, style: \"muted\" },\n ];\n const labels = formatGraphTreeRows(lines, options.showObjectIds === true);\n for (let offset = 0; offset < capacity; offset++) {\n const index = scrollTop + offset;\n const line = lines[index];\n rows.push({\n text: line ? \" \" + labels[index] : \"\",\n key: line?.key,\n style: line && index === selected ? \"selected\" : line?.ref ? \"reference\" : \"value\",\n });\n }\n rows.push(\n { text: separator, style: \"muted\" },\n { text: ` ${options.status ?? (model ? model.selectedKey : \"Waiting for first root…\")}`, style: options.error ? \"error\" : \"muted\" },\n { text: ` ${lines.length === 0 ? 0 : selected + 1}/${lines.length} ${model?.cachedObjects ?? 0} cached objects`\n + ` IDs:${options.showObjectIds ? \"on\" : \"off\"}`, style: \"reference\" },\n );\n return { rows: rows.slice(0, Math.max(0, options.rows)), scrollTop };\n}\n\nexport function clampGraphScroll(count: number, selected: number, top: number, capacity: number, reveal = true): number {\n return Math.max(0, Math.min(\n !reveal || capacity === 0 ? top : selected < top ? selected\n : selected >= top + capacity ? selected - capacity + 1 : top,\n Math.max(0, count - capacity),\n ));\n}\n\n/** Relative labels and branches are computed before slicing, so scrolled rows retain ancestry. */\nexport function formatGraphTreeRows(lines: readonly GraphTreeLine[], showObjectIds: boolean): readonly string[] {\n const ancestors: GraphTreeLine[] = [];\n const ancestorIndices: number[] = [];\n const nextSiblings = new Map<number, number>();\n const hasSibling: boolean[] = [];\n for (let index = lines.length - 1; index >= 0; index--) {\n const depth = lines[index]!.depth;\n hasSibling[index] = nextSiblings.has(depth);\n for (const deeper of nextSiblings.keys()) if (deeper > depth) nextSiblings.delete(deeper);\n nextSiblings.set(depth, index);\n }\n return lines.map((line, index) => {\n ancestors.length = line.depth;\n ancestorIndices.length = line.depth;\n const parent = ancestors[line.depth - 1];\n const label = line.key === \"$\" ? \"root\" : line.key.slice((parent?.key ?? \"$\").length).replace(/^\\./, \"\");\n ancestors[line.depth] = line;\n ancestorIndices[line.depth] = index;\n const marker = line.targetKey !== undefined ? \"↪\" : line.expandable ? line.expanded && line.loaded ? \"▾\" : \"▸\" : \" \";\n const content = line.ref === undefined ? line.text.slice(line.key.length).replace(/^ = /, \" \")\n : ` ${line.ref.kind}${showObjectIds ? `:${line.ref.id}` : \"\"}`\n + (line.summary === undefined ? \"\" : ` ${line.summary}`)\n + (line.description === undefined ? \"\" : ` — ${line.description}`)\n + (line.loaded ? \"\" : \" [fetch on expand]\")\n + (line.targetKey === undefined ? \"\" : ` [link to ${line.targetKey}]`);\n const branch = line.depth === 0 ? \"\" : ancestorIndices.slice(1, line.depth)\n .map(ancestor => hasSibling[ancestor] ? \"│ \" : \" \").join(\"\")\n + (hasSibling[index] ? \"├─ \" : \"└─ \");\n return `${branch}${marker} ${label}${content}`;\n });\n}\n\nexport function anchorGraphScrollTop(previous: readonly GraphTreeLine[], next: readonly GraphTreeLine[], scrollTop: number): number {\n const indices = new Map(next.map((line, index) => [line.key, index]));\n for (let distance = 0; distance < previous.length; distance++) {\n for (const index of distance === 0 ? [scrollTop] : [scrollTop + distance, scrollTop - distance]) {\n const line = previous[index];\n const position = line === undefined ? undefined : indices.get(line.key);\n if (position !== undefined) return position;\n }\n }\n return scrollTop;\n}\n\nconst segments = new Intl.Segmenter(undefined, { granularity: \"grapheme\" });\nfunction cellWidth(text: string): number {\n const code = text.codePointAt(0)!;\n if (/^\\p{Mark}+$/u.test(text)) return 0;\n if (/[\\p{Extended_Pictographic}\\p{Regional_Indicator}]/u.test(text)) return 2;\n return code >= 0x1100 && (code <= 0x115f || code === 0x2329 || code === 0x232a\n || code >= 0x2e80 && code <= 0xa4cf && code !== 0x303f\n || code >= 0xac00 && code <= 0xd7a3 || code >= 0xf900 && code <= 0xfaff\n || code >= 0xfe10 && code <= 0xfe19 || code >= 0xfe30 && code <= 0xfe6f\n || code >= 0xff00 && code <= 0xff60 || code >= 0xffe0 && code <= 0xffe6\n || code >= 0x20000 && code <= 0x3fffd) ? 2 : 1;\n}\n\n/** Sanitize first, then clip/pad by terminal cells so Ink never wraps a frame row. */\nexport function graphFrameText(text: string, columns: number, pad = false): string {\n const width = Math.max(0, columns);\n const characters = [...segments.segment(safeTerminalText(text))].map(value => value.segment);\n let result = \"\", used = 0;\n const total = characters.reduce((sum, value) => sum + cellWidth(value), 0);\n const clipped = total > width;\n for (const character of characters) {\n const size = cellWidth(character);\n if (used + size > width - (clipped ? 1 : 0)) break;\n used += size;\n result += character;\n }\n if (clipped && width > 0) { result += \"…\"; used++; }\n return result + (pad ? \" \".repeat(Math.max(0, width - used)) : \"\");\n}\n","import { emitKeypressEvents, type Key } from \"node:readline\";\nimport { stdin, stdout } from \"node:process\";\nimport { autorun, observableValue } from \"@vscode/observables\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\nimport type { GraphTreeLine } from \"./inspectGraphModel\";\nimport type { GraphExplorerModel } from \"./inspectGraphView\";\nimport type { GraphTimings } from \"./inspectGraphTiming\";\nimport { anchorGraphScrollTop, formatGraphTreeRows } from \"./graphFrame\";\nexport { anchorGraphScrollTop } from \"./graphFrame\";\n\nexport class GraphTerminal {\n private readonly _view = observableValue<{ model: GraphExplorerModel; version: number } | undefined>(this, undefined);\n private readonly _busy = observableValue(this, false);\n private readonly _updating = observableValue(this, false);\n private readonly _error = observableValue<string | undefined>(this, undefined);\n private readonly _revision = observableValue(this, 0);\n private readonly _scrollTop = observableValue(this, 0);\n private readonly _showObjectIds = observableValue(this, false);\n private _renderedLines: readonly GraphTreeLine[] = [];\n private _renderedModel: GraphExplorerModel | undefined;\n private _revealSelection = true;\n private readonly _raw = stdin.isRaw;\n private readonly _wasFlowing = stdin.readableFlowing === true;\n private readonly _rendering: { dispose(): void };\n private _action: Promise<void> = Promise.resolve();\n private _disposed = false;\n private readonly _resolve: () => void;\n private readonly _reject: (error: unknown) => void;\n public readonly result: Promise<void>;\n\n public constructor(\n private readonly _title: string,\n private readonly _params: string,\n private readonly _repaint: (text: string) => void = text => { stdout.write(text); },\n private readonly _timings?: GraphTimings,\n ) {\n let resolve!: () => void;\n let reject!: (error: unknown) => void;\n this.result = new Promise<void>((res, rej) => { resolve = res; reject = rej; });\n this._resolve = resolve;\n this._reject = reject;\n stdout.write(\"\\x1b[?1049h\\x1b[?25l\\x1b[?7l\");\n emitKeypressEvents(stdin);\n stdin.setRawMode(true);\n stdin.resume();\n stdin.on(\"keypress\", this._onKey);\n stdout.on(\"resize\", this._invalidate);\n this._rendering = autorun(reader => {\n const view = this._view.read(reader);\n const busy = this._busy.read(reader);\n const updating = this._updating.read(reader);\n const error = this._error.read(reader);\n const showObjectIds = this._showObjectIds.read(reader);\n this._revision.read(reader);\n const model = view?.model;\n const lines = model?.lines ?? [];\n const scrollTop = model !== this._renderedModel\n ? anchorGraphScrollTop(this._renderedLines, lines, this._scrollTop.get())\n : this._scrollTop.get();\n const render = () => renderGraphScreen(model, {\n title: this._title,\n params: this._params,\n version: view?.version,\n columns: stdout.columns || 80,\n rows: stdout.rows || 24,\n scrollTop,\n revealSelection: this._revealSelection,\n showObjectIds,\n status: error ?? (updating ? \"Refreshing root...\" : busy ? \"Loading object...\" : undefined),\n error: error !== undefined,\n });\n const frame = this._timings?.measureSync(\"screen\", render, { version: view?.version ?? 0 }) ?? render();\n this._scrollTop.set(frame.scrollTop, undefined);\n this._renderedLines = lines;\n this._renderedModel = model;\n this._repaint(frame.text);\n });\n }\n\n public async beginUpdate(): Promise<void> {\n this._updating.set(true, undefined);\n await this._action;\n }\n\n public async finishUpdate(model: GraphExplorerModel, version: number, signal?: AbortSignal): Promise<void> {\n while (!this._disposed) {\n await this._action;\n signal?.throwIfAborted();\n const source = this._view.get()?.model;\n const paths = source?.expandedPaths;\n await model.restoreExpanded(signal, source);\n signal?.throwIfAborted();\n if (this._busy.get() || source?.expandedPaths !== paths) continue;\n if (source !== undefined) {\n const selected = source.selectedKey;\n model.select(Math.max(0, model.lines.findIndex(line => line.key === selected)));\n }\n this.update(model, version);\n return;\n }\n }\n\n public update(model: GraphExplorerModel, version: number): void {\n if (this._disposed) return;\n this._revealSelection = this._view.get() === undefined;\n this._view.set({ model, version }, undefined);\n this._updating.set(false, undefined);\n }\n\n public dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._rendering.dispose();\n stdin.off(\"keypress\", this._onKey);\n stdout.off(\"resize\", this._invalidate);\n stdin.setRawMode(this._raw ?? false);\n if (!this._wasFlowing) stdin.pause();\n stdout.write(\"\\x1b[0m\\x1b[?7h\\x1b[?25h\\x1b[?1049l\");\n this._resolve();\n }\n\n private readonly _invalidate = (): void => {\n this._revision.set(this._revision.get() + 1, undefined);\n };\n\n private readonly _onKey = (text: string, key: Key): void => {\n if (text === \"q\" || key.name === \"escape\" || (key.ctrl && key.name === \"c\")) {\n this.dispose();\n return;\n }\n if (this._disposed) return;\n if (text === \"i\" && !key.ctrl && !key.meta) {\n this._showObjectIds.set(!this._showObjectIds.get(), undefined);\n return;\n }\n const expands = key.name === \"right\" || key.name === \"return\" || text === \"l\" || text === \" \";\n if (this._busy.get() && expands) return;\n const action = this._handleKey(text, key).catch(error => {\n this._reject(error);\n this.dispose();\n });\n if (expands) this._action = action;\n };\n\n private async _handleKey(text: string, key: Key): Promise<void> {\n const model = this._view.get()?.model;\n if (model === undefined) return;\n this._revealSelection = true;\n this._error.set(undefined, undefined);\n const page = Math.max(1, (stdout.rows || 24) - 7);\n if (key.name === \"down\" || text === \"j\") model.move(1);\n else if (key.name === \"up\" || text === \"k\") model.move(-1);\n else if (key.name === \"pagedown\") model.move(page);\n else if (key.name === \"pageup\") model.move(-page);\n else if (key.name === \"home\" || text === \"g\") model.select(0);\n else if (key.name === \"end\" || text === \"G\") model.select(model.lines.length - 1);\n else if (key.name === \"left\" || text === \"h\") model.collapseSelected();\n else if (key.name === \"right\" || key.name === \"return\" || text === \"l\" || text === \" \") {\n this._busy.set(true, undefined);\n try {\n await model.expandSelected();\n } catch (error) {\n this._error.set(error instanceof Error ? error.message : String(error), undefined);\n } finally {\n this._busy.set(false, undefined);\n }\n }\n this._invalidate();\n }\n}\n\nexport interface GraphScreenOptions {\n readonly title: string;\n readonly params: string;\n readonly version?: number;\n readonly columns: number;\n readonly rows: number;\n readonly scrollTop: number;\n readonly revealSelection?: boolean;\n readonly showObjectIds?: boolean;\n readonly status?: string;\n readonly error?: boolean;\n}\n\nexport function renderGraphScreen(\n model: GraphExplorerModel | undefined,\n options: GraphScreenOptions,\n): { readonly text: string; readonly scrollTop: number } {\n const width = Math.max(1, options.columns - 1);\n const height = Math.max(1, options.rows);\n const capacity = Math.max(1, height - 7);\n const lines = model?.lines ?? [];\n const selected = model?.selectedIndex ?? 0;\n const scrollTop = Math.max(0, Math.min(\n options.revealSelection === false ? options.scrollTop\n : selected < options.scrollTop ? selected\n : selected >= options.scrollTop + capacity ? selected - capacity + 1 : options.scrollTop,\n Math.max(0, lines.length - capacity),\n ));\n const frame: string[] = [];\n const row = (text: string, style = \"\\x1b[37m\"): void => {\n frame.push(`${style}${clip(text, width)}\\x1b[K\\x1b[0m`);\n };\n row(` GRAPH EXPLORER ${options.version === undefined ? \"CONNECTING\" : `LIVE v${options.version}`}`, \"\\x1b[1;36m\");\n row(` ${options.title} ${options.params}`, \"\\x1b[90m\");\n row(\" \" + \"\\u2500\".repeat(Math.max(0, width - 2)), \"\\x1b[90m\");\n const labels = formatGraphTreeRows(lines, options.showObjectIds === true);\n for (let offset = 0; offset < capacity; offset++) {\n const index = scrollTop + offset;\n row(index < lines.length ? \" \" + labels[index] : \"\",\n index === selected && lines.length > 0 ? \"\\x1b[1;30;46m\"\n : lines[index]?.ref === undefined ? \"\\x1b[37m\" : \"\\x1b[36m\");\n }\n row(\" \" + \"\\u2500\".repeat(Math.max(0, width - 2)), \"\\x1b[90m\");\n row(` ${options.status ?? (model === undefined ? \"Waiting for first root...\" : model.selectedKey)}`,\n options.error ? \"\\x1b[31m\" : \"\\x1b[90m\");\n row(` ${lines.length === 0 ? 0 : selected + 1}/${lines.length} ${model?.cachedObjects ?? 0} cached objects`\n + ` \\u2191\\u2193 move \\u2192/Enter open \\u2190 close i IDs:${options.showObjectIds ? \"on\" : \"off\"} q quit`, \"\\x1b[36m\");\n return {\n text: frame.slice(0, height).map((line, index) => `\\x1b[${index + 1};1H${line}`).join(\"\") + \"\\x1b[J\",\n scrollTop,\n };\n}\n\nfunction clip(text: string, width: number): string {\n const characters = [...safeTerminalText(text)];\n return characters.length <= width ? characters.join(\"\")\n : characters.slice(0, Math.max(0, width - 1)).join(\"\") + \"\\u2026\";\n}\n","export interface GraphTiming {\n readonly phase: string;\n readonly wallMs: number;\n readonly cpuUserMs: number;\n readonly cpuSystemMs: number;\n readonly ok: boolean;\n readonly detail: Readonly<Record<string, number>>;\n}\n\nexport class GraphTimings {\n public constructor(private readonly _emit: (timing: GraphTiming) => void) {}\n\n public measureSync<T>(phase: string, operation: () => T, detail: GraphTiming[\"detail\"] = {}): T {\n const finish = this._start(phase, detail);\n let ok = false;\n try {\n const result = operation();\n ok = true;\n return result;\n } finally {\n finish(ok);\n }\n }\n\n public async measureAsync<T>(phase: string, operation: () => Promise<T>, detail: GraphTiming[\"detail\"] = {}): Promise<T> {\n const finish = this._start(phase, detail);\n let ok = false;\n try {\n const result = await operation();\n ok = true;\n return result;\n } finally {\n finish(ok);\n }\n }\n\n private _start(phase: string, detail: GraphTiming[\"detail\"]): (ok: boolean) => void {\n const start = performance.now();\n const cpu = process.cpuUsage();\n return ok => {\n const elapsedCpu = process.cpuUsage(cpu);\n this._emit({\n phase,\n wallMs: performance.now() - start,\n cpuUserMs: elapsedCpu.user / 1000,\n cpuSystemMs: elapsedCpu.system / 1000,\n ok,\n detail,\n });\n };\n }\n}\n","import type {\n JsonValue,\n} from \"@hediet/linkrpc\";\nimport type {\n GraphBatchRequest as LinkRpcGraphBatchRequest,\n GraphBatchResult as LinkRpcGraphBatchResult,\n GraphHave as LinkRpcGraphHave,\n GraphNeed as LinkRpcGraphNeed,\n GraphObject as LinkRpcGraphObject,\n GraphRef,\n GraphLimits,\n MissingGraphObject,\n} from \"@hediet/linkrpc-infra/graph\";\nimport { evaluateGraphPresentation, isGraphRef, standardGraphRuntimeOptions, type GraphPresentation } from \"@hediet/linkrpc-infra/graph\";\nimport type { GraphTimings } from \"./inspectGraphTiming\";\n\nexport type GraphBatchRequest = LinkRpcGraphBatchRequest<GraphRef>;\nexport type GraphBatchResult = LinkRpcGraphBatchResult<GraphRef, JsonValue>;\nexport type GraphHave = LinkRpcGraphHave<GraphRef>;\nexport type GraphNeed = LinkRpcGraphNeed<GraphRef>;\nexport type GraphObject = LinkRpcGraphObject<GraphRef, JsonValue>;\nexport type { GraphRef };\n\nexport type GraphBatchFetch = (\n request: GraphBatchRequest,\n signal: AbortSignal,\n) => Promise<unknown>;\n\nexport interface GraphFetchOptions {\n readonly timings?: GraphTimings;\n readonly signal?: AbortSignal;\n readonly maxObjects?: number;\n readonly maxBytes?: number;\n readonly maxRounds?: number;\n readonly timeoutMs?: number;\n}\n\nexport class GraphObjectCache {\n private readonly _objects = new Map<string, GraphObject>();\n\n public get size(): number {\n return this._objects.size;\n }\n\n public get(ref: GraphRef): GraphObject | undefined {\n return this._objects.get(graphRefKey(ref));\n }\n\n public has(ref: GraphRef): boolean {\n return this._objects.has(graphRefKey(ref));\n }\n\n public put(objects: readonly GraphObject[]): void {\n for (const object of objects) {\n const key = graphRefKey(object.ref);\n const previous = this._objects.get(key);\n if (previous !== undefined && !jsonEqual(previous.value, object.value)) {\n throw new Error(`Graph server returned conflicting values for ${formatGraphRef(object.ref)}`);\n }\n this._objects.set(key, object);\n }\n }\n\n public have(): readonly GraphHave[] {\n return [...this._objects.values()]\n .map(({ ref }) => ({ ref, coverage: \"object\" as const }))\n .sort((a, b) => graphRefKey(a.ref).localeCompare(graphRefKey(b.ref)));\n }\n}\n\nexport class GraphLoader {\n private readonly _limits: GraphLimits;\n private readonly _maxRounds: number;\n private readonly _timeoutMs: number;\n private readonly _signal: AbortSignal | undefined;\n private readonly _timings: GraphTimings | undefined;\n\n public constructor(\n private readonly _fetch: GraphBatchFetch,\n public readonly cache = new GraphObjectCache(),\n options: GraphFetchOptions = {},\n ) {\n this._signal = options.signal;\n this._timings = options.timings;\n this._limits = {\n maxObjects: options.maxObjects ?? 256,\n maxBytes: options.maxBytes ?? 1_048_576,\n };\n this._maxRounds = options.maxRounds ?? 32;\n this._timeoutMs = options.timeoutMs ?? 5_000;\n if (!Number.isInteger(this._limits.maxObjects) || this._limits.maxObjects <= 0) {\n throw new Error(\"maxObjects must be a positive integer\");\n }\n if (!Number.isInteger(this._limits.maxBytes) || this._limits.maxBytes <= 0) {\n throw new Error(\"maxBytes must be a positive integer\");\n }\n if (!Number.isInteger(this._maxRounds) || this._maxRounds <= 0) {\n throw new Error(\"maxRounds must be a positive integer\");\n }\n if (!Number.isInteger(this._timeoutMs) || this._timeoutMs <= 0) {\n throw new Error(\"timeoutMs must be a positive integer\");\n }\n }\n\n public async load(needs: readonly GraphNeed[]): Promise<void> {\n const normalizedNeeds = normalizeNeeds(needs);\n const objectOnly = normalizedNeeds.every(need => need.paths.every(path => path === \"/\"));\n for (let round = 0; ; round++) {\n this._signal?.throwIfAborted();\n const pendingNeeds = objectOnly\n ? normalizedNeeds.filter(need => !this.cache.has(need.ref))\n : normalizedNeeds;\n if (pendingNeeds.length === 0) return;\n if (round >= this._maxRounds) {\n throw new Error(\n `Graph fetch did not converge after ${this._maxRounds} rounds; `\n + `${normalizedNeeds.length} need(s) remain`,\n );\n }\n const before = this.cache.size;\n const fetch = () => withTimeout(\n (signal) => this._fetch({\n needs: pendingNeeds,\n // Object-only reads cannot encounter cached descendants.\n have: objectOnly ? [] : this.cache.have(),\n limits: this._limits,\n }, signal),\n this._timeoutMs,\n \"graph batch fetch\",\n this._signal,\n );\n const raw = await (this._timings?.measureAsync(\"fetch\", fetch, { needs: pendingNeeds.length, round }) ?? fetch());\n const processResult = () => {\n const result = parseGraphBatchResult(raw);\n assertNoMissing(result.missing);\n this.cache.put(result.objects);\n return result;\n };\n const result = this._timings?.measureSync(\"cache\", processResult) ?? processResult();\n if (result.complete) return;\n if (this.cache.size === before) {\n throw new Error(\n \"Graph server returned an incomplete batch without progress\",\n );\n }\n }\n }\n}\n\nexport interface GraphTreeLine {\n readonly key: string;\n readonly depth: number;\n readonly text: string;\n readonly ref?: GraphRef;\n readonly expandable: boolean;\n readonly expanded?: boolean;\n readonly loaded?: boolean;\n readonly targetKey?: string;\n readonly summary?: string;\n readonly description?: string;\n readonly presentationPending?: readonly GraphRef[];\n readonly selector?: string;\n}\n\nexport function createGraphTree(\n root: GraphRef,\n cache: GraphObjectCache,\n expanded: ReadonlySet<string>,\n maxDepth = Number.POSITIVE_INFINITY,\n presentation?: GraphPresentation,\n): readonly GraphTreeLine[] {\n const lines: GraphTreeLine[] = [];\n const firstPaths = new Map<string, string>();\n appendRef(root, \"$\", 0, new Set(), lines, firstPaths, cache, expanded, maxDepth, []);\n if (presentation === undefined) return lines;\n return lines.map(line => {\n if (line.ref === undefined || !Object.hasOwn(presentation.rules, line.ref.kind)) return line;\n const result = evaluateGraphPresentation(line.ref, presentation, ref => cache.get(ref));\n return { ...line, summary: result.label, description: result.secondary, presentationPending: result.pending };\n });\n}\n\nexport function graphRefsInValue(value: JsonValue): readonly GraphRef[] {\n const refs = new Map<string, GraphRef>();\n visitValue(value, (ref) => refs.set(graphRefKey(ref), ref));\n return [...refs.values()];\n}\n\nexport const graphRefKey = standardGraphRuntimeOptions.refKey;\n\nexport function formatGraphRef(ref: GraphRef): string {\n return `${ref.kind}:${ref.id}`;\n}\n\nexport function parseGraphRef(value: unknown, location = \"graph ref\"): GraphRef {\n if (!isGraphRef(value)) throw new Error(`${location} must contain exactly string kind and id fields`);\n return value;\n}\n\nexport function parseGraphBatchResult(value: unknown): GraphBatchResult {\n const record = asRecord(value, \"graph batch result\");\n if (!Array.isArray(record.objects)) {\n throw new Error(\"graph batch result.objects must be an array\");\n }\n if (!Array.isArray(record.missing)) {\n throw new Error(\"graph batch result.missing must be an array\");\n }\n if (typeof record.complete !== \"boolean\") {\n throw new Error(\"graph batch result.complete must be a boolean\");\n }\n const objects = record.objects.map((item, index): GraphObject => {\n const object = asRecord(item, `graph batch result.objects[${index}]`);\n if (!Object.hasOwn(object, \"value\")) {\n throw new Error(`graph batch result.objects[${index}].value is required`);\n }\n assertJsonValue(object.value, `graph batch result.objects[${index}].value`);\n return {\n ref: parseGraphRef(object.ref, `graph batch result.objects[${index}].ref`),\n value: object.value,\n };\n });\n const missing = record.missing.map((item, index) =>\n parseMissing(item, `graph batch result.missing[${index}]`));\n return { objects, missing, complete: record.complete };\n}\n\nfunction parseGraphNeed(value: unknown, location: string): GraphNeed {\n const record = asRecord(value, location);\n if (!Array.isArray(record.paths)) {\n throw new Error(`${location}.paths must be an array`);\n }\n const paths = record.paths.map((path, pathIndex) => {\n if (typeof path !== \"string\" || !path.startsWith(\"/\")) {\n throw new Error(`${location}.paths[${pathIndex}] must be a JSON pointer string`);\n }\n return path;\n });\n return { ref: parseGraphRef(record.ref, `${location}.ref`), paths };\n}\n\nfunction normalizeNeeds(needs: readonly GraphNeed[]): readonly GraphNeed[] {\n const result = new Map<string, { ref: GraphRef; paths: Set<string> }>();\n for (const need of needs) {\n const key = graphRefKey(need.ref);\n let entry = result.get(key);\n if (entry === undefined) {\n entry = { ref: need.ref, paths: new Set() };\n result.set(key, entry);\n }\n for (const path of need.paths) entry.paths.add(path);\n }\n return [...result.values()].map(({ ref, paths }) => ({ ref, paths: [...paths] }));\n}\n\nfunction parseMissing(value: unknown, location: string): MissingGraphObject<GraphRef> {\n const record = asRecord(value, location);\n const reasons = new Set([\"missing\", \"expired\", \"forbidden\", \"oversized\"]);\n if (typeof record.reason !== \"string\" || !reasons.has(record.reason)) {\n throw new Error(`${location}.reason is unsupported`);\n }\n if (record.detail !== undefined && typeof record.detail !== \"string\") {\n throw new Error(`${location}.detail must be a string when present`);\n }\n return {\n ref: parseGraphRef(record.ref, `${location}.ref`),\n reason: record.reason as MissingGraphObject<GraphRef>[\"reason\"],\n ...(record.detail === undefined ? {} : { detail: record.detail }),\n };\n}\n\nfunction assertNoMissing(missing: readonly MissingGraphObject<GraphRef>[]): void {\n if (missing.length === 0) return;\n const details = missing.map((item) =>\n `${formatGraphRef(item.ref)}: ${item.reason}${item.detail === undefined ? \"\" : ` (${item.detail})`}`);\n throw new Error(`Graph references unavailable:\\n${details.map((line) => ` ${line}`).join(\"\\n\")}`);\n}\n\nfunction appendRef(\n ref: GraphRef,\n path: string,\n depth: number,\n ancestors: ReadonlySet<string>,\n lines: GraphTreeLine[],\n firstPaths: Map<string, string>,\n cache: GraphObjectCache,\n expanded: ReadonlySet<string>,\n maxDepth: number,\n selector: readonly string[] | undefined,\n): void {\n const refKey = graphRefKey(ref);\n const priorPath = firstPaths.get(refKey);\n const cycle = ancestors.has(refKey);\n const object = cache.get(ref);\n const marker = cycle\n ? ` ↩ cycle to ${priorPath ?? formatGraphRef(ref)}`\n : priorPath !== undefined ? ` ↗ shared with ${priorPath}` : \"\";\n lines.push({\n key: path,\n depth,\n text: `${path} → ${formatGraphRef(ref)}${object === undefined ? \" [not loaded]\" : marker}`,\n ref,\n ...(selector === undefined ? {} : { selector: selector.length === 0 ? \"/\" : `/${selector.join(\"/\")}` }),\n expandable: !cycle && priorPath === undefined && depth < maxDepth,\n expanded: expanded.has(refKey),\n loaded: object !== undefined,\n targetKey: cycle || priorPath !== undefined ? priorPath : undefined,\n summary: object?.value !== null && typeof object?.value === \"object\" && !Array.isArray(object.value)\n ? typeof object.value.title === \"string\" ? object.value.title\n : typeof object.value.name === \"string\" ? object.value.name : undefined\n : undefined,\n });\n if (object === undefined || cycle || priorPath !== undefined || depth >= maxDepth) return;\n firstPaths.set(refKey, path);\n if (!expanded.has(refKey)) return;\n const nextAncestors = new Set(ancestors);\n nextAncestors.add(refKey);\n appendValue(object.value, path, depth + 1, nextAncestors, lines, firstPaths, cache, expanded, maxDepth, selector);\n}\n\nfunction appendValue(\n value: JsonValue,\n path: string,\n depth: number,\n ancestors: ReadonlySet<string>,\n lines: GraphTreeLine[],\n firstPaths: Map<string, string>,\n cache: GraphObjectCache,\n expanded: ReadonlySet<string>,\n maxDepth: number,\n selector: readonly string[] | undefined,\n): void {\n if (isGraphRef(value)) {\n appendRef(value, path, depth, ancestors, lines, firstPaths, cache, expanded, maxDepth,\n selector === undefined ? undefined : [...selector, \"@\"]);\n return;\n }\n if (Array.isArray(value)) {\n if (value.length === 0) lines.push({ key: path, depth, text: `${path} = []`, expandable: false });\n value.forEach((item, index) =>\n appendValue(item, `${path}[${index}]`, depth, ancestors, lines, firstPaths, cache, expanded, maxDepth,\n selector === undefined ? undefined : [...selector, String(index)]));\n return;\n }\n if (value !== null && typeof value === \"object\") {\n const entries = Object.entries(value);\n if (entries.length === 0) lines.push({ key: path, depth, text: `${path} = {}`, expandable: false });\n for (const [name, child] of entries) {\n if (child !== undefined) {\n appendValue(child, propertyPath(path, name), depth, ancestors, lines, firstPaths, cache, expanded, maxDepth,\n selector === undefined || name === \"*\" || name === \"**\" || name === \"@\"\n ? undefined : [...selector, name.replaceAll(\"~\", \"~0\").replaceAll(\"/\", \"~1\")]);\n }\n }\n return;\n }\n lines.push({ key: path, depth, text: `${path} = ${JSON.stringify(value)}`, expandable: false });\n}\n\nfunction visitValue(value: JsonValue, visitor: (ref: GraphRef) => void): void {\n if (isGraphRef(value)) {\n visitor(value);\n return;\n }\n if (Array.isArray(value)) {\n for (const item of value) visitValue(item, visitor);\n return;\n }\n if (value !== null && typeof value === \"object\") {\n for (const child of Object.values(value)) {\n if (child !== undefined) visitValue(child, visitor);\n }\n }\n}\n\nfunction propertyPath(parent: string, name: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(name)\n ? `${parent}.${name}`\n : `${parent}[${JSON.stringify(name)}]`;\n}\n\nexport async function withTimeout<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n timeoutMs: number,\n label: string,\n signal?: AbortSignal,\n): Promise<T> {\n signal?.throwIfAborted();\n const controller = new AbortController();\n let timer: NodeJS.Timeout | undefined;\n let onAbort!: () => void;\n const timeout = new Promise<never>((_resolve, reject) => {\n onAbort = () => {\n controller.abort(signal?.reason);\n reject(controller.signal.reason);\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n timer = setTimeout(() => {\n const error = new Error(`${label} timed out after ${timeoutMs}ms`);\n controller.abort(error);\n reject(error);\n }, timeoutMs);\n });\n try {\n return await Promise.race([operation(controller.signal), timeout]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n}\n\nfunction asRecord(value: unknown, location: string): Record<string, unknown> {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(`${location} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction assertJsonValue(value: unknown, location: string): asserts value is JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return;\n if (typeof value === \"number\" && Number.isFinite(value)) return;\n if (Array.isArray(value)) {\n value.forEach((item, index) => assertJsonValue(item, `${location}[${index}]`));\n return;\n }\n if (typeof value === \"object\") {\n for (const [key, child] of Object.entries(value)) {\n assertJsonValue(child, `${location}.${key}`);\n }\n return;\n }\n throw new Error(`${location} must be a JSON value`);\n}\n\nfunction jsonEqual(a: JsonValue, b: JsonValue): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n","import type { JsonValue } from \"@hediet/linkrpc\";\nimport { isGraphRef, type GraphPresentation } from \"@hediet/linkrpc-infra/graph\";\nimport { observableValue } from \"@vscode/observables\";\nimport {\n GraphLoader,\n createGraphTree,\n formatGraphRef,\n graphRefKey,\n graphRefsInValue,\n type GraphRef,\n type GraphTreeLine,\n} from \"./inspectGraphModel\";\nimport type { GraphTimings } from \"./inspectGraphTiming\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\n\nexport interface GraphViewOptions {\n readonly depth?: number;\n}\n\nexport class GraphExplorerModel {\n private readonly _expanded = observableValue<ReadonlySet<string>>(this, new Set());\n private readonly _expandedPaths = observableValue<ReadonlySet<string>>(this, new Set([\"$\"]));\n private readonly _selectedKey = observableValue(this, \"$\");\n private _cachedTree: {\n readonly size: number;\n readonly expanded: ReadonlySet<string>;\n readonly lines: readonly GraphTreeLine[];\n } | undefined;\n\n public constructor(\n public readonly root: GraphRef,\n private readonly _loader: GraphLoader,\n private readonly _maxDepth = Number.POSITIVE_INFINITY,\n state?: {\n readonly selectedKey?: string;\n readonly expanded?: ReadonlySet<string>;\n readonly expandedPaths?: ReadonlySet<string>;\n },\n private readonly _timings?: GraphTimings,\n private readonly _presentation?: GraphPresentation,\n ) {\n const expanded = new Set(state?.expanded);\n if (state?.expandedPaths === undefined || state.expandedPaths.has(\"$\")) expanded.add(graphRefKey(root));\n else expanded.delete(graphRefKey(root));\n this._expanded.set(expanded, undefined);\n this._expandedPaths.set(new Set(state?.expandedPaths ?? [\"$\"]), undefined);\n this._selectedKey.set(state?.selectedKey ?? \"$\", undefined);\n }\n\n public get lines(): readonly GraphTreeLine[] {\n const size = this._loader.cache.size;\n const expanded = this._expanded.get();\n if (this._cachedTree?.size !== size || this._cachedTree.expanded !== expanded) {\n const build = () => createGraphTree(this.root, this._loader.cache, expanded, this._maxDepth, this._presentation);\n this._cachedTree = { size, expanded, lines: this._timings?.measureSync(\"tree\", build) ?? build() };\n }\n return this._cachedTree.lines;\n }\n\n public get selectedIndex(): number {\n const exact = this.lines.findIndex((line) => line.key === this._selectedKey.get());\n return exact === -1 ? 0 : exact;\n }\n\n public get selectedKey(): string {\n return this.lines[this.selectedIndex]?.key ?? \"$\";\n }\n\n public get expandedKeys(): ReadonlySet<string> {\n return this._expanded.get();\n }\n\n public get expandedPaths(): ReadonlySet<string> {\n return this._expandedPaths.get();\n }\n\n public get cachedObjects(): number {\n return this._loader.cache.size;\n }\n\n public async prefetchExpanded(root: GraphRef): Promise<void> {\n const paths = this.lines.flatMap(line =>\n line.expandable && line.expanded && line.selector !== undefined ? [line.selector] : []);\n if (paths.length > 0) await this._loader.load([{ ref: root, paths }]);\n }\n\n public async restoreExpanded(signal?: AbortSignal, source?: GraphExplorerModel): Promise<void> {\n let paths: ReadonlySet<string>;\n do {\n paths = source?.expandedPaths ?? this.expandedPaths;\n if (source !== undefined) {\n this._expanded.set(new Set(source.expandedKeys), undefined);\n this._expandedPaths.set(paths, undefined);\n }\n const pending = new Set(paths);\n while (pending.size > 0) {\n signal?.throwIfAborted();\n const available = this.lines.filter(line => pending.has(line.key) && line.ref !== undefined && line.expandable);\n if (available.length === 0) break;\n const needs = available.flatMap(line => line.ref !== undefined && !this._loader.cache.has(line.ref)\n ? [{ ref: line.ref, paths: [\"/\"] }] : []);\n if (needs.length > 0) await this._loader.load(needs);\n signal?.throwIfAborted();\n const expanded = new Set(this._expanded.get());\n for (const line of available) {\n pending.delete(line.key);\n if (line.ref !== undefined) expanded.add(graphRefKey(line.ref));\n }\n this._expanded.set(expanded, undefined);\n if (source !== undefined && source.expandedPaths !== paths) break;\n }\n await this._loadVisibleObjects();\n signal?.throwIfAborted();\n } while (source !== undefined && source.expandedPaths !== paths);\n if (source !== undefined) this._selectedKey.set(source.selectedKey, undefined);\n }\n\n private async _loadVisibleObjects(): Promise<void> {\n // Fetch the displayed references, not their descendants. Collapsed rows\n // can then show titles without recursively opening the graph.\n const needs = this.lines.flatMap(line => line.ref !== undefined\n ? [{ ref: line.ref, paths: [\"/\"] }] : []);\n await this._loader.load(needs);\n await this.loadPresentation();\n }\n\n public async loadPresentation(): Promise<void> {\n // The evaluator stops at the first unresolved candidate. Re-evaluate after\n // each bounded object-only batch, never fetching a graph closure for labels.\n for (let round = 0; round < 32; round++) {\n const refs = this.lines.flatMap(line => line.presentationPending ?? []);\n if (refs.length === 0) return;\n const before = this._loader.cache.size;\n await this._loader.load(refs.map(ref => ({ ref, paths: [\"/\"] })));\n if (this._loader.cache.size === before) return;\n }\n }\n\n public select(index: number): void {\n const line = this.lines[index];\n if (line === undefined) throw new Error(`No graph line ${index + 1}`);\n this._selectedKey.set(line.key, undefined);\n }\n\n public move(delta: number): void {\n const lines = this.lines;\n if (lines.length === 0) return;\n const index = Math.max(0, Math.min(lines.length - 1, this.selectedIndex + delta));\n this._selectedKey.set(lines[index].key, undefined);\n }\n\n public async expandSelected(): Promise<void> {\n const line = this.lines[this.selectedIndex];\n if (line?.targetKey !== undefined) {\n this._selectedKey.set(line.targetKey, undefined);\n return;\n }\n if (line?.ref === undefined || !line.expandable) return;\n if (line.expanded && (this.lines[this.selectedIndex + 1]?.depth ?? -1) > line.depth) {\n this.move(1);\n return;\n }\n await this._expand(line);\n }\n\n private async _expand(line: GraphTreeLine): Promise<void> {\n if (line.ref === undefined) return;\n if (!this._loader.cache.has(line.ref)) {\n await this._loader.load([{ ref: line.ref, paths: [\"/\"] }]);\n }\n const key = graphRefKey(line.ref);\n const canonical = this.lines.find(item => item.ref !== undefined\n && graphRefKey(item.ref) === key && item.expandable)?.key ?? line.key;\n this._expanded.set(new Set([...this._expanded.get(), key]), undefined);\n this._expandedPaths.set(new Set([...this._expandedPaths.get(), canonical]), undefined);\n if (this._selectedKey.get() === line.key) this._selectedKey.set(canonical, undefined);\n await this._loadVisibleObjects();\n }\n\n public collapseSelected(): void {\n const lines = this.lines;\n const line = lines[this.selectedIndex];\n if (line?.ref !== undefined && line.expandable && line.expanded) {\n const refKey = graphRefKey(line.ref);\n const aliases = new Set(lines.filter(item => item.ref !== undefined\n && graphRefKey(item.ref) === refKey).map(item => item.key));\n this._expanded.set(new Set([...this._expanded.get()].filter(key => key !== refKey)), undefined);\n this._expandedPaths.set(new Set([...this._expandedPaths.get()].filter(path => !aliases.has(path))), undefined);\n return;\n }\n for (let index = this.selectedIndex - 1; index >= 0; index--) {\n if (lines[index].depth < (line?.depth ?? 0)) {\n this.select(index);\n return;\n }\n }\n }\n}\n\nexport async function loadGraphDepth(\n root: GraphRef,\n loader: GraphLoader,\n depth: number,\n): Promise<void> {\n if (!Number.isInteger(depth) || depth < 0) {\n throw new Error(\"depth must be a non-negative integer\");\n }\n let frontier = [root];\n const visited = new Set<string>();\n for (let level = 0; level <= depth && frontier.length > 0; level++) {\n const needs = frontier\n .filter((ref) => !loader.cache.has(ref))\n .map((ref) => ({ ref, paths: [\"/\"] }));\n if (needs.length > 0) await loader.load(needs);\n if (level === depth) break;\n const next = new Map<string, GraphRef>();\n for (const ref of frontier) {\n const key = graphRefKey(ref);\n if (visited.has(key)) continue;\n visited.add(key);\n const object = loader.cache.get(ref);\n if (object === undefined) {\n throw new Error(`Graph object ${formatGraphRef(ref)} is missing or expired`);\n }\n for (const child of graphRefsInValue(object.value)) {\n if (!visited.has(graphRefKey(child))) next.set(graphRefKey(child), child);\n }\n }\n frontier = [...next.values()];\n }\n}\n\nexport function renderGraphTree(\n model: GraphExplorerModel,\n options: { readonly selected?: boolean } = {},\n): string {\n const selectedIndex = model.selectedIndex;\n return model.lines.map((line, index) => {\n const cursor = options.selected === true\n ? (index === selectedIndex ? \"> \" : \" \")\n : \"\";\n const presentation = [line.summary, line.description].filter(value => value !== undefined).join(\" — \");\n return `${cursor}${\" \".repeat(line.depth)}${line.text}${presentation ? ` ${safeTerminalText(presentation)}` : \"\"}`;\n }).join(\"\\n\");\n}\n\nexport function renderGraphJson(root: GraphRef, loader: GraphLoader): string {\n return JSON.stringify(materializeGraphValue(root, loader, new Set()), null, 2);\n}\n\nfunction materializeGraphValue(\n ref: GraphRef,\n loader: GraphLoader,\n ancestors: ReadonlySet<string>,\n): JsonValue {\n const key = graphRefKey(ref);\n if (ancestors.has(key)) return { $ref: formatGraphRef(ref), $cycle: true };\n const object = loader.cache.get(ref);\n if (object === undefined) return { $ref: formatGraphRef(ref), $missing: true };\n const nextAncestors = new Set(ancestors);\n nextAncestors.add(key);\n return replaceRefs(object.value, loader, nextAncestors);\n}\n\nfunction replaceRefs(\n value: JsonValue,\n loader: GraphLoader,\n ancestors: ReadonlySet<string>,\n): JsonValue {\n if (isGraphRef(value)) return materializeGraphValue(value, loader, ancestors);\n if (Array.isArray(value)) return value.map((item) => replaceRefs(item, loader, ancestors));\n if (value !== null && typeof value === \"object\") {\n return Object.fromEntries(\n Object.entries(value).flatMap(([key, child]) =>\n child === undefined ? [] : [[key, replaceRefs(child, loader, ancestors)]]),\n );\n }\n return value;\n}\n","import { stdout } from \"node:process\";\nimport {\n createSchemaToZod,\n interfaceTemplateMemberName,\n INTERFACE_TEMPLATES_EXTENSION,\n type JsonValue,\n type LinkRpcInterfaceSchema,\n type InterfaceTemplateArgument,\n type InterfaceTemplatesMetadata,\n} from \"@hediet/linkrpc\";\nimport {\n IMMUTABLE_GRAPH_INTERFACE_ID,\n ROOT_WATCH_INTERFACE_ID,\n validateGraphInterfaceSchema,\n graphPresentationSchema,\n} from \"@hediet/linkrpc-infra/graph\";\nimport type { DiscoveredListing } from \"@hediet/linkrpc/hub/common\";\nimport type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { GraphTerminal } from \"./inspectGraphTerminal\";\nimport { GraphTimings, type GraphTiming } from \"./inspectGraphTiming\";\nimport {\n GraphLoader,\n GraphObjectCache,\n graphRefKey,\n parseGraphRef,\n withTimeout,\n type GraphBatchFetch,\n type GraphRef,\n} from \"./inspectGraphModel\";\nimport {\n GraphExplorerModel,\n loadGraphDepth,\n renderGraphJson,\n renderGraphTree,\n} from \"./inspectGraphView\";\n\nexport interface GraphTarget {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly graphInterfaceId: string;\n readonly root: string;\n readonly watchMethod: string;\n readonly batchMethod: string;\n readonly paramsArgument: InterfaceTemplateArgument;\n readonly refArgument: InterfaceTemplateArgument;\n readonly valueArgument: InterfaceTemplateArgument;\n readonly presentationMethod?: string;\n}\n\nexport interface InspectGraphOptions {\n readonly targets: readonly GraphTarget[];\n readonly onModel?: (model: GraphExplorerModel, version: number) => void | Promise<void>;\n readonly onUpdating?: () => void | Promise<void>;\n readonly logTiming?: boolean;\n readonly onTiming?: (timing: GraphTiming) => void;\n readonly serviceId?: string;\n readonly interfaceId?: string;\n readonly root?: string;\n readonly params?: unknown;\n readonly depth?: number;\n readonly path?: string;\n readonly watch?: boolean;\n readonly json?: boolean;\n readonly maxObjects?: number;\n readonly maxBytes?: number;\n readonly maxRounds?: number;\n readonly timeoutMs?: number;\n readonly interactive?: boolean;\n readonly stop?: Promise<void>;\n readonly emit?: (text: string) => void;\n readonly repaint?: (text: string) => void;\n}\n\nexport interface GraphDiscovery {\n readonly targets: readonly GraphTarget[];\n readonly warnings: readonly string[];\n}\n\ninterface GraphRootDescriptor {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly root: string;\n readonly watchMethod: string;\n readonly paramsArgument: InterfaceTemplateArgument;\n readonly refArgument: InterfaceTemplateArgument;\n}\n\ninterface GraphStoreDescriptor {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly batchMethod: string;\n readonly refArgument: InterfaceTemplateArgument;\n readonly valueArgument: InterfaceTemplateArgument;\n}\n\nexport function graphDescriptorsFromSchema(\n listing: DiscoveredListing,\n schema: LinkRpcInterfaceSchema,\n): {\n readonly roots: readonly GraphRootDescriptor[];\n readonly stores: readonly GraphStoreDescriptor[];\n} {\n const metadata = schema[INTERFACE_TEMPLATES_EXTENSION] as InterfaceTemplatesMetadata | undefined;\n if (metadata === undefined) return { roots: [], stores: [] };\n validateGraphInterfaceSchema(schema);\n const graphInstances = metadata.instances.filter((instance) =>\n metadata.templates[instance.template]?.id === IMMUTABLE_GRAPH_INTERFACE_ID);\n const rootInstances = metadata.instances.filter((instance) =>\n metadata.templates[instance.template]?.id === ROOT_WATCH_INTERFACE_ID);\n return {\n roots: rootInstances.map((root) => ({\n serviceId: listing.serviceId,\n interfaceId: listing.interfaceId,\n hash: listing.hash,\n root: root.name,\n watchMethod: wireMethod(listing.serviceId, listing.interfaceId, interfaceTemplateMemberName(root, 'watch')),\n paramsArgument: requiredArgument(root.arguments, \"params\", root.name),\n refArgument: requiredArgument(root.arguments, \"ref\", root.name),\n })),\n stores: graphInstances.map((graph) => ({\n serviceId: listing.serviceId,\n interfaceId: listing.interfaceId,\n hash: listing.hash,\n batchMethod: wireMethod(listing.serviceId, listing.interfaceId, interfaceTemplateMemberName(graph, 'batchObjGet')),\n refArgument: requiredArgument(graph.arguments, \"ref\", graph.name),\n valueArgument: requiredArgument(graph.arguments, \"value\", graph.name),\n })),\n };\n}\n\nexport async function inspectGraphCommand(\n channel: CliChannel,\n options: InspectGraphOptions,\n): Promise<string> {\n const discovery: GraphDiscovery = { targets: options.targets, warnings: [] };\n const target = selectGraphTarget(discovery.targets, options);\n if (target === undefined) {\n return renderGraphTargetList(discovery);\n }\n const params = validateSchemaValue(options.params === undefined ? {} : options.params, target.paramsArgument, \"root params\");\n const refValidator = schemaValidator(target.refArgument);\n const valueValidator = schemaValidator(target.valueArgument);\n const timings = options.onTiming !== undefined || options.logTiming\n ? new GraphTimings(options.onTiming ?? (timing => {\n process.stderr.write(`linkrpc: timing ${JSON.stringify(timing)}\\n`);\n }))\n : undefined;\n const fetch: GraphBatchFetch = async (request, signal) => {\n const call = channel.sendRequestWithStream(target.batchMethod, {\n needs: request.needs.map(({ ref, paths }) => ({ ref, paths: [...paths] })),\n have: request.have.map(item => ({ ...item })),\n limits: { ...request.limits },\n });\n const cancel = (): void => {\n call.cancel(\"graph batch cancelled\");\n call.dispose?.();\n };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try {\n const result = await call.result;\n validateBatchPayload(result, refValidator, valueValidator);\n return result;\n } finally {\n signal.removeEventListener(\"abort\", cancel);\n call.dispose?.();\n }\n };\n const cancellation = new AbortController();\n const loader = new GraphLoader(fetch, new GraphObjectCache(), { ...options, timings, signal: cancellation.signal });\n const emit = options.emit ?? ((text) => stdout.write(`${text}\\n`));\n const interactive = options.interactive === true;\n const navigable = interactive || options.onModel !== undefined;\n let firstOutput = \"\";\n let currentModel: GraphExplorerModel | undefined;\n const terminal = interactive\n ? new GraphTerminal(`${target.serviceId || \"local\"} / ${target.interfaceId} / ${target.root}`, JSON.stringify(params), options.repaint, timings)\n : undefined;\n const stopRequested = terminal !== undefined\n ? options.stop === undefined ? terminal.result : Promise.race([terminal.result, options.stop])\n : options.stop;\n const stop = stopRequested?.then(() => { cancellation.abort(); });\n try {\n await watchRoots(channel, target, params as JsonValue, stop, options.timeoutMs ?? 5_000, async ({ version, ref }, call) => {\n const refresh = async () => {\n await terminal?.beginUpdate();\n await options.onUpdating?.();\n cancellation.signal.throwIfAborted();\n validateWith(refValidator, ref, \"root watch ref\");\n if (options.path !== undefined) {\n await loader.load([{ ref, paths: [normalizeGraphPath(options.path)] }]);\n } else {\n if (navigable && currentModel !== undefined) await currentModel.prefetchExpanded(ref);\n await loadGraphDepth(ref, loader, options.depth ?? (navigable ? 0 : 2));\n }\n const presentation = options.json || target.presentationMethod === undefined ? undefined\n : await withTimeout(async signal => {\n const call = channel.sendRequestWithStream(target.presentationMethod!, {});\n const cancel = () => { call.cancel(\"graph presentation cancelled\"); call.dispose?.(); };\n signal.addEventListener(\"abort\", cancel, { once: true });\n try { return graphPresentationSchema.parse(await call.result); }\n finally { signal.removeEventListener(\"abort\", cancel); call.dispose?.(); }\n }, options.timeoutMs ?? 5_000, \"graph presentation\", cancellation.signal);\n const model = new GraphExplorerModel(ref, loader, navigable ? undefined : options.depth, navigable\n ? currentModel === undefined ? undefined : {\n selectedKey: currentModel.selectedKey,\n expanded: currentModel.expandedKeys,\n expandedPaths: currentModel.expandedPaths,\n }\n : { expanded: new Set(loader.cache.have().map((item) => graphRefKey(item.ref))) }, timings, presentation);\n await model.loadPresentation();\n cancellation.signal.throwIfAborted();\n if (options.onModel !== undefined) {\n await options.onModel(model, version);\n } else if (terminal !== undefined) {\n const restore = () => terminal.finishUpdate(model, version, cancellation.signal);\n await (timings?.measureAsync(\"restore\", restore, { version }) ?? restore());\n } else {\n const render = () => options.json === true\n ? renderGraphJson(ref, loader)\n : renderGraphTree(model);\n const rendered = timings?.measureSync(\"output\", render, { version }) ?? render();\n if (options.watch === true) emit(options.json === true ? JSON.stringify(JSON.parse(rendered)) : rendered);\n else firstOutput = rendered;\n }\n await call.send({ accept: version });\n currentModel = model;\n return interactive || options.watch === true;\n };\n return timings?.measureAsync(\"refresh\", refresh, { version }) ?? refresh();\n });\n } catch (error) {\n if (!cancellation.signal.aborted) throw error;\n } finally {\n cancellation.abort();\n terminal?.dispose();\n }\n for (const warning of discovery.warnings) {\n process.stderr.write(`linkrpc: ${warning}\\n`);\n }\n return firstOutput;\n}\n\nexport function selectGraphTarget(\n targets: readonly GraphTarget[],\n options: Pick<InspectGraphOptions, \"serviceId\" | \"interfaceId\" | \"root\">,\n): GraphTarget | undefined {\n if (\n options.serviceId === undefined\n && options.interfaceId === undefined\n && options.root === undefined\n ) {\n return undefined;\n }\n const matches = targets.filter((target) =>\n (options.serviceId === undefined || target.serviceId === options.serviceId)\n && (options.interfaceId === undefined || target.interfaceId === options.interfaceId)\n && (options.root === undefined || target.root === options.root));\n if (matches.length === 0) {\n if (options.serviceId !== undefined || options.interfaceId !== undefined || options.root !== undefined) {\n throw new Error(\"No graph root matches the requested service, interface, and root selectors\");\n }\n return undefined;\n }\n if (matches.length > 1) {\n throw new Error(\n `Graph selection is ambiguous (${matches.length} roots); specify --service, --interface, and --root`,\n );\n }\n return matches[0];\n}\n\nexport function renderGraphTargetList(discovery: GraphDiscovery): string {\n if (discovery.targets.length === 0) {\n const suffix = discovery.warnings.length === 0\n ? \"\"\n : `\\n${discovery.warnings.map((warning) => `warning: ${warning}`).join(\"\\n\")}`;\n return `No graph-capable reflected interface templates found.${suffix}`;\n }\n return [\n \"Available graph roots:\",\n ...discovery.targets.map((target) =>\n ` ${target.serviceId || \"<root>\"}::${target.interfaceId} root=${target.root} `\n + `objects=${target.graphInterfaceId}`),\n ...discovery.warnings.map((warning) => `warning: ${warning}`),\n ].join(\"\\n\");\n}\n\ninterface RootOffer {\n readonly version: number;\n readonly ref: GraphRef;\n}\n\nexport async function watchRoots(\n channel: Pick<CliChannel, \"sendRequestWithStream\">,\n target: GraphTarget,\n params: JsonValue,\n stop: Promise<void> | undefined,\n timeoutMs: number,\n onOffer: (\n offer: RootOffer,\n call: ReturnType<CliChannel[\"sendRequestWithStream\"]>,\n ) => Promise<boolean>,\n): Promise<void> {\n let queue = Promise.resolve(true);\n let received = false;\n let resolveFirst!: () => void;\n let rejectFirst!: (error: unknown) => void;\n const first = new Promise<void>((resolve, reject) => {\n resolveFirst = resolve;\n rejectFirst = reject;\n });\n let fail!: (error: unknown) => void;\n const failed = new Promise<never>((_resolve, reject) => { fail = reject; });\n const timer = setTimeout(() => {\n if (!received) fail(new Error(`Graph root watch produced no root within ${timeoutMs}ms`));\n }, timeoutMs);\n let call!: ReturnType<CliChannel[\"sendRequestWithStream\"]>;\n call = channel.sendRequestWithStream(target.watchMethod, params, {\n onStreamMessage: (payload) => {\n queue = queue.then(async (keepWatching) => {\n if (!keepWatching) return false;\n const offer = parseRootOffer(payload);\n received = true;\n const keep = await onOffer(offer, call);\n resolveFirst();\n return keep;\n }).catch((error: unknown) => {\n rejectFirst(error);\n fail(error);\n return false;\n });\n },\n });\n const stopped = stop?.then(() => \"stop\" as const);\n try {\n const outcome = await Promise.race([\n first.then(() => \"first\" as const),\n call.result.then(() => \"result\" as const),\n failed,\n ...(stopped === undefined ? [] : [stopped]),\n ]);\n if (outcome === \"result\" && !received) {\n throw new Error(\"Graph root watch ended before offering a root\");\n }\n if (outcome === \"first\" && await queue) {\n await Promise.race([call.result, failed, ...(stopped === undefined ? [] : [stopped])]);\n }\n await queue;\n } finally {\n clearTimeout(timer);\n call.cancel(\"graph explorer finished\");\n call.dispose?.();\n }\n}\n\nfunction validateBatchPayload(\n value: JsonValue,\n refValidator: ReturnType<typeof schemaValidator>,\n valueValidator: ReturnType<typeof schemaValidator>,\n): void {\n if (value === null || Array.isArray(value) || typeof value !== \"object\") {\n throw new Error(\"graph batch result must be an object\");\n }\n if (!Array.isArray(value.objects)) return;\n value.objects.forEach((object, index) => {\n if (object === null || Array.isArray(object) || typeof object !== \"object\") return;\n validateWith(refValidator, object.ref, `graph batch objects[${index}].ref`);\n validateWith(valueValidator, object.value, `graph batch objects[${index}].value`);\n });\n}\n\nfunction schemaValidator(argument: InterfaceTemplateArgument) {\n return createSchemaToZod(argument.components?.schemas ?? {}).toZod(argument.schema);\n}\n\nfunction validateSchemaValue(\n value: unknown,\n argument: InterfaceTemplateArgument,\n location: string,\n): unknown {\n const validator = schemaValidator(argument);\n validateWith(validator, value, location);\n return value;\n}\n\nfunction validateWith(\n validator: ReturnType<typeof schemaValidator>,\n value: unknown,\n location: string,\n): void {\n const result = validator.safeParse(value);\n if (!result.success) {\n throw new Error(`${location} does not match its reflected schema: ${result.error.message}`);\n }\n}\n\nfunction parseRootOffer(value: JsonValue): RootOffer {\n if (value === null || Array.isArray(value) || typeof value !== \"object\") {\n throw new Error(\"root watch event must be an object\");\n }\n if (typeof value.version !== \"number\" || !Number.isSafeInteger(value.version)) {\n throw new Error(\"root watch event.version must be a safe integer\");\n }\n return { version: value.version, ref: parseGraphRef(value.ref, \"root watch event.ref\") };\n}\n\nfunction requiredArgument(\n args: Readonly<Record<string, InterfaceTemplateArgument>>,\n name: string,\n instance: string,\n): InterfaceTemplateArgument {\n const argument = args[name];\n if (argument === undefined) {\n throw new Error(`Graph template instance \"${instance}\" is missing schema argument \"${name}\"`);\n }\n return argument;\n}\n\nfunction wireMethod(serviceId: string, interfaceId: string, member: string): string {\n return serviceId.length === 0\n ? `${interfaceId}::${member}`\n : `${serviceId}::${interfaceId}::${member}`;\n}\n\nfunction normalizeGraphPath(path: string): string {\n if (path === \"/\") return path;\n if (!path.startsWith(\"/\")) throw new Error(\"--path must be a JSON pointer beginning with '/'\");\n return path;\n}\n","import type { ViewCommand, ViewKeybinding, ViewKeyEvent, ViewSession } from \"./types\";\n\nexport interface ViewHostActions {\n readonly quit: () => void;\n readonly nextTab?: () => void;\n readonly toggleScope?: () => void;\n readonly back?: () => void;\n}\n\nexport function matchesKey(binding: ViewKeybinding, event: ViewKeyEvent): boolean {\n return (binding.key.length === 1 && !binding.ctrl && !binding.meta ? event.input === binding.key\n : event.name === binding.key || event.input === binding.key)\n && !!binding.ctrl === !!event.ctrl && !!binding.meta === !!event.meta\n // Terminals often infer shift for uppercase letters. The literal already encodes it.\n && (binding.shift === undefined && binding.key.length === 1 || !!binding.shift === !!event.shift);\n}\n\n/** Host bindings take precedence; capture only releases ordinary keys, never Ctrl+C. */\nexport function hostCommands(actions: ViewHostActions, capturesInput = false): readonly ViewCommand[] {\n return [\n { id: \"host.quit\", title: \"Quit\", keybindings: [{ key: \"c\", ctrl: true }, ...capturesInput ? [] : [{ key: \"q\" }]], execute: actions.quit },\n ...capturesInput ? [] : [\n ...actions.nextTab ? [{ id: \"host.nextTab\", title: \"Next view\", keybindings: [{ key: \"tab\" }], execute: actions.nextTab }] : [],\n ...actions.toggleScope ? [{ id: \"host.scope\", title: \"Switch scope\", keybindings: [{ key: \"v\" }], execute: actions.toggleScope }] : [],\n ...actions.back ? [{ id: \"host.back\", title: \"Services\", keybindings: [{ key: \"escape\" }], execute: actions.back }] : [],\n ],\n ];\n}\n\nexport function availableViewCommands(\n commands: readonly ViewCommand[], reserved: readonly ViewCommand[] = [],\n): readonly ViewCommand[] {\n const claimed = reserved.filter(command => command.enabled !== false).flatMap(command => command.keybindings);\n const result: ViewCommand[] = [];\n for (const command of commands) {\n if (command.enabled === false) continue;\n const keybindings = command.keybindings.filter(binding => !claimed.some(key =>\n key.key === binding.key && !!key.ctrl === !!binding.ctrl && !!key.meta === !!binding.meta\n && (key.key.length === 1 && (key.shift === undefined || binding.shift === undefined)\n || !!key.shift === !!binding.shift)));\n claimed.push(...keybindings);\n if (keybindings.length > 0) result.push({ ...command, keybindings });\n }\n return result;\n}\n\nfunction dispatch(commands: readonly ViewCommand[], event: ViewKeyEvent): boolean {\n const command = commands.find(command => command.enabled !== false\n && command.keybindings.some(binding => matchesKey(binding, event)));\n if (!command) return false;\n command.execute();\n return true;\n}\n\nexport function dispatchViewKey(session: ViewSession, event: ViewKeyEvent): boolean {\n if (dispatch(session.commands.get(), event)) return true;\n return session.capturesInput === true && session.handleTextInput?.(event) === true;\n}\n\n/** A true result means consumed: callers must not dispatch the event a second time. */\nexport function dispatchHostKey(session: ViewSession | undefined, event: ViewKeyEvent, actions: ViewHostActions): boolean {\n if (dispatch(hostCommands(actions, session?.capturesInput), event)) return true;\n return session ? dispatchViewKey(session, event) : false;\n}\n\nexport function formatKeybinding(binding: ViewKeybinding): string {\n const labels: Record<string, string> = {\n up: \"↑\", down: \"↓\", left: \"←\", right: \"→\", return: \"Enter\", escape: \"Esc\",\n pageup: \"PgUp\", pagedown: \"PgDn\", home: \"Home\", end: \"End\", tab: \"Tab\",\n backspace: \"Backspace\", delete: \"Delete\", \" \": \"Space\",\n };\n return `${binding.ctrl ? \"Ctrl+\" : \"\"}${binding.meta ? \"Alt+\" : \"\"}${binding.shift ? \"Shift+\" : \"\"}${labels[binding.key] ?? binding.key}`;\n}\n\nexport function formatCommandLegend(commands: readonly ViewCommand[]): string {\n return availableViewCommands(commands).map(command =>\n `${command.keybindings.map(formatKeybinding).join(\"/\")}: ${command.title}`).join(\" · \");\n}\n","import React from \"react\";\nimport { Box, Text } from \"ink\";\nimport { autorun } from \"@vscode/observables\";\nimport type { ViewSession } from \"./types\";\nimport { availableViewCommands, formatCommandLegend, hostCommands, type ViewHostActions } from \"./commands\";\nimport { safeTerminalText } from \"../ui/terminalText\";\n\nconst noop = () => {};\n\n/** The legend and keyboard dispatcher use the same availability and reservation policy. */\nexport class CommandLegend extends React.Component<{\n readonly session: ViewSession;\n readonly tabbed?: boolean;\n readonly active?: boolean;\n readonly columns?: number;\n readonly maxRows?: number;\n}, { revision: number }> {\n state = { revision: 0 };\n private subscription: { dispose(): void } | undefined;\n componentDidMount(): void { this.subscribe(); }\n componentDidUpdate(previous: Readonly<{ session: ViewSession; tabbed?: boolean; active?: boolean }>): void {\n if (previous.session !== this.props.session) this.subscribe();\n }\n private subscribe(): void {\n this.subscription?.dispose();\n this.subscription = autorun(reader => {\n this.props.session.commands.read(reader);\n this.setState(previous => ({ revision: previous.revision + 1 }));\n });\n }\n componentWillUnmount(): void { this.subscription?.dispose(); }\n render(): React.ReactNode {\n const { session, tabbed, active = true, columns = 80, maxRows } = this.props;\n const lines = viewLegendLines(session, { tabbed, active, columns, maxRows });\n return <Box flexDirection=\"column\" flexShrink={0} height={lines.length}>\n {lines.map((line, index) => <Text key={index} dimColor wrap=\"truncate-end\">{line}</Text>)}\n </Box>;\n }\n}\n\nexport function viewLegendLines(session: ViewSession, options: {\n readonly tabbed?: boolean; readonly active?: boolean; readonly columns: number; readonly maxRows?: number;\n}): readonly string[] {\n const { tabbed, active = true, columns, maxRows = Infinity } = options;\n const actions: ViewHostActions = tabbed\n ? { quit: noop, nextTab: noop, toggleScope: noop, back: noop } : { quit: noop };\n const host = hostCommands(actions, active && session.capturesInput);\n const commands = [...host, ...active ? availableViewCommands(session.commands.get(), host) : []];\n const words = safeTerminalText(formatCommandLegend(commands)).split(\" \");\n const lines: string[] = [];\n let line = \"\";\n for (const word of words) {\n if (line && [...`${line} ${word}`].length > columns) { lines.push(line); line = \"\"; }\n line += (line ? \" \" : \"\") + word;\n }\n if (line) lines.push(line);\n const visible = lines.slice(0, Math.max(1, maxRows));\n if (lines.length > visible.length && visible.length > 0) {\n visible[visible.length - 1] = [...visible[visible.length - 1]!].slice(0, Math.max(0, columns - 2)).join(\"\").trimEnd() + \" …\";\n }\n return visible;\n}\n","import React from \"react\";\nimport { Box, measureElement, type DOMElement } from \"ink\";\nimport { autorun, observableValue } from \"@vscode/observables\";\nimport type { ViewSession } from \"./types\";\nimport { CommandLegend, viewLegendLines } from \"./CommandLegend\";\n\n/** Gives content exactly the rows left after the command-driven legend. */\nexport class ViewFrame extends React.Component<{\n readonly session: ViewSession;\n readonly rows: number;\n readonly columns?: number;\n readonly maxColumns?: number;\n readonly tabbed?: boolean;\n readonly active?: boolean;\n}, { revision: number }> {\n state = { revision: 0 };\n private subscription: { dispose(): void } | undefined;\n private readonly measuredColumns = observableValue(this, 1);\n private readonly root = React.createRef<DOMElement>();\n private mounted = false;\n private appliedViewport: { readonly session: ViewSession; readonly rows: number; readonly columns: number } | undefined;\n componentDidMount(): void { this.mounted = true; this.subscribe(); this.layout(); }\n componentDidUpdate(previous: Readonly<ViewFrame[\"props\"]>): void {\n if (previous.session !== this.props.session) this.subscribe();\n this.layout();\n }\n componentWillUnmount(): void { this.mounted = false; this.subscription?.dispose(); }\n private subscribe(): void {\n this.subscription?.dispose();\n this.subscription = autorun(reader => {\n this.props.session.commands.read(reader);\n this.measuredColumns.read(reader);\n this.setState(previous => ({ revision: previous.revision + 1 }));\n });\n }\n private get columns(): number {\n return Math.min(this.props.columns ?? this.measuredColumns.get(), this.props.maxColumns ?? Infinity);\n }\n private get legendRows(): number {\n return viewLegendLines(this.props.session, { ...this.props, columns: this.columns,\n maxRows: Math.min(this.props.session.maxLegendRows ?? Infinity,\n this.props.tabbed ? Math.min(2, Math.max(1, this.props.rows - 7)) : Math.max(1, this.props.rows - 7)) }).length;\n }\n private layout(): void {\n const rows = Math.max(1, this.props.rows - this.legendRows);\n const columns = this.columns;\n const previous = this.appliedViewport;\n if (previous?.session !== this.props.session || previous.rows !== rows || previous.columns !== columns) {\n this.props.session.setViewport?.(rows, columns);\n this.appliedViewport = { session: this.props.session, rows, columns };\n this.setState(value => ({ revision: value.revision + 1 }));\n }\n // Yoga dimensions become final after the commit, not during render/mount.\n queueMicrotask(() => {\n if (!this.mounted || this.props.columns !== undefined || !this.root.current) return;\n const width = Math.max(1, Math.floor(measureElement(this.root.current).width));\n if (width !== this.measuredColumns.get()) this.measuredColumns.set(width, undefined);\n });\n }\n render(): React.ReactNode {\n const { session, rows, tabbed, active } = this.props;\n const columns = this.columns;\n const legendRows = this.legendRows;\n const contentRows = Math.max(1, rows - legendRows);\n const ready = this.appliedViewport?.session === session\n && this.appliedViewport.rows === contentRows && this.appliedViewport.columns === columns;\n return <Box ref={this.root} flexDirection=\"column\" width={this.props.columns ?? \"100%\"} minWidth={0}\n height={rows} flexShrink={0} overflow=\"hidden\">\n <Box flexDirection=\"column\" height={contentRows} flexShrink={0} overflow=\"hidden\">\n {/* Ink 5 uses the innermost clip, so a stale oversized child can escape its parent's clip. */}\n <Box display={ready ? \"flex\" : \"none\"} flexDirection=\"column\" height={contentRows} width={columns}>\n {session.element}\n </Box>\n </Box>\n <CommandLegend session={session} columns={columns} maxRows={legendRows} tabbed={tabbed} active={active} />\n </Box>;\n }\n}\n","import React from \"react\";\nimport { render } from \"ink\";\nimport { emitKeypressEvents, type Key } from \"node:readline\";\nimport { stdin, stdout } from \"node:process\";\nimport type { ViewSession } from \"./types\";\nimport { dispatchHostKey } from \"./commands\";\nimport { ViewFrame } from \"./ViewFrame\";\n\n/** Runs any contributed view and drains its I/O before returning connection ownership. */\nexport async function runViewTui(session: ViewSession): Promise<void> {\n let instance: ReturnType<typeof render> | undefined;\n let ownsInput = false;\n const raw = stdin.isRaw;\n const flowing = stdin.readableFlowing === true;\n const onKey = (input: string, key: Key) =>\n dispatchHostKey(session, { ...key, input }, { quit: () => instance?.unmount() });\n const element = () => <ViewFrame session={session} rows={stdout.rows || 24} columns={stdout.columns || 80} />;\n const onResize = () => {\n instance?.rerender(element());\n };\n const onStop = () => instance?.unmount();\n try {\n if (!stdin.isTTY || !stdout.isTTY) throw new Error(\"--tui requires an interactive terminal; omit --tui for a snapshot\");\n onResize();\n instance = render(element(), { stdin, stdout, exitOnCtrlC: false });\n emitKeypressEvents(stdin);\n stdin.setRawMode(true);\n ownsInput = true;\n stdin.resume();\n stdin.on(\"keypress\", onKey);\n stdout.on(\"resize\", onResize);\n process.once(\"SIGINT\", onStop);\n process.once(\"SIGTERM\", onStop);\n await instance.waitUntilExit();\n } finally {\n session.dispose();\n stdin.off(\"keypress\", onKey);\n stdout.off(\"resize\", onResize);\n process.off(\"SIGINT\", onStop);\n process.off(\"SIGTERM\", onStop);\n if (ownsInput) {\n stdin.setRawMode(raw ?? false);\n if (!flowing) stdin.pause();\n }\n instance?.unmount();\n await session.disposeAsync?.();\n }\n}\n","import React from \"react\";\nimport { Box, Text } from \"ink\";\nimport { autorun, derived, observableValue } from \"@vscode/observables\";\nimport { stdout } from \"node:process\";\nimport type { ViewCommand, ViewKeyEvent, ViewOpenContext, ViewSession } from \"../../views/types\";\nimport { runViewTui } from \"../../views/runViewTui\";\nimport { inspectGraphCommand, type GraphTarget } from \"./inspectGraph\";\nimport type { GraphExplorerModel } from \"./inspectGraphView\";\nimport { anchorGraphScrollTop, clampGraphScroll, createGraphFrame, graphChromeRows, graphFrameText, type GraphFrameRow } from \"./graphFrame\";\n\ninterface State {\n readonly cursor: number;\n readonly params: string;\n readonly editing: boolean;\n readonly active: boolean;\n readonly model?: GraphExplorerModel;\n readonly version?: number;\n readonly error?: string;\n readonly revision: number;\n readonly viewportRows?: number;\n readonly showObjectIds?: boolean;\n readonly viewportColumns?: number;\n readonly scrollTop?: number;\n readonly busy?: boolean;\n readonly refreshing?: boolean;\n}\n\n/** A tab owns one watch. Disposing invalidates callbacks before cancelling I/O. */\nexport class GraphSession implements ViewSession {\n readonly state = observableValue<State>(this, { cursor: 0, params: \"{}\", editing: false, active: false, revision: 0 });\n readonly element = <GraphPanel session={this} />;\n private generation = 0;\n private stop: (() => void) | undefined;\n private disposed = false;\n private action = Promise.resolve();\n private readonly pending = new Set<Promise<void>>();\n private started = false;\n\n constructor(\n private readonly context: ViewOpenContext,\n readonly roots: readonly GraphTarget[],\n private options: Readonly<Record<string, unknown>> = {},\n ) {}\n get capturesInput(): boolean { return this.state.get().editing; }\n setViewport(rows: number, columns = this.state.get().viewportColumns ?? stdout.columns ?? 80): void {\n const state = this.state.get();\n if (state.viewportRows !== rows || state.viewportColumns !== columns) this.update({\n viewportRows: rows, viewportColumns: columns,\n scrollTop: clampGraphScroll(state.model?.lines.length ?? this.roots.length, state.model?.selectedIndex ?? state.cursor,\n state.scrollTop ?? 0, Math.max(0, rows - graphChromeRows), false),\n });\n }\n captureState(): unknown {\n const state = this.state.get();\n return { root: this.roots[state.cursor]?.root, interfaceId: this.roots[state.cursor]?.interfaceId,\n params: state.params, started: this.started, showObjectIds: state.showObjectIds };\n }\n restoreState(value: unknown): void {\n const state = value as { root?: string; interfaceId?: string; params?: string; started?: boolean; showObjectIds?: boolean } | undefined;\n if (!state) return;\n const cursor = this.roots.findIndex(root => root.root === state.root && root.interfaceId === state.interfaceId);\n if (cursor < 0) return;\n this.update({ cursor, params: state.params ?? \"{}\", showObjectIds: state.showObjectIds });\n if (state.started) this.start(this.options);\n }\n\n readonly commands = derived(this, (reader): readonly ViewCommand[] => {\n const state = this.state.read(reader);\n const graph = state.active || state.model !== undefined;\n if (this.disposed) return [];\n const command = (id: string, title: string, keys: readonly string[], execute: () => void, enabled = true): ViewCommand => ({\n id: `graph.${id}`, title, keybindings: keys.map(key => ({ key })), enabled, execute,\n context: state.editing ? \"Editing parameters\" : graph ? \"Graph\" : \"Roots\",\n });\n if (state.editing) return [\n command(\"finishParams\", \"Finish parameters\", [\"return\", \"escape\"], () => this.update({ editing: false })),\n command(\"deleteParam\", \"Delete character\", [\"backspace\", \"delete\"],\n () => this.update({ params: this.state.get().params.slice(0, -1) }), state.params.length > 0),\n ];\n const model = state.model;\n const index = graph ? model?.selectedIndex ?? 0 : state.cursor;\n const count = graph ? model?.lines.length ?? 0 : this.roots.length;\n const move = (delta: number) => {\n if (!graph) this.selectRoot(Math.max(0, Math.min(this.roots.length - 1, this.state.get().cursor + delta)));\n else this.enqueue(model => model.move(delta));\n };\n const select = (last: boolean) => {\n if (!graph) this.selectRoot(last ? this.roots.length - 1 : 0);\n else this.enqueue(model => model.select(last ? model.lines.length - 1 : 0));\n };\n const page = Math.max(1, (state.viewportRows ?? 24) - graphChromeRows);\n const selected = model?.lines[model.selectedIndex];\n return [\n command(\"up\", \"Previous\", [\"up\", \"k\"], () => move(-1), index > 0),\n command(\"down\", \"Next\", [\"down\", \"j\"], () => move(1), index + 1 < count),\n command(\"pageUp\", \"Page up\", [\"pageup\"], () => move(-page), index > 0),\n command(\"pageDown\", \"Page down\", [\"pagedown\"], () => move(page), index + 1 < count),\n command(\"first\", \"First\", [\"home\", \"g\"], () => select(false), index > 0),\n command(\"last\", \"Last\", [\"end\", \"G\"], () => select(true), index + 1 < count),\n ...graph ? [\n command(\"collapse\", \"Collapse / parent\", [\"left\", \"h\", \"backspace\"],\n () => this.enqueue(model => model.collapseSelected()), !!selected && (selected.expanded || selected.depth > 0)),\n command(\"expand\", \"Expand / follow\", [\"right\", \"return\", \"l\", \" \"],\n () => this.enqueue(model => model.expandSelected()), !state.busy && !!selected && (selected.expandable || selected.targetKey !== undefined)),\n command(\"ids\", state.showObjectIds ? \"Hide object IDs\" : \"Show object IDs\", [\"i\"],\n () => this.update({ showObjectIds: !this.state.get().showObjectIds }), !!model),\n command(\"roots\", \"Roots\", [\"r\"], () => {\n this.started = false; this.cancel(); this.update({ active: false, model: undefined, error: undefined, scrollTop: 0, version: undefined });\n }),\n ] : [\n command(\"attach\", \"Open root\", [\"return\"], () => this.start(this.options), count > 0),\n ],\n command(\"params\", \"Edit parameters\", [\"p\"], () => {\n this.started = false; this.cancel(); this.update({ editing: true, active: false, model: undefined, version: undefined, scrollTop: 0 });\n }, this.roots.length > 0),\n ];\n });\n\n private selectRoot(cursor: number): void {\n const state = this.state.get();\n this.update({ cursor, scrollTop: clampGraphScroll(this.roots.length, cursor, state.scrollTop ?? 0,\n Math.max(0, (state.viewportRows ?? 24) - graphChromeRows)) });\n }\n\n handleTextInput(event: ViewKeyEvent): boolean {\n if (this.disposed || !this.capturesInput) return false;\n if (event.ctrl || event.meta || !event.input || /[\\x00-\\x1f\\x7f]/.test(event.input)) return false;\n this.update({ params: this.state.get().params + event.input });\n return true;\n }\n\n private enqueue(execute: (model: GraphExplorerModel) => void | Promise<void>): void {\n const state = this.state.get();\n const model = state.model;\n if (!model) return;\n const generation = this.generation;\n this.action = this.action.then(async () => {\n if (this.disposed || generation !== this.generation) return;\n this.update({ busy: true, error: undefined });\n await execute(model);\n if (!this.disposed && generation === this.generation) this.update({\n busy: false, scrollTop: clampGraphScroll(model.lines.length, model.selectedIndex, this.state.get().scrollTop ?? 0,\n Math.max(0, (this.state.get().viewportRows ?? 24) - graphChromeRows)),\n });\n }).catch(error => {\n if (!this.disposed && generation === this.generation) this.update({ busy: false, error: String(error) });\n });\n }\n\n start(options: Readonly<Record<string, unknown>> = this.options): void {\n if (this.disposed) return;\n this.options = options;\n this.cancel();\n const generation = this.generation;\n const state = this.state.get();\n const root = this.roots[state.cursor];\n if (!root) { this.update({ error: \"No compatible graph roots\" }); return; }\n let params: unknown;\n try { params = JSON.parse(state.params); }\n catch { this.update({ error: \"Root parameters must be valid JSON\" }); return; }\n const stop = new Promise<void>(resolve => { this.stop = resolve; });\n this.started = true;\n this.update({ active: true, model: undefined, error: undefined, version: undefined, scrollTop: 0, busy: false, refreshing: false });\n const completion = inspectGraphCommand(this.context.channel, {\n targets: [root], root: root.root, params, stop, watch: true, depth: 0, interactive: false,\n maxObjects: options.maxObjects as number | undefined,\n maxBytes: options.maxBytes as number | undefined,\n maxRounds: options.maxRounds as number | undefined,\n timeoutMs: options.timeoutMs as number | undefined,\n logTiming: options.logTiming === true,\n onUpdating: async () => {\n if (this.disposed || generation !== this.generation) return;\n this.update({ refreshing: true });\n await this.action;\n },\n onModel: async (model, version) => {\n while (!this.disposed && generation === this.generation) {\n const action = this.action;\n await action;\n if (this.disposed || generation !== this.generation) return;\n await model.restoreExpanded(undefined, this.state.get().model);\n if (action !== this.action) continue;\n if (!this.disposed && generation === this.generation) {\n const previous = this.state.get();\n const top = previous.model ? anchorGraphScrollTop(previous.model.lines, model.lines, previous.scrollTop ?? 0) : 0;\n this.update({ model, version, refreshing: false,\n scrollTop: clampGraphScroll(model.lines.length, model.selectedIndex, top,\n Math.max(0, (previous.viewportRows ?? 24) - graphChromeRows), false) });\n }\n return;\n }\n },\n }).then(() => {\n if (!this.disposed && generation === this.generation) this.update({ active: false, refreshing: false });\n }, error => {\n if (!this.disposed && generation === this.generation) this.update({ active: false, refreshing: false, error: String(error) });\n });\n this.pending.add(completion);\n void completion.then(() => this.pending.delete(completion), () => this.pending.delete(completion));\n }\n\n update(value: Partial<State>): void {\n if (this.disposed) return;\n const previous = this.state.get();\n this.state.set({ ...previous, ...value, revision: previous.revision + 1 }, undefined);\n }\n private cancel(): void { this.generation++; this.stop?.(); this.stop = undefined; }\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.cancel();\n this.state.set({ ...this.state.get(), revision: this.state.get().revision + 1 }, undefined);\n }\n async disposeAsync(): Promise<void> {\n this.dispose();\n await Promise.allSettled([...this.pending, this.action]);\n }\n}\n\nexport class GraphPanel extends React.Component<{ readonly session: GraphSession }, { revision: number }> {\n state = { revision: 0 };\n private subscription: { dispose(): void } | undefined;\n componentDidMount(): void {\n this.subscription = autorun(reader => {\n const value = this.props.session.state.read(reader);\n this.setState({ revision: value.revision });\n });\n }\n componentWillUnmount(): void { this.subscription?.dispose(); }\n render(): React.ReactNode {\n const session = this.props.session;\n const state = session.state.get();\n const model = state.model;\n const height = Math.max(1, state.viewportRows ?? stdout.rows ?? 24);\n const width = Math.max(1, state.viewportColumns ?? stdout.columns ?? 80);\n const root = session.roots[state.cursor];\n const graph = state.active || model !== undefined;\n const status = state.error ?? (state.refreshing ? \"Refreshing root…\"\n : state.busy ? \"Loading object…\" : undefined);\n const frame = createGraphFrame(model, {\n title: root ? `${root.serviceId || \"local\"} / ${root.interfaceId} / ${root.root}` : \"No compatible roots\",\n params: `params: ${state.params}${state.editing ? \"█\" : \"\"}`,\n rows: height, columns: width, scrollTop: state.scrollTop ?? 0,\n revealSelection: false, version: state.version, showObjectIds: state.showObjectIds, status,\n error: state.error !== undefined,\n phase: !graph ? state.editing ? \"EDIT PARAMETERS\" : \"SELECT ROOT\"\n : !state.active ? `STOPPED${state.version === undefined ? \"\" : ` v${state.version}`}` : undefined,\n });\n let rows: readonly GraphFrameRow[] = frame.rows;\n if (!graph) {\n const capacity = Math.max(0, height - graphChromeRows);\n const top = state.scrollTop ?? 0;\n rows = ([\n ...rows.slice(0, 3),\n ...Array.from({ length: capacity }, (_, offset): GraphFrameRow => {\n const item = session.roots[top + offset];\n return { text: item ? ` ${item.serviceId || \"local\"} / ${item.interfaceId} / ${item.root}` : \"\",\n style: item && top + offset === state.cursor ? \"selected\" : \"value\" };\n }),\n { text: ` ${\"─\".repeat(Math.max(0, width - 2))}`, style: \"muted\" },\n { text: state.error ?? ` schema: ${JSON.stringify(root?.paramsArgument.schema ?? {})}`, style: state.error ? \"error\" : \"muted\" },\n { text: ` ${root ? state.cursor + 1 : 0}/${session.roots.length} roots`, style: \"reference\" },\n ] satisfies readonly GraphFrameRow[]).slice(0, height);\n }\n return <Box flexDirection=\"column\" width={width} height={height} flexShrink={0} overflow=\"hidden\">\n {rows.map((row, index) => <Text key={index} wrap=\"truncate-end\"\n bold={row.style === \"header\" || row.style === \"selected\"}\n dimColor={row.style === \"muted\"}\n color={row.style === \"selected\" ? \"black\" : row.style === \"error\" ? \"red\"\n : row.style === \"header\" || row.style === \"reference\" ? \"cyan\" : \"white\"}\n backgroundColor={row.style === \"selected\" ? \"cyan\" : undefined}>\n {graphFrameText(row.text, width, row.style === \"selected\") || \" \"}\n </Text>)}\n </Box>;\n }\n}\n\nexport async function runGraphTui(context: ViewOpenContext, roots: readonly GraphTarget[], options: Readonly<Record<string, unknown>>): Promise<void> {\n const session = new GraphSession(context, roots, options);\n const cursor = roots.findIndex(root => (options.root === undefined || root.root === options.root)\n && (options.interface === undefined || root.interfaceId === options.interface));\n if (cursor < 0) throw new Error(\"No matching graph root\");\n session.update({ cursor, params: String(options.params ?? \"{}\") });\n const running = runViewTui(session);\n if (roots.length === 1 || options.root !== undefined) session.start(options);\n await running;\n}\n","import { interfaceTemplateArgumentsEquivalent } from \"@hediet/linkrpc\";\nimport { GRAPH_INTERFACE_TAG, graphPresentationInterface } from \"@hediet/linkrpc-infra/graph\";\nimport type { ViewContribution, ViewOpenContext } from \"../../views/types\";\nimport { graphDescriptorsFromSchema, inspectGraphCommand, type GraphTarget } from \"./inspectGraph\";\nimport { GraphSession, runGraphTui } from \"./session\";\n\nexport function resolveGraphRoots(context: ViewOpenContext): GraphTarget[] {\n return context.interfaces.flatMap(listing => {\n const presentation = (context.target.serviceInterfaces ?? context.target.interfaces).find(candidate =>\n candidate.serviceId === listing.serviceId && candidate.interfaceId === graphPresentationInterface.info.id\n && candidate.hash === graphPresentationInterface.toSchema().hash);\n const { roots, stores } = graphDescriptorsFromSchema({ ...listing, hash: listing.hash ?? \"\" }, listing.schema);\n return roots.map(root => {\n const compatible = stores.filter(store => interfaceTemplateArgumentsEquivalent(store.refArgument, root.refArgument));\n if (compatible.length !== 1) throw new Error(`Root \"${root.root}\" requires exactly one compatible object store`);\n const store = compatible[0]!;\n const route = (method: string) => listing.isDefault ? method.slice(method.lastIndexOf(\"::\") + 2) : method;\n return {\n ...root, graphInterfaceId: store.interfaceId, watchMethod: route(root.watchMethod),\n batchMethod: route(store.batchMethod), valueArgument: store.valueArgument,\n ...(presentation === undefined ? {} : {\n presentationMethod: presentation.isDefault ? \"get\"\n : [presentation.serviceId, presentation.interfaceId, \"get\"].filter(Boolean).join(\"::\"),\n }),\n };\n });\n });\n}\n\nexport const graphView: ViewContribution = {\n id: \"graph\", title: \"Graph\", modes: [\"cli\", \"tui\"],\n conditions: [\n { kind: \"interface\", interface: { tag: GRAPH_INTERFACE_TAG } },\n { kind: \"service\", implements: { tag: GRAPH_INTERFACE_TAG } },\n ],\n configureCommand(command) {\n command\n .option(\"--mode <mode>\", \"roots, snapshot, or watch (watch --json emits one snapshot per JSONL line)\", \"snapshot\")\n .option(\"--root <name>\", \"root instance name (required if ambiguous)\")\n .option(\"--params <json>\", \"root parameters as JSON\", \"{}\")\n .option(\"--depth <number>\", \"snapshot traversal depth\", nonNegativeInteger)\n .option(\"--path <pointer>\", \"graph JSON pointer selector\")\n .option(\"--max-objects <number>\", \"maximum objects per batch\", positiveInteger)\n .option(\"--max-bytes <number>\", \"maximum bytes per batch\", positiveInteger)\n .option(\"--max-rounds <number>\", \"maximum batch rounds\", positiveInteger)\n .option(\"--log-timing\", \"write graph timing diagnostics to stderr\");\n },\n async open(context, options) {\n const mode = options.mode ?? \"snapshot\";\n if (![\"roots\", \"snapshot\", \"watch\"].includes(String(mode))) throw new Error(\"--mode must be roots, snapshot, or watch\");\n const roots = resolveGraphRoots(context);\n if (roots.length === 0) throw new Error(\"Selected target has no compatible graph roots; advertised tags are not a contract\");\n const selected = roots.filter(root => (options.root === undefined || root.root === options.root)\n && (options.interface === undefined || root.interfaceId === options.interface));\n if (options.tui === true) {\n if (options.json === true || mode !== \"snapshot\") throw new Error(\"--tui cannot be combined with --json or --mode roots/watch\");\n if (options.path !== undefined || options.depth !== undefined) throw new Error(\"--tui loads on demand; --path and --depth apply to snapshots/watch\");\n if (selected.length === 0) throw new Error(\"No matching graph root. Use --mode roots.\");\n if (options.root !== undefined && selected.length > 1) throw new Error(\"Graph root is ambiguous; specify --interface\");\n await runGraphTui(context, selected, options);\n return \"\";\n }\n if (mode === \"roots\") {\n const rows = selected.map(root => ({ interfaceId: root.interfaceId, root: root.root, params: root.paramsArgument }));\n return options.json ? JSON.stringify(rows, null, 2) : rows.map(row => `${row.interfaceId} ${row.root} ${JSON.stringify(row.params.schema)}`).join(\"\\n\");\n }\n if (selected.length !== 1) throw new Error(selected.length === 0\n ? \"No matching graph root. Use --mode roots.\"\n : \"Graph root is ambiguous. Use --mode roots, then --root and optionally --interface.\");\n let params: unknown;\n try { params = JSON.parse(String(options.params ?? \"{}\")); }\n catch { throw new Error(\"--params must be valid JSON\"); }\n let stop!: () => void;\n const stopped = options.stop as Promise<void> | undefined ?? new Promise<void>(resolve => { stop = resolve; });\n const onStop = () => stop?.();\n process.once(\"SIGINT\", onStop);\n process.once(\"SIGTERM\", onStop);\n try {\n return await inspectGraphCommand(context.channel, {\n targets: selected, root: selected[0]!.root, params,\n depth: options.depth as number | undefined, path: options.path as string | undefined,\n watch: mode === \"watch\", json: options.json === true, interactive: false, stop: stopped,\n maxObjects: options.maxObjects as number | undefined,\n maxBytes: options.maxBytes as number | undefined,\n maxRounds: options.maxRounds as number | undefined,\n timeoutMs: options.timeoutMs as number | undefined,\n logTiming: options.logTiming === true,\n emit: options.emit as ((text: string) => void) | undefined,\n });\n } finally {\n process.off(\"SIGINT\", onStop);\n process.off(\"SIGTERM\", onStop);\n }\n },\n createSession(context) { return new GraphSession(context, resolveGraphRoots(context)); },\n};\n\nfunction nonNegativeInteger(value: string): number {\n const number = Number(value);\n if (!Number.isSafeInteger(number) || number < 0) throw new Error(\"Expected a non-negative integer\");\n return number;\n}\nfunction positiveInteger(value: string): number {\n const number = nonNegativeInteger(value);\n if (number === 0) throw new Error(\"Expected a positive integer\");\n return number;\n}\n","import type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { computeInterfaceHash, type JsonValue } from \"@hediet/linkrpc\";\nimport { parse } from \"zod/mini\";\nimport {\n applyJsonDocumentEdits, loggingInterface, logDocumentSchema, logStreamEventSchema,\n type LogDocument, type LogEntry, type LogLevel,\n} from \"@hediet/linkrpc-infra\";\nimport type { ResolvedViewInterface, ViewOpenContext } from \"../../views/types\";\n\nexport const levels = [\"trace\", \"debug\", \"info\", \"warn\", \"error\"] as const;\nexport interface LoggingTarget {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n readonly route: (member: string) => string;\n}\nexport interface LogFrame {\n readonly revision: number;\n readonly document: LogDocument;\n readonly entries: readonly LogEntry[];\n readonly hidden: number;\n}\nexport interface LogOptions {\n readonly level: LogLevel;\n readonly tail: number;\n readonly maxBytes: number;\n readonly timeoutMs: number;\n}\n\nexport function resolveLoggingTargets(context: ViewOpenContext): LoggingTarget[] {\n const selected = context.interfaces.filter(listing =>\n listing.interfaceId === \"linkrpc.logging\" || listing.tags?.includes(\"linkrpc.logging\"));\n return selected.map(listing => {\n validateLoggingSchema(listing);\n return {\n serviceId: listing.serviceId, interfaceId: listing.interfaceId, hash: listing.schema.hash,\n route: member => listing.isDefault ? member\n : [listing.serviceId, listing.interfaceId, member].filter(Boolean).join(\"::\"),\n };\n });\n}\n\nfunction validateLoggingSchema(listing: ResolvedViewInterface): void {\n const canonical = loggingInterface.toSchema();\n if (listing.interfaceId !== canonical.id\n || listing.schema.id !== canonical.id\n || computeInterfaceHash({ ...canonical, methods: listing.schema.methods,\n components: listing.schema.components }) !== canonical.hash) {\n throw new Error(`Interface ${listing.interfaceId} does not implement the canonical logging contract (tags are discovery hints)`);\n }\n}\n\nexport function logOptions(options: Readonly<Record<string, unknown>>): LogOptions {\n const level = String(options.level ?? \"trace\") as LogLevel;\n if (![...levels, \"off\"].includes(level)) throw new Error(\"--level must be trace, debug, info, warn, error, or off\");\n const tail = options.tail ?? 200;\n const maxBytes = options.maxBytes ?? 2_000_000;\n const timeoutMs = options.timeoutMs ?? 5_000;\n if (!Number.isSafeInteger(tail) || Number(tail) < 1 || Number(tail) > 10_000) throw new Error(\"--tail must be an integer from 1 to 10000\");\n if (!Number.isSafeInteger(maxBytes) || Number(maxBytes) < 1024 || Number(maxBytes) > 50_000_000) throw new Error(\"--max-bytes must be an integer from 1024 to 50000000\");\n if (!Number.isSafeInteger(timeoutMs) || Number(timeoutMs) < 1) throw new Error(\"--timeout-ms must be a positive integer\");\n return { level, tail: Number(tail), maxBytes: Number(maxBytes), timeoutMs: Number(timeoutMs) };\n}\n\nfunction flatten(entries: readonly LogEntry[], result: LogEntry[] = [], depth = 0): LogEntry[] {\n if (depth > 32) throw new Error(\"Log entry nesting exceeds 32 levels\");\n for (const entry of entries) {\n result.push(entry);\n if (entry.entries) flatten(entry.entries, result, depth + 1);\n }\n return result;\n}\n\nexport function frame(revision: number, document: LogDocument, options: LogOptions): LogFrame {\n const filtered = flatten(document.entries).filter(entry =>\n options.level !== \"off\" && levels.indexOf(entry.level) >= levels.indexOf(options.level as typeof levels[number]));\n return {\n revision, document, entries: filtered.slice(-options.tail),\n hidden: filtered.length - Math.min(filtered.length, options.tail),\n };\n}\n\nfunction checkedDocument(value: unknown, maxBytes: number): LogDocument {\n checkedSize(value, maxBytes);\n return parse(logDocumentSchema, value);\n}\n\nfunction checkedSize(value: unknown, maxBytes: number): void {\n if (Buffer.byteLength(JSON.stringify(value) ?? \"\", \"utf8\") > maxBytes) {\n throw new Error(`Logging payload exceeds --max-bytes (${maxBytes}); stream stopped to bound memory`);\n }\n}\n\nexport async function readLogSnapshot(channel: CliChannel, target: LoggingTarget, options: LogOptions): Promise<LogFrame> {\n const value = await withDeadline(\n channel.sendRequest(target.route(\"getLogSnapshot\"), {}, { interfaceHash: target.hash }), options.timeoutMs);\n const result = value as { revision?: unknown; document?: unknown };\n if (!Number.isSafeInteger(result?.revision) || Number(result.revision) < 0) throw new Error(\"Invalid logging snapshot revision\");\n return frame(Number(result.revision), checkedDocument(result.document, options.maxBytes), options);\n}\n\nexport async function watchLog(\n channel: CliChannel, target: LoggingTarget, options: LogOptions,\n emit: (value: LogFrame) => void, stop: Promise<void>,\n): Promise<void> {\n let revision: number | undefined;\n let document: LogDocument | undefined;\n let pending = 0;\n let queue = Promise.resolve();\n let fail!: (error: unknown) => void;\n const failure = new Promise<never>((_, reject) => { fail = reject; });\n const call = channel.sendRequestWithStream(target.route(\"watchLog\"), {}, {\n interfaceHash: target.hash,\n onStreamMessage: payload => {\n if (++pending > 128) { fail(new Error(\"Logging stream backlog exceeded 128 events; stopping slow consumer\")); return; }\n queue = queue.then(async () => {\n try {\n checkedSize(payload, options.maxBytes);\n const event = logStreamEventSchema.parse(payload);\n if (event.type === \"snapshot\") {\n revision = event.revision;\n document = checkedDocument(event.document, options.maxBytes);\n } else {\n if (revision === undefined || event.revision !== revision + 1) {\n const latest = await readLogSnapshot(channel, target, options);\n revision = latest.revision;\n document = latest.document;\n emit(latest);\n if (event.revision <= revision) return;\n if (event.revision !== revision + 1) throw new Error(`Logging revision gap after resync: ${revision} -> ${event.revision}`);\n }\n // A validated wire document is JSON data, but its domain\n // interface has no index signature required by JsonValue.\n const jsonDocument: JsonValue = JSON.parse(JSON.stringify(document));\n document = checkedDocument(applyJsonDocumentEdits(jsonDocument, event.edits), options.maxBytes);\n revision = event.revision;\n }\n emit(frame(revision, document, options));\n } finally { pending--; }\n }).catch(fail);\n },\n });\n const timer = setTimeout(() => {\n if (revision === undefined) fail(new Error(`Logging watch produced no snapshot within ${options.timeoutMs}ms`));\n }, options.timeoutMs);\n try {\n const outcome = await Promise.race([call.result.then(() => \"ended\" as const), stop.then(() => \"stop\" as const), failure]);\n await Promise.race([queue, failure]);\n if (outcome === \"ended\" && revision === undefined) throw new Error(\"Logging watch ended without a snapshot\");\n } finally {\n clearTimeout(timer);\n call.cancel(\"logging view closed\");\n call.dispose?.();\n void call.result.catch(() => {});\n }\n}\n\nasync function withDeadline<T>(promise: Promise<T>, ms: number): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([promise, new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`Logging snapshot timed out after ${ms}ms`)), ms);\n })]);\n } finally { clearTimeout(timer); }\n}\n","import React from \"react\";\nimport { Box, Text } from \"ink\";\nimport { autorun, derived, observableValue } from \"@vscode/observables\";\nimport type { ViewCommand, ViewOpenContext, ViewSession } from \"../../views/types\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\nimport { levels, watchLog, type LoggingTarget, type LogFrame, type LogOptions } from \"./model\";\nimport type { LogEntry } from \"@hediet/linkrpc-infra\";\n\ninterface State {\n readonly revision: number;\n readonly frame?: LogFrame;\n readonly cursor: number;\n readonly paused: boolean;\n readonly follow: boolean;\n readonly level: LogOptions[\"level\"];\n readonly cleared: readonly LogEntry[];\n readonly rows: number;\n readonly error?: string;\n}\n\nexport class LoggingSession implements ViewSession {\n readonly state = observableValue<State>(this, {\n revision: 0, cursor: 0, paused: false, follow: true, level: \"trace\", cleared: [], rows: 24,\n });\n readonly element = <LoggingPanel session={this} />;\n private stop!: () => void;\n private completion: Promise<void> | undefined;\n private disposed = false;\n private generation = 0;\n private latest?: LogFrame;\n constructor(private readonly context: ViewOpenContext, readonly target: LoggingTarget, private readonly options: LogOptions) {\n this.update({ level: options.level });\n this.start();\n }\n private update(patch: Partial<State>): void {\n if (this.disposed) return;\n const state = this.state.get();\n this.state.set({ ...state, ...patch, revision: state.revision + 1 }, undefined);\n }\n private start(): void {\n const generation = ++this.generation;\n const stop = new Promise<void>(resolve => { this.stop = resolve; });\n this.completion = watchLog(this.context.channel, this.target, { ...this.options, level: \"trace\" }, value => {\n if (this.disposed || generation !== this.generation) return;\n this.latest = value;\n const state = this.state.get();\n if (state.paused) return;\n this.showLatest();\n }, stop).then(() => {\n if (!this.disposed && generation === this.generation) this.update({ error: \"Logging watch ended\" });\n }, error => {\n if (!this.disposed && generation === this.generation) this.update({ error: String(error) });\n });\n }\n private showLatest(): void {\n if (!this.latest) return;\n const state = this.state.get();\n const cleared = state.frame && this.latest.revision < state.frame.revision\n ? [] : retainedCleared(state.cleared, this.latest.entries);\n const entries = visibleEntries({ ...state, frame: this.latest, cleared });\n this.update({ frame: this.latest, cleared, cursor: state.follow\n ? Math.max(0, entries.length - 1) : Math.min(state.cursor, Math.max(0, entries.length - 1)) });\n }\n get displayedEntries(): readonly LogEntry[] { return visibleEntries(this.state.get()); }\n setViewport(rows: number): void { if (this.state.get().rows !== rows) this.update({ rows }); }\n captureState(): unknown {\n const { level, follow, paused } = this.state.get();\n return { level, follow, paused };\n }\n restoreState(value: unknown): void {\n const state = value as Partial<Pick<State, \"level\" | \"follow\" | \"paused\">> | undefined;\n if (state) this.update({\n level: [...levels, \"off\"].includes(state.level as typeof levels[number]) ? state.level : this.state.get().level,\n follow: state.follow === false ? false : true, paused: state.paused === true,\n });\n }\n readonly commands = derived(this, (reader): readonly ViewCommand[] => {\n const state = this.state.read(reader);\n if (this.disposed) return [];\n const entries = visibleEntries(state);\n const command = (id: string, title: string, key: string, execute: () => void, enabled = true): ViewCommand =>\n ({ id: `logging.${id}`, title, context: \"Logging\", keybindings: [{ key }], execute, enabled });\n const move = (delta: number) => this.update({\n cursor: Math.max(0, Math.min(entries.length - 1, this.state.get().cursor + delta)),\n follow: false,\n });\n return [\n command(\"up\", \"Previous entry\", \"up\", () => move(-1), state.cursor > 0),\n command(\"down\", \"Next entry\", \"down\", () => move(1), state.cursor + 1 < entries.length),\n command(\"pageUp\", \"Page up\", \"pageup\", () => move(-Math.max(1, state.rows - 4)), state.cursor > 0),\n command(\"pageDown\", \"Page down\", \"pagedown\", () => move(Math.max(1, state.rows - 4)), state.cursor + 1 < entries.length),\n command(\"follow\", state.follow ? \"Stop following\" : \"Follow latest\", \"f\",\n () => this.update({ follow: !state.follow, cursor: state.follow ? state.cursor : Math.max(0, entries.length - 1) })),\n command(\"pause\", state.paused ? \"Resume updates\" : \"Pause updates\", \"p\", () => {\n this.update({ paused: !state.paused });\n if (state.paused) this.showLatest();\n }),\n command(\"clear\", \"Clear displayed entries (local)\", \"c\",\n () => this.update({ cleared: state.frame?.entries ?? [], cursor: 0 })),\n command(\"filter\", `Minimum level: ${state.level}`, \"l\", () => {\n const list = [...levels, \"off\"] as const;\n this.update({ level: list[(list.indexOf(state.level) + 1) % list.length]!, cursor: 0 });\n }),\n ];\n });\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n this.generation++;\n this.stop?.();\n this.state.set({ ...this.state.get(), revision: this.state.get().revision + 1 }, undefined);\n }\n async disposeAsync(): Promise<void> { this.dispose(); await this.completion; }\n}\n\nfunction visibleEntries(state: State): readonly LogEntry[] {\n return state.frame?.entries.slice(state.cleared.length).filter(entry =>\n state.level !== \"off\" && levels.indexOf(entry.level) >= levels.indexOf(state.level as typeof levels[number])) ?? [];\n}\n\nfunction retainedCleared(previous: readonly LogEntry[], current: readonly LogEntry[]): readonly LogEntry[] {\n if (previous.length === 0 || current.length === 0) return [];\n const oldKeys = previous.map(entry => JSON.stringify(entry));\n const newKeys = current.map(entry => JSON.stringify(entry));\n // The wire format has no entry identity. Ambiguous duplicate values must\n // reappear rather than accidentally hiding a newly appended identical log.\n if (new Set(oldKeys).size !== oldKeys.length || new Set(newKeys).size !== newKeys.length) return [];\n for (let count = Math.min(previous.length, current.length); count > 0; count--) {\n if (oldKeys.slice(-count).every((key, index) => key === newKeys[index])) return current.slice(0, count);\n }\n return [];\n}\n\nexport class LoggingPanel extends React.Component<{ readonly session: LoggingSession }, { revision: number }> {\n state = { revision: 0 };\n private subscription?: { dispose(): void };\n componentDidMount(): void {\n this.subscription = autorun(reader => this.setState({ revision: this.props.session.state.read(reader).revision }));\n }\n componentWillUnmount(): void { this.subscription?.dispose(); }\n render(): React.ReactNode {\n const state = this.props.session.state.get();\n const entries = this.props.session.displayedEntries;\n const rows = Math.max(1, state.rows - 4);\n const start = Math.max(0, Math.min(state.cursor, entries.length - 1) - rows + 1);\n return <Box flexDirection=\"column\" flexGrow={1} overflow=\"hidden\">\n <Text bold>Logging {safeTerminalText(this.props.session.target.serviceId || \"<root>\")} revision {state.frame?.revision ?? \"…\"}</Text>\n <Text dimColor>level {state.level} · {state.paused ? \"paused\" : \"live\"} · {state.follow ? \"follow\" : \"manual\"} · {state.frame?.hidden ?? 0} earlier hidden · clear is local</Text>\n {state.error && <Text color=\"red\">{safeTerminalText(state.error)}</Text>}\n {entries.slice(start, start + rows).map((entry, index) =>\n <Text key={`${start + index}:${entry.timestamp}`} color={start + index === state.cursor ? \"cyan\" : undefined} wrap=\"truncate-end\">\n {start + index === state.cursor ? \"› \" : \" \"}\n {safeTerminalText(`${entry.timestamp} ${entry.level.toUpperCase()} ${entry.message}`\n + (entry.attributes ? ` ${JSON.stringify(entry.attributes)}` : \"\")\n + (entry.error ? ` ${entry.error.name ?? \"Error\"}: ${entry.error.message}${entry.error.stack ? ` ${entry.error.stack}` : \"\"}` : \"\"))}\n </Text>)}\n </Box>;\n }\n}\n","import { runViewTui } from \"../../views/runViewTui\";\nimport type { ViewContribution } from \"../../views/types\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\nimport { LoggingSession } from \"./session\";\nimport { logOptions, readLogSnapshot, resolveLoggingTargets, watchLog, type LogFrame } from \"./model\";\n\nexport function formatLogFrame(value: LogFrame, json: boolean): string {\n if (json) return JSON.stringify({\n revision: value.revision, service: value.document.service,\n startedAt: value.document.startedAt, state: value.document.state,\n entries: value.entries, hidden: value.hidden,\n });\n const lines = value.entries.map(entry => {\n const details = entry.attributes ? ` ${JSON.stringify(entry.attributes)}` : \"\";\n const error = entry.error ? ` ${entry.error.name ?? \"Error\"}: ${entry.error.message}${entry.error.stack ? ` ${entry.error.stack}` : \"\"}` : \"\";\n return safeTerminalText(`${entry.timestamp} ${entry.level.toUpperCase()} ${entry.message}${details}${error}`);\n });\n return [`${safeTerminalText(value.document.service)} revision=${value.revision} (${value.hidden} earlier matching entries hidden)`, ...lines].join(\"\\n\");\n}\n\nexport const loggingView: ViewContribution = {\n id: \"logging\", title: \"Logging\", modes: [\"cli\", \"tui\"],\n conditions: [\n { kind: \"interface\", interface: { interfaceId: \"linkrpc.logging\" } },\n { kind: \"service\", implements: { interfaceId: \"linkrpc.logging\" } },\n { kind: \"interface\", interface: { tag: \"linkrpc.logging\" } },\n { kind: \"service\", implements: { tag: \"linkrpc.logging\" } },\n ],\n configureCommand(command) {\n command\n .option(\"--mode <mode>\", \"snapshot (read-only) or watch (one frame per revision)\", \"snapshot\")\n .option(\"--level <level>\", \"client-side minimum level: trace, debug, info, warn, error, off\", \"trace\")\n .option(\"--tail <count>\", \"maximum displayed matching entries\", positiveInteger, 200)\n .option(\"--max-bytes <bytes>\", \"maximum in-memory log document size\", positiveInteger, 2_000_000);\n },\n async open(context, options) {\n const targets = resolveLoggingTargets(context).filter(target =>\n options.interface === undefined || target.interfaceId === options.interface);\n if (targets.length !== 1) throw new Error(targets.length\n ? \"Multiple logging interfaces in this service; use --interface or an interface --target\"\n : \"Selected target has no canonical logging interface\");\n const target = targets[0]!;\n const config = logOptions(options);\n const mode = options.mode ?? \"snapshot\";\n if (mode !== \"snapshot\" && mode !== \"watch\") throw new Error(\"--mode must be snapshot or watch\");\n if (options.tui === true) {\n if (options.json === true || mode !== \"snapshot\") throw new Error(\"--tui cannot be combined with --json or --mode watch\");\n const session = new LoggingSession(context, target, config);\n await runViewTui(session);\n return \"\";\n }\n if (mode === \"snapshot\") return formatLogFrame(await readLogSnapshot(context.channel, target, config), options.json === true);\n let release!: () => void;\n const stop = options.stop as Promise<void> | undefined ?? new Promise<void>(resolve => { release = resolve; });\n const onStop = () => release?.();\n const emit = options.emit as ((text: string) => void) | undefined ?? (text => process.stdout.write(`${text}\\n`));\n process.once(\"SIGINT\", onStop);\n process.once(\"SIGTERM\", onStop);\n try {\n await watchLog(context.channel, target, config, value => emit(formatLogFrame(value, options.json === true)), stop);\n return \"\";\n } finally {\n process.off(\"SIGINT\", onStop);\n process.off(\"SIGTERM\", onStop);\n }\n },\n createSession(context) {\n const targets = resolveLoggingTargets(context);\n if (targets.length !== 1) throw new Error(\"Logging service is ambiguous; select an interface target\");\n return new LoggingSession(context, targets[0]!, logOptions({}));\n },\n};\n\nfunction positiveInteger(text: string): number {\n const value = Number(text);\n if (!Number.isSafeInteger(value) || value < 1) throw new Error(\"Expected a positive integer\");\n return value;\n}\n","import { renderMermaidASCII } from \"beautiful-mermaid\";\nimport type { TopologyGraph } from \"@hediet/linkrpc/inspection\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\n\nexport interface TopologyDocument {\n readonly lines: readonly string[];\n readonly mermaid: string;\n readonly warnings: readonly string[];\n}\n\n/** JSON-compatible escaping also neutralizes terminal C1 and bidi controls. */\nexport function topologyJson(value: unknown, indent?: number): string {\n return JSON.stringify(value, null, indent).replace(/[\\u007f-\\u009f\\p{Cf}\\p{Zl}\\p{Zp}]/gu,\n character => character.split(\"\").map(unit => `\\\\u${unit.charCodeAt(0).toString(16).padStart(4, \"0\")}`).join(\"\"));\n}\n\nfunction boxHint(label: string): string {\n const text = label.replace(/[^a-zA-Z0-9 ._-]/gu, \"_\");\n return text.length > 26 ? `${text.slice(0, 23)}...` : text;\n}\n\n/** Only generated IDs and a bounded, allowlisted label alphabet enter Mermaid syntax. */\nexport function topologyDocument(graph: TopologyGraph): TopologyDocument {\n const identifiers = new Map<string, number>();\n const warnings: string[] = [];\n for (const node of graph.nodes) {\n if (identifiers.has(node.nodeId)) throw new Error(`Duplicate topology node ID: ${safeTerminalText(JSON.stringify(node.nodeId))}`);\n identifiers.set(node.nodeId, identifiers.size);\n }\n const declared = identifiers.size;\n const include = (nodeId: string) => {\n if (!identifiers.has(nodeId)) {\n identifiers.set(nodeId, identifiers.size);\n warnings.push(`Unlisted node referenced by the result: ${topologyJson(nodeId)}`);\n }\n };\n include(graph.entryNodeId);\n for (const link of graph.links) { include(link.from.nodeId); include(link.to.nodeId); }\n for (const route of graph.routes) include(route.nodeId);\n const key = (id: string) => `N${identifiers.get(id)! + 1}`;\n const definitions = [...identifiers].map(([id, index]) =>\n `n${index}[\"${key(id)}${index >= declared ? \" unlisted\" : \"\"}${id === graph.entryNodeId ? \" entry\" : \"\"}`\n + (index < declared ? ` - ${boxHint(graph.nodes[index]!.label ?? id)}` : \"\") + '\"]');\n const pairs = new Set<string>();\n for (const link of graph.links) {\n const from = identifiers.get(link.from.nodeId)!, to = identifiers.get(link.to.nodeId)!;\n pairs.add(`n${Math.min(from, to)} --- n${Math.max(from, to)}`);\n }\n const mermaid = [\"graph LR\", ...definitions, ...pairs].join(\"\\n\");\n let diagram: string;\n if (identifiers.size > 200 || pairs.size > 400) {\n diagram = \"Diagram omitted: layout exceeds 200 nodes or 400 distinct connections. Complete records follow.\";\n } else {\n try {\n diagram = identifiers.size === 0 ? \"(empty topology)\" : renderMermaidASCII(mermaid, {\n useAscii: false, colorMode: \"none\", paddingX: 3, paddingY: 2, boxBorderPadding: 0,\n });\n } catch (error) {\n diagram = `Diagram unavailable: ${String(error)}. Complete records follow.`;\n }\n }\n const lines = [\n `TOPOLOGY — observer ${topologyJson(graph.observerServiceId)}; entry ${key(graph.entryNodeId)}`,\n \"One service's observed graph. Lines are connections, not RPC direction.\",\n \"Parallel links share a diagram line; LINKS below preserves every endpoint and transport record.\",\n \"Box labels are abbreviated ASCII-safe hints; NODES preserves complete Unicode labels.\",\n \"\",\n ...diagram.split(\"\\n\").map(line => line.trimEnd()),\n \"\",\n `NODES (${graph.nodes.length}) — complete records, including ports and descriptors`,\n ...graph.nodes.map(node => `${key(node.nodeId)} ${topologyJson(node)}`),\n ...[...identifiers].filter(([, index]) => index >= declared).map(([id]) => `${key(id)} unlisted node ${topologyJson(id)}`),\n \"\",\n `LINKS (${graph.links.length}) — from/to are transport endpoint roles, not RPC arrows`,\n ...graph.links.map((link, index) => `L${index + 1} ${key(link.from.nodeId)} -- ${key(link.to.nodeId)} ${topologyJson(link)}`),\n \"\",\n `ROUTES (${graph.routes.length}) — claims from this result only`,\n ...graph.routes.map((route, index) => `R${index + 1} ${key(route.nodeId)} ${topologyJson(route)}`),\n ...warnings.length ? [\"\", \"WARNINGS\", ...warnings] : [],\n ].map(safeTerminalText);\n return { lines, mermaid, warnings };\n}\n","import { parse } from \"zod/mini\";\nimport { computeInterfaceHash, LinkRpcConnection, type IRequestSender, type JsonValue, type RawStreamingCall, type StreamSendOpts } from \"@hediet/linkrpc\";\nimport { topologyInterface, zTopologyGraph, type TopologyGraph } from \"@hediet/linkrpc/inspection\";\nimport { TopologyClient, type TopologyWatch } from \"@hediet/linkrpc-infra/inspection\";\nimport type { ViewOpenContext } from \"../../views/types\";\n\nexport interface TopologyTarget {\n readonly serviceId: string;\n readonly hash: string;\n readonly isDefault: boolean;\n}\n\nexport function resolveTopologyTarget(context: ViewOpenContext): TopologyTarget {\n const candidates = context.interfaces.filter(value => value.interfaceId === topologyInterface.info.id);\n if (candidates.length !== 1) throw new Error(\"Select exactly one canonical hubrpc.topology interface\");\n const listing = candidates[0]!;\n const canonical = topologyInterface.toSchema();\n if (listing.schema.id !== canonical.id\n || computeInterfaceHash(listing.schema) !== listing.schema.hash\n || computeInterfaceHash({\n ...canonical, methods: listing.schema.methods, components: listing.schema.components,\n }) !== canonical.hash) {\n throw new Error(\"Selected hubrpc.topology schema does not match the canonical inspection contract\");\n }\n return { serviceId: listing.serviceId, hash: listing.schema.hash, isDefault: listing.isDefault === true };\n}\n\nexport function topologyTimeout(options: Readonly<Record<string, unknown>>): number {\n const timeout = Number(options.timeoutMs ?? 5_000);\n if (!Number.isSafeInteger(timeout) || timeout < 1) throw new Error(\"--timeout-ms must be a positive integer\");\n return timeout;\n}\n\n/**\n * A send-only, non-owning connection adapter. Typed inspection clients still validate\n * the canonical contract; this adapter supplies the selected default/qualified route.\n */\nexport class TopologyReader {\n readonly client: TopologyClient;\n private readonly calls = new Set<RawStreamingCall>();\n private readonly pending = new Set<Promise<JsonValue>>();\n private disposed = false;\n\n constructor(context: ViewOpenContext, readonly target: TopologyTarget, timeoutMs: number) {\n const start = (method: string, params: JsonValue | undefined, options?: StreamSendOpts): RawStreamingCall => {\n if (this.disposed) throw new Error(\"Topology view is closed\");\n const member = method.split(\"::\").at(-1)!;\n if (member !== \"getGraph\" && member !== \"watchGraph\") throw new Error(`Unexpected topology member: ${member}`);\n const route = target.isDefault ? member : [target.serviceId, topologyInterface.info.id, member].filter(Boolean).join(\"::\");\n const raw = context.channel.sendRequestWithStream(route, params, { ...options, interfaceHash: target.hash });\n let rejectLocal!: (error: unknown) => void;\n const result = Promise.race([raw.result, new Promise<never>((_, reject) => { rejectLocal = reject; })]);\n const call: RawStreamingCall = {\n result,\n send: value => raw.send(value),\n ping: () => raw.ping(),\n cancel: reason => raw.cancel(reason),\n dispose: reason => {\n try { raw.dispose?.(reason); }\n finally { rejectLocal(new Error(reason ?? \"Topology request disposed\")); }\n },\n };\n this.calls.add(call);\n this.pending.add(result);\n const finish = () => { this.calls.delete(call); this.pending.delete(result); };\n void result.then(finish, finish);\n return call;\n };\n const sender: IRequestSender = {\n sendRequest: (method, params, options) => start(method, params, options).result,\n sendRequestWithStream: start,\n sendNotification: async () => { throw new Error(\"Topology has no notification members\"); },\n close() {},\n };\n this.client = new TopologyClient(new LinkRpcConnection(sender), target.serviceId, timeoutMs);\n }\n\n async snapshot(): Promise<TopologyGraph> { return parse(zTopologyGraph, await this.client.getGraph()); }\n dispose(): void {\n if (this.disposed) return;\n this.disposed = true;\n for (const call of this.calls) {\n try { call.cancel(\"topology view closed\"); } catch { /* The underlying connection may already be closed. */ }\n finally { call.dispose?.(\"topology view closed\"); }\n }\n }\n async waitForIdle(): Promise<void> { await Promise.allSettled([...this.pending]); }\n}\n\nexport class TopologyObservation {\n private readonly reader: TopologyReader;\n private readonly watch: TopologyWatch;\n private readonly requests = new Set<Promise<void>>();\n private stopping = false;\n private cancellation: Promise<void> | undefined;\n readonly done: Promise<void>;\n readonly ready: Promise<TopologyGraph>;\n\n constructor(\n context: ViewOpenContext, target: TopologyTarget, timeoutMs: number,\n private readonly callbacks: { onGraph(graph: TopologyGraph): void; onError(error: unknown): void; onEnd(): void },\n ) {\n this.reader = new TopologyReader(context, target, timeoutMs);\n this.watch = this.reader.client.watch({\n onGraph: graph => this.accept(graph),\n onError: error => { if (!this.stopping) callbacks.onError(error); },\n });\n this.ready = this.watch.ready;\n void this.ready.catch(() => {});\n this.done = this.watch.done.then(\n () => { if (!this.stopping) callbacks.onEnd(); },\n error => { if (!this.stopping) { callbacks.onError(error); callbacks.onEnd(); } },\n );\n }\n private accept(graph: TopologyGraph): void {\n if (!this.stopping) this.callbacks.onGraph(parse(zTopologyGraph, graph));\n }\n refresh(): Promise<void> {\n if (this.stopping) return Promise.resolve();\n const request = this.reader.snapshot().then(graph => this.accept(graph)).catch(error => {\n if (!this.stopping) this.callbacks.onError(error);\n });\n this.requests.add(request);\n void request.then(() => this.requests.delete(request), () => this.requests.delete(request));\n return request;\n }\n dispose(): void {\n if (this.stopping) return;\n this.stopping = true;\n this.cancellation = this.watch.cancel(\"topology view closed\");\n void this.cancellation.catch(() => {});\n this.reader.dispose();\n }\n async disposeAsync(): Promise<void> {\n this.dispose();\n await Promise.allSettled([this.ready, this.done, this.cancellation, ...this.requests]);\n await this.reader.waitForIdle();\n }\n}\n\nexport async function readTopology(context: ViewOpenContext, target: TopologyTarget, timeoutMs: number): Promise<TopologyGraph> {\n const reader = new TopologyReader(context, target, timeoutMs);\n try { return await reader.snapshot(); }\n finally { reader.dispose(); await reader.waitForIdle(); }\n}\n\nexport async function watchTopology(\n context: ViewOpenContext, target: TopologyTarget, timeoutMs: number,\n onGraph: (graph: TopologyGraph) => void, stop: Promise<void>,\n): Promise<void> {\n let fail!: (error: unknown) => void;\n const failure = new Promise<never>((_, reject) => { fail = reject; });\n const observation = new TopologyObservation(context, target, timeoutMs, {\n onGraph,\n onError: fail,\n onEnd: () => fail(new Error(\"Topology invalidation watch ended\")),\n });\n try { await Promise.race([stop, failure]); }\n finally { await observation.disposeAsync(); }\n}\n","import React from \"react\";\nimport { Box, Text } from \"ink\";\nimport { autorun, derived, observableValue } from \"@vscode/observables\";\nimport type { ViewCommand, ViewOpenContext, ViewSession } from \"../../views/types\";\nimport { formatCommandLegend } from \"../../views/commands\";\nimport { safeTerminalText } from \"../../ui/terminalText\";\nimport { topologyDocument } from \"./diagram\";\nimport { TopologyObservation, type TopologyTarget } from \"./model\";\n\ninterface State {\n readonly lines: readonly string[];\n readonly rows: number;\n readonly columns: number;\n readonly top: number;\n readonly left: number;\n readonly snapshots: number;\n readonly nodes: number;\n readonly links: number;\n readonly help: boolean;\n readonly helpTop: number;\n readonly refreshing: boolean;\n readonly ended: boolean;\n readonly error?: string;\n readonly disposed: boolean;\n}\n\nexport class TopologySession implements ViewSession {\n readonly element = <TopologyPanel session={this} />;\n readonly maxLegendRows = 2;\n readonly state = observableValue<State>(this, {\n lines: [], rows: 24, columns: 80, top: 0, left: 0, snapshots: 0, nodes: 0, links: 0,\n help: false, helpTop: 0, refreshing: false, ended: false, disposed: false,\n });\n private readonly observation: TopologyObservation;\n constructor(context: ViewOpenContext, readonly target: TopologyTarget, timeoutMs: number) {\n this.observation = new TopologyObservation(context, target, timeoutMs, {\n onGraph: graph => {\n const document = topologyDocument(graph);\n this.update({ lines: document.lines, snapshots: this.state.get().snapshots + 1,\n nodes: graph.nodes.length, links: graph.links.length, error: undefined });\n },\n onError: error => this.update({ error: String(error) }),\n onEnd: () => this.update({ ended: true, error: this.state.get().error ?? \"Topology invalidation watch ended\" }),\n });\n }\n private update(patch: Partial<State>): void {\n const state = this.state.get();\n if (!state.disposed) this.state.set({ ...state, ...patch }, undefined);\n }\n setViewport(rows: number, columns = this.state.get().columns): void {\n const state = this.state.get();\n if (state.rows !== rows || state.columns !== columns) this.update({ rows, columns });\n }\n captureState(): unknown { const { top, left } = this.state.get(); return { top, left }; }\n restoreState(value: unknown): void {\n const state = value as { top?: number; left?: number } | undefined;\n if (state) this.update({ top: Math.max(0, Number(state.top) || 0), left: Math.max(0, Number(state.left) || 0) });\n }\n readonly commands = derived(this, (reader): readonly ViewCommand[] => {\n const state = this.state.read(reader);\n if (state.disposed) return [];\n const lines = this.content(state);\n const page = Math.max(1, state.rows - 2);\n const maxTop = Math.max(0, lines.length - page);\n const maxLeft = Math.max(0, lines.reduce((length, line) => Math.max(length, [...line].length), 0) - 1);\n const top = Math.min(state.help ? state.helpTop : state.top, maxTop);\n const left = state.help ? 0 : Math.min(state.left, maxLeft);\n const move = (vertical: number, horizontal = 0) => {\n const next = Math.max(0, Math.min(maxTop, top + vertical));\n this.update(state.help ? { helpTop: next } : { top: next, left: Math.max(0, Math.min(maxLeft, left + horizontal)) });\n };\n const command = (id: string, title: string, keys: readonly string[], execute: () => void, enabled = true): ViewCommand => ({\n id: `topology.${id}`, title, context: state.help ? \"Topology commands\" : \"Topology\",\n keybindings: keys.map(key => ({ key })), execute, enabled,\n });\n return [\n command(\"help\", state.help ? \"Close commands\" : \"Show commands\", [\"?\"], () => this.update({ help: !state.help, helpTop: 0 })),\n command(\"refresh\", \"Refresh snapshot\", [\"r\"], () => {\n this.update({ refreshing: true });\n void this.observation.refresh().finally(() => this.update({ refreshing: false }));\n }, !state.refreshing),\n command(\"up\", \"Scroll up\", [\"up\", \"k\"], () => move(-1), top > 0),\n command(\"down\", \"Scroll down\", [\"down\", \"j\"], () => move(1), top < maxTop),\n command(\"pageUp\", \"Page up\", [\"pageup\"], () => move(-page), top > 0),\n command(\"pageDown\", \"Page down\", [\"pagedown\"], () => move(page), top < maxTop),\n command(\"first\", \"First line\", [\"home\", \"g\"], () => move(-maxTop), top > 0),\n command(\"last\", \"Last line\", [\"end\", \"G\"], () => move(maxTop), top < maxTop),\n command(\"left\", \"Scroll left\", [\"left\", \"h\"], () => move(0, -8), !state.help && left > 0),\n command(\"right\", \"Scroll right\", [\"right\", \"l\"], () => move(0, 8), !state.help && left < maxLeft),\n command(\"pageLeft\", \"Page left\", [\"[\"], () => move(0, -state.columns), !state.help && left > 0),\n command(\"pageRight\", \"Page right\", [\"]\"], () => move(0, state.columns), !state.help && left < maxLeft),\n ];\n });\n\n private content(state: State): readonly string[] {\n // A fixed count breaks the dependency cycle between help scrolling and the\n // command list; actual help text is generated from that list in render().\n if (state.help) return Array.from({ length: 13 }, () => \"\");\n return state.lines.length ? state.lines : [state.error ? `Fetch/watch failed: ${state.error}` : \"Loading topology…\"];\n }\n displayLines(): readonly string[] {\n const state = this.state.get();\n if (!state.help) return this.content(state);\n return [\"TOPOLOGY COMMANDS (unavailable commands are marked)\", ...this.commands.get().map(command =>\n formatCommandLegend([{ ...command, enabled: true }]) + (command.enabled === false ? \" [unavailable]\" : \"\"))];\n }\n dispose(): void {\n if (this.state.get().disposed) return;\n this.state.set({ ...this.state.get(), disposed: true }, undefined);\n this.observation.dispose();\n }\n async disposeAsync(): Promise<void> { this.dispose(); await this.observation.disposeAsync(); }\n}\n\nexport class TopologyPanel extends React.Component<{ readonly session: TopologySession }, { revision: number }> {\n state = { revision: 0 };\n private subscription: { dispose(): void } | undefined;\n componentDidMount(): void {\n this.subscription = autorun(reader => {\n this.props.session.state.read(reader);\n this.setState(value => ({ revision: value.revision + 1 }));\n });\n }\n componentWillUnmount(): void { this.subscription?.dispose(); }\n render(): React.ReactNode {\n const { session } = this.props;\n const state = session.state.get();\n const lines = session.displayLines();\n const capacity = Math.max(1, state.rows - 2);\n const top = Math.min(state.help ? state.helpTop : state.top, Math.max(0, lines.length - capacity));\n const maxLeft = Math.max(0, lines.reduce((length, line) => Math.max(length, [...line].length), 0) - 1);\n const left = state.help ? 0 : Math.min(state.left, maxLeft);\n const status = state.error ? `ERROR: ${state.error}` : state.refreshing ? \"Refreshing…\"\n : `Lines ${top + 1}–${Math.min(lines.length, top + capacity)}/${lines.length} · character ${left + 1} · ${state.nodes} nodes / ${state.links} links`;\n return <Box flexDirection=\"column\" width={state.columns} height={state.rows} flexShrink={0} overflow=\"hidden\">\n {state.rows > 1 && <Box height={1} flexShrink={0} overflow=\"hidden\">\n <Text bold color={state.error ? \"red\" : \"cyan\"} wrap=\"truncate-end\">\n {safeTerminalText(`TOPOLOGY ${state.ended ? \"STOPPED\" : \"LIVE\"} — ${session.target.serviceId || \"<root>\"} · snapshot ${state.snapshots}`)}\n </Text>\n </Box>}\n {Array.from({ length: capacity }, (_, offset) => <Box key={offset} height={1} flexShrink={0} overflow=\"hidden\">\n <Text wrap=\"truncate-end\">{[...safeTerminalText(lines[top + offset] ?? \"\")].slice(left).join(\"\") || \" \"}</Text>\n </Box>)}\n {state.rows > 2 && <Box height={1} flexShrink={0} overflow=\"hidden\">\n <Text dimColor={!state.error} color={state.error ? \"red\" : undefined} wrap=\"truncate-end\">{safeTerminalText(status)}</Text>\n </Box>}\n </Box>;\n }\n}\n","import type { ViewContribution } from \"../../views/types\";\nimport { topologyInterface } from \"@hediet/linkrpc/inspection\";\nimport { runViewTui } from \"../../views/runViewTui\";\nimport { topologyDocument, topologyJson } from \"./diagram\";\nimport { readTopology, resolveTopologyTarget, topologyTimeout, watchTopology } from \"./model\";\nimport { TopologySession } from \"./session\";\n\nexport const topologyView: ViewContribution = {\n id: \"topology\", title: \"Topology\", modes: [\"cli\", \"tui\"],\n conditions: [\n { kind: \"interface\", interface: { interfaceId: topologyInterface.info.id } },\n { kind: \"service\", implements: { interfaceId: topologyInterface.info.id } },\n ],\n configureCommand(command) {\n command.option(\"--mode <mode>\", \"snapshot or watch (watch --json emits complete snapshots as JSONL)\", \"snapshot\");\n },\n async open(context, options) {\n const target = resolveTopologyTarget(context);\n const timeoutMs = topologyTimeout(options);\n const mode = options.mode ?? \"snapshot\";\n if (mode !== \"snapshot\" && mode !== \"watch\") throw new Error(\"--mode must be snapshot or watch\");\n if (options.interface !== undefined && options.interface !== topologyInterface.info.id) throw new Error(\"Topology requires hubrpc.topology\");\n if (options.tui === true) {\n if (options.json === true || mode !== \"snapshot\") throw new Error(\"--tui cannot be combined with --json or --mode watch\");\n await runViewTui(new TopologySession(context, target, timeoutMs));\n return \"\";\n }\n if (mode === \"snapshot\") {\n const graph = await readTopology(context, target, timeoutMs);\n return options.json ? topologyJson(graph, 2) : topologyDocument(graph).lines.join(\"\\n\");\n }\n let release!: () => void;\n const stop = options.stop as Promise<void> | undefined ?? new Promise<void>(resolve => { release = resolve; });\n const onStop = () => release?.();\n const emit = options.emit as ((text: string) => void) | undefined ?? (text => process.stdout.write(`${text}\\n`));\n process.once(\"SIGINT\", onStop);\n process.once(\"SIGTERM\", onStop);\n try {\n await watchTopology(context, target, timeoutMs,\n graph => emit(options.json ? topologyJson(graph) : topologyDocument(graph).lines.join(\"\\n\")), stop);\n return \"\";\n } finally {\n process.off(\"SIGINT\", onStop);\n process.off(\"SIGTERM\", onStop);\n }\n },\n createSession(context) { return new TopologySession(context, resolveTopologyTarget(context), topologyTimeout({})); },\n};\n","import { graphView } from \"../infra/graph/contribution\";\nimport { loggingView } from \"../infra/logging/contribution\";\nimport { topologyView } from \"../infra/topology/contribution\";\nimport type { ViewContribution } from \"./types\";\n\nexport const views: readonly ViewContribution[] = [graphView, loggingView, topologyView];\n\nexport function getView(id: string): ViewContribution {\n const view = views.find(value => value.id === id);\n if (!view) throw new Error(`Unknown view \"${id}\". Run view list.`);\n return view;\n}\n","import type { Command } from \"commander\";\nimport type { CliChannel } from \"@hediet/linkrpc-client-internal\";\nimport { discoverViewTargets, resolveViewSelection } from \"../views/discovery\";\nimport { getView, views } from \"../views/registry\";\nimport { formatCondition } from \"../views/types\";\n\nexport function viewList(json = false): string {\n const rows = views.map(view => ({\n id: view.id, title: view.title, modes: view.modes,\n conditions: view.conditions.map(formatCondition),\n }));\n return json ? JSON.stringify(rows, null, 2)\n : [\"VIEW MODES TARGET CONDITIONS\", ...rows.map(row => `${row.id} ${row.modes.join(\",\")} ${row.conditions.join(\" | \")}`)].join(\"\\n\");\n}\n\nexport function registerViewCommands(\n program: Command,\n withChannel: (action: (channel: CliChannel) => Promise<void>) => Promise<void>,\n emit: (text: string) => void = text => { if (text) process.stdout.write(`${text}\\n`); },\n): void {\n const command = program.command(\"view\").description(\"Discover and open compiled-in interface and service views\");\n command.command(\"list\").description(\"List views, modes, and target conditions without connecting\")\n .option(\"--json\", \"JSON output\")\n .action(options => { emit(viewList(options.json)); });\n command.command(\"targets <view>\").description(\"List matching stable targets (no graph watches or object loads)\")\n .option(\"--json\", \"JSON output\")\n .option(\"--max-depth <number>\", \"directory recursion bound\", nonNegativeInteger)\n .option(\"--timeout-ms <number>\", \"reflection deadline in milliseconds\", positiveInteger)\n .action(async (id: string, options) => {\n const view = getView(id);\n await withChannel(async channel => {\n const discovery = await discoverViewTargets(channel, view, options);\n emit(options.json ? JSON.stringify(discovery, null, 2)\n : [\"TARGET KIND SERVICE INTERFACE\",\n ...discovery.targets.map(target => `${target.id} ${target.kind} ${target.serviceId || \"<root>\"} ${target.interfaceId ?? \"*\"}`),\n ...discovery.warnings.map(warning => `warning: ${warning}`)].join(\"\\n\"));\n });\n });\n const open = command.command(\"open\").description(\"Open a view; default is noninteractive, --tui is explicit\");\n for (const view of views) {\n const child = open.command(view.id).description(view.title)\n .option(\"--target <id>\", \"stable ID from view targets (otherwise resolve exact selectors on this connection)\")\n .option(\"--interface <id>\", \"exact interface ID; must uniquely resolve without --target\")\n .option(\"--service <id>\", \"exact service route; narrows --interface or selects a service target\")\n .option(\"--json\", \"JSON snapshot / JSONL watch output\")\n .option(\"--tui\", \"interactive terminal renderer\")\n .option(\"--max-depth <number>\", \"directory recursion bound\", nonNegativeInteger)\n .option(\"--timeout-ms <number>\", \"reflection and graph call deadline\", positiveInteger);\n view.configureCommand(child);\n child.action(async options => {\n if (options.target === undefined && options.interface === undefined && options.service === undefined) {\n throw new Error(\"Specify --target, or an exact --interface / --service selector\");\n }\n await withChannel(async channel => {\n const context = await resolveViewSelection(channel, view, options);\n emit(await view.open(context, options));\n });\n });\n }\n}\n\nfunction nonNegativeInteger(value: string): number {\n const result = Number(value);\n if (!Number.isSafeInteger(result) || result < 0) throw new Error(\"Expected a non-negative integer\");\n return result;\n}\nfunction positiveInteger(value: string): number {\n const result = nonNegativeInteger(value);\n if (result === 0) throw new Error(\"Expected a positive integer\");\n return result;\n}\n","import { createInterface } from 'node:readline/promises';\nimport { Command, InvalidArgumentError, Option } from 'commander';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { managedEndpointsInterface } from '@hediet/linkrpc-hub-daemon/client';\nimport { resolveLocalEndpoint } from './localEndpoint';\nimport { checkDaemonInterfaces, contextNamespace, registerServices, restartLocalDaemon, serviceAttachCommand, useLocalManagement } from './commands/services';\nimport { DetachKeys } from './commands/consoleSession';\nimport { attachConsole, listConsoleTargets } from './commands/consoleAttach';\nimport { bootstrapApprovalCapability } from '@hediet/linkrpc-infra/approval';\nimport { LinkRpcConnection, type JsonValue } from '@hediet/linkrpc';\nimport { connectNdjson, formatEndpointUri, isHubEndpoint, parseEndpointUri } from '@hediet/linkrpc/node';\nimport { connectionTokenBinderInterface } from '@hediet/linkrpc-hub/hub/server/connection-token-binder';\nimport { tapTransport } from '@hediet/linkrpc-hub/hub/server/transit';\nimport { callCommand, notifyCommand } from './commands/call';\nimport { listCaps } from './commands/caps';\nimport { executeBatch, parseBatchArgs } from './commands/batch';\nimport {\n disconnectBroker,\n getBrokerStatus,\n stopConnectionBroker,\n readBrokerNotifications,\n} from './commands/connectionBrokerClient';\nimport {\n runConnectionBroker,\n spawnConnectionBroker,\n} from './commands/connectionBrokerProcess';\nimport { parseDuration, parseConnectionLimit, parseConnectionLimitMilliseconds, type ConnectionLimit } from './duration';\nimport { checkCompatCommand, formatVerdict } from './commands/checkCompat';\nimport { codegenCommand } from './commands/codegen';\nimport { exportContractCommand } from './commands/contract';\nimport { completionsCommand } from './commands/completions';\nimport { defaultsCommand } from './commands/defaults';\nimport { hashCommand } from './commands/hash';\nimport { internalCompleteCommand } from './commands/internalComplete';\nimport { lsCommand, requestDirectoryAccess } from './commands/ls';\nimport { topologyCommand, type TopologyFormat } from './commands/topology';\nimport { pingCommand } from './commands/ping';\nimport {\n topologyParticipantsCommand,\n trafficWatchCommand,\n} from './commands/participantWatch';\nimport { schemaCommand } from './commands/schema';\nimport { loadHubConfig, printHubConfigSchema, serveCommand } from './commands/serve';\nimport { proxyCommand, tunnelCommand } from './commands/tunnel';\nimport { connectAs } from './commands/connectAs';\nimport { openDialTransport, openTargetTransport, type DialEndpoint } from './commands/connectAsTransports';\nimport { mcpForwardCommand } from './commands/mcpForward';\nimport { jsonRpcStdioCommand } from './commands/jsonRpcStdio';\nimport { jsonRpcExportCommand, JsonRpcExportRoutes } from './commands/jsonRpcExport';\nimport { validateJsonRpcExport } from '@hediet/linkrpc-infra/json-rpc/node';\nimport {\n createHubApprovalCommandClient,\n formatApprovalDecision,\n formatApprovalRequests,\n type ApprovalCommandClient,\n} from './commands/approval';\nimport { cliIdentity, formatCliIdentity } from './commands/identity';\nimport {\n connect as connectEndpoint,\n connectViaRootOverlay,\n connectViaTransport,\n type CliConnection,\n type ConnectLogOptions,\n} from '@hediet/linkrpc-client-internal';\nimport { type HubConfig } from '@hediet/linkrpc-client-internal';\nimport { runHub, type RunningHub } from './engine/runHub';\nimport {\n type ResolvedEndpoint,\n resolveTargetEndpoint,\n resolvedEndpointToConfig,\n} from '@hediet/linkrpc-client-internal';\nimport {\n type SigningSession,\n setupSigning,\n requestReflectionAccess,\n requestTopologyAccess,\n} from '@hediet/linkrpc-client-internal';\nimport { cliIdentityTarget, deleteCliIdentity, readCliIdentity } from '@hediet/linkrpc-client-internal';\nimport { MethodRefWithOptHash } from './methodRef';\nimport { renderMethodParamHelp } from './methodHelp';\nimport { rewriteParamShortcuts } from './paramFlags';\nimport { formatPrincipalSource, parsePrincipalSpec, type PrincipalSpec } from '@hediet/linkrpc-client-internal';\nimport { findMethodInSchema } from '@hediet/linkrpc-client-internal';\nimport { fetchSchemaForMethodRef } from './schemaLookup';\nimport {\n loadStaticHubSchema,\n resolveStaticHubSchemaSource,\n} from './staticHubSchema';\nimport {\n ContextStore,\n type ContextReference,\n type ContextValues,\n type SelectedContext,\n type StoredContext,\n type ValidationMode,\n formatContextReference,\n} from './contexts';\nimport {\n type CliProfile,\n type ResolvedInvocationContext,\n resolveInvocationContext,\n resolveInvocationEndpoint,\n validationDefault,\n resolveSigning,\n} from './invocationContext';\nimport { resolveCliInvocation } from './cliInvocation';\nimport { withStaticHubReflection } from './commands/staticHubReflection';\nimport { registerViewCommands } from './commands/view';\n\nexport async function main(\n rawArgv: readonly string[],\n executableName: 'linkrpc' | 'rpc' | 'hub' = 'linkrpc',\n): Promise<void> {\n const cliInvocation = resolveCliInvocation(rawArgv, executableName);\n const profile = cliInvocation.profile;\n const program = new Command();\n program.configureHelp({ showGlobalOptions: true });\n program\n .name(cliInvocation.programName)\n .description(\n profile === 'hub'\n ? 'CLI / TUI for LinkRPC hubs. Shared RPC commands use hub initialization, signing, '\n + 'capability negotiation, and required schema validation by default.'\n : 'CLI / TUI for JSON-RPC and LinkRPC endpoints. Shared commands use the RPC profile '\n + 'with automatic schema validation and no endpoint environment override by default.',\n )\n .option(\n '--endpoint <uri>',\n 'endpoint URI (linkrpc:local, unix:/path?token=…, npipe://./pipe/…, ws[s]://host?token=…, ' +\n 'ws-no-init://host?…, ' +\n 'cmd:?command=… or cmd-stdio:?command=…)',\n )\n .option('--endpoint-cmd <command>', 'spawn a server, connect via an injected env socket')\n .option('--endpoint-cmd-stdio <command>', 'spawn a child and talk over its stdio')\n .option(\n '--endpoint-cmd-env <key=value>',\n 'env var for the --endpoint-cmd / --endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option(\n '--endpoint-token <token>',\n 'fill the exact token=% placeholder in --endpoint (or a context endpoint)',\n )\n .option(\n '--endpoint-cmd-cwd <dir>',\n 'working directory for the --endpoint-cmd / --endpoint-cmd-stdio child',\n )\n .option(\n '--context <selector>',\n 'use an exact folder, id:<name>, :root, or :empty context; otherwise look up from cwd',\n )\n .option(\n '--context-set',\n 'persist context-capable overrides supplied on this command to the active context',\n )\n .option(\n '--new-context <selector>',\n 'create a new context from the effective command values; fails if it already exists',\n )\n .option('--schema <path-or-url>', 'static schema catalog used for discovery and validation')\n .option('--daemon-service <id>', 'daemon management service ID on the selected Hub')\n .option('--detach-keys <keys>', \"TTY console detach sequence in Docker syntax, e.g. 'ctrl-b,d' (default) or 'ctrl-p,ctrl-q'\")\n .option(\n '--validation <mode>',\n 'schema validation mode: auto, required, or off',\n parseValidationMode,\n )\n .option('--use-env', 'allow LINKRPC_* / legacy HUBRPC_* endpoint variables to override context')\n .option('--no-use-env', 'ignore LINKRPC_* / legacy HUBRPC_* endpoint variables')\n .option('--sign', 'enable Hub signing and stored capabilities (Hub profile default)')\n .option('--no-sign', 'disable Hub signing and stored capabilities (RPC profile default)')\n .option(\n '--provision-identity',\n 'with --endpoint-cmd: provision & reuse a persistent identity (slot derived from cwd + command)',\n )\n .option(\n '--provision-identity-slot <slot>',\n 'with --endpoint-cmd: provision & reuse a persistent identity under this explicit slot id',\n )\n .option(\n '--principal <spec>',\n 'identity to sign calls with: \"managed\" (default, falls back to user:hubrpc-cli), ' +\n '\"user:<id>\" (per-user data dir), or \"file:<path>\"',\n (v) => {\n try {\n parsePrincipalSpec(v);\n } catch (e) {\n throw new InvalidArgumentError((e as Error).message);\n }\n return v;\n },\n )\n .option(\n '--log-messages',\n profile === 'hub'\n ? 'log every JSON-RPC message to stderr, one coalesced flow per line (like the ' +\n 'VS Code \"linkrpc Flows\" channel). For `serve` / `-c, --config` this is the ' +\n 'in-process hub\\'s routed traffic; for a direct `--endpoint` connection it taps ' +\n 'the client transport. Ignored by `ui`.'\n : 'log every JSON-RPC message on a direct endpoint connection to stderr, one ' +\n 'coalesced flow per line (like the VS Code \"linkrpc Flows\" channel). Ignored by `ui`.',\n )\n .option(\n '--log-transport',\n 'log every raw JSON-RPC message sent and received to stderr, including transport initialization; '\n + 'may expose tokens and other sensitive payloads',\n )\n .showHelpAfterError();\n if (profile === 'hub') {\n program.option(\n '-c, --config <file>',\n 'run an in-process hub from this declarative config file and target it (see `serve --print-schema`)',\n );\n }\n /** Parse the effective context/flag principal once the pre-action hook has resolved it. */\n const getPrincipalSpec = (): PrincipalSpec =>\n parsePrincipalSpec(g_invocation?.values.principal);\n\n // Resolved once per command after inherited options, context defaults, and\n // the profile-specific environment policy have been merged.\n let endpoint: ResolvedEndpoint | undefined;\n let pendingContextSet:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n readonly values: ContextValues;\n }\n | undefined;\n let pendingNewContext:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n readonly values: ContextValues;\n }\n | undefined;\n let preparedNewContext:\n | {\n readonly store: ContextStore;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n }\n | undefined;\n /** Create a context from the effective values, then make it the selected context of this invocation. */\n const createAndSelectContext = async (reference: Exclude<ContextReference, { readonly kind: 'empty'; }>) => {\n if (g_contextStore === undefined || g_invocation === undefined) throw new Error('context resolver is unavailable');\n await createContextFromInvocation(g_contextStore, reference, g_invocation.values);\n const useEnvironment = explicitOption<boolean>(program, 'useEnv');\n g_invocation = await resolveInvocationContext({\n profile, store: g_contextStore, selector: formatContextReference(reference),\n cliOverrides: g_invocation.cliOverrides, ...(useEnvironment !== undefined ? { useEnvironment } : {}),\n });\n };\n program.hook('preAction', async (_thisCommand, actionCommand) => {\n const commandPath = getCommandPath(actionCommand);\n const store = new ContextStore();\n const cliOverrides = collectContextOverrides(program, actionCommand);\n const selector = explicitOption<string>(program, 'context');\n const useEnvironment = explicitOption<boolean>(program, 'useEnv');\n g_contextStore = store;\n g_invocation = await resolveInvocationContext({\n profile,\n store,\n ...(selector !== undefined ? { selector } : {}),\n cliOverrides,\n ...(useEnvironment !== undefined ? { useEnvironment } : {}),\n });\n if (profile === 'rpc' && g_invocation.values.config !== undefined) {\n throw new Error('--config is only available in the hub profile');\n }\n\n if (program.opts().contextSet === true) {\n if (program.opts().newContext !== undefined) {\n throw new Error('--context-set cannot be combined with --new-context');\n }\n if (Object.keys(cliOverrides).length === 0) {\n throw new Error('--context-set requires at least one context-capable override');\n }\n assertExplicitRootMutation(g_invocation.selected);\n if (g_invocation.selected.context === undefined) {\n throw new Error('No context exists to update. Use --new-context . to create one.');\n }\n pendingContextSet = {\n store,\n reference: mutableReference(g_invocation.selected.reference),\n values: cliOverrides,\n };\n }\n\n if (program.opts().newContext !== undefined) {\n const reference = mutableReference(\n await store.resolveReference(program.opts().newContext as string),\n );\n await store.assertCanCreate(reference);\n preparedNewContext = { store, reference };\n }\n if (preparedNewContext !== undefined && commandPath !== 'connection create') {\n pendingNewContext = {\n store,\n reference: preparedNewContext.reference,\n values: g_invocation.values,\n };\n }\n if (commandPath.startsWith('services ') && preparedNewContext !== undefined) {\n await createContextFromInvocation(preparedNewContext.store, preparedNewContext.reference, g_invocation.values);\n pendingNewContext = undefined;\n }\n if ((commandPath === 'context' || commandPath === 'context show') && preparedNewContext !== undefined) {\n // Create first, so that the command shows the new context rather than the one it was derived from.\n await createAndSelectContext(preparedNewContext.reference);\n pendingNewContext = undefined;\n }\n\n endpoint = commandUsesEndpoint(commandPath) || hasEndpointOverrides(cliOverrides)\n ? resolveInvocationEndpoint(g_invocation, actionCommand.name() === 'tunnel')\n : undefined;\n g_hubConfigPath = g_invocation.values.config;\n // Message logging goes to stderr, which would corrupt the full-screen\n // TUI — so it applies to every command except `ui`.\n g_logMessages = program.opts().logMessages === true\n && actionCommand.name() !== 'ui';\n g_logTransport = program.opts().logTransport === true\n && actionCommand.name() !== 'ui';\n });\n program.hook('postAction', async () => {\n if (pendingContextSet !== undefined) {\n await pendingContextSet.store.set(\n pendingContextSet.reference,\n pendingContextSet.values,\n );\n process.stderr.write(\n `linkrpc: updated context ${formatContextReference(pendingContextSet.reference)}.\\n`,\n );\n pendingContextSet = undefined;\n }\n if (pendingNewContext !== undefined) {\n await createContextFromInvocation(\n pendingNewContext.store,\n pendingNewContext.reference,\n pendingNewContext.values,\n );\n pendingNewContext = undefined;\n }\n });\n\n if (profile === 'hub') registerServices(program, {\n detachKeys,\n attachCommand: id => {\n if (!g_invocation) throw new Error('Context resolver is unavailable');\n const reference = preparedNewContext?.reference ?? g_invocation.selected.reference;\n return serviceAttachCommand({\n context: formatContextReference(reference),\n namespace: g_invocation.values.namespace ?? contextNamespace(reference),\n id, overrides: g_invocation.cliOverrides, useEnv: g_invocation.environmentApplied,\n });\n },\n restart: async () => {\n if (endpoint !== undefined || g_hubConfigPath !== undefined || g_invocation?.values.daemonService !== undefined) {\n throw new Error('services restart only replaces the default local daemon, not a selected Hub endpoint or routed daemon. Run `hub --context :empty --no-use-env services restart` to explicitly choose the local daemon.');\n }\n await restartLocalDaemon();\n },\n namespace: () => {\n if (!g_invocation) throw new Error('Context resolver is unavailable');\n return g_invocation.values.namespace ?? contextNamespace(preparedNewContext?.reference ?? g_invocation.selected.reference);\n },\n use: async (startLocal, action) => {\n if (endpoint === undefined && g_hubConfigPath === undefined) {\n return useLocalManagement(startLocal, action);\n }\n let result: Awaited<ReturnType<typeof action>> | undefined;\n await withChannel(endpoint, getPrincipalSpec(), async channel => {\n const connection = new LinkRpcConnection(channel);\n const serviceId = g_invocation?.values.daemonService\n ?? `${(await connection.get(hubGrantedServiceIdInterface).getHubServiceId({})).hubServiceId}/daemon`;\n await checkDaemonInterfaces(connection, serviceId);\n result = await action(connection.get(managedEndpointsInterface, { serviceId }), { local: false });\n }, { requestReflectionAccess: false, autoNegotiatePerCall: true });\n return result!;\n },\n });\n\n program\n .command('attach [serviceId]')\n .description(\n 'Attach to a console of any service implementing the `linkrpc.console.v1` interface template '\n + '(found through the `linkrpc.console` directory tag). Without a service, list available consoles. '\n + 'Pipe consoles: Ctrl+D on an empty line detaches. TTY consoles: keys go to the program; the detach '\n + 'keys (default Ctrl+B, then d) detach.',\n )\n .option('--params <json>', \"params of the console template instance, e.g. '{\\\"namespace\\\":\\\"…\\\",\\\"id\\\":\\\"main\\\"}'\", '{}')\n .option('--interface <id>', 'interface containing the console instance')\n .option('--instance <name>', 'console template instance name, when an interface has several')\n .option('--read-only', 'observe output without sending input')\n .action(async (serviceId: string | undefined, opts: { params: string; interface?: string; instance?: string; readOnly?: boolean }) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n if (serviceId === undefined) {\n process.stdout.write(`${await listConsoleTargets(channel)}\\n`);\n return;\n }\n await attachConsole(channel, {\n serviceId, params: opts.params, readOnly: opts.readOnly,\n ...(opts.interface === undefined ? {} : { interfaceId: opts.interface }),\n ...(opts.instance === undefined ? {} : { instance: opts.instance }),\n detachKeys: detachKeys(),\n reattachCommand: [cliInvocation.programName, 'attach', serviceId,\n ...(opts.params === '{}' ? [] : ['--params', `'${opts.params}'`]),\n ...(opts.instance === undefined ? [] : ['--instance', opts.instance])].join(' '),\n });\n }, { autoNegotiatePerCall: true });\n });\n\n program\n .command('ls')\n .description(\n 'List services and interfaces. Walks the bus recursively, following `hubrpc.directory` references.',\n )\n .option('--interface <id>', 'filter by interfaceId')\n .option('--interface-prefix <prefix>', 'filter by interfaceId prefix')\n .option('--service <id>', 'list a single service (no recursion)')\n .option('--service-prefix <prefix>', 'filter by serviceId prefix')\n .option('--search <regexp>', 'case-insensitive regexp over listings')\n .option('--depth <n>', 'max recursion depth (default 5)', (v) => Number.parseInt(v, 10))\n .option('--with-members', 'include request and notification members from interface schemas')\n .option('--json', 'legacy flat listing JSON; use --format json for graph state')\n .option('--format <format>', 'pretty, json, or jsonl')\n .option('--dump <file>', 'write topology and all schemas to one JSON fixture file')\n .option(\n '--dump-patches <file>',\n 'write progressive RFC 6902 operations as JSON Lines; use - for stdout',\n )\n .option('--stream', 'legacy patch-log JSONL; use --format jsonl for reconstructable graph state')\n .option('--watch', 'continue observing directory changes until interrupted')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel, session) => {\n const format = resolveGraphFormat(opts.format, {\n json: opts.json === true,\n stream: opts.stream === true,\n watch: opts.watch === true,\n });\n const legacyOutput = opts.format === undefined && opts.watch !== true;\n const out = await lsCommand(channel, {\n requestDirectoryAccess: session === undefined ? undefined : serviceId =>\n requestDirectoryAccess(session, serviceId, {\n watch: opts.watch,\n withMembers: opts.withMembers,\n dumpPath: opts.dump,\n dumpPatchesPath: opts.dumpPatches,\n }),\n log: message => { process.stderr.write(`linkrpc: ${message}\\n`); },\n interfaceId: opts.interface,\n interfacePrefix: opts.interfacePrefix,\n serviceId: opts.service,\n servicePrefix: opts.servicePrefix,\n search: opts.search,\n withMembers: !!opts.withMembers,\n json: !!opts.json,\n format: legacyOutput ? undefined : format,\n dumpPath: opts.dump,\n dumpPatchesPath: opts.dumpPatches,\n stream: !!opts.stream,\n watch: !!opts.watch,\n emitLine: (line) => { process.stdout.write(line + '\\n'); },\n emitFrame: (frame) => { repaintTerminal(frame); },\n stop: opts.watch ? _untilSignalled() : undefined,\n maxDepth: typeof opts.depth === 'number' && !Number.isNaN(opts.depth) ?\n opts.depth :\n undefined,\n });\n if (out.length > 0) process.stdout.write(out + '\\n');\n }, { requestReflectionAccess: false, autoNegotiatePerCall: false });\n });\n\n if (profile === 'hub') {\n const topology = program\n .command('topology')\n .description('Inspect and optionally watch the merged transport topology.')\n .option(\n '--source <serviceId>',\n 'topology provider serviceId; repeat for multiple fixed sources',\n collectOption,\n )\n .option('--depth <n>', 'directory discovery depth (default 5)', (v) => Number.parseInt(v, 10))\n .option('--node <nodeId>', 'filter by exact node id')\n .option('--service <serviceId>', 'filter route claims by exact service id')\n .option('--kind <kind>', 'filter nodes by hub or endpoint')\n .option('--search <regexp>', 'case-insensitive regexp over node metadata and routes')\n .option('--format <format>', 'pretty, json, or jsonl')\n .option('--json', 'alias for --format json')\n .option('--stream', 'alias for --format jsonl')\n .option('--watch', 'continue observing directory and topology changes')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const format = resolveGraphFormat(opts.format, {\n json: opts.json === true,\n stream: opts.stream === true,\n watch: opts.watch === true,\n });\n const kind = opts.kind === undefined ? undefined : String(opts.kind);\n if (kind !== undefined && kind !== 'hub' && kind !== 'endpoint') {\n throw new InvalidArgumentError(\"--kind must be 'hub' or 'endpoint'\");\n }\n const out = await topologyCommand(channel, {\n sources: opts.source,\n maxDepth: typeof opts.depth === 'number' && !Number.isNaN(opts.depth)\n ? opts.depth\n : undefined,\n nodeId: opts.node,\n serviceId: opts.service,\n kind,\n search: opts.search,\n format,\n watch: opts.watch === true,\n emitLine: (line) => { process.stdout.write(line + '\\n'); },\n emitFrame: (frame) => { repaintTerminal(frame); },\n stop: opts.watch ? _untilSignalled() : undefined,\n });\n if (out.length > 0) process.stdout.write(out + '\\n');\n }, {\n requestReflectionAccess: false,\n requestTopologyAccess: { sourceServiceIds: opts.source },\n });\n });\n\n topology\n .command('participants')\n .description('List participant nodes; --search accepts a case-insensitive regexp.')\n .option('--search <regexp>', 'full-text regexp over participant metadata and routes')\n .option('--json', 'raw JSON output')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await topologyParticipantsCommand(channel, opts.search);\n process.stdout.write(opts.json ? out + '\\n' : out + '\\n');\n }, {\n requestReflectionAccess: false,\n requestTopologyAccess: {},\n });\n });\n\n program\n .command('traffic')\n .description('Observe participant traffic.')\n .command('watch')\n .description('Watch node-wide traffic for a selected participant.')\n .option('--search <regexp>', 'participant metadata search regexp')\n .option('--node <nodeId>', 'select an exact topology node id')\n .option('--method <prefix>', 'only methods beginning with this prefix')\n .option('--payloads <bytes>', 'include payloads up to this many bytes', (v) => Number.parseInt(v, 10))\n .option('--format <format>', 'pretty, plain, or jsonl')\n .option('--resume [file]', 'restore the previous participant/filter selection')\n .action(async (opts) => {\n const format = opts.format as 'pretty' | 'plain' | 'jsonl';\n if (!['pretty', 'plain', 'jsonl'].includes(format)) {\n throw new InvalidArgumentError('--format must be pretty, plain, or jsonl');\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n await trafficWatchCommand(channel, {\n search: opts.search,\n nodeId: opts.node,\n methodPrefix: opts.method,\n payloadBytes: opts.payloads,\n format,\n resume: opts.resume,\n stop: _untilSignalled(),\n });\n }, { requestReflectionAccess: true });\n });\n }\n\n program\n .command('defaults')\n .description('Print the preset service / interface for form-1 calls.')\n .option('--json', 'raw JSON output')\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await defaultsCommand(channel, { json: !!opts.json });\n process.stdout.write(out + '\\n');\n });\n });\n\n program\n .command('codegen')\n .description('Generate reusable TypeScript interfaces and bindings from an offline contract.')\n .requiredOption('--input <bundle>', 'local static hub schema bundle')\n .option('--interface <id>', 'generate only this interface (requires --name)')\n .option('--name <name>', 'single-interface exported TypeScript const name')\n .option('--names <file>', 'whole-contract JSON interfaceNames/bindingNames overrides')\n .requiredOption('--output <file>', 'generated TypeScript output file')\n .option(\n '--preserve-wire-schema',\n 'freeze the canonical input schema verbatim in the generated definition',\n )\n .option('--check', 'fail if the output is missing or stale without overwriting it')\n .action(async (opts) => {\n await codegenCommand({\n input: opts.input,\n interfaceId: opts.interface,\n name: opts.name,\n output: opts.output,\n preserveWireSchema: opts.preserveWireSchema === true,\n check: opts.check === true,\n names: opts.names,\n });\n });\n\n program.command('contract')\n .description('Export reusable static interface and binding contracts.')\n .command('export')\n .requiredOption('--output <file>', 'contract JSON destination, or - for stdout')\n .option('--service <id>', 'reflection scope (defaults to the endpoint root)')\n .option('--max-depth <depth>', 'maximum directory referral depth', (value) => {\n if (!/^\\d+$/.test(value)) throw new InvalidArgumentError('depth must be a non-negative integer');\n return Number(value);\n })\n .action(async (opts) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n await exportContractCommand(channel, {\n output: opts.output,\n serviceId: opts.service,\n maxDepth: opts.maxDepth,\n });\n }, { requestReflectionAccess: true });\n });\n\n const schema = program\n .command('schema')\n .description('Inspect, hash, and compare LinkRPC interface schemas.');\n\n schema\n .command('show <interfaceRef>')\n .description('Print an interface schema. `<interfaceRef>` is `id[@hash]`.')\n .option('--method <name>', 'show only this method')\n .option('--service <id>', 'route the lookup to this service (form-3); needed behind a hub')\n .option('--json', 'raw JSON output')\n .action(async (interfaceRef: string, opts) => {\n const { id, hash } = parseInterfaceRef(interfaceRef);\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await schemaCommand(channel, {\n interfaceId: id,\n hash,\n method: opts.method,\n serviceId: opts.service,\n json: !!opts.json,\n });\n process.stdout.write(out + '\\n');\n });\n });\n\n schema\n .command('hash <schema>')\n .description('Compute the hash of a local LinkRpcInterfaceSchema JSON file.')\n .action((schemaPath: string) => {\n const out = hashCommand({ schemaPath });\n process.stdout.write(out + '\\n');\n });\n\n schema\n .command('check-compat <interfaceId> <local>')\n .description('Compare a local schema against the live interface schema.')\n .action(async (interfaceId: string, local: string) => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const verdict = await checkCompatCommand(channel, { interfaceId, localPath: local });\n process.stdout.write(formatVerdict(verdict) + '\\n');\n if (verdict.kind === 'incompatible') process.exitCode = 1;\n });\n });\n\n /**\n * Render `commander`'s static help for the given command, then (if a\n * methodRef is provided and an endpoint is reachable) fetch the live\n * schema and append a \"Method parameters\" block describing the\n * supported `--p:<name>` shortcuts.\n *\n * Best-effort: schema fetch failures degrade to static help with an\n * inline note instead of erroring out.\n */\n const _printCallHelp = async (cmd: Command, methodRef: string): Promise<void> => {\n process.stdout.write(cmd.helpInformation());\n if (methodRef.length === 0) {\n process.stdout.write(\n '\\n(Pass a methodRef to see method-specific --p:<name> flags, e.g.\\n'\n + ' hub call acme.email::send --help)\\n',\n );\n return;\n }\n if (endpoint === undefined) {\n const ignoredEnvironmentHint = ignoredEndpointEnvironmentHint();\n process.stdout.write(\n `\\n(No endpoint configured: pass ${endpointOptionsDescription()}.\\n`\n + (ignoredEnvironmentHint === undefined ? '' : `${ignoredEnvironmentHint}.\\n`)\n + 'To see method-specific --p:<name> flags here.)\\n',\n );\n return;\n }\n let ref: MethodRefWithOptHash;\n try {\n ref = MethodRefWithOptHash.parseMethodRef(methodRef);\n } catch (e) {\n process.stdout.write(`\\n(Could not parse method reference: ${(e as Error).message})\\n`);\n return;\n }\n try {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const schema = await fetchSchemaForMethodRef(channel, ref);\n if (schema === undefined) {\n process.stdout.write(\n '\\n(Bare-method refs (form 1) need a preset interface to look up the schema.)\\n',\n );\n return;\n }\n const method = findMethodInSchema(schema, ref.methodName);\n if (method === undefined) {\n process.stdout.write(\n `\\n(Method \"${ref.methodName}\" not found on interface ${schema.id}@${schema.hash}.)\\n`,\n );\n return;\n }\n const rendered = renderMethodParamHelp(method, schema);\n if (rendered.text.length > 0) {\n process.stdout.write('\\n' + rendered.text);\n }\n }, { requestReflectionAccess: false, autoNegotiatePerCall: false });\n } catch (e) {\n process.stdout.write(`\\n(Could not fetch method schema: ${(e as Error).message})\\n`);\n }\n };\n\n const call = program.command('call [methodRef]');\n const caps = profile === 'hub'\n ? program.command('caps').description('List stored capabilities or request access for a call.')\n : undefined;\n caps?.command('list')\n .description('List capabilities stored for the selected principal (including expired grants).')\n .option('--json', 'machine-readable JSON output')\n .action(async (opts: { json?: boolean }) => {\n await withResolvedSigning(endpoint, getPrincipalSpec(), async (_conn, session) => {\n process.stdout.write(listCaps(session, opts.json === true) + '\\n');\n });\n });\n const capsRequest = caps?.command('request [methodRef]')\n .description('Request and store a capability without invoking the method.');\n\n const addCapabilityOptions = (cmd: Command): Command => cmd\n .option('--cap:allow-param <kv...>', 'top-level key=matcher JSON (exact, enum, prefix, subsetOf, any)')\n .option('--cap:allow-prefix <prefix>', 'allow a string prefix for the immediately preceding parameter')\n .option('--cap:allow-any', 'allow any JSON value for the immediately preceding parameter')\n .option('--cap:allow-enum <json>', 'allow one value from a JSON array for the preceding parameter')\n .option('--cap:allow-subset <json>', 'allow an array of items from a JSON string array for the preceding parameter')\n .addOption(new Option('--cap:duration <duration>', 'requested grant lifetime')\n .choices(['shortLived', 'longLived', 'persistent']).default('persistent'));\n\n const configureCall = (cmd: Command, capabilityOnly: boolean): void => {\n cmd\n .description(\n (capabilityOnly ? 'Request a capability without executing a call. ' : 'Invoke a request. ')\n + '`<methodRef>` is `[svc::][iface::]method[@hash]`. '\n + 'Use `--p:<name> <value>` (or `--p:<name>=<value>`) as a shortcut for '\n + '`--param <name>=<value>`. Run `hub call <methodRef> --help` to see the '\n + 'method-specific `--p:` flags derived from the live schema.',\n )\n .option('--params <json>', 'inline params JSON, or \"-\" to read stdin')\n .option('--param <kv...>', 'param override, key=value (JSON or string)')\n .option('--no-validate', 'skip schema-based param validation')\n // Disable commander's built-in --help so we can intercept it and\n // append the dynamic \"Method parameters\" block.\n .helpOption(false)\n .option('-h, --help', 'show help (includes method params when reachable)')\n .action(async (methodRef: string | undefined, opts, cmd: Command) => {\n if (opts.help) {\n await _printCallHelp(cmd, methodRef ?? '');\n return;\n }\n if (methodRef === undefined) {\n process.stderr.write(\"linkrpc: missing required argument 'methodRef'.\\n\");\n process.stderr.write(cmd.helpInformation());\n process.exit(2);\n }\n const requestCap = opts['cap:request'] === true;\n const allowParams = opts['cap:allowParam'];\n if (!capabilityOnly && allowParams !== undefined && !requestCap) {\n throw new Error('--cap:allow-param requires --cap:request.');\n }\n if (!capabilityOnly && cmd.getOptionValueSource('cap:duration') === 'cli' && !requestCap) {\n throw new Error('--cap:duration requires --cap:request.');\n }\n resolveSigning(profile, g_invocation?.values ?? {}, capabilityOnly || requestCap);\n const validation = opts.validate === false ? 'off' : effectiveValidation(profile);\n if ((capabilityOnly || requestCap) && validation === 'off') {\n throw new Error('Capability requests require schema validation; remove --no-validate/--validation off.');\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel, session) => {\n const out = await callCommand(channel, {\n methodRef,\n paramsArg: opts.params,\n paramOverrides: opts.param,\n validation,\n allowParams,\n requestCap,\n capabilityOnly,\n signingSession: session,\n duration: opts['cap:duration'],\n });\n process.stdout.write(out + '\\n');\n }, {\n requestReflectionAccess: (capabilityOnly || requestCap)\n && validation !== 'off',\n requireSigning: capabilityOnly || requestCap,\n autoNegotiatePerCall: false,\n });\n });\n addCapabilityOptions(cmd);\n };\n configureCall(call, false);\n call.option('--cap:request', 'ensure a stored capability covers the requested scope before calling');\n if (capsRequest !== undefined) configureCall(capsRequest, true);\n\n program\n .command('notify [methodRef]')\n .description(\n 'Fire a notification (no response). Same `--p:<name>` shortcuts as `call`.',\n )\n .option('--params <json>', 'inline params JSON, or \"-\" to read stdin')\n .option('--param <kv...>', 'param override, key=value')\n .option('--no-validate', 'skip schema-based param validation')\n .helpOption(false)\n .option('-h, --help', 'show help (includes method params when reachable)')\n .action(async (methodRef: string | undefined, opts, cmd: Command) => {\n if (opts.help) {\n await _printCallHelp(cmd, methodRef ?? '');\n return;\n }\n if (methodRef === undefined) {\n process.stderr.write(\"linkrpc: missing required argument 'methodRef'.\\n\");\n process.stderr.write(cmd.helpInformation());\n process.exit(2);\n }\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const validation = opts.validate === false\n ? 'off'\n : effectiveValidation(profile);\n const out = await notifyCommand(channel, {\n methodRef,\n paramsArg: opts.params,\n paramOverrides: opts.param,\n validation,\n });\n process.stdout.write(out + '\\n');\n }, { requestReflectionAccess: effectiveValidation(profile) !== 'off' });\n });\n\n program\n .command('batch [batchArgs...]')\n .description(\n 'Run sequential calls and notifications on one connection. Start each operation with '\n + '`--call <method>` or `--notify <method>`; following `--params`, `--param`, and '\n + '`--no-validate` flags apply to that operation.',\n )\n .allowUnknownOption()\n .addHelpText('after', `\nBatch options:\n --call <method> start a request operation\n --notify <method> start a notification operation\n --params <json> set inline JSON params for the preceding operation\n --param <key=value> add a param override to the preceding operation (repeatable)\n --no-validate skip validation for the preceding operation\n --continue-on-error record an error and continue with later operations\n`)\n .action(async (batchArgs: string[]) => {\n const plan = parseBatchArgs(batchArgs);\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const results = await executeBatch(plan, {\n call: (options) => callCommand(channel, options),\n notify: (options) => notifyCommand(channel, options),\n }, {\n validation: effectiveValidation(profile),\n onStreamChunk: ({ index, method, payload }) => {\n const text = typeof payload === 'string'\n ? payload\n : JSON.stringify(payload);\n process.stderr.write(`[${index + 1} ${method}] ${text}\\n`);\n },\n });\n process.stdout.write(JSON.stringify(results, undefined, 2) + '\\n');\n }, {\n requestReflectionAccess: effectiveValidation(profile) !== 'off'\n && plan.operations.some((operation) => !operation.noValidate),\n });\n });\n\n const connection = program\n .command('connection')\n .description('Create, inspect, consume, and destroy persistent RPC connections.');\n\n connection\n .command('create')\n .description('Create a detached persistent connection and print its local endpoint.')\n .option('--timeout <duration>', 'transport inactivity limit (duration or inf; omitted: inf)')\n .option('--ttl <duration>', 'hard lifetime limit (duration or inf; omitted: inf)')\n .option(\n '--notification-limit <count>',\n 'maximum buffered incoming notifications',\n (value) => parsePositiveInteger(value, '--notification-limit'),\n )\n .action(async (opts: {\n timeout?: string;\n ttl?: string;\n notificationLimit?: number;\n }) => {\n if (opts.timeout === undefined && opts.ttl === undefined) {\n throw new Error('connection create requires an explicit --timeout or --ttl (use inf for unlimited)');\n }\n if (g_hubConfigPath !== undefined) {\n throw new Error('connection create does not support --config; use an endpoint URI or command endpoint');\n }\n const schemaSource = g_invocation?.values.schema === undefined\n ? undefined\n : resolveStaticHubSchemaSource(g_invocation.values.schema);\n if (schemaSource !== undefined) {\n await loadStaticHubSchema(schemaSource);\n }\n const timeout = opts.timeout ?? 'inf';\n const ttl = opts.ttl ?? 'inf';\n const notificationLimit = opts.notificationLimit\n ?? g_invocation?.values.notificationLimit\n ?? 1_000;\n const brokerEndpoint = await spawnConnectionBroker({\n remote: needEndpoint(endpoint),\n timeoutMs: parseConnectionLimit(timeout),\n ttlMs: parseConnectionLimit(ttl),\n notificationLimit,\n schemaSource,\n });\n if (preparedNewContext !== undefined) {\n if (g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n try {\n await createConnectionContext(\n preparedNewContext.store,\n preparedNewContext.reference,\n g_invocation.values,\n brokerEndpoint,\n );\n } catch (error) {\n try {\n await stopConnectionBroker(brokerEndpoint);\n } catch (cleanupError) {\n throw new AggregateError(\n [error, cleanupError],\n 'failed to create the context and stop the new connection broker',\n );\n }\n throw error;\n }\n }\n process.stdout.write(brokerEndpoint + '\\n');\n });\n\n connection\n .command('status')\n .description('Read status from the connection broker at the configured endpoint.')\n .action(async () => {\n await withRawConnection(endpoint, async (channel) => {\n process.stdout.write(JSON.stringify(await getBrokerStatus(channel), undefined, 2) + '\\n');\n });\n });\n\n connection\n .command('destroy')\n .description('Stop the connection broker at the configured endpoint.')\n .action(async () => {\n await withRawConnection(endpoint, async (channel) => {\n await disconnectBroker(channel);\n });\n });\n\n connection\n .command('notifications')\n .description(\n 'Read server notifications buffered by the persistent connection; --follow emits JSON Lines.',\n )\n .option('--after <sequence>', 'read notifications after this sequence', (value) =>\n parseNonNegativeInteger(value, '--after'), 0)\n .option('--wait <duration>', 'wait for a notification before returning')\n .option('--follow', 'continue waiting and print notifications as JSON lines')\n .action(async (opts: { after: number; wait?: string; follow?: boolean; }) => {\n const waitMs = opts.wait === undefined\n ? (opts.follow ? 25_000 : 0)\n : Math.min(parseDuration(opts.wait), 30_000);\n await withRawConnection(endpoint, async (channel) => {\n let after = opts.after;\n do {\n const batch = await readBrokerNotifications(channel, { after, waitMs });\n if (opts.follow) {\n for (const notification of batch.notifications) {\n process.stdout.write(JSON.stringify(notification) + '\\n');\n }\n } else {\n process.stdout.write(JSON.stringify(batch, undefined, 2) + '\\n');\n }\n after = batch.next;\n } while (opts.follow);\n });\n });\n\n const context = program\n .command('context')\n .description('Show how the active context resolves, or explicitly modify shared context defaults.')\n .action(() => {\n printSelectedContext(true);\n });\n\n context\n .command('show')\n .description('Show only the selected context and its stored defaults.')\n .action(() => {\n printSelectedContext(false);\n });\n\n context\n .command('create <selector>')\n .description('Create a context (a folder, id:<name>) from the effective values, including flags on this command; same as hub context --new-context <selector>.')\n .action(async (selector: string) => {\n if (g_contextStore === undefined) throw new Error('context store is unavailable');\n if (preparedNewContext !== undefined) throw new Error('Use either context create <selector> or --new-context, not both');\n const reference = mutableReference(await g_contextStore.resolveReference(selector));\n await g_contextStore.assertCanCreate(reference);\n await createAndSelectContext(reference);\n printSelectedContext(false);\n });\n\n context\n .command('list')\n .description('List every path and named context in the global store, and the root context, which always exists.')\n .action(async () => {\n if (g_contextStore === undefined) throw new Error('context store is unavailable');\n const references = (await g_contextStore.list()).map(item => formatContextReference(item.reference));\n if (!references.includes(':root')) references.push(':root');\n for (const reference of references.sort()) process.stdout.write(`${reference}\\n`);\n });\n\n context\n .command('set')\n .description(\n 'Set explicit context-capable flags on an existing context, or create one with --new-context.',\n )\n .option('--unset <key...>', 'remove one or more stored context values')\n .action(async (opts: { unset?: string[] }) => {\n if (g_contextStore === undefined || g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n if (preparedNewContext !== undefined) {\n if ((opts.unset?.length ?? 0) > 0) throw new Error('--unset cannot be used with --new-context');\n return;\n }\n assertExplicitRootMutation(g_invocation.selected);\n if (g_invocation.selected.context === undefined) {\n throw new Error('No context exists to update. Use hub context set --new-context . with your desired flags.');\n }\n const target = mutableReference(g_invocation.selected.reference);\n const overrides = g_invocation.cliOverrides;\n const unset = (opts.unset ?? []).map(parseContextValueKey);\n if (Object.keys(overrides).length === 0 && unset.length === 0) {\n throw new Error('context set requires at least one context-capable flag or --unset');\n }\n let result = Object.keys(overrides).length === 0\n ? g_invocation.selected.context\n : await g_contextStore.set(target, overrides);\n if (unset.length > 0) {\n result = await g_contextStore.unset(target, unset);\n }\n process.stdout.write(`Updated context ${formatContextReference(target)}.\\n`);\n if (result !== undefined) printContextValues(result.values, false);\n });\n\n context\n .command('remove')\n .description('Stop any owned connection and remove the selected context; removing :root resets it to no defaults.')\n .action(async () => {\n if (g_contextStore === undefined || g_invocation === undefined) {\n throw new Error('context resolver is unavailable');\n }\n const reference = g_invocation.selected.reference;\n if (\n reference.kind === 'empty'\n || (reference.kind === 'root' && explicitOption<string>(program, 'context') === undefined)\n ) {\n throw new Error('select the context to remove explicitly with --context');\n }\n const removed = await g_contextStore.remove(reference);\n if (!removed) throw new Error(`context ${formatContextReference(reference)} does not exist`);\n process.stdout.write(reference.kind === 'root'\n ? 'Reset context :root to no stored defaults (the root context always exists).\\n'\n : `Removed context ${formatContextReference(reference)}.\\n`);\n });\n\n program\n .command('_connection-broker')\n .description('(internal) Run a persistent connection broker.')\n .requiredOption('--remote-endpoint <uri>')\n .requiredOption('--timeout-ms <milliseconds-or-inf>', '', parseConnectionLimitMilliseconds)\n .requiredOption('--ttl-ms <milliseconds-or-inf>', '', parseConnectionLimitMilliseconds)\n .option('--notification-limit <count>', '', (value) =>\n parsePositiveInteger(value, '--notification-limit'), 1_000)\n .option('--schema <path-or-url>')\n .action(async (opts: {\n remoteEndpoint: string;\n timeoutMs: ConnectionLimit;\n ttlMs: ConnectionLimit;\n notificationLimit: number;\n schema?: string;\n }) => {\n const running = await runConnectionBroker({\n remote: parseEndpointUri(opts.remoteEndpoint),\n timeoutMs: opts.timeoutMs,\n ttlMs: opts.ttlMs,\n notificationLimit: opts.notificationLimit,\n ...(opts.schema === undefined\n ? {}\n : { staticHubSchema: await loadStaticHubSchema(opts.schema) }),\n });\n process.stdout.write(running.endpoint + '\\n');\n await running.stopped;\n });\n\n program\n .command('ping')\n .description('One reflection round-trip; prints latency.')\n .action(async () => {\n await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const out = await pingCommand(channel);\n process.stdout.write(out + '\\n');\n });\n });\n if (profile === 'hub') {\n const exportRoutes = new JsonRpcExportRoutes();\n program\n .command('json-rpc-export')\n .description('Export Hub JSON-RPC services through one authenticated raw WebSocket listener.')\n .requiredOption('--target-endpoint <uri>', 'Listener URI, e.g. listen:ws://127.0.0.1:8123')\n .option('--target-token <token>', 'Local client authentication token (or put token in target URI)')\n .option('--target-token-query-param <name>', 'Accepted token query parameter (repeatable; replaces defaults tkn and token)', collectOption)\n .option('--serviceId <id>', 'Begin a route; follow each occurrence with --path', value => {\n exportRoutes.serviceId(value);\n return value;\n })\n .option('--path <path>', 'Path for the preceding service ID; repeat pairs for multiple routes', value => {\n exportRoutes.path(value);\n return value;\n })\n .action(async (opts: { targetEndpoint: string; targetToken?: string; targetTokenQueryParam?: readonly string[] }) => {\n const options = {\n targetEndpoint: opts.targetEndpoint,\n token: opts.targetToken,\n tokenQueryParameters: opts.targetTokenQueryParam,\n routes: exportRoutes.getRoutes(),\n };\n validateJsonRpcExport(options);\n const localEp = needEndpoint(endpoint);\n const local = await connectEndpoint(localEp, wireLog('hub'));\n try {\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n const server = await jsonRpcExportCommand({\n ...options,\n local,\n onError: error => process.stderr.write(`linkrpc: ${error.message}\\n`),\n });\n try {\n process.stderr.write(`linkrpc: JSON-RPC export listening at ${server.endpoint}\\n`);\n await _untilSignalled();\n } finally {\n await server.close();\n }\n } finally {\n local.close();\n }\n });\n program\n .command('json-rpc-stdio <serviceId>')\n .description(\n 'Expose <serviceId>::jsonRpcConnection::connectRaw as a newline-delimited '\n + \"JSON-RPC endpoint on this process's stdin/stdout.\",\n )\n .option('--params <json>', 'JSON value passed to the remote transport factory')\n .action(async (serviceId: string, opts: { params?: string; }) => {\n const localEp = needEndpoint(endpoint);\n let params: JsonValue | undefined;\n if (opts.params !== undefined) {\n try {\n params = JSON.parse(opts.params) as JsonValue;\n } catch (error) {\n throw new InvalidArgumentError(\n `invalid --params JSON: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n const local = await connectEndpoint(localEp, wireLog('hub'));\n try {\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n await jsonRpcStdioCommand({\n local,\n serviceId,\n ...(params === undefined ? {} : { params }),\n });\n } finally {\n local.close();\n }\n });\n\n program\n .command('serve [config]')\n .description(\n 'Run a hub from a declarative config file and block until interrupted. '\n + 'The same config format drives the CLI hub, the server hub, and the VS Code extension.',\n )\n .option('--print-schema', 'print the config JSON Schema and exit')\n .option('--cmd-interactive', 'forward stdin to the single cmd endpoint (errors if more than one)')\n .action(async (config: string | undefined, opts: { printSchema?: boolean; cmdInteractive?: boolean; }) => {\n if (opts.printSchema) {\n process.stdout.write(printHubConfigSchema() + '\\n');\n return;\n }\n if (config === undefined) {\n process.stderr.write('linkrpc: serve requires a <config> file (or --print-schema).\\n');\n process.exit(2);\n }\n await serveCommand({\n configPath: config,\n cmdInteractive: opts.cmdInteractive,\n logMessages: g_logMessages,\n });\n });\n\n addTargetEndpointOptions(program\n .command('tunnel <serviceId>')\n .description(\n 'Claim <serviceId> on the source hub (--endpoint*) and forward every request it ' +\n 'routes here to a target endpoint over a second connection. The target endpoint ' +\n 'is set via --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio; ' +\n 'when it is --target-endpoint-cmd, the spawned child sees ' +\n \"`hubGrantedServiceId::get().grantedServiceIdNamespace` = <serviceId> from its local hub, \" +\n 'and global --provision-identity[-slot] applies to it. With `-c, --config`, the ' +\n 'source hub is instead appended to the config as an endpoint claiming <serviceId>, ' +\n 'and the in-process hub serves it (the config provides the target). Runs until Ctrl-C.',\n ))\n .option(\n '--bidi',\n 'also forward every request/notification the target endpoint emits back to the ' +\n 'source hub, exposing the hub to the endpoint (forwards everything, unsigned)',\n )\n .action(async (serviceId: string, cmdOpts: TargetEndpointCliOptions & {\n bidi?: boolean;\n }) => {\n const localEp = needEndpoint(endpoint);\n\n // Config mode: append the source hub to the loaded config as an\n // endpoint claiming <serviceId>, then run that in-process hub. The\n // config itself provides the target that serves the service id, so\n // the manual two-connection forward path is not used.\n if (g_hubConfigPath !== undefined) {\n const baseConfig = loadHubConfig(g_hubConfigPath);\n const claimEndpoint = resolvedEndpointToConfig(localEp, {\n claimServiceIds: [serviceId],\n });\n const config: HubConfig = {\n ...baseConfig,\n // The in-process hub serves <serviceId> and claims it on the\n // source, so it must mount its own services under <serviceId>\n // (not the default 'hub') for the claim and routing to line up.\n hubServiceId: serviceId,\n endpoints: [...baseConfig.endpoints, claimEndpoint],\n };\n const running = await runHub({ config, logMessages: g_logMessages });\n process.stderr.write(\n `linkrpc: tunnel: claimed '${serviceId}' on source via config hub. Ctrl-C to stop.\\n`,\n );\n await new Promise<void>((resolve) => {\n const stop = (): void => {\n running.dispose();\n resolve();\n };\n process.once('SIGINT', stop);\n process.once('SIGTERM', stop);\n });\n return;\n }\n\n const globalOpts = program.opts();\n const targetEp = resolveTargetEndpointOrExit(cmdOpts, globalOpts, 'tunnel');\n const local = await connectEndpoint(localEp, wireLog('source'));\n const remote = await connectTargetEndpoint(targetEp, serviceId);\n try {\n // Sign the claim where the source hub requires it (managed\n // identity with local-keypair fallback). The remote side is\n // left unsigned so requests forward verbatim.\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n // Stop when either side goes away, and exit non-zero so a\n // supervisor (e.g. the hub daemon) restarts the tunnel: a\n // claim without a live target would only time out calls.\n const lost = Promise.race([\n local.closed.then(() => 'source'),\n remote.closed.then(() => 'target'),\n ]).then((side) => {\n process.stderr.write(`linkrpc: tunnel: the ${side} connection closed\\n`);\n process.exitCode = 1;\n });\n await tunnelCommand({ serviceId, local, remote, bidi: cmdOpts.bidi, stop: Promise.race([lost, _untilSignalled()]) });\n } finally {\n remote.close();\n local.close();\n }\n });\n\n addTargetEndpointOptions(program\n .command('proxy')\n .description(\n 'Connect a participant to the hub (--endpoint*) through this process. The participant is ' +\n \"this process's stdin/stdout (--stdio) or a target endpoint (--target-endpoint*). By \" +\n 'default the proxy does not sign anything: calls the participant makes are forwarded to ' +\n 'the hub as they are (unsigned, or with the signature the participant attached). ' +\n '--sign-as re-signs them with an identity of this machine, --no-outbound drops them, and ' +\n '--claim makes the hub route a service id to the participant. ' +\n 'Runs until the participant disconnects or Ctrl-C.',\n ))\n .option('--stdio', \"use this process's stdin/stdout as the participant\")\n .option(\n '--sign-as [principal]',\n 'sign every call the participant makes as <principal> (\"managed\", \"user:<id>\" or ' +\n '\"file:<path>\"; default: --principal, i.e. the managed Hub identity falling back to ' +\n 'user:hubrpc-cli) and request capabilities for those calls, prompting for approval ' +\n 'when needed. This lends the participant that identity; use it for participants that ' +\n 'cannot sign but must call services behind forwardChecking',\n )\n .option(\n '--claim <serviceId>',\n 'register <serviceId> on the hub (this registration is signed as --principal) and ' +\n \"forward requests for it to the participant unchanged, keeping callers' signatures\",\n )\n .option('--no-outbound', 'drop calls the participant makes instead of forwarding them to the hub')\n .action(async (cmdOpts: TargetEndpointCliOptions & {\n stdio?: boolean;\n signAs?: string | true;\n claim?: string;\n outbound: boolean;\n }) => {\n const localEp = needEndpoint(endpoint);\n if (cmdOpts.stdio === hasTargetEndpoint(cmdOpts)) {\n process.stderr.write('linkrpc: proxy requires exactly one of --stdio or --target-endpoint*.\\n');\n process.exit(2);\n }\n if (g_invocation?.cliOverrides.sign === true) {\n process.stderr.write('linkrpc: proxy does not use --sign; pass --sign-as [principal] to sign participant calls.\\n');\n process.exit(2);\n }\n if (cmdOpts.signAs !== undefined && !cmdOpts.outbound) {\n process.stderr.write('linkrpc: proxy --sign-as has no effect with --no-outbound.\\n');\n process.exit(2);\n }\n const targetEp = cmdOpts.stdio\n ? undefined\n : resolveTargetEndpointOrExit(cmdOpts, program.opts(), 'proxy');\n const hub = await connectEndpoint(localEp, wireLog('hub'));\n // The proxy signs only what was asked for: participant calls with --sign-as,\n // and its own --claim registration.\n if (cmdOpts.signAs !== undefined || cmdOpts.claim !== undefined) {\n const principal = typeof cmdOpts.signAs === 'string'\n ? parsePrincipalSpec(cmdOpts.signAs)\n : getPrincipalSpec();\n reportIdentity(await setupSigning(hub.channel, hub.signing, principal, {\n negotiateHubCaps: isHubEndpoint(localEp),\n }));\n }\n // Connect the participant last: proxyCommand installs its forwarders\n // synchronously, before any message the participant sent is dispatched.\n const participant = targetEp === undefined\n ? await connectStdioParticipant()\n : await connectTargetEndpoint(targetEp, cmdOpts.claim ?? '').then((connection) => ({ connection, closed: connection.closed }));\n try {\n await proxyCommand({\n hub,\n participant: participant.connection,\n outbound: !cmdOpts.outbound ? 'none' : cmdOpts.signAs !== undefined ? 'signed' : 'verbatim',\n ...(cmdOpts.claim !== undefined ? { claimServiceId: cmdOpts.claim } : {}),\n ...(participant.closed !== undefined ? { stop: participant.closed } : {}),\n });\n } finally {\n participant.connection.close();\n hub.close();\n }\n });\n\n program\n .command('connect-as <binderServiceId> <slot>')\n .description(\n 'Mint a single-use identity token for <slot> from the <binderServiceId> ' +\n '(a service implementing connectionTokenBinder, typically the hub service id), ' +\n 'then splice a target endpoint onto the hub as a first-class participant with that ' +\n 'slot\\'s managed identity and a granted serviceId namespace (--granted-service-id, ' +\n 'defaulting to <slot>). No local hub is started: the CLI ' +\n 'proxies the connection (target ⟷ CLI ⟷ hub), so it works with every target kind and ' +\n '--log-messages taps the full flow. The hub-facing bound-token listener is ' +\n '--hub-endpoint (defaults to --endpoint when that is a ws/socket). Runs until Ctrl-C.',\n )\n .option(\n '--hub-endpoint <uri>',\n 'ws/socket bound-token listener to splice the target onto (default: --endpoint)',\n )\n .option('--target-endpoint <uri>', 'target endpoint URI (unix:/…, ws[s]://…)')\n .option('--target-endpoint-cmd <command>', 'spawn the target as a server; it dials the CLI back')\n .option('--target-endpoint-cmd-stdio <command>', 'spawn the target and talk linkrpc over its stdio')\n .option(\n '--target-endpoint-cmd-env <key=value>',\n 'env var for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option('--target-endpoint-token <token>', 'token overriding the target URI token')\n .option(\n '--target-endpoint-cmd-cwd <dir>',\n 'working directory for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child',\n )\n .option(\n '--granted-service-id <serviceId>',\n 'serviceId namespace to grant the target (default: <slot>)',\n )\n .action(async (binderServiceId: string, slot: string, cmdOpts: {\n hubEndpoint?: string;\n targetEndpoint?: string;\n targetEndpointCmd?: string;\n targetEndpointCmdStdio?: string;\n targetEndpointCmdEnv?: Record<string, string>;\n targetEndpointToken?: string;\n targetEndpointCmdCwd?: string;\n grantedServiceId?: string;\n }) => {\n const localEp = needEndpoint(endpoint);\n\n // Resolve the hub-facing (bound-token) listener the target is spliced\n // onto. Defaults to --endpoint when that is itself a dial-able ws/socket.\n let hubEp: DialEndpoint;\n try {\n hubEp = _resolveDialEndpoint(cmdOpts.hubEndpoint, localEp);\n } catch (e) {\n process.stderr.write(`linkrpc: ${(e as Error).message}\\n`);\n process.exit(2);\n }\n\n const targetRes = resolveTargetEndpoint({\n targetEndpoint: cmdOpts.targetEndpoint,\n targetEndpointCmd: cmdOpts.targetEndpointCmd,\n targetEndpointCmdStdio: cmdOpts.targetEndpointCmdStdio,\n targetEndpointCmdEnv: cmdOpts.targetEndpointCmdEnv,\n targetEndpointToken: cmdOpts.targetEndpointToken,\n targetEndpointCmdCwd: cmdOpts.targetEndpointCmdCwd,\n });\n if (targetRes.error) {\n process.stderr.write(`linkrpc: ${targetRes.error}\\n`);\n process.exit(2);\n }\n if (!targetRes.endpoint) {\n process.stderr.write(\n 'linkrpc: connect-as requires --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio.\\n',\n );\n process.exit(2);\n }\n const targetEp = targetRes.endpoint;\n\n // Broker connection: sign the mint call where the hub requires it.\n const broker = await connectEndpoint(localEp, wireLog('broker'));\n try {\n const session = await setupSigning(broker.channel, broker.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n\n const brokerConn = new LinkRpcConnection(broker.rpcChannel);\n const binder = brokerConn.service(binderServiceId).get(connectionTokenBinderInterface);\n\n const logLine = (line: string): void => { process.stderr.write(`linkrpc: ${line}\\n`); };\n const serviceIdNamespace = cmdOpts.grantedServiceId ?? slot;\n await connectAs({\n mintToken: async () => {\n const { token } = await binder.bindConnectionToken({\n identitySlot: slot,\n serviceIdNamespace,\n });\n logLine(\n `connect-as: minted token for identity slot '${slot}'` +\n `${serviceIdNamespace !== slot ? `, granted serviceId '${serviceIdNamespace}'` : ''}` +\n ` via ${binderServiceId}`,\n );\n return token;\n },\n openHubTransport: (token) => openDialTransport(hubEp, token),\n openTargetTransport: () => openTargetTransport(targetEp, logLine),\n ...(g_logMessages\n ? {\n tapTarget: (t) => tapTransport(t, {\n log: logLine,\n localLabel: 'cli',\n remoteLabel: 'target',\n }),\n }\n : {}),\n log: logLine,\n stop: _untilSignalled(),\n });\n } finally {\n broker.close();\n }\n });\n\n program\n .command('mcp-forward [mcpCommand...]')\n .description(\n 'Expose an MCP server through the hub (--endpoint*) as a transparent forwarder. ' +\n 'By default it claims this connection\\'s granted serviceId namespace; pass ' +\n '--serviceId to claim a specific prefix. The MCP server command follows `--`, e.g. ' +\n '`linkrpc mcp-forward -- npx -y @modelcontextprotocol/server-everything` or ' +\n '`linkrpc mcp-forward --serviceId my-mcp -- npx -y @modelcontextprotocol/server-everything`. ' +\n 'Each consumer that opens `<serviceId>::vscode.mcp-forward::connect` spawns a fresh child ' +\n 'and gets its MCP stdio bridged raw over the stream. Runs until Ctrl-C.',\n )\n .option(\n '--serviceId <serviceId>',\n 'serviceId prefix to claim (default: the connection\\'s granted serviceId namespace)',\n )\n .option(\n '--env <key=value>',\n 'env var for the spawned MCP server child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .action(async (mcpCommand: string[] | undefined, cmdOpts: {\n serviceId?: string;\n env?: Record<string, string>;\n }) => {\n const localEp = needEndpoint(endpoint);\n if (!mcpCommand || mcpCommand.length === 0) {\n process.stderr.write(\n 'linkrpc: mcp-forward requires an MCP server command after `--`, e.g. ' +\n '`mcp-forward -- npx -y @modelcontextprotocol/server-everything`.\\n',\n );\n process.exit(2);\n }\n const local = await connectEndpoint(localEp, wireLog('hub'));\n try {\n const session = await setupSigning(local.channel, local.signing, getPrincipalSpec(), {\n negotiateHubCaps: isHubEndpoint(localEp),\n });\n reportIdentity(session);\n await mcpForwardCommand({\n ...(cmdOpts.serviceId !== undefined ? { serviceId: cmdOpts.serviceId } : {}),\n local,\n command: { argv: mcpCommand },\n ...(cmdOpts.env !== undefined ? { env: cmdOpts.env } : {}),\n });\n } finally {\n local.close();\n }\n });\n\n program\n .command('identity')\n .description('Inspect the persistent principal used by connected CLI commands.')\n .command('show')\n .description('Print the resolved persistent CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (opts: { json?: boolean; }) => {\n await withResolvedSigning(endpoint, getPrincipalSpec(), async (_conn, session) => {\n const out = formatCliIdentity(cliIdentity(session), opts.json === true);\n process.stdout.write(out + '\\n');\n });\n });\n\n const approval = program\n .command('approval')\n .description('Inspect and decide pending Hub access approval requests.');\n\n approval\n .command('requests')\n .description('List pending requests whose capability audience is this CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (opts: { json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const out = formatApprovalRequests(\n await client.requests(),\n client.principalId,\n opts.json === true,\n );\n process.stdout.write(out + '\\n');\n });\n });\n\n approval\n .command('approve <request-id>')\n .description('Approve one pending request for this CLI identity.')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (requestId: string, opts: { json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const outcome = await client.approve(requestId);\n process.stdout.write(\n formatApprovalDecision(\n 'approved',\n requestId,\n client.principalId,\n opts.json === true,\n outcome,\n ) + '\\n',\n );\n });\n });\n\n approval\n .command('deny <request-id>')\n .description('Deny one pending request for this CLI identity.')\n .option('--reason <text>', 'optional denial reason')\n .option('--json', 'stable machine-readable JSON output')\n .action(async (requestId: string, opts: { reason?: string; json?: boolean; }) => {\n await withApprovalClient(endpoint, getPrincipalSpec(), async (client) => {\n const outcome = await client.deny(requestId, opts.reason);\n process.stdout.write(\n formatApprovalDecision(\n 'denied',\n requestId,\n client.principalId,\n opts.json === true,\n outcome,\n ) + '\\n',\n );\n });\n });\n\n approval\n .command('ui')\n .description('Watch pending requests and approve or deny them interactively in the terminal.')\n .action(async () => {\n if (\n process.stdin.isTTY !== true\n || process.stdout.isTTY !== true\n || !Number.isInteger(process.stdout.columns)\n || process.stdout.columns <= 0\n || !Number.isInteger(process.stdout.rows)\n || process.stdout.rows <= 0\n ) {\n throw new Error('approval ui requires an interactive terminal with visible output');\n }\n const stop = new AbortController();\n const onSignal = () => stop.abort();\n await withApprovalClient(\n endpoint,\n getPrincipalSpec(),\n async (client) => {\n process.once('SIGINT', onSignal);\n process.once('SIGTERM', onSignal);\n try {\n const { runApprovalUi } = await import('./approval-ui/runApprovalUi');\n await runApprovalUi({ client, signal: stop.signal });\n } finally {\n process.removeListener('SIGINT', onSignal);\n process.removeListener('SIGTERM', onSignal);\n }\n },\n () => { /* Ink owns the terminal while the approval UI is active. */ },\n );\n });\n }\n\n registerViewCommands(program, action => withChannel(endpoint, getPrincipalSpec(), action));\n\n program\n .command('ui')\n .description('Launch the terminal UI (form-based browser of services + methods).')\n .action(async () => {\n const acquired = await acquireConnection(endpoint);\n const { runUi } = await import('./ui/runUi');\n try {\n await runUi({\n endpoint: acquired.ep, principalSpec: getPrincipalSpec(), profile,\n schema: g_invocation?.values.schema === undefined ? undefined\n : await loadStaticHubSchema(g_invocation.values.schema),\n });\n } finally {\n acquired.running?.dispose();\n }\n });\n\n if (profile === 'hub') {\n program\n .command('logout')\n .description(\n 'Delete the stored keypair and cached capabilities of the identity selected by --principal '\n + '(default: the user:hubrpc-cli fallback). Asks for confirmation unless --yes is given. '\n + 'The next call mints a fresh keypair, which hubs that trusted the old key do not accept.',\n )\n .option('-y, --yes', 'delete without asking for confirmation')\n .action(async (opts: { yes?: boolean }) => {\n const target = cliIdentityTarget(getPrincipalSpec());\n const principal = await readCliIdentity(target);\n if (principal === undefined) {\n process.stdout.write(`linkrpc: no stored identity for ${target.label} (${target.file}).\\n`);\n return;\n }\n const description = `identity ${target.label} (${principal}) at ${target.file}`;\n if (opts.yes !== true) {\n if (process.stdin.isTTY !== true || process.stderr.isTTY !== true) {\n throw new Error(`Refusing to delete ${description} without confirmation; pass --yes.`);\n }\n const readline = createInterface({ input: process.stdin, output: process.stderr });\n const answer = await readline.question(\n `Delete ${description} and its cached capabilities? This cannot be undone. [y/N] `,\n ).finally(() => readline.close());\n if (!/^y(es)?$/i.test(answer.trim())) {\n process.stderr.write('linkrpc: logout cancelled.\\n');\n return;\n }\n }\n for (const f of await deleteCliIdentity(target)) {\n process.stdout.write(`removed ${f}\\n`);\n }\n });\n }\n\n program\n .command('completions <shell>')\n .description(\n 'Print a shell completion script. Supported: powershell. Install with ' +\n '`hub completions powershell | Out-String | Invoke-Expression` (one-shot) or ' +\n 'append to $PROFILE.',\n )\n .action((shell: string) => {\n try {\n const script = completionsCommand({ shell });\n process.stdout.write(script);\n if (!script.endsWith('\\n')) process.stdout.write('\\n');\n } catch (e) {\n process.stderr.write(`linkrpc: ${(e as Error).message}\\n`);\n process.exit(2);\n }\n });\n\n program\n .command('_complete')\n .description(\n '(internal) Emit completion candidates for a partial command line. ' +\n 'Invoked by the scripts produced by `hub completions`.',\n )\n .option('--line <line>', 'the partial command line, including the binary name')\n .option('--point <n>', 'cursor position (0-indexed) into --line', (v) => Number.parseInt(v, 10))\n .action(async (opts: { line?: string; point?: number; }) => {\n // The completer must NEVER write to stderr or non-zero-exit — that\n // would surface in the user's prompt. Always exit 0 with whatever\n // we managed to compute (possibly nothing). Force-exit at the end\n // so any open socket / setup-signing timer can't keep the process\n // alive past the action — that hangs the user's shell on TAB.\n try {\n const line = opts.line ?? '';\n const point = typeof opts.point === 'number' && !Number.isNaN(opts.point)\n ? opts.point\n : line.length;\n const out = await internalCompleteCommand({ line, point });\n if (out.length > 0) process.stdout.write(out + '\\n');\n } catch {\n // swallow\n }\n // Force-exit: completion is one-shot and must never hang.\n process.exit(0);\n });\n\n if (profile === 'rpc') {\n program\n .command('hub')\n .description('Run the same shared commands with the hub profile and expose hub-only commands.');\n }\n\n await program.parseAsync([\n 'node',\n cliInvocation.programName,\n ...rewriteParamShortcuts(cliInvocation.argv),\n ]);\n}\n\nfunction collectContextOverrides(program: Command, actionCommand: Command): ContextValues {\n const opts = program.opts();\n const result: Record<string, unknown> = {};\n copyExplicit(program, opts, result, 'endpoint');\n copyExplicit(program, opts, result, 'endpointCmd');\n copyExplicit(program, opts, result, 'endpointCmdStdio');\n copyExplicit(program, opts, result, 'endpointCmdEnv');\n copyExplicit(program, opts, result, 'endpointToken');\n copyExplicit(program, opts, result, 'endpointCmdCwd');\n copyExplicit(program, opts, result, 'config');\n copyExplicit(program, opts, result, 'provisionIdentity');\n copyExplicit(program, opts, result, 'provisionIdentitySlot');\n copyExplicit(program, opts, result, 'principal');\n copyExplicit(program, opts, result, 'sign');\n copyExplicit(program, opts, result, 'schema');\n copyExplicit(program, opts, result, 'validation');\n copyExplicit(program, opts, result, 'daemonService');\n copyExplicit(program, opts, result, 'detachKeys');\n for (let command: Command | null = actionCommand; command; command = command.parent) {\n if (command.name() === 'services') copyExplicit(command, command.opts(), result, 'namespace');\n }\n\n if (getCommandPath(actionCommand) === 'connection create') {\n const actionOpts = actionCommand.opts();\n copyExplicit(actionCommand, actionOpts, result, 'timeout', 'connectionTimeout');\n copyExplicit(actionCommand, actionOpts, result, 'ttl', 'connectionTtl');\n copyExplicit(actionCommand, actionOpts, result, 'notificationLimit');\n }\n return result as ContextValues;\n}\n\nfunction copyExplicit(\n command: Command,\n source: Record<string, unknown>,\n target: Record<string, unknown>,\n optionName: string,\n contextName = optionName,\n): void {\n if (command.getOptionValueSource(optionName) === 'cli') {\n target[contextName] = source[optionName];\n }\n}\n\nfunction explicitOption<T>(command: Command, name: string): T | undefined {\n return command.getOptionValueSource(name) === 'cli'\n ? command.opts()[name] as T\n : undefined;\n}\n\nasync function createContextFromInvocation(\n store: ContextStore,\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n values: ContextValues,\n ownedConnection?: StoredContext['ownedConnection'],\n): Promise<void> {\n await store.replace(reference, values, { createOnly: true, ownedConnection });\n process.stderr.write(`linkrpc: created context ${formatContextReference(reference)}.\\n`);\n}\n\nasync function createConnectionContext(\n store: ContextStore,\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n values: ContextValues,\n brokerEndpoint: string,\n): Promise<void> {\n const {\n endpoint: _endpoint,\n endpointCmd: _endpointCmd,\n endpointCmdStdio: _endpointCmdStdio,\n endpointCmdEnv: _endpointCmdEnv,\n endpointToken: _endpointToken,\n endpointCmdCwd: _endpointCmdCwd,\n provisionIdentity: _provisionIdentity,\n provisionIdentitySlot: _provisionIdentitySlot,\n ...rest\n } = values;\n const connectionEndpoint = splitEndpointToken(brokerEndpoint);\n await createContextFromInvocation(store, reference, {\n ...rest,\n ...connectionEndpoint,\n }, { endpoint: brokerEndpoint });\n}\n\nfunction splitEndpointToken(endpoint: string): Pick<ContextValues, 'endpoint' | 'endpointToken'> {\n const parsed = parseEndpointUri(endpoint);\n if ((parsed.kind !== 'socket' && parsed.kind !== 'ws') || parsed.token === undefined) {\n return { endpoint };\n }\n const { token, ...withoutToken } = parsed;\n const separator = formatEndpointUri(withoutToken).includes('?') ? '&' : '?';\n return {\n endpoint: `${formatEndpointUri(withoutToken)}${separator}token=%`,\n endpointToken: token,\n };\n}\n\nfunction mutableReference(\n reference: ContextReference,\n): Exclude<ContextReference, { readonly kind: 'empty'; }> {\n if (reference.kind === 'empty') {\n throw new Error(':empty is immutable and cannot be modified');\n }\n return reference;\n}\n\n/** The root context applies to every folder without a context: change it only when selected explicitly. */\nfunction assertExplicitRootMutation(selected: SelectedContext): void {\n if (selected.selectedBy === 'root') {\n throw new Error('No folder or named context applies here, so the root context is in effect. '\n + 'To change defaults for every such folder, select it explicitly with --context :root; '\n + 'to create a context for this folder, use --new-context .');\n }\n}\n\nfunction printSelectedContext(effective: boolean): void {\n if (g_invocation === undefined) throw new Error('context resolver is unavailable');\n const selected = g_invocation.selected;\n process.stdout.write('Context\\n');\n process.stdout.write(` Reference: ${formatContextReference(selected.reference)}\\n`);\n process.stdout.write(` Selected via: ${contextSelectionDescription(selected.selectedBy)}\\n`);\n if (effective) {\n process.stdout.write(` Profile: ${g_invocation.profile}\\n`);\n const environmentStatus = g_invocation.environmentApplied\n ? Object.keys(g_invocation.environmentValues).length > 0\n ? 'enabled'\n : 'enabled (no variables set)'\n : 'disabled';\n process.stdout.write(\n ` Environment overrides: ${environmentStatus}\\n`,\n );\n }\n\n process.stdout.write('\\nStored defaults\\n');\n printContextValues(selected.context?.values ?? {}, false);\n if (!effective) return;\n\n process.stdout.write('\\nEffective values\\n');\n printContextValues(g_invocation.values, false, (key) => {\n if (hasContextValue(g_invocation?.cliOverrides, key)) return 'command line';\n if (hasContextValue(g_invocation?.environmentValues, key)) return 'environment';\n if (hasContextValue(g_invocation?.contextValues, key)) return 'context';\n return undefined;\n });\n}\n\nfunction contextSelectionDescription(selectedBy: ResolvedInvocationContext['selected']['selectedBy']): string {\n switch (selectedBy) {\n case 'argument': return '--context';\n case 'environment': return 'LINKRPC_CONTEXT (HUBRPC_CONTEXT fallback)';\n case 'cwd': return 'current-directory lookup';\n case 'root': return ':root fallback (no folder context applies)';\n case 'empty': return 'no matching context (:empty)';\n }\n}\n\nfunction hasContextValue(\n values: ContextValues | undefined,\n key: keyof ContextValues,\n): boolean {\n return values !== undefined && values[key] !== undefined;\n}\n\nfunction printContextValues(\n values: ContextValues,\n revealToken: boolean,\n source?: (key: keyof ContextValues) => string | undefined,\n): void {\n const entries = Object.entries(values);\n if (entries.length === 0) {\n process.stdout.write(' (none)\\n');\n return;\n }\n for (const [key, value] of entries) {\n const contextKey = key as keyof ContextValues;\n const rendered = key === 'endpointToken' && !revealToken\n ? '<stored>'\n : key === 'endpoint' && typeof value === 'string' && !revealToken\n ? redactEndpointTokens(value)\n : typeof value === 'string'\n ? value\n : JSON.stringify(value);\n const valueSource = source?.(contextKey);\n process.stdout.write(\n ` --${contextValueFlag(contextKey)} = ${rendered}${valueSource ? ` (${valueSource})` : ''}\\n`,\n );\n }\n\n function redactEndpointTokens(endpoint: string): string {\n return endpoint.replace(/([?&]token=)([^&#]*)/g, (_match, prefix: string, token: string) =>\n `${prefix}${token === '%' ? '%' : '<stored>'}`);\n }\n}\n\nfunction contextValueFlag(key: keyof ContextValues): string {\n const names: Record<keyof ContextValues, string> = {\n daemonService: 'daemon-service',\n detachKeys: 'detach-keys',\n namespace: 'namespace',\n endpoint: 'endpoint',\n endpointCmd: 'endpoint-cmd',\n endpointCmdStdio: 'endpoint-cmd-stdio',\n endpointCmdEnv: 'endpoint-cmd-env',\n endpointToken: 'endpoint-token',\n endpointCmdCwd: 'endpoint-cmd-cwd',\n config: 'config',\n provisionIdentity: 'provision-identity',\n provisionIdentitySlot: 'provision-identity-slot',\n principal: 'principal',\n sign: 'sign',\n schema: 'schema',\n validation: 'validation',\n connectionTimeout: 'connection-timeout',\n connectionTtl: 'connection-ttl',\n notificationLimit: 'notification-limit',\n };\n return names[key];\n}\n\nfunction parseContextValueKey(value: string): keyof ContextValues {\n const entry = (Object.keys({\n daemonService: true,\n detachKeys: true,\n namespace: true,\n endpoint: true,\n endpointCmd: true,\n endpointCmdStdio: true,\n endpointCmdEnv: true,\n endpointToken: true,\n endpointCmdCwd: true,\n config: true,\n provisionIdentity: true,\n provisionIdentitySlot: true,\n principal: true,\n sign: true,\n schema: true,\n validation: true,\n connectionTimeout: true,\n connectionTtl: true,\n notificationLimit: true,\n }) as (keyof ContextValues)[]).find((key) => contextValueFlag(key) === value);\n if (entry === undefined) throw new InvalidArgumentError(`unknown context value \"${value}\"`);\n return entry;\n}\n\nfunction effectiveValidation(profile: CliProfile): ValidationMode {\n return g_invocation?.values.validation ?? validationDefault(profile);\n}\n\n/** The configured TTY detach sequence; validated when used, so invalid stored values fail with a clear message. */\nfunction detachKeys(): DetachKeys | undefined {\n const spec = g_invocation?.values.detachKeys;\n return spec === undefined ? undefined : DetachKeys.parse(spec);\n}\n\nfunction parseValidationMode(value: string): ValidationMode {\n if (value === 'auto' || value === 'required' || value === 'off') return value;\n throw new InvalidArgumentError(\"--validation must be 'auto', 'required', or 'off'\");\n}\n\nfunction getCommandPath(command: Command): string {\n const names: string[] = [];\n for (let cursor: Command | null = command; cursor?.parent !== null; cursor = cursor.parent) {\n names.unshift(cursor.name());\n }\n return names.join(' ');\n}\n\nfunction commandUsesEndpoint(commandPath: string): boolean {\n return !(\n commandPath === 'context'\n || commandPath.startsWith('context ')\n || commandPath === 'codegen'\n || commandPath === 'schema hash'\n || commandPath === 'completions'\n || commandPath === '_complete'\n || commandPath === '_connection-broker'\n || commandPath === 'serve'\n || commandPath === 'logout'\n );\n}\n\nfunction hasEndpointOverrides(values: ContextValues): boolean {\n return values.endpoint !== undefined\n || values.endpointCmd !== undefined\n || values.endpointCmdStdio !== undefined\n || values.endpointCmdEnv !== undefined\n || values.endpointToken !== undefined\n || values.endpointCmdCwd !== undefined\n || values.provisionIdentity !== undefined\n || values.provisionIdentitySlot !== undefined;\n}\n\nasync function withChannel(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (channel: import('@hediet/linkrpc-client-internal').CliChannel, session?: SigningSession) => Promise<void>,\n opts: {\n requestReflectionAccess?: boolean;\n requestTopologyAccess?: { readonly sourceServiceIds?: readonly string[] };\n requireSigning?: boolean;\n autoNegotiatePerCall?: boolean;\n } = {},\n): Promise<void> {\n const sign = resolveSigning(g_invocation?.profile ?? 'rpc', g_invocation?.values ?? {}, opts.requireSigning);\n const acquired = await acquireConnection(endpoint);\n // When `--config` runs an in-process hub, that hub already logs its routed\n // traffic (richer than the client leg) — so only tap the wire for a direct\n // remote connection, to avoid double-logging the control socket.\n const conn = await connectEndpoint(acquired.ep, acquired.running === undefined ? wireLog('hub') : undefined);\n try {\n const schemaSource = g_invocation?.values.schema;\n const channel = schemaSource === undefined\n ? conn.channel\n : withStaticHubReflection(conn.channel, await loadStaticHubSchema(schemaSource));\n if (\n acquired.ep.kind === 'ws-no-init'\n || (acquired.ep.kind === 'socket' && acquired.ep.brokerMode === 'raw')\n ) {\n if (opts.requireSigning || g_invocation?.values.sign === true) {\n throw new Error('Signing requires an initialized LinkRPC endpoint.');\n }\n await fn(channel);\n return;\n }\n if (!sign) {\n await fn(channel);\n return;\n }\n\n const session = await setupSigning(conn.channel, conn.signing, principalSpec, {\n negotiateHubCaps: acquired.running !== undefined || isHubEndpoint(acquired.ep),\n autoNegotiatePerCall: opts.autoNegotiatePerCall,\n });\n reportIdentity(session);\n // Up-front, batched reflection grant across all services. One consent\n // prompt covers `ls` / `schema` / `defaults`; if denied we fall back to\n // per-call auto-cap negotiation installed by `setupSigning`.\n if (\n opts.requestReflectionAccess !== false\n && schemaSource === undefined\n && (acquired.running !== undefined || isHubEndpoint(acquired.ep))\n ) {\n const status = await requestReflectionAccess(session);\n if (status === 'denied') {\n process.stderr.write(\n 'linkrpc: reflection access denied; falling back to per-call negotiation.\\n',\n );\n }\n }\n if (\n opts.requestTopologyAccess !== undefined\n && (acquired.running !== undefined || isHubEndpoint(acquired.ep))\n ) {\n const status = await requestTopologyAccess(session, opts.requestTopologyAccess);\n if (status === 'denied') {\n process.stderr.write(\n 'linkrpc: topology access denied; topology sources may be inaccessible.\\n',\n );\n }\n }\n await fn(channel, session);\n } finally {\n conn.close();\n acquired.running?.dispose();\n }\n}\n\nasync function withResolvedSigning(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (connection: CliConnection, session: SigningSession) => Promise<void>,\n): Promise<void> {\n resolveSigning(g_invocation?.profile ?? 'rpc', g_invocation?.values ?? {}, true);\n const acquired = await acquireConnection(endpoint);\n if (\n acquired.ep.kind === 'ws-no-init'\n || (acquired.ep.kind === 'socket' && acquired.ep.brokerMode === 'raw')\n ) {\n acquired.running?.dispose();\n throw new Error('identity and approval commands require a LinkRPC endpoint');\n }\n const conn = await connectEndpoint(acquired.ep, acquired.running === undefined ? wireLog('hub') : undefined);\n try {\n const session = await setupSigning(conn.channel, conn.signing, principalSpec, {\n negotiateHubCaps: acquired.running !== undefined || isHubEndpoint(acquired.ep),\n autoNegotiatePerCall: false,\n });\n await fn(conn, session);\n } finally {\n conn.close();\n acquired.running?.dispose();\n }\n}\n\nasync function withApprovalClient(\n endpoint: ResolvedEndpoint | undefined,\n principalSpec: PrincipalSpec,\n fn: (client: ApprovalCommandClient) => Promise<void>,\n log: (line: string) => void = (line) => process.stderr.write(`linkrpc: ${line}\\n`),\n): Promise<void> {\n await withResolvedSigning(endpoint, principalSpec, async (conn, session) => {\n reportIdentity(session);\n await bootstrapApprovalCapability(session.principal);\n const connection = new LinkRpcConnection(conn.rpcChannel);\n const client = createHubApprovalCommandClient(\n connection,\n session.principal.identity,\n log,\n () => session.principal.capBag.capabilities,\n () => bootstrapApprovalCapability(session.principal, log),\n );\n try {\n await fn(client);\n } finally {\n client.dispose();\n }\n });\n}\n\nasync function withRawConnection(\n endpoint: ResolvedEndpoint | undefined,\n fn: (channel: import('@hediet/linkrpc-client-internal').CliChannel) => Promise<void>,\n): Promise<void> {\n if (g_hubConfigPath !== undefined) {\n throw new Error('connection broker commands do not support --config');\n }\n const conn = await connectEndpoint(needEndpoint(endpoint), wireLog('connection broker'));\n try {\n await fn(conn.channel);\n } finally {\n conn.close();\n }\n}\n\nfunction parsePositiveInteger(value: string, option: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed <= 0) {\n throw new InvalidArgumentError(`${option} must be a positive integer`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string, option: string): number {\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError(`${option} must be a non-negative integer`);\n }\n return parsed;\n}\n\n/**\n * Module-level config path, set per-command in the `preAction` hook. When set,\n * client commands run an in-process hub from the config and target its private\n * control socket instead of `--endpoint`.\n */\nlet g_hubConfigPath: string | undefined;\nlet g_contextStore: ContextStore | undefined;\nlet g_invocation: ResolvedInvocationContext | undefined;\n\n/**\n * Module-level flag, set per-command in the `preAction` hook. When set, the\n * in-process hub (`-c, --config` or `serve`) logs every routed JSON-RPC\n * message to stderr. Forced off for `ui` (it would corrupt the TUI).\n */\nlet g_logMessages = false;\nlet g_logTransport = false;\n\n/**\n * Build the wire-tap options for a direct {@link connect}, or `undefined` when\n * `--log-messages` is off. Logs every JSON-RPC message crossing the client\n * transport to stderr, rendered like the hub \"Flows\" view — the way to observe\n * a connection that never routes through a local hub.\n */\nfunction wireLog(remoteLabel: string): ConnectLogOptions | undefined {\n if (!g_logMessages && !g_logTransport) return undefined;\n return {\n ...(g_logMessages\n ? { log: (line: string) => process.stderr.write(`linkrpc: ${line}\\n`) }\n : {}),\n ...(g_logTransport\n ? {\n trace: (direction: 'send' | 'receive', message: import('@hediet/linkrpc').JsonRpcMessage) =>\n process.stderr.write(`linkrpc: transport ${direction} ${JSON.stringify(message)}\\n`),\n }\n : {}),\n remoteLabel,\n };\n}\n\n/**\n * Resolve the endpoint a client command should connect to. With `--config`,\n * spins up an in-process hub and returns its control socket (the caller must\n * `running.dispose()` when done); otherwise returns the resolved `--endpoint`.\n */\nasync function acquireConnection(\n endpoint: ResolvedEndpoint | undefined,\n): Promise<{ ep: ResolvedEndpoint; running?: RunningHub; }> {\n if (g_hubConfigPath !== undefined) {\n const config: HubConfig = loadHubConfig(g_hubConfigPath);\n const running = await runHub({ config, logMessages: g_logMessages });\n return {\n ep: { kind: 'socket', path: running.controlEndpoint.path, token: running.controlEndpoint.token },\n running,\n };\n }\n if (endpoint === undefined && g_invocation?.profile === 'hub') {\n // Without a configured endpoint, the hub profile uses the local Hub daemon whenever it runs.\n try {\n return { ep: resolveLocalEndpoint() };\n } catch {\n const ignoredEnvironmentHint = ignoredEndpointEnvironmentHint();\n throw new Error('No endpoint configured through flags, environment, or context, and the local Hub daemon is not running. '\n + `Pass ${endpointOptionsDescription()}, or start the daemon (any \\`hub services run\\` starts it).`\n + (ignoredEnvironmentHint === undefined ? '' : ` ${ignoredEnvironmentHint}.`));\n }\n }\n return { ep: needEndpoint(endpoint) };\n}\n\n/** Print the identity used to sign calls to stderr (keeps stdout clean for JSON output). */\nfunction reportIdentity(session: SigningSession): void {\n process.stderr.write(\n `linkrpc: identity ${formatPrincipalSource(session.principalSource, session.principal.id)\n }\\n`,\n );\n}\n\nfunction needEndpoint(endpoint: ResolvedEndpoint | undefined): ResolvedEndpoint {\n if (!endpoint) {\n const ignoredEnvironmentHint = ignoredEndpointEnvironmentHint();\n process.stderr.write(\n `linkrpc: this command requires ${endpointOptionsDescription()}.\\n`\n + (ignoredEnvironmentHint === undefined ? '' : `linkrpc: ${ignoredEnvironmentHint}.\\n`),\n );\n process.exit(2);\n }\n return endpoint;\n}\n\nfunction endpointOptionsDescription(): string {\n const options = '--endpoint / --endpoint-cmd / --endpoint-cmd-stdio or a configured context';\n return g_invocation?.profile === 'hub' && g_invocation.environmentApplied\n ? `${options} or LINKRPC_ENDPOINT`\n : options;\n}\n\nfunction ignoredEndpointEnvironmentHint(): string | undefined {\n const invocation = g_invocation;\n if (invocation === undefined || invocation.environmentApplied) return undefined;\n const variable = process.env.LINKRPC_ENDPOINT !== undefined\n ? 'LINKRPC_ENDPOINT'\n : process.env.HUBRPC_ENDPOINT !== undefined\n ? 'HUBRPC_ENDPOINT'\n : undefined;\n if (variable === undefined) return undefined;\n return invocation.profile === 'rpc'\n ? `${variable} is set but only used by hub commands: run \\`linkrpc hub <command>\\` (or pass --use-env)`\n : `${variable} is set but ignored because environment overrides are disabled; pass --use-env to apply it`;\n}\n\ninterface TargetEndpointCliOptions {\n readonly targetEndpoint?: string;\n readonly targetEndpointCmd?: string;\n readonly targetEndpointCmdStdio?: string;\n readonly targetEndpointCmdEnv?: Record<string, string>;\n readonly targetEndpointToken?: string;\n readonly targetEndpointCmdCwd?: string;\n}\n\n/** The `--target-endpoint*` options shared by `tunnel` and `proxy`. */\nfunction addTargetEndpointOptions(command: Command): Command {\n return command\n .option(\n '--target-endpoint <uri>',\n 'target endpoint URI (unix:/path?token=…, npipe://./pipe/…, ws[s]://host?token=…, ' +\n 'cmd:?command=… or cmd-stdio:?command=…)',\n )\n .option(\n '--target-endpoint-cmd <command>',\n 'spawn the target as a server, connect via an injected env socket; the child sees ' +\n 'the claimed service id as grantedServiceIdNamespace via hubGrantedServiceId::get',\n )\n .option(\n '--target-endpoint-cmd-stdio <command>',\n 'spawn the target and talk linkrpc over its stdio',\n )\n .option(\n '--target-endpoint-cmd-env <key=value>',\n 'env var for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child (repeatable)',\n (val: string, acc: Record<string, string> | undefined) => {\n const eq = val.indexOf('=');\n if (eq === -1) {\n throw new InvalidArgumentError(`expected key=value, got '${val}'`);\n }\n const next = acc ?? {};\n next[val.slice(0, eq)] = val.slice(eq + 1);\n return next;\n },\n )\n .option(\n '--target-endpoint-token <token>',\n 'token overriding the target URI token (no env fallback for the target)',\n )\n .option(\n '--target-endpoint-cmd-cwd <dir>',\n 'working directory for the --target-endpoint-cmd / --target-endpoint-cmd-stdio child',\n );\n}\n\nfunction hasTargetEndpoint(opts: TargetEndpointCliOptions): boolean {\n return opts.targetEndpoint !== undefined\n || opts.targetEndpointCmd !== undefined\n || opts.targetEndpointCmdStdio !== undefined;\n}\n\nfunction resolveTargetEndpointOrExit(\n opts: TargetEndpointCliOptions,\n globalOpts: Record<string, unknown>,\n commandName: string,\n): ResolvedEndpoint {\n const targetRes = resolveTargetEndpoint({\n ...opts,\n provisionIdentity: globalOpts.provisionIdentity as boolean | undefined,\n provisionIdentitySlot: globalOpts.provisionIdentitySlot as string | undefined,\n });\n if (targetRes.error) {\n process.stderr.write(`linkrpc: ${targetRes.error}\\n`);\n process.exit(2);\n }\n if (!targetRes.endpoint) {\n process.stderr.write(\n `linkrpc: ${commandName} requires --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio.\\n`,\n );\n process.exit(2);\n }\n // Honor the legacy LINKRPC_REMOTE_ENDPOINT_TOKEN env var as a fallback\n // for token-bearing target URIs.\n const targetEp = targetRes.endpoint;\n const remoteTok = process.env.LINKRPC_REMOTE_ENDPOINT_TOKEN;\n return remoteTok !== undefined && (targetEp.kind === 'socket' || targetEp.kind === 'ws')\n && targetEp.token === undefined\n ? { ...targetEp, token: remoteTok }\n : targetEp;\n}\n\n/**\n * Connect straight to a target endpoint — no routing hub. A spawned cmd-env\n * child is fronted with a RootOverlay: its root-form calls (identity::*,\n * hubGrantedServiceId::*, reflection, hubAccess) are served locally while every\n * forwarded request is relayed to the child through the overlay splitter. This\n * keeps --provision-identity working (identity::* is served) without the 'hub'\n * service id / claim-wait dance a full local hub imposes.\n */\nasync function connectTargetEndpoint(target: ResolvedEndpoint, grantedNamespace: string): Promise<CliConnection> {\n if (target.kind !== 'cmd-env') {\n return connectEndpoint(target, wireLog('target'));\n }\n return connectViaRootOverlay({\n command: target.command,\n provisionSlot: target.provisionSlot,\n env: target.env,\n ...(target.cwd !== undefined ? { cwd: target.cwd } : {}),\n grantedNamespace,\n log: wireLog('target'),\n });\n}\n\n/** This process's stdin/stdout as a participant; `closed` resolves when stdin ends. */\nasync function connectStdioParticipant(): Promise<{ connection: CliConnection; closed: Promise<void>; }> {\n let markClosed!: () => void;\n const closed = new Promise<void>((resolve) => { markClosed = resolve; });\n const { transport } = await connectNdjson({\n input: process.stdin,\n output: process.stdout,\n onClose: () => markClosed(),\n });\n return { connection: connectViaTransport(transport), closed };\n}\n\n/**\n * Resolve the ws/socket bound-token listener `connect-as` splices the target\n * onto: an explicit `--hub-endpoint <uri>`, else the fallback endpoint when it\n * is itself a dial-able ws/socket. Throws otherwise (cmd endpoints aren't\n * dial-able bound listeners).\n */\nfunction _resolveDialEndpoint(\n hubEndpoint: string | undefined,\n fallback: ResolvedEndpoint,\n): DialEndpoint {\n if (hubEndpoint !== undefined) {\n const spec = parseEndpointUri(hubEndpoint);\n if (spec.kind !== 'ws' && spec.kind !== 'socket') {\n throw new Error(`--hub-endpoint must be a ws/socket URI, got '${spec.kind}'`);\n }\n return spec;\n }\n if (fallback.kind === 'ws' || fallback.kind === 'socket') {\n return fallback;\n }\n throw new Error(\n 'connect-as requires --hub-endpoint <ws/socket uri> (the bound-token listener); ' +\n `--endpoint resolved to '${fallback.kind}', which is not a dial-able bound listener`,\n );\n}\n\n/** Resolve on the next `SIGINT` / `SIGTERM`. */\nfunction _untilSignalled(): Promise<void> {\n return new Promise<void>((resolve) => {\n const done = (): void => {\n process.removeListener('SIGINT', done);\n process.removeListener('SIGTERM', done);\n resolve();\n };\n process.once('SIGINT', done);\n process.once('SIGTERM', done);\n });\n}\n\nfunction resolveGraphFormat(\n rawFormat: unknown,\n aliases: { readonly json: boolean; readonly stream: boolean; readonly watch: boolean },\n): TopologyFormat {\n if (aliases.json && aliases.stream) {\n throw new InvalidArgumentError('--json and --stream cannot be combined');\n }\n if (rawFormat !== undefined && (aliases.json || aliases.stream)) {\n throw new InvalidArgumentError('--format cannot be combined with --json or --stream');\n }\n if (rawFormat !== undefined\n && rawFormat !== 'pretty'\n && rawFormat !== 'json'\n && rawFormat !== 'jsonl') {\n throw new InvalidArgumentError(\"--format must be 'pretty', 'json', or 'jsonl'\");\n }\n if (aliases.json) return 'json';\n if (aliases.stream) return 'jsonl';\n if (rawFormat !== undefined) return rawFormat;\n return aliases.watch && !process.stdout.isTTY ? 'jsonl' : 'pretty';\n}\n\nfunction collectOption(value: string, previous: readonly string[] | undefined): readonly string[] {\n return [...(previous ?? []), value];\n}\n\nfunction repaintTerminal(frame: string): void {\n process.stdout.write(`\\u001b[2J\\u001b[H${frame}\\n`);\n}\n\nfunction parseInterfaceRef(raw: string): { id: string; hash: string | undefined; } {\n const at = raw.lastIndexOf('@');\n if (at > 0 && !raw.slice(at + 1).includes('::')) {\n return { id: raw.slice(0, at), hash: raw.slice(at + 1) };\n }\n return { id: raw, hash: undefined };\n}\n\nexport function runCli(executableName: 'linkrpc' | 'rpc' | 'hub'): void {\n main(process.argv.slice(2), executableName).catch(async (e: unknown) => {\n const message = formatCliError(e);\n process.stderr.write(`linkrpc: ${message}\\n`);\n if (process.argv[2] === '_connection-broker') {\n await new Promise<void>((resolve, reject) => {\n process.stdout.write(JSON.stringify({ error: message }) + '\\n', error => {\n if (error) reject(error);\n else resolve();\n });\n });\n }\n process.exit(1);\n });\n}\n\nfunction formatCliError(error: unknown): string {\n if (typeof error !== 'object' || error === null) return String(error);\n\n const value = error as {\n readonly code?: unknown;\n readonly message?: unknown;\n readonly data?: unknown;\n };\n const message = typeof value.message === 'string' ? value.message : String(error);\n if (typeof value.code !== 'number' && typeof value.code !== 'string') return message;\n\n const data = value.data === undefined ? '' : ` data=${safeJson(value.data)}`;\n return `[${value.code}] ${message}${data}`;\n}\n\nfunction safeJson(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n"],"x_google_ignoreList":[35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAa,sBAAb,MAAiC;CAKR;CAEA;CACA;CACA;CARrB;CACA;CAEA,YACI,QACA,QACA,OACA,YACA,QACF;EALmB,KAAA,SAAA;EAEA,KAAA,QAAA;EACA,KAAA,aAAA;EACA,KAAA,SAAA;EAEjB,KAAK,UAAU,OAAO,SAAS;EAC/B,IAAI,OAAO,OAAO;GACd,KAAK,YAAYA,kBAAgB;IAAE,OAAO;IAAQ;IAAQ,UAAU;IAAM,QAAQ;IAAI,aAAa;GAAE,CAAC;GACtG,KAAK,UAAU,GAAG,QAAQ,KAAK,OAAO;GACtC,KAAK,UAAU,GAAG,UAAU,UAAU;GACtC,KAAK,UAAU,GAAG,SAAS,MAAM;GACjC,OAAO,GAAG,YAAY,KAAK,WAAW;EAC1C,OAAO;GACH,OAAO,GAAG,QAAQ,KAAK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