@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
@@ -0,0 +1,74 @@
1
+ import { basename, isAbsolute, join, relative, sep } from 'node:path';
2
+ import { childId } from '../../naming.js';
3
+ import { isFile, isInside, isPlainObject, readJsonObject, realOrLexical } from '../../paths.js';
4
+ /** Read a direct executable or interpreter + script without running any shell code. */
5
+ function commandFile(command, home) {
6
+ // Keep quoted paths whole; don't scan later arguments for something that merely looks like a plugin file.
7
+ const words = command.trim().match(/(?:"[^"]*"|'[^']*'|\\[^\r\n]|[^\s"'\\;&|<>])+/gu)
8
+ ?.map(word => word.replace(/"([^"]*)"|'([^']*)'|\\([ \t])/gu, (_match, double, single, escaped) => double ?? single ?? escaped ?? '')) ?? [];
9
+ while (/^\w+=/u.test(words[0] ?? ''))
10
+ words.shift();
11
+ if (words[0] !== undefined && basename(words[0]) === 'env') {
12
+ words.shift();
13
+ while (/^\w+=/u.test(words[0] ?? ''))
14
+ words.shift();
15
+ }
16
+ const first = words[0];
17
+ if (first === undefined)
18
+ return undefined;
19
+ const runner = /^(?:node(?:js)?|bun|deno|bash|sh|zsh|python(?:\d(?:\.\d+)?)?|ruby|perl)(?:\.exe)?$/u.test(basename(first));
20
+ const word = words[runner ? (words[1] === '--' || (words[1] === 'run' && /^(?:bun|deno)$/u.test(basename(first))) ? 2 : 1) : 0];
21
+ if (word === undefined)
22
+ return undefined;
23
+ const path = word.replace(/^(?:~|\$HOME|\$\{HOME\})(?=[\\/])/u, home);
24
+ return isAbsolute(path) && isFile(path) ? path : undefined;
25
+ }
26
+ /** Locate the owner among the plugins Forge actually discovered, not arbitrary cache entries. */
27
+ export function claudeStatusLineProvider(command, plugins, home) {
28
+ const file = commandFile(command, home);
29
+ if (file === undefined)
30
+ return undefined;
31
+ const claudePlugins = plugins.filter(plugin => plugin.source === 'claude-code' && plugin.manifest['scope'] !== 'user' && plugin.manifest['scope'] !== 'project');
32
+ const index = readJsonObject(join(home, '.claude', 'plugins', 'installed_plugins.json'))?.['plugins'];
33
+ const installed = isPlainObject(index) ? Object.entries(index) : [];
34
+ const realFile = realOrLexical(file);
35
+ // Prefer the deepest root when discovered directories overlap.
36
+ const matches = claudePlugins.flatMap(plugin => {
37
+ const roots = [plugin.root];
38
+ for (const [key, records] of installed) {
39
+ if (!Array.isArray(records))
40
+ continue;
41
+ const paths = records.flatMap(record => isPlainObject(record) && typeof record['installPath'] === 'string' && isAbsolute(record['installPath']) ? [record['installPath']] : []);
42
+ if (!paths.some(path => realOrLexical(path) === realOrLexical(plugin.root)))
43
+ continue;
44
+ roots.push(...paths);
45
+ const [name, market] = key.split('@');
46
+ const segment = (value) => value !== undefined && value !== '' && value !== '.' && value !== '..' && !/[\\/]/u.test(value);
47
+ if (segment(name) && segment(market))
48
+ roots.push(join(home, '.claude', 'plugins', 'cache', market, name));
49
+ }
50
+ const depth = Math.max(0, ...roots.filter(root => isInside(root, file) || isInside(realOrLexical(root), realFile)).map(root => root.length));
51
+ return depth === 0 ? [] : [{ plugin, depth }];
52
+ }).sort((a, b) => b.depth - a.depth);
53
+ const plugin = matches[0]?.plugin;
54
+ if (plugin === undefined)
55
+ return undefined;
56
+ const declared = plugin.components.find((part) => part.kind === 'ui' && part.surface === 'statusline');
57
+ const component = declared ?? {
58
+ id: childId(plugin.id, 'ui', 'statusline'),
59
+ kind: 'ui',
60
+ surface: 'statusline',
61
+ name: 'statusline',
62
+ specPath: file,
63
+ ...(isInside(plugin.root, file) ? { path: relative(plugin.root, file).split(sep).join('/') } : {}),
64
+ description: 'status line configured in Claude Code settings',
65
+ };
66
+ return { plugin, component };
67
+ }
68
+ export function claudeSettingsStatusLine(plugin) {
69
+ if (plugin.source !== 'claude-code' || plugin.manifest['scope'] !== 'user')
70
+ return undefined;
71
+ const component = plugin.components.find((part) => part.kind === 'ui' && part.name === 'statusline-settings' && part.surface === 'statusline');
72
+ const spec = component?.metadata?.['statusLine'];
73
+ return component !== undefined && isPlainObject(spec) && typeof spec['command'] === 'string' ? { component, command: spec['command'] } : undefined;
74
+ }
@@ -1,5 +1,5 @@
1
1
  import type { ForeignPlugin, HookComponent, McpComponent, SettingsComponent } from '../../types.js';
2
- /** One plugin Claude Code has installed. */
2
+ /** One plugin Claude Code has installed, in one scope. */
3
3
  export interface InstalledClaudePlugin {
4
4
  /** `name@marketplace`. */
5
5
  readonly key: string;
@@ -7,13 +7,41 @@ export interface InstalledClaudePlugin {
7
7
  readonly marketplace: string;
8
8
  readonly root: string;
9
9
  readonly version?: string;
10
+ /** `user`, or `project` / `local` for an install that only one project's sessions load. */
10
11
  readonly scope: string;
11
- /** False when settings disable it (`enabledPlugins[key] === false`). */
12
+ /** The project a `project` or `local` install belongs to. */
13
+ readonly projectPath?: string;
14
+ /** Whether Claude Code loads it where it applies: `enabledPlugins` resolved as Claude Code resolves it. */
12
15
  readonly enabled: boolean;
13
16
  readonly gitCommitSha?: string;
14
17
  }
15
- /** The plugins Claude Code loads, newest entry per plugin, existing roots only. */
16
- export declare function installedClaudePlugins(home?: string): InstalledClaudePlugin[];
18
+ /** Whether an install applies to every session (user scope), rather than to one project's. */
19
+ export declare function isGlobalClaudeInstall(plugin: Pick<InstalledClaudePlugin, 'scope' | 'projectPath'>): boolean;
20
+ /** What Claude Code records as installed, and how much of that could be read. */
21
+ export interface ClaudeInstalls {
22
+ readonly plugins: readonly InstalledClaudePlugin[];
23
+ /** Installs recorded with no install folder left on disk: still installed, not readable now. */
24
+ readonly unresolved: ReadonlyArray<Pick<InstalledClaudePlugin, 'key' | 'scope' | 'projectPath'> & {
25
+ readonly message: string;
26
+ }>;
27
+ /** What could not be read: `installed_plugins.json`, an entry of it, or a settings file that decides what is on. */
28
+ readonly unread: readonly string[];
29
+ }
30
+ /**
31
+ * The plugins Claude Code has installed, from `installed_plugins.json` (which records each install with its
32
+ * `scope`, `installPath` and `version`, https://code.claude.com/docs/en/plugins/loading#check-which-stage-a-plugin-reached):
33
+ * the newest existing install per plugin and scope (and project, for a project-bound scope). A user-scope
34
+ * install never gives way to a newer one of another project. A missing index records nothing; one that does not
35
+ * parse (Claude Code may be writing it) is `unread`, never "nothing installed".
36
+ * @param managedDir - the system directory of Claude Code's managed settings (see {@link claudeManagedSettingsDir}).
37
+ */
38
+ export declare function installedClaudePlugins(home?: string, managedDir?: string): ClaudeInstalls;
39
+ /**
40
+ * The system directory of Claude Code's file-based managed settings
41
+ * (https://code.claude.com/docs/en/managed-settings.md#where-each-mechanism-stores-the-policy). MDM profiles,
42
+ * the registry and server-managed settings are not files Harness Forge can read.
43
+ */
44
+ export declare function claudeManagedSettingsDir(platform?: NodeJS.Platform): string;
17
45
  /**
18
46
  * The user's own Claude Code assets as one plugin.
19
47
  * @returns undefined when `~/.claude` holds nothing to bring over.
@@ -36,8 +64,11 @@ export declare function scanClaudeUserAssets(home?: string): ForeignPlugin | und
36
64
  * @returns undefined when the directory has no Claude Code project assets.
37
65
  */
38
66
  export declare function scanClaudeProjectAssets(cwd: string, home?: string): ForeignPlugin | undefined;
39
- /** The permission rules and environment of one or more settings files, merged in order. */
40
- export declare function claudeSettingsComponent(pluginId: string, files: readonly string[], values: readonly Record<string, unknown>[]): SettingsComponent | undefined;
67
+ /**
68
+ * The permission rules and environment of one or more settings files, merged in order.
69
+ * @param ruleRoot - where the files' `/path` file rules anchor (see `SettingsComponent.ruleRoot`).
70
+ */
71
+ export declare function claudeSettingsComponent(pluginId: string, files: readonly string[], values: readonly Record<string, unknown>[], ruleRoot: string): SettingsComponent | undefined;
41
72
  /** The `hooks` of a settings file as an inline hooks component. */
42
73
  export declare function settingsHooksComponent(pluginId: string, path: string, settings: Record<string, unknown>, name?: string): HookComponent | undefined;
43
74
  /** MCP servers of a user or project map, named as Claude Code names them. */
@@ -7,54 +7,170 @@
7
7
  * and MCP servers without a plugin prefix, and so does DSH.
8
8
  *
9
9
  * Installed plugins come from `~/.claude/plugins/installed_plugins.json`,
10
- * the list Claude Code itself loads, with the enabled state from settings.
10
+ * the list Claude Code itself loads, with the enabled state from settings
11
+ * resolved in Claude Code's precedence.
11
12
  * @module @kirkchinese/harness-forge-core
12
13
  */
14
+ import { readdirSync } from 'node:fs';
13
15
  import { homedir } from 'node:os';
14
16
  import { dirname, join, resolve } from 'node:path';
15
17
  import { scanPlugin } from '../../manifest.js';
16
18
  import { childId, shortHash } from '../../naming.js';
17
19
  import { fingerprintPlugin } from '../../fingerprint.js';
18
- import { isDirectory, isFile, isPlainObject, readJsonObject, stringArrayField, stringField } from '../../paths.js';
19
- /** The plugins Claude Code loads, newest entry per plugin, existing roots only. */
20
- export function installedClaudePlugins(home = homedir()) {
21
- const index = readJsonObject(join(home, '.claude', 'plugins', 'installed_plugins.json'));
22
- const plugins = isPlainObject(index?.['plugins']) ? index['plugins'] : {};
23
- const enabled = enabledPlugins(home);
20
+ import { isDirectory, isFile, isPlainObject, LEADS_TO_SHARE, leadsToShare, readJsonObject, readJsonRecord, stringArrayField, stringField } from '../../paths.js';
21
+ /**
22
+ * The install scopes that bind a plugin to one project: Claude Code installs with `--scope project` or
23
+ * `--scope local` record the project they were run in, and only that project's sessions load them
24
+ * (https://code.claude.com/docs/en/plugins/loading#find-where-a-plugin-is-enabled).
25
+ */
26
+ const PROJECT_SCOPES = new Set(['project', 'local']);
27
+ /** Whether an install applies to every session (user scope), rather than to one project's. */
28
+ export function isGlobalClaudeInstall(plugin) {
29
+ return !PROJECT_SCOPES.has(plugin.scope) && plugin.projectPath === undefined;
30
+ }
31
+ /**
32
+ * The plugins Claude Code has installed, from `installed_plugins.json` (which records each install with its
33
+ * `scope`, `installPath` and `version`, https://code.claude.com/docs/en/plugins/loading#check-which-stage-a-plugin-reached):
34
+ * the newest existing install per plugin and scope (and project, for a project-bound scope). A user-scope
35
+ * install never gives way to a newer one of another project. A missing index records nothing; one that does not
36
+ * parse (Claude Code may be writing it) is `unread`, never "nothing installed".
37
+ * @param managedDir - the system directory of Claude Code's managed settings (see {@link claudeManagedSettingsDir}).
38
+ */
39
+ export function installedClaudePlugins(home = homedir(), managedDir = claudeManagedSettingsDir()) {
40
+ const unread = [];
41
+ const settingsOf = (path) => {
42
+ const read = readJsonRecord(path);
43
+ if (read.problem !== undefined)
44
+ unread.push(read.problem);
45
+ return enabledPluginsOf(read.value);
46
+ };
47
+ const indexPath = join(home, '.claude', 'plugins', 'installed_plugins.json');
48
+ const index = readJsonRecord(indexPath);
49
+ if (index.problem !== undefined)
50
+ unread.push(index.problem);
51
+ const listed = index.value?.['plugins'];
52
+ if (listed !== undefined && !isPlainObject(listed))
53
+ unread.push(`${indexPath}: "plugins" is not an object`);
54
+ const plugins = isPlainObject(listed) ? listed : {};
55
+ const managed = managedEnabledPlugins(managedDir, unread);
56
+ const user = settingsOf(join(home, '.claude', 'settings.json'));
24
57
  const out = [];
58
+ const unresolved = [];
25
59
  for (const [key, entries] of Object.entries(plugins)) {
26
- if (!Array.isArray(entries))
27
- continue;
28
- const records = entries.filter(isPlainObject);
29
- const latest = records
30
- .filter(record => typeof record['installPath'] === 'string' && isDirectory(String(record['installPath'])))
31
- .sort((a, b) => String(b['lastUpdated'] ?? b['installedAt'] ?? '').localeCompare(String(a['lastUpdated'] ?? a['installedAt'] ?? '')))[0];
32
- if (latest === undefined)
60
+ if (!Array.isArray(entries)) {
61
+ unread.push(`${indexPath}: the entry of ${key} is not a list`);
33
62
  continue;
63
+ }
64
+ const newest = new Map();
65
+ const missing = new Map();
66
+ for (const record of entries) {
67
+ if (!isPlainObject(record) || typeof record['installPath'] !== 'string') {
68
+ unread.push(`${indexPath}: an install of ${key} has no install folder`);
69
+ continue;
70
+ }
71
+ const scope = stringField(record, 'scope') ?? 'user';
72
+ const project = PROJECT_SCOPES.has(scope) ? stringField(record, 'projectPath') : undefined;
73
+ const group = `${scope}\0${project === undefined ? '' : resolve(project)}`;
74
+ if (!isDirectory(record['installPath'])) {
75
+ missing.set(group, { scope, ...(project !== undefined ? { projectPath: resolve(project) } : {}), path: record['installPath'] });
76
+ continue;
77
+ }
78
+ const known = newest.get(group);
79
+ if (known === undefined || updatedAt(record).localeCompare(updatedAt(known)) > 0)
80
+ newest.set(group, record);
81
+ }
82
+ for (const [group, gone] of missing) {
83
+ if (!newest.has(group))
84
+ unresolved.push({ key, scope: gone.scope, ...(gone.projectPath !== undefined ? { projectPath: gone.projectPath } : {}), message: `Claude Code records ${key} at ${gone.path}, which is not there` });
85
+ }
34
86
  const [name = key, marketplace = ''] = key.split('@');
35
- const version = stringField(latest, 'version');
36
- const sha = stringField(latest, 'gitCommitSha');
37
- out.push({
38
- key,
39
- name,
40
- marketplace,
41
- root: resolve(String(latest['installPath'])),
42
- ...(version !== undefined ? { version } : {}),
43
- scope: stringField(latest, 'scope') ?? 'user',
44
- enabled: enabled[key] !== false,
45
- ...(sha !== undefined ? { gitCommitSha: sha } : {}),
46
- });
87
+ for (const record of newest.values()) {
88
+ const scope = stringField(record, 'scope') ?? 'user';
89
+ const projectPath = PROJECT_SCOPES.has(scope) ? stringField(record, 'projectPath') : undefined;
90
+ // Lowest precedence first: user, then the project's `settings.json` and `settings.local.json`, then managed. A
91
+ // project's settings decide only that project's installs, which the global view leaves out: they cost no completeness.
92
+ const layers = [user, ...(projectPath === undefined ? [] : ['settings.json', 'settings.local.json'].map(file => enabledPluginsOf(readJsonObject(join(projectPath, '.claude', file))))), managed];
93
+ const version = stringField(record, 'version');
94
+ const sha = stringField(record, 'gitCommitSha');
95
+ out.push({
96
+ key,
97
+ name,
98
+ marketplace,
99
+ root: resolve(String(record['installPath'])),
100
+ ...(version !== undefined ? { version } : {}),
101
+ scope,
102
+ ...(projectPath !== undefined ? { projectPath: resolve(projectPath) } : {}),
103
+ enabled: resolveEnabled(key, layers),
104
+ ...(sha !== undefined ? { gitCommitSha: sha } : {}),
105
+ });
106
+ }
47
107
  }
48
- return out.sort((a, b) => a.key.localeCompare(b.key, 'en'));
108
+ out.sort((a, b) => a.key.localeCompare(b.key, 'en') || a.scope.localeCompare(b.scope, 'en') || (a.projectPath ?? '').localeCompare(b.projectPath ?? '', 'en'));
109
+ return { plugins: out, unresolved, unread: [...new Set(unread)] };
110
+ }
111
+ function updatedAt(record) {
112
+ return String(record['lastUpdated'] ?? record['installedAt'] ?? '');
113
+ }
114
+ /**
115
+ * Claude Code merges `enabledPlugins` key by key: the value from the highest-precedence source that mentions
116
+ * the plugin applies (https://code.claude.com/docs/en/plugins/loading#find-where-a-plugin-is-enabled). An
117
+ * installed plugin that no source mentions is on.
118
+ * @param layers - lowest precedence first.
119
+ */
120
+ function resolveEnabled(key, layers) {
121
+ let enabled = true;
122
+ for (const layer of layers)
123
+ if (key in layer)
124
+ enabled = layer[key];
125
+ return enabled;
49
126
  }
50
- /** `enabledPlugins` from user settings. */
51
- function enabledPlugins(home) {
52
- const settings = readJsonObject(join(home, '.claude', 'settings.json'));
127
+ /** The `enabledPlugins` entries of one settings document. */
128
+ function enabledPluginsOf(settings) {
53
129
  const value = settings?.['enabledPlugins'];
54
130
  if (!isPlainObject(value))
55
131
  return {};
56
132
  return Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === 'boolean'));
57
133
  }
134
+ /**
135
+ * The system directory of Claude Code's file-based managed settings
136
+ * (https://code.claude.com/docs/en/managed-settings.md#where-each-mechanism-stores-the-policy). MDM profiles,
137
+ * the registry and server-managed settings are not files Harness Forge can read.
138
+ */
139
+ export function claudeManagedSettingsDir(platform = process.platform) {
140
+ if (platform === 'darwin')
141
+ return '/Library/Application Support/ClaudeCode';
142
+ if (platform === 'win32')
143
+ return 'C:\\Program Files\\ClaudeCode';
144
+ return '/etc/claude-code';
145
+ }
146
+ /**
147
+ * `enabledPlugins` of the managed settings files: `managed-settings.json`, then `managed-settings.d/*.json` in name
148
+ * order, later ones winning. What could not be read is added to `unread`.
149
+ */
150
+ function managedEnabledPlugins(dir, unread) {
151
+ let drop = [];
152
+ const dropIns = join(dir, 'managed-settings.d');
153
+ // A drop-in folder on a link to a network share it is not on cannot be listed (see `leadsToShare`).
154
+ if (leadsToShare(dropIns))
155
+ unread.push(`${dropIns} could not be listed (${LEADS_TO_SHARE})`);
156
+ else
157
+ try {
158
+ drop = readdirSync(dropIns).filter(file => file.endsWith('.json') && !file.startsWith('.')).sort();
159
+ }
160
+ catch (error) {
161
+ // No drop-in directory is none to read; one that cannot be listed is not.
162
+ const code = error.code;
163
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
164
+ unread.push(`${join(dir, 'managed-settings.d')} could not be listed (${error instanceof Error ? error.message : String(error)})`);
165
+ }
166
+ const files = [join(dir, 'managed-settings.json'), ...drop.map(file => join(dir, 'managed-settings.d', file))];
167
+ return Object.assign({}, ...files.map((file) => {
168
+ const read = readJsonRecord(file);
169
+ if (read.problem !== undefined)
170
+ unread.push(read.problem);
171
+ return enabledPluginsOf(read.value);
172
+ }));
173
+ }
58
174
  /**
59
175
  * The user's own Claude Code assets as one plugin.
60
176
  * @returns undefined when `~/.claude` holds nothing to bring over.
@@ -69,7 +185,7 @@ export function scanClaudeUserAssets(home = homedir()) {
69
185
  const components = base.components.filter(component => ['skill', 'command', 'agent', 'ui'].includes(component.kind));
70
186
  const settingsPath = join(root, 'settings.json');
71
187
  const settings = readJsonObject(settingsPath) ?? {};
72
- const settingsComponent = claudeSettingsComponent(base.id, [settingsPath], [settings]);
188
+ const settingsComponent = claudeSettingsComponent(base.id, [settingsPath], [settings], root);
73
189
  if (settingsComponent !== undefined)
74
190
  components.push(settingsComponent);
75
191
  const hooks = settingsHooksComponent(base.id, settingsPath, settings);
@@ -152,7 +268,7 @@ export function scanClaudeProjectAssets(cwd, home = homedir()) {
152
268
  }
153
269
  const settingsFiles = ['settings.json', 'settings.local.json'].map(file => join(root, '.claude', file)).filter(isFile);
154
270
  const settingsValues = settingsFiles.map(file => readJsonObject(file) ?? {});
155
- const settings = claudeSettingsComponent(pluginId, settingsFiles, settingsValues);
271
+ const settings = claudeSettingsComponent(pluginId, settingsFiles, settingsValues, root);
156
272
  if (settings !== undefined)
157
273
  components.push(settings);
158
274
  for (const [index, file] of settingsFiles.entries()) {
@@ -208,8 +324,11 @@ function samePath(left, right) {
208
324
  };
209
325
  return normalize(left) === normalize(right);
210
326
  }
211
- /** The permission rules and environment of one or more settings files, merged in order. */
212
- export function claudeSettingsComponent(pluginId, files, values) {
327
+ /**
328
+ * The permission rules and environment of one or more settings files, merged in order.
329
+ * @param ruleRoot - where the files' `/path` file rules anchor (see `SettingsComponent.ruleRoot`).
330
+ */
331
+ export function claudeSettingsComponent(pluginId, files, values, ruleRoot) {
213
332
  const permissions = { allow: [], deny: [], ask: [] };
214
333
  const env = {};
215
334
  let disableAllHooks;
@@ -241,6 +360,7 @@ export function claudeSettingsComponent(pluginId, files, values) {
241
360
  description: `${String(ruleCount)} permission rule(s), ${String(Object.keys(env).length)} environment variable(s)`,
242
361
  files: files.filter(isFile),
243
362
  permissions: merged,
363
+ ruleRoot,
244
364
  env,
245
365
  ...(disableAllHooks !== undefined ? { disableAllHooks } : {}),
246
366
  ...(outputStyle !== undefined ? { outputStyle } : {}),
@@ -304,6 +424,7 @@ export function mcpComponents(pluginId, servers, scope) {
304
424
  id: childId(pluginId, 'mcp', name),
305
425
  kind: 'mcp',
306
426
  name,
427
+ declaredName: name,
307
428
  description: `${scope}-scope ${transport} MCP server`,
308
429
  transport,
309
430
  ...(command !== undefined ? { command } : {}),
@@ -1,13 +1,14 @@
1
1
  /**
2
2
  * The Codex dialect: `.codex-plugin/plugin.json` plugins (merged over a
3
3
  * portable root `plugin.json`), the user's `$CODEX_HOME` and project
4
- * `.codex/` directories.
4
+ * `.codex/` directories, and the plugins Codex has installed (see `plugins.ts`).
5
5
  * @module @kirkchinese/harness-forge-core
6
6
  */
7
7
  import { join } from 'node:path';
8
8
  import { scanPlugin } from '../../manifest.js';
9
9
  import { isFile } from '../../paths.js';
10
10
  import { codexHome, scanCodexProjectAssets, scanCodexUserAssets } from './user-assets.js';
11
+ import { codexInstallKey, codexMarketplaces, installedCodexPlugins } from './plugins.js';
11
12
  export const codexDialect = {
12
13
  id: 'codex',
13
14
  label: 'Codex',
@@ -20,5 +21,11 @@ export const codexDialect = {
20
21
  scan: home => scanCodexUserAssets(home),
21
22
  emptyMessage: 'holds no Codex skills, prompts, MCP servers, rules or instructions',
22
23
  },
24
+ harnessPlugins: {
25
+ roots: home => [join(home, '.codex', 'plugins')],
26
+ list: home => installedCodexPlugins(home),
27
+ marketplaces: home => codexMarketplaces(home),
28
+ identify: (home, root) => codexInstallKey(root, home),
29
+ },
23
30
  projectAssets: (cwd, home) => scanCodexProjectAssets(cwd, home),
24
31
  };
@@ -0,0 +1,17 @@
1
+ import type { McpComponent, McpNotStartedCode } from '../../types.js';
2
+ /** Where the server is declared, for its component identity and description. */
3
+ export interface CodexMcpBase {
4
+ readonly id: string;
5
+ readonly name: string;
6
+ /** The name the configuration declares (see `McpComponent.declaredName`). */
7
+ readonly declaredName?: string;
8
+ readonly path?: string;
9
+ /** What the default description says the server is, e.g. `user-scope` or `plugin`. */
10
+ readonly scope: string;
11
+ /** What `enabled = false` is reported as. */
12
+ readonly disabledCode: Extract<McpNotStartedCode, 'disabled-in-plugin' | 'disabled-in-config'>;
13
+ }
14
+ /** A server that is not started, with the reason `code` says in English. */
15
+ export declare function notStartedBy(code: McpNotStartedCode): NonNullable<McpComponent['notStarted']>;
16
+ /** Translate one Codex server entry. */
17
+ export declare function codexMcpServer(raw: Record<string, unknown>, base: CodexMcpBase): McpComponent;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * One Codex MCP server entry, as Codex reads it, translated once for both
3
+ * places Codex declares servers: `config.toml` `[mcp_servers.<name>]` and a
4
+ * plugin's `.mcp.json` / `mcp.json` / manifest `mcpServers`.
5
+ *
6
+ * Fields follow the Codex MCP reference
7
+ * (https://developers.openai.com/codex/mcp, "Configure with config.toml";
8
+ * https://github.com/openai/codex/blob/main/docs/config.md points there).
9
+ * Variables Codex passes through are referenced as `${NAME}`, expanded when
10
+ * the server starts.
11
+ *
12
+ * Read but not used: `omit_tools_from` (which of Codex's own tool surfaces,
13
+ * such as code mode or deferred tools, leave the server's tools out; DSH has
14
+ * neither surface) and `tools.<tool>.output_token_limit` (a Codex truncation
15
+ * budget; DSH bounds tool output itself).
16
+ * @module @kirkchinese/harness-forge-core
17
+ */
18
+ import { isPlainObject } from '../../paths.js';
19
+ /** Codex approval modes that ask before a call: `prompt`, and `writes`, which asks for tools not marked read-only. Read-only hints are only known once the server lists its tools, so `writes` asks for every tool. */
20
+ const ASKING_APPROVAL_MODES = new Set(['prompt', 'writes']);
21
+ /** Codex's `auth` value that signs in with the user's ChatGPT session. */
22
+ const CHATGPT_AUTH = 'chatgpt';
23
+ /** The English wording of each reason a server is not started, for logs, plans and agents; screens word the code themselves. */
24
+ const NOT_STARTED_DETAIL = {
25
+ 'disabled-in-plugin': 'disabled in the plugin',
26
+ 'disabled-in-config': 'disabled in config.toml',
27
+ 'needs-chatgpt-sign-in': 'needs ChatGPT sign-in, which DSH cannot provide',
28
+ };
29
+ /** A server that is not started, with the reason `code` says in English. */
30
+ export function notStartedBy(code) {
31
+ return { reason: code === 'needs-chatgpt-sign-in' ? 'unsupported' : 'disabled', code, detail: NOT_STARTED_DETAIL[code] };
32
+ }
33
+ /** Milliseconds in one of Codex's `*_sec` values. */
34
+ const MS_PER_SECOND = 1000;
35
+ /** Translate one Codex server entry. */
36
+ export function codexMcpServer(raw, base) {
37
+ const command = typeof raw['command'] === 'string' ? raw['command'] : undefined;
38
+ const url = typeof raw['url'] === 'string' ? raw['url'] : undefined;
39
+ const args = strings(raw['args']);
40
+ // `env_vars` entries are names, or `{ name, source }`; DSH runs servers locally, so every source reads the local environment.
41
+ const passed = Array.isArray(raw['env_vars'])
42
+ ? raw['env_vars'].map(item => typeof item === 'string' ? item : isPlainObject(item) && typeof item['name'] === 'string' ? item['name'] : undefined)
43
+ .filter((item) => item !== undefined)
44
+ : [];
45
+ const env = { ...Object.fromEntries(passed.map(variable => [variable, `\${${variable}}`])), ...stringRecord(raw['env']) };
46
+ const headers = {
47
+ ...stringRecord(raw['http_headers']),
48
+ ...Object.fromEntries(Object.entries(stringRecord(raw['env_http_headers'])).map(([header, variable]) => [header, `\${${variable}}`])),
49
+ ...(typeof raw['bearer_token_env_var'] === 'string' ? { Authorization: `Bearer \${${raw['bearer_token_env_var']}}` } : {}),
50
+ };
51
+ const transport = codexTransport(raw['type'], command, url);
52
+ const enabledTools = Array.isArray(raw['enabled_tools']) ? strings(raw['enabled_tools']) : undefined;
53
+ const disabledTools = strings(raw['disabled_tools']);
54
+ const approval = toolApproval(raw);
55
+ const startupTimeoutMs = seconds(raw['startup_timeout_sec']);
56
+ const toolTimeoutMs = seconds(raw['tool_timeout_sec']);
57
+ const notStarted = raw['enabled'] === false
58
+ ? notStartedBy(base.disabledCode)
59
+ : raw['auth'] === CHATGPT_AUTH ? notStartedBy('needs-chatgpt-sign-in') : undefined;
60
+ return {
61
+ id: base.id,
62
+ kind: 'mcp',
63
+ name: base.name,
64
+ ...(base.declaredName !== undefined ? { declaredName: base.declaredName } : {}),
65
+ ...(base.path !== undefined ? { path: base.path } : {}),
66
+ description: typeof raw['description'] === 'string' ? raw['description'] : `${base.scope} ${transport} MCP server`,
67
+ transport,
68
+ ...(command !== undefined ? { command } : {}),
69
+ ...(args.length > 0 ? { args } : {}),
70
+ ...(Object.keys(env).length > 0 ? { env } : {}),
71
+ ...(typeof raw['cwd'] === 'string' ? { cwd: raw['cwd'] } : {}),
72
+ ...(url !== undefined ? { url } : {}),
73
+ ...(Object.keys(headers).length > 0 ? { headers } : {}),
74
+ ...(enabledTools !== undefined ? { enabledTools } : {}),
75
+ ...(disabledTools.length > 0 ? { disabledTools } : {}),
76
+ ...(approval !== undefined ? { toolApproval: approval } : {}),
77
+ ...(startupTimeoutMs !== undefined ? { startupTimeoutMs } : {}),
78
+ ...(toolTimeoutMs !== undefined ? { toolTimeoutMs } : {}),
79
+ ...(notStarted !== undefined ? { notStarted } : {}),
80
+ };
81
+ }
82
+ /** Codex's `type`: `http` and `streamable_http` are Streamable HTTP; without one, `command` is stdio and `url` Streamable HTTP. */
83
+ function codexTransport(type, command, url) {
84
+ if (type === 'stdio')
85
+ return 'stdio';
86
+ if (type === 'http' || type === 'streamable-http' || type === 'streamable_http' || type === 'streamableHttp')
87
+ return 'streamable-http';
88
+ if (type === 'sse')
89
+ return 'sse';
90
+ return command !== undefined ? 'stdio' : url !== undefined ? 'streamable-http' : 'unknown';
91
+ }
92
+ /** The tools that ask first; undefined when none does. */
93
+ function toolApproval(raw) {
94
+ const asks = (mode) => typeof mode === 'string' ? ASKING_APPROVAL_MODES.has(mode) : undefined;
95
+ const askByDefault = asks(raw['default_tools_approval_mode']) ?? false;
96
+ const tools = {};
97
+ if (isPlainObject(raw['tools'])) {
98
+ for (const [tool, settings] of Object.entries(raw['tools'])) {
99
+ const ask = isPlainObject(settings) ? asks(settings['approval_mode']) : undefined;
100
+ if (ask !== undefined && ask !== askByDefault)
101
+ tools[tool] = ask;
102
+ }
103
+ }
104
+ return askByDefault || Object.values(tools).some(Boolean) ? { askByDefault, tools } : undefined;
105
+ }
106
+ function seconds(value) {
107
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.round(value * MS_PER_SECOND) : undefined;
108
+ }
109
+ function strings(value) {
110
+ return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
111
+ }
112
+ function stringRecord(value) {
113
+ return isPlainObject(value)
114
+ ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === 'string'))
115
+ : {};
116
+ }
@@ -0,0 +1,16 @@
1
+ import type { HarnessMarketplace, HarnessPluginList } from '../types.js';
2
+ /**
3
+ * The plugins `config.toml` lists, each at the cached version Codex loads. A listed plugin with no cached version is
4
+ * `unresolved` (still installed); a `config.toml` that does not parse, or a cache folder that cannot be listed, is
5
+ * `unread`, never "nothing installed".
6
+ */
7
+ export declare function installedCodexPlugins(home?: string): HarnessPluginList;
8
+ /**
9
+ * The `<name>@<marketplace>` a folder of Codex's cache (`plugins/cache/<marketplace>/<name>/<version>`) is a version
10
+ * of, listed or not.
11
+ */
12
+ export declare function codexInstallKey(root: string, home?: string): string | undefined;
13
+ /** The folders from `cache` down to `root`, when `root` is below it. */
14
+ export declare function cachePath(cache: string, root: string): string[] | undefined;
15
+ /** The local marketplaces `config.toml` adds (`[marketplaces.<name>]` with a local `source`). */
16
+ export declare function codexMarketplaces(home?: string): HarnessMarketplace[];