@srobroek/harness-kit 1.0.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -0
- package/package.json +3 -1
- package/runtime/claude/render.mjs +29 -0
- package/runtime/omp/template-extension.ts +70 -0
- package/runtime/opencode/agents.ts +75 -0
- package/runtime/opencode/content.ts +118 -0
- package/runtime/opencode/frontmatter.ts +22 -0
- package/runtime/opencode/session.ts +50 -0
- package/src/config.ts +9 -1
- package/src/generate.ts +105 -6
- package/src/index.ts +1 -0
- package/src/runtime.ts +60 -0
- package/src/testing.ts +49 -0
package/README.md
CHANGED
|
@@ -42,6 +42,7 @@ bun must be on `PATH`, because the `harness-kit` bin has a bun shebang. `npm ci`
|
|
|
42
42
|
| `harnesses` | all three | Harnesses the repo targets. A plugin may list only these. Claude and OMP each get a marketplace file; OpenCode has none. |
|
|
43
43
|
| `commonDirs` | `skills`, `rules` | Directories under `plugins/<name>/common/` copied into each harness tree. Add `templates`, `scripts` or `formulas` as needed. |
|
|
44
44
|
| `kinds` | the eight kinds without `templates` and `styles` | Rows of the inventory tables and keys of `inventory.json`. Any of `skills agents commands rules templates styles hooks tools extensions mcp`. |
|
|
45
|
+
| `sharedDir` | `shared` | Repo-level directory of items that several plugins take; see "Shared items". |
|
|
45
46
|
| `pluginKey` | `agent-plugins` | Key in each plugin's `package.json` that holds its settings. |
|
|
46
47
|
| `ompScope` | `@agent-plugins` | npm scope of the generated OMP package name. |
|
|
47
48
|
| `generatedBy` | `harness-kit build` | Names the generator in the note at the top of generated Markdown. |
|
|
@@ -60,6 +61,40 @@ Each plugin's `package.json` carries `name` (equal to the directory), `version`,
|
|
|
60
61
|
- An OMP rule with no front matter gets `alwaysApply: true`. A rule with its own front matter, such as `description:`, is copied unchanged.
|
|
61
62
|
- `__pycache__` directories are ignored.
|
|
62
63
|
|
|
64
|
+
### Shared items
|
|
65
|
+
|
|
66
|
+
When two plugins ship the same agent, skill or rule, keep one copy in the repo's `shared/` directory (`sharedDir` in the config). Its layout follows `commonDirs`: `shared/agents/x.md`, `shared/skills/y/`, `shared/rules/z.md`. A plugin takes items by listing them in its `agent-plugins` key:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
"shared": ["agents/adversarial-challenger", "rules/z"]
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
`harness-kit build` copies each listed item into every harness tree of the plugin, as if it sat in the plugin's own `common/`: the same `x.<harness>.md` variants, the same OMP `alwaysApply` rule. Each plugin stays complete on its own. Copied Markdown carries a `<!-- Generated by … from shared/… -->` header, placed after the front matter so the front matter still parses; other files copy unchanged. `build --check` fails when the shared file changes and a copy does not, and dropping an item removes its copies.
|
|
73
|
+
|
|
74
|
+
An item names a file without its extension (`agents/x`) or a directory (`skills/y`). Only listed items are copied. These are errors: an item that does not exist, an item whose first segment is not in `commonDirs` (an `agents` item needs `agents` there), and a plugin that also has its own file at the same path in `common/`.
|
|
75
|
+
|
|
76
|
+
#### Two installed plugins with the same agent
|
|
77
|
+
|
|
78
|
+
- **OpenCode:** registering the same agent name twice normally lets the last plugin loaded win. The vendored `agents` module avoids that: `registerAgents(ctx.agent, loadAgentFiles(root))` skips an agent another plugin already registered and logs one debug line (`console.debug`, or the `debug` option). The first plugin loaded wins, so a version skew between the two copies is the same on every start.
|
|
79
|
+
- **Claude Code:** it prefixes each plugin's agents with the plugin name (`plugin-a:challenger`, `plugin-b:challenger`). Both stay available, and harness-kit cannot change that. A version skew shows up as two agents with different text.
|
|
80
|
+
|
|
81
|
+
### Vendored runtime modules
|
|
82
|
+
|
|
83
|
+
Several plugins carry the same runtime code. harness-kit ships it as small modules without dependencies and copies them into a plugin's harness trees. A plugin opts in with `runtime` in its `agent-plugins` key: `true` for every module of its harnesses, or a list.
|
|
84
|
+
|
|
85
|
+
| Module | Harness | Provides |
|
|
86
|
+
| --- | --- | --- |
|
|
87
|
+
| `frontmatter` | opencode | `isRecord`, `parseFrontmatter` |
|
|
88
|
+
| `content` | opencode | `loadSkills`, `loadRules`, `loadPrompt`, `resolveOptions`, `renderTemplate`, `setupContent`: registers `skills/`, `rules/` and `templates/` with the host. Needs `frontmatter`. |
|
|
89
|
+
| `agents` | opencode | `loadAgentFiles`, `registerAgents`: registers `agents/*.md`, skipping an agent another plugin already registered. Needs `frontmatter`. |
|
|
90
|
+
| `session` | opencode | `createRootResolver`, `rootOf`: resolve a session to its root session |
|
|
91
|
+
| `render` | claude | `render.mjs`, a SessionStart hook: `node "${CLAUDE_PLUGIN_ROOT}/_kit/render.mjs" <template>` prints `templates/<template>.md` with the options filled in |
|
|
92
|
+
| `template-extension` | omp | `templateExtension(name)`: an extension that appends the rendered `templates/<name>.md` to the system prompt, with options from `<name>.json` in the OMP agent directory |
|
|
93
|
+
|
|
94
|
+
`harness-kit build` writes the modules to `<harness>/_kit/` as generated files with a `// Generated by …` header. `build --check` catches edits and leftovers, and dropping `runtime` removes the directory. The installed plugin imports only its own copy: nothing loads harness-kit at runtime, and no harness imports another harness's module. A plugin without `runtime` produces the same output as before. Do not list `_kit` in `commonDirs`.
|
|
95
|
+
|
|
96
|
+
Test helpers are not vendored. `@srobroek/harness-kit/testing` exports `createFakeContext({ options?, existingSkills?, existingAgents? })`, a fake OpenCode host context that records the system parts, skills, agents and disposals a plugin registers.
|
|
97
|
+
|
|
63
98
|
## Commands
|
|
64
99
|
|
|
65
100
|
```sh
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@srobroek/harness-kit",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"description": "Shared build tooling for multi-harness agent plugin repos: generator, version stamping, Claude validation, presets and CI workflows.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -17,11 +17,13 @@
|
|
|
17
17
|
},
|
|
18
18
|
"exports": {
|
|
19
19
|
".": "./src/index.ts",
|
|
20
|
+
"./testing": "./src/testing.ts",
|
|
20
21
|
"./tsconfig.base.json": "./tsconfig.base.json",
|
|
21
22
|
"./release.config.js": "./release.config.js"
|
|
22
23
|
},
|
|
23
24
|
"files": [
|
|
24
25
|
"src",
|
|
26
|
+
"runtime",
|
|
25
27
|
"tsconfig.base.json",
|
|
26
28
|
"release.config.js"
|
|
27
29
|
],
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// SessionStart hook: print a template with its options filled in. The output joins the session context.
|
|
2
|
+
// Run it as `node "${CLAUDE_PLUGIN_ROOT}/_kit/render.mjs" <template>`, where <template> is a file name under
|
|
3
|
+
// `templates/` without the `.md` extension. Claude Code exports each userConfig option as
|
|
4
|
+
// CLAUDE_PLUGIN_OPTION_<NAME> (uppercase). A missing or empty value takes the default from options.json.
|
|
5
|
+
import { readFileSync } from "node:fs"
|
|
6
|
+
import { dirname, join } from "node:path"
|
|
7
|
+
import { fileURLToPath } from "node:url"
|
|
8
|
+
|
|
9
|
+
const PLACEHOLDER = /\$\{user_config\.([a-z][a-z0-9_]*)\}/g
|
|
10
|
+
|
|
11
|
+
export function render(template, defaults, env) {
|
|
12
|
+
return template.replace(PLACEHOLDER, (whole, name) => {
|
|
13
|
+
if (!(name in defaults)) return whole
|
|
14
|
+
const given = env[`CLAUDE_PLUGIN_OPTION_${name.toUpperCase()}`]
|
|
15
|
+
return given === undefined || given === "" ? defaults[name] : given
|
|
16
|
+
})
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
20
|
+
const name = process.argv[2]
|
|
21
|
+
if (!name) {
|
|
22
|
+
console.error("usage: render.mjs <template>")
|
|
23
|
+
process.exit(2)
|
|
24
|
+
}
|
|
25
|
+
const root = join(dirname(fileURLToPath(import.meta.url)), "..")
|
|
26
|
+
const defaults = JSON.parse(readFileSync(join(root, "options.json"), "utf8"))
|
|
27
|
+
const template = readFileSync(join(root, "templates", `${name}.md`), "utf8")
|
|
28
|
+
process.stdout.write(render(template, defaults, process.env))
|
|
29
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs"
|
|
2
|
+
import { homedir } from "node:os"
|
|
3
|
+
import { dirname, join } from "node:path"
|
|
4
|
+
import { fileURLToPath } from "node:url"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* An OMP extension that appends a rendered template to the system prompt. OMP has no per-extension options, and a
|
|
8
|
+
* marketplace install copies the tree into OMP's cache, so the options live in `<name>.json` in the OMP agent directory
|
|
9
|
+
* (`$PI_CODING_AGENT_DIR`, default `~/.omp/agent`): a JSON object of strings with the names in `options.json`. A missing
|
|
10
|
+
* file means the defaults. A file that cannot be parsed, or that holds an unknown name or a non-string, is reported once
|
|
11
|
+
* and the defaults apply.
|
|
12
|
+
*
|
|
13
|
+
* `templateExtension("secrets")` renders `templates/secrets.md` and appends it before each prompt (`before_agent_start`).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const PLACEHOLDER = /\$\{user_config\.([a-z][a-z0-9_]*)\}/g
|
|
17
|
+
|
|
18
|
+
/** The slice of the OMP extension API this file uses. */
|
|
19
|
+
interface Api {
|
|
20
|
+
on(event: "before_agent_start", handler: (event: { systemPrompt: string[] }) => { systemPrompt: string[] }): void
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function agentDir(env: Record<string, string | undefined> = process.env): string {
|
|
24
|
+
const custom = env.PI_CODING_AGENT_DIR?.trim()
|
|
25
|
+
return custom ? custom : join(homedir(), ".omp", "agent")
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The defaults with the user's file on top. Throws on an unknown name or a non-string value. */
|
|
29
|
+
export function resolveOptions(defaults: Record<string, string>, given: unknown, fileName = "options file"): Record<string, string> {
|
|
30
|
+
const values = { ...defaults }
|
|
31
|
+
if (given === undefined) return values
|
|
32
|
+
if (typeof given !== "object" || given === null || Array.isArray(given)) throw new Error(`${fileName} must be an object`)
|
|
33
|
+
for (const [name, value] of Object.entries(given)) {
|
|
34
|
+
if (!(name in defaults)) throw new Error(`unknown option "${name}"`)
|
|
35
|
+
if (typeof value !== "string") throw new Error(`option "${name}" must be a string`)
|
|
36
|
+
values[name] = value
|
|
37
|
+
}
|
|
38
|
+
return values
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function render(template: string, values: Record<string, string>): string {
|
|
42
|
+
return template.replace(PLACEHOLDER, (whole, name: string) => values[name] ?? whole)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface Deps {
|
|
46
|
+
/** Install tree holding `templates/` and `options.json`; defaults to the parent of the `_kit` directory. */
|
|
47
|
+
root?: string
|
|
48
|
+
/** Path of the user's options file; defaults to `<name>.json` in the agent directory. */
|
|
49
|
+
optionsPath?: string
|
|
50
|
+
warn?: (message: string) => void
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function templateExtension(name: string) {
|
|
54
|
+
return function extension(pi: Api, deps: Deps = {}): void {
|
|
55
|
+
const root = deps.root ?? join(dirname(fileURLToPath(import.meta.url)), "..")
|
|
56
|
+
const warn = deps.warn ?? ((message: string) => console.error(`${name}: ${message}`))
|
|
57
|
+
const defaults = JSON.parse(readFileSync(join(root, "options.json"), "utf8")) as Record<string, string>
|
|
58
|
+
const path = deps.optionsPath ?? join(agentDir(), `${name}.json`)
|
|
59
|
+
let values = defaults
|
|
60
|
+
if (existsSync(path)) {
|
|
61
|
+
try {
|
|
62
|
+
values = resolveOptions(defaults, JSON.parse(readFileSync(path, "utf8")), `${name}.json`)
|
|
63
|
+
} catch (error) {
|
|
64
|
+
warn(`${path}: ${error instanceof Error ? error.message : String(error)}; using the defaults`)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const text = render(readFileSync(join(root, "templates", `${name}.md`), "utf8"), values).trim()
|
|
68
|
+
pi.on("before_agent_start", (event) => ({ systemPrompt: [...event.systemPrompt, text] }))
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
import { parseFrontmatter } from "./frontmatter.ts";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Agent registration for an OpenCode plugin that ships `agents/<id>.md`.
|
|
7
|
+
*
|
|
8
|
+
* Two installed plugins can ship the same agent (a repo-level `shared/` item copied into both). OpenCode would
|
|
9
|
+
* register the id twice and the last plugin loaded would win, so a version skew between the copies would depend on
|
|
10
|
+
* load order in the other direction. `registerAgents` skips an id that is already registered and logs one debug
|
|
11
|
+
* line, so the first plugin loaded wins every time.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export interface AgentFile {
|
|
15
|
+
/** The file name without `.md`. */
|
|
16
|
+
id: string;
|
|
17
|
+
path: string;
|
|
18
|
+
/** A `key: value` line of the front matter. */
|
|
19
|
+
field(key: string): string | undefined;
|
|
20
|
+
/** The prompt: the text after the front matter, trimmed. */
|
|
21
|
+
system: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** The agent files under `root/agents/*.md`, in name order. */
|
|
25
|
+
export function loadAgentFiles(root: string): AgentFile[] {
|
|
26
|
+
const dir = join(root, "agents");
|
|
27
|
+
if (!existsSync(dir)) return [];
|
|
28
|
+
return readdirSync(dir)
|
|
29
|
+
.filter((file) => file.endsWith(".md"))
|
|
30
|
+
.sort()
|
|
31
|
+
.map((file) => {
|
|
32
|
+
const path = join(dir, file);
|
|
33
|
+
const frontmatter = parseFrontmatter(readFileSync(path, "utf8"));
|
|
34
|
+
const text = frontmatter ? frontmatter.body : readFileSync(path, "utf8");
|
|
35
|
+
return { id: basename(file, ".md"), path, field: (key: string) => frontmatter?.field(key), system: text.trim() };
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The slice of `ctx.agent` this module uses. */
|
|
40
|
+
interface AgentHost {
|
|
41
|
+
transform(change: (editor: { get(id: string): unknown; update(id: string, change: (draft: any) => void): void }) => void): Promise<{ dispose: () => Promise<void> }>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface RegisterOptions {
|
|
45
|
+
/** Fill a new agent's draft from its file. Defaults to `description`, `mode` and `system`. */
|
|
46
|
+
apply?: (draft: any, file: AgentFile) => void;
|
|
47
|
+
/** Receives the line logged for a skipped agent. Defaults to `console.debug`. */
|
|
48
|
+
debug?: (line: string) => void;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Registers the agents the host does not know yet. Returns the registration to dispose, and the ids it skipped. */
|
|
52
|
+
export async function registerAgents(agent: AgentHost, files: AgentFile[], options: RegisterOptions = {}) {
|
|
53
|
+
const apply =
|
|
54
|
+
options.apply ??
|
|
55
|
+
((draft: any, file: AgentFile) => {
|
|
56
|
+
const description = file.field("description");
|
|
57
|
+
const mode = file.field("mode");
|
|
58
|
+
if (description !== undefined) draft.description = description;
|
|
59
|
+
if (mode !== undefined) draft.mode = mode;
|
|
60
|
+
draft.system = file.system;
|
|
61
|
+
});
|
|
62
|
+
const debug = options.debug ?? ((line: string) => console.debug(line));
|
|
63
|
+
const skipped: string[] = [];
|
|
64
|
+
const registration = await agent.transform((editor) => {
|
|
65
|
+
for (const file of files) {
|
|
66
|
+
if (editor.get(file.id) !== undefined) {
|
|
67
|
+
skipped.push(file.id);
|
|
68
|
+
debug(`agent "${file.id}" is already registered by another plugin; skipping the copy in ${file.path}`);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
editor.update(file.id, (draft) => apply(draft, file));
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
return { dispose: registration.dispose, skipped };
|
|
75
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { parseFrontmatter } from "./frontmatter.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Content runtime of an OpenCode plugin. The plugin ships markdown and nothing else:
|
|
8
|
+
* - `rules/*.md` and `templates/*.md` go into the `system` prompt of every model request (`ctx.session.hook("context")`).
|
|
9
|
+
* A template may hold `${user_config.<name>}` placeholders. Each takes the plugin entry's option of that name, else the
|
|
10
|
+
* default in `options.json` (generated from the `options` of the plugin's package.json).
|
|
11
|
+
* - `skills/<name>/SKILL.md` register through `ctx.skill.transform`, unless the user already has a skill of that name.
|
|
12
|
+
*
|
|
13
|
+
* The system part is a standalone part. agent-efficiency's lean trimming (`leanSystem`) removes the `Instructions from:`
|
|
14
|
+
* sections of AGENTS.md files, the model identity and the worktree hint, and nothing else, so these rules reach every
|
|
15
|
+
* subagent, including the read-only ones that the trimming otherwise slims down.
|
|
16
|
+
*
|
|
17
|
+
* This file holds no import of `@opencode/plugin`, so tests load it without the host package; the plugin's `main.ts` wraps it.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
export interface SkillDefinition {
|
|
21
|
+
id: string;
|
|
22
|
+
name: string;
|
|
23
|
+
description: string;
|
|
24
|
+
path: string;
|
|
25
|
+
content: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** The slice of the host context this runtime uses. */
|
|
29
|
+
type Context = any;
|
|
30
|
+
|
|
31
|
+
const PLACEHOLDER = /\$\{user_config\.([a-z][a-z0-9_]*)\}/g;
|
|
32
|
+
|
|
33
|
+
/** The defaults of `options.json` with the plugin entry's options on top. Throws on an unknown name or a non-string value. */
|
|
34
|
+
export function resolveOptions(root: string, given: unknown): Record<string, string> {
|
|
35
|
+
const file = join(root, "options.json");
|
|
36
|
+
const defaults: Record<string, string> = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
|
|
37
|
+
const values = { ...defaults };
|
|
38
|
+
if (given === undefined || given === null) return values;
|
|
39
|
+
if (typeof given !== "object" || Array.isArray(given)) throw new Error("plugin options must be an object");
|
|
40
|
+
for (const [name, value] of Object.entries(given)) {
|
|
41
|
+
if (!(name in defaults)) throw new Error(`unknown option "${name}" (known: ${Object.keys(defaults).join(", ") || "none"})`);
|
|
42
|
+
if (typeof value !== "string") throw new Error(`option "${name}" must be a string`);
|
|
43
|
+
values[name] = value;
|
|
44
|
+
}
|
|
45
|
+
return values;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Fill the `${user_config.<name>}` placeholders of a template. A placeholder without a value stays as written. */
|
|
49
|
+
export function renderTemplate(text: string, values: Record<string, string>): string {
|
|
50
|
+
return text.replace(PLACEHOLDER, (whole, name: string) => values[name] ?? whole);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function markdownIn(dir: string): string[] {
|
|
54
|
+
if (!existsSync(dir)) return [];
|
|
55
|
+
return readdirSync(dir)
|
|
56
|
+
.filter((file) => file.endsWith(".md"))
|
|
57
|
+
.sort()
|
|
58
|
+
.map((file) => join(dir, file));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The text of every `rules/*.md` file under `root`, trimmed, in name order, joined by blank lines. Empty when there is none. */
|
|
62
|
+
export function loadRules(root: string): string {
|
|
63
|
+
return markdownIn(join(root, "rules"))
|
|
64
|
+
.map((file) => readFileSync(file, "utf8").trim())
|
|
65
|
+
.join("\n\n");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The text pushed into the system prompt: every rule, then every rendered template, each trimmed, joined by blank lines. */
|
|
69
|
+
export function loadPrompt(root: string, options: Record<string, string>): string {
|
|
70
|
+
const rules = markdownIn(join(root, "rules")).map((file) => readFileSync(file, "utf8").trim());
|
|
71
|
+
const templates = markdownIn(join(root, "templates")).map((file) => renderTemplate(readFileSync(file, "utf8"), options).trim());
|
|
72
|
+
return [...rules, ...templates].join("\n\n");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** The skills under `root/skills/<name>/SKILL.md`. A skill whose front matter lacks a name or description is skipped. */
|
|
76
|
+
export function loadSkills(root: string): SkillDefinition[] {
|
|
77
|
+
const dir = join(root, "skills");
|
|
78
|
+
if (!existsSync(dir)) return [];
|
|
79
|
+
const found: SkillDefinition[] = [];
|
|
80
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).filter((item) => item.isDirectory()).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
81
|
+
const path = join(dir, entry.name, "SKILL.md");
|
|
82
|
+
if (!existsSync(path)) continue;
|
|
83
|
+
const frontmatter = parseFrontmatter(readFileSync(path, "utf8"));
|
|
84
|
+
const name = frontmatter?.field("name");
|
|
85
|
+
const description = frontmatter?.field("description");
|
|
86
|
+
if (!frontmatter || !name || !description) continue;
|
|
87
|
+
found.push({ id: name, name, description, path, content: frontmatter.body.trim() });
|
|
88
|
+
}
|
|
89
|
+
return found;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export interface SetupOptions {
|
|
93
|
+
/** Install tree holding `rules/`, `templates/`, `skills/` and `options.json`; defaults to the parent of the `_kit` directory. */
|
|
94
|
+
root?: string;
|
|
95
|
+
/** Raw plugin options; defaults to the plugin entry's `options`. */
|
|
96
|
+
options?: unknown;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export async function setupContent(ctx: Context, setup: SetupOptions = {}) {
|
|
100
|
+
const root = setup.root ?? join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
101
|
+
const options = resolveOptions(root, setup.options ?? ctx.options);
|
|
102
|
+
const registrations: Array<{ dispose: () => Promise<void> }> = [];
|
|
103
|
+
const skills = loadSkills(root);
|
|
104
|
+
if (skills.length > 0 && ctx.skill?.transform) {
|
|
105
|
+
registrations.push(
|
|
106
|
+
await ctx.skill.transform((editor: any) => {
|
|
107
|
+
for (const skill of skills) if (editor.get?.(skill.id) === undefined) editor.add(skill);
|
|
108
|
+
}),
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
const prompt = loadPrompt(root, options);
|
|
112
|
+
if (prompt !== "" && ctx.session?.hook) {
|
|
113
|
+
registrations.push(await ctx.session.hook("context", (event: { system: Array<{ type: string; text: string }> }) => void event.system.push({ type: "text", text: prompt })));
|
|
114
|
+
}
|
|
115
|
+
return async () => {
|
|
116
|
+
for (const registration of registrations.reverse()) await registration.dispose();
|
|
117
|
+
};
|
|
118
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Small helpers shared by the vendored OpenCode runtime modules. No dependencies. */
|
|
2
|
+
|
|
3
|
+
export const isRecord = (value: unknown): value is Record<string, unknown> =>
|
|
4
|
+
typeof value === "object" && value !== null && !Array.isArray(value);
|
|
5
|
+
|
|
6
|
+
export interface Frontmatter {
|
|
7
|
+
/** The value of a `key: value` line in the front matter, trimmed; undefined when the key is absent or empty. */
|
|
8
|
+
field(key: string): string | undefined;
|
|
9
|
+
/** The text after the closing `---`. */
|
|
10
|
+
body: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Splits `---` front matter from the body. Undefined when the text does not start with a front-matter block. */
|
|
14
|
+
export function parseFrontmatter(text: string): Frontmatter | undefined {
|
|
15
|
+
const match = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(text);
|
|
16
|
+
if (!match) return undefined;
|
|
17
|
+
const head = match[1] ?? "";
|
|
18
|
+
return {
|
|
19
|
+
field: (key) => head.match(new RegExp(`^${key}:\\s*(.+?)\\s*$`, "m"))?.[1],
|
|
20
|
+
body: match[2] ?? "",
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
const MAX_DEPTH = 10;
|
|
2
|
+
|
|
3
|
+
type SessionGet = (input: { sessionID: string }) => Promise<{ parentID?: string | null } | undefined>;
|
|
4
|
+
|
|
5
|
+
/** Resolves any session to its root by walking `parentID`, and caches every session on the walked chain. */
|
|
6
|
+
export function createRootResolver(get: SessionGet) {
|
|
7
|
+
const cache = new Map<string, string>();
|
|
8
|
+
function remember(chain: string[], root: string): string {
|
|
9
|
+
for (const id of chain) cache.set(id, root);
|
|
10
|
+
return root;
|
|
11
|
+
}
|
|
12
|
+
return {
|
|
13
|
+
/** Record a session the host reported as a root. */
|
|
14
|
+
markRoot(sessionID: string) {
|
|
15
|
+
cache.set(sessionID, sessionID);
|
|
16
|
+
},
|
|
17
|
+
/** The root id, or undefined when the chain cannot be read in `MAX_DEPTH` steps (callers fail closed). */
|
|
18
|
+
async resolve(sessionID: string): Promise<string | undefined> {
|
|
19
|
+
const chain: string[] = [];
|
|
20
|
+
let id = sessionID;
|
|
21
|
+
for (let depth = 0; depth <= MAX_DEPTH; depth += 1) {
|
|
22
|
+
const known = cache.get(id);
|
|
23
|
+
if (known !== undefined) return remember(chain, known);
|
|
24
|
+
chain.push(id);
|
|
25
|
+
let parent: string | null | undefined;
|
|
26
|
+
try {
|
|
27
|
+
const session = await get({ sessionID: id });
|
|
28
|
+
if (session === undefined) return undefined;
|
|
29
|
+
parent = session.parentID;
|
|
30
|
+
} catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
if (!parent) return remember(chain, id);
|
|
34
|
+
id = parent;
|
|
35
|
+
}
|
|
36
|
+
return undefined;
|
|
37
|
+
},
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The root of a session in the TUI's synced data, or the first id whose parent is not loaded. */
|
|
42
|
+
export function rootOf(get: (id: string) => { parentID?: string | null } | undefined, sessionID: string): string {
|
|
43
|
+
let id = sessionID;
|
|
44
|
+
for (let depth = 0; depth < MAX_DEPTH; depth += 1) {
|
|
45
|
+
const parent = get(id)?.parentID;
|
|
46
|
+
if (!parent) return id;
|
|
47
|
+
id = parent;
|
|
48
|
+
}
|
|
49
|
+
return id;
|
|
50
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -20,6 +20,8 @@ export type Config = {
|
|
|
20
20
|
/** Directories under plugins/<name>/common/ that are copied into each harness tree. */
|
|
21
21
|
commonDirs: string[]
|
|
22
22
|
kinds: Kind[]
|
|
23
|
+
/** Repo-level directory whose items plugins list in `shared`; its layout follows `commonDirs` (shared/agents/x.md). */
|
|
24
|
+
sharedDir: string
|
|
23
25
|
/** Key in plugins/<name>/package.json that holds the plugin's own settings. */
|
|
24
26
|
pluginKey: string
|
|
25
27
|
/** npm scope of the generated OMP package name. */
|
|
@@ -37,7 +39,7 @@ export type Config = {
|
|
|
37
39
|
omp: { packageType?: "module" | "commonjs" }
|
|
38
40
|
}
|
|
39
41
|
|
|
40
|
-
const TOP_KEYS = ["marketplace", "harnesses", "commonDirs", "kinds", "pluginKey", "ompScope", "generatedBy", "claude", "omp"]
|
|
42
|
+
const TOP_KEYS = ["marketplace", "harnesses", "commonDirs", "kinds", "sharedDir", "pluginKey", "ompScope", "generatedBy", "claude", "omp"]
|
|
41
43
|
const DIR_NAME = /^[a-z0-9][a-z0-9._-]*$/
|
|
42
44
|
const PACKAGE_SCOPE = /^@[a-z0-9][a-z0-9._-]*$/
|
|
43
45
|
|
|
@@ -80,11 +82,16 @@ export function resolveConfig(raw: unknown, where = CONFIG_FILE): Config {
|
|
|
80
82
|
if (typeof dir !== "string" || !DIR_NAME.test(dir)) fail(where, `"commonDirs" entry ${JSON.stringify(dir)} must be a plain directory name`)
|
|
81
83
|
}
|
|
82
84
|
if (new Set(raw.commonDirs).size !== raw.commonDirs.length) fail(where, '"commonDirs" lists a directory twice')
|
|
85
|
+
if (raw.commonDirs.includes("_kit")) fail(where, '"commonDirs" cannot list "_kit", which holds the vendored runtime modules')
|
|
83
86
|
commonDirs = raw.commonDirs as string[]
|
|
84
87
|
}
|
|
85
88
|
|
|
86
89
|
const kinds = raw.kinds === undefined ? DEFAULT_KINDS : pickList(where, "kinds", "kind", raw.kinds, KNOWN_KINDS)
|
|
87
90
|
|
|
91
|
+
const sharedDir = raw.sharedDir === undefined ? "shared" : nonEmptyString(where, "sharedDir", raw.sharedDir)
|
|
92
|
+
if (!DIR_NAME.test(sharedDir)) fail(where, `"sharedDir" must be a plain directory name, got "${sharedDir}"`)
|
|
93
|
+
if (["plugins", "_kit", "node_modules"].includes(sharedDir) || commonDirs.includes(sharedDir)) fail(where, `"sharedDir" cannot be "${sharedDir}"`)
|
|
94
|
+
|
|
88
95
|
const pluginKey = raw.pluginKey === undefined ? "agent-plugins" : nonEmptyString(where, "pluginKey", raw.pluginKey)
|
|
89
96
|
const ompScope = raw.ompScope === undefined ? "@agent-plugins" : nonEmptyString(where, "ompScope", raw.ompScope)
|
|
90
97
|
if (!PACKAGE_SCOPE.test(ompScope)) fail(where, `"ompScope" must look like "@scope", got "${ompScope}"`)
|
|
@@ -120,6 +127,7 @@ export function resolveConfig(raw: unknown, where = CONFIG_FILE): Config {
|
|
|
120
127
|
harnesses,
|
|
121
128
|
commonDirs,
|
|
122
129
|
kinds,
|
|
130
|
+
sharedDir,
|
|
123
131
|
pluginKey,
|
|
124
132
|
ompScope,
|
|
125
133
|
generatedBy,
|
package/src/generate.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
|
|
6
6
|
import path from "node:path"
|
|
7
7
|
import { type Config, type Harness, KNOWN_HARNESSES, KNOWN_KINDS, type Kind } from "./config"
|
|
8
|
+
import { RUNTIME_DIR, type RuntimeModuleName, resolveRuntime, vendoredSource } from "./runtime"
|
|
8
9
|
import { fail, isRecord, json, nonEmptyString } from "./util"
|
|
9
10
|
|
|
10
11
|
export type { Harness, Kind }
|
|
@@ -31,6 +32,10 @@ export type Plugin = {
|
|
|
31
32
|
license?: string
|
|
32
33
|
/** The Claude `userConfig` schema, copied into plugin.json as is. Exclusive with `options`. */
|
|
33
34
|
userConfig?: Record<string, unknown>
|
|
35
|
+
/** Items of the repo's shared directory this plugin takes, like `agents/x` or `skills/y`. Copied into every harness tree. */
|
|
36
|
+
shared?: string[]
|
|
37
|
+
/** Runtime modules vendored into the harness trees as `_kit/`, with their dependencies. Absent when the plugin opts out. */
|
|
38
|
+
runtime?: RuntimeModuleName[]
|
|
34
39
|
}
|
|
35
40
|
|
|
36
41
|
export type Output = { file: string; contents: string | Buffer }
|
|
@@ -38,6 +43,7 @@ export type Drift = { changed: string[]; extra: string[] }
|
|
|
38
43
|
|
|
39
44
|
const NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/
|
|
40
45
|
const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/
|
|
46
|
+
const SHARED_ITEM = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+$/
|
|
41
47
|
const OPTION_NAME = /^[a-z][a-z0-9_]*$/
|
|
42
48
|
const OPENCODE_SDK_RANGE = ">=2.1.4 <3"
|
|
43
49
|
const MODULE_EXTENSION = /\.(?:[cm]?[jt]s)$/
|
|
@@ -124,13 +130,16 @@ export function readPlugin(root: string, name: string, config: Config): Plugin {
|
|
|
124
130
|
if (own.userConfig !== undefined && !isRecord(own.userConfig)) fail(where, `"${key}.userConfig" must be an object`)
|
|
125
131
|
const userConfig = own.userConfig as Record<string, unknown> | undefined
|
|
126
132
|
if (options && userConfig) fail(where, `set either "${key}.options" or "${key}.userConfig", not both: options generate the userConfig`)
|
|
133
|
+
const selectedHarnesses = KNOWN_HARNESSES.filter((h) => harnesses.includes(h))
|
|
134
|
+
const runtime = readRuntime(where, key, own.runtime, selectedHarnesses)
|
|
135
|
+
const shared = readShared(where, key, own.shared, config)
|
|
127
136
|
// Keep canonical harness order so output does not depend on how the author ordered the list.
|
|
128
137
|
return {
|
|
129
138
|
name,
|
|
130
139
|
version,
|
|
131
140
|
description,
|
|
132
141
|
category,
|
|
133
|
-
harnesses:
|
|
142
|
+
harnesses: selectedHarnesses,
|
|
134
143
|
scope,
|
|
135
144
|
discrepancies,
|
|
136
145
|
options,
|
|
@@ -138,6 +147,34 @@ export function readPlugin(root: string, name: string, config: Config): Plugin {
|
|
|
138
147
|
author,
|
|
139
148
|
license,
|
|
140
149
|
userConfig,
|
|
150
|
+
shared,
|
|
151
|
+
runtime,
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function readShared(where: string, key: string, raw: unknown, config: Config): string[] | undefined {
|
|
156
|
+
if (raw === undefined) return undefined
|
|
157
|
+
if (!Array.isArray(raw) || raw.length === 0) fail(where, `"${key}.shared" must be a non-empty list of items like "agents/name"`)
|
|
158
|
+
for (const item of raw) {
|
|
159
|
+
if (typeof item !== "string" || !SHARED_ITEM.test(item) || item.split("/").includes("..")) {
|
|
160
|
+
fail(where, `"${key}.shared" item ${JSON.stringify(item)} must be a relative path like "agents/name"`)
|
|
161
|
+
}
|
|
162
|
+
const dir = item.split("/")[0]!
|
|
163
|
+
if (!config.commonDirs.includes(dir)) fail(where, `shared item "${item}" is in "${dir}", which is not in commonDirs (${config.commonDirs.join(", ")})`)
|
|
164
|
+
}
|
|
165
|
+
if (new Set(raw).size !== raw.length) fail(where, `"${key}.shared" lists an item twice`)
|
|
166
|
+
return raw as string[]
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function readRuntime(where: string, key: string, raw: unknown, harnesses: Harness[]): RuntimeModuleName[] | undefined {
|
|
170
|
+
if (raw === undefined || raw === false) return undefined
|
|
171
|
+
const valid = raw === true || (Array.isArray(raw) && raw.length > 0 && raw.every((item) => typeof item === "string"))
|
|
172
|
+
if (!valid) fail(where, `"${key}.runtime" must be true or a non-empty list of module names`)
|
|
173
|
+
try {
|
|
174
|
+
const modules = resolveRuntime(raw as boolean | string[], harnesses)
|
|
175
|
+
return modules.length > 0 ? modules : undefined
|
|
176
|
+
} catch (error) {
|
|
177
|
+
return fail(where, `"${key}.runtime": ${error instanceof Error ? error.message : String(error)}`)
|
|
141
178
|
}
|
|
142
179
|
}
|
|
143
180
|
|
|
@@ -185,7 +222,10 @@ function checkOpencodeEntries(root: string, plugin: Plugin): void {
|
|
|
185
222
|
|
|
186
223
|
export function readPlugins(root: string, config: Config): Plugin[] {
|
|
187
224
|
const plugins = listDirs(path.join(root, "plugins")).map((name) => readPlugin(root, name, config))
|
|
188
|
-
for (const plugin of plugins)
|
|
225
|
+
for (const plugin of plugins) {
|
|
226
|
+
checkOpencodeEntries(root, plugin)
|
|
227
|
+
resolveShared(root, plugin, config)
|
|
228
|
+
}
|
|
189
229
|
return plugins
|
|
190
230
|
}
|
|
191
231
|
|
|
@@ -218,16 +258,67 @@ function commonFilesFor(files: string[], harness: Harness): Array<[string, strin
|
|
|
218
258
|
return picked
|
|
219
259
|
}
|
|
220
260
|
|
|
261
|
+
/** The plain (variant-free) name of a file: `x.claude.md` and `x.md` both give `x.md`. */
|
|
262
|
+
function plainName(file: string): string {
|
|
263
|
+
const match = VARIANT.exec(path.basename(file))
|
|
264
|
+
return match ? path.join(path.dirname(file), `${match[1]}${match[3]}`) : file
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Whether a file of the shared directory belongs to the item `rest` (the part after the kind directory). */
|
|
268
|
+
function belongsToItem(file: string, rest: string): boolean {
|
|
269
|
+
if (file === rest || file.startsWith(`${rest}/`)) return true
|
|
270
|
+
if (stripExtension(file) === rest) return true
|
|
271
|
+
return stripExtension(plainName(file)) === rest
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Shared files a plugin takes, by kind directory: paths relative to <sharedDir>/<dir>. Throws on a missing item or a clash. */
|
|
275
|
+
function resolveShared(root: string, plugin: Plugin, config: Config): Map<string, string[]> {
|
|
276
|
+
const taken = new Map<string, string[]>()
|
|
277
|
+
const common = path.join(pluginDir(root, plugin), "common")
|
|
278
|
+
for (const item of plugin.shared ?? []) {
|
|
279
|
+
const [dir, ...parts] = item.split("/") as [string, ...string[]]
|
|
280
|
+
const rest = parts.join("/")
|
|
281
|
+
const base = path.join(root, config.sharedDir, dir)
|
|
282
|
+
const files = listFiles(base).filter((file) => belongsToItem(file, rest))
|
|
283
|
+
if (files.length === 0) fail(`plugins/${plugin.name}/package.json`, `shared item "${item}" not found in ${config.sharedDir}/${dir}/`)
|
|
284
|
+
const own = new Set(listFiles(path.join(common, dir)).map(plainName))
|
|
285
|
+
for (const file of files) {
|
|
286
|
+
if (own.has(plainName(file))) {
|
|
287
|
+
fail(`plugins/${plugin.name}`, `shared item "${item}" clashes with its own common/${dir}/${plainName(file)}; remove one of them`)
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
taken.set(dir, [...(taken.get(dir) ?? []), ...files])
|
|
291
|
+
}
|
|
292
|
+
return taken
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Header for a copy of a shared Markdown file, placed after any front matter so the front matter still parses. */
|
|
296
|
+
function withSharedHeader(text: string, note: string): string {
|
|
297
|
+
const front = /^---\r?\n[\s\S]*?\r?\n---\r?\n?/.exec(text)
|
|
298
|
+
if (!front) return `${note}\n\n${text}`
|
|
299
|
+
const head = front[0].endsWith("\n") ? front[0] : `${front[0]}\n`
|
|
300
|
+
return `${head}${note}\n${text.slice(front[0].length)}`
|
|
301
|
+
}
|
|
302
|
+
|
|
221
303
|
function ownedCopies(root: string, plugin: Plugin, config: Config): Output[] {
|
|
222
304
|
const common = path.join(pluginDir(root, plugin), "common")
|
|
305
|
+
const shared = resolveShared(root, plugin, config)
|
|
223
306
|
const outputs: Output[] = []
|
|
224
307
|
for (const harness of plugin.harnesses) {
|
|
225
308
|
for (const dir of config.commonDirs) {
|
|
226
|
-
|
|
227
|
-
|
|
309
|
+
const own = listFiles(path.join(common, dir))
|
|
310
|
+
const taken = shared.get(dir) ?? []
|
|
311
|
+
for (const [source, dest] of commonFilesFor([...own, ...taken].sort(), harness)) {
|
|
312
|
+
const isShared = taken.includes(source)
|
|
313
|
+
const origin = isShared ? path.join(root, config.sharedDir, dir, source) : path.join(common, dir, source)
|
|
314
|
+
let contents: string | Buffer = readFileSync(origin)
|
|
228
315
|
if (harness === "omp" && dir === "rules" && !contents.subarray(0, 3).equals(Buffer.from("---"))) {
|
|
229
316
|
contents = OMP_ALWAYS_APPLY + contents.toString("utf8")
|
|
230
317
|
}
|
|
318
|
+
if (isShared && source.endsWith(".md")) {
|
|
319
|
+
const note = `<!-- Generated by ${config.generatedBy} from ${config.sharedDir}/${dir}/${source}. Do not edit. -->`
|
|
320
|
+
contents = withSharedHeader(contents.toString("utf8"), note)
|
|
321
|
+
}
|
|
231
322
|
outputs.push({ file: path.join(harnessDir(root, plugin, harness), dir, dest), contents })
|
|
232
323
|
}
|
|
233
324
|
}
|
|
@@ -235,6 +326,14 @@ function ownedCopies(root: string, plugin: Plugin, config: Config): Output[] {
|
|
|
235
326
|
return outputs
|
|
236
327
|
}
|
|
237
328
|
|
|
329
|
+
/** The opted-in runtime modules, copied into each harness tree's `_kit/` directory. */
|
|
330
|
+
function runtimeCopies(root: string, plugin: Plugin, config: Config): Output[] {
|
|
331
|
+
return (plugin.runtime ?? []).map((name) => {
|
|
332
|
+
const { harness, file, contents } = vendoredSource(name, config.generatedBy)
|
|
333
|
+
return { file: path.join(harnessDir(root, plugin, harness), RUNTIME_DIR, file), contents }
|
|
334
|
+
})
|
|
335
|
+
}
|
|
336
|
+
|
|
238
337
|
function ompExtensions(root: string, plugin: Plugin): string[] {
|
|
239
338
|
const dir = path.join(harnessDir(root, plugin, "omp"), "extensions")
|
|
240
339
|
if (!existsSync(dir)) return []
|
|
@@ -455,7 +554,7 @@ export function render(root: string, plugins: Plugin[], config: Config): Output[
|
|
|
455
554
|
}))
|
|
456
555
|
const entries: PluginInventory[] = []
|
|
457
556
|
for (const plugin of plugins) {
|
|
458
|
-
const copies = ownedCopies(root, plugin, config)
|
|
557
|
+
const copies = [...ownedCopies(root, plugin, config), ...runtimeCopies(root, plugin, config)]
|
|
459
558
|
const entry = buildInventory(root, plugin, copies, config)
|
|
460
559
|
entries.push(entry)
|
|
461
560
|
outputs.push(...manifests(root, plugin, config), ...optionDefaults(root, plugin), ...copies)
|
|
@@ -475,7 +574,7 @@ export function render(root: string, plugins: Plugin[], config: Config): Output[
|
|
|
475
574
|
function ownedFiles(root: string, plugins: Plugin[], config: Config): string[] {
|
|
476
575
|
return plugins.flatMap((plugin) =>
|
|
477
576
|
plugin.harnesses.flatMap((harness) =>
|
|
478
|
-
config.commonDirs.flatMap((dir) => {
|
|
577
|
+
[...config.commonDirs, RUNTIME_DIR].flatMap((dir) => {
|
|
479
578
|
const base = path.join(harnessDir(root, plugin, harness), dir)
|
|
480
579
|
return listFiles(base).map((file) => path.join(base, file))
|
|
481
580
|
}),
|
package/src/index.ts
CHANGED
|
@@ -18,3 +18,4 @@ export {
|
|
|
18
18
|
export { type ValidateOptions, validateClaude } from "./validate-claude"
|
|
19
19
|
export { compareVersions, type Exec, PACKAGE_NAME, pinnedVersion, update, type UpdateResult } from "./update"
|
|
20
20
|
export { workflowRefWarnings } from "./workflow-refs"
|
|
21
|
+
export { RUNTIME_MODULES, RUNTIME_MODULE_NAMES, type RuntimeModuleName, resolveRuntime } from "./runtime"
|
package/src/runtime.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
// Runtime modules that a plugin can vendor into its harness trees. `harness-kit build` copies the opted-in modules
|
|
2
|
+
// to <harness>/_kit/ as generated files, so an installed plugin imports only its own copy and nothing loads harness-kit.
|
|
3
|
+
|
|
4
|
+
import { readFileSync } from "node:fs"
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import type { Harness } from "./config"
|
|
7
|
+
|
|
8
|
+
export type RuntimeModule = {
|
|
9
|
+
harness: Harness
|
|
10
|
+
/** File name under runtime/<harness>/ and under the tree's _kit/ directory. */
|
|
11
|
+
file: string
|
|
12
|
+
/** Modules this one imports; they are vendored with it. */
|
|
13
|
+
requires: string[]
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export const RUNTIME_DIR = "_kit"
|
|
17
|
+
|
|
18
|
+
export const RUNTIME_MODULES = {
|
|
19
|
+
frontmatter: { harness: "opencode", file: "frontmatter.ts", requires: [] },
|
|
20
|
+
content: { harness: "opencode", file: "content.ts", requires: ["frontmatter"] },
|
|
21
|
+
agents: { harness: "opencode", file: "agents.ts", requires: ["frontmatter"] },
|
|
22
|
+
session: { harness: "opencode", file: "session.ts", requires: [] },
|
|
23
|
+
render: { harness: "claude", file: "render.mjs", requires: [] },
|
|
24
|
+
"template-extension": { harness: "omp", file: "template-extension.ts", requires: [] },
|
|
25
|
+
} as const satisfies Record<string, RuntimeModule>
|
|
26
|
+
|
|
27
|
+
export type RuntimeModuleName = keyof typeof RUNTIME_MODULES
|
|
28
|
+
export const RUNTIME_MODULE_NAMES = Object.keys(RUNTIME_MODULES) as RuntimeModuleName[]
|
|
29
|
+
|
|
30
|
+
const SOURCE_ROOT = path.join(import.meta.dir, "..", "runtime")
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* The modules a plugin vendors, in canonical order, with their dependencies. `true` means every module of the
|
|
34
|
+
* plugin's harnesses. Throws a message (without a location) on an unknown module or one for a harness the plugin lacks.
|
|
35
|
+
*/
|
|
36
|
+
export function resolveRuntime(request: boolean | string[], harnesses: readonly Harness[]): RuntimeModuleName[] {
|
|
37
|
+
const wanted = new Set<RuntimeModuleName>()
|
|
38
|
+
if (request === true) {
|
|
39
|
+
for (const name of RUNTIME_MODULE_NAMES) if (harnesses.includes(RUNTIME_MODULES[name].harness)) wanted.add(name)
|
|
40
|
+
} else if (Array.isArray(request)) {
|
|
41
|
+
for (const name of request) {
|
|
42
|
+
if (!(name in RUNTIME_MODULES)) throw new Error(`unknown runtime module "${String(name)}" (use ${RUNTIME_MODULE_NAMES.join(", ")})`)
|
|
43
|
+
const module = RUNTIME_MODULES[name as RuntimeModuleName]
|
|
44
|
+
if (!harnesses.includes(module.harness)) throw new Error(`runtime module "${name}" is for ${module.harness}, which the plugin does not list`)
|
|
45
|
+
wanted.add(name as RuntimeModuleName)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
for (const name of wanted) for (const dep of RUNTIME_MODULES[name].requires) wanted.add(dep as RuntimeModuleName)
|
|
49
|
+
return RUNTIME_MODULE_NAMES.filter((name) => wanted.has(name))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const COMMENT = /\.(?:[cm]?[jt]s)$/
|
|
53
|
+
|
|
54
|
+
/** The vendored text of a module: a generated-by header, then the source. */
|
|
55
|
+
export function vendoredSource(name: RuntimeModuleName, generatedBy: string): { harness: Harness; file: string; contents: string } {
|
|
56
|
+
const { harness, file } = RUNTIME_MODULES[name]
|
|
57
|
+
const source = readFileSync(path.join(SOURCE_ROOT, harness, file), "utf8")
|
|
58
|
+
if (!COMMENT.test(file)) throw new Error(`cannot add a header to ${file}`)
|
|
59
|
+
return { harness, file, contents: `// Generated by ${generatedBy}. Do not edit.\n${source}` }
|
|
60
|
+
}
|
package/src/testing.ts
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// Test helpers for plugins that vendor the OpenCode runtime. Import from "@srobroek/harness-kit/testing".
|
|
2
|
+
|
|
3
|
+
export type SystemPart = { type: string; text: string }
|
|
4
|
+
export type RegisteredSkill = { id: string; description: string; content: string; [key: string]: unknown }
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* A fake OpenCode host context that records what a plugin registers: the `system` parts pushed through
|
|
8
|
+
* `ctx.session.hook("context")`, the skills added through `ctx.skill.transform`, the agents registered through
|
|
9
|
+
* `ctx.agent.transform` (a draft per id, filled by `editor.update`), and how many registrations were disposed.
|
|
10
|
+
*/
|
|
11
|
+
export function createFakeContext(config: { options?: unknown; existingSkills?: string[]; existingAgents?: string[] } = {}) {
|
|
12
|
+
const system: SystemPart[] = []
|
|
13
|
+
const skills = new Map<string, RegisteredSkill>(
|
|
14
|
+
(config.existingSkills ?? []).map((id) => [id, { id, description: "own", content: "own" }]),
|
|
15
|
+
)
|
|
16
|
+
const agents = new Map<string, Record<string, unknown>>((config.existingAgents ?? []).map((id) => [id, { system: "own" }]))
|
|
17
|
+
let disposed = 0
|
|
18
|
+
const ctx = {
|
|
19
|
+
options: config.options,
|
|
20
|
+
session: {
|
|
21
|
+
hook: async (_name: string, handler: (event: { system: SystemPart[] }) => void) => {
|
|
22
|
+
handler({ system })
|
|
23
|
+
return { dispose: async () => void disposed++ }
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
agent: {
|
|
27
|
+
transform: async (
|
|
28
|
+
change: (editor: { get(id: string): unknown; update(id: string, change: (draft: Record<string, unknown>) => void): void }) => void,
|
|
29
|
+
) => {
|
|
30
|
+
change({
|
|
31
|
+
get: (id) => agents.get(id),
|
|
32
|
+
update: (id, edit) => {
|
|
33
|
+
const draft = agents.get(id) ?? {}
|
|
34
|
+
edit(draft)
|
|
35
|
+
agents.set(id, draft)
|
|
36
|
+
},
|
|
37
|
+
})
|
|
38
|
+
return { dispose: async () => void disposed++ }
|
|
39
|
+
},
|
|
40
|
+
},
|
|
41
|
+
skill: {
|
|
42
|
+
transform: async (change: (editor: { get(id: string): unknown; add(skill: RegisteredSkill): void }) => void) => {
|
|
43
|
+
change({ get: (id) => skills.get(id), add: (skill) => void skills.set(skill.id, skill) })
|
|
44
|
+
return { dispose: async () => void disposed++ }
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
}
|
|
48
|
+
return { ctx, system, skills, agents, disposed: () => disposed }
|
|
49
|
+
}
|