superpowers.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 bootstrap)
  24. const extractAndStripFrontmatter = (content) => {
  25. const match = content.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
  26. if (!match) return { frontmatter: {}, content };
  27. const frontmatterStr = match[1];
  28. const body = match[2];
  29. const frontmatter = {};
  30. for (const line of frontmatterStr.split('\n')) {
  31. const colonIdx = line.indexOf(':');
  32. if (colonIdx > 0) {
  33. const key = line.slice(0, colonIdx).trim();
  34. const value = line.slice(colonIdx + 1).trim().replace(/^["']|["']$/g, '');
  35. frontmatter[key] = value;
  36. }
  37. }
  38. return { frontmatter, content: body };
  39. };
  40. // Module-level cache for bootstrap content.
  41. // The SKILL.md file does not change during a session, so reading + parsing it
  42. // once eliminates redundant fs.existsSync + fs.readFileSync + regex work on
  43. // every agent step. See #1202 for the full analysis.
  44. let _bootstrapCache = undefined; // undefined = not yet loaded, null = file missing
  45. // Helper to generate bootstrap content (cached after first call)
  46. const getBootstrapContent = () => {
  47. // Return cached result on subsequent calls
  48. if (_bootstrapCache !== undefined) return _bootstrapCache;
  49. // Try to load using-superpowers skill
  50. const skillPath = path.join(superpowersSkillsDir, 'using-superpowers', 'SKILL.md');
  51. if (!fs.existsSync(skillPath)) {
  52. _bootstrapCache = null;
  53. return null;
  54. }
  55. const fullContent = fs.readFileSync(skillPath, 'utf8');
  56. const { content } = extractAndStripFrontmatter(fullContent);
  57. const toolMapping = `**Tool Mapping for OpenCode:**
  58. When skills request actions, substitute OpenCode equivalents:
  59. - Create or update todos → \`todowrite\`
  60. - \`Subagent (general-purpose):\` → \`task\` with \`subagent_type: "general"\`
  61. - Invoke a skill → OpenCode's native \`skill\` tool
  62. - Read files → \`read\`
  63. - Create, edit, or delete files → \`apply_patch\`
  64. - Run shell commands → \`bash\`
  65. - Search files → \`grep\`, \`glob\`
  66. - Fetch a URL → \`webfetch\`
  67. Use OpenCode's native \`skill\` tool to list and load skills.`;
  68. _bootstrapCache = `<EXTREMELY_IMPORTANT>
  69. You have superpowers.
  70. **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.**
  71. ${content}
  72. ${toolMapping}
  73. </EXTREMELY_IMPORTANT>`;
  74. return _bootstrapCache;
  75. };
  76. // --- Task-subagent (child session) detection --------------------------------
  77. //
  78. // #2160: the bootstrap drives controller workflows (brainstorming, planning,
  79. // approval cycles). Injecting it into task subagent sessions makes workers
  80. // restart design/approval cycles for work the parent already authorised; the
  81. // <SUBAGENT-STOP> note inside the bootstrap relies on model compliance, which
  82. // is not reliable. Detect child sessions structurally instead: OpenCode task
  83. // sessions are created with a parentID, so when the session carrying the
  84. // message has a parentID we skip bootstrap injection. Skills stay registered
  85. // for every session — workers keep explicit access to execution skills.
  86. // sessionID -> is-child decision. parentID never changes for a session, so
  87. // the result is cached for life and the injection hook (which fires on every
  88. // agent step) pays only one client roundtrip per session.
  89. const _childSessionCache = new Map();
  90. const isChildSession = async (fetchSession, sessionID) => {
  91. if (!sessionID) return false; // unknown session: keep current behavior
  92. if (_childSessionCache.has(sessionID)) return _childSessionCache.get(sessionID);
  93. let isChild = false;
  94. try {
  95. const result = await fetchSession(sessionID);
  96. // V1's SDK returns { data: Session }; V2's ctx returns the record itself.
  97. const session = result && typeof result === 'object' && result.data && typeof result.data === 'object' && !('parentID' in result)
  98. ? result.data
  99. : result;
  100. isChild = Boolean(session && typeof session === 'object' && session.parentID);
  101. } catch (err) {
  102. // Fail open: on lookup errors keep injecting (previous behavior) and do
  103. // not cache, so a transient failure can recover on the next step.
  104. console.error('[superpowers] session lookup failed, treating session as top-level:', err);
  105. return false;
  106. }
  107. _childSessionCache.set(sessionID, isChild);
  108. return isChild;
  109. };
  110. /**
  111. * V1 Plugin Function (named export + default.server)
  112. *
  113. * Used by V1 (OpenCode 1.x): discovered via named export scanning.
  114. * Provides: config hook (V1 skills registration) + bootstrap injection
  115. * (experimental.chat.messages.transform).
  116. */
  117. export const SuperpowersPlugin = async ({ client, directory }) => {
  118. return {
  119. // Inject skills path into live config so OpenCode discovers superpowers skills
  120. // without requiring manual symlinks or config file edits.
  121. config: async (config) => {
  122. // V2: skills is a flat array — skip, setup() handles V2 skill registration
  123. if (Array.isArray(config.skills)) return;
  124. // V1: skills is { paths: [...] }
  125. config.skills = config.skills || {};
  126. config.skills.paths = config.skills.paths || [];
  127. if (!config.skills.paths.includes(superpowersSkillsDir)) {
  128. config.skills.paths.push(superpowersSkillsDir);
  129. }
  130. },
  131. // Inject bootstrap into the first user message of each top-level session.
  132. // Using a user message instead of a system message avoids:
  133. // 1. Token bloat from system messages repeated every turn (#750)
  134. // 2. Multiple system messages breaking Qwen and other models (#894)
  135. //
  136. // The hook fires on every agent step (not just every turn) because
  137. // opencode's prompt.ts reloads messages from DB each step. Fresh message
  138. // arrays may need injection again, so getBootstrapContent() must not do
  139. // repeated disk work.
  140. 'experimental.chat.messages.transform': async (_input, output) => {
  141. const bootstrap = getBootstrapContent();
  142. if (!bootstrap || !output.messages.length) return;
  143. const firstUser = output.messages.find(m => m.info.role === 'user');
  144. if (!firstUser || !firstUser.parts.length) return;
  145. // Guard: skip if first user message already contains bootstrap.
  146. if (firstUser.parts.some(p => p.type === 'text' && p.text.includes('EXTREMELY_IMPORTANT'))) return;
  147. // #2160: never restart the controller workflow inside task subagent
  148. // (child) sessions. V1 passes no input to this hook (verified in the
  149. // 1.18.x bundle: trigger(..., {}, {messages})), so take the sessionID
  150. // from the message record itself.
  151. if (client && await isChildSession(
  152. (id) => client.session.get({ path: { id } }),
  153. firstUser.info.sessionID,
  154. )) return;
  155. const ref = firstUser.parts[0];
  156. firstUser.parts.unshift({ ...ref, type: 'text', text: bootstrap });
  157. }
  158. };
  159. };
  160. /**
  161. * V2 Setup Function (default.setup)
  162. *
  163. * Called by V2 PluginSupervisor (packages/core/src/plugin/supervisor.ts).
  164. * Performs two things:
  165. *
  166. * 1. Registers every skills/<name>/SKILL.md as a native Skill.Info object
  167. * via ctx.skill.transform((draft) => draft.add(info)).
  168. * V2 removed the old draft.source() directory registration; the draft API
  169. * is now { list, add, update, remove } where add() decodes plain objects:
  170. * { id, name, description?, slash?, autoinvoke?, location, content }.
  171. * See packages/core/src/plugin/skill.ts and packages/schema/src/skill.ts.
  172. * 2. Injects bootstrap context via ctx.session.hook("context"), the V2
  173. * equivalent of V1's experimental.chat.messages.transform.
  174. */
  175. async function setup(ctx) {
  176. // V1 (observed on opencode 1.18.18) also invokes default.setup, but with a
  177. // V1-shaped ctx that lacks the skill/session domains. Detect it and return
  178. // quietly — V1 is served entirely by the SuperpowersPlugin named export.
  179. if (!ctx || !ctx.skill || typeof ctx.skill.transform !== 'function' || !ctx.session || typeof ctx.session.hook !== 'function') {
  180. return;
  181. }
  182. // 1. Register skills (one transform; one draft.add per skill)
  183. try {
  184. const skills = [];
  185. if (fs.existsSync(superpowersSkillsDir)) {
  186. for (const entry of fs.readdirSync(superpowersSkillsDir, { withFileTypes: true })) {
  187. if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
  188. const skillPath = path.join(superpowersSkillsDir, entry.name, 'SKILL.md');
  189. if (!fs.existsSync(skillPath)) continue;
  190. const { frontmatter, content } = extractAndStripFrontmatter(fs.readFileSync(skillPath, 'utf8'));
  191. skills.push({
  192. id: entry.name,
  193. name: frontmatter.name || entry.name,
  194. ...(frontmatter.description ? { description: frontmatter.description } : {}),
  195. location: skillPath,
  196. content,
  197. });
  198. }
  199. }
  200. await ctx.skill.transform((draft) => {
  201. for (const skill of skills) draft.add(skill);
  202. });
  203. } catch (err) {
  204. // Never break plugin activation: one failing plugin takes down the whole
  205. // V2 generation (including provider/catalog plugins => no models in TUI).
  206. console.error('[superpowers] skill registration failed:', err);
  207. }
  208. // 2. Inject bootstrap into first user message via V2 session context hook
  209. try {
  210. await ctx.session.hook('context', async (event) => {
  211. try {
  212. const bootstrap = getBootstrapContent();
  213. if (!bootstrap || !event.messages || !event.messages.length) return;
  214. const firstUser = event.messages.find(m => m.role === 'user');
  215. if (!firstUser || !firstUser.content || !firstUser.content.length) return;
  216. if (firstUser.content.some(p => p.type === 'text' && p.text && p.text.includes('EXTREMELY_IMPORTANT'))) return;
  217. // #2160: the context event carries the sessionID directly. Skip the
  218. // controller bootstrap when this prompt belongs to a task subagent
  219. // (child) session. Skills registered above stay available to workers.
  220. if (typeof ctx.session.get === 'function' && await isChildSession(
  221. (id) => ctx.session.get({ sessionID: id }),
  222. event.sessionID,
  223. )) return;
  224. firstUser.content.unshift({ type: 'text', text: bootstrap });
  225. } catch (err) {
  226. // Never let hook callback errors break the request pipeline.
  227. console.error('[superpowers] context hook failed:', err);
  228. }
  229. });
  230. } catch (err) {
  231. console.error('[superpowers] session hook registration failed:', err);
  232. }
  233. }
  234. /**
  235. * Default Export: { id, server, setup }
  236. *
  237. * V2 PluginSupervisor reads { id, setup }.
  238. * V1 reads named export SuperpowersPlugin.
  239. * server() is exported for V1 compatibility.
  240. */
  241. export default {
  242. id: 'superpowers',
  243. server: SuperpowersPlugin,
  244. setup,
  245. };