relay-dsh-plugin-manager 0.2.6 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/conversation.ts","../src/hot-runtime.ts","../src/source.ts","../src/search.ts","../src/profile.ts","../src/plans.ts","../src/operations.ts","../src/manager.ts","../src/providers.ts","../src/restart.ts","../src/runner.ts","../src/telemetry.ts","../src/index.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis'\nimport type { CommandInvocation } from '@deepseek-ai/dsh-commands'\nimport { createUserMessage } from '@deepseek-ai/dsh-llm'\nimport { defineTool, type ToolRunContext } from '@deepseek-ai/dsh-tools'\nimport '@deepseek-ai/dsh-user-questions'\nimport type { PluginManager } from './manager.ts'\nimport type { ConfirmationPlan, PlanAction } from './plans.ts'\nimport { fail } from './errors.ts'\n\ntype JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }\n\nfunction jsonValue(value: unknown): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue\n}\n\nfunction renderJson(_args: unknown, value: JsonValue): Array<{ type: 'text'; text: string }> {\n return [{ type: 'text', text: JSON.stringify(value, null, 2) }]\n}\n\ninterface ConfirmationCursor {\n sessionId: string\n userMessageSeq: number\n expiresAt: number\n plan: ConfirmationPlan\n}\n\nconst APPROVE_LABEL = 'Approve plugin change'\nconst DECLINE_LABEL = 'Decline'\n\nfunction sessionEvents(session: object): ReadonlyArray<{ type: string; seq: number }> {\n const snapshot = Reflect.get(session, 'snapshotEvents') as unknown\n if (typeof snapshot === 'function') {\n return Reflect.apply(snapshot, session, []) as ReadonlyArray<{ type: string; seq: number }>\n }\n const events = Reflect.get(session, 'events') as unknown\n if (!Array.isArray(events)) throw new TypeError('DSH Session exposes neither snapshotEvents() nor events')\n return events as ReadonlyArray<{ type: string; seq: number }>\n}\n\nfunction confirmationCursor(\n execution: ToolRunContext,\n): Pick<ConfirmationCursor, 'sessionId' | 'userMessageSeq'> | null {\n const session = execution.agent?.session\n if (session === undefined) return null\n let userMessageSeq = -1\n for (const event of sessionEvents(session)) if (event.type === 'user/message') userMessageSeq = event.seq\n return { sessionId: String(session.id), userMessageSeq }\n}\n\nfunction planDetail(plan: ConfirmationPlan): string {\n const lines = [\n `Operation: ${plan.action}`,\n `Profile: ${plan.profile}`,\n `Impact: ${plan.impact}`,\n `Restart expected: ${plan.restartExpected ? 'yes' : 'no'}`,\n ]\n if (plan.action === 'install_many') {\n lines.push('Plugins:')\n for (const item of plan.items) lines.push(`- ${item.packageName}: ${item.installSpec}`)\n if (plan.missingPeerDependencies.length > 0) {\n lines.push('Missing required peer dependencies:')\n for (const peer of plan.missingPeerDependencies) {\n lines.push(`- ${peer.packageName} (${peer.ranges.join(', ')}) required by ${peer.requiredBy.join(', ')}`)\n }\n }\n } else {\n if (plan.packageName !== undefined) lines.push(`Plugin: ${plan.packageName}`)\n if (plan.installSpec !== undefined) lines.push(`Source: ${plan.installSpec}`)\n if (plan.currentSource !== undefined) lines.push(`Current source: ${plan.currentSource}`)\n }\n return lines.join('\\n')\n}\n\nfunction confirmationBinding(\n confirmations: Map<string, ConfirmationCursor>,\n token: string,\n execution: ToolRunContext,\n now: number,\n): ConfirmationCursor {\n const binding = confirmations.get(token)\n const cursor = confirmationCursor(execution)\n if (binding === undefined || cursor === null || cursor.sessionId !== binding.sessionId) {\n fail('CONFIRMATION_REQUIRED', 'Confirmation token is not bound to this DSH conversation.')\n }\n if (binding.expiresAt <= now) {\n confirmations.delete(token)\n fail('CONFIRMATION_EXPIRED', 'Confirmation token has expired.')\n }\n return binding\n}\n\nexport function registerConversationSurface(ctx: Context, manager: PluginManager): void {\n const confirmations = new Map<string, ConfirmationCursor>()\n ctx.tools.register(defineTool({\n name: 'plugin_discover',\n description: 'Read-only DSH plugin discovery. List installed plugins, search registered sources (including GitHub owner:NAME), inspect one npm/GitHub repository source, or query plugin/operation status. Search candidates form one relevance-ranked result page: present every possibly relevant candidate in ascending rank, exclude candidates whose purpose is clearly unrelated, and NEVER silently truncate the remaining page to a fixed top-N. Ranking is not a compatibility, security, or installation approval. Search result repository and recommendedSource values can be passed directly to inspect and plan. This tool never changes the profile.',\n parameters: {\n action: {\n type: 'string',\n enum: ['list', 'search', 'inspect', 'status'],\n required: true,\n description: 'The read-only operation.',\n },\n query: { type: 'string', description: 'Natural-language query or GitHub owner:NAME search.' },\n target: { type: 'string', description: 'npm package, github:owner/repo, https://github.com/owner/repo, github.com/owner/repo, or installed package name.' },\n operationId: { type: 'string', description: 'Operation id returned by plugin_manage.' },\n maxResults: { type: 'integer', description: 'Ranked result-page size from 1 to 20. Use 20 for ordinary need-based searches unless the user explicitly asks for fewer.' },\n },\n output: { schema: { type: 'json' }, render: renderJson },\n timeoutMs: 35_000,\n isConcurrencySafe: () => true,\n execute: async (args, execution) => jsonValue(await manager.discover(args, execution.signal)),\n }))\n\n ctx.tools.register(defineTool({\n name: 'plugin_manage',\n description: 'Plan and run DSH plugin mutations. ALWAYS call action=plan first and show its impact. NEVER treat the request that produced a plan as confirmation. Prefer action=confirm with its confirmationToken to show the plugin-owned DSH approval UI and execute an exact approval. Alternatively, call action=execute only after a later explicit user Chat message. NEVER wrap a plugin plan in generic ask_user_question. Use install_many with sources for one multi-plugin plan and confirmation. Install sources are npm or GitHub; search providers do not define installers.',\n parameters: {\n action: {\n type: 'string',\n enum: ['plan', 'confirm', 'execute', 'status', 'cancel'],\n required: true,\n description: 'Lifecycle stage. Mutations require plan followed by controlled confirm or later-message execute.',\n },\n operation: {\n type: 'string',\n enum: ['install', 'install_many', 'remove', 'update', 'enable', 'disable', 'restart'],\n description: 'Mutation to plan.',\n },\n target: { type: 'string', description: 'Installed package name, or install source when source is omitted.' },\n source: { type: 'string', description: 'npm package/version or canonical GitHub repository/ref.' },\n sources: {\n type: 'array',\n items: { type: 'string' },\n description: 'Ordered npm/GitHub sources for operation=install_many (1-20 items).',\n },\n confirmationToken: { type: 'string', description: 'One-use token from a prior plan.' },\n operationId: { type: 'string', description: 'Tracked operation id.' },\n },\n output: { schema: { type: 'json' }, render: renderJson },\n execute: async (args, execution) => {\n if (args.action === 'plan') {\n if (args.operation === undefined) fail('INVALID_ACTION', 'Planning requires an operation.')\n const plan = await manager.plan({\n operation: args.operation as PlanAction,\n ...(args.target === undefined ? {} : { target: args.target }),\n ...(args.source === undefined ? {} : { source: args.source }),\n ...(args.sources === undefined ? {} : { sources: args.sources }),\n }, execution.signal)\n const cursor = confirmationCursor(execution)\n if (cursor === null) fail('CONFIRMATION_REQUIRED', 'Planning requires a DSH Agent session.')\n const now = Date.now()\n for (const [token, binding] of confirmations) if (binding.expiresAt <= now) confirmations.delete(token)\n confirmations.set(plan.confirmationToken, {\n ...cursor,\n expiresAt: Date.parse(plan.expiresAt),\n plan,\n })\n return jsonValue(plan)\n }\n if (args.action === 'confirm') {\n if (args.confirmationToken === undefined) fail('CONFIRMATION_REQUIRED', 'Confirmation requires a token.')\n const binding = confirmationBinding(confirmations, args.confirmationToken, execution, Date.now())\n const questionId = `plugin-plan:${binding.plan.id}`\n const answer = await ctx.userQuestions.ask({\n questions: [{\n id: questionId,\n question: 'Apply this plugin change?',\n detail: planDetail(binding.plan),\n header: 'Plugin plan',\n options: [\n { label: APPROVE_LABEL, description: 'Apply the exact plan shown above.' },\n { label: DECLINE_LABEL, description: 'Keep the profile unchanged.' },\n ],\n multiSelect: false,\n intent: { kind: 'plan-review', approve: APPROVE_LABEL },\n }],\n ...(execution.agent === undefined ? {} : { agent: execution.agent }),\n signal: execution.signal,\n })\n const answered = answer.answers[0]\n const isExactAnswer = answer.answers.length === 1\n && answered?.id === questionId\n && answered.custom === undefined\n && answered.selected.length === 1\n if (!isExactAnswer) {\n fail('CONFIRMATION_INVALID', 'Plugin confirmation did not match the requested plan and was not executed.')\n }\n if (answered.selected[0] === DECLINE_LABEL) {\n return jsonValue({ status: 'declined', planId: binding.plan.id })\n }\n if (answered.selected[0] !== APPROVE_LABEL) {\n fail('CONFIRMATION_INVALID', 'Plugin confirmation used an unknown choice and was not executed.')\n }\n confirmations.delete(args.confirmationToken)\n return jsonValue(manager.execute(args.confirmationToken))\n }\n if (args.action === 'execute') {\n if (args.confirmationToken === undefined) fail('CONFIRMATION_REQUIRED', 'Execution requires a confirmation token.')\n const binding = confirmationBinding(confirmations, args.confirmationToken, execution, Date.now())\n const cursor = confirmationCursor(execution)\n if (cursor === null) fail('CONFIRMATION_REQUIRED', 'Execution requires a DSH Agent session.')\n if (cursor.userMessageSeq <= binding.userMessageSeq) {\n fail('CONFIRMATION_REQUIRED', 'Wait for a later explicit user confirmation before execution.')\n }\n confirmations.delete(args.confirmationToken)\n return jsonValue(manager.execute(args.confirmationToken))\n }\n if (args.operationId === undefined) fail('OPERATION_NOT_FOUND', `${args.action} requires an operation id.`)\n return jsonValue(args.action === 'cancel'\n ? manager.cancel(args.operationId)\n : manager.operation(args.operationId))\n },\n }))\n\n ctx.commands.register({\n name: 'plugins',\n description: 'manage DSH plugins through this conversation',\n input: { hint: '<request>' },\n handler: ({ agent, rawInput }: CommandInvocation) => {\n const request = rawInput.trim() === ''\n ? 'List the installed DSH plugins and summarize their status.'\n : rawInput.trim()\n agent.steer(createUserMessage({\n content: [{ type: 'text', text: request }],\n source: { kind: 'user' },\n }))\n return { kind: 'success', text: 'Plugin request submitted to this conversation.' }\n },\n })\n}\n","import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { parse } from 'yaml'\nimport type { PackageSurface } from './profile.ts'\n\nexport interface HotInsertRow {\n id: string\n name: string\n}\n\nexport interface HotActivationResult {\n active: boolean\n restartRequired: boolean\n reason: string | null\n}\n\ninterface PluginHandle {\n await(): Promise<unknown>\n dispose(): Promise<unknown> | void\n}\n\ninterface HotContext {\n plugin(plugin: unknown, config: unknown): PluginHandle\n logger?: { info?(message: string): void; warn?(message: string): void }\n}\n\nexport function parseSimpleHotPatch(text: string): HotInsertRow[] | null {\n let value: unknown\n try {\n value = parse(text)\n } catch {\n return null\n }\n if (!Array.isArray(value) || value.length === 0) return null\n const rows: HotInsertRow[] = []\n for (const patch of value) {\n if (typeof patch !== 'object' || patch === null || Array.isArray(patch)) return null\n if (Object.keys(patch).length !== 1 || !Array.isArray((patch as { insert?: unknown }).insert)) return null\n for (const raw of (patch as { insert: unknown[] }).insert) {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null\n const entry = raw as { id?: unknown; name?: unknown }\n if (Object.keys(entry).some(key => key !== 'id' && key !== 'name')) return null\n if (typeof entry.id !== 'string' || entry.id === '' || typeof entry.name !== 'string' || entry.name === '') return null\n rows.push({ id: entry.id, name: entry.name })\n }\n }\n return rows.length === 0 ? null : rows\n}\n\nexport class HotRuntime {\n private readonly handles = new Map<string, PluginHandle>()\n private sequence = 0\n private includeClass: unknown | null | undefined\n private readonly ctx: HotContext\n private readonly profileDir: string\n private readonly timeoutMs: number\n private readonly loadInclude?: () => Promise<unknown | null>\n\n constructor(\n ctx: HotContext,\n profileDir: string,\n timeoutMs = 10_000,\n loadInclude?: () => Promise<unknown | null>,\n ) {\n this.ctx = ctx\n this.profileDir = profileDir\n this.timeoutMs = timeoutMs\n this.loadInclude = loadInclude\n this.clean()\n }\n\n private hotDir(): string {\n return join(this.profileDir, '.relay-plugin-manager')\n }\n\n clean(): void {\n let files: string[]\n try {\n files = readdirSync(this.hotDir())\n } catch {\n return\n }\n for (const file of files) if (/^hot-\\d+\\.yml$/u.test(file)) rmSync(join(this.hotDir(), file), { force: true })\n }\n\n private async include(): Promise<unknown | null> {\n if (this.includeClass !== undefined) return this.includeClass\n if (this.loadInclude !== undefined) {\n this.includeClass = await this.loadInclude()\n return this.includeClass\n }\n try {\n const module = await import('@deepseek-ai/cordis-plugin-include') as { Include?: new (...args: never[]) => object; default?: new (...args: never[]) => object }\n const Include = module.Include ?? module.default\n if (Include === undefined) throw new Error('missing Include export')\n this.includeClass = class RuntimeHotInclude extends Include {\n write(): void {}\n }\n } catch {\n this.includeClass = null\n }\n return this.includeClass\n }\n\n async activate(surface: PackageSurface): Promise<HotActivationResult> {\n if (this.handles.has(surface.packageName)) return { active: true, restartRequired: false, reason: null }\n const Include = await this.include()\n if (Include === null) return { active: false, restartRequired: true, reason: 'DSH Include runtime is unavailable.' }\n let rows: HotInsertRow[] | null = null\n if (surface.bundlePatch !== null) {\n try {\n rows = parseSimpleHotPatch(readFileSync(\n join(this.profileDir, 'node_modules', surface.packageName, surface.bundlePatch),\n 'utf8',\n ))\n } catch {\n rows = null\n }\n if (rows === null) {\n return { active: false, restartRequired: true, reason: 'Bundle patch is not a plain insert-only patch.' }\n }\n } else if (surface.client) {\n rows = [{ id: `client-${surface.packageName.replace(/[^A-Za-z0-9_.-]/gu, '-')}`, name: surface.packageName }]\n } else {\n return { active: false, restartRequired: true, reason: 'Package has no hot-activatable DSH surface.' }\n }\n mkdirSync(this.hotDir(), { recursive: true, mode: 0o700 })\n const file = join(this.hotDir(), `hot-${String(++this.sequence)}.yml`)\n writeFileSync(file, rows.map(row => [\n '- id: ' + JSON.stringify(`rpm-${row.id}`),\n ' name: ' + JSON.stringify(row.name),\n ].join('\\n')).join('\\n') + '\\n', { mode: 0o600 })\n let handle: PluginHandle | undefined\n let timeout: NodeJS.Timeout | undefined\n try {\n handle = this.ctx.plugin(Include, { path: pathToFileURL(file).href })\n await Promise.race([\n handle.await(),\n new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(() => reject(new Error('hot activation timed out')), this.timeoutMs)\n }),\n ])\n this.handles.set(surface.packageName, handle)\n return { active: true, restartRequired: false, reason: null }\n } catch (error) {\n try { await handle?.dispose() } catch { /* best effort */ }\n return {\n active: false,\n restartRequired: true,\n reason: error instanceof Error ? error.message : String(error),\n }\n } finally {\n if (timeout !== undefined) clearTimeout(timeout)\n }\n }\n\n async deactivate(packageName: string): Promise<boolean> {\n const handle = this.handles.get(packageName)\n if (handle === undefined) return false\n this.handles.delete(packageName)\n try {\n await handle.dispose()\n return true\n } catch {\n return false\n }\n }\n\n isActive(packageName: string): boolean {\n return this.handles.has(packageName)\n }\n}\n","import { fail } from './errors.ts'\n\nexport const EXACT_SEMVER = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/u\nexport const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u\nexport const FULL_COMMIT = /^[a-f0-9]{40}$/iu\nconst GITHUB_PART = /^[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,98}[A-Za-z0-9])?$/u\nconst UNSAFE_TOKEN = /[\\u0000-\\u0020\\u007f;&|`$<>]/u\n\nexport interface NpmPluginSource {\n kind: 'npm'\n package: string\n version?: string\n}\n\nexport interface GithubPluginSource {\n kind: 'github'\n owner: string\n repo: string\n ref?: string\n}\n\nexport type PluginSource = NpmPluginSource | GithubPluginSource\n\nexport interface PluginInspection {\n source: PluginSource\n sourceType: PluginSource['kind']\n requestedSpec: string\n installSpec: string\n packageName: string\n version?: string\n commit?: string\n integrity?: string\n repository: string | null\n description: string | null\n bundlePatch: string | null\n client: boolean\n peerDependencies: Record<string, string>\n}\n\nfunction manifestPeerDependencies(value: unknown): Record<string, string> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}\n const manifest = value as { peerDependencies?: unknown; peerDependenciesMeta?: unknown }\n const peers = manifest.peerDependencies\n if (typeof peers !== 'object' || peers === null || Array.isArray(peers)) return {}\n const metadata = typeof manifest.peerDependenciesMeta === 'object'\n && manifest.peerDependenciesMeta !== null\n && !Array.isArray(manifest.peerDependenciesMeta)\n ? manifest.peerDependenciesMeta as Record<string, unknown>\n : {}\n return Object.fromEntries(Object.entries(peers).flatMap(([name, range]) => {\n if (!NPM_NAME.test(name) || typeof range !== 'string') return []\n const peerMetadata = metadata[name]\n if (typeof peerMetadata === 'object' && peerMetadata !== null && !Array.isArray(peerMetadata)\n && (peerMetadata as { optional?: unknown }).optional === true) return []\n const normalized = range.trim()\n return normalized === '' || normalized.length > 500 ? [] : [[name, normalized]]\n }))\n}\n\nexport interface FetchOptions {\n fetch?: typeof globalThis.fetch\n env?: NodeJS.ProcessEnv\n signal?: AbortSignal\n}\n\nfunction safeToken(value: unknown): string {\n const source = String(value ?? '').trim()\n if (source === '' || source.startsWith('-') || UNSAFE_TOKEN.test(source)) {\n fail('INVALID_SOURCE', 'Plugin source must be one safe npm or GitHub token.')\n }\n return source\n}\n\nexport function parseNpmSpec(value: unknown, requireExact = false): NpmPluginSource {\n const spec = safeToken(value)\n let packageName = spec\n let version: string | undefined\n const separator = spec.lastIndexOf('@')\n const scopedBoundary = spec.startsWith('@') ? spec.indexOf('/') : -1\n if (separator > Math.max(0, scopedBoundary)) {\n packageName = spec.slice(0, separator)\n version = spec.slice(separator + 1)\n }\n if (!NPM_NAME.test(packageName)) {\n fail('INVALID_NPM_SPEC', 'Plugin source is not a valid npm package name.')\n }\n if (version !== undefined && !EXACT_SEMVER.test(version)) {\n fail('INVALID_NPM_VERSION', 'npm plugin versions must be exact semantic versions.')\n }\n if (requireExact && version === undefined) {\n fail('IMMUTABLE_SOURCE_REQUIRED', 'Installation requires an exact npm version.')\n }\n return { kind: 'npm', package: packageName, ...(version === undefined ? {} : { version }) }\n}\n\nexport function isGithubPart(value: string): boolean {\n return GITHUB_PART.test(value) && value !== '.' && value !== '..' && !value.endsWith('.git')\n}\n\nfunction ownerOnlyGithubSpec(spec: string): string | null {\n const match = /^(?:github:|(?:https:\\/\\/)?github\\.com\\/)([^/#]+)\\/?$/u.exec(spec)\n return match !== null && isGithubPart(match[1]!) ? match[1]! : null\n}\n\nexport function parseGithubSpec(value: unknown, requireCommit = false): GithubPluginSource | null {\n const spec = safeToken(value)\n const ownerOnly = ownerOnlyGithubSpec(spec)\n if (ownerOnly !== null) {\n fail(\n 'GITHUB_OWNER_REQUIRES_SEARCH',\n `GitHub owner discovery requires action=search with query owner:${ownerOnly}.`,\n { owner: ownerOnly },\n )\n }\n const normalizedSpec = spec.startsWith('github.com/') ? `https://${spec}` : spec\n let owner: string | undefined\n let repo: string | undefined\n let ref: string | undefined\n if (normalizedSpec.startsWith('github:')) {\n const match = /^github:([^/]+)\\/([^#]+?)(?:#(.+))?$/u.exec(normalizedSpec)\n if (match === null) fail('INVALID_GITHUB_SPEC', 'GitHub source must use github:owner/repo[#ref].')\n owner = match[1]\n repo = match[2]\n ref = match[3]\n } else if (normalizedSpec.startsWith('https://github.com/')) {\n let url: URL\n try {\n url = new URL(normalizedSpec)\n } catch {\n fail('INVALID_GITHUB_SPEC', 'GitHub URL is invalid.')\n }\n if (url.protocol !== 'https:' || url.hostname !== 'github.com' || url.search !== '') {\n fail('INVALID_GITHUB_SPEC', 'Only canonical HTTPS github.com repository URLs are supported.')\n }\n const parts = url.pathname.split('/').filter(Boolean)\n owner = parts[0]\n repo = parts[1]?.replace(/\\.git$/u, '')\n if (parts.length > 2) {\n if ((parts[2] !== 'tree' && parts[2] !== 'commit') || parts.length < 4) {\n fail('INVALID_GITHUB_SPEC', 'GitHub URL must identify a repository, tree, or commit.')\n }\n ref = decodeURIComponent(parts.slice(3).join('/'))\n } else if (url.hash !== '') {\n fail('INVALID_GITHUB_SPEC', 'Use a tree/commit URL or github:owner/repo#ref for GitHub refs.')\n }\n } else if (/^[A-Za-z][A-Za-z0-9+.-]*:\\/\\//u.test(normalizedSpec)) {\n fail('INVALID_GITHUB_SPEC', 'Only canonical HTTPS github.com repository URLs are supported.')\n } else {\n return null\n }\n if (!isGithubPart(owner ?? '') || !isGithubPart(repo ?? '')) {\n fail('INVALID_GITHUB_SPEC', 'GitHub owner or repository name is invalid.')\n }\n if (ref !== undefined && (ref === '' || ref.length > 200 || UNSAFE_TOKEN.test(ref))) {\n fail('INVALID_GITHUB_REF', 'GitHub ref is invalid.')\n }\n if (requireCommit && !FULL_COMMIT.test(ref ?? '')) {\n fail('IMMUTABLE_SOURCE_REQUIRED', 'Installation requires a full GitHub commit.')\n }\n return { kind: 'github', owner: owner!, repo: repo!, ...(ref === undefined ? {} : { ref }) }\n}\n\nexport function parsePluginSource(value: string | PluginSource): PluginSource {\n if (typeof value === 'string') return parseGithubSpec(value) ?? parseNpmSpec(value)\n if (value.kind === 'npm') {\n return parseNpmSpec(`${value.package}${value.version === undefined ? '' : `@${value.version}`}`)\n }\n return parseGithubSpec(`github:${value.owner}/${value.repo}${value.ref === undefined ? '' : `#${value.ref}`}`)!\n}\n\nexport function renderSource(source: PluginSource): string {\n if (source.kind === 'npm') return `${source.package}${source.version === undefined ? '' : `@${source.version}`}`\n return `github:${source.owner}/${source.repo}${source.ref === undefined ? '' : `#${source.ref}`}`\n}\n\nfunction manifestDsh(value: unknown): { bundlePatch: string | null; client: boolean } {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return { bundlePatch: null, client: false }\n const dsh = (value as { dsh?: unknown }).dsh\n if (typeof dsh !== 'object' || dsh === null || Array.isArray(dsh)) return { bundlePatch: null, client: false }\n const bundle = (dsh as { bundle?: unknown }).bundle\n const patch = typeof bundle === 'object' && bundle !== null && !Array.isArray(bundle)\n ? (bundle as { patch?: unknown }).patch\n : undefined\n return {\n bundlePatch: typeof patch === 'string' && patch.trim() !== '' ? patch : null,\n client: (dsh as { client?: unknown }).client !== undefined,\n }\n}\n\nexport function validatePluginManifest(\n manifest: unknown,\n expectedName?: string,\n): { packageName: string; bundlePatch: string | null; client: boolean } {\n if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {\n fail('INVALID_PLUGIN_MANIFEST', 'Plugin package manifest must be an object.')\n }\n const packageName = String((manifest as { name?: unknown }).name ?? '')\n if (!NPM_NAME.test(packageName)) fail('INVALID_PLUGIN_MANIFEST', 'Plugin manifest has no valid package name.')\n if (expectedName !== undefined && packageName !== expectedName) {\n fail('PACKAGE_NAME_MISMATCH', 'Resolved package name does not match the requested npm package.')\n }\n const surface = manifestDsh(manifest)\n if (surface.bundlePatch === null && !surface.client) {\n fail('NOT_DSH_PLUGIN', `${packageName} declares neither dsh.bundle.patch nor dsh.client.`)\n }\n return { packageName, ...surface }\n}\n\nasync function fetchJson(url: string, options: FetchOptions, headers: Record<string, string> = {}): Promise<unknown> {\n const fetchImpl = options.fetch ?? globalThis.fetch\n let response: Response\n try {\n response = await fetchImpl(url, {\n headers: { accept: 'application/json', ...headers },\n redirect: 'follow',\n signal: options.signal,\n })\n } catch (error) {\n fail('NETWORK_ERROR', `Could not reach plugin source: ${error instanceof Error ? error.message : String(error)}`)\n }\n if (!response.ok) fail('SOURCE_HTTP_ERROR', `Plugin source returned HTTP ${response.status}.`, { url, status: response.status })\n try {\n return await response.json()\n } catch {\n fail('INVALID_SOURCE_METADATA', 'Plugin source returned invalid JSON metadata.', { url })\n }\n}\n\nfunction repositoryIdentity(value: unknown): string | null {\n const raw = typeof value === 'string'\n ? value\n : typeof value === 'object' && value !== null\n ? (value as { url?: unknown }).url\n : undefined\n if (typeof raw !== 'string' || raw.trim() === '') return null\n const normalized = raw.trim()\n .replace(/^git\\+/u, '')\n .replace(/^git@github\\.com:/u, 'https://github.com/')\n .replace(/^github:/u, 'https://github.com/')\n .replace(/\\.git(?:#.*)?$/u, '')\n .replace(/\\/$/u, '')\n const match = /^https:\\/\\/github\\.com\\/([^/]+)\\/([^/]+)$/iu.exec(normalized)\n return match === null\n ? normalized.toLowerCase()\n : `github.com/${match[1]!.toLowerCase()}/${match[2]!.toLowerCase()}`\n}\n\nfunction npmMetadataUrl(name: string, version?: string): string {\n return `https://registry.npmjs.org/${encodeURIComponent(name).replace(/^%40/u, '@')}/${encodeURIComponent(version ?? 'latest')}`\n}\n\nexport async function inspectNpm(source: NpmPluginSource, options: FetchOptions = {}): Promise<PluginInspection> {\n const manifest = await fetchJson(npmMetadataUrl(source.package, source.version), options)\n const plugin = validatePluginManifest(manifest, source.package)\n const version = String((manifest as { version?: unknown }).version ?? '')\n if (!EXACT_SEMVER.test(version)) fail('INVALID_NPM_VERSION', 'Registry metadata has no exact semantic version.')\n const integrity = (manifest as { dist?: { integrity?: unknown } }).dist?.integrity\n if (typeof integrity !== 'string' || !/^sha512-[A-Za-z0-9+/=]+$/u.test(integrity)) {\n fail('NPM_INTEGRITY_MISSING', 'Registry metadata has no SHA-512 package integrity.')\n }\n const exact: NpmPluginSource = { kind: 'npm', package: plugin.packageName, version }\n return {\n source: exact,\n sourceType: 'npm',\n requestedSpec: renderSource(source),\n installSpec: renderSource(exact),\n packageName: plugin.packageName,\n version,\n integrity,\n repository: repositoryIdentity((manifest as { repository?: unknown }).repository),\n description: typeof (manifest as { description?: unknown }).description === 'string'\n ? (manifest as { description: string }).description\n : null,\n bundlePatch: plugin.bundlePatch,\n client: plugin.client,\n peerDependencies: manifestPeerDependencies(manifest),\n }\n}\n\nfunction githubHeaders(env: NodeJS.ProcessEnv = process.env): Record<string, string> {\n const token = env.GITHUB_TOKEN ?? env.GH_TOKEN\n return {\n 'user-agent': 'relay-dsh-plugin-manager',\n 'x-github-api-version': '2022-11-28',\n ...(token === undefined || token === '' ? {} : { authorization: `Bearer ${token}` }),\n }\n}\n\nexport async function inspectGithub(source: GithubPluginSource, options: FetchOptions = {}): Promise<PluginInspection> {\n const headers = githubHeaders(options.env)\n let ref = source.ref\n if (ref === undefined) {\n const repository = await fetchJson(`https://api.github.com/repos/${source.owner}/${source.repo}`, options, headers)\n ref = typeof (repository as { default_branch?: unknown }).default_branch === 'string'\n ? (repository as { default_branch: string }).default_branch\n : undefined\n if (ref === undefined || ref === '') fail('INVALID_SOURCE_METADATA', 'GitHub repository has no default branch.')\n }\n const commit = await fetchJson(\n `https://api.github.com/repos/${source.owner}/${source.repo}/commits/${encodeURIComponent(ref)}`,\n options,\n headers,\n )\n const sha = String((commit as { sha?: unknown }).sha ?? '').toLowerCase()\n if (!FULL_COMMIT.test(sha)) fail('INVALID_SOURCE_METADATA', 'GitHub did not resolve the source to a full commit.')\n const manifest = await fetchJson(\n `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${sha}/package.json`,\n options,\n )\n const plugin = validatePluginManifest(manifest)\n const exact: GithubPluginSource = { kind: 'github', owner: source.owner, repo: source.repo, ref: sha }\n return {\n source: exact,\n sourceType: 'github',\n requestedSpec: renderSource(source),\n installSpec: renderSource(exact),\n packageName: plugin.packageName,\n commit: sha,\n repository: `github.com/${source.owner.toLowerCase()}/${source.repo.toLowerCase()}`,\n description: typeof (manifest as { description?: unknown }).description === 'string'\n ? (manifest as { description: string }).description\n : null,\n bundlePatch: plugin.bundlePatch,\n client: plugin.client,\n peerDependencies: manifestPeerDependencies(manifest),\n }\n}\n\nexport async function inspectPluginSource(\n value: string | PluginSource,\n options: FetchOptions = {},\n): Promise<PluginInspection> {\n const source = parsePluginSource(value)\n return source.kind === 'npm' ? inspectNpm(source, options) : inspectGithub(source, options)\n}\n\nexport function inspectionIdentity(inspection: PluginInspection): string {\n return inspection.repository ?? `${inspection.sourceType}:${inspection.packageName.toLowerCase()}`\n}\n","import type {\n PluginSearchCandidate,\n PluginSearchProvider,\n PluginSearchRequest,\n PluginSearchRuntime,\n} from './search-runtime.ts'\nimport {\n inspectionIdentity,\n inspectPluginSource,\n isGithubPart,\n parsePluginSource,\n type FetchOptions,\n type PluginInspection,\n type PluginSource,\n} from './source.ts'\nimport { fail } from './errors.ts'\n\nexport interface SearchResultSource {\n inspection: PluginInspection\n providers: string[]\n evidence: string[]\n}\n\nexport interface SearchResult {\n query: string\n candidates: Array<{\n rank: number\n identity: string\n packageName: string\n description: string | null\n repository: string | null\n repositoryOwner: string | null\n providers: string[]\n matchReasons: string[]\n sources: SearchResultSource[]\n recommendedSource: string\n }>\n presentation: {\n order: 'rank_ascending'\n returnedCandidates: number\n requestedMaximum: number\n includeEveryPossiblyRelevant: true\n excludeClearlyIrrelevant: true\n silentTopNTruncation: false\n }\n providerErrors: Array<{ provider: string; error: string }>\n rejectedCandidates: number\n}\n\nexport interface SearchOptions extends FetchOptions {\n maxResults?: number\n providerTimeoutMs?: number\n inspect?: typeof inspectPluginSource\n}\n\nfunction searchQuery(value: string): string {\n const query = value.trim()\n if (query === '' || query.length > 120 || /[\\u0000-\\u001f\\u007f]/u.test(query)) {\n fail('INVALID_SEARCH_QUERY', 'Search query must contain 1 to 120 printable characters.')\n }\n return query\n}\n\ninterface ParsedSearchQuery {\n query: string\n providerQuery: string\n intent?: PluginSearchRequest['intent']\n}\n\nfunction githubOwnerIntent(query: string): Omit<ParsedSearchQuery, 'query'> | null {\n const explicit = [\n /^owner:([^\\s]+)$/iu,\n /^github:([^/\\s]+)$/iu,\n /^(?:https:\\/\\/)?github\\.com\\/([^/\\s]+)\\/?$/iu,\n /^([^\\s]+)\\s+dsh\\s+plugins?$/iu,\n /^(?:dsh\\s+)?plugins?\\s+(?:by|from)\\s+([^\\s]+)$/iu,\n ]\n for (const pattern of explicit) {\n const match = pattern.exec(query)\n if (match === null) continue\n const owner = match[1]!\n if (!isGithubPart(owner)) fail('INVALID_SEARCH_QUERY', 'GitHub owner query contains an invalid owner name.')\n return { providerQuery: owner, intent: { kind: 'github-owner', owner, fallbackToText: false } }\n }\n if (/^[A-Za-z0-9]+$/u.test(query) && /\\d/u.test(query) && isGithubPart(query)) {\n return { providerQuery: query, intent: { kind: 'github-owner', owner: query, fallbackToText: true } }\n }\n return null\n}\n\nfunction parseSearchQuery(value: string): ParsedSearchQuery {\n const query = searchQuery(value)\n return { query, ...(githubOwnerIntent(query) ?? { providerQuery: query }) }\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new Error('search cancelled')\n}\n\nasync function searchProvider(\n provider: PluginSearchProvider,\n query: string,\n intent: PluginSearchRequest['intent'],\n maxResults: number,\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): Promise<readonly PluginSearchCandidate[]> {\n const controller = new AbortController()\n const onAbort = (): void => controller.abort(parent?.reason)\n if (parent?.aborted === true) throw abortReason(parent)\n parent?.addEventListener('abort', onAbort, { once: true })\n const timeout = setTimeout(() => controller.abort(new Error(`provider timed out after ${timeoutMs}ms`)), timeoutMs)\n try {\n const result = await provider.search({\n query,\n maxResults,\n signal: controller.signal,\n ...(intent === undefined ? {} : { intent }),\n })\n if (!Array.isArray(result)) throw new TypeError('provider result must be an array')\n return result.slice(0, maxResults)\n } finally {\n clearTimeout(timeout)\n parent?.removeEventListener('abort', onAbort)\n }\n}\n\ninterface DiscoveredSource {\n source: PluginSource\n provider: string\n evidence: string[]\n match: PluginSearchCandidate['match']\n rank: number\n}\n\nfunction candidateSources(provider: string, rows: readonly PluginSearchCandidate[]): DiscoveredSource[] {\n const output: DiscoveredSource[] = []\n const ranked = [...rows].sort((left, right) => (right.score ?? 0) - (left.score ?? 0) || left.id.localeCompare(right.id))\n for (const [rank, candidate] of ranked.entries()) {\n if (typeof candidate.id !== 'string' || candidate.id.trim() === '' || !Array.isArray(candidate.sources)) continue\n for (const raw of candidate.sources.slice(0, 3)) {\n try {\n output.push({\n source: parsePluginSource(raw),\n provider,\n evidence: [...(candidate.evidence ?? [])].filter(value => typeof value === 'string').slice(0, 5),\n match: candidate.match,\n rank,\n })\n } catch {\n // Provider data is untrusted. Invalid sources are rejected during normalization.\n }\n }\n }\n return output\n}\n\nexport async function searchPlugins(\n runtime: Pick<PluginSearchRuntime, 'entries'>,\n rawQuery: string,\n options: SearchOptions = {},\n): Promise<SearchResult> {\n const parsed = parseSearchQuery(rawQuery)\n const maxResults = Math.max(1, Math.min(20, options.maxResults ?? 20))\n const timeoutMs = Math.max(100, options.providerTimeoutMs ?? 10_000)\n const providers = runtime.entries()\n const settled = await Promise.allSettled(providers.map(async provider => ({\n provider: provider.id,\n rows: await searchProvider(\n provider,\n parsed.providerQuery,\n parsed.intent,\n maxResults,\n options.signal,\n timeoutMs,\n ),\n })))\n if (options.signal?.aborted === true) throw abortReason(options.signal)\n\n const providerErrors: SearchResult['providerErrors'] = []\n const discovered: DiscoveredSource[] = []\n for (let index = 0; index < settled.length; index += 1) {\n const result = settled[index]!\n const provider = providers[index]!.id\n if (result.status === 'rejected') {\n providerErrors.push({ provider, error: result.reason instanceof Error ? result.reason.message : String(result.reason) })\n continue\n }\n discovered.push(...candidateSources(result.value.provider, result.value.rows))\n }\n\n const inspect = options.inspect ?? inspectPluginSource\n const inspected = await Promise.all(discovered.map(async item => {\n try {\n const inspection = await inspect(item.source, options)\n return { ok: true as const, item, inspection }\n } catch {\n return { ok: false as const }\n }\n }))\n\n const projects = new Map<string, Omit<SearchResult['candidates'][number], 'rank'> & {\n rank: number\n matchPriority: number\n }>()\n let rejectedCandidates = 0\n for (const result of inspected) {\n if (!result.ok) {\n rejectedCandidates += 1\n continue\n }\n const identity = inspectionIdentity(result.inspection)\n const repositoryOwner = /^github\\.com\\/([^/]+)\\//iu\n .exec(result.inspection.repository ?? '')?.[1]?.toLowerCase() ?? null\n const exactOwner = result.item.match?.kind === 'github-owner'\n && repositoryOwner === result.item.match.value.toLowerCase()\n const existing = projects.get(identity) ?? {\n identity,\n packageName: result.inspection.packageName,\n description: result.inspection.description,\n repository: result.inspection.repository,\n repositoryOwner,\n providers: [],\n matchReasons: [],\n sources: [],\n recommendedSource: result.inspection.installSpec,\n rank: result.item.rank,\n matchPriority: exactOwner ? 0 : 1,\n }\n if (!existing.providers.includes(result.item.provider)) existing.providers.push(result.item.provider)\n if (exactOwner) {\n const reason = `Exact GitHub owner: ${result.item.match!.value}`\n if (!existing.matchReasons.includes(reason)) existing.matchReasons.push(reason)\n }\n const sameSource = existing.sources.find(source => source.inspection.installSpec === result.inspection.installSpec)\n if (sameSource === undefined) {\n existing.sources.push({\n inspection: result.inspection,\n providers: [result.item.provider],\n evidence: [...result.item.evidence],\n })\n } else {\n if (!sameSource.providers.includes(result.item.provider)) sameSource.providers.push(result.item.provider)\n for (const evidence of result.item.evidence) if (!sameSource.evidence.includes(evidence)) sameSource.evidence.push(evidence)\n }\n existing.rank = Math.min(existing.rank, result.item.rank)\n existing.matchPriority = Math.min(existing.matchPriority, exactOwner ? 0 : 1)\n const npm = existing.sources.find(source => source.inspection.sourceType === 'npm')\n existing.recommendedSource = npm?.inspection.installSpec ?? existing.sources[0]!.inspection.installSpec\n projects.set(identity, existing)\n }\n\n const candidates = [...projects.values()]\n .sort((left, right) => left.matchPriority - right.matchPriority\n || left.rank - right.rank\n || left.packageName.localeCompare(right.packageName))\n .slice(0, maxResults)\n .map(({ rank: _providerRank, matchPriority: _matchPriority, ...candidate }, index) => ({\n ...candidate,\n rank: index + 1,\n providers: candidate.providers.sort(),\n }))\n return {\n query: parsed.query,\n candidates,\n presentation: {\n order: 'rank_ascending',\n returnedCandidates: candidates.length,\n requestedMaximum: maxResults,\n includeEveryPossiblyRelevant: true,\n excludeClearlyIrrelevant: true,\n silentTopNTruncation: false,\n },\n providerErrors,\n rejectedCandidates,\n }\n}\n","import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { parseDocument, type Document } from 'yaml'\nimport { fail } from './errors.ts'\n\nexport const MANAGER_PACKAGE = 'relay-dsh-plugin-manager'\nconst STATE_VERSION = 1\nconst STATE_DIR = '.relay-plugin-manager'\n\nexport interface ProfileManifest {\n dependencies?: Record<string, string>\n dsh?: { profile?: { bundles?: string[] } }\n}\n\nexport interface ManagerState {\n version: 1\n disabled: Record<string, string[]>\n}\n\nexport interface PackageSurface {\n packageName: string\n source: string\n bundle: boolean\n bundlePatch: string | null\n client: boolean\n entryIds: string[] | null\n}\n\nexport interface LoaderEntrySnapshot {\n id: string\n name?: string\n disabled: boolean\n phase: string | null\n}\n\nexport interface PluginStatus {\n packageName: string\n source: string\n bundle: boolean\n enablement: 'enabled' | 'disabled' | 'mixed' | 'unknown'\n runtime: 'active' | 'inactive' | 'failed' | 'loading' | 'unknown'\n restartRequired: boolean\n entryIds: string[] | null\n}\n\nfunction readJsonObject<T extends object>(file: string, missing: T): T {\n try {\n const parsed: unknown = JSON.parse(readFileSync(file, 'utf8'))\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return missing\n return parsed as T\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return missing\n fail('PROFILE_READ_FAILED', `Could not read ${file}: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nfunction atomicWrite(file: string, text: string): void {\n try {\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 })\n const temporary = `${file}.tmp-${process.pid}-${Date.now()}`\n writeFileSync(temporary, text, { mode: 0o600 })\n renameSync(temporary, file)\n } catch (error) {\n fail('PROFILE_WRITE_FAILED', `Could not write ${file}: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nexport function writeProfileManifest(dir: string, manifest: ProfileManifest): void {\n atomicWrite(join(dir, 'package.json'), `${JSON.stringify(manifest, null, 2)}\\n`)\n}\n\nexport function reconcileRemovedPackage(dir: string, packageName: string): void {\n const manifest = readProfileManifest(dir)\n if (manifest.dependencies !== undefined) delete manifest.dependencies[packageName]\n const bundles = manifest.dsh?.profile?.bundles\n if (bundles !== undefined) manifest.dsh!.profile!.bundles = bundles.filter(name => name !== packageName)\n writeProfileManifest(dir, manifest)\n}\n\nexport function dshHome(env: NodeJS.ProcessEnv = process.env): string {\n const configured = env.DSH_HOME?.trim()\n return resolve(configured === undefined || configured === '' ? join(homedir(), '.dsh') : configured)\n}\n\nexport function profileDirectory(profile = 'web', env: NodeJS.ProcessEnv = process.env): string {\n return join(dshHome(env), 'profiles', profile)\n}\n\nexport function readProfileManifest(dir: string): ProfileManifest {\n return readJsonObject<ProfileManifest>(join(dir, 'package.json'), {})\n}\n\nexport function profileManifestText(dir: string): string | null {\n try {\n return readFileSync(join(dir, 'package.json'), 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n fail('PROFILE_READ_FAILED', `Could not read profile manifest: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nexport function restoreProfileManifest(dir: string, text: string | null): void {\n if (text === null) return\n atomicWrite(join(dir, 'package.json'), text)\n}\n\nfunction packageManifest(dir: string, packageName: string): Record<string, unknown> | null {\n const file = join(dir, 'node_modules', packageName, 'package.json')\n if (!existsSync(file)) return null\n return readJsonObject<Record<string, unknown>>(file, {})\n}\n\nexport function bundleEntryIds(dir: string, packageName: string, patch: string): string[] | null {\n try {\n const document = parseDocument(readFileSync(join(dir, 'node_modules', packageName, patch), 'utf8'))\n if (document.errors.length > 0 || !Array.isArray(document.toJS())) return null\n const ids: string[] = []\n for (const row of document.toJS() as unknown[]) {\n if (typeof row !== 'object' || row === null || Array.isArray(row)) continue\n const inserted = (row as { insert?: unknown }).insert\n if (!Array.isArray(inserted)) continue\n for (const entry of inserted) {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return null\n const id = (entry as { id?: unknown }).id\n if (typeof id !== 'string' || id.trim() === '') return null\n if (!ids.includes(id)) ids.push(id)\n }\n }\n return ids.length === 0 ? null : ids\n } catch {\n return null\n }\n}\n\nexport function packageSurface(dir: string, packageName: string, source: string): PackageSurface {\n const manifest = packageManifest(dir, packageName)\n const dsh = typeof manifest?.dsh === 'object' && manifest.dsh !== null && !Array.isArray(manifest.dsh)\n ? manifest.dsh as { bundle?: unknown; client?: unknown }\n : {}\n const bundle = typeof dsh.bundle === 'object' && dsh.bundle !== null && !Array.isArray(dsh.bundle)\n ? dsh.bundle as { patch?: unknown }\n : {}\n const patch = typeof bundle.patch === 'string' && bundle.patch.trim() !== '' ? bundle.patch : null\n return {\n packageName,\n source,\n bundle: patch !== null,\n bundlePatch: patch,\n client: dsh.client !== undefined,\n entryIds: patch === null ? null : bundleEntryIds(dir, packageName, patch),\n }\n}\n\nfunction statePath(dir: string): string {\n return join(dir, STATE_DIR, 'state.json')\n}\n\nexport function readManagerState(dir: string): ManagerState {\n const state = readJsonObject<Partial<ManagerState>>(statePath(dir), {})\n const disabled: Record<string, string[]> = {}\n if (state.version === STATE_VERSION && typeof state.disabled === 'object' && state.disabled !== null) {\n for (const [name, ids] of Object.entries(state.disabled)) {\n if (Array.isArray(ids) && ids.every(id => typeof id === 'string')) disabled[name] = [...new Set(ids)]\n }\n }\n return { version: STATE_VERSION, disabled }\n}\n\nfunction writeManagerState(dir: string, state: ManagerState): void {\n atomicWrite(statePath(dir), `${JSON.stringify(state, null, 2)}\\n`)\n}\n\nfunction patchDocument(file: string): Document.Parsed {\n let source = '[]\\n'\n try {\n source = readFileSync(file, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n fail('PROFILE_READ_FAILED', `Could not read profile patch: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n const document = parseDocument(source)\n if (document.errors.length > 0) fail('ENABLEMENT_CONFLICT', 'Profile cordis.patch.yml is not valid YAML.')\n const value = document.toJS()\n if (value === null) document.contents = document.createNode([]) as never\n else if (!Array.isArray(value)) fail('ENABLEMENT_CONFLICT', 'Profile cordis.patch.yml must contain a patch list.')\n return document\n}\n\nfunction exactDisabledRow(value: unknown, id: string): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const keys = Object.keys(value)\n return keys.length === 2 && (value as { id?: unknown }).id === id && (value as { disabled?: unknown }).disabled === true\n}\n\nexport function disablePackage(dir: string, surface: PackageSurface): string[] {\n if (surface.packageName === MANAGER_PACKAGE) fail('PROTECTED_PLUGIN', 'The plugin manager cannot disable itself.')\n if (surface.entryIds === null || surface.entryIds.length === 0) {\n fail('ENABLEMENT_UNSUPPORTED', `${surface.packageName} has no safely attributable Loader entry ids.`)\n }\n const file = join(dir, 'cordis.patch.yml')\n const state = readManagerState(dir)\n const document = patchDocument(file)\n const rows = document.toJS() as unknown[]\n const alreadyOwned = new Set(state.disabled[surface.packageName] ?? [])\n for (const id of surface.entryIds) {\n const existing = rows.find(row => typeof row === 'object' && row !== null && !Array.isArray(row)\n && (row as { id?: unknown }).id === id)\n if (existing !== undefined && !(alreadyOwned.has(id) && exactDisabledRow(existing, id))) {\n fail('ENABLEMENT_CONFLICT', `Profile patch already owns Loader entry \"${id}\"; it will not be overwritten.`)\n }\n if (existing === undefined) document.add({ id, disabled: true })\n }\n state.disabled[surface.packageName] = [...surface.entryIds]\n atomicWrite(file, document.toString())\n writeManagerState(dir, state)\n return [...surface.entryIds]\n}\n\nexport function enablePackage(dir: string, surface: PackageSurface): string[] {\n if (surface.packageName === MANAGER_PACKAGE) fail('PROTECTED_PLUGIN', 'The plugin manager cannot change its own enablement.')\n const state = readManagerState(dir)\n const owned = state.disabled[surface.packageName]\n if (owned === undefined || owned.length === 0) return []\n const file = join(dir, 'cordis.patch.yml')\n const document = patchDocument(file)\n const rows = document.toJS() as unknown[]\n for (const id of owned) {\n const matching = rows.filter(row => typeof row === 'object' && row !== null && !Array.isArray(row)\n && (row as { id?: unknown }).id === id)\n if (matching.some(row => !exactDisabledRow(row, id))) {\n fail('ENABLEMENT_CONFLICT', `Manager-owned Loader entry \"${id}\" was modified and will not be removed.`)\n }\n }\n const keep = rows.filter(row => !owned.some(id => exactDisabledRow(row, id)))\n document.contents = document.createNode(keep) as never\n delete state.disabled[surface.packageName]\n atomicWrite(file, document.toString())\n writeManagerState(dir, state)\n return [...owned]\n}\n\nfunction runtimeState(entries: LoaderEntrySnapshot[]): PluginStatus['runtime'] {\n const phases = entries.map(entry => entry.phase)\n if (phases.includes('failed')) return 'failed'\n if (phases.includes('active')) return 'active'\n if (phases.some(phase => phase === 'loading' || phase === 'pending')) return 'loading'\n if (entries.length > 0) return 'inactive'\n return 'unknown'\n}\n\nexport function listPluginStatuses(dir: string, loaderEntries: readonly LoaderEntrySnapshot[] = []): PluginStatus[] {\n const manifest = readProfileManifest(dir)\n const bundles = new Set(manifest.dsh?.profile?.bundles ?? [])\n const state = readManagerState(dir)\n return Object.entries(manifest.dependencies ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(([packageName, source]) => {\n const surface = packageSurface(dir, packageName, source)\n const ids = surface.entryIds\n const entries = ids === null ? [] : loaderEntries.filter(entry => ids.includes(entry.id))\n let enablement: PluginStatus['enablement'] = 'unknown'\n if (ids !== null) {\n const disabledIds = new Set(state.disabled[packageName] ?? [])\n const disabled = ids.filter(id => disabledIds.has(id) || entries.some(entry => entry.id === id && entry.disabled)).length\n enablement = disabled === 0 ? 'enabled' : disabled === ids.length ? 'disabled' : 'mixed'\n }\n const runtime = runtimeState(entries)\n return {\n packageName,\n source,\n bundle: bundles.has(packageName) || surface.bundle,\n enablement,\n runtime,\n restartRequired: surface.bundle && runtime === 'unknown' && !state.disabled[packageName],\n entryIds: ids,\n }\n })\n}\n","import { createHash, randomUUID } from 'node:crypto'\nimport { fail } from './errors.ts'\n\nexport type MutationAction = 'install' | 'remove' | 'update' | 'enable' | 'disable' | 'restart'\nexport type PlanAction = MutationAction | 'install_many'\n\nexport interface SinglePlanInput {\n action: MutationAction\n profile: 'web'\n packageName?: string\n installSpec?: string\n currentSource?: string\n impact: string\n restartExpected: boolean\n items?: never\n missingPeerDependencies?: never\n}\n\nexport interface InstallPlanItem {\n action: 'install'\n packageName: string\n installSpec: string\n impact: string\n restartExpected: boolean\n}\n\nexport interface MissingPeerDependency {\n packageName: string\n ranges: string[]\n requiredBy: string[]\n suggestedSource: string\n}\n\nexport interface InstallManyPlanInput {\n action: 'install_many'\n profile: 'web'\n items: InstallPlanItem[]\n missingPeerDependencies: MissingPeerDependency[]\n impact: string\n restartExpected: boolean\n packageName?: never\n installSpec?: never\n currentSource?: never\n}\n\nexport type PlanInput = SinglePlanInput | InstallManyPlanInput\n\ninterface ConfirmationFields {\n id: string\n digest: string\n confirmationToken: string\n createdAt: string\n expiresAt: string\n}\n\nexport type ConfirmationPlan<Input extends PlanInput = PlanInput> = Input & ConfirmationFields\n\nexport interface PlanStoreOptions {\n now?: () => number\n random?: () => string\n ttlMs?: number\n}\n\nexport class PlanStore {\n private readonly plans = new Map<string, ConfirmationPlan>()\n private readonly used = new Set<string>()\n private readonly now: () => number\n private readonly random: () => string\n private readonly ttlMs: number\n\n constructor(options: PlanStoreOptions = {}) {\n this.now = options.now ?? Date.now\n this.random = options.random ?? randomUUID\n this.ttlMs = options.ttlMs ?? 10 * 60_000\n }\n\n create<Input extends PlanInput>(input: Input): ConfirmationPlan<Input> {\n const created = this.now()\n const id = this.random()\n const confirmationToken = this.random()\n const snapshot = structuredClone(input)\n const digest = createHash('sha256').update(JSON.stringify({ id, ...snapshot })).digest('hex')\n const plan = deepFreeze({\n ...snapshot,\n id,\n digest,\n confirmationToken,\n createdAt: new Date(created).toISOString(),\n expiresAt: new Date(created + this.ttlMs).toISOString(),\n })\n this.plans.set(confirmationToken, plan)\n return plan as ConfirmationPlan<Input>\n }\n\n consume(token: string): ConfirmationPlan {\n if (this.used.has(token)) fail('CONFIRMATION_REPLAYED', 'Confirmation token has already been used.')\n const plan = this.plans.get(token)\n if (plan === undefined) fail('CONFIRMATION_REQUIRED', 'A valid confirmation token is required.')\n this.plans.delete(token)\n this.used.add(token)\n if (this.now() >= Date.parse(plan.expiresAt)) fail('CONFIRMATION_EXPIRED', 'Confirmation token has expired.')\n return plan\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null || Object.isFrozen(value)) return value\n for (const child of Object.values(value)) deepFreeze(child)\n return Object.freeze(value)\n}\n","import { randomUUID } from 'node:crypto'\nimport { fail } from './errors.ts'\nimport type { PlanAction } from './plans.ts'\n\nexport type OperationStatus =\n | 'queued'\n | 'running'\n | 'succeeded'\n | 'succeeded_restart_required'\n | 'waiting_for_manual_restart'\n | 'failed'\n | 'cancelled'\n\nexport type CompletedOperationStatus = Exclude<OperationStatus, 'queued' | 'running' | 'cancelled'>\n\nexport interface OperationSnapshot<T = unknown> {\n id: string\n action: PlanAction\n target: string\n status: OperationStatus\n progress: string\n startedAt: string\n finishedAt?: string\n result?: T\n error?: { code?: string; message: string }\n}\n\ninterface OperationRecord {\n snapshot: OperationSnapshot<unknown>\n controller: AbortController\n done: Promise<void>\n resolveDone(): void\n execute(context: OperationContext): Promise<unknown>\n complete(result: unknown): OperationCompletion\n}\n\nexport interface OperationContext {\n signal: AbortSignal\n progress(message: string): void\n}\n\nexport interface OperationCompletion {\n status: CompletedOperationStatus\n progress?: string\n error?: { code?: string; message: string }\n}\n\nexport class OperationTracker {\n private readonly records = new Map<string, OperationRecord>()\n private readonly queue: string[] = []\n private active: string | null = null\n private readonly random: () => string\n private readonly now: () => number\n\n constructor(options: { random?: () => string; now?: () => number } = {}) {\n this.random = options.random ?? randomUUID\n this.now = options.now ?? Date.now\n }\n\n start<T>(\n action: PlanAction,\n target: string,\n execute: (context: OperationContext) => Promise<T>,\n complete: (result: T) => OperationCompletion = () => ({ status: 'succeeded' }),\n ): OperationSnapshot<T> {\n const id = this.random()\n const controller = new AbortController()\n const snapshot: OperationSnapshot<T> = {\n id,\n action,\n target,\n status: 'queued',\n progress: 'queued',\n startedAt: new Date(this.now()).toISOString(),\n }\n let resolveDone!: () => void\n const record: OperationRecord = {\n snapshot,\n controller,\n done: new Promise<void>(resolve => { resolveDone = resolve }),\n resolveDone,\n execute: async context => await execute(context),\n complete: result => complete(result as T),\n }\n this.records.set(id, record)\n this.queue.push(id)\n queueMicrotask(() => this.drain())\n return structuredClone(snapshot)\n }\n\n private drain(): void {\n if (this.active !== null) return\n const id = this.queue.shift()\n if (id === undefined) return\n const record = this.records.get(id)\n if (record === undefined || record.snapshot.status !== 'queued') {\n queueMicrotask(() => this.drain())\n return\n }\n this.active = id\n void this.run(id, record)\n }\n\n private async run(id: string, record: OperationRecord): Promise<void> {\n const { snapshot, controller } = record\n snapshot.status = 'running'\n snapshot.progress = 'running'\n try {\n const result = await record.execute({\n signal: controller.signal,\n progress: message => { snapshot.progress = message.slice(0, 500) },\n })\n snapshot.result = result\n if (controller.signal.aborted) {\n snapshot.status = 'cancelled'\n snapshot.progress = 'cancelled'\n } else {\n const completion = record.complete(result)\n snapshot.status = completion.status\n snapshot.progress = completion.progress ?? 'completed'\n if (completion.error !== undefined) snapshot.error = completion.error\n }\n } catch (error) {\n if (controller.signal.aborted) {\n snapshot.status = 'cancelled'\n snapshot.progress = 'cancelled'\n } else {\n snapshot.status = 'failed'\n snapshot.progress = 'failed'\n snapshot.error = {\n ...typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string'\n ? { code: error.code }\n : {},\n message: error instanceof Error ? error.message : String(error),\n }\n }\n } finally {\n snapshot.finishedAt = new Date(this.now()).toISOString()\n if (this.active === id) this.active = null\n record.resolveDone()\n queueMicrotask(() => this.drain())\n }\n }\n\n get(id: string): OperationSnapshot {\n const record = this.records.get(id)\n if (record === undefined) fail('OPERATION_NOT_FOUND', `Plugin operation ${id} was not found.`)\n return structuredClone(record.snapshot)\n }\n\n cancel(id: string): OperationSnapshot {\n const record = this.records.get(id)\n if (record === undefined) fail('OPERATION_NOT_FOUND', `Plugin operation ${id} was not found.`)\n if (record.snapshot.status === 'queued') {\n const index = this.queue.indexOf(id)\n if (index >= 0) this.queue.splice(index, 1)\n record.controller.abort(new Error('Plugin operation cancelled by user.'))\n record.snapshot.status = 'cancelled'\n record.snapshot.progress = 'cancelled'\n record.snapshot.finishedAt = new Date(this.now()).toISOString()\n record.resolveDone()\n } else if (record.snapshot.status === 'running') {\n record.snapshot.progress = 'cancelling'\n record.controller.abort(new Error('Plugin operation cancelled by user.'))\n }\n return structuredClone(record.snapshot)\n }\n\n async wait(id: string): Promise<OperationSnapshot> {\n const record = this.records.get(id)\n if (record === undefined) fail('OPERATION_NOT_FOUND', `Plugin operation ${id} was not found.`)\n await record.done\n return this.get(id)\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { PluginSearchRuntime } from './search-runtime.ts'\nimport { searchPlugins, type SearchOptions, type SearchResult } from './search.ts'\nimport {\n inspectPluginSource,\n NPM_NAME,\n parseGithubSpec,\n parseNpmSpec,\n renderSource,\n type FetchOptions,\n type PluginInspection,\n} from './source.ts'\nimport {\n disablePackage,\n enablePackage,\n listPluginStatuses,\n packageSurface,\n profileManifestText,\n readProfileManifest,\n reconcileRemovedPackage,\n restoreProfileManifest,\n type LoaderEntrySnapshot,\n type PackageSurface,\n type PluginStatus,\n} from './profile.ts'\nimport {\n PlanStore,\n type ConfirmationPlan,\n type InstallPlanItem,\n type MissingPeerDependency,\n type MutationAction,\n type PlanAction,\n} from './plans.ts'\nimport {\n OperationTracker,\n type OperationCompletion,\n type OperationContext,\n type OperationSnapshot,\n} from './operations.ts'\nimport type { DshCliRunner, RunnerResult } from './runner.ts'\nimport type { HotRuntime, HotActivationResult } from './hot-runtime.ts'\nimport type { DshRestarter } from './restart.ts'\nimport { fail } from './errors.ts'\nimport type { Telemetry } from './telemetry.ts'\n\ninterface LoaderEntryLike {\n id?: string\n disabled?: boolean\n options?: { id?: string; name?: string }\n fiber?: { state?: number | string }\n}\n\ninterface LoaderLike {\n entries(): Iterable<LoaderEntryLike>\n}\n\nexport interface PluginManagerDependencies {\n profileDir: string\n searchRuntime: Pick<PluginSearchRuntime, 'entries'>\n runner: Pick<DshCliRunner, 'runPlugin'>\n hot: Pick<HotRuntime, 'activate' | 'deactivate' | 'isActive'>\n restarter: Pick<DshRestarter, 'available' | 'schedule'>\n loader?: LoaderLike\n inspect?: typeof inspectPluginSource\n plans?: PlanStore\n operations?: OperationTracker\n fetchOptions?: Omit<FetchOptions, 'signal'>\n hmrTimeoutMs?: number\n telemetry?: Telemetry\n}\n\nexport interface DiscoverRequest {\n action: 'list' | 'search' | 'inspect' | 'status'\n query?: string\n target?: string\n operationId?: string\n maxResults?: number\n}\n\nexport interface PlanRequest {\n operation: PlanAction\n target?: string\n source?: string\n sources?: string[]\n}\n\nexport interface MutationResult {\n action: MutationAction\n packageName?: string\n installSpec?: string\n changed: boolean\n activated?: boolean\n restartRequired: boolean\n reason?: string\n nextAction?: string\n command?: { exitCode: number; stdout: string; stderr: string }\n restart?: { helperPid: number | undefined; logFile: string }\n}\n\nexport type InstallManyItemStatus =\n | 'succeeded'\n | 'succeeded_restart_required'\n | 'waiting_for_manual_restart'\n | 'failed'\n | 'cancelled'\n | 'skipped'\n\nexport interface InstallManyItemResult {\n packageName: string\n installSpec: string\n status: InstallManyItemStatus\n result?: MutationResult\n error?: { code?: string; message: string }\n}\n\nexport interface InstallManyResult {\n action: 'install_many'\n changed: boolean\n restartRequired: boolean\n nextAction?: string\n items: InstallManyItemResult[]\n}\n\nconst MAX_INSTALL_MANY_SOURCES = 20\n\nconst FIBER_PHASE: Record<number, string | null> = {\n 0: 'pending',\n 1: 'loading',\n 2: 'active',\n 3: 'failed',\n 4: null,\n 5: 'unloading',\n}\n\nconst PROTECTED_ENTRY_IDS = new Set([\n 'relay-plugin-search-runtime',\n 'relay-plugin-manager-host',\n 'commands',\n 'tools',\n 'webserver',\n 'web-runtime',\n])\n\nconst TELEMETRY_ERROR_CODES = new Set([\n 'INVALID_SOURCE', 'INVALID_NPM_SPEC', 'INVALID_NPM_VERSION', 'INVALID_GITHUB_SPEC',\n 'INVALID_GITHUB_REF', 'GITHUB_OWNER_REQUIRES_SEARCH', 'IMMUTABLE_SOURCE_REQUIRED',\n 'NETWORK_ERROR', 'SOURCE_HTTP_ERROR', 'INVALID_SOURCE_METADATA', 'INVALID_PLUGIN_MANIFEST',\n 'NOT_DSH_PLUGIN', 'PACKAGE_NAME_MISMATCH', 'NPM_INTEGRITY_MISSING', 'INVALID_SEARCH_QUERY',\n 'INVALID_ACTION', 'INVALID_BATCH', 'DUPLICATE_SEARCH_PROVIDER', 'PROFILE_READ_FAILED',\n 'PROFILE_WRITE_FAILED', 'PLUGIN_NOT_INSTALLED', 'PLUGIN_ALREADY_INSTALLED',\n 'ENABLEMENT_UNSUPPORTED', 'ENABLEMENT_CONFLICT', 'PROTECTED_PLUGIN', 'CONFIRMATION_REQUIRED',\n 'CONFIRMATION_INVALID', 'CONFIRMATION_EXPIRED', 'CONFIRMATION_REPLAYED', 'PLAN_STALE',\n 'OPERATION_NOT_FOUND', 'DSH_COMMAND_FAILED', 'BATCH_INSTALL_FAILED', 'POSTCONDITION_FAILED',\n 'RESTART_UNAVAILABLE',\n])\n\nfunction safePackageName(value: string | undefined): string {\n const name = value?.trim() ?? ''\n if (!NPM_NAME.test(name)) fail('INVALID_NPM_SPEC', 'A valid installed package name is required.')\n return name\n}\n\nfunction queryLengthBucket(value: string | undefined): string {\n const length = value?.trim().length ?? 0\n if (length === 0) return 'empty'\n if (length <= 10) return '1-10'\n if (length <= 30) return '11-30'\n if (length <= 80) return '31-80'\n return '81+'\n}\n\nfunction commandResult(result: RunnerResult): MutationResult['command'] {\n return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr }\n}\n\nfunction operationError(error: unknown): { code?: string; message: string } {\n return {\n ...typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string'\n ? { code: error.code }\n : {},\n message: error instanceof Error ? error.message : String(error),\n }\n}\n\nfunction telemetryErrorCode(error: unknown): string {\n const code = operationError(error).code\n return code !== undefined && TELEMETRY_ERROR_CODES.has(code) ? code : 'UNKNOWN'\n}\n\nfunction installedPackageManifest(profileDir: string, packageName: string): { name?: unknown; version?: unknown } | null {\n try {\n return JSON.parse(readFileSync(join(profileDir, 'node_modules', packageName, 'package.json'), 'utf8')) as {\n name?: unknown\n version?: unknown\n }\n } catch {\n return null\n }\n}\n\nfunction installedSourceMatches(packageName: string, dependency: string, installSpec: string): boolean {\n const github = parseGithubSpec(installSpec, true)\n if (github !== null) return dependency === installSpec\n const npm = parseNpmSpec(installSpec, true)\n return npm.package === packageName && dependency === npm.version\n}\n\nexport class PluginManager {\n private readonly profileDir: string\n private readonly searchRuntime: PluginManagerDependencies['searchRuntime']\n private readonly runner: PluginManagerDependencies['runner']\n private readonly hot: PluginManagerDependencies['hot']\n private readonly restarter: PluginManagerDependencies['restarter']\n private readonly loader?: LoaderLike\n private readonly inspect: typeof inspectPluginSource\n private readonly plans: PlanStore\n private readonly operations: OperationTracker\n private readonly fetchOptions: Omit<FetchOptions, 'signal'>\n private readonly hmrTimeoutMs: number\n private readonly telemetry: Telemetry\n\n constructor(dependencies: PluginManagerDependencies) {\n this.profileDir = dependencies.profileDir\n this.searchRuntime = dependencies.searchRuntime\n this.runner = dependencies.runner\n this.hot = dependencies.hot\n this.restarter = dependencies.restarter\n this.loader = dependencies.loader\n this.inspect = dependencies.inspect ?? inspectPluginSource\n this.plans = dependencies.plans ?? new PlanStore()\n this.operations = dependencies.operations ?? new OperationTracker()\n this.fetchOptions = dependencies.fetchOptions ?? {}\n this.hmrTimeoutMs = dependencies.hmrTimeoutMs ?? 5_000\n this.telemetry = dependencies.telemetry ?? { capture() {} }\n }\n\n private capture(event: string, properties: Readonly<Record<string, string | number | boolean>> = {}): void {\n try {\n this.telemetry.capture(event, properties)\n } catch {\n // Analytics is deliberately best-effort and cannot affect plugin operations.\n }\n }\n\n private loaderEntries(): LoaderEntrySnapshot[] {\n if (this.loader === undefined) return []\n return [...this.loader.entries()].flatMap((entry) => {\n const id = entry.options?.id ?? entry.id\n if (id === undefined || id === '') return []\n const rawPhase = entry.fiber?.state\n const phase = typeof rawPhase === 'number' ? (FIBER_PHASE[rawPhase] ?? 'unknown') : rawPhase ?? null\n return [{\n id,\n ...(entry.options?.name === undefined ? {} : { name: entry.options.name }),\n disabled: entry.disabled === true,\n phase,\n }]\n })\n }\n\n list(): PluginStatus[] {\n return listPluginStatuses(this.profileDir, this.loaderEntries())\n }\n\n async discover(request: DiscoverRequest, signal?: AbortSignal): Promise<unknown> {\n this.capture('plugin_manager_used', {\n surface: 'discover',\n action: request.action,\n ...(request.action === 'search'\n ? { has_query: (request.query?.trim().length ?? 0) > 0, query_length_bucket: queryLengthBucket(request.query) }\n : {}),\n })\n if (request.action === 'list') return { profile: 'web', plugins: this.list() }\n if (request.action === 'search') {\n const options: SearchOptions = {\n ...this.fetchOptions,\n signal,\n maxResults: request.maxResults,\n inspect: this.inspect,\n }\n return await searchPlugins(this.searchRuntime, request.query ?? '', options)\n }\n if (request.action === 'inspect') {\n if (request.target === undefined) fail('INVALID_SOURCE', 'A plugin source is required for inspection.')\n return await this.inspect(request.target, { ...this.fetchOptions, signal })\n }\n if (request.operationId !== undefined) return this.operations.get(request.operationId)\n if (request.target === undefined) return { profile: 'web', plugins: this.list() }\n const name = safePackageName(request.target)\n const status = this.list().find(plugin => plugin.packageName === name)\n if (status === undefined) fail('PLUGIN_NOT_INSTALLED', `${name} is not installed in the web profile.`)\n return status\n }\n\n private installed(name: string): { source: string; surface: PackageSurface } {\n const source = readProfileManifest(this.profileDir).dependencies?.[name]\n if (source === undefined) fail('PLUGIN_NOT_INSTALLED', `${name} is not installed in the web profile.`)\n return { source, surface: packageSurface(this.profileDir, name, source) }\n }\n\n private assertEnablementAllowed(surface: PackageSurface): void {\n if (surface.entryIds?.some(id => PROTECTED_ENTRY_IDS.has(id)) === true) {\n fail('PROTECTED_PLUGIN', `${surface.packageName} owns protected DSH infrastructure and cannot be toggled.`)\n }\n }\n\n private async updateInspection(name: string, sourceOverride: string | undefined, signal?: AbortSignal): Promise<PluginInspection> {\n if (sourceOverride !== undefined) {\n const inspection = await this.inspect(sourceOverride, { ...this.fetchOptions, signal })\n if (inspection.packageName !== name) fail('PACKAGE_NAME_MISMATCH', 'Update source resolves to a different package name.')\n return inspection\n }\n const current = this.installed(name).source\n const github = parseGithubSpec(current)\n const source = github === null\n ? name\n : renderSource({ kind: 'github', owner: github.owner, repo: github.repo })\n return await this.inspect(source, { ...this.fetchOptions, signal })\n }\n\n async plan(request: PlanRequest, signal?: AbortSignal): Promise<ConfirmationPlan> {\n this.capture('plugin_manager_used', {\n surface: 'plan',\n action: request.operation,\n ...(request.operation === 'install_many' ? { batch_size: request.sources?.length ?? 0 } : {}),\n })\n if (request.operation === 'install_many') return await this.planInstallMany(request.sources, signal)\n if (request.operation === 'restart') {\n if (!this.restarter.available()) fail('RESTART_UNAVAILABLE', 'Automatic restart is unavailable in this deployment.')\n return this.plans.create({\n action: 'restart', profile: 'web', impact: 'Restart the running DSH process.', restartExpected: true,\n })\n }\n if (request.operation === 'install') {\n const source = request.source ?? request.target\n if (source === undefined) fail('INVALID_SOURCE', 'Install requires an npm or GitHub source.')\n const inspection = await this.inspect(source, { ...this.fetchOptions, signal })\n if (readProfileManifest(this.profileDir).dependencies?.[inspection.packageName] !== undefined) {\n fail('PLUGIN_ALREADY_INSTALLED', `${inspection.packageName} is already installed; use update.`)\n }\n return this.plans.create({\n action: 'install', profile: 'web', packageName: inspection.packageName,\n installSpec: inspection.installSpec,\n impact: `Install ${inspection.packageName} from ${inspection.installSpec}.`,\n restartExpected: inspection.bundlePatch !== null,\n })\n }\n const name = safePackageName(request.target)\n const installed = this.installed(name)\n if (request.operation === 'update') {\n const inspection = await this.updateInspection(name, request.source, signal)\n return this.plans.create({\n action: 'update', profile: 'web', packageName: name, currentSource: installed.source,\n installSpec: inspection.installSpec,\n impact: `Update ${name} from ${installed.source} to ${inspection.installSpec}.`,\n restartExpected: true,\n })\n }\n if (request.operation === 'enable' || request.operation === 'disable') {\n this.assertEnablementAllowed(installed.surface)\n if (installed.surface.entryIds === null) {\n fail('ENABLEMENT_UNSUPPORTED', `${name} has no safely attributable Loader entries.`)\n }\n }\n return this.plans.create({\n action: request.operation,\n profile: 'web',\n packageName: name,\n currentSource: installed.source,\n impact: request.operation === 'disable'\n ? `Disable ${name}. Conversations currently using capabilities from this plugin may be interrupted; confirm from another backend or session when continuity matters.`\n : `${request.operation[0]!.toUpperCase()}${request.operation.slice(1)} ${name}.`,\n restartExpected: request.operation === 'remove',\n })\n }\n\n private async planInstallMany(sources: string[] | undefined, signal?: AbortSignal): Promise<ConfirmationPlan> {\n if (sources === undefined || sources.length === 0 || sources.length > MAX_INSTALL_MANY_SOURCES) {\n fail('INVALID_BATCH', `Multi-install requires between 1 and ${MAX_INSTALL_MANY_SOURCES} sources.`)\n }\n const inspections = await Promise.all(sources.map(source => this.inspect(source, { ...this.fetchOptions, signal })))\n const profileDependencies = readProfileManifest(this.profileDir).dependencies ?? {}\n const requestedPackages = new Set<string>()\n for (const inspection of inspections) {\n if (requestedPackages.has(inspection.packageName)) {\n fail('INVALID_BATCH', `Multi-install resolves more than one source to ${inspection.packageName}.`)\n }\n if (profileDependencies[inspection.packageName] !== undefined) {\n fail('PLUGIN_ALREADY_INSTALLED', `${inspection.packageName} is already installed; use update.`)\n }\n requestedPackages.add(inspection.packageName)\n }\n\n const missing = new Map<string, { ranges: Set<string>; requiredBy: Set<string> }>()\n for (const inspection of inspections) {\n for (const [packageName, range] of Object.entries(inspection.peerDependencies)) {\n if (profileDependencies[packageName] !== undefined || requestedPackages.has(packageName)) continue\n const entry = missing.get(packageName) ?? { ranges: new Set<string>(), requiredBy: new Set<string>() }\n entry.ranges.add(range)\n entry.requiredBy.add(inspection.packageName)\n missing.set(packageName, entry)\n }\n }\n const missingPeerDependencies: MissingPeerDependency[] = [...missing]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([packageName, entry]) => ({\n packageName,\n ranges: [...entry.ranges].sort(),\n requiredBy: [...entry.requiredBy].sort(),\n suggestedSource: packageName,\n }))\n const items: InstallPlanItem[] = inspections.map(inspection => ({\n action: 'install',\n packageName: inspection.packageName,\n installSpec: inspection.installSpec,\n impact: `Install ${inspection.packageName} from ${inspection.installSpec}.`,\n restartExpected: inspection.bundlePatch !== null,\n }))\n return this.plans.create({\n action: 'install_many',\n profile: 'web',\n items,\n missingPeerDependencies,\n impact: `Install ${items.length} plugins serially: ${items.map(item => item.packageName).join(', ')}.`,\n restartExpected: items.some(item => item.restartExpected),\n })\n }\n\n execute(confirmationToken: string): OperationSnapshot {\n const plan = this.plans.consume(confirmationToken)\n this.assertPlanFresh(plan)\n if (plan.action === 'install_many') {\n const automaticRestartAvailable = this.restarter.available()\n return this.operations.start(\n 'install_many',\n `${plan.items.length} plugins`,\n async context => {\n this.assertPlanFresh(plan)\n return await this.installMany(plan.items, context, automaticRestartAvailable)\n },\n result => this.batchCompletion(result, automaticRestartAvailable),\n )\n }\n const target = plan.packageName ?? 'dsh'\n const automaticRestartAvailable = this.restarter.available()\n return this.operations.start(plan.action, target, async context => {\n this.assertPlanFresh(plan)\n if (plan.action === 'restart') {\n context.progress('scheduling restart')\n const restart = this.restarter.schedule()\n return { action: 'restart', changed: true, restartRequired: false, restart } satisfies MutationResult\n }\n if (plan.packageName === undefined) fail('POSTCONDITION_FAILED', 'Mutation plan has no package name.')\n if (plan.action === 'install' || plan.action === 'update') {\n if (plan.installSpec === undefined) fail('POSTCONDITION_FAILED', 'Install/update plan has no immutable source.')\n if (plan.action === 'install') this.capture('plugin_install_started', { plugin_name: plan.packageName })\n try {\n const result = this.withRestartGuidance(\n await this.installOrUpdate(plan.action, plan.packageName, plan.installSpec, context),\n automaticRestartAvailable,\n )\n if (plan.action === 'install') {\n this.capture('plugin_install_succeeded', {\n plugin_name: plan.packageName,\n activated: result.activated === true,\n restart_required: result.restartRequired,\n })\n }\n return result\n } catch (error) {\n if (plan.action === 'install') {\n this.capture('plugin_install_failed', {\n plugin_name: plan.packageName,\n error_code: telemetryErrorCode(error),\n })\n }\n throw error\n }\n }\n if (plan.action === 'remove') {\n return this.withRestartGuidance(await this.remove(plan.packageName, context), automaticRestartAvailable)\n }\n return this.withRestartGuidance(await this.toggle(plan.action, plan.packageName, context), automaticRestartAvailable)\n }, result => this.mutationCompletion(result, automaticRestartAvailable))\n }\n\n private assertPlanFresh(plan: ConfirmationPlan): void {\n const dependencies = readProfileManifest(this.profileDir).dependencies ?? {}\n if (plan.action === 'install_many') {\n for (const item of plan.items) {\n if (dependencies[item.packageName] !== undefined) {\n fail('PLAN_STALE', `${item.packageName} was installed after this plan was created; create a new plan.`)\n }\n }\n return\n }\n if (plan.action === 'install' && plan.packageName !== undefined && dependencies[plan.packageName] !== undefined) {\n fail('PLAN_STALE', `${plan.packageName} was installed after this plan was created; create a new plan.`)\n }\n if (plan.action !== 'install' && plan.action !== 'restart' && plan.packageName !== undefined\n && dependencies[plan.packageName] !== plan.currentSource) {\n fail('PLAN_STALE', `${plan.packageName} changed after this plan was created; create a new plan.`)\n }\n }\n\n private withRestartGuidance<Result extends { restartRequired: boolean; nextAction?: string }>(\n result: Result,\n automaticRestartAvailable: boolean,\n ): Result {\n if (!result.restartRequired) return result\n return {\n ...result,\n nextAction: automaticRestartAvailable\n ? 'Plan and confirm a separate DSH restart to activate this change.'\n : 'Restart DSH through the deployment supervisor or operator workflow to activate this change.',\n }\n }\n\n private mutationCompletion(\n result: { restartRequired: boolean },\n automaticRestartAvailable: boolean,\n ): { status: 'succeeded' | 'succeeded_restart_required' | 'waiting_for_manual_restart' } {\n if (!result.restartRequired) return { status: 'succeeded' }\n return { status: automaticRestartAvailable ? 'succeeded_restart_required' : 'waiting_for_manual_restart' }\n }\n\n private async installMany(\n items: readonly InstallPlanItem[],\n context: OperationContext,\n automaticRestartAvailable: boolean,\n ): Promise<InstallManyResult> {\n const results: InstallManyItemResult[] = []\n const skipRemaining = (start: number): void => {\n for (const item of items.slice(start)) {\n results.push({\n packageName: item.packageName,\n installSpec: item.installSpec,\n status: 'skipped',\n error: { message: 'Skipped because an earlier batch item did not complete.' },\n })\n }\n }\n\n for (const [index, item] of items.entries()) {\n if (context.signal.aborted) {\n results.push({\n packageName: item.packageName,\n installSpec: item.installSpec,\n status: 'cancelled',\n error: { message: 'Batch cancelled before this item started.' },\n })\n skipRemaining(index + 1)\n break\n }\n context.progress(`install_many: ${index + 1}/${items.length} installing ${item.packageName}`)\n this.capture('plugin_install_started', { plugin_name: item.packageName, batch: true })\n try {\n const result = this.withRestartGuidance(\n await this.installOrUpdate('install', item.packageName, item.installSpec, context),\n automaticRestartAvailable,\n )\n results.push({\n packageName: item.packageName,\n installSpec: item.installSpec,\n status: this.mutationCompletion(result, automaticRestartAvailable).status,\n result,\n })\n this.capture('plugin_install_succeeded', {\n plugin_name: item.packageName,\n batch: true,\n activated: result.activated === true,\n restart_required: result.restartRequired,\n })\n } catch (error) {\n results.push({\n packageName: item.packageName,\n installSpec: item.installSpec,\n status: context.signal.aborted ? 'cancelled' : 'failed',\n error: operationError(error),\n })\n this.capture('plugin_install_failed', {\n plugin_name: item.packageName,\n batch: true,\n error_code: telemetryErrorCode(error),\n })\n skipRemaining(index + 1)\n break\n }\n }\n const result: InstallManyResult = {\n action: 'install_many',\n changed: results.some(item => item.result?.changed === true),\n restartRequired: results.some(item => item.result?.restartRequired === true),\n items: results,\n }\n return this.withRestartGuidance(result, automaticRestartAvailable)\n }\n\n private batchCompletion(\n result: InstallManyResult,\n automaticRestartAvailable: boolean,\n ): OperationCompletion {\n const failed = result.items.find(item => item.status === 'failed')\n if (failed !== undefined) {\n return {\n status: 'failed',\n progress: `failed at ${failed.packageName}`,\n error: {\n code: 'BATCH_INSTALL_FAILED',\n message: `${failed.packageName} failed: ${failed.error?.message ?? 'unknown error'}`,\n },\n }\n }\n return this.mutationCompletion(result, automaticRestartAvailable)\n }\n\n operation(id: string): OperationSnapshot {\n return this.operations.get(id)\n }\n\n cancel(id: string): OperationSnapshot {\n return this.operations.cancel(id)\n }\n\n wait(id: string): Promise<OperationSnapshot> {\n return this.operations.wait(id)\n }\n\n private async installOrUpdate(\n action: 'install' | 'update',\n packageName: string,\n installSpec: string,\n context: { signal: AbortSignal; progress(message: string): void },\n ): Promise<MutationResult> {\n const before = profileManifestText(this.profileDir)\n context.progress(`${action}: running official DSH plugin command`)\n const result = await this.runner.runPlugin('web', ['add', '--save-exact', installSpec], context.signal, context.progress)\n if (result.exitCode !== 0 || result.timedOut || result.cancelled) {\n restoreProfileManifest(this.profileDir, before)\n fail('DSH_COMMAND_FAILED', `Official DSH plugin command failed with exit code ${result.exitCode}.`, commandResult(result))\n }\n const manifest = readProfileManifest(this.profileDir)\n const dependency = manifest.dependencies?.[packageName]\n const surface = dependency === undefined ? null : packageSurface(this.profileDir, packageName, dependency)\n const installedManifest = installedPackageManifest(this.profileDir, packageName)\n const bundleCount = manifest.dsh?.profile?.bundles?.filter(name => name === packageName).length ?? 0\n const validSurface = surface !== null && (surface.bundle || surface.client)\n const validBundleMembership = surface !== null && (surface.bundle ? bundleCount === 1 : bundleCount === 0)\n const validIdentity = installedManifest?.name === packageName\n const validSource = dependency !== undefined && installedSourceMatches(packageName, dependency, installSpec)\n const npmSource = parseGithubSpec(installSpec, true) === null ? parseNpmSpec(installSpec, true) : null\n const validVersion = npmSource === null || installedManifest?.version === npmSource.version\n if (!validSource || !validSurface || !validBundleMembership || !validIdentity || !validVersion) {\n restoreProfileManifest(this.profileDir, before)\n fail('POSTCONDITION_FAILED', `Official command completed but ${packageName} did not satisfy profile postconditions.`)\n }\n let activation: HotActivationResult\n if (action === 'update') {\n activation = { active: false, restartRequired: true, reason: 'Updated bundles activate after DSH restart.' }\n } else {\n context.progress('install: attempting restart-free activation')\n activation = await this.hot.activate(surface)\n }\n return {\n action,\n packageName,\n installSpec,\n changed: true,\n activated: activation.active,\n restartRequired: activation.restartRequired,\n ...(activation.reason === null ? {} : { reason: activation.reason }),\n command: commandResult(result),\n }\n }\n\n private async remove(\n packageName: string,\n context: { signal: AbortSignal; progress(message: string): void },\n ): Promise<MutationResult> {\n this.installed(packageName)\n const before = profileManifestText(this.profileDir)\n const wasHot = this.hot.isActive(packageName)\n context.progress('remove: running official DSH plugin command')\n const result = await this.runner.runPlugin('web', ['remove', packageName], context.signal, context.progress)\n const packageExists = existsSync(join(this.profileDir, 'node_modules', packageName, 'package.json'))\n if (result.exitCode !== 0 || result.timedOut || result.cancelled) {\n if (!result.cancelled && !packageExists) reconcileRemovedPackage(this.profileDir, packageName)\n else restoreProfileManifest(this.profileDir, before)\n if (packageExists || result.cancelled) {\n fail('DSH_COMMAND_FAILED', `Official DSH plugin remove failed with exit code ${result.exitCode}.`, commandResult(result))\n }\n }\n const manifest = readProfileManifest(this.profileDir)\n const remains = manifest.dependencies?.[packageName] !== undefined\n || manifest.dsh?.profile?.bundles?.includes(packageName) === true\n if (remains) fail('POSTCONDITION_FAILED', `${packageName} remains in the profile after removal.`)\n const deactivated = wasHot ? await this.hot.deactivate(packageName) : false\n return {\n action: 'remove',\n packageName,\n changed: true,\n activated: false,\n restartRequired: !deactivated,\n ...deactivated ? {} : { reason: 'A boot-loaded plugin remains in the current process until DSH restarts.' },\n command: commandResult(result),\n }\n }\n\n private async toggle(\n action: 'enable' | 'disable',\n packageName: string,\n context: { signal: AbortSignal; progress(message: string): void },\n ): Promise<MutationResult> {\n const { surface } = this.installed(packageName)\n this.assertEnablementAllowed(surface)\n context.progress(`${action}: updating profile patch`)\n const ids = action === 'disable' ? disablePackage(this.profileDir, surface) : enablePackage(this.profileDir, surface)\n if (action === 'disable' && this.hot.isActive(packageName)) await this.hot.deactivate(packageName)\n if (action === 'enable' && !this.loaderEntries().some(entry => surface.entryIds?.includes(entry.id))) {\n const activation = await this.hot.activate(surface)\n return {\n action, packageName, changed: ids.length > 0, activated: activation.active,\n restartRequired: activation.restartRequired,\n ...(activation.reason === null ? {} : { reason: activation.reason }),\n }\n }\n const expectedDisabled = action === 'disable'\n const deadline = Date.now() + this.hmrTimeoutMs\n let verified = false\n while (Date.now() < deadline && !context.signal.aborted) {\n const relevant = this.loaderEntries().filter(entry => surface.entryIds?.includes(entry.id))\n if (relevant.length > 0 && relevant.every(entry => entry.disabled === expectedDisabled)) {\n verified = true\n break\n }\n await new Promise(resolve => setTimeout(resolve, 50))\n }\n return {\n action,\n packageName,\n changed: ids.length > 0,\n activated: action === 'enable' && verified,\n restartRequired: !verified,\n ...verified ? {} : { reason: 'Loader HMR state could not be verified; restart is required.' },\n }\n }\n}\n\nexport type { SearchResult }\n","import type { PluginSearchProvider } from './search-runtime.ts'\nimport { isGithubPart, NPM_NAME } from './source.ts'\n\nconst MAX_PROVIDER_RESULTS = 20\nconst REGISTRY_SNAPSHOT_ID = /^discovery\\.[a-z0-9.-]+$/u\n\nfunction query(value: string): string {\n const normalized = value.trim()\n if (normalized === '' || normalized.length > 120 || /[\\u0000-\\u001f\\u007f]/u.test(normalized)) {\n throw new Error('Search query must contain 1 to 120 printable characters.')\n }\n return normalized\n}\n\nexport function npmSearchProvider(fetchImpl: typeof globalThis.fetch = globalThis.fetch): PluginSearchProvider {\n return {\n id: 'npm',\n async search(request) {\n const text = query(request.query)\n const response = await fetchImpl(\n `https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(`${text} keywords:dsh-plugin`)}&size=${Math.min(request.maxResults, MAX_PROVIDER_RESULTS)}`,\n { signal: request.signal, headers: { accept: 'application/json' } },\n )\n if (!response.ok) throw new Error(`npm search returned HTTP ${response.status}`)\n const data = await response.json() as { objects?: Array<{ package?: { name?: unknown; description?: unknown; links?: { homepage?: unknown; repository?: unknown } }; score?: { final?: unknown } }> }\n const searched = (data.objects ?? []).flatMap((entry) => {\n const name = entry.package?.name\n if (typeof name !== 'string' || !NPM_NAME.test(name)) return []\n return [{\n id: `npm:${name}`,\n title: name,\n ...(typeof entry.package?.description === 'string' ? { description: entry.package.description } : {}),\n ...(typeof entry.package?.links?.homepage === 'string' ? { homepage: entry.package.links.homepage } : {}),\n ...(typeof entry.package?.links?.repository === 'string' ? { repository: entry.package.links.repository } : {}),\n sources: [{ kind: 'npm' as const, package: name }],\n ...(typeof entry.score?.final === 'number' ? { score: entry.score.final } : {}),\n }]\n })\n if (!NPM_NAME.test(text) || searched.some(candidate => candidate.sources.some(source => source.kind === 'npm' && source.package === text))) {\n return searched\n }\n return [{\n id: `npm:${text}`,\n title: text,\n sources: [{ kind: 'npm' as const, package: text }],\n score: Number.MAX_SAFE_INTEGER,\n evidence: ['Exact npm package-name query'],\n }, ...searched]\n },\n }\n}\n\nexport function githubSearchProvider(\n fetchImpl: typeof globalThis.fetch = globalThis.fetch,\n env: NodeJS.ProcessEnv = process.env,\n): PluginSearchProvider {\n return {\n id: 'github',\n async search(request) {\n const text = query(request.query)\n const token = env.GITHUB_TOKEN ?? env.GH_TOKEN\n type Repository = {\n id?: unknown\n full_name?: unknown\n description?: unknown\n html_url?: unknown\n stargazers_count?: unknown\n }\n const search = async (searchText: string): Promise<{ response: Response; items: Repository[] }> => {\n const response = await fetchImpl(\n `https://api.github.com/search/repositories?q=${encodeURIComponent(searchText)}&per_page=${Math.min(request.maxResults, MAX_PROVIDER_RESULTS)}`,\n {\n signal: request.signal,\n headers: {\n accept: 'application/vnd.github+json',\n 'user-agent': 'relay-dsh-plugin-manager',\n 'x-github-api-version': '2022-11-28',\n ...(token === undefined || token === '' ? {} : { authorization: `Bearer ${token}` }),\n },\n },\n )\n if (!response.ok) return { response, items: [] }\n const data = await response.json() as { items?: Repository[] }\n return { response, items: data.items ?? [] }\n }\n\n const owner = request.intent?.kind === 'github-owner' ? request.intent.owner : undefined\n let exactOwner = owner !== undefined\n let result = await search(owner === undefined\n ? `${text} topic:dsh-plugin`\n : `user:${owner} topic:dsh-plugin`)\n let entries = result.items\n if (owner !== undefined) {\n entries = entries.filter(entry => typeof entry.full_name === 'string'\n && entry.full_name.split('/')[0]?.toLowerCase() === owner.toLowerCase())\n const shouldFallback = request.intent?.fallbackToText === true\n && (result.response.status === 422 || (result.response.ok && entries.length === 0))\n if (shouldFallback) {\n result = await search(`${text} topic:dsh-plugin`)\n entries = result.items\n exactOwner = false\n }\n }\n if (!result.response.ok) throw new Error(`GitHub search returned HTTP ${result.response.status}`)\n\n return entries.flatMap((entry) => {\n if (typeof entry.full_name !== 'string') return []\n const [repositoryOwner, repo, ...extra] = entry.full_name.split('/')\n if (repositoryOwner === undefined || repo === undefined || extra.length > 0) return []\n return [{\n id: `github:${entry.id ?? entry.full_name}`,\n title: entry.full_name,\n ...(typeof entry.description === 'string' ? { description: entry.description } : {}),\n ...(typeof entry.html_url === 'string' ? { homepage: entry.html_url, repository: entry.html_url } : {}),\n sources: [{ kind: 'github' as const, owner: repositoryOwner, repo }],\n ...(typeof entry.stargazers_count === 'number' ? { score: entry.stargazers_count } : {}),\n evidence: [\n `GitHub repository owner: ${repositoryOwner}`,\n ...(exactOwner ? [`Exact GitHub owner query: ${owner!}`] : []),\n `GitHub stars: ${String(entry.stargazers_count ?? 0)}`,\n ],\n ...(exactOwner ? { match: { kind: 'github-owner' as const, value: owner! } } : {}),\n }]\n })\n },\n }\n}\n\nfunction registryEndpoint(value: string): string {\n let url: URL\n try { url = new URL(value) } catch { throw new Error('Registry URL must be an absolute URL.') }\n const local = url.hostname === '127.0.0.1' || url.hostname === 'localhost' || url.hostname === '::1'\n if (url.protocol !== 'https:' && !(local && url.protocol === 'http:')) {\n throw new Error('Registry URL must use HTTPS, except for an explicit local development endpoint.')\n }\n if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {\n throw new Error('Registry URL cannot contain credentials, query parameters, or a fragment.')\n }\n url.pathname = `${url.pathname.replace(/\\/$/u, '')}/v1/plugins:search`\n return url.href\n}\n\nfunction boundedText(value: unknown, maximum = 4_000): string | undefined {\n return typeof value === 'string' && value.trim() !== '' && value.length <= maximum ? value : undefined\n}\n\nfunction queryLocale(value: string): 'zh-CN' | 'en' {\n return /\\p{Script=Han}/u.test(value) ? 'zh-CN' : 'en'\n}\n\nfunction registryCandidate(value: unknown, snapshotId: string): Awaited<ReturnType<PluginSearchProvider['search']>>[number] | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null\n const candidate = value as {\n entry?: {\n entry_id?: unknown\n identity?: { name?: unknown; repository_url?: unknown; repository_full_name?: unknown }\n imported_content?: { description?: { 'zh-CN'?: unknown; en?: unknown }; trust?: unknown }\n sources?: unknown\n resolution?: { status?: unknown }\n }\n match?: { score?: unknown; reason_codes?: unknown }\n }\n const entry = candidate.entry\n if (typeof entry !== 'object' || entry === null\n || boundedText(entry.entry_id, 100) === undefined\n || boundedText(entry.identity?.name, 214) === undefined\n || entry.imported_content?.trust !== 'untrusted_text'\n || entry.resolution?.status !== 'source_only'\n || !Array.isArray(entry.sources)) return null\n const sources = entry.sources.flatMap((source): Array<{ kind: 'npm'; package: string } | { kind: 'github'; owner: string; repo: string; ref?: string }> => {\n if (typeof source !== 'object' || source === null || Array.isArray(source)) return []\n const item = source as { kind?: unknown; package_name?: unknown; repository?: unknown; spec?: unknown; exact?: unknown }\n if (item.exact !== false) return []\n if (item.kind === 'npm' && typeof item.package_name === 'string' && NPM_NAME.test(item.package_name)) {\n return [{ kind: 'npm', package: item.package_name }]\n }\n if (item.kind !== 'github' || typeof item.repository !== 'string' || typeof item.spec !== 'string') return []\n const [owner, repo, ...extra] = item.repository.split('/')\n if (owner === undefined || repo === undefined || extra.length > 0 || !isGithubPart(owner) || !isGithubPart(repo)) return []\n const prefix = `github:${item.repository}`\n if (!item.spec.startsWith(prefix)) return []\n const suffix = item.spec.slice(prefix.length)\n if (suffix !== '' && !suffix.startsWith('#')) return []\n return [{ kind: 'github', owner, repo, ...(suffix === '' ? {} : { ref: suffix.slice(1) }) }]\n })\n if (sources.length === 0) return null\n const zh = boundedText(entry.imported_content?.description?.['zh-CN'])\n const en = boundedText(entry.imported_content?.description?.en)\n const repository = boundedText(entry.identity?.repository_url, 500)\n const reasonCodes = Array.isArray(candidate.match?.reason_codes)\n ? candidate.match.reason_codes.filter((item): item is string => typeof item === 'string' && /^[a-z0-9_]+$/u.test(item)).slice(0, 8)\n : []\n const score = typeof candidate.match?.score === 'number' && Number.isFinite(candidate.match.score) && candidate.match.score >= 0\n ? candidate.match.score\n : undefined\n return {\n id: `registry:${entry.entry_id}`,\n title: entry.identity!.name as string,\n ...(zh !== undefined || en !== undefined ? { description: zh ?? en } : {}),\n ...(repository === undefined ? {} : { homepage: repository, repository }),\n sources,\n ...(score === undefined ? {} : { score }),\n evidence: [\n `DSH Registry source snapshot: ${snapshotId}`,\n 'Registry discovery record only; compatibility and security not tested',\n ...reasonCodes.map(code => `Registry match: ${code}`),\n ],\n }\n}\n\nexport function registrySearchProvider(\n baseUrl: string,\n fetchImpl: typeof globalThis.fetch = globalThis.fetch,\n): PluginSearchProvider {\n const endpoint = registryEndpoint(baseUrl)\n return {\n id: 'dsh-registry',\n async search(request) {\n const text = query(request.query)\n const response = await fetchImpl(endpoint, {\n method: 'POST',\n signal: request.signal,\n headers: { accept: 'application/json', 'content-type': 'application/json' },\n body: JSON.stringify({\n schema_version: '1.0.0', query: text, locale: queryLocale(text),\n limit: Math.min(request.maxResults, MAX_PROVIDER_RESULTS),\n }),\n })\n if (!response.ok) throw new Error(`DSH Registry search returned HTTP ${response.status}`)\n const data = await response.json() as { snapshot_id?: unknown; candidates?: unknown }\n if (typeof data.snapshot_id !== 'string' || !REGISTRY_SNAPSHOT_ID.test(data.snapshot_id) || !Array.isArray(data.candidates)) {\n throw new Error('DSH Registry search returned an invalid discovery response.')\n }\n return data.candidates.flatMap(candidate => {\n const normalized = registryCandidate(candidate, data.snapshot_id as string)\n return normalized === null ? [] : [normalized]\n }).slice(0, Math.min(request.maxResults, MAX_PROVIDER_RESULTS))\n },\n }\n}\n","import { spawn } from 'node:child_process'\nimport { join } from 'node:path'\nimport { tmpdir } from 'node:os'\nimport { writeFileSync } from 'node:fs'\nimport { fail } from './errors.ts'\n\nexport function detectedSupervisor(env: NodeJS.ProcessEnv = process.env, ppid = process.ppid): string | null {\n const systemd = (env.INVOCATION_ID ?? '') !== '' || (env.JOURNAL_STREAM ?? '') !== ''\n return systemd && ppid === 1 ? 'systemd' : null\n}\n\nexport function restartAllowed(\n allowRestart: boolean | undefined,\n env: NodeJS.ProcessEnv = process.env,\n ppid = process.ppid,\n): boolean {\n if (allowRestart !== undefined) return allowRestart\n return detectedSupervisor(env, ppid) === null\n}\n\nexport interface RestarterOptions {\n allowRestart?: boolean\n env?: NodeJS.ProcessEnv\n argv?: string[]\n execPath?: string\n cwd?: string\n ppid?: number\n spawn?: typeof spawn\n terminate?: () => void\n}\n\nexport class DshRestarter {\n private readonly options: RestarterOptions\n\n constructor(options: RestarterOptions = {}) {\n this.options = options\n }\n\n available(): boolean {\n return restartAllowed(this.options.allowRestart, this.options.env, this.options.ppid)\n }\n\n schedule(): { helperPid: number | undefined; logFile: string } {\n if (!this.available()) fail('RESTART_UNAVAILABLE', 'Automatic restart is disabled or owned by the process supervisor.')\n const argv = this.options.argv ?? process.argv\n if (argv[1] === undefined) fail('RESTART_UNAVAILABLE', 'The current DSH entry point cannot be identified.')\n const execPath = this.options.execPath ?? process.execPath\n const cwd = this.options.cwd ?? process.cwd()\n const env = this.options.env ?? process.env\n const logFile = join(tmpdir(), `relay-dsh-plugin-manager-restart-${Date.now()}.log`)\n const source = [\n \"const { spawn } = require('node:child_process')\",\n \"const fs = require('node:fs')\",\n 'setTimeout(() => {',\n ` const out = fs.openSync(${JSON.stringify(logFile)}, 'a')`,\n ` const child = spawn(${JSON.stringify(execPath)}, ${JSON.stringify(argv.slice(1))}, {`,\n ` cwd: ${JSON.stringify(cwd)}, env: process.env, detached: true, stdio: ['ignore', out, out]`,\n ' })',\n \" child.on('error', error => fs.appendFileSync(\" + JSON.stringify(logFile) + \", String(error) + '\\\\n'))\",\n ' child.unref()',\n '}, 1200)',\n ].join('\\n')\n writeFileSync(logFile, '', { flag: 'a', mode: 0o600 })\n const helper = (this.options.spawn ?? spawn)(execPath, ['-e', source], {\n detached: true,\n stdio: 'ignore',\n env,\n })\n helper.unref()\n setTimeout(this.options.terminate ?? (() => process.kill(process.pid, 'SIGTERM')), 500).unref()\n return { helperPid: helper.pid, logFile }\n }\n}\n","import { spawn, type ChildProcess } from 'node:child_process'\nimport { existsSync, realpathSync } from 'node:fs'\n\nexport interface DshLaunch {\n file: string\n prefix: string[]\n cwd: string\n shell: boolean\n}\n\nexport interface RunnerResult {\n exitCode: number\n signal: NodeJS.Signals | null\n stdout: string\n stderr: string\n cancelled: boolean\n timedOut: boolean\n}\n\nexport interface RunnerOptions {\n env?: NodeJS.ProcessEnv\n argv?: string[]\n execPath?: string\n cwd?: string\n platform?: NodeJS.Platform\n spawn?: typeof spawn\n timeoutMs?: number\n maxOutputBytes?: number\n}\n\nexport function resolveDshLaunch(options: RunnerOptions = {}): DshLaunch {\n const env = options.env ?? process.env\n const argv = options.argv ?? process.argv\n const execPath = options.execPath ?? process.execPath\n const cwd = options.cwd ?? process.cwd()\n const platform = options.platform ?? process.platform\n const configured = env.DSH_EXECUTABLE?.trim()\n let file: string\n let prefix: string[]\n if (configured !== undefined && configured !== '') {\n file = configured\n prefix = []\n } else if (argv[1] !== undefined && existsSync(argv[1])) {\n file = execPath\n prefix = [realpathSync(argv[1])]\n } else {\n file = 'dsh'\n prefix = []\n }\n return {\n file,\n prefix,\n cwd,\n shell: platform === 'win32' && /\\.(?:cmd|bat)$/iu.test(file),\n }\n}\n\nfunction boundedAppend(current: string, chunk: Buffer | string, maxBytes: number): string {\n const combined = current + chunk.toString()\n return Buffer.byteLength(combined) <= maxBytes ? combined : combined.slice(-maxBytes)\n}\n\nexport class DshCliRunner {\n private readonly options: RunnerOptions\n\n constructor(options: RunnerOptions = {}) {\n this.options = options\n }\n\n runPlugin(\n profile: string,\n args: readonly string[],\n signal: AbortSignal,\n progress: (message: string) => void = () => undefined,\n ): Promise<RunnerResult> {\n const launch = resolveDshLaunch(this.options)\n const spawnImpl = this.options.spawn ?? spawn\n const timeoutMs = this.options.timeoutMs ?? 5 * 60_000\n const maxOutput = this.options.maxOutputBytes ?? 64 * 1024\n return new Promise((resolve, reject) => {\n let child: ChildProcess\n try {\n child = spawnImpl(\n launch.file,\n [...launch.prefix, 'plugin', '--profile', profile, ...args],\n {\n cwd: launch.cwd,\n env: this.options.env ?? process.env,\n shell: launch.shell,\n stdio: ['ignore', 'pipe', 'pipe'],\n },\n )\n } catch (error) {\n reject(error)\n return\n }\n let stdout = ''\n let stderr = ''\n let timedOut = false\n let cancelled = false\n let settled = false\n const terminate = (reason: 'timeout' | 'cancel'): void => {\n if (reason === 'timeout') timedOut = true\n else cancelled = true\n child.kill('SIGTERM')\n setTimeout(() => { if (!settled) child.kill('SIGKILL') }, 2_000).unref()\n }\n const timer = setTimeout(() => terminate('timeout'), timeoutMs)\n const onAbort = (): void => terminate('cancel')\n if (signal.aborted) onAbort()\n else signal.addEventListener('abort', onAbort, { once: true })\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout = boundedAppend(stdout, chunk, maxOutput)\n progress(chunk.toString().trim().slice(-500))\n })\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr = boundedAppend(stderr, chunk, maxOutput)\n progress(chunk.toString().trim().slice(-500))\n })\n child.once('error', (error) => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n settled = true\n reject(error)\n })\n child.once('close', (code, closeSignal) => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n settled = true\n resolve({\n exitCode: code ?? 1,\n signal: closeSignal,\n stdout,\n stderr,\n cancelled,\n timedOut,\n })\n })\n })\n }\n}\n","import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\n\nconst DEFAULT_ENDPOINT = 'https://dsh-plugins.tech/v1/telemetry/events'\nconst STATE_DIRECTORY = '.relay-plugin-manager'\nconst STATE_FILE = 'telemetry.json'\nconst SCHEMA_VERSION = '1.1.0'\nconst EVENTS = new Set([\n 'plugin_manager_used',\n 'plugin_install_started',\n 'plugin_install_succeeded',\n 'plugin_install_failed',\n])\n\nexport type TelemetryProperty = string | number | boolean\n\nexport interface Telemetry {\n capture(event: string, properties?: Readonly<Record<string, TelemetryProperty>>): void\n}\n\nexport interface TelemetryConfig {\n /** Anonymous operational telemetry is enabled unless this is explicitly false. */\n enabled?: boolean\n /** Registry telemetry endpoint. Only the canonical service or localhost is accepted. */\n endpoint?: string\n /** Marks an operator-controlled acceptance run so analytics can exclude it. */\n test?: boolean\n}\n\ninterface TelemetryRuntime {\n fetch: typeof fetch\n random(): string\n}\n\nconst noopTelemetry: Telemetry = Object.freeze({ capture() {} })\n\nfunction safeEndpoint(value: string | undefined): string | null {\n try {\n const parsed = new URL(value ?? DEFAULT_ENDPOINT)\n const local = ['localhost', '127.0.0.1', '::1'].includes(parsed.hostname)\n const canonical = parsed.protocol === 'https:' && parsed.hostname === 'dsh-plugins.tech'\n if ((!local && !canonical) || (local && !['http:', 'https:'].includes(parsed.protocol))) return null\n if (parsed.username !== '' || parsed.password !== '' || parsed.pathname !== '/v1/telemetry/events'\n || parsed.search !== '' || parsed.hash !== '') return null\n return parsed.href\n } catch {\n return null\n }\n}\n\nfunction anonymousId(profileDir: string, random: () => string): string {\n const directory = join(profileDir, STATE_DIRECTORY)\n const path = join(directory, STATE_FILE)\n try {\n const existing = JSON.parse(readFileSync(path, 'utf8')) as { anonymousId?: unknown }\n if (typeof existing.anonymousId === 'string' && /^[0-9a-f-]{36}$/iu.test(existing.anonymousId)) {\n return existing.anonymousId\n }\n } catch {\n // A missing or damaged local state file is replaced below.\n }\n const id = random()\n try {\n mkdirSync(directory, { recursive: true, mode: 0o700 })\n writeFileSync(path, `${JSON.stringify({ anonymousId: id })}\\n`, { mode: 0o600 })\n } catch {\n // Telemetry must never block plugin management; the process-scoped id still works.\n }\n return id\n}\n\nfunction allowedProperties(event: string, properties: Readonly<Record<string, TelemetryProperty>>): boolean {\n const keys = new Set(Object.keys(properties))\n const exact = (required: readonly string[], optional: readonly string[] = []): boolean => {\n if (required.some(key => !keys.has(key))) return false\n return [...keys].every(key => required.includes(key) || optional.includes(key))\n }\n if (event === 'plugin_manager_used') {\n if (!exact(['surface', 'action'], ['has_query', 'query_length_bucket', 'batch_size'])) return false\n if (!['discover', 'plan'].includes(String(properties.surface))) return false\n return typeof properties.action === 'string'\n }\n if (event === 'plugin_install_started') return exact(['plugin_name'], ['batch'])\n if (event === 'plugin_install_succeeded') return exact(['plugin_name', 'activated', 'restart_required'], ['batch'])\n if (event === 'plugin_install_failed') return exact(['plugin_name', 'error_code'], ['batch'])\n return false\n}\n\nexport function createTelemetry(\n profileDir: string,\n config: TelemetryConfig | undefined,\n runtime: TelemetryRuntime = { fetch, random: randomUUID },\n): Telemetry {\n if (config?.enabled === false) return noopTelemetry\n const endpoint = safeEndpoint(config?.endpoint)\n if (endpoint === null) return noopTelemetry\n let distinctId: string | undefined\n\n return Object.freeze({\n capture(event: string, properties: Readonly<Record<string, TelemetryProperty>> = {}): void {\n if (!EVENTS.has(event) || !allowedProperties(event, properties)) return\n distinctId ??= anonymousId(profileDir, runtime.random)\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 5_000)\n timeout.unref?.()\n try {\n void runtime.fetch(endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n schema_version: SCHEMA_VERSION,\n anonymous_id: distinctId,\n event,\n properties,\n ...(config?.test === true ? { is_test: true } : {}),\n }),\n signal: controller.signal,\n }).catch(() => undefined).finally(() => clearTimeout(timeout))\n } catch {\n clearTimeout(timeout)\n }\n },\n })\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport '@deepseek-ai/cordis-plugin-loader'\nimport '@deepseek-ai/dsh-user-questions'\nimport { registerConversationSurface } from './conversation.ts'\nimport { HotRuntime } from './hot-runtime.ts'\nimport { PluginManager } from './manager.ts'\nimport { profileDirectory } from './profile.ts'\nimport { githubSearchProvider, npmSearchProvider, registrySearchProvider } from './providers.ts'\nimport { DshRestarter } from './restart.ts'\nimport { DshCliRunner } from './runner.ts'\nimport { createTelemetry, type TelemetryConfig } from './telemetry.ts'\n\nexport const name = 'relay-dsh-plugin-manager'\nexport const inject = ['pluginSearch', 'tools', 'commands', 'userQuestions', 'loader']\nexport const DEFAULT_REGISTRY_ORIGIN = 'https://dsh-plugins.tech'\n\nexport interface Config {\n allowRestart?: boolean\n registryUrl?: string | false\n telemetry?: TelemetryConfig\n}\n\nexport function apply(ctx: Context, config: Config = {}): void {\n const profileDir = profileDirectory('web')\n const telemetry = config.telemetry ?? {\n enabled: process.env.RELAY_PLUGIN_MANAGER_TELEMETRY !== '0',\n endpoint: process.env.RELAY_PLUGIN_MANAGER_TELEMETRY_ENDPOINT,\n test: process.env.RELAY_PLUGIN_MANAGER_TELEMETRY_TEST === '1',\n }\n ctx.pluginSearch.register(npmSearchProvider())\n ctx.pluginSearch.register(githubSearchProvider())\n const configuredRegistryUrl = config.registryUrl ?? process.env.DSH_PLUGIN_REGISTRY_URL?.trim()\n const registryUrl = config.registryUrl === false ? undefined : configuredRegistryUrl || DEFAULT_REGISTRY_ORIGIN\n if (registryUrl !== undefined) ctx.pluginSearch.register(registrySearchProvider(registryUrl))\n\n const manager = new PluginManager({\n profileDir,\n searchRuntime: ctx.pluginSearch,\n runner: new DshCliRunner(),\n hot: new HotRuntime(ctx, profileDir),\n restarter: new DshRestarter({ allowRestart: config.allowRestart }),\n loader: ctx.loader,\n telemetry: createTelemetry(profileDir, telemetry),\n })\n registerConversationSurface(ctx, manager)\n}\n\nexport { PluginManager } from './manager.ts'\nexport type {\n DiscoverRequest,\n InstallManyItemResult,\n InstallManyItemStatus,\n InstallManyResult,\n MutationResult,\n PlanRequest,\n} from './manager.ts'\nexport type {\n PluginSearchCandidate,\n PluginSearchMatch,\n PluginSearchProvider,\n PluginSearchRequest,\n} from './search-runtime.ts'\nexport type { PluginInspection, PluginSource } from './source.ts'\nexport type { TelemetryConfig } from './telemetry.ts'\n"],"mappings":";;;;;;;;;;;;;AAWA,SAAS,UAAU,OAA2B;CAC5C,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;AAEA,SAAS,WAAW,OAAgB,OAAyD;CAC3F,OAAO,CAAC;EAAE,MAAM;EAAQ,MAAM,KAAK,UAAU,OAAO,MAAM,CAAC;CAAE,CAAC;AAChE;AASA,MAAM,gBAAgB;AACtB,MAAM,gBAAgB;AAEtB,SAAS,cAAc,SAA+D;CACpF,MAAM,WAAW,QAAQ,IAAI,SAAS,gBAAgB;CACtD,IAAI,OAAO,aAAa,YACtB,OAAO,QAAQ,MAAM,UAAU,SAAS,CAAC,CAAC;CAE5C,MAAM,SAAS,QAAQ,IAAI,SAAS,QAAQ;CAC5C,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,MAAM,IAAI,UAAU,yDAAyD;CACzG,OAAO;AACT;AAEA,SAAS,mBACP,WACiE;CACjE,MAAM,UAAU,UAAU,OAAO;CACjC,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC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","../src/source.ts","../src/search.ts","../src/profile.ts","../src/plans.ts","../src/operations.ts","../src/task-solutions.ts","../src/manager.ts","../src/providers.ts","../src/restart.ts","../src/runner.ts","../src/telemetry.ts","../src/index.ts"],"sourcesContent":["import type { Context } from '@deepseek-ai/cordis'\nimport type { CommandInvocation } from '@deepseek-ai/dsh-commands'\nimport { createUserMessage } from '@deepseek-ai/dsh-llm'\nimport { defineTool, type ToolRunContext } from '@deepseek-ai/dsh-tools'\nimport '@deepseek-ai/dsh-user-questions'\nimport type { PluginManager } from './manager.ts'\nimport type { ConfirmationPlan, PlanAction } from './plans.ts'\nimport { fail } from './errors.ts'\n\ntype JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue }\n\nfunction jsonValue(value: unknown): JsonValue {\n return JSON.parse(JSON.stringify(value)) as JsonValue\n}\n\nfunction renderJson(_args: unknown, value: JsonValue): Array<{ type: 'text'; text: string }> {\n return [{ type: 'text', text: JSON.stringify(value, null, 2) }]\n}\n\ninterface ConfirmationCursor {\n sessionId: string\n userMessageSeq: number\n expiresAt: number\n plan: ConfirmationPlan\n}\n\nconst APPROVE_LABEL = 'Approve plugin change'\nconst DECLINE_LABEL = 'Decline'\n\nfunction sessionEvents(session: object): ReadonlyArray<{ type: string; seq: number }> {\n const snapshot = Reflect.get(session, 'snapshotEvents') as unknown\n if (typeof snapshot === 'function') {\n return Reflect.apply(snapshot, session, []) as ReadonlyArray<{ type: string; seq: number }>\n }\n const events = Reflect.get(session, 'events') as unknown\n if (!Array.isArray(events)) throw new TypeError('DSH Session exposes neither snapshotEvents() nor events')\n return events as ReadonlyArray<{ type: string; seq: number }>\n}\n\nfunction confirmationCursor(\n execution: ToolRunContext,\n): Pick<ConfirmationCursor, 'sessionId' | 'userMessageSeq'> | null {\n const session = execution.agent?.session\n if (session === undefined) return null\n let userMessageSeq = -1\n for (const event of sessionEvents(session)) if (event.type === 'user/message') userMessageSeq = event.seq\n return { sessionId: String(session.id), userMessageSeq }\n}\n\nfunction planDetail(plan: ConfirmationPlan): string {\n const lines = [\n `Operation: ${plan.action}`,\n `Profile: ${plan.profile}`,\n `Impact: ${plan.impact}`,\n `Restart expected: ${plan.restartExpected ? 'yes' : 'no'}`,\n ]\n if (plan.action === 'install_many') {\n lines.push('Plugins:')\n for (const item of plan.items) lines.push(`- ${item.packageName}: ${item.installSpec}`)\n if (plan.missingPeerDependencies.length > 0) {\n lines.push('Missing required peer dependencies:')\n for (const peer of plan.missingPeerDependencies) {\n lines.push(`- ${peer.packageName} (${peer.ranges.join(', ')}) required by ${peer.requiredBy.join(', ')}`)\n }\n }\n } else {\n if (plan.packageName !== undefined) lines.push(`Plugin: ${plan.packageName}`)\n if (plan.installSpec !== undefined) lines.push(`Source: ${plan.installSpec}`)\n if (plan.currentSource !== undefined) lines.push(`Current source: ${plan.currentSource}`)\n }\n return lines.join('\\n')\n}\n\nfunction confirmationBinding(\n confirmations: Map<string, ConfirmationCursor>,\n token: string,\n execution: ToolRunContext,\n now: number,\n): ConfirmationCursor {\n const binding = confirmations.get(token)\n const cursor = confirmationCursor(execution)\n if (binding === undefined || cursor === null || cursor.sessionId !== binding.sessionId) {\n fail('CONFIRMATION_REQUIRED', 'Confirmation token is not bound to this DSH conversation.')\n }\n if (binding.expiresAt <= now) {\n confirmations.delete(token)\n fail('CONFIRMATION_EXPIRED', 'Confirmation token has expired.')\n }\n return binding\n}\n\nexport function registerConversationSurface(ctx: Context, manager: PluginManager): void {\n const confirmations = new Map<string, ConfirmationCursor>()\n ctx.tools.register(defineTool({\n name: 'plugin_discover',\n description: 'Read-only DSH plugin discovery. Use search for one capability, exact identity, or GitHub owner:NAME. For a task needing multiple responsibilities, use search_roles: decompose the task into the smallest set of mutually distinct required/optional coverage roles, even when one plugin may ultimately cover several roles. Keep coherent operations on the same resource together: browsing, filtering, and previewing files are one file-browser responsibility. Every ongoing observation that finishes later is the deliberate exception and needs separate roles for source-specific state/event reading and for durable waiting/scheduling that resumes the original session; never merge those coverage responsibilities. Give each role a focused capability query and declare unresolved user choices as ambiguities. It returns inspected candidates grouped by role but does not claim they are relevant until reviewed. Exclude unrelated candidates, retain materially different alternatives, then call assess_solution with only reviewed candidate identities from each role. Assessment verifies role membership, merges one solution used by multiple roles, and reports the smallest complete answer only when every required role is selected and no ambiguity remains; never repeat npm/GitHub aliases, pad results, or silently impose a fixed top count. Ranking and directory placement are relevance evidence, not compatibility, security, or installation approval. Search result repository and recommendedSource values can be passed directly to inspect and plan. This tool never changes the profile.',\n parameters: {\n action: {\n type: 'string',\n enum: ['list', 'search', 'search_roles', 'assess_solution', 'inspect', 'status'],\n required: true,\n description: 'The read-only operation.',\n },\n query: { type: 'string', description: 'Natural-language query or GitHub owner:NAME search. Required for search and search_roles; for search_roles this is the complete user task and must contain 1 to 1000 printable characters.' },\n target: { type: 'string', description: 'npm package, github:owner/repo, https://github.com/owner/repo, github.com/owner/repo, or installed package name.' },\n operationId: { type: 'string', description: 'Operation id returned by plugin_manage.' },\n maxResults: { type: 'integer', description: 'Ranked result-page size from 1 to 20. Use 20 for ordinary need-based searches unless the user explicitly asks for fewer.' },\n maxResultsPerRole: { type: 'integer', description: 'Candidate-pool size from 1 to 20 for each search_roles role. Defaults to 20.' },\n roles: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n id: { type: 'string', required: true, description: 'Stable lowercase role id.' },\n label: { type: 'string', required: true, description: 'Short user-facing responsibility label containing 1 to 80 printable characters.' },\n query: { type: 'string', required: true, description: 'Focused capability query for this role, without unrelated responsibilities; must contain 1 to 120 printable characters.' },\n required: { type: 'boolean', description: 'False only when the user explicitly made this role optional.' },\n },\n },\n description: 'For search_roles, the smallest mutually distinct coverage responsibilities needed to complete the task; keep roles distinct even if one plugin may cover several.',\n },\n ambiguities: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n id: { type: 'string', required: true },\n question: { type: 'string', required: true },\n options: { type: 'array', items: { type: 'string' }, required: true },\n },\n },\n description: 'Material unresolved user choices. Any ambiguity prevents a complete assessment.',\n },\n solutionId: { type: 'string', description: 'Short-lived id returned by search_roles.' },\n selections: {\n type: 'array',\n items: {\n type: 'object',\n additionalProperties: false,\n properties: {\n roleId: { type: 'string', required: true },\n candidateIdentities: { type: 'array', items: { type: 'string' }, required: true },\n },\n },\n description: 'For assess_solution, reviewed candidates grouped by role; first is primary and remaining entries are materially different alternatives.',\n },\n },\n output: { schema: { type: 'json' }, render: renderJson },\n timeoutMs: 35_000,\n isConcurrencySafe: () => true,\n execute: async (args, execution) => jsonValue(await manager.discover(args, execution.signal)),\n }))\n\n ctx.tools.register(defineTool({\n name: 'plugin_manage',\n description: 'Plan and run DSH plugin mutations. ALWAYS call action=plan first and show its impact. NEVER treat the request that produced a plan as confirmation. Prefer action=confirm with its confirmationToken to show the plugin-owned DSH approval UI and execute an exact approval. Alternatively, call action=execute only after a later explicit user Chat message. NEVER wrap a plugin plan in generic ask_user_question. Use install_many with sources for one multi-plugin plan and confirmation. Install sources are npm or GitHub; search providers do not define installers.',\n parameters: {\n action: {\n type: 'string',\n enum: ['plan', 'confirm', 'execute', 'status', 'cancel'],\n required: true,\n description: 'Lifecycle stage. Mutations require plan followed by controlled confirm or later-message execute.',\n },\n operation: {\n type: 'string',\n enum: ['install', 'install_many', 'remove', 'update', 'enable', 'disable', 'restart'],\n description: 'Mutation to plan.',\n },\n target: { type: 'string', description: 'Installed package name, or install source when source is omitted.' },\n source: { type: 'string', description: 'npm package/version or canonical GitHub repository/ref.' },\n sources: {\n type: 'array',\n items: { type: 'string' },\n description: 'Ordered npm/GitHub sources for operation=install_many (1-20 items).',\n },\n confirmationToken: { type: 'string', description: 'One-use token from a prior plan.' },\n operationId: { type: 'string', description: 'Tracked operation id.' },\n },\n output: { schema: { type: 'json' }, render: renderJson },\n execute: async (args, execution) => {\n if (args.action === 'plan') {\n if (args.operation === undefined) fail('INVALID_ACTION', 'Planning requires an operation.')\n const plan = await manager.plan({\n operation: args.operation as PlanAction,\n ...(args.target === undefined ? {} : { target: args.target }),\n ...(args.source === undefined ? {} : { source: args.source }),\n ...(args.sources === undefined ? {} : { sources: args.sources }),\n }, execution.signal)\n const cursor = confirmationCursor(execution)\n if (cursor === null) fail('CONFIRMATION_REQUIRED', 'Planning requires a DSH Agent session.')\n const now = Date.now()\n for (const [token, binding] of confirmations) if (binding.expiresAt <= now) confirmations.delete(token)\n confirmations.set(plan.confirmationToken, {\n ...cursor,\n expiresAt: Date.parse(plan.expiresAt),\n plan,\n })\n return jsonValue(plan)\n }\n if (args.action === 'confirm') {\n if (args.confirmationToken === undefined) fail('CONFIRMATION_REQUIRED', 'Confirmation requires a token.')\n const binding = confirmationBinding(confirmations, args.confirmationToken, execution, Date.now())\n const questionId = `plugin-plan:${binding.plan.id}`\n const answer = await ctx.userQuestions.ask({\n questions: [{\n id: questionId,\n question: 'Apply this plugin change?',\n detail: planDetail(binding.plan),\n header: 'Plugin plan',\n options: [\n { label: APPROVE_LABEL, description: 'Apply the exact plan shown above.' },\n { label: DECLINE_LABEL, description: 'Keep the profile unchanged.' },\n ],\n multiSelect: false,\n intent: { kind: 'plan-review', approve: APPROVE_LABEL },\n }],\n ...(execution.agent === undefined ? {} : { agent: execution.agent }),\n signal: execution.signal,\n })\n const answered = answer.answers[0]\n const isExactAnswer = answer.answers.length === 1\n && answered?.id === questionId\n && answered.custom === undefined\n && answered.selected.length === 1\n if (!isExactAnswer) {\n fail('CONFIRMATION_INVALID', 'Plugin confirmation did not match the requested plan and was not executed.')\n }\n if (answered.selected[0] === DECLINE_LABEL) {\n return jsonValue({ status: 'declined', planId: binding.plan.id })\n }\n if (answered.selected[0] !== APPROVE_LABEL) {\n fail('CONFIRMATION_INVALID', 'Plugin confirmation used an unknown choice and was not executed.')\n }\n confirmations.delete(args.confirmationToken)\n return jsonValue(manager.execute(args.confirmationToken))\n }\n if (args.action === 'execute') {\n if (args.confirmationToken === undefined) fail('CONFIRMATION_REQUIRED', 'Execution requires a confirmation token.')\n const binding = confirmationBinding(confirmations, args.confirmationToken, execution, Date.now())\n const cursor = confirmationCursor(execution)\n if (cursor === null) fail('CONFIRMATION_REQUIRED', 'Execution requires a DSH Agent session.')\n if (cursor.userMessageSeq <= binding.userMessageSeq) {\n fail('CONFIRMATION_REQUIRED', 'Wait for a later explicit user confirmation before execution.')\n }\n confirmations.delete(args.confirmationToken)\n return jsonValue(manager.execute(args.confirmationToken))\n }\n if (args.operationId === undefined) fail('OPERATION_NOT_FOUND', `${args.action} requires an operation id.`)\n return jsonValue(args.action === 'cancel'\n ? manager.cancel(args.operationId)\n : manager.operation(args.operationId))\n },\n }))\n\n ctx.commands.register({\n name: 'plugins',\n description: 'manage DSH plugins through this conversation',\n input: { hint: '<request>' },\n handler: ({ agent, rawInput }: CommandInvocation) => {\n const request = rawInput.trim() === ''\n ? 'List the installed DSH plugins and summarize their status.'\n : rawInput.trim()\n agent.steer(createUserMessage({\n content: [{ type: 'text', text: request }],\n source: { kind: 'user' },\n }))\n return { kind: 'success', text: 'Plugin request submitted to this conversation.' }\n },\n })\n}\n","import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { parse } from 'yaml'\nimport type { PackageSurface } from './profile.ts'\n\nexport interface HotInsertRow {\n id: string\n name: string\n}\n\nexport interface HotActivationResult {\n active: boolean\n restartRequired: boolean\n reason: string | null\n}\n\ninterface PluginHandle {\n await(): Promise<unknown>\n dispose(): Promise<unknown> | void\n}\n\ninterface HotContext {\n plugin(plugin: unknown, config: unknown): PluginHandle\n logger?: { info?(message: string): void; warn?(message: string): void }\n}\n\nexport function parseSimpleHotPatch(text: string): HotInsertRow[] | null {\n let value: unknown\n try {\n value = parse(text)\n } catch {\n return null\n }\n if (!Array.isArray(value) || value.length === 0) return null\n const rows: HotInsertRow[] = []\n for (const patch of value) {\n if (typeof patch !== 'object' || patch === null || Array.isArray(patch)) return null\n if (Object.keys(patch).length !== 1 || !Array.isArray((patch as { insert?: unknown }).insert)) return null\n for (const raw of (patch as { insert: unknown[] }).insert) {\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) return null\n const entry = raw as { id?: unknown; name?: unknown }\n if (Object.keys(entry).some(key => key !== 'id' && key !== 'name')) return null\n if (typeof entry.id !== 'string' || entry.id === '' || typeof entry.name !== 'string' || entry.name === '') return null\n rows.push({ id: entry.id, name: entry.name })\n }\n }\n return rows.length === 0 ? null : rows\n}\n\nexport class HotRuntime {\n private readonly handles = new Map<string, PluginHandle>()\n private sequence = 0\n private includeClass: unknown | null | undefined\n private readonly ctx: HotContext\n private readonly profileDir: string\n private readonly timeoutMs: number\n private readonly loadInclude?: () => Promise<unknown | null>\n\n constructor(\n ctx: HotContext,\n profileDir: string,\n timeoutMs = 10_000,\n loadInclude?: () => Promise<unknown | null>,\n ) {\n this.ctx = ctx\n this.profileDir = profileDir\n this.timeoutMs = timeoutMs\n this.loadInclude = loadInclude\n this.clean()\n }\n\n private hotDir(): string {\n return join(this.profileDir, '.relay-plugin-manager')\n }\n\n clean(): void {\n let files: string[]\n try {\n files = readdirSync(this.hotDir())\n } catch {\n return\n }\n for (const file of files) if (/^hot-\\d+\\.yml$/u.test(file)) rmSync(join(this.hotDir(), file), { force: true })\n }\n\n private async include(): Promise<unknown | null> {\n if (this.includeClass !== undefined) return this.includeClass\n if (this.loadInclude !== undefined) {\n this.includeClass = await this.loadInclude()\n return this.includeClass\n }\n try {\n const module = await import('@deepseek-ai/cordis-plugin-include') as { Include?: new (...args: never[]) => object; default?: new (...args: never[]) => object }\n const Include = module.Include ?? module.default\n if (Include === undefined) throw new Error('missing Include export')\n this.includeClass = class RuntimeHotInclude extends Include {\n write(): void {}\n }\n } catch {\n this.includeClass = null\n }\n return this.includeClass\n }\n\n async activate(surface: PackageSurface): Promise<HotActivationResult> {\n if (this.handles.has(surface.packageName)) return { active: true, restartRequired: false, reason: null }\n const Include = await this.include()\n if (Include === null) return { active: false, restartRequired: true, reason: 'DSH Include runtime is unavailable.' }\n let rows: HotInsertRow[] | null = null\n if (surface.bundlePatch !== null) {\n try {\n rows = parseSimpleHotPatch(readFileSync(\n join(this.profileDir, 'node_modules', surface.packageName, surface.bundlePatch),\n 'utf8',\n ))\n } catch {\n rows = null\n }\n if (rows === null) {\n return { active: false, restartRequired: true, reason: 'Bundle patch is not a plain insert-only patch.' }\n }\n } else if (surface.client) {\n rows = [{ id: `client-${surface.packageName.replace(/[^A-Za-z0-9_.-]/gu, '-')}`, name: surface.packageName }]\n } else {\n return { active: false, restartRequired: true, reason: 'Package has no hot-activatable DSH surface.' }\n }\n mkdirSync(this.hotDir(), { recursive: true, mode: 0o700 })\n const file = join(this.hotDir(), `hot-${String(++this.sequence)}.yml`)\n writeFileSync(file, rows.map(row => [\n '- id: ' + JSON.stringify(`rpm-${row.id}`),\n ' name: ' + JSON.stringify(row.name),\n ].join('\\n')).join('\\n') + '\\n', { mode: 0o600 })\n let handle: PluginHandle | undefined\n let timeout: NodeJS.Timeout | undefined\n try {\n handle = this.ctx.plugin(Include, { path: pathToFileURL(file).href })\n await Promise.race([\n handle.await(),\n new Promise<never>((_resolve, reject) => {\n timeout = setTimeout(() => reject(new Error('hot activation timed out')), this.timeoutMs)\n }),\n ])\n this.handles.set(surface.packageName, handle)\n return { active: true, restartRequired: false, reason: null }\n } catch (error) {\n try { await handle?.dispose() } catch { /* best effort */ }\n return {\n active: false,\n restartRequired: true,\n reason: error instanceof Error ? error.message : String(error),\n }\n } finally {\n if (timeout !== undefined) clearTimeout(timeout)\n }\n }\n\n async deactivate(packageName: string): Promise<boolean> {\n const handle = this.handles.get(packageName)\n if (handle === undefined) return false\n this.handles.delete(packageName)\n try {\n await handle.dispose()\n return true\n } catch {\n return false\n }\n }\n\n isActive(packageName: string): boolean {\n return this.handles.has(packageName)\n }\n}\n","import { fail } from './errors.ts'\n\nexport const EXACT_SEMVER = /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/u\nexport const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u\nexport const FULL_COMMIT = /^[a-f0-9]{40}$/iu\nconst GITHUB_PART = /^[A-Za-z0-9](?:[A-Za-z0-9_.-]{0,98}[A-Za-z0-9])?$/u\nconst UNSAFE_TOKEN = /[\\u0000-\\u0020\\u007f;&|`$<>]/u\n\nexport interface NpmPluginSource {\n kind: 'npm'\n package: string\n version?: string\n}\n\nexport interface GithubPluginSource {\n kind: 'github'\n owner: string\n repo: string\n ref?: string\n}\n\nexport type PluginSource = NpmPluginSource | GithubPluginSource\n\nexport interface PluginInspection {\n source: PluginSource\n sourceType: PluginSource['kind']\n requestedSpec: string\n installSpec: string\n packageName: string\n version?: string\n commit?: string\n integrity?: string\n repository: string | null\n description: string | null\n bundlePatch: string | null\n client: boolean\n peerDependencies: Record<string, string>\n}\n\nfunction manifestPeerDependencies(value: unknown): Record<string, string> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}\n const manifest = value as { peerDependencies?: unknown; peerDependenciesMeta?: unknown }\n const peers = manifest.peerDependencies\n if (typeof peers !== 'object' || peers === null || Array.isArray(peers)) return {}\n const metadata = typeof manifest.peerDependenciesMeta === 'object'\n && manifest.peerDependenciesMeta !== null\n && !Array.isArray(manifest.peerDependenciesMeta)\n ? manifest.peerDependenciesMeta as Record<string, unknown>\n : {}\n return Object.fromEntries(Object.entries(peers).flatMap(([name, range]) => {\n if (!NPM_NAME.test(name) || typeof range !== 'string') return []\n const peerMetadata = metadata[name]\n if (typeof peerMetadata === 'object' && peerMetadata !== null && !Array.isArray(peerMetadata)\n && (peerMetadata as { optional?: unknown }).optional === true) return []\n const normalized = range.trim()\n return normalized === '' || normalized.length > 500 ? [] : [[name, normalized]]\n }))\n}\n\nexport interface FetchOptions {\n fetch?: typeof globalThis.fetch\n env?: NodeJS.ProcessEnv\n signal?: AbortSignal\n}\n\nfunction safeToken(value: unknown): string {\n const source = String(value ?? '').trim()\n if (source === '' || source.startsWith('-') || UNSAFE_TOKEN.test(source)) {\n fail('INVALID_SOURCE', 'Plugin source must be one safe npm or GitHub token.')\n }\n return source\n}\n\nexport function parseNpmSpec(value: unknown, requireExact = false): NpmPluginSource {\n const spec = safeToken(value)\n let packageName = spec\n let version: string | undefined\n const separator = spec.lastIndexOf('@')\n const scopedBoundary = spec.startsWith('@') ? spec.indexOf('/') : -1\n if (separator > Math.max(0, scopedBoundary)) {\n packageName = spec.slice(0, separator)\n version = spec.slice(separator + 1)\n }\n if (!NPM_NAME.test(packageName)) {\n fail('INVALID_NPM_SPEC', 'Plugin source is not a valid npm package name.')\n }\n if (version !== undefined && !EXACT_SEMVER.test(version)) {\n fail('INVALID_NPM_VERSION', 'npm plugin versions must be exact semantic versions.')\n }\n if (requireExact && version === undefined) {\n fail('IMMUTABLE_SOURCE_REQUIRED', 'Installation requires an exact npm version.')\n }\n return { kind: 'npm', package: packageName, ...(version === undefined ? {} : { version }) }\n}\n\nexport function isGithubPart(value: string): boolean {\n return GITHUB_PART.test(value) && value !== '.' && value !== '..' && !value.endsWith('.git')\n}\n\nfunction ownerOnlyGithubSpec(spec: string): string | null {\n const match = /^(?:github:|(?:https:\\/\\/)?github\\.com\\/)([^/#]+)\\/?$/u.exec(spec)\n return match !== null && isGithubPart(match[1]!) ? match[1]! : null\n}\n\nexport function parseGithubSpec(value: unknown, requireCommit = false): GithubPluginSource | null {\n const spec = safeToken(value)\n const ownerOnly = ownerOnlyGithubSpec(spec)\n if (ownerOnly !== null) {\n fail(\n 'GITHUB_OWNER_REQUIRES_SEARCH',\n `GitHub owner discovery requires action=search with query owner:${ownerOnly}.`,\n { owner: ownerOnly },\n )\n }\n const normalizedSpec = spec.startsWith('github.com/') ? `https://${spec}` : spec\n let owner: string | undefined\n let repo: string | undefined\n let ref: string | undefined\n if (normalizedSpec.startsWith('github:')) {\n const match = /^github:([^/]+)\\/([^#]+?)(?:#(.+))?$/u.exec(normalizedSpec)\n if (match === null) fail('INVALID_GITHUB_SPEC', 'GitHub source must use github:owner/repo[#ref].')\n owner = match[1]\n repo = match[2]\n ref = match[3]\n } else if (normalizedSpec.startsWith('https://github.com/')) {\n let url: URL\n try {\n url = new URL(normalizedSpec)\n } catch {\n fail('INVALID_GITHUB_SPEC', 'GitHub URL is invalid.')\n }\n if (url.protocol !== 'https:' || url.hostname !== 'github.com' || url.search !== '') {\n fail('INVALID_GITHUB_SPEC', 'Only canonical HTTPS github.com repository URLs are supported.')\n }\n const parts = url.pathname.split('/').filter(Boolean)\n owner = parts[0]\n repo = parts[1]?.replace(/\\.git$/u, '')\n if (parts.length > 2) {\n if ((parts[2] !== 'tree' && parts[2] !== 'commit') || parts.length < 4) {\n fail('INVALID_GITHUB_SPEC', 'GitHub URL must identify a repository, tree, or commit.')\n }\n ref = decodeURIComponent(parts.slice(3).join('/'))\n } else if (url.hash !== '') {\n fail('INVALID_GITHUB_SPEC', 'Use a tree/commit URL or github:owner/repo#ref for GitHub refs.')\n }\n } else if (/^[A-Za-z][A-Za-z0-9+.-]*:\\/\\//u.test(normalizedSpec)) {\n fail('INVALID_GITHUB_SPEC', 'Only canonical HTTPS github.com repository URLs are supported.')\n } else {\n return null\n }\n if (!isGithubPart(owner ?? '') || !isGithubPart(repo ?? '')) {\n fail('INVALID_GITHUB_SPEC', 'GitHub owner or repository name is invalid.')\n }\n if (ref !== undefined && (ref === '' || ref.length > 200 || UNSAFE_TOKEN.test(ref))) {\n fail('INVALID_GITHUB_REF', 'GitHub ref is invalid.')\n }\n if (requireCommit && !FULL_COMMIT.test(ref ?? '')) {\n fail('IMMUTABLE_SOURCE_REQUIRED', 'Installation requires a full GitHub commit.')\n }\n return { kind: 'github', owner: owner!, repo: repo!, ...(ref === undefined ? {} : { ref }) }\n}\n\nexport function parsePluginSource(value: string | PluginSource): PluginSource {\n if (typeof value === 'string') return parseGithubSpec(value) ?? parseNpmSpec(value)\n if (value.kind === 'npm') {\n return parseNpmSpec(`${value.package}${value.version === undefined ? '' : `@${value.version}`}`)\n }\n return parseGithubSpec(`github:${value.owner}/${value.repo}${value.ref === undefined ? '' : `#${value.ref}`}`)!\n}\n\nexport function renderSource(source: PluginSource): string {\n if (source.kind === 'npm') return `${source.package}${source.version === undefined ? '' : `@${source.version}`}`\n return `github:${source.owner}/${source.repo}${source.ref === undefined ? '' : `#${source.ref}`}`\n}\n\nfunction manifestDsh(value: unknown): { bundlePatch: string | null; client: boolean } {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return { bundlePatch: null, client: false }\n const dsh = (value as { dsh?: unknown }).dsh\n if (typeof dsh !== 'object' || dsh === null || Array.isArray(dsh)) return { bundlePatch: null, client: false }\n const bundle = (dsh as { bundle?: unknown }).bundle\n const patch = typeof bundle === 'object' && bundle !== null && !Array.isArray(bundle)\n ? (bundle as { patch?: unknown }).patch\n : undefined\n return {\n bundlePatch: typeof patch === 'string' && patch.trim() !== '' ? patch : null,\n client: (dsh as { client?: unknown }).client !== undefined,\n }\n}\n\nexport function validatePluginManifest(\n manifest: unknown,\n expectedName?: string,\n): { packageName: string; bundlePatch: string | null; client: boolean } {\n if (typeof manifest !== 'object' || manifest === null || Array.isArray(manifest)) {\n fail('INVALID_PLUGIN_MANIFEST', 'Plugin package manifest must be an object.')\n }\n const packageName = String((manifest as { name?: unknown }).name ?? '')\n if (!NPM_NAME.test(packageName)) fail('INVALID_PLUGIN_MANIFEST', 'Plugin manifest has no valid package name.')\n if (expectedName !== undefined && packageName !== expectedName) {\n fail('PACKAGE_NAME_MISMATCH', 'Resolved package name does not match the requested npm package.')\n }\n const surface = manifestDsh(manifest)\n if (surface.bundlePatch === null && !surface.client) {\n fail('NOT_DSH_PLUGIN', `${packageName} declares neither dsh.bundle.patch nor dsh.client.`)\n }\n return { packageName, ...surface }\n}\n\nasync function fetchJson(url: string, options: FetchOptions, headers: Record<string, string> = {}): Promise<unknown> {\n const fetchImpl = options.fetch ?? globalThis.fetch\n let response: Response\n try {\n response = await fetchImpl(url, {\n headers: { accept: 'application/json', ...headers },\n redirect: 'follow',\n signal: options.signal,\n })\n } catch (error) {\n fail('NETWORK_ERROR', `Could not reach plugin source: ${error instanceof Error ? error.message : String(error)}`)\n }\n if (!response.ok) fail('SOURCE_HTTP_ERROR', `Plugin source returned HTTP ${response.status}.`, { url, status: response.status })\n try {\n return await response.json()\n } catch {\n fail('INVALID_SOURCE_METADATA', 'Plugin source returned invalid JSON metadata.', { url })\n }\n}\n\nfunction repositoryIdentity(value: unknown): string | null {\n const raw = typeof value === 'string'\n ? value\n : typeof value === 'object' && value !== null\n ? (value as { url?: unknown }).url\n : undefined\n if (typeof raw !== 'string' || raw.trim() === '') return null\n const normalized = raw.trim()\n .replace(/^git\\+/u, '')\n .replace(/^git@github\\.com:/u, 'https://github.com/')\n .replace(/^github:/u, 'https://github.com/')\n .replace(/\\.git(?:#.*)?$/u, '')\n .replace(/\\/$/u, '')\n const match = /^https:\\/\\/github\\.com\\/([^/]+)\\/([^/]+)$/iu.exec(normalized)\n return match === null\n ? normalized.toLowerCase()\n : `github.com/${match[1]!.toLowerCase()}/${match[2]!.toLowerCase()}`\n}\n\nfunction npmMetadataUrl(name: string, version?: string): string {\n return `https://registry.npmjs.org/${encodeURIComponent(name).replace(/^%40/u, '@')}/${encodeURIComponent(version ?? 'latest')}`\n}\n\nexport async function inspectNpm(source: NpmPluginSource, options: FetchOptions = {}): Promise<PluginInspection> {\n const manifest = await fetchJson(npmMetadataUrl(source.package, source.version), options)\n const plugin = validatePluginManifest(manifest, source.package)\n const version = String((manifest as { version?: unknown }).version ?? '')\n if (!EXACT_SEMVER.test(version)) fail('INVALID_NPM_VERSION', 'Registry metadata has no exact semantic version.')\n const integrity = (manifest as { dist?: { integrity?: unknown } }).dist?.integrity\n if (typeof integrity !== 'string' || !/^sha512-[A-Za-z0-9+/=]+$/u.test(integrity)) {\n fail('NPM_INTEGRITY_MISSING', 'Registry metadata has no SHA-512 package integrity.')\n }\n const exact: NpmPluginSource = { kind: 'npm', package: plugin.packageName, version }\n return {\n source: exact,\n sourceType: 'npm',\n requestedSpec: renderSource(source),\n installSpec: renderSource(exact),\n packageName: plugin.packageName,\n version,\n integrity,\n repository: repositoryIdentity((manifest as { repository?: unknown }).repository),\n description: typeof (manifest as { description?: unknown }).description === 'string'\n ? (manifest as { description: string }).description\n : null,\n bundlePatch: plugin.bundlePatch,\n client: plugin.client,\n peerDependencies: manifestPeerDependencies(manifest),\n }\n}\n\nfunction githubHeaders(env: NodeJS.ProcessEnv = process.env): Record<string, string> {\n const token = env.GITHUB_TOKEN ?? env.GH_TOKEN\n return {\n 'user-agent': 'relay-dsh-plugin-manager',\n 'x-github-api-version': '2022-11-28',\n ...(token === undefined || token === '' ? {} : { authorization: `Bearer ${token}` }),\n }\n}\n\nexport async function inspectGithub(source: GithubPluginSource, options: FetchOptions = {}): Promise<PluginInspection> {\n const headers = githubHeaders(options.env)\n let ref = source.ref\n if (ref === undefined) {\n const repository = await fetchJson(`https://api.github.com/repos/${source.owner}/${source.repo}`, options, headers)\n ref = typeof (repository as { default_branch?: unknown }).default_branch === 'string'\n ? (repository as { default_branch: string }).default_branch\n : undefined\n if (ref === undefined || ref === '') fail('INVALID_SOURCE_METADATA', 'GitHub repository has no default branch.')\n }\n const commit = await fetchJson(\n `https://api.github.com/repos/${source.owner}/${source.repo}/commits/${encodeURIComponent(ref)}`,\n options,\n headers,\n )\n const sha = String((commit as { sha?: unknown }).sha ?? '').toLowerCase()\n if (!FULL_COMMIT.test(sha)) fail('INVALID_SOURCE_METADATA', 'GitHub did not resolve the source to a full commit.')\n const manifest = await fetchJson(\n `https://raw.githubusercontent.com/${source.owner}/${source.repo}/${sha}/package.json`,\n options,\n )\n const plugin = validatePluginManifest(manifest)\n const exact: GithubPluginSource = { kind: 'github', owner: source.owner, repo: source.repo, ref: sha }\n return {\n source: exact,\n sourceType: 'github',\n requestedSpec: renderSource(source),\n installSpec: renderSource(exact),\n packageName: plugin.packageName,\n commit: sha,\n repository: `github.com/${source.owner.toLowerCase()}/${source.repo.toLowerCase()}`,\n description: typeof (manifest as { description?: unknown }).description === 'string'\n ? (manifest as { description: string }).description\n : null,\n bundlePatch: plugin.bundlePatch,\n client: plugin.client,\n peerDependencies: manifestPeerDependencies(manifest),\n }\n}\n\nexport async function inspectPluginSource(\n value: string | PluginSource,\n options: FetchOptions = {},\n): Promise<PluginInspection> {\n const source = parsePluginSource(value)\n return source.kind === 'npm' ? inspectNpm(source, options) : inspectGithub(source, options)\n}\n\nexport function inspectionIdentity(inspection: PluginInspection): string {\n return inspection.repository ?? `${inspection.sourceType}:${inspection.packageName.toLowerCase()}`\n}\n","import type {\n PluginSearchCandidate,\n PluginSearchProvider,\n PluginSearchRequest,\n PluginSearchRuntime,\n} from './search-runtime.ts'\nimport {\n inspectionIdentity,\n inspectPluginSource,\n isGithubPart,\n parsePluginSource,\n type FetchOptions,\n type PluginInspection,\n type PluginSource,\n} from './source.ts'\nimport { fail } from './errors.ts'\n\nexport interface SearchResultSource {\n inspection: PluginInspection\n providers: string[]\n evidence: string[]\n}\n\nexport interface SearchResult {\n query: string\n candidates: Array<{\n rank: number\n identity: string\n packageName: string\n description: string | null\n repository: string | null\n repositoryOwner: string | null\n providers: string[]\n matchReasons: string[]\n semanticMatches: Array<{\n directoryVersion: string | null\n canonicalPathKey: string | null\n canonicalPath: string[]\n matchedCapabilities: string[]\n retrievalSources: string[]\n }>\n sources: SearchResultSource[]\n recommendedSource: string\n }>\n presentation: {\n order: 'rank_ascending'\n returnedCandidates: number\n requestedMaximum: number\n includeEveryDistinctRelevantSolution: true\n excludeClearlyIrrelevant: true\n deduplicateEquivalentSources: true\n padToRequestedMaximum: false\n silentTopNTruncation: false\n }\n providerErrors: Array<{ provider: string; error: string }>\n rejectedCandidates: number\n}\n\nexport interface SearchOptions extends FetchOptions {\n maxResults?: number\n providerTimeoutMs?: number\n inspect?: typeof inspectPluginSource\n}\n\nfunction searchQuery(value: string): string {\n const query = value.trim()\n if (query === '' || query.length > 120 || /[\\u0000-\\u001f\\u007f]/u.test(query)) {\n fail('INVALID_SEARCH_QUERY', 'Search query must contain 1 to 120 printable characters.')\n }\n return query\n}\n\ninterface ParsedSearchQuery {\n query: string\n providerQuery: string\n intent?: PluginSearchRequest['intent']\n}\n\nfunction githubOwnerIntent(query: string): Omit<ParsedSearchQuery, 'query'> | null {\n const explicit = [\n /^owner:([^\\s]+)$/iu,\n /^github:([^/\\s]+)$/iu,\n /^(?:https:\\/\\/)?github\\.com\\/([^/\\s]+)\\/?$/iu,\n /^([^\\s]+)\\s+dsh\\s+plugins?$/iu,\n /^(?:dsh\\s+)?plugins?\\s+(?:by|from)\\s+([^\\s]+)$/iu,\n ]\n for (const pattern of explicit) {\n const match = pattern.exec(query)\n if (match === null) continue\n const owner = match[1]!\n if (!isGithubPart(owner)) fail('INVALID_SEARCH_QUERY', 'GitHub owner query contains an invalid owner name.')\n return { providerQuery: owner, intent: { kind: 'github-owner', owner, fallbackToText: false } }\n }\n if (/^[A-Za-z0-9]+$/u.test(query) && /\\d/u.test(query) && isGithubPart(query)) {\n return { providerQuery: query, intent: { kind: 'github-owner', owner: query, fallbackToText: true } }\n }\n return null\n}\n\nfunction parseSearchQuery(value: string): ParsedSearchQuery {\n const query = searchQuery(value)\n return { query, ...(githubOwnerIntent(query) ?? { providerQuery: query }) }\n}\n\nfunction abortReason(signal: AbortSignal): Error {\n return signal.reason instanceof Error ? signal.reason : new Error('search cancelled')\n}\n\nasync function searchProvider(\n provider: PluginSearchProvider,\n query: string,\n intent: PluginSearchRequest['intent'],\n maxResults: number,\n parent: AbortSignal | undefined,\n timeoutMs: number,\n): Promise<readonly PluginSearchCandidate[]> {\n const controller = new AbortController()\n const onAbort = (): void => controller.abort(parent?.reason)\n if (parent?.aborted === true) throw abortReason(parent)\n parent?.addEventListener('abort', onAbort, { once: true })\n const timeout = setTimeout(() => controller.abort(new Error(`provider timed out after ${timeoutMs}ms`)), timeoutMs)\n try {\n const result = await provider.search({\n query,\n maxResults,\n signal: controller.signal,\n ...(intent === undefined ? {} : { intent }),\n })\n if (!Array.isArray(result)) throw new TypeError('provider result must be an array')\n return result.slice(0, maxResults)\n } finally {\n clearTimeout(timeout)\n parent?.removeEventListener('abort', onAbort)\n }\n}\n\ninterface DiscoveredSource {\n source: PluginSource\n provider: string\n evidence: string[]\n match: PluginSearchCandidate['match']\n rank: number\n}\n\nfunction candidateSources(provider: string, rows: readonly PluginSearchCandidate[]): DiscoveredSource[] {\n const output: DiscoveredSource[] = []\n const ranked = [...rows].sort((left, right) => (right.score ?? 0) - (left.score ?? 0) || left.id.localeCompare(right.id))\n for (const [rank, candidate] of ranked.entries()) {\n if (typeof candidate.id !== 'string' || candidate.id.trim() === '' || !Array.isArray(candidate.sources)) continue\n for (const raw of candidate.sources.slice(0, 3)) {\n try {\n output.push({\n source: parsePluginSource(raw),\n provider,\n evidence: [...(candidate.evidence ?? [])].filter(value => typeof value === 'string').slice(0, 5),\n match: candidate.match,\n rank,\n })\n } catch {\n // Provider data is untrusted. Invalid sources are rejected during normalization.\n }\n }\n }\n return output\n}\n\nfunction candidateMatchReasons(match: PluginSearchCandidate['match']): string[] {\n if (match?.kind === 'github-owner') return []\n if (match?.kind === 'exact-identifier') return [`Exact identifier: ${match.value}`]\n if (match?.kind !== 'registry') return []\n return [\n ...(match.exactIdentifier ? ['Exact Registry identifier'] : []),\n ...(match.canonicalPath.length === 0 ? [] : [`Semantic directory: ${match.canonicalPath.join(' / ')}`]),\n ...(match.matchedCapabilities.length === 0 ? [] : [`Matched capabilities: ${match.matchedCapabilities.join(', ')}`]),\n ]\n}\n\nfunction matchPriority(match: PluginSearchCandidate['match'], exactOwner: boolean): number {\n if (exactOwner || match?.kind === 'exact-identifier' || (match?.kind === 'registry' && match.exactIdentifier)) return 0\n return 1\n}\n\nfunction semanticMatch(match: PluginSearchCandidate['match']): SearchResult['candidates'][number]['semanticMatches'][number] | null {\n if (match?.kind !== 'registry' || (match.canonicalPath.length === 0 && match.matchedCapabilities.length === 0)) return null\n return {\n directoryVersion: match.directoryVersion ?? null,\n canonicalPathKey: match.canonicalPathKey ?? null,\n canonicalPath: [...match.canonicalPath],\n matchedCapabilities: [...match.matchedCapabilities],\n retrievalSources: [...match.retrievalSources],\n }\n}\n\nexport async function searchPlugins(\n runtime: Pick<PluginSearchRuntime, 'entries'>,\n rawQuery: string,\n options: SearchOptions = {},\n): Promise<SearchResult> {\n const parsed = parseSearchQuery(rawQuery)\n const maxResults = Math.max(1, Math.min(20, options.maxResults ?? 20))\n const timeoutMs = Math.max(100, options.providerTimeoutMs ?? 10_000)\n const providers = runtime.entries()\n const settled = await Promise.allSettled(providers.map(async provider => ({\n provider: provider.id,\n rows: await searchProvider(\n provider,\n parsed.providerQuery,\n parsed.intent,\n maxResults,\n options.signal,\n timeoutMs,\n ),\n })))\n if (options.signal?.aborted === true) throw abortReason(options.signal)\n\n const providerErrors: SearchResult['providerErrors'] = []\n const discovered: DiscoveredSource[] = []\n for (let index = 0; index < settled.length; index += 1) {\n const result = settled[index]!\n const provider = providers[index]!.id\n if (result.status === 'rejected') {\n providerErrors.push({ provider, error: result.reason instanceof Error ? result.reason.message : String(result.reason) })\n continue\n }\n discovered.push(...candidateSources(result.value.provider, result.value.rows))\n }\n\n const inspect = options.inspect ?? inspectPluginSource\n const inspected = await Promise.all(discovered.map(async item => {\n try {\n const inspection = await inspect(item.source, options)\n return { ok: true as const, item, inspection }\n } catch {\n return { ok: false as const }\n }\n }))\n\n const accepted = inspected.flatMap(result => result.ok ? [result] : [])\n const parent = accepted.map((_, index) => index)\n const root = (index: number): number => {\n let current = index\n while (parent[current] !== current) current = parent[current]!\n while (parent[index] !== index) {\n const next = parent[index]!\n parent[index] = current\n index = next\n }\n return current\n }\n const join = (left: number, right: number): void => {\n const leftRoot = root(left)\n const rightRoot = root(right)\n if (leftRoot === rightRoot) return\n parent[Math.max(leftRoot, rightRoot)] = Math.min(leftRoot, rightRoot)\n }\n const aliasOwner = new Map<string, number>()\n for (const [index, result] of accepted.entries()) {\n const aliases = [\n `package:${result.inspection.packageName.toLowerCase()}`,\n ...(result.inspection.repository === null ? [] : [`repository:${result.inspection.repository.toLowerCase()}`]),\n ]\n for (const alias of aliases) {\n const owner = aliasOwner.get(alias)\n if (owner === undefined) aliasOwner.set(alias, index)\n else join(index, owner)\n }\n }\n\n const projects = new Map<number, Omit<SearchResult['candidates'][number], 'rank'> & {\n rank: number\n matchPriority: number\n }>()\n const rejectedCandidates = inspected.length - accepted.length\n for (const [acceptedIndex, result] of accepted.entries()) {\n const project = root(acceptedIndex)\n const identity = inspectionIdentity(result.inspection)\n const repositoryOwner = /^github\\.com\\/([^/]+)\\//iu\n .exec(result.inspection.repository ?? '')?.[1]?.toLowerCase() ?? null\n const exactOwnerValue = result.item.match?.kind === 'github-owner' ? result.item.match.value : null\n const exactOwner = exactOwnerValue !== null\n && repositoryOwner === exactOwnerValue.toLowerCase()\n const reasons = candidateMatchReasons(result.item.match)\n const semantic = semanticMatch(result.item.match)\n const existing = projects.get(project) ?? {\n identity,\n packageName: result.inspection.packageName,\n description: result.inspection.description,\n repository: result.inspection.repository,\n repositoryOwner,\n providers: [],\n matchReasons: [],\n semanticMatches: [],\n sources: [],\n recommendedSource: result.inspection.installSpec,\n rank: result.item.rank,\n matchPriority: matchPriority(result.item.match, exactOwner),\n }\n if (!existing.providers.includes(result.item.provider)) existing.providers.push(result.item.provider)\n if (exactOwner) {\n const reason = `Exact GitHub owner: ${exactOwnerValue}`\n if (!existing.matchReasons.includes(reason)) existing.matchReasons.push(reason)\n }\n for (const reason of reasons) if (!existing.matchReasons.includes(reason)) existing.matchReasons.push(reason)\n if (semantic !== null && !existing.semanticMatches.some(item => item.directoryVersion === semantic.directoryVersion\n && item.canonicalPathKey === semantic.canonicalPathKey)) existing.semanticMatches.push(semantic)\n const sameSource = existing.sources.find(source => source.inspection.installSpec === result.inspection.installSpec)\n if (sameSource === undefined) {\n existing.sources.push({\n inspection: result.inspection,\n providers: [result.item.provider],\n evidence: [...result.item.evidence],\n })\n } else {\n if (!sameSource.providers.includes(result.item.provider)) sameSource.providers.push(result.item.provider)\n for (const evidence of result.item.evidence) if (!sameSource.evidence.includes(evidence)) sameSource.evidence.push(evidence)\n }\n existing.rank = Math.min(existing.rank, result.item.rank)\n existing.matchPriority = Math.min(existing.matchPriority, matchPriority(result.item.match, exactOwner))\n const npm = existing.sources.find(source => source.inspection.sourceType === 'npm')\n existing.recommendedSource = npm?.inspection.installSpec ?? existing.sources[0]!.inspection.installSpec\n projects.set(project, existing)\n }\n\n const candidates = [...projects.values()]\n .sort((left, right) => left.matchPriority - right.matchPriority\n || left.rank - right.rank\n || left.packageName.localeCompare(right.packageName))\n .slice(0, maxResults)\n .map(({ rank: _providerRank, matchPriority: _matchPriority, ...candidate }, index) => ({\n ...candidate,\n rank: index + 1,\n providers: candidate.providers.sort(),\n }))\n return {\n query: parsed.query,\n candidates,\n presentation: {\n order: 'rank_ascending',\n returnedCandidates: candidates.length,\n requestedMaximum: maxResults,\n includeEveryDistinctRelevantSolution: true,\n excludeClearlyIrrelevant: true,\n deduplicateEquivalentSources: true,\n padToRequestedMaximum: false,\n silentTopNTruncation: false,\n },\n providerErrors,\n rejectedCandidates,\n }\n}\n","import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { dirname, join, resolve } from 'node:path'\nimport { parseDocument, type Document } from 'yaml'\nimport { fail } from './errors.ts'\n\nexport const MANAGER_PACKAGE = 'relay-dsh-plugin-manager'\nconst STATE_VERSION = 1\nconst STATE_DIR = '.relay-plugin-manager'\n\nexport interface ProfileManifest {\n dependencies?: Record<string, string>\n dsh?: { profile?: { bundles?: string[] } }\n}\n\nexport interface ManagerState {\n version: 1\n disabled: Record<string, string[]>\n}\n\nexport interface PackageSurface {\n packageName: string\n source: string\n bundle: boolean\n bundlePatch: string | null\n client: boolean\n entryIds: string[] | null\n}\n\nexport interface LoaderEntrySnapshot {\n id: string\n name?: string\n disabled: boolean\n phase: string | null\n}\n\nexport interface PluginStatus {\n packageName: string\n source: string\n bundle: boolean\n enablement: 'enabled' | 'disabled' | 'mixed' | 'unknown'\n runtime: 'active' | 'inactive' | 'failed' | 'loading' | 'unknown'\n restartRequired: boolean\n entryIds: string[] | null\n}\n\nfunction readJsonObject<T extends object>(file: string, missing: T): T {\n try {\n const parsed: unknown = JSON.parse(readFileSync(file, 'utf8'))\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return missing\n return parsed as T\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return missing\n fail('PROFILE_READ_FAILED', `Could not read ${file}: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nfunction atomicWrite(file: string, text: string): void {\n try {\n mkdirSync(dirname(file), { recursive: true, mode: 0o700 })\n const temporary = `${file}.tmp-${process.pid}-${Date.now()}`\n writeFileSync(temporary, text, { mode: 0o600 })\n renameSync(temporary, file)\n } catch (error) {\n fail('PROFILE_WRITE_FAILED', `Could not write ${file}: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nexport function writeProfileManifest(dir: string, manifest: ProfileManifest): void {\n atomicWrite(join(dir, 'package.json'), `${JSON.stringify(manifest, null, 2)}\\n`)\n}\n\nexport function reconcileRemovedPackage(dir: string, packageName: string): void {\n const manifest = readProfileManifest(dir)\n if (manifest.dependencies !== undefined) delete manifest.dependencies[packageName]\n const bundles = manifest.dsh?.profile?.bundles\n if (bundles !== undefined) manifest.dsh!.profile!.bundles = bundles.filter(name => name !== packageName)\n writeProfileManifest(dir, manifest)\n}\n\nexport function dshHome(env: NodeJS.ProcessEnv = process.env): string {\n const configured = env.DSH_HOME?.trim()\n return resolve(configured === undefined || configured === '' ? join(homedir(), '.dsh') : configured)\n}\n\nexport function profileDirectory(profile = 'web', env: NodeJS.ProcessEnv = process.env): string {\n return join(dshHome(env), 'profiles', profile)\n}\n\nexport function readProfileManifest(dir: string): ProfileManifest {\n return readJsonObject<ProfileManifest>(join(dir, 'package.json'), {})\n}\n\nexport function profileManifestText(dir: string): string | null {\n try {\n return readFileSync(join(dir, 'package.json'), 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n fail('PROFILE_READ_FAILED', `Could not read profile manifest: ${error instanceof Error ? error.message : String(error)}`)\n }\n}\n\nexport function restoreProfileManifest(dir: string, text: string | null): void {\n if (text === null) return\n atomicWrite(join(dir, 'package.json'), text)\n}\n\nfunction packageManifest(dir: string, packageName: string): Record<string, unknown> | null {\n const file = join(dir, 'node_modules', packageName, 'package.json')\n if (!existsSync(file)) return null\n return readJsonObject<Record<string, unknown>>(file, {})\n}\n\nexport function bundleEntryIds(dir: string, packageName: string, patch: string): string[] | null {\n try {\n const document = parseDocument(readFileSync(join(dir, 'node_modules', packageName, patch), 'utf8'))\n if (document.errors.length > 0 || !Array.isArray(document.toJS())) return null\n const ids: string[] = []\n for (const row of document.toJS() as unknown[]) {\n if (typeof row !== 'object' || row === null || Array.isArray(row)) continue\n const inserted = (row as { insert?: unknown }).insert\n if (!Array.isArray(inserted)) continue\n for (const entry of inserted) {\n if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) return null\n const id = (entry as { id?: unknown }).id\n if (typeof id !== 'string' || id.trim() === '') return null\n if (!ids.includes(id)) ids.push(id)\n }\n }\n return ids.length === 0 ? null : ids\n } catch {\n return null\n }\n}\n\nexport function packageSurface(dir: string, packageName: string, source: string): PackageSurface {\n const manifest = packageManifest(dir, packageName)\n const dsh = typeof manifest?.dsh === 'object' && manifest.dsh !== null && !Array.isArray(manifest.dsh)\n ? manifest.dsh as { bundle?: unknown; client?: unknown }\n : {}\n const bundle = typeof dsh.bundle === 'object' && dsh.bundle !== null && !Array.isArray(dsh.bundle)\n ? dsh.bundle as { patch?: unknown }\n : {}\n const patch = typeof bundle.patch === 'string' && bundle.patch.trim() !== '' ? bundle.patch : null\n return {\n packageName,\n source,\n bundle: patch !== null,\n bundlePatch: patch,\n client: dsh.client !== undefined,\n entryIds: patch === null ? null : bundleEntryIds(dir, packageName, patch),\n }\n}\n\nfunction statePath(dir: string): string {\n return join(dir, STATE_DIR, 'state.json')\n}\n\nexport function readManagerState(dir: string): ManagerState {\n const state = readJsonObject<Partial<ManagerState>>(statePath(dir), {})\n const disabled: Record<string, string[]> = {}\n if (state.version === STATE_VERSION && typeof state.disabled === 'object' && state.disabled !== null) {\n for (const [name, ids] of Object.entries(state.disabled)) {\n if (Array.isArray(ids) && ids.every(id => typeof id === 'string')) disabled[name] = [...new Set(ids)]\n }\n }\n return { version: STATE_VERSION, disabled }\n}\n\nfunction writeManagerState(dir: string, state: ManagerState): void {\n atomicWrite(statePath(dir), `${JSON.stringify(state, null, 2)}\\n`)\n}\n\nfunction patchDocument(file: string): Document.Parsed {\n let source = '[]\\n'\n try {\n source = readFileSync(file, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n fail('PROFILE_READ_FAILED', `Could not read profile patch: ${error instanceof Error ? error.message : String(error)}`)\n }\n }\n const document = parseDocument(source)\n if (document.errors.length > 0) fail('ENABLEMENT_CONFLICT', 'Profile cordis.patch.yml is not valid YAML.')\n const value = document.toJS()\n if (value === null) document.contents = document.createNode([]) as never\n else if (!Array.isArray(value)) fail('ENABLEMENT_CONFLICT', 'Profile cordis.patch.yml must contain a patch list.')\n return document\n}\n\nfunction exactDisabledRow(value: unknown, id: string): boolean {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const keys = Object.keys(value)\n return keys.length === 2 && (value as { id?: unknown }).id === id && (value as { disabled?: unknown }).disabled === true\n}\n\nexport function disablePackage(dir: string, surface: PackageSurface): string[] {\n if (surface.packageName === MANAGER_PACKAGE) fail('PROTECTED_PLUGIN', 'The plugin manager cannot disable itself.')\n if (surface.entryIds === null || surface.entryIds.length === 0) {\n fail('ENABLEMENT_UNSUPPORTED', `${surface.packageName} has no safely attributable Loader entry ids.`)\n }\n const file = join(dir, 'cordis.patch.yml')\n const state = readManagerState(dir)\n const document = patchDocument(file)\n const rows = document.toJS() as unknown[]\n const alreadyOwned = new Set(state.disabled[surface.packageName] ?? [])\n for (const id of surface.entryIds) {\n const existing = rows.find(row => typeof row === 'object' && row !== null && !Array.isArray(row)\n && (row as { id?: unknown }).id === id)\n if (existing !== undefined && !(alreadyOwned.has(id) && exactDisabledRow(existing, id))) {\n fail('ENABLEMENT_CONFLICT', `Profile patch already owns Loader entry \"${id}\"; it will not be overwritten.`)\n }\n if (existing === undefined) document.add({ id, disabled: true })\n }\n state.disabled[surface.packageName] = [...surface.entryIds]\n atomicWrite(file, document.toString())\n writeManagerState(dir, state)\n return [...surface.entryIds]\n}\n\nexport function enablePackage(dir: string, surface: PackageSurface): string[] {\n if (surface.packageName === MANAGER_PACKAGE) fail('PROTECTED_PLUGIN', 'The plugin manager cannot change its own enablement.')\n const state = readManagerState(dir)\n const owned = state.disabled[surface.packageName]\n if (owned === undefined || owned.length === 0) return []\n const file = join(dir, 'cordis.patch.yml')\n const document = patchDocument(file)\n const rows = document.toJS() as unknown[]\n for (const id of owned) {\n const matching = rows.filter(row => typeof row === 'object' && row !== null && !Array.isArray(row)\n && (row as { id?: unknown }).id === id)\n if (matching.some(row => !exactDisabledRow(row, id))) {\n fail('ENABLEMENT_CONFLICT', `Manager-owned Loader entry \"${id}\" was modified and will not be removed.`)\n }\n }\n const keep = rows.filter(row => !owned.some(id => exactDisabledRow(row, id)))\n document.contents = document.createNode(keep) as never\n delete state.disabled[surface.packageName]\n atomicWrite(file, document.toString())\n writeManagerState(dir, state)\n return [...owned]\n}\n\nfunction runtimeState(entries: LoaderEntrySnapshot[]): PluginStatus['runtime'] {\n const phases = entries.map(entry => entry.phase)\n if (phases.includes('failed')) return 'failed'\n if (phases.includes('active')) return 'active'\n if (phases.some(phase => phase === 'loading' || phase === 'pending')) return 'loading'\n if (entries.length > 0) return 'inactive'\n return 'unknown'\n}\n\nexport function listPluginStatuses(dir: string, loaderEntries: readonly LoaderEntrySnapshot[] = []): PluginStatus[] {\n const manifest = readProfileManifest(dir)\n const bundles = new Set(manifest.dsh?.profile?.bundles ?? [])\n const state = readManagerState(dir)\n return Object.entries(manifest.dependencies ?? {}).sort(([left], [right]) => left.localeCompare(right)).map(([packageName, source]) => {\n const surface = packageSurface(dir, packageName, source)\n const ids = surface.entryIds\n const entries = ids === null ? [] : loaderEntries.filter(entry => ids.includes(entry.id))\n let enablement: PluginStatus['enablement'] = 'unknown'\n if (ids !== null) {\n const disabledIds = new Set(state.disabled[packageName] ?? [])\n const disabled = ids.filter(id => disabledIds.has(id) || entries.some(entry => entry.id === id && entry.disabled)).length\n enablement = disabled === 0 ? 'enabled' : disabled === ids.length ? 'disabled' : 'mixed'\n }\n const runtime = runtimeState(entries)\n return {\n packageName,\n source,\n bundle: bundles.has(packageName) || surface.bundle,\n enablement,\n runtime,\n restartRequired: surface.bundle && runtime === 'unknown' && !state.disabled[packageName],\n entryIds: ids,\n }\n })\n}\n","import { createHash, randomUUID } from 'node:crypto'\nimport { fail } from './errors.ts'\n\nexport type MutationAction = 'install' | 'remove' | 'update' | 'enable' | 'disable' | 'restart'\nexport type PlanAction = MutationAction | 'install_many'\n\nexport interface SinglePlanInput {\n action: MutationAction\n profile: 'web'\n packageName?: string\n installSpec?: string\n currentSource?: string\n impact: string\n restartExpected: boolean\n items?: never\n missingPeerDependencies?: never\n}\n\nexport interface InstallPlanItem {\n action: 'install'\n packageName: string\n installSpec: string\n impact: string\n restartExpected: boolean\n}\n\nexport interface MissingPeerDependency {\n packageName: string\n ranges: string[]\n requiredBy: string[]\n suggestedSource: string\n}\n\nexport interface InstallManyPlanInput {\n action: 'install_many'\n profile: 'web'\n items: InstallPlanItem[]\n missingPeerDependencies: MissingPeerDependency[]\n impact: string\n restartExpected: boolean\n packageName?: never\n installSpec?: never\n currentSource?: never\n}\n\nexport type PlanInput = SinglePlanInput | InstallManyPlanInput\n\ninterface ConfirmationFields {\n id: string\n digest: string\n confirmationToken: string\n createdAt: string\n expiresAt: string\n}\n\nexport type ConfirmationPlan<Input extends PlanInput = PlanInput> = Input & ConfirmationFields\n\nexport interface PlanStoreOptions {\n now?: () => number\n random?: () => string\n ttlMs?: number\n}\n\nexport class PlanStore {\n private readonly plans = new Map<string, ConfirmationPlan>()\n private readonly used = new Set<string>()\n private readonly now: () => number\n private readonly random: () => string\n private readonly ttlMs: number\n\n constructor(options: PlanStoreOptions = {}) {\n this.now = options.now ?? Date.now\n this.random = options.random ?? randomUUID\n this.ttlMs = options.ttlMs ?? 10 * 60_000\n }\n\n create<Input extends PlanInput>(input: Input): ConfirmationPlan<Input> {\n const created = this.now()\n const id = this.random()\n const confirmationToken = this.random()\n const snapshot = structuredClone(input)\n const digest = createHash('sha256').update(JSON.stringify({ id, ...snapshot })).digest('hex')\n const plan = deepFreeze({\n ...snapshot,\n id,\n digest,\n confirmationToken,\n createdAt: new Date(created).toISOString(),\n expiresAt: new Date(created + this.ttlMs).toISOString(),\n })\n this.plans.set(confirmationToken, plan)\n return plan as ConfirmationPlan<Input>\n }\n\n consume(token: string): ConfirmationPlan {\n if (this.used.has(token)) fail('CONFIRMATION_REPLAYED', 'Confirmation token has already been used.')\n const plan = this.plans.get(token)\n if (plan === undefined) fail('CONFIRMATION_REQUIRED', 'A valid confirmation token is required.')\n this.plans.delete(token)\n this.used.add(token)\n if (this.now() >= Date.parse(plan.expiresAt)) fail('CONFIRMATION_EXPIRED', 'Confirmation token has expired.')\n return plan\n }\n}\n\nfunction deepFreeze<T>(value: T): T {\n if (typeof value !== 'object' || value === null || Object.isFrozen(value)) return value\n for (const child of Object.values(value)) deepFreeze(child)\n return Object.freeze(value)\n}\n","import { randomUUID } from 'node:crypto'\nimport { fail } from './errors.ts'\nimport type { PlanAction } from './plans.ts'\n\nexport type OperationStatus =\n | 'queued'\n | 'running'\n | 'succeeded'\n | 'succeeded_restart_required'\n | 'waiting_for_manual_restart'\n | 'failed'\n | 'cancelled'\n\nexport type CompletedOperationStatus = Exclude<OperationStatus, 'queued' | 'running' | 'cancelled'>\n\nexport interface OperationSnapshot<T = unknown> {\n id: string\n action: PlanAction\n target: string\n status: OperationStatus\n progress: string\n startedAt: string\n finishedAt?: string\n result?: T\n error?: { code?: string; message: string }\n}\n\ninterface OperationRecord {\n snapshot: OperationSnapshot<unknown>\n controller: AbortController\n done: Promise<void>\n resolveDone(): void\n execute(context: OperationContext): Promise<unknown>\n complete(result: unknown): OperationCompletion\n}\n\nexport interface OperationContext {\n signal: AbortSignal\n progress(message: string): void\n}\n\nexport interface OperationCompletion {\n status: CompletedOperationStatus\n progress?: string\n error?: { code?: string; message: string }\n}\n\nexport class OperationTracker {\n private readonly records = new Map<string, OperationRecord>()\n private readonly queue: string[] = []\n private active: string | null = null\n private readonly random: () => string\n private readonly now: () => number\n\n constructor(options: { random?: () => string; now?: () => number } = {}) {\n this.random = options.random ?? randomUUID\n this.now = options.now ?? Date.now\n }\n\n start<T>(\n action: PlanAction,\n target: string,\n execute: (context: OperationContext) => Promise<T>,\n complete: (result: T) => OperationCompletion = () => ({ status: 'succeeded' }),\n ): OperationSnapshot<T> {\n const id = this.random()\n const controller = new AbortController()\n const snapshot: OperationSnapshot<T> = {\n id,\n action,\n target,\n status: 'queued',\n progress: 'queued',\n startedAt: new Date(this.now()).toISOString(),\n }\n let resolveDone!: () => void\n const record: OperationRecord = {\n snapshot,\n controller,\n done: new Promise<void>(resolve => { resolveDone = resolve }),\n resolveDone,\n execute: async context => await execute(context),\n complete: result => complete(result as T),\n }\n this.records.set(id, record)\n this.queue.push(id)\n queueMicrotask(() => this.drain())\n return structuredClone(snapshot)\n }\n\n private drain(): void {\n if (this.active !== null) return\n const id = this.queue.shift()\n if (id === undefined) return\n const record = this.records.get(id)\n if (record === undefined || record.snapshot.status !== 'queued') {\n queueMicrotask(() => this.drain())\n return\n }\n this.active = id\n void this.run(id, record)\n }\n\n private async run(id: string, record: OperationRecord): Promise<void> {\n const { snapshot, controller } = record\n snapshot.status = 'running'\n snapshot.progress = 'running'\n try {\n const result = await record.execute({\n signal: controller.signal,\n progress: message => { snapshot.progress = message.slice(0, 500) },\n })\n snapshot.result = result\n if (controller.signal.aborted) {\n snapshot.status = 'cancelled'\n snapshot.progress = 'cancelled'\n } else {\n const completion = record.complete(result)\n snapshot.status = completion.status\n snapshot.progress = completion.progress ?? 'completed'\n if (completion.error !== undefined) snapshot.error = completion.error\n }\n } catch (error) {\n if (controller.signal.aborted) {\n snapshot.status = 'cancelled'\n snapshot.progress = 'cancelled'\n } else {\n snapshot.status = 'failed'\n snapshot.progress = 'failed'\n snapshot.error = {\n ...typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string'\n ? { code: error.code }\n : {},\n message: error instanceof Error ? error.message : String(error),\n }\n }\n } finally {\n snapshot.finishedAt = new Date(this.now()).toISOString()\n if (this.active === id) this.active = null\n record.resolveDone()\n queueMicrotask(() => this.drain())\n }\n }\n\n get(id: string): OperationSnapshot {\n const record = this.records.get(id)\n if (record === undefined) fail('OPERATION_NOT_FOUND', `Plugin operation ${id} was not found.`)\n return structuredClone(record.snapshot)\n }\n\n cancel(id: string): OperationSnapshot {\n const record = this.records.get(id)\n if (record === undefined) fail('OPERATION_NOT_FOUND', `Plugin operation ${id} was not found.`)\n if (record.snapshot.status === 'queued') {\n const index = this.queue.indexOf(id)\n if (index >= 0) this.queue.splice(index, 1)\n record.controller.abort(new Error('Plugin operation cancelled by user.'))\n record.snapshot.status = 'cancelled'\n record.snapshot.progress = 'cancelled'\n record.snapshot.finishedAt = new Date(this.now()).toISOString()\n record.resolveDone()\n } else if (record.snapshot.status === 'running') {\n record.snapshot.progress = 'cancelling'\n record.controller.abort(new Error('Plugin operation cancelled by user.'))\n }\n return structuredClone(record.snapshot)\n }\n\n async wait(id: string): Promise<OperationSnapshot> {\n const record = this.records.get(id)\n if (record === undefined) fail('OPERATION_NOT_FOUND', `Plugin operation ${id} was not found.`)\n await record.done\n return this.get(id)\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport { fail } from './errors.ts'\nimport type { SearchResult } from './search.ts'\n\nconst DEFAULT_TTL_MS = 10 * 60 * 1_000\nconst MAX_ROLES = 8\nconst MAX_AMBIGUITIES = 4\nconst MAX_OPTIONS = 8\nconst MAX_DRAFTS = 32\nconst ROLE_ID = /^[a-z][a-z0-9_]{0,63}$/u\n\nexport interface TaskRoleInput {\n id: string\n label: string\n query: string\n required?: boolean\n}\n\nexport interface TaskRole {\n id: string\n label: string\n query: string\n required: boolean\n}\n\nexport interface TaskAmbiguityInput {\n id: string\n question: string\n options: string[]\n}\n\nexport interface TaskSolutionPlan {\n task: string\n roles: TaskRole[]\n ambiguities: TaskAmbiguityInput[]\n}\n\nexport type TaskSolutionCandidate = Omit<SearchResult['candidates'][number], 'sources'>\n\nexport interface TaskRoleSearchGroup extends TaskRole {\n candidates: TaskSolutionCandidate[]\n providerErrors: SearchResult['providerErrors']\n rejectedCandidates: number\n}\n\nexport interface TaskSolutionDraft {\n schemaVersion: '1.0.0'\n solutionId: string\n task: string\n status: 'needs_review' | 'incomplete' | 'ambiguous'\n createdAt: number\n expiresAt: number\n roles: TaskRoleSearchGroup[]\n ambiguities: TaskAmbiguityInput[]\n}\n\nexport interface TaskRoleSelection {\n roleId: string\n candidateIdentities: string[]\n}\n\nexport interface AssessedTaskRole extends TaskRole {\n status: 'covered' | 'missing_required' | 'missing_optional'\n primaryCandidateIdentity: string | null\n alternativeCandidateIdentities: string[]\n}\n\nexport interface TaskSolutionAssessment {\n schemaVersion: '1.0.0'\n solutionId: string\n task: string\n status: 'complete' | 'incomplete' | 'ambiguous'\n roles: AssessedTaskRole[]\n ambiguities: TaskAmbiguityInput[]\n solutions: Array<TaskSolutionCandidate & { roleIds: string[] }>\n coverage: {\n requiredRoles: number\n coveredRequiredRoles: number\n optionalRoles: number\n coveredOptionalRoles: number\n missingRequiredRoleIds: string[]\n complete: boolean\n }\n}\n\nfunction bounded(value: unknown, name: string, maximum: number): string {\n const text = typeof value === 'string' ? value.trim() : ''\n if (text === '' || text.length > maximum || /[\\u0000-\\u001f\\u007f]/u.test(text)) {\n fail('INVALID_TASK_SOLUTION', `${name} must contain 1 to ${String(maximum)} printable characters.`)\n }\n return text\n}\n\nexport function validateTaskSolutionPlan(\n taskValue: string,\n roleValues: TaskRoleInput[],\n ambiguityValues: TaskAmbiguityInput[] = [],\n): TaskSolutionPlan {\n const task = bounded(taskValue, 'Task', 1_000)\n if (!Array.isArray(roleValues) || roleValues.length < 1 || roleValues.length > MAX_ROLES) {\n fail('INVALID_TASK_SOLUTION', `A task solution requires 1 to ${String(MAX_ROLES)} roles.`)\n }\n const roleIds = new Set<string>()\n const roleLabels = new Set<string>()\n const roleQueries = new Set<string>()\n const roles = roleValues.map((value): TaskRole => {\n const id = typeof value?.id === 'string' ? value.id.trim() : ''\n if (!ROLE_ID.test(id)) fail('INVALID_TASK_SOLUTION', 'Role ids must be lowercase stable identifiers.')\n if (roleIds.has(id)) fail('INVALID_TASK_SOLUTION', 'Role ids must be unique.')\n roleIds.add(id)\n const label = bounded(value.label, 'Role label', 80)\n const query = bounded(value.query, 'Role query', 120)\n const labelKey = label.toLocaleLowerCase()\n const queryKey = query.toLocaleLowerCase().replace(/\\s+/gu, ' ')\n if (roleLabels.has(labelKey) || roleQueries.has(queryKey)) {\n fail('INVALID_TASK_SOLUTION', 'Role labels and focused queries must be unique.')\n }\n roleLabels.add(labelKey)\n roleQueries.add(queryKey)\n return {\n id,\n label,\n query,\n required: value.required !== false,\n }\n })\n if (!Array.isArray(ambiguityValues) || ambiguityValues.length > MAX_AMBIGUITIES) {\n fail('INVALID_TASK_SOLUTION', `A task solution supports at most ${String(MAX_AMBIGUITIES)} unresolved ambiguities.`)\n }\n const ambiguityIds = new Set<string>()\n const ambiguities = ambiguityValues.map((value): TaskAmbiguityInput => {\n const id = typeof value?.id === 'string' ? value.id.trim() : ''\n if (!ROLE_ID.test(id) || ambiguityIds.has(id) || roleIds.has(id)) fail('INVALID_TASK_SOLUTION', 'Ambiguity ids must be unique lowercase stable identifiers and cannot reuse a role id.')\n ambiguityIds.add(id)\n if (!Array.isArray(value.options) || value.options.length < 2 || value.options.length > MAX_OPTIONS) {\n fail('INVALID_TASK_SOLUTION', `Each ambiguity requires 2 to ${String(MAX_OPTIONS)} options.`)\n }\n const options = value.options.map(option => bounded(option, 'Ambiguity option', 80))\n if (new Set(options).size !== options.length) fail('INVALID_TASK_SOLUTION', 'Ambiguity options must be unique.')\n return { id, question: bounded(value.question, 'Ambiguity question', 200), options }\n })\n return { task, roles, ambiguities }\n}\n\nfunction candidateSummary(candidate: SearchResult['candidates'][number]): TaskSolutionCandidate {\n const { sources: _sources, ...summary } = candidate\n return structuredClone(summary)\n}\n\nexport interface TaskSolutionStoreOptions {\n now?: () => number\n id?: () => string\n ttlMs?: number\n}\n\nexport class TaskSolutionStore {\n private readonly now: () => number\n private readonly id: () => string\n private readonly ttlMs: number\n private readonly drafts = new Map<string, TaskSolutionDraft>()\n\n constructor(options: TaskSolutionStoreOptions = {}) {\n this.now = options.now ?? Date.now\n this.id = options.id ?? (() => `task-solution:${randomUUID()}`)\n this.ttlMs = options.ttlMs ?? DEFAULT_TTL_MS\n if (!Number.isSafeInteger(this.ttlMs) || this.ttlMs < 1_000 || this.ttlMs > 60 * 60 * 1_000) {\n throw new RangeError('Task solution ttlMs must be from 1 second to 1 hour.')\n }\n }\n\n create(input: {\n task: string\n roles: TaskRoleInput[]\n ambiguities?: TaskAmbiguityInput[]\n searches: Record<string, SearchResult>\n }): TaskSolutionDraft {\n const plan = validateTaskSolutionPlan(input.task, input.roles, input.ambiguities)\n const now = this.now()\n for (const [id, draft] of this.drafts) if (draft.expiresAt <= now) this.drafts.delete(id)\n while (this.drafts.size >= MAX_DRAFTS) this.drafts.delete(this.drafts.keys().next().value as string)\n\n const roles = plan.roles.map((role): TaskRoleSearchGroup => {\n const search = input.searches[role.id]\n if (search === undefined) fail('INVALID_TASK_SOLUTION', `Search results are missing for role ${role.id}.`)\n return {\n ...role,\n candidates: search.candidates.map(candidateSummary),\n providerErrors: structuredClone(search.providerErrors),\n rejectedCandidates: search.rejectedCandidates,\n }\n })\n const requiredCandidateMissing = roles.some(role => role.required && role.candidates.length === 0)\n const draft: TaskSolutionDraft = {\n schemaVersion: '1.0.0',\n solutionId: bounded(this.id(), 'Task solution id', 200),\n task: plan.task,\n status: plan.ambiguities.length > 0 ? 'ambiguous' : requiredCandidateMissing ? 'incomplete' : 'needs_review',\n createdAt: now,\n expiresAt: now + this.ttlMs,\n roles,\n ambiguities: plan.ambiguities,\n }\n if (this.drafts.has(draft.solutionId)) fail('INVALID_TASK_SOLUTION', 'Task solution id must be unique.')\n this.drafts.set(draft.solutionId, draft)\n return structuredClone(draft)\n }\n\n assess(solutionIdValue: string, selectionValues: TaskRoleSelection[]): TaskSolutionAssessment {\n const solutionId = bounded(solutionIdValue, 'Task solution id', 200)\n const draft = this.drafts.get(solutionId)\n if (draft === undefined) fail('TASK_SOLUTION_NOT_FOUND', 'Task solution draft was not found.')\n if (draft.expiresAt <= this.now()) {\n this.drafts.delete(solutionId)\n fail('TASK_SOLUTION_EXPIRED', 'Task solution draft has expired; search the roles again.')\n }\n if (!Array.isArray(selectionValues) || selectionValues.length > draft.roles.length) fail('INVALID_TASK_SOLUTION', 'Task solution selections must contain at most one row per role.')\n const roleById = new Map(draft.roles.map(role => [role.id, role]))\n const selections = new Map<string, string[]>()\n for (const value of selectionValues) {\n const roleId = typeof value?.roleId === 'string' ? value.roleId.trim() : ''\n const role = roleById.get(roleId)\n if (role === undefined) fail('INVALID_TASK_SOLUTION', `Unknown task solution role ${roleId}.`)\n if (selections.has(roleId)) fail('INVALID_TASK_SOLUTION', `Role ${roleId} has duplicate selection rows.`)\n if (!Array.isArray(value.candidateIdentities) || value.candidateIdentities.length > 20) fail('INVALID_TASK_SOLUTION', `Role ${roleId} has too many candidate identities.`)\n const identities = value.candidateIdentities.map(identity => bounded(identity, 'Candidate identity', 500))\n if (new Set(identities).size !== identities.length) fail('INVALID_TASK_SOLUTION', `Role ${roleId} contains a duplicate candidate.`)\n const available = new Set(role.candidates.map(candidate => candidate.identity))\n for (const identity of identities) {\n if (!available.has(identity)) fail('INVALID_TASK_SOLUTION', `${identity} is not a candidate for role ${roleId}.`)\n }\n selections.set(roleId, identities)\n }\n\n const solutions = new Map<string, TaskSolutionCandidate & { roleIds: string[] }>()\n const roles = draft.roles.map((role): AssessedTaskRole => {\n const identities = selections.get(role.id) ?? []\n for (const identity of identities) {\n const candidate = role.candidates.find(item => item.identity === identity)!\n const existing = solutions.get(identity)\n if (existing === undefined) solutions.set(identity, { ...structuredClone(candidate), roleIds: [role.id] })\n else if (!existing.roleIds.includes(role.id)) existing.roleIds.push(role.id)\n }\n return {\n id: role.id,\n label: role.label,\n query: role.query,\n required: role.required,\n status: identities.length > 0 ? 'covered' : role.required ? 'missing_required' : 'missing_optional',\n primaryCandidateIdentity: identities[0] ?? null,\n alternativeCandidateIdentities: identities.slice(1),\n }\n })\n const required = roles.filter(role => role.required)\n const optional = roles.filter(role => !role.required)\n const missingRequiredRoleIds = required.filter(role => role.status !== 'covered').map(role => role.id)\n const complete = missingRequiredRoleIds.length === 0 && draft.ambiguities.length === 0\n return {\n schemaVersion: '1.0.0',\n solutionId,\n task: draft.task,\n status: draft.ambiguities.length > 0 ? 'ambiguous' : complete ? 'complete' : 'incomplete',\n roles,\n ambiguities: structuredClone(draft.ambiguities),\n solutions: [...solutions.values()],\n coverage: {\n requiredRoles: required.length,\n coveredRequiredRoles: required.filter(role => role.status === 'covered').length,\n optionalRoles: optional.length,\n coveredOptionalRoles: optional.filter(role => role.status === 'covered').length,\n missingRequiredRoleIds,\n complete,\n },\n }\n }\n}\n","import { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { PluginSearchRuntime } from './search-runtime.ts'\nimport { searchPlugins, type SearchOptions, type SearchResult } from './search.ts'\nimport {\n inspectPluginSource,\n NPM_NAME,\n parseGithubSpec,\n parseNpmSpec,\n renderSource,\n type FetchOptions,\n type PluginInspection,\n} from './source.ts'\nimport {\n disablePackage,\n enablePackage,\n listPluginStatuses,\n packageSurface,\n profileManifestText,\n readProfileManifest,\n reconcileRemovedPackage,\n restoreProfileManifest,\n type LoaderEntrySnapshot,\n type PackageSurface,\n type PluginStatus,\n} from './profile.ts'\nimport {\n PlanStore,\n type ConfirmationPlan,\n type InstallPlanItem,\n type MissingPeerDependency,\n type MutationAction,\n type PlanAction,\n} from './plans.ts'\nimport {\n OperationTracker,\n type OperationCompletion,\n type OperationContext,\n type OperationSnapshot,\n} from './operations.ts'\nimport type { DshCliRunner, RunnerResult } from './runner.ts'\nimport type { HotRuntime, HotActivationResult } from './hot-runtime.ts'\nimport type { DshRestarter } from './restart.ts'\nimport { fail } from './errors.ts'\nimport type { Telemetry } from './telemetry.ts'\nimport {\n TaskSolutionStore,\n validateTaskSolutionPlan,\n type TaskAmbiguityInput,\n type TaskRoleInput,\n type TaskRoleSelection,\n} from './task-solutions.ts'\n\ninterface LoaderEntryLike {\n id?: string\n disabled?: boolean\n options?: { id?: string; name?: string }\n fiber?: { state?: number | string }\n}\n\ninterface LoaderLike {\n entries(): Iterable<LoaderEntryLike>\n}\n\nexport interface PluginManagerDependencies {\n profileDir: string\n searchRuntime: Pick<PluginSearchRuntime, 'entries'>\n runner: Pick<DshCliRunner, 'runPlugin'>\n hot: Pick<HotRuntime, 'activate' | 'deactivate' | 'isActive'>\n restarter: Pick<DshRestarter, 'available' | 'schedule'>\n loader?: LoaderLike\n inspect?: typeof inspectPluginSource\n plans?: PlanStore\n operations?: OperationTracker\n fetchOptions?: Omit<FetchOptions, 'signal'>\n hmrTimeoutMs?: number\n telemetry?: Telemetry\n taskSolutions?: TaskSolutionStore\n}\n\nexport interface DiscoverRequest {\n action: 'list' | 'search' | 'search_roles' | 'assess_solution' | 'inspect' | 'status'\n query?: string\n target?: string\n operationId?: string\n maxResults?: number\n maxResultsPerRole?: number\n roles?: TaskRoleInput[]\n ambiguities?: TaskAmbiguityInput[]\n solutionId?: string\n selections?: TaskRoleSelection[]\n}\n\nexport interface PlanRequest {\n operation: PlanAction\n target?: string\n source?: string\n sources?: string[]\n}\n\nexport interface MutationResult {\n action: MutationAction\n packageName?: string\n installSpec?: string\n changed: boolean\n activated?: boolean\n restartRequired: boolean\n reason?: string\n nextAction?: string\n command?: { exitCode: number; stdout: string; stderr: string }\n restart?: { helperPid: number | undefined; logFile: string }\n}\n\nexport type InstallManyItemStatus =\n | 'succeeded'\n | 'succeeded_restart_required'\n | 'waiting_for_manual_restart'\n | 'failed'\n | 'cancelled'\n | 'skipped'\n\nexport interface InstallManyItemResult {\n packageName: string\n installSpec: string\n status: InstallManyItemStatus\n result?: MutationResult\n error?: { code?: string; message: string }\n}\n\nexport interface InstallManyResult {\n action: 'install_many'\n changed: boolean\n restartRequired: boolean\n nextAction?: string\n items: InstallManyItemResult[]\n}\n\nconst MAX_INSTALL_MANY_SOURCES = 20\n\nconst FIBER_PHASE: Record<number, string | null> = {\n 0: 'pending',\n 1: 'loading',\n 2: 'active',\n 3: 'failed',\n 4: null,\n 5: 'unloading',\n}\n\nconst PROTECTED_ENTRY_IDS = new Set([\n 'relay-plugin-search-runtime',\n 'relay-plugin-manager-host',\n 'commands',\n 'tools',\n 'webserver',\n 'web-runtime',\n])\n\nconst TELEMETRY_ERROR_CODES = new Set([\n 'INVALID_SOURCE', 'INVALID_NPM_SPEC', 'INVALID_NPM_VERSION', 'INVALID_GITHUB_SPEC',\n 'INVALID_GITHUB_REF', 'GITHUB_OWNER_REQUIRES_SEARCH', 'IMMUTABLE_SOURCE_REQUIRED',\n 'NETWORK_ERROR', 'SOURCE_HTTP_ERROR', 'INVALID_SOURCE_METADATA', 'INVALID_PLUGIN_MANIFEST',\n 'NOT_DSH_PLUGIN', 'PACKAGE_NAME_MISMATCH', 'NPM_INTEGRITY_MISSING', 'INVALID_SEARCH_QUERY',\n 'INVALID_ACTION', 'INVALID_BATCH', 'DUPLICATE_SEARCH_PROVIDER', 'PROFILE_READ_FAILED',\n 'PROFILE_WRITE_FAILED', 'PLUGIN_NOT_INSTALLED', 'PLUGIN_ALREADY_INSTALLED',\n 'ENABLEMENT_UNSUPPORTED', 'ENABLEMENT_CONFLICT', 'PROTECTED_PLUGIN', 'CONFIRMATION_REQUIRED',\n 'CONFIRMATION_INVALID', 'CONFIRMATION_EXPIRED', 'CONFIRMATION_REPLAYED', 'PLAN_STALE',\n 'OPERATION_NOT_FOUND', 'DSH_COMMAND_FAILED', 'BATCH_INSTALL_FAILED', 'POSTCONDITION_FAILED',\n 'RESTART_UNAVAILABLE', 'INVALID_TASK_SOLUTION', 'TASK_SOLUTION_NOT_FOUND', 'TASK_SOLUTION_EXPIRED',\n])\n\nfunction safePackageName(value: string | undefined): string {\n const name = value?.trim() ?? ''\n if (!NPM_NAME.test(name)) fail('INVALID_NPM_SPEC', 'A valid installed package name is required.')\n return name\n}\n\nfunction queryLengthBucket(value: string | undefined): string {\n const length = value?.trim().length ?? 0\n if (length === 0) return 'empty'\n if (length <= 10) return '1-10'\n if (length <= 30) return '11-30'\n if (length <= 80) return '31-80'\n return '81+'\n}\n\nfunction commandResult(result: RunnerResult): MutationResult['command'] {\n return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr }\n}\n\nfunction operationError(error: unknown): { code?: string; message: string } {\n return {\n ...typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string'\n ? { code: error.code }\n : {},\n message: error instanceof Error ? error.message : String(error),\n }\n}\n\nfunction telemetryErrorCode(error: unknown): string {\n const code = operationError(error).code\n return code !== undefined && TELEMETRY_ERROR_CODES.has(code) ? code : 'UNKNOWN'\n}\n\nfunction installedPackageManifest(profileDir: string, packageName: string): { name?: unknown; version?: unknown } | null {\n try {\n return JSON.parse(readFileSync(join(profileDir, 'node_modules', packageName, 'package.json'), 'utf8')) as {\n name?: unknown\n version?: unknown\n }\n } catch {\n return null\n }\n}\n\nfunction installedSourceMatches(packageName: string, dependency: string, installSpec: string): boolean {\n const github = parseGithubSpec(installSpec, true)\n if (github !== null) return dependency === installSpec\n const npm = parseNpmSpec(installSpec, true)\n return npm.package === packageName && dependency === npm.version\n}\n\nexport class PluginManager {\n private readonly profileDir: string\n private readonly searchRuntime: PluginManagerDependencies['searchRuntime']\n private readonly runner: PluginManagerDependencies['runner']\n private readonly hot: PluginManagerDependencies['hot']\n private readonly restarter: PluginManagerDependencies['restarter']\n private readonly loader?: LoaderLike\n private readonly inspect: typeof inspectPluginSource\n private readonly plans: PlanStore\n private readonly operations: OperationTracker\n private readonly fetchOptions: Omit<FetchOptions, 'signal'>\n private readonly hmrTimeoutMs: number\n private readonly telemetry: Telemetry\n private readonly taskSolutions: TaskSolutionStore\n\n constructor(dependencies: PluginManagerDependencies) {\n this.profileDir = dependencies.profileDir\n this.searchRuntime = dependencies.searchRuntime\n this.runner = dependencies.runner\n this.hot = dependencies.hot\n this.restarter = dependencies.restarter\n this.loader = dependencies.loader\n this.inspect = dependencies.inspect ?? inspectPluginSource\n this.plans = dependencies.plans ?? new PlanStore()\n this.operations = dependencies.operations ?? new OperationTracker()\n this.fetchOptions = dependencies.fetchOptions ?? {}\n this.hmrTimeoutMs = dependencies.hmrTimeoutMs ?? 5_000\n this.telemetry = dependencies.telemetry ?? { capture() {} }\n this.taskSolutions = dependencies.taskSolutions ?? new TaskSolutionStore()\n }\n\n private capture(event: string, properties: Readonly<Record<string, string | number | boolean>> = {}): void {\n try {\n this.telemetry.capture(event, properties)\n } catch {\n // Analytics is deliberately best-effort and cannot affect plugin operations.\n }\n }\n\n private loaderEntries(): LoaderEntrySnapshot[] {\n if (this.loader === undefined) return []\n return [...this.loader.entries()].flatMap((entry) => {\n const id = entry.options?.id ?? entry.id\n if (id === undefined || id === '') return []\n const rawPhase = entry.fiber?.state\n const phase = typeof rawPhase === 'number' ? (FIBER_PHASE[rawPhase] ?? 'unknown') : rawPhase ?? null\n return [{\n id,\n ...(entry.options?.name === undefined ? {} : { name: entry.options.name }),\n disabled: entry.disabled === true,\n phase,\n }]\n })\n }\n\n list(): PluginStatus[] {\n return listPluginStatuses(this.profileDir, this.loaderEntries())\n }\n\n async discover(request: DiscoverRequest, signal?: AbortSignal): Promise<unknown> {\n this.capture('plugin_manager_used', {\n surface: 'discover',\n action: request.action,\n ...(request.action === 'search' || request.action === 'search_roles'\n ? { has_query: (request.query?.trim().length ?? 0) > 0, query_length_bucket: queryLengthBucket(request.query) }\n : {}),\n })\n if (request.action === 'list') return { profile: 'web', plugins: this.list() }\n if (request.action === 'search') {\n const options: SearchOptions = {\n ...this.fetchOptions,\n signal,\n maxResults: request.maxResults,\n inspect: this.inspect,\n }\n return await searchPlugins(this.searchRuntime, request.query ?? '', options)\n }\n if (request.action === 'search_roles') {\n const plan = validateTaskSolutionPlan(request.query ?? '', request.roles ?? [], request.ambiguities ?? [])\n const maxResultsPerRole = request.maxResultsPerRole ?? 20\n if (!Number.isInteger(maxResultsPerRole) || maxResultsPerRole < 1 || maxResultsPerRole > 20) {\n fail('INVALID_TASK_SOLUTION', 'maxResultsPerRole must be an integer from 1 to 20.')\n }\n const searches = await Promise.all(plan.roles.map(async role => [role.id, await searchPlugins(\n this.searchRuntime,\n role.query,\n { ...this.fetchOptions, signal, maxResults: maxResultsPerRole, inspect: this.inspect },\n )] as const))\n return this.taskSolutions.create({\n task: plan.task,\n roles: plan.roles,\n ambiguities: plan.ambiguities,\n searches: Object.fromEntries(searches),\n })\n }\n if (request.action === 'assess_solution') {\n if (request.solutionId === undefined) fail('INVALID_TASK_SOLUTION', 'A task solution id is required for assessment.')\n return this.taskSolutions.assess(request.solutionId, request.selections ?? [])\n }\n if (request.action === 'inspect') {\n if (request.target === undefined) fail('INVALID_SOURCE', 'A plugin source is required for inspection.')\n return await this.inspect(request.target, { ...this.fetchOptions, signal })\n }\n if (request.operationId !== undefined) return this.operations.get(request.operationId)\n if (request.target === undefined) return { profile: 'web', plugins: this.list() }\n const name = safePackageName(request.target)\n const status = this.list().find(plugin => plugin.packageName === name)\n if (status === undefined) fail('PLUGIN_NOT_INSTALLED', `${name} is not installed in the web profile.`)\n return status\n }\n\n private installed(name: string): { source: string; surface: PackageSurface } {\n const source = readProfileManifest(this.profileDir).dependencies?.[name]\n if (source === undefined) fail('PLUGIN_NOT_INSTALLED', `${name} is not installed in the web profile.`)\n return { source, surface: packageSurface(this.profileDir, name, source) }\n }\n\n private assertEnablementAllowed(surface: PackageSurface): void {\n if (surface.entryIds?.some(id => PROTECTED_ENTRY_IDS.has(id)) === true) {\n fail('PROTECTED_PLUGIN', `${surface.packageName} owns protected DSH infrastructure and cannot be toggled.`)\n }\n }\n\n private async updateInspection(name: string, sourceOverride: string | undefined, signal?: AbortSignal): Promise<PluginInspection> {\n if (sourceOverride !== undefined) {\n const inspection = await this.inspect(sourceOverride, { ...this.fetchOptions, signal })\n if (inspection.packageName !== name) fail('PACKAGE_NAME_MISMATCH', 'Update source resolves to a different package name.')\n return inspection\n }\n const current = this.installed(name).source\n const github = parseGithubSpec(current)\n const source = github === null\n ? name\n : renderSource({ kind: 'github', owner: github.owner, repo: github.repo })\n return await this.inspect(source, { ...this.fetchOptions, signal })\n }\n\n async plan(request: PlanRequest, signal?: AbortSignal): Promise<ConfirmationPlan> {\n this.capture('plugin_manager_used', {\n surface: 'plan',\n action: request.operation,\n ...(request.operation === 'install_many' ? { batch_size: request.sources?.length ?? 0 } : {}),\n })\n if (request.operation === 'install_many') return await this.planInstallMany(request.sources, signal)\n if (request.operation === 'restart') {\n if (!this.restarter.available()) fail('RESTART_UNAVAILABLE', 'Automatic restart is unavailable in this deployment.')\n return this.plans.create({\n action: 'restart', profile: 'web', impact: 'Restart the running DSH process.', restartExpected: true,\n })\n }\n if (request.operation === 'install') {\n const source = request.source ?? request.target\n if (source === undefined) fail('INVALID_SOURCE', 'Install requires an npm or GitHub source.')\n const inspection = await this.inspect(source, { ...this.fetchOptions, signal })\n if (readProfileManifest(this.profileDir).dependencies?.[inspection.packageName] !== undefined) {\n fail('PLUGIN_ALREADY_INSTALLED', `${inspection.packageName} is already installed; use update.`)\n }\n return this.plans.create({\n action: 'install', profile: 'web', packageName: inspection.packageName,\n installSpec: inspection.installSpec,\n impact: `Install ${inspection.packageName} from ${inspection.installSpec}.`,\n restartExpected: inspection.bundlePatch !== null,\n })\n }\n const name = safePackageName(request.target)\n const installed = this.installed(name)\n if (request.operation === 'update') {\n const inspection = await this.updateInspection(name, request.source, signal)\n return this.plans.create({\n action: 'update', profile: 'web', packageName: name, currentSource: installed.source,\n installSpec: inspection.installSpec,\n impact: `Update ${name} from ${installed.source} to ${inspection.installSpec}.`,\n restartExpected: true,\n })\n }\n if (request.operation === 'enable' || request.operation === 'disable') {\n this.assertEnablementAllowed(installed.surface)\n if (installed.surface.entryIds === null) {\n fail('ENABLEMENT_UNSUPPORTED', `${name} has no safely attributable Loader entries.`)\n }\n }\n return this.plans.create({\n action: request.operation,\n profile: 'web',\n packageName: name,\n currentSource: installed.source,\n impact: request.operation === 'disable'\n ? `Disable ${name}. Conversations currently using capabilities from this plugin may be interrupted; confirm from another backend or session when continuity matters.`\n : `${request.operation[0]!.toUpperCase()}${request.operation.slice(1)} ${name}.`,\n restartExpected: request.operation === 'remove',\n })\n }\n\n private async planInstallMany(sources: string[] | undefined, signal?: AbortSignal): Promise<ConfirmationPlan> {\n if (sources === undefined || sources.length === 0 || sources.length > MAX_INSTALL_MANY_SOURCES) {\n fail('INVALID_BATCH', `Multi-install requires between 1 and ${MAX_INSTALL_MANY_SOURCES} sources.`)\n }\n const inspections = await Promise.all(sources.map(source => this.inspect(source, { ...this.fetchOptions, signal })))\n const profileDependencies = readProfileManifest(this.profileDir).dependencies ?? {}\n const requestedPackages = new Set<string>()\n for (const inspection of inspections) {\n if (requestedPackages.has(inspection.packageName)) {\n fail('INVALID_BATCH', `Multi-install resolves more than one source to ${inspection.packageName}.`)\n }\n if (profileDependencies[inspection.packageName] !== undefined) {\n fail('PLUGIN_ALREADY_INSTALLED', `${inspection.packageName} is already installed; use update.`)\n }\n requestedPackages.add(inspection.packageName)\n }\n\n const missing = new Map<string, { ranges: Set<string>; requiredBy: Set<string> }>()\n for (const inspection of inspections) {\n for (const [packageName, range] of Object.entries(inspection.peerDependencies)) {\n if (profileDependencies[packageName] !== undefined || requestedPackages.has(packageName)) continue\n const entry = missing.get(packageName) ?? { ranges: new Set<string>(), requiredBy: new Set<string>() }\n entry.ranges.add(range)\n entry.requiredBy.add(inspection.packageName)\n missing.set(packageName, entry)\n }\n }\n const missingPeerDependencies: MissingPeerDependency[] = [...missing]\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([packageName, entry]) => ({\n packageName,\n ranges: [...entry.ranges].sort(),\n requiredBy: [...entry.requiredBy].sort(),\n suggestedSource: packageName,\n }))\n const items: InstallPlanItem[] = inspections.map(inspection => ({\n action: 'install',\n packageName: inspection.packageName,\n installSpec: inspection.installSpec,\n impact: `Install ${inspection.packageName} from ${inspection.installSpec}.`,\n restartExpected: inspection.bundlePatch !== null,\n }))\n return this.plans.create({\n action: 'install_many',\n profile: 'web',\n items,\n missingPeerDependencies,\n impact: `Install ${items.length} plugins serially: ${items.map(item => item.packageName).join(', ')}.`,\n restartExpected: items.some(item => item.restartExpected),\n })\n }\n\n execute(confirmationToken: string): OperationSnapshot {\n const plan = this.plans.consume(confirmationToken)\n this.assertPlanFresh(plan)\n if (plan.action === 'install_many') {\n const automaticRestartAvailable = this.restarter.available()\n return this.operations.start(\n 'install_many',\n `${plan.items.length} plugins`,\n async context => {\n this.assertPlanFresh(plan)\n return await this.installMany(plan.items, context, automaticRestartAvailable)\n },\n result => this.batchCompletion(result, automaticRestartAvailable),\n )\n }\n const target = plan.packageName ?? 'dsh'\n const automaticRestartAvailable = this.restarter.available()\n return this.operations.start(plan.action, target, async context => {\n this.assertPlanFresh(plan)\n if (plan.action === 'restart') {\n context.progress('scheduling restart')\n const restart = this.restarter.schedule()\n return { action: 'restart', changed: true, restartRequired: false, restart } satisfies MutationResult\n }\n if (plan.packageName === undefined) fail('POSTCONDITION_FAILED', 'Mutation plan has no package name.')\n if (plan.action === 'install' || plan.action === 'update') {\n if (plan.installSpec === undefined) fail('POSTCONDITION_FAILED', 'Install/update plan has no immutable source.')\n if (plan.action === 'install') this.capture('plugin_install_started', { plugin_name: plan.packageName })\n try {\n const result = this.withRestartGuidance(\n await this.installOrUpdate(plan.action, plan.packageName, plan.installSpec, context),\n automaticRestartAvailable,\n )\n if (plan.action === 'install') {\n this.capture('plugin_install_succeeded', {\n plugin_name: plan.packageName,\n activated: result.activated === true,\n restart_required: result.restartRequired,\n })\n }\n return result\n } catch (error) {\n if (plan.action === 'install') {\n this.capture('plugin_install_failed', {\n plugin_name: plan.packageName,\n error_code: telemetryErrorCode(error),\n })\n }\n throw error\n }\n }\n if (plan.action === 'remove') {\n return this.withRestartGuidance(await this.remove(plan.packageName, context), automaticRestartAvailable)\n }\n return this.withRestartGuidance(await this.toggle(plan.action, plan.packageName, context), automaticRestartAvailable)\n }, result => this.mutationCompletion(result, automaticRestartAvailable))\n }\n\n private assertPlanFresh(plan: ConfirmationPlan): void {\n const dependencies = readProfileManifest(this.profileDir).dependencies ?? {}\n if (plan.action === 'install_many') {\n for (const item of plan.items) {\n if (dependencies[item.packageName] !== undefined) {\n fail('PLAN_STALE', `${item.packageName} was installed after this plan was created; create a new plan.`)\n }\n }\n return\n }\n if (plan.action === 'install' && plan.packageName !== undefined && dependencies[plan.packageName] !== undefined) {\n fail('PLAN_STALE', `${plan.packageName} was installed after this plan was created; create a new plan.`)\n }\n if (plan.action !== 'install' && plan.action !== 'restart' && plan.packageName !== undefined\n && dependencies[plan.packageName] !== plan.currentSource) {\n fail('PLAN_STALE', `${plan.packageName} changed after this plan was created; create a new plan.`)\n }\n }\n\n private withRestartGuidance<Result extends { restartRequired: boolean; nextAction?: string }>(\n result: Result,\n automaticRestartAvailable: boolean,\n ): Result {\n if (!result.restartRequired) return result\n return {\n ...result,\n nextAction: automaticRestartAvailable\n ? 'Plan and confirm a separate DSH restart to activate this change.'\n : 'Restart DSH through the deployment supervisor or operator workflow to activate this change.',\n }\n }\n\n private mutationCompletion(\n result: { restartRequired: boolean },\n automaticRestartAvailable: boolean,\n ): { status: 'succeeded' | 'succeeded_restart_required' | 'waiting_for_manual_restart' } {\n if (!result.restartRequired) return { status: 'succeeded' }\n return { status: automaticRestartAvailable ? 'succeeded_restart_required' : 'waiting_for_manual_restart' }\n }\n\n private async installMany(\n items: readonly InstallPlanItem[],\n context: OperationContext,\n automaticRestartAvailable: boolean,\n ): Promise<InstallManyResult> {\n const results: InstallManyItemResult[] = []\n const skipRemaining = (start: number): void => {\n for (const item of items.slice(start)) {\n results.push({\n packageName: item.packageName,\n installSpec: item.installSpec,\n status: 'skipped',\n error: { message: 'Skipped because an earlier batch item did not complete.' },\n })\n }\n }\n\n for (const [index, item] of items.entries()) {\n if (context.signal.aborted) {\n results.push({\n packageName: item.packageName,\n installSpec: item.installSpec,\n status: 'cancelled',\n error: { message: 'Batch cancelled before this item started.' },\n })\n skipRemaining(index + 1)\n break\n }\n context.progress(`install_many: ${index + 1}/${items.length} installing ${item.packageName}`)\n this.capture('plugin_install_started', { plugin_name: item.packageName, batch: true })\n try {\n const result = this.withRestartGuidance(\n await this.installOrUpdate('install', item.packageName, item.installSpec, context),\n automaticRestartAvailable,\n )\n results.push({\n packageName: item.packageName,\n installSpec: item.installSpec,\n status: this.mutationCompletion(result, automaticRestartAvailable).status,\n result,\n })\n this.capture('plugin_install_succeeded', {\n plugin_name: item.packageName,\n batch: true,\n activated: result.activated === true,\n restart_required: result.restartRequired,\n })\n } catch (error) {\n results.push({\n packageName: item.packageName,\n installSpec: item.installSpec,\n status: context.signal.aborted ? 'cancelled' : 'failed',\n error: operationError(error),\n })\n this.capture('plugin_install_failed', {\n plugin_name: item.packageName,\n batch: true,\n error_code: telemetryErrorCode(error),\n })\n skipRemaining(index + 1)\n break\n }\n }\n const result: InstallManyResult = {\n action: 'install_many',\n changed: results.some(item => item.result?.changed === true),\n restartRequired: results.some(item => item.result?.restartRequired === true),\n items: results,\n }\n return this.withRestartGuidance(result, automaticRestartAvailable)\n }\n\n private batchCompletion(\n result: InstallManyResult,\n automaticRestartAvailable: boolean,\n ): OperationCompletion {\n const failed = result.items.find(item => item.status === 'failed')\n if (failed !== undefined) {\n return {\n status: 'failed',\n progress: `failed at ${failed.packageName}`,\n error: {\n code: 'BATCH_INSTALL_FAILED',\n message: `${failed.packageName} failed: ${failed.error?.message ?? 'unknown error'}`,\n },\n }\n }\n return this.mutationCompletion(result, automaticRestartAvailable)\n }\n\n operation(id: string): OperationSnapshot {\n return this.operations.get(id)\n }\n\n cancel(id: string): OperationSnapshot {\n return this.operations.cancel(id)\n }\n\n wait(id: string): Promise<OperationSnapshot> {\n return this.operations.wait(id)\n }\n\n private async installOrUpdate(\n action: 'install' | 'update',\n packageName: string,\n installSpec: string,\n context: { signal: AbortSignal; progress(message: string): void },\n ): Promise<MutationResult> {\n const before = profileManifestText(this.profileDir)\n context.progress(`${action}: running official DSH plugin command`)\n const result = await this.runner.runPlugin('web', ['add', '--save-exact', installSpec], context.signal, context.progress)\n if (result.exitCode !== 0 || result.timedOut || result.cancelled) {\n restoreProfileManifest(this.profileDir, before)\n fail('DSH_COMMAND_FAILED', `Official DSH plugin command failed with exit code ${result.exitCode}.`, commandResult(result))\n }\n const manifest = readProfileManifest(this.profileDir)\n const dependency = manifest.dependencies?.[packageName]\n const surface = dependency === undefined ? null : packageSurface(this.profileDir, packageName, dependency)\n const installedManifest = installedPackageManifest(this.profileDir, packageName)\n const bundleCount = manifest.dsh?.profile?.bundles?.filter(name => name === packageName).length ?? 0\n const validSurface = surface !== null && (surface.bundle || surface.client)\n const validBundleMembership = surface !== null && (surface.bundle ? bundleCount === 1 : bundleCount === 0)\n const validIdentity = installedManifest?.name === packageName\n const validSource = dependency !== undefined && installedSourceMatches(packageName, dependency, installSpec)\n const npmSource = parseGithubSpec(installSpec, true) === null ? parseNpmSpec(installSpec, true) : null\n const validVersion = npmSource === null || installedManifest?.version === npmSource.version\n if (!validSource || !validSurface || !validBundleMembership || !validIdentity || !validVersion) {\n restoreProfileManifest(this.profileDir, before)\n fail('POSTCONDITION_FAILED', `Official command completed but ${packageName} did not satisfy profile postconditions.`)\n }\n let activation: HotActivationResult\n if (action === 'update') {\n activation = { active: false, restartRequired: true, reason: 'Updated bundles activate after DSH restart.' }\n } else {\n context.progress('install: attempting restart-free activation')\n activation = await this.hot.activate(surface)\n }\n return {\n action,\n packageName,\n installSpec,\n changed: true,\n activated: activation.active,\n restartRequired: activation.restartRequired,\n ...(activation.reason === null ? {} : { reason: activation.reason }),\n command: commandResult(result),\n }\n }\n\n private async remove(\n packageName: string,\n context: { signal: AbortSignal; progress(message: string): void },\n ): Promise<MutationResult> {\n this.installed(packageName)\n const before = profileManifestText(this.profileDir)\n const wasHot = this.hot.isActive(packageName)\n context.progress('remove: running official DSH plugin command')\n const result = await this.runner.runPlugin('web', ['remove', packageName], context.signal, context.progress)\n const packageExists = existsSync(join(this.profileDir, 'node_modules', packageName, 'package.json'))\n if (result.exitCode !== 0 || result.timedOut || result.cancelled) {\n if (!result.cancelled && !packageExists) reconcileRemovedPackage(this.profileDir, packageName)\n else restoreProfileManifest(this.profileDir, before)\n if (packageExists || result.cancelled) {\n fail('DSH_COMMAND_FAILED', `Official DSH plugin remove failed with exit code ${result.exitCode}.`, commandResult(result))\n }\n }\n const manifest = readProfileManifest(this.profileDir)\n const remains = manifest.dependencies?.[packageName] !== undefined\n || manifest.dsh?.profile?.bundles?.includes(packageName) === true\n if (remains) fail('POSTCONDITION_FAILED', `${packageName} remains in the profile after removal.`)\n const deactivated = wasHot ? await this.hot.deactivate(packageName) : false\n return {\n action: 'remove',\n packageName,\n changed: true,\n activated: false,\n restartRequired: !deactivated,\n ...deactivated ? {} : { reason: 'A boot-loaded plugin remains in the current process until DSH restarts.' },\n command: commandResult(result),\n }\n }\n\n private async toggle(\n action: 'enable' | 'disable',\n packageName: string,\n context: { signal: AbortSignal; progress(message: string): void },\n ): Promise<MutationResult> {\n const { surface } = this.installed(packageName)\n this.assertEnablementAllowed(surface)\n context.progress(`${action}: updating profile patch`)\n const ids = action === 'disable' ? disablePackage(this.profileDir, surface) : enablePackage(this.profileDir, surface)\n if (action === 'disable' && this.hot.isActive(packageName)) await this.hot.deactivate(packageName)\n if (action === 'enable' && !this.loaderEntries().some(entry => surface.entryIds?.includes(entry.id))) {\n const activation = await this.hot.activate(surface)\n return {\n action, packageName, changed: ids.length > 0, activated: activation.active,\n restartRequired: activation.restartRequired,\n ...(activation.reason === null ? {} : { reason: activation.reason }),\n }\n }\n const expectedDisabled = action === 'disable'\n const deadline = Date.now() + this.hmrTimeoutMs\n let verified = false\n while (Date.now() < deadline && !context.signal.aborted) {\n const relevant = this.loaderEntries().filter(entry => surface.entryIds?.includes(entry.id))\n if (relevant.length > 0 && relevant.every(entry => entry.disabled === expectedDisabled)) {\n verified = true\n break\n }\n await new Promise(resolve => setTimeout(resolve, 50))\n }\n return {\n action,\n packageName,\n changed: ids.length > 0,\n activated: action === 'enable' && verified,\n restartRequired: !verified,\n ...verified ? {} : { reason: 'Loader HMR state could not be verified; restart is required.' },\n }\n }\n}\n\nexport type { SearchResult }\n","import type { PluginSearchProvider } from './search-runtime.ts'\nimport { isGithubPart, NPM_NAME } from './source.ts'\n\nconst MAX_PROVIDER_RESULTS = 20\nconst REGISTRY_KEYWORD_CHALLENGER_POOL = 21\nconst REGISTRY_DIRECTORY_POOL = 50\nconst RECIPROCAL_RANK_OFFSET = 20\nconst KEYWORD_RANK_WEIGHT = 0.1\nconst DIRECTORY_RANK_WEIGHT = 0.2\nconst IDENTITY_TERM_BOOST = 0.01\nconst REGISTRY_SNAPSHOT_ID = /^discovery\\.[a-z0-9.-]+$/u\nconst REGISTRY_DIRECTORY_VERSION = /^[a-z0-9][a-z0-9._-]{0,127}$/u\n\nfunction query(value: string): string {\n const normalized = value.trim()\n if (normalized === '' || normalized.length > 120 || /[\\u0000-\\u001f\\u007f]/u.test(normalized)) {\n throw new Error('Search query must contain 1 to 120 printable characters.')\n }\n return normalized\n}\n\nexport function npmSearchProvider(fetchImpl: typeof globalThis.fetch = globalThis.fetch): PluginSearchProvider {\n return {\n id: 'npm',\n async search(request) {\n const text = query(request.query)\n const response = await fetchImpl(\n `https://registry.npmjs.org/-/v1/search?text=${encodeURIComponent(`${text} keywords:dsh-plugin`)}&size=${Math.min(request.maxResults, MAX_PROVIDER_RESULTS)}`,\n { signal: request.signal, headers: { accept: 'application/json' } },\n )\n if (!response.ok) throw new Error(`npm search returned HTTP ${response.status}`)\n const data = await response.json() as { objects?: Array<{ package?: { name?: unknown; description?: unknown; links?: { homepage?: unknown; repository?: unknown } }; score?: { final?: unknown } }> }\n const searched = (data.objects ?? []).flatMap((entry) => {\n const name = entry.package?.name\n if (typeof name !== 'string' || !NPM_NAME.test(name)) return []\n return [{\n id: `npm:${name}`,\n title: name,\n ...(typeof entry.package?.description === 'string' ? { description: entry.package.description } : {}),\n ...(typeof entry.package?.links?.homepage === 'string' ? { homepage: entry.package.links.homepage } : {}),\n ...(typeof entry.package?.links?.repository === 'string' ? { repository: entry.package.links.repository } : {}),\n sources: [{ kind: 'npm' as const, package: name }],\n ...(typeof entry.score?.final === 'number' ? { score: entry.score.final } : {}),\n }]\n })\n if (!NPM_NAME.test(text) || searched.some(candidate => candidate.sources.some(source => source.kind === 'npm' && source.package === text))) {\n return searched\n }\n return [{\n id: `npm:${text}`,\n title: text,\n sources: [{ kind: 'npm' as const, package: text }],\n score: Number.MAX_SAFE_INTEGER,\n evidence: ['Exact npm package-name query'],\n match: { kind: 'exact-identifier' as const, value: text },\n }, ...searched]\n },\n }\n}\n\nexport function githubSearchProvider(\n fetchImpl: typeof globalThis.fetch = globalThis.fetch,\n env: NodeJS.ProcessEnv = process.env,\n): PluginSearchProvider {\n return {\n id: 'github',\n async search(request) {\n const text = query(request.query)\n const token = env.GITHUB_TOKEN ?? env.GH_TOKEN\n type Repository = {\n id?: unknown\n full_name?: unknown\n description?: unknown\n html_url?: unknown\n stargazers_count?: unknown\n }\n const search = async (searchText: string): Promise<{ response: Response; items: Repository[] }> => {\n const response = await fetchImpl(\n `https://api.github.com/search/repositories?q=${encodeURIComponent(searchText)}&per_page=${Math.min(request.maxResults, MAX_PROVIDER_RESULTS)}`,\n {\n signal: request.signal,\n headers: {\n accept: 'application/vnd.github+json',\n 'user-agent': 'relay-dsh-plugin-manager',\n 'x-github-api-version': '2022-11-28',\n ...(token === undefined || token === '' ? {} : { authorization: `Bearer ${token}` }),\n },\n },\n )\n if (!response.ok) return { response, items: [] }\n const data = await response.json() as { items?: Repository[] }\n return { response, items: data.items ?? [] }\n }\n\n const owner = request.intent?.kind === 'github-owner' ? request.intent.owner : undefined\n let exactOwner = owner !== undefined\n let result = await search(owner === undefined\n ? `${text} topic:dsh-plugin`\n : `user:${owner} topic:dsh-plugin`)\n let entries = result.items\n if (owner !== undefined) {\n entries = entries.filter(entry => typeof entry.full_name === 'string'\n && entry.full_name.split('/')[0]?.toLowerCase() === owner.toLowerCase())\n const shouldFallback = request.intent?.fallbackToText === true\n && (result.response.status === 422 || (result.response.ok && entries.length === 0))\n if (shouldFallback) {\n result = await search(`${text} topic:dsh-plugin`)\n entries = result.items\n exactOwner = false\n }\n }\n if (!result.response.ok) throw new Error(`GitHub search returned HTTP ${result.response.status}`)\n\n return entries.flatMap((entry) => {\n if (typeof entry.full_name !== 'string') return []\n const [repositoryOwner, repo, ...extra] = entry.full_name.split('/')\n if (repositoryOwner === undefined || repo === undefined || extra.length > 0) return []\n return [{\n id: `github:${entry.id ?? entry.full_name}`,\n title: entry.full_name,\n ...(typeof entry.description === 'string' ? { description: entry.description } : {}),\n ...(typeof entry.html_url === 'string' ? { homepage: entry.html_url, repository: entry.html_url } : {}),\n sources: [{ kind: 'github' as const, owner: repositoryOwner, repo }],\n ...(typeof entry.stargazers_count === 'number' ? { score: entry.stargazers_count } : {}),\n evidence: [\n `GitHub repository owner: ${repositoryOwner}`,\n ...(exactOwner ? [`Exact GitHub owner query: ${owner!}`] : []),\n `GitHub stars: ${String(entry.stargazers_count ?? 0)}`,\n ],\n ...(exactOwner ? { match: { kind: 'github-owner' as const, value: owner! } } : {}),\n }]\n })\n },\n }\n}\n\nfunction registryEndpoint(value: string, operation: 'search' | 'route'): string {\n let url: URL\n try { url = new URL(value) } catch { throw new Error('Registry URL must be an absolute URL.') }\n const local = url.hostname === '127.0.0.1' || url.hostname === 'localhost' || url.hostname === '::1'\n if (url.protocol !== 'https:' && !(local && url.protocol === 'http:')) {\n throw new Error('Registry URL must use HTTPS, except for an explicit local development endpoint.')\n }\n if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {\n throw new Error('Registry URL cannot contain credentials, query parameters, or a fragment.')\n }\n url.pathname = `${url.pathname.replace(/\\/$/u, '')}/v1/plugins:${operation}`\n return url.href\n}\n\nfunction boundedText(value: unknown, maximum = 4_000): string | undefined {\n return typeof value === 'string' && value.trim() !== '' && value.length <= maximum ? value : undefined\n}\n\nfunction queryLocale(value: string): 'zh-CN' | 'en' {\n return /\\p{Script=Han}/u.test(value) ? 'zh-CN' : 'en'\n}\n\ninterface RegistryResponseMetadata {\n snapshotId: string\n strategy: 'keyword' | 'keyword-plus-semantic-directory-v1'\n directoryVersion?: string\n locale: 'zh-CN' | 'en'\n}\n\nfunction safeCodes(value: unknown, maximum = 20): string[] {\n return Array.isArray(value)\n ? value.filter((item): item is string => typeof item === 'string' && /^[a-z0-9._-]+$/u.test(item)).slice(0, maximum)\n : []\n}\n\nfunction safePath(value: unknown, locale: 'zh-CN' | 'en'): string[] {\n if (!Array.isArray(value)) return []\n return value.flatMap(item => {\n if (typeof item !== 'object' || item === null || Array.isArray(item)) return []\n const path = item as { en?: unknown; zh_CN?: unknown }\n const label = locale === 'en'\n ? boundedText(path.en, 200) ?? boundedText(path.zh_CN, 200)\n : boundedText(path.zh_CN, 200) ?? boundedText(path.en, 200)\n return label === undefined ? [] : [label]\n }).slice(0, 8)\n}\n\nfunction registryCandidate(value: unknown, metadata: RegistryResponseMetadata): Awaited<ReturnType<PluginSearchProvider['search']>>[number] | null {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return null\n const candidate = value as {\n entry?: {\n entry_id?: unknown\n identity?: { name?: unknown; repository_url?: unknown; repository_full_name?: unknown }\n imported_content?: { description?: { 'zh-CN'?: unknown; en?: unknown }; trust?: unknown }\n sources?: unknown\n resolution?: { status?: unknown }\n }\n match?: {\n score?: unknown\n reason_codes?: unknown\n retrieval_sources?: unknown\n keyword_reason_codes?: unknown\n canonical_path_key?: unknown\n canonical_primary_path?: unknown\n matched_capabilities?: unknown\n }\n }\n const entry = candidate.entry\n if (typeof entry !== 'object' || entry === null\n || boundedText(entry.entry_id, 100) === undefined\n || boundedText(entry.identity?.name, 214) === undefined\n || entry.imported_content?.trust !== 'untrusted_text'\n || entry.resolution?.status !== 'source_only'\n || !Array.isArray(entry.sources)) return null\n const sources = entry.sources.flatMap((source): Array<{ kind: 'npm'; package: string } | { kind: 'github'; owner: string; repo: string; ref?: string }> => {\n if (typeof source !== 'object' || source === null || Array.isArray(source)) return []\n const item = source as { kind?: unknown; package_name?: unknown; repository?: unknown; spec?: unknown; exact?: unknown }\n if (item.exact !== false) return []\n if (item.kind === 'npm' && typeof item.package_name === 'string' && NPM_NAME.test(item.package_name)) {\n return [{ kind: 'npm', package: item.package_name }]\n }\n if (item.kind !== 'github' || typeof item.repository !== 'string' || typeof item.spec !== 'string') return []\n const [owner, repo, ...extra] = item.repository.split('/')\n if (owner === undefined || repo === undefined || extra.length > 0 || !isGithubPart(owner) || !isGithubPart(repo)) return []\n const prefix = `github:${item.repository}`\n if (!item.spec.startsWith(prefix)) return []\n const suffix = item.spec.slice(prefix.length)\n if (suffix !== '' && !suffix.startsWith('#')) return []\n return [{ kind: 'github', owner, repo, ...(suffix === '' ? {} : { ref: suffix.slice(1) }) }]\n })\n if (sources.length === 0) return null\n const zh = boundedText(entry.imported_content?.description?.['zh-CN'])\n const en = boundedText(entry.imported_content?.description?.en)\n const repository = boundedText(entry.identity?.repository_url, 500)\n const reasonCodes = safeCodes(candidate.match?.reason_codes ?? candidate.match?.keyword_reason_codes, 8)\n const retrievalSources = safeCodes(candidate.match?.retrieval_sources, 8)\n const canonicalPathKey = boundedText(candidate.match?.canonical_path_key, 500)\n const canonicalPath = safePath(candidate.match?.canonical_primary_path, metadata.locale)\n const matchedCapabilities = safeCodes(candidate.match?.matched_capabilities, 8)\n const exactIdentifier = reasonCodes.includes('exact_identifier')\n const score = typeof candidate.match?.score === 'number' && Number.isFinite(candidate.match.score) && candidate.match.score >= 0\n ? candidate.match.score\n : undefined\n return {\n id: `registry:${entry.entry_id}`,\n title: entry.identity!.name as string,\n ...(zh !== undefined || en !== undefined ? { description: zh ?? en } : {}),\n ...(repository === undefined ? {} : { homepage: repository, repository }),\n sources,\n ...(score === undefined ? {} : { score }),\n evidence: [\n `DSH Registry source snapshot: ${metadata.snapshotId}`,\n ...(metadata.directoryVersion === undefined ? [] : [`DSH Registry directory version: ${metadata.directoryVersion}`]),\n ...(canonicalPath.length === 0 ? [] : [`Semantic directory: ${canonicalPath.join(' / ')}`]),\n ...(matchedCapabilities.length === 0 ? [] : [`Matched capabilities: ${matchedCapabilities.join(', ')}`]),\n 'Registry discovery record only; compatibility and security not tested',\n ...reasonCodes.map(code => `Registry match: ${code}`),\n ],\n match: {\n kind: 'registry',\n strategy: metadata.strategy,\n snapshotId: metadata.snapshotId,\n ...(metadata.directoryVersion === undefined ? {} : { directoryVersion: metadata.directoryVersion }),\n retrievalSources,\n keywordReasonCodes: reasonCodes,\n ...(canonicalPathKey === undefined ? {} : { canonicalPathKey }),\n canonicalPath,\n matchedCapabilities,\n exactIdentifier,\n },\n }\n}\n\ninterface ParsedRegistryResponse {\n metadata: RegistryResponseMetadata\n candidates: Awaited<ReturnType<PluginSearchProvider['search']>>\n}\n\nasync function parseRegistryResponse(\n response: Response,\n strategy: RegistryResponseMetadata['strategy'],\n locale: RegistryResponseMetadata['locale'],\n): Promise<ParsedRegistryResponse> {\n if (!response.ok) throw new Error(`DSH Registry ${strategy === 'keyword' ? 'search' : 'directory route'} returned HTTP ${response.status}`)\n const data = await response.json() as {\n snapshot_id?: unknown\n directory_version?: unknown\n candidates?: unknown\n is_final_recommendation?: unknown\n grants_install_approval?: unknown\n }\n const directoryVersion = strategy === 'keyword-plus-semantic-directory-v1'\n && typeof data.directory_version === 'string'\n && REGISTRY_DIRECTORY_VERSION.test(data.directory_version)\n ? data.directory_version\n : undefined\n if (typeof data.snapshot_id !== 'string' || !REGISTRY_SNAPSHOT_ID.test(data.snapshot_id)\n || !Array.isArray(data.candidates)\n || data.is_final_recommendation === true\n || data.grants_install_approval === true\n || (strategy === 'keyword-plus-semantic-directory-v1' && directoryVersion === undefined)) {\n throw new Error('DSH Registry search returned an invalid discovery response.')\n }\n const metadata: RegistryResponseMetadata = {\n snapshotId: data.snapshot_id,\n strategy,\n locale,\n ...(directoryVersion === undefined ? {} : { directoryVersion }),\n }\n return {\n metadata,\n candidates: data.candidates.flatMap(candidate => {\n const normalized = registryCandidate(candidate, metadata)\n return normalized === null ? [] : [normalized]\n }),\n }\n}\n\nconst IDENTITY_STOP_TERMS = new Set([\n 'and', 'dsh', 'for', 'from', 'inside', 'into', 'plugin', 'plugins', 'the', 'use', 'using', 'with',\n])\n\nfunction identityTermCoverage(searchText: string, candidate: Awaited<ReturnType<PluginSearchProvider['search']>>[number]): number {\n const terms = [...new Set(searchText.toLowerCase().match(/[a-z0-9@]+/gu) ?? [])]\n .filter(term => term.length >= 3 && !IDENTITY_STOP_TERMS.has(term))\n if (terms.length === 0) return 0\n const identityTerms = new Set(`${candidate.title} ${candidate.repository ?? ''}`.toLowerCase().split(/[^a-z0-9@]+/gu).filter(Boolean))\n return terms.filter(term => identityTerms.has(term)).length / terms.length\n}\n\nfunction mergeRegistryRankings(\n searchText: string,\n keyword: ParsedRegistryResponse | null,\n directory: ParsedRegistryResponse | null,\n limit: number,\n): Awaited<ReturnType<PluginSearchProvider['search']>> {\n type Ranked = { candidate: Awaited<ReturnType<PluginSearchProvider['search']>>[number]; score: number; keywordRank?: number; directoryRank?: number }\n const combined = new Map<string, Ranked>()\n for (const [source, response, weight] of [\n ['keyword', keyword, KEYWORD_RANK_WEIGHT],\n ['directory', directory, DIRECTORY_RANK_WEIGHT],\n ] as const) {\n if (response === null) continue\n response.candidates.forEach((candidate, index) => {\n // When keyword search is healthy, the directory may rerank its bounded\n // candidate pool but cannot flood the page with loosely related siblings.\n if (source === 'directory' && keyword !== null && !combined.has(candidate.id)) return\n const current = combined.get(candidate.id) ?? { candidate, score: 0 }\n current.score += weight / (RECIPROCAL_RANK_OFFSET + index + 1)\n if (source === 'keyword') current.keywordRank = index + 1\n else {\n current.directoryRank = index + 1\n current.candidate = candidate\n }\n combined.set(candidate.id, current)\n })\n }\n return [...combined.values()].map(item => {\n const keywordMatch = keyword?.candidates.find(candidate => candidate.id === item.candidate.id)?.match\n const directoryMatch = directory?.candidates.find(candidate => candidate.id === item.candidate.id)?.match\n const exactIdentifier = (keywordMatch?.kind === 'registry' && keywordMatch.exactIdentifier)\n || (directoryMatch?.kind === 'registry' && directoryMatch.exactIdentifier)\n const registryMatch = directoryMatch?.kind === 'registry'\n ? directoryMatch\n : keywordMatch?.kind === 'registry' ? keywordMatch : null\n const score = item.score\n + IDENTITY_TERM_BOOST * identityTermCoverage(searchText, item.candidate)\n + (exactIdentifier ? 1 : 0)\n return {\n ...item.candidate,\n score,\n ...(registryMatch === null ? {} : {\n match: {\n ...registryMatch,\n strategy: directory === null ? 'keyword' as const : 'keyword-plus-semantic-directory-v1' as const,\n keywordReasonCodes: keywordMatch?.kind === 'registry' ? keywordMatch.keywordReasonCodes : registryMatch.keywordReasonCodes,\n exactIdentifier,\n },\n }),\n evidence: [\n ...item.candidate.evidence ?? [],\n `Registry rank fusion: keyword=${String(item.keywordRank ?? 'none')}, directory=${String(item.directoryRank ?? 'none')}`,\n ],\n }\n }).sort((left, right) => (right.score ?? 0) - (left.score ?? 0) || left.id.localeCompare(right.id)).slice(0, limit)\n}\n\nexport interface RegistrySearchProviderOptions {\n strategy?: 'keyword' | 'hybrid'\n}\n\nexport function registrySearchProvider(\n baseUrl: string,\n fetchImpl: typeof globalThis.fetch = globalThis.fetch,\n options: RegistrySearchProviderOptions = {},\n): PluginSearchProvider {\n const keywordEndpoint = registryEndpoint(baseUrl, 'search')\n const directoryEndpoint = registryEndpoint(baseUrl, 'route')\n const strategy = options.strategy ?? 'hybrid'\n return {\n id: 'dsh-registry',\n async search(request) {\n const text = query(request.query)\n const locale = queryLocale(text)\n const outputLimit = Math.min(request.maxResults, MAX_PROVIDER_RESULTS)\n const requestEndpoint = async (endpoint: string, responseStrategy: RegistryResponseMetadata['strategy'], limit: number) => parseRegistryResponse(await fetchImpl(endpoint, {\n method: 'POST',\n signal: request.signal,\n headers: { accept: 'application/json', 'content-type': 'application/json' },\n body: JSON.stringify({ schema_version: '1.0.0', query: text, locale, limit }),\n }), responseStrategy, locale)\n if (strategy === 'keyword') {\n return (await requestEndpoint(keywordEndpoint, 'keyword', outputLimit)).candidates.slice(0, outputLimit)\n }\n const [keywordResult, directoryResult] = await Promise.allSettled([\n requestEndpoint(keywordEndpoint, 'keyword', REGISTRY_KEYWORD_CHALLENGER_POOL),\n requestEndpoint(directoryEndpoint, 'keyword-plus-semantic-directory-v1', REGISTRY_DIRECTORY_POOL),\n ])\n const keyword = keywordResult.status === 'fulfilled' ? keywordResult.value : null\n const directory = directoryResult.status === 'fulfilled' ? directoryResult.value : null\n if (keyword === null && directory === null) {\n const reasons = [keywordResult, directoryResult].map(result => result.status === 'rejected'\n ? result.reason instanceof Error ? result.reason.message : String(result.reason)\n : '').filter(Boolean)\n throw new Error(`DSH Registry search failed: ${reasons.join('; ')}`)\n }\n if (keyword !== null && directory !== null && keyword.metadata.snapshotId !== directory.metadata.snapshotId) {\n throw new Error('DSH Registry keyword and directory responses reference different snapshots.')\n }\n return mergeRegistryRankings(text, keyword, directory, outputLimit)\n },\n }\n}\n","import { spawn } from 'node:child_process'\nimport { join } from 'node:path'\nimport { tmpdir } from 'node:os'\nimport { writeFileSync } from 'node:fs'\nimport { fail } from './errors.ts'\n\nexport function detectedSupervisor(env: NodeJS.ProcessEnv = process.env, ppid = process.ppid): string | null {\n const systemd = (env.INVOCATION_ID ?? '') !== '' || (env.JOURNAL_STREAM ?? '') !== ''\n return systemd && ppid === 1 ? 'systemd' : null\n}\n\nexport function restartAllowed(\n allowRestart: boolean | undefined,\n env: NodeJS.ProcessEnv = process.env,\n ppid = process.ppid,\n): boolean {\n if (allowRestart !== undefined) return allowRestart\n return detectedSupervisor(env, ppid) === null\n}\n\nexport interface RestarterOptions {\n allowRestart?: boolean\n env?: NodeJS.ProcessEnv\n argv?: string[]\n execPath?: string\n cwd?: string\n ppid?: number\n spawn?: typeof spawn\n terminate?: () => void\n}\n\nexport class DshRestarter {\n private readonly options: RestarterOptions\n\n constructor(options: RestarterOptions = {}) {\n this.options = options\n }\n\n available(): boolean {\n return restartAllowed(this.options.allowRestart, this.options.env, this.options.ppid)\n }\n\n schedule(): { helperPid: number | undefined; logFile: string } {\n if (!this.available()) fail('RESTART_UNAVAILABLE', 'Automatic restart is disabled or owned by the process supervisor.')\n const argv = this.options.argv ?? process.argv\n if (argv[1] === undefined) fail('RESTART_UNAVAILABLE', 'The current DSH entry point cannot be identified.')\n const execPath = this.options.execPath ?? process.execPath\n const cwd = this.options.cwd ?? process.cwd()\n const env = this.options.env ?? process.env\n const logFile = join(tmpdir(), `relay-dsh-plugin-manager-restart-${Date.now()}.log`)\n const source = [\n \"const { spawn } = require('node:child_process')\",\n \"const fs = require('node:fs')\",\n 'setTimeout(() => {',\n ` const out = fs.openSync(${JSON.stringify(logFile)}, 'a')`,\n ` const child = spawn(${JSON.stringify(execPath)}, ${JSON.stringify(argv.slice(1))}, {`,\n ` cwd: ${JSON.stringify(cwd)}, env: process.env, detached: true, stdio: ['ignore', out, out]`,\n ' })',\n \" child.on('error', error => fs.appendFileSync(\" + JSON.stringify(logFile) + \", String(error) + '\\\\n'))\",\n ' child.unref()',\n '}, 1200)',\n ].join('\\n')\n writeFileSync(logFile, '', { flag: 'a', mode: 0o600 })\n const helper = (this.options.spawn ?? spawn)(execPath, ['-e', source], {\n detached: true,\n stdio: 'ignore',\n env,\n })\n helper.unref()\n setTimeout(this.options.terminate ?? (() => process.kill(process.pid, 'SIGTERM')), 500).unref()\n return { helperPid: helper.pid, logFile }\n }\n}\n","import { spawn, type ChildProcess } from 'node:child_process'\nimport { existsSync, realpathSync } from 'node:fs'\n\nexport interface DshLaunch {\n file: string\n prefix: string[]\n cwd: string\n shell: boolean\n}\n\nexport interface RunnerResult {\n exitCode: number\n signal: NodeJS.Signals | null\n stdout: string\n stderr: string\n cancelled: boolean\n timedOut: boolean\n}\n\nexport interface RunnerOptions {\n env?: NodeJS.ProcessEnv\n argv?: string[]\n execPath?: string\n cwd?: string\n platform?: NodeJS.Platform\n spawn?: typeof spawn\n timeoutMs?: number\n maxOutputBytes?: number\n}\n\nexport function resolveDshLaunch(options: RunnerOptions = {}): DshLaunch {\n const env = options.env ?? process.env\n const argv = options.argv ?? process.argv\n const execPath = options.execPath ?? process.execPath\n const cwd = options.cwd ?? process.cwd()\n const platform = options.platform ?? process.platform\n const configured = env.DSH_EXECUTABLE?.trim()\n let file: string\n let prefix: string[]\n if (configured !== undefined && configured !== '') {\n file = configured\n prefix = []\n } else if (argv[1] !== undefined && existsSync(argv[1])) {\n file = execPath\n prefix = [realpathSync(argv[1])]\n } else {\n file = 'dsh'\n prefix = []\n }\n return {\n file,\n prefix,\n cwd,\n shell: platform === 'win32' && /\\.(?:cmd|bat)$/iu.test(file),\n }\n}\n\nfunction boundedAppend(current: string, chunk: Buffer | string, maxBytes: number): string {\n const combined = current + chunk.toString()\n return Buffer.byteLength(combined) <= maxBytes ? combined : combined.slice(-maxBytes)\n}\n\nexport class DshCliRunner {\n private readonly options: RunnerOptions\n\n constructor(options: RunnerOptions = {}) {\n this.options = options\n }\n\n runPlugin(\n profile: string,\n args: readonly string[],\n signal: AbortSignal,\n progress: (message: string) => void = () => undefined,\n ): Promise<RunnerResult> {\n const launch = resolveDshLaunch(this.options)\n const spawnImpl = this.options.spawn ?? spawn\n const timeoutMs = this.options.timeoutMs ?? 5 * 60_000\n const maxOutput = this.options.maxOutputBytes ?? 64 * 1024\n return new Promise((resolve, reject) => {\n let child: ChildProcess\n try {\n child = spawnImpl(\n launch.file,\n [...launch.prefix, 'plugin', '--profile', profile, ...args],\n {\n cwd: launch.cwd,\n env: this.options.env ?? process.env,\n shell: launch.shell,\n stdio: ['ignore', 'pipe', 'pipe'],\n },\n )\n } catch (error) {\n reject(error)\n return\n }\n let stdout = ''\n let stderr = ''\n let timedOut = false\n let cancelled = false\n let settled = false\n const terminate = (reason: 'timeout' | 'cancel'): void => {\n if (reason === 'timeout') timedOut = true\n else cancelled = true\n child.kill('SIGTERM')\n setTimeout(() => { if (!settled) child.kill('SIGKILL') }, 2_000).unref()\n }\n const timer = setTimeout(() => terminate('timeout'), timeoutMs)\n const onAbort = (): void => terminate('cancel')\n if (signal.aborted) onAbort()\n else signal.addEventListener('abort', onAbort, { once: true })\n child.stdout?.on('data', (chunk: Buffer) => {\n stdout = boundedAppend(stdout, chunk, maxOutput)\n progress(chunk.toString().trim().slice(-500))\n })\n child.stderr?.on('data', (chunk: Buffer) => {\n stderr = boundedAppend(stderr, chunk, maxOutput)\n progress(chunk.toString().trim().slice(-500))\n })\n child.once('error', (error) => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n settled = true\n reject(error)\n })\n child.once('close', (code, closeSignal) => {\n clearTimeout(timer)\n signal.removeEventListener('abort', onAbort)\n settled = true\n resolve({\n exitCode: code ?? 1,\n signal: closeSignal,\n stdout,\n stderr,\n cancelled,\n timedOut,\n })\n })\n })\n }\n}\n","import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { randomUUID } from 'node:crypto'\n\nconst DEFAULT_ENDPOINT = 'https://dsh-plugins.tech/v1/telemetry/events'\nconst STATE_DIRECTORY = '.relay-plugin-manager'\nconst STATE_FILE = 'telemetry.json'\nconst SCHEMA_VERSION = '1.1.0'\nconst EVENTS = new Set([\n 'plugin_manager_used',\n 'plugin_install_started',\n 'plugin_install_succeeded',\n 'plugin_install_failed',\n])\n\nexport type TelemetryProperty = string | number | boolean\n\nexport interface Telemetry {\n capture(event: string, properties?: Readonly<Record<string, TelemetryProperty>>): void\n}\n\nexport interface TelemetryConfig {\n /** Anonymous operational telemetry is enabled unless this is explicitly false. */\n enabled?: boolean\n /** Registry telemetry endpoint. Only the canonical service or localhost is accepted. */\n endpoint?: string\n /** Marks an operator-controlled acceptance run so analytics can exclude it. */\n test?: boolean\n}\n\ninterface TelemetryRuntime {\n fetch: typeof fetch\n random(): string\n}\n\nconst noopTelemetry: Telemetry = Object.freeze({ capture() {} })\n\nfunction safeEndpoint(value: string | undefined): string | null {\n try {\n const parsed = new URL(value ?? DEFAULT_ENDPOINT)\n const local = ['localhost', '127.0.0.1', '::1'].includes(parsed.hostname)\n const canonical = parsed.protocol === 'https:' && parsed.hostname === 'dsh-plugins.tech'\n if ((!local && !canonical) || (local && !['http:', 'https:'].includes(parsed.protocol))) return null\n if (parsed.username !== '' || parsed.password !== '' || parsed.pathname !== '/v1/telemetry/events'\n || parsed.search !== '' || parsed.hash !== '') return null\n return parsed.href\n } catch {\n return null\n }\n}\n\nfunction anonymousId(profileDir: string, random: () => string): string {\n const directory = join(profileDir, STATE_DIRECTORY)\n const path = join(directory, STATE_FILE)\n try {\n const existing = JSON.parse(readFileSync(path, 'utf8')) as { anonymousId?: unknown }\n if (typeof existing.anonymousId === 'string' && /^[0-9a-f-]{36}$/iu.test(existing.anonymousId)) {\n return existing.anonymousId\n }\n } catch {\n // A missing or damaged local state file is replaced below.\n }\n const id = random()\n try {\n mkdirSync(directory, { recursive: true, mode: 0o700 })\n writeFileSync(path, `${JSON.stringify({ anonymousId: id })}\\n`, { mode: 0o600 })\n } catch {\n // Telemetry must never block plugin management; the process-scoped id still works.\n }\n return id\n}\n\nfunction allowedProperties(event: string, properties: Readonly<Record<string, TelemetryProperty>>): boolean {\n const keys = new Set(Object.keys(properties))\n const exact = (required: readonly string[], optional: readonly string[] = []): boolean => {\n if (required.some(key => !keys.has(key))) return false\n return [...keys].every(key => required.includes(key) || optional.includes(key))\n }\n if (event === 'plugin_manager_used') {\n if (!exact(['surface', 'action'], ['has_query', 'query_length_bucket', 'batch_size'])) return false\n if (!['discover', 'plan'].includes(String(properties.surface))) return false\n return typeof properties.action === 'string'\n }\n if (event === 'plugin_install_started') return exact(['plugin_name'], ['batch'])\n if (event === 'plugin_install_succeeded') return exact(['plugin_name', 'activated', 'restart_required'], ['batch'])\n if (event === 'plugin_install_failed') return exact(['plugin_name', 'error_code'], ['batch'])\n return false\n}\n\nexport function createTelemetry(\n profileDir: string,\n config: TelemetryConfig | undefined,\n runtime: TelemetryRuntime = { fetch, random: randomUUID },\n): Telemetry {\n if (config?.enabled === false) return noopTelemetry\n const endpoint = safeEndpoint(config?.endpoint)\n if (endpoint === null) return noopTelemetry\n let distinctId: string | undefined\n\n return Object.freeze({\n capture(event: string, properties: Readonly<Record<string, TelemetryProperty>> = {}): void {\n if (!EVENTS.has(event) || !allowedProperties(event, properties)) return\n distinctId ??= anonymousId(profileDir, runtime.random)\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), 5_000)\n timeout.unref?.()\n try {\n void runtime.fetch(endpoint, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n schema_version: SCHEMA_VERSION,\n anonymous_id: distinctId,\n event,\n properties,\n ...(config?.test === true ? { is_test: true } : {}),\n }),\n signal: controller.signal,\n }).catch(() => undefined).finally(() => clearTimeout(timeout))\n } catch {\n clearTimeout(timeout)\n }\n },\n })\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport '@deepseek-ai/cordis-plugin-loader'\nimport '@deepseek-ai/dsh-user-questions'\nimport { registerConversationSurface } from './conversation.ts'\nimport { HotRuntime } from './hot-runtime.ts'\nimport { PluginManager } from './manager.ts'\nimport { profileDirectory } from './profile.ts'\nimport { githubSearchProvider, npmSearchProvider, registrySearchProvider } from './providers.ts'\nimport { DshRestarter } from './restart.ts'\nimport { DshCliRunner } from './runner.ts'\nimport { createTelemetry, type TelemetryConfig } from './telemetry.ts'\n\nexport const name = 'relay-dsh-plugin-manager'\nexport const inject = ['pluginSearch', 'tools', 'commands', 'userQuestions', 'loader']\nexport const DEFAULT_REGISTRY_ORIGIN = 'https://dsh-plugins.tech'\n\nexport interface Config {\n allowRestart?: boolean\n registryUrl?: string | false\n telemetry?: TelemetryConfig\n}\n\nexport function apply(ctx: Context, config: Config = {}): void {\n const profileDir = profileDirectory('web')\n const telemetry = config.telemetry ?? {\n enabled: process.env.RELAY_PLUGIN_MANAGER_TELEMETRY !== '0',\n endpoint: process.env.RELAY_PLUGIN_MANAGER_TELEMETRY_ENDPOINT,\n test: process.env.RELAY_PLUGIN_MANAGER_TELEMETRY_TEST === '1',\n }\n ctx.pluginSearch.register(npmSearchProvider())\n ctx.pluginSearch.register(githubSearchProvider())\n const configuredRegistryUrl = config.registryUrl ?? process.env.DSH_PLUGIN_REGISTRY_URL?.trim()\n const registryUrl = config.registryUrl === false ? undefined : configuredRegistryUrl || DEFAULT_REGISTRY_ORIGIN\n if (registryUrl !== undefined) ctx.pluginSearch.register(registrySearchProvider(registryUrl))\n\n const manager = new PluginManager({\n profileDir,\n searchRuntime: ctx.pluginSearch,\n runner: new DshCliRunner(),\n hot: new HotRuntime(ctx, profileDir),\n restarter: new DshRestarter({ allowRestart: config.allowRestart }),\n loader: ctx.loader,\n telemetry: createTelemetry(profileDir, telemetry),\n })\n registerConversationSurface(ctx, manager)\n}\n\nexport { PluginManager } from './manager.ts'\nexport type {\n DiscoverRequest,\n InstallManyItemResult,\n InstallManyItemStatus,\n InstallManyResult,\n MutationResult,\n PlanRequest,\n} from './manager.ts'\nexport type {\n PluginSearchCandidate,\n PluginSearchMatch,\n PluginSearchProvider,\n PluginSearchRequest,\n} from './search-runtime.ts'\nexport type { PluginInspection, PluginSource } from './source.ts'\nexport type { TelemetryConfig } from './telemetry.ts'\nexport type {\n TaskAmbiguityInput,\n TaskRoleInput,\n TaskRoleSelection,\n TaskSolutionAssessment,\n TaskSolutionDraft,\n} from './task-solutions.ts'\n"],"mappings":";;;;;;;;;;;;;AAWA,SAAS,UAAU,OAA2B;CAC5C,OAAO,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AACzC;AAEA,SAAS,WAAW,OAAgB,OAAyD;CAC3F,OAAO,CAAC;EAAE,MAAM;EAAQ,MAAM,KAAK,UAAU,OAAO,MAAM,CAAC;CAAE,CAAC;AAChE;AASA,MAAM,gBAAgB;AACtB,MAAM,gBAAgB;AAEtB,SAAS,cAAc,SAA+D;CACpF,MAAM,WAAW,QAAQ,IAAI,SAAS,gBAAgB;CACtD,IAAI,OAAO,aAAa,YACtB,OAAO,QAAQ,MAAM,UAAU,SAAS,CAAC,CAAC;CAE5C,MAAM,SAAS,QAAQ,IAAI,SAAS,QAAQ;CAC5C,IAAI,CAAC,MAAM,QAAQ,MAAM,GAAG,MAAM,IAAI,UAAU,yDAAyD;CACzG,OAAO;AACT;AAEA,SAAS,mBACP,WACiE;CACjE,MAAM,UAAU,UAAU,OAAO;CACjC,IAAI,YAAY,KAAA,GAAW,OAAO;CAClC,IAAI,iBAAiB;CACrB,KAAK,MAAM,SAAS,cAAc,OAAO,GAAG,IAAI,MAAM,SAAS,gBAAgB,iBAAiB,MAAM;CACtG,OAAO;EAAE,WAAW,OAAO,QAAQ,EAAE;EAAG;CAAe;AACzD;AAEA,SAAS,WAAW,MAAgC;CAClD,MAAM,QAAQ;EACZ,cAAc,KAAK;EACnB,YAAY,KAAK;EACjB,WAAW,KAAK;EAChB,qBAAqB,KAAK,kBAAkB,QAAQ;CACtD;CACA,IAAI,KAAK,WAAW,gBAAgB;EAClC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