Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions pkgs/mcpx/plugin/core/options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* Core option resolution, against the v1 semantics the resolver
* documents (oracle: the resolveOptions contract in options.ts --
* plugin option first, then the environment variable, then the
* caller's default; an explicit empty bin is a decision to forbid
* spawning, never an absence; an unrecognised truthy value is
* undefined, so the default applies).
*
* bun test plugin/core/options.test.ts
*/
import { describe, expect, test } from "bun:test";
import { resolveOptions, truthy } from "./options.ts";

describe("truthy (oracle: v1 truthy parse)", () => {
test("recognised spellings parse, unrecognised is undefined", () => {
expect(truthy("1")).toBe(true);
expect(truthy("off")).toBe(false);
expect(truthy(true)).toBe(true);
expect(truthy("maybe")).toBeUndefined();
expect(truthy("")).toBeUndefined();
expect(truthy(undefined)).toBeUndefined();
});
});

describe("resolveOptions (oracle: option > env > default)", () => {
test("defaults land when nothing is set", () => {
const r = resolveOptions(undefined, {});
expect(r.backend).toBe("auto");
expect(r.remember).toBe("session");
expect(r.annotate).toBe(true);
expect(r.tools).toBe(false);
expect(r.instructions).toBe(false);
expect(r.toolTiming).toBe(false);
expect(r.answerSampling).toBe(true);
expect(r.endpoint).toBeUndefined();
expect(r.bin).toBeUndefined();
});

test("env beats default, option beats env", () => {
const env = { MCPX_PLUGIN_BACKEND: "cli", MCPX_DAEMON_ENDPOINT: "unix:///tmp/x" };
expect(resolveOptions(undefined, env).backend).toBe("cli");
expect(resolveOptions({ backend: "v1" }, env).backend).toBe("v1");
expect(resolveOptions(undefined, env).endpoint).toBe("unix:///tmp/x");
});

test("an explicit empty bin forbids spawning and survives resolution", () => {
expect(resolveOptions({ bin: "" }, { MCPX_PLUGIN_BIN: "/usr/bin/mcpx" }).bin).toBe("");
expect(resolveOptions(undefined, { MCPX_PLUGIN_BIN: "/usr/bin/mcpx" }).bin).toBe("/usr/bin/mcpx");
});

test("binArgs strings split, arrays pass through", () => {
expect(resolveOptions({ binArgs: "--flag value" }, {}).binArgs).toEqual(["--flag", "value"]);
expect(resolveOptions({ binArgs: ["a"] }, {}).binArgs).toEqual(["a"]);
});

test("disabledTools parses arrays and separated strings", () => {
expect(resolveOptions({ disabledTools: ["mcpx_exec"] }, {}).disabledTools).toEqual(["mcpx_exec"]);
expect(resolveOptions(undefined, { MCPX_PLUGIN_DISABLED_TOOLS: "mcpx_exec, mcpx_search" }).disabledTools).toEqual([
"mcpx_exec",
"mcpx_search",
]);
});
});
149 changes: 149 additions & 0 deletions pkgs/mcpx/plugin/core/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
/**
* Plugin options, harness-free core (#1861): the single home for the
* Options type, the v1-way resolver and its helpers, consumed by both
* OpenCode adapters. v2 resolves through resolveOptions below; v1
* (mcpx-session.ts) imports the shared Options type and truthy parse
* and applies its own adapter defaults on top (full env by default,
* TUNING.bin / TUNING.missCooldownMs fallbacks, headless detection) --
* those defaults are adapter decisions, not core semantics.
*
* Settings guard: TestThePluginReadsNoUndeclaredSetting scans plugin/**,
* so the v2 tree reads only names the registry or the script-env contract
* declares — the MCPX_PLUGIN_* names in internal/settings/plugin.go, plus
* MCPX_DAEMON_ENDPOINT / MCPX_ENDPOINT / MCPX_SOCKET from scriptenv.go,
* the same names v1 reads. The reads are
* property accesses (env.MCPX_PLUGIN_BIN and friends), never quoted
* literals: TestTheScriptEnvironmentIsWhatTheCodeSets treats a quoted
* MCPX_* name as a variable the plugin SETS into a child's environment,
* and these are reads, not sets. (An earlier draft listed the names in
* a quoted array and failed that test on all twelve.)
*/
import { goDurationMs, splitArgs } from "./daemon.ts";

