@kirkchinese/harness-forge-core 0.4.0 → 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 (56) hide show
  1. package/lib/assess.js +24 -4
  2. package/lib/contracts.d.ts +1 -1
  3. package/lib/dialects/claude-code/index.js +38 -41
  4. package/lib/dialects/claude-code/sessions/discover.js +31 -17
  5. package/lib/dialects/claude-code/sessions/parse.js +89 -83
  6. package/lib/dialects/claude-code/sessions/title.d.ts +23 -0
  7. package/lib/dialects/claude-code/sessions/title.js +74 -0
  8. package/lib/dialects/claude-code/statusline.d.ts +12 -0
  9. package/lib/dialects/claude-code/statusline.js +74 -0
  10. package/lib/dialects/claude-code/user-assets.d.ts +37 -6
  11. package/lib/dialects/claude-code/user-assets.js +155 -34
  12. package/lib/dialects/codex/index.js +8 -1
  13. package/lib/dialects/codex/mcp-server.d.ts +17 -0
  14. package/lib/dialects/codex/mcp-server.js +116 -0
  15. package/lib/dialects/codex/plugins.d.ts +16 -0
  16. package/lib/dialects/codex/plugins.js +120 -0
  17. package/lib/dialects/codex/user-assets.d.ts +10 -6
  18. package/lib/dialects/codex/user-assets.js +26 -42
  19. package/lib/dialects/opencode/index.js +43 -8
  20. package/lib/dialects/opencode/inventory.d.ts +100 -0
  21. package/lib/dialects/opencode/inventory.js +318 -0
  22. package/lib/dialects/opencode/plugin-id.d.ts +21 -0
  23. package/lib/dialects/opencode/plugin-id.js +296 -0
  24. package/lib/dialects/opencode/scan.d.ts +22 -0
  25. package/lib/dialects/opencode/scan.js +119 -121
  26. package/lib/dialects/types.d.ts +60 -6
  27. package/lib/discover.d.ts +32 -7
  28. package/lib/discover.js +58 -17
  29. package/lib/fingerprint.js +7 -0
  30. package/lib/harness-installs.d.ts +42 -0
  31. package/lib/harness-installs.js +59 -0
  32. package/lib/index.d.ts +6 -0
  33. package/lib/index.js +5 -0
  34. package/lib/instructions.d.ts +28 -2
  35. package/lib/instructions.js +202 -30
  36. package/lib/license.js +12 -11
  37. package/lib/manifest.d.ts +6 -0
  38. package/lib/manifest.js +41 -12
  39. package/lib/marketplace.d.ts +15 -1
  40. package/lib/marketplace.js +55 -38
  41. package/lib/paths.d.ts +65 -0
  42. package/lib/paths.js +152 -2
  43. package/lib/plan.js +3 -1
  44. package/lib/port-brief.d.ts +28 -5
  45. package/lib/port-brief.js +52 -10
  46. package/lib/remote.d.ts +121 -0
  47. package/lib/remote.js +352 -0
  48. package/lib/sessions/index.d.ts +1 -0
  49. package/lib/sessions/index.js +1 -0
  50. package/lib/sessions/lines.d.ts +57 -0
  51. package/lib/sessions/lines.js +122 -0
  52. package/lib/text.d.ts +9 -0
  53. package/lib/text.js +19 -0
  54. package/lib/trust.js +19 -6
  55. package/lib/types.d.ts +48 -1
  56. package/package.json +1 -1
package/lib/port-brief.js CHANGED
@@ -7,6 +7,8 @@
7
7
  */
8
8
  import { isAbsolute, join } from 'node:path';
9
9
  import { kebabCase } from './naming.js';
10
+ /** The DSH home when `$DSH_HOME` is not set, as the user would type it. */
11
+ export const DEFAULT_DSH_HOME = '~/.dsh';
10
12
  /** Longest manifest excerpt quoted in a brief, in characters. */
11
13
  const MANIFEST_LIMIT = 4_000;
12
14
  /** The npm name of the adapter for one part: unscoped, `dsh-adapter-<plugin>-<part>`. */
@@ -15,13 +17,11 @@ export function adapterPackageName(plugin, component) {
15
17
  const part = kebabCase(component.name);
16
18
  return `dsh-adapter-${part === pluginName || part.length === 0 ? pluginName : `${pluginName}-${part}`}`;
17
19
  }
18
- /**
19
- * Where the creator suggests authoring the adapter, as the user would type it:
20
- * outside every workspace and the original plugin, so it survives both and the
21
- * local install keeps pointing at it.
22
- */
20
+ /** Directory under the user's home where creation sessions author local adapters by default. */
21
+ export const ADAPTERS_DIR = 'dsh-adapters';
22
+ /** Where the creator suggests authoring the adapter, as the user would type it. */
23
23
  export function defaultAdapterDir(packageName) {
24
- return `~/dsh-adapters/${packageName}`;
24
+ return `~/${ADAPTERS_DIR}/${packageName}`;
25
25
  }
26
26
  /** The gaps a brief is about: the component's own, without license and version notes. */
