superclawd 0.1.86 → 0.1.88

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/dist/index.js CHANGED
@@ -1,29 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
3
- import{spawn as fn,spawnSync as zr,execSync as Qr}from"node:child_process";import{fileURLToPath as dn}from"node:url";import{existsSync as mn}from"node:fs";import{resolve as Zr,dirname as eo,join as to}from"node:path";import{homedir as hn}from"node:os";import{join as te}from"node:path";import{randomBytes as wn}from"node:crypto";import{readFileSync as Sn,writeFileSync as Ge,mkdirSync as je,chmodSync as kn,existsSync as Fe}from"node:fs";var J=(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase(),S=J==="mock",q=process.env.SUPERCLAWD_MCP_API_URL||"https://mcp-api.superclawd.com",ne=process.env.SUPERCLAWD_API_URL||"https://api.superclawd.com",x=process.env.SUPERCLAWD_HOME||te(hn(),".superclawd"),re=te(x,"sessions"),ee=te(x,"config.json");function yn(e){if(!e||typeof e!="object")return{};let t=e,n=t.credentials??{...typeof t.keyId=="string"?{keyId:t.keyId}:{},...typeof t.secret=="string"?{secret:t.secret}:{},...typeof t.workspace=="string"?{workspace:t.workspace}:{}},r=t.preferences??{...typeof t.skipPermissions=="boolean"?{skipPermissions:t.skipPermissions}:{},...typeof t.notifications=="boolean"?{notifications:t.notifications}:{},...typeof t.chooseWorkspaceAtStartup=="boolean"?{chooseWorkspaceAtStartup:t.chooseWorkspaceAtStartup}:{},...typeof t.experimental=="boolean"?{experimental:t.experimental}:{}},o={};return Object.keys(n).length&&(o.credentials=n),Object.keys(r).length&&(o.preferences=r),typeof t.machineId=="string"&&(o.machineId=t.machineId),o}function Ke(){let e=A()??{};if(e.machineId)return e.machineId;let t=wn(16).toString("hex");return G({...e,machineId:t}),t}function A(){try{return yn(JSON.parse(Sn(ee,"utf8")))}catch{return null}}function G(e){je(x,{recursive:!0}),Ge(ee,`${JSON.stringify(e,null,2)}
4
- `,{mode:384});try{kn(ee,384)}catch{}}function Ye(){return A()?.preferences?.skipPermissions===!0}function En(){return A()?.preferences?.notifications===!0}function Be(){return A()?.preferences?.chooseWorkspaceAtStartup!==!1}function ke(e){let t=A()??{};G({...t,credentials:{...t.credentials,workspace:e}})}function oe(){let e=A();e?.credentials?.workspace&&G({...e,credentials:{...e.credentials,workspace:""}})}function He(){return A()?.preferences?.experimental===!0}function qe(){return A()?.preferences?.keepAwake===!0}function Je(){return A()?.preferences?.privateMemory!==!1}function Ve(){return A()?.preferences?.pipelinesMcp===!0}function Xe(e){return te(e,"config.json")}function Cn(e,t){try{je(e,{recursive:!0}),Ge(Xe(e),`${JSON.stringify(t,null,2)}
5
- `)}catch{}}function ze(e,t,n=!1){Fe(Xe(e))||Cn(e,{notifications:n?!1:En(),...t?{workspace:t}:{}})}function Qe(){Fe(ee)||G({credentials:{keyId:"",secret:"",workspace:""},preferences:{notifications:!1,skipPermissions:!1,chooseWorkspaceAtStartup:!0,privateMemory:!0}})}var Ze=1e3*60*60*24*3;function et(){if(S)return{ok:!0,session:{keyId:process.env.SUPERCLAWD_MCP_KEY||"mock-key",secret:process.env.SUPERCLAWD_MCP_SECRET||"mock-secret",workspace:process.env.SUPERCLAWD_MCP_WORKSPACE||"mock-workspace",apiUrl:q}};let e=A()?.credentials??{},t=process.env.SUPERCLAWD_MCP_KEY||e.keyId,n=process.env.SUPERCLAWD_MCP_SECRET||e.secret,r=process.env.SUPERCLAWD_MCP_WORKSPACE||e.workspace||"";return!t||!n?{ok:!1,error:"Not authenticated. Run `superclawd login` (or set SUPERCLAWD_MCP_KEY + SUPERCLAWD_MCP_SECRET)."}:{ok:!0,session:{keyId:t,secret:n,workspace:r,apiUrl:q}}}import{spawn as ye}from"node:child_process";var tt=e=>{process.env.SUPERCLAWD_DEBUG&&process.stderr.write(`keep-awake: ${e}
6
- `)};function Rn(){try{switch(process.platform){case"darwin":return ye("caffeinate",["-i","-w",String(process.pid)],{stdio:"ignore"});case"linux":return ye("systemd-inhibit",["--what=sleep:idle","--who=SuperClawd","--why=SuperClawd session running","--mode=block","cat"],{stdio:["pipe","ignore","ignore"]});case"win32":{let e=[`$p = Add-Type -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint e);' -Name P -Namespace W -PassThru;`,"$p::SetThreadExecutionState(0x80000000 -bor 0x00000001) | Out-Null;","[void][Console]::In.ReadToEnd();"].join(" ");return ye("powershell",["-NoProfile","-NonInteractive","-Command",e],{stdio:["pipe","ignore","ignore"]})}default:return null}}catch{return null}}function nt(){let e=Rn();if(!e)return tt(`unsupported platform ${process.platform}`),null;e.unref(),e.on("error",n=>tt(n.message));let t=!1;return{stop(){if(!t){t=!0;try{e.kill()}catch{}}}}}import{spawnSync as rt}from"node:child_process";import Pn from"node:readline/promises";import{readFileSync as _n,writeFileSync as vn,mkdirSync as bn}from"node:fs";import{join as An}from"node:path";var Mn=1500,ot=24*60*60*1e3,st=An(x,"update-state.json");function xn(e,t){let n=s=>s.split("-")[0].split(".").map(i=>parseInt(i,10)||0),r=n(e),o=n(t);for(let s=0;s<3;s++){let i=r[s]??0,a=o[s]??0;if(i!==a)return i>a}return!1}async function $n(e){let t=new AbortController,n=setTimeout(()=>t.abort(),Mn);try{let r=await fetch(`https://registry.npmjs.org/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:t.signal});return r.ok?(await r.json())["dist-tags"]?.latest??null:null}catch{return null}finally{clearTimeout(n)}}function it(){try{return JSON.parse(_n(st,"utf8"))}catch{return{}}}function Ln(e){try{bn(x,{recursive:!0}),vn(st,JSON.stringify(e,null,2))}catch{}}function at(e,t){let n=it();n[e]={...n[e],...t},Ln(n)}async function Ee(e,t,n=Date.now()){let r=it()[e]??{},o=r.latest??null;return(!r.checkedAt||n-r.checkedAt>=ot)&&(o=await $n(e),at(e,{latest:o??void 0,checkedAt:n})),!o||!xn(o,t)||r.dismissed===o||r.notifiedAt&&n-r.notifiedAt<ot?null:{latest:o}}function In(e){return!(e.includes("-p")||e.includes("--print"))&&!!process.stdin.isTTY}function Ce(e,t,n,r){process.stderr.write(`\u26A0 ${e} ${t} is outdated (latest ${n}). Update with: ${r}
7
- `)}async function Re(e,t,n){let r=Pn.createInterface({input:process.stdin,output:process.stderr});try{process.stderr.write(`
3
+ var Xe=["opus","fable","sonnet","haiku"],Dn={opus:"claude-opus-5-5",fable:"claude-fable-5-1",sonnet:"claude-sonnet-5-5",haiku:"claude-haiku-5-5"},Tn=/^claude-(opus|fable|sonnet|haiku)-latest$/,Un=/^claude-[a-z0-9][a-z0-9.-]{0,80}(\[1m\])?$/;function Wn(e){let t=e.trim().toLowerCase(),n=Tn.exec(t);return n?n[1]:Xe.includes(t)?t:null}function ze(e){let t={};if(!e||typeof e!="object")return t;for(let n of Xe){let r=e[n];typeof r=="string"&&Un.test(r)&&(t[n]=r)}return t}function re(e,t={}){let n=(e??"").trim();if(!n||n==="default")return null;let r=Wn(n);return r?t[r]??Dn[r]:n}import{spawn as On,spawnSync as Io,execSync as Lo}from"node:child_process";import{fileURLToPath as $n}from"node:url";import{existsSync as In,readFileSync as Do}from"node:fs";import{resolve as To,dirname as Uo,join as Wo}from"node:path";import{homedir as Fn}from"node:os";import{join as se}from"node:path";import{randomBytes as Nn}from"node:crypto";import{readFileSync as jn,writeFileSync as Qe,mkdirSync as Ze,chmodSync as Gn,existsSync as et}from"node:fs";var z=(process.env.SUPERCLAWD_BACKEND||"real").toLowerCase(),_=z==="mock",V=process.env.SUPERCLAWD_MCP_API_URL||"https://mcp-api.superclawd.com",ie=process.env.SUPERCLAWD_API_URL||"https://api.superclawd.com",D=process.env.SUPERCLAWD_HOME||se(Fn(),".superclawd"),ae=se(D,"sessions"),oe=se(D,"config.json");function Yn(e){if(!e||typeof e!="object")return{};let t=e,n=t.credentials??{...typeof t.keyId=="string"?{keyId:t.keyId}:{},...typeof t.secret=="string"?{secret:t.secret}:{},...typeof t.workspace=="string"?{workspace:t.workspace}:{}},r=t.preferences??{...typeof t.skipPermissions=="boolean"?{skipPermissions:t.skipPermissions}:{},...typeof t.notifications=="boolean"?{notifications:t.notifications}:{},...typeof t.chooseWorkspaceAtStartup=="boolean"?{chooseWorkspaceAtStartup:t.chooseWorkspaceAtStartup}:{},...typeof t.experimental=="boolean"?{experimental:t.experimental}:{}},o={};return Object.keys(n).length&&(o.credentials=n),Object.keys(r).length&&(o.preferences=r),typeof t.machineId=="string"&&(o.machineId=t.machineId),o}function tt(){let e=L()??{};if(e.machineId)return e.machineId;let t=Nn(16).toString("hex");return G({...e,machineId:t}),t}function L(){try{return Yn(JSON.parse(jn(oe,"utf8")))}catch{return null}}function G(e){Ze(D,{recursive:!0}),Qe(oe,`${JSON.stringify(e,null,2)}
4
+ `,{mode:384});try{Gn(oe,384)}catch{}}function nt(){return L()?.preferences?.skipPermissions===!0}function Kn(){return L()?.preferences?.notifications===!0}function rt(){return L()?.preferences?.chooseWorkspaceAtStartup!==!1}function Me(e){let t=L()??{};G({...t,credentials:{...t.credentials,workspace:e}})}function le(){let e=L();e?.credentials?.workspace&&G({...e,credentials:{...e.credentials,workspace:""}})}function ot(){return L()?.preferences?.experimental===!0}function st(){return L()?.preferences?.keepAwake===!0}function it(){return L()?.preferences?.privateMemory!==!1}function at(){return L()?.preferences?.pipelinesMcp===!0}function lt(e){return se(e,"config.json")}function Bn(e,t){try{Ze(e,{recursive:!0}),Qe(lt(e),`${JSON.stringify(t,null,2)}
5
+ `)}catch{}}function ct(e,t,n=!1){et(lt(e))||Bn(e,{notifications:n?!1:Kn(),...t?{workspace:t}:{}})}function ut(){et(oe)||G({credentials:{keyId:"",secret:"",workspace:""},preferences:{notifications:!1,skipPermissions:!1,chooseWorkspaceAtStartup:!0,privateMemory:!0}})}var dt=1e3*60*60*24*3;function pt(){if(_)return{ok:!0,session:{keyId:process.env.SUPERCLAWD_MCP_KEY||"mock-key",secret:process.env.SUPERCLAWD_MCP_SECRET||"mock-secret",workspace:process.env.SUPERCLAWD_MCP_WORKSPACE||"mock-workspace",apiUrl:V}};let e=L()?.credentials??{},t=process.env.SUPERCLAWD_MCP_KEY||e.keyId,n=process.env.SUPERCLAWD_MCP_SECRET||e.secret,r=process.env.SUPERCLAWD_MCP_WORKSPACE||e.workspace||"";return!t||!n?{ok:!1,error:"Not authenticated. Run `superclawd login` (or set SUPERCLAWD_MCP_KEY + SUPERCLAWD_MCP_SECRET)."}:{ok:!0,session:{keyId:t,secret:n,workspace:r,apiUrl:V}}}import{spawn as be}from"node:child_process";var ft=e=>{process.env.SUPERCLAWD_DEBUG&&process.stderr.write(`keep-awake: ${e}
6
+ `)};function Hn(){try{switch(process.platform){case"darwin":return be("caffeinate",["-i","-w",String(process.pid)],{stdio:"ignore"});case"linux":return be("systemd-inhibit",["--what=sleep:idle","--who=SuperClawd","--why=SuperClawd session running","--mode=block","cat"],{stdio:["pipe","ignore","ignore"]});case"win32":{let e=[`$p = Add-Type -MemberDefinition '[DllImport("kernel32.dll")] public static extern uint SetThreadExecutionState(uint e);' -Name P -Namespace W -PassThru;`,"$p::SetThreadExecutionState(0x80000000 -bor 0x00000001) | Out-Null;","[void][Console]::In.ReadToEnd();"].join(" ");return be("powershell",["-NoProfile","-NonInteractive","-Command",e],{stdio:["pipe","ignore","ignore"]})}default:return null}}catch{return null}}function mt(){let e=Hn();if(!e)return ft(`unsupported platform ${process.platform}`),null;e.unref(),e.on("error",n=>ft(n.message));let t=!1;return{stop(){if(!t){t=!0;try{e.kill()}catch{}}}}}import{spawnSync as gt}from"node:child_process";import qn from"node:readline/promises";import{readFileSync as Jn,writeFileSync as Vn,mkdirSync as Xn}from"node:fs";import{join as zn}from"node:path";var Qn=1500,ht=24*60*60*1e3,St=zn(D,"update-state.json");function Zn(e,t){let n=s=>s.split("-")[0].split(".").map(i=>parseInt(i,10)||0),r=n(e),o=n(t);for(let s=0;s<3;s++){let i=r[s]??0,l=o[s]??0;if(i!==l)return i>l}return!1}async function er(e){let t=new AbortController,n=setTimeout(()=>t.abort(),Qn);try{let r=await fetch(`https://registry.npmjs.org/${e}`,{headers:{accept:"application/vnd.npm.install-v1+json"},signal:t.signal});return r.ok?(await r.json())["dist-tags"]?.latest??null:null}catch{return null}finally{clearTimeout(n)}}function wt(){try{return JSON.parse(Jn(St,"utf8"))}catch{return{}}}function tr(e){try{Xn(D,{recursive:!0}),Vn(St,JSON.stringify(e,null,2))}catch{}}function yt(e,t){let n=wt();n[e]={...n[e],...t},tr(n)}async function Ae(e,t,n=Date.now()){let r=wt()[e]??{},o=r.latest??null;return(!r.checkedAt||n-r.checkedAt>=ht)&&(o=await er(e),yt(e,{latest:o??void 0,checkedAt:n})),!o||!Zn(o,t)||r.dismissed===o||r.notifiedAt&&n-r.notifiedAt<ht?null:{latest:o}}function nr(e){return!(e.includes("-p")||e.includes("--print"))&&!!process.stdin.isTTY}function xe(e,t,n,r){process.stderr.write(`\u26A0 ${e} ${t} is outdated (latest ${n}). Update with: ${r}
7
+ `)}async function $e(e,t,n){let r=qn.createInterface({input:process.stdin,output:process.stderr});try{process.stderr.write(`
8
8
  ${e} ${t} is outdated \u2014 ${n} is available.
9
- `);let o=(await r.question(" [U] Update now (default) [R] Run anyway > ")).trim().toLowerCase();return o==="r"||o==="run"?"run":"update"}finally{r.close()}}function Y(e,t){at(e,{notifiedAt:Date.now(),...t?{dismissed:t}:{}})}async function ct(e,t){if(process.env.SUPERCLAWD_NO_UPDATE||process.env.SUPERCLAWD_BACKEND==="mock"||process.env.SUPERCLAWD_UPDATED)return{};let n=await Ee("superclawd",e);if(!n)return{};let{latest:r}=n;if(!In(t))return Ce("SuperClawd",e,r,"superclawd update"),Y("superclawd"),{};if(await Re("SuperClawd",e,r)==="run")return Y("superclawd",r),{};Y("superclawd"),process.stderr.write(`Updating (npm i -g superclawd@latest) \u2026
10
- `);let s=rt("npm install -g superclawd@latest",{stdio:"inherit",shell:!0});if(s.status!==0)return process.stderr.write(`\u2717 Update failed (npm exited ${s.status??"?"}). Running ${e} for now.
11
- `),{};let i=rt("superclawd",t,{stdio:"inherit",env:{...process.env,SUPERCLAWD_UPDATED:"1"}});return i.error?(process.stderr.write(`\u2713 Updated to ${r}. Re-run your command.
12
- `),{exitCode:0}):{exitCode:i.status??0}}import{randomUUID as lt}from"node:crypto";function ut(e){let t={"content-type":"application/json","x-mcp-key-id":e.keyId,"x-mcp-secret":e.secret,"x-workspace-slug":e.workspace,"x-request-id":lt()};return process.env.SUPERCLAWD_EXPERIMENTAL==="true"&&(t["x-experimental"]="true"),t}async function se(e,t,n){let r=`${e.apiUrl}${t}`;if(n){let i=new URLSearchParams;for(let[l,c]of Object.entries(n))c!==void 0&&c!==""&&i.set(l,c);let a=i.toString();a&&(r+=(r.includes("?")?"&":"?")+a)}let o=await fetch(r,{headers:ut(e)}),s=await o.json().catch(()=>null);return{status:o.status,ok:o.ok,body:s}}async function pt(e,t,n){try{let r=await fetch(`${e}/api/prompt/workspaces`,{headers:{"content-type":"application/json","x-mcp-key-id":t,"x-mcp-secret":n,"x-request-id":lt()}}),o=await r.json().catch(()=>null);return{ok:r.ok,status:r.status,workspaces:o?.workspaces??[]}}catch{return{ok:!1,status:0,workspaces:[]}}}async function dt(e,t,n,r={}){let o=await fetch(`${e.apiUrl}${t}`,{method:"POST",headers:{...ut(e),...r},body:JSON.stringify(n)}),s=await o.json().catch(()=>null);return{status:o.status,ok:o.ok,body:s}}async function Pe(e,t){e.message("Loading your workspaces\u2026");let n=await pt(q,t.keyId,t.secret);if(!n.ok||n.workspaces.length===0)return{};let r=new Set(n.workspaces.map(i=>i.slug)),o=t.workspace&&r.has(t.workspace)?t.workspace:void 0;if(t.workspace&&!r.has(t.workspace)&&oe(),n.workspaces.length===1){let i=n.workspaces[0].slug;return i!==o&&ke(i),{workspace:i}}let s=await e.selectWorkspace(n.workspaces,{currentSlug:o,defaultSlug:o,onSetDefault:i=>ke(i)});return s===null?{cancelled:!0}:{workspace:s}}async function _e(e){if(S)return{ok:!0};try{let t=await se(e,"/api/prompt/catalog");return t.ok?{ok:!0}:t.status===401?{ok:!1,error:"Your credentials are invalid or expired. Run `superclawd login` again."}:t.status===404?{ok:!1,workspaceInvalid:!0,error:"Workspace not found. Run `superclawd` and pick a workspace."}:t.status===403?{ok:!1,workspaceInvalid:!0,error:"You are not a member of this workspace."}:t.status===502||t.status===503||t.status===504?{ok:!1,error:`SuperClawd backend is unreachable or starting up (HTTP ${t.status}). Try again in a moment.`}:{ok:!1,error:`Auth check failed (HTTP ${t.status}).`}}catch(t){return{ok:!1,error:`Cannot reach SuperClawd backend (${String(t)}).`}}}var ve=[{id:"skill-backend-001",name:"backend-api-conventions",action:"code",executionMode:"auto",description:"writing, creating, modifying, or reviewing backend API code \u2014 HTTP endpoints, routes, controllers, request handlers, or server-side validation and security",categories:[{name:"endpoint-design",instructions:["Name routes with plural nouns and kebab-case (e.g. /user-profiles).","Return RFC-7807 problem+json on errors, never bare strings.","Validate and sanitize every request body against a schema before use."]},{name:"security",instructions:["Use parameterized queries only; never string-concatenate SQL.","Rate-limit auth endpoints to 5 requests/minute per IP."]}]},{id:"skill-testing-001",name:"testing-standards",action:"test",executionMode:"auto",description:"writing or updating automated tests \u2014 unit tests, integration tests, test files, assertions, mocks, or test coverage",categories:[{name:"unit",instructions:["One behavioral assertion per test; name tests as should_<expectation>.","Mock only at process boundaries (network, fs, clock)."]}]},{id:"skill-always-001",name:"repo-foundations",action:"behave",executionMode:"always",description:"foundational rules that always apply in this repository",categories:[{name:"house-rules",instructions:["Every source file must start with a one-line header comment describing its purpose.","Prefer clarity over cleverness; match the surrounding code's style."]}]}];var ft=[{id:"guardrail-no-rm-rf",match:{tools:["Bash"],commandPatterns:["\\brm\\s+-rf\\b","\\brm\\s+-fr\\b"]},action:"deny",message:"Destructive 'rm -rf' is blocked by a workspace guardrail. Remove paths explicitly and deliberately instead."},{id:"guardrail-payments-edits",match:{tools:["Edit","Write","MultiEdit","NotebookEdit"],pathGlobs:["**/payments/**"]},action:"ask",message:"Edits under payments/ touch billing-critical code \u2014 confirm before proceeding (workspace guardrail)."}],mt=[{id:"agent-reviewer-001",name:"code-reviewer",description:"Reviews a diff for correctness and security issues. Use after writing code.",vendor:"anthropic",model:"claude-sonnet-4-6",prompt:"You are a meticulous senior code reviewer. Examine the change for correctness, security, and clarity. Report concrete findings with file:line; do not rewrite the code unless asked.",mode:"subagent",tools:{read:"allow",glob:"allow",grep:"allow",edit:"deny",write:"deny",bash:"deny",webfetch:"deny",task:"deny"},steps:null,inheritWorkspaceContext:!1},{id:"agent-orchestrator-001",name:"orchestrator",description:"Coordinates multi-step coding tasks and delegates focused work. Use when a task spans several files or steps.",vendor:"anthropic",model:"claude-sonnet-4-6",prompt:"You are an orchestrator. Break the request into concrete steps, perform the edits directly, and keep changes minimal and focused on what was asked.",mode:"subagent",tools:{read:"allow",glob:"allow",grep:"allow",edit:"allow",write:"allow",bash:"deny",webfetch:"deny",task:"allow"},steps:null,inheritWorkspaceContext:!0}],gt=[{name:"ship-checklist",description:"Run this team's pre-merge checklist.",arguments:[{name:"scope",description:"what is being shipped",required:!1}],content:`Pre-merge checklist for $ARGUMENTS:
9
+ `);let o=(await r.question(" [U] Update now (default) [R] Run anyway > ")).trim().toLowerCase();return o==="r"||o==="run"?"run":"update"}finally{r.close()}}function H(e,t){yt(e,{notifiedAt:Date.now(),...t?{dismissed:t}:{}})}async function kt(e,t){if(process.env.SUPERCLAWD_NO_UPDATE||process.env.SUPERCLAWD_BACKEND==="mock"||process.env.SUPERCLAWD_UPDATED)return{};let n=await Ae("superclawd",e);if(!n)return{};let{latest:r}=n;if(!nr(t))return xe("SuperClawd",e,r,"superclawd update"),H("superclawd"),{};if(await $e("SuperClawd",e,r)==="run")return H("superclawd",r),{};H("superclawd"),process.stderr.write(`Updating (npm i -g superclawd@latest) \u2026
10
+ `);let s=gt("npm install -g superclawd@latest",{stdio:"inherit",shell:!0});if(s.status!==0)return process.stderr.write(`\u2717 Update failed (npm exited ${s.status??"?"}). Running ${e} for now.
11
+ `),{};let i=gt("superclawd",t,{stdio:"inherit",env:{...process.env,SUPERCLAWD_UPDATED:"1"}});return i.error?(process.stderr.write(`\u2713 Updated to ${r}. Re-run your command.
12
+ `),{exitCode:0}):{exitCode:i.status??0}}import{randomUUID as Et}from"node:crypto";function Rt(e){let t={"content-type":"application/json","x-mcp-key-id":e.keyId,"x-mcp-secret":e.secret,"x-workspace-slug":e.workspace,"x-request-id":Et()};return process.env.SUPERCLAWD_EXPERIMENTAL==="true"&&(t["x-experimental"]="true"),process.env.SUPERCLAWD_MEMORY_OFF==="1"&&(t["x-superclawd-memory"]="off"),t}async function ce(e,t,n){let r=`${e.apiUrl}${t}`;if(n){let i=new URLSearchParams;for(let[u,a]of Object.entries(n))a!==void 0&&a!==""&&i.set(u,a);let l=i.toString();l&&(r+=(r.includes("?")?"&":"?")+l)}let o=await fetch(r,{headers:Rt(e)}),s=await o.json().catch(()=>null);return{status:o.status,ok:o.ok,body:s}}async function Ct(e,t,n){try{let r=await fetch(`${e}/api/prompt/workspaces`,{headers:{"content-type":"application/json","x-mcp-key-id":t,"x-mcp-secret":n,"x-request-id":Et()}}),o=await r.json().catch(()=>null);return{ok:r.ok,status:r.status,workspaces:o?.workspaces??[]}}catch{return{ok:!1,status:0,workspaces:[]}}}async function _t(e,t,n,r={}){let o=await fetch(`${e.apiUrl}${t}`,{method:"POST",headers:{...Rt(e),...r},body:JSON.stringify(n)}),s=await o.json().catch(()=>null);return{status:o.status,ok:o.ok,body:s}}async function Oe(e,t){e.message("Loading your workspaces\u2026");let n=await Ct(V,t.keyId,t.secret);if(!n.ok||n.workspaces.length===0)return{};let r=new Set(n.workspaces.map(i=>i.slug)),o=t.workspace&&r.has(t.workspace)?t.workspace:void 0;if(t.workspace&&!r.has(t.workspace)&&le(),n.workspaces.length===1){let i=n.workspaces[0].slug;return i!==o&&Me(i),{workspace:i}}let s=await e.selectWorkspace(n.workspaces,{currentSlug:o,defaultSlug:o,onSetDefault:i=>Me(i)});return s===null?{cancelled:!0}:{workspace:s}}async function Ie(e){if(_)return{ok:!0};try{let t=await ce(e,"/api/prompt/catalog");return t.ok?{ok:!0}:t.status===401?{ok:!1,kind:"credentials",error:"Your credentials are invalid or expired. Run `superclawd login` again."}:t.status===404?{ok:!1,workspaceInvalid:!0,kind:"workspace",error:"Workspace not found. Run `superclawd` and pick a workspace."}:t.status===403?{ok:!1,workspaceInvalid:!0,kind:"workspace",error:"You are not a member of this workspace."}:t.status===502||t.status===503||t.status===504?{ok:!1,kind:"unreachable",error:`SuperClawd backend is unreachable or starting up (HTTP ${t.status}). Try again in a moment.`}:{ok:!1,kind:"other",error:`Auth check failed (HTTP ${t.status}).`}}catch(t){return{ok:!1,kind:"unreachable",error:`Cannot reach SuperClawd backend (${String(t)}).`}}}var Le=[{id:"skill-backend-001",name:"backend-api-conventions",action:"code",executionMode:"auto",description:"writing, creating, modifying, or reviewing backend API code \u2014 HTTP endpoints, routes, controllers, request handlers, or server-side validation and security",categories:[{name:"endpoint-design",instructions:["Name routes with plural nouns and kebab-case (e.g. /user-profiles).","Return RFC-7807 problem+json on errors, never bare strings.","Validate and sanitize every request body against a schema before use."]},{name:"security",instructions:["Use parameterized queries only; never string-concatenate SQL.","Rate-limit auth endpoints to 5 requests/minute per IP."]}]},{id:"skill-testing-001",name:"testing-standards",action:"test",executionMode:"auto",description:"writing or updating automated tests \u2014 unit tests, integration tests, test files, assertions, mocks, or test coverage",categories:[{name:"unit",instructions:["One behavioral assertion per test; name tests as should_<expectation>.","Mock only at process boundaries (network, fs, clock)."]}]},{id:"skill-always-001",name:"repo-foundations",action:"behave",executionMode:"always",description:"foundational rules that always apply in this repository",categories:[{name:"house-rules",instructions:["Every source file must start with a one-line header comment describing its purpose.","Prefer clarity over cleverness; match the surrounding code's style."]}]}];var vt=[{id:"guardrail-no-rm-rf",match:{tools:["Bash"],commandPatterns:["\\brm\\s+-rf\\b","\\brm\\s+-fr\\b"]},action:"deny",message:"Destructive 'rm -rf' is blocked by a workspace guardrail. Remove paths explicitly and deliberately instead."},{id:"guardrail-payments-edits",match:{tools:["Edit","Write","MultiEdit","NotebookEdit"],pathGlobs:["**/payments/**"]},action:"ask",message:"Edits under payments/ touch billing-critical code \u2014 confirm before proceeding (workspace guardrail)."}],Pt=[{id:"agent-reviewer-001",name:"code-reviewer",description:"Reviews a diff for correctness and security issues. Use after writing code.",vendor:"anthropic",model:"claude-sonnet-4-6",prompt:"You are a meticulous senior code reviewer. Examine the change for correctness, security, and clarity. Report concrete findings with file:line; do not rewrite the code unless asked.",mode:"subagent",tools:{read:"allow",glob:"allow",grep:"allow",edit:"deny",write:"deny",bash:"deny",webfetch:"deny",task:"deny"},steps:null,inheritWorkspaceContext:!1},{id:"agent-orchestrator-001",name:"orchestrator",description:"Coordinates multi-step coding tasks and delegates focused work. Use when a task spans several files or steps.",vendor:"anthropic",model:"claude-sonnet-4-6",prompt:"You are an orchestrator. Break the request into concrete steps, perform the edits directly, and keep changes minimal and focused on what was asked.",mode:"subagent",tools:{read:"allow",glob:"allow",grep:"allow",edit:"allow",write:"allow",bash:"deny",webfetch:"deny",task:"allow"},steps:null,inheritWorkspaceContext:!0}],Mt=[{name:"ship-checklist",description:"Run this team's pre-merge checklist.",arguments:[{name:"scope",description:"what is being shipped",required:!1}],content:`Pre-merge checklist for $ARGUMENTS:
13
13
  1. Tests pass and cover new behavior.
14
14
  2. No secrets or debug logging left in.
15
15
  3. Public APIs documented.
16
- 4. Changelog updated.`}],ht=[{name:"error-codes",description:"Canonical list of this platform's error codes.",content:`E1001 invalid_input
16
+ 4. Changelog updated.`}],bt=[{name:"error-codes",description:"Canonical list of this platform's error codes.",content:`E1001 invalid_input
17
17
  E1002 unauthorized
18
18
  E1003 rate_limited
19
- E2001 upstream_unavailable`}];var wt=[{id:"workflow-deploy-001",name:"production-deploy",description:"deploying to production, cutting a release, or shipping to prod",itemCount:6,content:`Production deploy workflow:
19
+ E2001 upstream_unavailable`}];var At=[{id:"workflow-deploy-001",name:"production-deploy",description:"deploying to production, cutting a release, or shipping to prod",itemCount:6,content:`Production deploy workflow:
20
20
  1. Confirm CI is green on main.
21
21
  2. Bump version + update changelog.
22
22
  3. Tag the release.
23
23
  4. Run db migrations.
24
24
  5. Deploy and watch error rate for 10m.
25
- 6. Announce in #releases.`}];function Dn(){let e=ve.filter(n=>n.executionMode==="auto").map(n=>({id:n.id,name:n.name,action:n.action,executionMode:n.executionMode,description:n.description,userInvocable:n.userInvocable})),t=ve.filter(n=>n.executionMode==="always").flatMap(n=>n.categories.flatMap(r=>r.instructions)).map((n,r)=>`${r+1}. ${n}`).join(`
26
- `);return{skills:e,agents:mt,agentTeams:[],commands:gt.map(({name:n,description:r,arguments:o,team:s})=>({name:n,description:r,arguments:o,team:s??null})),resources:ht.map(({name:n,description:r})=>({name:n,description:r})),workflows:wt.map(({id:n,name:r,description:o})=>({id:n,name:r,description:o})),mcpServers:[],guardrails:ft,policyGuardrails:[],foundational:{text:t},teamMemoryEnabled:!0,repoMemoryEnabled:!0,agentMemoryEnabled:!0}}async function St(e){if(S)return Dn();let t=await se(e,"/api/prompt/catalog",{repoFingerprint:process.env.SUPERCLAWD_REPO_FINGERPRINT});if(!t.ok||!t.body)throw new Error(`Failed to fetch catalog (HTTP ${t.status}).`);return{skills:(t.body.skills??[]).filter(r=>r.executionMode==="auto"),agents:(t.body.agents??[]).map(r=>({...r,learnedMemories:r.learnedMemories??[]})),agentTeams:(t.body.agentTeams??[]).map(r=>({...r,linkedWorkflows:r.linkedWorkflows??[]})),commands:t.body.commands??[],resources:t.body.resources??[],workflows:t.body.workflows??[],mcpServers:t.body.mcpServers??[],guardrails:t.body.guardrails??[],policyGuardrails:t.body.policyGuardrails??[],foundational:{text:t.body.foundational?.text??""},teamMemoryEnabled:t.body.teamMemoryEnabled??!0,repoMemoryEnabled:t.body.repoMemoryEnabled??!0,agentMemoryEnabled:t.body.agentMemoryEnabled??!0}}async function kt(e,t,n=!0){if(S)return!0;try{return(await dt(e,"/api/prompt/inspector",{ide:!0,platform:"claude-code",llm_model:"claude",x_session_request_id:t,notify_on_checkpoint:n,enable_session_files:!1},{"x-session-request-id":t})).ok}catch{return!1}}import{mkdirSync as Pr,writeFileSync as _r,chmodSync as vr}from"node:fs";import{dirname as Ht,join as qt}from"node:path";function $(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||"skill"}function Tn(e){return`${(e.description??e.name).trim().replace(/\.$/,"")}.`}function On(e){return`# ${e.name} (SuperClawd-managed)
25
+ 6. Announce in #releases.`}];function rr(){let e=Le.filter(n=>n.executionMode==="auto").map(n=>({id:n.id,name:n.name,action:n.action,executionMode:n.executionMode,description:n.description,userInvocable:n.userInvocable})),t=Le.filter(n=>n.executionMode==="always").flatMap(n=>n.categories.flatMap(r=>r.instructions)).map((n,r)=>`${r+1}. ${n}`).join(`
26
+ `);return{skills:e,agents:Pt,agentTeams:[],commands:Mt.map(({name:n,description:r,arguments:o,team:s})=>({name:n,description:r,arguments:o,team:s??null})),resources:bt.map(({name:n,description:r})=>({name:n,description:r})),workflows:At.map(({id:n,name:r,description:o})=>({id:n,name:r,description:o})),mcpServers:[],guardrails:vt,policyGuardrails:[],foundational:{text:t},teamMemoryEnabled:!0,repoMemoryEnabled:!0,agentMemoryEnabled:!0}}async function De(e){if(_)return rr();let t=await ce(e,"/api/prompt/catalog",{repoFingerprint:process.env.SUPERCLAWD_REPO_FINGERPRINT});if(!t.ok||!t.body)throw new Error(`Failed to fetch catalog (HTTP ${t.status}).`);return{skills:(t.body.skills??[]).filter(r=>r.executionMode==="auto"),agents:(t.body.agents??[]).map(r=>({...r,learnedMemories:r.learnedMemories??[]})),agentTeams:(t.body.agentTeams??[]).map(r=>({...r,linkedWorkflows:r.linkedWorkflows??[]})),commands:t.body.commands??[],resources:t.body.resources??[],workflows:t.body.workflows??[],mcpServers:t.body.mcpServers??[],guardrails:t.body.guardrails??[],policyGuardrails:t.body.policyGuardrails??[],foundational:{text:t.body.foundational?.text??""},teamMemoryEnabled:t.body.teamMemoryEnabled??!0,repoMemoryEnabled:t.body.repoMemoryEnabled??!0,agentMemoryEnabled:t.body.agentMemoryEnabled??!0,modelFamilies:ze(t.body.modelFamilies)}}var or=["PRIORITY RULE: The user's request always takes priority over the team memories","MORE MEMORIES (titles only"];function xt(e){let t=e.foundational.text??"",n=or.map(r=>t.indexOf(r)).filter(r=>r>=0).reduce((r,o)=>Math.min(r,o),Number.POSITIVE_INFINITY);return{...e,foundational:{...e.foundational,text:Number.isFinite(n)?t.slice(0,n).trimEnd():t},agents:e.agents.map(r=>({...r,learnedMemories:[]})),teamMemoryEnabled:!1,repoMemoryEnabled:!1,agentMemoryEnabled:!1}}async function $t(e,t,n=!0){if(_)return!0;try{return(await _t(e,"/api/prompt/inspector",{ide:!0,platform:"claude-code",llm_model:"claude",x_session_request_id:t,notify_on_checkpoint:n,enable_session_files:!1},{"x-session-request-id":t})).ok}catch{return!1}}import{mkdirSync as to,writeFileSync as no,chmodSync as ro}from"node:fs";import{dirname as pn,join as fn}from"node:path";function U(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,64)||"skill"}function sr(e){return`${(e.description??e.name).trim().replace(/\.$/,"")}.`}function ir(e){return`# ${e.name} (SuperClawd-managed)
27
27
 
28
28
  The authoritative instructions for this skill are managed in SuperClawd and
29
29
  are **not** included here. You must fetch them before acting.
@@ -37,13 +37,13 @@ are **not** included here. You must fetch them before acting.
37
37
 
38
38
  Do not proceed using only this description \u2014 it is a pointer, not the rules.
39
39
  If \`get_directives\` returns an error, tell the user and stop.
40
- `}function Un(e){let t=Tn(e).replace(/"/g,'\\"'),n=e.userInvocable??!1;return`---
41
- name: ${$(e.name)}
40
+ `}function ar(e){let t=sr(e).replace(/"/g,'\\"'),n=e.userInvocable??!1;return`---
41
+ name: ${U(e.name)}
42
42
  description: "${t}"
43
43
  user-invocable: ${n}
44
44
  ---
45
45
 
46
- `}function yt(e,t){let n=new Set(t),r=[];for(let o of e){let s=$(o.name),i=2;for(;n.has(s);)s=`${$(o.name)}-${i++}`;n.add(s),r.push({relPath:`skills/${s}/SKILL.md`,content:Un(o)+On(o)})}return r}var Wn=`SUPERCLAWD \u2014 operating manual (always in effect):
46
+ `}function Ot(e,t){let n=new Set(t),r=[];for(let o of e){let s=U(o.name),i=2;for(;n.has(s);)s=`${U(o.name)}-${i++}`;n.add(s),r.push({relPath:`skills/${s}/SKILL.md`,content:ar(o)+ir(o)})}return r}var It=`SUPERCLAWD \u2014 operating manual (always in effect):
47
47
  - The ALWAYS rules below are ALREADY LOADED and active for this entire session.
48
48
  Apply them directly to all work. Do NOT call any tool to fetch them \u2014 you
49
49
  already have them in full.
@@ -52,8 +52,7 @@ user-invocable: ${n}
52
52
  the \`get_directives\` tool with that file's skillId (a UUID) BEFORE acting,
53
53
  and apply what it returns. Those skill files are pointers, not the rules.
54
54
  - Only call \`get_directives\` with a UUID skillId taken from an activated skill
55
- file. Never call it for the ALWAYS rules, and never pass a skill name.
56
- - MEMORY: when the user states something durable \u2014 a fact, preference, or standing
55
+ file. Never call it for the ALWAYS rules, and never pass a skill name.`,lr=`- MEMORY: when the user states something durable \u2014 a fact, preference, or standing
57
56
  rule, ESPECIALLY phrased as "remember\u2026", "from now on", "always", or "going
58
57
  forward" \u2014 call \`record_memory\` RIGHT AWAY to persist it (silently; it picks the
59
58
  scope on its own: the user's PRIVATE memory, the TEAM's, or the REPO's). Acknowledging
@@ -66,38 +65,39 @@ user-invocable: ${n}
66
65
  \`record_memory\` for it; never claim a preference is "already" a saved convention, or
67
66
  that it "will persist", unless you just recorded it (or confirmed it via
68
67
  \`list_memories\`). A background pass also captures durable facts at session end as a
69
- backstop \u2014 but never rely on it for an explicit request; record that now.`;function be(e){let t=Wn,n=(e||"").trim();return n&&(t+=`
68
+ backstop \u2014 but never rely on it for an explicit request; record that now.`;function Te(e){let t=process.env.SUPERCLAWD_MEMORY_OFF==="1"?It:`${It}
69
+ ${lr}`,n=(e||"").trim();return n&&(t+=`
70
70
 
71
71
  ALWAYS \u2014 foundational rules (already loaded & active for this whole session; apply directly, never fetch):
72
- ${n}`),t}function Nn(e){return e.inheritWorkspaceContext!==!1}function Gn(e){return be(e).trim()}function jn(e){return`You are SuperClawd agent \`${e.id}\`. SuperClawd automatically remembers the durable, reusable lessons from your work and applies them on your future runs \u2014 you do NOT need to save anything yourself.`}function Fn(e){let t=(e.learnedMemories??[]).filter(r=>r.trim());return t.length===0?"":`AGENT MEMORY \u2014 lessons you've learned in past work (apply by default; a more specific instruction wins):
72
+ ${n}`),t}function cr(e){return e.inheritWorkspaceContext!==!1}function ur(e){return Te(e).trim()}function dr(e){return process.env.SUPERCLAWD_MEMORY_OFF==="1"?`You are SuperClawd agent \`${e.id}\`.`:`You are SuperClawd agent \`${e.id}\`. SuperClawd automatically remembers the durable, reusable lessons from your work and applies them on your future runs \u2014 you do NOT need to save anything yourself.`}function pr(e){let t=(e.learnedMemories??[]).filter(r=>r.trim());return t.length===0?"":`AGENT MEMORY \u2014 lessons you've learned in past work (apply by default; a more specific instruction wins):
73
73
  `+t.map(r=>`- ${r.trim()}`).join(`
74
- `)}function Ae(e,t){let n=[];if(Nn(e)){let o=Gn(t);o&&n.push(o)}n.push(jn(e));let r=Fn(e);return r&&n.push(r),n.push(e.prompt),n.join(`
74
+ `)}function Ue(e,t){let n=[];if(cr(e)){let o=ur(t);o&&n.push(o)}n.push(dr(e));let r=pr(e);return r&&n.push(r),n.push(e.prompt),n.join(`
75
75
 
76
76
  ---
77
77
 
78
- `)}var V="superclawd",ie="core",ae=`mcp__plugin_${V}_${ie}__`,Me=e=>`${ae}${e}`,Et=`${ae}*`,Kn=`${V}:`,ce=e=>`${Kn}${e}`;var le={read:"Read",glob:"Glob",grep:"Grep",edit:"Edit",write:"Write",bash:"Bash",webfetch:"WebFetch",task:"Task"};function Yn(e){return e==="allow"||e==="ask"||e===!0}var xe=Me("get_workflow"),Ct=Me("get_directives"),Bn=e=>ce(e);function Hn(e,t=!1,n=!1,r=!1){let o=e.tools??{},s=Object.keys(le).filter(i=>Yn(o[i])).map(i=>le[i]);return t&&!s.includes(le.task)&&s.push(le.task),n&&!s.includes(xe)&&s.push(xe),r&&!s.includes(Ct)&&s.push(Ct),s}function qn(e,t=!1,n=!1){let r=[`name: ${$(e.name)}`,`description: "${(e.description??e.name).replace(/"/g,'\\"')}"`];e.vendor==="anthropic"&&e.model&&e.model!=="default"&&r.push(`model: ${JSON.stringify(e.model)}`);let o=(e.skills?.length??0)>0,s=Hn(e,t,n,o);return s.length&&r.push(`tools: ${s.join(", ")}`),e.skills?.length&&r.push(`skills: ${e.skills.join(", ")}`),`---
79
- ${r.join(`
78
+ `)}var X="superclawd",ue="core",de=`mcp__plugin_${X}_${ue}__`,We=e=>`${de}${e}`,Lt=`${de}*`,fr=`${X}:`,pe=e=>`${fr}${e}`,Dt=e=>`mcp__plugin_${X}_${e}`;var fe={read:"Read",glob:"Glob",grep:"Grep",edit:"Edit",write:"Write",bash:"Bash",webfetch:"WebFetch",task:"Task"};function mr(e){return e==="allow"||e==="ask"||e===!0}var Fe=We("get_workflow"),Tt=We("get_directives"),gr=e=>pe(e);function hr(e,t=!1,n=!1,r=!1,o=[]){let s=e.tools??{},i=Object.keys(fe).filter(l=>mr(s[l])).map(l=>fe[l]);t&&!i.includes(fe.task)&&i.push(fe.task),n&&!i.includes(Fe)&&i.push(Fe),r&&!i.includes(Tt)&&i.push(Tt);for(let l of o)i.includes(l)||i.push(l);return i}function Sr(e,t,n=!1,r=!1,o=[],s={}){let i=[`name: ${t}`,`description: "${(e.description??e.name).replace(/"/g,'\\"')}"`],l=e.vendor==="anthropic"?re(e.model,s):null;l&&i.push(`model: ${JSON.stringify(l)}`);let u=(e.skills?.length??0)>0,a=hr(e,n,r,u,o);return a.length&&i.push(`tools: ${a.join(", ")}`),e.skills?.length&&i.push(`skills: ${e.skills.join(", ")}`),`---
79
+ ${i.join(`
80
80
  `)}
81
81
  ---
82
82
 
83
- `}function ue(e){let t=new Set;return e.map(n=>{let r=$(n.name),o=2;for(;t.has(r);)r=`${$(n.name)}-${o++}`;return t.add(r),{slug:r,agent:n}})}function Rt(e){let t={};for(let{slug:n,agent:r}of ue(e))t[n]=r.id;return t}function Jn(e,t){let n=t.map(s=>`- \`${Bn(s.slug)}\` \u2014 ${s.description??s.slug}`).join(`
83
+ `}function me(e){let t=new Set;return e.map(n=>{let r=U(n.name),o=2;for(;t.has(r);)r=`${U(n.name)}-${o++}`;return t.add(r),{slug:r,agent:n}})}function Ut(e){let t={};for(let{slug:n,agent:r}of me(e))t[n]=r.id;return t}function wr(e,t){let n=t.map(s=>`- \`${gr(s.slug)}\` \u2014 ${s.description??s.slug}`).join(`
84
84
  `),r=`## Team Lead \u2014 ${e.name}
85
85
  You lead the **${e.name}** agent team. When given a task, decompose it and **delegate to your team members via the Agent tool** \u2014 then **synthesize** their outputs into one consolidated answer. Delegate using the EXACT agent name shown below (including the \`superclawd:\` prefix). Call the Agent tool and use the result it returns directly \u2014 it returns the member's full output when that member finishes. To run members in parallel, issue multiple Agent calls in a single step; they run concurrently and each returns its own result. Do NOT run members as background agents, and NEVER poll for a "\`.done\`"/completion file or run a \`sleep\`/\`until\` wait loop \u2014 there is no such marker, so it will hang forever; just read the Agent tool's returned result. Your members:
86
86
  ${n}`,o=e.linkedWorkflows??[];if(o.length){let s=o.map(i=>`- ${i.name} (workflowId: ${i.id}) \u2014 ${i.description??""}`).join(`
87
87
  `);r+=`
88
88
 
89
89
  ### Linked workflows
90
- You **MAY** run any of these linked workflows if (and only if) one is relevant to the task \u2014 there is **no obligation** to run any. To run one, call the \`${xe}\` MCP tool with its \`workflowId\`, then follow the returned steps in order.
91
- ${s}`}return r}function Pt(e,t={},n=[]){let r=t.foundationalText??"",o=ue(e),s=new Map;for(let{slug:l,agent:c}of o)s.set(c.id,{slug:l,description:c.description});let i=new Map,a=new Set;for(let l of n){let c=l.memberAgentIds.map(E=>s.get(E)).filter(E=>!!E),g=Jn(l,c),y=i.get(l.leadAgentId)??[];y.push(g),i.set(l.leadAgentId,y),l.linkedWorkflows?.length&&a.add(l.leadAgentId)}return o.map(({slug:l,agent:c})=>{let g=i.get(c.id),y=!!g&&g.length>0,E=a.has(c.id),f=y?[Ae(c,r),...g].join(`
90
+ You **MAY** run any of these linked workflows if (and only if) one is relevant to the task \u2014 there is **no obligation** to run any. To run one, call the \`${Fe}\` MCP tool with its \`workflowId\`, then follow the returned steps in order.
91
+ ${s}`}return r}function Wt(e,t={},n=[]){let r=t.foundationalText??"",o=me(e),s=new Map;for(let{slug:u,agent:a}of o)s.set(a.id,{slug:u,description:a.description});let i=new Map,l=new Set;for(let u of n){let a=u.memberAgentIds.map(y=>s.get(y)).filter(y=>!!y),f=wr(u,a),w=i.get(u.leadAgentId)??[];w.push(f),i.set(u.leadAgentId,w),u.linkedWorkflows?.length&&l.add(u.leadAgentId)}return o.map(({slug:u,agent:a})=>{let f=i.get(a.id),w=!!f&&f.length>0,y=l.has(a.id),b=w?[Ue(a,r),...f].join(`
92
92
 
93
93
  ---
94
94
 
95
- `):Ae(c,r);return{relPath:`agents/${l}.md`,content:qn(c,y,E)+f}})}function Vn(e){return e.arguments.length?e.arguments.map(t=>t.required?`<${t.name}>`:`[${t.name}]`).join(" "):""}function Xn(e){let t=[`description: "${e.description.replace(/"/g,'\\"')}"`],n=Vn(e);return n&&t.push(`argument-hint: ${n}`),`---
95
+ `):Ue(a,r);return{relPath:`agents/${u}.md`,content:Sr(a,u,w,y,t.extraTools,t.modelFamilies)+b}})}function yr(e){return e.arguments.length?e.arguments.map(t=>t.required?`<${t.name}>`:`[${t.name}]`).join(" "):""}function kr(e){let t=[`description: "${e.description.replace(/"/g,'\\"')}"`],n=yr(e);return n&&t.push(`argument-hint: ${n}`),`---
96
96
  ${t.join(`
97
97
  `)}
98
98
  ---
99
99
 
100
- `}function zn(e,t){let n=`This is the SuperClawd command **${e.name}**. Its content is managed in
100
+ `}function Er(e,t){let n=`This is the SuperClawd command **${e.name}**. Its content is managed in
101
101
  SuperClawd and fetched on use.
102
102
 
103
103
  **REQUIRED \u2014 do this now:**
@@ -107,11 +107,11 @@ SuperClawd and fetched on use.
107
107
 
108
108
  Do not improvise the command from this description.
109
109
  `,r=e.team;if(r&&t.has(r.leadAgentId)){let o=t.get(r.leadAgentId);return`## Team: ${r.name}
110
- Run this command WITH the **${r.name}** agent team. Delegate the task to its lead \`${ce(o)}\` via the Agent tool \u2014 the lead will decompose it, fan out to its members, and synthesize \u2014 then return the lead's result. Do the work through the team rather than alone. Call the Agent tool and use the result it returns directly; do NOT run the lead as a background agent or poll for a "\`.done\`"/completion file (there is none \u2014 it will hang).
110
+ Run this command WITH the **${r.name}** agent team. Delegate the task to its lead \`${pe(o)}\` via the Agent tool \u2014 the lead will decompose it, fan out to its members, and synthesize \u2014 then return the lead's result. Do the work through the team rather than alone. Call the Agent tool and use the result it returns directly; do NOT run the lead as a background agent or poll for a "\`.done\`"/completion file (there is none \u2014 it will hang).
111
111
 
112
112
  ---
113
113
 
114
- `+n}return n}function _t(e,t){let n=new Map(ue(t).map(({slug:s,agent:i})=>[i.id,s])),r=new Set,o=[];for(let s of e){let i=$(s.name),a=2;for(;r.has(i);)i=`${$(s.name)}-${a++}`;r.add(i),o.push({relPath:`commands/${i}.md`,content:Xn(s)+zn(s,n)})}return o}function Qn(e,t){let n=e.mode==="reference",r=(e.description??e.name).trim().replace(/\.$/,""),o=(n?`${r}. Read the '${e.name}' SuperClawd reference workflow to understand how this works (do not execute it).`:`${r}. Runs the '${e.name}' SuperClawd workflow.`).replace(/"/g,'\\"'),s=n?`# ${e.name} (SuperClawd workflow \u2014 REFERENCE)
114
+ `+n}return n}function Ft(e,t){let n=new Map(me(t).map(({slug:s,agent:i})=>[i.id,s])),r=new Set,o=[];for(let s of e){let i=U(s.name),l=2;for(;r.has(i);)i=`${U(s.name)}-${l++}`;r.add(i),o.push({relPath:`commands/${i}.md`,content:kr(s)+Er(s,n)})}return o}function Rr(e,t){let n=e.mode==="reference",r=(e.description??e.name).trim().replace(/\.$/,""),o=(n?`${r}. Read the '${e.name}' SuperClawd reference workflow to understand how this works (do not execute it).`:`${r}. Runs the '${e.name}' SuperClawd workflow.`).replace(/"/g,'\\"'),s=n?`# ${e.name} (SuperClawd workflow \u2014 REFERENCE)
115
115
 
116
116
  This is a **structured explanation** of how a system or flow works \u2014 NOT a procedure to run.
117
117
 
@@ -135,7 +135,7 @@ description: "${o}"
135
135
  user-invocable: false
136
136
  ---
137
137
 
138
- ${s}`}}function Zn(e,t){let n=e.mode==="reference",r=n?`Read the SuperClawd reference workflow **${e.name}** to understand how it works:
138
+ ${s}`}}function Cr(e,t){let n=e.mode==="reference",r=n?`Read the SuperClawd reference workflow **${e.name}** to understand how it works:
139
139
 
140
140
  1. Call the \`get_workflow\` tool with \`workflowId\`: \`${e.id}\`.
141
141
  2. **Read** the returned steps to understand the flow \u2014 do not execute them.
@@ -147,7 +147,7 @@ ${s}`}}function Zn(e,t){let n=e.mode==="reference",r=n?`Read the SuperClawd refe
147
147
  description: "${o}"
148
148
  ---
149
149
 
150
- ${r}`}}function vt(e){let t=new Set,n=[];for(let r of e){let o=$(r.name),s=2;for(;t.has(o);)o=`${$(r.name)}-${s++}`;t.add(o),n.push(Qn(r,o)),r.userInvocable===!0&&n.push(Zn(r,o))}return n}var er=`---
150
+ ${r}`}}function Nt(e){let t=new Set,n=[];for(let r of e){let o=U(r.name),s=2;for(;t.has(o);)o=`${U(r.name)}-${s++}`;t.add(o),n.push(Rr(r,o)),r.userInvocable===!0&&n.push(Cr(r,o))}return n}var _r=`---
151
151
  description: Audit this session against your active SuperClawd directives.
152
152
  ---
153
153
 
@@ -159,7 +159,7 @@ Audit the work done so far in this session against your active SuperClawd direct
159
159
  4. Flag anything relevant you may have skipped \u2014 and if so, fetch and apply/run it now.
160
160
 
161
161
  Be concise; this is a compliance check, not a code review.
162
- `,tr=`---
162
+ `,vr=`---
163
163
  description: Show SuperClawd service status, workspace info, and credit balance.
164
164
  ---
165
165
 
@@ -170,14 +170,14 @@ Give me a concise SuperClawd status overview. Call these tools and summarize the
170
170
  3. \`check_balance\` \u2014 current credit balance.
171
171
 
172
172
  Present it as a tidy summary; do not take any other action.
173
- `,nr=`---
173
+ `,Pr=`---
174
174
  description: Toggle SuperClawd notifications for this session.
175
175
  ---
176
176
 
177
177
  The user wants to flip SuperClawd notifications for this session.
178
178
 
179
179
  Call the \`notifications\` tool (no arguments \u2014 it toggles the current on/off state), then report the resulting state in one short line. Do not take any other action.
180
- `,rr=`---
180
+ `,Mr=`---
181
181
  description: Apply maximum extended thinking (ultrathink) to the work at hand.
182
182
  argument-hint: "[task or question]"
183
183
  ---
@@ -185,60 +185,65 @@ argument-hint: "[task or question]"
185
185
  To perform this work, please ultrathink \u2014 reason as deeply and carefully as you can before acting. Surface edge cases, weigh alternatives, and check your assumptions.
186
186
 
187
187
  $ARGUMENTS
188
- `;function bt(){return[{relPath:"commands/audit-work.md",content:er},{relPath:"commands/status.md",content:tr},{relPath:"commands/notifications.md",content:nr},{relPath:"commands/ultrathink.md",content:rr}]}import{existsSync as or,readFileSync as sr,writeFileSync as ir,chmodSync as ar,mkdirSync as cr}from"node:fs";import{execSync as lr}from"node:child_process";import{dirname as ur,join as At}from"node:path";function $t(e){let t="hooks/foundational-fallback.txt",n=`${e.pluginDir}/${t}`,r=`${e.pluginDir}/hooks/reminder-context.txt`,o=`${e.pluginDir}/stepcount`,s=h=>({type:"command",command:`node "${e.helperPath}" ${h}`}),i=h=>({...s(h),async:!0}),a={SessionStart:[{hooks:[s(`foundational "${n}" SessionStart`)]}],Notification:[{matcher:"permission_prompt|elicitation_dialog|elicitation_complete|elicitation_response|auth_success",hooks:[i(`notify-local attention "${e.launchId}"`),i(`notify attention "${e.launchId}"`)]}],Stop:[{hooks:[i(`notify-local stop "${e.launchId}"`)]}],SessionEnd:[{hooks:[i(`notify completion "${e.launchId}"`)]}]},l=[{relPath:t,content:e.foundational.text??""}],c=Number(process.env.SUPERCLAWD_REMIND_EVERY??8),g=process.env.SUPERCLAWD_REPO_MEMORY!=="0",y=process.env.SUPERCLAWD_AGENT_MEMORY!=="0",E=process.env.SUPERCLAWD_PRIVATE_MEMORY==="1",f=process.env.SUPERCLAWD_NO_CAPTURE==="1",d=!f&&!!process.env.SUPERCLAWD_REPO_FINGERPRINT&&(g||E),p=(e.foundational.text??"").trim(),P=p?`REMINDER \u2014 these SuperClawd always-rules remain in effect:
189
- ${p}`:"";if(c>0&&P&&(a.PostToolUse=[{matcher:"*",hooks:[s(`remind "${r}" "${o}"`)]}],l.push({relPath:"hooks/reminder-context.txt",content:P})),d){let h={hooks:[i(`capture "${e.launchId}"`)]};a.Stop.push(h),a.SessionEnd.push(h)}let u=e.agents??[];if(!f&&y&&u.length){let h="hooks/agent-map.json",m=`${e.pluginDir}/${h}`;l.push({relPath:h,content:JSON.stringify(Rt(u))}),a.SubagentStop=[{hooks:[i(`capture-agent "${m}" "${e.launchId}"`)]}]}let w=[];if(e.gate&&w.push({matcher:`${ae}.*`,hooks:[s("gate")]}),e.guardrails?.length){let h="hooks/guardrails.json",m=`${e.pluginDir}/${h}`;l.push({relPath:h,content:JSON.stringify(e.guardrails,null,2)}),w.push({matcher:"*",hooks:[s(`guardrails "${m}"`)]})}if(e.policyGuardrails?.length){let h="hooks/policy-guardrails.json",m=`${e.pluginDir}/${h}`;l.push({relPath:h,content:JSON.stringify(e.policyGuardrails,null,2)}),w.push({matcher:"Bash",hooks:[s(`policy "${m}"`)]})}return process.env.SUPERCLAWD_AUTO_RETRIEVE!=="0"&&(a.UserPromptSubmit=[{hooks:[s("retrieve prompt")]}],w.push({matcher:"Read",hooks:[s("retrieve file")]})),w.length&&(a.PreToolUse=w),l.push({relPath:"hooks/hooks.json",content:JSON.stringify({hooks:a},null,2)}),l}var Mt="# superclawd-report-commit";function xt(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function Lt(e){let{cwd:t,helperPath:n,env:r}=e,o="";try{let c=lr("git rev-parse --git-path hooks",{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();c&&(o=c.startsWith("/")?c:At(t,c))}catch{return{installed:!1,reason:"not a git repo"}}if(!o)return{installed:!1,reason:"no hooks dir"};let s=At(o,"post-commit");if(or(s)){let c="";try{c=sr(s,"utf8")}catch{return{installed:!1,reason:"post-commit unreadable; skipped"}}if(!c.includes(Mt))return{installed:!1,reason:"existing user post-commit hook; skipped"}}let a=["SUPERCLAWD_BACKEND","SUPERCLAWD_MCP_API_URL","SUPERCLAWD_REPO_FINGERPRINT","SUPERCLAWD_MCP_KEY","SUPERCLAWD_MCP_SECRET","SUPERCLAWD_MCP_WORKSPACE","NODE_EXTRA_CA_CERTS","SUPERCLAWD_HOME","SUPERCLAWD_CLAUDE_BIN","SUPERCLAWD_POLICY_MODEL"].filter(c=>r[c]!==void 0&&r[c]!=="").map(c=>`export ${c}=${xt(r[c])}`).join(`
190
- `),l=`#!/bin/sh
191
- ${Mt}
188
+ `;function jt(){return[{relPath:"commands/audit-work.md",content:_r},{relPath:"commands/status.md",content:vr},{relPath:"commands/notifications.md",content:Pr},{relPath:"commands/ultrathink.md",content:Mr}]}import{existsSync as br,readFileSync as Ar,writeFileSync as xr,chmodSync as $r,mkdirSync as Or}from"node:fs";import{execSync as Ir}from"node:child_process";import{dirname as Lr,join as Gt}from"node:path";function Bt(e){let t="hooks/foundational-fallback.txt",n=`${e.pluginDir}/${t}`,r=`${e.pluginDir}/hooks/reminder-context.txt`,o=`${e.pluginDir}/stepcount`,s=S=>({type:"command",command:`node "${e.helperPath}" ${S}`}),i=S=>({...s(S),async:!0}),l={SessionStart:[{hooks:[s(`foundational "${n}" SessionStart`)]}],Notification:[{matcher:"permission_prompt|elicitation_dialog|elicitation_complete|elicitation_response|auth_success",hooks:[i(`notify-local attention "${e.launchId}"`),i(`notify attention "${e.launchId}"`)]}],Stop:[{hooks:[i(`notify-local stop "${e.launchId}"`)]}],SessionEnd:[{hooks:[i(`notify completion "${e.launchId}"`)]}]},u=[{relPath:t,content:e.foundational.text??""}],a=Number(process.env.SUPERCLAWD_REMIND_EVERY??8),f=process.env.SUPERCLAWD_REPO_MEMORY!=="0",w=process.env.SUPERCLAWD_AGENT_MEMORY!=="0",y=process.env.SUPERCLAWD_PRIVATE_MEMORY==="1",b=process.env.SUPERCLAWD_NO_CAPTURE==="1",P=!b&&!!process.env.SUPERCLAWD_REPO_FINGERPRINT&&(f||y),E=(e.foundational.text??"").trim(),h=E?`REMINDER \u2014 these SuperClawd always-rules remain in effect:
189
+ ${E}`:"";if(a>0&&h&&(l.PostToolUse=[{matcher:"*",hooks:[s(`remind "${r}" "${o}"`)]}],u.push({relPath:"hooks/reminder-context.txt",content:h})),P){let S={hooks:[i(`capture "${e.launchId}"`)]};l.Stop.push(S),l.SessionEnd.push(S)}let d=e.agents??[];if(!b&&w&&d.length){let S="hooks/agent-map.json",m=`${e.pluginDir}/${S}`;u.push({relPath:S,content:JSON.stringify(Ut(d))}),l.SubagentStop=[{hooks:[i(`capture-agent "${m}" "${e.launchId}"`)]}]}let c=[];if(e.gate&&c.push({matcher:`${de}.*`,hooks:[s("gate")]}),e.guardrails?.length){let S="hooks/guardrails.json",m=`${e.pluginDir}/${S}`;u.push({relPath:S,content:JSON.stringify(e.guardrails,null,2)}),c.push({matcher:"*",hooks:[s(`guardrails "${m}"`)]})}if(e.policyGuardrails?.length){let S="hooks/policy-guardrails.json",m=`${e.pluginDir}/${S}`;u.push({relPath:S,content:JSON.stringify(e.policyGuardrails,null,2)}),c.push({matcher:"Bash",hooks:[s(`policy "${m}"`)]})}return process.env.SUPERCLAWD_AUTO_RETRIEVE!=="0"&&(l.UserPromptSubmit=[{hooks:[s("retrieve prompt")]}],c.push({matcher:"Read",hooks:[s("retrieve file")]})),c.length&&(l.PreToolUse=c),u.push({relPath:"hooks/hooks.json",content:JSON.stringify({hooks:l},null,2)}),u}var Yt="# superclawd-report-commit";function Kt(e){return`'${String(e).replace(/'/g,"'\\''")}'`}function Ht(e){let{cwd:t,helperPath:n,env:r}=e,o="";try{let a=Ir("git rev-parse --git-path hooks",{cwd:t,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();a&&(o=a.startsWith("/")?a:Gt(t,a))}catch{return{installed:!1,reason:"not a git repo"}}if(!o)return{installed:!1,reason:"no hooks dir"};let s=Gt(o,"post-commit");if(br(s)){let a="";try{a=Ar(s,"utf8")}catch{return{installed:!1,reason:"post-commit unreadable; skipped"}}if(!a.includes(Yt))return{installed:!1,reason:"existing user post-commit hook; skipped"}}let l=["SUPERCLAWD_BACKEND","SUPERCLAWD_MCP_API_URL","SUPERCLAWD_REPO_FINGERPRINT","SUPERCLAWD_MCP_KEY","SUPERCLAWD_MCP_SECRET","SUPERCLAWD_MCP_WORKSPACE","NODE_EXTRA_CA_CERTS","SUPERCLAWD_HOME","SUPERCLAWD_CLAUDE_BIN","SUPERCLAWD_POLICY_MODEL"].filter(a=>r[a]!==void 0&&r[a]!=="").map(a=>`export ${a}=${Kt(r[a])}`).join(`
190
+ `),u=`#!/bin/sh
191
+ ${Yt}
192
192
  # Auto-generated by superclawd \u2014 reports Learned Memory staleness after each
193
193
  # commit. Safe to delete; superclawd will not recreate it if you replace it.
194
- ${a}
195
- node ${xt(n)} report-commit >/dev/null 2>&1 &
196
- `;try{cr(ur(s),{recursive:!0}),ir(s,l),ar(s,493)}catch(c){return{installed:!1,reason:`write failed: ${String(c)}`}}return{installed:!0,reason:"installed"}}import{spawn as $e,spawnSync as Nt}from"node:child_process";import b from"node:fs";import v from"node:path";import{fileURLToPath as pr}from"node:url";import{createRequire as dr}from"node:module";var j="@superclawd-ai/pipelines",Ie=v.join(x,"pipelines.pid"),De=v.join(x,"pipelines.port"),It=v.join(x,"pipelines.log"),fr=v.join(x,"pipelines-mcp.json"),Gt=63210,jt=2e4;function mr(e){let t="",n=null,r=!1;for(let o=0;o<e.length;o++){let s=e[o],i=e[o+1];if(s==="--port"||s==="-p"){let a=Number(i);i&&Number.isInteger(a)&&a>0&&a<65536&&(n=a,o++)}else s==="-d"||s==="--detach"?r=!0:!s.startsWith("-")&&!t&&(t=s)}return{sub:t,port:n,detach:r}}function Le(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Dt(e){try{let t=Number(b.readFileSync(e,"utf8").trim());return Number.isInteger(t)&&t>0?t:null}catch{return null}}function pe(){let e=Dt(Ie),t=Dt(De);return{pid:e,port:t,alive:e!==null&&Le(e)}}function gr(){try{let e=JSON.parse(b.readFileSync(fr,"utf8"));return e&&typeof e=="object"?e:null}catch{return null}}function Ft(){if(!Ve())return null;let e=gr(),t=e?.port??Gt,n=e?.token;return{name:"pipelines",type:"http",url:`http://127.0.0.1:${t}/mcp`,...n?{headers:{Authorization:`Bearer ${n}`}}:{}}}function Tt(e,t){b.mkdirSync(x,{recursive:!0}),b.writeFileSync(Ie,String(e)),b.writeFileSync(De,String(t))}function X(){for(let e of[Ie,De])try{b.unlinkSync(e)}catch{}}function Kt(){let e=process.env.SUPERCLAWD_PIPELINES_DIR;if(e)return b.existsSync(e)?e:null;let t=v.dirname(pr(import.meta.url));for(let n=0;n<8;n++){let r=v.join(t,"apps","pipelines");if(b.existsSync(v.join(r,"server","index.ts"))||b.existsSync(v.join(r,"dist-server","index.mjs")))return r;let o=v.dirname(t);if(o===t)break;t=o}try{let n=dr(import.meta.url),r=v.dirname(n.resolve("@superclawd-ai/pipelines/package.json"));if(b.existsSync(v.join(r,"dist-server","index.mjs")))return r}catch{}return null}function hr(e){let t=[v.join(e,"node_modules",".bin","tsx"),v.join(e,"..","..","node_modules",".bin","tsx")];for(let n of t)if(b.existsSync(n))return n;return"tsx"}function wr(){let e=Kt();if(!e)return null;let t=v.join(e,"dist-server","index.mjs");if(b.existsSync(t))return{cmd:process.execPath,args:[t],cwd:e};let n=v.join(e,"server","index.ts");return b.existsSync(n)?{cmd:hr(e),args:[n],cwd:e}:null}async function Ot(e,t=jt){let n=Date.now()+t;for(;Date.now()<n;){if(await Yt(e))return!0;await new Promise(r=>setTimeout(r,250))}return!1}async function Yt(e){let t=new AbortController,n=setTimeout(()=>t.abort(),1e3);try{return(await fetch(`http://localhost:${e}/api/session`,{signal:t.signal})).ok}catch{return!1}finally{clearTimeout(n)}}function Ut(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{$e(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref()}catch{}}function L(e){process.stdout.write(e+`
197
- `)}function F(e){process.stderr.write(e+`
198
- `)}async function Sr(e){let t=pe(),n=a=>`http://localhost:${a}`;if(t.alive&&t.port)return L(`Pipelines is already running (pid ${t.pid}) at ${n(t.port)}`),e.detach||Ut(n(t.port)),0;t.pid&&!t.alive&&X(),await Cr(!!process.stdin.isTTY&&!e.detach);let r=wr();if(!r)return F(`\u2717 Couldn't locate the Pipelines app.
199
- Set SUPERCLAWD_PIPELINES_DIR to its directory (the one containing server/index.ts).`),1;let o=e.port??Gt,s={...process.env,PIPELINES_PORT:String(o)};if(e.detach){b.mkdirSync(x,{recursive:!0});let a=b.openSync(It,"a"),l=$e(r.cmd,r.args,{cwd:r.cwd,env:s,detached:!0,stdio:["ignore",a,a]});return l.unref(),l.pid?(Tt(l.pid,o),await Ot(o)?(L(`\u2713 Pipelines started (pid ${l.pid}) at ${n(o)}`),0):(F(`\u2717 Daemon didn't become ready within ${jt/1e3}s. See ${It}`),1)):(F("\u2717 Failed to spawn the Pipelines daemon."),1)}L(`Starting Pipelines at ${n(o)} \u2026 (Ctrl-C to stop)`);let i=$e(r.cmd,r.args,{cwd:r.cwd,env:s,stdio:"inherit"});return i.pid&&Tt(i.pid,o),Ot(o).then(a=>{a&&Ut(n(o))}),await new Promise(a=>{i.on("error",l=>{F(`\u2717 Could not launch the daemon: ${l.message}`),X(),a(1)}),i.on("close",l=>{X(),a(l??0)})})}async function kr(){let e=pe();if(!e.pid||!e.alive)return L("Pipelines is not running."),X(),0;let t=n=>{try{process.kill(-e.pid,n)}catch{try{process.kill(e.pid,n)}catch{}}};t("SIGTERM");for(let n=0;n<40&&Le(e.pid);n++)await new Promise(r=>setTimeout(r,100));return Le(e.pid)&&t("SIGKILL"),X(),L("\u2713 Pipelines stopped."),0}async function yr(){let e=pe();if(!e.alive)return L("Pipelines: stopped."),0;let t=e.port?await Yt(e.port):!1;return L(`Pipelines: running (pid ${e.pid}) on port ${e.port??"?"} \u2014 `+(t?"responding \u2713":"not responding yet")),0}function Er(e){try{return JSON.parse(b.readFileSync(v.join(e,"package.json"),"utf8")).version??null}catch{return null}}async function Cr(e){if(process.env.SUPERCLAWD_NO_UPDATE||process.env.SUPERCLAWD_BACKEND==="mock")return;let t=Kt(),n=t?Er(t):null;if(!n)return;let r=await Ee(j,n);if(!r)return;let{latest:o}=r;if(!e){Ce("Pipelines",n,o,"superclawd pipelines update"),Y(j);return}if(await Re("Pipelines",n,o)==="run"){Y(j,o);return}Y(j),L(`Updating Pipelines (npm i -g ${j}@latest) \u2026`);let i=Nt(`npm install -g ${j}@latest`,{stdio:"inherit",shell:!0});i.status!==0?F(`\u2717 Update failed (npm exited ${i.status??"?"}). Starting ${n} for now.`):L(`\u2713 Updated to ${o}.`)}function Rr(){if(pe().alive)return F("\u2717 Stop the daemon first: superclawd pipelines stop"),1;L(`Updating Pipelines (npm i -g ${j}@latest) \u2026`);let t=Nt(`npm install -g ${j}@latest`,{stdio:"inherit",shell:!0});return t.status!==0?(F(`\u2717 Update failed (npm exited ${t.status??"?"}).`),t.status??1):(L("\u2713 Updated. Start again with: superclawd pipelines start"),0)}function Wt(){return["superclawd pipelines \u2014 run the local Pipelines app",""," start [--port <n>] [-d] Start the daemon (foreground; -d detaches). Opens the browser."," stop Stop the running daemon."," status Show whether the daemon is running."," update Update the Pipelines app (daemon must be stopped)."].join(`
200
- `)}async function Bt(e){let t=mr(e);switch(t.sub){case"start":return Sr(t);case"stop":return kr();case"status":return yr();case"update":return Rr();case"":case"help":return L(Wt()),0;default:return F(`Unknown pipelines command: ${t.sub}`),L(Wt()),1}}function br(e){let t={},n=[];for(let r of e){if(!r.name||r.name===ie||r.name===V||t[r.name])continue;let o={};r.type==="http"?(o.type="http",o.url=r.url,r.headers&&Object.keys(r.headers).length&&(o.headers=r.headers)):(o.command=r.command,r.args&&r.args.length&&(o.args=r.args)),r.env&&Object.keys(r.env).length&&(o.env=r.env),t[r.name]=o,n.push(r.name)}return{map:t,names:n}}function Ar(e,t,n,r,o){let s={SUPERCLAWD_BACKEND:J,SUPERCLAWD_MCP_API_URL:q,SUPERCLAWD_SESSION_ID:n};return S||(s.SUPERCLAWD_MCP_KEY=e.keyId,s.SUPERCLAWD_MCP_SECRET=e.secret,s.SUPERCLAWD_MCP_WORKSPACE=e.workspace),process.env.NODE_EXTRA_CA_CERTS&&(s.NODE_EXTRA_CA_CERTS=process.env.NODE_EXTRA_CA_CERTS),process.env.SUPERCLAWD_HOME&&(s.SUPERCLAWD_HOME=process.env.SUPERCLAWD_HOME),process.env.SUPERCLAWD_LOG_FILE&&(s.SUPERCLAWD_LOG_FILE=process.env.SUPERCLAWD_LOG_FILE),process.env.SUPERCLAWD_DEBUG&&(s.SUPERCLAWD_DEBUG=process.env.SUPERCLAWD_DEBUG),process.env.SUPERCLAWD_MOCK_TIER&&(s.SUPERCLAWD_MOCK_TIER=process.env.SUPERCLAWD_MOCK_TIER),process.env.SUPERCLAWD_MOCK_BALANCE&&(s.SUPERCLAWD_MOCK_BALANCE=process.env.SUPERCLAWD_MOCK_BALANCE),process.env.SUPERCLAWD_EXPERIMENTAL&&(s.SUPERCLAWD_EXPERIMENTAL=process.env.SUPERCLAWD_EXPERIMENTAL),process.env.SUPERCLAWD_REPO_FINGERPRINT&&(s.SUPERCLAWD_REPO_FINGERPRINT=process.env.SUPERCLAWD_REPO_FINGERPRINT),process.env.SUPERCLAWD_TEAM_MEMORY&&(s.SUPERCLAWD_TEAM_MEMORY=process.env.SUPERCLAWD_TEAM_MEMORY),process.env.SUPERCLAWD_REPO_MEMORY&&(s.SUPERCLAWD_REPO_MEMORY=process.env.SUPERCLAWD_REPO_MEMORY),process.env.SUPERCLAWD_AGENT_MEMORY&&(s.SUPERCLAWD_AGENT_MEMORY=process.env.SUPERCLAWD_AGENT_MEMORY),process.env.SUPERCLAWD_PRIVATE_MEMORY&&(s.SUPERCLAWD_PRIVATE_MEMORY=process.env.SUPERCLAWD_PRIVATE_MEMORY),process.env.SUPERCLAWD_PIPELINES_TOOLS&&(s.SUPERCLAWD_PIPELINES_TOOLS=process.env.SUPERCLAWD_PIPELINES_TOOLS),process.env.SUPERCLAWD_PIPELINES_URL&&(s.SUPERCLAWD_PIPELINES_URL=process.env.SUPERCLAWD_PIPELINES_URL),process.env.SUPERCLAWD_PIPELINES_TICKET&&(s.SUPERCLAWD_PIPELINES_TICKET=process.env.SUPERCLAWD_PIPELINES_TICKET),r.length&&(s.SUPERCLAWD_RESOURCES=JSON.stringify(r.map(a=>({name:a.name,description:a.description})))),{relPath:".claude-plugin/plugin.json",content:JSON.stringify({name:V,description:"SuperClawd skills + live, metered directives for Claude Code.",mcpServers:{[ie]:{command:"node",args:[t],env:s},...o}},null,2)}}function Jt(e){let{pluginDir:t,session:n,catalog:r,serverPath:o,launchId:s}=e,i=qt(Ht(o),"hook-helper.mjs"),a=process.env.SUPERCLAWD_GATE==="1",l=br(r.mcpServers),c=Ft();if(c&&!l.map[c.name]){let d={type:"http",url:c.url};c.headers&&(d.headers=c.headers),l.map[c.name]=d,l.names.push(c.name)}let g=[...Pt(r.agents,{foundationalText:r.foundational.text},r.agentTeams),..._t(r.commands,r.agents),...vt(r.workflows),...bt()],y=new Set;for(let d of g){let p=/^commands\/(.+)\.md$/.exec(d.relPath),P=/^skills\/(.+)\/SKILL\.md$/.exec(d.relPath);p&&y.add(p[1]),P&&y.add(P[1])}let E=[Ar(n,o,s,r.resources,l.map),...yt(r.skills,y),...g,...$t({foundational:r.foundational,helperPath:i,pluginDir:t,launchId:s,gate:a,guardrails:r.guardrails,policyGuardrails:r.policyGuardrails,agents:r.agents})],f=[];for(let d of E){let p=qt(t,d.relPath);Pr(Ht(p),{recursive:!0}),_r(p,d.content),d.executable&&vr(p,493),f.push(d.relPath)}return{pluginDir:t,skillCount:r.skills.length,agentCount:r.agents.length,commandCount:r.commands.length,workflowCount:r.workflows.length,mcpServerNames:l.names,files:f}}import{mkdirSync as Mr,rmSync as Vt,readdirSync as xr,statSync as $r}from"node:fs";import{join as Te}from"node:path";import{randomBytes as Lr}from"node:crypto";function Xt(){let e=`${Date.now().toString(36)}-${Lr(4).toString("hex")}`,t=Te(re,e),n=Te(t,"plugin");return Mr(n,{recursive:!0}),{id:e,dir:t,pluginDir:n}}function zt(e){try{Vt(e.dir,{recursive:!0,force:!0})}catch{}}function Qt(e=Date.now()){let t=0,n=[];try{n=xr(re)}catch{return 0}for(let r of n){let o=Te(re,r);try{e-$r(o).mtimeMs>Ze&&(Vt(o,{recursive:!0,force:!0}),t++)}catch{}}return t}import{hostname as Ir}from"node:os";import{spawn as Dr}from"node:child_process";var Tr=e=>new Promise(t=>setTimeout(t,e));function Or(e){try{let t=process.platform,o=Dr(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}async function Zt(){if(S)return process.stdout.write(`Mock mode \u2014 login is not needed.
201
- `),{ok:!0};let e=Ke(),t=Ir()||"Unknown device",n;try{let c=await fetch(`${ne}/api/auth/cli/device/start`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({machineId:e,hostname:t})});if(!c.ok)return{ok:!1,error:`Couldn't start login (HTTP ${c.status}).`};n=await c.json()}catch{return{ok:!1,error:`Couldn't reach ${ne}.`}}let r=n.verification_uri_complete||n.verification_uri;process.stdout.write(`
194
+ ${l}
195
+ node ${Kt(n)} report-commit >/dev/null 2>&1 &
196
+ `;try{Or(Lr(s),{recursive:!0}),xr(s,u),$r(s,493)}catch(a){return{installed:!1,reason:`write failed: ${String(a)}`}}return{installed:!0,reason:"installed"}}import{spawn as Ne,spawnSync as Zt}from"node:child_process";import O from"node:fs";import $ from"node:path";import{fileURLToPath as Dr}from"node:url";import{createRequire as Tr}from"node:module";var Y="@superclawd-ai/pipelines",Ge=$.join(D,"pipelines.pid"),Ye=$.join(D,"pipelines.port"),qt=$.join(D,"pipelines.log"),Ur=$.join(D,"pipelines-mcp.json"),en=63210,tn=2e4;function Wr(e){let t="",n=null,r=!1;for(let o=0;o<e.length;o++){let s=e[o],i=e[o+1];if(s==="--port"||s==="-p"){let l=Number(i);i&&Number.isInteger(l)&&l>0&&l<65536&&(n=l,o++)}else s==="-d"||s==="--detach"?r=!0:!s.startsWith("-")&&!t&&(t=s)}return{sub:t,port:n,detach:r}}function je(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function Jt(e){try{let t=Number(O.readFileSync(e,"utf8").trim());return Number.isInteger(t)&&t>0?t:null}catch{return null}}function ge(){let e=Jt(Ge),t=Jt(Ye);return{pid:e,port:t,alive:e!==null&&je(e)}}function Fr(){try{let e=JSON.parse(O.readFileSync(Ur,"utf8"));return e&&typeof e=="object"?e:null}catch{return null}}function nn(){if(!at())return null;let e=Fr(),t=e?.port??en,n=e?.token;return{name:"pipelines",type:"http",url:`http://127.0.0.1:${t}/mcp`,...n?{headers:{Authorization:`Bearer ${n}`}}:{}}}function Vt(e,t){O.mkdirSync(D,{recursive:!0}),O.writeFileSync(Ge,String(e)),O.writeFileSync(Ye,String(t))}function Q(){for(let e of[Ge,Ye])try{O.unlinkSync(e)}catch{}}function rn(){let e=process.env.SUPERCLAWD_PIPELINES_DIR;if(e)return O.existsSync(e)?e:null;let t=$.dirname(Dr(import.meta.url));for(let n=0;n<8;n++){let r=$.join(t,"apps","pipelines");if(O.existsSync($.join(r,"server","index.ts"))||O.existsSync($.join(r,"dist-server","index.mjs")))return r;let o=$.dirname(t);if(o===t)break;t=o}try{let n=Tr(import.meta.url),r=$.dirname(n.resolve("@superclawd-ai/pipelines/package.json"));if(O.existsSync($.join(r,"dist-server","index.mjs")))return r}catch{}return null}function Nr(e){let t=[$.join(e,"node_modules",".bin","tsx"),$.join(e,"..","..","node_modules",".bin","tsx")];for(let n of t)if(O.existsSync(n))return n;return"tsx"}function jr(){let e=rn();if(!e)return null;let t=$.join(e,"dist-server","index.mjs");if(O.existsSync(t))return{cmd:process.execPath,args:[t],cwd:e};let n=$.join(e,"server","index.ts");return O.existsSync(n)?{cmd:Nr(e),args:[n],cwd:e}:null}async function Xt(e,t=tn){let n=Date.now()+t;for(;Date.now()<n;){if(await on(e))return!0;await new Promise(r=>setTimeout(r,250))}return!1}async function on(e){let t=new AbortController,n=setTimeout(()=>t.abort(),1e3);try{return(await fetch(`http://localhost:${e}/api/session`,{signal:t.signal})).ok}catch{return!1}finally{clearTimeout(n)}}function zt(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";try{Ne(t,[e],{stdio:"ignore",detached:!0,shell:process.platform==="win32"}).unref()}catch{}}function T(e){process.stdout.write(e+`
197
+ `)}function K(e){process.stderr.write(e+`
198
+ `)}async function Gr(e){let t=ge(),n=l=>`http://localhost:${l}`;if(t.alive&&t.port)return T(`Pipelines is already running (pid ${t.pid}) at ${n(t.port)}`),e.detach||zt(n(t.port)),0;t.pid&&!t.alive&&Q(),await Hr(!!process.stdin.isTTY&&!e.detach);let r=jr();if(!r)return K(`\u2717 Couldn't locate the Pipelines app.
199
+ Set SUPERCLAWD_PIPELINES_DIR to its directory (the one containing server/index.ts).`),1;let o=e.port??en,s={...process.env,PIPELINES_PORT:String(o)};if(e.detach){O.mkdirSync(D,{recursive:!0});let l=O.openSync(qt,"a"),u=Ne(r.cmd,r.args,{cwd:r.cwd,env:s,detached:!0,stdio:["ignore",l,l]});return u.unref(),u.pid?(Vt(u.pid,o),await Xt(o)?(T(`\u2713 Pipelines started (pid ${u.pid}) at ${n(o)}`),0):(K(`\u2717 Daemon didn't become ready within ${tn/1e3}s. See ${qt}`),1)):(K("\u2717 Failed to spawn the Pipelines daemon."),1)}T(`Starting Pipelines at ${n(o)} \u2026 (Ctrl-C to stop)`);let i=Ne(r.cmd,r.args,{cwd:r.cwd,env:s,stdio:"inherit"});return i.pid&&Vt(i.pid,o),Xt(o).then(l=>{l&&zt(n(o))}),await new Promise(l=>{i.on("error",u=>{K(`\u2717 Could not launch the daemon: ${u.message}`),Q(),l(1)}),i.on("close",u=>{Q(),l(u??0)})})}async function Yr(){let e=ge();if(!e.pid||!e.alive)return T("Pipelines is not running."),Q(),0;let t=n=>{try{process.kill(-e.pid,n)}catch{try{process.kill(e.pid,n)}catch{}}};t("SIGTERM");for(let n=0;n<40&&je(e.pid);n++)await new Promise(r=>setTimeout(r,100));return je(e.pid)&&t("SIGKILL"),Q(),T("\u2713 Pipelines stopped."),0}async function Kr(){let e=ge();if(!e.alive)return T("Pipelines: stopped."),0;let t=e.port?await on(e.port):!1;return T(`Pipelines: running (pid ${e.pid}) on port ${e.port??"?"} \u2014 `+(t?"responding \u2713":"not responding yet")),0}function Br(e){try{return JSON.parse(O.readFileSync($.join(e,"package.json"),"utf8")).version??null}catch{return null}}async function Hr(e){if(process.env.SUPERCLAWD_NO_UPDATE||process.env.SUPERCLAWD_BACKEND==="mock")return;let t=rn(),n=t?Br(t):null;if(!n)return;let r=await Ae(Y,n);if(!r)return;let{latest:o}=r;if(!e){xe("Pipelines",n,o,"superclawd pipelines update"),H(Y);return}if(await $e("Pipelines",n,o)==="run"){H(Y,o);return}H(Y),T(`Updating Pipelines (npm i -g ${Y}@latest) \u2026`);let i=Zt(`npm install -g ${Y}@latest`,{stdio:"inherit",shell:!0});i.status!==0?K(`\u2717 Update failed (npm exited ${i.status??"?"}). Starting ${n} for now.`):T(`\u2713 Updated to ${o}.`)}function qr(){if(ge().alive)return K("\u2717 Stop the daemon first: superclawd pipelines stop"),1;T(`Updating Pipelines (npm i -g ${Y}@latest) \u2026`);let t=Zt(`npm install -g ${Y}@latest`,{stdio:"inherit",shell:!0});return t.status!==0?(K(`\u2717 Update failed (npm exited ${t.status??"?"}).`),t.status??1):(T("\u2713 Updated. Start again with: superclawd pipelines start"),0)}function Qt(){return["superclawd pipelines \u2014 run the local Pipelines app",""," start [--port <n>] [-d] Start the daemon (foreground; -d detaches). Opens the browser."," stop Stop the running daemon."," status Show whether the daemon is running."," update Update the Pipelines app (daemon must be stopped)."].join(`
200
+ `)}async function sn(e){let t=Wr(e);switch(t.sub){case"start":return Gr(t);case"stop":return Yr();case"status":return Kr();case"update":return qr();case"":case"help":return T(Qt()),0;default:return K(`Unknown pipelines command: ${t.sub}`),T(Qt()),1}}import{spawn as Jr}from"node:child_process";import B from"node:fs";import Vr from"node:os";import N from"node:path";import{fileURLToPath as Xr}from"node:url";import{createRequire as zr}from"node:module";var ln="@superclawd-ai/fda",Qr={badFlags:64,claudeMissing:69,cloudUnavailable:75,agentNotFound:76,credentials:77,workspaceInvalid:78};function he(e,t){return process.stderr.write(`${JSON.stringify({fda_error:{class:e,message:t}})}
201
+ `),Qr[e]}var Se=new Set(["fda","fda-browser","fda-calendar"]);function cn(e){if(!e)return null;let t;try{t=JSON.parse(B.readFileSync(e,"utf8"))}catch{return null}if(!t||typeof t!="object"||Array.isArray(t))return null;let n={};for(let[r,o]of Object.entries(t)){if(!Se.has(r)||!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(s.type==="http"&&typeof s.url=="string"){let i={type:"http",url:s.url};an(s.headers)&&(i.headers=s.headers),n[r]=i}else if(typeof s.command=="string"){let i={command:s.command};Array.isArray(s.args)&&s.args.every(l=>typeof l=="string")&&(i.args=s.args),an(s.env)&&(i.env=s.env),n[r]=i}}return Object.keys(n).length?n:null}function an(e){return!!e&&typeof e=="object"&&!Array.isArray(e)&&Object.values(e).every(t=>typeof t=="string")}function un(e,t){let n={},r=[];for(let o of e.names)Se.has(o)||!e.map[o]||(n[o]=e.map[o],r.push(o));for(let[o,s]of Object.entries(t))n[o]=s,r.push(o);return{map:n,names:r}}function Ke(e,t=["SIGINT","SIGTERM","SIGHUP"]){let n=o=>{try{e.kill(o)}catch{}};for(let o of t)process.on(o,n);let r=()=>{for(let o of t)process.off(o,n)};return e.once("close",r),r}function Be(e){return e?128+(Vr.constants.signals[e]??9):1}function Zr(){let e=process.env.SUPERCLAWD_FDA_DIR;if(e)return B.existsSync(e)?e:null;let t=N.dirname(Xr(import.meta.url));for(let n=0;n<8;n++){let r=N.join(t,"apps","fda");if(B.existsSync(N.join(r,"server","cli.ts"))||B.existsSync(N.join(r,"dist-server","cli.mjs")))return r;let o=N.dirname(t);if(o===t)break;t=o}try{let n=zr(import.meta.url),r=N.dirname(n.resolve(`${ln}/package.json`));if(B.existsSync(N.join(r,"dist-server","cli.mjs")))return r}catch{}return null}function eo(e){let t=N.join(e,"dist-server","cli.mjs");if(B.existsSync(t))return{cmd:process.execPath,args:[t]};let n=N.join(e,"server","cli.ts");if(!B.existsSync(n))return null;for(let r of[N.join(e,"node_modules",".bin","tsx"),N.join(e,"..","..","node_modules",".bin","tsx")])if(B.existsSync(r))return{cmd:r,args:[n]};return{cmd:"tsx",args:[n]}}function dn(e){let t=Zr(),n=t?eo(t):null;return!t||!n?(process.stderr.write(`SuperClawd FDA isn't installed.
202
+ Install it with: npm i -g ${ln}
203
+ `),Promise.resolve(1)):new Promise(r=>{let o=Jr(n.cmd,[...n.args,...e],{stdio:"inherit",cwd:process.cwd()});Ke(o),o.on("error",s=>{process.stderr.write(`\u2717 Could not start SuperClawd FDA: ${s.message}
204
+ `),r(127)}),o.on("close",(s,i)=>r(s??Be(i)))})}function oo(e){let t={},n=[];for(let r of e){if(!r.name||r.name===ue||r.name===X||t[r.name])continue;let o={};r.type==="http"?(o.type="http",o.url=r.url,r.headers&&Object.keys(r.headers).length&&(o.headers=r.headers)):(o.command=r.command,r.args&&r.args.length&&(o.args=r.args)),r.env&&Object.keys(r.env).length&&(o.env=r.env),t[r.name]=o,n.push(r.name)}return{map:t,names:n}}function so(e,t,n,r,o){let s={SUPERCLAWD_BACKEND:z,SUPERCLAWD_MCP_API_URL:V,SUPERCLAWD_SESSION_ID:n};return _||(s.SUPERCLAWD_MCP_KEY=e.keyId,s.SUPERCLAWD_MCP_SECRET=e.secret,s.SUPERCLAWD_MCP_WORKSPACE=e.workspace),process.env.NODE_EXTRA_CA_CERTS&&(s.NODE_EXTRA_CA_CERTS=process.env.NODE_EXTRA_CA_CERTS),process.env.SUPERCLAWD_HOME&&(s.SUPERCLAWD_HOME=process.env.SUPERCLAWD_HOME),process.env.SUPERCLAWD_LOG_FILE&&(s.SUPERCLAWD_LOG_FILE=process.env.SUPERCLAWD_LOG_FILE),process.env.SUPERCLAWD_DEBUG&&(s.SUPERCLAWD_DEBUG=process.env.SUPERCLAWD_DEBUG),process.env.SUPERCLAWD_MOCK_TIER&&(s.SUPERCLAWD_MOCK_TIER=process.env.SUPERCLAWD_MOCK_TIER),process.env.SUPERCLAWD_MOCK_BALANCE&&(s.SUPERCLAWD_MOCK_BALANCE=process.env.SUPERCLAWD_MOCK_BALANCE),process.env.SUPERCLAWD_EXPERIMENTAL&&(s.SUPERCLAWD_EXPERIMENTAL=process.env.SUPERCLAWD_EXPERIMENTAL),process.env.SUPERCLAWD_REPO_FINGERPRINT&&(s.SUPERCLAWD_REPO_FINGERPRINT=process.env.SUPERCLAWD_REPO_FINGERPRINT),process.env.SUPERCLAWD_TEAM_MEMORY&&(s.SUPERCLAWD_TEAM_MEMORY=process.env.SUPERCLAWD_TEAM_MEMORY),process.env.SUPERCLAWD_REPO_MEMORY&&(s.SUPERCLAWD_REPO_MEMORY=process.env.SUPERCLAWD_REPO_MEMORY),process.env.SUPERCLAWD_AGENT_MEMORY&&(s.SUPERCLAWD_AGENT_MEMORY=process.env.SUPERCLAWD_AGENT_MEMORY),process.env.SUPERCLAWD_PRIVATE_MEMORY&&(s.SUPERCLAWD_PRIVATE_MEMORY=process.env.SUPERCLAWD_PRIVATE_MEMORY),process.env.SUPERCLAWD_MEMORY_OFF&&(s.SUPERCLAWD_MEMORY_OFF=process.env.SUPERCLAWD_MEMORY_OFF),process.env.SUPERCLAWD_PIPELINES_TOOLS&&(s.SUPERCLAWD_PIPELINES_TOOLS=process.env.SUPERCLAWD_PIPELINES_TOOLS),process.env.SUPERCLAWD_PIPELINES_URL&&(s.SUPERCLAWD_PIPELINES_URL=process.env.SUPERCLAWD_PIPELINES_URL),process.env.SUPERCLAWD_PIPELINES_TICKET&&(s.SUPERCLAWD_PIPELINES_TICKET=process.env.SUPERCLAWD_PIPELINES_TICKET),r.length&&(s.SUPERCLAWD_RESOURCES=JSON.stringify(r.map(l=>({name:l.name,description:l.description})))),{relPath:".claude-plugin/plugin.json",content:JSON.stringify({name:X,description:"SuperClawd skills + live, metered directives for Claude Code.",mcpServers:{[ue]:{command:"node",args:[t],env:s},...o}},null,2)}}function mn(e){let{pluginDir:t,session:n,catalog:r,serverPath:o,launchId:s,fda:i}=e,l=fn(pn(o),"hook-helper.mjs"),u=process.env.SUPERCLAWD_GATE==="1",a=oo(r.mcpServers),f=i?null:nn();if(f&&!a.map[f.name]){let h={type:"http",url:f.url};f.headers&&(h.headers=f.headers),a.map[f.name]=h,a.names.push(f.name)}i&&e.fdaServers&&(a=un(a,e.fdaServers));let w=[...Wt(r.agents,{foundationalText:r.foundational.text,modelFamilies:r.modelFamilies,extraTools:i&&e.fdaServers?Object.keys(e.fdaServers).filter(h=>Se.has(h)).map(Dt):[]},r.agentTeams),...Ft(r.commands,r.agents),...Nt(r.workflows),...jt()],y=new Set;for(let h of w){let d=/^commands\/(.+)\.md$/.exec(h.relPath),c=/^skills\/(.+)\/SKILL\.md$/.exec(h.relPath);d&&y.add(d[1]),c&&y.add(c[1])}let b=[so(n,o,s,r.resources,a.map),...Ot(r.skills,y),...w,...Bt({foundational:r.foundational,helperPath:l,pluginDir:t,launchId:s,gate:u,guardrails:r.guardrails,policyGuardrails:r.policyGuardrails,agents:r.agents})],P=[],E=[];for(let h of b){let d=fn(t,h.relPath);to(pn(d),{recursive:!0,mode:448}),no(d,h.content,{mode:384}),h.executable&&ro(d,448),P.push(h.relPath);let c=/^agents\/(.+)\.md$/.exec(h.relPath);c&&E.push(c[1])}return{pluginDir:t,skillCount:r.skills.length,agentCount:r.agents.length,commandCount:r.commands.length,workflowCount:r.workflows.length,mcpServerNames:a.names,agentSlugs:E,files:P}}function gn(e,t){let n=["--allowedTools",Lt];for(let r of e)t.planOnly&&r!=="fda"||n.push("--allowedTools",`mcp__plugin_superclawd_${r}__*`);return t.planOnly?(n.push("--permission-mode","plan"),n.push("--disallowedTools","Edit","Write","NotebookEdit","Bash","Agent","Task","WebFetch","WebSearch","mcp__plugin_superclawd_fda-browser","mcp__plugin_superclawd_fda-calendar"),n.push("--setting-sources","user")):t.permissionMode?n.push("--permission-mode",t.permissionMode):t.skipPermissions&&n.push("--dangerously-skip-permissions"),n}import{mkdirSync as io,rmSync as hn,readdirSync as ao,statSync as lo}from"node:fs";import{join as He}from"node:path";import{randomBytes as co}from"node:crypto";function Sn(){let e=`${Date.now().toString(36)}-${co(4).toString("hex")}`,t=He(ae,e),n=He(t,"plugin");return io(n,{recursive:!0,mode:448}),{id:e,dir:t,pluginDir:n}}function we(e){try{hn(e.dir,{recursive:!0,force:!0})}catch{}}function wn(e=Date.now()){let t=0,n=[];try{n=ao(ae)}catch{return 0}for(let r of n){let o=He(ae,r);try{e-lo(o).mtimeMs>dt&&(hn(o,{recursive:!0,force:!0}),t++)}catch{}}return t}import{hostname as uo}from"node:os";import{spawn as po}from"node:child_process";var fo=e=>new Promise(t=>setTimeout(t,e));function mo(e){try{let t=process.platform,o=po(t==="darwin"?"open":t==="win32"?"cmd":"xdg-open",t==="win32"?["/c","start","",e]:[e],{stdio:"ignore",detached:!0});o.on("error",()=>{}),o.unref()}catch{}}async function yn(){if(_)return process.stdout.write(`Mock mode \u2014 login is not needed.
205
+ `),{ok:!0};let e=tt(),t=uo()||"Unknown device",n;try{let a=await fetch(`${ie}/api/auth/cli/device/start`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({machineId:e,hostname:t})});if(!a.ok)return{ok:!1,error:`Couldn't start login (HTTP ${a.status}).`};n=await a.json()}catch{return{ok:!1,error:`Couldn't reach ${ie}.`}}let r=n.verification_uri_complete||n.verification_uri;process.stdout.write(`
202
206
  To authorize this machine, open:
203
207
  ${r}
204
208
 
205
209
  and confirm this code matches: ${n.user_code}
206
210
 
207
- `),Or(r),process.stdout.write(`Waiting for approval\u2026 (Ctrl-C to cancel)
208
- `);let o=(n.interval||5)*1e3,s=Date.now()+(n.expires_in||600)*1e3,i,a;for(;Date.now()<s;){await Tr(o);let c;try{c=await(await fetch(`${ne}/api/auth/cli/device/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({deviceCode:n.device_code})})).json()}catch{continue}if(c.status==="approved"){i=c.key_id,a=c.secret;break}if(c.status==="denied")return{ok:!1,error:"Request was denied in the browser."};if(c.status==="expired")return{ok:!1,error:"Login request expired. Run `superclawd login` again."}}if(!i||!a)return{ok:!1,error:"Login timed out. Run `superclawd login` again."};process.stdout.write(`\u2713 Authorized.
211
+ `),mo(r),process.stdout.write(`Waiting for approval\u2026 (Ctrl-C to cancel)
212
+ `);let o=(n.interval||5)*1e3,s=Date.now()+(n.expires_in||600)*1e3,i,l;for(;Date.now()<s;){await fo(o);let a;try{a=await(await fetch(`${ie}/api/auth/cli/device/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({deviceCode:n.device_code})})).json()}catch{continue}if(a.status==="approved"){i=a.key_id,l=a.secret;break}if(a.status==="denied")return{ok:!1,error:"Request was denied in the browser."};if(a.status==="expired")return{ok:!1,error:"Login request expired. Run `superclawd login` again."}}if(!i||!l)return{ok:!1,error:"Login timed out. Run `superclawd login` again."};process.stdout.write(`\u2713 Authorized.
209
213
 
210
- `);let l=A()??{};return G({...l,credentials:{...l.credentials,keyId:i,secret:a}}),process.stdout.write("\u2713 Logged in. Run `superclawd` to choose a workspace and start.\n\n"),{ok:!0}}var C="\x1B",de=[{key:"notifications",label:"Notifications",description:"Default for new sessions \u2014 ping when Claude needs you or finishes",defaultOn:!1},{key:"skipPermissions",label:"Dangerously skip permissions",description:"Launch Claude Code with --dangerously-skip-permissions (no approval prompts)",defaultOn:!1},{key:"chooseWorkspaceAtStartup",label:"Choose workspace at startup",description:"Pick the workspace to boot into each time you run superclawd",defaultOn:!0},{key:"experimental",label:"Experimental mode",description:"Run the latest unpublished (draft) versions instead of the stable release",defaultOn:!1},{key:"keepAwake",label:"Keep Awake",description:"Prevent your computer from sleeping while a session is running",defaultOn:!1},{key:"privateMemory",label:"Private Memory",description:"Remember your personal preferences across all your sessions (private to you, never shared)",defaultOn:!0},{key:"pipelinesMcp",label:"Pipelines MCP",description:"Let Claude Code drive your Pipelines board (requires SuperClawd Pipelines running)",defaultOn:!1}].sort((e,t)=>e.label.localeCompare(t.label)),Oe=(e,t)=>e.preferences?.[t.key]??t.defaultOn;async function en(){let e=A()??{},t=process.stdin;if(!t.isTTY){process.stdout.write(`SuperClawd options:
211
- `);for(let n of de)process.stdout.write(` ${Oe(e,n)?"on ":"off"} ${n.label}
212
- `);return}await new Promise(n=>{let r=de.length,o=r+2,s=0,i=d=>{d||process.stdout.write(`${C}[${o}A`);for(let p=0;p<r;p++){let P=de[p],u=p===s?`${C}[38;5;208m\u276F `:" ",w=Oe(e,P)?`${C}[38;5;208m[\u2713]${C}[0m`:"[ ]";process.stdout.write(`${C}[2K${u}${w} ${P.label}${C}[0m ${C}[2m${P.description}${C}[0m
213
- `)}process.stdout.write(`${C}[2K
214
- `),process.stdout.write(`${C}[2K${C}[2mPress Esc (or Ctrl-C) to exit${C}[0m
214
+ `);let u=L()??{};return G({...u,credentials:{...u.credentials,keyId:i,secret:l}}),process.stdout.write("\u2713 Logged in. Run `superclawd` to choose a workspace and start.\n\n"),{ok:!0}}var M="\x1B",ye=[{key:"notifications",label:"Notifications",description:"Default for new sessions \u2014 ping when Claude needs you or finishes",defaultOn:!1},{key:"skipPermissions",label:"Dangerously skip permissions",description:"Launch Claude Code with --dangerously-skip-permissions (no approval prompts)",defaultOn:!1},{key:"chooseWorkspaceAtStartup",label:"Choose workspace at startup",description:"Pick the workspace to boot into each time you run superclawd",defaultOn:!0},{key:"experimental",label:"Experimental mode",description:"Run the latest unpublished (draft) versions instead of the stable release",defaultOn:!1},{key:"keepAwake",label:"Keep Awake",description:"Prevent your computer from sleeping while a session is running",defaultOn:!1},{key:"privateMemory",label:"Private Memory",description:"Remember your personal preferences across all your sessions (private to you, never shared)",defaultOn:!0},{key:"pipelinesMcp",label:"Pipelines MCP",description:"Let Claude Code drive your Pipelines board (requires SuperClawd Pipelines running)",defaultOn:!1}].sort((e,t)=>e.label.localeCompare(t.label)),qe=(e,t)=>e.preferences?.[t.key]??t.defaultOn;async function kn(){let e=L()??{},t=process.stdin;if(!t.isTTY){process.stdout.write(`SuperClawd options:
215
+ `);for(let n of ye)process.stdout.write(` ${qe(e,n)?"on ":"off"} ${n.label}
216
+ `);return}await new Promise(n=>{let r=ye.length,o=r+2,s=0,i=P=>{P||process.stdout.write(`${M}[${o}A`);for(let E=0;E<r;E++){let h=ye[E],d=E===s?`${M}[38;5;208m\u276F `:" ",c=qe(e,h)?`${M}[38;5;208m[\u2713]${M}[0m`:"[ ]";process.stdout.write(`${M}[2K${d}${c} ${h.label}${M}[0m ${M}[2m${h.description}${M}[0m
217
+ `)}process.stdout.write(`${M}[2K
218
+ `),process.stdout.write(`${M}[2K${M}[2mPress Esc (or Ctrl-C) to exit${M}[0m
215
219
  `)};process.stdout.write(`
216
- SuperClawd options ${C}[2m(\u2191/\u2193 move \xB7 Space/Enter to toggle)${C}[0m
217
- ${C}[?7l${C}[?25l`),i(!0),t.setRawMode(!0),t.resume();let a=!1,l=()=>{if(!a){a=!0;try{t.setRawMode(!1)}catch{}process.stdout.write(`${C}[?7h${C}[?25h`)}},c=["SIGINT","SIGTERM","SIGHUP"],g=()=>l(),y=d=>{l(),process.kill(process.pid,d)};process.once("exit",g);for(let d of c)process.once(d,y);let E=()=>{t.off("data",f),process.off("exit",g);for(let d of c)process.off(d,y);t.pause(),l(),process.stdout.write(`
218
- `)},f=d=>{let p=d.toString();if(p===""||p===C)E(),n();else if(p==="\r"||p===`
219
- `||p===" "){let P=de[s];e.preferences={...e.preferences,[P.key]:!Oe(e,P)},G(e),i(!1)}else p===`${C}[A`||p==="k"?(s=(s-1+r)%r,i(!1)):(p===`${C}[B`||p==="j")&&(s=(s+1)%r,i(!1))};t.on("data",f)})}import{execSync as sn}from"node:child_process";var k="\x1B",W=`${k}[38;5;208m`,H=`${k}[2m`,ge=`${k}[31m`,R=`${k}[0m`,Ur=`${k}[?1049h`,tn=`${k}[?1049l`,Wr=`${k}[?25l`,Ue=`${k}[?25h`,Nr=`${k}[?1007l`,nn=`${k}[?1007h`,Gr=`${k}[?1000l${k}[?1002l${k}[?1003l${k}[?1004l${k}[?1006l${k}[?1015l`,We=`${k}[2J${k}[H`,fe=[" _ _"," ____ _ _ __ ___ _ _ __| |__ ___ __ ____| |","(_-< || | '_ \\/ -_) '_/ _| / _` \\ V V / _` |","/__/\\_,_| .__/\\___|_| \\__|_\\__,_|\\_/\\_/\\__,_|"," |_|"],rn=45,z=36,jr=140,Fr=350,T=e=>void process.stdout.write(e),Kr=e=>new Promise(t=>setTimeout(t,e)),B=e=>e>0?" ".repeat(e):"",an=process.platform!=="win32";function Yr(){if(!an)return null;try{return sn("stty -g </dev/tty",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function on(e){if(an)try{sn(`stty ${e} </dev/tty`,{stdio:"ignore"})}catch{}}var me=null;function cn(e){me?.(),me=null,process.stderr.write(`${ge}\u2717 ${e}${R}
220
- `)}function Br(e,t){return T(`${W}${fe.join(`
221
- `)}${R} ${H}v${t}${R}
222
-
223
- `),{async phase(n,r){T(`${H} \xB7 ${r}${R}
224
- `)},message(n){T(`${H} \xB7 ${n}${R}
225
- `)},async selectWorkspace(n,r){return r?.currentSlug??n[0]?.slug??null},async ready(n){T(`${W} \u2713 ${n}${R}
226
- `)},fail(n){T(`${ge} \u2717 ${n}${R}
227
- `)},note(n){T(` ${n}
228
- `)},handoff(){},finish(){}}}function Hr(e,t){let n=Yr(),r=0,o=!0,s=!1,i=u=>{u.includes(3)&&g()},a=()=>{let u=process.stdin;if(u.isTTY){try{u.setRawMode(!0)}catch{}u.resume(),u.on("data",i),s=!0}},l=()=>{if(!s)return;let u=process.stdin;u.off("data",i);try{u.setRawMode(!1)}catch{}u.pause(),s=!1},c=()=>{l();try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}T(Ue+nn+tn),n&&on(n)},g=()=>{o&&c(),o=!1,process.exit(130)},y=()=>{l(),o&&T(Ue+nn+tn)},E=()=>{process.off("SIGINT",g),process.off("SIGTERM",g),process.off("exit",y),me=null};on("-echo"),T(Ur+Wr+Nr+Gr),a(),process.on("SIGINT",g),process.on("SIGTERM",g),process.on("exit",y),me=c;let f=(u,w)=>{let _=process.stdout.columns||80,h=process.stdout.rows||24,m=Math.floor(u*z/e);m<0&&(m=0),m>z&&(m=z);let I="\u2588".repeat(m)+"\u2591".repeat(z-m),U=Math.floor(u*100/e),O=z+6,M=Math.max(0,Math.floor((h-9)/2)),N=We+`
229
- `.repeat(M),D=Math.max(0,Math.floor((_-rn)/2));for(let gn of fe)N+=`${B(D)}${W}${gn}${R}
230
- `;N+=`
231
- `;let K=Math.max(0,Math.floor((_-w.length)/2));N+=`${B(K)}${H}${w}${R}
232
-
233
- `;let Q=Math.max(0,Math.floor((_-O)/2));N+=`${B(Q)}${W}${I}${R} ${String(U).padStart(3)}%
234
- `;let Z=`v${t}`,we=Math.max(1,h-1),Se=Math.max(1,_-Z.length-1);N+=`${k}[${we};${Se}H${W}${Z}${R}`,T(N)},d=async(u,w,_)=>{let h=_-(Date.now()-r);h>0&&await Kr(h),f(u,w),r=Date.now()},p=u=>{let w=process.stdout.columns||80,_=process.stdout.rows||24,h=Math.max(0,Math.floor((_-(fe.length+1+u.length))/2)),m=We+`
235
- `.repeat(h),I=Math.max(0,Math.floor((w-rn)/2));for(let O of fe)m+=`${B(I)}${W}${O}${R}
220
+ SuperClawd options ${M}[2m(\u2191/\u2193 move \xB7 Space/Enter to toggle)${M}[0m
221
+ ${M}[?7l${M}[?25l`),i(!0),t.setRawMode(!0),t.resume();let l=!1,u=()=>{if(!l){l=!0;try{t.setRawMode(!1)}catch{}process.stdout.write(`${M}[?7h${M}[?25h`)}},a=["SIGINT","SIGTERM","SIGHUP"],f=()=>u(),w=P=>{u(),process.kill(process.pid,P)};process.once("exit",f);for(let P of a)process.once(P,w);let y=()=>{t.off("data",b),process.off("exit",f);for(let P of a)process.off(P,w);t.pause(),u(),process.stdout.write(`
222
+ `)},b=P=>{let E=P.toString();if(E===""||E===M)y(),n();else if(E==="\r"||E===`
223
+ `||E===" "){let h=ye[s];e.preferences={...e.preferences,[h.key]:!qe(e,h)},G(e),i(!1)}else E===`${M}[A`||E==="k"?(s=(s-1+r)%r,i(!1)):(E===`${M}[B`||E==="j")&&(s=(s+1)%r,i(!1))};t.on("data",b)})}import{execSync as vn}from"node:child_process";var v="\x1B",j=`${v}[38;5;208m`,J=`${v}[2m`,Re=`${v}[31m`,A=`${v}[0m`,go=`${v}[?1049h`,En=`${v}[?1049l`,ho=`${v}[?25l`,Je=`${v}[?25h`,So=`${v}[?1007l`,Rn=`${v}[?1007h`,wo=`${v}[?1000l${v}[?1002l${v}[?1003l${v}[?1004l${v}[?1006l${v}[?1015l`,Ve=`${v}[2J${v}[H`,ke=[" _ _"," ____ _ _ __ ___ _ _ __| |__ ___ __ ____| |","(_-< || | '_ \\/ -_) '_/ _| / _` \\ V V / _` |","/__/\\_,_| .__/\\___|_| \\__|_\\__,_|\\_/\\_/\\__,_|"," |_|"],Cn=45,Z=36,yo=140,ko=350,W=e=>void process.stdout.write(e),Eo=e=>new Promise(t=>setTimeout(t,e)),q=e=>e>0?" ".repeat(e):"",Pn=process.platform!=="win32";function Ro(){if(!Pn)return null;try{return vn("stty -g </dev/tty",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{return null}}function _n(e){if(Pn)try{vn(`stty ${e} </dev/tty`,{stdio:"ignore"})}catch{}}var Ee=null;function Mn(e){Ee?.(),Ee=null,process.stderr.write(`${Re}\u2717 ${e}${A}
224
+ `)}function Co(e,t){return W(`${j}${ke.join(`
225
+ `)}${A} ${J}v${t}${A}
226
+
227
+ `),{async phase(n,r){W(`${J} \xB7 ${r}${A}
228
+ `)},message(n){W(`${J} \xB7 ${n}${A}
229
+ `)},async selectWorkspace(n,r){return r?.currentSlug??n[0]?.slug??null},async ready(n){W(`${j} \u2713 ${n}${A}
230
+ `)},fail(n){W(`${Re} \u2717 ${n}${A}
231
+ `)},note(n){W(` ${n}
232
+ `)},handoff(){},finish(){}}}function _o(e,t){let n=Ro(),r=0,o=!0,s=!1,i=d=>{d.includes(3)&&f()},l=()=>{let d=process.stdin;if(d.isTTY){try{d.setRawMode(!0)}catch{}d.resume(),d.on("data",i),s=!0}},u=()=>{if(!s)return;let d=process.stdin;d.off("data",i);try{d.setRawMode(!1)}catch{}d.pause(),s=!1},a=()=>{u();try{process.stdin.isTTY&&process.stdin.setRawMode(!1)}catch{}W(Je+Rn+En),n&&_n(n)},f=()=>{o&&a(),o=!1,process.exit(130)},w=()=>{u(),o&&W(Je+Rn+En)},y=()=>{process.off("SIGINT",f),process.off("SIGTERM",f),process.off("exit",w),Ee=null};_n("-echo"),W(go+ho+So+wo),l(),process.on("SIGINT",f),process.on("SIGTERM",f),process.on("exit",w),Ee=a;let b=(d,c)=>{let R=process.stdout.columns||80,S=process.stdout.rows||24,m=Math.floor(d*Z/e);m<0&&(m=0),m>Z&&(m=Z);let I="\u2588".repeat(m)+"\u2591".repeat(Z-m),x=Math.floor(d*100/e),k=Z+6,p=Math.max(0,Math.floor((S-9)/2)),g=Ve+`
233
+ `.repeat(p),C=Math.max(0,Math.floor((R-Cn)/2));for(let Ln of ke)g+=`${q(C)}${j}${Ln}${A}
234
+ `;g+=`
235
+ `;let F=Math.max(0,Math.floor((R-c.length)/2));g+=`${q(F)}${J}${c}${A}
236
+
237
+ `;let te=Math.max(0,Math.floor((R-k)/2));g+=`${q(te)}${j}${I}${A} ${String(x).padStart(3)}%
238
+ `;let ne=`v${t}`,ve=Math.max(1,S-1),Pe=Math.max(1,R-ne.length-1);g+=`${v}[${ve};${Pe}H${j}${ne}${A}`,W(g)},P=async(d,c,R)=>{let S=R-(Date.now()-r);S>0&&await Eo(S),b(d,c),r=Date.now()},E=d=>{let c=process.stdout.columns||80,R=process.stdout.rows||24,S=Math.max(0,Math.floor((R-(ke.length+1+d.length))/2)),m=Ve+`
239
+ `.repeat(S),I=Math.max(0,Math.floor((c-Cn)/2));for(let k of ke)m+=`${q(I)}${j}${k}${A}
236
240
  `;m+=`
237
- `;for(let O of u)m+=`${O}
238
- `;let U=`v${t}`;m+=`${k}[${Math.max(1,_-1)};${Math.max(1,w-U.length-1)}H${W}${U}${R}`,T(m)},P=(u,w,_)=>{let h=process.stdout.columns||80,m="Select your workspace \u2191/\u2193 \xB7 enter launches \xB7 d sets default \xB7 esc cancels",I=Math.max(0,Math.floor((h-m.length)/2)),U=D=>` ${D.name} ${D.slug} \xB7 ${D.role}`,O=Math.max(...u.map(D=>U(D).length)),M=Math.max(0,Math.floor((h-O)/2)),N=[`${B(I)}${H}${m}${R}`,""];for(let D=0;D<u.length;D++){let K=u[D],Q=D===w,Z=Q?`${W}\u276F `:" ",we=Q?`${W}${K.name}${R}`:K.name,Se=K.slug===_?` ${W}\u2605 default${R}`:"";N.push(`${B(M)}${Z}${we} ${H}${K.slug} \xB7 ${K.role}${R}${Se}`)}p(N)};return{phase:(u,w)=>d(u-1,w,jr),ready:u=>d(e,u,Fr),message(u){let w=process.stdout.columns||80,_=Math.max(0,Math.floor((w-u.length)/2));p([`${B(_)}${H}${u}${R}`]),r=Date.now()},selectWorkspace(u,w){return new Promise(_=>{let h=w?.currentSlug?u.findIndex(O=>O.slug===w.currentSlug):-1,m=h>=0?h:0,I=w?.defaultSlug;s&&process.stdin.off("data",i),P(u,m,I);let U=O=>{let M=O.toString();M===""||M===k?(process.stdin.off("data",U),_(null)):M==="\r"||M===`
239
- `?(process.stdin.off("data",U),process.stdin.on("data",i),_(u[m].slug)):M==="d"||M==="D"?(I=u[m].slug,w?.onSetDefault?.(I),P(u,m,I)):M===`${k}[A`||M==="k"?(m=(m-1+u.length)%u.length,P(u,m,I)):(M===`${k}[B`||M==="j")&&(m=(m+1)%u.length,P(u,m,I))};process.stdin.on("data",U)})},fail(u){o&&c(),o=!1,E(),process.stderr.write(`${ge}\u2717 ${u}${R}
240
- `)},note(){},handoff(){s&&(process.stdin.off("data",i),process.stdin.pause(),s=!1),T(We+Ue),process.off("SIGINT",g),process.off("SIGTERM",g)},finish(){o&&c(),o=!1,E()}}}function qr(){return process.platform!=="win32"?!0:!!(process.env.WT_SESSION||process.env.TERM_PROGRAM||process.env.TERM)}function Jr(){return{async phase(){},message(){},async selectWorkspace(e,t){return t?.currentSlug??e[0]?.slug??null},async ready(){},fail(e){process.stderr.write(`${ge}\u2717 ${e}${R}
241
- `)},note(){},handoff(){},finish(){}}}function ln(e){if(e.quiet)return Jr();let t=process.stdout.isTTY===!0,n=e.version??"";return e.plain||!t||!qr()?Br(e.total,n):Hr(e.total,n)}var Vr=["low","medium","high","xhigh","max"];function un(e){let t=!1,n="",r=null,o=!1,s=!1,i=null,a=!1,l=!1,c="board",g=null,y=null,E=null;for(let f=0;f<e.length;f++){let d=e[f],p=e[f+1];d==="-p"||d==="--print"?(t=!0,p&&!p.startsWith("-")&&(n=p,f++)):d==="--workspace"||d==="-w"?p&&!p.startsWith("-")&&(r=p,f++):d==="--no-capture"?o=!0:d==="--resume"||d==="-r"?(s=!0,p&&!p.startsWith("-")&&(i=p,f++)):d==="--pipelines"?a=!0:d==="--pipelines-tools"?l=!0:d.startsWith("--pipelines-tools=")?(l=!0,c=d.slice(18)==="restricted"?"restricted":"board"):d==="--session-id"?p&&!p.startsWith("-")&&(g=p,f++):d==="--model"?p&&!p.startsWith("-")&&(y=p,f++):d==="--effort"&&p&&Vr.includes(p)&&(E=p,f++)}return{printMode:t,printPrompt:n,workspace:r,noCapture:o,resume:s,resumeSessionId:i,pipelines:a,pipelinesTools:l,pipelinesToolsMode:c,sessionId:g,model:y,effort:E}}var pn={name:"superclawd",version:"0.1.86",description:"Claude Code, supercharged \u2014 your team's standards, every session. The superclawd CLI loads your workspace's skills, agents, commands, workflows, and live directives into Claude Code as a plugin.",author:"SuperClawd <support@superclawd.com>",license:"SEE LICENSE IN LICENSE",homepage:"https://superclawd.com",repository:{type:"git",url:"https://github.com/superclawd-ai/superclawd"},bugs:{url:"https://github.com/superclawd-ai/superclawd/issues"},keywords:["superclawd","claude-code","claude","plugin","skills","agents","mcp","ai-assistant","coding-standards","model-context-protocol"],engines:{node:">=20"},type:"module",main:"dist/index.js",bin:{superclawd:"dist/index.js"},files:["dist","README.md","LICENSE"],scripts:{build:"node build.mjs",dev:"node build.mjs && tsx src/index.ts",typecheck:"tsc --noEmit",lint:"eslint 'src/**/*.{ts,tsx}'","lint:fix":"eslint 'src/**/*.{ts,tsx}' --fix",format:"prettier --check 'src/**/*.{ts,tsx}'","format:fix":"prettier --write 'src/**/*.{ts,tsx}'",selftest:"tsx test/mcp-selftest.ts","test:guardrails":"tsx test/guardrails-eval.test.ts",test:"node build.mjs && tsx test/mcp-selftest.ts && tsx test/pipelines-tools.test.ts && tsx test/guardrails-eval.test.ts && tsx test/hooks-capture.test.ts && tsx test/translator-teams.test.ts && tsx test/run-args.test.ts && tsx test/pipelines.test.ts && tsx test/update-check.test.ts && tsx test/retrieve.test.ts && tsx test/config-private-memory.test.ts && tsx test/config-choose-workspace.test.ts && tsx test/config.test.ts && tsx test/translator-basics.test.ts && tsx test/hook-helper-guardrails.test.ts && tsx test/capture-prompts.test.ts && tsx test/mcp-backend-real.test.ts && tsx test/catalog.test.ts",prepublishOnly:"npm run build","publish:npm":"npm publish","version:bump":"npm version patch --no-git-tag-version"},dependencies:{"@modelcontextprotocol/sdk":"^1.7.0",zod:"^3.24.2"},devDependencies:{"@eslint/js":"^9.39.1","@types/node":"^22.10.0","@typescript-eslint/eslint-plugin":"^8.44.1","@typescript-eslint/parser":"^8.44.1",esbuild:"^0.24.0",eslint:"^9.36.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4",prettier:"^3.6.2",tsx:"^4.19.0",typescript:"^5.7.0"}};var Ne=pn.version,he=process.env.SUPERCLAWD_DRY_RUN==="1"||process.argv.includes("--dry-run");function no(){try{let e=Qr("git remote get-url origin",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(e)return e.replace(/\.git$/,"").toLowerCase()}catch{}return`dir:${Zr(process.cwd())}`}function ro(){if(process.env.SUPERCLAWD_MCP_SERVER_PATH)return process.env.SUPERCLAWD_MCP_SERVER_PATH;let e=dn(new URL("./mcp-server.mjs",import.meta.url));return mn(e)?e:dn(new URL("../dist/mcp-server.mjs",import.meta.url))}function oo(){return`superclawd \u2014 Claude Code, supercharged with your SuperClawd workspace.
241
+ `;for(let k of d)m+=`${k}
242
+ `;let x=`v${t}`;m+=`${v}[${Math.max(1,R-1)};${Math.max(1,c-x.length-1)}H${j}${x}${A}`,W(m)},h=(d,c,R)=>{let S=process.stdout.columns||80,m="Select your workspace \u2191/\u2193 \xB7 enter launches \xB7 d sets default \xB7 esc cancels",I=Math.max(0,Math.floor((S-m.length)/2)),x=C=>` ${C.name} ${C.slug} \xB7 ${C.role}`,k=Math.max(...d.map(C=>x(C).length)),p=Math.max(0,Math.floor((S-k)/2)),g=[`${q(I)}${J}${m}${A}`,""];for(let C=0;C<d.length;C++){let F=d[C],te=C===c,ne=te?`${j}\u276F `:" ",ve=te?`${j}${F.name}${A}`:F.name,Pe=F.slug===R?` ${j}\u2605 default${A}`:"";g.push(`${q(p)}${ne}${ve} ${J}${F.slug} \xB7 ${F.role}${A}${Pe}`)}E(g)};return{phase:(d,c)=>P(d-1,c,yo),ready:d=>P(e,d,ko),message(d){let c=process.stdout.columns||80,R=Math.max(0,Math.floor((c-d.length)/2));E([`${q(R)}${J}${d}${A}`]),r=Date.now()},selectWorkspace(d,c){return new Promise(R=>{let S=c?.currentSlug?d.findIndex(k=>k.slug===c.currentSlug):-1,m=S>=0?S:0,I=c?.defaultSlug;s&&process.stdin.off("data",i),h(d,m,I);let x=k=>{let p=k.toString();p===""||p===v?(process.stdin.off("data",x),R(null)):p==="\r"||p===`
243
+ `?(process.stdin.off("data",x),process.stdin.on("data",i),R(d[m].slug)):p==="d"||p==="D"?(I=d[m].slug,c?.onSetDefault?.(I),h(d,m,I)):p===`${v}[A`||p==="k"?(m=(m-1+d.length)%d.length,h(d,m,I)):(p===`${v}[B`||p==="j")&&(m=(m+1)%d.length,h(d,m,I))};process.stdin.on("data",x)})},fail(d){o&&a(),o=!1,y(),process.stderr.write(`${Re}\u2717 ${d}${A}
244
+ `)},note(){},handoff(){s&&(process.stdin.off("data",i),process.stdin.pause(),s=!1),W(Ve+Je),process.off("SIGINT",f),process.off("SIGTERM",f)},finish(){o&&a(),o=!1,y()}}}function vo(){return process.platform!=="win32"?!0:!!(process.env.WT_SESSION||process.env.TERM_PROGRAM||process.env.TERM)}function Po(){return{async phase(){},message(){},async selectWorkspace(e,t){return t?.currentSlug??e[0]?.slug??null},async ready(){},fail(e){process.stderr.write(`${Re}\u2717 ${e}${A}
245
+ `)},note(){},handoff(){},finish(){}}}function bn(e){if(e.quiet)return Po();let t=process.stdout.isTTY===!0,n=e.version??"";return e.plain||!t||!vo()?Co(e.total,n):_o(e.total,n)}var Mo=["text","json","stream-json"],bo=["auto"],Ao=/^(?:0*[1-9]\d*(?:\.\d+)?|0*\.\d*[1-9]\d*|0+\.\d*[1-9]\d*)$/,xo=/^[1-9]\d*$/,$o=["low","medium","high","xhigh","max"];function An(e){let t=!1,n="",r=null,o=!1,s=!1,i=!1,l=null,u=!1,a=!1,f="board",w=null,y=null,b=null,P=!1,E=null,h=null,d=null,c=null,R=!1,S=null,m=null,I=[],x=(k,p,g)=>p!==void 0&&!p.startsWith("--")&&g(p)?p:(I.push(k),null);for(let k=0;k<e.length;k++){let p=e[k],g=e[k+1];if(p==="-p"||p==="--print")t=!0,g&&!g.startsWith("-")&&(n=g,k++);else if(p==="--workspace"||p==="-w")g&&!g.startsWith("-")&&(r=g,k++);else if(p==="--no-capture")o=!0;else if(p==="--no-memory")s=!0;else if(p==="--resume"||p==="-r")i=!0,g&&!g.startsWith("-")&&(l=g,k++);else if(p==="--pipelines")u=!0;else if(p==="--pipelines-tools")a=!0;else if(p.startsWith("--pipelines-tools="))a=!0,f=p.slice(18)==="restricted"?"restricted":"board";else if(p==="--session-id")g&&!g.startsWith("-")&&(w=g,k++);else if(p==="--model")g&&!g.startsWith("-")&&(y=g,k++);else if(p==="--fda")P=!0;else if(p==="--plan-only")R=!0;else if(p==="--agent")E=x(p,g,C=>!C.startsWith("-")),E!==null&&k++;else if(p==="--prompt-file")h=x(p,g,C=>!C.startsWith("-")),h!==null&&k++;else if(p==="--output-format"){let C=x(p,g,F=>Mo.includes(F));C!==null&&(d=C,k++)}else if(p==="--permission-mode"){let C=x(p,g,F=>bo.includes(F));C!==null&&(c=C,k++)}else p==="--max-budget-usd"?(S=x(p,g,C=>Ao.test(C)),S!==null&&k++):p==="--max-turns"?(m=x(p,g,C=>xo.test(C)),m!==null&&k++):p==="--effort"&&g&&$o.includes(g)&&(b=g,k++)}return{printMode:t,printPrompt:n,workspace:r,noCapture:o,noMemory:s,resume:i,resumeSessionId:l,pipelines:u,pipelinesTools:a,pipelinesToolsMode:f,sessionId:w,model:y,effort:b,fda:P,agent:E,promptFile:h,outputFormat:d,permissionMode:c,planOnly:R,maxBudgetUsd:S,maxTurns:m,invalid:I}}var xn={name:"superclawd",version:"0.1.88",description:"Claude Code, supercharged \u2014 your team's standards, every session. The superclawd CLI loads your workspace's skills, agents, commands, workflows, and live directives into Claude Code as a plugin.",author:"SuperClawd <support@superclawd.com>",license:"SEE LICENSE IN LICENSE",homepage:"https://superclawd.com",repository:{type:"git",url:"https://github.com/superclawd-ai/superclawd"},bugs:{url:"https://github.com/superclawd-ai/superclawd/issues"},keywords:["superclawd","claude-code","claude","plugin","skills","agents","mcp","ai-assistant","coding-standards","model-context-protocol"],engines:{node:">=20"},type:"module",main:"dist/index.js",bin:{superclawd:"dist/index.js"},files:["dist","README.md","LICENSE"],scripts:{build:"node build.mjs",dev:"node build.mjs && tsx src/index.ts",typecheck:"tsc --noEmit",lint:"eslint 'src/**/*.{ts,tsx}'","lint:fix":"eslint 'src/**/*.{ts,tsx}' --fix",format:"prettier --check 'src/**/*.{ts,tsx}'","format:fix":"prettier --write 'src/**/*.{ts,tsx}'",selftest:"tsx test/mcp-selftest.ts","test:guardrails":"tsx test/guardrails-eval.test.ts",test:"node build.mjs && tsx test/mcp-selftest.ts && tsx test/pipelines-tools.test.ts && tsx test/guardrails-eval.test.ts && tsx test/hooks-capture.test.ts && tsx test/translator-teams.test.ts && tsx test/run-args.test.ts && tsx test/pipelines.test.ts && tsx test/update-check.test.ts && tsx test/retrieve.test.ts && tsx test/config-private-memory.test.ts && tsx test/config-choose-workspace.test.ts && tsx test/config.test.ts && tsx test/translator-basics.test.ts && tsx test/hook-helper-guardrails.test.ts && tsx test/capture-prompts.test.ts && tsx test/mcp-backend-real.test.ts && tsx test/catalog.test.ts && tsx test/fda.test.ts && tsx test/models.test.ts",prepublishOnly:"npm run build","publish:npm":"npm publish","version:bump":"npm version patch --no-git-tag-version"},dependencies:{"@modelcontextprotocol/sdk":"^1.7.0",zod:"^3.24.2"},devDependencies:{"@eslint/js":"^9.39.1","@types/node":"^22.10.0","@typescript-eslint/eslint-plugin":"^8.44.1","@typescript-eslint/parser":"^8.44.1",esbuild:"^0.24.0",eslint:"^9.36.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.4",prettier:"^3.6.2",tsx:"^4.19.0",typescript:"^5.7.0"}};var Fo=Date.now();function ee(e){process.env.SUPERCLAWD_TIMING==="1"&&process.stderr.write(`[timing] ${Date.now()-Fo} ms ${e}
246
+ `)}var _e=xn.version,Ce=process.env.SUPERCLAWD_DRY_RUN==="1"||process.argv.includes("--dry-run");function No(){try{let e=Lo("git remote get-url origin",{encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim();if(e)return e.replace(/\.git$/,"").toLowerCase()}catch{}return`dir:${To(process.cwd())}`}function jo(){if(process.env.SUPERCLAWD_MCP_SERVER_PATH)return process.env.SUPERCLAWD_MCP_SERVER_PATH;let e=$n(new URL("./mcp-server.mjs",import.meta.url));return In(e)?e:$n(new URL("../dist/mcp-server.mjs",import.meta.url))}function Go(){return`superclawd \u2014 Claude Code, supercharged with your SuperClawd workspace.
242
247
 
243
248
  Usage:
244
249
  superclawd Launch Claude with your skills/agents/directives loaded
@@ -249,6 +254,7 @@ Usage:
249
254
  superclawd config Toggle launch options + default notifications preference
250
255
  superclawd update Update to the latest version (npm i -g superclawd)
251
256
  superclawd pipelines [start|stop|status|update] Run the local Pipelines app (start opens your browser)
257
+ superclawd fda <command> SuperClawd FDA (forward deployed agent) machine commands
252
258
  superclawd version
253
259
  superclawd help
254
260
 
@@ -256,22 +262,22 @@ Run flags:
256
262
  --workspace <id> Workspace for the run (highest precedence: flag \u2192 SUPERCLAWD_MCP_WORKSPACE \u2192 stored default).
257
263
  Interactive with none set \u2192 prompts; print mode with none \u2192 errors.
258
264
  Print-mode flags (with -p):
259
- --model <alias> Model for the run (e.g. haiku, sonnet, opus) \u2014 forwarded to claude
265
+ --model <alias> Model for the run: a family (opus, fable, sonnet, haiku = the latest of it) or an exact model id
260
266
  --effort <level> Reasoning effort: low | medium | high | xhigh | max
261
267
  --no-capture Don't write learned memories for this run (handy for behavior tests)
268
+ --no-memory No SuperClawd memory for this run (nothing loaded, no memory tools, no capture)
262
269
 
263
270
  Not authenticated yet? Run \`superclawd login\` first.
264
- `}function so(){try{return!zr("claude",["--version"],{stdio:"ignore"}).error}catch{return!1}}function io(e,t=[],n,r,o,s,i){let a=["--plugin-dir",e.pluginDir];a.push("--allowedTools",Et);for(let l of t)a.push("--allowedTools",`mcp__plugin_superclawd_${l}__*`);return(Ye()||n)&&a.push("--dangerously-skip-permissions"),r?(a.push("--resume"),r.sessionId&&a.push(r.sessionId)):o&&a.push("--session-id",o),s&&a.push("--model",s),i&&a.push("--effort",i),n&&a.push("-p",n.prompt),new Promise(l=>{let c=fn("claude",a,{stdio:"inherit",env:{...process.env,CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"}});c.on("error",g=>l({code:127,error:`Could not launch claude: ${g.message}. Is Claude Code installed and on PATH?`})),c.on("close",g=>l({code:g??137}))})}function ao(){return process.stdout.write(`Updating superclawd (npm i -g superclawd@latest)\u2026
265
- `),new Promise(e=>{let t=fn("npm install -g superclawd@latest",{stdio:"inherit",shell:!0});t.on("error",n=>{process.stderr.write(`\u2717 Could not run npm: ${n.message}. Is npm on your PATH?
271
+ `}function Yo(){try{return!Io("claude",["--version"],{stdio:"ignore"}).error}catch{return!1}}function Ko(e,t=[],n,r,o,s,i,l={}){let u=["--plugin-dir",e.pluginDir];u.push(...gn(t,{planOnly:l.planOnly,permissionMode:l.permissionMode,skipPermissions:nt()||!!n})),l.agent&&u.push("--agent",l.agent),l.outputFormat&&(u.push("--output-format",l.outputFormat),l.outputFormat==="stream-json"&&u.push("--verbose")),l.maxBudgetUsd&&u.push("--max-budget-usd",l.maxBudgetUsd),l.maxTurns&&u.push("--max-turns",l.maxTurns),r?(u.push("--resume"),r.sessionId&&u.push(r.sessionId)):o&&u.push("--session-id",o),s&&u.push("--model",s),i&&u.push("--effort",i);let a=n&&l.promptOnStdin?n.prompt:null;return n&&(u.push("-p"),a===null&&u.push(n.prompt)),new Promise(f=>{let w=On("claude",u,{stdio:a!==null?["pipe","inherit","inherit"]:"inherit",env:process.env.SUPERCLAWD_MEMORY_OFF==="1"?{...process.env}:{...process.env,CLAUDE_CODE_DISABLE_AUTO_MEMORY:"1"}});a!==null&&w.stdin&&(w.stdin.on("error",()=>{}),w.stdin.end(a)),l.fda&&Ke(w),w.on("error",y=>f({code:127,error:`Could not launch claude: ${y.message}. Is Claude Code installed and on PATH?`})),w.on("close",(y,b)=>f({code:y??Be(b)}))})}function Bo(){return process.stdout.write(`Updating superclawd (npm i -g superclawd@latest)\u2026
272
+ `),new Promise(e=>{let t=On("npm install -g superclawd@latest",{stdio:"inherit",shell:!0});t.on("error",n=>{process.stderr.write(`\u2717 Could not run npm: ${n.message}. Is npm on your PATH?
266
273
  `),e(127)}),t.on("close",n=>{n===0?process.stdout.write("\u2713 Updated. Run `superclawd version` to confirm.\n"):process.stderr.write(`\u2717 Update failed (npm exited ${n}).
267
- `),e(n??1)})})}async function co(e){if(e.printMode&&!e.printPrompt.trim())return process.stderr.write(`Provide a prompt: superclawd -p "<your prompt>"
268
- `),1;if(e.pipelines&&(process.env.SUPERCLAWD_NO_UPDATE="1"),e.pipelinesTools&&(process.env.SUPERCLAWD_PIPELINES_TOOLS=e.pipelinesToolsMode),!he){let f=await ct(Ne,process.argv.slice(2));if(f.exitCode!==void 0)return f.exitCode}if(e.noCapture&&(process.env.SUPERCLAWD_NO_CAPTURE="1"),!he&&!so())return process.stderr.write(`\u2717 Claude Code isn't installed (or isn't on your PATH).
274
+ `),e(n??1)})})}async function Ho(e){let t=null,n=(c,R)=>(t?.(),t=null,e.fda?he(c,R):(process.stderr.write(`${R}
275
+ `),1)),r;if(e.fda){if(e.invalid.length)return n("badFlags",`Invalid value for: ${[...new Set(e.invalid)].join(", ")}`);if(!e.promptFile)return n("badFlags","--fda requires --prompt-file (the prompt never goes on the command line).");if(e.printPrompt)return n("badFlags","Use either -p <prompt> or --prompt-file, not both.");if(e.planOnly&&e.permissionMode)return n("badFlags","--plan-only and --permission-mode are exclusive.");let c=cn(process.env.SUPERCLAWD_FDA_MCP_FILE);if(!c)return n("badFlags","SUPERCLAWD_FDA_MCP_FILE is missing, unreadable, or has no FDA server.");r=c}if(e.promptFile)try{e={...e,printMode:!0,printPrompt:Do(e.promptFile,"utf8")}}catch(c){return n("badFlags",`Cannot read --prompt-file: ${String(c)}`)}if(e.printMode&&!e.printPrompt.trim())return n("badFlags",'Provide a prompt: superclawd -p "<your prompt>"');if((e.pipelines||e.fda)&&(process.env.SUPERCLAWD_NO_UPDATE="1"),e.pipelinesTools&&(process.env.SUPERCLAWD_PIPELINES_TOOLS=e.pipelinesToolsMode),!Ce&&!e.fda){let c=await kt(_e,process.argv.slice(2));if(c.exitCode!==void 0)return c.exitCode}if(e.noCapture&&(process.env.SUPERCLAWD_NO_CAPTURE="1"),e.noMemory&&(process.env.SUPERCLAWD_MEMORY_OFF="1",process.env.SUPERCLAWD_NO_CAPTURE="1"),!Ce&&!Yo())return e.fda?n("claudeMissing","Claude Code isn't installed or isn't on PATH."):(process.stderr.write(`\u2717 Claude Code isn't installed (or isn't on your PATH).
269
276
 
270
277
  SuperClawd supercharges Claude Code, so you'll need it first:
271
278
  \u2192 https://claude.com/code
272
279
 
273
280
  Once it's installed, run \`superclawd\` again.
274
- `),1;S||Qe(),!S&&He()&&(process.env.SUPERCLAWD_EXPERIMENTAL="true"),process.env.SUPERCLAWD_REPO_FINGERPRINT=no();let t=et();if(!t.ok&&!S)return process.stderr.write(`${t.error??"Could not resolve credentials."}
275
- `),1;let n=t.session;e.workspace&&(n={...n,workspace:e.workspace});let r=ln({total:5,plain:he,quiet:e.printMode,version:Ne});if(!S&&!e.printMode&&!e.workspace&&process.stdin.isTTY&&(!n.workspace||Be())){let f=await Pe(r,n);if(f.cancelled)return r.finish(),130;f.workspace&&(n={...n,workspace:f.workspace})}if(!S&&!n.workspace)return r.finish(),process.stderr.write("No workspace selected. Pass --workspace <id>, set SUPERCLAWD_MCP_WORKSPACE, or run `superclawd` interactively once to pick a default.\n"),1;await r.phase(1,"Resolving credentials\u2026"),await r.phase(2,"Authenticating\u2026");let o=await _e(n);if(o.workspaceInvalid&&!S&&!e.printMode&&!e.workspace&&process.stdin.isTTY){oe();let f=await Pe(r,{...n,workspace:""});if(f.cancelled)return r.finish(),130;f.workspace&&(n={...n,workspace:f.workspace},await r.phase(2,"Authenticating\u2026"),o=await _e(n))}if(!o.ok)return r.fail(o.error??"Authentication failed."),1;await r.phase(3,S?"Loading mock catalog\u2026":"Fetching your workspace\u2026");let s;try{s=await St(n)}catch(f){return r.fail(`Catalog fetch failed: ${String(f)}`),1}process.env.SUPERCLAWD_TEAM_MEMORY=s.teamMemoryEnabled?"1":"0",process.env.SUPERCLAWD_REPO_MEMORY=s.repoMemoryEnabled?"1":"0",process.env.SUPERCLAWD_AGENT_MEMORY=s.agentMemoryEnabled?"1":"0",process.env.SUPERCLAWD_PRIVATE_MEMORY=S||Je()?"1":"0",await r.phase(4,"Establishing session\u2026"),Qt();let i=Xt();ze(i.dir,n.workspace,e.pipelines===!0);let a=ro();if(!mn(a))return r.fail(`Bundled MCP server not found at ${a}. Run \`npm run build\` first.`),1;await kt(n,i.id,e.pipelines!==!0),await r.phase(5,"Generating plugin\u2026");let l=Jt({pluginDir:i.pluginDir,session:n,catalog:s,serverPath:a,launchId:i.id});if(!S)try{let f=to(eo(a),"hook-helper.mjs"),d=Lt({cwd:process.cwd(),helperPath:f,env:{SUPERCLAWD_BACKEND:J,SUPERCLAWD_MCP_API_URL:n.apiUrl,SUPERCLAWD_REPO_FINGERPRINT:process.env.SUPERCLAWD_REPO_FINGERPRINT,SUPERCLAWD_MCP_KEY:n.keyId,SUPERCLAWD_MCP_SECRET:n.secret,SUPERCLAWD_MCP_WORKSPACE:n.workspace,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,SUPERCLAWD_HOME:process.env.SUPERCLAWD_HOME,SUPERCLAWD_CLAUDE_BIN:process.env.SUPERCLAWD_CLAUDE_BIN,SUPERCLAWD_POLICY_MODEL:process.env.SUPERCLAWD_POLICY_MODEL}});!d.installed&&d.reason!=="not a git repo"&&r.note(`Post-commit hook: ${d.reason}`)}catch{}let c=S?"mock":n.workspace;if(await r.ready(`${c} \xB7 ${l.skillCount} skills \xB7 ${l.commandCount} commands \xB7 ${l.workflowCount} workflows`),he){r.note("Dry run \u2014 not launching Claude. Generated files:");for(let f of l.files)r.note(` ${f}`);return 0}r.handoff();let g=!S&&qe()?nt():null,{code:y,error:E}=await io(i,l.mcpServerNames,e.printMode?{prompt:e.printPrompt}:void 0,e.resume?{sessionId:e.resumeSessionId}:void 0,e.sessionId,e.model,e.effort);return g?.stop(),r.finish(),zt(i),E&&process.stderr.write(`${E}
276
- `),E?127:y}async function lo(){let e=await Zt();return e.cancelled||e.ok?0:(process.stderr.write(`\u2717 ${e.error??"Login failed."}
277
- `),1)}async function uo(){let[e]=process.argv.slice(2).filter(t=>t!=="--dry-run");switch(e){case"login":process.exit(await lo());return;case"config":await en(),process.exit(0);return;case"update":process.exit(await ao());return;case"pipelines":{let t=process.argv.slice(2).filter(n=>n!=="--dry-run");process.exit(await Bt(t.slice(t.indexOf("pipelines")+1)));return}case"version":case"--version":case"-v":console.log(Ne);return;case"help":case"--help":case"-h":console.log(oo());return;default:process.exit(await co(un(process.argv.slice(2))))}}uo().catch(e=>{cn(String(e)),process.exit(1)});
281
+ `),1);_||ut(),!_&&ot()&&(process.env.SUPERCLAWD_EXPERIMENTAL="true"),process.env.SUPERCLAWD_REPO_FINGERPRINT=No();let o=pt();if(!o.ok&&!_)return n("credentials",o.error??"Could not resolve credentials.");let s=o.session;e.workspace&&(s={...s,workspace:e.workspace});let i=bn({total:5,plain:Ce,quiet:e.printMode,version:_e});if(t=()=>i.finish(),!_&&!e.printMode&&!e.workspace&&process.stdin.isTTY&&(!s.workspace||rt())){let c=await Oe(i,s);if(c.cancelled)return i.finish(),130;c.workspace&&(s={...s,workspace:c.workspace})}if(!_&&!s.workspace)return n("workspaceInvalid","No workspace selected. Pass --workspace <id>, set SUPERCLAWD_MCP_WORKSPACE, or run `superclawd` interactively once to pick a default.");await i.phase(1,"Resolving credentials\u2026"),await i.phase(2,"Authenticating\u2026");let l=e.fda?De(s).then(c=>({c}),c=>({e:c})):null;ee("start \u2192 auth");let u=await Ie(s);if(ee("auth done"),u.workspaceInvalid&&!_&&!e.printMode&&!e.workspace&&process.stdin.isTTY){le();let c=await Oe(i,{...s,workspace:""});if(c.cancelled)return i.finish(),130;c.workspace&&(s={...s,workspace:c.workspace},await i.phase(2,"Authenticating\u2026"),u=await Ie(s))}if(!u.ok)return e.fda?n(u.kind==="credentials"?"credentials":u.kind==="workspace"?"workspaceInvalid":"cloudUnavailable",u.error??"Authentication failed."):(i.fail(u.error??"Authentication failed."),1);await i.phase(3,_?"Loading mock catalog\u2026":"Fetching your workspace\u2026");let a;try{if(l){let c=await l;if("e"in c)throw c.e;a=c.c}else a=await De(s);ee("catalog done")}catch(c){return e.fda?n("cloudUnavailable",`Catalog fetch failed: ${String(c)}`):(i.fail(`Catalog fetch failed: ${String(c)}`),1)}if(e.noMemory&&(a=xt(a)),process.env.SUPERCLAWD_TEAM_MEMORY=a.teamMemoryEnabled?"1":"0",process.env.SUPERCLAWD_REPO_MEMORY=a.repoMemoryEnabled?"1":"0",process.env.SUPERCLAWD_AGENT_MEMORY=a.agentMemoryEnabled?"1":"0",process.env.SUPERCLAWD_PRIVATE_MEMORY=_||it()?"1":"0",e.noMemory)for(let c of["SUPERCLAWD_TEAM_MEMORY","SUPERCLAWD_REPO_MEMORY","SUPERCLAWD_AGENT_MEMORY","SUPERCLAWD_PRIVATE_MEMORY"])process.env[c]="0";await i.phase(4,"Establishing session\u2026"),wn();let f=Sn();ct(f.dir,s.workspace,e.pipelines===!0||e.fda);let w=jo();if(!In(w)){we(f);let c=`Bundled MCP server not found at ${w}. Run \`npm run build\` first.`;return e.fda?n("badFlags",c):(i.fail(c),1)}await $t(s,f.id,e.pipelines!==!0&&!e.fda),ee("session established"),e.fda&&(process.env.SUPERCLAWD_FOUNDATIONAL_FROM_LAUNCH="1"),await i.phase(5,"Generating plugin\u2026");let y=mn({pluginDir:f.pluginDir,session:s,catalog:a,serverPath:w,launchId:f.id,fda:e.fda,fdaServers:r}),b=e.agent?.startsWith("superclawd:")?e.agent.slice(11):null;if(b!==null&&!y.agentSlugs.includes(b))return we(f),n("agentNotFound",`Agent "${b}" isn't available in this workspace (deleted or disabled?).`);if(!_&&!e.fda)try{let c=Wo(Uo(w),"hook-helper.mjs"),R=Ht({cwd:process.cwd(),helperPath:c,env:{SUPERCLAWD_BACKEND:z,SUPERCLAWD_MCP_API_URL:s.apiUrl,SUPERCLAWD_REPO_FINGERPRINT:process.env.SUPERCLAWD_REPO_FINGERPRINT,SUPERCLAWD_MCP_KEY:s.keyId,SUPERCLAWD_MCP_SECRET:s.secret,SUPERCLAWD_MCP_WORKSPACE:s.workspace,NODE_EXTRA_CA_CERTS:process.env.NODE_EXTRA_CA_CERTS,SUPERCLAWD_HOME:process.env.SUPERCLAWD_HOME,SUPERCLAWD_CLAUDE_BIN:process.env.SUPERCLAWD_CLAUDE_BIN,SUPERCLAWD_POLICY_MODEL:process.env.SUPERCLAWD_POLICY_MODEL}});!R.installed&&R.reason!=="not a git repo"&&i.note(`Post-commit hook: ${R.reason}`)}catch{}let P=_?"mock":s.workspace;if(await i.ready(`${P} \xB7 ${y.skillCount} skills \xB7 ${y.commandCount} commands \xB7 ${y.workflowCount} workflows`),Ce){i.note("Dry run \u2014 not launching Claude. Generated files:");for(let c of y.files)i.note(` ${c}`);return 0}i.handoff();let E=!_&&st()?mt():null;ee("spawning claude");let{code:h,error:d}=await Ko(f,y.mcpServerNames,e.printMode?{prompt:e.printPrompt}:void 0,e.resume?{sessionId:e.resumeSessionId}:void 0,e.sessionId,re(e.model,a.modelFamilies),e.effort,{agent:e.agent,outputFormat:e.outputFormat,permissionMode:e.permissionMode,planOnly:e.planOnly,maxBudgetUsd:e.maxBudgetUsd,maxTurns:e.maxTurns,promptOnStdin:!!e.promptFile,fda:e.fda});return E?.stop(),i.finish(),we(f),d&&e.fda?he("claudeMissing",d):(d&&process.stderr.write(`${d}
282
+ `),d?127:h)}async function qo(){let e=await yn();return e.cancelled||e.ok?0:(process.stderr.write(`\u2717 ${e.error??"Login failed."}
283
+ `),1)}async function Jo(){let[e]=process.argv.slice(2).filter(t=>t!=="--dry-run");switch(e){case"login":process.exit(await qo());return;case"config":await kn(),process.exit(0);return;case"update":process.exit(await Bo());return;case"pipelines":{let t=process.argv.slice(2).filter(n=>n!=="--dry-run");process.exit(await sn(t.slice(t.indexOf("pipelines")+1)));return}case"fda":{let t=process.argv.slice(2);process.exit(await dn(t.slice(t.indexOf("fda")+1)));return}case"version":case"--version":case"-v":process.argv.includes("--json")?console.log(JSON.stringify({version:_e,features:["fda-1","no-memory"]})):console.log(_e);return;case"help":case"--help":case"-h":console.log(Go());return;default:process.exit(await Ho(An(process.argv.slice(2))))}}Jo().catch(e=>{process.argv.includes("--fda")&&process.exit(he("badFlags",`Unexpected error: ${String(e)}`)),Mn(String(e)),process.exit(1)});