@kirkchinese/harness-forge 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (279) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +46 -2
  3. package/assets/icon.svg +12 -0
  4. package/cordis.patch.yml +28 -0
  5. package/docs/DETAIL.zh.md +47 -0
  6. package/lib/agents/presets.d.ts +98 -0
  7. package/lib/agents/presets.js +292 -0
  8. package/lib/agents/profiles.d.ts +58 -0
  9. package/lib/agents/profiles.js +279 -0
  10. package/lib/agents/row.d.ts +17 -0
  11. package/lib/agents/row.js +148 -0
  12. package/lib/client/paths.d.ts +12 -0
  13. package/lib/client/paths.js +68 -0
  14. package/lib/client/styles.d.ts +8 -0
  15. package/lib/client/styles.js +89 -0
  16. package/lib/client/typert.d.ts +25 -0
  17. package/lib/client/typert.js +158 -0
  18. package/lib/client.js +23823 -0
  19. package/lib/commands/definition.d.ts +40 -0
  20. package/lib/commands/definition.js +113 -0
  21. package/lib/commands/output-styles.d.ts +42 -0
  22. package/lib/commands/output-styles.js +152 -0
  23. package/lib/commands/row.d.ts +9 -0
  24. package/lib/commands/row.js +157 -0
  25. package/lib/context/instructions.d.ts +32 -0
  26. package/lib/context/instructions.js +88 -0
  27. package/lib/context/row.d.ts +16 -0
  28. package/lib/context/row.js +17 -0
  29. package/lib/dsh/commands.d.ts +30 -0
  30. package/lib/dsh/commands.js +61 -0
  31. package/lib/dsh/host.d.ts +110 -0
  32. package/lib/dsh/host.js +217 -0
  33. package/lib/dsh/model-route.d.ts +21 -0
  34. package/lib/dsh/model-route.js +37 -0
  35. package/lib/dsh/session-records.d.ts +78 -0
  36. package/lib/dsh/session-records.js +36 -0
  37. package/lib/dsh/subagents.d.ts +46 -0
  38. package/lib/dsh/subagents.js +14 -0
  39. package/lib/forge/contract.d.ts +271 -0
  40. package/lib/forge/contract.js +45 -0
  41. package/lib/forge/follow.d.ts +30 -0
  42. package/lib/forge/follow.js +73 -0
  43. package/lib/forge/ledger.d.ts +206 -0
  44. package/lib/forge/ledger.js +1005 -0
  45. package/lib/forge/live-mounts.d.ts +45 -0
  46. package/lib/forge/live-mounts.js +78 -0
  47. package/lib/forge/npm.d.ts +31 -0
  48. package/lib/forge/npm.js +60 -0
  49. package/lib/forge/projects.d.ts +97 -0
  50. package/lib/forge/projects.js +343 -0
  51. package/lib/forge/receipts.d.ts +5 -0
  52. package/lib/forge/receipts.js +31 -0
  53. package/lib/forge/remote/archive.d.ts +65 -0
  54. package/lib/forge/remote/archive.js +565 -0
  55. package/lib/forge/remote/code-parts.d.ts +18 -0
  56. package/lib/forge/remote/code-parts.js +76 -0
  57. package/lib/forge/remote/fetch.d.ts +265 -0
  58. package/lib/forge/remote/fetch.js +1133 -0
  59. package/lib/forge/remote/service.d.ts +256 -0
  60. package/lib/forge/remote/service.js +868 -0
  61. package/lib/forge/row.d.ts +32 -0
  62. package/lib/forge/row.js +59 -0
  63. package/lib/forge/service.d.ts +115 -0
  64. package/lib/forge/service.js +290 -0
  65. package/lib/forge/settings.d.ts +43 -0
  66. package/lib/forge/settings.js +122 -0
  67. package/lib/forge/state.d.ts +129 -0
  68. package/lib/forge/state.js +266 -0
  69. package/lib/forge/trust.d.ts +48 -0
  70. package/lib/forge/trust.js +107 -0
  71. package/lib/forge/turns.d.ts +13 -0
  72. package/lib/forge/turns.js +56 -0
  73. package/lib/hooks/broker/engine.d.ts +112 -0
  74. package/lib/hooks/broker/engine.js +722 -0
  75. package/lib/hooks/broker/helpers.d.ts +10 -0
  76. package/lib/hooks/broker/helpers.js +22 -0
  77. package/lib/hooks/broker/lifecycle.d.ts +65 -0
  78. package/lib/hooks/broker/lifecycle.js +342 -0
  79. package/lib/hooks/broker/session-events.d.ts +27 -0
  80. package/lib/hooks/broker/session-events.js +205 -0
  81. package/lib/hooks/broker/tools.d.ts +52 -0
  82. package/lib/hooks/broker/tools.js +424 -0
  83. package/lib/hooks/broker/types.d.ts +264 -0
  84. package/lib/hooks/broker/types.js +1 -0
  85. package/lib/hooks/broker.d.ts +80 -0
  86. package/lib/hooks/broker.js +95 -0
  87. package/lib/hooks/codex-user.d.ts +5 -0
  88. package/lib/hooks/codex-user.js +109 -0
  89. package/lib/hooks/condition.d.ts +87 -0
  90. package/lib/hooks/condition.js +602 -0
  91. package/lib/hooks/config.d.ts +85 -0
  92. package/lib/hooks/config.js +154 -0
  93. package/lib/hooks/glob.d.ts +41 -0
  94. package/lib/hooks/glob.js +114 -0
  95. package/lib/hooks/matcher.d.ts +20 -0
  96. package/lib/hooks/matcher.js +39 -0
  97. package/lib/hooks/notice.d.ts +17 -0
  98. package/lib/hooks/notice.js +39 -0
  99. package/lib/hooks/output.d.ts +56 -0
  100. package/lib/hooks/output.js +214 -0
  101. package/lib/hooks/permissions.d.ts +19 -0
  102. package/lib/hooks/permissions.js +202 -0
  103. package/lib/hooks/powershell-aliases.d.ts +19 -0
  104. package/lib/hooks/powershell-aliases.js +58 -0
  105. package/lib/hooks/process.d.ts +64 -0
  106. package/lib/hooks/process.js +289 -0
  107. package/lib/hooks/row.d.ts +17 -0
  108. package/lib/hooks/row.js +96 -0
  109. package/lib/hooks/runner.d.ts +98 -0
  110. package/lib/hooks/runner.js +322 -0
  111. package/lib/hooks/shell-commands.d.ts +28 -0
  112. package/lib/hooks/shell-commands.js +241 -0
  113. package/lib/hooks/shell.d.ts +44 -0
  114. package/lib/hooks/shell.js +129 -0
  115. package/lib/hooks/transcript.d.ts +28 -0
  116. package/lib/hooks/transcript.js +141 -0
  117. package/lib/hooks/vocabulary.d.ts +57 -0
  118. package/lib/hooks/vocabulary.js +366 -0
  119. package/lib/index.d.ts +31 -0
  120. package/lib/index.js +287 -0
  121. package/lib/mcp/auth.d.ts +35 -0
  122. package/lib/mcp/auth.js +178 -0
  123. package/lib/mcp/catalog.d.ts +39 -0
  124. package/lib/mcp/catalog.js +69 -0
  125. package/lib/mcp/mount.d.ts +113 -0
  126. package/lib/mcp/mount.js +317 -0
  127. package/lib/mcp/policy.d.ts +42 -0
  128. package/lib/mcp/policy.js +43 -0
  129. package/lib/mcp/remote.d.ts +45 -0
  130. package/lib/mcp/remote.js +133 -0
  131. package/lib/mcp/row.d.ts +9 -0
  132. package/lib/mcp/row.js +225 -0
  133. package/lib/mods/bundler.d.ts +38 -0
  134. package/lib/mods/bundler.js +157 -0
  135. package/lib/mods/chain.d.ts +103 -0
  136. package/lib/mods/chain.js +436 -0
  137. package/lib/mods/claude.d.ts +27 -0
  138. package/lib/mods/claude.js +56 -0
  139. package/lib/mods/engine.d.ts +160 -0
  140. package/lib/mods/engine.js +701 -0
  141. package/lib/mods/expect.d.ts +8 -0
  142. package/lib/mods/expect.js +248 -0
  143. package/lib/mods/host.d.ts +105 -0
  144. package/lib/mods/host.js +462 -0
  145. package/lib/mods/loader.d.ts +53 -0
  146. package/lib/mods/loader.js +231 -0
  147. package/lib/mods/ops.d.ts +13 -0
  148. package/lib/mods/ops.js +117 -0
  149. package/lib/mods/row.d.ts +9 -0
  150. package/lib/mods/row.js +77 -0
  151. package/lib/mods/runtime.d.ts +60 -0
  152. package/lib/mods/runtime.js +133 -0
  153. package/lib/mods/service/commands.d.ts +17 -0
  154. package/lib/mods/service/commands.js +121 -0
  155. package/lib/mods/service/drawings.d.ts +36 -0
  156. package/lib/mods/service/drawings.js +64 -0
  157. package/lib/mods/service/sessions.d.ts +63 -0
  158. package/lib/mods/service/sessions.js +345 -0
  159. package/lib/mods/service/tools.d.ts +32 -0
  160. package/lib/mods/service/tools.js +253 -0
  161. package/lib/mods/service/turns.d.ts +33 -0
  162. package/lib/mods/service/turns.js +136 -0
  163. package/lib/mods/service/types.d.ts +151 -0
  164. package/lib/mods/service/types.js +1 -0
  165. package/lib/mods/service.d.ts +72 -0
  166. package/lib/mods/service.js +104 -0
  167. package/lib/mods/surfaces.d.ts +93 -0
  168. package/lib/mods/surfaces.js +309 -0
  169. package/lib/mods/values.d.ts +30 -0
  170. package/lib/mods/values.js +95 -0
  171. package/lib/opencode/bun.d.ts +40 -0
  172. package/lib/opencode/bun.js +168 -0
  173. package/lib/opencode/convert.d.ts +53 -0
  174. package/lib/opencode/convert.js +255 -0
  175. package/lib/opencode/row.d.ts +22 -0
  176. package/lib/opencode/row.js +104 -0
  177. package/lib/opencode/runtime/core.d.ts +74 -0
  178. package/lib/opencode/runtime/core.js +249 -0
  179. package/lib/opencode/runtime/events.d.ts +80 -0
  180. package/lib/opencode/runtime/events.js +281 -0
  181. package/lib/opencode/runtime/mount.d.ts +27 -0
  182. package/lib/opencode/runtime/mount.js +283 -0
  183. package/lib/opencode/runtime/server.d.ts +27 -0
  184. package/lib/opencode/runtime/server.js +354 -0
  185. package/lib/opencode/runtime/types.d.ts +109 -0
  186. package/lib/opencode/runtime/types.js +1 -0
  187. package/lib/opencode/runtime.d.ts +55 -0
  188. package/lib/opencode/runtime.js +79 -0
  189. package/lib/porting/adapter-paths.d.ts +13 -0
  190. package/lib/porting/adapter-paths.js +120 -0
  191. package/lib/porting/port-gap.d.ts +36 -0
  192. package/lib/porting/port-gap.js +158 -0
  193. package/lib/porting/port-sessions.d.ts +41 -0
  194. package/lib/porting/port-sessions.js +98 -0
  195. package/lib/porting/prompt.d.ts +23 -0
  196. package/lib/porting/prompt.js +51 -0
  197. package/lib/porting/row.d.ts +16 -0
  198. package/lib/porting/row.js +27 -0
  199. package/lib/porting/verify-port.d.ts +46 -0
  200. package/lib/porting/verify-port.js +82 -0
  201. package/lib/presets/fs-search.d.ts +25 -0
  202. package/lib/presets/fs-search.js +17 -0
  203. package/lib/presets/tool-filter.d.ts +35 -0
  204. package/lib/presets/tool-filter.js +91 -0
  205. package/lib/sessions/chat-import.d.ts +48 -0
  206. package/lib/sessions/chat-import.js +44 -0
  207. package/lib/sessions/claude.d.ts +35 -0
  208. package/lib/sessions/claude.js +104 -0
  209. package/lib/sessions/codex-discover.d.ts +34 -0
  210. package/lib/sessions/codex-discover.js +205 -0
  211. package/lib/sessions/codex-meta.d.ts +63 -0
  212. package/lib/sessions/codex-meta.js +148 -0
  213. package/lib/sessions/codex-text.d.ts +9 -0
  214. package/lib/sessions/codex-text.js +44 -0
  215. package/lib/sessions/codex.d.ts +42 -0
  216. package/lib/sessions/codex.js +270 -0
  217. package/lib/sessions/opencode.d.ts +38 -0
  218. package/lib/sessions/opencode.js +339 -0
  219. package/lib/sessions/persist.d.ts +162 -0
  220. package/lib/sessions/persist.js +377 -0
  221. package/lib/sessions/row.d.ts +15 -0
  222. package/lib/sessions/row.js +101 -0
  223. package/lib/sessions/turns.d.ts +31 -0
  224. package/lib/sessions/turns.js +63 -0
  225. package/lib/sessions/zstd.d.ts +15 -0
  226. package/lib/sessions/zstd.js +152 -0
  227. package/lib/shared/invocation.d.ts +169 -0
  228. package/lib/shared/invocation.js +325 -0
  229. package/lib/shared/render.d.ts +101 -0
  230. package/lib/shared/render.js +1353 -0
  231. package/lib/shared/util.d.ts +21 -0
  232. package/lib/shared/util.js +32 -0
  233. package/lib/skills/bundled.d.ts +3 -0
  234. package/lib/skills/bundled.js +42 -0
  235. package/lib/skills/provider.d.ts +74 -0
  236. package/lib/skills/provider.js +346 -0
  237. package/lib/skills/row.d.ts +22 -0
  238. package/lib/skills/row.js +204 -0
  239. package/lib/workbench/adapter-coverage.d.ts +65 -0
  240. package/lib/workbench/adapter-coverage.js +141 -0
  241. package/lib/workbench/model-tools.d.ts +10 -0
  242. package/lib/workbench/model-tools.js +122 -0
  243. package/lib/workbench/overview.d.ts +153 -0
  244. package/lib/workbench/overview.js +246 -0
  245. package/lib/workbench/remote.d.ts +161 -0
  246. package/lib/workbench/remote.js +561 -0
  247. package/lib/workbench/row.d.ts +15 -0
  248. package/lib/workbench/row.js +16 -0
  249. package/lib/workbench/settings.d.ts +19 -0
  250. package/lib/workbench/settings.js +60 -0
  251. package/lib/workbench/workbench.d.ts +130 -0
  252. package/lib/workbench/workbench.js +361 -0
  253. package/locale/agents/en.json +6 -0
  254. package/locale/agents/zh.json +6 -0
  255. package/locale/commands/en.json +6 -0
  256. package/locale/commands/zh.json +6 -0
  257. package/locale/context/en.json +6 -0
  258. package/locale/context/zh.json +6 -0
  259. package/locale/en.json +6 -0
  260. package/locale/hooks/en.json +6 -0
  261. package/locale/hooks/zh.json +6 -0
  262. package/locale/mcp/en.json +6 -0
  263. package/locale/mcp/zh.json +6 -0
  264. package/locale/mods/en.json +6 -0
  265. package/locale/mods/zh.json +6 -0
  266. package/locale/opencode/en.json +6 -0
  267. package/locale/opencode/zh.json +6 -0
  268. package/locale/porter/en.json +6 -0
  269. package/locale/porter/zh.json +6 -0
  270. package/locale/sessions/en.json +6 -0
  271. package/locale/sessions/zh.json +6 -0
  272. package/locale/skills/en.json +6 -0
  273. package/locale/skills/zh.json +6 -0
  274. package/locale/workbench/en.json +6 -0
  275. package/locale/workbench/zh.json +6 -0
  276. package/locale/zh.json +7 -0
  277. package/package.json +247 -3
  278. package/runtime/opencode-host.mjs +270 -0
  279. package/skills/harness-forge/SKILL.md +47 -0