export type Options = {
/** A daemon named outright. `unix:///path` or `http://host:port`. */
endpoint?: string;
/** A socket named outright. */
socket?: string;
/** The mcpx binary, or "" to forbid spawning one. */
bin?: string;
/** Arguments to put before mcpx's own, as a vector or a string. */
binArgs?: string[] | string;
/** Where the opt-in tools get their answers: auto, v1 or cli. */
backend?: "auto" | "v1" | "cli";
/** Default scope for a daemon choice made this session. */
remember?: "session" | "until-gone" | "indefinite";
/** How much to inject into shell environments. */
env?: "minimal" | "standard" | "full";
instructions?: boolean;
toolTiming?: boolean;
/**
* Answer mcpx sampling questions (broker sample rows routed to the
* agent) with ctx.generate.text. Default on when the host offers
* ctx.generate; false turns the watcher off. Plugin-option only --
* no env name is declared for it in the settings registry, and the
* settings guard forbids reading undeclared MCPX_* names.
*/
answerSampling?: boolean;
tools?: boolean;
/** Offer mcpx_daemon_status and mcpx_daemon_select. Default: when unclear. */
daemonTools?: boolean;
/** Report ambiguity on tool results. Default on. */
annotate?: boolean;
/** Override the "is anyone looking at this" guess. */
headless?: boolean;
/**
* Model-facing mcpx tool names (mcpx_exec, ...) hidden from every
* session this plugin serves (#5122): the user-facing writer for the
* per-session tool-filter policy — setup records it as each new
* session's policy in ctx.storage, unless that session already has
* a policy of its own. Env: MCPX_PLUGIN_DISABLED_TOOLS (comma- or
* space-separated). Names outside the mcpx_ namespace are dropped
* when the policy is read, so this can never hide a host tool.
*/
disabledTools?: string[];
};

/** A tool-name list from an option array or a separated env string. */
const nameList = (v: unknown): string[] | undefined => {
if (Array.isArray(v))
return v
.map(String)
.map((x) => x.trim())
.filter(Boolean);
if (typeof v === "string")
return v
.split(/[\s,]+/)
.map((x) => x.trim())
.filter(Boolean);
return undefined;
};

const str = (v: unknown): string | undefined => (v === undefined || v === null || v === "" ? undefined : String(v));

/**
* The bin resolution only: nullish, the v1 way. An explicit "" is a
* decision — forbid spawning — not an absence: str() would collapse it
* to undefined and runBin would fall back to MCPX_PLUGIN_BIN or the
* default binary, spawning exactly what the user forbade.
*/
const binStr = (v: unknown): string | undefined => (v === undefined || v === null ? undefined : String(v));

/** The v1 truthy parse: an unrecognised value is undefined, not false. */
export const truthy = (v: unknown): boolean | undefined => {
if (v === undefined || v === null || v === "") return undefined;
if (typeof v === "boolean") return v;
const s = String(v).toLowerCase();
if (s === "1" || s === "true" || s === "yes" || s === "on") return true;
if (s === "0" || s === "false" || s === "no" || s === "off") return false;
return undefined;
};

/**
* Resolve raw options the v1 way — plugin option first, then the
* environment variable, then the caller's default — for the settings
* the v2 core needs. Unset fields stay undefined, except toolTiming,
* whose v1 default is false (opt-in): a resolved false is a decision,
* and index.ts registers no timing hook for it.
*
* `discoveryRetryMs` is not a v1 Options field; it is the resolved
* plugin.discoveryRetry setting (a duration the registry declares and
* v1 applied to its discovery ladder), carried beside the options
* because tools.ts's ladder is its only consumer in this tree.
*
* Still unresolved here, deliberately: env / headless. The v2 core
* has no consumer for them yet — env sized v1's shell.env payload
* (the v2 environment route sends the full env by design, §3), and
* headless gated v1's toasts (the v2 context slice has no TUI
* channel). Resolving a setting nothing reads would be the
* declared-but-unread bug in a new costume. (instructions was on
* this list until the tools slice: the context hook now gates its
* paragraph on it, exactly as v1's system transform did, so it is
* resolved above.)
*/
export type ResolvedOptions = Options & { discoveryRetryMs?: number };

export function resolveOptions(raw: Options | undefined, env: Record<string, string | undefined>): ResolvedOptions {
const o = raw ?? {};
return {
endpoint: str(o.endpoint) ?? str(env.MCPX_DAEMON_ENDPOINT) ?? str(env.MCPX_ENDPOINT),
socket: str(o.socket) ?? str(env.MCPX_SOCKET),
bin: binStr(o.bin) ?? str(env.MCPX_PLUGIN_BIN),
binArgs: Array.isArray(o.binArgs)
? o.binArgs
: typeof o.binArgs === "string"
? splitArgs(o.binArgs)
: splitArgs(env.MCPX_PLUGIN_BIN_ARGS),
backend: (str(o.backend) ?? str(env.MCPX_PLUGIN_BACKEND) ?? "auto") as Options["backend"],
remember: (str(o.remember) ?? str(env.MCPX_PLUGIN_REMEMBER) ?? "session") as Options["remember"],
env: (str(o.env) ?? str(env.MCPX_PLUGIN_ENV)) as Options["env"],
tools: o.tools ?? truthy(env.MCPX_PLUGIN_TOOLS) ?? false,
instructions: o.instructions ?? truthy(env.MCPX_PLUGIN_INSTRUCTIONS) ?? false,
daemonTools: o.daemonTools ?? truthy(env.MCPX_PLUGIN_DAEMON_TOOLS),
annotate: o.annotate ?? truthy(env.MCPX_PLUGIN_ANNOTATE) ?? true,
toolTiming: o.toolTiming ?? truthy(env.MCPX_PLUGIN_TOOL_TIMING) ?? false,
answerSampling: o.answerSampling ?? true,
discoveryRetryMs: goDurationMs(env.MCPX_PLUGIN_DISCOVERY_RETRY),
disabledTools: nameList(o.disabledTools) ?? nameList(env.MCPX_PLUGIN_DISABLED_TOOLS),
};
}
29 changes: 29 additions & 0 deletions pkgs/mcpx/plugin/core/timing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* Core timing log (oracle: the createTimingLog contract in
* timing.ts -- every execute.after input becomes one record, in
* order, handed to the optional sink; failures are first-class
* rows, not invisible).
*
* bun test plugin/core/timing.test.ts
*/
import { describe, expect, test } from "bun:test";
import { createTimingLog, type ToolTimingRecord } from "./timing.ts";

