@hediet/linkrpc-cli 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runComplete-BkQwzPbF.js","names":["path","fs","spawnCommand","fetchSchema","path","fs","path","interfaceKey"],"sources":["../../src/mcpForward.interface.ts","../../src/methodRef.ts","../../src/paramParsing.ts","../../src/validation.ts","../../../../packages-private/linkrpc-client/src/localHub.ts","../../../../packages-private/linkrpc-client/src/endpoint.ts","../../../../packages-private/linkrpc-client/src/connect.ts","../../../../packages-private/linkrpc-client/src/principal.ts","../../../../packages-private/linkrpc-client/src/identity.ts","../../../../packages-private/linkrpc-client/src/reflection.ts","../../../../packages-private/linkrpc-client/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/contexts.ts","../../src/invocationContext.ts","../../src/staticHubSchema.ts","../../src/commands/staticHubReflection.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 | false;\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 —\n * fall back to a single `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 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 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}\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: AttachedLink = {\n claimPrefix: () => { },\n releasePrefix: () => false,\n edgeId: 'overlay-uplink',\n dispose: () => { },\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({ endpoint: socketPath });\n\n const accepted = new Promise<NodeSocketTransport>((resolve) => {\n socketServer.setConnectionHandler((t) => resolve(t));\n });\n\n const child = spawnCommand(opts.command, {\n // The child speaks linkrpc over the socket, so its stdio stays free for\n // diagnostics — inherit it so a child that fails to start is visible.\n stdio: ['ignore', 'inherit', 'inherit'],\n env: { ...process.env, ...opts.env, LINKRPC_ENDPOINT: socketPath, LINKRPC_TOKEN: token },\n ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),\n });\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 const dispose = (): void => {\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 const childTransport = await Promise.race([\n accepted,\n new Promise<never>((_resolve, reject) => {\n child.once('exit', (code) =>\n reject(new Error(`overlay: cmd-env child exited (code ${code ?? '?'}) before connecting`)),\n );\n }),\n ]).catch((err: unknown) => {\n dispose();\n throw err;\n });\n\n overlay.connectParticipant(childTransport);\n return { uplink: pair.b, 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 { 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\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 { transport } = await connectNdjson({\n input: child.stdout,\n output: child.stdin,\n onClose: () => {\n if (!child.killed) child.kill();\n },\n trace: log?.trace,\n });\n return _makeCliConnection(transport, () => {\n if (!child.killed) child.kill();\n }, log);\n}\n\n/**\n * Start a private in-process hub, spawn the child as a participant, then\n * connect to the hub's socket. The child registers its services against the\n * hub exactly as it would against a remote one; we tear the hub + child down\n * when the connection closes.\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 connectViaLocalHub({ command, provisionSlot, env, cwd, log });\n}\n\n/**\n * Spawn a child under an in-process local hub (`startLocalHub`) and connect\n * to that hub over a socket. Backs the standard `cmd-env` endpoint path; the\n * hub + child are torn down when the connection closes.\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);\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 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);\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 { 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);\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): 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 return {\n channel,\n rpcChannel: wrapped,\n signing,\n setRequestHandler: (handler) => wrapped.setRequestHandler(handler),\n close: () => {\n channel.close();\n onClose();\n },\n };\n}\n\nexport { RpcError };\n","import type { IRequestSender, Principal, SigningCallCtx } from '@hediet/linkrpc';\nimport {\n createManagedPrincipal,\n createSelfManagedPrincipal,\n createSelfManagedPrincipalFromFile,\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\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 {\n principal: await createSelfManagedPrincipal(MANAGED_FALLBACK_USER_ID),\n source: { kind: 'managed-fallback', userId: MANAGED_FALLBACK_USER_ID },\n };\n }\n case 'user':\n return {\n principal: await createSelfManagedPrincipal(spec.id),\n source: { kind: 'user', id: spec.id },\n };\n case 'file':\n return {\n principal: await createSelfManagedPrincipalFromFile(spec.path),\n source: { kind: 'file', path: spec.path },\n };\n }\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 { loadOrCreateIdentity } from \"@hediet/linkrpc/node\";\nimport { MANAGED_FALLBACK_USER_ID } from \"./principal\";\n\n/**\n * Stable slot id for the on-disk keypair used by the managed-with-fallback\n * default (and `--principal user:hubrpc-cli`). The same slot always loads the\n * same keypair so persistent caps issued by the hub keep working across CLI\n * invocations.\n */\n/**\n * Delete the CLI's persistent identity keypair and its cached caps. The\n * next CLI command will mint a fresh keypair and trigger a new consent\n * modal. Returns the files that were removed (empty when there was no\n * stored state).\n */\nexport async function logoutCliIdentity(): Promise<string[]> {\n // `loadOrCreateIdentity` is the only API that knows the on-disk\n // path for the slot; calling it here just to discover the path may\n // briefly create a fresh keypair if one didn't exist, which we then\n // delete on the line below. Net effect: end state is empty either\n // way, and the cost is one wasted keygen on the no-op path.\n const identity = await loadOrCreateIdentity({ id: MANAGED_FALLBACK_USER_ID });\n const capsFile = _capsFile(identity.file);\n const removed: string[] = [];\n for (const f of [identity.file, 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.replace(/\\.json$/, \".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 permissionMatchesTarget,\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 } = await resolvePrincipal(principalSpec, channel);\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 let inAccessNegotiation = false;\n const provider: CapProvider = async ({ method, params, nonce, signedAtMs, interfaceHash }) => {\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 = presentCaps.length > 0 ? { capabilities: presentCaps } : {};\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 if (_capBagCovers(presentCaps, call)) 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, {\n call,\n method,\n params,\n nonce,\n signedAtMs,\n interfaceHash,\n });\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 if (oneShot.length > 0) {\n return { capabilities: [...durable, ...oneShot] };\n }\n return durable.length > 0\n ? { capabilities: durable }\n : ({} satisfies HubCapProviderResult);\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/** True when a durable (non-one-shot) cap in the bag authorises `target`. */\nfunction _capBagCovers(caps: readonly SignedCapability[], target: CallTarget): boolean {\n return caps.some((sc) => !_isOneShotCap(sc) && sc.permissions.some((p) => permissionMatchesTarget(target, p)));\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';\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 /** 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: '--validation', takesValue: true, valueType: 'free' },\n { name: '--use-env', takesValue: false },\n { name: '--no-use-env', 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 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 ],\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: '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.',\n positionals: [],\n options: [\n { name: '--timeout', takesValue: true, valueType: 'free' },\n { name: '--ttl', takesValue: true, valueType: 'free' },\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: '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: 'free' },\n { name: '--ttl', takesValue: true, valueType: 'free' },\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: '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 }\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 // `--p:<name>` shortcut: only meaningful under `call` / `notify`, and\n // only when the user has already typed the methodRef 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?.name === 'call' || ctx.subcommand?.name === 'notify')\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","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';\n\nexport type ValidationMode = 'auto' | 'required' | 'off';\n\nexport interface ContextValues {\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 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 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 const rootReference: ContextReference = { kind: 'root' };\n const root = contexts.get(contextKey(rootReference));\n if (root !== undefined) {\n return {\n reference: rootReference,\n context: root,\n selectedBy: 'root',\n explicitlySelected: false,\n };\n }\n return {\n reference: { kind: 'empty' },\n context: undefined,\n selectedBy: 'empty',\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 && existing !== undefined) {\n throw new Error(`context ${formatContextReference(reference)} already exists`);\n }\n const now = new Date().toISOString();\n const context: StoredContext = {\n key,\n reference,\n values: existing === undefined\n ? normalizeContextValues(values)\n : mergeContextValues(existing.values, values),\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 if ((await this._read()).has(contextKey(reference))) {\n throw new Error(`context ${formatContextReference(reference)} already exists`);\n }\n }\n\n public async replace(\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 && existing !== undefined) {\n throw new Error(`context ${formatContextReference(reference)} already exists`);\n }\n const now = new Date().toISOString();\n const context: StoredContext = {\n key,\n reference,\n values: normalizeContextValues(values),\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);\n if (existing === undefined) {\n throw new Error(`context ${formatContextReference(reference)} does not exist`);\n }\n const values = { ...existing.values } as Record<keyof ContextValues, unknown>;\n for (const item of keys) delete values[item];\n const context: StoredContext = {\n ...existing,\n values: normalizeContextValues(values as ContextValues),\n updatedAt: new Date().toISOString(),\n };\n contexts.set(key, context);\n return { value: context, changed: true };\n });\n }\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 return this._mutate((contexts) => {\n const removed = contexts.delete(contextKey(reference));\n return { value: removed, 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 if (context === undefined && !allowMissing) {\n throw new Error(`context ${formatContextReference(reference)} does not exist`);\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 result = update(contexts);\n if (result.changed) await this._write(contexts);\n return result.value;\n } finally {\n await release();\n }\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\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 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 return {\n key: raw.key,\n reference,\n values: normalizeContextValues(raw.values),\n createdAt: raw.createdAt,\n updatedAt: raw.updatedAt,\n };\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';\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 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 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 {\n computeInterfaceHash,\n type LinkRpcInterfaceSchema,\n} from '@hediet/linkrpc';\n\nexport interface StaticInterfaceReference {\n interfaceId: string;\n interfaceHash: string;\n}\n\nexport interface StaticService {\n serviceId: string;\n interfaces: StaticInterfaceReference[];\n}\n\nexport interface StaticHubSchemaDocument {\n services: StaticService[];\n defaultInterface?: StaticInterfaceReference;\n interfaceSchemas: LinkRpcInterfaceSchema[];\n}\n\nexport type StaticHubSchema = StaticHubSchemaDocument;\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) {\n throw new Error(`HTTP ${response.status} ${response.statusText}`.trimEnd());\n }\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\nexport function parseStaticHubSchema(value: unknown): StaticHubSchema {\n const root = expectRecord(value, 'hub schema');\n const rawServices = expectArray(root.services, 'services');\n const rawSchemas = expectArray(root.interfaceSchemas, 'interfaceSchemas');\n\n const interfaceSchemas = rawSchemas.map((schema, index) =>\n parseInterfaceSchema(schema, `interfaceSchemas[${index}]`));\n const schemasByKey = new Map<string, LinkRpcInterfaceSchema>();\n for (const schema of interfaceSchemas) {\n const key = interfaceKey(schema.id, schema.hash);\n if (schemasByKey.has(key)) {\n throw new Error(`interfaceSchemas contains duplicate ${schema.id}@${schema.hash}`);\n }\n schemasByKey.set(key, schema);\n }\n\n const services = rawServices.map((service, index) =>\n parseService(service, `services[${index}]`));\n for (const [serviceIndex, service] of services.entries()) {\n for (const [interfaceIndex, ref] of service.interfaces.entries()) {\n requireResolvedReference(\n ref,\n schemasByKey,\n `services[${serviceIndex}].interfaces[${interfaceIndex}]`,\n );\n }\n }\n\n const defaultInterface = root.defaultInterface === undefined\n ? undefined\n : parseInterfaceReference(root.defaultInterface, 'defaultInterface');\n if (defaultInterface !== undefined) {\n requireResolvedReference(defaultInterface, schemasByKey, 'defaultInterface');\n }\n\n return {\n services,\n ...(defaultInterface === undefined ? {} : { defaultInterface }),\n interfaceSchemas,\n };\n}\n\nfunction parseService(value: unknown, path: string): StaticService {\n const service = expectRecord(value, path);\n if (typeof service.serviceId !== 'string') {\n throw new Error(`${path}.serviceId must be a string`);\n }\n return {\n serviceId: service.serviceId,\n interfaces: expectArray(service.interfaces, `${path}.interfaces`).map((ref, index) =>\n parseInterfaceReference(ref, `${path}.interfaces[${index}]`)),\n };\n}\n\nfunction parseInterfaceReference(value: unknown, path: string): StaticInterfaceReference {\n const ref = expectRecord(value, path);\n if (typeof ref.interfaceId !== 'string' || ref.interfaceId.length === 0) {\n throw new Error(`${path}.interfaceId must be a non-empty string`);\n }\n if (typeof ref.interfaceHash !== 'string' || ref.interfaceHash.length === 0) {\n throw new Error(`${path}.interfaceHash must be a non-empty string`);\n }\n return {\n interfaceId: ref.interfaceId,\n interfaceHash: ref.interfaceHash,\n };\n}\n\nfunction parseInterfaceSchema(value: unknown, path: string): LinkRpcInterfaceSchema {\n const schema = expectRecord(value, path);\n if (typeof schema.id !== 'string' || schema.id.length === 0) {\n throw new Error(`${path}.id must be a non-empty string`);\n }\n if (typeof schema.hash !== 'string' || schema.hash.length === 0) {\n throw new Error(`${path}.hash must be a non-empty string`);\n }\n if (typeof schema.methods !== 'object' || schema.methods === null || Array.isArray(schema.methods)) {\n throw new Error(`${path}.methods must be an object`);\n }\n for (const [name, method] of Object.entries(schema.methods)) {\n if (name.length === 0) {\n throw new Error(`${path}.methods keys must be non-empty strings`);\n }\n const parsed = expectRecord(method, `${path}.methods.${name}`);\n if (!Object.hasOwn(parsed, 'params')) {\n throw new Error(`${path}.methods.${name}.params is required`);\n }\n }\n\n const typed = schema as unknown as LinkRpcInterfaceSchema;\n const computedHash = computeInterfaceHash(typed);\n if (computedHash !== typed.hash) {\n throw new Error(\n `${path} hash mismatch for ${typed.id}: declared ${typed.hash}, computed ${computedHash}`,\n );\n }\n return typed;\n}\n\nfunction requireResolvedReference(\n ref: StaticInterfaceReference,\n schemasByKey: ReadonlyMap<string, LinkRpcInterfaceSchema>,\n path: string,\n): void {\n if (!schemasByKey.has(interfaceKey(ref.interfaceId, ref.interfaceHash))) {\n throw new Error(`${path} ${formatReference(ref)} does not resolve to an interface schema`);\n }\n}\n\nfunction formatReference(ref: StaticInterfaceReference): string {\n return `${ref.interfaceId}@${ref.interfaceHash}`;\n}\n\nfunction interfaceKey(interfaceId: string, interfaceHash: string): string {\n return `${interfaceId}\\0${interfaceHash}`;\n}\n\nfunction expectRecord(value: unknown, path: string): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n throw new Error(`${path} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction expectArray(value: unknown, path: string): unknown[] {\n if (!Array.isArray(value)) {\n throw new Error(`${path} must be an array`);\n }\n return value;\n}\n","import {\n ErrorCode,\n type LinkRpcInterfaceSchema,\n type IncomingCall,\n type IRequestSender,\n type JsonValue,\n type 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}\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 })));\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 }\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 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) 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),\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) 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","/**\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';\nimport { parsePrincipalSpec } from '@hediet/linkrpc-client';\nimport { connect } from '@hediet/linkrpc-client';\nimport { isHubEndpoint } from '@hediet/linkrpc/node';\nimport { type ResolvedEndpoint } from '@hediet/linkrpc-client';\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,CAA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