27
27
  export function gapsOf(component, gaps) {
@@ -86,6 +86,9 @@ export function extensionPointsFor(component, gaps) {
86
86
  const kinds = new Set(gaps.map(gap => gap.kind));
87
87
  if (component.kind === 'ui' || kinds.has('ui-surface')) {
88
88
  points.add('Client UI plugin: a React component registered into a Web slot through `ctx.slots` (dsh-doc `references/ui-plugin.md`), styled with the `--dsw-alias-*` theme tokens');
89
+ if (component.kind === 'ui' && component.surface === 'statusline') {
90
+ points.add('For the default Web status-line placement, look for the session-scoped `conversation.composer.dock` slot below the composer; confirm it at runtime after the user replies');
91
+ }
89
92
  points.add('Host session projection with `wire.view`, so the Client receives a value already derived from the session log');
90
93
  points.add('A Host Remote namespace (a `TypertRemoteService`) when the Client half needs Host data that is not a session projection');
91
94
  }
@@ -118,10 +121,10 @@ export function extensionPointsFor(component, gaps) {
118
121
  export function openQuestionsFor(component, gaps) {
119
122
  const questions = [];
120
123
  if (component.kind === 'ui' && component.surface === 'statusline') {
121
- questions.push('Where the status line shows: DSH draws none of its own and several Web slots could hold one line per session (confirm their names with `cordis_inspect_query` before asking). Default: the slot nearest to where Claude Code draws it, one line under the message input.');
124
+ questions.push('Where the status line shows in the DSH Web UI. Default: just below the message input.');
122
125
  }
123
126
  else if (component.kind === 'ui' && component.surface !== 'output-style') {
124
- questions.push(`Where the ${component.surface} surface appears in the DSH Web UI, when more than one slot fits (confirm slot names with \`cordis_inspect_query\` first). Default: the slot closest to where the original shows it.`);
127
+ questions.push(`Where the ${component.surface} surface appears in the DSH Web UI. Default: as close as possible to where the original shows it.`);
125
128
  }
126
129
  for (const gap of gaps) {
127
130
  if (gap.kind === 'unsupported-event')
@@ -133,6 +136,33 @@ export function openQuestionsFor(component, gaps) {
133
136
  }
134
137
  const bullet = (line) => `- ${line}`;
135
138
  const code = (path) => `\`${path}\``;
139
+ /**
140
+ * Where this DSH keeps its data, and how the adapter finds the same at run
141
+ * time (dsh-doc `references/plugin-development.md` and the `profileContext`
142
+ * and shell environment DSH provides). The resolved values are for the
143
+ * creator's checks only: the adapter's source must resolve them itself.
144
+ */
145
+ export function dataLocationLines(runtime) {
146
+ const facts = runtime === undefined
147
+ ? [bullet(`DSH home: \`$DSH_HOME\` (default \`${DEFAULT_DSH_HOME}\`); the profile is the one DSH runs. Find both as below.`)]
148
+ : [
149
+ bullet(`DSH home: ${code(runtime.dshHome)} (${runtime.dshHomeFromEnv ? 'from `$DSH_HOME`' : `the default \`${DEFAULT_DSH_HOME}\`; \`$DSH_HOME\` is not set`})`),
150
+ bullet(runtime.profile === undefined
151
+ ? 'Current profile: none (DSH was started without a profile)'
152
+ : `Current profile: \`${runtime.profile.name}\`, directory ${code(runtime.profile.dir)}`),
153
+ ];
154
+ return [
155
+ ...facts,
156
+ bullet('These values are this session\'s, for your checks. The adapter finds them at run time: a Host plugin reads the profile from `ctx.get(\'profileContext\')` (`name`, `dir`; present only when DSH runs a profile) and the home from `process.env.DSH_HOME`, else `~/.dsh` under `os.homedir()`; a shell command reads `$DSH_PROFILE`, `$DSH_PROFILE_DIR` and `$DSH_HOME`. A Client plugin gets session data from its slot context and Host projections, not from files.'),
157
+ ];
158
+ }
159
+ /** The rules every adapter keeps when it touches session, profile or harness data. */
160
+ export const DATA_RULES = [
161
+ 'Use DSH\'s runtime services and the context the adapter receives for session and profile data wherever DSH offers them (a Host projection with `wire.view`, a Host service, the slot\'s session, `profileContext`), not the files behind them.',
162
+ `When a file path is truly needed, resolve it at run time from \`$DSH_HOME\` (default \`${DEFAULT_DSH_HOME}\`) and the profile DSH runs, never a hard-coded home path such as \`~/.dsh\` or \`/home/<user>/.dsh\`.`,
163
+ 'Never read or iterate other profiles: no listing of `profiles/`, no guessing a profile by name; only the profile DSH runs.',
164
+ 'Never read another harness\'s or DSH\'s private files beyond what the part needs: no other sessions, credentials, settings or logs it does not show.',
165
+ ];
136
166
  /**
137
167
  * Write the brief for one part, as Markdown. It names the original's files
138
168
  * by absolute path so the adapter reuses them where it can.
@@ -193,6 +223,16 @@ export function portBrief(input) {
193
223
  '',
194
224
  ...extensionPointsFor(component, gaps).map(bullet),
195
225
  '',
226
+ '## Where DSH keeps its data',
227
+ '',
228
+ ...dataLocationLines(input.runtime),
229
+ '',
230
+ '## Data access rules',
231
+ '',
232
+ 'Firm rules; an adapter that breaks one is not done:',
233
+ '',
234
+ ...DATA_RULES.map(bullet),
235
+ '',
196
236
  '## Questions for the user',
197
237
  '',
198
238
  bullet(`Where the adapter's source lives. Default: \`${defaultAdapterDir(packageName)}\`.`),
@@ -202,10 +242,11 @@ export function portBrief(input) {
202
242
  '',
203
243
  bullet('In a DSH session of this profile, the behaviour from your one-sentence description happens: the tool answers, the command runs, the hook acts on the event, or the surface draws.'),
204
244
  bullet(`The adapter calls or loads the original's own code and data from ${code(plugin.root)} wherever it can, rather than copying or re-implementing them; anything it had to re-implement is listed in its README.`),
205
- bullet('The adapter loads without errors (check the plugin list and the Host log) and disabling it in the Plugin Manager removes everything it registered.'),
245
+ bullet('The adapter loads without errors (check `plugin_manager` `list_bundles` and `cordis_inspect_query`) and disabling it in the Plugin Manager removes everything it registered.'),
206
246
  bullet(`Its \`package.json\` declares \`"harnessForge": { "ports": [{ "plugin": ${JSON.stringify(plugin.name)}, "component": ${JSON.stringify(component.name)} }] }\`, so Harness Forge shows this part as covered by the adapter.`),
207
247
  bullet('Its README says what it restores, how it finds the original plugin, and every remaining difference from the original.'),
208
- bullet(`\`harness_verify_port\` with \`${JSON.stringify({ pluginId: plugin.id, componentId: component.id })}\` answers \`"covered": true\`.`),
248
+ bullet(`\`harness_verify_port\` with \`${JSON.stringify({ pluginId: plugin.id, componentId: component.id })}\` answers \`"covered": true\`; its \`paths\` check finds no hard-coded DSH home and no scan of \`profiles/\` in the adapter's source.`),
249
+ bullet('It keeps the data access rules above: run it with `$DSH_HOME` pointing elsewhere and it still reads only the running profile\'s data.'),
209
250
  '',
210
251
  '## Constraints',
211
252
  '',
@@ -213,6 +254,7 @@ export function portBrief(input) {
213
254
  bullet('Install it as a LOCAL plugin into the current profile only (`plugin_manager` `install_bundle` with the absolute package directory). Do not install it anywhere else.'),
214
255
  bullet('Publishing is optional: publish nothing unless the user explicitly asks, and then only under the user\'s own npm scope.'),
215
256
  bullet(`Respect the original's license (${license ?? 'unknown: ask the user before reusing any of its code'}): keep its copyright and license notices for anything reused, and credit ${plugin.name} in the README.`),
257
+ bullet('Verify what the page shows with `cordis_inspect_query` (Client `Slots.listSubTree`) or by asking the user. Never read DSH\'s access token or logs, `/proc` of another process, or another process\'s files, and never drive a browser with credentials taken from them.'),
216
258
  bullet('Put no token or session data into the adapter. If the user later wants to publish it, it must find the original at run time instead of by a path of this machine.'),
217
259
  ];
218
260
  return `${lines.join('\n')}\n`;
@@ -0,0 +1,121 @@
1
+ import type { MarketplaceSource } from './marketplace.js';
2
+ /** A git repository, or one directory of it. */
3
+ export interface GitSpec {
4
+ readonly kind: 'git';
5
+ /** Clone URL. */
6
+ readonly url: string;
7
+ /** Branch or tag; the default branch when absent. */
8
+ readonly ref?: string;
9
+ /** Full commit SHA this source is pinned to. */
10
+ readonly sha?: string;
11
+ /** Directory of the plugin inside the repository. */
12
+ readonly subpath?: string;
13
+ /** Set when the repository is on GitHub: allows the HTTPS archive fallback when git is missing. */
14
+ readonly github?: {
15
+ readonly owner: string;
16
+ readonly repo: string;
17
+ };
18
+ }
19
+ /** A `marketplace.json` served over HTTP(S). Its entries cannot use relative paths. */
20
+ export interface JsonSpec {
21
+ readonly kind: 'json';
22
+ readonly url: string;
23
+ }
24
+ /** An npm package. */
25
+ export interface NpmSpec {
26
+ readonly kind: 'npm';
27
+ readonly package: string;
28
+ /** Version, range or dist-tag; `latest` when absent. */
29
+ readonly version?: string;
30
+ readonly registry?: string;
31
+ }
32
+ /** A zip archive over HTTPS (a Claude Code `archive` plugin source). */
33
+ export interface ArchiveSpec {
34
+ readonly kind: 'archive';
35
+ readonly url: string;
36
+ readonly sha256?: string;
37
+ }
38
+ /** A folder on this computer. */
39
+ export interface LocalSpec {
40
+ readonly kind: 'local';
41
+ readonly path: string;
42
+ }
43
+ /** Where something to install comes from. */
44
+ export type RemoteSpec = GitSpec | JsonSpec | NpmSpec | ArchiveSpec | LocalSpec;
45
+ /** A marketplace Harness Forge lists ready to browse; each is confirmed from its publisher's documentation. */
46
+ export interface DefaultMarketplace {
47
+ /** The marketplace's `name`, as its harness shows it. */
48
+ readonly id: string;
49
+ /** What the person would paste for it. */
50
+ readonly input: string;
51
+ readonly harness: 'claude-code' | 'codex';
52
+ /** Where its publisher documents it. */
53
+ readonly docs: string;
54
+ }
55
+ /**
56
+ * Anthropic's official and community marketplaces and its two topic marketplaces
57
+ * (https://code.claude.com/docs/en/plugins/anthropic-marketplaces), and OpenAI's
58
+ * curated Codex plugins (https://developers.openai.com/codex/plugins/build).
59
+ */
60
+ export declare const DEFAULT_MARKETPLACES: readonly DefaultMarketplace[];
61
+ /** Whether a string is a full (40 hex digit) commit SHA. */
62
+ export declare function isFullSha(value: string): boolean;
63
+ /**
64
+ * Whether a branch or tag name is one git accepts (`git check-ref-format`) and
65
+ * cannot be read as an option: no leading `-`, no `..`, `@{`, `//`, control
66
+ * characters, spaces or `~^:?*[\`, no component starting with `.` or ending
67
+ * with `.lock`, and not ending with `/` or `.`.
68
+ */
69
+ export declare function isValidRef(ref: string): boolean;
70
+ /** Whether an npm version, range or dist-tag stays a registry lookup (never a git, URL or path spec). */
71
+ export declare function isRegistryRange(value: string): boolean;
72
+ /** The GitHub repository a clone URL names, or undefined for another host. */
73
+ export declare function githubOf(url: string): {
74
+ owner: string;
75
+ repo: string;
76
+ } | undefined;
77
+ /**
78
+ * Read what a person pasted.
79
+ * @throws {HarnessError} `unsupported-source` when it names nothing Harness Forge can fetch.
80
+ */
81
+ export declare function parseRemoteInput(raw: string): RemoteSpec;
82
+ /** The transport a git URL uses: `https`, `http`, `ssh` (also `user@host:path`), `git`, `file`, or undefined for anything else. */
83
+ export declare function gitTransport(url: string): 'https' | 'http' | 'ssh' | 'git' | 'file' | undefined;
84
+ /**
85
+ * Where a marketplace entry's plugin is fetched from, or undefined for an entry
86
+ * inside the marketplace (a `path` source) and for sources Harness Forge does not
87
+ * fetch (`command`: it would run a command from the marketplace on this computer).
88
+ */
89
+ export declare function specOfSource(source: MarketplaceSource): RemoteSpec | undefined;
90
+ /**
91
+ * Why Harness Forge does not fetch what a marketplace entry names, or undefined
92
+ * when it does: a marketplace may not steer Harness Forge to another transport
93
+ * (`ssh`, `file`, `ext::`…) than HTTPS, to an unpinned commit it claims to pin,
94
+ * to a ref git could read as an option, out of the repository, or (for npm) to
95
+ * a spec that is not a registry lookup. Which registry it may name is decided
96
+ * when it is fetched, against the person's configuration.
97
+ */
98
+ export declare function marketplaceProblem(spec: RemoteSpec): string | undefined;
99
+ /**
100
+ * Why an npm dependency spec is not installed, or undefined when it is a
101
+ * registry lookup (a version, range or tag, or an `npm:name@range` alias).
102
+ * Git, GitHub, `file:`, `link:`, `workspace:` and URL specs are refused: npm
103
+ * fetches them from elsewhere and may run their `prepare` script to build them.
104
+ */
105
+ export declare function dependencyProblem(name: string, spec: string): string | undefined;
106
+ /** The source a fetched plugin is known by: what installed status and stored copies are keyed by. */
107
+ export declare function specIdentity(spec: RemoteSpec): string;
108
+ /** One line naming a source for the person: `github.com/owner/repo@ref/path`, a URL, `npm:name@version`. */
109
+ export declare function describeSpec(spec: RemoteSpec): string;
110
+ /** The web page of a source, when it has one: what the confirmation links to. */
111
+ export declare function pageOfSpec(spec: RemoteSpec): string | undefined;
112
+ /** npm's own registry: the one a marketplace may name besides the person's configured registry. */
113
+ export declare const NPM_REGISTRY = "https://registry.npmjs.org/";
114
+ /** A registry URL with one trailing slash, scheme and host lowercased; undefined when it is not an http(s) URL. */
115
+ export declare function normalizeRegistry(registry: string): string | undefined;
116
+ /** The page of an npm package version on the registry it comes from: npmjs.com for npm's own, else the registry's document of it. */
117
+ export declare function npmPage(registry: string, name: string, version: string): string;
118
+ /** The GitHub archive URL of a ref or commit (`HEAD` for the default branch). */
119
+ export declare function githubTarball(owner: string, repo: string, ref?: string): string;
120
+ /** The GitHub API URL that answers a ref's commit SHA as plain text (with `Accept: application/vnd.github.sha`). */
121
+ export declare function githubCommitApi(owner: string, repo: string, ref?: string): string;
package/lib/remote.js ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * What a person pastes to get a plugin from the network, and where each
3
+ * marketplace entry's plugin is fetched from. Pure: no network, no disk.
4
+ *
5
+ * - `owner/repo`, `owner/repo@ref`, `owner/repo#ref`, `github:owner/repo` and
6
+ * `https://github.com/owner/repo[/tree/<ref>/<path>]` name a GitHub repository
7
+ * (a marketplace, or a single plugin).
8
+ * - Any other `https://`, `http://`, `ssh://`, `git@host:path` or `file://` URL
9
+ * is a git repository (`#ref` pins a ref), except an `http(s)` URL ending in
10
+ * `.json`, which is a hosted `marketplace.json`.
11
+ * - `@scope/name`, `name`, `name@version`, `npm:<spec>` and
12
+ * `https://www.npmjs.com/package/<name>` are npm packages (OpenCode plugins).
13
+ * - An absolute or `./`/`~` path is a local folder.
14
+ *
15
+ * What a person pastes may name any host they choose. What a marketplace names
16
+ * is the marketplace's say-so: {@link marketplaceProblem} limits it to HTTPS
17
+ * (and npm's registry), full commit SHAs and well-formed refs.
18
+ * @module @kirkchinese/harness-forge-core
19
+ */
20
+ import { HarnessError } from './contracts.js';
21
+ import { stripTrailing } from './text.js';
22
+ /**
23
+ * Anthropic's official and community marketplaces and its two topic marketplaces
24
+ * (https://code.claude.com/docs/en/plugins/anthropic-marketplaces), and OpenAI's
25
+ * curated Codex plugins (https://developers.openai.com/codex/plugins/build).
26
+ */
27
+ export const DEFAULT_MARKETPLACES = [
28
+ { id: 'claude-plugins-official', input: 'anthropics/claude-plugins-official', harness: 'claude-code', docs: 'https://code.claude.com/docs/en/plugins/anthropic-marketplaces' },
29
+ { id: 'claude-community', input: 'anthropics/claude-plugins-community', harness: 'claude-code', docs: 'https://code.claude.com/docs/en/plugins/anthropic-marketplaces' },
30
+ { id: 'anthropic-agent-skills', input: 'anthropics/skills', harness: 'claude-code', docs: 'https://code.claude.com/docs/en/plugins/anthropic-marketplaces' },
31
+ { id: 'knowledge-work-plugins', input: 'anthropics/knowledge-work-plugins', harness: 'claude-code', docs: 'https://code.claude.com/docs/en/plugins/anthropic-marketplaces' },
32
+ { id: 'openai-curated', input: 'openai/plugins', harness: 'codex', docs: 'https://developers.openai.com/codex/plugins/build' },
33
+ ];
34
+ const OWNER = '[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})';
35
+ const REPO = '[A-Za-z0-9._-]+';
36
+ // One optional `/sub/path` group (its class includes `/`): `(?:/[^@#\s]+)*` matches the same text but backtracks exponentially.
37
+ const SHORTHAND = new RegExp(`^(?:github:)?(${OWNER})/(${REPO}?)((?:/[^@#\\s]+)?)(?:[@#](\\S+))?$`, 'u');
38
+ /** npm's package name rules, loosely: lowercase, URL-safe, optional scope. */
39
+ const NPM_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/u;
40
+ const SHA = /^[0-9a-f]{40}$/u;
41
+ /** An npm version, range or dist-tag: never a URL, a path or a git spec (no `/`, no `:`). */
42
+ const NPM_RANGE = /^[\w.^~<>=|*+\-\s]*$/u;
43
+ /** Whether a string is a full (40 hex digit) commit SHA. */
44
+ export function isFullSha(value) {
45
+ return SHA.test(value);
46
+ }
47
+ /**
48
+ * Whether a branch or tag name is one git accepts (`git check-ref-format`) and
49
+ * cannot be read as an option: no leading `-`, no `..`, `@{`, `//`, control
50
+ * characters, spaces or `~^:?*[\`, no component starting with `.` or ending
51
+ * with `.lock`, and not ending with `/` or `.`.
52
+ */
53
+ export function isValidRef(ref) {
54
+ if (ref.length === 0 || ref.length > 255 || ref === '@')
55
+ return false;
56
+ if (!/^[A-Za-z0-9._/@+-]+$/u.test(ref) || ref.startsWith('-') || ref.startsWith('/') || ref.endsWith('/') || ref.endsWith('.'))
57
+ return false;
58
+ if (ref.includes('..') || ref.includes('@{') || ref.includes('//'))
59
+ return false;
60
+ return ref.split('/').every(part => part.length > 0 && !part.startsWith('.') && !part.endsWith('.lock'));
61
+ }
62
+ /** Whether an npm version, range or dist-tag stays a registry lookup (never a git, URL or path spec). */
63
+ export function isRegistryRange(value) {
64
+ return NPM_RANGE.test(value) && !value.trim().startsWith('-');
65
+ }
66
+ /** Whether a directory inside a repository stays inside it and cannot be read as an option. */
67
+ function isSafeSubpath(path) {
68
+ const parts = path.split(/[\\/]/u);
69
+ return !path.startsWith('-') && !path.startsWith('/') && !/^[A-Za-z]:/u.test(path) && !parts.includes('..');
70
+ }
71
+ function invalid(input, why) {
72
+ return new HarnessError('unsupported-source', `${why}: ${input}`, {
73
+ suggestion: 'Paste owner/repo, a git URL, a URL to marketplace.json, or an npm package name.',
74
+ });
75
+ }
76
+ /** The GitHub repository a clone URL names, or undefined for another host. */
77
+ export function githubOf(url) {
78
+ const match = /^(?:https?:\/\/(?:www\.)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([^/\s]+)\/([^/\s#?]+?)(?:\.git)?\/?$/iu.exec(url);
79
+ if (match === null)
80
+ return undefined;
81
+ return { owner: match[1], repo: match[2] };
82
+ }
83
+ function github(owner, repo, ref, subpath) {
84
+ const clean = repo.replace(/\.git$/u, '');
85
+ if (ref !== undefined && ref.length > 0 && !SHA.test(ref) && !isValidRef(ref))
86
+ throw invalid(ref, 'not a branch, tag or commit name git accepts');
87
+ if (subpath !== undefined && subpath.length > 0 && !isSafeSubpath(subpath))
88
+ throw invalid(subpath, 'the directory leaves the repository');
89
+ return {
90
+ kind: 'git',
91
+ url: `https://github.com/${owner}/${clean}.git`,
92
+ github: { owner, repo: clean },
93
+ ...(ref !== undefined && ref.length > 0 ? SHA.test(ref) ? { sha: ref } : { ref } : {}),
94
+ ...(subpath !== undefined && subpath.length > 0 ? { subpath } : {}),
95
+ };
96
+ }
97
+ /** Split an npm spec `name@version` (scope-aware). */
98
+ function npmSpec(spec) {
99
+ const at = spec.indexOf('@', spec.startsWith('@') ? 1 : 0);
100
+ const name = at < 0 ? spec : spec.slice(0, at);
101
+ const version = at < 0 ? undefined : spec.slice(at + 1);
102
+ if (!NPM_NAME.test(name) || version === '' || (version !== undefined && !isRegistryRange(version)))
103
+ return undefined;
104
+ return { kind: 'npm', package: name, ...(version !== undefined ? { version } : {}) };
105
+ }
106
+ /**
107
+ * Read what a person pasted.
108
+ * @throws {HarnessError} `unsupported-source` when it names nothing Harness Forge can fetch.
109
+ */
110
+ export function parseRemoteInput(raw) {
111
+ const input = raw.trim();
112
+ if (input.length === 0)
113
+ throw invalid(input, 'nothing to fetch');
114
+ if (/^(?:\/|~[/\\]?|\.{1,2}[/\\]|[A-Za-z]:[/\\])/u.test(input) || input === '~' || input === '.')
115
+ return { kind: 'local', path: input };
116
+ if (input.startsWith('npm:')) {
117
+ const spec = npmSpec(input.slice(4));
118
+ if (spec === undefined)
119
+ throw invalid(input, 'not an npm package name');
120
+ return spec;
121
+ }
122
+ if (/^https?:\/\//iu.test(input)) {
123
+ let url;
124
+ try {
125
+ url = new URL(input);
126
+ }
127
+ catch {
128
+ throw invalid(input, 'not a valid URL');
129
+ }
130
+ const host = url.hostname.toLowerCase();
131
+ if (host === 'github.com' || host === 'www.github.com') {
132
+ const parts = url.pathname.split('/').filter(part => part.length > 0);
133
+ if (parts.length < 2)
134
+ throw invalid(input, 'not a GitHub repository URL');
135
+ const [owner, repo, kind, ref, ...rest] = parts;
136
+ const fragment = url.hash.length > 1 ? decodeURIComponent(url.hash.slice(1)) : undefined;
137
+ if ((kind === 'tree' || kind === 'blob') && ref !== undefined) {
138
+ const path = rest.join('/');
139
+ // A link to a marketplace.json file in the repository: the repository is the marketplace.
140
+ const subpath = /(?:^|\/)\.claude-plugin\/marketplace\.json$|(?:^|\/)\.agents\/plugins\/marketplace\.json$/u.test(path) ? undefined : path.replace(/\/?(?:\.claude-plugin|\.codex-plugin)\/plugin\.json$/u, '');
141
+ return github(owner, repo, decodeURIComponent(ref), subpath);
142
+ }
143
+ if (kind !== undefined && kind !== 'tree')
144
+ throw invalid(input, 'not a GitHub repository URL');
145
+ return github(owner, repo, fragment);
146
+ }
147
+ if (host === 'www.npmjs.com' || host === 'npmjs.com') {
148
+ const match = /^\/package\/((?:@[^/]+\/)?[^/]+)(?:\/v\/([^/]+))?/u.exec(url.pathname);
149
+ const spec = match === null ? undefined : npmSpec(`${decodeURIComponent(match[1])}${match[2] !== undefined ? `@${match[2]}` : ''}`);
150
+ if (spec === undefined)
151
+ throw invalid(input, 'not an npm package page');
152
+ return spec;
153
+ }
154
+ if (/\.json$/iu.test(url.pathname))
155
+ return { kind: 'json', url: url.href };
156
+ return gitUrl(input);
157
+ }
158
+ if (/^(?:ssh|git|file):\/\//iu.test(input) || /^[\w.-]+@[\w.-]+:/u.test(input))
159
+ return gitUrl(input);
160
+ const shorthand = SHORTHAND.exec(input);
161
+ if (shorthand !== null && shorthand[2] !== undefined && shorthand[2].length > 0 && !input.startsWith('@')) {
162
+ return github(shorthand[1], shorthand[2], shorthand[4], shorthand[3]?.replace(/^\//u, ''));
163
+ }
164
+ const spec = npmSpec(input);
165
+ if (spec !== undefined)
166
+ return spec;
167
+ throw invalid(input, 'not a repository, URL or package');
168
+ }
169
+ /** A git URL with an optional `#ref` (a full SHA there pins the commit). */
170
+ function gitUrl(input) {
171
+ const hash = input.indexOf('#');
172
+ const url = hash < 0 ? input : input.slice(0, hash);
173
+ const ref = hash < 0 ? undefined : input.slice(hash + 1);
174
+ if (url.startsWith('-') || /\s/u.test(url))
175
+ throw invalid(input, 'not a git URL');
176
+ const hub = githubOf(url);
177
+ if (hub !== undefined)
178
+ return github(hub.owner, hub.repo, ref);
179
+ if (ref !== undefined && ref.length > 0 && !SHA.test(ref) && !isValidRef(ref))
180
+ throw invalid(ref, 'not a branch, tag or commit name git accepts');
181
+ return { kind: 'git', url, ...(ref !== undefined && ref.length > 0 ? SHA.test(ref) ? { sha: ref } : { ref } : {}) };
182
+ }
183
+ /** The transport a git URL uses: `https`, `http`, `ssh` (also `user@host:path`), `git`, `file`, or undefined for anything else. */
184
+ export function gitTransport(url) {
185
+ const scheme = /^([A-Za-z][A-Za-z0-9+.-]*):\/\//u.exec(url)?.[1]?.toLowerCase();
186
+ if (scheme === 'https' || scheme === 'http' || scheme === 'ssh' || scheme === 'git' || scheme === 'file')
187
+ return scheme;
188
+ if (scheme === undefined && /^[\w.-]+@[\w.-]+:(?!\/\/)/u.test(url) && !url.startsWith('-'))
189
+ return 'ssh';
190
+ return undefined;
191
+ }
192
+ /**
193
+ * Where a marketplace entry's plugin is fetched from, or undefined for an entry
194
+ * inside the marketplace (a `path` source) and for sources Harness Forge does not
195
+ * fetch (`command`: it would run a command from the marketplace on this computer).
196
+ */
197
+ export function specOfSource(source) {
198
+ if (source.kind === 'git' && source.url !== undefined) {
199
+ let base;
200
+ try {
201
+ base = /^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+$/u.test(source.url) ? github(...source.url.split('/')) : gitUrl(source.url);
202
+ }
203
+ catch {
204
+ return undefined;
205
+ }
206
+ const sha = source.sha ?? base.sha;
207
+ return {
208
+ kind: 'git',
209
+ url: base.url,
210
+ ...(base.github !== undefined ? { github: base.github } : {}),
211
+ ...(source.ref !== undefined ? { ref: source.ref } : base.ref !== undefined ? { ref: base.ref } : {}),
212
+ // A sha that is not a full commit SHA is kept, for marketplaceProblem to refuse rather than fetch unpinned.
213
+ ...(sha !== undefined ? { sha: sha.toLowerCase() } : {}),
214
+ ...(source.subpath !== undefined ? { subpath: source.subpath.replace(/^\.\//u, '') } : {}),
215
+ };
216
+ }
217
+ if (source.kind === 'npm' && source.package !== undefined) {
218
+ const spec = source.package.startsWith('https://') ? undefined : npmSpec(source.package);
219
+ if (spec === undefined)
220
+ return undefined;
221
+ return { ...spec, ...(spec.version === undefined && source.version !== undefined ? { version: source.version } : {}), ...(source.registry !== undefined ? { registry: source.registry } : {}) };
222
+ }
223
+ if (source.kind === 'archive' && source.url !== undefined && /^https:\/\//iu.test(source.url)) {
224
+ return { kind: 'archive', url: source.url, ...(source.sha256 !== undefined ? { sha256: source.sha256.toLowerCase() } : {}) };
225
+ }
226
+ return undefined;
227
+ }
228
+ /**
229
+ * Why Harness Forge does not fetch what a marketplace entry names, or undefined
230
+ * when it does: a marketplace may not steer Harness Forge to another transport
231
+ * (`ssh`, `file`, `ext::`…) than HTTPS, to an unpinned commit it claims to pin,
232
+ * to a ref git could read as an option, out of the repository, or (for npm) to
233
+ * a spec that is not a registry lookup. Which registry it may name is decided
234
+ * when it is fetched, against the person's configuration.
235
+ */
236
+ export function marketplaceProblem(spec) {
237
+ switch (spec.kind) {
238
+ case 'git': {
239
+ if (gitTransport(spec.url) !== 'https')
240
+ return `only https git URLs are fetched for a marketplace entry: ${spec.url}`;
241
+ try {
242
+ const url = new URL(spec.url);
243
+ if (url.username.length > 0 || url.password.length > 0)
244
+ return 'a marketplace entry may not carry credentials in its URL';
245
+ }
246
+ catch {
247
+ return `not a URL: ${spec.url}`;
248
+ }
249
+ if (spec.sha !== undefined && !SHA.test(spec.sha))
250
+ return `sha is not a full 40-character commit SHA: ${spec.sha}`;
251
+ if (spec.ref !== undefined && !isValidRef(spec.ref))
252
+ return `not a branch or tag name git accepts: ${spec.ref}`;
253
+ if (spec.subpath !== undefined && !isSafeSubpath(spec.subpath))
254
+ return `the plugin path leaves its repository: ${spec.subpath}`;
255
+ return undefined;
256
+ }
257
+ case 'npm':
258
+ if (!NPM_NAME.test(spec.package))
259
+ return `not an npm package name: ${spec.package}`;
260
+ if (spec.version !== undefined && !isRegistryRange(spec.version))
261
+ return `not an npm version or range: ${spec.version}`;
262
+ if (spec.registry !== undefined && !/^https:\/\//iu.test(spec.registry))
263
+ return `only an https npm registry is used: ${spec.registry}`;
264
+ return undefined;
265
+ case 'archive':
266
+ if (!/^https:\/\//iu.test(spec.url))
267
+ return `only https archives are fetched: ${spec.url}`;
268
+ if (spec.sha256 !== undefined && !/^[0-9a-f]{64}$/u.test(spec.sha256))
269
+ return `sha256 is not a SHA-256 digest: ${spec.sha256}`;
270
+ return undefined;
271
+ case 'json':
272
+ case 'local':
273
+ return `a marketplace entry cannot be a ${spec.kind === 'json' ? 'marketplace' : 'local folder'}`;
274
+ }
275
+ }
276
+ /**
277
+ * Why an npm dependency spec is not installed, or undefined when it is a
278
+ * registry lookup (a version, range or tag, or an `npm:name@range` alias).
279
+ * Git, GitHub, `file:`, `link:`, `workspace:` and URL specs are refused: npm
280
+ * fetches them from elsewhere and may run their `prepare` script to build them.
281
+ */
282
+ export function dependencyProblem(name, spec) {
283
+ if (isRegistryRange(spec))
284
+ return undefined;
285
+ const alias = /^npm:((?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*)(?:@(.*))?$/u.exec(spec);
286
+ if (alias !== null && (alias[2] === undefined || isRegistryRange(alias[2])))
287
+ return undefined;
288
+ return `${name} is "${spec}": Harness Forge installs dependencies from the npm registry only, not from git, a URL or a local path`;
289
+ }
290
+ /** The source a fetched plugin is known by: what installed status and stored copies are keyed by. */
291
+ export function specIdentity(spec) {
292
+ switch (spec.kind) {
293
+ case 'git': return `git:${spec.url}${spec.subpath !== undefined ? `//${stripTrailing(spec.subpath.replace(/\\/gu, '/'), '/')}` : ''}`;
294
+ case 'npm': return `npm:${spec.registry ?? ''}:${spec.package}`;
295
+ case 'json': return `json:${spec.url}`;
296
+ case 'archive': return `archive:${spec.url}`;
297
+ case 'local': return `local:${spec.path}`;
298
+ }
299
+ }
300
+ /** One line naming a source for the person: `github.com/owner/repo@ref/path`, a URL, `npm:name@version`. */
301
+ export function describeSpec(spec) {
302
+ switch (spec.kind) {
303
+ case 'git': {
304
+ const base = spec.github !== undefined ? `github.com/${spec.github.owner}/${spec.github.repo}` : spec.url;
305
+ return `${base}${spec.ref !== undefined ? `#${spec.ref}` : ''}${spec.subpath !== undefined ? ` (${spec.subpath})` : ''}`;
306
+ }
307
+ case 'npm': return `npm:${spec.package}${spec.version !== undefined ? `@${spec.version}` : ''}`;
308
+ case 'json':
309
+ case 'archive': return spec.url;
310
+ case 'local': return spec.path;
311
+ }
312
+ }
313
+ /** The web page of a source, when it has one: what the confirmation links to. */
314
+ export function pageOfSpec(spec) {
315
+ if (spec.kind === 'git' && spec.github !== undefined) {
316
+ const at = spec.sha ?? spec.ref;
317
+ return `https://github.com/${spec.github.owner}/${spec.github.repo}${at !== undefined || spec.subpath !== undefined ? `/tree/${at ?? 'HEAD'}${spec.subpath !== undefined ? `/${spec.subpath}` : ''}` : ''}`;
318
+ }
319
+ if (spec.kind === 'git' && /^https?:\/\//iu.test(spec.url))
320
+ return spec.url.replace(/\.git$/u, '');
321
+ if (spec.kind === 'json' || spec.kind === 'archive')
322
+ return spec.url;
323
+ return undefined;
324
+ }
325
+ /** npm's own registry: the one a marketplace may name besides the person's configured registry. */
326
+ export const NPM_REGISTRY = 'https://registry.npmjs.org/';
327
+ /** A registry URL with one trailing slash, scheme and host lowercased; undefined when it is not an http(s) URL. */
328
+ export function normalizeRegistry(registry) {
329
+ try {
330
+ const url = new URL(registry.trim());
331
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
332
+ return undefined;
333
+ return `${url.origin}${stripTrailing(url.pathname, '/')}/`;
334
+ }
335
+ catch {
336
+ return undefined;
337
+ }
338
+ }
339
+ /** The page of an npm package version on the registry it comes from: npmjs.com for npm's own, else the registry's document of it. */
340
+ export function npmPage(registry, name, version) {
341
+ return normalizeRegistry(registry) === NPM_REGISTRY
342
+ ? `https://www.npmjs.com/package/${name}/v/${encodeURIComponent(version)}`
343
+ : `${normalizeRegistry(registry) ?? registry}${name.replace('/', '%2F')}`;
344
+ }
345
+ /** The GitHub archive URL of a ref or commit (`HEAD` for the default branch). */
346
+ export function githubTarball(owner, repo, ref = 'HEAD') {
347
+ return `https://codeload.github.com/${owner}/${repo}/tar.gz/${encodeURIComponent(ref).replace(/%2F/gu, '/')}`;
348
+ }
349
+ /** The GitHub API URL that answers a ref's commit SHA as plain text (with `Accept: application/vnd.github.sha`). */
350
+ export function githubCommitApi(owner, repo, ref = 'HEAD') {
351
+ return `https://api.github.com/repos/${owner}/${repo}/commits/${encodeURIComponent(ref)}`;
352
+ }
@@ -9,6 +9,7 @@
9
9
  export * from './model.js';
10
10
  export * from './adapter.js';
11
11
  export * from './synthesize.js';
12
+ export * from './lines.js';
12
13
  export { claudeCodeAdapter } from '../dialects/claude-code/sessions/adapter.js';
13
14
  export { readClaudeSession, type ClaudeReadOptions } from '../dialects/claude-code/sessions/parse.js';
14
15
  export { discoverClaudeCodeSessions } from '../dialects/claude-code/sessions/discover.js';
@@ -9,6 +9,7 @@
9
9
  export * from './model.js';
10
10
  export * from './adapter.js';
11
11
  export * from './synthesize.js';
12
+ export * from './lines.js';
12
13
  export { claudeCodeAdapter } from '../dialects/claude-code/sessions/adapter.js';
13
14
  export { readClaudeSession } from '../dialects/claude-code/sessions/parse.js';
14
15
  export { discoverClaudeCodeSessions } from '../dialects/claude-code/sessions/discover.js';