@@ -0,0 +1,868 @@
1
+ /**
2
+ * Plugins from the network: open a marketplace (or a single plugin) someone
3
+ * pasted, fetch one entry into a directory of Harness Forge's own, show what it
4
+ * contains before anything runs, install it through the ledger like a local
5
+ * plugin, and later check for updates, which are shown and confirmed the same
6
+ * way. Nothing is written into `~/.claude`, `~/.codex`, OpenCode's
7
+ * configuration or the DSH profile.
8
+ *
9
+ * What is installed is exactly what was shown: a prepared plugin waits in a
10
+ * staging directory of its own, its files' digest bound to the confirmation;
11
+ * the confirmation checks the digest again and moves it into a directory
12
+ * named by its source, revision and digest, which is never replaced or
13
+ * deleted while an install uses it.
14
+ *
15
+ * Layout under `<data>/remote/`:
16
+ * - `state.json`: the marketplaces the person added and what was installed from where.
17
+ * - `cache/git/<key>/<sha>/`: checkouts read to browse a marketplace and copied from.
18
+ * - `staging/<random>/`: one prepared plugin waiting for its confirmation.
19
+ * - `plugins/<key>/`: installed copies, keyed by source identity, revision and files.
20
+ * @module @kirkchinese/harness-forge
21
+ */
22
+ import { createHash, randomBytes } from 'node:crypto';
23
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
24
+ import { basename, dirname, join, relative, resolve } from 'node:path';
25
+ import { assess, DEFAULT_MARKETPLACES, describeSpec, detectSource, HarnessError, isInside, isPlainObject, kebabCase, marketplaceProblem, npmPage, pageOfSpec, parseMarketplace, parseRemoteInput, readMarketplace, specIdentity, specOfSource, } from '@kirkchinese/harness-forge-core';
26
+ import { messageOf } from '../../shared/util.js';
27
+ import { partOf } from '../../workbench/overview.js';
28
+ import { copyTree, treeDigest } from './archive.js';
29
+ import { codePartsOf } from './code-parts.js';
30
+ import { dependenciesOf, RemoteFetcher } from './fetch.js';
31
+ /** Pending confirmations and update checks are dropped after this long (and their files with them). */
32
+ const PENDING_MS = 30 * 60_000;
33
+ /** The revision of a copy of a folder on this computer, which has no history to name one. */
34
+ const LOCAL_REVISION = 'local';
35
+ /** Entry fields that are the marketplace's, not the plugin manifest's. */
36
+ const ENTRY_ONLY = new Set(['source', 'strict', 'category', 'tags', 'policy', 'relevance', 'metadata', 'headers', 'headersHelper', 'defaultEnabled', 'engines']);
37
+ /** Component fields an entry adds to a `plugin.json` (Claude Code's strict mode). */
38
+ const COMPONENT_FIELDS = ['commands', 'agents', 'skills', 'hooks', 'outputStyles', 'themes'];
39
+ function short(revision) {
40
+ return /^[0-9a-f]{40}$/u.test(revision) ? revision.slice(0, 12) : revision;
41
+ }
42
+ function safeName(value) {
43
+ return kebabCase(value).slice(0, 60) || 'plugin';
44
+ }
45
+ function marketplaceHarness(index) {
46
+ return index.manifestPath.replace(/\\/gu, '/').includes('/.agents/plugins/') ? 'codex' : 'claude-code';
47
+ }
48
+ /** Find the marketplace manifest of a checkout. */
49
+ function marketplaceIn(dir) {
50
+ for (const candidate of [join(dir, '.claude-plugin', 'marketplace.json'), join(dir, '.agents', 'plugins', 'marketplace.json')]) {
51
+ if (existsSync(candidate))
52
+ return readMarketplace(candidate);
53
+ }
54
+ return undefined;
55
+ }
56
+ function homePath(path) {
57
+ return resolve(path.replace(/^~(?=$|[/\\])/u, process.env['HOME'] ?? process.env['USERPROFILE'] ?? '~'));
58
+ }
59
+ function changed(what, now, checked) {
60
+ return new HarnessError('fetch-failed', `${what} changed since it was checked (now ${short(now)}, checked ${short(checked)})`, { suggestion: 'Check for updates again.' });
61
+ }
62
+ /** A part across revisions: its kind and name (ids carry the plugin's, which a copy elsewhere may not share). */
63
+ function partKey(component) {
64
+ return `${component.kind}:${component.name}`;
65
+ }
66
+ /** Each part's files and settings, to tell an update's new and changed parts. */
67
+ function partDigests(plugin) {
68
+ const out = new Map();
69
+ for (const component of plugin.components) {
70
+ const path = component.path === undefined ? undefined : resolve(plugin.root, component.path);
71
+ let files = '';
72
+ try {
73
+ files = path !== undefined && existsSync(path) ? treeDigest(path) : '';
74
+ }
75
+ catch {
76
+ files = '';
77
+ }
78
+ const settings = JSON.stringify(component.metadata ?? null).split(plugin.root).join('<root>');
79
+ out.set(partKey(component), createHash('sha256').update(`${files}\0${settings}`).digest('hex'));
80
+ }
81
+ return out;
82
+ }
83
+ /** The hosts in what the person pasted: what a proxy may be asked for on their say-so. */
84
+ function pastedHosts(...inputs) {
85
+ return inputs.flatMap((input) => {
86
+ try {
87
+ const spec = parseRemoteInput(input);
88
+ if (spec.kind !== 'git' && spec.kind !== 'json' && spec.kind !== 'archive')
89
+ return [];
90
+ const scp = /^[\w.-]+@([\w.-]+):(?!\/\/)/u.exec(spec.url);
91
+ return [scp !== null ? scp[1] : new URL(spec.url).hostname];
92
+ }
93
+ catch {
94
+ return [];
95
+ }
96
+ });
97
+ }
98
+ /** An install as a confirmation or an update check binds it. */
99
+ function baseOf(install) {
100
+ return { pluginId: install.pluginId, root: install.root, revision: install.revision, ...(install.digest !== undefined ? { digest: install.digest } : {}) };
101
+ }
102
+ /** Whether an install is still the copy `base` recorded. */
103
+ function sameBase(now, base) {
104
+ return now.pluginId === base.pluginId && now.root === base.root && now.revision === base.revision && now.digest === base.digest;
105
+ }
106
+ /** What an origin's source was pasted as. */
107
+ function pastedOf(origin) {
108
+ return origin.kind === 'direct' ? origin.input : origin.marketplace;
109
+ }
110
+ /** A warning naming the links a copy left out, when it left any. */
111
+ function linkWarnings(skipped) {
112
+ if (skipped.length === 0)
113
+ return {};
114
+ return { warnings: [`Links are not installed; left out: ${skipped.slice(0, 5).join(', ')}${skipped.length > 5 ? ` and ${String(skipped.length - 5)} more` : ''}`] };
115
+ }
116
+ /** The installed-plugins service. */
117
+ export class RemotePlugins {
118
+ root;
119
+ host;
120
+ fetcher;
121
+ state;
122
+ /** `base`: the installed copy the candidate replaces; `explicit` when the person asked to update it. */
123
+ pending = new Map();
124
+ /** `base`: the installed copy the check compared, which the update it found replaces. */
125
+ checks = new Map();
126
+ statePath;
127
+ /** Fetching, installing and collecting run one at a time, so a collection never takes files being made or read. */
128
+ queue = Promise.resolve();
129
+ constructor(root, host, deps, limits) {
130
+ this.root = root;
131
+ this.host = host;
132
+ this.fetcher = new RemoteFetcher(root, deps, limits);
133
+ this.statePath = join(root, 'state.json');
134
+ this.state = this.read();
135
+ }
136
+ read() {
137
+ try {
138
+ const value = JSON.parse(readFileSync(this.statePath, 'utf8'));
139
+ return {
140
+ version: 1,
141
+ sources: Array.isArray(value.sources) ? value.sources.filter(source => typeof source?.input === 'string') : [],
142
+ installs: Array.isArray(value.installs) ? value.installs.filter(install => typeof install?.pluginId === 'string' && typeof install.root === 'string' && typeof install.identity === 'string') : [],
143
+ };
144
+ }
145
+ catch {
146
+ return { version: 1, sources: [], installs: [] };
147
+ }
148
+ }
149
+ persist() {
150
+ mkdirSync(this.root, { recursive: true });
151
+ const temporary = `${this.statePath}.tmp`;
152
+ writeFileSync(temporary, `${JSON.stringify(this.state, null, 2)}\n`, 'utf8');
153
+ renameSync(temporary, this.statePath);
154
+ }
155
+ exclusive(run) {
156
+ const next = this.queue.then(run, run);
157
+ this.queue = next.catch(() => undefined);
158
+ return next;
159
+ }
160
+ /**
161
+ * The default and added marketplaces, and what was installed through Get plugins; an install taken from a
162
+ * local marketplace's own folder names that marketplace (`localMarketplace`).
163
+ */
164
+ async sources() {
165
+ return {
166
+ defaults: DEFAULT_MARKETPLACES,
167
+ added: this.state.sources.filter(source => !DEFAULT_MARKETPLACES.some(item => item.input === source.input)),
168
+ installs: this.installs().map(install => (install.origin.kind === 'marketplace' && install.revision === LOCAL_REVISION ? { ...install, localMarketplace: install.origin.marketplaceName } : install)),
169
+ git: await this.fetcher.hasGit(),
170
+ };
171
+ }
172
+ /** Installs whose plugin is still in the ledger. */
173
+ installs() {
174
+ return this.state.installs.filter(install => this.host.installed(install.pluginId));
175
+ }
176
+ // --- browsing ---------------------------------------------------------------
177
+ /** Open what was pasted: a marketplace's entries, or one plugin. A marketplace opened from the network is remembered. */
178
+ open(input) {
179
+ return this.exclusive(() => this.openNow(input));
180
+ }
181
+ async openNow(input) {
182
+ this.collect();
183
+ const spec = parseRemoteInput(input);
184
+ const opened = await this.load(spec, this.fetcher.context('user', pastedHosts(input)));
185
+ if (opened.index !== undefined) {
186
+ const index = opened.index;
187
+ const harness = marketplaceHarness(index);
188
+ if (spec.kind !== 'local' && !this.state.sources.some(source => source.input === input.trim())) {
189
+ this.state.sources.push({ input: input.trim(), name: index.name, harness, addedAt: new Date().toISOString() });
190
+ this.persist();
191
+ }
192
+ const marketIdentity = specIdentity(spec);
193
+ const installed = new Map(this.installs().map(install => [install.identity, install.pluginId]));
194
+ return {
195
+ kind: 'marketplace',
196
+ input: input.trim(),
197
+ name: index.name,
198
+ ...(index.description !== undefined ? { description: index.description } : {}),
199
+ ...(index.owner !== undefined ? { owner: index.owner } : {}),
200
+ harness,
201
+ source: describeSpec(spec),
202
+ ...(pageOfSpec(spec) !== undefined ? { page: pageOfSpec(spec) } : {}),
203
+ ...(opened.revision !== undefined ? { revision: short(opened.revision) } : {}),
204
+ entries: index.entries.map(entry => this.entryView(entry, installed.get(this.entryIdentity(marketIdentity, index, entry)))),
205
+ warnings: index.warnings,
206
+ };
207
+ }
208
+ return {
209
+ kind: 'plugin',
210
+ input: input.trim(),
211
+ name: opened.name ?? describeSpec(spec),
212
+ harness: opened.harness ?? 'opencode',
213
+ source: describeSpec(spec),
214
+ ...(opened.page ?? pageOfSpec(spec)) !== undefined ? { page: (opened.page ?? pageOfSpec(spec)) } : {},
215
+ ...(opened.revision !== undefined ? { revision: short(opened.revision) } : {}),
216
+ ...(opened.registry !== undefined ? { registry: opened.registry } : {}),
217
+ entries: [],
218
+ warnings: [],
219
+ };
220
+ }
221
+ /** Stop listing an added marketplace. */
222
+ forget(input) {
223
+ const before = this.state.sources.length;
224
+ this.state.sources = this.state.sources.filter(source => source.input !== input.trim());
225
+ if (this.state.sources.length === before)
226
+ return false;
227
+ this.persist();
228
+ return true;
229
+ }
230
+ /** Why Harness Forge does not fetch an entry's source, or undefined when it does. */
231
+ problemOf(source) {
232
+ if (source.kind === 'command')
233
+ return 'runs a command from the marketplace on this computer';
234
+ if (source.kind === 'path')
235
+ return undefined;
236
+ const spec = specOfSource(source);
237
+ if (spec === undefined)
238
+ return `source "${source.kind}" is not supported`;
239
+ return marketplaceProblem(spec);
240
+ }
241
+ /** An entry's full identity: the marketplace's source, the entry, and the source the entry names (its path inside the marketplace, or its own). */
242
+ entryIdentity(marketIdentity, index, entry) {
243
+ const source = entry.source;
244
+ const own = source.kind === 'path' && source.path !== undefined
245
+ ? `path:${relative(index.root, source.path).replace(/\\/gu, '/')}`
246
+ : (() => {
247
+ const spec = specOfSource(source);
248
+ return spec === undefined ? source.kind : specIdentity(spec);
249
+ })();
250
+ return `${marketIdentity}!${entry.name}!${own}`;
251
+ }
252
+ entryView(entry, installed) {
253
+ const source = entry.source;
254
+ const unsupported = this.problemOf(source);
255
+ return {
256
+ name: entry.name,
257
+ ...(entry.description !== undefined ? { description: entry.description } : {}),
258
+ ...(entry.version !== undefined ? { version: entry.version } : {}),
259
+ ...(entry.category !== undefined ? { category: entry.category } : {}),
260
+ from: source.kind === 'path' ? 'marketplace' : source.kind === 'npm' ? `npm:${source.package ?? ''}` : source.url ?? source.kind,
261
+ ...(unsupported !== undefined ? { unsupported } : {}),
262
+ ...(installed !== undefined ? { installed } : {}),
263
+ };
264
+ }
265
+ /** Read a source (at `sha`, for a git source being updated): a marketplace index with the commit it was read at, or what a single plugin is. */
266
+ async load(spec, context, sha) {
267
+ switch (spec.kind) {
268
+ case 'local': {
269
+ const path = homePath(spec.path);
270
+ const index = marketplaceIn(path) ?? (path.endsWith('.json') ? readMarketplace(path) : undefined);
271
+ if (index !== undefined)
272
+ return { index };
273
+ return { name: basename(path), harness: detectSource(path), checkout: path };
274
+ }
275
+ case 'json': {
276
+ const data = await this.fetcher.json(spec.url, context);
277
+ return { index: parseMarketplace(data, join(this.root, 'cache', 'none'), spec.url, { filesAvailable: false }) };
278
+ }
279
+ case 'npm': {
280
+ const found = await this.fetcher.npmLatest(spec, context);
281
+ return { name: spec.package, harness: 'opencode', revision: found.version, registry: found.registry, page: npmPage(found.registry, found.name, found.version) };
282
+ }
283
+ case 'archive':
284
+ return { name: basename(new URL(spec.url).pathname).replace(/\.zip$/iu, ''), harness: 'claude-code' };
285
+ case 'git': {
286
+ const { dir, sha: at } = await this.fetcher.checkout(spec, context, sha);
287
+ const base = RemoteFetcher.inside(dir, spec.subpath);
288
+ const index = marketplaceIn(base);
289
+ if (index !== undefined)
290
+ return { index, revision: at, checkout: base };
291
+ const harness = detectSource(base);
292
+ return { name: spec.subpath !== undefined ? basename(spec.subpath) : spec.github?.repo ?? basename(spec.url).replace(/\.git$/u, ''), harness, revision: at, checkout: base };
293
+ }
294
+ }
295
+ }
296
+ // --- installing ---------------------------------------------------------------
297
+ /**
298
+ * Fetch a plugin (a marketplace's `entry`, or the pasted source itself) and
299
+ * say what it contains; nothing of it runs or is installed until
300
+ * {@link install} gets the returned token.
301
+ */
302
+ prepare(input, entry) {
303
+ return this.exclusive(async () => {
304
+ this.collect();
305
+ const origin = entry === undefined || entry.length === 0
306
+ ? { kind: 'direct', input: input.trim() }
307
+ : { kind: 'marketplace', marketplace: input.trim(), marketIdentity: '', marketplaceName: '', entry };
308
+ return this.confirmation(await this.fetchCandidate(origin, this.fetcher.context('user', pastedHosts(input))));
309
+ });
310
+ }
311
+ /**
312
+ * Bind a staged candidate to a token and say what it contains (for an
313
+ * update, what changed). A candidate from the source of an installed plugin
314
+ * (the same identity) replaces that install when confirmed, as an update does.
315
+ */
316
+ confirmation(candidate, update, checked) {
317
+ try {
318
+ let replacing = update ?? this.installs().find(install => install.identity === candidate.identity);
319
+ let plugin = this.host.scan(candidate.root, candidate.dialect, replacing?.pluginId);
320
+ if (replacing !== undefined && plugin.id !== replacing.pluginId) {
321
+ if (update !== undefined)
322
+ throw new HarnessError('manifest-invalid', `the new revision is a different plugin (${plugin.id}, not ${update.pluginId})`, { suggestion: 'Remove the plugin and install the new one.' });
323
+ replacing = undefined;
324
+ plugin = this.host.scan(candidate.root, candidate.dialect);
325
+ }
326
+ let before;
327
+ let removed = [];
328
+ if (update !== undefined) {
329
+ try {
330
+ const current = this.host.scan(update.root, update.dialect);
331
+ before = partDigests(current);
332
+ const kept = new Set(plugin.components.map(partKey));
333
+ removed = current.components.filter(component => !kept.has(partKey(component))).map(component => component.name);
334
+ }
335
+ catch {
336
+ before = new Map();
337
+ }
338
+ }
339
+ const after = before !== undefined ? partDigests(plugin) : undefined;
340
+ const token = randomBytes(16).toString('hex');
341
+ const base = checked ?? (replacing === undefined ? undefined : baseOf(replacing));
342
+ this.pending.set(token, { candidate, name: plugin.displayName ?? plugin.name, at: Date.now(), ...(base !== undefined ? { base } : {}), explicit: update !== undefined });
343
+ const dependencyCount = candidate.npm === undefined ? undefined : Object.keys(candidate.npm.dependencies.dependencies).length + Object.keys(candidate.npm.dependencies.optionalDependencies).length;
344
+ const gaps = new Map();
345
+ const allGaps = assess(plugin).gaps;
346
+ for (const gap of allGaps)
347
+ if (gap.componentId !== undefined && !gaps.has(gap.componentId))
348
+ gaps.set(gap.componentId, gap.summary);
349
+ const changeOf = (key) => {
350
+ if (before === undefined || after === undefined)
351
+ return undefined;
352
+ const was = before.get(key);
353
+ return was === undefined ? 'new' : was !== after.get(key) ? 'changed' : undefined;
354
+ };
355
+ return {
356
+ token,
357
+ name: plugin.displayName ?? plugin.name,
358
+ ...(plugin.version !== undefined ? { version: plugin.version } : {}),
359
+ harness: plugin.source,
360
+ source: candidate.source,
361
+ ...(candidate.page !== undefined ? { page: candidate.page } : {}),
362
+ revision: short(candidate.revision),
363
+ ...(candidate.registry !== undefined ? { registry: candidate.registry } : {}),
364
+ ...(dependencyCount !== undefined ? { dependencies: dependencyCount } : {}),
365
+ parts: plugin.components.map((component) => {
366
+ const change = changeOf(partKey(component));
367
+ const reasons = gaps.has(component.id) ? partOf(component, allGaps, undefined, undefined).reasons : [];
368
+ return { kind: component.kind, name: component.name, ...(gaps.has(component.id) ? { gap: gaps.get(component.id) } : {}), ...(reasons.length > 0 ? { reasons } : {}), ...(change !== undefined ? { change } : {}) };
369
+ }),
370
+ codeParts: codePartsOf(plugin, allGaps),
371
+ works: plugin.components.filter(component => !gaps.has(component.id)).length,
372
+ total: plugin.components.length,
373
+ warnings: [...(candidate.warnings ?? []), ...plugin.warnings.map(warning => warning.message)],
374
+ pluginId: plugin.id,
375
+ alreadyInstalled: replacing !== undefined || this.host.installed(plugin.id),
376
+ ...(update !== undefined ? { update: { from: short(update.revision), to: short(candidate.revision), removed } } : {}),
377
+ };
378
+ }
379
+ catch (error) {
380
+ this.discard(candidate);
381
+ throw error;
382
+ }
383
+ }
384
+ /** Install (or, for an update, apply) exactly what {@link prepare} or {@link prepareUpdate} showed. */
385
+ install(token) {
386
+ return this.exclusive(() => this.installNow(token));
387
+ }
388
+ async installNow(token) {
389
+ const pending = this.pending.get(token);
390
+ if (pending === undefined)
391
+ throw new HarnessError('plan-not-found', 'this confirmation expired; open the plugin again', { suggestion: 'Choose Install again.' });
392
+ this.pending.delete(token);
393
+ const { candidate, base } = pending;
394
+ if (base !== undefined) {
395
+ // Bound to the copy it replaces: confirming an older plan after a newer one was applied would roll it back.
396
+ const now = this.state.installs.find(install => install.pluginId === base.pluginId);
397
+ if (pending.explicit && (now === undefined || !this.host.installed(base.pluginId))) {
398
+ this.discard(candidate);
399
+ throw new HarnessError('not-installed', `${base.pluginId} is no longer installed`);
400
+ }
401
+ if (now !== undefined && !sameBase(baseOf(now), base)) {
402
+ this.discard(candidate);
403
+ throw new HarnessError('plan-not-found', `${base.pluginId} changed since this was prepared (it is at ${short(now.revision)} now)`, { suggestion: pending.explicit ? 'Check for updates again.' : 'Open the plugin again.' });
404
+ }
405
+ }
406
+ // Named by its source, revision and files, so the same plugin fetched again shares the directory.
407
+ const finalDir = join(this.root, 'plugins', createHash('sha256').update(`${candidate.identity}\0${candidate.revision}\0${candidate.digest}`).digest('hex').slice(0, 32));
408
+ let root;
409
+ let result;
410
+ try {
411
+ // Bound to what the confirmation showed: anything else is not installed.
412
+ if (!existsSync(candidate.root) || treeDigest(candidate.root) !== candidate.digest) {
413
+ throw new HarnessError('fetch-failed', 'the fetched files changed after they were shown; open the plugin again');
414
+ }
415
+ let inStage = relative(candidate.stage, candidate.root);
416
+ if (candidate.npm !== undefined) {
417
+ await this.fetcher.npmDependencies(candidate.stage, candidate.npm.dependencies, candidate.registry, this.fetcher.context('user'));
418
+ // Beside its dependencies, where Node looks for them.
419
+ const placed = join(candidate.stage, 'node_modules', ...candidate.npm.name.split('/'));
420
+ mkdirSync(dirname(placed), { recursive: true });
421
+ renameSync(candidate.root, placed);
422
+ inStage = relative(candidate.stage, placed);
423
+ }
424
+ const user = this.state.installs.find(install => install.dir !== undefined && resolve(install.dir) === resolve(finalDir));
425
+ if (existsSync(finalDir) && user !== undefined) {
426
+ // The same source, revision and files are installed already, if the directory still holds what was installed.
427
+ if (user.digest === undefined || treeDigest(finalDir) !== user.digest)
428
+ throw new HarnessError('fetch-failed', `the installed copy of ${user.name} changed on disk; remove the plugin and install it again`);
429
+ rmSync(candidate.stage, { recursive: true, force: true });
430
+ }
431
+ else {
432
+ rmSync(finalDir, { recursive: true, force: true });
433
+ mkdirSync(dirname(finalDir), { recursive: true });
434
+ renameSync(candidate.stage, finalDir);
435
+ }
436
+ root = join(finalDir, inStage);
437
+ if (base !== undefined && (pending.explicit || this.host.installed(base.pluginId))) {
438
+ // An update, or the source of an installed plugin again: its copy is replaced, keeping its id and the parts switched off.
439
+ await this.host.reroot(base.pluginId, root, candidate.dialect);
440
+ result = { pluginId: base.pluginId };
441
+ }
442
+ else {
443
+ result = await this.host.install(root, candidate.dialect);
444
+ }
445
+ }
446
+ catch (error) {
447
+ this.discard(candidate);
448
+ if (!this.inUse(finalDir))
449
+ rmSync(finalDir, { recursive: true, force: true });
450
+ throw error;
451
+ }
452
+ const digest = treeDigest(finalDir);
453
+ const previous = this.state.installs.find(install => install.pluginId === result.pluginId);
454
+ this.state.installs = this.state.installs.filter(install => install.pluginId !== result.pluginId);
455
+ this.state.installs.push({
456
+ pluginId: result.pluginId,
457
+ name: pending.name,
458
+ dialect: candidate.dialect,
459
+ origin: candidate.origin,
460
+ identity: candidate.identity,
461
+ source: candidate.source,
462
+ ...(candidate.page !== undefined ? { page: candidate.page } : {}),
463
+ revision: candidate.revision,
464
+ ...(candidate.marketRevision !== undefined ? { marketRevision: candidate.marketRevision } : {}),
465
+ ...(candidate.integrity !== undefined ? { integrity: candidate.integrity } : {}),
466
+ ...(candidate.registry !== undefined ? { registry: candidate.registry } : {}),
467
+ root,
468
+ dir: finalDir,
469
+ digest,
470
+ installedAt: previous?.installedAt ?? new Date().toISOString(),
471
+ ...(previous !== undefined ? { updatedAt: new Date().toISOString() } : {}),
472
+ });
473
+ this.persist();
474
+ if (previous?.dir !== undefined && previous.dir !== finalDir)
475
+ this.deleteDir(previous.dir);
476
+ return { ...result, revision: short(candidate.revision), updated: pending.explicit };
477
+ }
478
+ /** Drop a confirmation that was not taken, with its files. */
479
+ cancel(token) {
480
+ const pending = this.pending.get(token);
481
+ if (pending === undefined)
482
+ return false;
483
+ this.pending.delete(token);
484
+ this.discard(pending.candidate);
485
+ return true;
486
+ }
487
+ // --- updates --------------------------------------------------------------------
488
+ /**
489
+ * Compare each install's revision with what its source points at now. An
490
+ * update found comes with a token: preparing it fetches exactly that
491
+ * revision. One failing source does not stop the others.
492
+ */
493
+ checkUpdates(pluginId) {
494
+ return this.exclusive(async () => {
495
+ this.collect();
496
+ const context = this.fetcher.context('user', pastedHosts(...this.installs().map(install => pastedOf(install.origin))));
497
+ const opened = new Map();
498
+ const out = [];
499
+ for (const install of this.installs()) {
500
+ if (pluginId !== undefined && install.pluginId !== pluginId)
501
+ continue;
502
+ try {
503
+ const pins = await this.latestPins(install, context, opened);
504
+ const update = pins !== undefined && (pins.revision !== install.revision || (pins.integrity !== undefined && pins.integrity !== install.integrity) || (pins.identity !== undefined && pins.identity !== install.identity));
505
+ let token;
506
+ if (update) {
507
+ token = randomBytes(16).toString('hex');
508
+ this.checks.set(token, { pins: pins, base: baseOf(install), at: Date.now() });
509
+ }
510
+ out.push({ pluginId: install.pluginId, name: install.name, current: short(install.revision), ...(pins !== undefined ? { latest: short(pins.revision) } : {}), update, ...(token !== undefined ? { token } : {}) });
511
+ }
512
+ catch (error) {
513
+ out.push({ pluginId: install.pluginId, name: install.name, current: short(install.revision), update: false, error: messageOf(error) });
514
+ }
515
+ }
516
+ return out;
517
+ });
518
+ }
519
+ /**
520
+ * Fetch the revision an update check found (the `token` it returned) and say
521
+ * what it contains and what changed; {@link install} applies it. Refused
522
+ * when the source no longer gives that revision.
523
+ */
524
+ prepareUpdate(pluginId, token) {
525
+ return this.exclusive(async () => {
526
+ this.collect();
527
+ const check = this.checks.get(token);
528
+ if (check === undefined || check.base.pluginId !== pluginId)
529
+ throw new HarnessError('plan-not-found', 'this update check expired; check for updates again', { suggestion: 'Choose Check for updates again.' });
530
+ this.checks.delete(token);
531
+ const install = this.installs().find(item => item.pluginId === pluginId);
532
+ if (install === undefined)
533
+ throw new HarnessError('not-installed', `${pluginId} was not installed from the network`);
534
+ // Bound to the copy the check compared: an update found against it does not apply to one installed since.
535
+ if (!sameBase(baseOf(install), check.base))
536
+ throw new HarnessError('plan-not-found', `${pluginId} changed since the check (it is at ${short(install.revision)} now)`, { suggestion: 'Check for updates again.' });
537
+ const candidate = await this.fetchCandidate(install.origin, this.fetcher.context('user', pastedHosts(pastedOf(install.origin))), check.pins);
538
+ if (check.pins.identity !== undefined && candidate.identity !== check.pins.identity) {
539
+ this.discard(candidate);
540
+ throw new HarnessError('fetch-failed', 'the marketplace changed where this plugin comes from since the check', { suggestion: 'Check for updates again.' });
541
+ }
542
+ return this.confirmation(candidate, install, check.base);
543
+ });
544
+ }
545
+ /** The plugin was removed from the ledger: forget its install and delete the files it used. */
546
+ released(pluginId) {
547
+ const install = this.state.installs.find(item => item.pluginId === pluginId);
548
+ if (install === undefined)
549
+ return;
550
+ this.state.installs = this.state.installs.filter(item => item.pluginId !== pluginId);
551
+ this.persist();
552
+ if (install.dir !== undefined)
553
+ this.deleteDir(install.dir);
554
+ }
555
+ /** What an install's source gives now, or undefined for a source that does not change (a local folder, an unpinned archive). */
556
+ async latestPins(install, context, opened) {
557
+ const origin = install.origin;
558
+ if (origin.kind === 'direct') {
559
+ const spec = parseRemoteInput(origin.input);
560
+ if (spec.kind === 'git')
561
+ return { revision: await this.fetcher.latest(spec, context) };
562
+ if (spec.kind === 'npm') {
563
+ const found = await this.fetcher.npmLatest(spec, context);
564
+ return { revision: found.version, integrity: found.integrity };
565
+ }
566
+ return undefined;
567
+ }
568
+ const marketSpec = parseRemoteInput(origin.marketplace);
569
+ let load = opened.get(origin.marketplace);
570
+ if (load === undefined) {
571
+ load = this.load(marketSpec, context);
572
+ opened.set(origin.marketplace, load);
573
+ }
574
+ const { index, revision } = await load;
575
+ const entry = index?.entries.find(item => item.name === origin.entry);
576
+ if (index === undefined || entry === undefined)
577
+ throw new HarnessError('entry-not-found', `the marketplace no longer lists ${origin.entry}`);
578
+ const identity = this.entryIdentity(specIdentity(marketSpec), index, entry);
579
+ const market = revision !== undefined ? { marketRevision: revision } : {};
580
+ if (entry.source.kind === 'path')
581
+ return revision === undefined ? undefined : { revision, ...market, identity };
582
+ const problem = this.problemOf(entry.source);
583
+ if (problem !== undefined)
584
+ throw new HarnessError('unsupported-source', `${entry.name}: ${problem}`);
585
+ const source = specOfSource(entry.source);
586
+ const entryContext = RemoteFetcher.as(context, 'marketplace');
587
+ if (source.kind === 'git')
588
+ return { revision: await this.fetcher.latest(source, entryContext), ...market, identity };
589
+ if (source.kind === 'npm') {
590
+ const found = await this.fetcher.npmLatest(source, entryContext);
591
+ return { revision: found.version, integrity: found.integrity, ...market, identity: `${specIdentity(marketSpec)}!${entry.name}!npm:${found.registry}:${found.name}` };
592
+ }
593
+ if (source.kind === 'archive' && source.sha256 !== undefined)
594
+ return { revision: source.sha256, ...market, identity };
595
+ return undefined;
596
+ }
597
+ // --- fetching one plugin -----------------------------------------------------------
598
+ /** A staging directory of its own, which only one candidate uses. */
599
+ newStage() {
600
+ const dir = join(this.root, 'staging', randomBytes(12).toString('hex'));
601
+ mkdirSync(dir, { recursive: true });
602
+ return dir;
603
+ }
604
+ /** Run `fill` in a new staging directory; the candidate it returns gets the digest of its root. On failure the directory goes. */
605
+ async staged(fill) {
606
+ const stage = this.newStage();
607
+ try {
608
+ const candidate = await fill(stage);
609
+ return { ...candidate, stage, digest: treeDigest(candidate.root) };
610
+ }
611
+ catch (error) {
612
+ rmSync(stage, { recursive: true, force: true });
613
+ throw error;
614
+ }
615
+ }
616
+ async fetchCandidate(origin, context, pins) {
617
+ if (origin.kind === 'direct') {
618
+ let spec = parseRemoteInput(origin.input);
619
+ if (spec.kind === 'json')
620
+ throw new HarnessError('unsupported-source', 'a marketplace.json lists plugins; choose one of them');
621
+ const identity = specIdentity(spec);
622
+ if (pins !== undefined && spec.kind === 'git') {
623
+ if (spec.sha !== undefined && spec.sha !== pins.revision)
624
+ throw changed('the pinned commit', spec.sha, pins.revision);
625
+ spec = { ...spec, sha: pins.revision };
626
+ }
627
+ if (pins !== undefined && spec.kind === 'npm')
628
+ spec = { ...spec, version: pins.revision };
629
+ return this.fetchSpec(spec, origin, context, { identity, ...(pins !== undefined ? { pins } : {}) });
630
+ }
631
+ const marketSpec = parseRemoteInput(origin.marketplace);
632
+ const marketIdentity = specIdentity(marketSpec);
633
+ const { index, revision, checkout } = await this.load(marketSpec, context, pins?.marketRevision);
634
+ if (index === undefined)
635
+ throw new HarnessError('manifest-not-found', `${describeSpec(marketSpec)} has no marketplace.json`);
636
+ if (pins?.marketRevision !== undefined && revision !== pins.marketRevision)
637
+ throw changed('the marketplace', revision ?? 'none', pins.marketRevision);
638
+ const entry = index.entries.find(item => item.name === origin.entry);
639
+ if (entry === undefined)
640
+ throw new HarnessError('entry-not-found', `marketplace ${index.name} has no plugin "${origin.entry}"`);
641
+ const resolvedOrigin = { kind: 'marketplace', marketplace: origin.marketplace, marketIdentity, marketplaceName: index.name, entry: entry.name };
642
+ const identity = this.entryIdentity(marketIdentity, index, entry);
643
+ const dialect = marketplaceHarness(index);
644
+ const page = pageOfSpec(marketSpec);
645
+ const market = revision !== undefined ? { marketRevision: revision } : {};
646
+ if (entry.source.kind === 'path' && entry.source.path !== undefined) {
647
+ const from = entry.source.path;
648
+ // A marketplace on this computer is another harness's folder, which it may refresh at any time: what is
649
+ // shown and installed is a copy taken from it once, like a checkout's, and the folder itself is never used.
650
+ const local = marketSpec.kind === 'local';
651
+ const boundary = local ? index.root : checkout;
652
+ if (!local && (checkout === undefined || revision === undefined))
653
+ throw new HarnessError('unsupported-source', `${entry.name} is inside a marketplace fetched by URL, which has no files`);
654
+ if (!local && pins !== undefined && pins.revision !== revision)
655
+ throw changed(entry.name, revision ?? 'none', pins.revision);
656
+ return this.staged(async (stage) => {
657
+ const root = join(stage, safeName(entry.name));
658
+ const skipped = copyTree(from, root, boundary);
659
+ this.applyEntry(root, entry, dialect);
660
+ return local
661
+ ? { root, dialect, origin: resolvedOrigin, identity, source: from, revision: LOCAL_REVISION, ...linkWarnings(skipped) }
662
+ : { root, dialect, origin: resolvedOrigin, identity, source: `${describeSpec(marketSpec)} → ${entry.name}`, ...(page !== undefined ? { page } : {}), revision: revision, ...market, ...linkWarnings(skipped) };
663
+ });
664
+ }
665
+ const problem = this.problemOf(entry.source);
666
+ if (problem !== undefined) {
667
+ throw new HarnessError('unsupported-source', entry.source.kind === 'command'
668
+ ? `${entry.name} is produced by running a command on this computer; Harness Forge does not run marketplace commands`
669
+ : `${entry.name}: ${problem}`);
670
+ }
671
+ let spec = specOfSource(entry.source);
672
+ if (pins !== undefined) {
673
+ if (spec.kind === 'git') {
674
+ if (spec.sha !== undefined && spec.sha !== pins.revision)
675
+ throw changed(entry.name, spec.sha, pins.revision);
676
+ spec = { ...spec, sha: pins.revision };
677
+ }
678
+ else if (spec.kind === 'npm')
679
+ spec = { ...spec, version: pins.revision };
680
+ else if (spec.kind === 'archive')
681
+ spec = { ...spec, sha256: pins.revision };
682
+ }
683
+ return this.fetchSpec(spec, resolvedOrigin, RemoteFetcher.as(context, 'marketplace'), { identity, entry, dialect, ...market, ...(pins !== undefined ? { pins } : {}), marketIdentity: `${marketIdentity}!${entry.name}` });
684
+ }
685
+ /** Fetch a git, npm or archive source into a staging directory of its own. */
686
+ async fetchSpec(spec, origin, context, options) {
687
+ const { entry, dialect: marketDialect, pins } = options;
688
+ const page = pageOfSpec(spec);
689
+ const common = { origin, identity: options.identity, source: describeSpec(spec), ...(page !== undefined ? { page } : {}), ...(options.marketRevision !== undefined ? { marketRevision: options.marketRevision } : {}) };
690
+ switch (spec.kind) {
691
+ case 'local': {
692
+ // A folder on this computer is copied like a checkout: what is shown and installed cannot change under it.
693
+ const from = homePath(spec.path);
694
+ return this.staged(async (stage) => {
695
+ const root = join(stage, safeName(basename(from)));
696
+ const skipped = copyTree(from, root);
697
+ return { ...common, root, dialect: marketDialect ?? detectSource(root), revision: LOCAL_REVISION, ...linkWarnings(skipped) };
698
+ });
699
+ }
700
+ case 'git': {
701
+ const { dir: checkout, sha } = await this.fetcher.checkout(spec, context);
702
+ if (pins !== undefined && sha !== pins.revision)
703
+ throw changed('the source', sha, pins.revision);
704
+ const from = RemoteFetcher.inside(checkout, spec.subpath);
705
+ const name = entry?.name ?? (spec.subpath !== undefined ? basename(spec.subpath) : spec.github?.repo ?? basename(spec.url).replace(/\.git$/u, ''));
706
+ const dialect = marketDialect ?? detectSource(from);
707
+ return this.staged(async (stage) => {
708
+ const root = join(stage, safeName(name));
709
+ const skipped = copyTree(from, root, checkout);
710
+ if (entry !== undefined)
711
+ this.applyEntry(root, entry, dialect);
712
+ return { ...common, root, dialect, revision: sha, ...linkWarnings(skipped) };
713
+ });
714
+ }
715
+ case 'npm': {
716
+ const found = await this.fetcher.npmLatest(spec, context);
717
+ if (pins !== undefined && found.version !== pins.revision)
718
+ throw changed(spec.package, found.version, pins.revision);
719
+ if (pins?.integrity !== undefined && found.integrity !== pins.integrity)
720
+ throw new HarnessError('fetch-failed', `${spec.package}@${found.version} is not the tarball that was checked`, { suggestion: 'Check for updates again.' });
721
+ const registryIdentity = `npm:${found.registry}:${found.name}`;
722
+ return this.staged(async (stage) => {
723
+ const { dir, manifest } = await this.fetcher.npmFetch(found, stage, context);
724
+ const dependencies = dependenciesOf(manifest);
725
+ if (entry !== undefined && marketDialect !== undefined)
726
+ this.applyEntry(dir, entry, marketDialect);
727
+ return {
728
+ ...common,
729
+ identity: options.marketIdentity !== undefined ? `${options.marketIdentity}!${registryIdentity}` : registryIdentity,
730
+ source: `npm:${found.name}@${found.version}`,
731
+ page: npmPage(found.registry, found.name, found.version),
732
+ root: dir,
733
+ dialect: marketDialect ?? detectSource(dir),
734
+ revision: found.version,
735
+ integrity: found.integrity,
736
+ registry: found.registry,
737
+ npm: { name: found.name, dependencies },
738
+ };
739
+ });
740
+ }
741
+ case 'archive':
742
+ return this.staged(async (stage) => {
743
+ const { root, digest } = await this.fetcher.archive(spec, join(stage, 'archive'), context);
744
+ if (entry !== undefined && marketDialect !== undefined)
745
+ this.applyEntry(root, entry, marketDialect);
746
+ return { ...common, root, dialect: marketDialect ?? detectSource(root), revision: digest };
747
+ });
748
+ case 'json':
749
+ throw new HarnessError('unsupported-source', 'a marketplace.json lists plugins; choose one of them');
750
+ }
751
+ }
752
+ /**
753
+ * A Claude Code marketplace entry is also manifest (code.claude.com, "How an
754
+ * entry combines with plugin.json"): with no `plugin.json`, the entry is the
755
+ * manifest; with one, the entry's component fields are added to it unless the
756
+ * entry says `"strict": false`, where they conflict. The copy is Harness
757
+ * Forge's own, so the combined manifest is written into it and read by the
758
+ * scanner like any other.
759
+ */
760
+ applyEntry(root, entry, dialect) {
761
+ if (dialect !== 'claude-code')
762
+ return;
763
+ const path = join(root, '.claude-plugin', 'plugin.json');
764
+ const fields = entry.fields;
765
+ const own = existsSync(path) ? (() => {
766
+ try {
767
+ const value = JSON.parse(readFileSync(path, 'utf8'));
768
+ return isPlainObject(value) ? value : undefined;
769
+ }
770
+ catch {
771
+ return undefined;
772
+ }
773
+ })() : undefined;
774
+ const declared = COMPONENT_FIELDS.filter(key => fields[key] !== undefined);
775
+ if (own !== undefined) {
776
+ if (declared.length === 0)
777
+ return;
778
+ if (fields['strict'] === false)
779
+ throw new HarnessError('manifest-invalid', `Plugin ${entry.name} has conflicting manifests: both plugin.json and marketplace entry specify components`);
780
+ const merged = { ...own };
781
+ for (const key of declared) {
782
+ if (key === 'hooks') {
783
+ merged['hooks'] = isPlainObject(fields['hooks']) && isPlainObject(own['hooks']) ? { ...own['hooks'], ...fields['hooks'] } : fields['hooks'];
784
+ continue;
785
+ }
786
+ const list = (value) => value === undefined ? [] : Array.isArray(value) ? value : [value];
787
+ // Appended paths supplement the default directory; the scanner reads an explicit command list instead of it, so it is named.
788
+ merged[key] = [...list(own[key] ?? (key === 'commands' ? './commands' : undefined)), ...list(fields[key])];
789
+ }
790
+ writeFileSync(path, `${JSON.stringify(merged, null, 2)}\n`, 'utf8');
791
+ return;
792
+ }
793
+ const manifest = { name: entry.name };
794
+ for (const [key, value] of Object.entries(fields))
795
+ if (!ENTRY_ONLY.has(key))
796
+ manifest[key] = value;
797
+ mkdirSync(join(root, '.claude-plugin'), { recursive: true });
798
+ writeFileSync(path, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
799
+ }
800
+ // --- files ------------------------------------------------------------------------
801
+ /** Whether an install uses a directory under `plugins/`. */
802
+ inUse(dir) {
803
+ const target = resolve(dir);
804
+ return this.state.installs.some(install => install.dir !== undefined && resolve(install.dir) === target);
805
+ }
806
+ /** Delete a candidate's staging directory; it is the candidate's alone. */
807
+ discard(candidate) {
808
+ const staging = resolve(this.root, 'staging');
809
+ if (isInside(staging, resolve(candidate.stage)))
810
+ rmSync(candidate.stage, { recursive: true, force: true });
811
+ }
812
+ /** Delete an installed copy under `plugins/` once no install uses it. Never anything outside it. */
813
+ deleteDir(dir) {
814
+ const plugins = resolve(this.root, 'plugins');
815
+ const target = resolve(dir);
816
+ if (!isInside(plugins, target) || this.inUse(target))
817
+ return;
818
+ rmSync(target, { recursive: true, force: true });
819
+ }
820
+ /**
821
+ * Drop expired confirmations and update checks, staging directories no
822
+ * confirmation holds, copies no install uses (an interrupted install), and
823
+ * all but the newest checkout of each source. Runs inside the queue, so no
824
+ * fetch is writing or reading them.
825
+ */
826
+ collect() {
827
+ const now = Date.now();
828
+ for (const [token, pending] of this.pending) {
829
+ if (now - pending.at < PENDING_MS)
830
+ continue;
831
+ this.pending.delete(token);
832
+ this.discard(pending.candidate);
833
+ }
834
+ for (const [token, check] of this.checks)
835
+ if (now - check.at >= PENDING_MS)
836
+ this.checks.delete(token);
837
+ const held = new Set([...this.pending.values()].map(pending => resolve(pending.candidate.stage)));
838
+ const used = new Set(this.state.installs.flatMap(install => install.dir !== undefined ? [resolve(install.dir)] : []));
839
+ const sweep = (parent, keep) => {
840
+ if (!existsSync(parent))
841
+ return;
842
+ for (const name of readdirSync(parent)) {
843
+ const path = resolve(parent, name);
844
+ if (!keep(path))
845
+ rmSync(path, { recursive: true, force: true });
846
+ }
847
+ };
848
+ sweep(join(this.root, 'staging'), path => held.has(path));
849
+ sweep(join(this.root, 'plugins'), path => used.has(path));
850
+ const git = join(this.root, 'cache', 'git');
851
+ if (!existsSync(git))
852
+ return;
853
+ for (const key of readdirSync(git)) {
854
+ const keyDir = join(git, key);
855
+ let checkouts;
856
+ try {
857
+ checkouts = readdirSync(keyDir).map(name => ({ path: join(keyDir, name), at: statSync(join(keyDir, name)).mtimeMs }));
858
+ }
859
+ catch {
860
+ continue;
861
+ }
862
+ const newest = checkouts.filter(item => !basename(item.path).startsWith('.tmp-')).sort((a, b) => b.at - a.at)[0];
863
+ for (const item of checkouts)
864
+ if (item !== newest)
865
+ rmSync(item.path, { recursive: true, force: true });
866
+ }
867
+ }
868
+ }