dsh-hiss-plugins 0.0.0-stage → 1.0.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.
@@ -0,0 +1,150 @@
1
+ import { resolveGitBash } from "./resolve.js";
2
+
3
+ /**
4
+ * Build the Git Bash shell executor.
5
+ *
6
+ * The Windows runner chain (`dsh-sandbox-local`'s `windows-acl` rung) confines commands
7
+ * with a write-restricted token. MSYS2 — the runtime inside Git Bash — creates a named
8
+ * object while starting up and asks for write access with the *user's* SID, which a
9
+ * write-restricted token never grants: `bash.exe` dies at DLL init with
10
+ * `couldn't create signal pipe, Win32 error 5`. No plugin can repair that, so this
11
+ * executor does not pretend otherwise. It reuses DSH's own sandbox-consuming executor
12
+ * and adds two things:
13
+ *
14
+ * 1. the exact `bash.exe` to run, instead of PATH's `bash` (which on Windows is the WSL
15
+ * launcher), and
16
+ * 2. the MSYS2 startup failure as a sandbox-denial signature, so the framework's own
17
+ * denial marker and one-shot escalation path report it instead of a mystery crash.
18
+ *
19
+ * The result is that all three permission modes keep their exact meaning: full access
20
+ * runs Git Bash directly, and read-only/workspace-write refuse it the way they refuse any
21
+ * other write the policy does not allow — with the approval-gated escalation as the
22
+ * exit.
23
+ *
24
+ * @module dsh-hiss-plugins/gitbash/gitbash-executor
25
+ */
26
+
27
+ /**
28
+ * MSYS2's fatal startup line. The exit code alone is not a signature: `0xC0000142`
29
+ * (`STATUS_DLL_INIT_FAILED`) is what every console-isolated or token-denied child
30
+ * reports, so matching the text keeps unrelated crashes out of the denial surface.
31
+ */
32
+ export const MSYS_STARTUP_SIGNATURE = "couldn't create signal pipe";
33
+
34
+ /**
35
+ * Appended to a confined startup failure so the model and the operator read the cause
36
+ * instead of a bare `[sandbox: file access denied]` next to an MSYS2 DLL-init line.
37
+ */
38
+ export const CONFINED_STARTUP_NOTE =
39
+ "dsh-gitbash: Git Bash cannot start inside the Windows file sandbox — MSYS2 needs a named object " +
40
+ "that the sandbox's restricted token denies. This is expected in read-only/workspace-write: retry " +
41
+ "with sandbox_permissions: danger-full-access, or run the session in danger-full-access.";
42
+
43
+ /**
44
+ * Add the explanatory note to a settled run the sandbox denied for MSYS2's start-up
45
+ * failure. Every other result — including full-access runs and ordinary policy denials —
46
+ * passes through untouched, and the note is appended to stderr text only, leaving
47
+ * `truncated` and spill paths as the subprocess service reported them.
48
+ * @param {object} result - a settled {@link ShellRunResult}.
49
+ * @returns {object} the same result, annotated when it is a confined MSYS2 startup failure.
50
+ */
51
+ export function explainConfinedStartupFailure(result) {
52
+ if (result.sandbox?.denied !== true) return result;
53
+ if (!String(result.stderr?.text ?? "").includes(MSYS_STARTUP_SIGNATURE)) return result;
54
+ const text = String(result.stderr.text);
55
+ return {
56
+ ...result,
57
+ stderr: { ...result.stderr, text: `${text.endsWith("\n") ? text : `${text}\n`}${CONFINED_STARTUP_NOTE}\n` },
58
+ };
59
+ }
60
+
61
+ /**
62
+ * Substitute the resolved Git Bash for the bare `bash` the base's unconfined path asks
63
+ * for.
64
+ *
65
+ * `danger-full-access` is the one mode where MSYS2 can start at all, and the inherited
66
+ * local executor builds that argv from the literal `bash` — which on Windows resolves to
67
+ * the WSL launcher on PATH, a Linux VM with a different filesystem. The confined path
68
+ * already carries the resolved path inside the sandbox runner's argv, so only the bare
69
+ * three-entry `bash -c <command>` shape is rewritten and every other argv passes through.
70
+ * @param {string[]} argv - the executable and arguments the base is about to spawn.
71
+ * @param {string} bashPath - the resolved Git Bash executable.
72
+ * @returns {string[]} the argv to spawn.
73
+ */
74
+ export function withResolvedBash(argv, bashPath) {
75
+ return argv.length === 3 && argv[0] === "bash" && argv[1] === "-c" ? [bashPath, ...argv.slice(1)] : argv;
76
+ }
77
+
78
+ /**
79
+ * Create the executor class from a sandbox-consuming base class.
80
+ *
81
+ * The base is a parameter rather than a static import so this module stays free of host
82
+ * dependencies: `executor.js` wires the real `SandboxBashExecutor`, and tests drive the
83
+ * same behavior through a fake base.
84
+ * @param {typeof import("@deepseek-ai/dsh-bash-sandbox").SandboxBashExecutor} Base - the sandbox-consuming bash executor to extend.
85
+ * @param {object} [options] - construction inputs.
86
+ * @param {() => string} [options.resolveBash] - Git Bash resolver, injected for tests.
87
+ * @param {NodeJS.Platform} [options.platform] - platform the row runs on, injected for tests.
88
+ * @returns {typeof Base} a Service plugin registering as `ctx.shell`.
89
+ */
90
+ export function createGitBashExecutor(Base, { resolveBash = resolveGitBash, platform = process.platform } = {}) {
91
+ return class GitBashExecutor extends Base {
92
+ static inject = [...(Base.inject ?? [])];
93
+ /** Absolute `bash.exe` every command runs as. */
94
+ bashPath;
95
+ constructor(ctx, config) {
96
+ super(ctx, config);
97
+ if (platform !== "win32") throw new Error("dsh-gitbash: this row is Windows-only; the bundle patch disables it on other platforms");
98
+ this.bashPath = resolveBash();
99
+ ctx.logger.info(`dsh-gitbash: confined shell git bash = ${this.bashPath}`);
100
+ }
101
+ /**
102
+ * Wrap one command for the sandbox, replacing the inherited `bash` lookup with the
103
+ * resolved Git Bash path and teaching the shared classifier MSYS2's startup failure.
104
+ * The provider confines asynchronously and accepts the signal that cancels preparation,
105
+ * so the resolved argv is awaited before it is spread and the signal is forwarded.
106
+ * @param {string} command - shell source for the inner `bash -c`.
107
+ * @param {object} policy - resolved confined execution policy.
108
+ * @param {AbortSignal} [signal] - cancellation of confinement preparation.
109
+ * @returns {Promise<object>} the provider's exact argv and settlement-classification facts.
110
+ */
111
+ async confine(command, policy, signal) {
112
+ const confined = await this.ctx.sandbox.confine([this.bashPath, "-c", command], policy, signal);
113
+ return {
114
+ ...confined,
115
+ denialSignatures: [...(confined.denialSignatures ?? []), MSYS_STARTUP_SIGNATURE],
116
+ };
117
+ }
118
+ /**
119
+ * Keep the spawned program the resolved Git Bash on the unconfined path, whose argv the
120
+ * base builds itself as the literal three-entry `bash -c <command>`. A confined run
121
+ * prepares its own argv through {@link confine} and hands it over as a callback, so only
122
+ * an argv array is rewritten and every other call shape passes through untouched.
123
+ * @param {object} spec - the resolved spec being spawned.
124
+ * @param {string[]|((signal: AbortSignal) => string[]|Promise<string[]>)} argvOrPrepare - the base's argv, or its preparation callback.
125
+ * @param {Function} [onStarted] - the base's provider-facts hook.
126
+ * @returns {object|Promise<object>} the live process handle.
127
+ */
128
+ executeArgv(spec, argvOrPrepare, onStarted) {
129
+ return super.executeArgv(
130
+ spec,
131
+ Array.isArray(argvOrPrepare) ? withResolvedBash(argvOrPrepare, this.bashPath) : argvOrPrepare,
132
+ onStarted,
133
+ );
134
+ }
135
+ /**
136
+ * Annotate a denied MSYS2 startup failure on the settled outcome. The public entry is
137
+ * `execute()`, which resolves with the process handle before the command has run, so the
138
+ * annotation wraps `result()` — the one place the settled run and its sandbox facts are
139
+ * both available — rather than a settled return value.
140
+ * @param {object} spec - the resolved spec being spawned.
141
+ * @returns {Promise<object>} the live process handle.
142
+ */
143
+ async execute(spec) {
144
+ const handle = await super.execute(spec);
145
+ const settled = handle.result.bind(handle);
146
+ handle.result = () => settled().then(explainConfinedStartupFailure);
147
+ return handle;
148
+ }
149
+ };
150
+ }
@@ -0,0 +1,49 @@
1
+ import { SandboxBashExecutor } from "@deepseek-ai/dsh-bash-sandbox";
2
+ import * as BashTool from "@deepseek-ai/dsh-tool-bash";
3
+ import { createGitBashExecutor } from "./gitbash-executor.js";
4
+
5
+ /**
6
+ * The `dsh-hiss-plugins/gitbash` row: this machine's Git Bash as a
7
+ * first-class shell on Windows.
8
+ *
9
+ * A composition root rather than an executor. The bundle patch gives this one row its own
10
+ * realm (`isolate: {shell, settings}`) and this module mounts both halves into it:
11
+ *
12
+ * 1. `createGitBashExecutor(SandboxBashExecutor)` registers `ctx.shell` — DSH's own
13
+ * sandbox-consuming bash executor, running the resolved `bash.exe` instead of PATH's
14
+ * `bash` (the WSL launcher on Windows) and reporting MSYS2's startup failure as a
15
+ * sandbox denial. It inherits `dsh-bash-sandbox` → `dsh-bash-local`, whose constructor
16
+ * installs the shared `shell` settings namespace; the host's Windows executor already
17
+ * registered it and `ctx.settings.register` fails loud on a duplicate, so the row
18
+ * isolates `settings` too and this executor registers nothing.
19
+ * 2. `tool-bash` sits next to its provider, which is the only place it resolves this
20
+ * realm's executor. Left outside the realm it would silently resolve the host's pwsh
21
+ * executor and the `bash` tool would run PowerShell.
22
+ *
23
+ * Both halves hang off ONE top-level row because children of a `cordis:group` are
24
+ * unaddressable for the plugin manager: a nested row can never be switched on or off from
25
+ * the Plugins page (`test/patch.test.js` guards that shape). The host's own
26
+ * `pwsh-sandbox` row keeps providing the root `shell`, so every pre-existing row and
27
+ * preset resolves exactly as before.
28
+ *
29
+ * The rest of the rationale — why the host `shell` row is not replaced, and why a confined
30
+ * `bash` call is reported as a sandbox denial — lives in `cordis.patch.yml` and
31
+ * `gitbash-executor.js`.
32
+ *
33
+ * @module dsh-hiss-plugins/gitbash
34
+ */
35
+ const GitBashExecutor = createGitBashExecutor(SandboxBashExecutor);
36
+
37
+ export const name = "dsh-hiss-plugins-gitbash";
38
+ export const inject = [];
39
+
40
+ /**
41
+ * Mount the executor and its consumer into this row's realm.
42
+ * @param {object} ctx - the row's context.
43
+ * @param {object} [config] - the row's config, forwarded to the executor.
44
+ * @returns {void}
45
+ */
46
+ export function apply(ctx, config) {
47
+ ctx.plugin(GitBashExecutor, config);
48
+ ctx.plugin(BashTool);
49
+ }
@@ -0,0 +1,98 @@
1
+ import { existsSync } from "node:fs";
2
+ import { basename, delimiter, dirname, join } from "node:path";
3
+
4
+ /**
5
+ * Locate the Git for Windows installation that owns `bash.exe`.
6
+ *
7
+ * A bare `bash` on PATH is not good enough on Windows: `C:\Windows\System32\bash.exe`
8
+ * (the WSL launcher) and the `WindowsApps` alias sit on every PATH and would silently
9
+ * hand the model a Linux VM instead of Git Bash, whose filesystem and `cwd` mapping
10
+ * differ completely. So every discovery route below is validated against the Git for
11
+ * Windows layout — `bin/bash.exe` next to `cmd/git.exe` — and an explicitly configured
12
+ * path is the only route that skips the layout check.
13
+ *
14
+ * @module dsh-hiss-plugins/gitbash/resolve
15
+ */
16
+
17
+ /** Environment variable naming one exact `bash.exe`, for non-standard or portable installs. */
18
+ export const BASH_PATH_ENV = "DSH_GIT_BASH";
19
+
20
+ /** Environment variables naming a Git for Windows installation root. */
21
+ export const GIT_ROOT_ENVS = ["GIT_ROOT", "GIT_INSTALL_ROOT"];
22
+
23
+ /** The `bash.exe` a Git for Windows root owns. */
24
+ export function bashPathIn(root) {
25
+ return join(root, "bin", "bash.exe");
26
+ }
27
+
28
+ /** Whether `root` carries the Git for Windows layout: `bin/bash.exe` plus `cmd/git.exe` or `usr/bin/bash.exe`. */
29
+ export function isGitRoot(root, exists = existsSync) {
30
+ return (
31
+ exists(bashPathIn(root)) &&
32
+ (exists(join(root, "cmd", "git.exe")) || exists(join(root, "usr", "bin", "bash.exe")))
33
+ );
34
+ }
35
+
36
+ /**
37
+ * Installation roots implied by PATH, in PATH order. A directory holding `git.exe`
38
+ * implies its parent (`<root>\cmd` in the standard install); a directory that is itself
39
+ * a Git root is taken as is. Directories such as `System32` and `WindowsApps` hold a
40
+ * `bash.exe` but no `git.exe`, so they never produce a candidate.
41
+ * @param {string} pathValue - a raw PATH value.
42
+ * @param {(path: string) => boolean} [exists] - file probe, injected for tests.
43
+ * @returns {string[]} candidate roots, unresolved against the layout check.
44
+ */
45
+ export function rootsFromPath(pathValue, exists = existsSync) {
46
+ const roots = [];
47
+ for (const entry of String(pathValue ?? "").split(delimiter)) {
48
+ if (entry.length === 0) continue;
49
+ if (exists(join(entry, "git.exe"))) roots.push(basename(entry).toLowerCase() === "cmd" ? dirname(entry) : entry);
50
+ }
51
+ return roots;
52
+ }
53
+
54
+ /** Roots a standard Windows install can use, in preference order. */
55
+ export function defaultRoots(env = process.env) {
56
+ const roots = [];
57
+ for (const name of ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"]) {
58
+ const base = env[name];
59
+ if (typeof base === "string" && base.length > 0) roots.push(join(base, "Git"));
60
+ }
61
+ if (typeof env.LOCALAPPDATA === "string" && env.LOCALAPPDATA.length > 0) {
62
+ roots.push(join(env.LOCALAPPDATA, "Programs", "Git"));
63
+ }
64
+ return roots;
65
+ }
66
+
67
+ /**
68
+ * Resolve the Git Bash executable to run.
69
+ *
70
+ * Precedence is explicit-before-discovered: a configured path that does not exist is an
71
+ * error rather than a silent fallback, because falling back would run a different shell
72
+ * than the one the operator pinned.
73
+ * @param {object} [options] - resolution inputs.
74
+ * @param {NodeJS.ProcessEnv} [options.env] - environment to read.
75
+ * @param {(path: string) => boolean} [options.exists] - file probe, injected for tests.
76
+ * @returns {string} absolute path of the `bash.exe` to execute.
77
+ * @throws {Error} when no Git Bash is found, naming every route that was tried.
78
+ */
79
+ export function resolveGitBash({ env = process.env, exists = existsSync } = {}) {
80
+ const explicit = env[BASH_PATH_ENV];
81
+ if (typeof explicit === "string" && explicit.length > 0) {
82
+ if (!exists(explicit)) throw new Error(`dsh-gitbash: ${BASH_PATH_ENV} points at a missing file: ${explicit}`);
83
+ return explicit;
84
+ }
85
+ for (const name of GIT_ROOT_ENVS) {
86
+ const root = env[name];
87
+ if (typeof root !== "string" || root.length === 0) continue;
88
+ const candidate = bashPathIn(root);
89
+ if (!exists(candidate)) throw new Error(`dsh-gitbash: ${name} does not hold bin/bash.exe: ${root}`);
90
+ return candidate;
91
+ }
92
+ const roots = [...rootsFromPath(env.PATH, exists), ...defaultRoots(env)];
93
+ for (const root of roots) if (isGitRoot(root, exists)) return bashPathIn(root);
94
+ throw new Error(
95
+ `dsh-gitbash: no Git for Windows installation found among ${roots.length} candidate root(s). ` +
96
+ `Install Git for Windows, or set ${BASH_PATH_ENV} to the bash.exe to run.`,
97
+ );
98
+ }
package/lib/index.js ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * The bundle's carrier row: no host behaviour of its own.
3
+ *
4
+ * It exists because the client module system only serves a package's browser half
5
+ * (`lib/client.js`) when that package holds a Loader row — the management tab in the
6
+ * Plugins page arrives through this row and nothing else. The four features live in
7
+ * their own top-level rows, so switching one of them never removes this seat.
8
+ *
9
+ * @module dsh-hiss-plugins
10
+ */
11
+ export const name = "dsh-hiss-plugins";
12
+ export const inject = [];
13
+ export function apply() {}
@@ -0,0 +1,158 @@
1
+ import { access, readFile } from "node:fs/promises";
2
+ import { dirname, join, resolve } from "node:path";
3
+
4
+ /**
5
+ * Whether a path exists, without caring why it does not.
6
+ * @param {string} path - absolute path to test.
7
+ * @returns {Promise<boolean>} true when the path is readable.
8
+ */
9
+ async function exists(path) {
10
+ try {
11
+ await access(path);
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Locate the `.mcp.json` governing a session directory: the file in `cwd`
20
+ * itself, else the nearest ancestor's. The walk stops at the first directory
21
+ * holding `.git` — the project root — so a session inside a repository never
22
+ * inherits a parent repository's servers. A path with no `.git` anywhere walks
23
+ * to the filesystem root.
24
+ *
25
+ * @param {string} cwd - the session's absolute working directory.
26
+ * @returns {Promise<string | undefined>} absolute config path, or undefined.
27
+ */
28
+ export async function findConfigPath(cwd) {
29
+ let current = resolve(cwd);
30
+ for (;;) {
31
+ const candidate = join(current, ".mcp.json");
32
+ if (await exists(candidate)) return candidate;
33
+ if (await exists(join(current, ".git"))) return undefined;
34
+ const parent = dirname(current);
35
+ if (parent === current) return undefined;
36
+ current = parent;
37
+ }
38
+ }
39
+
40
+ /** `${VAR}` with an optional `:-default`, as Claude Code writes them. */
41
+ const VARIABLE = /\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
42
+
43
+ /**
44
+ * Interpolate `${VAR}` / `${VAR:-default}` in a string. An unset variable with
45
+ * no default becomes the empty string, matching shell defaults closely enough
46
+ * that a missing token fails visibly at the server rather than silently
47
+ * launching with a literal `${TOKEN}`.
48
+ *
49
+ * @param {string} value - raw string from the config file.
50
+ * @returns {string} the interpolated string.
51
+ */
52
+ export function expand(value) {
53
+ return value.replace(VARIABLE, (_match, name, fallback) => process.env[name] ?? fallback ?? "");
54
+ }
55
+
56
+ /** Expand every string in a nested value; non-strings pass through. */
57
+ function expandDeep(value) {
58
+ if (typeof value === "string") return expand(value);
59
+ if (Array.isArray(value)) return value.map(expandDeep);
60
+ if (value !== null && typeof value === "object") {
61
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, expandDeep(entry)]));
62
+ }
63
+ return value;
64
+ }
65
+
66
+ /** True for a plain object, so arrays and null are rejected as records. */
67
+ function isRecord(value) {
68
+ return value !== null && typeof value === "object" && !Array.isArray(value);
69
+ }
70
+
71
+ /** Every value a string, or undefined when the record is absent. */
72
+ function stringRecord(value, field, serverName) {
73
+ if (value === undefined) return undefined;
74
+ if (!isRecord(value)) throw new Error(`"${serverName}": ${field} must be an object`);
75
+ for (const [key, entry] of Object.entries(value)) {
76
+ if (typeof entry !== "string") throw new Error(`"${serverName}": ${field}.${key} must be a string`);
77
+ }
78
+ return value;
79
+ }
80
+
81
+ /**
82
+ * Turn one `mcpServers` entry into the config the host MCP client accepts.
83
+ * Throws for anything the client could not use, so the caller can report the
84
+ * server by name and carry on with its siblings.
85
+ *
86
+ * @param {string} serverName - the entry's key, which becomes the tool namespace.
87
+ * @param {unknown} entry - the raw entry value.
88
+ * @param {string} projectDir - directory holding `.mcp.json`, the stdio default cwd.
89
+ * @returns {Record<string, unknown>} an unvalidated `dsh-mcp-client` config.
90
+ */
91
+ function toSpec(serverName, entry, projectDir) {
92
+ if (!isRecord(entry)) throw new Error(`"${serverName}": entry must be an object`);
93
+ const type = entry.type ?? "stdio";
94
+ if (type === "http") {
95
+ if (typeof entry.url !== "string" || entry.url === "") throw new Error(`"${serverName}": url must be a non-empty string`);
96
+ const headers = stringRecord(entry.headers, "headers", serverName);
97
+ return {
98
+ transport: "streamable-http",
99
+ serverName,
100
+ url: entry.url,
101
+ ...(headers === undefined ? {} : { headers }),
102
+ };
103
+ }
104
+ if (type !== "stdio") throw new Error(`"${serverName}": unsupported transport "${String(type)}"`);
105
+ if (typeof entry.command !== "string" || entry.command === "") {
106
+ throw new Error(`"${serverName}": command must be a non-empty string`);
107
+ }
108
+ const args = entry.args ?? [];
109
+ if (!Array.isArray(args) || args.some((arg) => typeof arg !== "string")) {
110
+ throw new Error(`"${serverName}": args must be an array of strings`);
111
+ }
112
+ const env = stringRecord(entry.env, "env", serverName);
113
+ if (entry.cwd !== undefined && typeof entry.cwd !== "string") throw new Error(`"${serverName}": cwd must be a string`);
114
+ return {
115
+ transport: "stdio",
116
+ serverName,
117
+ command: entry.command,
118
+ args,
119
+ ...(env === undefined ? {} : { env }),
120
+ cwd: resolve(projectDir, entry.cwd ?? "."),
121
+ };
122
+ }
123
+
124
+ /**
125
+ * Read one `.mcp.json` and describe every server in it. The file is untrusted
126
+ * project content, so a malformed entry is reported by name rather than
127
+ * dropped: a silently missing tool is indistinguishable from a broken one.
128
+ *
129
+ * @param {string} configPath - absolute path to the `.mcp.json`.
130
+ * @param {string} cwd - the session directory the config was found for.
131
+ * @returns {Promise<{ servers: { serverName: string, spec: Record<string, unknown> }[], skipped: { serverName: string, reason: string }[] }>}
132
+ * the servers to mount, and the entries that could not be used.
133
+ * @throws when the file is unreadable, is not JSON, or has a malformed `mcpServers`.
134
+ */
135
+ export async function loadServers(configPath, cwd) {
136
+ const raw = await readFile(configPath, "utf8");
137
+ let parsed;
138
+ try {
139
+ parsed = JSON.parse(raw);
140
+ } catch (error) {
141
+ throw new Error(`${configPath} is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
142
+ }
143
+ if (!isRecord(parsed)) throw new Error(`${configPath} must contain a JSON object`);
144
+ const declared = parsed.mcpServers;
145
+ if (declared === undefined) return { servers: [], skipped: [] };
146
+ if (!isRecord(declared)) throw new Error(`${configPath}: mcpServers must be an object`);
147
+ const projectDir = dirname(resolve(configPath));
148
+ const servers = [];
149
+ const skipped = [];
150
+ for (const [serverName, entry] of Object.entries(declared)) {
151
+ try {
152
+ servers.push({ serverName, spec: toSpec(serverName, expandDeep(entry), projectDir) });
153
+ } catch (error) {
154
+ skipped.push({ serverName, reason: error instanceof Error ? error.message : String(error) });
155
+ }
156
+ }
157
+ return { servers, skipped };
158
+ }
@@ -0,0 +1,85 @@
1
+ import * as McpClient from "@deepseek-ai/dsh-mcp-client";
2
+ import { findConfigPath, loadServers } from "./config.js";
3
+
4
+ export const name = "project-mcp";
5
+ export const inject = ["agents"];
6
+
7
+ /** Readable text for anything a rejected promise or a schema can throw. */
8
+ function message(error) {
9
+ return error instanceof Error ? error.message : String(error);
10
+ }
11
+
12
+ /**
13
+ * Mount every server declared by the session project's `.mcp.json` into one
14
+ * agent's own scope. `agent.ctx` is the agent's scoped context, so the mount
15
+ * lives and dies with the agent: two sessions in different projects never
16
+ * collide on a server name, and a subagent created under this agent inherits
17
+ * the same tools without mounting anything itself.
18
+ *
19
+ * Every failure is reported and skipped. `.mcp.json` is untrusted project
20
+ * content, and a bad entry must cost its own server at most — never the
21
+ * session, which is why nothing here rejects.
22
+ *
23
+ * @param {import("@deepseek-ai/cordis").Context} ctx - host context, for logging.
24
+ * @param {{ session?: { header?: { cwd?: string } }, ctx?: unknown }} agent - the live agent.
25
+ * @returns {Promise<number>} how many servers were mounted.
26
+ */
27
+ export async function mountProjectMcp(ctx, agent) {
28
+ const cwd = agent?.session?.header?.cwd;
29
+ if (typeof cwd !== "string" || cwd === "") return 0;
30
+ const configPath = await findConfigPath(cwd);
31
+ if (configPath === undefined) return 0;
32
+
33
+ let loaded;
34
+ try {
35
+ loaded = await loadServers(configPath, cwd);
36
+ } catch (error) {
37
+ ctx.logger.warn(`project-mcp: ${message(error)}`);
38
+ return 0;
39
+ }
40
+ for (const { serverName, reason } of loaded.skipped) {
41
+ ctx.logger.warn(`project-mcp: ${configPath}: "${serverName}" was skipped: ${reason}`);
42
+ }
43
+
44
+ let mounted = 0;
45
+ for (const { serverName, spec } of loaded.servers) {
46
+ let config;
47
+ try {
48
+ // The bridge's own schema is the gate: it decides what a server may
49
+ // ask the host process to do, and it rejects a name that would make
50
+ // an unusable tool namespace.
51
+ config = McpClient.Config(spec);
52
+ } catch (error) {
53
+ ctx.logger.warn(`project-mcp: ${configPath}: "${serverName}" is not a usable MCP server: ${message(error)}`);
54
+ continue;
55
+ }
56
+ try {
57
+ await agent.ctx.plugin(McpClient, config);
58
+ mounted += 1;
59
+ } catch (error) {
60
+ ctx.logger.warn(`project-mcp: ${configPath}: "${serverName}" failed to start: ${message(error)}`);
61
+ }
62
+ }
63
+ return mounted;
64
+ }
65
+
66
+ /**
67
+ * Mount the project's servers for every agent whose session directory declares
68
+ * them. The registration is awaited by the agent registry before creation
69
+ * completes, so a session's first turn already sees its MCP tools.
70
+ *
71
+ * @param {import("@deepseek-ai/cordis").Context} ctx - the host context.
72
+ */
73
+ export function apply(ctx) {
74
+ const wire = async (agent) => {
75
+ try {
76
+ const mounted = await mountProjectMcp(ctx, agent);
77
+ if (mounted > 0) ctx.logger.info(`project-mcp: mounted ${mounted} server(s) for ${agent.id}`);
78
+ } catch (error) {
79
+ ctx.logger.warn(`project-mcp: mounting failed for ${String(agent?.id)}: ${message(error)}`);
80
+ }
81
+ };
82
+ ctx.on("agent/created", ({ agent }) => wire(agent));
83
+ // A reload mid-session must reach agents that are already live.
84
+ for (const agent of ctx.agents.list()) void wire(agent);
85
+ }
package/locale/en.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "meta": {
3
+ "title": "dsh-hiss-plugins",
4
+ "description": "One DeepSeek Harness bundle carrying four switchable plugins — colgrep, codegraph, project-mcp and git-bash — managed from a tab in the Plugins page."
5
+ },
6
+ "loading": "Reading plugins…",
7
+ "error": "Plugins are unavailable: {error}",
8
+ "retry": "Retry",
9
+ "empty": "This bundle declares no plugin rows.",
10
+ "enabledTag": "Enabled",
11
+ "disabledTag": "Disabled",
12
+ "toggleAria": "Toggle {name}",
13
+ "toggleFailed": "Switching {name} failed: {error}",
14
+ "restartRequired": "The change to {name} takes effect after DSH restarts.",
15
+ "reasonManagementRequired": "DSH manages this plugin itself, so it cannot be switched from this page.",
16
+ "reasonUnaddressable": "This plugin's row cannot be addressed in the profile; edit cordis.patch.yml by hand.",
17
+ "reasonUnknown": "This plugin cannot be switched from this page ({code}).",
18
+ "featureColgrepDescription": "semantic code search tool",
19
+ "featureCodegraphDescription": "CodeGraph MCP tools",
20
+ "featureProjectMcpDescription": "mounts the project's .mcp.json per session",
21
+ "featureGitbashDescription": "Git Bash shell on Windows"
22
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "meta": {
3
+ "title": "dsh-hiss-plugins",
4
+ "description": "一个 DeepSeek Harness 组合包,携带 colgrep、codegraph、project-mcp、git-bash 四个可独立开关的插件,并在插件页提供管理标签。"
5
+ },
6
+ "loading": "正在读取插件…",
7
+ "error": "暂时无法读取插件:{error}",
8
+ "retry": "重试",
9
+ "empty": "本包没有声明任何插件行。",
10
+ "enabledTag": "已启用",
11
+ "disabledTag": "已停用",
12
+ "toggleAria": "切换 {name}",
13
+ "toggleFailed": "切换 {name} 失败:{error}",
14
+ "restartRequired": "{name} 的改动将在重启 DSH 后生效。",
15
+ "reasonManagementRequired": "该插件由 DSH 自身管理,无法在这个页面切换。",
16
+ "reasonUnaddressable": "无法在 profile 中定位该插件的行,请手动修改 cordis.patch.yml。",
17
+ "reasonUnknown": "该插件无法在这个页面切换({code})。",
18
+ "featureColgrepDescription": "语义代码检索工具",
19
+ "featureCodegraphDescription": "代码图 MCP 工具",
20
+ "featureProjectMcpDescription": "按会话挂载项目 .mcp.json",
21
+ "featureGitbashDescription": "Windows 上的 Git Bash shell"
22
+ }