describe("createTimingLog (oracle: one record per input, sink sees each)", () => {
test("records completed and error rows in order and sinks them", () => {
const seen: ToolTimingRecord[] = [];
const log = createTimingLog((r) => seen.push(r));
const a = log.hook({ tool: "mcpx_exec", sessionID: "s1", status: "completed" });
const b = log.hook({ tool: "mcpx_search", sessionID: "s1", status: "error" });
expect(log.records).toEqual([a, b]);
expect(seen).toEqual([a, b]);
expect(b.status).toBe("error");
expect(typeof a.at).toBe("number");
});

test("works without a sink", () => {
const log = createTimingLog();
log.hook({ tool: "t", sessionID: "s", status: "completed" });
expect(log.records.length).toBe(1);
});
});
44 changes: 44 additions & 0 deletions pkgs/mcpx/plugin/core/timing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Tool timing records, harness-free core (#1861): the record shape and
* the in-memory log both adapters share; the v2 tree re-exports this
* module from v2/timing.ts.
*
* Tool timing from tool.hook("execute.after") (design doc §2.1). Unlike v1,
* the hook input is a status union — { status: "completed", result } or
* { status: "error", ... } — so failures are recorded as first-class rows
* instead of being invisible. Records are kept in memory for the session and
* handed to an optional sink (the caller decides where timings go).
*/
export type ToolTimingRecord = {
tool: string;
sessionID: string;
status: "completed" | "error";
at: number;
};

export type ExecuteAfterInput = {
tool: string;
sessionID: string;
status: "completed" | "error";
};

export function createTimingLog(sink?: (record: ToolTimingRecord) => void): {
hook: (input: ExecuteAfterInput) => ToolTimingRecord;
records: ToolTimingRecord[];
} {
const records: ToolTimingRecord[] = [];
return {
records,
hook(input) {
const record: ToolTimingRecord = {
tool: input.tool,
sessionID: input.sessionID,
status: input.status,
at: Date.now(),
};
records.push(record);
sink?.(record);
return record;
},
};
}
36 changes: 1 addition & 35 deletions pkgs/mcpx/plugin/opencode/mcpx-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
type DiscoverOptions,
type Target,
} from "../core/daemon.ts";
import { truthy, type Options } from "../core/options.ts";
// The only reliable way to tell, in v1, whether anyone is looking at a
// screen. See `headless` below.
import { isMainThread } from "node:worker_threads";
Expand Down Expand Up @@ -75,43 +76,8 @@ import { isMainThread } from "node:worker_threads";
*/

/** Everything this plugin can be told, from config or from the environment. */
type Options = {
/** A daemon named outright. `unix:///path` or `http://host:port`. */
endpoint?: string;
/** A socket named outright. */
socket?: string;
/** The mcpx binary, or "" to forbid spawning one. */
bin?: string;
/** Arguments to put before mcpx's own, as a vector or a string. */
binArgs?: string[] | string;
/** Where the opt-in tools get their answers: auto, v1 or cli. */
backend?: "auto" | "v1" | "cli";
/** Default scope for a daemon choice made this session. */
remember?: "session" | "until-gone" | "indefinite";
/** How much to inject into shell environments. */
env?: "minimal" | "standard" | "full";
instructions?: boolean;
toolTiming?: boolean;
tools?: boolean;
/** Offer mcpx_daemon_status and mcpx_daemon_select. Default: when unclear. */
daemonTools?: boolean;
/** Report ambiguity on tool results. Default on. */
annotate?: boolean;
/** Override the "is anyone looking at this" guess. */
headless?: boolean;
};

type Level = "minimal" | "standard" | "full";

const truthy = (v: unknown): boolean | undefined => {
if (v === undefined || v === null || v === "") return undefined;
if (typeof v === "boolean") return v;
const s = String(v).toLowerCase();
if (s === "1" || s === "true" || s === "yes" || s === "on") return true;
if (s === "0" || s === "false" || s === "no" || s === "off") return false;
return undefined;
};

/** Set a variable only when it is actually something. */
const put = (env: Record<string, string>, key: string, value: unknown): void => {
if (value === undefined || value === null) return;
Expand Down
Loading
Loading