superpowers.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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.0.4/2.0.7) 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.4 and 2.0.7
  75. // host contracts).
  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, edit, or delete files → use \`patch\` with \`patchText\` when available; otherwise use \`write\` to create or overwrite files, \`edit\` for targeted changes, and \`shell\` for deletion
  83. - Run shell commands → \`shell\` (\`command\`, \`workdir\`, \`timeout\`, \`background\`)
  84. - Search files → \`grep\`, \`glob\`
  85. - Fetch a URL → \`webfetch\`
  86. - Search the web → \`websearch\`
  87. Use OpenCode's native \`skill\` tool to list and load skills.`;
  88. // Module-level cache for bootstrap content, keyed by tool mapping (host
  89. // flavor). The SKILL.md file does not change during a session, so reading +
  90. // parsing it once eliminates redundant fs.existsSync + fs.readFileSync +
  91. // regex work on every agent step. See #1202 for the full analysis.
  92. const _bootstrapCache = new Map(); // mapping -> bootstrap (null = file missing)
  93. // Helper to generate bootstrap content (cached after first call per mapping)
  94. const getBootstrapContent = (toolMapping) => {
  95. // Return cached result on subsequent calls
  96. if (_bootstrapCache.has(toolMapping)) return _bootstrapCache.get(toolMapping);
  97. // Try to load using-superpowers skill
  98. const skillPath = path.join(superpowersSkillsDir, 'using-superpowers', 'SKILL.md');
  99. if (!fs.existsSync(skillPath)) {
  100. _bootstrapCache.set(toolMapping, null);
  101. return null;
  102. }
  103. const fullContent = fs.readFileSync(skillPath, 'utf8');
  104. const { content } = extractAndStripFrontmatter(fullContent);
  105. _bootstrapCache.set(toolMapping, `<EXTREMELY_IMPORTANT>
  106. You have superpowers.
  107. **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.**
  108. ${content}
  109. ${toolMapping}
  110. </EXTREMELY_IMPORTANT>`);
  111. return _bootstrapCache.get(toolMapping);
  112. };
  113. // --- Task-subagent (child session) detection --------------------------------
  114. //
  115. // #2160: the bootstrap drives controller workflows (brainstorming, planning,
  116. // approval cycles). Injecting it into task subagent sessions makes workers
  117. // restart design/approval cycles for work the parent already authorised; the
  118. // <SUBAGENT-STOP> note inside the bootstrap relies on model compliance, which
  119. // is not reliable. Detect child sessions structurally instead: a parentID on
  120. // the session is the child signal on both flavors (task sessions are created
  121. // with one; top-level sessions simply lack the field), so when the session
  122. // carrying the message has a parentID we skip bootstrap injection. Skills
  123. // stay registered for every session — workers keep explicit access to
  124. // execution skills.
  125. // sessionID -> is-child decision. parentID never changes for a session, so
  126. // the result is cached until eviction and the injection hook (which fires on
  127. // every agent step) pays only one client roundtrip per session. The V2
  128. // service process is long-lived and sessions accumulate over weeks, so the
  129. // cache is bounded: when full, drop the oldest quarter (Map iterates keys in
  130. // insertion order). An evicted session merely pays one extra lookup if seen
  131. // again.
  132. const CHILD_SESSION_CACHE_MAX = 512;
  133. const _childSessionCache = new Map();
  134. const _cacheChildSession = (sessionID, isChild) => {
  135. if (_childSessionCache.size >= CHILD_SESSION_CACHE_MAX) {
  136. let toDrop = Math.ceil(CHILD_SESSION_CACHE_MAX / 4);
  137. for (const key of _childSessionCache.keys()) {
  138. if (toDrop-- <= 0) break;
  139. _childSessionCache.delete(key);
  140. }
  141. }
  142. _childSessionCache.set(sessionID, isChild);
  143. };
  144. const isChildSession = async (fetchSession, sessionID) => {
  145. if (!sessionID) return false; // unknown session: keep current behavior
  146. if (_childSessionCache.has(sessionID)) return _childSessionCache.get(sessionID);
  147. let isChild = false;
  148. try {
  149. const result = await fetchSession(sessionID);
  150. // V1 returns a successful SDK envelope while V2 returns a direct session
  151. // record. Validate both shapes before classifying or caching the result;
  152. // resolved SDK errors must follow the same fail-open path as rejections.
  153. if (!result || typeof result !== 'object' || Array.isArray(result)) {
  154. throw new Error('Session lookup returned no usable record');
  155. }
  156. if (result.error != null || result.response?.ok === false) {
  157. throw new Error('Session lookup was unsuccessful');
  158. }
  159. const session = 'data' in result ? result.data : result;
  160. if (!session || typeof session !== 'object' || Array.isArray(session) || session.id !== sessionID) {
  161. throw new Error('Session lookup returned an invalid session identity');
  162. }
  163. if (session.parentID !== undefined &&
  164. (typeof session.parentID !== 'string' || session.parentID.length === 0)) {
  165. throw new Error('Session lookup returned an invalid parent identity');
  166. }
  167. isChild = session.parentID !== undefined;
  168. } catch (err) {
  169. // Fail open: on lookup errors keep injecting (previous behavior) and do
  170. // not cache, so a transient failure can recover on the next step.
  171. console.error('[superpowers] session lookup failed, treating session as top-level:', err);
  172. return false;
  173. }
  174. _cacheChildSession(sessionID, isChild);
  175. return isChild;
  176. };
  177. /**
  178. * V1 Plugin Function (named export + default.server)
  179. *
  180. * Used by V1 (OpenCode 1.x): discovered via named export scanning.
  181. * Provides: config hook (V1 skills registration) + bootstrap injection
  182. * (experimental.chat.messages.transform).
  183. */
  184. export const SuperpowersPlugin = async ({ client, directory }) => {
  185. return {
  186. // Inject skills path into live config so OpenCode discovers superpowers skills
  187. // without requiring manual symlinks or config file edits.
  188. config: async (config) => {
  189. // V2: skills is a flat array — skip, setup() handles V2 skill registration
  190. if (Array.isArray(config.skills)) return;
  191. // V1: skills is { paths: [...] }
  192. config.skills = config.skills || {};
  193. config.skills.paths = config.skills.paths || [];
  194. if (!config.skills.paths.includes(superpowersSkillsDir)) {
  195. config.skills.paths.push(superpowersSkillsDir);
  196. }
  197. },
  198. // Inject bootstrap into the first user message of each top-level session.
  199. // Using a user message instead of a system message avoids:
  200. // 1. Token bloat from system messages repeated every turn (#750)
  201. // 2. Multiple system messages breaking Qwen and other models (#894)
  202. //
  203. // The hook fires on every agent step (not just every turn) because
  204. // opencode's prompt.ts reloads messages from DB each step. Fresh message
  205. // arrays may need injection again, so getBootstrapContent() must not do
  206. // repeated disk work.
  207. 'experimental.chat.messages.transform': async (_input, output) => {
  208. const bootstrap = getBootstrapContent(V1_MAPPING);
  209. if (!bootstrap || !output.messages.length) return;
  210. const firstUser = output.messages.find(m => m.info.role === 'user');
  211. if (!firstUser || !firstUser.parts.length) return;
  212. // Guard: skip if first user message already contains bootstrap.
  213. if (firstUser.parts.some(p => p.type === 'text' && p.text.includes('EXTREMELY_IMPORTANT'))) return;
  214. // #2160: never restart the controller workflow inside task subagent
  215. // (child) sessions. V1 passes no input to this hook (verified in the
  216. // 1.18.x bundle: trigger(..., {}, {messages})), so take the sessionID
  217. // from the message record itself.
  218. if (client && await isChildSession(
  219. (id) => client.session.get({ path: { id } }),
  220. firstUser.info.sessionID,
  221. )) return;
  222. const ref = firstUser.parts[0];
  223. firstUser.parts.unshift({ ...ref, type: 'text', text: bootstrap });
  224. }
  225. };
  226. };
  227. /**
  228. * V2 Setup Function (default.setup)
  229. *
  230. * Called by V2 PluginSupervisor (packages/core/src/plugin/supervisor.ts).
  231. * Performs two things:
  232. *
  233. * 1. Registers every skills/<name>/SKILL.md as a native Skill.Info object
  234. * via ctx.skill.transform((draft) => draft.add(info)).
  235. * V2 removed the old draft.source() directory registration; the draft API
  236. * is now { list, add, update, remove } where add() decodes plain objects
  237. * against the host's Skill.Info schema (OpenCode 2.0.4 contract):
  238. * { id, name, description?, autoinvoke?, path, content }. The file field
  239. * is `path` — renamed from `location` in upstream commit 199aabe9e2,
  240. * first released in v2.0.4.
  241. * See packages/core/src/plugin/skill.ts and packages/schema/src/skill.ts.
  242. * 2. Injects bootstrap context via ctx.session.hook("context"), the V2
  243. * equivalent of V1's experimental.chat.messages.transform.
  244. */
  245. async function setup(ctx) {
  246. // V1 (observed on opencode 1.18.18) also invokes default.setup, but with a
  247. // V1-shaped ctx that lacks the skill/session domains. Detect it and return
  248. // quietly — V1 is served entirely by the SuperpowersPlugin named export.
  249. if (!ctx || !ctx.skill || typeof ctx.skill.transform !== 'function' || !ctx.session || typeof ctx.session.hook !== 'function') {
  250. return;
  251. }
  252. // 1. Register skills (one transform; one draft.add per skill)
  253. try {
  254. const skills = [];
  255. if (fs.existsSync(superpowersSkillsDir)) {
  256. for (const entry of fs.readdirSync(superpowersSkillsDir, { withFileTypes: true })) {
  257. if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
  258. const skillPath = path.join(superpowersSkillsDir, entry.name, 'SKILL.md');
  259. if (!fs.existsSync(skillPath)) continue;
  260. const { frontmatter, content } = extractAndStripFrontmatter(fs.readFileSync(skillPath, 'utf8'));
  261. skills.push({
  262. id: entry.name,
  263. name: frontmatter.name || entry.name,
  264. ...(frontmatter.description ? { description: frontmatter.description } : {}),
  265. // Skill.Info renamed its required file field `location` -> `path`
  266. // in OpenCode v2.0.4 (upstream commit 199aabe9e2).
  267. path: skillPath,
  268. content,
  269. });
  270. }
  271. }
  272. await ctx.skill.transform((draft) => {
  273. // draft.add() decodes against the host's Skill.Info schema and throws
  274. // synchronously on a mismatch. A throw escaping this callback is what
  275. // the host escalates into an asynchronous hard-disable of the entire
  276. // plugin ("Plugin disabled after skill.transform failed") — the
  277. // try/catch around ctx.skill.transform never sees it, and the
  278. // bootstrap hook is torn down as collateral. Contain failures per
  279. // skill so one rejected payload skips that skill instead of killing
  280. // skills AND bootstrap.
  281. for (const skill of skills) {
  282. try {
  283. draft.add(skill);
  284. } catch (err) {
  285. console.error(`[superpowers] skill "${skill.id}" rejected by host, skipping:`, err);
  286. }
  287. }
  288. });
  289. } catch (err) {
  290. // Never break plugin activation: one failing plugin takes down the whole
  291. // V2 generation (including provider/catalog plugins => no models in TUI).
  292. console.error('[superpowers] skill registration failed:', err);
  293. }
  294. // 2. Inject bootstrap into first user message via V2 session context hook
  295. try {
  296. await ctx.session.hook('context', async (event) => {
  297. try {
  298. const bootstrap = getBootstrapContent(V2_MAPPING);
  299. if (!bootstrap || !event.messages || !event.messages.length) return;
  300. const firstUser = event.messages.find(m => m.role === 'user');
  301. if (firstUser && (!firstUser.content || !firstUser.content.length)) return;
  302. if (firstUser?.content.some(p => p.type === 'text' && p.text && p.text.includes('EXTREMELY_IMPORTANT'))) return;
  303. // #2160: the context event carries the sessionID directly. Skip the
  304. // controller bootstrap when this prompt belongs to a task subagent
  305. // (child) session. Skills registered above stay available to workers.
  306. if (typeof ctx.session.get === 'function' && await isChildSession(
  307. (id) => ctx.session.get({ sessionID: id }),
  308. event.sessionID,
  309. )) return;
  310. // Native compaction can leave only an opaque checkpoint. Keep it
  311. // intact and append the transient bootstrap as a user message.
  312. if (firstUser) {
  313. firstUser.content.unshift({ type: 'text', text: bootstrap });
  314. } else {
  315. event.messages.push({ role: 'user', content: [{ type: 'text', text: bootstrap }] });
  316. }
  317. } catch (err) {
  318. // Never let hook callback errors break the request pipeline.
  319. console.error('[superpowers] context hook failed:', err);
  320. }
  321. });
  322. } catch (err) {
  323. console.error('[superpowers] session hook registration failed:', err);
  324. }
  325. }
  326. /**
  327. * Default Export: { id, server, setup }
  328. *
  329. * V2 PluginSupervisor reads { id, setup }.
  330. * V1 reads named export SuperpowersPlugin.
  331. * server() is exported for V1 compatibility.
  332. */
  333. export default {
  334. id: 'superpowers',
  335. server: SuperpowersPlugin,
  336. setup,
  337. };