relay-dsh-plugin-manager 0.2.2 → 0.2.3
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/CHANGELOG.md +20 -0
- package/README.md +17 -4
- package/README.zh.md +15 -4
- package/SPEC.md +7 -0
- package/docs/acceptance/live-registry-2026-09-04.md +28 -0
- package/docs/acceptance.md +1 -0
- package/lib/index.d.ts +3 -1
- package/lib/index.js +105 -1
- package/lib/index.js.map +1 -1
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,25 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project are documented here.
|
|
4
4
|
|
|
5
|
+
## [0.2.3] - 2026-09-04
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- Enable the read-only DSH Plugin Registry at `https://dsh-plugins.tech` by
|
|
10
|
+
default, with explicit opt-out and HTTPS-only override support.
|
|
11
|
+
- Search more than 3,000 source records using Chinese task text, English task
|
|
12
|
+
text or plugin names, while treating Registry descriptions as untrusted
|
|
13
|
+
source-only facts.
|
|
14
|
+
- Resolve every Registry candidate again through the manager's existing local
|
|
15
|
+
npm/GitHub inspection before presenting an immutable install source.
|
|
16
|
+
- Add reproducible live Registry acceptance without reading a Profile or
|
|
17
|
+
performing any plugin mutation.
|
|
18
|
+
|
|
19
|
+
### Compatibility
|
|
20
|
+
|
|
21
|
+
- Retain the verified DSH `0.1.2-rc.1`, `0.1.2-alpha.3` and legacy
|
|
22
|
+
`0.1.1-rc.2` compatibility ranges from `0.2.3-rc.1`.
|
|
23
|
+
|
|
5
24
|
## [0.2.1] - 2026-09-01
|
|
6
25
|
|
|
7
26
|
### Compatibility
|
|
@@ -101,3 +120,4 @@ All notable changes to this project are documented here.
|
|
|
101
120
|
[0.1.0-rc.4]: https://github.com/yangbobo2021/relay-dsh-plugin-manager/compare/v0.1.0-rc.3...v0.1.0-rc.4
|
|
102
121
|
[0.1.0]: https://github.com/yangbobo2021/relay-dsh-plugin-manager/compare/v0.1.0-rc.4...v0.1.0
|
|
103
122
|
[0.1.1]: https://github.com/yangbobo2021/relay-dsh-plugin-manager/compare/v0.1.0...v0.1.1
|
|
123
|
+
[0.2.3]: https://github.com/yangbobo2021/relay-dsh-plugin-manager/compare/v0.2.2...v0.2.3
|
package/README.md
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
# Manage DeepSeek Harness Plugins from Chat
|
|
2
2
|
|
|
3
|
-
> **Now supports DSH `0.1.2-rc.1` while retaining `0.1.2-alpha.3` compatibility.**
|
|
3
|
+
> **Now supports DSH `0.1.2-rc.1` while retaining `0.1.2-alpha.3` compatibility.** Stable `0.2.3` adds the default evidence-backed DSH Registry search provider. [Install it from npm](https://www.npmjs.com/package/relay-dsh-plugin-manager) · [Compatibility evidence](https://github.com/yangbobo2021/Relay/tree/codex/relay-foundation/dsh-lab/dsh-0.1.2-rc.1-20260903).
|
|
4
4
|
|
|
5
|
-
> **Release
|
|
5
|
+
> **Release channel:** `latest` → `0.2.3`.
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
npx @deepseek-ai/dsh@0.1.2-rc.1 plugin --profile web add relay-dsh-plugin-manager@0.2.
|
|
8
|
+
npx @deepseek-ai/dsh@0.1.2-rc.1 plugin --profile web add relay-dsh-plugin-manager@0.2.3
|
|
9
9
|
npx @deepseek-ai/dsh@0.1.2-rc.1 web
|
|
10
10
|
```
|
|
11
11
|
|
|
@@ -14,7 +14,7 @@ npx @deepseek-ai/dsh@0.1.2-rc.1 web
|
|
|
14
14
|
[](https://www.npmjs.com/package/relay-dsh-plugin-manager)
|
|
15
15
|
[](https://github.com/yangbobo2021/relay-dsh-plugin-manager/stargazers)
|
|
16
16
|
[](LICENSE)
|
|
17
|
-
[](https://github.com/deepseek-ai/deepseek-harness)
|
|
18
18
|
[](.github/workflows/release.yml)
|
|
19
19
|
|
|
20
20
|
English | [中文](README.zh.md)
|
|
@@ -100,6 +100,19 @@ missing companion peers, waits for one confirmation, and runs the installs in
|
|
|
100
100
|
sequence. Completed changes that still need restart are reported explicitly as
|
|
101
101
|
restart-required or waiting for a manual restart.
|
|
102
102
|
|
|
103
|
+
### DSH Registry discovery provider
|
|
104
|
+
|
|
105
|
+
The source-only Registry search provider uses `https://dsh-plugins.tech` by
|
|
106
|
+
default. Set plugin option `registryUrl` or environment variable
|
|
107
|
+
`DSH_PLUGIN_REGISTRY_URL` to override the Registry origin (for example, a local
|
|
108
|
+
preview at `http://127.0.0.1:4174`). Non-local URLs must use HTTPS. Set
|
|
109
|
+
`registryUrl: false` to disable Registry discovery explicitly.
|
|
110
|
+
|
|
111
|
+
This provider sends only the task query, inferred Chinese/English locale, and
|
|
112
|
+
result limit. Returned candidates are
|
|
113
|
+
always inspected locally through the same npm/GitHub flow before any plan can be
|
|
114
|
+
created; Registry descriptions are untrusted text and cannot authorize changes.
|
|
115
|
+
|
|
103
116
|
## Part of Relay
|
|
104
117
|
|
|
105
118
|
This plugin is developed in the
|
package/README.zh.md
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
# 在 DeepSeek Harness 对话中管理插件
|
|
2
2
|
|
|
3
|
-
> **现已支持 DSH `0.1.2-rc.1`,并保留对 `0.1.2-alpha.3` 的兼容。**
|
|
3
|
+
> **现已支持 DSH `0.1.2-rc.1`,并保留对 `0.1.2-alpha.3` 的兼容。** 稳定版 `0.2.3` 默认接入了有证据边界的 DSH Registry 搜索。[从 npm 安装](https://www.npmjs.com/package/relay-dsh-plugin-manager) · [兼容性证据](https://github.com/yangbobo2021/Relay/tree/codex/relay-foundation/dsh-lab/dsh-0.1.2-rc.1-20260903)。
|
|
4
4
|
|
|
5
|
-
> **发布通道:** `latest` → `0.2.
|
|
5
|
+
> **发布通道:** `latest` → `0.2.3`。
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
npx @deepseek-ai/dsh@0.1.2-rc.1 plugin --profile web add relay-dsh-plugin-manager@0.2.
|
|
8
|
+
npx @deepseek-ai/dsh@0.1.2-rc.1 plugin --profile web add relay-dsh-plugin-manager@0.2.3
|
|
9
9
|
npx @deepseek-ai/dsh@0.1.2-rc.1 web
|
|
10
10
|
```
|
|
11
11
|
|
|
@@ -14,7 +14,7 @@ npx @deepseek-ai/dsh@0.1.2-rc.1 web
|
|
|
14
14
|
[](https://www.npmjs.com/package/relay-dsh-plugin-manager)
|
|
15
15
|
[](https://github.com/yangbobo2021/relay-dsh-plugin-manager/stargazers)
|
|
16
16
|
[](LICENSE)
|
|
17
|
-
[](https://github.com/deepseek-ai/deepseek-harness)
|
|
18
18
|
[](.github/workflows/release.yml)
|
|
19
19
|
|
|
20
20
|
[English](README.md) | 中文
|
|
@@ -95,6 +95,17 @@ dsh web
|
|
|
95
95
|
一次确认后依次安装。修改完成但仍需重启时,状态会明确区分“需要另行重启”和
|
|
96
96
|
“等待人工重启”。
|
|
97
97
|
|
|
98
|
+
### DSH Registry 发现数据源
|
|
99
|
+
|
|
100
|
+
来源级 Registry 搜索 provider 默认使用 `https://dsh-plugins.tech`。可设置插件
|
|
101
|
+
配置 `registryUrl`,或环境变量 `DSH_PLUGIN_REGISTRY_URL` 覆盖 Registry 根地址
|
|
102
|
+
(本地预览示例:`http://127.0.0.1:4174`);非本机地址必须使用 HTTPS。设置
|
|
103
|
+
`registryUrl: false` 可显式关闭 Registry 发现。
|
|
104
|
+
|
|
105
|
+
该 provider 只发送任务查询、推断出的中英文语言和结果数量。返回候选仍必须进入同一套本地 npm/GitHub
|
|
106
|
+
检查流程,完成检查后才能生成计划;Registry 描述属于不可信文本,不能授权任何
|
|
107
|
+
变更。
|
|
108
|
+
|
|
98
109
|
## 与 Relay 的关系
|
|
99
110
|
|
|
100
111
|
本插件在 [Relay](https://github.com/yangbobo2021/Relay) 的 integration 工作区中
|
package/SPEC.md
CHANGED
|
@@ -49,6 +49,7 @@ service.
|
|
|
49
49
|
| PM-022 | Preserve required manifest peer-dependency metadata during source inspection while respecting `peerDependenciesMeta.optional`. A multi-install plan reports required peers absent from both the current profile and the requested set, deduplicated with their ranges, dependents, and suggested npm source. Planning never silently adds an unrequested companion plugin. |
|
|
50
50
|
| PM-023 | `plugin_manage confirm` owns its DSH question: it validates the token, expiry, and exact Session before asking; supplies a stable plan-specific id, visible plan detail, exact approve/decline options, and `plan-review` intent; and executes in that same tool call only for the exact single approve answer. Declines, malformed or unrelated answers, provider failure/cancellation, and cross-session attempts do not execute or consume a still-valid plan. Generic model-authored question results are never mutation authority. |
|
|
51
51
|
| PM-024 | GitHub owner discovery recognizes `owner:<name>`, owner-only GitHub identities, `<name> DSH plugins`, and conservative bare identifiers containing digits. It sends a typed owner intent to providers, uses GitHub's exact owner qualifier, case-insensitively verifies returned ownership, and ranks verified owner matches first. Owner-only `inspect` fails with an actionable error directing callers to search. Every emitted repository identity is accepted by `inspect`; every recommended immutable source is accepted by `plan`. |
|
|
52
|
+
| PM-025 | Register a read-only DSH Registry provider against `https://dsh-plugins.tech` by default, with an explicit `registryUrl: false` opt-out and HTTPS-only configuration override. Send only the task query, inferred Chinese/English locale and result limit; accept only source-level untrusted DiscoveryEntry records, convert their npm/GitHub descriptors into core-owned source types, and submit them to the same mandatory local inspection used by all providers. Registry responses cannot supply exact versions, approval, plans, installers, or profile state, and provider failure remains isolated. |
|
|
52
53
|
|
|
53
54
|
## Command Grammar
|
|
54
55
|
|
|
@@ -93,6 +94,12 @@ confirmation, installation, rollback, activation, and restart.
|
|
|
93
94
|
Provider scores are not globally comparable. The manager uses them only within
|
|
94
95
|
one provider before deterministic cross-provider ordering.
|
|
95
96
|
|
|
97
|
+
The `dsh-registry` provider defaults to `https://dsh-plugins.tech`. Plugin
|
|
98
|
+
configuration `registryUrl` or environment variable `DSH_PLUGIN_REGISTRY_URL`
|
|
99
|
+
may override that origin for controlled deployment, while `registryUrl: false`
|
|
100
|
+
disables it explicitly. Non-local overrides require HTTPS. The provider transmits
|
|
101
|
+
no Profile, installed inventory, path, credential, or conversation transcript.
|
|
102
|
+
|
|
96
103
|
## Explicit Non-Goals
|
|
97
104
|
|
|
98
105
|
- Settings controls, dashboard, or any other second management workflow. The
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Live DSH Registry Acceptance — 2026-09-04
|
|
2
|
+
|
|
3
|
+
This record captures A-032 against the formal beta Registry and real public
|
|
4
|
+
npm/GitHub metadata. It does not install or mutate a DSH Profile.
|
|
5
|
+
|
|
6
|
+
## Inputs
|
|
7
|
+
|
|
8
|
+
- Registry origin: `https://dsh-plugins.tech`
|
|
9
|
+
- Registry release: `25e64a93599d255ba65ea63ee77b47b62a2e6cd8`
|
|
10
|
+
- Discovery snapshot: `discovery.awesome-dsh-plugin.2026-09-03.v1-0-2.5346e7049c20`
|
|
11
|
+
- Discovery entries: 3,019
|
|
12
|
+
- Command: `npm run acceptance:live:registry`
|
|
13
|
+
|
|
14
|
+
## Results
|
|
15
|
+
|
|
16
|
+
| Scenario | Result |
|
|
17
|
+
| --- | --- |
|
|
18
|
+
| Chinese task `管理插件` | Passed; five locally inspected candidates |
|
|
19
|
+
| English task `workspace files` | Passed; five locally inspected candidates |
|
|
20
|
+
| Exact name `dsh-plugin-manager` | Passed; four locally inspected candidates and one rejected malformed/non-plugin source |
|
|
21
|
+
| Deliberate missing name | Passed; honest empty result without provider failure |
|
|
22
|
+
| Registry authority | Passed; `source_only`, `untrusted_text`, `is_final_recommendation: false`, `grants_install_approval: false` |
|
|
23
|
+
| Local resolution | Passed; every surfaced candidate resolved to an exact npm SemVer or full GitHub commit before presentation |
|
|
24
|
+
|
|
25
|
+
The live run returned no Registry provider errors. Unit and host integration
|
|
26
|
+
tests separately prove request minimization, locale selection, endpoint
|
|
27
|
+
validation, explicit opt-out, malformed-response rejection, provider failure
|
|
28
|
+
isolation and mandatory local inspection.
|
package/docs/acceptance.md
CHANGED
|
@@ -37,6 +37,7 @@ This matrix is the release contract. Tests name the relevant `PM-*` ids.
|
|
|
37
37
|
| A-029 `github.com/owner/repo`, canonical HTTPS, and `github:owner/repo` inspect to the same immutable plugin; emitted repository identities round-trip into inspect and recommended sources round-trip into install planning | PM-007, PM-008, PM-024 | source unit + manager integration + opt-in live schemeless inspection |
|
|
38
38
|
| A-030 owner-only inspect forms return actionable search guidance while malformed, unsafe, and non-GitHub inputs remain rejected without weakening source validation | PM-018, PM-024 | source/manager negative unit |
|
|
39
39
|
| A-031 search results feed one immutable multi-install plan through the real DSH tool and user-question registries; no mutation starts before one exact UI approval, then child installs execute serially and approval replay is rejected | PM-002, PM-005, PM-009, PM-010, PM-015, PM-023, PM-024 | combined host/tool/search/question/manager integration |
|
|
40
|
+
| A-032 The default formal Registry searches at least 3,000 source records for Chinese task text, English task text, exact plugin names and an honest empty result; every returned source is locally inspected to an immutable npm version or GitHub commit, while Registry authority remains source-only, untrusted, non-recommending and non-approving | PM-005, PM-006, PM-025 | provider/unit/host integration tests plus `npm run acceptance:live:registry` |
|
|
40
41
|
|
|
41
42
|
## Test Layers
|
|
42
43
|
|
package/lib/index.d.ts
CHANGED
|
@@ -327,10 +327,12 @@ declare class PluginManager {
|
|
|
327
327
|
//#region src/index.d.ts
|
|
328
328
|
declare const name = "relay-dsh-plugin-manager";
|
|
329
329
|
declare const inject: string[];
|
|
330
|
+
declare const DEFAULT_REGISTRY_ORIGIN = "https://dsh-plugins.tech";
|
|
330
331
|
interface Config {
|
|
331
332
|
allowRestart?: boolean;
|
|
333
|
+
registryUrl?: string | false;
|
|
332
334
|
}
|
|
333
335
|
declare function apply(ctx: Context, config?: Config): void;
|
|
334
336
|
//#endregion
|
|
335
|
-
export { Config, type DiscoverRequest, type InstallManyItemResult, type InstallManyItemStatus, type InstallManyResult, type MutationResult, type PlanRequest, type PluginInspection, PluginManager, type PluginSearchCandidate, type PluginSearchMatch, type PluginSearchProvider, type PluginSearchRequest, type PluginSource, apply, inject, name };
|
|
337
|
+
export { Config, DEFAULT_REGISTRY_ORIGIN, type DiscoverRequest, type InstallManyItemResult, type InstallManyItemStatus, type InstallManyResult, type MutationResult, type PlanRequest, type PluginInspection, PluginManager, type PluginSearchCandidate, type PluginSearchMatch, type PluginSearchProvider, type PluginSearchRequest, type PluginSource, apply, inject, name };
|
|
336
338
|
//# sourceMappingURL=index.d.ts.map
|
package/lib/index.js
CHANGED
|
@@ -1687,6 +1687,7 @@ var PluginManager = class {
|
|
|
1687
1687
|
//#endregion
|
|
1688
1688
|
//#region src/providers.ts
|
|
1689
1689
|
const MAX_PROVIDER_RESULTS = 12;
|
|
1690
|
+
const REGISTRY_SNAPSHOT_ID = /^discovery\.[a-z0-9.-]+$/u;
|
|
1690
1691
|
function query(value) {
|
|
1691
1692
|
const normalized = value.trim();
|
|
1692
1693
|
if (normalized === "" || normalized.length > 120 || /[\u0000-\u001f\u007f]/u.test(normalized)) throw new Error("Search query must contain 1 to 120 printable characters.");
|
|
@@ -1802,6 +1803,105 @@ function githubSearchProvider(fetchImpl = globalThis.fetch, env = process.env) {
|
|
|
1802
1803
|
}
|
|
1803
1804
|
};
|
|
1804
1805
|
}
|
|
1806
|
+
function registryEndpoint(value) {
|
|
1807
|
+
let url;
|
|
1808
|
+
try {
|
|
1809
|
+
url = new URL(value);
|
|
1810
|
+
} catch {
|
|
1811
|
+
throw new Error("Registry URL must be an absolute URL.");
|
|
1812
|
+
}
|
|
1813
|
+
const local = url.hostname === "127.0.0.1" || url.hostname === "localhost" || url.hostname === "::1";
|
|
1814
|
+
if (url.protocol !== "https:" && !(local && url.protocol === "http:")) throw new Error("Registry URL must use HTTPS, except for an explicit local development endpoint.");
|
|
1815
|
+
if (url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") throw new Error("Registry URL cannot contain credentials, query parameters, or a fragment.");
|
|
1816
|
+
url.pathname = `${url.pathname.replace(/\/$/u, "")}/v1/plugins:search`;
|
|
1817
|
+
return url.href;
|
|
1818
|
+
}
|
|
1819
|
+
function boundedText(value, maximum = 4e3) {
|
|
1820
|
+
return typeof value === "string" && value.trim() !== "" && value.length <= maximum ? value : void 0;
|
|
1821
|
+
}
|
|
1822
|
+
function queryLocale(value) {
|
|
1823
|
+
return /\p{Script=Han}/u.test(value) ? "zh-CN" : "en";
|
|
1824
|
+
}
|
|
1825
|
+
function registryCandidate(value, snapshotId) {
|
|
1826
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
|
|
1827
|
+
const candidate = value;
|
|
1828
|
+
const entry = candidate.entry;
|
|
1829
|
+
if (typeof entry !== "object" || entry === null || boundedText(entry.entry_id, 100) === void 0 || boundedText(entry.identity?.name, 214) === void 0 || entry.imported_content?.trust !== "untrusted_text" || entry.resolution?.status !== "source_only" || !Array.isArray(entry.sources)) return null;
|
|
1830
|
+
const sources = entry.sources.flatMap((source) => {
|
|
1831
|
+
if (typeof source !== "object" || source === null || Array.isArray(source)) return [];
|
|
1832
|
+
const item = source;
|
|
1833
|
+
if (item.exact !== false) return [];
|
|
1834
|
+
if (item.kind === "npm" && typeof item.package_name === "string" && NPM_NAME.test(item.package_name)) return [{
|
|
1835
|
+
kind: "npm",
|
|
1836
|
+
package: item.package_name
|
|
1837
|
+
}];
|
|
1838
|
+
if (item.kind !== "github" || typeof item.repository !== "string" || typeof item.spec !== "string") return [];
|
|
1839
|
+
const [owner, repo, ...extra] = item.repository.split("/");
|
|
1840
|
+
if (owner === void 0 || repo === void 0 || extra.length > 0 || !isGithubPart(owner) || !isGithubPart(repo)) return [];
|
|
1841
|
+
const prefix = `github:${item.repository}`;
|
|
1842
|
+
if (!item.spec.startsWith(prefix)) return [];
|
|
1843
|
+
const suffix = item.spec.slice(prefix.length);
|
|
1844
|
+
if (suffix !== "" && !suffix.startsWith("#")) return [];
|
|
1845
|
+
return [{
|
|
1846
|
+
kind: "github",
|
|
1847
|
+
owner,
|
|
1848
|
+
repo,
|
|
1849
|
+
...suffix === "" ? {} : { ref: suffix.slice(1) }
|
|
1850
|
+
}];
|
|
1851
|
+
});
|
|
1852
|
+
if (sources.length === 0) return null;
|
|
1853
|
+
const zh = boundedText(entry.imported_content?.description?.["zh-CN"]);
|
|
1854
|
+
const en = boundedText(entry.imported_content?.description?.en);
|
|
1855
|
+
const repository = boundedText(entry.identity?.repository_url, 500);
|
|
1856
|
+
const reasonCodes = Array.isArray(candidate.match?.reason_codes) ? candidate.match.reason_codes.filter((item) => typeof item === "string" && /^[a-z0-9_]+$/u.test(item)).slice(0, 8) : [];
|
|
1857
|
+
const score = typeof candidate.match?.score === "number" && Number.isFinite(candidate.match.score) && candidate.match.score >= 0 ? candidate.match.score : void 0;
|
|
1858
|
+
return {
|
|
1859
|
+
id: `registry:${entry.entry_id}`,
|
|
1860
|
+
title: entry.identity.name,
|
|
1861
|
+
...zh !== void 0 || en !== void 0 ? { description: zh ?? en } : {},
|
|
1862
|
+
...repository === void 0 ? {} : {
|
|
1863
|
+
homepage: repository,
|
|
1864
|
+
repository
|
|
1865
|
+
},
|
|
1866
|
+
sources,
|
|
1867
|
+
...score === void 0 ? {} : { score },
|
|
1868
|
+
evidence: [
|
|
1869
|
+
`DSH Registry source snapshot: ${snapshotId}`,
|
|
1870
|
+
"Registry discovery record only; compatibility and security not tested",
|
|
1871
|
+
...reasonCodes.map((code) => `Registry match: ${code}`)
|
|
1872
|
+
]
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
function registrySearchProvider(baseUrl, fetchImpl = globalThis.fetch) {
|
|
1876
|
+
const endpoint = registryEndpoint(baseUrl);
|
|
1877
|
+
return {
|
|
1878
|
+
id: "dsh-registry",
|
|
1879
|
+
async search(request) {
|
|
1880
|
+
const text = query(request.query);
|
|
1881
|
+
const response = await fetchImpl(endpoint, {
|
|
1882
|
+
method: "POST",
|
|
1883
|
+
signal: request.signal,
|
|
1884
|
+
headers: {
|
|
1885
|
+
accept: "application/json",
|
|
1886
|
+
"content-type": "application/json"
|
|
1887
|
+
},
|
|
1888
|
+
body: JSON.stringify({
|
|
1889
|
+
schema_version: "1.0.0",
|
|
1890
|
+
query: text,
|
|
1891
|
+
locale: queryLocale(text),
|
|
1892
|
+
limit: Math.min(request.maxResults, MAX_PROVIDER_RESULTS)
|
|
1893
|
+
})
|
|
1894
|
+
});
|
|
1895
|
+
if (!response.ok) throw new Error(`DSH Registry search returned HTTP ${response.status}`);
|
|
1896
|
+
const data = await response.json();
|
|
1897
|
+
if (typeof data.snapshot_id !== "string" || !REGISTRY_SNAPSHOT_ID.test(data.snapshot_id) || !Array.isArray(data.candidates)) throw new Error("DSH Registry search returned an invalid discovery response.");
|
|
1898
|
+
return data.candidates.flatMap((candidate) => {
|
|
1899
|
+
const normalized = registryCandidate(candidate, data.snapshot_id);
|
|
1900
|
+
return normalized === null ? [] : [normalized];
|
|
1901
|
+
}).slice(0, Math.min(request.maxResults, MAX_PROVIDER_RESULTS));
|
|
1902
|
+
}
|
|
1903
|
+
};
|
|
1904
|
+
}
|
|
1805
1905
|
//#endregion
|
|
1806
1906
|
//#region src/restart.ts
|
|
1807
1907
|
function detectedSupervisor(env = process.env, ppid = process.ppid) {
|
|
@@ -1978,10 +2078,14 @@ const inject = [
|
|
|
1978
2078
|
"userQuestions",
|
|
1979
2079
|
"loader"
|
|
1980
2080
|
];
|
|
2081
|
+
const DEFAULT_REGISTRY_ORIGIN = "https://dsh-plugins.tech";
|
|
1981
2082
|
function apply(ctx, config = {}) {
|
|
1982
2083
|
const profileDir = profileDirectory("web");
|
|
1983
2084
|
ctx.pluginSearch.register(npmSearchProvider());
|
|
1984
2085
|
ctx.pluginSearch.register(githubSearchProvider());
|
|
2086
|
+
const configuredRegistryUrl = config.registryUrl ?? process.env.DSH_PLUGIN_REGISTRY_URL?.trim();
|
|
2087
|
+
const registryUrl = config.registryUrl === false ? void 0 : configuredRegistryUrl || "https://dsh-plugins.tech";
|
|
2088
|
+
if (registryUrl !== void 0) ctx.pluginSearch.register(registrySearchProvider(registryUrl));
|
|
1985
2089
|
registerConversationSurface(ctx, new PluginManager({
|
|
1986
2090
|
profileDir,
|
|
1987
2091
|
searchRuntime: ctx.pluginSearch,
|
|
@@ -1992,6 +2096,6 @@ function apply(ctx, config = {}) {
|
|
|
1992
2096
|
}));
|
|
1993
2097
|
}
|
|
1994
2098
|
//#endregion
|
|
1995
|
-
export { PluginManager, apply, inject, name };
|
|
2099
|
+
export { DEFAULT_REGISTRY_ORIGIN, PluginManager, apply, inject, name };
|
|
1996
2100
|
|
|
1997
2101
|
//# sourceMappingURL=index.js.map
|
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/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 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: 'Maximum merged search results.' },\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 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 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 ?? 6))\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, SearchResult['candidates'][number] & {\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: _rank, matchPriority: _matchPriority, ...candidate }) => ({\n ...candidate,\n providers: candidate.providers.sort(),\n }))\n return { query: parsed.query, candidates, providerErrors, rejectedCandidates }\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'\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}\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\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 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 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\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 }\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 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 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 return this.withRestartGuidance(\n await this.installOrUpdate(plan.action, plan.packageName, plan.installSpec, context),\n automaticRestartAvailable,\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 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 } 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 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 { NPM_NAME } from './source.ts'\n\nconst MAX_PROVIDER_RESULTS = 12\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","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 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 } from './providers.ts'\nimport { DshRestarter } from './restart.ts'\nimport { DshCliRunner } from './runner.ts'\n\nexport const name = 'relay-dsh-plugin-manager'\nexport const inject = ['pluginSearch', 'tools', 'commands', 'userQuestions', 'loader']\n\nexport interface Config {\n allowRestart?: boolean\n}\n\nexport function apply(ctx: Context, config: Config = {}): void {\n const profileDir = profileDirectory('web')\n ctx.pluginSearch.register(npmSearchProvider())\n ctx.pluginSearch.register(githubSearchProvider())\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 })\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'\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,gBAA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":["../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/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 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: 'Maximum merged search results.' },\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 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 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 ?? 6))\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, SearchResult['candidates'][number] & {\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: _rank, matchPriority: _matchPriority, ...candidate }) => ({\n ...candidate,\n providers: candidate.providers.sort(),\n }))\n return { query: parsed.query, candidates, providerErrors, rejectedCandidates }\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'\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}\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\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 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 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\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 }\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 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 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 return this.withRestartGuidance(\n await this.installOrUpdate(plan.action, plan.packageName, plan.installSpec, context),\n automaticRestartAvailable,\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 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 } 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 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 = 12\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 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'\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}\n\nexport function apply(ctx: Context, config: Config = {}): void {\n const profileDir = profileDirectory('web')\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 })\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'\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,MAAM,KAAK,UAAU;EACrB,KAAK,MAAM,QAAQ,KAAK,OAAO,MAAM,KAAK,KAAK,KAAK,YAAY,IAAI,K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R;KACA;KACA;KACA;IACF,CAAC;GACH,CAAC;EACH,CAAC;CACH;AACF;;;ACjIA,MAAa,OAAO;AACpB,MAAa,SAAS;CAAC;CAAgB;CAAS;CAAY;CAAiB;AAAQ;AACrF,MAAa,0BAA0B;AAOvC,SAAgB,MAAM,KAAc,SAAiB,CAAC,GAAS;CAC7D,MAAM,aAAa,iBAAiB,KAAK;CACzC,IAAI,aAAa,SAAS,kBAAkB,CAAC;CAC7C,IAAI,aAAa,SAAS,qBAAqB,CAAC;CAChD,MAAM,wBAAwB,OAAO,eAAe,QAAQ,IAAI,yBAAyB,KAAK;CAC9F,MAAM,cAAc,OAAO,gBAAgB,QAAQ,KAAA,IAAY,yBAAA;CAC/D,IAAI,gBAAgB,KAAA,GAAW,IAAI,aAAa,SAAS,uBAAuB,WAAW,CAAC;CAU5F,4BAA4B,KAAK,IARb,cAAc;EAChC;EACA,eAAe,IAAI;EACnB,QAAQ,IAAI,aAAa;EACzB,KAAK,IAAI,WAAW,KAAK,UAAU;EACnC,WAAW,IAAI,aAAa,EAAE,cAAc,OAAO,aAAa,CAAC;EACjE,QAAQ,IAAI;CACd,CACuC,CAAC;AAC1C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "relay-dsh-plugin-manager",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "Conversation-first plugin discovery and lifecycle management for DeepSeek Harness.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"deepseek-harness",
|
|
@@ -36,6 +36,7 @@
|
|
|
36
36
|
"test:unit": "vitest run test/unit",
|
|
37
37
|
"test:integration": "vitest run test/integration",
|
|
38
38
|
"acceptance:live:codex": "RELAY_LIVE_PLUGIN_ACCEPTANCE=1 vitest run test/live/codex.live.test.ts --reporter=verbose",
|
|
39
|
+
"acceptance:live:registry": "node --experimental-strip-types scripts/accept-live-registry.mjs",
|
|
39
40
|
"acceptance:controlled": "node --experimental-strip-types scripts/accept-controlled-lifecycle.mjs",
|
|
40
41
|
"acceptance": "node scripts/accept-local-package.mjs",
|
|
41
42
|
"release:dry-run": "npm publish --dry-run --tag next",
|