@hediet/linkrpc-cli 0.0.3-next.20260922.2 → 0.0.3-next.20260924.1
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 +164 -6
- package/dist/chunks/{cli-FDKN1ydZ.js → cli-CY5WVWEQ.js} +3552 -2015
- package/dist/chunks/cli-CY5WVWEQ.js.map +1 -0
- package/dist/chunks/dist-BOcSU4-O.js +1500 -0
- package/dist/chunks/dist-BOcSU4-O.js.map +1 -0
- package/dist/chunks/{runApprovalUi-CTyhiDpa.js → runApprovalUi-C4yIUu8Y.js} +5 -4
- package/dist/chunks/{runApprovalUi-CTyhiDpa.js.map → runApprovalUi-C4yIUu8Y.js.map} +1 -1
- package/dist/chunks/{runComplete-Du5wmOdB.js → runComplete-F95L0neY.js} +19 -17
- package/dist/chunks/runComplete-F95L0neY.js.map +1 -0
- package/dist/chunks/{runUi-CuJr8_tY.js → runUi-Dp2P3aNN.js} +639 -92
- package/dist/chunks/runUi-Dp2P3aNN.js.map +1 -0
- package/dist/chunks/{scroll--AVfTs5W.js → scroll-CY9Rcshb.js} +2 -2
- package/dist/chunks/{scroll--AVfTs5W.js.map → scroll-CY9Rcshb.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 +6 -6
- package/dist/chunks/cli-FDKN1ydZ.js.map +0 -1
- package/dist/chunks/runComplete-Du5wmOdB.js.map +0 -1
- package/dist/chunks/runUi-CuJr8_tY.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-CY5WVWEQ.js","names":["fetchSchema","fetchSchema","CLAIM_METHOD","_untilSignalled","traceMessageTransport","fetchSchema","toJsonValue","participantLabel","fetchSchema","_untilSignalled","hubConnection","fetchSchema","nonNegativeInteger","positiveInteger","positiveInteger","connectEndpoint"],"sources":["../../src/output.ts","../../src/suggest.ts","../../src/schemaLookup.ts","../../src/commands/call.ts","../../src/commands/batch.ts","../../src/commands/tunnel.ts","../../src/commands/connectionBroker.ts","../../src/commands/connectionBrokerClient.ts","../../src/commands/connectionBrokerProcess.ts","../../src/duration.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/approvalPresentation.ts","../../src/commands/approval.ts","../../src/commands/identity.ts","../../src/engine/runHub.ts","../../src/methodHelp.ts","../../src/paramFlags.ts","../../src/views/types.ts","../../src/views/discovery.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 { 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","/**\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';\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';\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, findMethodInSchema } from '@hediet/linkrpc-client';\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 {\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 /**\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 validation = opts.noValidate ? 'off' : (opts.validation ?? 'required');\n if (validation !== 'off') await validateParams(channel, ref, params, 'call', validation);\n const onStreamChunk = opts.onStreamChunk ?? writeChunkToStderr;\n try {\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 });\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<void> {\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 await _failWithSuggestion(channel, ref, verb);\n }\n const method = findMethodInSchema(schema, ref.methodName);\n if (!method) {\n await _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}\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\n/**\n * Friendly explanation for `permissionRequired` (-32401). Typical when the\n * CLI couldn't acquire a capability via `hubAccess::requestAccess` and the\n * target service gates on caps. The earlier `capability negotiation\n * skipped` warning explains *why* we couldn't get one; this footer tells\n * the user what to do.\n */\nfunction _formatPermissionRequired(e: RpcError): string {\n return [\n `Permission required: ${e.message}`,\n ' The hub gates this call on a capability, and none was acquired.',\n ' If your hub uses an access handler, accept the consent prompt and retry.',\n ' Otherwise, the hub admin has to issue a capability to this CLI identity',\n ` (\\`hub logout\\` then retry to mint a fresh identity).`,\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 { ErrorCode, type IncomingCall, type IRequestHandler, type JsonValue, RpcError } from '@hediet/linkrpc';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { hubServiceIdRegistryInterface } from '@hediet/linkrpc/hub/common';\nimport type { CliConnection } from '@hediet/linkrpc-client';\n\n/**\n * The wire method for the provenance claim front door. Mirrors\n * `Hub.registerServiceIdNamespace`, which calls\n * `connection.get(hubGrantedServiceIdInterface).register({ serviceId })`\n * with no serviceId prefix — i.e. interface-form\n * `hubGrantedServiceId::register`. The claimed serviceId must be\n * within the connection's granted namespace.\n */\nconst CLAIM_METHOD = `${hubGrantedServiceIdInterface.info.id}::register`;\nconst GET_CLAIM_NAMESPACE_METHOD = `${hubGrantedServiceIdInterface.info.id}::get`;\nconst GET_HUB_SERVICE_ID_METHOD = `${hubGrantedServiceIdInterface.info.id}::getHubServiceId`;\n\nexport interface TunnelOptions {\n readonly serviceId: string;\n /** Live connection to the hub we claim `serviceId` on and receive requests from. */\n readonly local: CliConnection;\n /** Live connection to the endpoint we forward every received request to. */\n readonly remote: CliConnection;\n /**\n * When set, also forward every request/notification the {@link remote}\n * endpoint emits back to {@link local} (the hub), exposing the hub to the\n * endpoint. Forwards everything verbatim (unsigned).\n */\n readonly bidi?: boolean;\n /**\n * Resolves to stop the tunnel (e.g. on SIGINT). When omitted, the tunnel\n * runs until the process is signalled (`SIGINT` / `SIGTERM`).\n */\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 service tunnel until stopped.\n *\n * Claims `serviceId` on {@link TunnelOptions.local} via the hub claim\n * interface, then forwards every inbound request/notification verbatim onto\n * {@link TunnelOptions.remote} and pipes the response back. Forwarding is\n * signature-preserving: the original caller's `$hubrpc` envelope rides inside\n * `params`, so the remote send is issued unsigned (`signerOverride: null`) to\n * avoid re-wrapping it. The streaming sub-protocol is bridged both ways, so\n * long-running / streaming calls forward their in-flight stream messages and\n * cancellation, not just the final response.\n *\n * When {@link TunnelOptions.bidi} is set, the mirror forwarder is also bound on\n * {@link TunnelOptions.remote}, so every request/notification the endpoint\n * emits is forwarded verbatim back to the hub.\n *\n * Resolves when {@link TunnelOptions.stop} resolves (or on `SIGINT`/`SIGTERM`).\n */\nexport async function tunnelCommand(opts: TunnelOptions): Promise<void> {\n const log = opts.log ?? ((line) => process.stderr.write(line + '\\n'));\n\n // Bind the catch-all forwarder BEFORE claiming so no request can race in\n // between the claim landing and the handler being installed.\n opts.local.setRequestHandler(createForwardingHandler(opts.remote));\n\n // When bidirectional, mirror the forwarder on the remote so every request\n // and notification the endpoint emits is routed back to the source hub.\n if (opts.bidi) {\n opts.remote.setRequestHandler(createForwardingHandler(opts.local));\n }\n\n // Claim via root namespace when in-namespace, otherwise via the hub-level\n // service id registry.\n await _claimServiceId(opts.local, opts.serviceId);\n log(\n opts.bidi\n ? `tunnel: claimed '${opts.serviceId}' — forwarding requests to remote (bidirectional)`\n : `tunnel: claimed '${opts.serviceId}' — forwarding requests to remote`,\n );\n\n await (opts.stop ?? _untilSignalled());\n log('tunnel: stopping');\n}\n\n/**\n * Build the inbound handler that forwards every request/notification received\n * on one connection onto `to`, bridging the streaming sub-protocol both ways\n * (see {@link _forwardRequest}). Used for the source→target direction and, in\n * bidirectional mode, the mirror.\n */\nexport function createForwardingHandler(to: CliConnection): IRequestHandler {\n return {\n handleRequest: (call) => _forwardRequest(to, call),\n handleNotification: (call) => _forwardNotification(to, call),\n };\n}\n\nasync function _claimServiceId(local: CliConnection, serviceId: string): Promise<void> {\n const namespaceRes = await local.channel.sendRequest(GET_CLAIM_NAMESPACE_METHOD, {});\n const grantedNamespace =\n typeof namespaceRes === 'object'\n && namespaceRes !== null\n && 'grantedServiceIdNamespace' in namespaceRes\n && typeof (namespaceRes as { grantedServiceIdNamespace?: unknown; }).grantedServiceIdNamespace === 'string'\n ? (namespaceRes as { grantedServiceIdNamespace: string; }).grantedServiceIdNamespace\n : '';\n\n if (_isServiceIdUnder(serviceId, grantedNamespace)) {\n await local.channel.sendRequest(CLAIM_METHOD, { serviceId });\n return;\n }\n\n const hubIdRes = await local.channel.sendRequest(GET_HUB_SERVICE_ID_METHOD, {});\n const hubServiceId =\n typeof hubIdRes === 'object'\n && hubIdRes !== null\n && 'hubServiceId' in hubIdRes\n && typeof (hubIdRes as { hubServiceId?: unknown; }).hubServiceId === 'string'\n ? (hubIdRes as { hubServiceId: string; }).hubServiceId\n : undefined;\n if (!hubServiceId) {\n throw new Error('tunnel: failed to resolve hub service id for out-of-namespace claim');\n }\n\n const registerMethod = `${hubServiceId}::${hubServiceIdRegistryInterface.info.id}::registerServiceId`;\n await local.channel.sendRequest(registerMethod, { requestedPrefix: serviceId });\n}\n\nfunction _isServiceIdUnder(serviceId: string, namespace: string): boolean {\n if (namespace === '') return false;\n return serviceId === namespace || serviceId.startsWith(`${namespace}/`);\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\nasync function _forwardRequest(\n remote: CliConnection,\n call: IncomingCall,\n): Promise<{ result: JsonValue; } | { error: { code: number; message: string; data?: JsonValue; }; }> {\n // Bridge the streaming sub-protocol both ways so long-running / streaming\n // calls forward transparently, not just their final response:\n // - callee → caller progress: relayed via `onStreamMessage` → `call.stream.send`\n // - caller → callee input: relayed via `call.stream.onMessage` → `rc.send`\n // - caller cancellation (disconnect / idle / explicit): via `call.signal` → `rc.cancel`\n // `signerOverride: null` forwards verbatim: the inbound `$hubrpc` envelope\n // (if any) is preserved instead of being re-signed.\n const rc = remote.channel.sendRequestWithStream(call.method, call.params, {\n ctx: { signerOverride: null },\n onStreamMessage: (payload) => { void call.stream.send(payload); },\n });\n call.stream.onMessage((payload) => rc.send(payload));\n const cancelRemote = (): void => rc.cancel((call.signal.reason as Error | undefined)?.message);\n if (call.signal.aborted) {\n cancelRemote();\n } else {\n call.signal.addEventListener('abort', cancelRemote, { once: true });\n }\n try {\n const result = await rc.result;\n return { result };\n } catch (err) {\n if (err instanceof RpcError) {\n return { error: { code: err.code, message: err.message, data: err.data } };\n }\n return {\n error: { code: ErrorCode.internalError, message: (err as Error).message },\n };\n }\n}\n\nfunction _forwardNotification(remote: CliConnection, call: IncomingCall): void {\n void remote.channel\n .sendNotification(call.method, call.params, { ctx: { signerOverride: null } })\n .catch(() => { /* notifications are fire-and-forget */ });\n}","import {\n ErrorCode,\n type IncomingCall,\n type IRequestHandler,\n type JsonValue,\n} from \"@hediet/linkrpc\";\nimport type { CliConnection } from \"@hediet/linkrpc-client\";\nimport type { StaticHubSchema } from \"../staticHubSchema\";\nimport { StaticHubReflection } from \"./staticHubReflection\";\nimport { createForwardingHandler } from \"./tunnel\";\n\nexport const BROKER_INTERFACE_ID = \"hubrpc.connectionBroker\";\nexport const BROKER_STATUS_METHOD = `${BROKER_INTERFACE_ID}::status`;\nexport const BROKER_READ_NOTIFICATIONS_METHOD = `${BROKER_INTERFACE_ID}::readNotifications`;\nexport const BROKER_DISCONNECT_METHOD = `${BROKER_INTERFACE_ID}::disconnect`;\n\nexport interface ConnectionBrokerOptions {\n readonly id: string;\n readonly remoteEndpoint: string;\n readonly mode: \"linkrpc\" | \"raw\";\n readonly startedAt: number;\n readonly timeoutMs: number;\n readonly ttlMs: number;\n readonly notificationLimit?: number;\n readonly now?: () => number;\n readonly onStop?: (reason: BrokerStopReason) => void;\n readonly staticHubSchema?: StaticHubSchema;\n}\n\nexport type BrokerStopReason = \"disconnect\" | \"timeout\" | \"ttl\" | \"disposed\";\n\nexport interface BufferedNotification {\n readonly sequence: number;\n readonly receivedAt: number;\n readonly method: string;\n readonly params?: JsonValue;\n}\n\ninterface NotificationReadResult {\n readonly notifications: readonly BufferedNotification[];\n readonly next: number;\n readonly droppedBefore: number;\n}\n\ninterface NotificationWaiter {\n readonly after: number;\n readonly resolve: (result: NotificationReadResult) => void;\n readonly timer: ReturnType<typeof setTimeout>;\n readonly signal: AbortSignal;\n readonly onAbort: () => void;\n}\n\nexport class ConnectionBroker {\n private readonly _now: () => number;\n private readonly _notificationLimit: number;\n private readonly _notifications: BufferedNotification[] = [];\n private readonly _waiters = new Set<NotificationWaiter>();\n private readonly _remoteForwarder: IRequestHandler;\n private readonly _staticReflection: StaticHubReflection | undefined;\n private readonly _startedAt: number;\n private _nextNotificationSequence = 1;\n private readonly _locals = new Set<CliConnection>();\n private _timeoutTimer: ReturnType<typeof setTimeout> | undefined;\n private _ttlTimer: ReturnType<typeof setTimeout> | undefined;\n private _lastActivityAt: number;\n private _resolveStopped!: (reason: BrokerStopReason) => void;\n private _disposed = false;\n\n public readonly stopped = new Promise<BrokerStopReason>((resolve) => {\n this._resolveStopped = resolve;\n });\n public stoppedReason: BrokerStopReason | undefined;\n\n constructor(\n private readonly _remote: CliConnection,\n private readonly _options: ConnectionBrokerOptions,\n ) {\n this._now = _options.now ?? Date.now;\n this._notificationLimit = _options.notificationLimit ?? 1_000;\n this._startedAt = _options.startedAt;\n this._lastActivityAt = _options.startedAt;\n this._remoteForwarder = createForwardingHandler(_remote);\n this._staticReflection = _options.staticHubSchema === undefined\n ? undefined\n : new StaticHubReflection(_options.staticHubSchema);\n this._remote.setRequestHandler({\n handleRequest: (call) => this._handleRemoteRequest(call),\n handleNotification: (call) => this._bufferNotification(call),\n });\n this._resetTimeout();\n this._ttlTimer = setTimeout(\n () => this._stop(\"ttl\"),\n Math.max(0, this._options.ttlMs - (this._now() - this._startedAt)),\n );\n this._ttlTimer.unref?.();\n }\n\n public attach(local: CliConnection): void {\n if (this._disposed) {\n throw new Error(\"connection broker is stopped\");\n }\n this._locals.add(local);\n local.setRequestHandler({\n handleRequest: (call) => this._handleLocalRequest(call),\n handleNotification: (call) => this._handleLocalNotification(call),\n });\n this.recordActivity();\n }\n\n public detach(local: CliConnection): void {\n if (!this._locals.delete(local)) return;\n local.setRequestHandler(undefined);\n }\n\n public recordActivity(): void {\n if (this._disposed) return;\n this._lastActivityAt = this._now();\n this._resetTimeout();\n }\n\n public dispose(): void {\n this._stop(\"disposed\");\n }\n\n private async _handleLocalRequest(call: IncomingCall) {\n this.recordActivity();\n switch (call.method) {\n case BROKER_STATUS_METHOD:\n return { result: this._status() as unknown as JsonValue };\n case BROKER_READ_NOTIFICATIONS_METHOD:\n return {\n result: await this._readNotifications(call.params, call.signal) as unknown as JsonValue,\n };\n case BROKER_DISCONNECT_METHOD:\n setTimeout(() => this._stop(\"disconnect\"), 0);\n return { result: { disconnected: true } };\n default:\n if (call.method.startsWith(`${BROKER_INTERFACE_ID}::`)) {\n return {\n error: {\n code: ErrorCode.methodNotFound,\n message: `Unknown connection broker method: ${call.method}`,\n },\n };\n }\n const reflected = this._staticReflection?.tryHandleRequest(call);\n if (reflected !== undefined) {\n return reflected;\n }\n return this._remoteForwarder.handleRequest(call);\n }\n }\n\n private _handleLocalNotification(call: IncomingCall): void {\n this.recordActivity();\n if (call.method.startsWith(`${BROKER_INTERFACE_ID}::`)) {\n return;\n }\n this._remoteForwarder.handleNotification(call);\n }\n\n private _handleRemoteRequest(call: IncomingCall) {\n this.recordActivity();\n if (this._locals.size !== 1) {\n return Promise.resolve({\n error: {\n code: ErrorCode.peerDisconnected,\n message: this._locals.size === 0\n ? \"No local broker client is attached\"\n : \"Cannot route a reverse request while multiple local broker clients are attached\",\n },\n });\n }\n const local = this._locals.values().next().value!;\n return createForwardingHandler(local).handleRequest(call);\n }\n\n private _bufferNotification(call: IncomingCall): void {\n this.recordActivity();\n const notification: BufferedNotification = {\n sequence: this._nextNotificationSequence++,\n receivedAt: this._now(),\n method: call.method,\n ...(call.params === undefined ? {} : { params: call.params }),\n };\n this._notifications.push(notification);\n if (this._notifications.length > this._notificationLimit) {\n this._notifications.splice(0, this._notifications.length - this._notificationLimit);\n }\n this._settleReadyWaiters();\n }\n\n private _status(): JsonValue {\n return {\n id: this._options.id,\n mode: this._options.mode,\n remoteEndpoint: this._options.remoteEndpoint,\n startedAt: this._startedAt,\n lastActivityAt: this._lastActivityAt,\n timeoutMs: this._options.timeoutMs,\n ttlMs: this._options.ttlMs,\n notificationCount: this._notifications.length,\n nextNotificationSequence: this._nextNotificationSequence,\n localClientCount: this._locals.size,\n };\n }\n\n private _readNotifications(\n params: JsonValue | undefined,\n signal: AbortSignal,\n ): Promise<NotificationReadResult> {\n const parsed = parseReadParams(params);\n const immediate = this._collectNotifications(parsed.after);\n if (immediate.notifications.length > 0 || parsed.waitMs === 0) {\n return Promise.resolve(immediate);\n }\n return new Promise<NotificationReadResult>((resolve) => {\n const waiter: NotificationWaiter = {\n after: parsed.after,\n resolve,\n timer: setTimeout(() => this._settleWaiter(waiter), parsed.waitMs),\n signal,\n onAbort: () => this._settleWaiter(waiter),\n };\n waiter.timer.unref?.();\n signal.addEventListener(\"abort\", waiter.onAbort, { once: true });\n this._waiters.add(waiter);\n });\n }\n\n private _collectNotifications(after: number): NotificationReadResult {\n const notifications = this._notifications.filter((item) => item.sequence > after);\n const next = notifications.at(-1)?.sequence ?? after;\n return {\n notifications,\n next,\n droppedBefore: this._notifications[0]?.sequence ?? this._nextNotificationSequence,\n };\n }\n\n private _settleReadyWaiters(): void {\n for (const waiter of [...this._waiters]) {\n if (this._notifications.some((item) => item.sequence > waiter.after)) {\n this._settleWaiter(waiter);\n }\n }\n }\n\n private _settleWaiter(waiter: NotificationWaiter): void {\n if (!this._waiters.delete(waiter)) return;\n clearTimeout(waiter.timer);\n waiter.signal.removeEventListener(\"abort\", waiter.onAbort);\n waiter.resolve(this._collectNotifications(waiter.after));\n }\n\n private _resetTimeout(): void {\n if (this._timeoutTimer !== undefined) {\n clearTimeout(this._timeoutTimer);\n }\n this._timeoutTimer = setTimeout(() => this._stop(\"timeout\"), this._options.timeoutMs);\n this._timeoutTimer.unref?.();\n }\n\n private _stop(reason: BrokerStopReason): void {\n if (this._disposed) return;\n this._disposed = true;\n this.stoppedReason = reason;\n if (this._timeoutTimer !== undefined) clearTimeout(this._timeoutTimer);\n if (this._ttlTimer !== undefined) clearTimeout(this._ttlTimer);\n for (const waiter of [...this._waiters]) {\n this._settleWaiter(waiter);\n }\n for (const local of this._locals) {\n local.close();\n }\n this._locals.clear();\n this._remote.close();\n this._resolveStopped(reason);\n this._options.onStop?.(reason);\n }\n}\n\nfunction parseReadParams(params: JsonValue | undefined): { after: number; waitMs: number; } {\n if (params === undefined) return { after: 0, waitMs: 0 };\n if (typeof params !== \"object\" || params === null || Array.isArray(params)) {\n throw new Error(\"readNotifications params must be an object\");\n }\n const after = \"after\" in params ? params.after : 0;\n const waitMs = \"waitMs\" in params ? params.waitMs : 0;\n if (typeof after !== \"number\" || !Number.isSafeInteger(after) || after < 0) {\n throw new Error(\"readNotifications after must be a non-negative integer\");\n }\n if (\n typeof waitMs !== \"number\"\n || !Number.isSafeInteger(waitMs)\n || waitMs < 0\n || waitMs > 30_000\n ) {\n throw new Error(\"readNotifications waitMs must be an integer between 0 and 30000\");\n }\n return { after, waitMs };\n}\n","import type { JsonValue } from \"@hediet/linkrpc\";\nimport type { CliChannel } from \"@hediet/linkrpc-client\";\nimport {\n BROKER_DISCONNECT_METHOD,\n BROKER_READ_NOTIFICATIONS_METHOD,\n BROKER_STATUS_METHOD,\n type BufferedNotification,\n} from \"./connectionBroker\";\n\nexport interface ReadBrokerNotificationsOptions {\n readonly after?: number;\n readonly waitMs?: number;\n}\n\nexport interface BrokerNotificationBatch {\n readonly notifications: readonly BufferedNotification[];\n readonly next: number;\n readonly droppedBefore: number;\n}\n\nexport function getBrokerStatus(channel: CliChannel): Promise<JsonValue> {\n return channel.sendRequest(BROKER_STATUS_METHOD, {});\n}\n\nexport async function disconnectBroker(channel: CliChannel): Promise<void> {\n await channel.sendRequest(BROKER_DISCONNECT_METHOD, {});\n}\n\nexport async function readBrokerNotifications(\n channel: CliChannel,\n options: ReadBrokerNotificationsOptions = {},\n): Promise<BrokerNotificationBatch> {\n const value = await channel.sendRequest(BROKER_READ_NOTIFICATIONS_METHOD, {\n after: options.after ?? 0,\n waitMs: options.waitMs ?? 0,\n });\n if (!isRecord(value) || !Array.isArray(value.notifications)) {\n throw new Error(\"connection broker returned an invalid notification batch\");\n }\n const next = value.next;\n const droppedBefore = value.droppedBefore;\n if (\n typeof next !== \"number\"\n || !Number.isSafeInteger(next)\n || typeof droppedBefore !== \"number\"\n || !Number.isSafeInteger(droppedBefore)\n ) {\n throw new Error(\"connection broker returned invalid notification sequence metadata\");\n }\n const notifications = value.notifications.map(parseNotification);\n return { notifications, next, droppedBefore };\n}\n\nfunction parseNotification(value: unknown): BufferedNotification {\n if (\n !isRecord(value)\n || typeof value.sequence !== \"number\"\n || !Number.isSafeInteger(value.sequence)\n || typeof value.receivedAt !== \"number\"\n || !Number.isSafeInteger(value.receivedAt)\n || typeof value.method !== \"string\"\n ) {\n throw new Error(\"connection broker returned an invalid notification\");\n }\n return {\n sequence: value.sequence,\n receivedAt: value.receivedAt,\n method: value.method,\n ...(\"params\" in value ? { params: value.params as JsonValue } : {}),\n };\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\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\";\nimport type { StaticHubSchema } from \"../staticHubSchema\";\nimport { ConnectionBroker, type BrokerStopReason } from \"./connectionBroker\";\n\nexport interface RunConnectionBrokerOptions {\n readonly remote: ResolvedEndpoint;\n readonly timeoutMs: number;\n readonly ttlMs: number;\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: number;\n readonly ttlMs: number;\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 ?? 15_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 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(\"exit\", onExit);\n };\n stdout.on(\"data\", onData);\n child.once(\"error\", onError);\n child.once(\"exit\", onExit);\n });\n}\n","const DURATION_PATTERN = /^(\\d+)(ms|s|m|min|h)$/;\n\nconst UNIT_MS: Readonly<Record<string, number>> = {\n ms: 1,\n s: 1_000,\n m: 60_000,\n min: 60_000,\n h: 3_600_000,\n};\n\nexport function parseDuration(value: string): number {\n const match = DURATION_PATTERN.exec(value.trim());\n if (match === null) {\n throw new Error(`invalid duration '${value}' (expected e.g. 250ms, 30s, 5min, or 2h)`);\n }\n const amount = Number.parseInt(match[1], 10);\n const durationMs = amount * UNIT_MS[match[2]];\n if (!Number.isSafeInteger(durationMs) || durationMs <= 0) {\n throw new Error(`invalid duration '${value}' (must be greater than zero)`);\n }\n return durationMs;\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\";\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';\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\";\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 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 } from \"@hediet/linkrpc-client\";\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 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, { maxDepth: opts.maxDepth });\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(channel, all, (listing) => listing.discoveredFrom)\n : all;\n if (format === \"json\") return formatJson(legacyOutput ? output : state);\n return renderTree(output, opts.interfaceId);\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 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\nasync function addMembers<T extends ServiceListing>(\n channel: CliChannel,\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 = fetchSchema(\n channel,\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\"> = {},\n): Promise<HubDump> {\n const explorer = new HubDirectoryExplorer(channel, {\n maxDepth: opts.maxDepth ?? DEFAULT_WALK_DEPTH,\n });\n await explorer.explore();\n const cache = await fetchDumpSchemas(channel, 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 channel: CliChannel,\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 fetchSchema(\n channel,\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 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(channel, 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\";\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\";\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';\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\";\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';\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';\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';\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 { jcsCanonicalize, type Pattern, type Permission } from '@hediet/linkrpc';\nimport type { HubAccessManifestRequest } from '@hediet/linkrpc/hub/common';\nimport type { AccessDirectPermission } from '@hediet/linkrpc-hub/hub/server';\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 LinkRpcConnection,\n jcsCanonicalize,\n type Permission,\n type Principal,\n type SignedCapability,\n TransportPair,\n type SigningCallCtx,\n type SigningIdentity,\n} from '@hediet/linkrpc';\nimport {\n HubDirectoryExplorer,\n hubAccessManifestInterface,\n type HubAccessManifestDecision,\n type HubAccessManifestRequest,\n type IHubAccessManifest,\n} from '@hediet/linkrpc/hub/common';\nimport {\n AggregatingHubAccessManifest,\n ApproveClient,\n buildSlotPermissions,\n registerAggregatingManifest,\n runManifestApprover,\n toSignedPermissions,\n type AggregatorSource,\n type ConsentPrompt,\n} from '@hediet/linkrpc-hub';\nimport {\n CapabilityProposalIssuer,\n candidatesForSlot,\n durationToExp,\n type AccessDirectPermission,\n type AccessDurationName,\n type AccessSlotRequest,\n type DirectoryEntry,\n} from '@hediet/linkrpc-hub/hub/server';\nimport { autorun } from '@vscode/observables';\nimport { createApprovalPresentation } from '../approvalPresentation';\nimport { formatJson } from '../output';\n\n/**\n * The only authority an approval command needs for inspecting and updating\n * manifests across a federated Hub.\n */\nexport const approvalCommandPermissions: readonly Permission[] = [\n {\n target: {\n serviceId: { prefix: '' },\n interfaceId: { exact: 'hubAccessManifest' },\n members: [{ prefix: '' }],\n },\n canInvoke: true,\n },\n {\n target: {\n serviceId: { prefix: '' },\n interfaceId: { exact: 'hubrpc.directory' },\n members: [{ prefix: '' }],\n },\n canInvoke: true,\n },\n];\n\nconst approvalCommandPermissionsJson = jcsCanonicalize(approvalCommandPermissions);\n\n/**\n * Installs the root identity's narrowly scoped self-capability used by the\n * approval scanner. Reusing the non-expiring exact grant prevents repeated\n * commands from growing the principal's durable capability bag.\n */\nexport async function bootstrapApprovalCommandCapability(\n principal: Principal,\n): Promise<SignedCapability> {\n const existing = principal.capBag.capabilities.find((capability) =>\n capability.issuer === principal.id\n && capability.audience === principal.id\n && capability.expiresAtMs === undefined\n && capability.parentHash === undefined\n && jcsCanonicalize(capability.permissions) === approvalCommandPermissionsJson\n );\n if (existing) {\n return existing;\n }\n\n const issuer = new CapabilityProposalIssuer(principal.identity);\n const capability = await issuer.mint({\n audience: principal.id,\n permissions: approvalCommandPermissions,\n });\n await principal.capBag.add(capability);\n return capability;\n}\n\nconst MANIFEST_INTERFACE_ID = hubAccessManifestInterface.info.id;\nconst AGGREGATE_SERVICE_ID = 'linkrpc-cli.approvals';\nconst EXTERNAL_ID_PREFIX = 'ar1_';\n\nexport interface PendingApprovalRequest {\n readonly id: string;\n readonly request: HubAccessManifestRequest;\n /** Manifest revision containing the request rendered to the operator. */\n readonly revision: number;\n /** Service ID of the hubAccessManifest that supplied this request. */\n readonly sourceServiceId?: string;\n}\n\nexport type ApprovalDecisionOutcome = 'applied' | 'still-pending';\n\nexport interface PreparedApproval {\n readonly pending: PendingApprovalRequest;\n /** Exact permissions that will be signed, including one-shot call binding. */\n readonly permissions: readonly Permission[];\n readonly resolvedSlot?: {\n readonly serviceId: string;\n readonly satisfiedInterfaces: readonly string[];\n };\n}\n\nexport interface ApprovalSnapshot {\n readonly state: 'connecting' | 'live' | 'stale';\n readonly requests: readonly PendingApprovalRequest[];\n readonly error?: string;\n}\n\nexport interface ApprovalSubscription {\n dispose(): void;\n}\n\nexport interface ApprovalCommandClientOptions {\n readonly manifest: IHubAccessManifest;\n readonly identity: SigningIdentity;\n readonly fetchDirectory?: () => Promise<readonly DirectoryEntry[]>;\n readonly log?: (line: string) => void;\n readonly dispose?: () => void;\n readonly timeoutMs?: number;\n}\n\n/**\n * CLI-facing approval operations over the hub's shared manifest frontend.\n * The underlying {@link ApproveClient} remains authoritative for snapshots and\n * acknowledgement. One-shot commands mint before calling its acknowledged\n * decision path; {@link runManifestApprover} drives the interactive UI.\n */\nexport class ApprovalCommandClient {\n private readonly _principalId: string;\n private readonly _manifest: IHubAccessManifest;\n private readonly _client: ApproveClient;\n private readonly _issuer: CapabilityProposalIssuer;\n private readonly _fetchDirectory: ApprovalCommandClientOptions['fetchDirectory'];\n private readonly _log: (line: string) => void;\n private readonly _disposeExtra: (() => void) | undefined;\n private _lastClientError: string | undefined;\n private _disposed = false;\n\n constructor(options: ApprovalCommandClientOptions) {\n this._principalId = options.identity.publicSigningIdentity.principal;\n this._manifest = options.manifest;\n this._issuer = new CapabilityProposalIssuer(options.identity);\n this._fetchDirectory = options.fetchDirectory;\n this._log = options.log ?? (() => { /* quiet */ });\n this._disposeExtra = options.dispose;\n this._client = new ApproveClient({\n manifest: this._manifest,\n ownPrincipalId: this._principalId,\n timeoutMs: options.timeoutMs,\n log: (line) => {\n this._lastClientError = line;\n this._log(line);\n },\n });\n }\n\n public get principalId(): string {\n return this._principalId;\n }\n\n public async requests(): Promise<readonly PendingApprovalRequest[]> {\n return this._toPendingRequests(await this._currentRequests());\n }\n\n /**\n * Subscribe to the authoritative manifest snapshot. The callback is invoked\n * immediately and whenever the watch reconnects or the request set changes.\n */\n public watch(listener: (snapshot: ApprovalSnapshot) => void): ApprovalSubscription {\n return autorun((reader) => {\n const state = this._client.state.read(reader);\n const requests = this._toPendingRequests(this._client.requests.read(reader));\n listener({\n state,\n requests,\n ...(state === 'stale' && this._lastClientError !== undefined\n ? { error: this._lastClientError }\n : {}),\n });\n });\n }\n\n /** Force an immediate manifest reconciliation. */\n public async refresh(): Promise<void> {\n await this._currentRequests();\n }\n\n public async deny(\n externalId: string,\n reason?: string,\n expected?: PendingApprovalRequest,\n ): Promise<ApprovalDecisionOutcome> {\n const internalId = decodeApprovalRequestId(externalId);\n const pending = await this._requirePending(internalId, externalId);\n if (expected !== undefined) this._requireUnchanged(pending, expected);\n const result = await this._client.decide(internalId, {\n status: 'denied',\n ...(reason !== undefined ? { reason } : {}),\n });\n if (result === 'gone') {\n throw new Error(`approval request '${externalId}' is no longer pending`);\n }\n return result;\n }\n\n public async approve(externalId: string): Promise<ApprovalDecisionOutcome> {\n return this.approvePrepared(await this.prepareApproval(externalId));\n }\n\n /**\n * Resolve the exact authority that an approval will mint. Interactive\n * surfaces render this result before asking for confirmation.\n */\n public async prepareApproval(externalId: string): Promise<PreparedApproval> {\n const internalId = decodeApprovalRequestId(externalId);\n const pending = await this._requirePending(internalId, externalId);\n const resolved = await this._resolveRequest(pending.request);\n if ('denied' in resolved) {\n throw new Error(`approval request '${externalId}' cannot be granted: ${resolved.denied}`);\n }\n const sourceServiceId = approvalRequestSource(internalId);\n return {\n pending: {\n id: externalId,\n request: pending.request,\n revision: pending.revision,\n ...(sourceServiceId === undefined ? {} : { sourceServiceId }),\n },\n permissions: await toSignedPermissions(\n resolved.permissions,\n pending.request.consumer.principal,\n pending.request.duration,\n ),\n ...(resolved.resolvedSlot === undefined ? {} : { resolvedSlot: resolved.resolvedSlot }),\n };\n }\n\n /** Approve only if the request is still exactly the one that was reviewed. */\n public async approvePrepared(prepared: PreparedApproval): Promise<ApprovalDecisionOutcome> {\n const externalId = prepared.pending.id;\n const internalId = decodeApprovalRequestId(externalId);\n const pending = await this._requirePending(internalId, externalId);\n this._requireUnchanged(pending, prepared.pending);\n const decision = await this._grantDecision(prepared);\n // Await the authoritative post-write snapshot before the CLI prints success.\n const result = await this._client.decide(internalId, decision);\n if (result === 'gone') {\n throw new Error(`approval request '${externalId}' is no longer pending`);\n }\n if (decision.status !== 'granted') {\n throw new Error(\n `approval request '${externalId}' could not be granted`\n + (decision.reason !== undefined ? `: ${decision.reason}` : ''),\n );\n }\n return result;\n }\n\n public async runInteractive(signal: AbortSignal, prompt?: ConsentPrompt): Promise<void> {\n await this._currentRequests();\n const approver = runManifestApprover({\n manifest: this._manifest,\n issuer: this._issuer,\n ownPrincipalId: this._principalId,\n ...(this._fetchDirectory !== undefined ? { fetchDirectory: this._fetchDirectory } : {}),\n ...(prompt !== undefined ? { prompt } : {}),\n log: this._log,\n });\n try {\n await waitForAbort(signal);\n } finally {\n approver.dispose();\n }\n }\n\n public dispose(): void {\n if (this._disposed) return;\n this._disposed = true;\n this._client.dispose();\n this._disposeExtra?.();\n }\n\n private async _currentRequests() {\n await this._client.refresh();\n if (this._client.state.get() === 'stale') {\n throw new Error(this._lastClientError ?? 'could not read pending approval requests');\n }\n return this._client.requests.get();\n }\n\n private _toPendingRequests(\n requests: readonly {\n readonly id: string;\n readonly request: HubAccessManifestRequest;\n readonly revision: number;\n }[],\n ): readonly PendingApprovalRequest[] {\n return requests\n .map(({ id, request, revision }) => {\n const sourceServiceId = approvalRequestSource(id);\n return {\n id: encodeApprovalRequestId(id),\n request,\n revision,\n ...(sourceServiceId === undefined ? {} : { sourceServiceId }),\n };\n })\n .sort((a, b) => a.id.localeCompare(b.id));\n }\n\n private async _requirePending(\n internalId: string,\n externalId: string,\n ): Promise<{ readonly id: string; readonly request: HubAccessManifestRequest; readonly revision: number; }> {\n const requests = await this._currentRequests();\n const pending = requests.find((request) => request.id === internalId);\n if (!pending) {\n throw new Error(\n `approval request '${externalId}' is not pending for principal '${this._principalId}'`,\n );\n }\n return pending;\n }\n\n private _requireUnchanged(\n actual: { readonly request: HubAccessManifestRequest; readonly revision: number; },\n expected: PendingApprovalRequest,\n ): void {\n if (jcsCanonicalize(actual.request) !== jcsCanonicalize(expected.request)) {\n throw new Error(\n `approval request '${expected.id}' changed after it was reviewed; review it again`,\n );\n }\n }\n\n private async _resolveRequest(\n request: HubAccessManifestRequest,\n ): Promise<\n | {\n readonly permissions: readonly AccessDirectPermission[];\n readonly resolvedSlot?: {\n readonly serviceId: string;\n readonly satisfiedInterfaces: readonly string[];\n };\n }\n | { readonly denied: string; }\n > {\n let permissions: readonly AccessDirectPermission[];\n let resolvedSlot:\n | { readonly serviceId: string; readonly satisfiedInterfaces: readonly string[]; }\n | undefined;\n if (request.kind === 'direct') {\n permissions = request.permissions as readonly AccessDirectPermission[];\n } else {\n if (this._fetchDirectory === undefined) {\n return { denied: 'no directory available to resolve discover candidates' };\n }\n const slot: AccessSlotRequest = {\n interfaces: request.interfaces.map((item) => ({\n id: item.id,\n required: item.required !== false,\n ...(item.hash !== undefined ? { hash: item.hash } : {}),\n })),\n members: request.members.map((item) => ({\n interfaceId: item.interfaceId,\n member: item.member,\n required: item.required !== false,\n })),\n };\n const candidate = candidatesForSlot(slot, await this._fetchDirectory())[0];\n if (!candidate) {\n return { denied: 'no candidate service satisfies the requested interfaces' };\n }\n const present = new Set(candidate.satisfiedInterfaces.map((item) => item.id));\n permissions = buildSlotPermissions(\n candidate.serviceId,\n slot.interfaces,\n slot.members,\n present,\n ) as AccessDirectPermission[];\n resolvedSlot = {\n serviceId: candidate.serviceId,\n satisfiedInterfaces: candidate.satisfiedInterfaces.map((item) => item.id),\n };\n }\n return {\n permissions,\n ...(resolvedSlot === undefined ? {} : { resolvedSlot }),\n };\n }\n\n private async _grantDecision(prepared: PreparedApproval): Promise<HubAccessManifestDecision> {\n const request = prepared.pending.request;\n const capability = await this._issuer.mint({\n audience: request.consumer.principal,\n permissions: prepared.permissions,\n expiresAtMs: durationToExp(request.duration as AccessDurationName | undefined),\n });\n return {\n status: 'granted',\n granted: prepared.resolvedSlot === undefined\n ? { kind: 'direct', capabilities: [capability] }\n : {\n kind: 'discover',\n serviceId: prepared.resolvedSlot.serviceId,\n satisfiedInterfaces: [...prepared.resolvedSlot.satisfiedInterfaces],\n capabilities: [capability],\n },\n };\n }\n}\n\n/**\n * Discover every manifest in the connected hub and expose it through one\n * validated, namespaced aggregate. This is the same discovery/validation path\n * used by the hub's approval UI.\n */\nexport function createHubApprovalCommandClient(\n connection: LinkRpcConnection<unknown, SigningCallCtx>,\n identity: SigningIdentity,\n log?: (line: string) => void,\n): ApprovalCommandClient {\n const hubConnection = connection as unknown as LinkRpcConnection;\n const explorer = new HubDirectoryExplorer(hubConnection.channel);\n const sourceCache = new Map<string, AggregatorSource>();\n let directoryChanged: (() => void) | undefined;\n const watchStarted = explorer.watch(() => directoryChanged?.());\n const fetchDirectory = async (): Promise<readonly DirectoryEntry[]> => {\n await watchStarted;\n return explorer.result.listings.map((entry) => ({\n serviceId: entry.serviceId,\n interfaceId: entry.interfaceId,\n hash: entry.hash,\n ...(entry.serviceDescription === undefined\n ? {}\n : { serviceDescription: entry.serviceDescription }),\n ...(entry.rootPrincipalSets === undefined\n ? {}\n : { rootPrincipalSets: entry.rootPrincipalSets }),\n }));\n };\n const resolveSources = async () => {\n const directory = await fetchDirectory();\n const serviceIds = [...new Set(\n directory\n .filter((entry) => entry.interfaceId === MANIFEST_INTERFACE_ID)\n .map((entry) => entry.serviceId),\n )].sort();\n log?.(\n `approval: discovered ${serviceIds.length} manifest source`\n + `${serviceIds.length === 1 ? '' : 's'}`\n + `${serviceIds.length > 0 ? `: ${serviceIds.join(', ')}` : ''}`,\n );\n const active = new Set(serviceIds);\n for (const serviceId of sourceCache.keys()) {\n if (!active.has(serviceId)) sourceCache.delete(serviceId);\n }\n return serviceIds.map((serviceId) => {\n const cached = sourceCache.get(serviceId);\n if (cached !== undefined) return cached;\n const manifest = serviceId === ''\n ? connection.get(hubAccessManifestInterface)\n : connection.service(serviceId).get(hubAccessManifestInterface);\n const source: AggregatorSource = {\n tag: serviceId,\n manifest: withApprovalSourceLogging(manifest, serviceId, log),\n preserveOrigin: false,\n };\n sourceCache.set(serviceId, source);\n return source;\n });\n };\n\n const aggregate = new AggregatingHubAccessManifest({\n resolveSources,\n watchSources: (onChange) => {\n directoryChanged = onChange;\n return () => {\n if (directoryChanged === onChange) directoryChanged = undefined;\n };\n },\n log,\n });\n const pair = new TransportPair();\n const aggregateServer = LinkRpcConnection.fromTransport(pair.a);\n const aggregateClient = LinkRpcConnection.fromTransport(pair.b);\n registerAggregatingManifest(aggregateServer, aggregate, { serviceId: AGGREGATE_SERVICE_ID });\n\n return new ApprovalCommandClient({\n manifest: aggregateClient.service(AGGREGATE_SERVICE_ID).get(hubAccessManifestInterface),\n identity,\n fetchDirectory,\n log,\n dispose: () => {\n aggregate.dispose();\n void watchStarted.then((stop) => stop(), () => undefined);\n explorer.dispose();\n aggregateClient.close();\n aggregateServer.close();\n },\n });\n}\n\nfunction withApprovalSourceLogging(\n manifest: IHubAccessManifest,\n serviceId: string,\n log: ((line: string) => void) | undefined,\n): IHubAccessManifest {\n if (!log) return manifest;\n const getDesired = manifest.getDesired.bind(manifest);\n return new Proxy(manifest, {\n get: (target, property, receiver) => {\n if (property !== 'getDesired') return Reflect.get(target, property, receiver);\n return async (...args: Parameters<typeof getDesired>) => {\n const result = await getDesired(...args);\n const count = Object.keys(result.requested).length;\n log(\n `approval: source '${serviceId || '<root>'}' has ${count} pending request`\n + (count === 1 ? '' : 's'),\n );\n return result;\n };\n },\n });\n}\n\nexport function encodeApprovalRequestId(internalId: string): string {\n if (internalId.length === 0) throw new Error('cannot encode an empty approval request id');\n return `${EXTERNAL_ID_PREFIX}${Buffer.from(internalId, 'utf8').toString('base64url')}`;\n}\n\nexport function decodeApprovalRequestId(externalId: string): string {\n if (!new RegExp(`^${EXTERNAL_ID_PREFIX}[A-Za-z0-9_-]+$`).test(externalId)) {\n throw new Error(`invalid approval request id '${externalId}'`);\n }\n\n const encoded = externalId.slice(EXTERNAL_ID_PREFIX.length);\n const decoded = Buffer.from(encoded, 'base64url').toString('utf8');\n if (decoded.length === 0 || encodeApprovalRequestId(decoded) !== externalId) {\n throw new Error(`invalid approval request id '${externalId}'`);\n }\n return decoded;\n}\n\nfunction approvalRequestSource(internalId: string): string | undefined {\n const separator = internalId.indexOf('\\u0000');\n return separator < 0 ? undefined : internalId.slice(0, separator);\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\nfunction waitForAbort(signal: AbortSignal): Promise<void> {\n if (signal.aborted) return Promise.resolve();\n return new Promise((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }));\n}\n","import type { PrincipalSource, SigningSession } from '@hediet/linkrpc-client';\nimport { formatPrincipalSource } from '@hediet/linkrpc-client';\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 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","import type { CliChannel } from \"@hediet/linkrpc-client\";\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}\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\";\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)).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","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.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 { isGraphRef, standardGraphRuntimeOptions } 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 selector?: string;\n}\n\nexport function createGraphTree(\n root: GraphRef,\n cache: GraphObjectCache,\n expanded: ReadonlySet<string>,\n maxDepth = Number.POSITIVE_INFINITY,\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 return lines;\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\nasync 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 } 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\";\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 ) {\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);\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 }\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 return `${cursor}${\" \".repeat(line.depth)}${line.text}`;\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} from \"@hediet/linkrpc-infra/graph\";\nimport type { DiscoveredListing } from \"@hediet/linkrpc/hub/common\";\nimport type { CliChannel } from \"@hediet/linkrpc-client\";\nimport { GraphTerminal } from \"./inspectGraphTerminal\";\nimport { GraphTimings, type GraphTiming } from \"./inspectGraphTiming\";\nimport {\n GraphLoader,\n GraphObjectCache,\n graphRefKey,\n parseGraphRef,\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}\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 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);\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 } 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 { 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 };\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\";\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({ ...canonical, methods: listing.schema.methods,\n components: listing.schema.components }) !== 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\";\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 } from 'commander';\nimport { LinkRpcConnection, type JsonValue } from '@hediet/linkrpc';\nimport { 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 { executeBatch, parseBatchArgs } from './commands/batch';\nimport {\n disconnectBroker,\n getBrokerStatus,\n readBrokerNotifications,\n} from './commands/connectionBrokerClient';\nimport {\n runConnectionBroker,\n spawnConnectionBroker,\n} from './commands/connectionBrokerProcess';\nimport { parseDuration } 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 } 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 { 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 {\n bootstrapApprovalCommandCapability,\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 type CliConnection,\n type ConnectLogOptions,\n} from '@hediet/linkrpc-client';\nimport { type HubConfig } from '@hediet/linkrpc-client';\nimport { runHub, type RunningHub } from './engine/runHub';\nimport {\n type ResolvedEndpoint,\n resolveTargetEndpoint,\n resolvedEndpointToConfig,\n} from '@hediet/linkrpc-client';\nimport {\n type SigningSession,\n setupSigning,\n requestReflectionAccess,\n requestTopologyAccess,\n} from '@hediet/linkrpc-client';\nimport { logoutCliIdentity } from '@hediet/linkrpc-client';\nimport { MethodRefWithOptHash } from './methodRef';\nimport { renderMethodParamHelp } from './methodHelp';\nimport { rewriteParamShortcuts } from './paramFlags';\nimport { formatPrincipalSource, parsePrincipalSpec, type PrincipalSpec } from '@hediet/linkrpc-client';\nimport { findMethodInSchema } from '@hediet/linkrpc-client';\nimport { fetchSchemaForMethodRef } from './schemaLookup';\nimport {\n loadStaticHubSchema,\n resolveStaticHubSchemaSource,\n} from './staticHubSchema';\nimport {\n ContextStore,\n type ContextReference,\n type ContextValues,\n type ValidationMode,\n formatContextReference,\n} from './contexts';\nimport {\n type CliProfile,\n type ResolvedInvocationContext,\n mutationReference,\n resolveInvocationContext,\n resolveInvocationEndpoint,\n validationDefault,\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 (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(\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(\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 program.hook('preAction', async (_thisCommand, actionCommand) => {\n const commandPath = getCommandPath(actionCommand);\n const allowMissingContext = commandPath === 'context set';\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 allowMissingContext,\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 pendingContextSet = {\n store,\n reference: await mutationReference(store, g_invocation.selected),\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\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 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) => {\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 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 });\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 });\n } catch (e) {\n process.stdout.write(`\\n(Could not fetch method schema: ${(e as Error).message})\\n`);\n }\n };\n\n program\n .command('call [methodRef]')\n .description(\n 'Invoke a request. `<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 await withChannel(endpoint, getPrincipalSpec(), async (channel) => {\n const validation = opts.validate === false\n ? 'off'\n : effectiveValidation(profile);\n const out = await callCommand(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('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>', 'exit after this much transport inactivity')\n .option('--ttl <duration>', 'hard maximum broker lifetime')\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 (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 ?? g_invocation?.values.connectionTimeout ?? '30s';\n const ttl = opts.ttl ?? g_invocation?.values.connectionTtl ?? '5min';\n const notificationLimit = opts.notificationLimit\n ?? g_invocation?.values.notificationLimit\n ?? 1_000;\n const brokerEndpoint = await spawnConnectionBroker({\n remote: needEndpoint(endpoint),\n timeoutMs: parseDuration(timeout),\n ttlMs: parseDuration(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('list')\n .description('List every path, named, and root context in the global store.')\n .action(async () => {\n if (g_contextStore === undefined) throw new Error('context store is unavailable');\n for (const item of await g_contextStore.list()) {\n process.stdout.write(`${formatContextReference(item.reference)}\\n`);\n }\n });\n\n context\n .command('set')\n .description(\n 'Set explicit context-capable flags on the active context; creates a cwd context when none exists.',\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 const target = explicitOption<string>(program, 'context') !== undefined\n ? mutableReference(g_invocation.selected.reference)\n : await mutationReference(g_contextStore, g_invocation.selected);\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('Remove the selected context from the global store.')\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(`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>', '', (value) =>\n parsePositiveInteger(value, '--timeout-ms'))\n .requiredOption('--ttl-ms <milliseconds>', '', (value) =>\n parsePositiveInteger(value, '--ttl-ms'))\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: number;\n ttlMs: number;\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 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 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 '--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 'grantedServiceIdNamespace = <serviceId> 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 .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: {\n targetEndpoint?: string;\n targetEndpointCmd?: string;\n targetEndpointCmdStdio?: string;\n targetEndpointCmdEnv?: Record<string, string>;\n targetEndpointToken?: string;\n targetEndpointCmdCwd?: string;\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 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 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: tunnel requires --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio.\\n',\n );\n process.exit(2);\n }\n const targetEp = targetRes.endpoint;\n // Honor the legacy LINKRPC_REMOTE_ENDPOINT_TOKEN env var as a fallback\n // for token-bearing target URIs.\n const remoteTok = process.env.LINKRPC_REMOTE_ENDPOINT_TOKEN;\n const targetEpWithToken: ResolvedEndpoint =\n remoteTok !== undefined && (targetEp.kind === 'socket' || targetEp.kind === 'ws')\n && targetEp.token === undefined\n ? { ...targetEp, token: remoteTok }\n : targetEp;\n\n const local = await connectEndpoint(localEp, wireLog('source'));\n // Connect straight to the target endpoint — no routing hub. For a\n // spawned cmd-env child we front it with a RootOverlay: its root-form\n // calls (identity::*, hubGrantedServiceId::*, reflection, hubAccess)\n // are served locally while every claimed request the tunnel forwards\n // is relayed to the child through the overlay splitter. This keeps\n // --provision-identity working (identity::* is served) without the\n // 'hub' service id / claim-wait dance a full local hub imposes.\n let remote: CliConnection;\n if (targetEpWithToken.kind === 'cmd-env') {\n remote = await connectViaRootOverlay({\n command: targetEpWithToken.command,\n provisionSlot: targetEpWithToken.provisionSlot,\n env: targetEpWithToken.env,\n ...(targetEpWithToken.cwd !== undefined ? { cwd: targetEpWithToken.cwd } : {}),\n grantedNamespace: serviceId,\n log: wireLog('target'),\n });\n } else {\n remote = await connectEndpoint(targetEpWithToken, wireLog('target'));\n }\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 await tunnelCommand({ serviceId, local, remote, bidi: cmdOpts.bidi });\n } finally {\n remote.close();\n local.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, 'schema');\n copyExplicit(program, opts, result, 'validation');\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): Promise<void> {\n await store.replace(reference, values, { createOnly: true });\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 });\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\nasync function stopConnectionBroker(endpoint: string): Promise<void> {\n const connection = await connectEndpoint(parseEndpointUri(endpoint));\n try {\n await disconnectBroker(connection.channel);\n } finally {\n connection.close();\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\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';\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 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 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 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 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\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').CliChannel) => Promise<void>,\n opts: {\n requestReflectionAccess?: boolean;\n requestTopologyAccess?: { readonly sourceServiceIds?: readonly string[] };\n } = {},\n): Promise<void> {\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 await fn(channel);\n return;\n }\n if (g_invocation?.profile === 'rpc') {\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 });\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);\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 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 bootstrapApprovalCommandCapability(session.principal);\n const connection = new LinkRpcConnection(conn.rpcChannel);\n const client = createHubApprovalCommandClient(\n connection,\n session.principal.identity,\n 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').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 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\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((e: unknown) => {\n process.stderr.write(`linkrpc: ${formatCliError(e)}\\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,SAAgB,cAAc,OAAoC;CAC9D,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAEhC,MAAM,WADO,UAAU,MAAM,aAAa,GAAG,MAAM,IAAI,MAAA,CAClC,KAAK;CAC1B,IAAI,QAAQ,WAAW,GAAG,OAAO,KAAA;CACjC,IAAI;EACA,OAAO,KAAK,MAAM,OAAO;CAC7B,SAAS,GAAG;EACR,MAAM,IAAI,MAAM,2BAA4B,EAAY,QAAQ,EAAE;CACtE;AACJ;AAEA,SAAgB,WAAW,GAAoB;CAC3C,IAAI,MAAM,KAAA,GAAW,OAAO;CAC5B,OAAO,KAAK,UAAU,GAAG,MAAM,CAAC;AACpC;;;ACSA,MAAM,iBAAiB;AAEvB,SAAS,mBAAmB,IAAqB;CAC7C,OAAO,GAAG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