superpowers.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. /**
  2. * Superpowers plugin for OpenCode.ai
  3. *
  4. * Dual-compatible with OpenCode V1 and V2.
  5. *
  6. * V1 (opencode): loaded via named export SuperpowersPlugin — provides config
  7. * hook for skills registration and experimental.chat.messages.transform for
  8. * bootstrap injection.
  9. *
  10. * V2 (opencode2): loaded via default export { id, setup } by PluginSupervisor.
  11. * setup() registers skills natively via ctx.skill.transform(), and injects
  12. * bootstrap context via ctx.session.hook("context").
  13. *
  14. * No external dependencies — pure JavaScript works in both V1 and V2 without
  15. * installing @opencode-ai/plugin or effect.
  16. */
  17. import path from 'path';
  18. import fs from 'fs';
  19. import { fileURLToPath } from 'url';
  20. const __dirname = path.dirname(fileURLToPath(import.meta.url));
  21. // Skills directory shared by V1 (config hook) and V2 (setup/ctx.skill.transform)
  22. const superpowersSkillsDir = path.resolve(__dirname, '../../skills');
  23. // Simple frontmatter extraction (avoid dependency on skills-core for
  24. // bootstrap). Handles plain `key: value` lines, quoted values, YAML block
  25. // scalar markers (`>`, `|`) with indented continuation lines, and CRLF line
  26. // endings. Not a full YAML parser — nested maps flatten into their parent
  27. // key's value, which is fine for the name/description fields consumed here.
  28. const extractAndStripFrontmatter = (content) => {
  29. const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/);
  30. if (!match) return { frontmatter: {}, content };
  31. const frontmatterStr = match[1];
  32. const body = match[2];
  33. const frontmatter = {};
  34. let lastKey = null;
  35. for (const rawLine of frontmatterStr.split('\n')) {
  36. const line = rawLine.replace(/\r$/, '');
  37. const colonIdx = line.indexOf(':');
  38. if (colonIdx > 0 && !/^\s/.test(line)) {
  39. const key = line.slice(0, colonIdx).trim();
  40. const value = line.slice(colonIdx + 1).trim().replace(/^["']|["']$/g, '');
  41. // Block scalar markers (>, |, optionally with +/- chomping) carry no
  42. // value themselves; the indented lines that follow do.
  43. frontmatter[key] = /^(>[+-]?|\|[+-]?)$/.test(value) ? '' : value;
  44. lastKey = key;
  45. } else if (lastKey !== null && line.trim() !== '') {
  46. // Continuation of a multi-line value: append rather than drop so long
  47. // descriptions survive parsing. Newlines collapse to spaces — good
  48. // enough for the single-line name/description fields consumed here.
  49. frontmatter[lastKey] = `${frontmatter[lastKey]} ${line.trim()}`.trim();
  50. }
  51. }
  52. return { frontmatter, content: body };
  53. };
  54. // Tool mapping injected into the bootstrap, differentiated by host flavor.
  55. // V1 (OpenCode 1.18.x) and V2 (OpenCode 2.x beta) expose different built-in
  56. // tools, so each flavor's injection path picks its own constant below.
  57. // Exported for tests (tests/opencode/test-bootstrap-caching.mjs).
  58. // V1 built-ins: todowrite, task (subagent_type), skill, read, apply_patch,
  59. // bash, grep, glob, webfetch.
  60. export const V1_MAPPING = `**Tool Mapping for OpenCode:**
  61. When skills request actions, substitute OpenCode equivalents:
  62. - Create or update todos → \`todowrite\`
  63. - \`Subagent (general-purpose):\` → \`task\` with \`subagent_type: "general"\`
  64. - Invoke a skill → OpenCode's native \`skill\` tool
  65. - Read files → \`read\`
  66. - Create, edit, or delete files → \`apply_patch\`
  67. - Run shell commands → \`bash\`
  68. - Search files → \`grep\`, \`glob\`
  69. - Fetch a URL → \`webfetch\`
  70. Use OpenCode's native \`skill\` tool to list and load skills.`;
  71. // V2 built-ins: no todo tool at all; task → subagent (agent name in 'agent',
  72. // continuation via sessionID); apply_patch → patch (patchText, same patch
  73. // format); bash → shell. read, write, edit, grep, glob, webfetch, websearch,
  74. // and skill all exist under those names (verified against the 2.0.3 tool
  75. // catalog served by /api/plugin).
  76. export const V2_MAPPING = `**Tool Mapping for OpenCode:**
  77. When skills request actions, substitute OpenCode equivalents:
  78. - Create or update todos → OpenCode v2 has no todo tool; track the plan in a markdown file (or the harness's plan facility) instead
  79. - \`Subagent (general-purpose):\` → \`subagent\` with \`agent: "general"\` (give it \`description\` and \`prompt\`, optionally \`background\`; pass \`sessionID\` to continue a previous subagent)
  80. - Invoke a skill → OpenCode's native \`skill\` tool
  81. - Read files → \`read\`
  82. - Create or overwrite a file → \`write\`
  83. - Edit files → \`edit\` for targeted changes, or \`patch\` with \`patchText\` (same patch format) when a skill speaks in patch format or deletes files
  84. - Run shell commands → \`shell\` (\`command\`, \`workdir\`, \`timeout\`, \`background\`)
  85. - Search files → \`grep\`, \`glob\`
  86. - Fetch a URL → \`webfetch\`
  87. - Search the web → \`websearch\`
  88. Use OpenCode's native \`skill\` tool to list and load skills.`;
  89. // Module-level cache for bootstrap content, keyed by tool mapping (host
  90. // flavor). The SKILL.md file does not change during a session, so reading +
  91. // parsing it once eliminates redundant fs.existsSync + fs.readFileSync +
  92. // regex work on every agent step. See #1202 for the full analysis.
  93. const _bootstrapCache = new Map(); // mapping -> bootstrap (null = file missing)
  94. // Helper to generate bootstrap content (cached after first call per mapping)
  95. const getBootstrapContent = (toolMapping) => {
  96. // Return cached result on subsequent calls
  97. if (_bootstrapCache.has(toolMapping)) return _bootstrapCache.get(toolMapping);
  98. // Try to load using-superpowers skill
  99. const skillPath = path.join(superpowersSkillsDir, 'using-superpowers', 'SKILL.md');
  100. if (!fs.existsSync(skillPath)) {
  101. _bootstrapCache.set(toolMapping, null);
  102. return null;
  103. }
  104. const fullContent = fs.readFileSync(skillPath, 'utf8');
  105. const { content } = extractAndStripFrontmatter(fullContent);
  106. _bootstrapCache.set(toolMapping, `<EXTREMELY_IMPORTANT>
  107. You have superpowers.
  108. **IMPORTANT: The using-superpowers skill content is included below. It is ALREADY LOADED - you are currently following it. Do NOT use the skill tool to load "using-superpowers" again - that would be redundant.**
  109. ${content}
  110. ${toolMapping}
  111. </EXTREMELY_IMPORTANT>`);
  112. return _bootstrapCache.get(toolMapping);
  113. };
  114. // --- Task-subagent (child session) detection --------------------------------
  115. //
  116. // #2160: the bootstrap drives controller workflows (brainstorming, planning,
  117. // approval cycles). Injecting it into task subagent sessions makes workers
  118. // restart design/approval cycles for work the parent already authorised; the
  119. // <SUBAGENT-STOP> note inside the bootstrap relies on model compliance, which
  120. // is not reliable. Detect child sessions structurally instead: a parentID on
  121. // the session is the child signal on both flavors (task sessions are created
  122. // with one; top-level sessions simply lack the field), so when the session
  123. // carrying the message has a parentID we skip bootstrap injection. Skills
  124. // stay registered for every session — workers keep explicit access to
  125. // execution skills.
  126. // sessionID -> is-child decision. parentID never changes for a session, so
  127. // the result is cached until eviction and the injection hook (which fires on
  128. // every agent step) pays only one client roundtrip per session. The V2
  129. // service process is long-lived and sessions accumulate over weeks, so the
  130. // cache is bounded: when full, drop the oldest quarter (Map iterates keys in
  131. // insertion order). An evicted session merely pays one extra lookup if seen
  132. // again.
  133. const CHILD_SESSION_CACHE_MAX = 512;
  134. const _childSessionCache = new Map();
  135. const _cacheChildSession = (sessionID, isChild) => {
  136. if (_childSessionCache.size >= CHILD_SESSION_CACHE_MAX) {
  137. let toDrop = Math.ceil(CHILD_SESSION_CACHE_MAX / 4);
  138. for (const key of _childSessionCache.keys()) {
  139. if (toDrop-- <= 0) break;
  140. _childSessionCache.delete(key);
  141. }
  142. }
  143. _childSessionCache.set(sessionID, isChild);
  144. };
  145. const isChildSession = async (fetchSession, sessionID) => {
  146. if (!sessionID) return false; // unknown session: keep current behavior
  147. if (_childSessionCache.has(sessionID)) return _childSessionCache.get(sessionID);
  148. let isChild = false;
  149. try {
  150. const result = await fetchSession(sessionID);
  151. // V1 returns a successful SDK envelope while V2 returns a direct session
  152. // record. Validate both shapes before classifying or caching the result;
  153. // resolved SDK errors must follow the same fail-open path as rejections.
  154. if (!result || typeof result !== 'object' || Array.isArray(result)) {
  155. throw new Error('Session lookup returned no usable record');
  156. }
  157. if (result.error != null || result.response?.ok === false) {
  158. throw new Error('Session lookup was unsuccessful');
  159. }
  160. const session = 'data' in result ? result.data : result;
  161. if (!session || typeof session !== 'object' || Array.isArray(session) || session.id !== sessionID) {
  162. throw new Error('Session lookup returned an invalid session identity');
  163. }
  164. if (session.parentID !== undefined &&
  165. (typeof session.parentID !== 'string' || session.parentID.length === 0)) {
  166. throw new Error('Session lookup returned an invalid parent identity');
  167. }
  168. isChild = session.parentID !== undefined;
  169. } catch (err) {
  170. // Fail open: on lookup errors keep injecting (previous behavior) and do
  171. // not cache, so a transient failure can recover on the next step.
  172. console.error('[superpowers] session lookup failed, treating session as top-level:', err);
  173. return false;
  174. }
  175. _cacheChildSession(sessionID, isChild);
  176. return isChild;
  177. };
  178. /**
  179. * V1 Plugin Function (named export + default.server)
  180. *
  181. * Used by V1 (OpenCode 1.x): discovered via named export scanning.
  182. * Provides: config hook (V1 skills registration) + bootstrap injection
  183. * (experimental.chat.messages.transform).
  184. */
  185. export const SuperpowersPlugin = async ({ client, directory }) => {
  186. return {
  187. // Inject skills path into live config so OpenCode discovers superpowers skills
  188. // without requiring manual symlinks or config file edits.
  189. config: async (config) => {
  190. // V2: skills is a flat array — skip, setup() handles V2 skill registration
  191. if (Array.isArray(config.skills)) return;
  192. // V1: skills is { paths: [...] }
  193. config.skills = config.skills || {};
  194. config.skills.paths = config.skills.paths || [];
  195. if (!config.skills.paths.includes(superpowersSkillsDir)) {
  196. config.skills.paths.push(superpowersSkillsDir);
  197. }
  198. },
  199. // Inject bootstrap into the first user message of each top-level session.
  200. // Using a user message instead of a system message avoids:
  201. // 1. Token bloat from system messages repeated every turn (#750)
  202. // 2. Multiple system messages breaking Qwen and other models (#894)
  203. //
  204. // The hook fires on every agent step (not just every turn) because
  205. // opencode's prompt.ts reloads messages from DB each step. Fresh message
  206. // arrays may need injection again, so getBootstrapContent() must not do
  207. // repeated disk work.
  208. 'experimental.chat.messages.transform': async (_input, output) => {
  209. const bootstrap = getBootstrapContent(V1_MAPPING);
  210. if (!bootstrap || !output.messages.length) return;
  211. const firstUser = output.messages.find(m => m.info.role === 'user');
  212. if (!firstUser || !firstUser.parts.length) return;
  213. // Guard: skip if first user message already contains bootstrap.
  214. if (firstUser.parts.some(p => p.type === 'text' && p.text.includes('EXTREMELY_IMPORTANT'))) return;
  215. // #2160: never restart the controller workflow inside task subagent
  216. // (child) sessions. V1 passes no input to this hook (verified in the
  217. // 1.18.x bundle: trigger(..., {}, {messages})), so take the sessionID
  218. // from the message record itself.
  219. if (client && await isChildSession(
  220. (id) => client.session.get({ path: { id } }),
  221. firstUser.info.sessionID,
  222. )) return;
  223. const ref = firstUser.parts[0];
  224. firstUser.parts.unshift({ ...ref, type: 'text', text: bootstrap });
  225. }
  226. };
  227. };
  228. /**
  229. * V2 Setup Function (default.setup)
  230. *
  231. * Called by V2 PluginSupervisor (packages/core/src/plugin/supervisor.ts).
  232. * Performs two things:
  233. *
  234. * 1. Registers every skills/<name>/SKILL.md as a native Skill.Info object
  235. * via ctx.skill.transform((draft) => draft.add(info)).
  236. * V2 removed the old draft.source() directory registration; the draft API
  237. * is now { list, add, update, remove } where add() decodes plain objects
  238. * against the host's Skill.Info schema (OpenCode 2.0.4 contract):
  239. * { id, name, description?, autoinvoke?, path, content }. The file field
  240. * is `path` — renamed from `location` in upstream commit 199aabe9e2,
  241. * first released in v2.0.4.
  242. * See packages/core/src/plugin/skill.ts and packages/schema/src/skill.ts.
  243. * 2. Injects bootstrap context via ctx.session.hook("context"), the V2
  244. * equivalent of V1's experimental.chat.messages.transform.
  245. */
  246. async function setup(ctx) {
  247. // V1 (observed on opencode 1.18.18) also invokes default.setup, but with a
  248. // V1-shaped ctx that lacks the skill/session domains. Detect it and return
  249. // quietly — V1 is served entirely by the SuperpowersPlugin named export.
  250. if (!ctx || !ctx.skill || typeof ctx.skill.transform !== 'function' || !ctx.session || typeof ctx.session.hook !== 'function') {
  251. return;
  252. }
  253. // 1. Register skills (one transform; one draft.add per skill)
  254. try {
  255. const skills = [];
  256. if (fs.existsSync(superpowersSkillsDir)) {
  257. for (const entry of fs.readdirSync(superpowersSkillsDir, { withFileTypes: true })) {
  258. if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
  259. const skillPath = path.join(superpowersSkillsDir, entry.name, 'SKILL.md');
  260. if (!fs.existsSync(skillPath)) continue;
  261. const { frontmatter, content } = extractAndStripFrontmatter(fs.readFileSync(skillPath, 'utf8'));
  262. skills.push({
  263. id: entry.name,
  264. name: frontmatter.name || entry.name,
  265. ...(frontmatter.description ? { description: frontmatter.description } : {}),
  266. // Skill.Info renamed its required file field `location` -> `path`
  267. // in OpenCode v2.0.4 (upstream commit 199aabe9e2).
  268. path: skillPath,
  269. content,
  270. });
  271. }
  272. }
  273. await ctx.skill.transform((draft) => {
  274. // draft.add() decodes against the host's Skill.Info schema and throws
  275. // synchronously on a mismatch. A throw escaping this callback is what
  276. // the host escalates into an asynchronous hard-disable of the entire
  277. // plugin ("Plugin disabled after skill.transform failed") — the
  278. // try/catch around ctx.skill.transform never sees it, and the
  279. // bootstrap hook is torn down as collateral. Contain failures per
  280. // skill so one rejected payload skips that skill instead of killing
  281. // skills AND bootstrap.
  282. for (const skill of skills) {
  283. try {
  284. draft.add(skill);
  285. } catch (err) {
  286. console.error(`[superpowers] skill "${skill.id}" rejected by host, skipping:`, err);
  287. }
  288. }
  289. });
  290. } catch (err) {
  291. // Never break plugin activation: one failing plugin takes down the whole
  292. // V2 generation (including provider/catalog plugins => no models in TUI).
  293. console.error('[superpowers] skill registration failed:', err);
  294. }
  295. // 2. Inject bootstrap into first user message via V2 session context hook
  296. try {
  297. await ctx.session.hook('context', async (event) => {
  298. try {
  299. const bootstrap = getBootstrapContent(V2_MAPPING);
  300. if (!bootstrap || !event.messages || !event.messages.length) return;
  301. const firstUser = event.messages.find(m => m.role === 'user');
  302. if (firstUser && (!firstUser.content || !firstUser.content.length)) return;
  303. if (firstUser?.content.some(p => p.type === 'text' && p.text && p.text.includes('EXTREMELY_IMPORTANT'))) return;
  304. // #2160: the context event carries the sessionID directly. Skip the
  305. // controller bootstrap when this prompt belongs to a task subagent
  306. // (child) session. Skills registered above stay available to workers.
  307. if (typeof ctx.session.get === 'function' && await isChildSession(
  308. (id) => ctx.session.get({ sessionID: id }),
  309. event.sessionID,
  310. )) return;
  311. // Native compaction can leave only an opaque checkpoint. Keep it
  312. // intact and append the transient bootstrap as a user message.
  313. if (firstUser) {
  314. firstUser.content.unshift({ type: 'text', text: bootstrap });
  315. } else {
  316. event.messages.push({ role: 'user', content: [{ type: 'text', text: bootstrap }] });
  317. }
  318. } catch (err) {
  319. // Never let hook callback errors break the request pipeline.
  320. console.error('[superpowers] context hook failed:', err);
  321. }
  322. });
  323. } catch (err) {
  324. console.error('[superpowers] session hook registration failed:', err);
  325. }
  326. }
  327. /**
  328. * Default Export: { id, server, setup }
  329. *
  330. * V2 PluginSupervisor reads { id, setup }.
  331. * V1 reads named export SuperpowersPlugin.
  332. * server() is exported for V1 compatibility.
  333. */
  334. export default {
  335. id: 'superpowers',
  336. server: SuperpowersPlugin,
  337. setup,
  338. };