diff --git a/assets/oh-my-opencode.schema.json b/assets/oh-my-opencode.schema.json index d8e3095a3..19bcf2aaf 100644 --- a/assets/oh-my-opencode.schema.json +++ b/assets/oh-my-opencode.schema.json @@ -55,6 +55,8 @@ "review-work", "remove-ai-slops", "init-deep", + "security-research", + "security-review", "team-mode" ] } diff --git a/package.json b/package.json index 3760bc61f..63ac771b0 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,7 @@ "typecheck:packages": "tsgo --noEmit -p packages/rules-engine/tsconfig.json && tsgo --noEmit -p packages/ast-grep-core/tsconfig.json && tsgo --noEmit -p packages/ast-grep-mcp/tsconfig.json && tsgo --noEmit -p packages/utils/tsconfig.json && tsgo --noEmit -p packages/model-core/tsconfig.json && tsgo --noEmit -p packages/prompts-core/tsconfig.json && tsgo --noEmit -p packages/comment-checker-core/tsconfig.json && tsgo --noEmit -p packages/hashline-core/tsconfig.json && tsgo --noEmit -p packages/boulder-state/tsconfig.json && tsgo --noEmit -p packages/agents-md-core/tsconfig.json && tsgo --noEmit -p packages/omo-codex/tsconfig.json", "typecheck:script": "tsgo --noEmit -p script/tsconfig.json", "test": "bun test", - "test:codex": "bun test src/cli/cli-installer.platform.test.ts src/cli/install-codex/codex-cache.test.ts src/cli/install-codex/codex-config-agent-cleanup.test.ts src/cli/install-codex/codex-config-toml.test.ts src/cli/install-codex/install-codex.test.ts src/cli/install-codex/link-cached-plugin-agents.test.ts packages/omo-codex/src/**/*.test.ts packages/utils/src/jsonc-parser.test.ts packages/utils/src/frontmatter.test.ts packages/hashline-core/src/hash-computation.test.ts packages/hashline-core/src/smoke-untested-modules.test.ts packages/rules-engine/src/index.test.ts packages/rules-engine/src/security-boundary.test.ts packages/agents-md-core/src/injector.test.ts && node --test packages/omo-codex/plugin/test/*.test.mjs packages/omo-codex/scripts/install-cache-copy.test.mjs packages/omo-codex/scripts/install-config.test.mjs packages/omo-codex/scripts/install-local.test.mjs packages/omo-codex/scripts/install-mcp-runtime.test.mjs packages/omo-codex/scripts/install-agent-links.test.mjs packages/omo-codex/scripts/install-bin-links.test.mjs packages/omo-codex/scripts/sync-telemetry-component.test.mjs", + "test:codex": "bun run build:ast-grep-mcp && bun run build:lsp-tools-mcp && bun run --cwd packages/omo-codex/plugin build && bun test src/cli/cli-installer.platform.test.ts src/cli/install-codex/codex-cache.test.ts src/cli/install-codex/codex-config-agent-cleanup.test.ts src/cli/install-codex/codex-config-toml.test.ts src/cli/install-codex/install-codex.test.ts src/cli/install-codex/link-cached-plugin-agents.test.ts packages/omo-codex/src/**/*.test.ts packages/utils/src/jsonc-parser.test.ts packages/utils/src/frontmatter.test.ts packages/hashline-core/src/hash-computation.test.ts packages/hashline-core/src/smoke-untested-modules.test.ts packages/rules-engine/src/index.test.ts packages/rules-engine/src/security-boundary.test.ts packages/agents-md-core/src/injector.test.ts && node --test packages/omo-codex/plugin/test/*.test.mjs packages/omo-codex/scripts/install-cache-copy.test.mjs packages/omo-codex/scripts/install-config.test.mjs packages/omo-codex/scripts/install-local.test.mjs packages/omo-codex/scripts/install-mcp-runtime.test.mjs packages/omo-codex/scripts/install-agent-links.test.mjs packages/omo-codex/scripts/install-bin-links.test.mjs packages/omo-codex/scripts/sync-telemetry-component.test.mjs", "test:windows-codex": "bun run test:codex", "build:ast-grep-mcp": "bun run --cwd packages/ast-grep-mcp build" }, diff --git a/packages/lsp-tools-mcp b/packages/lsp-tools-mcp index 80cc06a3e..103e28ea4 160000 --- a/packages/lsp-tools-mcp +++ b/packages/lsp-tools-mcp @@ -1 +1 @@ -Subproject commit 80cc06a3ed70eaa9a38b4e0ce3e34b4d98a02c51 +Subproject commit 103e28ea438d5eb1f50d441b44262bc0367f4191 diff --git a/packages/omo-codex/plugin/components/lsp/src/codex-hook.ts b/packages/omo-codex/plugin/components/lsp/src/codex-hook.ts index 5587923b4..8bd565354 100644 --- a/packages/omo-codex/plugin/components/lsp/src/codex-hook.ts +++ b/packages/omo-codex/plugin/components/lsp/src/codex-hook.ts @@ -1,8 +1,8 @@ import { readFileSync } from "node:fs"; import { stdin as processStdin } from "node:process"; -import { disposeDefaultLspManager } from "@code-yeongyu/lsp-tools-mcp/dist/lsp/manager.js"; -import { executeLspDiagnostics } from "@code-yeongyu/lsp-tools-mcp/dist/tools.js"; +import { disposeDefaultLspManager } from "../../../../../lsp-tools-mcp/dist/lsp/manager.js"; +import { executeLspDiagnostics } from "../../../../../lsp-tools-mcp/dist/tools.js"; export type DiagnosticsRunner = (filePath: string) => Promise; diff --git a/packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts b/packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts index 1b0390e5d..af99201c2 100644 --- a/packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts +++ b/packages/omo-codex/plugin/components/lsp/test/package-smoke.test.ts @@ -56,6 +56,7 @@ describe("plugin package metadata", () => { const hooksJson = readHooksJson("hooks/hooks.json"); const mcpJson = readMcpJson(".mcp.json"); const cliSource = readFileSync("src/cli.ts", "utf8"); + const codexHookSource = readFileSync("src/codex-hook.ts", "utf8"); const sourceFiles = readdirSync("src"); // when @@ -80,6 +81,9 @@ describe("plugin package metadata", () => { expect(cliSource).not.toContain("./lazy-lsp-mcp.js"); expect(cliSource).not.toContain("@code-yeongyu/lsp-tools-mcp"); expect(cliSource).toContain("../../../../../lsp-tools-mcp/dist/cli.js"); + expect(codexHookSource).not.toContain("@code-yeongyu/lsp-tools-mcp"); + expect(codexHookSource).toContain("../../../../../lsp-tools-mcp/dist/lsp/manager.js"); + expect(codexHookSource).toContain("../../../../../lsp-tools-mcp/dist/tools.js"); expect(sourceFiles.filter((name) => name.startsWith("lazy-mcp") || name === "lazy-lsp-mcp.ts")).toEqual([]); }); diff --git a/script/publish-workflow.test.ts b/script/publish-workflow.test.ts index a4a279ad4..505b76b99 100644 --- a/script/publish-workflow.test.ts +++ b/script/publish-workflow.test.ts @@ -75,6 +75,20 @@ describe("test workflows", () => { expect(buildNeedsCodexMatrix, "Build must wait for Codex compatibility checks").toBe(true) }) + test("builds bundled MCP runtimes before Codex compatibility tests", () => { + // #given + const packageManifest = readFileSync(new URL("../package.json", import.meta.url), "utf8") + + // #when + const codexTestScriptBuildsMcpRuntimes = + packageManifest.includes( + '"test:codex": "bun run build:ast-grep-mcp && bun run build:lsp-tools-mcp && bun run --cwd packages/omo-codex/plugin build && bun test', + ) + + // #then + expect(codexTestScriptBuildsMcpRuntimes, "test:codex must build bundled MCP dists before installer tests copy them").toBe(true) + }) + test("pins every workflow Bun setup to the tested runtime", () => { for (const workflowPath of workflowPaths) { // #given diff --git a/src/cli/config-manager/add-plugin-to-opencode-config.ts b/src/cli/config-manager/add-plugin-to-opencode-config.ts index 8cb7d0838..5346bbb53 100644 --- a/src/cli/config-manager/add-plugin-to-opencode-config.ts +++ b/src/cli/config-manager/add-plugin-to-opencode-config.ts @@ -1,15 +1,207 @@ -import { readFileSync, writeFileSync } from "node:fs" +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs" +import { basename, dirname, join } from "node:path" import type { ConfigMergeResult } from "../types" import { PLUGIN_NAME, LEGACY_PLUGIN_NAME } from "../../shared" import { backupConfigFile } from "./backup-config" import { getConfigDir } from "./config-context" import { ensureConfigDirectoryExists } from "./ensure-config-directory-exists" import { formatErrorWithSuggestion } from "./format-error-with-suggestion" -import { detectConfigFormat } from "./opencode-config-format" +import { detectConfigFormat, type ConfigFormat } from "./opencode-config-format" import { parseOpenCodeConfigFileWithError, type OpenCodeConfig } from "./parse-opencode-config-file" import { getPluginNameWithVersion } from "./plugin-name-with-version" import { checkVersionCompatibility, extractVersionFromPluginEntry } from "./version-compatibility" +type ConfigTarget = { + readonly format: ConfigFormat + readonly path: string + readonly primary: boolean +} + +function detectConfigFormatInDir(configDir: string): { readonly format: ConfigFormat; readonly path: string } { + const configJsonc = join(configDir, "opencode.jsonc") + const configJson = join(configDir, "opencode.json") + + if (existsSync(configJsonc)) { + return { format: "jsonc", path: configJsonc } + } + if (existsSync(configJson)) { + return { format: "json", path: configJson } + } + return { format: "none", path: configJson } +} + +function getParentConfigDirForProfile(configDir: string): string | null { + const parentDir = dirname(configDir) + if (basename(parentDir) !== "profiles") return null + return dirname(parentDir) +} + +function listProfileConfigDirs(rootConfigDir: string): string[] { + const profilesDir = join(rootConfigDir, "profiles") + if (!existsSync(profilesDir)) return [] + + return readdirSync(profilesDir, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => join(profilesDir, entry.name)) + .filter((profileDir) => detectConfigFormatInDir(profileDir).format !== "none") +} + +function getConfigTargets(): ConfigTarget[] { + const primaryConfigDir = getConfigDir() + const rootConfigDir = getParentConfigDirForProfile(primaryConfigDir) ?? primaryConfigDir + const targetDirs = new Set([primaryConfigDir]) + + if (rootConfigDir !== primaryConfigDir && detectConfigFormatInDir(rootConfigDir).format !== "none") { + targetDirs.add(rootConfigDir) + } + + for (const profileConfigDir of listProfileConfigDirs(rootConfigDir)) { + targetDirs.add(profileConfigDir) + } + + return Array.from(targetDirs).map((configDir) => { + const detected = detectConfigFormatInDir(configDir) + return { + ...detected, + primary: configDir === primaryConfigDir, + } + }) +} + +function isSourceOmoPluginEntry(plugin: string): boolean { + const normalized = plugin.toLowerCase().replaceAll("\\", "/") + if (!normalized.startsWith("file://")) return false + + return /\/(omo(?:-[^/]*)?|oh-my-opencode|oh-my-openagent)\/(src|dist)\/index\.(ts|js)$/.test(normalized) +} + +function isPackageOmoPluginEntry(plugin: string): boolean { + return plugin === PLUGIN_NAME || plugin.startsWith(`${PLUGIN_NAME}@`) || + plugin === LEGACY_PLUGIN_NAME || plugin.startsWith(`${LEGACY_PLUGIN_NAME}@`) +} + +function isOurPlugin(plugin: string): boolean { + return isPackageOmoPluginEntry(plugin) || isSourceOmoPluginEntry(plugin) +} + +function findOurPluginEntry(plugins: readonly string[]): string | undefined { + return plugins.find(isOurPlugin) +} + +function findSourcePluginEntryInTarget(target: ConfigTarget): string | null { + if (target.format === "none") return null + + const parseResult = parseOpenCodeConfigFileWithError(target.path) + const plugins = parseResult.config?.plugin ?? [] + return plugins.find(isSourceOmoPluginEntry) ?? null +} + +function choosePluginEntry(params: { + readonly existingEntry: string | undefined + readonly fallbackEntry: string + readonly preferredSourceEntry: string | null +}): string { + if (params.existingEntry && isSourceOmoPluginEntry(params.existingEntry)) { + return params.existingEntry + } + if (params.preferredSourceEntry) { + return params.preferredSourceEntry + } + return params.fallbackEntry +} + +function writePluginEntryToTarget(params: { + readonly target: ConfigTarget + readonly currentVersion: string + readonly fallbackEntry: string + readonly preferredSourceEntry: string | null +}): ConfigMergeResult { + const { target, currentVersion, fallbackEntry, preferredSourceEntry } = params + const pluginEntry = choosePluginEntry({ + existingEntry: undefined, + fallbackEntry, + preferredSourceEntry, + }) + + try { + if (target.format === "none") { + const config: OpenCodeConfig = { plugin: [pluginEntry] } + writeFileSync(target.path, JSON.stringify(config, null, 2) + "\n") + return { success: true, configPath: target.path } + } + + const parseResult = parseOpenCodeConfigFileWithError(target.path) + if (!parseResult.config) { + return { + success: false, + configPath: target.path, + error: parseResult.error ?? "Failed to parse config file", + } + } + + const config = parseResult.config + const plugins = config.plugin ?? [] + const existingEntry = findOurPluginEntry(plugins) + const nextPluginEntry = choosePluginEntry({ + existingEntry, + fallbackEntry, + preferredSourceEntry, + }) + + if (existingEntry && !preferredSourceEntry) { + const installedVersion = extractVersionFromPluginEntry(existingEntry) + const compatibility = checkVersionCompatibility(installedVersion, currentVersion) + + if (!compatibility.canUpgrade) { + return { + success: false, + configPath: target.path, + error: compatibility.reason ?? "Version compatibility check failed", + } + } + + const backupResult = backupConfigFile(target.path) + if (!backupResult.success) { + return { + success: false, + configPath: target.path, + error: `Failed to create backup: ${backupResult.error}`, + } + } + } + + const normalizedPlugins = plugins.filter((plugin) => !isOurPlugin(plugin)) + normalizedPlugins.push(nextPluginEntry) + + config.plugin = normalizedPlugins + + if (target.format === "jsonc") { + const content = readFileSync(target.path, "utf-8") + const pluginArrayRegex = /((?:"plugin"|plugin)\s*:\s*)\[([\s\S]*?)\]/ + const match = content.match(pluginArrayRegex) + + if (match) { + const formattedPlugins = normalizedPlugins.map((p) => `"${p}"`).join(",\n ") + const newContent = content.replace(pluginArrayRegex, `$1[\n ${formattedPlugins}\n ]`) + writeFileSync(target.path, newContent) + } else { + const newContent = content.replace(/(\{)/, `$1\n "plugin": ["${nextPluginEntry}"],`) + writeFileSync(target.path, newContent) + } + } else { + writeFileSync(target.path, JSON.stringify(config, null, 2) + "\n") + } + + return { success: true, configPath: target.path } + } catch (err) { + return { + success: false, + configPath: target.path, + error: formatErrorWithSuggestion(err, "update opencode config"), + } + } +} + export async function addPluginToOpenCodeConfig(currentVersion: string): Promise { try { ensureConfigDirectoryExists() @@ -21,91 +213,27 @@ export async function addPluginToOpenCodeConfig(currentVersion: string): Promise } } - const { format, path } = detectConfigFormat() + const primaryTarget = detectConfigFormat() + const targets = getConfigTargets() + const preferredSourceEntry = targets + .map((target) => findSourcePluginEntryInTarget(target)) + .find((entry): entry is string => entry !== null) ?? null const pluginEntry = await getPluginNameWithVersion(currentVersion, PLUGIN_NAME) - try { - if (format === "none") { - const config: OpenCodeConfig = { plugin: [pluginEntry] } - writeFileSync(path, JSON.stringify(config, null, 2) + "\n") - return { success: true, configPath: path } - } + let primaryResult: ConfigMergeResult | null = null + for (const target of targets) { + const result = writePluginEntryToTarget({ + target, + currentVersion, + fallbackEntry: pluginEntry, + preferredSourceEntry, + }) - const parseResult = parseOpenCodeConfigFileWithError(path) - if (!parseResult.config) { - return { - success: false, - configPath: path, - error: parseResult.error ?? "Failed to parse config file", - } - } - - const config = parseResult.config - const plugins = config.plugin ?? [] - - const canonicalEntries = plugins.filter( - (plugin) => plugin === PLUGIN_NAME || plugin.startsWith(`${PLUGIN_NAME}@`) - ) - const legacyEntries = plugins.filter( - (plugin) => plugin === LEGACY_PLUGIN_NAME || plugin.startsWith(`${LEGACY_PLUGIN_NAME}@`) - ) - const otherPlugins = plugins.filter( - (plugin) => !(plugin === PLUGIN_NAME || plugin.startsWith(`${PLUGIN_NAME}@`)) - && !(plugin === LEGACY_PLUGIN_NAME || plugin.startsWith(`${LEGACY_PLUGIN_NAME}@`)) - ) - - const existingEntry = canonicalEntries[0] ?? legacyEntries[0] - if (existingEntry) { - const installedVersion = extractVersionFromPluginEntry(existingEntry) - const compatibility = checkVersionCompatibility(installedVersion, currentVersion) - - if (!compatibility.canUpgrade) { - return { - success: false, - configPath: path, - error: compatibility.reason ?? "Version compatibility check failed", - } - } - - const backupResult = backupConfigFile(path) - if (!backupResult.success) { - return { - success: false, - configPath: path, - error: `Failed to create backup: ${backupResult.error}`, - } - } - } - - const normalizedPlugins = [...otherPlugins] - - normalizedPlugins.push(pluginEntry) - - config.plugin = normalizedPlugins - - if (format === "jsonc") { - const content = readFileSync(path, "utf-8") - const pluginArrayRegex = /((?:"plugin"|plugin)\s*:\s*)\[([\s\S]*?)\]/ - const match = content.match(pluginArrayRegex) - - if (match) { - const formattedPlugins = normalizedPlugins.map((p) => `"${p}"`).join(",\n ") - const newContent = content.replace(pluginArrayRegex, `$1[\n ${formattedPlugins}\n ]`) - writeFileSync(path, newContent) - } else { - const newContent = content.replace(/(\{)/, `$1\n "plugin": ["${pluginEntry}"],`) - writeFileSync(path, newContent) - } - } else { - writeFileSync(path, JSON.stringify(config, null, 2) + "\n") - } - - return { success: true, configPath: path } - } catch (err) { - return { - success: false, - configPath: path, - error: formatErrorWithSuggestion(err, "update opencode config"), + if (!result.success) return result + if (target.primary) { + primaryResult = result } } + + return primaryResult ?? { success: true, configPath: primaryTarget.path } } diff --git a/src/cli/config-manager/plugin-detection.test.ts b/src/cli/config-manager/plugin-detection.test.ts index e4ebd1b6e..f9cd3fda5 100644 --- a/src/cli/config-manager/plugin-detection.test.ts +++ b/src/cli/config-manager/plugin-detection.test.ts @@ -184,4 +184,56 @@ describe("addPluginToOpenCodeConfig - single package writes", () => { expect(savedContent.includes('"plugin": [\n "oh-my-openagent"\n ]')).toBe(true) expect(savedContent.includes("oh-my-opencode")).toBe(false) }) + + it("mirrors an existing source plugin entry into profile configs", async () => { + // given + const sourcePlugin = "file:///Users/yeongyu/local-workspaces/omo/src/index.ts" + writeFileSync(testConfigPath, JSON.stringify({ plugin: [sourcePlugin] }, null, 2) + "\n", "utf-8") + + const profileDir = join(testConfigDir, "profiles", "today") + const profileConfigPath = join(profileDir, "opencode.json") + mkdirSync(profileDir, { recursive: true }) + writeFileSync( + profileConfigPath, + JSON.stringify({ $schema: "https://opencode.ai/config.json" }, null, 2) + "\n", + "utf-8", + ) + + // when + const result = await addPluginToOpenCodeConfig("3.11.0") + + // then + expect(result.success).toBe(true) + const savedRootConfig = JSON.parse(readFileSync(testConfigPath, "utf-8")) + const savedProfileConfig = JSON.parse(readFileSync(profileConfigPath, "utf-8")) + expect(savedRootConfig.plugin).toEqual([sourcePlugin]) + expect(savedProfileConfig.plugin).toEqual([sourcePlugin]) + }) + + it("uses the parent source plugin entry when OPENCODE_CONFIG_DIR points at a profile", async () => { + // given + const sourcePlugin = "file:///Users/yeongyu/local-workspaces/omo/src/index.ts" + writeFileSync(testConfigPath, JSON.stringify({ plugin: [sourcePlugin] }, null, 2) + "\n", "utf-8") + + const profileDir = join(testConfigDir, "profiles", "today") + const profileConfigPath = join(profileDir, "opencode.json") + mkdirSync(profileDir, { recursive: true }) + writeFileSync( + profileConfigPath, + JSON.stringify({ $schema: "https://opencode.ai/config.json" }, null, 2) + "\n", + "utf-8", + ) + + process.env.OPENCODE_CONFIG_DIR = profileDir + resetConfigContext() + + // when + const result = await addPluginToOpenCodeConfig("3.11.0") + + // then + expect(result.success).toBe(true) + expect(result.configPath.endsWith("/profiles/today/opencode.json")).toBe(true) + const savedProfileConfig = JSON.parse(readFileSync(profileConfigPath, "utf-8")) + expect(savedProfileConfig.plugin).toEqual([sourcePlugin]) + }) }) diff --git a/src/config/schema/agent-names.test.ts b/src/config/schema/agent-names.test.ts index e3212ae22..de8b3fbc5 100644 --- a/src/config/schema/agent-names.test.ts +++ b/src/config/schema/agent-names.test.ts @@ -4,10 +4,16 @@ import { describe, expect, test } from "bun:test" import { OhMyOpenCodeConfigSchema } from "./oh-my-opencode-config" describe("OhMyOpenCodeConfigSchema disabled_skills", () => { - test("accepts review-work, remove-ai-slops, and init-deep", () => { + test("accepts review-work, shared skills, and runtime security skills", () => { // given const config = { - disabled_skills: ["review-work", "remove-ai-slops", "init-deep"], + disabled_skills: [ + "review-work", + "remove-ai-slops", + "init-deep", + "security-research", + "security-review", + ], } // when @@ -20,6 +26,8 @@ describe("OhMyOpenCodeConfigSchema disabled_skills", () => { "review-work", "remove-ai-slops", "init-deep", + "security-research", + "security-review", ]) } }) diff --git a/src/config/schema/agent-names.ts b/src/config/schema/agent-names.ts index fdb587f24..808eede64 100644 --- a/src/config/schema/agent-names.ts +++ b/src/config/schema/agent-names.ts @@ -23,6 +23,8 @@ export const BuiltinSkillNameSchema = z.enum([ "review-work", "remove-ai-slops", "init-deep", + "security-research", + "security-review", "team-mode", ]) diff --git a/src/create-managers.ts b/src/create-managers.ts index 40b752983..090df376a 100644 --- a/src/create-managers.ts +++ b/src/create-managers.ts @@ -52,9 +52,10 @@ export function createManagers(args: { tmuxConfig: TmuxConfig modelCacheState: ModelCacheState backgroundNotificationHookEnabled: boolean + runtimeSkillSourceUrl?: string deps?: Partial }): Managers { - const { ctx, pluginConfig, tmuxConfig, modelCacheState, backgroundNotificationHookEnabled } = args + const { ctx, pluginConfig, tmuxConfig, modelCacheState, backgroundNotificationHookEnabled, runtimeSkillSourceUrl } = args const deps = { ...defaultCreateManagersDeps, ...args.deps } // Only mark the server as in-process when the SDK actually exposes a @@ -151,6 +152,7 @@ export function createManagers(args: { ctx: { directory: ctx.directory, client: ctx.client }, pluginConfig, modelCacheState, + runtimeSkillSourceUrl, }) return { tmuxSessionManager, diff --git a/src/features/AGENTS.md b/src/features/AGENTS.md index 77e088e2b..864e7d9dd 100644 --- a/src/features/AGENTS.md +++ b/src/features/AGENTS.md @@ -16,7 +16,7 @@ File counts are NON-TEST `.ts` files only (test files co-located but excluded fr | **background-agent** | 30 / 1 subdir (spawner/) | HIGH | yes | Task lifecycle, concurrency (5/key), 3s polling, spawner pattern, circuit breaker. Newer files: `parent-wake-notifier.ts` (587 LOC), `loop-detector`, `error-classifier`, `fallback-retry-handler`, `process-cleanup`, `subagent-spawn-limits`, `session-status-classifier`, `compaction-aware-message-resolver`. | | **tmux-subagent** | 27 | HIGH | yes | Tmux pane management, grid planning, session orchestration via `runTmuxCommand` | | **opencode-skill-loader** | 25 / 1 subdir (merger/) | HIGH | yes | YAML frontmatter skill discovery from 4 scopes (project > opencode > user > global) | -| **builtin-skills** | 17 / 5 subdirs | LOW–MED | yes | Built-in skill files (git-master, playwright, frontend-ui-ux, review-work, dev-browser, playwright-cli, **team-mode**, …) | +| **builtin-skills** | 20 / 6 subdirs | LOW–MED | yes | 12 built-in skill files (git-master, playwright, frontend-ui-ux, review-work, remove-ai-slops, init-deep, security-research, security-review, dev-browser, playwright-cli, **team-mode**, …) | | **skill-mcp-manager** | 11 | HIGH | yes | Tier-3 MCP client lifecycle per session (stdio + HTTP + OAuth) | | **claude-code-plugin-loader** | 11 | MEDIUM | yes | Unified Claude Code plugin discovery (commands, agents, skills, hooks, MCPs) | | **builtin-commands** | 11 / 1 subdir (templates/) | LOW | yes | Command templates: refactor, init-deep, handoff, ulw-loop, etc. | @@ -70,7 +70,7 @@ Eligible members: sisyphus, atlas, sisyphus-junior, hephaestus only. See [`team- State-first tmux integration. Centralized tmux command execution through `src/shared/tmux/runner.ts` (`runTmuxCommand`). Direct `Bun.spawn(["tmux", ...])` is FORBIDDEN — would drift from retry/timeout discipline. -### builtin-skills +### builtin-skills (12 skills) | Skill | LOC | MCP | Notes | |-------|-----|-----|-------| @@ -80,6 +80,9 @@ State-first tmux integration. Centralized tmux command execution through `src/sh | dev-browser | 221 | — | Persistent page state browser | | review-work | ~500 | — | 5-agent post-implementation review orchestrator | | $omo:remove-ai-slops | — | — | Remove AI code patterns | +| init-deep | — | — | Hierarchical AGENTS.md generation | +| security-research | SKILL.md | — | Team Mode exploitability-driven security research | +| security-review | wrapper | — | Alias for security-research | | **team-mode** | — | — | Loaded only when `team_mode.enabled` (skill explains the 12 tools to agents) | | frontend-ui-ux | 79 | — | Design-first UI development | | (git-master-skill-metadata) | — | — | Companion to git-master | diff --git a/src/features/builtin-skills/AGENTS.md b/src/features/builtin-skills/AGENTS.md index 9aa18be4a..cb9fa9f6b 100644 --- a/src/features/builtin-skills/AGENTS.md +++ b/src/features/builtin-skills/AGENTS.md @@ -1,4 +1,4 @@ -# src/features/builtin-skills/ — Built-in Skill Files +# src/features/builtin-skills/ — 12 Built-in Skill Files **Generated:** 2026-05-15 @@ -11,7 +11,7 @@ Skills shipped inside the plugin (always available, no install). Registered via ``` builtin-skills/ ├── index.ts # Barrel exports -├── skills.ts # createBuiltinSkills() factory +├── skills.ts # createBuiltinSkills() factory — registers all 12 below ├── types.ts # BuiltinSkill interface ├── skills/ │ ├── git-master.ts # 1111 LOC @@ -21,13 +21,18 @@ builtin-skills/ │ ├── dev-browser.ts # Persistent page state │ ├── frontend-ui-ux.ts # Design-first UI guidance │ ├── review-work.ts # 5-agent post-implementation review +│ ├── remove-ai-slops.ts # Shared skill loader for remove-ai-slops +│ ├── init-deep.ts # Shared skill loader for init-deep │ ├── team-mode.ts # 12 team_* tool documentation (gated) +│ ├── security-research.ts # Team Mode exploitability-driven security research +│ ├── security-review.ts # Alias for security-research │ ├── git-master-sections/ # Git-master prompt sub-sections │ └── index.ts # skill barrel ├── git-master/ # Resources for git-master skill ├── frontend-ui-ux/ # Resources for frontend-ui-ux skill ├── agent-browser/ # Resources for agent-browser variant -└── dev-browser/ # Resources for dev-browser +├── dev-browser/ # Resources for dev-browser +└── security-research/ # Resources for security-research ``` ## SKILL CATALOG @@ -42,6 +47,9 @@ builtin-skills/ | `frontend-ui-ux` | 79 | — | Design-first UI development guidance | | `review-work` | ~500 | — | Post-implementation review orchestrator (5 parallel agents) | | `$omo:remove-ai-slops` | — | — | Remove AI-generated code smells | +| `init-deep` | — | — | Hierarchical AGENTS.md generation | +| `security-research` | SKILL.md | — | Team Mode exploitability-driven security research | +| `security-review` | wrapper | — | Alias for `security-research` | | `team-mode` | — | — | **Conditional** — only loaded when `team_mode.enabled`; documents the 12 `team_*` tools and lifecycle | ## BROWSER VARIANT SELECTION diff --git a/src/features/builtin-skills/security-research/SKILL.md b/src/features/builtin-skills/security-research/SKILL.md new file mode 100644 index 000000000..35fe81a61 --- /dev/null +++ b/src/features/builtin-skills/security-research/SKILL.md @@ -0,0 +1,198 @@ +# Security Research - Team Mode Vulnerability Audit + +Use this skill to run a parallel security audit that separates real exploitability from generic concern. The team has 3 vulnerability hunters and 2 PoC engineers. + +## Hard Preconditions + +Before starting, verify: + +1. `team_*` tools are available. If not, stop and tell the user: + `security-research requires team-mode. Set team_mode.enabled: true in your oh-my-openagent config, restart opencode, then retry.` +2. You are in the main session, not a background subagent. +3. You have a concrete target: repository, diff range, PR, release candidate, path list, or threat surface. + +If the user provided no target, audit the current repository and current branch diff against its upstream or merge base. If there is no diff, audit the security-sensitive surfaces in the working tree. + +## Severity Standard + +Use these references as the scoring frame: + +- CWE for root-cause weakness classification: https://cwe.mitre.org/ +- OWASP WSTG for test methodology: https://devguide.owasp.org/en/06-verification/01-guides/01-wstg/ +- OWASP ASVS for control verification: https://owasp.org/www-project-application-security-verification-standard/ +- CVSS v4.0 for exploitability and impact scoring: https://www.first.org/cvss/v4.0/specification-document + +Rules: + +- No severity without an attack path. +- No critical or high finding without concrete exploit preconditions and impact. +- Keep CWE category separate from severity. +- Prefer a small, reproducible PoC over theoretical language. +- Never run destructive exploits against real services or third-party systems. +- Use local fixtures, toy payloads, dry runs, or static proof when real execution would be unsafe. + +## Team Roster + +Create one Team Mode run with these 5 members: + +| Member | Kind | Category | Role | +|--------|------|----------|------| +| `surface-hunter` | category | `deep` | Map entry points, trust boundaries, and reachable attack surfaces. | +| `auth-data-hunter` | category | `ultrabrain` | Hunt auth, authorization, data isolation, injection, and secret handling flaws. | +| `runtime-supply-hunter` | category | `unspecified-high` | Hunt filesystem, subprocess, archive, dependency, hook, MCP, and config risks. | +| `poc-engineer-a` | category | `unspecified-high` | Build minimal PoCs for the strongest candidate findings. | +| `poc-engineer-b` | category | `deep` | Independently reproduce, falsify, or downgrade candidate findings. | + +Call `team_create` with an inline spec: + +```typescript +team_create({ + inline_spec: { + name: "security-research", + description: "Parallel exploitability-driven security research team.", + members: [ + { + name: "surface-hunter", + kind: "category", + category: "deep", + prompt: "You map attack surface. Enumerate entry points, trust boundaries, attacker-controlled inputs, data sinks, privilege transitions, and sensitive assets. Return evidence with file paths and exact functions. Do not assign severity unless you can name an attack path." + }, + { + name: "auth-data-hunter", + kind: "category", + category: "ultrabrain", + prompt: "You hunt auth, authorization, tenant/data isolation, injection, SSRF, credential exposure, and confused-deputy flaws. Reason from attacker capability to impact. Return only findings with concrete exploit preconditions, CWE candidates, and verification steps." + }, + { + name: "runtime-supply-hunter", + kind: "category", + category: "unspecified-high", + prompt: "You hunt filesystem, subprocess, archive extraction, dependency, hook execution, MCP, config, and environment-variable risks. Check path traversal, command injection, unsafe downloads, permission boundaries, and supply-chain assumptions. Cite file paths and commands used." + }, + { + name: "poc-engineer-a", + kind: "category", + category: "unspecified-high", + prompt: "You build minimal safe PoCs for candidate findings. Use toy inputs and local-only execution. Your job is to prove or disprove exploitability, not to broaden scope. Report exact reproduction steps and expected output." + }, + { + name: "poc-engineer-b", + kind: "category", + category: "deep", + prompt: "You independently reproduce candidate findings and try to falsify them. Downgrade anything without a working path. If a PoC is unsafe to run, design a safe static or dry-run proof and explain the limit." + } + ] + } +}) +``` + +If a category is unavailable, retry once by replacing only that category with `unspecified-high`. Do not reduce the team below 5 members. + +## Workflow + +### Phase 0: Scope and Baseline + +Collect: + +- Target scope and reason for audit. +- Branch, base ref, diff, and changed files if this is a change review. +- Security-sensitive directories and files if this is a full-repo audit. +- Existing tests and commands that exercise relevant surfaces. +- Any user-stated constraints, such as no network calls or no destructive tests. + +Use `rg`, `git diff`, `git log`, LSP, and existing tests before assigning work. + +### Phase 1: Independent Hunter Pass + +Send one prompt to the 3 hunters: + +```text +Audit target: +{target summary} + +Context: +{diff, file list, security-sensitive paths, known constraints} + +Task: +Find candidate vulnerabilities in your assigned role. For each candidate include: +- title +- affected file/function +- attacker capability +- attack path +- impact +- CWE candidate +- exact evidence +- safe verification idea + +Reject generic hardening advice. Return only candidates with a plausible path. +``` + +Wait for all hunters. + +### Phase 2: PoC Pass + +Deduplicate hunter candidates. Send the strongest candidates to both PoC engineers. + +Each PoC engineer must return: + +- Reproduced, falsified, or unsafe-to-run. +- Exact commands, fixtures, or static proof. +- Observed output or reason it fails. +- Severity recommendation using exploitability and impact. +- Downgrade rationale for anything not reproduced. + +### Phase 3: Cross-Check + +Send the PoC results back to all 5 members. + +Ask every member: + +- Which findings survive? +- Which findings should be downgraded or removed? +- What remediation is smallest and specific? +- What regression test would prevent recurrence? + +### Phase 4: Final Report + +Produce this report: + +```markdown +## Security Research Result + +### Verdict +PASS | PASS WITH FINDINGS | BLOCK + +### Scope +- Target: +- Base/diff: +- Commands run: + +### Findings +| Severity | Title | CWE | Exploitability | Impact | PoC | Fix | +|----------|-------|-----|----------------|--------|-----|-----| + +### Finding Details +For each finding: +- Evidence: +- Attack path: +- PoC: +- Severity rationale: +- Minimal fix: +- Regression check: + +### Downgraded or Rejected Candidates +| Candidate | Reason | +|-----------|--------| + +### Residual Risk +- What was not tested and why. +``` + +## Output Rules + +- Lead with the verdict. +- Do not bury blocking issues. +- Do not report speculative findings as vulnerabilities. +- Do not claim CVSS precision unless you actually scored the metrics. +- Include exact file paths and commands for every surviving finding. +- If no findings survive PoC, say that plainly and list residual risk. diff --git a/src/features/builtin-skills/skills.test.ts b/src/features/builtin-skills/skills.test.ts index 3d71d3736..4480d7ef3 100644 --- a/src/features/builtin-skills/skills.test.ts +++ b/src/features/builtin-skills/skills.test.ts @@ -13,8 +13,8 @@ describe("createBuiltinSkills", () => { // then const browserSkill = skills.find((s) => s.name === "playwright") expect(browserSkill).toBeDefined() - expect(browserSkill!.description).toContain("browser") - expect(browserSkill!.mcpConfig?.playwright).toBeDefined() + expect(browserSkill?.description).toContain("browser") + expect(browserSkill?.mcpConfig?.playwright).toBeDefined() }) test("returns playwright skill when browserProvider is 'playwright'", () => { @@ -46,7 +46,7 @@ describe("createBuiltinSkills", () => { const playwrightSkill = skills.find((skill) => skill.name === "playwright") const agentBrowserSkill = skills.find((skill) => skill.name === "agent-browser") expect(devBrowserSkill).toBeDefined() - expect(devBrowserSkill!.description).toContain("Browser automation") + expect(devBrowserSkill?.description).toContain("Browser automation") expect(playwrightSkill).toBeUndefined() expect(agentBrowserSkill).toBeUndefined() expect(skillNames).not.toContain("playwright-cli") @@ -64,9 +64,9 @@ describe("createBuiltinSkills", () => { const agentBrowserSkill = skills.find((s) => s.name === "agent-browser") const playwrightSkill = skills.find((s) => s.name === "playwright") expect(agentBrowserSkill).toBeDefined() - expect(agentBrowserSkill!.description).toContain("browser") - expect(agentBrowserSkill!.allowedTools).toContain("Bash(agent-browser:*)") - expect(agentBrowserSkill!.template).toContain("agent-browser") + expect(agentBrowserSkill?.description).toContain("browser") + expect(agentBrowserSkill?.allowedTools).toContain("Bash(agent-browser:*)") + expect(agentBrowserSkill?.template).toContain("agent-browser") expect(playwrightSkill).toBeUndefined() }) @@ -79,13 +79,13 @@ describe("createBuiltinSkills", () => { const agentBrowserSkill = skills.find((s) => s.name === "agent-browser") // then - template should contain substantial content (inlined, not fallback) - expect(agentBrowserSkill!.template).toContain("## Quick start") - expect(agentBrowserSkill!.template).toContain("## Commands") - expect(agentBrowserSkill!.template).toContain("agent-browser open") - expect(agentBrowserSkill!.template).toContain("agent-browser snapshot") + expect(agentBrowserSkill?.template).toContain("## Quick start") + expect(agentBrowserSkill?.template).toContain("## Commands") + expect(agentBrowserSkill?.template).toContain("agent-browser open") + expect(agentBrowserSkill?.template).toContain("agent-browser snapshot") }) - test("always includes frontend-ui-ux, git-master, review-work, remove-ai-slops, and init-deep skills", () => { + test("always includes frontend-ui-ux, git-master, review-work, shared skills, and runtime security skills", () => { // given - both provider options // when @@ -100,10 +100,12 @@ describe("createBuiltinSkills", () => { expect(skills.find((s) => s.name === "review-work")).toBeDefined() expect(skills.find((s) => s.name === "remove-ai-slops")).toBeDefined() expect(skills.find((s) => s.name === "init-deep")).toBeDefined() + expect(skills.find((s) => s.name === "security-research")).toBeDefined() + expect(skills.find((s) => s.name === "security-review")).toBeDefined() } }) - test("returns exactly 6 skills regardless of provider", () => { + test("returns exactly 8 skills regardless of provider", () => { // given // when @@ -112,9 +114,9 @@ describe("createBuiltinSkills", () => { const devBrowserSkills = createBuiltinSkills({ browserProvider: "dev-browser" }) // then - expect(defaultSkills).toHaveLength(6) - expect(agentBrowserSkills).toHaveLength(6) - expect(devBrowserSkills).toHaveLength(6) + expect(defaultSkills).toHaveLength(8) + expect(agentBrowserSkills).toHaveLength(8) + expect(devBrowserSkills).toHaveLength(8) }) test("should exclude playwright when it is in disabledSkills", () => { @@ -132,7 +134,9 @@ describe("createBuiltinSkills", () => { expect(skills.map((s) => s.name)).toContain("review-work") expect(skills.map((s) => s.name)).toContain("remove-ai-slops") expect(skills.map((s) => s.name)).toContain("init-deep") - expect(skills.length).toBe(5) + expect(skills.map((s) => s.name)).toContain("security-research") + expect(skills.map((s) => s.name)).toContain("security-review") + expect(skills.length).toBe(7) }) test("should exclude multiple skills when they are in disabledSkills", () => { @@ -150,12 +154,25 @@ describe("createBuiltinSkills", () => { expect(skills.map((s) => s.name)).toContain("review-work") expect(skills.map((s) => s.name)).toContain("remove-ai-slops") expect(skills.map((s) => s.name)).toContain("init-deep") - expect(skills.length).toBe(4) + expect(skills.map((s) => s.name)).toContain("security-research") + expect(skills.map((s) => s.name)).toContain("security-review") + expect(skills.length).toBe(6) }) test("should return an empty array when all skills are disabled", () => { // #given - const options = { disabledSkills: new Set(["playwright", "frontend-ui-ux", "git-master", "review-work", "remove-ai-slops", "init-deep"]) } + const options = { + disabledSkills: new Set([ + "playwright", + "frontend-ui-ux", + "git-master", + "review-work", + "remove-ai-slops", + "init-deep", + "security-research", + "security-review", + ]), + } // #when const skills = createBuiltinSkills(options) @@ -172,7 +189,7 @@ describe("createBuiltinSkills", () => { const skills = createBuiltinSkills(options) // #then - expect(skills.length).toBe(6) + expect(skills.length).toBe(8) }) test("init-deep skill has correct structure", () => { @@ -199,13 +216,13 @@ describe("createBuiltinSkills", () => { // #then expect(reviewWork).toBeDefined() - expect(reviewWork!.description).toContain("review") - expect(reviewWork!.template).toContain("5-Agent Parallel Review Orchestrator") - expect(reviewWork!.template).toContain("Goal & Constraint Verification") - expect(reviewWork!.template).toContain("QA") - expect(reviewWork!.template).toContain("Code Quality") - expect(reviewWork!.template).toContain("Security") - expect(reviewWork!.template).toContain("Context Mining") + expect(reviewWork?.description).toContain("review") + expect(reviewWork?.template).toContain("5-Agent Parallel Review Orchestrator") + expect(reviewWork?.template).toContain("Goal & Constraint Verification") + expect(reviewWork?.template).toContain("QA") + expect(reviewWork?.template).toContain("Code Quality") + expect(reviewWork?.template).toContain("Security") + expect(reviewWork?.template).toContain("Context Mining") }) test("review-work skill explains Codex tool compatibility before OpenCode orchestration examples", () => { @@ -214,8 +231,9 @@ describe("createBuiltinSkills", () => { // #when const reviewWork = skills.find((s) => s.name === "review-work") - const compatibilityIndex = reviewWork!.template.indexOf("## Codex Harness Tool Compatibility") - const opencodeExampleIndex = reviewWork!.template.search(/\b(?:background_output|team_[a-z_]+|task)\s*\(/) + const reviewWorkTemplate = reviewWork?.template ?? "" + const compatibilityIndex = reviewWorkTemplate.indexOf("## Codex Harness Tool Compatibility") + const opencodeExampleIndex = reviewWorkTemplate.search(/\b(?:background_output|team_[a-z_]+|task)\s*\(/) // #then expect(compatibilityIndex >= 0).toBe(true) @@ -236,6 +254,34 @@ describe("createBuiltinSkills", () => { expect(removeAiSlops!.template).toContain("$omo:remove-ai-slops") }) + test("security-research skill has correct structure", () => { + // #given - default options + + // #when + const skills = createBuiltinSkills() + const securityResearch = skills.find((skill) => skill.name === "security-research") + + // #then + expect(securityResearch?.description).toContain("security research") + expect(securityResearch?.template).toContain("Security Research - Team Mode Vulnerability Audit") + expect(securityResearch?.template).toContain('name: "security-research"') + expect(securityResearch?.template).toContain("Security Research Result") + }) + + test("security-review skill remains a runtime alias for security-research", () => { + // #given - default options + + // #when + const skills = createBuiltinSkills() + const securityReview = skills.find((skill) => skill.name === "security-review") + const securityResearch = skills.find((skill) => skill.name === "security-research") + + // #then + expect(securityReview?.description).toContain("Alias for security-research") + expect(securityReview?.description).toContain("/security-review") + expect(securityReview?.template).toBe(securityResearch?.template) + }) + test("returns playwright-cli skill when browserProvider is 'playwright-cli'", () => { // given const options = { browserProvider: "playwright-cli" as const } @@ -247,9 +293,9 @@ describe("createBuiltinSkills", () => { const playwrightSkill = skills.find((s) => s.name === "playwright") const agentBrowserSkill = skills.find((s) => s.name === "agent-browser") expect(playwrightSkill).toBeDefined() - expect(playwrightSkill!.description).toContain("browser") - expect(playwrightSkill!.allowedTools).toContain("Bash(playwright-cli:*)") - expect(playwrightSkill!.mcpConfig).toBeUndefined() + expect(playwrightSkill?.description).toContain("browser") + expect(playwrightSkill?.allowedTools).toContain("Bash(playwright-cli:*)") + expect(playwrightSkill?.mcpConfig).toBeUndefined() expect(agentBrowserSkill).toBeUndefined() }) @@ -262,8 +308,8 @@ describe("createBuiltinSkills", () => { const skill = skills.find((s) => s.name === "playwright") // then - expect(skill!.template).toContain("playwright-cli open") - expect(skill!.template).toContain("playwright-cli snapshot") - expect(skill!.template).toContain("playwright-cli click") + expect(skill?.template).toContain("playwright-cli open") + expect(skill?.template).toContain("playwright-cli snapshot") + expect(skill?.template).toContain("playwright-cli click") }) }) diff --git a/src/features/builtin-skills/skills.ts b/src/features/builtin-skills/skills.ts index a8c47b72d..ccba18eae 100644 --- a/src/features/builtin-skills/skills.ts +++ b/src/features/builtin-skills/skills.ts @@ -11,6 +11,8 @@ import { initDeepSkill, removeAiSlopsSkill, reviewWorkSkill, + securityResearchSkill, + securityReviewSkill, teamModeSkill, } from "./skills/index" @@ -34,7 +36,16 @@ export function createBuiltinSkills(options: CreateBuiltinSkillsOptions = {}): B browserSkill = playwrightSkill } - const skills = [browserSkill, frontendUiUxSkill, gitMasterSkill, reviewWorkSkill, removeAiSlopsSkill, initDeepSkill] + const skills = [ + browserSkill, + frontendUiUxSkill, + gitMasterSkill, + reviewWorkSkill, + removeAiSlopsSkill, + initDeepSkill, + securityResearchSkill, + securityReviewSkill, + ] if (teamModeEnabled && !disabledSkills?.has("team-mode")) { skills.push(teamModeSkill) diff --git a/src/features/builtin-skills/skills/index.ts b/src/features/builtin-skills/skills/index.ts index f74a55043..1da5d4998 100644 --- a/src/features/builtin-skills/skills/index.ts +++ b/src/features/builtin-skills/skills/index.ts @@ -6,4 +6,6 @@ export { devBrowserSkill } from "./dev-browser" export { reviewWorkSkill } from "./review-work" export { removeAiSlopsSkill } from "./remove-ai-slops" export { initDeepSkill } from "./init-deep" +export { securityResearchSkill } from "./security-research" +export { securityReviewSkill } from "./security-review" export * from "./team-mode" diff --git a/src/features/builtin-skills/skills/security-research.ts b/src/features/builtin-skills/skills/security-research.ts new file mode 100644 index 000000000..f190bf13b --- /dev/null +++ b/src/features/builtin-skills/skills/security-research.ts @@ -0,0 +1,9 @@ +import type { BuiltinSkill } from "../types" +import securityResearchTemplate from "../security-research/SKILL.md" with { type: "text" } + +export const securityResearchSkill: BuiltinSkill = { + name: "security-research", + description: + "Team Mode security research skill. Orchestrates 3 vulnerability hunters and 2 PoC engineers to audit a codebase in parallel, prove exploitability, classify root causes, and calibrate severity by actual exploitability. Use for security review, vulnerability research, exploitability audit, pre-release security check, threat model validation, and `/security-research`. Triggers: 'security-research', 'security research', 'security review', 'vulnerability audit', 'exploitability audit', '보안 리뷰', '취약점 감사'.", + template: securityResearchTemplate, +} diff --git a/src/features/builtin-skills/skills/security-review.ts b/src/features/builtin-skills/skills/security-review.ts new file mode 100644 index 000000000..864f90c30 --- /dev/null +++ b/src/features/builtin-skills/skills/security-review.ts @@ -0,0 +1,8 @@ +import type { BuiltinSkill } from "../types" +import { securityResearchSkill } from "./security-research" + +export const securityReviewSkill: BuiltinSkill = { + name: "security-review", + description: `Alias for security-research and /security-review. ${securityResearchSkill.description}`, + template: securityResearchSkill.template, +} diff --git a/src/features/opencode-runtime-skills/index.ts b/src/features/opencode-runtime-skills/index.ts new file mode 100644 index 000000000..02f8d374c --- /dev/null +++ b/src/features/opencode-runtime-skills/index.ts @@ -0,0 +1,7 @@ +export { + applyRuntimeSkillSourceConfig, + selectRuntimeSecuritySkills, + type OpenCodeSkillHostConfig, + type RuntimeSkillSourceEntry, +} from "./runtime-skill-config" +export { createRuntimeSkillSourceServer, type RuntimeSkillSourceServer } from "./source-server" diff --git a/src/features/opencode-runtime-skills/runtime-skill-config.test.ts b/src/features/opencode-runtime-skills/runtime-skill-config.test.ts new file mode 100644 index 000000000..b1ca510f1 --- /dev/null +++ b/src/features/opencode-runtime-skills/runtime-skill-config.test.ts @@ -0,0 +1,102 @@ +import { describe, expect, test } from "bun:test" +import type { OhMyOpenCodeConfig } from "../../config" +import { + applyRuntimeSkillSourceConfig, + selectRuntimeSecuritySkills, + type OpenCodeSkillHostConfig, +} from "./runtime-skill-config" + +type DisabledSkillName = NonNullable[number] + +function createPluginConfig(disabledSkills?: readonly DisabledSkillName[]): OhMyOpenCodeConfig { + return { + git_master: { + commit_footer: true, + include_co_authored_by: true, + git_env_prefix: "GIT_MASTER=1", + }, + disabled_skills: disabledSkills ? [...disabledSkills] : undefined, + } +} + +describe("OpenCode runtime skill source config", () => { + test("adds the runtime source URL while preserving existing skill URLs and paths", () => { + // given + const config: OpenCodeSkillHostConfig = { + skills: { + urls: ["https://example.com/skills"], + paths: ["/keep/user/path"], + }, + } + + // when + applyRuntimeSkillSourceConfig({ + config, + pluginConfig: createPluginConfig(), + sourceUrl: "http://127.0.0.1:49152/", + }) + + // then + expect(config.skills?.urls).toEqual([ + "https://example.com/skills", + "http://127.0.0.1:49152/", + ]) + expect(config.skills?.paths).toEqual(["/keep/user/path"]) + }) + + test("deduplicates the runtime source URL", () => { + // given + const config: OpenCodeSkillHostConfig = { + skills: { + urls: ["http://127.0.0.1:49152/"], + }, + } + + // when + applyRuntimeSkillSourceConfig({ + config, + pluginConfig: createPluginConfig(), + sourceUrl: "http://127.0.0.1:49152/", + }) + + // then + expect(config.skills?.urls).toEqual(["http://127.0.0.1:49152/"]) + }) + + test("does not create skills config when every runtime security skill is disabled", () => { + // given + const config: OpenCodeSkillHostConfig = {} + + // when + applyRuntimeSkillSourceConfig({ + config, + pluginConfig: createPluginConfig(["security-research", "security-review"]), + sourceUrl: "http://127.0.0.1:49152/", + }) + + // then + expect(config.skills).toBeUndefined() + }) + + test("security-research disablement keeps security-review enabled", () => { + // given + const pluginConfig = createPluginConfig(["security-research"]) + + // when + const skills = selectRuntimeSecuritySkills(pluginConfig) + + // then + expect(skills.map((skill) => skill.name)).toEqual(["security-review"]) + }) + + test("security-review disablement suppresses only the review alias", () => { + // given + const pluginConfig = createPluginConfig(["security-review"]) + + // when + const skills = selectRuntimeSecuritySkills(pluginConfig) + + // then + expect(skills.map((skill) => skill.name)).toEqual(["security-research"]) + }) +}) diff --git a/src/features/opencode-runtime-skills/runtime-skill-config.ts b/src/features/opencode-runtime-skills/runtime-skill-config.ts new file mode 100644 index 000000000..a0db49c6b --- /dev/null +++ b/src/features/opencode-runtime-skills/runtime-skill-config.ts @@ -0,0 +1,65 @@ +import type { OhMyOpenCodeConfig } from "../../config" +import { securityResearchSkill, securityReviewSkill } from "../builtin-skills/skills/index" +import { createOpenCodeSkillMarkdown, type OpenCodeSkillMarkdown } from "./skill-markdown" + +export type RuntimeSkillSourceEntry = OpenCodeSkillMarkdown + +export type OpenCodeSkillsHostConfig = { + readonly paths?: readonly string[] + readonly urls?: readonly string[] + readonly [key: string]: unknown +} + +export type OpenCodeSkillHostConfig = Record & { + skills?: OpenCodeSkillsHostConfig +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value) +} + +function toStringList(value: unknown): string[] { + if (!Array.isArray(value)) return [] + return value.filter((item): item is string => typeof item === "string") +} + +function appendUnique(values: readonly string[], next: string): string[] { + if (values.includes(next)) return [...values] + return [...values, next] +} + +export function selectRuntimeSecuritySkills( + pluginConfig: Pick = {}, +): RuntimeSkillSourceEntry[] { + const disabledSkills = new Set(pluginConfig.disabled_skills ?? []) + const includeResearch = !disabledSkills.has("security-research") + const includeReview = !disabledSkills.has("security-review") + if (!includeResearch && !includeReview) return [] + + const skills = [] + if (includeResearch) { + skills.push(securityResearchSkill) + } + if (includeReview) { + skills.push(securityReviewSkill) + } + + return skills.map((skill) => createOpenCodeSkillMarkdown(skill)) +} + +export function applyRuntimeSkillSourceConfig(params: { + readonly config: OpenCodeSkillHostConfig + readonly pluginConfig: Pick + readonly sourceUrl: string +}): void { + if (selectRuntimeSecuritySkills(params.pluginConfig).length === 0) return + + const existingSkills = isRecord(params.config.skills) ? params.config.skills : {} + const existingUrls = toStringList(existingSkills.urls) + const nextUrls = appendUnique(existingUrls, params.sourceUrl) + + params.config.skills = { + ...existingSkills, + urls: nextUrls, + } +} diff --git a/src/features/opencode-runtime-skills/skill-markdown.ts b/src/features/opencode-runtime-skills/skill-markdown.ts new file mode 100644 index 000000000..dfced0427 --- /dev/null +++ b/src/features/opencode-runtime-skills/skill-markdown.ts @@ -0,0 +1,25 @@ +import type { BuiltinSkill } from "../builtin-skills/types" + +export type OpenCodeSkillMarkdown = { + readonly name: string + readonly description: string + readonly markdown: string +} + +export function createOpenCodeSkillMarkdown(skill: BuiltinSkill): OpenCodeSkillMarkdown { + const body = skill.template.trimStart() + const markdown = [ + "---", + `name: ${skill.name}`, + `description: ${JSON.stringify(skill.description)}`, + "---", + "", + body, + ].join("\n") + + return { + name: skill.name, + description: skill.description, + markdown, + } +} diff --git a/src/features/opencode-runtime-skills/source-server.test.ts b/src/features/opencode-runtime-skills/source-server.test.ts new file mode 100644 index 000000000..6fe0d3fe8 --- /dev/null +++ b/src/features/opencode-runtime-skills/source-server.test.ts @@ -0,0 +1,57 @@ +import { afterEach, describe, expect, test } from "bun:test" +import { createRuntimeSkillSourceServer } from "./source-server" +import { selectRuntimeSecuritySkills } from "./runtime-skill-config" + +let cleanupServer: { readonly stop: () => void } | undefined + +afterEach(() => { + cleanupServer?.stop() + cleanupServer = undefined +}) + +describe("runtime security skill source server", () => { + test("serves an OpenCode skill index and markdown files with matching frontmatter names", async () => { + // given + const source = createRuntimeSkillSourceServer({ + skills: selectRuntimeSecuritySkills(), + }) + cleanupServer = source + + // when + const indexResponse = await fetch(new URL("index.json", source.url)) + const index = await indexResponse.json() + const researchResponse = await fetch(new URL("security-research/SKILL.md", source.url)) + const reviewResponse = await fetch(new URL("security-review/SKILL.md", source.url)) + const researchMarkdown = await researchResponse.text() + const reviewMarkdown = await reviewResponse.text() + + // then + expect(indexResponse.status).toBe(200) + expect(index).toEqual({ + skills: [ + { name: "security-research", files: ["SKILL.md"] }, + { name: "security-review", files: ["SKILL.md"] }, + ], + }) + expect(researchResponse.status).toBe(200) + expect(reviewResponse.status).toBe(200) + expect(researchMarkdown).toStartWith("---\nname: security-research\n") + expect(reviewMarkdown).toStartWith("---\nname: security-review\n") + expect(researchMarkdown).toContain("Security Research - Team Mode Vulnerability Audit") + expect(reviewMarkdown).toContain("Security Research - Team Mode Vulnerability Audit") + }) + + test("returns 404 for unknown paths", async () => { + // given + const source = createRuntimeSkillSourceServer({ + skills: selectRuntimeSecuritySkills(), + }) + cleanupServer = source + + // when + const response = await fetch(new URL("missing/SKILL.md", source.url)) + + // then + expect(response.status).toBe(404) + }) +}) diff --git a/src/features/opencode-runtime-skills/source-server.ts b/src/features/opencode-runtime-skills/source-server.ts new file mode 100644 index 000000000..939b2b71e --- /dev/null +++ b/src/features/opencode-runtime-skills/source-server.ts @@ -0,0 +1,78 @@ +import type { RuntimeSkillSourceEntry } from "./runtime-skill-config" + +export type RuntimeSkillSourceServer = { + readonly url: string + readonly stop: () => void +} + +type BunServeServer = { + readonly url: URL + stop(closeActiveConnections?: boolean): void +} + +type BunServeRuntime = { + serve(options: { + readonly hostname: string + readonly port: number + readonly fetch: (request: Request) => Response | Promise + }): BunServeServer +} + +const runtime = globalThis as typeof globalThis & { Bun?: BunServeRuntime } + +function jsonResponse(body: unknown): Response { + return Response.json(body, { + headers: { + "cache-control": "no-store", + }, + }) +} + +function markdownResponse(markdown: string): Response { + return new Response(markdown, { + headers: { + "cache-control": "no-store", + "content-type": "text/markdown; charset=utf-8", + }, + }) +} + +export function createRuntimeSkillSourceServer(options: { + readonly skills: readonly RuntimeSkillSourceEntry[] +}): RuntimeSkillSourceServer { + const skillMarkdownByPath = new Map( + options.skills.map((skill) => [`/${skill.name}/SKILL.md`, skill.markdown]), + ) + const index = { + skills: options.skills.map((skill) => ({ + name: skill.name, + files: ["SKILL.md"], + })), + } + + const bun = runtime.Bun + if (!bun) { + throw new Error("Runtime skill source server requires Bun.serve") + } + + const server = bun.serve({ + hostname: "127.0.0.1", + port: 0, + fetch(request) { + const url = new URL(request.url) + if (url.pathname === "/" || url.pathname === "/index.json") { + return jsonResponse(index) + } + + const markdown = skillMarkdownByPath.get(url.pathname) + if (markdown) return markdownResponse(markdown) + + return new Response("not found", { status: 404 }) + }, + }) + + return { + url: server.url.toString(), + stop: () => server.stop(true), + } +} diff --git a/src/plugin-handlers/config-handler.test.ts b/src/plugin-handlers/config-handler.test.ts index bfc189341..39e785f9c 100644 --- a/src/plugin-handlers/config-handler.test.ts +++ b/src/plugin-handlers/config-handler.test.ts @@ -231,6 +231,93 @@ describe("MCP env allowlist initialization", () => { }) }) +describe("runtime security skill source registration", () => { + test("adds the runtime skill source URL to the live OpenCode config", async () => { + // given + const pluginConfig = createPluginConfig({}) + const config: Record = { + model: "anthropic/claude-opus-4-7", + agent: {}, + skills: { + urls: ["https://example.com/skills"], + paths: ["/tmp/user-skills"], + }, + } + const handler = createConfigHandler({ + ctx: { directory: "/tmp" }, + pluginConfig, + modelCacheState: { + anthropicContext1MEnabled: false, + modelContextLimitsCache: new Map(), + }, + runtimeSkillSourceUrl: "http://127.0.0.1:49152/", + }) + + // when + await handler(config) + + // then + expect(config.skills).toMatchObject({ + urls: ["https://example.com/skills", "http://127.0.0.1:49152/"], + paths: ["/tmp/user-skills"], + }) + }) + + test("adds the runtime skill source when only security-review remains enabled", async () => { + // given + const pluginConfig = createPluginConfig({ + disabled_skills: ["security-research"], + }) + const config: Record = { + model: "anthropic/claude-opus-4-7", + agent: {}, + } + const handler = createConfigHandler({ + ctx: { directory: "/tmp" }, + pluginConfig, + modelCacheState: { + anthropicContext1MEnabled: false, + modelContextLimitsCache: new Map(), + }, + runtimeSkillSourceUrl: "http://127.0.0.1:49152/", + }) + + // when + await handler(config) + + // then + expect(config.skills).toMatchObject({ + urls: ["http://127.0.0.1:49152/"], + }) + }) + + test("does not add a runtime skill source when both security skills are disabled", async () => { + // given + const pluginConfig = createPluginConfig({ + disabled_skills: ["security-research", "security-review"], + }) + const config: Record = { + model: "anthropic/claude-opus-4-7", + agent: {}, + } + const handler = createConfigHandler({ + ctx: { directory: "/tmp" }, + pluginConfig, + modelCacheState: { + anthropicContext1MEnabled: false, + modelContextLimitsCache: new Map(), + }, + runtimeSkillSourceUrl: "http://127.0.0.1:49152/", + }) + + // when + await handler(config) + + // then + expect(config.skills).toBeUndefined() + }) +}) + describe("Plan agent demote behavior", () => { test("orders core agents as sisyphus -> hephaestus -> prometheus -> atlas", async () => { // #given @@ -1002,10 +1089,11 @@ describe("Prometheus direct override priority over category", () => { // #then - prompt_append is appended to base prompt, not overwriting it const agents = config.agent as Record const pKey = getAgentListDisplayName("prometheus") + const prometheusPrompt = agents[pKey]?.prompt expect(agents[pKey]).toBeDefined() - expect(agents[pKey].prompt).toContain("Prometheus") - expect(agents[pKey].prompt).toContain(customInstructions) - expect(agents[pKey].prompt!.endsWith(customInstructions)).toBe(true) + expect(prometheusPrompt).toContain("Prometheus") + expect(prometheusPrompt).toContain(customInstructions) + expect(prometheusPrompt?.endsWith(customInstructions)).toBe(true) }) }) diff --git a/src/plugin-handlers/config-handler.ts b/src/plugin-handlers/config-handler.ts index 4ba6979f1..85ae1cf41 100644 --- a/src/plugin-handlers/config-handler.ts +++ b/src/plugin-handlers/config-handler.ts @@ -1,4 +1,5 @@ import type { OhMyOpenCodeConfig } from "../config"; +import { applyRuntimeSkillSourceConfig } from "../features/opencode-runtime-skills" import { setAdditionalAllowedMcpEnvVars } from "../features/claude-code-mcp-loader"; import type { ModelCacheState } from "../plugin-state"; import { log } from "../shared"; @@ -26,13 +27,14 @@ function collectTrustedVisionCapableModels( } export interface ConfigHandlerDeps { - ctx: { directory: string; client?: any }; + ctx: { directory: string; client?: unknown }; pluginConfig: OhMyOpenCodeConfig; modelCacheState: ModelCacheState; + runtimeSkillSourceUrl?: string; } export function createConfigHandler(deps: ConfigHandlerDeps) { - const { ctx, pluginConfig, modelCacheState } = deps; + const { ctx, pluginConfig, modelCacheState, runtimeSkillSourceUrl } = deps; return async (config: Record) => { const formatterConfig = config.formatter; @@ -59,6 +61,13 @@ export function createConfigHandler(deps: ConfigHandlerDeps) { applyToolConfig({ config, pluginConfig, agentResult }); await applyMcpConfig({ config, pluginConfig, ctx, pluginComponents }); await applyCommandConfig({ config, pluginConfig, ctx, pluginComponents }); + if (runtimeSkillSourceUrl) { + applyRuntimeSkillSourceConfig({ + config, + pluginConfig, + sourceUrl: runtimeSkillSourceUrl, + }) + } config.formatter = formatterConfig; diff --git a/src/plugin/skill-context.test.ts b/src/plugin/skill-context.test.ts index 75397fb0b..9e8e06533 100644 --- a/src/plugin/skill-context.test.ts +++ b/src/plugin/skill-context.test.ts @@ -19,6 +19,75 @@ describe("createSkillContext", () => { rmSync(testDirectory, { recursive: true, force: true }) }) + it("exposes security skills to the OMO skill tool context", async () => { + // given + const discoverConfigSourceSkillsSpy = spyOn( + skillLoader, + "discoverConfigSourceSkills", + ).mockResolvedValue([]) + const discoverUserClaudeSkillsSpy = spyOn( + skillLoader, + "discoverUserClaudeSkills", + ).mockResolvedValue([]) + const discoverProjectClaudeSkillsSpy = spyOn( + skillLoader, + "discoverProjectClaudeSkills", + ).mockResolvedValue([]) + const discoverOpencodeGlobalSkillsSpy = spyOn( + skillLoader, + "discoverOpencodeGlobalSkills", + ).mockResolvedValue([]) + const discoverOpencodeProjectSkillsSpy = spyOn( + skillLoader, + "discoverOpencodeProjectSkills", + ).mockResolvedValue([]) + const discoverProjectAgentsSkillsSpy = spyOn( + skillLoader, + "discoverProjectAgentsSkills", + ).mockResolvedValue([]) + const discoverGlobalAgentsSkillsSpy = spyOn( + skillLoader, + "discoverGlobalAgentsSkills", + ).mockResolvedValue([]) + const getSystemMcpServerNamesSpy = spyOn( + mcpLoader, + "getSystemMcpServerNames", + ).mockReturnValue(new Set()) + + const pluginConfig = OhMyOpenCodeConfigSchema.parse({}) + + try { + // when + const result = await createSkillContext({ + directory: testDirectory, + pluginConfig, + }) + + // then + expect(result.mergedSkills.some((skill) => skill.name === "security-research")).toBe(true) + expect(result.mergedSkills.some((skill) => skill.name === "security-review")).toBe(true) + expect(result.availableSkills).toContainEqual({ + name: "security-research", + description: expect.stringContaining("security research"), + location: "plugin", + }) + expect(result.availableSkills).toContainEqual({ + name: "security-review", + description: expect.stringContaining("/security-review"), + location: "plugin", + }) + } finally { + discoverConfigSourceSkillsSpy.mockRestore() + discoverUserClaudeSkillsSpy.mockRestore() + discoverProjectClaudeSkillsSpy.mockRestore() + discoverOpencodeGlobalSkillsSpy.mockRestore() + discoverOpencodeProjectSkillsSpy.mockRestore() + discoverProjectAgentsSkillsSpy.mockRestore() + discoverGlobalAgentsSkillsSpy.mockRestore() + getSystemMcpServerNamesSpy.mockRestore() + } + }) + it("excludes discovered playwright skill when browser provider is agent-browser", async () => { // given const discoveredPlaywrightDir = join(testDirectory, ".claude", "skills", "playwright") diff --git a/src/testing/create-plugin-module.test.ts b/src/testing/create-plugin-module.test.ts index 8f3fa06ad..95d370aef 100644 --- a/src/testing/create-plugin-module.test.ts +++ b/src/testing/create-plugin-module.test.ts @@ -32,6 +32,13 @@ const mockCreateManagers = mock(() => ({ skillMcpManager: { disconnectAll: async () => {} }, configHandler: async () => {}, })) +const mockRuntimeSkillSourceStop = mock(() => {}) +const mockCreateRuntimeSkillSourceServer = mock( + (options: { readonly skills: readonly { readonly name: string }[] }) => ({ + url: `http://127.0.0.1:49152/${options.skills.map((skill) => skill.name).join(",")}`, + stop: mockRuntimeSkillSourceStop, + }), +) const mockCreateTools = mock(async () => ({ mergedSkills: [], availableSkills: [], @@ -71,6 +78,7 @@ function createTestPluginModule(): ReturnType { isTmuxIntegrationEnabled: mockIsTmuxIntegrationEnabled as never, createRuntimeTmuxConfig: mockCreateRuntimeTmuxConfig as never, createManagers: mockCreateManagers as never, + createRuntimeSkillSourceServer: mockCreateRuntimeSkillSourceServer as never, createTools: mockCreateTools as never, createHooks: mockCreateHooks as never, createPluginInterface: mockCreatePluginInterface as never, @@ -91,6 +99,8 @@ describe("createPluginModule()", () => { mockInjectServerAuthIntoClient.mockClear() mockLoadPluginConfig.mockClear() mockCreateManagers.mockClear() + mockRuntimeSkillSourceStop.mockClear() + mockCreateRuntimeSkillSourceServer.mockClear() mockCreateTools.mockClear() mockCreateHooks.mockClear() mockCreatePluginInterface.mockClear() @@ -123,6 +133,71 @@ describe("createPluginModule()", () => { }) }) + describe("#given bundled security skills are enabled", () => { + it("#then startup exposes them through a runtime skill source URL", async () => { + // given + const pluginModule = createTestPluginModule() + mockLoadPluginConfig.mockReturnValue({}) + + // when + await pluginModule.server({ + directory: "/tmp/project", + client: {}, + } as Parameters[0]) + + // then + const sourceArgs = mockCreateRuntimeSkillSourceServer.mock.calls.at(0)?.[0] + expect(sourceArgs?.skills.map((skill) => skill.name)).toEqual([ + "security-research", + "security-review", + ]) + expect(mockCreateManagers.mock.calls.at(0)?.[0]).toMatchObject({ + runtimeSkillSourceUrl: "http://127.0.0.1:49152/security-research,security-review", + }) + }) + + it("#then dispose stops the runtime skill source", async () => { + // given + const pluginModule = createTestPluginModule() + mockLoadPluginConfig.mockReturnValue({}) + + // when + const hooks: Awaited> & { + dispose?: () => Promise + } = await pluginModule.server({ + directory: "/tmp/project", + client: {}, + } as Parameters[0]) + await hooks.dispose?.() + + // then + expect(mockRuntimeSkillSourceStop).toHaveBeenCalledTimes(1) + }) + }) + + describe("#given security-research is disabled", () => { + it("#then startup still exposes security-review through the runtime skill source", async () => { + // given + const pluginModule = createTestPluginModule() + mockLoadPluginConfig.mockReturnValue({ + disabled_skills: ["security-research"], + }) + + // when + await pluginModule.server({ + directory: "/tmp/project", + client: {}, + } as Parameters[0]) + + // then + const sourceArgs = mockCreateRuntimeSkillSourceServer.mock.calls.at(0)?.[0] + expect(sourceArgs?.skills.map((skill) => skill.name)).toEqual(["security-review"]) + expect(mockCreateManagers.mock.calls.at(0)?.[0]).toMatchObject({ + runtimeSkillSourceUrl: "http://127.0.0.1:49152/security-review", + }) + }) + }) + describe("#given duplicate OMO plugin entries are configured", () => { it("#then startup warns and returns no prompt-producing hooks", async () => { // given diff --git a/src/testing/create-plugin-module.ts b/src/testing/create-plugin-module.ts index 950185899..3e6455df1 100644 --- a/src/testing/create-plugin-module.ts +++ b/src/testing/create-plugin-module.ts @@ -6,7 +6,9 @@ import { createHooks } from "../create-hooks" import { createManagers } from "../create-managers" import { createRuntimeTmuxConfig, isTmuxIntegrationEnabled } from "../create-runtime-tmux-config" import { createTools } from "../create-tools" +import { createRuntimeSkillSourceServer, selectRuntimeSecuritySkills } from "../features/opencode-runtime-skills" import { initializeOpenClaw } from "../openclaw" +import { createPluginDispose } from "../plugin-dispose" import { createPluginInterface } from "../plugin-interface" import { loadPluginConfig } from "../plugin-config" import { createModelCacheState } from "../plugin-state" @@ -30,8 +32,9 @@ import { migrateLegacyWorkspaceDirectory } from "../shared/legacy-workspace-migr import { injectServerAuthIntoClient } from "../shared/opencode-server-auth" import { startBackgroundCheck as startTmuxCheck } from "../tools/interactive-bash" -type HooksWithCompactionAutocontinue = Hooks & { +type HooksWithRuntimeLifecycle = Hooks & { "experimental.compaction.autocontinue"?: CompactionAutocontinueHook + dispose?: () => Promise } export type PluginModuleDeps = { @@ -56,6 +59,7 @@ export type PluginModuleDeps = { createModelCacheState: typeof createModelCacheState createManagers: typeof createManagers createTools: typeof createTools + createRuntimeSkillSourceServer: typeof createRuntimeSkillSourceServer createHooks: typeof createHooks createPluginInterface: typeof createPluginInterface } @@ -82,6 +86,7 @@ const defaultPluginModuleDeps: PluginModuleDeps = { createModelCacheState, createManagers, createTools, + createRuntimeSkillSourceServer, createHooks, createPluginInterface, } @@ -111,6 +116,11 @@ export function createPluginModule(overrides: Partial = {}): P deps.injectServerAuthIntoClient(input.client) const pluginConfig = deps.loadPluginConfig(input.directory, input) + const runtimeSecuritySkills = selectRuntimeSecuritySkills(pluginConfig) + const runtimeSkillSource = + runtimeSecuritySkills.length > 0 + ? deps.createRuntimeSkillSourceServer({ skills: runtimeSecuritySkills }) + : undefined deps.initI18n(pluginConfig.i18n?.locale ? { locale: pluginConfig.i18n.locale } : undefined) deps.setAgentSortOrder(pluginConfig.agent_order) @@ -129,8 +139,12 @@ export function createPluginModule(overrides: Partial = {}): P "[team-mode] enabled=true but team-mode skill is disabled; skill docs hidden but tools still registered (D-29)", ) } - } catch (err) { - console.warn("[team-mode] init failed:", err) + } catch (error) { + if (error instanceof Error) { + console.warn("[team-mode] init failed:", error) + } else { + console.warn("[team-mode] init failed:", String(error)) + } } } const tmuxIntegrationEnabled = deps.isTmuxIntegrationEnabled(pluginConfig) @@ -154,6 +168,7 @@ export function createPluginModule(overrides: Partial = {}): P tmuxConfig, modelCacheState, backgroundNotificationHookEnabled: isHookEnabled("background-notification"), + runtimeSkillSourceUrl: runtimeSkillSource?.url, }) const toolsResult = await deps.createTools({ @@ -183,12 +198,23 @@ export function createPluginModule(overrides: Partial = {}): P tools: toolsResult.filteredTools, }) - const pluginHooks: HooksWithCompactionAutocontinue = { + const dispose = createPluginDispose({ + backgroundManager: managers.backgroundManager, + skillMcpManager: managers.skillMcpManager, + disposeHooks: hooks.disposeHooks, + }) + + const pluginHooks: HooksWithRuntimeLifecycle = { ...pluginInterface, "experimental.session.compacting": createSessionCompactingHandler(hooks), "experimental.compaction.autocontinue": createCompactionAutocontinueHandler(hooks), + + dispose: async (): Promise => { + runtimeSkillSource?.stop() + await dispose() + }, } return pluginHooks diff --git a/src/tools/skill/zauc-mocks-skill-tools/tools.test.ts b/src/tools/skill/zauc-mocks-skill-tools/tools.test.ts index ec28c3e66..5510ab8a0 100644 --- a/src/tools/skill/zauc-mocks-skill-tools/tools.test.ts +++ b/src/tools/skill/zauc-mocks-skill-tools/tools.test.ts @@ -834,6 +834,31 @@ describe("skill tool - nativeSkills integration", () => { }) }) +describe("skill tool - bundled security skills", () => { + it("loads security-research and security-review when the plugin skill context pre-seeds them", async () => { + //#given + const { builtinToLoadedSkill } = await import("../../../features/opencode-skill-loader/merger/builtin-skill-converter") + const { securityResearchSkill, securityReviewSkill } = await import("../../../features/builtin-skills/skills/index") + const tool = createSkillTool({ + directory: "/test", + skills: [ + builtinToLoadedSkill(securityResearchSkill), + builtinToLoadedSkill(securityReviewSkill), + ], + }) + + //#when + const researchResult = await tool.execute({ name: "security-research" }, mockContext) + const reviewResult = await tool.execute({ name: "security-review" }, mockContext) + + //#then + expect(researchResult).toContain("## Skill: security-research") + expect(researchResult).toContain("Security Research - Team Mode Vulnerability Audit") + expect(reviewResult).toContain("## Skill: security-review") + expect(reviewResult).toContain("Security Research - Team Mode Vulnerability Audit") + }) +}) + describe("skill tool - short name resolution", () => { it("resolves namespaced skill by short name when unambiguous", async () => { // given