@srobroek/harness-kit 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -60,6 +60,22 @@ Each plugin's `package.json` carries `name` (equal to the directory), `version`,
60
60
  - An OMP rule with no front matter gets `alwaysApply: true`. A rule with its own front matter, such as `description:`, is copied unchanged.
61
61
  - `__pycache__` directories are ignored.
62
62
 
63
+ ### Vendored runtime modules
64
+
65
+ 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.
66
+
67
+ | Module | Harness | Provides |
68
+ | --- | --- | --- |
69
+ | `frontmatter` | opencode | `isRecord`, `parseFrontmatter` |
70
+ | `content` | opencode | `loadSkills`, `loadRules`, `loadPrompt`, `resolveOptions`, `renderTemplate`, `setupContent`: registers `skills/`, `rules/` and `templates/` with the host. Needs `frontmatter`. |
71
+ | `session` | opencode | `createRootResolver`, `rootOf`: resolve a session to its root session |
72
+ | `render` | claude | `render.mjs`, a SessionStart hook: `node "${CLAUDE_PLUGIN_ROOT}/_kit/render.mjs" <template>` prints `templates/<template>.md` with the options filled in |
73
+ | `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 |
74
+
75
+ `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`.
76
+
77
+ Test helpers are not vendored. `@srobroek/harness-kit/testing` exports `createFakeContext({ options?, existingSkills? })`, a fake OpenCode host context that records the system parts, skills and disposals a plugin registers.
78
+
63
79
  ## Commands
64
80
 
65
81
  ```sh
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@srobroek/harness-kit",
3
- "version": "1.0.1",
3
+ "version": "1.1.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,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
@@ -80,6 +80,7 @@ export function resolveConfig(raw: unknown, where = CONFIG_FILE): Config {
80
80
  if (typeof dir !== "string" || !DIR_NAME.test(dir)) fail(where, `"commonDirs" entry ${JSON.stringify(dir)} must be a plain directory name`)
81
81
  }
82
82
  if (new Set(raw.commonDirs).size !== raw.commonDirs.length) fail(where, '"commonDirs" lists a directory twice')
83
+ if (raw.commonDirs.includes("_kit")) fail(where, '"commonDirs" cannot list "_kit", which holds the vendored runtime modules')
83
84
  commonDirs = raw.commonDirs as string[]
84
85
  }
85
86
 
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,8 @@ 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
+ /** Runtime modules vendored into the harness trees as `_kit/`, with their dependencies. Absent when the plugin opts out. */
36
+ runtime?: RuntimeModuleName[]
34
37
  }
35
38
 
36
39
  export type Output = { file: string; contents: string | Buffer }
@@ -124,13 +127,15 @@ export function readPlugin(root: string, name: string, config: Config): Plugin {
124
127
  if (own.userConfig !== undefined && !isRecord(own.userConfig)) fail(where, `"${key}.userConfig" must be an object`)
125
128
  const userConfig = own.userConfig as Record<string, unknown> | undefined
126
129
  if (options && userConfig) fail(where, `set either "${key}.options" or "${key}.userConfig", not both: options generate the userConfig`)
130
+ const selectedHarnesses = KNOWN_HARNESSES.filter((h) => harnesses.includes(h))
131
+ const runtime = readRuntime(where, key, own.runtime, selectedHarnesses)
127
132
  // Keep canonical harness order so output does not depend on how the author ordered the list.
128
133
  return {
129
134
  name,
130
135
  version,
131
136
  description,
132
137
  category,
133
- harnesses: KNOWN_HARNESSES.filter((h) => harnesses.includes(h)),
138
+ harnesses: selectedHarnesses,
134
139
  scope,
135
140
  discrepancies,
136
141
  options,
@@ -138,6 +143,19 @@ export function readPlugin(root: string, name: string, config: Config): Plugin {
138
143
  author,
139
144
  license,
140
145
  userConfig,
146
+ runtime,
147
+ }
148
+ }
149
+
150
+ function readRuntime(where: string, key: string, raw: unknown, harnesses: Harness[]): RuntimeModuleName[] | undefined {
151
+ if (raw === undefined || raw === false) return undefined
152
+ const valid = raw === true || (Array.isArray(raw) && raw.length > 0 && raw.every((item) => typeof item === "string"))
153
+ if (!valid) fail(where, `"${key}.runtime" must be true or a non-empty list of module names`)
154
+ try {
155
+ const modules = resolveRuntime(raw as boolean | string[], harnesses)
156
+ return modules.length > 0 ? modules : undefined
157
+ } catch (error) {
158
+ return fail(where, `"${key}.runtime": ${error instanceof Error ? error.message : String(error)}`)
141
159
  }
142
160
  }
143
161
 
@@ -235,6 +253,14 @@ function ownedCopies(root: string, plugin: Plugin, config: Config): Output[] {
235
253
  return outputs
236
254
  }
237
255
 
256
+ /** The opted-in runtime modules, copied into each harness tree's `_kit/` directory. */
257
+ function runtimeCopies(root: string, plugin: Plugin, config: Config): Output[] {
258
+ return (plugin.runtime ?? []).map((name) => {
259
+ const { harness, file, contents } = vendoredSource(name, config.generatedBy)
260
+ return { file: path.join(harnessDir(root, plugin, harness), RUNTIME_DIR, file), contents }
261
+ })
262
+ }
263
+
238
264
  function ompExtensions(root: string, plugin: Plugin): string[] {
239
265
  const dir = path.join(harnessDir(root, plugin, "omp"), "extensions")
240
266
  if (!existsSync(dir)) return []
@@ -455,7 +481,7 @@ export function render(root: string, plugins: Plugin[], config: Config): Output[
455
481
  }))
