dsh-hiss-plugins 0.0.0-stage → 1.1.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,125 @@
1
+ /**
2
+ * The ponytail adoption layer: the mode-aware prompt section and the `/ponytail`
3
+ * level switch.
4
+ *
5
+ * This restores the half of the deleted `@hilariouhiss/dsh-ponytail` plugin that DSH
6
+ * cannot supply natively. The six ponytail skills are discovered from a scanned root
7
+ * (`~/.agents/skills` by default) and `/ponytail-review` and friends already work
8
+ * through the harness's own user-invocation path, so this row vendors nothing and
9
+ * registers no skill provider and no per-skill commands. What is missing without it
10
+ * is the *level*: an always-on hint that keeps the skill in play, and a switch that
11
+ * changes how hard it applies.
12
+ *
13
+ * @module dsh-hiss-plugins/ponytail
14
+ */
15
+ import { createUserMessage } from "@deepseek-ai/dsh-llm";
16
+ import { renderSkillContent } from "@deepseek-ai/dsh-skill";
17
+ import { currentMode, parseLevel, resolveDefaultMode, setMode } from "./mode.js";
18
+
19
+ export const name = "ponytail";
20
+ export const inject = ["commands", "skills", "systemPrompt", "workingDirectory"];
21
+
22
+ /** The skill this layer adopts. */
23
+ const SKILL = "ponytail";
24
+
25
+ /** The adoption hint, unchanged from the plugin this replaces. */
26
+ export const HINT_TEXT = [
27
+ "Ponytail lazy-mode is available for coding work. ",
28
+ "Before any coding task — writing, editing, refactoring, fixing, reviewing, or choosing libraries/dependencies — ",
29
+ "load the `ponytail` skill with the `skill` tool (unless already loaded) and follow it: ",
30
+ "the simplest solution that works, reuse what already exists, standard library and platform features before new dependencies, ",
31
+ "fewest files, shortest working diff. ",
32
+ "Switch intensity with /ponytail lite|full|ultra; turn off with /ponytail off or by saying \"stop ponytail\".",
33
+ ].join("");
34
+
35
+ /**
36
+ * The section text for one assembly scope.
37
+ *
38
+ * The level is part of the hint so the text stays true after a restart, when the
39
+ * per-agent override is gone and the default is back in force.
40
+ *
41
+ * @param {object | undefined} scope the assembling agent, when there is one.
42
+ * @param {"off" | "lite" | "full" | "ultra"} fallback the resolved default level.
43
+ * @returns {string} the hint, or `''` when ponytail is off.
44
+ */
45
+ export function hintFor(scope, fallback) {
46
+ const level = currentMode(scope, fallback);
47
+ return level === "off" ? "" : `${HINT_TEXT} Current level: ${level}.`;
48
+ }
49
+
50
+ /**
51
+ * Register the global adoption section and the `/ponytail` command.
52
+ *
53
+ * @param {import("@deepseek-ai/cordis").Context} ctx - host context carrying
54
+ * `systemPrompt`, `commands`, `skills`, and `workingDirectory`.
55
+ */
56
+ export function apply(ctx) {
57
+ const defaultMode = resolveDefaultMode();
58
+ ctx.systemPrompt.section({
59
+ name: "ponytail:adoption",
60
+ order: 5,
61
+ text: (context) => hintFor(context.scope, defaultMode),
62
+ });
63
+ ctx.commands.register({
64
+ name: SKILL,
65
+ description: "switch ponytail lazy-mode intensity (lite|full|ultra|off)",
66
+ input: { hint: "[lite|full|ultra|off]" },
67
+ handler: (invocation) => runPonytail(ctx, invocation),
68
+ });
69
+ }
70
+
71
+ /**
72
+ * Execute one `/ponytail` invocation.
73
+ *
74
+ * The skill loads *before* the level changes: a level the model cannot act on is
75
+ * worse than no level at all, so a missing or unreadable skill leaves the state
76
+ * untouched.
77
+ *
78
+ * @param {object} ctx host context.
79
+ * @param {object} invocation the command invocation.
80
+ * @returns {Promise<{ kind: "success" | "error", text: string }>} the command result.
81
+ */
82
+ async function runPonytail(ctx, invocation) {
83
+ const level = parseLevel(invocation.rawInput);
84
+ if (level === undefined) {
85
+ return { kind: "error", text: "Usage: /ponytail [lite|full|ultra|off]" };
86
+ }
87
+ if (level === "off") {
88
+ setMode(invocation.agent, "off");
89
+ followup(invocation, "Ponytail off — revert to normal mode. Ignore the ponytail instructions until it is turned back on with /ponytail.");
90
+ return { kind: "success", text: "Ponytail off." };
91
+ }
92
+ let skill;
93
+ try {
94
+ skill = await ctx.skills.get(SKILL, {
95
+ cwd: await ctx.workingDirectory.ensure(invocation.agent, invocation.signal),
96
+ signal: invocation.signal,
97
+ scope: invocation.agent,
98
+ });
99
+ } catch (error) {
100
+ return { kind: "error", text: `Could not load the "${SKILL}" skill: ${error instanceof Error ? error.message : String(error)}` };
101
+ }
102
+ if (skill === undefined) {
103
+ return {
104
+ kind: "error",
105
+ text: `The "${SKILL}" skill is not available. Install it into a skills root DSH scans (for example the shared ~/.agents/skills root) and retry.`,
106
+ };
107
+ }
108
+ setMode(invocation.agent, level);
109
+ followup(invocation, `${renderSkillContent(skill)}\n\nPonytail level: ${level}. Apply the ${level} column of the Intensity table from now on.`);
110
+ return { kind: "success", text: `Ponytail mode set to ${level}.` };
111
+ }
112
+
113
+ /**
114
+ * Hand the model a durable user message through the same seam `/goal` uses, so the
115
+ * instructions are read on the very next step.
116
+ *
117
+ * @param {object} invocation the command invocation.
118
+ * @param {string} text the message text.
119
+ */
120
+ function followup(invocation, text) {
121
+ invocation.agent.followup(createUserMessage({
122
+ content: [{ type: "text", text }],
123
+ source: { kind: "skill-invocation", name: SKILL, form: "instructions" },
124
+ }));
125
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Ponytail level logic: the level grammar, the default-level resolution, and the
3
+ * per-agent override table.
4
+ *
5
+ * Deliberately free of host imports, so every branch here runs under this repo's own
6
+ * `node --test` without a DSH context (the same split `lib/gitbash/resolve.js` and
7
+ * `lib/project-mcp/config.js` use).
8
+ *
9
+ * @module dsh-hiss-plugins/ponytail/mode
10
+ */
11
+ import { readFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { join } from "node:path";
14
+
15
+ /** The levels the upstream skill documents, plus `off`. */
16
+ export const LEVELS = new Set(["lite", "full", "ultra", "off"]);
17
+
18
+ /**
19
+ * Per-agent level overrides.
20
+ *
21
+ * In-process and keyed by the agent object, exactly like the plugin this replaces:
22
+ * the level is a property of the running session, while the *default* is the
23
+ * durable value and comes from the environment or the upstream config file.
24
+ */
25
+ const modes = new WeakMap();
26
+
27
+ /**
28
+ * The level currently in force for one agent.
29
+ *
30
+ * @param {object | undefined} agent the agent (an assembly scope) or nothing.
31
+ * @param {"off" | "lite" | "full" | "ultra"} fallback the resolved default level.
32
+ * @returns {"off" | "lite" | "full" | "ultra"} the override, or the fallback.
33
+ */
34
+ export function currentMode(agent, fallback) {
35
+ return modes.get(agent) ?? fallback;
36
+ }
37
+
38
+ /**
39
+ * Record one agent's level override.
40
+ *
41
+ * @param {object} agent the agent whose level changes.
42
+ * @param {"off" | "lite" | "full" | "ultra"} level the new level.
43
+ */
44
+ export function setMode(agent, level) {
45
+ modes.set(agent, level);
46
+ }
47
+
48
+ /**
49
+ * Parse the `/ponytail` argument.
50
+ *
51
+ * @param {string} rawInput the exact text following the command name.
52
+ * @returns {"off" | "lite" | "full" | "ultra" | undefined} the level, a bare
53
+ * invocation meaning `full`, or `undefined` for anything the grammar rejects.
54
+ */
55
+ export function parseLevel(rawInput) {
56
+ if (typeof rawInput !== "string") return undefined;
57
+ const input = rawInput.trim().toLowerCase();
58
+ if (input.length === 0) return "full";
59
+ return LEVELS.has(input) ? input : undefined;
60
+ }
61
+
62
+ /**
63
+ * Normalize one candidate level from an environment variable or config file.
64
+ *
65
+ * @param {unknown} value the raw candidate.
66
+ * @returns {"off" | "lite" | "full" | "ultra" | undefined} the level, or nothing.
67
+ */
68
+ export function normalizeMode(value) {
69
+ if (typeof value !== "string") return undefined;
70
+ const mode = value.trim().toLowerCase();
71
+ return LEVELS.has(mode) ? mode : undefined;
72
+ }
73
+
74
+ /**
75
+ * The upstream-compatible config path: `%APPDATA%\ponytail\config.json` on Windows,
76
+ * `$XDG_CONFIG_HOME/ponytail/config.json` (default `~/.config`) elsewhere.
77
+ *
78
+ * @param {Record<string, string | undefined>} [env] environment to read.
79
+ * @returns {string} absolute path to the config file.
80
+ */
81
+ export function defaultConfigPath(env = process.env) {
82
+ if (process.platform === "win32" && typeof env.APPDATA === "string" && env.APPDATA !== "") {
83
+ return join(env.APPDATA, "ponytail", "config.json");
84
+ }
85
+ const xdg = typeof env.XDG_CONFIG_HOME === "string" && env.XDG_CONFIG_HOME !== ""
86
+ ? env.XDG_CONFIG_HOME
87
+ : join(homedir(), ".config");
88
+ return join(xdg, "ponytail", "config.json");
89
+ }
90
+
91
+ /**
92
+ * Resolve the default level the way upstream does: `PONYTAIL_DEFAULT_MODE` first,
93
+ * then the config file's `defaultMode`, then `full`. An unreadable, missing, or
94
+ * malformed config file is not an error — it just falls through.
95
+ *
96
+ * @param {Record<string, string | undefined>} [env] environment to read.
97
+ * @param {string} [configPath] config file to read.
98
+ * @returns {"off" | "lite" | "full" | "ultra"} the resolved default.
99
+ */
100
+ export function resolveDefaultMode(env = process.env, configPath = defaultConfigPath(env)) {
101
+ const fromEnv = normalizeMode(env.PONYTAIL_DEFAULT_MODE);
102
+ if (fromEnv !== undefined) return fromEnv;
103
+ try {
104
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
105
+ if (parsed !== null && typeof parsed === "object") {
106
+ const fromFile = normalizeMode(parsed.defaultMode);
107
+ if (fromFile !== undefined) return fromFile;
108
+ }
109
+ } catch {
110
+ // Missing, unreadable, or malformed config: fall through to the default.
111
+ }
112
+ return "full";
113
+ }