Compare commits

...
5 Commits
Author SHA1 Message Date
StanPonomarev 5b6d5fc301 Merge pull request 'fix tmp dirs' (#2) from fix/wrong_tmp_dir into main
Release / release (push) Successful in 9s
Reviewed-on: #2
2026-09-12 19:10:43 +02:00
StanPonomarev 62b56b6a8a fix tmp dirs
CI / verify (pull_request) Successful in 8s
2026-09-12 19:09:49 +02:00
StanPonomarev 99a0090a92 Merge pull request 'feat: add playwright' (#1) from feat/playwright into main
Release / release (push) Failing after 7s
Reviewed-on: #1
2026-09-12 18:59:28 +02:00
StanPonomarev 75e08a5c63 udate readme 2026-09-12 18:58:55 +02:00
StanPonomarev dfe9926c7c feat: add playwright 2026-09-12 18:56:00 +02:00
5 changed files with 350 additions and 53 deletions
+29
View File
@@ -0,0 +1,29 @@
name: CI
on:
pull_request:
permissions:
code: read
jobs:
verify:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: https://github.com/actions/checkout@v4
with:
github-server-url: ${{ gitea.server_url }}
persist-credentials: false
- name: Install Bun
uses: https://github.com/oven-sh/setup-bun@v2
with:
bun-version: "1.3.14"
- name: Verify and build
run: |
bun install --frozen-lockfile
bun run check
bun run lint
bun run format:check
bun run test
bun run build
+13 -52
View File
@@ -1,10 +1,10 @@
# stanp-opencode
OpenCode V2 plugin providing a `coordinate` agent and fast/good/deep worker pairs, with GPT routing or explicit custom model assignments. Your default agent and the built-in `build` agent remain unchanged.
stanp-opencode is an OpenCode V2 coordinator with specialist workers for fast, good, and deep tasks.
## Install the latest release
Requires **OpenCode V2 2.0.2** (`opencode2`), **Bun 1.3.14+**, Bash, curl, jq, and `sha256sum` (Linux/WSL). The native plugin API is pinned to `@opencode/plugin@2.0.2`; use the matching stable OpenCode release.
Requires OpenCode V2 2.0.2 (`opencode2`), Bun 1.3.14+, Bash, curl, jq, and `sha256sum` on Linux or WSL.
Run the installer without sudo:
@@ -12,71 +12,32 @@ Run the installer without sudo:
curl -fsSL https://git.krtss.de/StanPonomarev/stanp-opencode/raw/branch/main/install.sh | bash
```
From a checkout, run `bash install.sh` directly. Rerun the same script to upgrade to the latest published, non-prerelease Gitea release.
The installer downloads `stanp-opencode.tgz` and its SHA-256 checksum, verifies and extracts the self-contained archive, then activates the plugin only after importing and checking both the native V2 server and TUI exports. Download, extraction, and validation failures leave the previous active plugin untouched. The checksum detects corruption; it is not a signature independent of the release server.
Installation defaults to `~/.config/opencode` and respects `XDG_CONFIG_HOME`. Override it explicitly when needed:
```sh
OPENCODE_CONFIG_DIR=/path/to/opencode-config bash install.sh
```
The installer atomically replaces the package directory at `plugins/stanp-opencode` and adds its default GPT configuration to `opencode.json`. Existing unrelated JSON settings and `opencode.jsonc` are preserved. It does not create symlinks, install package dependencies, install OpenCode itself, or configure provider credentials.
Restart `opencode2` after installation (or `opencode2 service restart` for an existing service). Connect your provider, then select `coordinate` in the agent picker. The default configuration uses OpenAI GPT models; agents are only enabled when the required models are available.
Rerun the command to upgrade to the latest published release.
## Install from a local checkout
To build and install the current checkout instead of downloading a release, install Bash, jq, and **Bun 1.3.14+**, then run:
This requires Bash, jq, and Bun 1.3.14+:
```sh
bash /path/to/stanp-opencode/install-local.sh
```
The script may be invoked from any working directory. It runs `bun install --frozen-lockfile` (which may access the package registry) and `bun run build` in the checkout containing the script on every run. It validates the native V2 and TUI bundles, copies them into the same installed package layout as the release installer, and preserves existing plugin options, unrelated `opencode.json` settings, and `opencode.jsonc`. Dependency installation, build, validation, and configuration parsing failures leave the currently installed plugin and configuration untouched.
The script installs dependencies and builds the checkout before installing it.
The configuration directory defaults to `~/.config/opencode`, respects `XDG_CONFIG_HOME`, and can be overridden explicitly:
After either installation, restart `opencode2` or run `opencode2 service restart` for an existing service. Connect OpenAI and select `coordinate`. The required models must be available for the workers to run.
```sh
OPENCODE_CONFIG_DIR=/path/to/opencode-config bash /path/to/stanp-opencode/install-local.sh
```
Both installers use `~/.config/opencode`, respect `XDG_CONFIG_HOME`, and accept `OPENCODE_CONFIG_DIR` as an override.
Restart `opencode2` after installation (or `opencode2 service restart`).
## Configuration
## Configure
See [GPT configuration](examples/gpt.opencode.jsonc) and [custom model assignments](examples/custom.opencode.jsonc).
See [GPT configuration](examples/gpt.opencode.jsonc) and [custom model assignments](examples/custom.opencode.jsonc). When using the installer, point the example's plugin package entry at the installed package directory rather than the unpublished npm package name. Configured local plugin paths must be directories; pointing at `plugins/stanp-opencode.js` causes OpenCode to reject that configured entry and auto-load the file without its options:
For an installed plugin, use `./plugins/stanp-opencode` as the plugin package path. Set `lunaPriority` to `false` to avoid requesting priority pricing.
```jsonc
{
"plugins": [
{
"package": "./plugins/stanp-opencode",
"options": {
"mode": "gpt",
"provider": "openai",
"lunaPriority": true,
},
},
],
}
```
## Playwright
This relative path assumes the configuration file is in the selected global config directory. Use an absolute path in project configuration. Remove any old V1 `plugin` entry when migrating; V2 uses `plugins`. `lunaPriority` requests priority service where supported and can increase cost; set it to `false` to use the provider default.
The plugin supplies session-local `todoread` and `todowrite` tools when no other plugin provides them. In OpenCode V2 2.0.2, custom tools cannot open permission prompts: an `ask` or `deny` rule blocks these todo tools rather than bypassing the rule. Explicitly allow them if you want to use them.
When an MCP server named `codegraph` is already configured, its tools are exposed directly to `coordinate` and retain the built-in `build` agent's matching allow, ask, and deny rules. The plugin does not configure or start a missing server, and no other MCP server is exposed this way.
## ChatGPT subscription quota
When OpenCode's active `openai` integration uses ChatGPT OAuth, the plugin reads the same account usage endpoint as Codex. It queries before a session's first model request (including a resumed session and child sessions), about every 60 seconds, and when session execution completes, fails, is interrupted, or becomes idle. API-key connections and other providers make no quota requests and show no quota UI.
The automatically loaded TUI plugin adds each valid window returned by OpenAI to the sidebar, including named/model-specific limits. Absent or malformed windows are hidden. OpenAI's current Codex contract does not provide a per-window "informational" or "not enforced" flag, so an explicitly returned five-hour window is shown for every plan, including Pro; silently discarding it based only on plan and duration would misrepresent the authoritative response. Each line shows the latest **remaining** account quota and the estimated **percentage points** consumed while the root session family is active. A root session and all of its subagents share one baseline, so child activity is included without counting the same account delta once per child.
The estimate is based on changes in OpenAI's account-wide percentages, not token accounting. Concurrent ChatGPT/Codex use outside the session can therefore skew it upward. If multiple independent root sessions run concurrently, the account delta is inherently indivisible and may be attributed to each active root. Polling can miss usage immediately before a reset, and OpenAI may round the source percentages. Inactive session totals stay frozen, and a resumed family refreshes before becoming active so unrelated idle-time usage is excluded. Last successful values provide the baseline through temporary request failures. Tokens and account identifiers are never exposed through plugin RPC or written to plugin storage; only quota values, session IDs, and a one-way account fingerprint are persisted.
The plugin prefers a local Playwright MCP installation. If no local installation is available, Docker is required for the automatic fallback. Existing `playwright` configuration is preserved.
## Uninstall
Remove `plugins/stanp-opencode` from the selected config directory and remove any explicit configuration entry for it, then restart OpenCode.
Remove `plugins/stanp-opencode` from the selected configuration directory and remove its configuration entry, then restart OpenCode.
+4
View File
@@ -7,6 +7,7 @@ import { discover } from "./provider.js";
import { descriptions, routingGuide } from "./routing.js";
import { QuotaTracker } from "./quota.js";
import { QuotaRpc } from "./quota-rpc.js";
import { playwrightMcpCommand } from "./playwright.js";
// Permission actions use wildcards, not filesystem globs.
function matches(value: string, pattern: string) {
@@ -113,8 +114,11 @@ export default Plugin.define({
const assignments = selected.mode === "gpt" ? gptAgents : selected.agents;
let workers: (typeof workerNames)[number][] = [];
const active = new Set<string>();
const playwrightCommand = await playwrightMcpCommand(context.location.directory);
await context.mcp.transform((editor) => {
if (!editor.get("playwright"))
editor.set("playwright", { type: "local", command: playwrightCommand });
hasCodegraph = editor.get("codegraph") !== undefined;
if (hasCodegraph)
editor.update("codegraph", (server) => {
+145
View File
@@ -0,0 +1,145 @@
import { access, readFile, realpath } from "node:fs/promises";
import { constants } from "node:fs";
import { dirname, join, parse, resolve } from "node:path";
import { z } from "zod";
const dockerCommand = [
"docker",
"run",
"-i",
"--rm",
"--init",
"--pull=always",
"mcr.microsoft.com/playwright/mcp",
];
const directPackageManifest = z.object({
name: z.literal("@playwright/mcp"),
bin: z.string(),
});
const namedPackageManifest = z.object({
name: z.literal("@playwright/mcp"),
bin: z.object({ "playwright-mcp": z.string() }),
});
const playwrightPackageManifest = z.object({
name: z.literal("playwright"),
bin: z.object({ playwright: z.string() }),
});
const playwrightTestPackageManifest = z.object({
name: z.literal("@playwright/test"),
bin: z.object({ playwright: z.string() }),
dependencies: z.object({ playwright: z.string() }),
});
async function packageExecutable(packageRoot: string) {
try {
const input = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"));
const direct = directPackageManifest.safeParse(input);
const bin = direct.success
? direct.data.bin
: namedPackageManifest.parse(input).bin["playwright-mcp"];
const executable = resolve(packageRoot, bin);
await access(executable, constants.X_OK);
return executable;
} catch {
return;
}
}
async function ordinaryPackageExecutable(packageRoot: string) {
try {
const manifest = playwrightPackageManifest.parse(
JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8")),
);
const executable = resolve(packageRoot, manifest.bin.playwright);
await access(executable, constants.X_OK);
return executable;
} catch {
return;
}
}
async function playwrightDependency(packageRoot: string) {
let current = await realpath(packageRoot);
const root = parse(current).root;
while (true) {
const executable = await ordinaryPackageExecutable(
join(current, "node_modules/playwright"),
);
if (executable) return executable;
if (current === root) return;
current = dirname(current);
}
}
async function testPackageExecutable(packageRoot: string) {
try {
const manifest = playwrightTestPackageManifest.parse(
JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8")),
);
if (!(await playwrightDependency(packageRoot))) return;
const executable = resolve(packageRoot, manifest.bin.playwright);
await access(executable, constants.X_OK);
return executable;
} catch {
return;
}
}
async function verifiedPathExecutable(candidate: string, kind: "mcp" | "playwright") {
try {
await access(candidate, constants.X_OK);
const target = await realpath(candidate);
let directory = dirname(target);
const root = parse(directory).root;
while (true) {
const executable =
kind === "mcp"
? await packageExecutable(directory)
: ((await ordinaryPackageExecutable(directory)) ??
(await testPackageExecutable(directory)));
if (executable && (await realpath(executable)) === target) return candidate;
if (directory === root) return;
directory = dirname(directory);
}
} catch {
return;
}
}
export async function playwrightMcpCommand(
directory: string,
path = process.env.PATH ?? "",
): Promise<string[]> {
let current = resolve(directory);
const root = parse(current).root;
while (true) {
const executable = await packageExecutable(join(current, "node_modules/@playwright/mcp"));
if (executable) return [executable];
if (current === root) break;
current = dirname(current);
}
for (const entry of path.split(process.platform === "win32" ? ";" : ":")) {
if (!entry) continue;
const executable = await verifiedPathExecutable(join(entry, "playwright-mcp"), "mcp");
if (executable) return [executable];
}
current = resolve(directory);
while (true) {
const playwright = await ordinaryPackageExecutable(
join(current, "node_modules/playwright"),
);
const test = await testPackageExecutable(join(current, "node_modules/@playwright/test"));
if (playwright || test) return ["npx", "-y", "@playwright/mcp@latest"];
if (current === root) break;
current = dirname(current);
}
for (const entry of path.split(process.platform === "win32" ? ";" : ":")) {
if (!entry) continue;
const executable = await verifiedPathExecutable(join(entry, "playwright"), "playwright");
if (executable) return ["npx", "-y", "@playwright/mcp@latest"];
}
return [...dockerCommand];
}
+159 -1
View File
@@ -1,4 +1,7 @@
import { afterEach, expect, test } from "bun:test";
import { chmod, mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Agent, Model, Plugin, Provider } from "@opencode/plugin";
import type { AgentEditor } from "@opencode/plugin/promise/agent";
import type { DeepMutable } from "@opencode/plugin/promise/types";
@@ -8,6 +11,7 @@ import type { SessionContext } from "@opencode/plugin/promise/session";
import { z } from "zod";
import { gptAgents } from "../src/config.js";
import plugin from "../src/index.js";
import { playwrightMcpCommand } from "../src/playwright.js";
const providerID = Provider.ID.make("test");
function model(id: string): ModelInfo {
@@ -32,6 +36,7 @@ async function host(
{ type: "local"; command: string[]; codemode?: boolean; disabled?: boolean }
> = {},
configuredMcpTools: string[] = [],
directory = "/test",
) {
const agents = new Map<string, DeepMutable<Agent.Info>>();
const build: DeepMutable<Agent.Info> = Agent.Info.default(Agent.ID.make("build"));
@@ -64,11 +69,15 @@ async function host(
const mcpServers = new Map(Object.entries(structuredClone(configuredMcp)));
let mcpTransform!: (editor: {
get(name: string): (typeof configuredMcp)[string] | undefined;
set(name: string, server: (typeof configuredMcp)[string]): void;
update(name: string, update: (server: (typeof configuredMcp)[string]) => void): void;
}) => void;
const toolTransforms: ((editor: ToolEditor) => void)[] = [];
const editMcp = () => ({
get: (name: string) => mcpServers.get(name),
set(name: string, server: (typeof configuredMcp)[string]) {
mcpServers.set(name, structuredClone(server));
},
update(name: string, update: (server: (typeof configuredMcp)[string]) => void) {
const server = mcpServers.get(name);
if (server) update(server);
@@ -107,7 +116,7 @@ async function host(
// SAFETY: This test host implements the native APIs used by setup; unrelated context
// services are deliberately absent so unexpected new dependencies fail the test.
const context = {
location: { directory: "/test" },
location: { directory },
options,
catalog: {
model: {
@@ -408,6 +417,155 @@ test("coordinator inherits only codegraph MCP permissions when that server exist
});
});
test("playwright MCP prefers direct MCP, uses npx for Playwright, and preserves fallback behavior", async () => {
const originalPath = process.env.PATH;
const root = await mkdtemp(join(tmpdir(), "stanp-playwright-"));
try {
process.env.PATH = "";
const packageRoot = join(root, "local", "node_modules", "@playwright", "mcp");
const executable = join(packageRoot, "cli.js");
const localProject = join(root, "local", "project");
const globalProject = join(root, "global-project");
await mkdir(localProject, { recursive: true });
await mkdir(globalProject);
await mkdir(packageRoot, { recursive: true });
await writeFile(
join(packageRoot, "package.json"),
JSON.stringify({ name: "@playwright/mcp", bin: { "playwright-mcp": "cli.js" } }),
);
await writeFile(executable, "#!/usr/bin/env node\n");
await chmod(executable, 0o755);
const local = await host(allModels, { provider: "test" }, {}, [], localProject);
expect(local.mcpServers.get("playwright")).toEqual({
type: "local",
command: [executable],
});
const globalPackage = join(root, "global", "@playwright", "mcp");
const globalExecutable = join(globalPackage, "cli.js");
const globalBin = join(root, "bin");
const pathExecutable = join(globalBin, "playwright-mcp");
await mkdir(globalPackage, { recursive: true });
await mkdir(globalBin, { recursive: true });
await writeFile(
join(globalPackage, "package.json"),
JSON.stringify({ name: "@playwright/mcp", bin: { "playwright-mcp": "cli.js" } }),
);
await writeFile(globalExecutable, "#!/usr/bin/env node\n");
await chmod(globalExecutable, 0o755);
await symlink(globalExecutable, pathExecutable);
expect(await playwrightMcpCommand(globalProject, globalBin)).toEqual([pathExecutable]);
const ordinaryPackage = join(root, "ordinary-project", "node_modules", "playwright");
const ordinaryProject = join(root, "ordinary-project", "project");
const ordinaryExecutable = join(ordinaryPackage, "cli.js");
await mkdir(ordinaryPackage, { recursive: true });
await mkdir(ordinaryProject);
await writeFile(
join(ordinaryPackage, "package.json"),
JSON.stringify({ name: "playwright", bin: { playwright: "cli.js" } }),
);
await writeFile(ordinaryExecutable, "#!/usr/bin/env node\n");
await chmod(ordinaryExecutable, 0o755);
const ordinary = await host(allModels, { provider: "test" }, {}, [], ordinaryProject);
expect(ordinary.mcpServers.get("playwright")?.command).toEqual([
"npx",
"-y",
"@playwright/mcp@latest",
]);
const testPackage = join(root, "test-project", "node_modules", "@playwright", "test");
const testDependency = join(testPackage, "node_modules", "playwright");
const testProject = join(root, "test-project", "project");
await mkdir(testDependency, { recursive: true });
await mkdir(testProject);
await writeFile(
join(testPackage, "package.json"),
JSON.stringify({
name: "@playwright/test",
bin: { playwright: "cli.js" },
dependencies: { playwright: "1.0.0" },
}),
);
await writeFile(join(testPackage, "cli.js"), "#!/usr/bin/env node\n");
await chmod(join(testPackage, "cli.js"), 0o755);
await writeFile(
join(testDependency, "package.json"),
JSON.stringify({ name: "playwright", bin: { playwright: "cli.js" } }),
);
await writeFile(join(testDependency, "cli.js"), "#!/usr/bin/env node\n");
await chmod(join(testDependency, "cli.js"), 0o755);
expect(await playwrightMcpCommand(testProject, "")).toEqual([
"npx",
"-y",
"@playwright/mcp@latest",
]);
const pathPackage = join(root, "path-playwright", "playwright");
const pathBin = join(root, "playwright-bin");
const pathPlaywright = join(pathBin, "playwright");
await mkdir(pathPackage, { recursive: true });
await mkdir(pathBin);
await writeFile(
join(pathPackage, "package.json"),
JSON.stringify({ name: "playwright", bin: { playwright: "cli.js" } }),
);
await writeFile(join(pathPackage, "cli.js"), "#!/usr/bin/env node\n");
await chmod(join(pathPackage, "cli.js"), 0o755);
await symlink(join(pathPackage, "cli.js"), pathPlaywright);
expect(await playwrightMcpCommand(globalProject, pathBin)).toEqual([
"npx",
"-y",
"@playwright/mcp@latest",
]);
const ordinaryBin = join(root, "ordinary-bin");
const fakePlaywright = join(ordinaryBin, "playwright");
await mkdir(ordinaryBin);
await writeFile(fakePlaywright, "#!/usr/bin/env node\n");
await chmod(fakePlaywright, 0o755);
expect((await playwrightMcpCommand(globalProject, ordinaryBin))[0]).toBe("docker");
const fallback = await host();
expect(fallback.mcpServers.get("playwright")).toEqual({
type: "local",
command: [
"docker",
"run",
"-i",
"--rm",
"--init",
"--pull=always",
"mcr.microsoft.com/playwright/mcp",
],
});
const existing = await host(
allModels,
{ provider: "test" },
{
playwright: {
type: "local",
command: ["custom-playwright-mcp"],
disabled: true,
},
docs: { type: "local", command: ["docs"], codemode: true },
},
);
expect(existing.mcpServers.get("playwright")).toEqual({
type: "local",
command: ["custom-playwright-mcp"],
disabled: true,
});
expect(existing.mcpServers.get("docs")?.codemode).toBe(true);
} finally {
if (originalPath === undefined) delete process.env.PATH;
else process.env.PATH = originalPath;
await rm(root, { recursive: true, force: true });
}
});
test("manual calls and command-created child sessions cannot bypass delegation restrictions", async () => {
const result = await host(allModels.slice(0, 2));
for (const invoke of [result.delegate, result.command]) {