456
482
  const entries: PluginInventory[] = []
457
483
  for (const plugin of plugins) {
458
- const copies = ownedCopies(root, plugin, config)
484
+ const copies = [...ownedCopies(root, plugin, config), ...runtimeCopies(root, plugin, config)]
459
485
  const entry = buildInventory(root, plugin, copies, config)
460
486
  entries.push(entry)
461
487
  outputs.push(...manifests(root, plugin, config), ...optionDefaults(root, plugin), ...copies)
@@ -475,7 +501,7 @@ export function render(root: string, plugins: Plugin[], config: Config): Output[
475
501
  function ownedFiles(root: string, plugins: Plugin[], config: Config): string[] {
476
502
  return plugins.flatMap((plugin) =>
477
503
  plugin.harnesses.flatMap((harness) =>
478
- config.commonDirs.flatMap((dir) => {
504
+ [...config.commonDirs, RUNTIME_DIR].flatMap((dir) => {
479
505
  const base = path.join(harnessDir(root, plugin, harness), dir)
480
506
  return listFiles(base).map((file) => path.join(base, file))
481
507
  }),
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,59 @@
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
+ session: { harness: "opencode", file: "session.ts", requires: [] },
22
+ render: { harness: "claude", file: "render.mjs", requires: [] },
23
+ "template-extension": { harness: "omp", file: "template-extension.ts", requires: [] },
24
+ } as const satisfies Record<string, RuntimeModule>
25
+
26
+ export type RuntimeModuleName = keyof typeof RUNTIME_MODULES
27
+ export const RUNTIME_MODULE_NAMES = Object.keys(RUNTIME_MODULES) as RuntimeModuleName[]
28
+
29
+ const SOURCE_ROOT = path.join(import.meta.dir, "..", "runtime")
30
+
31
+ /**
32
+ * The modules a plugin vendors, in canonical order, with their dependencies. `true` means every module of the
33
+ * plugin's harnesses. Throws a message (without a location) on an unknown module or one for a harness the plugin lacks.
34
+ */
35
+ export function resolveRuntime(request: boolean | string[], harnesses: readonly Harness[]): RuntimeModuleName[] {
36
+ const wanted = new Set<RuntimeModuleName>()
37
+ if (request === true) {
38
+ for (const name of RUNTIME_MODULE_NAMES) if (harnesses.includes(RUNTIME_MODULES[name].harness)) wanted.add(name)
39
+ } else if (Array.isArray(request)) {
40
+ for (const name of request) {
41
+ if (!(name in RUNTIME_MODULES)) throw new Error(`unknown runtime module "${String(name)}" (use ${RUNTIME_MODULE_NAMES.join(", ")})`)
42
+ const module = RUNTIME_MODULES[name as RuntimeModuleName]
43
+ if (!harnesses.includes(module.harness)) throw new Error(`runtime module "${name}" is for ${module.harness}, which the plugin does not list`)
44
+ wanted.add(name as RuntimeModuleName)
45
+ }
46
+ }
47
+ for (const name of wanted) for (const dep of RUNTIME_MODULES[name].requires) wanted.add(dep as RuntimeModuleName)
48
+ return RUNTIME_MODULE_NAMES.filter((name) => wanted.has(name))
49
+ }
50
+
51
+ const COMMENT = /\.(?:[cm]?[jt]s)$/
52
+
53
+ /** The vendored text of a module: a generated-by header, then the source. */
54
+ export function vendoredSource(name: RuntimeModuleName, generatedBy: string): { harness: Harness; file: string; contents: string } {
55
+ const { harness, file } = RUNTIME_MODULES[name]
56
+ const source = readFileSync(path.join(SOURCE_ROOT, harness, file), "utf8")
57
+ if (!COMMENT.test(file)) throw new Error(`cannot add a header to ${file}`)
58
+ return { harness, file, contents: `// Generated by ${generatedBy}. Do not edit.\n${source}` }
59
+ }
package/src/testing.ts ADDED
@@ -0,0 +1,32 @@
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`, and how many registrations were disposed.
9
+ */
10
+ export function createFakeContext(config: { options?: unknown; existingSkills?: string[] } = {}) {
11
+ const system: SystemPart[] = []
12
+ const skills = new Map<string, RegisteredSkill>(
13
+ (config.existingSkills ?? []).map((id) => [id, { id, description: "own", content: "own" }]),
14
+ )
15
+ let disposed = 0
16
+ const ctx = {
17
+ options: config.options,
18
+ session: {
19
+ hook: async (_name: string, handler: (event: { system: SystemPart[] }) => void) => {
20
+ handler({ system })
21
+ return { dispose: async () => void disposed++ }
22
+ },
23
+ },
24
+ skill: {
25
+ transform: async (change: (editor: { get(id: string): unknown; add(skill: RegisteredSkill): void }) => void) => {
26
+ change({ get: (id) => skills.get(id), add: (skill) => void skills.set(skill.id, skill) })
27
+ return { dispose: async () => void disposed++ }
28
+ },
29
+ },
30
+ }
31
+ return { ctx, system, skills, disposed: () => disposed }
32
+ }