@hediet/linkrpc-cli 0.0.3-next.20261024.1 → 0.0.3-next.20261025.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runComplete-1DjMsU_0.js","names":["path","fs","spawnCommand","fetchSchema","path","fs","isRecord","path","fs","path"],"sources":["../../src/mcpForward.interface.ts","../../src/methodRef.ts","../../src/paramParsing.ts","../../src/validation.ts","../../../../packages-private/linkrpc-client-internal/src/localHub.ts","../../../../packages-private/linkrpc-client-internal/src/endpoint.ts","../../../../packages-private/linkrpc-client-internal/src/connect.ts","../../../../packages-private/linkrpc-client-internal/src/principal.ts","../../../../packages-private/linkrpc-client-internal/src/identity.ts","../../../../packages-private/linkrpc-client-internal/src/reflection.ts","../../../../packages-private/linkrpc-client-internal/src/hubSigning.ts","../../src/completions/directorySource.ts","../../src/completions/parse.ts","../../src/completions/tree.ts","../../src/completions/resolve.ts","../../src/cliInvocation.ts","../../src/completions/complete.ts","../../src/completions/cache.ts","../../src/duration.ts","../../src/commands/staticHubReflection.ts","../../src/commands/tunnel.ts","../../src/commands/connectionBroker.ts","../../src/commands/connectionBrokerClient.ts","../../src/contexts.ts","../../../linkrpc-hub-daemon/src/discovery.ts","../../../linkrpc-hub-daemon/src/callLog/callRecord.ts","../../../linkrpc-hub-daemon/src/managementInterface.ts","../../../linkrpc-hub-daemon/src/paths.ts","../../../linkrpc-hub-daemon/src/endpointInterface.ts","../../../linkrpc-hub-daemon/src/client.ts","../../src/localEndpoint.ts","../../src/invocationContext.ts","../../src/staticHubSchema.ts","../../src/completions/runComplete.ts"],"sourcesContent":["import { defineInterface, requestType } from \"@hediet/linkrpc\";\nimport { z } from \"zod\";\n\n/**\n * Transparent MCP tunnel.\n *\n * A single long-lived {@link mcpForwardInterface.connect} request opens one MCP\n * session \"leg\". The MCP JSON-RPC byte stream rides the linkrpc `$stream` duplex\n * correlated to that request — **no MCP method is modeled here**. Payloads are\n * opaque JSON-RPC messages, exactly as MCP emits them, so the forwarder that\n * serves this interface stays dumb: it shuttles frames between a child process'\n * stdio and the stream without ever parsing them.\n *\n * Why one duplex stream instead of request/response per MCP message: MCP is\n * bidirectional and asynchronous (server-initiated `notifications/.../\n * list_changed`, sampling requests). `$stream` already provides an ordered,\n * request-correlated, cancellable duplex that the runtime keeps alive with\n * periodic pings, so one stream == one MCP session leg.\n *\n * Lifecycle:\n * - The consumer (the aggregator) calls `connect()`, obtaining\n * `{ result, send, cancel, onMessage }`.\n * - `send({ frame })` carries a frame **to** the child (stdin);\n * `onMessage(({ frame }) => …)` receives frames **from** the child (stdout).\n * - Child exit → the forwarder resolves the request (`connect` returns) → the\n * consumer drops the client.\n * - Consumer dispose / service removed → `cancel()` → the forwarder kills the\n * child.\n *\n * Lives in the CLI package because the producer (`hub mcp-forward`) is a CLI\n * command; the in-extension aggregator imports this contract from here too.\n */\nexport const mcpForwardInterface = defineInterface(\n {\n id: \"vscode.mcp-forward\",\n description:\n \"Transparent MCP tunnel: one streaming request carries a full MCP \"\n + \"JSON-RPC session as opaque duplex stream frames.\",\n },\n {\n connect: requestType(\n z.object({\n /**\n * Advertised so a consumer can label/version the leg without\n * opening the inner MCP session. Purely informational.\n */\n clientInfo: z\n .object({ name: z.string(), version: z.string() })\n .optional(),\n }),\n z.object({\n /** Informational server identity, if the forwarder knows it. */\n serverInfo: z\n .object({ name: z.string(), version: z.string() })\n .optional(),\n }),\n {\n description:\n \"Open one MCP session leg. Resolves (void-ish) only when the \"\n + \"session ends (child exits or the caller cancels). The MCP \"\n + \"traffic is the stream, not the result.\",\n },\n ).withStream({\n // caller → forwarder: MCP frames going *to* the child.\n client: z.object({ frame: z.unknown() }),\n // forwarder → caller: MCP frames coming *from* the child.\n server: z.object({ frame: z.unknown() }),\n }),\n },\n);\n","/**\n * A method reference as accepted on the CLI: `[serviceId::][interfaceId::]name[@hash]`.\n */\nexport class MethodRefWithOptHash {\n public static parseMethodRef(input: string): MethodRefWithOptHash {\n if (input.length === 0) throw new Error('Method reference is empty.');\n\n let hash: string | undefined;\n let core = input;\n const atIdx = input.lastIndexOf('@');\n if (atIdx >= 0) {\n const candidate = input.slice(atIdx + 1);\n // `@` is only the hash separator if it follows the local name and the\n // hash itself contains no `::`. (Interface ids are allowed to contain\n // `.`/`-` so a stray `@` inside the name is a user error.)\n if (candidate.length > 0 && !candidate.includes('::')) {\n hash = candidate;\n core = input.slice(0, atIdx);\n }\n }\n\n const parts = core.split('::');\n if (parts.length === 0 || parts.some((p) => p.length === 0)) {\n throw new Error(`Invalid method reference: \"${input}\"`);\n }\n if (parts.length > 3) {\n throw new Error(`Invalid method reference: too many \"::\" separators in \"${input}\"`);\n }\n\n if (parts.length === 1) {\n return new MethodRefWithOptHash(undefined, undefined, parts[0], hash);\n }\n if (parts.length === 2) {\n return new MethodRefWithOptHash(undefined, parts[0], parts[1], hash);\n }\n return new MethodRefWithOptHash(parts[0], parts[1], parts[2], hash);\n }\n\n constructor(\n public readonly serviceId: string | undefined,\n public readonly interfaceId: string | undefined,\n public readonly methodName: string,\n public readonly hash: string | undefined,\n ) {}\n\n /** Method name as it goes on the wire (no hash, no whitespace). */\n getMethodOnWire(): string {\n if (this.serviceId !== undefined && this.interfaceId !== undefined) {\n return `${this.serviceId}::${this.interfaceId}::${this.methodName}`;\n }\n if (this.interfaceId !== undefined) {\n return `${this.interfaceId}::${this.methodName}`;\n }\n return this.methodName;\n }\n}\n","/**\n * Parse `--param k=v` style overrides into a JSON object. Values that parse\n * as JSON are used as-is (numbers, booleans, null, arrays, objects); the rest\n * are treated as strings. Nested keys use `.` segments: `--param user.name=x`.\n *\n * Combined with `--params <json>` (the whole params blob), `--param k=v`\n * entries layer on top (object-merge for `--params`, then per-key overrides).\n */\nexport interface ParseParamsOptions {\n /** Optional base params object (from `--params <json>` or stdin). */\n base?: unknown;\n /** Raw `--param k=v` strings, in order. */\n overrides?: readonly string[];\n}\n\nexport function parseParamOverride(raw: string): { path: string[]; value: unknown } {\n const eq = raw.indexOf(\"=\");\n if (eq <= 0) {\n throw new Error(`Invalid --param \"${raw}\" (expected key=value)`);\n }\n const key = raw.slice(0, eq);\n const valueStr = raw.slice(eq + 1);\n const path = key.split(\".\");\n if (path.some((p) => p.length === 0)) {\n throw new Error(`Invalid --param key \"${key}\" (empty segment)`);\n }\n const value = parseScalar(valueStr);\n return { path, value };\n}\n\nfunction parseScalar(raw: string): unknown {\n // Try JSON first: lets users pass numbers, booleans, null, arrays, objects.\n // Fall back to the raw string — the common `--param to=a@b.c` case.\n if (raw.length === 0) return \"\";\n const first = raw[0];\n if (first === '\"' || first === \"{\" || first === \"[\" || first === \"-\"\n || first === \"t\" || first === \"f\" || first === \"n\"\n || (first >= \"0\" && first <= \"9\")) {\n try {\n return JSON.parse(raw);\n } catch {\n // fall through\n }\n }\n return raw;\n}\n\nexport function mergeParams(opts: ParseParamsOptions): unknown {\n const base = opts.base !== undefined ? cloneJson(opts.base) : undefined;\n const overrides = opts.overrides ?? [];\n if (overrides.length === 0) return base;\n\n let root: unknown = base;\n for (const raw of overrides) {\n const { path, value } = parseParamOverride(raw);\n root = setDeep(root, path, value);\n }\n return root;\n}\n\nfunction setDeep(root: unknown, path: readonly string[], value: unknown): unknown {\n if (path.length === 1) {\n const target = asPlainObject(root) ?? {};\n target[path[0]] = value;\n return target;\n }\n const target = asPlainObject(root) ?? {};\n const [head, ...rest] = path;\n target[head] = setDeep(target[head], rest, value);\n return target;\n}\n\nfunction asPlainObject(v: unknown): Record<string, unknown> | undefined {\n if (v && typeof v === \"object\" && !Array.isArray(v)) {\n return v as Record<string, unknown>;\n }\n return undefined;\n}\n\nfunction cloneJson<T>(v: T): T {\n if (v === undefined) return v;\n return JSON.parse(JSON.stringify(v)) as T;\n}\n","import { isAssignable, type LinkRpcJsonSchema as SvcJsonSchema } from \"@hediet/linkrpc\";\n\n/**\n * Validate a concrete value against an `SvcJsonSchema`. Reuses linkrpc's\n * structural assignability — the value is lowered to a closed, const-shaped\n * schema and then asked \"is this assignable to the target?\". This avoids\n * pulling in a separate JSON-Schema validator and stays consistent with how\n * the connection layer reasons about interface compatibility.\n *\n * Returns `undefined` if the value is valid, or a short reason string.\n */\nexport function validateValueAgainstSchema(\n value: unknown,\n target: SvcJsonSchema,\n components: Record<string, SvcJsonSchema> = {},\n): string | undefined {\n const actual = valueToConstSchema(value);\n try {\n return isAssignable(actual, target, { schemas: components })\n ? undefined\n : \"does not match schema\";\n } catch (e) {\n return (e as Error).message;\n }\n}\n\n/**\n * Lower a JSON value to the tightest `SvcJsonSchema` that matches only it.\n * Primitives become `{ const }`; arrays become tuples with `items: false`\n * (forbidding extras); objects become closed records with every property\n * required.\n *\n * `undefined` becomes the empty closed object — that's the\n * \"no params supplied\" case, which is only assignable to a target that has\n * no required properties.\n */\nexport function valueToConstSchema(v: unknown): SvcJsonSchema {\n if (v === undefined) {\n return { type: \"object\", properties: {}, additionalProperties: false };\n }\n if (v === null || typeof v === \"boolean\" || typeof v === \"number\" || typeof v === \"string\") {\n return { const: v as never };\n }\n if (Array.isArray(v)) {\n return { type: \"array\", prefixItems: v.map(valueToConstSchema), items: false };\n }\n const obj = v as Record<string, unknown>;\n const properties: Record<string, SvcJsonSchema> = {};\n const required: string[] = [];\n for (const [k, val] of Object.entries(obj)) {\n properties[k] = valueToConstSchema(val);\n required.push(k);\n }\n return { type: \"object\", properties, required, additionalProperties: false };\n}\n\n// ---------------------------------------------------------------------------\n// Path-aware diagnostic validator\n// ---------------------------------------------------------------------------\n\n/**\n * One thing wrong with `value` at a given JSON path. Path uses dot/bracket\n * notation rooted at the validated value, e.g. `.query`, `.items[0].id`.\n * The empty string is the root.\n */\nexport interface ValidationIssue {\n readonly path: string;\n readonly reason: string;\n}\n\n/**\n * Walk `value` against `schema` and collect every mismatch we can pinpoint.\n * Returns `[]` on success. Each issue has a JSON-style path plus a single\n * line saying why that location is wrong — designed to be printed directly\n * under a \"Param validation failed:\" header.\n *\n * Coverage is best-effort: scalar / object / array / tuple / const / enum /\n * union / `$ref`. Unions report the branch with the fewest mismatches\n * (heuristic) so the user gets one concrete trail to fix instead of a\n * cascade of \"no branch matched\".\n */\nexport function explainValidation(\n value: unknown,\n schema: SvcJsonSchema,\n components: Record<string, SvcJsonSchema> = {},\n): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n _walk(value, schema, \"\", components, issues);\n return issues;\n}\n\nfunction _walk(\n value: unknown,\n schema: SvcJsonSchema,\n path: string,\n components: Record<string, SvcJsonSchema>,\n out: ValidationIssue[],\n): void {\n if (schema === true) return;\n if (schema === false) {\n out.push({ path, reason: \"no value is valid here\" });\n return;\n }\n if (\"$ref\" in schema) {\n const resolved = _resolveRef(schema.$ref, components);\n if (!resolved) {\n out.push({ path, reason: `unresolved $ref ${schema.$ref}` });\n return;\n }\n _walk(value, resolved, path, components, out);\n return;\n }\n if (\"const\" in schema) {\n if (!_jsonEq(value, schema.const)) {\n out.push({ path, reason: `expected ${_jsonShow(schema.const)}, got ${_describeValue(value)}` });\n }\n return;\n }\n if (\"enum\" in schema) {\n if (!schema.enum.some((v) => _jsonEq(value, v))) {\n const opts = schema.enum.slice(0, 5).map(_jsonShow).join(\" | \");\n const more = schema.enum.length > 5 ? ` | …` : \"\";\n out.push({\n path,\n reason: `expected one of ${opts}${more}, got ${_describeValue(value)}`,\n });\n }\n return;\n }\n if (\"anyOf\" in schema || \"oneOf\" in schema) {\n const branches = \"anyOf\" in schema ? schema.anyOf : schema.oneOf;\n // Pick the branch with the fewest sub-issues — heuristic best-effort\n // for \"what the user probably meant\".\n let best: ValidationIssue[] | undefined;\n for (const b of branches) {\n const sub: ValidationIssue[] = [];\n _walk(value, b, path, components, sub);\n if (sub.length === 0) return;\n if (!best || sub.length < best.length) best = sub;\n }\n if (best) out.push(...best);\n else out.push({ path, reason: \"value does not match any union branch\" });\n return;\n }\n\n // Type-based dispatch.\n const t = (schema as { type?: string }).type;\n switch (t) {\n case \"null\":\n if (value !== null) out.push({ path, reason: `expected null, got ${_describeValue(value)}` });\n return;\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n out.push({ path, reason: `expected boolean, got ${_describeValue(value)}` });\n }\n return;\n case \"number\":\n if (typeof value !== \"number\") {\n out.push({ path, reason: `expected number, got ${_describeValue(value)}` });\n }\n return;\n case \"integer\":\n if (typeof value !== \"number\" || !Number.isInteger(value)) {\n out.push({ path, reason: `expected integer, got ${_describeValue(value)}` });\n }\n return;\n case \"string\":\n if (typeof value !== \"string\") {\n out.push({ path, reason: `expected string, got ${_describeValue(value)}` });\n }\n return;\n case \"array\":\n _walkArray(value, schema as never, path, components, out);\n return;\n case \"object\":\n _walkObject(value, schema as never, path, components, out);\n return;\n default:\n // Unknown schema shape — fall back to a vague but honest message.\n out.push({ path, reason: \"does not match schema\" });\n }\n}\n\nfunction _walkObject(\n value: unknown,\n schema: {\n type: \"object\";\n properties: Record<string, SvcJsonSchema>;\n required?: string[];\n additionalProperties: SvcJsonSchema | false;\n },\n path: string,\n components: Record<string, SvcJsonSchema>,\n out: ValidationIssue[],\n): void {\n if (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n out.push({ path: path || \"(root)\", reason: `expected object, got ${_describeValue(value)}` });\n return;\n }\n const obj = value as Record<string, unknown>;\n for (const req of schema.required ?? []) {\n if (!(req in obj)) {\n const p = _joinKey(path, req);\n const propSchema = schema.properties[req];\n const typeHint = propSchema ? ` (${_typeHint(propSchema, components)})` : \"\";\n out.push({ path: p, reason: `required${typeHint}, but missing` });\n }\n }\n for (const [k, v] of Object.entries(obj)) {\n const propSchema = schema.properties[k];\n const p = _joinKey(path, k);\n if (propSchema !== undefined) {\n _walk(v, propSchema, p, components, out);\n } else if (schema.additionalProperties === false) {\n out.push({ path: p, reason: \"unknown property\" });\n } else {\n _walk(v, schema.additionalProperties, p, components, out);\n }\n }\n}\n\nfunction _walkArray(\n value: unknown,\n schema: { type: \"array\"; items?: SvcJsonSchema | false; prefixItems?: SvcJsonSchema[] },\n path: string,\n components: Record<string, SvcJsonSchema>,\n out: ValidationIssue[],\n): void {\n if (!Array.isArray(value)) {\n out.push({ path: path || \"(root)\", reason: `expected array, got ${_describeValue(value)}` });\n return;\n }\n const prefix = schema.prefixItems ?? [];\n for (let i = 0; i < value.length; i++) {\n if (i < prefix.length) {\n _walk(value[i], prefix[i], `${path}[${i}]`, components, out);\n } else if (schema.items === false) {\n out.push({ path: `${path}[${i}]`, reason: \"extra element (tuple is closed)\" });\n } else if (schema.items !== undefined) {\n _walk(value[i], schema.items, `${path}[${i}]`, components, out);\n }\n // schema.items === undefined && i >= prefix.length: nothing said\n }\n if (prefix.length > 0 && value.length < prefix.length && schema.items === false) {\n out.push({\n path: path || \"(root)\",\n reason: `expected tuple of length ${prefix.length}, got ${value.length}`,\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// describeSchema — compact \"expected shape\" summary\n// ---------------------------------------------------------------------------\n\n/**\n * Render an `SvcJsonSchema` as a short, copy-paste-friendly type expression.\n * Used as a hint next to required-property errors (`\"name required (string)\"`)\n * and as the \"Expected\" footer when full-on params reporting fires.\n */\nexport function describeSchema(\n schema: SvcJsonSchema,\n components: Record<string, SvcJsonSchema> = {},\n depth = 0,\n): string {\n if (schema === true) return \"any\";\n if (schema === false) return \"never\";\n if (\"$ref\" in schema) {\n const name = schema.$ref.split(\"/\").pop() ?? schema.$ref;\n return name;\n }\n if (\"const\" in schema) return _jsonShow(schema.const);\n if (\"enum\" in schema) {\n return schema.enum.slice(0, 6).map(_jsonShow).join(\" | \")\n + (schema.enum.length > 6 ? \" | …\" : \"\");\n }\n if (\"anyOf\" in schema || \"oneOf\" in schema) {\n const branches = \"anyOf\" in schema ? schema.anyOf : schema.oneOf;\n return branches.map((b) => describeSchema(b, components, depth + 1)).join(\" | \");\n }\n const t = (schema as { type?: string }).type;\n switch (t) {\n case \"null\":\n case \"boolean\":\n case \"number\":\n case \"integer\":\n case \"string\":\n return t;\n case \"array\": {\n const arr = schema as { items?: SvcJsonSchema | false; prefixItems?: SvcJsonSchema[] };\n if (arr.prefixItems && arr.prefixItems.length > 0) {\n const head = arr.prefixItems.map((s) => describeSchema(s, components, depth + 1)).join(\", \");\n if (arr.items === false || arr.items === undefined) return `[${head}]`;\n return `[${head}, …${describeSchema(arr.items, components, depth + 1)}]`;\n }\n return arr.items === false || arr.items === undefined\n ? \"[]\"\n : `${describeSchema(arr.items, components, depth + 1)}[]`;\n }\n case \"object\": {\n if (depth >= 2) return \"object\";\n const obj = schema as {\n properties?: Record<string, SvcJsonSchema>;\n required?: string[];\n additionalProperties?: SvcJsonSchema | boolean;\n };\n if (obj.properties === undefined) {\n return typeof obj.additionalProperties === \"object\"\n ? `Record<string, ${describeSchema(obj.additionalProperties, components, depth + 1)}>`\n : \"object\";\n }\n const reqSet = new Set(obj.required ?? []);\n const fields = Object.entries(obj.properties).map(([k, v]) => {\n const opt = reqSet.has(k) ? \"\" : \"?\";\n return `${k}${opt}: ${describeSchema(v, components, depth + 1)}`;\n });\n return `{ ${fields.join(\"; \")} }`;\n }\n }\n return \"any\";\n}\n\n/**\n * Multi-line table of an object schema's properties: name, required-marker,\n * type, and description. Used as the \"Expected params:\" footer printed under\n * a validation error. Returns `undefined` if `schema` is not an object with\n * named properties (params are closed objects) — fall back to a single\n * `describeSchema` line in that case.\n */\nexport function describeObjectParams(\n schema: SvcJsonSchema,\n components: Record<string, SvcJsonSchema> = {},\n): string | undefined {\n const resolved = _resolveTop(schema, components);\n if (!resolved || typeof resolved !== \"object\" || !(\"type\" in resolved) || resolved.type !== \"object\") {\n return undefined;\n }\n const obj = resolved as {\n type: \"object\";\n properties?: Record<string, SvcJsonSchema>;\n required?: string[];\n };\n if (obj.properties === undefined) return undefined;\n const required = new Set(obj.required ?? []);\n const rows: { name: string; type: string; req: string; desc: string; }[] = [];\n for (const [k, v] of Object.entries(obj.properties)) {\n const resolvedV = _resolveTop(v, components);\n const desc = (resolvedV && typeof resolvedV === \"object\" && \"description\" in resolvedV\n ? (resolvedV as { description?: string }).description\n : undefined) ?? \"\";\n rows.push({\n name: k,\n type: describeSchema(v, components, 1),\n req: required.has(k) ? \"required\" : \"optional\",\n desc,\n });\n }\n if (rows.length === 0) return \"(no params)\";\n const nameW = Math.max(...rows.map((r) => r.name.length));\n const typeW = Math.max(...rows.map((r) => r.type.length));\n const reqW = Math.max(...rows.map((r) => r.req.length));\n return rows\n .map((r) => {\n const head = ` ${r.name.padEnd(nameW)} ${r.type.padEnd(typeW)} ${r.req.padEnd(reqW)}`;\n return r.desc ? `${head} ${r.desc}` : head;\n })\n .join(\"\\n\");\n}\n\n// ---------------------------------------------------------------------------\n// helpers (private)\n// ---------------------------------------------------------------------------\n\nfunction _resolveTop(\n schema: SvcJsonSchema,\n components: Record<string, SvcJsonSchema>,\n): SvcJsonSchema | undefined {\n if (schema === true || schema === false) return schema;\n if (\"$ref\" in schema) return _resolveRef(schema.$ref, components);\n return schema;\n}\n\nfunction _resolveRef(\n ref: string,\n components: Record<string, SvcJsonSchema>,\n): SvcJsonSchema | undefined {\n const prefix = \"#/components/schemas/\";\n if (!ref.startsWith(prefix)) return undefined;\n return components[ref.slice(prefix.length)];\n}\n\nfunction _typeHint(schema: SvcJsonSchema, components: Record<string, SvcJsonSchema>): string {\n return describeSchema(schema, components, 1);\n}\n\nfunction _joinKey(parent: string, key: string): string {\n if (/^[A-Za-z_$][\\w$]*$/.test(key)) return `${parent}.${key}`;\n return `${parent}[${JSON.stringify(key)}]`;\n}\n\nfunction _jsonEq(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\nfunction _jsonShow(v: unknown): string {\n return typeof v === \"string\" ? JSON.stringify(v) : String(v);\n}\n\nfunction _describeValue(v: unknown): string {\n if (v === null) return \"null\";\n if (v === undefined) return \"undefined\";\n if (Array.isArray(v)) return `array (length ${v.length})`;\n if (typeof v === \"object\") return \"object\";\n if (typeof v === \"string\") return `string (${JSON.stringify(v.length > 40 ? v.slice(0, 37) + \"…\" : v)})`;\n return `${typeof v} (${JSON.stringify(v)})`;\n}\n","import { type Identity, InMemoryManagedIdentity, type IMessageTransport, TransportPair } from '@hediet/linkrpc';\nimport { Hub, HubConnectionAcceptor, anonymousHandler, createHubServiceInterfaces } from '@hediet/linkrpc-hub/hub/server/client';\nimport {\n type AttachedLink,\n registerHubServices,\n registerIdentityServices,\n RootOverlay,\n} from '@hediet/linkrpc-hub/hub/server/client';\nimport { type NodeSocketTransport, SocketServer } from '@hediet/linkrpc-hub/hub/server/node';\nimport type { RootProvision } from '@hediet/linkrpc-hub/hub/server/client';\nimport { type EndpointCommand, loadOrCreateIdentity } from '@hediet/linkrpc/node';\nimport { randomBytes } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\n\n/** Default serviceId namespace the local-hub child may claim (and sees via `hubGrantedServiceId::get`). */\nconst DEFAULT_LOCAL_NAMESPACE = 'local';\n\n/** Re-export for backwards compatibility within the CLI. */\nexport const LOCAL_NAMESPACE = DEFAULT_LOCAL_NAMESPACE;\n\n/** Subfolder (under the linkrpc data dir) holding provisioned identity slots. */\nconst PROVISION_SUBDIR = 'provisioned-identities';\n\n/** Provisioned slots untouched for longer than this are swept on next run. */\nconst PROVISION_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days\n\n/**\n * A running in-process hub plus the child it spawned. The CLI connects to\n * `socketPath` (presenting `token`) exactly as it would to any socket hub, and\n * calls {@link dispose} to tear the child + server down.\n */\nexport interface LocalHub {\n readonly socketPath: string;\n readonly token: string;\n dispose(): void;\n}\n\nexport interface StartLocalHubOptions {\n /** Command to spawn as the hub participant. */\n readonly command: EndpointCommand;\n /**\n * When set, the hub serves a *persistent* managed identity loaded from this\n * slot id (reused across runs). Omitted → a fresh ephemeral identity.\n */\n readonly provisionSlot: string | undefined;\n /** Extra env vars injected into the child (the hub's LINKRPC_* vars win). */\n readonly env?: Readonly<Record<string, string>>;\n /** Working directory for the spawned child. */\n readonly cwd?: string;\n /** Max time to wait for the child to claim its namespace. Default 30s. */\n readonly readyTimeoutMs?: number;\n}\n\n/**\n * Start an in-process hub on a private socket, spawn `command` as a participant\n * (handing it the socket + token via `LINKRPC_ENDPOINT` / `LINKRPC_TOKEN`), and\n * resolve once the child has registered a service under {@link LOCAL_NAMESPACE}.\n *\n * The hub is single-tenant and local: no claim policy (every well-formed claim\n * is allowed) and no provenance. Identity is either ephemeral (fresh per run)\n * or, when `provisionSlot` is set, a persisted managed identity so the child's\n * HPKE wrap/unwrap keys survive across runs.\n */\nexport async function startLocalHub(opts: StartLocalHubOptions): Promise<LocalHub> {\n const resolveIdentity = _makeIdentityResolver(opts.provisionSlot);\n const grantedNs = DEFAULT_LOCAL_NAMESPACE;\n\n const hub = new Hub();\n createHubServiceInterfaces(hub);\n\n const socketPath = SocketServer.allocSocketPath();\n const token = randomBytes(16).toString('hex');\n\n const socketServer = await SocketServer.start({\n endpoint: socketPath,\n });\n\n const acceptor = new HubConnectionAcceptor<NodeSocketTransport>({\n server: socketServer,\n hub,\n // No policy → allow every well-formed claim (single-tenant local hub).\n // A single anonymous handler admits the child and provisions its granted\n // namespace and (optionally) a persisted managed identity.\n handlers: [\n anonymousHandler({\n grantedServiceIdNamespace: grantedNs,\n ...(resolveIdentity ? { resolveIdentity } : {}),\n } satisfies RootProvision),\n ],\n });\n\n const child = spawnCommand(opts.command, {\n stdio: ['inherit', 'inherit', 'inherit'],\n env: { ...process.env, ...opts.env, LINKRPC_ENDPOINT: socketPath, LINKRPC_TOKEN: token },\n ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),\n });\n let childExited = false;\n child.once('exit', () => {\n childExited = true;\n });\n\n const dispose = (): void => {\n if (!child.killed) child.kill();\n acceptor.dispose();\n socketServer.dispose();\n if (process.platform !== 'win32') {\n try {\n fs.unlinkSync(socketPath);\n } catch { /* ignore */ }\n }\n };\n\n try {\n await _waitForClaim(hub, grantedNs, () => childExited, opts.readyTimeoutMs ?? 30_000);\n } catch (e) {\n dispose();\n throw e;\n }\n\n return { socketPath, token, dispose };\n}\n\n/**\n * A **RootOverlay** fronting a spawned `cmd-env` child, without a routing hub.\n * The child's root-form calls (`identity::*`, `hubGrantedServiceId::*`,\n * `hubrpc.directory`, `hubAccess`) are served locally on {@link RootOverlay.root};\n * every prefixed request/response is relayed verbatim over {@link uplink}.\n *\n * This is the tunnel's target front end: the tunnel drives {@link uplink} as the\n * \"parent\" so forwarded requests reach the child directly through the overlay\n * splitter. Unlike {@link startLocalHub} there is no hub, no `hub` service id,\n * and no claim to wait for — a plain service target works without the hub-claim\n * dance — while `--provision-identity` still gets `identity::*` served locally.\n */\nexport interface LocalOverlay {\n /** Transport carrying forwarded (prefixed) traffic to/from the participant. */\n readonly uplink: IMessageTransport;\n /** Resolves once the participant is gone (it exited or closed its connection). */\n readonly closed: Promise<void>;\n dispose(): void;\n}\n\nexport interface StartLocalOverlayOptions {\n /** Command to spawn as the participant. */\n readonly command: EndpointCommand;\n /**\n * When set, `identity::*` is served from a persistent managed identity\n * loaded from this slot (reused across runs). Omitted → no identity served.\n */\n readonly provisionSlot: string | undefined;\n /** Extra env vars injected into the child. */\n readonly env?: Readonly<Record<string, string>>;\n /** Working directory for the spawned child. */\n readonly cwd?: string;\n /**\n * ServiceId namespace surfaced to the child via `hubGrantedServiceId::get`\n * and freely claimable through `hubGrantedServiceId::register`.\n */\n readonly grantedNamespace: string;\n /** Max time to wait for the child to connect. Defaults to 10 seconds. */\n readonly readyTimeoutMs?: number;\n}\n\n/**\n * The overlay's claim front door has no routing table to write: the tunnel owns\n * the real claim on the source hub, and the splitter relays every uplink request\n * to the child regardless. So `hubGrantedServiceId::register` succeeds as a\n * no-op through this stub link.\n */\nconst _noopUpstream: Pick<AttachedLink, 'addPrefixRoute'> = {\n addPrefixRoute: () => { },\n};\n\nexport async function startLocalOverlay(opts: StartLocalOverlayOptions): Promise<LocalOverlay> {\n const resolveIdentity = _makeIdentityResolver(opts.provisionSlot);\n\n const socketPath = SocketServer.allocSocketPath();\n const token = randomBytes(16).toString('hex');\n const socketServer = await SocketServer.start({\n endpoint: socketPath,\n isTokenAccepted: async candidate => candidate === token,\n });\n\n let acceptedPeer = false;\n const accepted = new Promise<NodeSocketTransport>((resolve) => {\n socketServer.setConnectionHandler(t => {\n if (acceptedPeer) {\n t.dispose();\n return;\n }\n acceptedPeer = true;\n resolve(t);\n });\n });\n\n let child: ReturnType<typeof spawnCommand>;\n try {\n child = spawnCommand(opts.command, {\n // Keep parent stdout reserved for CLI/broker output.\n stdio: ['ignore', 'pipe', 'pipe'],\n env: { ...process.env, ...opts.env, LINKRPC_ENDPOINT: socketPath, LINKRPC_TOKEN: token },\n ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),\n });\n } catch (error) {\n socketServer.dispose();\n throw error;\n }\n child.stdout?.pipe(process.stderr, { end: false });\n child.stderr?.pipe(process.stderr, { end: false });\n let startupOutput = '';\n const captureStartupOutput = (chunk: Buffer): void => {\n startupOutput = (startupOutput + chunk.toString()).slice(-16_384);\n };\n child.stdout?.on('data', captureStartupOutput);\n child.stderr?.on('data', captureStartupOutput);\n\n const pair = new TransportPair();\n const overlay = new RootOverlay({ uplink: pair.a });\n registerHubServices(overlay.root, _noopUpstream, { grantedServiceIdNamespace: opts.grantedNamespace });\n if (resolveIdentity !== undefined) {\n registerIdentityServices(overlay.root, { resolveIdentity });\n }\n\n let disposed = false;\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n if (!child.killed) child.kill();\n overlay.dispose();\n pair.a.dispose();\n pair.b.dispose();\n socketServer.dispose();\n if (process.platform !== 'win32') {\n try {\n fs.unlinkSync(socketPath);\n } catch { /* ignore */ }\n }\n };\n\n let onExit!: (code: number | null) => void;\n let onError!: (error: Error) => void;\n let timer!: ReturnType<typeof setTimeout>;\n let childTransport: NodeSocketTransport;\n try {\n childTransport = await Promise.race([\n accepted,\n new Promise<never>((_resolve, reject) => {\n onExit = code => reject(new Error(`overlay: cmd-env child exited (code ${code ?? '?'}) before connecting`));\n onError = reject;\n child.once('close', onExit);\n child.once('error', onError);\n timer = setTimeout(() => reject(new Error('overlay: timed out waiting for cmd-env child to connect')),\n opts.readyTimeoutMs ?? 10_000);\n }),\n ]);\n } catch (error) {\n dispose();\n if (startupOutput.trim().length > 0) {\n throw new Error(\n `${error instanceof Error ? error.message : String(error)}\\nChild startup output (last 16384 characters):\\n${startupOutput.trim()}`,\n { cause: error },\n );\n }\n throw error;\n } finally {\n clearTimeout(timer);\n child.removeListener('close', onExit);\n child.removeListener('error', onError);\n child.stdout?.removeListener('data', captureStartupOutput);\n child.stderr?.removeListener('data', captureStartupOutput);\n }\n\n overlay.connectParticipant(childTransport);\n const closed = new Promise<void>((resolve) => {\n childTransport.onDidClose(() => resolve());\n child.once('exit', () => resolve());\n });\n return { uplink: pair.b, closed, dispose };\n}\n\n/**\n * Build the hub's `resolveIdentity`, or `undefined` when no identity should be\n * provided. Without `provisionSlot` the hub serves no identity at all — a child\n * that needs `identity::*` will fail. With it, a single persisted managed\n * identity is shared by all connections (stale slots swept first), so the\n * child's HPKE wrap/unwrap keys survive across runs.\n */\nfunction _makeIdentityResolver(\n provisionSlot: string | undefined,\n): (() => Promise<Identity>) | undefined {\n if (provisionSlot === undefined) {\n return undefined;\n }\n\n const dir = _provisionDir();\n _sweepProvisionedIdentities(dir);\n let shared: Promise<Identity> | undefined;\n return () => {\n if (!shared) {\n shared = (async () => {\n const persisted = await loadOrCreateIdentity({ id: provisionSlot, storeDir: dir });\n return new InMemoryManagedIdentity(persisted.keypair, persisted.wrapKeypair);\n })();\n }\n return shared;\n };\n}\n\n/** Resolve the slot id for a `--provision-identity` / `--provision-identity-slot` run. */\nexport function resolveProvisionSlot(\n explicitSlot: string | undefined,\n provisionIdentity: boolean,\n commandString: string,\n): string | undefined {\n if (explicitSlot !== undefined) {\n return explicitSlot;\n }\n if (provisionIdentity) {\n return JSON.stringify({ cwd: process.cwd(), cmdStr: commandString });\n }\n return undefined;\n}\n\n/** Dedicated provisioned-identity folder (sibling of linkrpc's user identities). */\nfunction _provisionDir(): string {\n const home = os.homedir();\n let base: string;\n if (process.platform === 'win32') {\n base = process.env.APPDATA ?? path.join(home, 'AppData', 'Roaming');\n } else if (process.platform === 'darwin') {\n base = path.join(home, 'Library', 'Application Support');\n } else {\n base = process.env.XDG_CONFIG_HOME ?? path.join(home, '.config');\n }\n return path.join(base, 'linkrpc', PROVISION_SUBDIR);\n}\n\n/** Delete provisioned identity files whose mtime is older than the max age. */\nfunction _sweepProvisionedIdentities(dir: string): void {\n let entries: string[];\n try {\n entries = fs.readdirSync(dir);\n } catch {\n return; // dir absent → nothing to sweep\n }\n const cutoff = Date.now() - PROVISION_MAX_AGE_MS;\n for (const name of entries) {\n if (!name.endsWith('.json')) continue;\n const file = path.join(dir, name);\n try {\n if (fs.statSync(file).mtimeMs < cutoff) fs.unlinkSync(file);\n } catch { /* ignore */ }\n }\n}\n\n/** Resolve once the child claims `prefix` (or a sub-prefix), else reject. */\nfunction _waitForClaim(\n hub: Hub,\n prefix: string,\n childExited: () => boolean,\n timeoutMs: number,\n): Promise<void> {\n const deadline = Date.now() + timeoutMs;\n return new Promise<void>((resolve, reject) => {\n const check = (): void => {\n if (hub.claimedPrefixes().some((p) => p === prefix || p.startsWith(`${prefix}/`))) {\n resolve();\n return;\n }\n if (childExited()) {\n reject(new Error('connect: command exited before registering a service'));\n return;\n }\n if (Date.now() >= deadline) {\n reject(new Error(`connect: timed out waiting for command to register a service under '${prefix}'`));\n return;\n }\n setTimeout(check, 50);\n };\n check();\n });\n}\n","/**\n * Endpoint resolution for the CLI = \"where the linkrpc server lives, and how to\n * reach (or start) it\". The parsed truth is the {@link ResolvedEndpoint} union from\n * `@hediet/linkrpc/node`; this module turns the ergonomic flags / env vars into\n * one.\n *\n * Sources, highest precedence first:\n * 1. `--endpoint-cmd <command>` → spawn a server, connect via injected env\n * 2. `--endpoint-cmd-stdio <command>` → spawn a child, talk over its stdio\n * 3. `--endpoint <uri>` → a literal strict endpoint URI\n * 4. `LINKRPC_ENDPOINT` / `HUBRPC_ENDPOINT` env vars → bare path / ws url\n *\n * `--endpoint-token` only applies to socket / ws endpoint URIs that contain an\n * exact `token=%` placeholder. Env vars support both `LINKRPC_*` and legacy\n * `HUBRPC_*`, with `LINKRPC_*` taking precedence. At most one of `--endpoint*`\n * may be given.\n * `ws-no-init:` preserves its query string verbatim and therefore does not use\n * `--endpoint-token`.\n */\nimport {\n type ResolvedEndpoint,\n formatEndpointUri,\n parseEndpointUri,\n LINKRPC_ENDPOINT_VAR,\n LINKRPC_TOKEN_VAR,\n} from \"@hediet/linkrpc/node\";\nimport { type EndpointConfig } from \"./config\";\nimport { resolveProvisionSlot } from \"./localHub\";\n\nexport type { ResolvedEndpoint } from \"@hediet/linkrpc/node\";\n\nexport interface ResolveEndpointInput {\n /** `--endpoint <uri>`: a literal strict endpoint URI. */\n readonly endpoint?: string;\n /** `--endpoint-cmd <command>`: spawn a server, connect via injected env. */\n readonly endpointCmd?: string;\n /** `--endpoint-cmd-stdio <command>`: spawn a child, talk over its stdio. */\n readonly endpointCmdStdio?: string;\n /** `--endpoint-cmd-env <key=value>`: extra env vars for the spawned child. */\n readonly endpointCmdEnv?: Readonly<Record<string, string>>;\n /** `--endpoint-cmd-cwd <dir>`: working directory for the spawned child. */\n readonly endpointCmdCwd?: string;\n /** `--endpoint-token <token>`: fills an explicit `?token=%` placeholder. */\n readonly endpointToken?: string;\n /** `--provision-identity`: provision a persistent identity for `--endpoint-cmd`. */\n readonly provisionIdentity?: boolean;\n /** `--provision-identity-slot <slot>`: explicit reusable slot id for provisioning. */\n readonly provisionIdentitySlot?: string;\n readonly env?: NodeJS.ProcessEnv;\n /**\n * When set, the provisioning options are validated by the caller (e.g. the\n * `tunnel` command, which routes them to its target cmd instead of source).\n * Suppresses the \"--provision-identity requires --endpoint-cmd\" check.\n */\n readonly provisioningHandledElsewhere?: boolean;\n}\n\nexport interface ResolveEndpointResult {\n readonly endpoint: ResolvedEndpoint | undefined;\n readonly error: string | undefined;\n}\n\nconst LEGACY_ENDPOINT_VAR = \"HUBRPC_ENDPOINT\";\nconst LEGACY_TOKEN_VAR = \"HUBRPC_TOKEN\";\nconst TOKEN_PLACEHOLDER = \"%\";\nconst TOKEN_PLACEHOLDER_PATTERN = /(?:[?&])token=(?<value>[^&#]*)/g;\n\n/** Apply a token override to socket / ws specs; commands carry no token. */\nfunction _withToken(spec: ResolvedEndpoint, token: string | undefined): ResolvedEndpoint {\n if (token === undefined) return spec;\n if (spec.kind === \"socket\") return { ...spec, token };\n if (spec.kind === \"ws\") return { ...spec, token };\n return spec;\n}\n\nfunction _getEnvValue(\n env: NodeJS.ProcessEnv,\n currentName: string,\n legacyName: string,\n): string | undefined {\n return env[currentName] ?? env[legacyName];\n}\n\nfunction _resolveUriEndpoint(\n uri: string,\n tokenOverride: string | undefined,\n fallbackToken: string | undefined,\n tokenFlagName: string,\n endpointName: string,\n): ResolvedEndpoint {\n const spec = parseEndpointUri(uri);\n if (tokenOverride !== undefined) {\n return _applyTokenOverride(spec, uri, tokenOverride, tokenFlagName, endpointName);\n }\n const rawTokenParams = [...uri.matchAll(TOKEN_PLACEHOLDER_PATTERN)]\n .map((match) => match.groups?.value ?? \"\");\n if (rawTokenParams.includes(TOKEN_PLACEHOLDER)) {\n if (rawTokenParams.length !== 1) {\n throw new Error(`${endpointName} must contain at most one token parameter`);\n }\n if (fallbackToken === undefined) {\n throw new Error(\n `${endpointName} contains token=% but no token value was provided`,\n );\n }\n return _withToken(spec, fallbackToken);\n }\n const embeddedToken = \"token\" in spec ? spec.token : undefined;\n const token = embeddedToken ?? fallbackToken;\n return _withToken(spec, token);\n}\n\nfunction _applyTokenOverride(\n spec: ResolvedEndpoint,\n uri: string,\n token: string,\n tokenFlagName: string,\n endpointName: string,\n): ResolvedEndpoint {\n if (spec.kind !== \"socket\" && spec.kind !== \"ws\") {\n throw new Error(\n `${tokenFlagName} is only supported for socket/unix/npipe and ws/wss ${endpointName} values`,\n );\n }\n if (token === TOKEN_PLACEHOLDER) {\n throw new Error(`${tokenFlagName} must not be '${TOKEN_PLACEHOLDER}'`);\n }\n const tokenParams = [...uri.matchAll(TOKEN_PLACEHOLDER_PATTERN)].map((m) => m.groups?.value ?? \"\");\n if (tokenParams.length !== 1 || tokenParams[0] !== TOKEN_PLACEHOLDER) {\n throw new Error(\n `${tokenFlagName} requires ${endpointName} to contain exactly '?token=%' or '&token=%'`,\n );\n }\n return _withToken(spec, token);\n}\n\n/**\n * Resolve the effective endpoint from flags + environment. Returns\n * `{ endpoint: undefined }` when nothing is configured (the caller may then\n * error out). Mutually-exclusive `--endpoint*` flags yield an `error`.\n */\nexport function resolveEndpoint(input: ResolveEndpointInput): ResolveEndpointResult {\n const env = input.env ?? process.env;\n const envEndpoint = _getEnvValue(env, LINKRPC_ENDPOINT_VAR, LEGACY_ENDPOINT_VAR);\n const explicit = [input.endpoint, input.endpointCmd, input.endpointCmdStdio].filter(\n (v) => v !== undefined,\n );\n if (explicit.length > 1) {\n return {\n endpoint: undefined,\n error: \"specify at most one of --endpoint, --endpoint-cmd, --endpoint-cmd-stdio\",\n };\n }\n if (\n (input.provisionIdentity === true || input.provisionIdentitySlot !== undefined)\n && input.endpointCmd === undefined\n && input.provisioningHandledElsewhere !== true\n ) {\n return {\n endpoint: undefined,\n error: \"--provision-identity / --provision-identity-slot require --endpoint-cmd\",\n };\n }\n if (\n input.endpointToken !== undefined\n && input.endpoint === undefined\n && envEndpoint === undefined\n ) {\n return {\n endpoint: undefined,\n error: \"--endpoint-token requires --endpoint or an endpoint environment variable containing token=%\",\n };\n }\n const cmdEnv = input.endpointCmdEnv;\n const cmdCwd = input.endpointCmdCwd;\n if (\n cmdEnv !== undefined && Object.keys(cmdEnv).length > 0\n && input.endpointCmd === undefined && input.endpointCmdStdio === undefined\n ) {\n return {\n endpoint: undefined,\n error: \"--endpoint-cmd-env requires --endpoint-cmd or --endpoint-cmd-stdio\",\n };\n }\n if (\n cmdCwd !== undefined\n && input.endpointCmd === undefined && input.endpointCmdStdio === undefined\n ) {\n return {\n endpoint: undefined,\n error: \"--endpoint-cmd-cwd requires --endpoint-cmd or --endpoint-cmd-stdio\",\n };\n }\n\n try {\n if (input.endpointCmd !== undefined) {\n const provisionSlot = resolveProvisionSlot(\n input.provisionIdentitySlot,\n input.provisionIdentity === true,\n input.endpointCmd,\n );\n return {\n endpoint: {\n kind: \"cmd-env\",\n command: { command: input.endpointCmd },\n ...(provisionSlot !== undefined ? { provisionSlot } : {}),\n ...(cmdEnv !== undefined ? { env: cmdEnv } : {}),\n ...(cmdCwd !== undefined ? { cwd: cmdCwd } : {}),\n },\n error: undefined,\n };\n }\n if (input.endpointCmdStdio !== undefined) {\n return {\n endpoint: {\n kind: \"cmd-stdio\",\n command: { command: input.endpointCmdStdio },\n ...(cmdEnv !== undefined ? { env: cmdEnv } : {}),\n ...(cmdCwd !== undefined ? { cwd: cmdCwd } : {}),\n },\n error: undefined,\n };\n }\n if (input.endpoint !== undefined) {\n return {\n endpoint: _resolveUriEndpoint(\n input.endpoint,\n input.endpointToken,\n undefined,\n \"--endpoint-token\",\n \"--endpoint\",\n ),\n error: undefined,\n };\n }\n\n if (envEndpoint) {\n return {\n endpoint: _resolveUriEndpoint(\n envEndpoint,\n input.endpointToken,\n _getEnvValue(env, LINKRPC_TOKEN_VAR, LEGACY_TOKEN_VAR),\n \"--endpoint-token\",\n `${LINKRPC_ENDPOINT_VAR}/${LEGACY_ENDPOINT_VAR}`,\n ),\n error: undefined,\n };\n }\n } catch (e) {\n return { endpoint: undefined, error: (e as Error).message };\n }\n\n return { endpoint: undefined, error: undefined };\n}\n\n/** One-line, token-redacted description of an endpoint for logs. */\nexport function formatEndpoint(spec: ResolvedEndpoint): string {\n return formatEndpointUri(spec);\n}\n\nexport interface ResolveTargetEndpointInput {\n /** `--target-endpoint <uri>`. */\n readonly targetEndpoint?: string;\n /** `--target-endpoint-cmd <command>`. */\n readonly targetEndpointCmd?: string;\n /** `--target-endpoint-cmd-stdio <command>`. */\n readonly targetEndpointCmdStdio?: string;\n /** `--target-endpoint-cmd-env <key=value>` (repeatable). */\n readonly targetEndpointCmdEnv?: Readonly<Record<string, string>>;\n /** `--target-endpoint-cmd-cwd <dir>`: working directory for the spawned target child. */\n readonly targetEndpointCmdCwd?: string;\n /** `--target-endpoint-token <token>`: fills an explicit `?token=%` placeholder. */\n readonly targetEndpointToken?: string;\n /**\n * Provisioning options to bind to the *target* cmd. Same semantics as\n * the global `--provision-identity[-slot]`; the `tunnel` command routes\n * them here when the target is a cmd.\n */\n readonly provisionIdentity?: boolean;\n readonly provisionIdentitySlot?: string;\n}\n\n/**\n * Resolve a *target* endpoint from `--target-*` flags. Mirrors\n * {@link resolveEndpoint} for tunnel-style commands that have both a source\n * (the hub the CLI claims on) and a target (the implementation that handles\n * inbound requests). Returns `{ endpoint: undefined }` when no `--target-*`\n * flag is set so the caller can error with a command-specific message.\n *\n * Unlike {@link resolveEndpoint}, no env-var fallback is consulted \\u2014 the\n * target is always explicit.\n */\nexport function resolveTargetEndpoint(input: ResolveTargetEndpointInput): ResolveEndpointResult {\n const explicit = [\n input.targetEndpoint,\n input.targetEndpointCmd,\n input.targetEndpointCmdStdio,\n ].filter((v) => v !== undefined);\n if (explicit.length > 1) {\n return {\n endpoint: undefined,\n error:\n \"specify at most one of --target-endpoint, --target-endpoint-cmd, --target-endpoint-cmd-stdio\",\n };\n }\n if (\n (input.provisionIdentity === true || input.provisionIdentitySlot !== undefined)\n && input.targetEndpointCmd === undefined\n ) {\n // For tunnel, provisioning binds to the target cmd \\u2014 not the source.\n // (The source typically signs with the user's `--principal` identity.)\n // Caller may still be okay if provisioning was consumed elsewhere; in\n // that case it wouldn't have reached us via this path.\n return {\n endpoint: undefined,\n error: \"--provision-identity / --provision-identity-slot require --target-endpoint-cmd\",\n };\n }\n if (input.targetEndpointToken !== undefined && input.targetEndpoint === undefined) {\n return {\n endpoint: undefined,\n error: \"--target-endpoint-token requires --target-endpoint containing token=%\",\n };\n }\n const cmdEnv = input.targetEndpointCmdEnv;\n const cmdCwd = input.targetEndpointCmdCwd;\n if (\n cmdEnv !== undefined && Object.keys(cmdEnv).length > 0\n && input.targetEndpointCmd === undefined && input.targetEndpointCmdStdio === undefined\n ) {\n return {\n endpoint: undefined,\n error: \"--target-endpoint-cmd-env requires --target-endpoint-cmd or --target-endpoint-cmd-stdio\",\n };\n }\n if (\n cmdCwd !== undefined\n && input.targetEndpointCmd === undefined && input.targetEndpointCmdStdio === undefined\n ) {\n return {\n endpoint: undefined,\n error: \"--target-endpoint-cmd-cwd requires --target-endpoint-cmd or --target-endpoint-cmd-stdio\",\n };\n }\n\n try {\n if (input.targetEndpointCmd !== undefined) {\n const provisionSlot = resolveProvisionSlot(\n input.provisionIdentitySlot,\n input.provisionIdentity === true,\n input.targetEndpointCmd,\n );\n return {\n endpoint: {\n kind: \"cmd-env\",\n command: { command: input.targetEndpointCmd },\n ...(provisionSlot !== undefined ? { provisionSlot } : {}),\n ...(cmdEnv !== undefined ? { env: cmdEnv } : {}),\n ...(cmdCwd !== undefined ? { cwd: cmdCwd } : {}),\n },\n error: undefined,\n };\n }\n if (input.targetEndpointCmdStdio !== undefined) {\n return {\n endpoint: {\n kind: \"cmd-stdio\",\n command: { command: input.targetEndpointCmdStdio },\n ...(cmdEnv !== undefined ? { env: cmdEnv } : {}),\n ...(cmdCwd !== undefined ? { cwd: cmdCwd } : {}),\n },\n error: undefined,\n };\n }\n if (input.targetEndpoint !== undefined) {\n return {\n endpoint: _resolveUriEndpoint(\n input.targetEndpoint,\n input.targetEndpointToken,\n undefined,\n \"--target-endpoint-token\",\n \"--target-endpoint\",\n ),\n error: undefined,\n };\n }\n } catch (e) {\n return { endpoint: undefined, error: (e as Error).message };\n }\n\n return { endpoint: undefined, error: undefined };\n}\n\n/**\n * Lower a resolved endpoint into a declarative {@link EndpointConfig} entry,\n * applying the given routing fields. Used by `tunnel -c, --config` to append\n * the source hub to a loaded config as a claiming endpoint, so the in-process\n * hub registers the service id on the source and routes its inbound calls\n * through the config-described target.\n *\n * A `cmd-env` endpoint's `provisionSlot` is carried over as a slotted managed\n * identity so the claim signs with a persistent identity.\n */\nexport function resolvedEndpointToConfig(\n spec: ResolvedEndpoint,\n routing: { readonly claimServiceIds: readonly string[]; },\n): EndpointConfig {\n const claimServiceIds = [...routing.claimServiceIds];\n switch (spec.kind) {\n case \"socket\":\n return {\n kind: \"socket\",\n path: spec.path,\n ...(spec.token !== undefined ? { token: spec.token } : {}),\n routeServiceIds: [],\n claimServiceIds,\n defaultRoute: false,\n };\n case \"ws\":\n return {\n kind: \"ws\",\n url: spec.url,\n ...(spec.token !== undefined ? { token: spec.token } : {}),\n routeServiceIds: [],\n claimServiceIds,\n defaultRoute: false,\n };\n case \"ws-no-init\":\n throw new Error(\"ws-no-init endpoints cannot be used as declarative hub routes\");\n case \"cmd-env\":\n return {\n kind: \"cmd-env\",\n ..._commandFields(spec.command),\n ...(spec.env !== undefined ? { env: { ...spec.env } } : {}),\n ...(spec.cwd !== undefined ? { cwd: spec.cwd } : {}),\n routeServiceIds: [],\n claimServiceIds,\n defaultRoute: false,\n ...(spec.provisionSlot !== undefined\n ? { managedIdentity: { slot: spec.provisionSlot } }\n : {}),\n };\n case \"cmd-stdio\":\n return {\n kind: \"cmd-stdio\",\n ..._commandFields(spec.command),\n ...(spec.env !== undefined ? { env: { ...spec.env } } : {}),\n ...(spec.cwd !== undefined ? { cwd: spec.cwd } : {}),\n routeServiceIds: [],\n claimServiceIds,\n defaultRoute: false,\n };\n }\n}\n\n/** Lower an {@link EndpointCommand} into the config's `cmd` / `argv` fields. */\nfunction _commandFields(\n command: { readonly command: string; } | { readonly argv: readonly string[]; },\n): { cmd: string; } | { argv: string[]; } {\n return \"command\" in command ? { cmd: command.command } : { argv: [...command.argv] };\n}\n","import {\n type CapProvider,\n type Channel,\n type IMessageTransport,\n type MessageTransportTrace,\n type IRequestHandler,\n type IRequestSender,\n JsonRpcChannel,\n type OneShotCapStaging,\n type Principal,\n RpcError,\n type SigningCallCtx,\n SigningSender,\n traceMessageTransport,\n} from '@hediet/linkrpc';\nimport {\n connectNdjson,\n type EndpointCommand,\n openWebSocket,\n runInitializeHandshake,\n WebSocketTransport,\n} from '@hediet/linkrpc/node';\nimport { tapTransport } from '@hediet/linkrpc-hub/hub/server/transit';\nimport { spawnCommand } from '@hediet/linkrpc-hub/spawn';\nimport * as net from 'node:net';\nimport type { ResolvedEndpoint } from './endpoint';\nimport { LOCAL_NAMESPACE, startLocalHub, startLocalOverlay } from './localHub';\n\n// `spawnCommand` is owned by the shared hub engine; the CLI re-exports it so\n// existing `./connect` import sites keep working. (Socket-path allocation now\n// lives on `SocketServer.allocSocketPath`.)\nexport { spawnCommand };\n\n/**\n * Mutable signing config consulted per-call by the {@link SigningSender}\n * wrapping a {@link CliConnection.channel}. Starts empty; `setupHubSigning`\n * installs a {@link Principal} (identity + persistent caps) and an optional\n * {@link OneShotCapStaging} policy. Mutating a field takes effect on the\n * next outbound call.\n */\nexport interface CliSigning {\n principal?: Principal;\n oneShotCaps?: OneShotCapStaging;\n capProvider?: CapProvider;\n}\n\n/**\n * Tee every JSON-RPC message crossing the connection's transport to a line\n * sink, rendered like the hub's \"Flows\" view. For inspecting a *direct*\n * connection that never routes through a local hub.\n */\nexport interface ConnectLogOptions {\n readonly log?: (line: string) => void;\n /** Edge label for the far end in the rendered path. Default `\"peer\"`. */\n readonly remoteLabel?: string;\n /** Max JSON length per payload before truncation. Default 200. */\n readonly maxPayload?: number;\n /** Raw message trace, attached before any transport handshake. */\n readonly trace?: MessageTransportTrace;\n}\n\n/**\n * A live linkrpc connection plus the underlying child / socket. The CLI\n * owns both so it can wait for the channel to drain before tearing the\n * peer down.\n *\n * `signing` is the mutable holder consulted by the {@link SigningSender}\n * wrapping `channel`. Starts empty (unsigned plain JSON-RPC); populated\n * by `setupHubSigning`. User code with its own signing requirements can\n * mutate it directly.\n */\nexport interface CliConnection {\n readonly channel: IRequestSender<SigningCallCtx>;\n readonly signing: CliSigning;\n /**\n * The underlying signing {@link Channel} (sender + inbound binding seam).\n * Hand this to `new LinkRpcConnection(conn.rpcChannel)` when a command needs\n * to **serve** typed interfaces over the connection (e.g. `mcp-forward`\n * registers `mcpForwardInterface` + `enableReflection`). Constructing a\n * `LinkRpcConnection` from it binds the inbound handler, so do not also use\n * {@link setRequestHandler} on the same connection — they are mutually\n * exclusive inbound modes (last writer wins).\n */\n readonly rpcChannel: Channel<unknown, SigningCallCtx>;\n /**\n * Bind the raw inbound request/notification handler for this connection.\n * Lets a command (e.g. `tunnel`) receive *all* requests the peer routes\n * here, bypassing the typed {@link LinkRpcConnection} dispatch. Pass\n * `undefined` to detach.\n */\n setRequestHandler(handler: IRequestHandler | undefined): void;\n /** Close the transport, reject pending requests, kill the child (cmd) or destroy the socket (hub). */\n close(): void;\n /**\n * Resolves once the connection is gone: the peer closed it (the child\n * exited, the socket or WebSocket closed) or {@link close} was called.\n */\n readonly closed: Promise<void>;\n}\n\nexport async function connect(\n endpoint: ResolvedEndpoint,\n log?: ConnectLogOptions,\n): Promise<CliConnection> {\n switch (endpoint.kind) {\n case 'cmd-stdio':\n return _connectCmdStdio(endpoint.command, endpoint.env, endpoint.cwd, log);\n case 'cmd-env':\n return _connectCmdEnv(endpoint.command, endpoint.provisionSlot, endpoint.env, endpoint.cwd, log);\n case 'ws':\n return _connectWs(endpoint, log);\n case 'ws-no-init':\n return _connectWs(endpoint, log);\n case 'socket':\n return _connectSocket(endpoint.path, endpoint.token, log);\n }\n}\n\n/**\n * Spawn a child from a command spec. `{ command }` is run through the OS shell\n * (so quoting / splitting follows the shell's rules); `{ argv }` is run\n * directly (no shell), except on Windows where `.cmd` shims need one.\n */\nasync function _connectCmdStdio(\n command: EndpointCommand,\n env: Readonly<Record<string, string>> | undefined,\n cwd: string | undefined,\n log?: ConnectLogOptions,\n): Promise<CliConnection> {\n const child = spawnCommand(command, {\n stdio: ['pipe', 'pipe', 'inherit'],\n ...(env !== undefined ? { env: { ...process.env, ...env } } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n });\n if (!child.stdin || !child.stdout) {\n throw new Error('connect: child process exposes no stdio');\n }\n const input = child.stdin;\n const close = () => {\n // A child handling SIGTERM may still wait on its open stdin pipe.\n if (!input.destroyed && !input.writableEnded) input.end();\n if (!child.killed) child.kill();\n };\n const peerClosed = new Promise<void>((resolve) => child.stdout!.once('close', () => resolve()));\n const { transport } = await connectNdjson({\n input: child.stdout,\n output: child.stdin,\n onClose: close,\n trace: log?.trace,\n });\n return _makeCliConnection(transport, close, log, peerClosed);\n}\n\n/**\n * Spawn one child and connect directly through its root overlay. A plain\n * endpoint needs no namespace claim; hub-aware children can still use the\n * overlay's namespace and identity services.\n */\nasync function _connectCmdEnv(\n command: EndpointCommand,\n provisionSlot: string | undefined,\n env: Readonly<Record<string, string>> | undefined,\n cwd: string | undefined,\n log?: ConnectLogOptions,\n): Promise<CliConnection> {\n return connectViaRootOverlay({ command, provisionSlot, env, cwd, log, grantedNamespace: LOCAL_NAMESPACE });\n}\n\n/**\n * Spawn a child under an in-process local hub (`startLocalHub`) and connect\n * to that hub over a socket. Unlike the standard `cmd-env` endpoint path, this\n * explicitly waits for a namespace claim. The hub and child close together.\n */\nexport async function connectViaLocalHub(opts: {\n readonly command: EndpointCommand;\n readonly provisionSlot: string | undefined;\n readonly env?: Readonly<Record<string, string>>;\n readonly cwd?: string;\n readonly log?: ConnectLogOptions;\n}): Promise<CliConnection> {\n const hub = await startLocalHub({\n command: opts.command,\n provisionSlot: opts.provisionSlot,\n env: opts.env,\n ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),\n });\n try {\n const conn = await _connectSocket(hub.socketPath, hub.token, opts.log);\n return {\n ...conn,\n close: () => {\n conn.close();\n hub.dispose();\n },\n };\n } catch (e) {\n hub.dispose();\n throw e;\n }\n}\n\n/**\n * Connect to a spawned `cmd-env` child through a {@link startLocalOverlay}\n * RootOverlay instead of a full local hub. Root-form calls (`identity::*`,\n * `hubGrantedServiceId::*`, `hubrpc.directory`, `hubAccess`) are served locally;\n * every prefixed request/response is relayed over the returned connection's\n * channel. Used by `tunnel --target-endpoint-cmd`: the tunnel forwards each\n * claimed request onto this channel and the overlay delivers it to the child —\n * no hub, no `hub` service id, no claim-wait, but `identity::*` still served so\n * `--provision-identity` targets work.\n */\nexport async function connectViaRootOverlay(opts: {\n readonly command: EndpointCommand;\n readonly provisionSlot: string | undefined;\n readonly env?: Readonly<Record<string, string>>;\n readonly cwd?: string;\n readonly grantedNamespace: string;\n readonly log?: ConnectLogOptions;\n}): Promise<CliConnection> {\n const overlay = await startLocalOverlay({\n command: opts.command,\n provisionSlot: opts.provisionSlot,\n ...(opts.env !== undefined ? { env: opts.env } : {}),\n ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),\n grantedNamespace: opts.grantedNamespace,\n });\n return _makeCliConnection(overlay.uplink, overlay.dispose, opts.log, overlay.closed);\n}\n\nfunction _connectWs(\n endpoint: Extract<ResolvedEndpoint, { kind: 'ws' | 'ws-no-init'; }>,\n log?: ConnectLogOptions,\n): Promise<CliConnection> {\n return openWebSocket(endpoint.url).then(async (ws) => {\n const closeWs = () => {\n try {\n ws.close();\n } catch { /* ignore */ }\n };\n const baseTransport = new WebSocketTransport(ws, closeWs);\n const peerClosed = new Promise<void>((resolve) => ws.addEventListener('close', () => resolve()));\n const transport = log?.trace === undefined\n ? baseTransport\n : traceMessageTransport(baseTransport, log.trace);\n if (endpoint.kind === 'ws') {\n try {\n await runInitializeHandshake(transport, {\n kind: 'client',\n token: endpoint.token ?? '',\n });\n } catch (err) {\n transport.dispose();\n closeWs();\n throw err;\n }\n }\n return _makeCliConnection(transport, closeWs, log, peerClosed);\n });\n}\n\nasync function _connectSocket(\n socketPath: string,\n token: string | undefined,\n log?: ConnectLogOptions,\n): Promise<CliConnection> {\n const socket = net.createConnection(socketPath);\n await new Promise<void>((resolve, reject) => {\n const onConnect = () => {\n socket.removeListener('error', onError);\n resolve();\n };\n const onError = (error: Error) => {\n socket.removeListener('connect', onConnect);\n socket.destroy();\n reject(error);\n };\n socket.once('connect', onConnect);\n socket.once('error', onError);\n });\n socket.on('error', () => socket.destroy());\n const peerClosed = new Promise<void>((resolve) => socket.once('close', () => resolve()));\n const { transport } = await connectNdjson({\n input: socket,\n output: socket,\n onClose: () => socket.destroy(),\n initialize: { kind: 'client', token: token ?? '' },\n trace: log?.trace,\n });\n return _makeCliConnection(transport, () => socket.destroy(), log, peerClosed);\n}\n\n/**\n * In-memory connection — for tests. The caller hands us a transport already\n * wired to a server-side channel (typically via `TransportPair`).\n */\nexport function connectViaTransport(transport: IMessageTransport): CliConnection {\n return _makeCliConnection(transport, () => { });\n}\n\nfunction _makeCliConnection(\n transport: IMessageTransport,\n onClose: () => void,\n log?: ConnectLogOptions,\n peerClosed?: Promise<void>,\n): CliConnection {\n const tapped = log?.log === undefined\n ? transport\n : tapTransport(transport, {\n log: log.log,\n localLabel: 'cli',\n remoteLabel: log.remoteLabel ?? 'peer',\n ...(log.maxPayload !== undefined ? { maxPayload: log.maxPayload } : {}),\n });\n const signing: CliSigning = {};\n const wrapped = SigningSender.wrapChannel(\n JsonRpcChannel.create(tapped),\n signing,\n );\n const channel = wrapped.sender;\n let markClosed!: () => void;\n const closedByCaller = new Promise<void>((resolve) => { markClosed = resolve; });\n return {\n channel,\n rpcChannel: wrapped,\n signing,\n setRequestHandler: (handler) => wrapped.setRequestHandler(handler),\n close: () => {\n channel.close();\n onClose();\n markClosed();\n },\n closed: peerClosed === undefined ? closedByCaller : Promise.race([peerClosed, closedByCaller]),\n };\n}\n\nexport { RpcError };\n","import * as fs from 'node:fs/promises';\nimport type { IRequestSender, Principal, SigningCallCtx } from '@hediet/linkrpc';\nimport {\n createManagedPrincipal,\n createSelfManagedPrincipal,\n createSelfManagedPrincipalFromFile,\n identityFilePath,\n} from '@hediet/linkrpc/node';\n\n/**\n * Identity slot the managed-with-fallback default falls back to when the peer\n * does not offer a managed identity overlay (e.g. a plain stdio server). Maps\n * to the same on-disk slot `logout` clears.\n */\nexport const MANAGED_FALLBACK_USER_ID = 'hubrpc-cli';\n\n/**\n * Which identity the CLI signs outbound calls with, parsed from `--principal`:\n * - `managed` — the peer signs for us via its `identity::*` overlay; falls\n * back to a local self-managed `{@link MANAGED_FALLBACK_USER_ID}` keypair\n * when no overlay is available.\n * - `user:<id>` — a local Ed25519 keypair stored in the per-user data dir,\n * keyed by `<id>`.\n * - `file:<path>` — a local Ed25519 keypair stored at exactly `<path>`.\n */\nexport type PrincipalSpec =\n | { readonly kind: 'managed'; }\n | { readonly kind: 'user'; readonly id: string; }\n | { readonly kind: 'file'; readonly path: string; };\n\n/**\n * Parse a `--principal` value. `undefined` and `managed` both yield the\n * managed-with-fallback default. Throws on malformed input.\n */\nexport function parsePrincipalSpec(raw: string | undefined): PrincipalSpec {\n if (raw === undefined || raw === 'managed') return { kind: 'managed' };\n if (raw.startsWith('user:')) {\n const id = raw.slice('user:'.length);\n if (id === '') throw new Error('--principal \"user:<id>\" requires a non-empty id');\n return { kind: 'user', id };\n }\n if (raw.startsWith('file:')) {\n const path = raw.slice('file:'.length);\n if (path === '') throw new Error('--principal \"file:<path>\" requires a non-empty path');\n return { kind: 'file', path };\n }\n throw new Error(\n `invalid --principal \"${raw}\" (expected \"managed\", \"user:<id>\", or \"file:<path>\")`,\n );\n}\n\n/**\n * Which identity actually ended up signing the calls, after resolution. Unlike\n * {@link PrincipalSpec} (what the user asked for), this records what was really\n * used — e.g. whether a `managed` request fell back to a local keypair because\n * the peer offered no identity overlay.\n */\nexport type PrincipalSource =\n | { readonly kind: 'managed'; }\n | { readonly kind: 'managed-fallback'; readonly userId: string; }\n | { readonly kind: 'user'; readonly id: string; }\n | { readonly kind: 'file'; readonly path: string; };\n\n/**\n * A resolved {@link Principal} together with a description of which identity\n * actually ended up signing the calls.\n */\nexport interface ResolvedPrincipal {\n readonly principal: Principal;\n readonly source: PrincipalSource;\n /**\n * Set when no keypair was stored for a local identity, so a fresh one was\n * just written to this file. Hubs that trusted a previous key for the same\n * slot do not accept the new one.\n */\n readonly createdFile?: string;\n}\n\n/**\n * Resolve a {@link PrincipalSpec} into a concrete {@link Principal}, given the\n * (signed) sender used to bootstrap a managed identity. Cheap/idempotent, so\n * it can be re-derived on each reconnect. Also reports the {@link PrincipalSource}\n * that was actually used, including whether `managed` fell back to a local key.\n */\nexport async function resolvePrincipal(\n spec: PrincipalSpec,\n sender: IRequestSender<SigningCallCtx>,\n): Promise<ResolvedPrincipal> {\n switch (spec.kind) {\n case 'managed':\n try {\n return {\n principal: await createManagedPrincipal(sender),\n source: { kind: 'managed' },\n };\n } catch {\n return _local(\n identityFilePath({ id: MANAGED_FALLBACK_USER_ID }),\n () => createSelfManagedPrincipal(MANAGED_FALLBACK_USER_ID),\n { kind: 'managed-fallback', userId: MANAGED_FALLBACK_USER_ID },\n );\n }\n case 'user':\n return _local(identityFilePath({ id: spec.id }), () => createSelfManagedPrincipal(spec.id), { kind: 'user', id: spec.id });\n case 'file':\n return _local(spec.path, () => createSelfManagedPrincipalFromFile(spec.path), { kind: 'file', path: spec.path });\n }\n}\n\nasync function _local(file: string, create: () => Promise<Principal>, source: PrincipalSource): Promise<ResolvedPrincipal> {\n const existed = await fs.access(file).then(() => true, () => false);\n const principal = await create();\n return existed ? { principal, source } : { principal, source, createdFile: file };\n}\n\n/**\n * Render a one-line, human-readable description of the identity used to sign\n * calls, e.g. `managed (node abcd012345…)` or\n * `local user:hubrpc-cli (node abcd012345…)`. `nodeId` is truncated to its\n * first 10 characters.\n */\nexport function formatPrincipalSource(source: PrincipalSource, nodeId: string): string {\n const node = `node ${nodeId.slice(0, 10)}…`;\n switch (source.kind) {\n case 'managed':\n return `managed (${node})`;\n case 'managed-fallback':\n return `local user:${source.userId} (managed unavailable) (${node})`;\n case 'user':\n return `local user:${source.id} (${node})`;\n case 'file':\n return `local file:${source.path} (${node})`;\n }\n}\n","import * as fs from \"node:fs/promises\";\nimport { base64UrlToBytes, principalForPublicKey, type PrincipalId } from \"@hediet/linkrpc\";\nimport { identityFilePath } from \"@hediet/linkrpc/node\";\nimport { MANAGED_FALLBACK_USER_ID, type PrincipalSpec } from \"./principal\";\n\n/** The locally stored keypair a {@link PrincipalSpec} signs with. */\nexport interface CliIdentityTarget {\n /** How the user names it, e.g. `user:hubrpc-cli` or `file:/path/key.json`. */\n readonly label: string;\n readonly file: string;\n readonly capsFile: string;\n}\n\n/**\n * The stored keypair `spec` uses, without reading or creating it. `managed`\n * identities are held by the peer, so `managed` names its local fallback slot.\n */\nexport function cliIdentityTarget(spec: PrincipalSpec): CliIdentityTarget {\n if (spec.kind === \"file\") {\n return { label: `file:${spec.path}`, file: spec.path, capsFile: _capsFile(spec.path) };\n }\n const id = spec.kind === \"user\" ? spec.id : MANAGED_FALLBACK_USER_ID;\n const file = identityFilePath({ id });\n return { label: `user:${id}`, file, capsFile: _capsFile(file) };\n}\n\n/** The principal stored at `target`, or `undefined` when there is no stored keypair. */\nexport async function readCliIdentity(target: CliIdentityTarget): Promise<PrincipalId | undefined> {\n let raw: string;\n try {\n raw = await fs.readFile(target.file, \"utf8\");\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw e;\n }\n const { publicKey } = JSON.parse(raw) as { publicKey?: unknown };\n if (typeof publicKey !== \"string\") throw new Error(`malformed identity file ${target.file}`);\n return principalForPublicKey(base64UrlToBytes(publicKey));\n}\n\n/**\n * Delete the keypair and cached capabilities at `target`. The next command\n * signing with it mints a fresh keypair, which hubs that trusted the old key\n * do not accept. Returns the files that were removed.\n */\nexport async function deleteCliIdentity(target: CliIdentityTarget): Promise<string[]> {\n const removed: string[] = [];\n for (const f of [target.file, target.capsFile]) {\n try {\n await fs.unlink(f);\n removed.push(f);\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code !== \"ENOENT\") throw e;\n }\n }\n return removed;\n}\n\nfunction _capsFile(identityFile: string): string {\n return identityFile.endsWith(\".json\") ? identityFile.replace(/\\.json$/, \".caps.json\") : `${identityFile}.caps.json`;\n}\n","import type { IRequestSender, SigningCallCtx } from \"@hediet/linkrpc\";\nimport {\n DEFAULT_WALK_DEPTH,\n type DiscoveredListing,\n fetchDirectory,\n fetchSchema,\n findMethodInSchema,\n type InaccessibleDirectory,\n type ListOptions,\n type ServiceListing,\n walkHub,\n type WalkHubOptions,\n type WalkHubResult,\n} from \"@hediet/linkrpc/hub/common\";\n\n/**\n * The sender every CLI command / reflection helper speaks over: the signing\n * decorator that wraps the live channel. Decoupled from the concrete\n * `JsonRpcChannel` so reconnect can swap the underlying channel transparently.\n */\nexport type CliChannel = IRequestSender<SigningCallCtx>;\n\n/**\n * The directory walk and the `hubrpc.directory` / `hubrpc.schemas` fetch\n * helpers now live in `@hediet/linkrpc` core (so the hub can share them for\n * access-candidate resolution). They are re-exported here so existing CLI\n * imports (`../reflection`) keep working.\n */\nexport {\n DEFAULT_WALK_DEPTH,\n fetchDirectory,\n fetchSchema,\n findMethodInSchema,\n walkHub,\n};\nexport { walkHubDetailed } from \"@hediet/linkrpc/hub/common\";\nexport type {\n DiscoveredListing,\n InaccessibleDirectory,\n ListOptions,\n ServiceListing,\n WalkHubOptions,\n WalkHubResult,\n};\n\nexport interface DefaultsResult {\n readonly serviceId?: string;\n readonly interfaceId?: string;\n readonly hash?: string;\n}\n\nexport async function fetchDefaults(channel: CliChannel): Promise<DefaultsResult> {\n const raw = await channel.sendRequest(\"hubrpc.defaults::get\", {}) as {\n serviceId?: string;\n interfaceId?: string;\n interfaceHash?: string;\n } | null | undefined;\n if (!raw) return {};\n return {\n serviceId: raw.serviceId,\n interfaceId: raw.interfaceId,\n hash: raw.interfaceHash,\n };\n}\n","import {\n type CapProvider,\n type CapProviderResult,\n type CallTarget,\n issueCapability,\n permissionMatchesTarget,\n permits,\n capabilityFreshAt,\n type IRequestSender,\n type Principal,\n type SignedCapability,\n type SigningCallCtx,\n} from '@hediet/linkrpc';\nimport {\n type HubAccessDuration,\n type HubAccessRequest,\n type HubAccessResult,\n} from '@hediet/linkrpc/hub/common';\nimport { hubAccessInterface } from '@hediet/linkrpc/hub/common';\nimport type { CliSigning } from './connect';\nimport { type PrincipalSource, type PrincipalSpec, resolvePrincipal } from './principal';\n\n/** How long before expiry to refresh a capability (2 seconds = transit + skew). */\nconst CAP_FRESHNESS_MARGIN_MS = 2000;\n\n/**\n * The reflection interfaces the CLI walks for `ls` / `schema` / `defaults`\n * / the TUI bus walk. We request all of them, across every service, in a\n * single up-front consent prompt so exploration doesn't re-prompt per\n * service id. See {@link requestReflectionAccess}.\n */\nconst REFLECTION_INTERFACE_IDS = [\n 'hubrpc.directory',\n 'hubrpc.schemas',\n 'hubrpc.defaults',\n] as const;\nconst TOPOLOGY_INTERFACE_ID = 'hubrpc.topology';\n\ntype HubCapProviderResult = Pick<CapProviderResult, 'capabilities' | 'interfaceHash' | 'signedAtMs'>;\n\nexport interface SigningSession {\n /** The identity installed on the channel for this session. */\n readonly principal: Principal;\n /** Which identity actually ended up signing (managed vs. local, etc.). */\n readonly principalSource: PrincipalSource;\n /**\n * The resolved wire method for `hubAccess::requestAccess` on this endpoint\n * (form-3 `<hubServiceId>::hubAccess::requestAccess` for hub endpoints, or\n * the form-2 fallback otherwise).\n */\n readonly hubAccessMethod: string;\n /**\n * Snapshot of the durable capabilities this connection currently holds —\n * the bootstrapped `hubAccess` cap plus anything granted via\n * {@link requestAccess}.\n */\n listGrants(): readonly SignedCapability[];\n /**\n * Explicitly request one or more capabilities from the hub in a single\n * consent prompt. Any durable (non-one-shot) caps the hub mints are added\n * to the connection's cap bag so subsequent calls present them\n * automatically. Use this instead of relying on per-call auto-negotiation.\n */\n requestAccess(req: HubAccessRequest): Promise<HubAccessResult>;\n}\n\n/**\n * Install signing on `signing` for any endpoint. Resolves the\n * {@link PrincipalSpec} into a concrete {@link Principal} (managed-with-\n * fallback, a user slot, or a file-backed keypair) and points the channel's\n * `SigningSender` at it so every outbound call is signed.\n *\n * When `negotiateHubCaps` is set (hub endpoints), it also ensures a persistent\n * `hubAccess` capability is cached on the principal's {@link CapBag} — requesting\n * one with a single signed round-trip on first run / cache miss. For hub\n * endpoints, it also installs a sign-time capability provider.\n *\n * By default (`autoNegotiatePerCall !== false`) that provider negotiates\n * per-call authority lazily using `callIntent` (method + params + nonce +\n * signedAtMs + optional interfaceHash), so one-shot grants can be pinned to the\n * exact call bytes being signed. Set `autoNegotiatePerCall: false` to disable\n * that: the provider then only presents caps already in the bag, and the caller\n * is expected to request access explicitly via\n * {@link SigningSession.requestAccess}.\n */\nexport async function setupSigning(\n channel: IRequestSender<SigningCallCtx>,\n signing: CliSigning,\n principalSpec: PrincipalSpec,\n opts: { negotiateHubCaps: boolean; autoNegotiatePerCall?: boolean; },\n): Promise<SigningSession> {\n const { principal, source: principalSource, createdFile } = await resolvePrincipal(principalSpec, channel);\n if (createdFile !== undefined) {\n process.stderr.write(\n `linkrpc: warning: no stored keypair was found, so a new identity ${principal.id} was created at `\n + `${createdFile}. Hubs that trusted a previous key for this identity will not accept it until `\n + 'they trust or delegate to the new one.\\n',\n );\n }\n\n signing.principal = principal;\n signing.oneShotCaps = undefined;\n signing.capProvider = undefined;\n\n // The hub serves `hubAccess::*` at the connection root (root form, never\n // forwarded → never gated), so the wire address is simply\n // `hubAccess::requestAccess`. No prefix discovery or bootstrap cap is\n // needed to reach the consent front door.\n const hubAccessMethod = `${hubAccessInterface.info.id}::requestAccess`;\n const consumerPrincipalId = principal.id;\n\n if (opts.negotiateHubCaps) {\n // The principal may itself be a capability root of the hub (its\n // `rootPrincipalIds`). Present a self-issued capability alongside the\n // bag: receivers only accept chains rooted at issuers they trust, so it\n // is inert elsewhere. It stays out of the bag, so coverage checks and\n // access negotiation still consider only delegated grants.\n const selfRoot = _issueSelfRootCapability(principal);\n let inAccessNegotiation = false;\n const provider: CapProvider = async ({ method, params, nonce, signedAtMs, interfaceHash }) => {\n const self = await selfRoot;\n let presentCaps = principal.capBag.capabilities;\n // Drop any cached cap that is expired (or expiring within the\n // safety margin) at this call's sign time. Without this, a stale\n // persisted cap from a previous session would be presented and the\n // gate would reject the call with `expired`. Filtering per-cap (not\n // whole-bag) keeps still-valid caps such as the `hubAccess` grant.\n presentCaps = presentCaps.filter((c) =>\n capabilityFreshAt(c, signedAtMs, CAP_FRESHNESS_MARGIN_MS),\n );\n const present: HubCapProviderResult = { capabilities: [...presentCaps, self] };\n if (inAccessNegotiation) return {} satisfies HubCapProviderResult;\n\n const call = _wireMethodToCall(method);\n if (!call) return present;\n if (call.serviceId === '' || call.interfaceId === hubAccessInterface.info.id) return present;\n const request: AccessCallRequest = { call, method, params, nonce, signedAtMs, interfaceHash };\n if (await _capBagCovers(presentCaps, consumerPrincipalId, request)) return present;\n\n // Per-call auto-negotiation is opt-out. When disabled, never trigger\n // a `requestAccess` round-trip behind a call — just present whatever\n // is already in the bag and let the call surface `permissionRequired`\n // if it is gated. The consumer is expected to call\n // `SigningSession.requestAccess` ahead of time.\n if (opts.autoNegotiatePerCall === false) return present;\n\n inAccessNegotiation = true;\n try {\n const granted = await _requestAccessForCall(channel, hubAccessMethod, consumerPrincipalId, request);\n\n if (granted.length === 0) return present;\n\n const oneShot = granted.filter(_isOneShotCap);\n const persistent = granted.filter((c) => !_isOneShotCap(c));\n if (persistent.length > 0) await principal.capBag.add(...persistent);\n\n // Re-read the bag and again drop any stale caps so a freshly\n // attached one-shot is never paired with an expired durable cap.\n const durable = principal.capBag.capabilities.filter((c) =>\n capabilityFreshAt(c, signedAtMs, CAP_FRESHNESS_MARGIN_MS),\n );\n return { capabilities: [...durable, ...oneShot, self] };\n } catch (err) {\n process.stderr.write(\n `linkrpc: capability negotiation skipped (${(err as Error).message})\\n`,\n );\n return present;\n } finally {\n inAccessNegotiation = false;\n }\n };\n signing.capProvider = provider;\n }\n\n return {\n principal,\n principalSource,\n hubAccessMethod,\n listGrants: () => principal.capBag.capabilities,\n requestAccess: (req) => _sessionRequestAccess(channel, hubAccessMethod, principal, req),\n };\n}\n\n/**\n * Up-front, explicit batched request for reflection access across *every*\n * service: `hubrpc.directory` / `hubrpc.schemas` / `hubrpc.defaults` with a\n * wildcard `serviceId` (`{ prefix: '' }`). One consent prompt covers the whole\n * bus, so `ls` / `schema` / `defaults` / the TUI walk stop re-prompting per\n * service id.\n *\n * Best-effort and fail-soft: a `denied` decision (or an open hub with no access\n * handler that rejects the call) is swallowed. Per-call auto-cap negotiation in\n * {@link setupSigning} then remains the fallback for individual gated calls.\n *\n * Returns the granted status so callers can log it; never throws.\n */\nexport async function requestReflectionAccess(\n session: SigningSession,\n opts: { duration?: HubAccessDuration } = {},\n): Promise<'granted' | 'denied' | 'skipped'> {\n if (REFLECTION_INTERFACE_IDS.every((interfaceId) =>\n _hasInterfaceAccess(session, interfaceId, { prefix: '' })\n )) return 'granted';\n try {\n const result = await session.requestAccess({\n consumer: {\n name: 'linkrpc-cli',\n purpose: 'Reflect on every service exposed by the hub (ls / schema / defaults).',\n },\n permissions: REFLECTION_INTERFACE_IDS.map((id) => ({\n target: {\n serviceId: { prefix: '' },\n interfaceId: { exact: id },\n members: [{ prefix: '' }],\n },\n canInvoke: true,\n })),\n duration: opts.duration ?? 'persistent',\n });\n return result.status === 'granted' ? 'granted' : 'denied';\n } catch {\n // Open hub / no access handler / unreachable consent door: fall back to\n // per-call auto-cap negotiation.\n return 'skipped';\n }\n\n}\n\n/**\n * Request topology access in one consent operation before fan-out begins.\n * Discovery mode needs both directory traversal and topology calls across the\n * bus; fixed-source mode requests topology only for those exact service ids.\n */\nexport async function requestTopologyAccess(\n session: SigningSession,\n opts: {\n readonly sourceServiceIds?: readonly string[];\n readonly duration?: HubAccessDuration;\n } = {},\n): Promise<'granted' | 'denied' | 'skipped'> {\n const sourceServiceIds = opts.sourceServiceIds === undefined\n ? undefined\n : [...new Set(opts.sourceServiceIds)].sort();\n const targets = sourceServiceIds === undefined\n ? [{ prefix: '' } as const]\n : sourceServiceIds.map((serviceId) => ({ exact: serviceId } as const));\n const needsDirectory = sourceServiceIds === undefined;\n const alreadyGranted = (!needsDirectory\n || _hasInterfaceAccess(session, 'hubrpc.directory', { prefix: '' }))\n && targets.every((target) =>\n _hasInterfaceAccess(session, TOPOLOGY_INTERFACE_ID, target));\n if (alreadyGranted) return 'granted';\n\n const permissions: Array<HubAccessRequest['permissions'][number]> = [];\n if (needsDirectory) {\n permissions.push({\n target: {\n serviceId: { prefix: '' },\n interfaceId: { exact: 'hubrpc.directory' },\n members: [{ prefix: '' }],\n },\n canInvoke: true,\n });\n }\n for (const serviceId of targets) {\n permissions.push({\n target: {\n serviceId,\n interfaceId: { exact: TOPOLOGY_INTERFACE_ID },\n members: [{ prefix: '' }],\n },\n canInvoke: true,\n });\n }\n\n try {\n const result = await session.requestAccess({\n consumer: {\n name: 'linkrpc-cli',\n purpose: sourceServiceIds === undefined\n ? 'Discover and inspect the topology exposed by every service on the hub.'\n : 'Inspect topology for the selected services.',\n },\n permissions,\n duration: opts.duration ?? 'persistent',\n });\n return result.status === 'granted' ? 'granted' : 'denied';\n } catch {\n return 'skipped';\n }\n}\n\nfunction _hasInterfaceAccess(\n session: SigningSession,\n interfaceId: string,\n requestedServiceId: { readonly exact: string } | { readonly prefix: '' },\n): boolean {\n const now = Date.now();\n return session.listGrants().some((capability) =>\n capability.audience === session.principal.id\n && capabilityFreshAt(capability, now, CAP_FRESHNESS_MARGIN_MS)\n && capability.permissions.some((permission) => {\n if (\n permission.canInvoke !== true\n || permission.callBind !== undefined\n || permission.params !== undefined\n || permission.target.interfaceHash !== undefined\n || !permission.target.members.some((member) =>\n 'prefix' in member && member.prefix === '')\n ) {\n return false;\n }\n if ('prefix' in requestedServiceId) {\n const grantedServiceId = permission.target.serviceId;\n return 'prefix' in grantedServiceId\n && grantedServiceId.prefix === ''\n && permissionMatchesTarget(\n { serviceId: '', interfaceId, member: '' },\n permission,\n );\n }\n return permissionMatchesTarget(\n { serviceId: requestedServiceId.exact, interfaceId, member: '' },\n permission,\n );\n })\n );\n}\n\n/** Parse a wire method into a {@link CallTarget}, or `undefined` for form-1/2. */\nfunction _wireMethodToCall(wireMethod: string): CallTarget | undefined {\n const parts = wireMethod.split('::');\n if (parts.length !== 3) return undefined;\n const [serviceId, interfaceId, member] = parts;\n return { serviceId, interfaceId, member };\n}\n\n/** A cap is one-shot when any permission is pinned to a single call via `callBind`. */\nfunction _isOneShotCap(sc: SignedCapability): boolean {\n return sc.permissions.some((p) => p.callBind !== undefined);\n}\n\n/** `principal` grants itself every call; only a receiver trusting it as a root honors this. */\nfunction _issueSelfRootCapability(principal: Principal): Promise<SignedCapability> {\n return issueCapability(principal.identity, {\n audience: principal.identity.publicSigningIdentity,\n permissions: [{\n target: { serviceId: { prefix: '' }, interfaceId: { prefix: '' }, members: [{ prefix: '' }] },\n canInvoke: true,\n }],\n });\n}\n\n/** Check held authority, not remote trust; the receiving gate selects accepted roots. */\nasync function _capBagCovers(\n caps: readonly SignedCapability[],\n signer: string,\n request: AccessCallRequest,\n): Promise<boolean> {\n const durable = caps.filter((capability) => !_isOneShotCap(capability));\n const result = await permits({\n target: { ...request.call, interfaceHash: request.interfaceHash },\n params: request.params,\n signer,\n nonce: request.nonce,\n signedAtMs: request.signedAtMs,\n // Call-bound capabilities are excluded above.\n callHash: '',\n }, durable, () => durable\n .filter((capability) => capability.parentHash === undefined)\n .map((capability) => ({ principal: capability.issuer, isPublic: false })),\n request.signedAtMs + CAP_FRESHNESS_MARGIN_MS);\n return result.ok;\n}\n\ninterface AccessCallRequest {\n readonly call: CallTarget;\n readonly method: string;\n readonly params: unknown;\n readonly nonce: string;\n readonly signedAtMs: number;\n readonly interfaceHash?: string;\n}\n\nasync function _requestAccessForCall(\n channel: IRequestSender<SigningCallCtx>,\n hubAccessMethod: string,\n consumerPrincipalId: string,\n req: AccessCallRequest,\n): Promise<SignedCapability[]> {\n const result = await _sendRequestAccess(channel, hubAccessMethod, {\n consumer: {\n name: 'linkrpc-cli',\n principal: consumerPrincipalId,\n purpose: `Invoke ${req.method}.`,\n },\n permissions: [{\n target: {\n serviceId: { exact: req.call.serviceId },\n interfaceId: { exact: req.call.interfaceId },\n members: [{ exact: req.call.member }],\n },\n canInvoke: true,\n callIntent: {\n method: req.method,\n params: req.params,\n nonce: req.nonce,\n signedAtMs: req.signedAtMs,\n ...(req.interfaceHash !== undefined ? { interfaceHash: req.interfaceHash } : {}),\n suggestion: 'once' as const,\n },\n }],\n // The hub mints both a once and an always proposal regardless; this\n // only nudges the default selection. The user's choice decides whether\n // the granted cap is one-shot or durable.\n duration: 'once',\n });\n if (result.status !== 'granted') return [];\n return result.capabilities ?? [];\n}\n\nasync function _sendRequestAccess(\n channel: IRequestSender<SigningCallCtx>,\n hubAccessMethod: string,\n params: unknown,\n): Promise<{ status: string; capabilities?: SignedCapability[]; reason?: string; }> {\n const raw = await _awaitWithApprovalNotice(channel.sendRequest(hubAccessMethod, params as never));\n return raw as unknown as {\n status: string;\n capabilities?: SignedCapability[];\n reason?: string;\n };\n}\n\n/** Delay before we tell the user an access request is parked awaiting approval. */\nconst APPROVAL_NOTICE_DELAY_MS = 750;\n\n/**\n * Await a `hubAccess::requestAccess` round-trip, printing a one-line hint to\n * stderr if it doesn't resolve quickly. Access requests park at the hub until a\n * human approver (admin) decides them, so without this notice the CLI looks\n * hung — it blocks with no output until approval. Fast requests (auto-approved\n * / open hub) stay silent because the notice only fires after\n * {@link APPROVAL_NOTICE_DELAY_MS}.\n */\nasync function _awaitWithApprovalNotice<T>(pending: Promise<T>): Promise<T> {\n const timer = setTimeout(() => {\n process.stderr.write(\n 'linkrpc: access request sent — waiting for the hub admin to approve it...\\n',\n );\n }, APPROVAL_NOTICE_DELAY_MS);\n timer.unref?.();\n try {\n return await pending;\n } finally {\n clearTimeout(timer);\n }\n}\n\n/**\n * Backs {@link SigningSession.requestAccess}. Sends a batched\n * `hubAccess::requestAccess`, then adds any durable (non-one-shot) caps the hub\n * minted to the principal's cap bag so later calls present them automatically.\n */\nasync function _sessionRequestAccess(\n channel: IRequestSender<SigningCallCtx>,\n hubAccessMethod: string,\n principal: Principal,\n req: HubAccessRequest,\n): Promise<HubAccessResult> {\n const result = await _sendRequestAccess(channel, hubAccessMethod, {\n consumer: { ...req.consumer, principal: principal.id },\n permissions: req.permissions,\n ...(req.duration !== undefined ? { duration: req.duration } : {}),\n });\n if (result.status === 'granted') {\n const capabilities = result.capabilities ?? [];\n const durable = capabilities.filter((c) => !_isOneShotCap(c));\n if (durable.length > 0) await principal.capBag.add(...durable);\n return { status: 'granted', capabilities, addedDurable: durable.length };\n }\n return { status: result.status, reason: result.reason };\n}\n","/**\n * Hub-backed source of completion candidates. Abstracted so the orchestrator\n * in {@link ./complete.ts} stays unit-testable: tests inject a hand-written\n * source, production wires {@link ChannelDirectorySource} which talks to a\n * live hub via the standard reflection helpers (with an optional file cache\n * provided by {@link ./cache}).\n *\n * The interface intentionally has three primitive operations:\n * - {@link entries} — the bus snapshot (serviceId, interfaceId) pairs\n * - {@link methodsOnInterface} — method names per (serviceId, interfaceId)\n * - {@link paramNamesForMethod} — param property names per method\n *\n * Everything else (distinct serviceIds, interfaces-on-service) is derived\n * by the orchestrator. This keeps cache coordination trivial: one snapshot,\n * one per-interface schema fetch per (sid, iid).\n */\nimport { fetchSchema, walkHub } from '@hediet/linkrpc-client-internal';\nimport type { IRequestSender, SigningCallCtx } from '@hediet/linkrpc';\n\nexport interface DirectoryEntry {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly hash: string;\n}\n\nexport interface DirectorySource {\n entries(): Promise<readonly DirectoryEntry[]>;\n methodsOnInterface(\n serviceId: string | undefined,\n interfaceId: string,\n ): Promise<readonly string[]>;\n /**\n * Property names of the method's params object schema, or `[]` if the\n * method takes no params / has a non-object params descriptor / does\n * not exist on the interface.\n */\n paramNamesForMethod(\n serviceId: string | undefined,\n interfaceId: string,\n methodName: string,\n ): Promise<readonly string[]>;\n}\n\n/** Distinct, sorted serviceIds (drops the empty `''` root). */\nexport function distinctServiceIds(entries: readonly DirectoryEntry[]): readonly string[] {\n return [...new Set(entries.map((e) => e.serviceId).filter((s) => s.length > 0))].sort();\n}\n\n/** Distinct, sorted interface ids across all services. */\nexport function distinctInterfaceIds(entries: readonly DirectoryEntry[]): readonly string[] {\n return [...new Set(entries.map((e) => e.interfaceId))].sort();\n}\n\n/** Distinct, sorted interface ids registered on a particular serviceId. */\nexport function interfacesOnService(\n entries: readonly DirectoryEntry[],\n serviceId: string,\n): readonly string[] {\n return [\n ...new Set(entries.filter((e) => e.serviceId === serviceId).map((e) => e.interfaceId)),\n ].sort();\n}\n\n/**\n * Live source: walks the hub once (memoized for the instance lifetime),\n * then derives every entry / methods lookup from that single snapshot +\n * lazy `fetchSchema` calls. Each (sid, iid) schema is fetched at most once\n * per instance regardless of how many downstream queries reference it.\n */\nexport class ChannelDirectorySource implements DirectorySource {\n private _walkPromise: Promise<readonly DirectoryEntry[]> | undefined;\n private readonly _schemaCache = new Map<string, Promise<{\n readonly methods: readonly string[];\n readonly paramsByMethod: ReadonlyMap<string, readonly string[]>;\n }>>();\n\n constructor(private readonly _channel: IRequestSender<SigningCallCtx>) {}\n\n entries(): Promise<readonly DirectoryEntry[]> {\n if (!this._walkPromise) {\n this._walkPromise = walkHub(this._channel).then((listings) =>\n listings.map((l) => ({\n serviceId: l.serviceId,\n interfaceId: l.interfaceId,\n hash: l.hash,\n })),\n );\n }\n return this._walkPromise;\n }\n\n async methodsOnInterface(\n serviceId: string | undefined,\n interfaceId: string,\n ): Promise<readonly string[]> {\n const schema = await this._fetchSchema(serviceId, interfaceId);\n return schema.methods;\n }\n\n async paramNamesForMethod(\n serviceId: string | undefined,\n interfaceId: string,\n methodName: string,\n ): Promise<readonly string[]> {\n const schema = await this._fetchSchema(serviceId, interfaceId);\n return schema.paramsByMethod.get(methodName) ?? [];\n }\n\n private _fetchSchema(\n serviceId: string | undefined,\n interfaceId: string,\n ): Promise<{\n readonly methods: readonly string[];\n readonly paramsByMethod: ReadonlyMap<string, readonly string[]>;\n }> {\n const key = `${serviceId ?? ''}::${interfaceId}`;\n let cached = this._schemaCache.get(key);\n if (!cached) {\n cached = (async () => {\n const schema = await fetchSchema(this._channel, interfaceId, undefined, serviceId);\n const methods = Object.keys(schema.methods).sort();\n const paramsByMethod = new Map<string, readonly string[]>();\n for (const [name, method] of Object.entries(schema.methods)) {\n const params = method.params;\n if (\n typeof params === 'object' && params !== null\n && (params as { type?: string }).type === 'object'\n ) {\n const props = (params as { properties?: Record<string, unknown> }).properties\n ?? {};\n paramsByMethod.set(name, Object.keys(props));\n } else {\n paramsByMethod.set(name, []);\n }\n }\n return { methods, paramsByMethod };\n })();\n this._schemaCache.set(key, cached);\n }\n return cached;\n }\n}\n","/**\n * Tokenize a shell-style command line and locate the token at the cursor.\n *\n * Used by the `_complete` subcommand to figure out what the user is currently\n * typing. Quoting rules are intentionally minimal (POSIX-ish, matching what\n * users actually type at a PowerShell prompt): single/double quoted strings\n * are single tokens; nothing else is special. Cross-shell quoting nuances\n * don't matter for completion — we only need to know where token boundaries\n * are well enough to pick the current word.\n */\n\nexport interface Token {\n readonly text: string;\n /** Byte offset where the token starts (including any opening quote). */\n readonly start: number;\n /** Byte offset one past the token end (including any closing quote). */\n readonly end: number;\n readonly quoted: boolean;\n}\n\n/** Whitespace per the simple POSIX rule (space, tab, newline). */\nfunction _isWs(ch: string): boolean {\n return ch === ' ' || ch === '\\t' || ch === '\\n' || ch === '\\r';\n}\n\nexport function tokenize(line: string): Token[] {\n const tokens: Token[] = [];\n let i = 0;\n while (i < line.length) {\n while (i < line.length && _isWs(line[i])) i++;\n if (i >= line.length) break;\n const start = i;\n const ch = line[i];\n let text = '';\n let quoted = false;\n if (ch === '\"' || ch === \"'\") {\n quoted = true;\n const q = ch;\n i++;\n while (i < line.length && line[i] !== q) {\n text += line[i++];\n }\n if (i < line.length) i++; // consume closing quote\n } else {\n while (i < line.length && !_isWs(line[i])) {\n text += line[i++];\n }\n }\n tokens.push({ text, start, end: i, quoted });\n }\n return tokens;\n}\n\nexport interface ParsedLine {\n readonly tokens: readonly Token[];\n /**\n * Tokens fully to the left of the cursor (i.e. context — never includes the\n * token the user is currently typing). The first token is the binary name.\n */\n readonly tokensBefore: readonly Token[];\n /**\n * The token the cursor is positioned in / at the right edge of, or\n * `undefined` when the cursor sits in whitespace (a \"new\" word).\n */\n readonly currentToken: Token | undefined;\n /**\n * Text the user has typed for the current word so far (token start →\n * cursor). Empty when {@link currentToken} is undefined. Used both for\n * prefix-filtering candidates and as the value PowerShell replaces.\n */\n readonly currentWordPrefix: string;\n}\n\n/**\n * Split `line` at `point` (0-indexed cursor position) into a previous-tokens\n * list + a possibly in-progress current word. Cursor inside or at the end of\n * a token = that token is the current word; cursor in whitespace = no current\n * token, new empty word at this position.\n */\nexport function parseLine(line: string, point: number): ParsedLine {\n const tokens = tokenize(line);\n const safePoint = Math.max(0, Math.min(line.length, point));\n\n // A cursor sitting on whitespace (or at the very start) means we're\n // typing a brand-new word at this column.\n const charLeftOfCursor = safePoint > 0 ? line[safePoint - 1] : ' ';\n const inGap = _isWs(charLeftOfCursor) || safePoint === 0;\n if (inGap) {\n const tokensBefore = tokens.filter((t) => t.end <= safePoint);\n return { tokens, tokensBefore, currentToken: undefined, currentWordPrefix: '' };\n }\n\n // Cursor is \"attached\" to a token: find the one containing the char\n // immediately to its left.\n const cur = tokens.find((t) => t.start <= safePoint - 1 && safePoint - 1 < t.end);\n if (!cur) {\n // Defensive: shouldn't happen given the gap check above.\n const tokensBefore = tokens.filter((t) => t.end <= safePoint);\n return { tokens, tokensBefore, currentToken: undefined, currentWordPrefix: '' };\n }\n const tokensBefore = tokens.filter((t) => t.end <= cur.start);\n return {\n tokens,\n tokensBefore,\n currentToken: cur,\n currentWordPrefix: cur.text.slice(0, safePoint - cur.start),\n };\n}\n","/**\n * Static description of the CLI's command surface, used to drive\n * completion. The runtime CLI is defined with `commander` in {@link ../cli};\n * this table mirrors it. A drift test\n * ({@link ./tree.test.ts}) verifies subcommand & flag names match.\n *\n * Keeping the tree static (rather than introspecting commander at\n * completion time) lets the completer run with zero startup cost in the\n * common static-only case and keeps the slot-resolution logic completely\n * pure — straightforward to unit-test.\n */\n\nexport type SlotType =\n /** A bare or qualified `[svc::][iface::]method[@hash]` reference. */\n | 'methodRef'\n /** A bare `interfaceId[@hash]` (e.g. `schema <interfaceRef>`). */\n | 'interfaceRef'\n /** A service id known to the hub. */\n | 'serviceId'\n /** A bare interface id, sans hash. */\n | 'interfaceId'\n /** One of the supported shell names (powershell, bash, zsh, fish). */\n | 'shell'\n | 'connectionLimit'\n /** Anything else — completer returns no dynamic suggestions. */\n | 'free';\n\nexport interface FlagDef {\n readonly name: string;\n readonly takesValue: boolean;\n readonly valueType?: SlotType;\n readonly description?: string;\n}\n\nexport interface PositionalDef {\n readonly name: string;\n readonly type: SlotType;\n}\n\nexport interface SubcommandDef {\n readonly name: string;\n readonly description: string;\n readonly options: readonly FlagDef[];\n readonly positionals: readonly PositionalDef[];\n readonly subcommands?: readonly SubcommandDef[];\n /** When set, extra positionals beyond {@link positionals} are completed as this type. */\n readonly variadic?: SlotType;\n /** Hide from subcommand-name completion (used for `_complete`). */\n readonly hidden?: boolean;\n}\n\nexport interface CommandTree {\n readonly globalOptions: readonly FlagDef[];\n readonly subcommands: readonly SubcommandDef[];\n}\n\nconst ENDPOINT_GLOBAL_OPTIONS: readonly FlagDef[] = [\n { name: '--endpoint', takesValue: true, valueType: 'free', description: 'endpoint URI' },\n { name: '--endpoint-cmd', takesValue: true, valueType: 'free' },\n { name: '--endpoint-cmd-stdio', takesValue: true, valueType: 'free' },\n { name: '--endpoint-cmd-env', takesValue: true, valueType: 'free' },\n { name: '--endpoint-cmd-cwd', takesValue: true, valueType: 'free' },\n { name: '--endpoint-token', takesValue: true, valueType: 'free' },\n { name: '--context', takesValue: true, valueType: 'free' },\n { name: '--context-set', takesValue: false },\n { name: '--new-context', takesValue: true, valueType: 'free' },\n { name: '--schema', takesValue: true, valueType: 'free' },\n { name: '--daemon-service', takesValue: true, valueType: 'serviceId' },\n { name: '--detach-keys', takesValue: true, valueType: 'free' },\n { name: '--validation', takesValue: true, valueType: 'free' },\n { name: '--use-env', takesValue: false },\n { name: '--no-use-env', takesValue: false },\n { name: '--sign', takesValue: false },\n { name: '--no-sign', takesValue: false },\n { name: '--provision-identity', takesValue: false },\n { name: '--provision-identity-slot', takesValue: true, valueType: 'free' },\n {\n name: '--principal',\n takesValue: true,\n valueType: 'free',\n description: '\"managed\", \"user:<id>\", or \"file:<path>\"',\n },\n];\n\nconst HUB_GLOBAL_OPTIONS: readonly FlagDef[] = [\n ...ENDPOINT_GLOBAL_OPTIONS,\n { name: '--config', takesValue: true, valueType: 'free' },\n];\n\nconst CAPABILITY_OPTIONS: readonly FlagDef[] = [\n { name: '--cap:allow-param', takesValue: true, valueType: 'free' },\n { name: '--cap:duration', takesValue: true, valueType: 'free' },\n { name: '--cap:allow-prefix', takesValue: true, valueType: 'free' },\n { name: '--cap:allow-any', takesValue: false },\n { name: '--cap:allow-enum', takesValue: true, valueType: 'free' },\n { name: '--cap:allow-subset', takesValue: true, valueType: 'free' },\n];\n\nconst SHARED_COMMANDS: readonly SubcommandDef[] = [\n {\n name: 'ls',\n description: 'List services and interfaces.',\n positionals: [],\n options: [\n { name: '--interface', takesValue: true, valueType: 'interfaceId' },\n { name: '--service', takesValue: true, valueType: 'serviceId' },\n { name: '--depth', takesValue: true, valueType: 'free' },\n { name: '--with-members', takesValue: false },\n { name: '--json', takesValue: false },\n { name: '--dump', takesValue: true, valueType: 'free' },\n { name: '--dump-patches', takesValue: true, valueType: 'free' },\n { name: '--stream', takesValue: false },\n { name: '--watch', takesValue: false },\n ],\n },\n {\n name: 'defaults',\n description: 'Print the preset service / interface.',\n positionals: [],\n options: [{ name: '--json', takesValue: false }],\n },\n {\n name: 'schema',\n description: 'Inspect, hash, and compare interface schemas.',\n positionals: [{ name: 'interfaceRef', type: 'interfaceRef' }],\n options: [],\n subcommands: [\n {\n name: 'show',\n description: 'Print an interface schema.',\n positionals: [{ name: 'interfaceRef', type: 'interfaceRef' }],\n options: [\n { name: '--method', takesValue: true, valueType: 'free' },\n { name: '--service', takesValue: true, valueType: 'serviceId' },\n { name: '--json', takesValue: false },\n ],\n },\n {\n name: 'hash',\n description: 'Hash a local schema.',\n positionals: [{ name: 'schema', type: 'free' }],\n options: [],\n },\n {\n name: 'check-compat',\n description: 'Compare a local schema against the live one.',\n positionals: [\n { name: 'interfaceId', type: 'interfaceId' },\n { name: 'local', type: 'free' },\n ],\n options: [],\n },\n ],\n },\n {\n name: 'call',\n description: 'Invoke a request.',\n positionals: [{ name: 'methodRef', type: 'methodRef' }],\n options: [\n { name: '--params', takesValue: true, valueType: 'free' },\n { name: '--param', takesValue: true, valueType: 'free' },\n { name: '--no-validate', takesValue: false },\n { name: '--cap:request', takesValue: false },\n ...CAPABILITY_OPTIONS,\n ],\n },\n {\n name: 'notify',\n description: 'Fire a notification (no response).',\n positionals: [{ name: 'methodRef', type: 'methodRef' }],\n options: [\n { name: '--params', takesValue: true, valueType: 'free' },\n { name: '--param', takesValue: true, valueType: 'free' },\n { name: '--no-validate', takesValue: false },\n ],\n },\n {\n name: 'attach',\n description: 'Attach to a linkrpc.console template instance (pipe or TTY), or list consoles.',\n positionals: [{ name: 'serviceId', type: 'serviceId' }],\n options: [\n { name: '--params', takesValue: true, valueType: 'free' },\n { name: '--interface', takesValue: true, valueType: 'free' },\n { name: '--instance', takesValue: true, valueType: 'free' },\n { name: '--read-only', takesValue: false },\n ],\n },\n {\n name: 'batch',\n description: 'Run sequential calls and notifications.',\n positionals: [],\n variadic: 'free',\n options: [],\n },\n {\n name: 'connection',\n description: 'Manage persistent RPC connections.',\n positionals: [],\n options: [],\n subcommands: [\n {\n name: 'create',\n description: 'Create a persistent connection; requires --timeout or --ttl.',\n positionals: [],\n options: [\n { name: '--timeout', takesValue: true, valueType: 'connectionLimit', description: 'Inactivity duration or inf (omitted: inf).' },\n { name: '--ttl', takesValue: true, valueType: 'connectionLimit', description: 'Lifetime duration or inf (omitted: inf).' },\n { name: '--notification-limit', takesValue: true, valueType: 'free' },\n ],\n },\n {\n name: 'status',\n description: 'Show persistent connection status.',\n positionals: [],\n options: [],\n },\n {\n name: 'notifications',\n description: 'Read buffered server notifications.',\n positionals: [],\n options: [\n { name: '--after', takesValue: true, valueType: 'free' },\n { name: '--wait', takesValue: true, valueType: 'free' },\n { name: '--follow', takesValue: false },\n ],\n },\n {\n name: 'destroy',\n description: 'Destroy a persistent connection.',\n positionals: [],\n options: [],\n },\n ],\n },\n {\n name: 'context',\n description: 'Show how the active context resolves, or modify its defaults.',\n positionals: [],\n options: [],\n subcommands: [\n { name: 'show', description: 'Show stored context defaults only.', positionals: [], options: [] },\n { name: 'create', description: 'Create a context.', positionals: [{ name: 'selector', type: 'free' }], options: [] },\n { name: 'list', description: 'List stored contexts.', positionals: [], options: [] },\n {\n name: 'set',\n description: 'Set values on the selected context.',\n positionals: [],\n options: [{ name: '--unset', takesValue: true, valueType: 'free' }],\n },\n { name: 'remove', description: 'Remove the selected context.', positionals: [], options: [] },\n ],\n },\n {\n name: 'ping',\n description: 'One reflection round-trip; prints latency.',\n positionals: [],\n options: [],\n },\n {\n name: 'ui',\n description: 'Launch the terminal UI.',\n positionals: [],\n options: [],\n },\n {\n name: 'completions',\n description: 'Print a shell completion script for the requested shell.',\n positionals: [{ name: 'shell', type: 'shell' }],\n options: [],\n },\n {\n name: '_complete',\n description: '(internal) Emit completion candidates for a partial command line.',\n positionals: [],\n options: [\n { name: '--line', takesValue: true, valueType: 'free' },\n { name: '--point', takesValue: true, valueType: 'free' },\n ],\n hidden: true,\n },\n {\n name: 'connect',\n description: 'Legacy alias for connection create.',\n positionals: [],\n options: [\n { name: '--timeout', takesValue: true, valueType: 'connectionLimit', description: 'Inactivity duration or inf (omitted: inf).' },\n { name: '--ttl', takesValue: true, valueType: 'connectionLimit', description: 'Lifetime duration or inf (omitted: inf).' },\n { name: '--notification-limit', takesValue: true, valueType: 'free' },\n ],\n },\n {\n name: 'connection-status',\n description: 'Legacy alias for connection status.',\n positionals: [],\n options: [],\n },\n {\n name: 'notifications',\n description: 'Legacy alias for connection notifications.',\n positionals: [],\n options: [\n { name: '--after', takesValue: true, valueType: 'free' },\n { name: '--wait', takesValue: true, valueType: 'free' },\n { name: '--follow', takesValue: false },\n ],\n },\n {\n name: 'disconnect',\n description: 'Legacy alias for connection destroy.',\n positionals: [],\n options: [],\n },\n {\n name: 'hash',\n description: 'Legacy alias for schema hash.',\n positionals: [{ name: 'schema', type: 'free' }],\n options: [],\n },\n {\n name: 'check-compat',\n description: 'Legacy alias for schema check-compat.',\n positionals: [\n { name: 'interfaceId', type: 'interfaceId' },\n { name: 'local', type: 'free' },\n ],\n options: [],\n },\n];\n\nconst HUB_ONLY_COMMANDS: readonly SubcommandDef[] = [\n {\n name: 'services',\n description: 'Manage daemon-owned processes and connections.',\n positionals: [],\n options: [{ name: '--namespace', takesValue: true, valueType: 'free' }],\n subcommands: [\n { name: 'restart', description: 'Replace the local daemon with the bundled daemon.', positionals: [], options: [] },\n {\n name: 'run', description: 'Run on the selected daemon.', positionals: [{ name: 'command', type: 'free' }],\n options: [\n { name: '--id', takesValue: true, valueType: 'free' },\n { name: '--persistent', takesValue: false },\n { name: '--restart', takesValue: true, valueType: 'free' },\n { name: '--detach', takesValue: false },\n { name: '--foreground', takesValue: false },\n { name: '--force', takesValue: false },\n { name: '--tty', takesValue: false },\n { name: '-t', takesValue: false },\n { name: '--no-rpc', takesValue: false },\n { name: '-x', takesValue: false },\n { name: '--cwd', takesValue: true, valueType: 'free' },\n { name: '--env', takesValue: true, valueType: 'free' },\n { name: '--readiness', takesValue: true, valueType: 'free' },\n ],\n },\n {\n name: 'connect', description: 'Connect an existing endpoint.', positionals: [],\n options: [\n { name: '--id', takesValue: true, valueType: 'free' },\n { name: '--persistent', takesValue: false },\n { name: '--restart', takesValue: true, valueType: 'free' },\n { name: '--force', takesValue: false },\n { name: '--target-endpoint', takesValue: true, valueType: 'free' },\n ],\n },\n { name: 'list', description: 'List managed endpoints.', positionals: [], options: [{ name: '--all-contexts', takesValue: false }] },\n ...['start', 'stop', 'remove', 'attach', 'logs', 'configure'].map((name): SubcommandDef => ({\n name, description: `${name} a managed endpoint.`, positionals: [],\n options: [\n { name: '--id', takesValue: true, valueType: 'free' },\n ...(name === 'logs' ? [{ name: '--follow', takesValue: false }] : []),\n ...(name === 'attach' ? [{ name: '--read-only', takesValue: false }] : []),\n ...(name === 'configure' ? [\n { name: '--persistent', takesValue: false },\n { name: '--no-persistent', takesValue: false },\n { name: '--restart', takesValue: true, valueType: 'free' as const },\n ] : []),\n ],\n })),\n ],\n },\n {\n name: 'caps',\n description: 'List stored capabilities or request access for a call.',\n positionals: [],\n options: [],\n subcommands: [\n {\n name: 'list',\n description: 'List stored capabilities.',\n positionals: [],\n options: [{ name: '--json', takesValue: false }],\n },\n {\n name: 'request',\n description: 'Request a capability without executing a call.',\n positionals: [{ name: 'methodRef', type: 'methodRef' }],\n options: [\n { name: '--params', takesValue: true, valueType: 'free' },\n { name: '--param', takesValue: true, valueType: 'free' },\n { name: '--no-validate', takesValue: false },\n ...CAPABILITY_OPTIONS,\n ],\n },\n ],\n },\n {\n name: 'topology',\n description: 'Inspect the merged transport topology.',\n positionals: [],\n options: [\n { name: '--source', takesValue: true, valueType: 'serviceId' },\n { name: '--depth', takesValue: true, valueType: 'free' },\n { name: '--node', takesValue: true, valueType: 'free' },\n { name: '--service', takesValue: true, valueType: 'serviceId' },\n { name: '--kind', takesValue: true, valueType: 'free' },\n { name: '--search', takesValue: true, valueType: 'free' },\n { name: '--format', takesValue: true, valueType: 'free' },\n { name: '--json', takesValue: false },\n { name: '--stream', takesValue: false },\n { name: '--watch', takesValue: false },\n ],\n subcommands: [{\n name: 'participants',\n description: 'List participant nodes.',\n positionals: [],\n options: [\n { name: '--search', takesValue: true, valueType: 'free' },\n { name: '--json', takesValue: false },\n ],\n }],\n },\n {\n name: 'traffic',\n description: 'Observe participant traffic.',\n positionals: [],\n options: [],\n subcommands: [{\n name: 'watch',\n description: 'Watch node-wide traffic.',\n positionals: [],\n options: [\n { name: '--search', takesValue: true, valueType: 'free' },\n { name: '--node', takesValue: true, valueType: 'free' },\n { name: '--method', takesValue: true, valueType: 'free' },\n { name: '--payloads', takesValue: true, valueType: 'free' },\n { name: '--format', takesValue: true, valueType: 'free' },\n { name: '--resume', takesValue: true, valueType: 'free' },\n ],\n }],\n },\n {\n name: 'identity',\n description: 'Inspect the persistent principal used by connected CLI commands.',\n positionals: [],\n options: [],\n subcommands: [{\n name: 'show',\n description: 'Show the resolved principal.',\n positionals: [],\n options: [{ name: '--json', takesValue: false }],\n }],\n },\n {\n name: 'approval',\n description: 'Inspect and decide pending Hub access approval requests.',\n positionals: [],\n options: [],\n subcommands: [\n {\n name: 'requests',\n description: 'List pending requests.',\n positionals: [],\n options: [{ name: '--json', takesValue: false }],\n },\n {\n name: 'approve',\n description: 'Approve a pending request.',\n positionals: [{ name: 'request-id', type: 'free' }],\n options: [{ name: '--json', takesValue: false }],\n },\n {\n name: 'deny',\n description: 'Deny a pending request.',\n positionals: [{ name: 'request-id', type: 'free' }],\n options: [\n { name: '--reason', takesValue: true, valueType: 'free' },\n { name: '--json', takesValue: false },\n ],\n },\n { name: 'ui', description: 'Open the approval UI.', positionals: [], options: [] },\n ],\n },\n {\n name: 'serve',\n description: 'Run a configured hub.',\n positionals: [{ name: 'config', type: 'free' }],\n options: [\n { name: '--print-schema', takesValue: false },\n { name: '--cmd-interactive', takesValue: false },\n ],\n },\n {\n name: 'tunnel',\n description: 'Claim a serviceId on the source hub and forward to a target.',\n positionals: [{ name: 'serviceId', type: 'serviceId' }],\n options: [\n { name: '--target-endpoint', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-cmd', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-cmd-stdio', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-cmd-env', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-cmd-cwd', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-token', takesValue: true, valueType: 'free' },\n ],\n },\n {\n name: 'connect-as',\n description: 'Mint a slot identity from a connectionTokenBinder service and splice a target onto the hub as that slot.',\n positionals: [\n { name: 'binderServiceId', type: 'serviceId' },\n { name: 'slot', type: 'free' },\n ],\n options: [\n { name: '--hub-endpoint', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-cmd', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-cmd-stdio', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-cmd-env', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-cmd-cwd', takesValue: true, valueType: 'free' },\n { name: '--target-endpoint-token', takesValue: true, valueType: 'free' },\n { name: '--granted-service-id', takesValue: true, valueType: 'serviceId' },\n ],\n },\n {\n name: 'mcp-forward',\n description: 'Expose an MCP server through the hub.',\n positionals: [],\n variadic: 'free',\n options: [\n { name: '--serviceId', takesValue: true, valueType: 'serviceId' },\n { name: '--env', takesValue: true, valueType: 'free' },\n ],\n },\n {\n name: 'logout',\n description: 'Delete the stored CLI identity.',\n positionals: [],\n options: [],\n },\n];\n\nexport const HUB_COMMAND_TREE: CommandTree = {\n globalOptions: HUB_GLOBAL_OPTIONS,\n subcommands: [...SHARED_COMMANDS, ...HUB_ONLY_COMMANDS],\n};\n\nexport const RPC_COMMAND_TREE: CommandTree = {\n globalOptions: ENDPOINT_GLOBAL_OPTIONS,\n subcommands: [\n ...SHARED_COMMANDS,\n {\n name: 'hub',\n description: 'Use the hub profile.',\n positionals: [],\n options: [{ name: '--config', takesValue: true, valueType: 'free' }],\n subcommands: [...SHARED_COMMANDS, ...HUB_ONLY_COMMANDS],\n },\n ],\n};\n\n/** Hub-profile tree retained as the default for direct resolver consumers. */\nexport const COMMAND_TREE = HUB_COMMAND_TREE;\n\n/**\n * Look up a flag by its long-form name from the leaf command through its\n * ancestors, then from the global options.\n */\nexport function findFlag(\n name: string,\n commandPath: readonly SubcommandDef[],\n tree: CommandTree,\n): FlagDef | undefined {\n const eq = name.indexOf('=');\n const flagName = eq >= 0 ? name.slice(0, eq) : name;\n for (let index = commandPath.length - 1; index >= 0; index--) {\n const flag = commandPath[index].options.find((option) => option.name === flagName);\n if (flag !== undefined) return flag;\n }\n return tree.globalOptions.find((option) => option.name === flagName);\n}\n","/**\n * Slot resolution: given the tokens before the cursor, figure out *what kind\n * of thing* the user is about to type next (a subcommand name, a flag name,\n * a flag value of some known type, or a positional of some known type).\n *\n * Pure function — no I/O. The orchestrator in {@link ./complete.ts} consumes\n * the resulting slot and either looks up static candidates (flag/subcommand\n * names) or queries the hub via a {@link DirectorySource}.\n */\nimport type { ParsedLine } from './parse';\nimport { type CommandTree, type FlagDef, findFlag, type SlotType, type SubcommandDef } from './tree';\n\nexport type Slot =\n | { readonly kind: 'subcommand'; readonly parent: SubcommandDef | undefined }\n | { readonly kind: 'flag-name'; readonly subcommand: SubcommandDef | undefined }\n | { readonly kind: 'flag-value'; readonly flag: FlagDef; readonly subcommand: SubcommandDef | undefined }\n | {\n readonly kind: 'positional';\n readonly type: SlotType;\n readonly subcommand: SubcommandDef;\n readonly index: number;\n }\n | { readonly kind: 'none' };\n\nexport interface ResolvedContext {\n readonly slot: Slot;\n /** Subcommand parsed from the tokens (undefined if none seen yet). */\n readonly subcommand: SubcommandDef | undefined;\n /** Selected commands from the root command through the active leaf. */\n readonly commandPath: readonly SubcommandDef[];\n /**\n * Flags already present on the line that take a value, paired with their\n * value (or `undefined` if the value followed in the next token).\n * Useful for extracting `--endpoint` etc. without re-parsing.\n */\n readonly seenFlagValues: ReadonlyMap<string, string | undefined>;\n /**\n * Positional values already typed (after the subcommand). Indexed\n * positionally — `seenPositionals[0]` is the first positional, etc.\n * Used to plumb e.g. the `methodRef` of `call <methodRef>` through to\n * dynamic completion for `--p:<name>` flags.\n */\n readonly seenPositionals: readonly string[];\n}\n\n/**\n * Walk the tokens before the cursor, tracking subcommand selection, current\n * positional index, and whether the next token is the value for a flag.\n * Returns the slot the cursor itself is in plus the surrounding context.\n */\nexport function resolveSlot(parsed: ParsedLine, tree: CommandTree): ResolvedContext {\n const tokens = parsed.tokensBefore;\n let subcommand: SubcommandDef | undefined;\n const commandPath: SubcommandDef[] = [];\n let positionalIndex = 0;\n let expectingValueFor: FlagDef | undefined;\n const seenFlagValues = new Map<string, string | undefined>();\n const seenPositionals: string[] = [];\n\n // tokens[0] is the binary name (`hub` / `linkrpc`). Skip it.\n for (let i = 1; i < tokens.length; i++) {\n const t = tokens[i].text;\n\n if (expectingValueFor !== undefined) {\n seenFlagValues.set(expectingValueFor.name, t);\n expectingValueFor = undefined;\n continue;\n }\n\n if (t.startsWith('-') && t.length > 1) {\n const eq = t.indexOf('=');\n const flagName = eq >= 0 ? t.slice(0, eq) : t;\n const flag = findFlag(flagName, commandPath, tree);\n if (flag?.takesValue) {\n if (eq >= 0) {\n seenFlagValues.set(flag.name, t.slice(eq + 1));\n } else {\n expectingValueFor = flag;\n }\n } else if (flag) {\n seenFlagValues.set(flag.name, undefined);\n }\n continue;\n }\n\n // Command or positional.\n if (subcommand === undefined) {\n const sub = tree.subcommands.find((s) => s.name === t);\n if (!sub) {\n // Unknown subcommand — abandon resolution.\n return {\n slot: { kind: 'none' },\n subcommand: undefined,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n subcommand = sub;\n commandPath.push(sub);\n positionalIndex = 0;\n } else if (subcommand.subcommands !== undefined && seenPositionals.length === 0) {\n const child = subcommand.subcommands.find((candidate) => candidate.name === t);\n if (child === undefined) {\n if (subcommand.positionals.length === 0 && subcommand.variadic === undefined) {\n return {\n slot: { kind: 'none' },\n subcommand,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n seenPositionals.push(t);\n positionalIndex++;\n continue;\n }\n subcommand = child;\n commandPath.push(child);\n positionalIndex = 0;\n seenPositionals.length = 0;\n } else {\n seenPositionals.push(t);\n positionalIndex++;\n }\n }\n\n const word = parsed.currentWordPrefix;\n\n if (expectingValueFor !== undefined) {\n return {\n slot: { kind: 'flag-value', flag: expectingValueFor, subcommand },\n subcommand,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n\n if (word.startsWith('-')) {\n const eq = word.indexOf('=');\n if (eq >= 0) {\n // `--foo=<value>`: still a flag-value slot, but only if `--foo`\n // exists and takes a value. Otherwise treat as flag-name (the\n // user might be mid-type).\n const flag = findFlag(word.slice(0, eq), commandPath, tree);\n if (flag?.takesValue) {\n return {\n slot: { kind: 'flag-value', flag, subcommand },\n subcommand,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n }\n return {\n slot: { kind: 'flag-name', subcommand },\n subcommand,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n\n if (subcommand === undefined) {\n return {\n slot: { kind: 'subcommand', parent: undefined },\n subcommand: undefined,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n\n if (subcommand.subcommands !== undefined && seenPositionals.length === 0) {\n const childMatches = subcommand.subcommands.some((child) =>\n child.name.startsWith(word));\n if (\n word.length > 0\n && !childMatches\n && subcommand.positionals[positionalIndex] !== undefined\n ) {\n const positional = subcommand.positionals[positionalIndex];\n return {\n slot: {\n kind: 'positional',\n type: positional.type,\n subcommand,\n index: positionalIndex,\n },\n subcommand,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n return {\n slot: { kind: 'subcommand', parent: subcommand },\n subcommand,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n\n const positional = subcommand.positionals[positionalIndex];\n if (positional !== undefined) {\n return {\n slot: { kind: 'positional', type: positional.type, subcommand, index: positionalIndex },\n subcommand,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n if (subcommand.variadic !== undefined) {\n return {\n slot: { kind: 'positional', type: subcommand.variadic, subcommand, index: positionalIndex },\n subcommand,\n commandPath,\n seenFlagValues,\n seenPositionals,\n };\n }\n return { slot: { kind: 'none' }, subcommand, commandPath, seenFlagValues, seenPositionals };\n}\n","import type { CliProfile } from './invocationContext';\n\nexport interface CliInvocation {\n readonly argv: readonly string[];\n readonly profile: CliProfile;\n readonly programName: string;\n}\n\nconst INHERITED_OPTIONS_WITH_VALUE = new Set([\n '--endpoint',\n '--endpoint-cmd',\n '--endpoint-cmd-stdio',\n '--endpoint-cmd-env',\n '--endpoint-token',\n '--endpoint-cmd-cwd',\n '--config',\n '-c',\n '--provision-identity-slot',\n '--principal',\n '--context',\n '--new-context',\n '--schema',\n '--validation',\n]);\n\nconst LEGACY_COMMANDS: Readonly<Record<string, readonly string[]>> = {\n connect: ['connection', 'create'],\n 'connection-status': ['connection', 'status'],\n notifications: ['connection', 'notifications'],\n disconnect: ['connection', 'destroy'],\n hash: ['schema', 'hash'],\n 'check-compat': ['schema', 'check-compat'],\n};\n\nconst SCHEMA_SUBCOMMANDS = new Set(['show', 'hash', 'check-compat', 'help']);\n\nexport function resolveCliInvocation(\n rawArgv: readonly string[],\n executablePath: string | undefined,\n): CliInvocation {\n const executable = normalizeCliExecutable(executablePath);\n let profile: CliProfile = executable === 'hub' ? 'hub' : 'rpc';\n let argv = [...rawArgv];\n let commandIndex = findCommandIndex(argv);\n\n if (profile === 'rpc' && commandIndex !== undefined && argv[commandIndex] === 'hub') {\n argv.splice(commandIndex, 1);\n profile = 'hub';\n commandIndex = findCommandIndex(argv);\n }\n\n if (commandIndex !== undefined) {\n const command = argv[commandIndex];\n const replacement = LEGACY_COMMANDS[command];\n if (replacement !== undefined) {\n argv.splice(commandIndex, 1, ...replacement);\n } else if (command === 'schema') {\n const schemaMemberIndex = findCommandIndex(argv, commandIndex + 1);\n const schemaMember = schemaMemberIndex === undefined ? undefined : argv[schemaMemberIndex];\n if (schemaMember !== undefined && !SCHEMA_SUBCOMMANDS.has(schemaMember)) {\n argv.splice(commandIndex + 1, 0, 'show');\n }\n }\n }\n\n const baseName = executable === 'hub' ? 'hub' : executable === 'rpc' ? 'rpc' : 'linkrpc';\n return {\n argv,\n profile,\n programName: profile === 'hub' && executable !== 'hub'\n ? `${baseName} hub`\n : baseName,\n };\n}\n\nexport function normalizeCliExecutable(executablePath: string | undefined): string {\n if (executablePath === undefined) return 'linkrpc';\n return (executablePath.split(/[\\\\/]/).pop() ?? executablePath)\n .replace(/\\.(?:cmd|exe|js|mjs|cjs)$/i, '');\n}\n\nfunction findCommandIndex(argv: readonly string[], start = 0): number | undefined {\n for (let index = start; index < argv.length; index++) {\n const arg = argv[index];\n if (arg === '--') return undefined;\n if (arg.startsWith('--') && arg.includes('=')) continue;\n if (INHERITED_OPTIONS_WITH_VALUE.has(arg)) {\n index++;\n continue;\n }\n if (arg.startsWith('-')) continue;\n return index;\n }\n return undefined;\n}\n","/**\n * Top-level completion orchestrator. Takes a command line + cursor position,\n * resolves what's being completed, and returns the candidate list. The\n * resolver is the only thing that needs to be wire-aware (subcommand /\n * positional / flag / flag-value); everything past that is either a static\n * filter against the {@link CommandTree} or a query against a\n * {@link DirectorySource}.\n */\nimport {\n distinctInterfaceIds,\n distinctServiceIds,\n interfacesOnService,\n type DirectorySource,\n} from './directorySource';\nimport { parseLine } from './parse';\nimport { resolveSlot, type ResolvedContext, type Slot } from './resolve';\nimport { normalizeCliExecutable } from '../cliInvocation';\nimport {\n HUB_COMMAND_TREE,\n RPC_COMMAND_TREE,\n type CommandTree,\n type SlotType,\n} from './tree';\n\nexport interface Completion {\n /** Text to replace the current word with. */\n readonly text: string;\n /** Tooltip / second-line detail (e.g. method signature). */\n readonly tooltip?: string;\n}\n\nexport interface CompleteOptions {\n readonly line: string;\n readonly point: number;\n readonly tree?: CommandTree;\n /**\n * Source of dynamic candidates. Omit to skip dynamic lookups entirely\n * (only static completions returned) — useful when no hub is configured.\n */\n readonly directory?: DirectorySource;\n}\n\nconst SHELLS: readonly string[] = ['powershell', 'bash', 'zsh', 'fish'];\n\n/**\n * Resolve completion candidates for the cursor at `point` in `line`.\n *\n * The slot kinds returned by {@link resolveSlot} map to:\n * - `subcommand` / `flag-name` / static-typed `flag-value` / static-typed\n * `positional` → filter against the {@link CommandTree}\n * - `flag-value` / `positional` with a dynamic slot type → call into\n * `directory` (skipped when `directory` is `undefined`)\n * - `flag-name` under `call`/`notify` with a methodRef typed → adds\n * `--p:<name>` shortcuts for the live params\n * - `none` → empty\n *\n * Candidates are always prefix-filtered so the caller (PowerShell) can\n * enumerate the result as-is. The output is sorted and de-duplicated.\n */\nexport async function complete(opts: CompleteOptions): Promise<Completion[]> {\n const parsed = parseLine(opts.line, opts.point);\n const executable = normalizeCliExecutable(parsed.tokensBefore[0]?.text);\n const tree = opts.tree\n ?? (executable === 'hub' ? HUB_COMMAND_TREE : RPC_COMMAND_TREE);\n const ctx = resolveSlot(parsed, tree);\n const prefix = parsed.currentWordPrefix;\n\n const stat = _staticCandidates(ctx, prefix, tree);\n const dyn = opts.directory\n ? await _dynamicCandidates(ctx, prefix, opts.directory)\n : [];\n\n const seen = new Set<string>();\n const merged: Completion[] = [];\n for (const c of [...stat, ...dyn]) {\n if (seen.has(c.text)) continue;\n seen.add(c.text);\n merged.push(c);\n }\n return merged.sort((a, b) => (a.text < b.text ? -1 : a.text > b.text ? 1 : 0));\n}\n\nfunction _staticCandidates(ctx: ResolvedContext, prefix: string, tree: CommandTree): Completion[] {\n const slot = ctx.slot;\n if (slot.kind === 'subcommand') {\n return (slot.parent?.subcommands ?? tree.subcommands)\n .filter((s) => !s.hidden && s.name.startsWith(prefix))\n .map((s) => ({ text: s.name, tooltip: s.description }));\n }\n if (slot.kind === 'flag-name') {\n const flags = [\n ...ctx.commandPath.flatMap((command) => command.options),\n ...tree.globalOptions,\n ];\n const eq = prefix.indexOf('=');\n const lookupPrefix = eq >= 0 ? prefix.slice(0, eq) : prefix;\n return flags\n .filter((f) => f.name.startsWith(lookupPrefix))\n .map((f) => ({ text: f.name, tooltip: f.description }));\n }\n if (slot.kind === 'flag-value' || slot.kind === 'positional') {\n const type: SlotType = slot.kind === 'flag-value' ? (slot.flag.valueType ?? 'free') : slot.type;\n if (type === 'shell') {\n return SHELLS.filter((s) => s.startsWith(prefix)).map((s) => ({ text: s }));\n }\n if (type === 'connectionLimit' && 'inf'.startsWith(prefix)) {\n return [{ text: 'inf', tooltip: 'Unlimited (no timer).' }];\n }\n }\n return [];\n}\n\nasync function _dynamicCandidates(\n ctx: ResolvedContext,\n prefix: string,\n dir: DirectorySource,\n): Promise<Completion[]> {\n const slot = ctx.slot;\n\n // Offer parameter shortcuts after a method-reference positional.\n // Triggers on flag-name slots (user typed `-...`) AND on the\n // post-positional gap (slot `none`) so an empty TAB after the methodRef\n // still surfaces the param flags.\n const inFlagOrEmptySlot = slot.kind === 'flag-name'\n || (slot.kind === 'none' && (prefix === '' || prefix.startsWith('-')));\n if (inFlagOrEmptySlot\n && ctx.subcommand?.positionals[0]?.type === 'methodRef'\n && ctx.seenPositionals.length >= 1) {\n const methodRef = ctx.seenPositionals[0];\n const ref = _parseMethodRefForCompletion(methodRef);\n if (ref !== undefined && ref.interfaceId !== undefined) {\n const names = await _safeParams(dir, ref.serviceId, ref.interfaceId, ref.methodName);\n return names\n .map((n) => `--p:${n}`)\n .filter((c) => c.startsWith(prefix))\n .map((c) => ({ text: c, tooltip: `method param: ${c.slice('--p:'.length)}` }));\n }\n }\n\n let type: SlotType | undefined;\n if (slot.kind === 'flag-value') type = slot.flag.valueType;\n else if (slot.kind === 'positional') type = slot.type;\n if (!type) return [];\n\n if (type === 'serviceId') {\n const entries = await dir.entries();\n return distinctServiceIds(entries)\n .filter((s) => s.startsWith(prefix))\n .map((s) => ({ text: s }));\n }\n if (type === 'interfaceId' || type === 'interfaceRef') {\n const entries = await dir.entries();\n return distinctInterfaceIds(entries)\n .filter((i) => i.startsWith(prefix))\n .map((i) => ({ text: i }));\n }\n if (type === 'methodRef') {\n return _completeMethodRef(prefix, dir);\n }\n return [];\n}\n\n/**\n * Complete a `[serviceId::][interfaceId::]methodName[@hash]` reference. The\n * three forms are disambiguated by how many `::` the prefix contains so far.\n * Each TAB-cycle is a complete word (no trailing `::`) — the user adds the\n * next separator themselves to drill in. That keeps PowerShell's TAB-cycle\n * advancing through peer candidates instead of re-stalling on a separator.\n *\n * 0 sep: `vscode.window` → serviceIds + root-hosted interfaceIds\n * (NOT service-bound interfaces, since\n * calling them bare won't route)\n * 1 sep: `azure-cli::Runner` → if `azure-cli` is a serviceId, suggest\n * `azure-cli::<iface>`; if it's also a\n * root interfaceId, suggest its methods\n * (form-2). Skip form-2 entirely when\n * `azure-cli` isn't root-hosted — fetching\n * a schema for any typed string would\n * spam the hub on every keystroke.\n * 2 sep: `azure-cli::Runner::g` → method names on (serviceId, interfaceId)\n */\nasync function _completeMethodRef(prefix: string, dir: DirectorySource): Promise<Completion[]> {\n const parts = prefix.split('::');\n const seps = parts.length - 1;\n const entries = await dir.entries();\n const sids = distinctServiceIds(entries);\n const rootInterfaceIds = new Set(\n entries.filter((e) => e.serviceId === '').map((e) => e.interfaceId),\n );\n\n if (seps === 0) {\n const out: Completion[] = [];\n for (const sid of sids) {\n if (sid.startsWith(prefix)) out.push({ text: sid, tooltip: `service ${sid}` });\n }\n for (const iid of [...rootInterfaceIds].sort()) {\n if (iid.startsWith(prefix)) out.push({ text: iid, tooltip: `interface ${iid}` });\n }\n return out;\n }\n\n if (seps === 1) {\n const [first] = parts;\n const out: Completion[] = [];\n\n if (sids.includes(first)) {\n for (const iid of interfacesOnService(entries, first)) {\n const c = `${first}::${iid}`;\n if (c.startsWith(prefix)) out.push({ text: c, tooltip: `${first} :: ${iid}` });\n }\n }\n // Form-2 (`<interfaceId>::<method>`) only makes sense when `first`\n // is actually a root-reachable interface — fetching schemas for\n // arbitrary typed strings would hit the hub on every TAB.\n if (rootInterfaceIds.has(first)) {\n const formTwoMethods = await _safeMethods(dir, undefined, first);\n for (const m of formTwoMethods) {\n const c = `${first}::${m}`;\n if (c.startsWith(prefix)) out.push({ text: c, tooltip: `${first} :: ${m}` });\n }\n }\n return out;\n }\n\n if (seps === 2) {\n const [sid, iid] = parts;\n const methods = await _safeMethods(dir, sid, iid);\n return methods\n .map((m) => `${sid}::${iid}::${m}`)\n .filter((c) => c.startsWith(prefix))\n .map((c) => ({ text: c }));\n }\n\n return [];\n}\n\nasync function _safeMethods(\n dir: DirectorySource,\n serviceId: string | undefined,\n interfaceId: string,\n): Promise<readonly string[]> {\n try {\n return await dir.methodsOnInterface(serviceId, interfaceId);\n } catch {\n return [];\n }\n}\n\nasync function _safeParams(\n dir: DirectorySource,\n serviceId: string | undefined,\n interfaceId: string,\n methodName: string,\n): Promise<readonly string[]> {\n try {\n return await dir.paramNamesForMethod(serviceId, interfaceId, methodName);\n } catch {\n return [];\n }\n}\n\n/**\n * Parse `[serviceId::][interfaceId::]methodName[@hash]` enough to look up\n * the method's params. Returns `undefined` for unrecognized shapes so the\n * orchestrator can skip the dynamic call. Independent of\n * `MethodRefWithOptHash` to keep the completions module dependency-free.\n */\nfunction _parseMethodRefForCompletion(\n raw: string,\n): { serviceId: string | undefined; interfaceId: string | undefined; methodName: string } | undefined {\n if (raw.length === 0) return undefined;\n // Strip optional `@<hash>` suffix.\n const at = raw.lastIndexOf('@');\n const core = at >= 0 && !raw.slice(at + 1).includes('::') ? raw.slice(0, at) : raw;\n const parts = core.split('::');\n if (parts.some((p) => p.length === 0)) return undefined;\n if (parts.length === 1) return { serviceId: undefined, interfaceId: undefined, methodName: parts[0] };\n if (parts.length === 2) return { serviceId: undefined, interfaceId: parts[0], methodName: parts[1] };\n if (parts.length === 3) return { serviceId: parts[0], interfaceId: parts[1], methodName: parts[2] };\n return undefined;\n}\n","/**\n * File-backed JSON cache for the directory snapshot + per-interface method\n * lists. Keyed by a stable identifier of the target hub (typically the\n * resolved endpoint URI sha) so TAB completion against different endpoints\n * doesn't share state.\n *\n * Cache lives under `os.tmpdir()/linkrpc-completions/`. I/O failures are\n * silently absorbed — the wrapper falls through to the inner source rather\n * than failing the completion request.\n */\nimport { createHash } from 'node:crypto';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport type { DirectoryEntry, DirectorySource } from './directorySource';\n\n/** TTL for the bus snapshot (services + interfaces). */\nconst SNAPSHOT_TTL_MS = 60_000;\n\n/** TTL for per-interface method lists (schemas change rarely). */\nconst METHODS_TTL_MS = 5 * 60_000;\n\nconst CACHE_DIR = path.join(os.tmpdir(), 'linkrpc-completions');\n\ninterface CachedSnapshot {\n readonly ts: number;\n readonly entries: readonly DirectoryEntry[];\n readonly methods: Record<string, { readonly ts: number; readonly names: readonly string[] }>;\n readonly params?: Record<string, { readonly ts: number; readonly names: readonly string[] }>;\n}\n\n/**\n * Wrap `inner` with a JSON-file cache scoped to `endpointKey`. Reads the\n * cache file once at construction; refills the bus snapshot lazily on the\n * first `entries()` call when the cache is missing or stale.\n */\nexport function withFileCache(inner: DirectorySource, endpointKey: string): DirectorySource {\n const file = _cacheFile(endpointKey);\n let cached = _loadFresh(file);\n\n let entriesPromise: Promise<readonly DirectoryEntry[]> | undefined;\n const ensureEntries = (): Promise<readonly DirectoryEntry[]> => {\n if (cached !== undefined) return Promise.resolve(cached.entries);\n if (!entriesPromise) {\n entriesPromise = inner.entries().then((entries) => {\n cached = { ts: Date.now(), entries, methods: {} };\n _save(file, cached);\n return entries;\n });\n }\n return entriesPromise;\n };\n\n return {\n entries: ensureEntries,\n async methodsOnInterface(serviceId, interfaceId) {\n const key = `${serviceId ?? ''}::${interfaceId}`;\n if (cached && cached.methods[key]) {\n const entry = cached.methods[key];\n if (Date.now() - entry.ts <= METHODS_TTL_MS) return entry.names;\n }\n const names = await inner.methodsOnInterface(serviceId, interfaceId);\n if (cached) {\n cached = {\n ...cached,\n methods: { ...cached.methods, [key]: { ts: Date.now(), names: [...names] } },\n };\n _save(file, cached);\n }\n return names;\n },\n async paramNamesForMethod(serviceId, interfaceId, methodName) {\n const key = `${serviceId ?? ''}::${interfaceId}::${methodName}`;\n if (cached && cached.params && cached.params[key]) {\n const entry = cached.params[key];\n if (Date.now() - entry.ts <= METHODS_TTL_MS) return entry.names;\n }\n const names = await inner.paramNamesForMethod(serviceId, interfaceId, methodName);\n if (cached) {\n const params = { ...(cached.params ?? {}), [key]: { ts: Date.now(), names: [...names] } };\n cached = { ...cached, params };\n _save(file, cached);\n }\n return names;\n },\n };\n}\n\nfunction _loadFresh(file: string): CachedSnapshot | undefined {\n try {\n const raw = fs.readFileSync(file, 'utf8');\n const parsed = JSON.parse(raw) as CachedSnapshot | null;\n if (!parsed || typeof parsed.ts !== 'number' || !Array.isArray(parsed.entries)) {\n return undefined;\n }\n if (Date.now() - parsed.ts > SNAPSHOT_TTL_MS) return undefined;\n return parsed;\n } catch {\n return undefined;\n }\n}\n\nfunction _save(file: string, snap: CachedSnapshot): void {\n try {\n fs.mkdirSync(CACHE_DIR, { recursive: true });\n fs.writeFileSync(file, JSON.stringify(snap));\n } catch {\n // Cache writes are best-effort; never propagate.\n }\n}\n\nfunction _cacheFile(endpointKey: string): string {\n const hash = createHash('sha256').update(endpointKey).digest('hex').slice(0, 16);\n return path.join(CACHE_DIR, `${hash}.json`);\n}\n","const DURATION_PATTERN = /^(\\d+)(ms|s|m|min|h)$/;\n\nexport type ConnectionLimit = number | \"inf\";\n\nexport function parseConnectionLimit(value: string): ConnectionLimit {\n return validateConnectionLimit(value === \"inf\" ? value : parseDuration(value));\n}\n\nexport function parseConnectionLimitMilliseconds(value: string): ConnectionLimit {\n if (value === \"inf\") return value;\n if (!/^\\d+$/.test(value)) {\n throw new Error(`invalid connection limit '${value}' (expected milliseconds or inf)`);\n }\n return validateConnectionLimit(Number(value));\n}\n\nexport function validateConnectionLimit(value: ConnectionLimit): ConnectionLimit {\n if (value !== \"inf\" && (!Number.isSafeInteger(value) || value <= 0 || value > 2_147_483_647)) {\n throw new Error(\"connection limit must be inf or between 1 and 2147483647 milliseconds\");\n }\n return value;\n}\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 {\n ErrorCode,\n type LinkRpcInterfaceSchema,\n type IncomingCall,\n type IRequestSender,\n type JsonValue,\n type ChannelResult as Result,\n RpcError,\n} from '@hediet/linkrpc';\nimport type {\n StaticHubSchema,\n StaticInterfaceReference,\n} from '../staticHubSchema';\n\nconst DIRECTORY_INTERFACE_ID = 'hubrpc.directory';\nconst SCHEMAS_INTERFACE_ID = 'hubrpc.schemas';\nconst DEFAULTS_INTERFACE_ID = 'hubrpc.defaults';\n\nconst DIRECTORY_LIST_METHOD = `${DIRECTORY_INTERFACE_ID}::list`;\nconst DIRECTORY_WATCH_METHOD = `${DIRECTORY_INTERFACE_ID}::watch`;\nconst SCHEMAS_GET_METHOD = `${SCHEMAS_INTERFACE_ID}::get`;\nconst DEFAULTS_GET_METHOD = `${DEFAULTS_INTERFACE_ID}::get`;\n\ninterface DirectoryItem {\n readonly serviceId: string;\n readonly interfaceId: string;\n readonly interfaceHash: string;\n readonly tags?: readonly string[];\n}\n\nexport class StaticHubReflection {\n private readonly _directory: readonly DirectoryItem[];\n private readonly _schemasByKey = new Map<string, LinkRpcInterfaceSchema>();\n private readonly _activeHashesById = new Map<string, Set<string>>();\n private readonly _hashesByServiceInterface = new Map<string, Set<string>>();\n\n constructor(private readonly _schema: StaticHubSchema) {\n this._directory = (_schema.services ?? []).flatMap((service) =>\n service.interfaces.map((ref) => ({\n serviceId: service.serviceId,\n interfaceId: ref.interfaceId,\n interfaceHash: ref.interfaceHash,\n tags: _schema.interfaceSchemas.find(schema => schema.id === ref.interfaceId && schema.hash === ref.interfaceHash)?.tags,\n })));\n for (const schema of _schema.interfaceSchemas) {\n this._schemasByKey.set(interfaceKey(schema.id, schema.hash), schema);\n }\n for (const item of this._directory) {\n const hashes = this._activeHashesById.get(item.interfaceId) ?? new Set<string>();\n hashes.add(item.interfaceHash);\n this._activeHashesById.set(item.interfaceId, hashes);\n const serviceKey = interfaceKey(item.serviceId, item.interfaceId);\n const serviceHashes = this._hashesByServiceInterface.get(serviceKey) ?? new Set<string>();\n serviceHashes.add(item.interfaceHash);\n this._hashesByServiceInterface.set(serviceKey, serviceHashes);\n }\n if (_schema.defaultInterface !== undefined) {\n const ref = _schema.defaultInterface;\n const hashes = this._activeHashesById.get(ref.interfaceId) ?? new Set<string>();\n hashes.add(ref.interfaceHash);\n this._activeHashesById.set(ref.interfaceId, hashes);\n }\n for (const { interface: ref } of _schema.bareInterfaces ?? []) {\n const hashes = this._activeHashesById.get(ref.interfaceId) ?? new Set<string>();\n hashes.add(ref.interfaceHash);\n this._activeHashesById.set(ref.interfaceId, hashes);\n }\n }\n\n public tryHandleRequest(call: IncomingCall): Promise<Result> | undefined {\n return this.tryHandle(call.method, call.params, call.signal);\n }\n\n public tryHandle(\n method: string,\n params: JsonValue | undefined,\n signal: AbortSignal,\n ): Promise<Result> | undefined {\n const reflectionCall = parseReflectionMethod(method);\n if (reflectionCall === undefined) {\n return undefined;\n }\n switch (reflectionCall.method) {\n case `${DEFAULTS_INTERFACE_ID}::listBindings`:\n return Promise.resolve({\n result: { bindings: (this._schema.bareInterfaces ?? []).map((binding) => ({\n prefix: binding.prefix,\n ...binding.interface,\n })) },\n });\n case DIRECTORY_LIST_METHOD:\n return Promise.resolve(this._listDirectory(params));\n case DIRECTORY_WATCH_METHOD:\n return this._watchDirectory(params, signal);\n case SCHEMAS_GET_METHOD:\n return Promise.resolve(this._getSchema(params, reflectionCall.serviceId));\n case DEFAULTS_GET_METHOD:\n return Promise.resolve({\n result: this._schema.defaultInterface === undefined\n ? {}\n : {\n interfaceId: this._schema.defaultInterface.interfaceId,\n interfaceHash: this._schema.defaultInterface.interfaceHash,\n },\n });\n default:\n return Promise.resolve(methodNotFound(method));\n }\n }\n\n private _listDirectory(params: JsonValue | undefined): Result {\n const parsed = parseDirectoryParams(params);\n if ('error' in parsed || 'result' in parsed) return parsed;\n\n const filtered = this._directory\n .filter((item) =>\n parsed.interfaceId === undefined || item.interfaceId === parsed.interfaceId)\n .filter((item) =>\n parsed.serviceId === undefined || item.serviceId === parsed.serviceId);\n const start = parsed.cursor ?? 0;\n if (start > filtered.length) {\n return invalidParams('directory cursor is outside the result set');\n }\n const end = parsed.limit === undefined\n ? filtered.length\n : Math.min(filtered.length, start + parsed.limit);\n return {\n result: {\n items: filtered.slice(start, end).map(({ serviceId, interfaceId, interfaceHash, tags }) => ({\n serviceId,\n interfaceId,\n interfaceHash,\n ...(tags === undefined ? {} : { tags: [...tags] }),\n })),\n ...(end < filtered.length ? { nextCursor: String(end) } : {}),\n },\n };\n }\n\n private _watchDirectory(params: JsonValue | undefined, signal: AbortSignal): Promise<Result> {\n const parsed = parseDirectoryParams(params, false);\n if ('error' in parsed || 'result' in parsed) return Promise.resolve(parsed);\n return new Promise<Result>((resolve) => {\n const done = (): void => resolve({ result: {} });\n if (signal.aborted) {\n done();\n return;\n }\n signal.addEventListener('abort', done, { once: true });\n });\n }\n\n private _getSchema(params: JsonValue | undefined, serviceId: string | undefined): Result {\n if (!isRecord(params)) {\n return invalidParams('schemas.get params must be an object');\n }\n const interfaceId = params.interfaceId;\n const hash = params.hash;\n if (typeof interfaceId !== 'string' || interfaceId.length === 0) {\n return invalidParams('schemas.get interfaceId must be a non-empty string');\n }\n if (hash !== undefined && typeof hash !== 'string') {\n return invalidParams('schemas.get hash must be a string');\n }\n\n let resolvedHash = hash;\n if (resolvedHash === undefined) {\n const active = serviceId === undefined\n ? [...(this._activeHashesById.get(interfaceId) ?? [])]\n : [\n ...(this._hashesByServiceInterface.get(interfaceKey(serviceId, interfaceId))\n ?? []),\n ];\n if (active.length !== 1) {\n return {\n error: {\n code: ErrorCode.methodNotFound,\n message: `Interface not found: ${interfaceId}`,\n data: { reason: 'unknown-interface', interfaceId },\n },\n };\n }\n resolvedHash = active[0];\n }\n const schema = this._schemasByKey.get(interfaceKey(interfaceId, resolvedHash));\n if (schema === undefined) {\n return {\n error: {\n code: ErrorCode.methodNotFound,\n message: `Interface not found: ${interfaceId}@${resolvedHash}`,\n data: {\n reason: 'unknown-interface',\n interfaceId,\n hash: resolvedHash,\n },\n },\n };\n }\n return { result: { schema } as unknown as JsonValue };\n }\n}\n\nexport function withStaticHubReflection<TContext>(\n sender: IRequestSender<TContext>,\n schema: StaticHubSchema,\n): IRequestSender<TContext> {\n const reflection = new StaticHubReflection(schema);\n const handle = (\n method: string,\n params: JsonValue | undefined,\n signal: AbortSignal,\n ): Promise<JsonValue> | undefined => {\n const result = reflection.tryHandle(method, params, signal);\n return result?.then(unwrapResult);\n };\n return {\n sendRequest: (method, params, opts) =>\n handle(method, params, new AbortController().signal)\n ?? sender.sendRequest(method, params, opts),\n sendNotification: (method, params, opts) =>\n sender.sendNotification(method, params, opts),\n sendRequestWithStream: (method, params, opts) => {\n const controller = new AbortController();\n const result = handle(method, params, controller.signal);\n if (result === undefined) {\n return sender.sendRequestWithStream(method, params, opts);\n }\n return {\n result,\n send: () => { },\n cancel: () => controller.abort(),\n dispose: () => controller.abort(),\n ping: () => Promise.resolve(),\n };\n },\n close: () => sender.close(),\n };\n}\n\nfunction unwrapResult(result: Result): JsonValue {\n if ('error' in result) {\n throw new RpcError(result.error.message, result.error.code, result.error.data);\n }\n return result.result;\n}\n\nfunction parseDirectoryParams(\n params: JsonValue | undefined,\n allowPagination = true,\n): {\n interfaceId?: string;\n serviceId?: string;\n cursor?: number;\n limit?: number;\n} | Result {\n if (params === undefined) return {};\n if (!isRecord(params)) {\n return invalidParams('directory params must be an object');\n }\n const interfaceId = optionalString(params.interfaceId);\n if (interfaceId === false) return invalidParams('directory interfaceId must be a string');\n const serviceId = optionalString(params.serviceId);\n if (serviceId === false) return invalidParams('directory serviceId must be a string');\n\n const result: {\n interfaceId?: string;\n serviceId?: string;\n cursor?: number;\n limit?: number;\n } = {\n ...(interfaceId === undefined ? {} : { interfaceId }),\n ...(serviceId === undefined ? {} : { serviceId }),\n };\n if (!allowPagination) return result;\n\n if (params.cursor !== undefined) {\n if (typeof params.cursor !== 'string' || !/^(0|[1-9]\\d*)$/.test(params.cursor)) {\n return invalidParams('directory cursor must be a non-negative integer string');\n }\n result.cursor = Number(params.cursor);\n }\n if (params.limit !== undefined) {\n if (\n typeof params.limit !== 'number'\n || !Number.isSafeInteger(params.limit)\n || params.limit <= 0\n ) {\n return invalidParams('directory limit must be a positive integer');\n }\n result.limit = params.limit;\n }\n return result;\n}\n\nfunction parseReflectionMethod(\n method: string,\n): { readonly method: string; readonly serviceId: string | undefined; } | undefined {\n const parts = method.split('::');\n const candidate = parts.length === 2\n ? method\n : parts.length === 3\n ? `${parts[1]}::${parts[2]}`\n : undefined;\n if (\n candidate?.startsWith(`${DIRECTORY_INTERFACE_ID}::`)\n || candidate?.startsWith(`${SCHEMAS_INTERFACE_ID}::`)\n || candidate?.startsWith(`${DEFAULTS_INTERFACE_ID}::`)\n ) {\n return {\n method: candidate,\n serviceId: parts.length === 3 ? parts[0] : undefined,\n };\n }\n return undefined;\n}\n\nfunction methodNotFound(method: string): Result {\n return {\n error: {\n code: ErrorCode.methodNotFound,\n message: `Unknown static reflection method: ${method}`,\n },\n };\n}\n\nfunction invalidParams(message: string): Result {\n return {\n error: {\n code: ErrorCode.invalidParams,\n message,\n },\n };\n}\n\nfunction optionalString(value: JsonValue | undefined): string | undefined | false {\n if (value === undefined) return undefined;\n return typeof value === 'string' ? value : false;\n}\n\nfunction interfaceKey(interfaceId: string, interfaceHash: string): string {\n return `${interfaceId}\\0${interfaceHash}`;\n}\n\nfunction isRecord(value: JsonValue | undefined): value is Record<string, JsonValue> {\n return value !== undefined\n && value !== null\n && typeof value === 'object'\n && !Array.isArray(value);\n}\n","import {\n ErrorCode,\n type IncomingCall,\n type IRequestHandler,\n type JsonValue,\n RpcError,\n type SigningCallCtx,\n} from '@hediet/linkrpc';\nimport { hubGrantedServiceIdInterface } from '@hediet/linkrpc/hub/common';\nimport { hubServiceIdRegistryInterface } from '@hediet/linkrpc/hub/common';\nimport type { CliConnection } from '@hediet/linkrpc-client-internal';\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\n/**\n * How calls the participant emits reach the hub:\n * - `signed`: re-sent under the proxy's own principal (managed identity +\n * capability negotiation), so an unsigned participant can call gated\n * services.\n * - `verbatim`: forwarded unsigned, preserving any `$hubrpc` envelope the\n * participant attached itself.\n * - `none`: not forwarded.\n */\nexport type OutboundForwarding = 'signed' | 'verbatim' | 'none';\n\nexport interface ProxyOptions {\n /** Live connection to the hub. Outbound `signed` calls use its signer. */\n readonly hub: CliConnection;\n /** Live connection to the participant the proxy stands in for. */\n readonly participant: CliConnection;\n /** Claim this service id on the hub and forward its requests verbatim to the participant. */\n readonly claimServiceId?: string;\n readonly outbound: OutboundForwarding;\n /**\n * Resolves to stop the proxy (e.g. when the participant disconnects). When\n * omitted, the proxy 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 * Stand in for a participant on the hub until stopped.\n *\n * Requests the hub routes to this connection (e.g. for\n * {@link ProxyOptions.claimServiceId}) are forwarded verbatim to the\n * participant: the original caller's `$hubrpc` envelope rides inside `params`,\n * so it is not re-wrapped. Calls the participant emits are forwarded to the hub\n * according to {@link ProxyOptions.outbound}. The streaming sub-protocol is\n * bridged both ways, so long-running / streaming calls forward their in-flight\n * stream messages and cancellation, not just the final response.\n */\nexport async function proxyCommand(opts: ProxyOptions): Promise<void> {\n const log = opts.log ?? ((line) => process.stderr.write(line + '\\n'));\n\n // Bind the catch-all forwarders BEFORE claiming so no request can race in\n // between the claim landing and the handler being installed.\n opts.hub.setRequestHandler(createForwardingHandler(opts.participant));\n if (opts.outbound !== 'none') {\n opts.participant.setRequestHandler(createForwardingHandler(opts.hub, opts.outbound));\n }\n\n if (opts.claimServiceId !== undefined) {\n await _claimServiceId(opts.hub, opts.claimServiceId);\n log(`proxy: claimed '${opts.claimServiceId}' — forwarding its requests to the participant unchanged`);\n }\n log({\n signed: 'proxy: forwarding participant calls to the hub, signed as the identity above',\n verbatim: 'proxy: forwarding participant calls to the hub as they are (not signed by the proxy)',\n none: 'proxy: dropping participant calls',\n }[opts.outbound]);\n\n await (opts.stop ?? _untilSignalled());\n log('proxy: stopping');\n}\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: a {@link proxyCommand} that\n * claims `serviceId` and, with `bidi`, forwards the endpoint's calls verbatim.\n */\nexport async function tunnelCommand(opts: TunnelOptions): Promise<void> {\n await proxyCommand({\n hub: opts.local,\n participant: opts.remote,\n claimServiceId: opts.serviceId,\n outbound: opts.bidi ? 'verbatim' : 'none',\n ...(opts.stop !== undefined ? { stop: opts.stop } : {}),\n ...(opts.log !== undefined ? { log: opts.log } : {}),\n });\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}). `signing` selects whether forwarded calls are\n * sent verbatim (default) or signed by `to`'s signer.\n */\nexport function createForwardingHandler(\n to: CliConnection,\n signing: Exclude<OutboundForwarding, 'none'> = 'verbatim',\n): IRequestHandler {\n // `signerOverride: null` forwards verbatim: an inbound `$hubrpc` envelope\n // (if any) is preserved instead of being re-signed.\n const ctx: SigningCallCtx = signing === 'verbatim' ? { signerOverride: null } : {};\n return {\n handleRequest: (call) => _forwardRequest(to, call, ctx),\n handleNotification: (call) => _forwardNotification(to, call, ctx),\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 ctx: SigningCallCtx,\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 const rc = remote.channel.sendRequestWithStream(call.method, call.params, {\n ctx,\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, ctx: SigningCallCtx): void {\n void remote.channel\n .sendNotification(call.method, call.params, { ctx })\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-internal\";\nimport type { StaticHubSchema } from \"../staticHubSchema\";\nimport { validateConnectionLimit, type ConnectionLimit } from \"../duration\";\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: ConnectionLimit;\n readonly ttlMs: ConnectionLimit;\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 validateConnectionLimit(_options.timeoutMs);\n validateConnectionLimit(_options.ttlMs);\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 if (this._options.ttlMs !== \"inf\") {\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\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 if (this._options.timeoutMs === \"inf\") return;\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 { withRpcTimeout, type JsonValue } from \"@hediet/linkrpc\";\nimport { connect, type CliChannel, type CliConnection } from \"@hediet/linkrpc-client-internal\";\nimport { parseEndpointUri } from \"@hediet/linkrpc/node\";\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 const call = channel.sendRequestWithStream(BROKER_DISCONNECT_METHOD, {});\n await withRpcTimeout(Object.assign(call.result, {\n cancel: (reason?: string) => call.cancel(reason),\n dispose: (reason?: string) => call.dispose?.(reason),\n }), BROKER_DISCONNECT_METHOD);\n}\n\nexport async function stopConnectionBroker(endpoint: string, allowMissing = false): Promise<void> {\n const parsed = parseEndpointUri(endpoint);\n if (parsed.kind !== \"socket\" || parsed.token === undefined || parsed.brokerMode === undefined) {\n throw new Error(\"owned connection must be an authenticated local broker endpoint\");\n }\n let connection: CliConnection;\n try {\n connection = await connect(parsed);\n } catch (error) {\n if (\n allowMissing\n && error instanceof Error\n && \"code\" in error\n && (error.code === \"ENOENT\" || error.code === \"ECONNREFUSED\")\n && \"syscall\" in error\n && error.syscall === \"connect\"\n ) {\n return;\n }\n throw error;\n }\n try {\n await disconnectBroker(connection.channel);\n } finally {\n connection.close();\n }\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 { chmod, mkdir, open, readFile, realpath, rename, stat, unlink, writeFile } from 'node:fs/promises';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport { stopConnectionBroker } from './commands/connectionBrokerClient';\n\nexport type ValidationMode = 'auto' | 'required' | 'off';\n\nexport interface ContextValues {\n readonly daemonService?: string;\n /** TTY console detach sequence in Docker syntax, e.g. `ctrl-b,d`. */\n readonly detachKeys?: string;\n readonly namespace?: string;\n readonly endpoint?: string;\n readonly endpointCmd?: string;\n readonly endpointCmdStdio?: string;\n readonly endpointCmdEnv?: Readonly<Record<string, string>>;\n readonly endpointToken?: string;\n readonly endpointCmdCwd?: string;\n readonly config?: string;\n readonly provisionIdentity?: boolean;\n readonly provisionIdentitySlot?: string;\n readonly principal?: string;\n readonly sign?: boolean;\n readonly schema?: string;\n readonly validation?: ValidationMode;\n readonly connectionTimeout?: string;\n readonly connectionTtl?: string;\n readonly notificationLimit?: number;\n}\n\nexport type ContextReference =\n | { readonly kind: 'empty'; }\n | { readonly kind: 'root'; }\n | { readonly kind: 'id'; readonly id: string; }\n | { readonly kind: 'path'; readonly path: string; };\n\nexport interface StoredContext {\n readonly key: string;\n readonly reference: Exclude<ContextReference, { readonly kind: 'empty'; }>;\n readonly values: ContextValues;\n readonly ownedConnection?: { readonly endpoint: string };\n readonly createdAt: string;\n readonly updatedAt: string;\n}\n\nexport interface SelectedContext {\n readonly reference: ContextReference;\n readonly context: StoredContext | undefined;\n readonly selectedBy: 'argument' | 'environment' | 'cwd' | 'root' | 'empty';\n readonly explicitlySelected: boolean;\n}\n\ninterface ContextDocument {\n readonly version: 1;\n readonly contexts: readonly StoredContext[];\n}\n\nexport interface ContextStoreOptions {\n readonly file?: string;\n readonly cwd?: string;\n}\n\nexport class ContextStore {\n private readonly _file: string;\n private readonly _cwd: string;\n\n public constructor(options: ContextStoreOptions = {}) {\n this._file = options.file ?? defaultContextStoreFile();\n this._cwd = path.resolve(options.cwd ?? process.cwd());\n }\n\n public get file(): string {\n return this._file;\n }\n\n public async select(options: {\n readonly selector?: string;\n readonly environmentSelector?: string;\n readonly allowMissing?: boolean;\n } = {}): Promise<SelectedContext> {\n const contexts = await this._read();\n if (options.selector !== undefined) {\n const reference = await this.resolveReference(options.selector);\n return this._selectedReference(\n contexts,\n reference,\n 'argument',\n true,\n options.allowMissing === true,\n );\n }\n if (options.environmentSelector !== undefined && options.environmentSelector !== '') {\n const reference = await this.resolveReference(options.environmentSelector);\n return this._selectedReference(\n contexts,\n reference,\n 'environment',\n false,\n options.allowMissing === true,\n );\n }\n\n let cursor = await canonicalDirectory(this._cwd);\n while (true) {\n const reference = normalizeContextReference({ kind: 'path', path: cursor });\n const context = contexts.get(contextKey(reference));\n if (context !== undefined) {\n return {\n reference,\n context,\n selectedBy: reference.kind === 'root' ? 'root' : 'cwd',\n explicitlySelected: false,\n };\n }\n const parent = path.dirname(cursor);\n if (parent === cursor) break;\n cursor = parent;\n }\n\n // The root context always exists: without stored defaults it is empty.\n return {\n reference: ROOT_REFERENCE,\n context: contexts.get(contextKey(ROOT_REFERENCE)) ?? implicitRootContext(),\n selectedBy: 'root',\n explicitlySelected: false,\n };\n }\n\n public async resolveReference(selector: string): Promise<ContextReference> {\n if (selector === ':empty') return { kind: 'empty' };\n if (selector === ':root') return { kind: 'root' };\n if (selector.startsWith('id:')) {\n const id = selector.slice('id:'.length);\n if (id.length === 0) {\n throw new Error('context selector \"id:\" requires a non-empty id');\n }\n return { kind: 'id', id };\n }\n if (selector.startsWith(':')) {\n throw new Error(\n `unknown context selector \"${selector}\" (expected a folder, id:<name>, :root, or :empty)`,\n );\n }\n const folder = path.resolve(this._cwd, selector);\n return normalizeContextReference({\n kind: 'path',\n path: await canonicalDirectory(folder),\n });\n }\n\n public async set(\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n values: ContextValues,\n options: { readonly createOnly?: boolean } = {},\n ): Promise<StoredContext> {\n reference = normalizeContextReference(reference);\n return this._mutate((contexts) => {\n const key = contextKey(reference);\n const existing = contexts.get(key);\n if (options.createOnly === true) assertCreatable(reference, existing);\n const now = new Date().toISOString();\n const mergedValues = existing === undefined\n ? normalizeContextValues(values)\n : mergeContextValues(existing.values, values);\n const context: StoredContext = {\n key,\n reference,\n values: mergedValues,\n ...retainedOwnership(existing, mergedValues),\n createdAt: existing?.createdAt ?? now,\n updatedAt: now,\n };\n contexts.set(key, context);\n return { value: context, changed: true };\n });\n }\n\n public async assertCanCreate(\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n ): Promise<void> {\n reference = normalizeContextReference(reference);\n assertCreatable(reference, (await this._read()).get(contextKey(reference)));\n }\n\n public async replace(\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n values: ContextValues,\n options: {\n readonly createOnly?: boolean;\n readonly ownedConnection?: StoredContext['ownedConnection'];\n } = {},\n ): Promise<StoredContext> {\n if (options.ownedConnection !== undefined && options.createOnly !== true) {\n throw new Error('connection ownership can only be assigned to a new context');\n }\n reference = normalizeContextReference(reference);\n return this._mutate((contexts) => {\n const key = contextKey(reference);\n const existing = contexts.get(key);\n if (options.createOnly === true) assertCreatable(reference, existing);\n const now = new Date().toISOString();\n const context: StoredContext = {\n key,\n reference,\n values: normalizeContextValues(values),\n ...(options.ownedConnection === undefined\n ? retainedOwnership(existing, values)\n : { ownedConnection: options.ownedConnection }),\n createdAt: existing?.createdAt ?? now,\n updatedAt: now,\n };\n contexts.set(key, context);\n return { value: context, changed: true };\n });\n }\n\n public async unset(\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n keys: readonly (keyof ContextValues)[],\n ): Promise<StoredContext> {\n reference = normalizeContextReference(reference);\n return this._mutate((contexts) => {\n const key = contextKey(reference);\n const existing = contexts.get(key) ?? (reference.kind === 'root' ? implicitRootContext() : undefined);\n if (existing === undefined) {\n throw missingContextError(reference);\n }\n const values = { ...existing.values } as Record<keyof ContextValues, unknown>;\n for (const item of keys) delete values[item];\n const { ownedConnection: _ownedConnection, ...rest } = existing;\n const context: StoredContext = {\n ...rest,\n values: normalizeContextValues(values as ContextValues),\n ...retainedOwnership(existing, values as ContextValues),\n updatedAt: new Date().toISOString(),\n };\n contexts.set(key, context);\n return { value: context, changed: true };\n });\n }\n\n /**\n * Remove a stored context. The root context always exists, so removing it\n * resets it to no stored defaults; that always succeeds.\n */\n public async remove(reference: ContextReference): Promise<boolean> {\n if (reference.kind === 'empty') {\n throw new Error(':empty is immutable and cannot be removed');\n }\n reference = normalizeContextReference(reference);\n const isRoot = reference.kind === 'root';\n return this._mutate((contexts) => {\n const removed = contexts.delete(contextKey(reference));\n return { value: removed || isRoot, changed: removed };\n });\n }\n\n public async list(): Promise<readonly StoredContext[]> {\n return [...(await this._read()).values()].sort((a, b) =>\n formatContextReference(a.reference).localeCompare(formatContextReference(b.reference)));\n }\n\n private _selectedReference(\n contexts: ReadonlyMap<string, StoredContext>,\n reference: ContextReference,\n selectedBy: SelectedContext['selectedBy'],\n explicitlySelected: boolean,\n allowMissing: boolean,\n ): SelectedContext {\n if (reference.kind === 'empty') {\n return { reference, context: undefined, selectedBy, explicitlySelected };\n }\n const context = contexts.get(contextKey(reference))\n ?? (reference.kind === 'root' ? implicitRootContext() : undefined);\n if (context === undefined && !allowMissing) {\n throw missingContextError(reference);\n }\n return { reference, context, selectedBy, explicitlySelected };\n }\n\n private async _read(): Promise<Map<string, StoredContext>> {\n let text: string;\n try {\n text = await readFile(this._file, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return new Map();\n throw error;\n }\n const value = JSON.parse(text) as Partial<ContextDocument>;\n if (value.version !== 1 || !Array.isArray(value.contexts)) {\n throw new Error(`invalid context store ${this._file}`);\n }\n const contexts = new Map<string, StoredContext>();\n for (const raw of value.contexts) {\n const context = parseStoredContext(raw);\n if (contexts.has(context.key)) {\n throw new Error(`duplicate context key \"${context.key}\" in ${this._file}`);\n }\n contexts.set(context.key, context);\n }\n return contexts;\n }\n\n private async _write(contexts: ReadonlyMap<string, StoredContext>): Promise<void> {\n await mkdir(path.dirname(this._file), { recursive: true });\n const document: ContextDocument = {\n version: 1,\n contexts: [...contexts.values()],\n };\n const temporary = `${this._file}.${process.pid}.${randomUUID()}.tmp`;\n await writeFile(temporary, JSON.stringify(document, undefined, 2) + '\\n', { mode: 0o600 });\n await rename(temporary, this._file);\n if (process.platform !== 'win32') await chmod(this._file, 0o600);\n }\n\n private async _mutate<T>(\n update: (contexts: Map<string, StoredContext>) => {\n readonly value: T;\n readonly changed: boolean;\n },\n ): Promise<T> {\n const release = await acquireContextStoreLock(this._file);\n try {\n const contexts = await this._read();\n const previous = new Map(contexts);\n const result = update(contexts);\n if (result.changed) {\n for (const [key, existing] of previous) {\n if (existing.ownedConnection === undefined) continue;\n const next = contexts.get(key);\n if (\n next?.ownedConnection?.endpoint === existing.ownedConnection.endpoint\n ) {\n continue;\n }\n try {\n await stopConnectionBroker(existing.ownedConnection.endpoint, true);\n } catch (error) {\n throw new Error(\n `failed to stop connection owned by context ${formatContextReference(existing.reference)}; context was not changed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n }\n await this._write(contexts);\n }\n return result.value;\n } finally {\n await release();\n }\n }\n}\n\nconst ROOT_REFERENCE: ContextReference = { kind: 'root' };\n\n/** The root context when it has no stored defaults: it always exists. */\nfunction implicitRootContext(): StoredContext {\n return { key: contextKey(ROOT_REFERENCE), reference: { kind: 'root' }, values: {}, createdAt: '', updatedAt: '' };\n}\n\nfunction assertCreatable(reference: ContextReference, existing: StoredContext | undefined): void {\n if (reference.kind === 'root') {\n throw new Error('The root context always exists; change its defaults with: hub context set --context :root <flags>');\n }\n if (existing !== undefined) throw new Error(`context ${formatContextReference(reference)} already exists`);\n}\n\nfunction retainedOwnership(\n existing: StoredContext | undefined,\n b: ContextValues,\n): Pick<StoredContext, 'ownedConnection'> {\n const a = existing?.values;\n return existing?.ownedConnection !== undefined\n && a !== undefined\n && a.endpoint === b.endpoint\n && a.endpointToken === b.endpointToken\n && a.endpointCmd === b.endpointCmd\n && a.endpointCmdStdio === b.endpointCmdStdio\n && a.config === b.config\n ? { ownedConnection: existing.ownedConnection }\n : {};\n}\n\nexport function mergeContextValues(\n base: ContextValues,\n overrides: ContextValues,\n): ContextValues {\n const result: Record<string, unknown> = { ...base };\n const endpointSelectors = ([\n ['endpoint', overrides.endpoint],\n ['endpointCmd', overrides.endpointCmd],\n ['endpointCmdStdio', overrides.endpointCmdStdio],\n ] as const).filter((entry) => entry[1] !== undefined);\n if (endpointSelectors.length === 1) {\n delete result.endpoint;\n delete result.endpointCmd;\n delete result.endpointCmdStdio;\n const selector = endpointSelectors[0][0];\n if (selector === 'endpoint') {\n delete result.endpointCmdEnv;\n delete result.endpointCmdCwd;\n delete result.provisionIdentity;\n delete result.provisionIdentitySlot;\n const endpoint = overrides.endpoint;\n if (\n overrides.endpointToken === undefined\n && endpoint !== undefined\n && !/(?:[?&])token=%(?:[&#]|$)/.test(endpoint)\n ) {\n delete result.endpointToken;\n }\n } else {\n delete result.endpointToken;\n if (selector === 'endpointCmdStdio') {\n delete result.provisionIdentity;\n delete result.provisionIdentitySlot;\n }\n }\n }\n for (const [key, value] of Object.entries(overrides)) {\n if (value !== undefined) result[key] = value;\n }\n return normalizeContextValues(result as ContextValues);\n}\n\nasync function acquireContextStoreLock(file: string): Promise<() => Promise<void>> {\n const lockFile = `${file}.lock`;\n const deadline = Date.now() + 5_000;\n await mkdir(path.dirname(file), { recursive: true });\n while (true) {\n try {\n const handle = await open(lockFile, 'wx', 0o600);\n try {\n await handle.writeFile(`${process.pid}\\n${new Date().toISOString()}\\n`);\n } catch (error) {\n await handle.close();\n await unlink(lockFile);\n throw error;\n }\n return async () => {\n await handle.close();\n try {\n await unlink(lockFile);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n\n try {\n const lockInfo = await stat(lockFile);\n if (Date.now() - lockInfo.mtimeMs > 30_000) {\n await unlink(lockFile);\n continue;\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;\n throw error;\n }\n if (Date.now() >= deadline) {\n throw new Error(`timed out waiting for context store lock ${lockFile}`);\n }\n await new Promise((resolve) => setTimeout(resolve, 25));\n }\n}\n\nfunction missingContextError(reference: ContextReference): Error {\n const selector = JSON.stringify(formatContextReference(reference));\n return new Error(`context ${formatContextReference(reference)} does not exist. Create it with --new-context ${selector} instead of --context ${selector}, or run: hub context --new-context ${selector}`);\n}\n\nexport function contextKey(reference: ContextReference): string {\n reference = normalizeContextReference(reference);\n switch (reference.kind) {\n case 'empty': return ':empty';\n case 'root': return ':root';\n case 'id': return `id:${reference.id}`;\n case 'path': {\n const normalized = path.normalize(reference.path);\n return `path:${process.platform === 'win32' ? normalized.toLowerCase() : normalized}`;\n }\n }\n}\n\nexport function formatContextReference(reference: ContextReference): string {\n reference = normalizeContextReference(reference);\n switch (reference.kind) {\n case 'empty': return ':empty';\n case 'root': return ':root';\n case 'id': return `id:${reference.id}`;\n case 'path': return reference.path;\n }\n}\n\nexport function defaultContextStoreFile(): string {\n const home = os.homedir();\n if (process.platform === 'win32') {\n return path.join(\n process.env.APPDATA ?? path.join(home, 'AppData', 'Roaming'),\n 'linkrpc',\n 'contexts.json',\n );\n }\n if (process.platform === 'darwin') {\n return path.join(home, 'Library', 'Application Support', 'linkrpc', 'contexts.json');\n }\n return path.join(\n process.env.XDG_CONFIG_HOME ?? path.join(home, '.config'),\n 'linkrpc',\n 'contexts.json',\n );\n}\n\nasync function canonicalDirectory(folder: string): Promise<string> {\n let info;\n try {\n info = await stat(folder);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n throw new Error(`context folder does not exist: ${folder}`);\n }\n throw error;\n }\n if (!info.isDirectory()) {\n throw new Error(`context path is not a directory: ${folder}`);\n }\n return path.normalize(await realpath(folder));\n}\n\nfunction normalizeContextReference(\n reference: Exclude<ContextReference, { readonly kind: 'empty'; }>,\n): Exclude<ContextReference, { readonly kind: 'empty'; }>;\nfunction normalizeContextReference(reference: ContextReference): ContextReference;\nfunction normalizeContextReference(reference: ContextReference): ContextReference {\n if (\n process.platform !== 'win32'\n && reference.kind === 'path'\n && path.parse(path.normalize(reference.path)).root === path.normalize(reference.path)\n ) {\n return { kind: 'root' };\n }\n return reference;\n}\n\nfunction normalizeContextValues(values: ContextValues): ContextValues {\n if (values.sign !== undefined && typeof values.sign !== 'boolean') {\n throw new Error('context sign must be a boolean');\n }\n return JSON.parse(JSON.stringify(values)) as ContextValues;\n}\n\nfunction parseStoredContext(value: unknown): StoredContext {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new Error('invalid context entry');\n }\n const raw = value as Partial<StoredContext>;\n if (\n typeof raw.key !== 'string'\n || typeof raw.createdAt !== 'string'\n || typeof raw.updatedAt !== 'string'\n || typeof raw.reference !== 'object'\n || raw.reference === null\n || typeof raw.values !== 'object'\n || raw.values === null\n ) {\n throw new Error('invalid context entry');\n }\n const reference = raw.reference as ContextReference;\n if (\n reference.kind === 'empty'\n || !['root', 'id', 'path'].includes(reference.kind)\n || (reference.kind === 'id' && typeof reference.id !== 'string')\n || (reference.kind === 'path' && typeof reference.path !== 'string')\n ) {\n throw new Error('invalid context reference');\n }\n if (raw.key !== contextKey(reference)) {\n throw new Error(`context key mismatch for ${formatContextReference(reference)}`);\n }\n if (raw.ownedConnection !== undefined && (\n typeof raw.ownedConnection !== 'object'\n || raw.ownedConnection === null\n || typeof raw.ownedConnection.endpoint !== 'string'\n )) {\n throw new Error('invalid context connection ownership');\n }\n return {\n key: raw.key,\n reference,\n values: normalizeContextValues(raw.values),\n ...(raw.ownedConnection === undefined ? {} : { ownedConnection: raw.ownedConnection }),\n createdAt: raw.createdAt,\n updatedAt: raw.updatedAt,\n };\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { z } from 'zod';\n\n/**\n * How to reach one daemon endpoint. The daemon writes one file for\n * applications ({@link HubHome.discoveryFile}) and one for management\n * ({@link HubHome.managementFile}); both are private to the user.\n */\nexport const EndpointDiscoverySchema = z.object({\n version: z.literal(1),\n pid: z.number().int(),\n /** Named pipe (Windows) or Unix socket path. */\n endpoint: z.string().min(1),\n /** Absent when the endpoint requires no token. */\n token: z.string().min(1).optional(),\n});\nexport type EndpointDiscovery = z.infer<typeof EndpointDiscoverySchema>;\n\n/** The published endpoint, or `undefined` when absent or unreadable. */\nexport function readEndpointDiscovery(file: string): EndpointDiscovery | undefined {\n let text: string;\n try {\n text = fs.readFileSync(file, 'utf8');\n } catch {\n return undefined;\n }\n try {\n const parsed = EndpointDiscoverySchema.safeParse(JSON.parse(text));\n return parsed.success ? parsed.data : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Atomically write a JSON file readable only by the current user. */\nexport function writePrivateJson(file: string, value: unknown): void {\n fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });\n const tmp = `${file}.${process.pid}.tmp`;\n fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\\n', { mode: 0o600 });\n fs.renameSync(tmp, file);\n}\n","/**\n * The persisted call-log record and its filter. Schema-only (no Node.js APIs)\n * so management clients and UIs can share it.\n */\nimport { logLevelSchema } from '@hediet/linkrpc-infra/logging';\nimport { z } from 'zod';\nimport { CallQuery } from './callQuery';\n\n/** `linkrpc.logging` levels. A threshold records calls at or above it. */\nexport const CallLogLevelSchema = z.enum(logLevelSchema.options);\nexport type CallLogLevel = z.infer<typeof CallLogLevelSchema>;\n\n/**\n * The level of a recorded call: failures are `error`, requests `info`,\n * notifications `debug`, and stream frames reported apart from their request\n * `trace`. `warn` records the same calls as `error`.\n */\nexport const CallRecordLevelSchema = z.enum(['error', 'info', 'debug', 'trace']);\nexport type CallRecordLevel = z.infer<typeof CallRecordLevelSchema>;\n\n/** One side of a call at the hub: the port's friendly label and its transport. */\nexport const CallPeerSchema = z.object({\n /** The port's claimed prefix (e.g. `hediet/devbox`) or an edge id (`e12`). */\n label: z.string(),\n /** E.g. `named-pipe \\\\.\\pipe\\linkrpc-hub-user` or `websocket 10.0.0.2:51234`. */\n transport: z.string().optional(),\n /** The configured daemon service connected through this port, e.g. `devtunnel`. */\n service: z.string().optional(),\n});\nexport type CallPeer = z.infer<typeof CallPeerSchema>;\n\n/**\n * One NDJSON line. A call still in flight is written as `pending` and written\n * again under the same `id` when it settles; readers keep the newest record per id.\n */\nexport const CallRecordSchema = z.object({\n v: z.literal(1),\n id: z.string(),\n /** Start, epoch ms. */\n at: z.number(),\n level: CallRecordLevelSchema,\n kind: z.enum(['request', 'notification', 'stream']),\n status: z.enum(['pending', 'completed', 'failed', 'unroutable', 'dropped']),\n durationMs: z.number(),\n /** The wire method, e.g. `hediet/pc2/compute::linkrpc.compute::exec`. */\n method: z.string(),\n serviceId: z.string().optional(),\n /** Where the call entered the hub. */\n from: CallPeerSchema,\n /** Where the hub forwarded it; absent when the hub consumed or dropped it. */\n to: CallPeerSchema.optional(),\n /** `$hubrpc.principal` of a signed call; verified when the hub checks forwarded calls. */\n principal: z.string().optional(),\n error: z.object({ code: z.number(), message: z.string() }).optional(),\n /** UTF-8 size of the application params (without `$hubrpc*` meta). */\n paramsBytes: z.number().int().optional(),\n resultBytes: z.number().int().optional(),\n /** Redacted and truncated per the `callLog.payloads` policy; absent for `mode: \"none\"`. */\n params: z.unknown().optional(),\n result: z.unknown().optional(),\n /** Stream frames folded into this record (frames shortly after the request starts). */\n streamFrames: z.number().int().optional(),\n});\nexport type CallRecord = z.infer<typeof CallRecordSchema>;\n\nexport const CallFilterSchema = z.object({\n /** A {@link CallQuery}: space-separated terms, `-term` to exclude, `method:<glob>` for methods. */\n text: z.string().optional(),\n /** Only records at or above this level, e.g. `error` for failures. */\n minLevel: CallRecordLevelSchema.optional(),\n /** Start time bounds, epoch ms (inclusive). */\n since: z.number().optional(),\n until: z.number().optional(),\n});\nexport type CallFilter = z.infer<typeof CallFilterSchema>;\n\nconst SEVERITY: Readonly<Record<CallLogLevel, number>> = { trace: 0, debug: 1, info: 2, warn: 3, error: 4, off: 5 };\n\n/** Whether a record at `level` is recorded or shown at `threshold`. */\nexport function isCallLevelEnabled(level: CallRecordLevel, threshold: CallLogLevel): boolean {\n return SEVERITY[level] >= SEVERITY[threshold];\n}\n\n/** Parses `filter` once; the result tests records against it. */\nexport function createCallMatcher(filter: CallFilter): (record: CallRecord) => boolean {\n const query = filter.text ? CallQuery.parse(filter.text) : undefined;\n return record => {\n if (filter.minLevel !== undefined && !isCallLevelEnabled(record.level, filter.minLevel)) return false;\n if (filter.since !== undefined && record.at < filter.since) return false;\n if (filter.until !== undefined && record.at > filter.until) return false;\n return query?.matches(record) ?? true;\n };\n}\n","import { defineInterface, requestType } from '@hediet/linkrpc';\nimport { z } from 'zod';\nimport { CallFilterSchema, CallLogLevelSchema, CallRecordSchema } from './callLog/callRecord';\n\nexport const ServiceStateSchema = z.enum([\n /** `enabled: false` in the config. */\n 'disabled',\n /** Exited without a pending restart. */\n 'stopped',\n /** Spawned, waiting for readiness (hub connection or spawn). */\n 'starting',\n 'running',\n /** Exited; restarting after a delay. */\n 'backoff',\n 'stopping',\n /** Exited abnormally and the restart policy gave up. */\n 'failed',\n]);\nexport type ServiceState = z.infer<typeof ServiceStateSchema>;\n\nexport const ServiceStatusSchema = z.object({\n name: z.string(),\n description: z.string().optional(),\n /** Namespace the service may claim on the hub. */\n serviceId: z.string(),\n enabled: z.boolean(),\n state: ServiceStateSchema,\n /** Epoch ms of the last state change. */\n since: z.number(),\n pid: z.number().int().optional(),\n /** Open hub connections of this service. */\n connections: z.number().int(),\n /** Restarts since the service was (re)configured. */\n restarts: z.number().int(),\n lastExit: z.object({\n code: z.number().int().nullable(),\n signal: z.string().nullable(),\n at: z.number(),\n }).optional(),\n error: z.string().optional(),\n});\nexport type ServiceStatus = z.infer<typeof ServiceStatusSchema>;\n\nexport const DaemonStatusSchema = z.object({\n pid: z.number().int(),\n version: z.string(),\n startedAt: z.number(),\n /** Application endpoint (named pipe or Unix socket). */\n endpoint: z.string(),\n configFile: z.string(),\n logFile: z.string(),\n config: z.object({\n /** Revision of the applied config file. */\n revision: z.string().optional(),\n appliedAt: z.number().optional(),\n /** Why the current file is not applied; the previous config keeps running. */\n error: z.string().optional(),\n }),\n hub: z.object({\n startedAt: z.number(),\n listeners: z.array(z.object({ type: z.string(), address: z.string() })),\n error: z.string().optional(),\n }),\n callLog: z.object({\n level: CallLogLevelSchema,\n /** Directory of the NDJSON call-log files. */\n directory: z.string(),\n /** Where the log is served as `linkrpc.logging` while the hub runs. */\n serviceId: z.string().optional(),\n error: z.string().optional(),\n }),\n services: z.array(ServiceStatusSchema),\n});\nexport type DaemonStatus = z.infer<typeof DaemonStatusSchema>;\n\nexport const LogLineSchema = z.object({\n at: z.number(),\n stream: z.enum(['stdout', 'stderr', 'daemon']),\n text: z.string(),\n});\nexport type LogLine = z.infer<typeof LogLineSchema>;\n\nexport const ConfigDocumentSchema = z.object({\n path: z.string(),\n text: z.string(),\n /** Opaque content revision; pass it back to `setConfig`. */\n revision: z.string(),\n});\nexport type ConfigDocument = z.infer<typeof ConfigDocumentSchema>;\n\n/** Management API of the local hub daemon, served on its management endpoint. */\nexport const hubDaemonManagementInterface = defineInterface(\n { id: 'linkrpc.hubDaemon', description: 'Manage the local LinkRPC hub daemon.' },\n {\n getStatus: requestType(z.object({}), DaemonStatusSchema),\n /** Streams the status on every change until cancelled. */\n watchStatus: requestType(z.object({}), z.object({})).withStream({ server: DaemonStatusSchema }),\n /** Re-read the config file and apply what changed. */\n reloadConfig: requestType(z.object({}), DaemonStatusSchema),\n getConfig: requestType(z.object({}), ConfigDocumentSchema),\n /** Validate, write, and apply; rejects when the file changed since `expectedRevision`. */\n setConfig: requestType(\n z.object({ text: z.string(), expectedRevision: z.string() }),\n z.object({ revision: z.string() }),\n ),\n /** Persistently enable or disable a service in the config file. */\n setServiceEnabled: requestType(z.object({ name: z.string(), enabled: z.boolean() }), z.object({})),\n restartService: requestType(z.object({ name: z.string() }), z.object({})),\n getServiceLogs: requestType(\n z.object({ name: z.string(), limit: z.number().int().positive().optional() }),\n z.object({ lines: z.array(LogLineSchema) }),\n ),\n /** Persist `callLog.level` in the config file and apply it (`off` stops recording). */\n setCallLogLevel: requestType(z.object({ level: CallLogLevelSchema }), z.object({})),\n /** Read recorded calls from the call-log files, newest first. */\n queryCalls: requestType(\n z.object({ filter: CallFilterSchema.optional(), limit: z.number().int().positive().max(5_000).optional() }),\n z.object({ calls: z.array(CallRecordSchema), truncated: z.boolean() }),\n ),\n /** Streams matching records as they are written, until cancelled. */\n watchCalls: requestType(z.object({ filter: CallFilterSchema.optional() }), z.object({}))\n .withStream({ server: CallRecordSchema }),\n /** Stop all services and exit. Intentional: autostart managers do not restart it. */\n shutdown: requestType(z.object({}), z.object({})),\n },\n);\n","import { createHash, randomUUID } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\n/** Overrides every hub location with one directory (tests, portable installs). */\nexport const LINKRPC_HUB_HOME_VAR = 'LINKRPC_HUB_HOME';\n\n/** Unix domain socket paths longer than this fail to bind on macOS. */\nconst MAX_UNIX_SOCKET_PATH = 103;\n\n/**\n * Where one per-user hub keeps its configuration, state, and local sockets.\n * All daemon, CLI, and desktop processes of a user resolve the same home.\n */\nexport class HubHome {\n /**\n * The per-user default:\n * - Windows: `%LOCALAPPDATA%\\linkrpc\\hub`\n * - macOS: `~/Library/Application Support/linkrpc/hub`\n * - Linux: `$XDG_CONFIG_HOME/linkrpc/hub` (config), `$XDG_STATE_HOME/linkrpc/hub`\n * (state), `$XDG_RUNTIME_DIR/linkrpc-hub` (sockets)\n *\n * `LINKRPC_HUB_HOME` places everything under one directory instead.\n */\n public static resolve(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n homedir: string = os.homedir(),\n ): HubHome {\n const p = platform === 'win32' ? path.win32 : path.posix;\n const override = env[LINKRPC_HUB_HOME_VAR];\n if (override) return HubHome.at(override, platform);\n if (platform === 'win32') {\n const base = p.join(env.LOCALAPPDATA ?? p.join(homedir, 'AppData', 'Local'), 'linkrpc', 'hub');\n return new HubHome(p.join(base, 'config.json'), base, p.join(base, 'run'), platform, undefined);\n }\n if (platform === 'darwin') {\n const base = p.join(homedir, 'Library', 'Application Support', 'linkrpc', 'hub');\n return new HubHome(p.join(base, 'config.json'), base, p.join(base, 'run'), platform, undefined);\n }\n const configDir = p.join(env.XDG_CONFIG_HOME || p.join(homedir, '.config'), 'linkrpc', 'hub');\n const stateDir = p.join(env.XDG_STATE_HOME || p.join(homedir, '.local', 'state'), 'linkrpc', 'hub');\n const runtimeDir = env.XDG_RUNTIME_DIR ? p.join(env.XDG_RUNTIME_DIR, 'linkrpc-hub') : p.join(stateDir, 'run');\n return new HubHome(p.join(configDir, 'config.json'), stateDir, runtimeDir, platform, undefined);\n }\n\n /** A custom home with config, state, and sockets all below `dir`. */\n public static at(dir: string, platform: NodeJS.Platform = process.platform): HubHome {\n const p = platform === 'win32' ? path.win32 : path.posix;\n return new HubHome(p.join(dir, 'config.json'), dir, p.join(dir, 'run'), platform, dir);\n }\n\n private constructor(\n public readonly configFile: string,\n public readonly stateDir: string,\n /** Private (0700) directory for Unix sockets. Unused on Windows. */\n public readonly runtimeDir: string,\n private readonly _platform: NodeJS.Platform,\n /** The directory of a custom home (`--home`, `LINKRPC_HUB_HOME`); `undefined` for the default. */\n public readonly customDir: string | undefined,\n ) { }\n\n private get _path(): path.PlatformPath {\n return this._platform === 'win32' ? path.win32 : path.posix;\n }\n\n public get configDir(): string {\n return this._path.dirname(this.configFile);\n }\n\n /** JSON Schema written next to the config for editor validation. */\n public get configSchemaFile(): string {\n return this._path.join(this.configDir, 'config.schema.json');\n }\n\n /** Endpoint + token for applications; present while the daemon runs. */\n public get discoveryFile(): string {\n return this._path.join(this.stateDir, 'hub.json');\n }\n\n /** Endpoint + token for the management API; present while the daemon runs. */\n public get managementFile(): string {\n return this._path.join(this.stateDir, 'management.json');\n }\n\n public get logFile(): string {\n return this._path.join(this.stateDir, 'daemon.log');\n }\n\n /** NDJSON call-log files (`callLog` in the config). */\n public get callLogDir(): string {\n return this._path.join(this.stateDir, 'calls');\n }\n\n /** Persistent managed identities of services. */\n public get identityDir(): string {\n return this._path.join(this.stateDir, 'identities');\n }\n\n /** Distinguishes OS registrations (autostart entries) of custom homes from the default one. */\n public get instanceName(): string {\n if (this.customDir === undefined) return 'linkrpc-hub';\n return `linkrpc-hub-${createHash('sha256').update(this.customDir).digest('hex').slice(0, 8)}`;\n }\n\n /**\n * The fixed application endpoint unless `localEndpoint.path` overrides it.\n * Windows pipes share one machine-wide namespace, so the name includes the\n * user; Unix sockets live in the user's private runtime directory.\n */\n public get defaultAppEndpoint(): string {\n if (this._platform === 'win32') {\n const user = os.userInfo().username.replace(/[^A-Za-z0-9._-]/g, '_');\n return `\\\\\\\\.\\\\pipe\\\\${this.instanceName}-${user}`;\n }\n return this._unixSocketPath('hub.sock');\n }\n\n /**\n * The single-instance lock endpoint. Fixed per home so that a second daemon\n * for the same home fails to bind it.\n */\n public get lockEndpoint(): string {\n if (this._platform === 'win32') {\n const key = createHash('sha256').update(this.stateDir.toLowerCase()).digest('hex').slice(0, 24);\n return `\\\\\\\\.\\\\pipe\\\\linkrpc-hub-lock-${key}`;\n }\n return this._unixSocketPath('daemon.lock');\n }\n\n /**\n * A fresh endpoint for a daemon listener. Windows pipe names are random\n * (pipes are a global namespace); Unix sockets live in the private runtime dir.\n */\n public allocEndpoint(name: string): string {\n if (this._platform === 'win32') return `\\\\\\\\.\\\\pipe\\\\linkrpc-hub-${name}-${randomUUID()}`;\n return this._unixSocketPath(`${name}.sock`);\n }\n\n private _unixSocketPath(name: string): string {\n const socketPath = this._path.join(this.runtimeDir, name);\n if (Buffer.byteLength(socketPath) > MAX_UNIX_SOCKET_PATH) {\n throw new Error(`socket path is too long for this platform: ${socketPath}`);\n }\n return socketPath;\n }\n}\n","import { defineInterface, requestType } from '@hediet/linkrpc';\nimport {\n ConsoleTemplate,\n consoleAttachParamsSchema,\n consoleClientMessageSchema,\n consoleExitSchema,\n consoleModeSchema,\n consoleServerMessageSchema,\n} from '@hediet/linkrpc-infra/console';\nimport { z } from 'zod';\nimport { ServiceStatusSchema } from './managementInterface';\n\nexport const endpointAddress = z.object({\n namespace: z.string().min(1),\n id: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/).default('main'),\n});\nexport const processSource = z.object({\n kind: z.literal('process'),\n command: z.array(z.string().min(1)).min(1),\n cwd: z.string().optional(),\n env: z.record(z.string(), z.string()).default({}),\n rpc: z.boolean().default(true),\n /** Run in a pseudoterminal: stdout and stderr merge, and attachments can resize it. */\n tty: z.boolean().default(false),\n readiness: z.enum(['connected', 'spawned']).default('connected'),\n});\nexport const endpointDefinition = endpointAddress.extend({\n source: z.discriminatedUnion('kind', [\n processSource,\n z.object({ kind: z.literal('connection'), endpoint: z.string().min(1) }),\n ]),\n persistent: z.boolean().default(false),\n restart: z.enum(['never', 'on-failure', 'always']).default('never'),\n});\nexport type EndpointDefinition = z.infer<typeof endpointDefinition>;\nexport type EndpointAddress = z.infer<typeof endpointAddress>;\nexport const endpointStatus = endpointAddress.extend({\n instanceId: z.string(),\n serviceId: z.string(),\n persistent: z.boolean(),\n restart: endpointDefinition.shape.restart,\n desired: z.boolean(),\n /** Owned by a `run` call that stops and removes it when the call ends. */\n owned: z.boolean(),\n sourceKind: z.enum(['process', 'connection']),\n rpc: z.boolean(),\n /** Process endpoints have a console, reachable through the `consoles` template instance. */\n console: z.object({ mode: consoleModeSchema }).optional(),\n runtime: ServiceStatusSchema,\n});\nexport type EndpointStatus = z.infer<typeof endpointStatus>;\n\nconst replace = z.boolean().optional()\n .describe('Stop and remove an existing endpoint with the same address first, including persistent and owned ones.');\nexport const runParams = z.object({\n definition: endpointDefinition.extend({ source: processSource }),\n /** The call owns the endpoint: ending it (cancellation, disconnect, or completion) stops and removes it. */\n owner: z.boolean().optional(),\n replace,\n console: consoleAttachParamsSchema,\n});\nexport type RunParams = z.infer<typeof runParams>;\nexport const runEvent = z.union([\n consoleServerMessageSchema,\n z.object({ t: z.literal('status'), status: endpointStatus }),\n]);\nexport type RunEvent = z.infer<typeof runEvent>;\nexport const watchEvent = z.discriminatedUnion('t', [\n z.object({ t: z.literal('status'), status: endpointStatus }),\n z.object({ t: z.literal('removed') }),\n]);\nexport type WatchEvent = z.infer<typeof watchEvent>;\n\n/** Console template parameters: the endpoint whose process console to use. */\nexport const consoleAddress = z.object({ namespace: z.string().min(1), id: z.string().min(1) });\n\nexport const managedEndpointsInterface = defineInterface({\n id: 'linkrpc.managedEndpoints',\n description: 'Manage named processes and connections on this execution host. Starting endpoints executes with this host user\\'s privileges. '\n + 'Process consoles are served by the `consoles` instance of the `linkrpc.console.v1` template, with the endpoint address as params.',\n}, {\n consoles: ConsoleTemplate({ params: consoleAddress }).mapMembers({ info: 'consoleInfo', attach: 'attachConsole' }),\n info: requestType(z.object({}), z.object({ hostname: z.string(), platform: z.string(), cwd: z.string(), servicePrefix: z.string() })),\n list: requestType(z.object({ namespace: z.string().optional() }), z.array(endpointStatus)),\n create: requestType(endpointDefinition.extend({ replace }), endpointStatus),\n run: requestType(runParams, z.object({ exit: z.nullable(consoleExitSchema) }), {\n description: 'Create a process endpoint and attach to its console in one call. The stream carries the '\n + '`linkrpc.console` attach protocol plus `status` events. Without `owner`, cancelling detaches.',\n }).withStream({ client: consoleClientMessageSchema, server: runEvent }),\n watch: requestType(endpointAddress, z.object({})).withStream({ server: watchEvent }),\n start: requestType(endpointAddress, endpointStatus),\n stop: requestType(endpointAddress, z.object({})),\n remove: requestType(endpointAddress, z.object({})),\n configure: requestType(endpointAddress.extend({\n persistent: z.boolean().optional(),\n restart: z.enum(['never', 'on-failure', 'always']).optional(),\n }), endpointStatus),\n});\n","/**\n * Client entry point: connect applications and management tools to the\n * user's local hub daemon. Free of hub-server dependencies.\n */\nimport type { InterfaceClient } from '@hediet/linkrpc';\nimport { connectToHub, LINKRPC_ENDPOINT_VAR, type ConnectToHubOptions, type HubClientHandle } from '@hediet/linkrpc/node';\nimport { readEndpointDiscovery } from './discovery';\nimport { hubDaemonManagementInterface } from './managementInterface';\nimport { HubHome } from './paths';\n\nexport * from './managementInterface';\nexport * from './callLog/callRecord';\nexport * from './callLog/callQuery';\nexport * from './endpointInterface';\nexport { type EndpointDiscovery, readEndpointDiscovery } from './discovery';\nexport { HubHome, LINKRPC_HUB_HOME_VAR } from './paths';\n\nexport interface ConnectToLocalHubOptions extends ConnectToHubOptions {\n readonly home?: HubHome;\n}\n\n/**\n * Connect to the local hub. Resolution order: explicit `endpoint`,\n * `LINKRPC_ENDPOINT` (set for services the daemon manages), then the running\n * daemon's discovery file.\n */\nexport async function connectToLocalHub(options: ConnectToLocalHubOptions = {}): Promise<HubClientHandle> {\n const { home, ...connectOptions } = options;\n if (connectOptions.endpoint !== undefined || process.env[LINKRPC_ENDPOINT_VAR]) {\n return connectToHub(connectOptions);\n }\n const resolvedHome = home ?? HubHome.resolve();\n const discovery = readEndpointDiscovery(resolvedHome.discoveryFile);\n if (!discovery) {\n throw new Error(`The local LinkRPC hub is not running (no ${resolvedHome.discoveryFile}).`);\n }\n return connectToHub({ ...connectOptions, endpoint: discovery.endpoint, token: discovery.token ?? '' });\n}\n\nexport interface HubManagementConnection {\n readonly management: InterfaceClient<typeof hubDaemonManagementInterface>;\n onClose(listener: () => void): { dispose(): void; };\n close(): void;\n}\n\n/** Connect to the daemon's management API. Rejects when the daemon is not running. */\nexport async function connectToHubManagement(home: HubHome = HubHome.resolve()): Promise<HubManagementConnection> {\n const discovery = readEndpointDiscovery(home.managementFile);\n if (!discovery) {\n throw new Error(`The local LinkRPC hub is not running (no ${home.managementFile}).`);\n }\n const handle = await connectToHub({ endpoint: discovery.endpoint, token: discovery.token ?? '' });\n return {\n management: handle.connection.get(hubDaemonManagementInterface),\n onClose: listener => handle.onClose(listener),\n close: () => handle.close(),\n };\n}\n","import { HubHome, readEndpointDiscovery } from '@hediet/linkrpc-hub-daemon/client';\nimport type { SocketEndpoint } from '@hediet/linkrpc/node';\n\nexport function resolveLocalEndpoint(): SocketEndpoint {\n const home = HubHome.resolve();\n const discovery = readEndpointDiscovery(home.discoveryFile);\n if (!discovery) throw new Error(`The local LinkRPC hub is not running (no ${home.discoveryFile}).`);\n return { kind: 'socket', path: discovery.endpoint, token: discovery.token };\n}\n","import {\n ContextStore,\n type ContextReference,\n type ContextValues,\n type SelectedContext,\n mergeContextValues,\n} from './contexts';\nimport {\n resolveEndpoint,\n type ResolvedEndpoint,\n} from '@hediet/linkrpc-client-internal';\nimport { formatEndpointUri } from '@hediet/linkrpc/node';\nimport { resolveLocalEndpoint } from './localEndpoint';\n\nexport type CliProfile = 'rpc' | 'hub';\n\nexport interface ResolvedInvocationContext {\n readonly profile: CliProfile;\n readonly selected: SelectedContext;\n readonly contextValues: ContextValues;\n readonly environmentValues: ContextValues;\n readonly values: ContextValues;\n readonly cliOverrides: ContextValues;\n readonly environmentApplied: boolean;\n}\n\nexport interface ResolveInvocationContextOptions {\n readonly profile: CliProfile;\n readonly store: ContextStore;\n readonly selector?: string;\n readonly cliOverrides?: ContextValues;\n readonly env?: NodeJS.ProcessEnv;\n readonly useEnvironment?: boolean;\n readonly allowMissingContext?: boolean;\n}\n\nexport async function resolveInvocationContext(\n options: ResolveInvocationContextOptions,\n): Promise<ResolvedInvocationContext> {\n const env = options.env ?? process.env;\n const environmentSelector = firstDefined(\n env.LINKRPC_CONTEXT,\n env.HUBRPC_CONTEXT,\n );\n const selected = await options.store.select({\n ...(options.selector !== undefined ? { selector: options.selector } : {}),\n ...(options.selector === undefined && environmentSelector !== undefined\n ? { environmentSelector }\n : {}),\n ...(options.allowMissingContext === true ? { allowMissing: true } : {}),\n });\n const environmentApplied = options.useEnvironment\n ?? (options.profile === 'hub' && options.selector === undefined);\n const contextValues = selected.context?.values ?? {};\n const environmentValues = environmentApplied ? contextValuesFromEnvironment(env) : {};\n const cliOverrides = options.cliOverrides ?? {};\n return {\n profile: options.profile,\n selected,\n contextValues,\n environmentValues,\n values: mergeContextValues(\n mergeContextValues(contextValues, environmentValues),\n cliOverrides,\n ),\n cliOverrides,\n environmentApplied,\n };\n}\n\nexport function contextValuesFromEnvironment(env: NodeJS.ProcessEnv): ContextValues {\n const endpoint = firstDefined(env.LINKRPC_ENDPOINT, env.HUBRPC_ENDPOINT);\n const endpointToken = firstDefined(env.LINKRPC_TOKEN, env.HUBRPC_TOKEN);\n return {\n ...(endpoint !== undefined ? { endpoint } : {}),\n ...(endpointToken !== undefined ? { endpointToken } : {}),\n };\n}\n\nexport async function mutationReference(\n store: ContextStore,\n selected: SelectedContext,\n): Promise<Exclude<ContextReference, { readonly kind: 'empty'; }>> {\n if (\n selected.reference.kind !== 'empty'\n && selected.reference.kind !== 'root'\n ) {\n return selected.reference;\n }\n const cwd = await store.resolveReference('.');\n if (cwd.kind === 'empty') throw new Error('current directory cannot be used as a context');\n return cwd;\n}\n\nexport function validationDefault(profile: CliProfile): 'auto' | 'required' {\n return profile === 'hub' ? 'required' : 'auto';\n}\n\nexport function resolveSigning(\n profile: CliProfile,\n values: Pick<ContextValues, 'sign'>,\n requiresSigning = false,\n): boolean {\n if (requiresSigning && values.sign === false) {\n throw new Error('Capability operations require signing; remove --no-sign or override the context with --sign.');\n }\n return values.sign ?? (requiresSigning || profile === 'hub');\n}\n\nexport function resolveInvocationEndpoint(\n invocation: ResolvedInvocationContext,\n provisioningHandledElsewhere = false,\n): ResolvedEndpoint | undefined {\n const cli = invocation.cliOverrides;\n const context = invocation.contextValues;\n const environment = invocation.environmentValues;\n const cliHasEndpoint = hasEndpointSelector(cli);\n const environmentHasEndpoint = environment.endpoint !== undefined;\n let input: Parameters<typeof resolveEndpoint>[0];\n\n if (cliHasEndpoint) {\n const inheritedToken = cli.endpoint !== undefined && hasTokenPlaceholder(cli.endpoint)\n ? environment.endpointToken ?? context.endpointToken\n : undefined;\n const token = cli.endpointToken ?? inheritedToken;\n input = {\n ...endpointInput(cli),\n ...(token !== undefined ? { endpointToken: token } : {}),\n provisioningHandledElsewhere,\n env: {},\n };\n } else if (environmentHasEndpoint) {\n input = {\n ...endpointInput(cli),\n ...(cli.endpointToken !== undefined ? { endpointToken: cli.endpointToken } : {}),\n provisioningHandledElsewhere,\n env: {\n LINKRPC_ENDPOINT: environment.endpoint,\n ...(environment.endpointToken !== undefined\n ? { LINKRPC_TOKEN: environment.endpointToken }\n : {}),\n },\n };\n } else {\n const values = { ...context, ...cli };\n const token = cli.endpointToken\n ?? environment.endpointToken\n ?? context.endpointToken;\n input = {\n ...endpointInput(values),\n ...(token !== undefined ? { endpointToken: token } : {}),\n provisioningHandledElsewhere,\n env: {},\n };\n }\n\n const uri = input.endpoint ?? (input.endpointCmd === undefined && input.endpointCmdStdio === undefined\n ? input.env?.LINKRPC_ENDPOINT : undefined);\n if (uri === 'linkrpc:local') {\n if (cli.endpointToken !== undefined) {\n throw new Error('linkrpc:local uses credentials from local Hub discovery; --endpoint-token is not supported.');\n }\n input = { ...input, endpoint: formatEndpointUri(resolveLocalEndpoint(), { revealToken: true }), endpointToken: undefined, env: {} };\n }\n const result = resolveEndpoint(input);\n if (result.error !== undefined) throw new Error(result.error);\n return result.endpoint;\n}\n\nfunction endpointInput(values: ContextValues): Parameters<typeof resolveEndpoint>[0] {\n return {\n ...(values.endpoint !== undefined ? { endpoint: values.endpoint } : {}),\n ...(values.endpointCmd !== undefined ? { endpointCmd: values.endpointCmd } : {}),\n ...(values.endpointCmdStdio !== undefined\n ? { endpointCmdStdio: values.endpointCmdStdio }\n : {}),\n ...(values.endpointCmdEnv !== undefined ? { endpointCmdEnv: values.endpointCmdEnv } : {}),\n ...(values.endpointCmdCwd !== undefined ? { endpointCmdCwd: values.endpointCmdCwd } : {}),\n ...(values.provisionIdentity !== undefined\n ? { provisionIdentity: values.provisionIdentity }\n : {}),\n ...(values.provisionIdentitySlot !== undefined\n ? { provisionIdentitySlot: values.provisionIdentitySlot }\n : {}),\n };\n}\n\nfunction hasEndpointSelector(values: ContextValues): boolean {\n return values.endpoint !== undefined\n || values.endpointCmd !== undefined\n || values.endpointCmdStdio !== undefined;\n}\n\nfunction hasTokenPlaceholder(endpoint: string): boolean {\n return /(?:[?&])token=%(?:[&#]|$)/.test(endpoint);\n}\n\nfunction firstDefined(...values: readonly (string | undefined)[]): string | undefined {\n return values.find((value) => value !== undefined);\n}\n","import { readFile } from 'node:fs/promises';\nimport { resolve } from 'node:path';\nimport { parseStaticHubSchema, type StaticHubSchema } from '@hediet/linkrpc';\n\nexport {\n parseStaticHubSchema,\n type StaticHubSchema,\n type StaticHubSchemaDocument,\n type StaticInterfaceReference,\n type StaticService,\n} from '@hediet/linkrpc';\n\nexport function resolveStaticHubSchemaSource(source: string): string {\n return isHttpUrl(source) ? source : resolve(source);\n}\n\nexport async function loadStaticHubSchema(source: string): Promise<StaticHubSchema> {\n let raw: unknown;\n try {\n let text: string;\n if (isHttpUrl(source)) {\n const response = await fetch(source);\n if (!response.ok) throw new Error(`HTTP ${response.status} ${response.statusText}`.trimEnd());\n text = await response.text();\n } else {\n text = await readFile(source, 'utf8');\n }\n raw = JSON.parse(text);\n } catch (error) {\n throw new Error(`Failed to load hub schema '${source}': ${(error as Error).message}`);\n }\n try {\n return parseStaticHubSchema(raw);\n } catch (error) {\n throw new Error(`Invalid hub schema '${source}': ${(error as Error).message}`);\n }\n}\n\nfunction isHttpUrl(source: string): boolean {\n return /^https?:\\/\\//i.test(source);\n}\n","/**\n * Shared completion core: resolve a command line + cursor into a structured\n * candidate list, opening a best-effort hub connection when the slot needs\n * dynamic data.\n *\n * This is the reusable engine behind two front-ends:\n * - the CLI's `_complete` command (see `../commands/internalComplete.ts`),\n * which formats the result as `text\\ttooltip` lines for shell scripts;\n * - the VS Code extension's terminal completion provider, which maps the\n * structured result onto `TerminalCompletionItem`s.\n *\n * Endpoint selection is caller-controllable: `endpointOverride` wins over the\n * line's `--endpoint`, and `env` controls (or disables, via `{}`) the\n * `LINKRPC_ENDPOINT` fallback — the extension passes `{}` so completion targets\n * the endpoint named on the line rather than the extension host's environment.\n */\nimport { setupSigning } from '@hediet/linkrpc-client-internal';\nimport { parsePrincipalSpec } from '@hediet/linkrpc-client-internal';\nimport { connect } from '@hediet/linkrpc-client-internal';\nimport { isHubEndpoint } from '@hediet/linkrpc/node';\nimport { type ResolvedEndpoint } from '@hediet/linkrpc-client-internal';\nimport { complete, type CompleteOptions, type Completion } from './complete';\nimport { withFileCache } from './cache';\nimport { ChannelDirectorySource, type DirectorySource } from './directorySource';\nimport { parseLine } from './parse';\nimport { resolveSlot, type Slot } from './resolve';\nimport {\n HUB_COMMAND_TREE,\n RPC_COMMAND_TREE,\n type SlotType,\n} from './tree';\nimport { ContextStore, type ContextValues } from '../contexts';\nimport {\n type CliProfile,\n resolveInvocationContext,\n resolveInvocationEndpoint,\n} from '../invocationContext';\nimport { loadStaticHubSchema, type StaticHubSchema } from '../staticHubSchema';\nimport { withStaticHubReflection } from '../commands/staticHubReflection';\nimport { normalizeCliExecutable } from '../cliInvocation';\n\n/** Slot types that require talking to a hub. Anything else is static-only. */\nconst DYNAMIC_SLOT_TYPES: ReadonlySet<SlotType> = new Set([\n 'serviceId',\n 'interfaceId',\n 'interfaceRef',\n 'methodRef',\n]);\n\nexport interface CompleteForLineOptions {\n readonly line: string;\n readonly point: number;\n /**\n * Endpoint URI to connect to, overriding any `--endpoint` on the line and\n * the env fallback. When omitted, the line's `--endpoint` (then `env`) is\n * used.\n */\n readonly endpointOverride?: string;\n /**\n * Environment consulted for the `LINKRPC_ENDPOINT` fallback. Defaults to\n * `process.env`. Pass `{}` to disable the env fallback entirely (the\n * extension does this so completion never targets the extension host's\n * environment).\n */\n readonly env?: NodeJS.ProcessEnv;\n /** Override the directory source (tests). */\n readonly directoryOverride?: DirectorySource;\n /** Suppress the connect attempt entirely (tests). */\n readonly skipConnect?: boolean;\n}\n\nexport interface CompleteForLineResult {\n /** Completion candidates, already prefix-filtered, sorted and de-duped. */\n readonly candidates: readonly Completion[];\n /** The resolved slot the cursor sits in (subcommand / flag / positional). */\n readonly slot: Slot;\n /**\n * Offset of the first character the candidate replaces (i.e. the start of\n * the current word). Equal to `point - replacementLength`.\n */\n readonly replacementIndex: number;\n /** Length of the current word prefix the candidate replaces. */\n readonly replacementLength: number;\n}\n\n/**\n * Resolve completion candidates for the cursor at `point` in `line`, opening a\n * hub connection only when the slot needs dynamic data.\n */\nexport async function completeForLine(\n opts: CompleteForLineOptions,\n): Promise<CompleteForLineResult> {\n const parsed = parseLine(opts.line, opts.point);\n const executable = normalizeCliExecutable(parsed.tokensBefore[0]?.text);\n const tree = executable === 'hub' ? HUB_COMMAND_TREE : RPC_COMMAND_TREE;\n const ctx = resolveSlot(parsed, tree);\n const profile: CliProfile = executable === 'hub' || ctx.commandPath[0]?.name === 'hub'\n ? 'hub'\n : 'rpc';\n const prefix = parsed.currentWordPrefix;\n\n let directory: DirectorySource | undefined = opts.directoryOverride;\n let closeConnection: (() => void) | undefined;\n if (!directory && !opts.skipConnect && _slotWantsDynamic(ctx.slot)) {\n const opened = await _openDirectoryFromLine(ctx.seenFlagValues, {\n endpointOverride: opts.endpointOverride,\n env: opts.env,\n profile,\n });\n directory = opened?.source;\n closeConnection = opened?.close;\n }\n\n try {\n const completeOpts: CompleteOptions = {\n line: opts.line,\n point: opts.point,\n tree,\n ...(directory !== undefined ? { directory } : {}),\n };\n const candidates = await complete(completeOpts);\n return {\n candidates,\n slot: ctx.slot,\n replacementIndex: opts.point - prefix.length,\n replacementLength: prefix.length,\n };\n } finally {\n closeConnection?.();\n }\n}\n\nfunction _slotWantsDynamic(slot: Slot): boolean {\n if (slot.kind === 'flag-value') {\n return slot.flag.valueType !== undefined && DYNAMIC_SLOT_TYPES.has(slot.flag.valueType);\n }\n if (slot.kind === 'positional') return DYNAMIC_SLOT_TYPES.has(slot.type);\n return false;\n}\n\ninterface OpenedDirectory {\n readonly source: DirectorySource;\n readonly close: () => void;\n}\n\ninterface OpenDirectoryOptions {\n readonly endpointOverride?: string;\n readonly env?: NodeJS.ProcessEnv;\n readonly profile: CliProfile;\n}\n\n/**\n * Try to open a `DirectorySource` against the hub the partial command line\n * points at (or `endpointOverride`). The returned `close()` MUST be called:\n * the underlying socket otherwise keeps the process alive past action return,\n * hanging the user's prompt.\n *\n * Any failure → `undefined` (the orchestrator falls back to static-only).\n */\nasync function _openDirectoryFromLine(\n seenFlagValues: ReadonlyMap<string, string | undefined>,\n opts: OpenDirectoryOptions,\n): Promise<OpenedDirectory | undefined> {\n try {\n return await _openDirectoryFromLineCore(seenFlagValues, opts);\n } catch {\n return undefined;\n }\n}\n\nasync function _openDirectoryFromLineCore(\n seenFlagValues: ReadonlyMap<string, string | undefined>,\n opts: OpenDirectoryOptions,\n): Promise<OpenedDirectory | undefined> {\n const invocation = await resolveInvocationContext({\n profile: opts.profile,\n store: new ContextStore(),\n selector: seenFlagValues.get('--context'),\n cliOverrides: completionContextOverrides(seenFlagValues, opts.endpointOverride),\n env: opts.env,\n useEnvironment: seenFlagValues.has('--use-env')\n ? true\n : seenFlagValues.has('--no-use-env')\n ? false\n : undefined,\n });\n let endpoint: ResolvedEndpoint | undefined;\n try {\n endpoint = resolveInvocationEndpoint(invocation);\n } catch {\n return undefined;\n }\n if (endpoint === undefined) return undefined;\n\n // Never spawn a child process during completion (cmd / cmd-stdio / cmd-env).\n if (\n endpoint.kind !== 'socket'\n && endpoint.kind !== 'ws'\n && endpoint.kind !== 'ws-no-init'\n ) return undefined;\n\n const opened = await _connectWithDeadline(endpoint, 800);\n if (!opened) return undefined;\n const isRaw = endpoint.kind === 'ws-no-init'\n || (endpoint.kind === 'socket' && endpoint.brokerMode === 'raw');\n if (opts.profile === 'hub' && !isRaw) {\n try {\n const principalSpec = parsePrincipalSpec(invocation.values.principal);\n await _withDeadline(\n setupSigning(opened.channel, opened.signing, principalSpec, {\n negotiateHubCaps: isHubEndpoint(endpoint),\n }),\n 800,\n );\n } catch {\n opened.close();\n return undefined;\n }\n }\n const staticSchema = invocation.values.schema === undefined\n ? undefined\n : await loadStaticHubSchema(invocation.values.schema);\n const channel = staticSchema === undefined\n ? opened.channel\n : withStaticHubReflection(opened.channel, staticSchema);\n const live = new ChannelDirectorySource(channel);\n const cached = withFileCache(live, _endpointCacheKey(endpoint, staticSchema));\n return { source: cached, close: () => opened.close() };\n}\n\nfunction completionContextOverrides(\n seen: ReadonlyMap<string, string | undefined>,\n endpointOverride: string | undefined,\n): ContextValues {\n const endpoint = endpointOverride ?? seen.get('--endpoint');\n return {\n ...(endpoint !== undefined ? { endpoint } : {}),\n ...(seen.get('--endpoint-cmd') !== undefined\n ? { endpointCmd: seen.get('--endpoint-cmd') }\n : {}),\n ...(seen.get('--endpoint-cmd-stdio') !== undefined\n ? { endpointCmdStdio: seen.get('--endpoint-cmd-stdio') }\n : {}),\n ...(endpointOverride === undefined && seen.get('--endpoint-token') !== undefined\n ? { endpointToken: seen.get('--endpoint-token') }\n : {}),\n ...(seen.has('--provision-identity') ? { provisionIdentity: true } : {}),\n ...(seen.get('--provision-identity-slot') !== undefined\n ? { provisionIdentitySlot: seen.get('--provision-identity-slot') }\n : {}),\n ...(seen.get('--principal') !== undefined ? { principal: seen.get('--principal') } : {}),\n ...(seen.get('--schema') !== undefined ? { schema: seen.get('--schema') } : {}),\n };\n}\n\n/**\n * Race `connect` against a soft deadline. On timeout, the connect promise's\n * resolved connection (if any) is closed so it doesn't leak.\n */\nasync function _connectWithDeadline(\n endpoint: ResolvedEndpoint,\n deadlineMs: number,\n): Promise<Awaited<ReturnType<typeof connect>> | undefined> {\n let timer: NodeJS.Timeout | undefined;\n let timedOut = false;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => {\n timedOut = true;\n resolve(undefined);\n }, deadlineMs);\n });\n try {\n const connectPromise = connect(endpoint).catch(() => undefined);\n const conn = await Promise.race([connectPromise, timeout]);\n if (timedOut) {\n // The connect may still resolve after we've moved on — make sure\n // we close it so the socket doesn't keep the process alive.\n void connectPromise.then((late) => late?.close());\n return undefined;\n }\n return conn ?? undefined;\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\n/** Reject `p` with a timeout error after `deadlineMs`, without leaking the timer. */\nasync function _withDeadline<T>(p: Promise<T>, deadlineMs: number): Promise<T> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('deadline exceeded')), deadlineMs);\n });\n try {\n return await Promise.race([p, timeout]);\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nfunction _endpointCacheKey(\n endpoint: ResolvedEndpoint,\n staticSchema: StaticHubSchema | undefined,\n): string {\n const endpointKey = endpoint.kind === 'socket'\n ? `socket:${endpoint.path}`\n : endpoint.kind === 'ws'\n ? `ws:${endpoint.url}`\n : endpoint.kind === 'ws-no-init'\n ? `ws-no-init:${endpoint.url}`\n : `${endpoint.kind}:?`;\n return staticSchema === undefined\n ? endpointKey\n : `${endpointKey}|schema:${JSON.stringify(staticSchema)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,sBAAsB,gBAC/B;CACI,IAAI;CACJ,aACI;AAER,GACA,EACI,SAAS,YACL,EAAE,OAAO;;;;;AAKL,YAAY,EACP,OAAO;CAAE,MAAM,EAAE,OAAO;CAAG,SAAS,EAAE,OAAO;AAAE,CAAC,CAAC,CACjD,SAAS,EAClB,CAAC,GACD,EAAE,OAAO;;AAEL,YAAY,EACP,OAAO;CAAE,MAAM,EAAE,OAAO;CAAG,SAAS,EAAE,OAAO;AAAE,CAAC,CAAC,CACjD,SAAS,EAClB,CAAC,GACD,EACI,aACI,+JAGR,CACJ,CAAC,CAAC,WAAW;CAET,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;CAEvC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC;AAC3C,CAAC,EACL,CACJ;;;;;;AClEA,IAAa,uBAAb,MAAa,qBAAqB;CAoCV;CACA;CACA;CACA;CAtCpB,OAAc,eAAe,OAAqC;EAC9D,IAAI,MAAM,WAAW,GAAG,MAAM,IAAI,MAAM,4BAA4B;EAEpE,IAAI;EACJ,IAAI,OAAO;EACX,MAAM,QAAQ,MA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