@hlix/cli 0.7.2 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +35 -34
- package/THIRD_PARTY_NOTICES +1 -28
- package/bin/hlix +1 -1
- package/dist/index-8rhfsnj8.js +399 -0
- package/dist/index.js +3 -3
- package/dist/main-exs93wtp.js +147 -0
- package/dist/package-32h7hjkw.js +2 -0
- package/package.json +11 -10
- package/skills/hlix/SKILL.md +23 -120
- package/dist/index-70g03k87.js +0 -446
- package/dist/main-73kw5ktg.js +0 -144
- package/dist/package-844qvsxr.js +0 -2
|
@@ -0,0 +1,399 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
class e extends Error{code;details;constructor(j,T,O){super(T);if(this.name="CliError",this.code=j,O!==void 0)this.details=O}}var R=1,oe=(j,T)=>({schemaVersion:1,command:j,data:T}),Ot=(j,T)=>({schemaVersion:1,command:j,error:T});function re(j){return`${JSON.stringify(j,null,2)}
|
|
3
|
+
`}function ke(j){let T=Math.max(0,...j.map(([O])=>O.length));return j.map(([O,N])=>`${O.padEnd(T)} ${N}`).join(`
|
|
4
|
+
`)}function Je(j,T){let O=j.map((F,L)=>Math.max(F.length,...T.map((H)=>(H[L]??"").length))),N=(F)=>F.map((L,H)=>L.padEnd(O[H])).join(" ").trimEnd();return[N(j),N(O.map((F)=>"-".repeat(F))),...T.map(N)].join(`
|
|
5
|
+
`)}import{statSync as fa}from"node:fs";import{dirname as ga,resolve as ha}from"node:path";import{closeSync as Kn,constants as Nt,existsSync as yn,fsyncSync as Bs,lstatSync as qn,mkdirSync as ra,openSync as Gs,readFileSync as Ws,renameSync as sa,statSync as zs,unlinkSync as Ks,writeFileSync as oa}from"node:fs";import{homedir as ia}from"node:os";import{dirname as aa,join as Vn}from"node:path";function Me(j=process.env){let T=j.HLIX_CONFIG_HOME??j.XDG_CONFIG_HOME??Vn(ia(),".config");return Vn(T,"hlix","credentials.json")}function qs(j=process.env){let T=j.HLIX_API_KEY;if(!T&&j.HLIX_SESSION_TOKEN)return{baseUrl:j.HLIX_BASE_URL??"https://server.hlix.ai",apiKey:"",sessionToken:j.HLIX_SESSION_TOKEN,...j.HLIX_WORKSPACE_ID?{organizationId:j.HLIX_WORKSPACE_ID}:{}};if(T)return{baseUrl:j.HLIX_BASE_URL??"https://server.hlix.ai",apiKey:T,...j.HLIX_WORKSPACE_ID?{organizationId:j.HLIX_WORKSPACE_ID}:{}};try{let O=JSON.parse(Ws(Me(j),"utf8"));return O.apiKey&&O.baseUrl?O:null}catch{return null}}function Vs(j=process.env){let T=Me(j);return yn(T)?T:null}function Xn(j=process.env){let T=Me(j);if(!yn(T))return{path:T,removed:!1,reason:"absent"};let O=qn(T);if(O.isSymbolicLink()||!O.isFile())throw Error("Refusing to remove a credential path that is not a regular file.");let N=process.getuid?.();if(N!==void 0&&zs(T).uid!==N)throw Error("Refusing to remove a credential file owned by another user.");let F;try{F=JSON.parse(Ws(T,"utf8"))}catch{F=null}let L=F;if(!L||typeof L.apiKey!=="string"||typeof L.baseUrl!=="string")throw Error(`Refusing to remove ${T}: it is not a credential written by this CLI.`);return Ks(T),{path:T,removed:!0,reason:"removed"}}function Xs(j,T=process.env){let O=Me(T),N=aa(O);if(ra(N,{recursive:!0,mode:448}),qn(N).isSymbolicLink())throw Error("Refusing to write credentials through a symlinked directory.");if(yn(O)){let H=qn(O);if(H.isSymbolicLink()||!H.isFile())throw Error("Refusing to replace a credential path that is not a regular file.");let M=process.getuid?.();if(M!==void 0&&zs(O).uid!==M)throw Error("Refusing to replace a credential file owned by another user.")}let F=Vn(N,`.credentials.${process.pid}.${crypto.randomUUID()}.tmp`),L;try{L=Gs(F,Nt.O_WRONLY|Nt.O_CREAT|Nt.O_EXCL|Nt.O_NOFOLLOW,384),oa(L,`${JSON.stringify(j,null,2)}
|
|
6
|
+
`,"utf8"),Bs(L),Kn(L),L=void 0,sa(F,O);let H=Gs(N,Nt.O_RDONLY);try{try{Bs(H)}catch(M){let U=M.code;if(U!=="EINVAL"&&U!=="ENOTSUP")throw M}}finally{Kn(H)}}catch(H){if(L!==void 0)Kn(L);if(yn(F))Ks(F);throw H}return O}import{constants as wn,existsSync as Zn,lstatSync as Qn,mkdirSync as ca,openSync as la,closeSync as Ys,fsyncSync as pa,readFileSync as Zs,renameSync as da,unlinkSync as ua,writeFileSync as Yn}from"node:fs";import{dirname as ma,join as Ft,resolve as vn}from"node:path";function Qs(j){if(!Zn(j))return;let T=Qn(j);if(T.isSymbolicLink()||!T.isFile())throw Error(`Refusing to replace a non-regular Hlix file: ${j}`)}function Lt(j,T){let O=ma(j);if(ca(O,{recursive:!0,mode:448}),Qn(O).isSymbolicLink())throw Error(`Refusing to write through a symlinked Hlix directory: ${O}`);Qs(j);let N=Ft(O,`.hlix-${process.pid}-${crypto.randomUUID()}.tmp`),F;try{F=la(N,wn.O_WRONLY|wn.O_CREAT|wn.O_EXCL|wn.O_NOFOLLOW,384),Yn(F,`${JSON.stringify(T,null,2)}
|
|
7
|
+
`,"utf8"),pa(F),Ys(F),F=void 0,da(N,j)}catch(L){if(F!==void 0)Ys(F);if(Zn(N))ua(N);throw L}}function Ht(j){return Ft(vn(j),".hlix","config.json")}function eo(j){return Ft(vn(j),".hlix","state.json")}function ht(j){try{let T=JSON.parse(Zs(Ht(j),"utf8"));return T.schemaVersion===1&&T.workspaceId&&T.apiUrl?T:null}catch{return null}}function bn(j,T){Lt(Ht(j),T);let O=Ft(vn(j),".hlix",".gitignore");if(!Zn(O))Yn(O,`state.json
|
|
8
|
+
`,{mode:420,flag:"wx"});Qs(O);let N=Ft(vn(j),".hlixignore");if(!Qn(N,{throwIfNoEntry:!1}))Yn(N,`# Additional project-local paths to exclude from Hlix snapshots.
|
|
9
|
+
`,{mode:420,flag:"wx"})}function er(j,T){Lt(eo(j),{...T,snapshotOnly:T.snapshotOnly??s(j)?.snapshotOnly,includedPaths:T.includedPaths??s(j)?.includedPaths})}function s(j){try{let T=JSON.parse(Zs(eo(j),"utf8"));return T.schemaVersion===1&&T.repoId&&/^[a-f0-9]{40}$/.test(T.commitSha)?T:null}catch{return null}}var tr="https://server.hlix.ai";function p(j){if(!j.credential)return null;if(j.credentialSource==="session")return"session (desktop)";if(j.credentialSource==="env")return"environment (HLIX_API_KEY)";return`file (${j.credentialPath})`}function t(j){let T=ha(j);for(;;){let O=ht(T);if(O)return{root:T,config:O};let N=ga(T);if(N===T)return null;T=N}}function no(j){try{return fa(j).isDirectory()}catch{return!1}}function kn(j){if(typeof j!=="string")return;let T=j.trim();return T?T:void 0}var to=(j,T)=>j.replace(/\/+$/,"")===T.replace(/\/+$/,"");function r(j){let{env:T,flags:O,cwd:N}=j,F=t(N),L=qs(T),H=L?T.HLIX_API_KEY?"env":T.HLIX_SESSION_TOKEN?"session":"file":null,M=H==="file"?L:null,U=kn(O["base-url"]),D=kn(T.HLIX_BASE_URL),J=kn(O.workspace),B=kn(T.HLIX_WORKSPACE_ID),W=U??D??F?.config.apiUrl??M?.baseUrl??tr,Y=U?"flag":D?"env":F?.config.apiUrl?"project":M?.baseUrl?"credential":"default",ee=J??B??F?.config.workspaceId??M?.organizationId??null,X=J?"flag":B?"env":F?.config.workspaceId?"project":M?.organizationId?"credential":null;return{baseUrl:W,baseUrlSource:Y,workspaceId:ee,workspaceSource:X,credential:L,credentialSource:H,credentialPath:Me(T),binding:F,conflict:ya(F,{flagBaseUrl:U,envBaseUrl:D,flagWorkspace:J,envWorkspace:B})}}function ya(j,T){if(!j)return null;let O=`${j.root} is bound to`,N="Drop the override, or point --cwd at a folder bound to it.";if(T.flagWorkspace&&T.flagWorkspace!==j.config.workspaceId)return`${O} workspace ${j.config.workspaceId}, but --workspace names ${T.flagWorkspace}. ${N}`;if(T.envWorkspace&&T.envWorkspace!==j.config.workspaceId)return`${O} workspace ${j.config.workspaceId}, but HLIX_WORKSPACE_ID names ${T.envWorkspace}. ${N}`;if(T.flagBaseUrl&&!to(T.flagBaseUrl,j.config.apiUrl))return`${O} ${j.config.apiUrl}, but --base-url names ${T.flagBaseUrl}. ${N}`;if(T.envBaseUrl&&!to(T.envBaseUrl,j.config.apiUrl))return`${O} ${j.config.apiUrl}, but HLIX_BASE_URL names ${T.envBaseUrl}. ${N}`;return null}import{resolve as Ta}from"node:path";import{parseArgs as Aa}from"node:util";import wa from"openapi-fetch";function nr(j){return wa({baseUrl:j.baseUrl,headers:j.headers,fetch:j.fetch})}var yt=(j)=>({kind:"apiKey",apiKey:j});var rr=(j)=>({kind:"bearer",token:j});function va(j){switch(j.kind){case"apiKey":return{"x-api-key":j.apiKey};case"session":return{cookie:j.cookie};case"bearer":return{authorization:`Bearer ${j.token}`}}}function ba(j){return j?{"X-Organization-Id":j}:{}}function ro(j,T){return{...va(j),...ba(T)}}function ka(j){if(typeof j!=="object"||j===null)return null;let{error:T}=j;return typeof T==="string"?T:null}class Ae extends Error{status;body;requestId;method;url;constructor(j,T){super(j);this.name=new.target.name,this.status=T.status,this.body=T.body,this.requestId=T.requestId??null,this.method=T.method,this.url=T.url}}class wt extends Ae{issues;constructor(j,T,O){super(j,T);this.issues=O}}class Mt extends Ae{}class Ut extends Ae{}class Dt extends Ae{}class nt extends Ae{}class Jt extends Ae{}class Bt extends Ae{retryAfter;constructor(j,T,O){super(j,T);this.retryAfter=O}}class Gt extends Ae{}class Wt extends Ae{}class vt extends Error{method;url;constructor(j,T){super(j,{cause:T.cause});this.name="HlixTransportError",this.method=T.method,this.url=T.url}}function Sa(j){if(typeof j!=="object"||j===null)return null;let T=j;if(T.success!==!1)return null;let O=T.error?.message;if(typeof O!=="string")return null;try{let N=JSON.parse(O);return Array.isArray(N)?N:[]}catch{return[]}}function ja(j){let T=j.get("retry-after");if(!T)return null;let O=Number(T);return Number.isFinite(O)&&O>=0?O:null}function rt(j,T,O){let N={status:j.status,body:T,requestId:j.headers.get("x-request-id"),method:O.method,url:O.url},F=ka(T),L=`${O.method} ${O.url} failed with ${j.status}`,H=Sa(T);if(H)return new wt(`${O.method} ${O.url}: request body failed validation`,N,H);let M=F??L;switch(j.status){case 400:return new Mt(M,N);case 401:return new Ut(M,N);case 403:return new Dt(M,N);case 404:return new nt(M,N);case 409:return new Jt(M,N);case 429:return new Bt(M,N,ja(j.headers));case 501:return new Gt(M,N);default:return j.status>=500?new Wt(M,N):new Ae(M,N)}}var so=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function Sn(j){return so.has(j.toUpperCase())}var Ea=new Set([429,500,502,503,504]);function xa(j){return Ea.has(j)}var sr={attempts:3,baseDelayMs:200,maxDelayMs:5000};function or(j,T,O,N=Math.random){if(O!==null)return Math.min(O*1000,T.maxDelayMs);let F=Math.min(T.baseDelayMs*2**j,T.maxDelayMs);return Math.round(N()*F)}function ir(j){if(!Sn(j.method))return!1;if(j.attempt+1>=j.policy.attempts)return!1;return j.status===null||xa(j.status)}var Pa=(j)=>new Promise((T)=>setTimeout(T,j));function $a(j){let T=j.headers.get("retry-after");if(!T)return null;let O=Number(T);return Number.isFinite(O)&&O>=0?O:null}function oo(j){let{base:T,policy:O}=j,N=j.sleep??Pa,F=j.random??Math.random;return async(L)=>{let H=L.method.toUpperCase(),M=Sn(H)?L.clone():null;for(let U=0;;U+=1){let D=U===0?L:M.clone(),J;try{J=await T(D)}catch(B){if(!M||!ir({method:H,attempt:U,policy:O,status:null}))throw new vt(`${H} ${L.url}: ${B instanceof Error?B.message:String(B)}`,{method:H,url:L.url,cause:B});await N(or(U,O,null,F));continue}if(!ir({method:H,attempt:U,policy:O,status:J.status}))return J;if(!M)return J;await N(or(U,O,$a(J),F))}}}function ie(j,T){if(j.response.ok)return j.data;throw rt(j.response,j.error??j.data,T)}var zt=(j)=>typeof j==="string"?j:"";function ar(j){let T;try{T=JSON.parse(j)}catch{return null}if(typeof T!=="object"||T===null)return null;let O=T;switch(O.type){case"idle":return{type:"idle"};case"done":return{type:"done"};case"active":return typeof O.runId==="string"?{type:"active",runId:O.runId}:{type:"active"};case"on_chat_model_stream":return{type:"on_chat_model_stream",delta:zt(O.delta)};case"reasoning":return{type:"reasoning",delta:zt(O.delta)};case"on_tool_start":return{type:"on_tool_start",name:zt(O.name),input:O.input};case"on_tool_end":return{type:"on_tool_end",name:zt(O.name),output:O.output};case"error":return{type:"error",message:zt(O.message)};default:return null}}var cr=(j)=>j.type==="done"||j.type==="idle"||j.type==="error";var _a=()=>({event:null,data:[],id:null,retry:null});function io(j,T,O){switch(T){case"event":j.event=O;return;case"data":j.data.push(O);return;case"id":if(!O.includes("\x00"))j.id=O;return;case"retry":{if(/^\d+$/.test(O))j.retry=Number(O);return}default:return}}function co(j){let T=j.data.join(`
|
|
10
|
+
`),{event:O,id:N}=j;if(j.data=[],j.event=null,T==="")return null;return{event:O,data:T,id:N,retry:j.retry}}function ao(j,T){if(T==="")return co(j);if(T.startsWith(":"))return null;let O=T.indexOf(":");if(O===-1)return io(j,T,""),null;let N=T.slice(0,O),F=T.slice(O+1);if(F.startsWith(" "))F=F.slice(1);return io(j,N,F),null}function Ca(j){let T=[],O=0;for(let N=0;N<j.length;N+=1){let F=j[N];if(F!==`
|
|
11
|
+
`&&F!=="\r")continue;if(T.push(j.slice(O,N)),F==="\r"&&j[N+1]===`
|
|
12
|
+
`)N+=1;O=N+1}return{lines:T,rest:j.slice(O)}}async function*jn(j,T){let O=j.getReader(),N=new TextDecoder,F=_a(),L="",H=()=>void O.cancel().catch(()=>{});T?.addEventListener("abort",H,{once:!0});try{for(;;){let{done:U,value:D}=await O.read();if(U)break;L+=N.decode(D,{stream:!0});let{lines:J,rest:B}=Ca(L);L=B;for(let W of J){let Y=ao(F,W);if(Y)yield Y}if(T?.aborted)return}if(L+=N.decode(),L!==""){let U=ao(F,L);if(U)yield U}let M=co(F);if(M)yield M}finally{T?.removeEventListener("abort",H),O.releaseLock()}}function Kt(j,T){return new Promise((O)=>{if(T?.aborted)return O();let N=setTimeout(F,j);function F(){clearTimeout(N),T?.removeEventListener("abort",F),O()}T?.addEventListener("abort",F,{once:!0})})}var pr=()=>crypto.randomUUID();function uo(j){return{threadId:j.threadId,runId:j.runId??pr(),state:{},messages:[{id:j.messageId??pr(),role:"user",content:j.text}],tools:[],context:[],forwardedProps:j.forwardedProps??{}}}function mo(j){return{threadId:j,runId:pr(),state:{},messages:[],tools:[],context:[]}}function dr(j){let T;try{T=JSON.parse(j)}catch{return null}if(typeof T!=="object"||T===null)return null;return typeof T.type==="string"?T:null}function ur(j,T={}){if(T.taskId)return`project:${j}:task:${T.taskId}`;if(T.cycleId)return`project:${j}:cycle:${T.cycleId}`;return`project:${j}`}var Ia=new Set(["done","merged","failed","pr_created","ci_passing"]),Ra=new Set(["done","pr_created","failed","canceled"]);function mr(j,T){let O=j.tasks.find((H)=>H.id===T);if(!O)return{state:"running",task:O};let N=O.cycleId?j.cycles.find((H)=>H.id===O.cycleId):void 0;if(!(!O.cycleId||N!==void 0&&Ra.has(N.status)))return{state:"running",task:O};if(Ia.has(O.status))return{state:"finished",task:O};if(!N)return{state:"running",task:O};let L=N?.status==="canceled"?"Task cycle was canceled":N?.status==="failed"?"Task cycle failed":"Task cycle ended before this task completed";return{state:"unmet",task:O,reason:L}}async function*fr(j){let T;for await(let O of j){if(O.type==="STATE_SNAPSHOT")T=structuredClone(O.snapshot);else if(O.type==="STATE_DELTA"){if(T===void 0)continue;T=fo(T,O.delta)}else if(O.type!=="CUSTOM"||T===void 0)continue;yield{state:T,event:O}}}function gr(j){if(j==="")return[];if(!j.startsWith("/"))throw Error(`Invalid JSON pointer: ${j}`);return j.slice(1).split("/").map((T)=>T.replace(/~1/g,"/").replace(/~0/g,"~"))}function hr(j,T){let O=j;for(let N of T.slice(0,-1)){if(typeof O!=="object"||O===null)throw Error(`Path not found: /${T.join("/")}`);O=O[N]}if(typeof O!=="object"||O===null)throw Error(`Path not found: /${T.join("/")}`);return{parent:O,key:T[T.length-1]}}function En(j,T,O){if(T==="-"&&O)return j.length;let N=Number(T);if(!/^(0|[1-9]\d*)$/.test(T)||N>j.length||!O&&N===j.length)throw Error(`Invalid array index: ${T}`);return N}function lo(j,T){let O=gr(T);if(O.length===0)return j;let{parent:N,key:F}=hr(j,O);if(Array.isArray(N))return N[En(N,F,!1)];if(!(F in N))throw Error(`Path not found: ${T}`);return N[F]}function po(j,T){let{parent:O,key:N}=hr(j,gr(T));if(Array.isArray(O))return O.splice(En(O,N,!1),1)[0];if(!(N in O))throw Error(`Path not found: ${T}`);let F=O[N];return delete O[N],F}function lr(j,T,O,N){let F=gr(T);if(F.length===0)return O;let{parent:L,key:H}=hr(j,F);if(Array.isArray(L))if(N==="add")L.splice(En(L,H,!0),0,O);else L[En(L,H,!1)]=O;else{if(N==="replace"&&!(H in L))throw Error(`Path not found: ${T}`);L[H]=O}return j}function fo(j,T){let O=structuredClone(j);for(let N of T)switch(N.op){case"add":case"replace":O=lr(O,N.path,structuredClone(N.value),N.op);break;case"remove":po(O,N.path);break;case"copy":O=lr(O,N.path,structuredClone(lo(O,N.from)),"add");break;case"move":{let F=po(O,N.from);O=lr(O,N.path,F,"add");break}case"test":if(JSON.stringify(lo(O,N.path))!==JSON.stringify(N.value))throw Error(`Test failed at ${N.path}`);break;default:throw Error(`Unknown patch operation: ${N.op}`)}return O}class bt{raw;baseUrl;headers;fetcher;constructor(j){this.baseUrl=j.baseUrl.replace(/\/+$/,"");let T=ro(j.credential,j.organizationId),O=new Set(Object.keys(T).map((L)=>L.toLowerCase()));this.headers={...Object.fromEntries(Object.entries(j.headers??{}).filter(([L])=>!O.has(L.toLowerCase()))),...T};let N={...sr,...j.retry},F=j.fetch??((L)=>globalThis.fetch(L));this.fetcher=oo({base:F,policy:N}),this.raw=nr({baseUrl:this.baseUrl,headers:this.headers,fetch:this.fetcher})}at(j,T){return{method:j,url:`${this.baseUrl}${T}`}}workspaces={list:async(j={})=>ie(await this.raw.GET("/v1/api/workspaces",j),this.at("GET","/v1/api/workspaces"))};projects={list:async()=>ie(await this.raw.GET("/v1/api/projects"),this.at("GET","/v1/api/projects")),get:async(j,T={})=>ie(await this.raw.GET("/v1/api/projects/{id}",{...T,params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}`)),create:async(j)=>ie(await this.raw.POST("/v1/api/projects",{body:j}),this.at("POST","/v1/api/projects")),delete:async(j)=>ie(await this.raw.DELETE("/v1/api/projects/{id}",{params:{path:{id:j}}}),this.at("DELETE",`/v1/api/projects/${j}`)),start:async(j,T)=>ie(await this.raw.POST("/v1/api/projects/{id}/start",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/projects/${j}/start`)),stop:async(j)=>ie(await this.raw.POST("/v1/api/projects/{id}/stop",{params:{path:{id:j}}}),this.at("POST",`/v1/api/projects/${j}/stop`)),resume:async(j)=>ie(await this.raw.POST("/v1/api/projects/{id}/resume",{params:{path:{id:j}}}),this.at("POST",`/v1/api/projects/${j}/resume`)),status:async(j,T={})=>ie(await this.raw.GET("/v1/api/projects/{id}/status",{...T,params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}/status`)),deliver:async(j)=>ie(await this.raw.POST("/v1/api/projects/{id}/delivery",{params:{path:{id:j}}}),this.at("POST",`/v1/api/projects/${j}/delivery`)),attachGithubRepository:async(j,T)=>ie(await this.raw.POST("/v1/api/projects/{id}/repos/github",{params:{path:{id:j}},body:{githubRepository:T}}),this.at("POST",`/v1/api/projects/${j}/repos/github`)),terminal:async(j)=>ie(await this.raw.GET("/v1/api/projects/{id}/terminal",{params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}/terminal`)),observeAgent:(j,T,O)=>this.observeAgent(j,T,O),workspace:(j)=>({environment:async()=>ie(await this.raw.GET("/v1/api/projects/{id}/environment",{params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}/environment`)),fs:async(T)=>ie(await this.raw.POST("/v1/api/projects/{id}/workspace/fs",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/projects/${j}/workspace/fs`)),exec:async(T)=>ie(await this.raw.POST("/v1/api/projects/{id}/workspace/exec",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/projects/${j}/workspace/exec`))})};secrets={listEntries:async(j)=>ie(await this.raw.GET("/v1/api/secrets/project/{projectId}/entries",{params:{path:{projectId:j}}}),this.at("GET",`/v1/api/secrets/project/${j}/entries`)),upsertEntries:async(j,T)=>ie(await this.raw.PUT("/v1/api/secrets/project/{projectId}/entries",{params:{path:{projectId:j}},body:T}),this.at("PUT",`/v1/api/secrets/project/${j}/entries`)),importFiles:async(j,T)=>ie(await this.raw.PUT("/v1/api/secrets/project/{projectId}/files",{params:{path:{projectId:j}},body:{files:T}}),this.at("PUT",`/v1/api/secrets/project/${j}/files`)),deleteEntry:async(j,T,O)=>ie(await this.raw.DELETE("/v1/api/secrets/project/{projectId}/entries/{key}",{params:{path:{projectId:j,key:T},...O===void 0?{}:{query:{source:O}}}}),this.at("DELETE",`/v1/api/secrets/project/${j}/entries/${encodeURIComponent(T)}`)),exportEntries:async(j,T={})=>{let O=`/v1/api/secrets/project/${j}/export`,N=`${this.baseUrl}${O}`,F=await this.fetcher(new Request(N,{method:"POST",headers:{...this.headers,"content-type":"application/json"},body:JSON.stringify({...T.source===void 0?{}:{source:T.source},...T.format===void 0?{}:{format:T.format}})}));if(!F.ok)throw rt(F,await F.json().catch(()=>{return}),{method:"POST",url:N});return F.text()}};repos={access:async(j,T,O="read")=>ie(await this.raw.POST("/v1/api/projects/{id}/repos/{repoId}/access",{params:{path:{id:j,repoId:T}},body:{scope:O}}),this.at("POST",`/v1/api/projects/${j}/repos/${T}/access`)),head:async(j,T,O={})=>ie(await this.raw.GET("/v1/api/projects/{id}/repos/{repoId}/head",{...O,params:{path:{id:j,repoId:T}}}),this.at("GET",`/v1/api/projects/${j}/repos/${T}/head`)),protectedFiles:async(j)=>ie(await this.raw.GET("/v1/api/projects/{id}/protected-files",{params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}/protected-files`)),watch:(j,T,O={})=>this.watchRepo(j,T,O)};resources={importSkill:async(j,T)=>ie(await this.raw.POST("/v1/api/projects/{id}/resources/skill",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/projects/${j}/resources/skill`)),importAgent:async(j,T)=>ie(await this.raw.POST("/v1/api/projects/{id}/resources/agent",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/projects/${j}/resources/agent`)),importMcp:async(j,T)=>ie(await this.raw.POST("/v1/api/projects/{id}/resources/mcp",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/projects/${j}/resources/mcp`))};async throwUploadError(j,T){let O=null;try{O=await j.json()}catch{O=await j.text().catch(()=>null)}throw rt(j,O,{method:"PUT",url:T})}tasks={list:async(j)=>ie(await this.raw.GET("/v1/api/tasks",{params:{query:j??{}}}),this.at("GET","/v1/api/tasks")),get:async(j)=>ie(await this.raw.GET("/v1/api/tasks/{id}",{params:{path:{id:j}}}),this.at("GET",`/v1/api/tasks/${j}`)),create:async(j)=>ie(await this.raw.POST("/v1/api/tasks",{body:j}),this.at("POST","/v1/api/tasks")),update:async(j,T)=>ie(await this.raw.PATCH("/v1/api/tasks/{id}",{params:{path:{id:j}},body:T}),this.at("PATCH",`/v1/api/tasks/${j}`)),listComments:async(j)=>ie(await this.raw.GET("/v1/api/tasks/{id}/comments",{params:{path:{id:j}}}),this.at("GET",`/v1/api/tasks/${j}/comments`)),addComment:async(j,T)=>ie(await this.raw.POST("/v1/api/tasks/{id}/comments",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/tasks/${j}/comments`)),review:async(j)=>ie(await this.raw.GET("/v1/api/tasks/{id}/review",{params:{path:{id:j}}}),this.at("GET",`/v1/api/tasks/${j}/review`))};modelConfig={setProjectHarness:async(j,T)=>ie(await this.raw.PUT("/v1/api/model-config/harness/{projectId}",{params:{path:{projectId:j}},body:{harness:T}}),this.at("PUT",`/v1/api/model-config/harness/${j}`)),clearProjectHarness:async(j)=>ie(await this.raw.DELETE("/v1/api/model-config/harness/{projectId}",{params:{path:{projectId:j}}}),this.at("DELETE",`/v1/api/model-config/harness/${j}`)),setHarness:async(j)=>ie(await this.raw.PUT("/v1/api/model-config/harness",{body:{harness:j}}),this.at("PUT","/v1/api/model-config/harness")),clearHarness:async()=>ie(await this.raw.DELETE("/v1/api/model-config/harness"),this.at("DELETE","/v1/api/model-config/harness")),resolvedHarness:async()=>ie(await this.raw.GET("/v1/api/model-config/harness/resolved"),this.at("GET","/v1/api/model-config/harness/resolved")),resolvedProjectHarness:async(j)=>ie(await this.raw.GET("/v1/api/model-config/harness/{projectId}/resolved",{params:{path:{projectId:j}}}),this.at("GET",`/v1/api/model-config/harness/${j}/resolved`))};ai={models:async(j,T)=>ie(await this.raw.GET("/v1/api/ai/w/{workspaceId}/models",{params:{path:{workspaceId:j}},...T?.signal?{signal:T.signal}:{}}),this.at("GET",`/v1/api/ai/w/${j}/models`))};cycles={list:async(j)=>ie(await this.raw.GET("/v1/api/cycles",{params:{query:j??{}}}),this.at("GET","/v1/api/cycles")),get:async(j)=>ie(await this.raw.GET("/v1/api/cycles/{id}",{params:{path:{id:j}}}),this.at("GET",`/v1/api/cycles/${j}`)),propose:async(j)=>ie(await this.raw.POST("/v1/api/cycles",{body:j}),this.at("POST","/v1/api/cycles"))};chat={send:async(j)=>ie(await this.raw.POST("/v1/api/chat/turns",{body:j}),this.at("POST","/v1/api/chat/turns")),turn:async(j,T)=>ie(await this.raw.GET("/v1/api/chat/turns/{turnId}",{params:{path:{turnId:j},query:T}}),this.at("GET",`/v1/api/chat/turns/${j}`))};live={run:(j,T,O)=>this.liveStream(`/agent/${j}/run`,uo(T),O),connect:(j,T,O)=>this.liveStream(`/agent/${j}/connect`,mo(T),O),stop:async(j,T,O)=>{let N=`/agent/${j}/stop/${encodeURIComponent(T)}`;return await(await this.livePost(N,O?{runId:O}:{})).json()},project:(j,T={})=>fr(this.live.connect("project-live",ur(j,T),T)),task:(j,T,O={})=>this.watchTask(j,T,O)};async*watchTask(j,T,O){let N="";for await(let{state:F}of this.live.project(j,{taskId:T,...O})){let L=mr(F,T),H=JSON.stringify(L);if(H===N)continue;if(N=H,yield L,L.state!=="running")return}}async livePost(j,T,O){let N=`${this.baseUrl}/v1/api/live${j}`,F=await this.fetcher(new Request(N,{method:"POST",headers:{...this.headers,"content-type":"application/json",accept:"text/event-stream"},body:JSON.stringify(T),signal:O?.signal}));if(F.ok)return F;let L=null;try{L=await F.json()}catch{L=null}throw rt(F,L,{method:"POST",url:N})}async*liveStream(j,T,O){let N=await this.livePost(j,T,O);if(!N.body)return;try{for await(let F of jn(N.body,O?.signal)){let L=dr(F.data);if(!L)continue;if(yield L,L.type==="RUN_FINISHED"||L.type==="RUN_ERROR")return}}finally{N.body.cancel().catch(()=>{})}}pendingRequests={list:async(j)=>ie(await this.raw.GET("/v1/api/pending-requests",{params:{query:j??{}}}),this.at("GET","/v1/api/pending-requests")),resolve:async(j,T)=>ie(await this.raw.POST("/v1/api/pending-requests/{id}/resolve",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/pending-requests/${j}/resolve`))};clientInvoices={list:async(j)=>ie(await this.raw.GET("/v1/api/client-billing/invoices",{params:{query:j??{}}}),this.at("GET","/v1/api/client-billing/invoices")),get:async(j)=>ie(await this.raw.GET("/v1/api/client-billing/invoices/{id}",{params:{path:{id:j}}}),this.at("GET",`/v1/api/client-billing/invoices/${j}`)),createDraft:async(j)=>ie(await this.raw.POST("/v1/api/client-billing/invoices",{body:j}),this.at("POST","/v1/api/client-billing/invoices")),issue:async(j)=>ie(await this.raw.POST("/v1/api/client-billing/invoices/{id}/issue",{params:{path:{id:j}},body:{}}),this.at("POST",`/v1/api/client-billing/invoices/${j}/issue`)),void:async(j,T)=>ie(await this.raw.POST("/v1/api/client-billing/invoices/{id}/void",{params:{path:{id:j}},body:{reason:T}}),this.at("POST",`/v1/api/client-billing/invoices/${j}/void`)),pay:async(j)=>ie(await this.raw.POST("/v1/api/client-billing/invoices/{id}/pay",{params:{path:{id:j}},body:{}}),this.at("POST",`/v1/api/client-billing/invoices/${j}/pay`)),paymentLink:async(j,T={})=>ie(await this.raw.POST("/v1/api/client-billing/invoices/{id}/payment-link",{params:{path:{id:j}},body:T}),this.at("POST",`/v1/api/client-billing/invoices/${j}/payment-link`))};async*observeAgent(j,T,O){let N=`/v1/api/projects/${j}/agents/${T}/observe`;for await(let F of this.stream(N,O)){let L=ar(F.data);if(!L)continue;if(yield L,cr(L))return}}async*watchRepo(j,T,O){let N;while(!O.signal?.aborted){let F=await this.repos.head(j,T,O);if(F.commitSha!==N)N=F.commitSha,yield{commitSha:N};await Kt(15000,O.signal)}}async*stream(j,T){let O=`${this.baseUrl}${j}`,N=new Request(O,{headers:{...this.headers,accept:"text/event-stream"},signal:T?.signal}),F=await globalThis.fetch(N);if(!F.ok||!F.body){let L=null;try{L=await F.json()}catch{L=null}throw rt(F,L,{method:"GET",url:O})}yield*jn(F.body,T?.signal)}}function yr(j){if(j instanceof e)return{code:j.code,status:null};if(j instanceof wt)return{code:"invalid_request",status:400};if(j instanceof Mt)return{code:"bad_request",status:400};if(j instanceof Ut)return{code:"unauthenticated",status:401};if(j instanceof Dt)return{code:"forbidden",status:403};if(j instanceof nt)return{code:"not_found",status:404};if(j instanceof Jt)return{code:"conflict",status:409};if(j instanceof Bt)return{code:"rate_limited",status:429};if(j instanceof Gt)return{code:"not_implemented",status:501};if(j instanceof Wt)return{code:"server_error",status:j.status};if(j instanceof vt)return{code:"unreachable",status:null};return{code:"unknown",status:null}}var xn=(j)=>{if(j instanceof wt&&j.issues.length>0){let T=j.issues.slice(0,5).map((N)=>{let F=N;return` - ${Array.isArray(F.path)&&F.path.length>0?`${F.path.join(".")}: `:""}${typeof F.message==="string"?F.message:JSON.stringify(N)}`}),O=j.issues.length-T.length;return`${j.message}
|
|
13
|
+
${T.join(`
|
|
14
|
+
`)}${O>0?`
|
|
15
|
+
… ${O} more`:""}`}return j instanceof Error?j.message:String(j)};function n(j,T){let O=r({env:j,flags:T.flags,cwd:T.cwd});if(O.conflict)throw new e("workspace_mismatch",O.conflict);if(!O.credential)throw new e("unauthenticated","No credential. Run `hlix auth login`, or set HLIX_API_KEY for CI.");return new bt({baseUrl:O.baseUrl,credential:O.credential.sessionToken?rr(O.credential.sessionToken):yt(O.credential.apiKey),...O.workspaceId?{organizationId:O.workspaceId}:{}})}function go(j){let T=Math.max(...j.map((N)=>N.name.length));return`hlix — the hlix control-plane CLI
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
hlix <command> [options]
|
|
19
|
+
|
|
20
|
+
Commands:
|
|
21
|
+
${[` hlix ${"".padEnd(T)} Open Hlix Code (interactive)`,...j.map((N)=>` hlix ${N.name.padEnd(T)} ${N.summary}`)].join(`
|
|
22
|
+
`)}
|
|
23
|
+
|
|
24
|
+
Options:
|
|
25
|
+
--json Machine-readable output (a versioned, stable contract)
|
|
26
|
+
--cwd <dir> Operate on another directory instead of the current one
|
|
27
|
+
--workspace <id> Workspace to act in, overriding the folder's binding
|
|
28
|
+
--base-url <url> API to talk to, overriding the folder's binding
|
|
29
|
+
--help Show this help
|
|
30
|
+
--version Show the installed CLI version
|
|
31
|
+
|
|
32
|
+
Hlix Code (hlix with no command):
|
|
33
|
+
--sandbox <choice> cloud, docker or local; --local is short for local
|
|
34
|
+
--docker-image <r> image the docker sandbox runs in
|
|
35
|
+
--harness <name> which coder does the work
|
|
36
|
+
--project <id> project to act in, when this folder is not bound
|
|
37
|
+
-p "<prompt>" one turn, print the answer, exit
|
|
38
|
+
--json with -p: one JSON object per event instead of prose
|
|
39
|
+
--allow-writes with -p: let the turn change files and run commands
|
|
40
|
+
--yolo approve every tool call for the whole session
|
|
41
|
+
|
|
42
|
+
A command targets the workspace named by, in order: an explicit flag, the
|
|
43
|
+
HLIX_* environment, the nearest .hlix/config.json, then the stored credential.
|
|
44
|
+
Run \`hlix status\` to see which one applied.
|
|
45
|
+
`}function yo(j,T){let O=[...Array(T.length+1).keys()];for(let N=1;N<=j.length;N+=1){let F=[N];for(let L=1;L<=T.length;L+=1)F[L]=Math.min(O[L]+1,F[L-1]+1,O[L-1]+(j[N-1]===T[L-1]?0:1));O=F}return O[T.length]}function Oa(j,T,O){let N=/Unknown option '--([^'=]+)/.exec(O)?.[1];if(!N)return O;let F=T.findIndex((U)=>U.startsWith("-")),L=F===-1?T:T.slice(0,F),H=new Set(["json","help","version","cwd","workspace","base-url",...Pn(j,L)?.command.options??[]]),M=null;for(let U of H){let D=yo(N,U);if(D<=2&&(!M||D<M.distance))M={name:U,distance:D}}return M?`${O}
|
|
46
|
+
Did you mean --${M.name}?`:O}function ho(j,T){let O=new Set;for(let L of j)O.add(L.name),O.add(L.name.split(" ")[0]);let N=null;for(let L of O){let H=yo(T,L);if(H<=2&&(!N||H<N.distance))N={name:L,distance:H}}if(!N)return null;if(j.some((L)=>L.name===N.name))return N.name;let F=j.filter((L)=>L.name.startsWith(`${N.name} `)).sort((L,H)=>L.name.length-H.name.length)[0];return F?F.name:N.name}function Pn(j,T){for(let O of[...j].sort((N,F)=>F.name.length-N.name.length)){let N=O.name.split(" ");if(N.every((F,L)=>T[L]===F))return{command:O,rest:T.slice(N.length)}}return null}function Na(j,T,O){let N=Oa(j,T,O);if(!/^Unknown option '/.test(O))return N;let F=N.replace(/\. To specify a positional argument[\s\S]*?after '--'[^\n]*/,"."),L=Pn(j,T.filter((H)=>!H.startsWith("-")));return L?`${F}
|
|
47
|
+
|
|
48
|
+
${L.command.usage}`:F}async function a(j,T,O){if(T.some((q)=>q==="--api-key"||q.startsWith("--api-key=")))return O.stderr("error: API keys are never accepted as command-line arguments. Run `hlix auth login` and use the hidden prompt.\n"),2;let N;try{N=Aa({args:T,allowPositionals:!0,strict:!0,options:{json:{type:"boolean"},help:{type:"boolean"},version:{type:"boolean"},cwd:{type:"string"},"base-url":{type:"string"},workspace:{type:"string"},"dry-run":{type:"boolean"},"no-connect-origin":{type:"boolean"},attach:{type:"boolean"},print:{type:"boolean"},web:{type:"boolean"},"env-file":{type:"string"},include:{type:"string"},history:{type:"string"},name:{type:"string"},stack:{type:"string"},status:{type:"string"},project:{type:"string"},yes:{type:"boolean"},global:{type:"boolean"},org:{type:"boolean"},title:{type:"string"},description:{type:"string"},force:{type:"boolean"},runtime:{type:"string"},duty:{type:"string"},profile:{type:"string"},server:{type:"string"},"allow-stdio":{type:"boolean"},source:{type:"string"},format:{type:"string"},out:{type:"string"},"from-stdin":{type:"boolean"},once:{type:"boolean"}}})}catch(q){let ne=T.includes("--json"),de=Na(j,T,xn(q));if(O.onFailure?.({code:"invalid_usage",message:de,status:null}),ne)O.stdout(re(Ot("cli",{code:"invalid_usage",message:de,status:null})));else O.stderr(`${de}
|
|
49
|
+
`);return 2}let F=N.values.json===!0,L=N.positionals;if(N.values.version===!0){let{version:q}=await import("./package-32h7hjkw.js");return O.stdout(`${q}
|
|
50
|
+
`),0}if(L.length===0||N.values.help===!0){let q=Pn(j,L);return O.stdout(q?`${q.command.usage}
|
|
51
|
+
`:go(j)),L.length===0&&N.values.help!==!0?1:0}let H=Pn(j,L);if(!H){let q=L.join(" "),ne=ho(j,q)??ho(j,L[0]),de=ne?`Unknown command: ${q}
|
|
52
|
+
Did you mean \`hlix ${ne}\`?`:`Unknown command: ${q}`;if(O.onFailure?.({code:"unknown_command",message:de,status:null}),F)O.stdout(re(Ot(q,{code:"unknown_command",message:de,status:null})));else O.stderr(`${de}
|
|
53
|
+
|
|
54
|
+
${go(j)}`);return 2}let M=new Set(["json","help","version","cwd","workspace","base-url"]),U=new Set(H.command.options??[]),D=Object.entries(N.values).filter(([q,ne])=>ne!==void 0&&!M.has(q)&&!U.has(q)).map(([q])=>`--${q}`),J=H.command.args??{min:0,max:0},B=H.rest.length<J.min?{code:"missing_argument",message:H.command.usage.split(`
|
|
55
|
+
`)[0]}:H.rest.length>J.max?{code:"invalid_usage",message:H.command.usage.split(`
|
|
56
|
+
`)[0]}:null,W=typeof N.values.cwd==="string"?N.values.cwd:void 0,Y=Ta(W??"."),ee=W!==void 0&&!no(Y)?{code:"invalid_usage",message:`--cwd is not a directory: ${Y}`}:null,X=D.length>0?{code:"invalid_usage",message:`Unsupported option for ${H.command.name}: ${D.join(", ")}`}:ee??B;if(X){if(O.onFailure?.({...X,status:null}),F)O.stdout(re(Ot(H.command.name,{...X,status:null})));else{let q=H.command.usage.startsWith(X.message)?H.command.usage:`${X.message}
|
|
57
|
+
|
|
58
|
+
${H.command.usage}`;O.stderr(`error: ${q}
|
|
59
|
+
`)}return 2}let V=N.values,Q={...O,args:H.rest,json:F,flags:V,cwd:Y,requireClient:(q)=>n(O.env,{cwd:q??Y,flags:V})};try{return await H.command.run(Q)}catch(q){let{code:ne,status:de}=yr(q);if(O.onFailure?.({code:ne,message:xn(q),status:de,...q instanceof e&&q.details!==void 0?{details:q.details}:{}}),F)O.stdout(re(Ot(H.command.name,{code:ne,message:xn(q),status:de})));else if(O.stderr(`error: ${xn(q)}
|
|
60
|
+
`),process.env.HLIX_DEBUG&&q instanceof Error&&q.stack)O.stderr(`${q.stack}
|
|
61
|
+
`);return ne==="unauthenticated"||ne==="forbidden"?3:1}}import{readFileSync as Fa}from"node:fs";import{homedir as La}from"node:os";import{join as Ha}from"node:path";var wo=20000;function u(j){if(j===void 0)return;let T=typeof j==="number"?j:Number(j.trim());return Number.isInteger(T)&&T>=wo?T:void 0}var c=["cloud","docker","local"],Ma={"claude-code":!0,codex:!0,"cursor-agent":!0,hlix:!0},o=Object.keys(Ma),m="hlix",vo={dockerImage:"docker sandbox only",harness:"local and docker sandboxes only",memoryTokens:"all sandboxes",model:"local and docker sandboxes only",sandbox:"all sandboxes",yolo:"all sandboxes"},kt=["dockerImage","harness","memoryTokens","model","sandbox","yolo"],wr=["projectId","workspaceId","apiUrl"];function vr(j=process.env){return Ha(j.HLIX_CONFIG_HOME??La(),".hlix","config.json")}function bo(j=process.env){try{let T=JSON.parse(Fa(vr(j),"utf8"));return T.schemaVersion===1?T:null}catch{return null}}function g(j,T=process.env){let O=bo(T),N=t(j),F=N?.root??null,L=N?.config??null,H={},M={},U=(D)=>{let J=L?.[D],B=O?.[D];if(J!==void 0)H[D]=J,M[D]="project";else if(B!==void 0)H[D]=B,M[D]="global"};for(let D of kt)U(D);for(let D of wr){let J=L?.[D];if(J!==void 0)H[D]=J,M[D]="project"}return{merged:H,sources:M,global:O,project:L,paths:{global:vr(T),project:F?Ht(F):null}}}function ko(j){return[...kt,...wr].map((O)=>({key:O,value:j.merged[O]??null,source:j.sources[O]??"default"}))}function Ua(j,T){if(j==="sandbox"&&!c.includes(T))return`sandbox must be one of ${c.join(", ")}; got "${T}".`;if(j==="harness"&&!o.includes(T))return`harness must be one of ${o.join(", ")}; got "${T}".`;if(j==="model"&&T.trim()==="")return"model must not be empty.";if(j==="memoryTokens"&&u(T)===void 0)return`memoryTokens must be a whole number of tokens, at least ${wo}; got "${T}".`;if(j==="dockerImage"&&T.trim()==="")return"dockerImage must not be empty.";if(j==="yolo"&&v(T)===void 0)return`yolo must be true or false; got "${T}".`;return null}function v(j){if(j===void 0)return;let T=j.trim().toLowerCase();if(["true","1","yes","on"].includes(T))return!0;if(["false","0","no","off"].includes(T))return!1;return}function br(j){if(kt.includes(j))return j;let T=wr.includes(j);throw new e("invalid_usage",T?`${j} is written by \`hlix init\` and \`hlix import\`, not by \`hlix config set\`.`:`Unknown setting: ${j}. Known settings: ${kt.join(", ")}.`)}function So(j,T){let O=Ua(j,T);if(O)throw new e("invalid_usage",O);return T}function h(j){if(j.scope==="global"){let N=vr(j.env),F=bo(j.env)??{schemaVersion:1};return Lt(N,{...F,[j.key]:j.value}),N}let T=t(j.cwd);if(!T)throw new e("not_initialized","This folder is not bound to hlix. Run `hlix init` here, or set it machine-wide with --global.");let O=Ht(T.root);return Lt(O,{...T.config,[j.key]:j.value}),O}import{createHash as Da}from"node:crypto";import{mkdirSync as Ja,readdirSync as _o,readFileSync as Ba,rmSync as Ga,statSync as Co,writeFileSync as Wa}from"node:fs";import{homedir as za,tmpdir as Ka}from"node:os";import{basename as Io,isAbsolute as qa,join as ue,relative as Va}from"node:path";var i=(j=process.env)=>j.HOME??j.USERPROFILE??za();function Ce(j){try{if(!Co(j).isFile())return null;return Ba(j,"utf8")}catch{return null}}function Xa(j){try{return Co(j).isDirectory()}catch{return!1}}function St(j,T){try{return _o(j,{withFileTypes:!0}).filter((O)=>O.isFile()&&O.name.endsWith(T)).map((O)=>ue(j,O.name)).sort()}catch{return[]}}function Ya(j){try{return _o(j,{withFileTypes:!0}).filter((T)=>T.isDirectory()||T.isSymbolicLink()).map((T)=>ue(j,T.name)).sort()}catch{return[]}}function Sr(j){let T=j.replace(/^\uFEFF/,""),O=T.indexOf(`
|
|
62
|
+
`);if(!T.startsWith("---")||O===-1)return{fields:{},body:T.trim()};let N=T.indexOf(`
|
|
63
|
+
---`,O);if(N===-1)return{fields:{},body:T.trim()};let F={};for(let H of T.slice(O+1,N).split(`
|
|
64
|
+
`)){let M=/^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(H);if(!M)continue;F[M[1]]=M[2].trim().replace(/^["']|["']$/g,"")}let L=T.indexOf(`
|
|
65
|
+
`,N+1);return{fields:F,body:L===-1?"":T.slice(L+1).trim()}}function Za(j){let T=j.trimStart(),O=/^"((?:[^"\\]|\\.)*)"/.exec(T)??/^'([^']*)'/.exec(T);if(O)return O[1].replace(/\\"/g,'"').replace(/\\n/g,`
|
|
66
|
+
`);if(T.startsWith("["))return[...T.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((F)=>F[1]??F[2]??"");if(T.startsWith("{")){let F={};for(let L of T.matchAll(/([A-Za-z0-9_.-]+)\s*=\s*"((?:[^"\\]|\\.)*)"/g))F[L[1]]=L[2].replace(/\\"/g,'"');return F}let N=/^[^\s#]+/.exec(T)?.[0];if(N===void 0)return;if(N==="true"||N==="false")return N==="true";if(/^-?\d+(\.\d+)?$/.test(N))return Number(N);return N}function Ro(j){let T={"":{}},O="",N=j.split(`
|
|
67
|
+
`);for(let F=0;F<N.length;F+=1){let H=N[F].trim();if(!H||H.startsWith("#"))continue;let M=/^\[\[?([^\]]+)\]\]?$/.exec(H);if(M){O=M[1].trim(),T[O]??={};continue}let U=/^([A-Za-z0-9_.-]+|"[^"]+")\s*=\s*(.*)$/.exec(H);if(!U)continue;let D=U[1].replace(/^"|"$/g,""),J=U[2];if(J.startsWith('"""')){let W=[],Y=J.slice(3);if(Y.includes('"""'))W.push(Y.slice(0,Y.indexOf('"""')));else{if(Y)W.push(Y);while(F+1<N.length){F+=1;let ee=N[F],X=ee.indexOf('"""');if(X===-1){W.push(ee);continue}W.push(ee.slice(0,X));break}}T[O][D]=W.join(`
|
|
68
|
+
`).replace(/^\n/,"");continue}let B=Za(J);if(B!==void 0)T[O][D]=B}return T}function kr(j,T){return j.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g,(O,N,F)=>{let L=T[N];return L!==void 0&&L!==""?L:F??""})}var jo=(j,T)=>{let O={};for(let[N,F]of Object.entries(j))if(typeof F==="string")O[N]=kr(F,T);return O},Qa=[{relative:"GEMINI.md",source:"gemini"},{relative:ue(".gemini","GEMINI.md"),source:"gemini"},{relative:".cursorrules",source:"cursor"},{relative:".windsurfrules",source:"windsurf"},{relative:ue(".github","copilot-instructions.md"),source:"copilot"}],ec=[{relative:ue(".gemini","GEMINI.md"),source:"gemini"}],tc=[{relative:ue(".cursor","rules"),source:"cursor",extension:".mdc"},{relative:ue(".windsurf","rules"),source:"windsurf",extension:".md"}];function nc(j,T){let O=ue(j,".clinerules"),N=Xa(O)?St(O,".md"):[O],F=[];for(let L of N){let H=Ce(L)?.trim();if(H)F.push({path:L,source:"cline",scope:T,content:H})}return F}function rc(j,T,O){let{fields:N,body:F}=Sr(T);if(N.alwaysApply==="false")return{path:j,source:"cursor",scope:O,reason:"alwaysApply: false"};if(!F)return{path:j,source:"cursor",scope:O,reason:"no rule body"};let L=N.globs?.replace(/^\[|\]$/g,"").trim();return{path:j,source:"cursor",scope:O,content:F,...L?{note:`Applies to: ${L}`}:{}}}var sc=["AGENTS.md","CLAUDE.md"],To=["",".claude"],E=["commands"];function oc(j,T){let O=[],N=new Set;for(let F of[...To,T])for(let L of sc){let H=ue(j,F,L),M=Ce(H)?.trim();if(!M||N.has(M))continue;N.add(M),O.push({path:H,content:M})}return O}function Eo(j,T){return oc(j,T).map((O)=>O.content)}var f=["AGENTS.md","CLAUDE.md","GEMINI.md"];function jr(j,T){for(let O of f)for(let N of[...To,T]){let F=ue(j,N,O),L=Ce(F)?.trim();if(L)return{path:F,content:L}}return null}var Er=(j=process.env)=>ue(j.HLIX_CONFIG_HOME??ue(i(j),".hlix"),"AGENTS.md");function y(j){let T=j.env??process.env,O=Er(T),N=Ce(O)?.trim();return{global:N?{path:O,content:N}:null,project:jr(j.cwd,j.configDir)}}var xo=(j)=>{let T=Math.round(j.length/4);return T>=1000?`${(T/1000).toFixed(1)}k tokens`:`${T} tokens`};function _(j,T,O=process.env){let N=[...j.global?[Oo(j.global.path,O)]:[],...j.project?[Vt(j.project.path,T)]:[]];return N.length===0?"":`rules: ${N.join(" + ")}`}function w(j,T,O=process.env,N=[]){let F=(L,H,M)=>H?`${L.padEnd(8)} ${M(H.path)} (${xo(H.content)})`:`${L.padEnd(8)} none`;return[F("user",j.global,(L)=>Oo(L,O)),F("project",j.project,(L)=>Vt(L,T)),...N.map((L)=>`${"nested".padEnd(8)} ${Vt(L.path,T)} (${xo(L.content)})`),"","User rules go first, the project's after, so the project wins a conflict.",N.length===0?"A subdirectory's own rules file is added when the agent first works in it.":"A nested file was added when the agent first touched a path under it.","Edit them with `hlix rules --edit` (this project) or `hlix rules --edit --global`."].join(`
|
|
69
|
+
`)}var Po=[{dir:".claude",source:"claude",harnessReads:!0},{dir:".agents",source:"agents",harnessReads:!0},{dir:".hlix",source:"hlix",harnessReads:!0},{dir:".codex",source:"codex",harnessReads:!1}],ic=[{relative:ue(".cursor","commands"),source:"cursor"},{relative:ue(".codex","prompts"),source:"codex"}],ac=[{relative:ue(".cursor","mcp.json"),source:"cursor",key:"mcpServers",format:"json"},{relative:ue(".windsurf","mcp.json"),source:"windsurf",key:"mcpServers",format:"json"},{relative:ue(".gemini","settings.json"),source:"gemini",key:"mcpServers",format:"json"},{relative:ue(".vscode","mcp.json"),source:"vscode",key:"servers",format:"json"},{relative:ue(".codex","config.toml"),source:"codex",key:"mcp_servers",format:"toml"},{relative:".mcp.json",source:"claude",key:"mcpServers",format:"json"}];function Ao(j){return[...ac,{relative:ue(j,"mcp.json"),source:"hlix",key:"mcpServers",format:"json"}]}var cc="found, not loaded (machine-wide; enable per project by copying into .hlix/mcp.json)",lc=(j)=>Ao(j).filter((T)=>T.source!=="vscode");function pc(j,T){if(!j||typeof j!=="object"||Array.isArray(j))return{reason:"not an object"};let O=j;if(O.enabled===!1||O.disabled===!0)return{reason:"disabled"};let N=typeof O.command==="string"&&O.command!=="",F=typeof O.url==="string"&&O.url!=="";if(N&&F)return{reason:'has both "command" and "url"'};if(N){let B=Array.isArray(O.args)?O.args.filter((Y)=>typeof Y==="string"):void 0,W=O.env&&typeof O.env==="object"&&!Array.isArray(O.env)?jo(O.env,T):void 0;return{config:{command:O.command,...B&&B.length>0?{args:B}:{},...W&&Object.keys(W).length>0?{env:W}:{}}}}if(!F)return{reason:'missing "command" or "url"'};let L=O.headers??O.http_headers,H=L&&typeof L==="object"&&!Array.isArray(L)?jo(L,T):{},M=O.bearer_token_env_var;if(typeof M==="string"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(M)&&!Object.keys(H).some((B)=>B.toLowerCase()==="authorization"))H.Authorization=`Bearer ${kr(`\${${M}}`,T)}`;let U=Object.entries(H).find(([B])=>B.toLowerCase()==="authorization")?.[1]?.trim(),D=U&&!/^Bearer$/i.test(U)&&!U.includes("${"),J=O.oauth===!0||O.oauth&&typeof O.oauth==="object"||typeof M==="string"&&!T[M];return{config:{url:kr(O.url,T),...J&&!D?{needsSignIn:!0}:{},...Object.keys(H).length>0?{headers:H}:{}}}}function $o(j,T,O,N){let F=Ce(j),L=[],H=[];if(F===null)return{servers:L,skipped:H};let M=[];if(T.format==="toml"){let U=Ro(F);M=Object.entries(U).filter(([D])=>D.startsWith(`${T.key}.`)).map(([D,J])=>[D.slice(T.key.length+1),J])}else try{let D=JSON.parse(F)?.[T.key];if(D&&typeof D==="object"&&!Array.isArray(D))M=Object.entries(D)}catch{return H.push({path:j,source:T.source,scope:O,reason:"not valid JSON"}),{servers:L,skipped:H}}for(let[U,D]of M){let J=pc(D,N);if("reason"in J){H.push({path:j,source:T.source,scope:O,reason:`${U}: ${J.reason}`});continue}L.push({path:j,source:T.source,scope:O,name:U,config:J.config})}return{servers:L,skipped:H}}function dc(j,T,O){let{fields:N,body:F}=Sr(T);if(!F)return{path:j,source:"claude",scope:O,reason:"no instructions"};let L=N.tools?.replace(/^\[|\]$/g,"").split(",").map((H)=>H.trim()).filter(Boolean);return{path:j,source:"claude",scope:O,name:N.name||Io(j,".md"),description:N.description??"",instructions:F,...L&&L.length>0&&L[0]!=="*"?{tools:L}:{},...N.model?{model:N.model}:{}}}function uc(j){let T=Ro(j)[""]??{},O=typeof T.prompt==="string"?T.prompt.trim():"";if(!O)return null;return{description:typeof T.description==="string"?T.description:"",body:O}}function b(j,T,O={}){let N=O.configDir??".hlix",F=O.env??process.env,L={instructions:[],skills:[],commands:[],generatedCommands:[],mcpServers:[],subagents:[],skipped:[]},H=(ee)=>{if("reason"in ee)L.skipped.push(ee);else L.instructions.push(ee)};for(let ee of Qa){let X=ue(j,ee.relative),V=Ce(X)?.trim();if(V)L.instructions.push({path:X,source:ee.source,scope:"project",content:V})}for(let ee of tc)for(let X of St(ue(j,ee.relative),ee.extension)){let V=Ce(X);if(V===null)continue;if(ee.source==="cursor"){H(rc(X,V,"project"));continue}let{body:Q}=Sr(V);if(Q)L.instructions.push({path:X,source:ee.source,scope:"project",content:Q})}for(let ee of nc(j,"project"))H(ee);let M=Eo(j,N),U=ue(j,".codex","AGENTS.md"),D=Ce(U)?.trim();if(D&&M.includes(D))L.skipped.push({path:U,source:"codex",scope:"project",reason:"same content as the project's AGENTS.md"});else if(D)L.instructions.push({path:U,source:"codex",scope:"project",content:D});for(let ee of ec){let X=ue(T,ee.relative),V=Ce(X)?.trim();if(V)L.instructions.push({path:X,source:ee.source,scope:"global",content:V})}let J=ue(T,".codex","AGENTS.md"),B=Ce(J)?.trim(),W=Eo(T,N);if(B&&W.includes(B))L.skipped.push({path:J,source:"codex",scope:"global",reason:"same content as the machine's AGENTS.md"});else if(B)L.instructions.push({path:J,source:"codex",scope:"global",content:B});for(let[ee,X]of[[j,"project"],[T,"global"]])for(let V of Po){let Q=ue(ee,V.dir===".hlix"?N:V.dir,"skills");if(!Ya(Q).some((ne)=>Ce(ue(ne,"SKILL.md"))!==null))continue;L.skills.push({path:Q,source:V.source,scope:X,harnessReads:V.harnessReads})}for(let[ee,X]of[[j,"project"],[T,"global"]]){for(let V of Po){if(!V.harnessReads)continue;let Q=ue(ee,V.dir,"commands");if(St(Q,".md").length===0)continue;L.commands.push({path:Q,source:V.source,scope:X,harnessReads:!0})}for(let V of ic){let Q=ue(ee,V.relative);if(St(Q,".md").length===0)continue;L.commands.push({path:Q,source:V.source,scope:X})}for(let V of St(ue(ee,".gemini","commands"),".toml")){let Q=Ce(V),q=Q===null?null:uc(Q);if(!q){L.skipped.push({path:V,source:"gemini",scope:X,reason:"no prompt field"});continue}L.generatedCommands.push({path:V,source:"gemini",scope:X,name:Io(V,".toml"),body:`---
|
|
70
|
+
description: ${q.description}
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
${q.body}
|
|
74
|
+
`})}}for(let ee of Ao(N)){let X=$o(ue(j,ee.relative),ee,"project",F);L.skipped.push(...X.skipped);for(let V of X.servers){let Q=L.mcpServers.findIndex((q)=>q.name===V.name);if(Q===-1)L.mcpServers.push(V);else L.mcpServers[Q]=V}}for(let ee of lc(N)){let X=$o(ue(T,ee.relative),ee,"global",F);for(let V of X.servers)L.skipped.push({path:V.path,source:V.source,scope:"global",reason:`${V.name}: ${cc}`})}let Y=[{dir:ue(".claude","agents"),source:"claude"},{dir:ue(N,"agents"),source:"hlix"}];for(let[ee,X]of[[j,"project"],[T,"global"]])for(let V of Y.flatMap((Q)=>St(ue(ee,Q.dir),".md"))){let Q=Ce(V);if(Q===null)continue;let q=dc(V,Q,X);if("reason"in q)L.skipped.push(q);else if(L.subagents.some((ne)=>ne.name===q.name))L.skipped.push({path:V,source:"claude",scope:X,reason:`a project agent already claims the name ${q.name}`});else L.subagents.push(q)}return L}function I(j,T){if(j.length===0)return null;let O=ue(Ka(),"hlix-standards-commands",Da("sha256").update(T).digest("hex").slice(0,16));try{Ga(O,{recursive:!0,force:!0}),Ja(O,{recursive:!0});for(let N of j)Wa(ue(O,`${N.name}.md`),N.body,"utf8");return O}catch{return null}}var mc=60000,Vt=(j,T)=>{let O=Va(T,j);return!O||O.startsWith("..")||qa(O)?j:O},Oo=(j,T=process.env)=>{let O=T.HLIX_CONFIG_HOME;if(O&&j.startsWith(`${O}/`))return`~/.hlix/${j.slice(O.length+1)}`;let N=i(T);return N&&j.startsWith(`${N}/`)?`~/${j.slice(N.length+1)}`:j};function A(j,T,O=mc){if(j.length===0)return"";let N=["# Project standards from other agent tools","","These files were written for other coding agents working in this same","project. Treat them as the project's instructions and follow them."].join(`
|
|
75
|
+
`),F=[],L=N.length,H=!1;for(let U of j){let D=`# From ${Vt(U.path,T)} (${U.source})`,J=U.note?`${D}
|
|
76
|
+
${U.note}`:D,B=O-L-J.length-4;if(B<=0){H=!0;break}let W=U.content.length<=B?U.content:`${U.content.slice(0,B)}
|
|
77
|
+
[truncated]`;if(W.length<U.content.length)H=!0;F.push(`${J}
|
|
78
|
+
|
|
79
|
+
${W}`),L+=J.length+W.length+4}let M=H?`
|
|
80
|
+
|
|
81
|
+
[The standards block reached its ${O}-character cap; some rules above are cut short or omitted.]`:"";return`${N}
|
|
82
|
+
|
|
83
|
+
${F.join(`
|
|
84
|
+
|
|
85
|
+
`)}${M}`}var qt=(j,T,O)=>`${j} ${j===1?T:O}`;function C(j){let T=[];if(j.instructions.length>0)T.push(qt(j.instructions.length,"instruction file","instruction files"));if(j.skills.length>0)T.push(qt(j.skills.length,"skill directory","skill directories"));let O=j.commands.length+j.generatedCommands.length;if(O>0)T.push(qt(O,"command source","command sources"));if(j.mcpServers.length>0)T.push(qt(j.mcpServers.length,"mcp server","mcp servers"));if(j.subagents.length>0)T.push(qt(j.subagents.length,"subagent","subagents"));if(T.length===0)return"";let N=[...new Set([...j.instructions,...j.skills,...j.commands,...j.generatedCommands,...j.mcpServers,...j.subagents].map((F)=>F.source))].sort();return`standards: ${T.join(" · ")} (${N.join(", ")})`}function No(j,T){let O=[],N=(L,H)=>{if(H.length===0)return;O.push(L,...H.map((M)=>` ${M}`),"")},F=(L)=>`${L.source}${L.scope==="global"?" (global)":""} ${Vt(L.path,T)}`;if(N("Instructions",j.instructions.map((L)=>`${F(L)}${L.note?` — ${L.note}`:""}`)),N("Skills",j.skills.map((L)=>`${F(L)}${L.harnessReads?" — already read by the harness":""}`)),N("Commands",[...j.commands.map((L)=>`${F(L)}${L.harnessReads?" — already read by the harness":""}`),...j.generatedCommands.map((L)=>`${F(L)} → /${L.name}`)]),N("MCP servers",j.mcpServers.map((L)=>`${F(L)} → ${L.name} (${"command"in L.config?"stdio":"http"})`)),N("Subagents",j.subagents.map((L)=>`${F(L)} → ${L.name}`)),N("Skipped",j.skipped.map((L)=>`${F(L)} — ${L.reason}`)),O.length===0)return`No standards from other agent tools were found in this folder.
|
|
86
|
+
`;return`${O.join(`
|
|
87
|
+
`).trimEnd()}
|
|
88
|
+
`}import{accessSync as fc,constants as gc,mkdirSync as hc,readFileSync as yc,realpathSync as wc,statSync as Lo,writeFileSync as vc}from"node:fs";import{homedir as bc}from"node:os";import{basename as kc,dirname as Fo,join as jt}from"node:path";var Sc={homebrew:"Homebrew",npm:"npm",installer:"installer",unknown:"unknown origin"},Ho=(j)=>j.HOME||bc();function Pr(j){return jt(j.XDG_DATA_HOME||jt(Ho(j),".local","share"),"hlix","hlix")}function Mo(j){try{return wc(j)}catch{return null}}function jc(j){try{let T=JSON.parse(yc(jt(Pr(j),"install.json"),"utf8"));if(typeof T.path==="string")return T.path}catch{}return jt(Ho(j),".local","bin","hlix")}function Ec(j,T){if(/\/Cellar\/hlix\//.test(j))return"homebrew";if(/\/node_modules\/@hlix\/cli\//.test(j))return"npm";if(Mo(jc(T))===j)return"installer";return"unknown"}function xr(j,T){let O=Mo(j);if(!O)return null;try{if(!Lo(O).isFile())return null;fc(O,gc.X_OK)}catch{return null}return{path:j,realPath:O,channel:Ec(O,T)}}function xc(j){let T=[];for(let O of(j.PATH??"").split(":")){if(!O)continue;let N=xr(jt(O,"hlix"),j);if(N&&!T.some((F)=>F.realPath===N.realPath))T.push(N)}return T}function $r(j,T=process.execPath){if(j.HLIX_SELF)return xr(j.HLIX_SELF,j);if(/^(node|bun)(\.exe)?$/.test(kc(T)))return null;return xr(T,j)}function _r(j){switch(j.channel){case"homebrew":return"brew uninstall hlix";case"npm":return"npm uninstall -g @hlix/cli";case"installer":return`${j.path} uninstall`;case"unknown":return`rm ${j.path}`}}var $n=(j)=>`${j.path} (${Sc[j.channel]})`;function Cr(j,T=process.execPath){let O=$r(j,T),N=xc(j);if(O&&!N.some((M)=>M.realPath===O.realPath))N.push(O);if(N.length<2)return{running:O,copies:N,duplicate:null};let[F,...L]=N,H=`${N.length} copies of hlix are installed: ${$n(F)} runs, ${L.map($n).join(" and ")} ${L.length===1?"does":"do"} not. Keep one: ${L.map(_r).join(" && ")}`;return{running:O,copies:N,duplicate:H}}var Pc=86400000;function P(j,T=Date.now(),O=process.execPath){let{duplicate:N}=Cr(j,O);if(!N)return null;let F=jt(Fo(Me(j)),"duplicate-notice");try{if(T-Lo(F).mtimeMs<Pc)return null}catch{}try{hc(Fo(F),{recursive:!0}),vc(F,`${N}
|
|
89
|
+
`)}catch{}return N}async function $c(j,T,O){let N=T.map((M)=>M.id);if(O){if(!N.includes(O))throw new e("workspace_mismatch",T.length===0?`This key belongs to a user who is not a member of any workspace, including ${O}.`:`This key cannot act in workspace ${O}. Available: ${N.join(", ")}.`);return O}if(T.length===0)throw new e("workspace_required","This key belongs to a user who is not a member of any workspace. Create or join one first.");let F=T[0];if(F&&T.length===1)return j.stderr(`Using your only workspace: ${F.name} (${F.id})
|
|
90
|
+
`),F.id;if(j.json||!j.promptChoice)throw new e("missing_argument",`--workspace is required here: this key can act in ${T.length} workspaces. Pass one of: ${N.join(", ")}.`);let L=Math.max(...T.map((M)=>M.name.length));j.stderr(`${T.map((M,U)=>` ${U+1}) ${M.name.padEnd(L)} ${M.slug} ${M.role} ${M.id}`).join(`
|
|
91
|
+
`)}
|
|
92
|
+
`);let H=await j.promptChoice(`Workspace [1-${T.length}]: `,T.length);return N[H]}var Ir={name:"auth login",summary:"Verify and store a credential for this machine",usage:["Usage: hlix auth login [--workspace <id>] [--base-url <url>]",""," --base-url Defaults to https://server.hlix.ai"," --workspace Workspace (organization) id to act in. Optional: the key's"," own workspaces are listed after it is read, and the only"," one is taken automatically.","","The API key is read from a hidden prompt and never accepted as an argument.","For CI, set HLIX_API_KEY and HLIX_WORKSPACE_ID in the environment."].join(`
|
|
93
|
+
`),supportsJson:!0,options:["base-url","workspace"],async run(j){let T=typeof j.flags.workspace==="string"?j.flags.workspace:j.env.HLIX_WORKSPACE_ID,O=j.env.HLIX_API_KEY??await j.readSecret?.("Hlix API key: ")??"";if(!O)throw new e("missing_credential","No API key entered. Run from a terminal or set HLIX_API_KEY for CI.");let N=typeof j.flags["base-url"]==="string"?j.flags["base-url"]:j.env.HLIX_BASE_URL??tr,F=new URL(N),L=F.hostname==="localhost"||F.hostname==="127.0.0.1"||F.hostname==="::1";if(F.protocol!=="https:"&&!(F.protocol==="http:"&&L))throw new e("invalid_base_url","--base-url must use HTTPS (HTTP is allowed only for localhost).");let H=new bt({baseUrl:N,credential:yt(O),retry:{attempts:1}}),M=await $c(j,await H.workspaces.list(),T);await new bt({baseUrl:N,credential:yt(O),organizationId:M,retry:{attempts:1}}).projects.list();let D=Xs({baseUrl:N,apiKey:O,organizationId:M},j.env);if(j.json)j.stdout(re(oe(Ir.name,{baseUrl:N,organizationId:M,credentialPath:D})));else j.stdout(`Signed in to ${N}
|
|
94
|
+
Credential stored at ${D}
|
|
95
|
+
`);return 0}},Rr={name:"auth status",summary:"Show which credential is in use, where it came from, and whether it works",usage:["Usage: hlix auth status [--json]","","Names the SOURCE of the credential — the stored file, HLIX_API_KEY, or the","desktop app's own session when hlix was opened from its Terminal tab — and","verifies it against the API. The credential itself is never printed, not even","a prefix: machine output gets piped into logs."].join(`
|
|
96
|
+
`),supportsJson:!0,async run(j){let T=r({env:j.env,flags:j.flags,cwd:j.cwd});if(T.conflict)throw new e("workspace_mismatch",T.conflict);if(!T.credential)throw new e("unauthenticated","No credential. Run `hlix auth login`, or set HLIX_API_KEY for CI.");try{await j.requireClient().projects.list()}catch(N){throw j.stderr(`credential from ${T.credentialSource}, workspace ${T.workspaceId??"none"}, api ${T.baseUrl}
|
|
97
|
+
`),N}let O={credentialSource:T.credentialSource,credentialPath:T.credentialSource==="file"?T.credentialPath:null,baseUrl:T.baseUrl,baseUrlSource:T.baseUrlSource,workspaceId:T.workspaceId,workspaceSource:T.workspaceSource,valid:!0};if(j.json)return j.stdout(re(oe(Rr.name,O))),0;return j.stdout(`${ke([["credential",p(T)??"none"],["api",`${T.baseUrl} (from ${T.baseUrlSource})`],["workspace",T.workspaceId?`${T.workspaceId} (from ${T.workspaceSource})`:"none"],["status","valid"]])}
|
|
98
|
+
`),0}},Et={name:"auth logout",summary:"Remove the stored credential from this machine",usage:["Usage: hlix auth logout [--yes] [--json]","","Removes ~/.config/hlix/credentials.json after confirming. A credential","supplied through HLIX_API_KEY is not removed — unset it in the shell that","set it — and neither is the desktop app's own session; sign out in the app."].join(`
|
|
99
|
+
`),supportsJson:!0,options:["yes"],async run(j){let T=r({env:j.env,flags:j.flags,cwd:j.cwd});if(T.credentialSource==="env"||T.credentialSource==="session"){let N=T.credentialSource==="session",F=N?"session":"environment",L=N?"This session belongs to the Hlix desktop app; sign out there to end it.":"HLIX_API_KEY is set in this environment; unset it there to sign out.",H=Vs(j.env);if(!H){let U={removed:!1,reason:F,path:null};if(j.json)j.stdout(re(oe(Et.name,U)));else j.stdout(`${L}
|
|
100
|
+
`);return 0}if(j.flags.yes!==!0){let U={removed:!1,reason:F,path:H};if(j.json)j.stdout(re(oe(Et.name,U)));else j.stdout(`${L}
|
|
101
|
+
A stored credential also exists at ${H} — repeat with --yes to remove it.
|
|
102
|
+
`);return 0}let M=Xn(j.env);if(j.json)j.stdout(re(oe(Et.name,M)));else j.stdout(`Removed ${M.path}
|
|
103
|
+
${N?"The desktop app's session is still in use; sign out there to finish.":"HLIX_API_KEY is still set in this environment; unset it there to finish signing out."}
|
|
104
|
+
`);return 0}if(j.flags.yes!==!0&&T.credential){if(j.json||!j.confirm)throw new e("approval_required","Removing the stored credential needs approval. Repeat with `--yes`.");if(!await j.confirm(`Remove the stored credential at ${T.credentialPath}? Signing back in needs the API key again.`))throw new e("cancelled","Logout cancelled.")}let O=Xn(j.env);if(j.json)j.stdout(re(oe(Et.name,O)));else j.stdout(O.removed?`Removed ${O.path}
|
|
105
|
+
`:`No stored credential at ${O.path}
|
|
106
|
+
`);return 0}};var Uo=kt.join(" | "),Tr={name:"config list",summary:"Show every setting in effect and which file supplied it",usage:["Usage: hlix config list [--cwd <dir>] [--json]","","Merges the machine-wide file with this folder's, per key, and names the","source of each value: project, global, or default (no file names it)."].join(`
|
|
107
|
+
`),supportsJson:!0,async run(j){let T=g(j.cwd,j.env),O=ko(T);if(j.json)return j.stdout(re(oe(Tr.name,{settings:O,paths:T.paths}))),0;return j.stdout(`${Je(["setting","value","source","applies to"],O.map((N)=>[N.key,N.value??"-",N.source,vo[N.key]??"this folder's binding"]))}
|
|
108
|
+
`),j.stdout(`
|
|
109
|
+
global ${T.paths.global}
|
|
110
|
+
`),j.stdout(`project ${T.paths.project??"- (this folder is not bound to hlix)"}
|
|
111
|
+
`),0}},Ar={name:"config get",summary:"Print one setting's effective value",usage:[`Usage: hlix config get <${Uo}> [--cwd <dir>] [--json]`,"","Prints the value the cascade resolves for one key, or exits 1 when no","file names it."].join(`
|
|
112
|
+
`),supportsJson:!0,args:{min:1,max:1},async run(j){let T=br(j.args[0]),O=g(j.cwd,j.env),N=O.merged[T]??null,F=O.sources[T]??"default";if(j.json)return j.stdout(re(oe(Ar.name,{key:T,value:N,source:F}))),N===null?1:0;if(N===null)return j.stderr(`${T} is not set. Set it with \`hlix config set ${T} <value>\`.
|
|
113
|
+
`),1;return j.stdout(`${N}
|
|
114
|
+
`),0}},Or={name:"config set",summary:"Set one setting for this folder, or for the machine with --global",usage:[`Usage: hlix config set <${Uo}> <value> [--global] [--cwd <dir>] [--json]`,"","Writes this folder's .hlix/config.json, or the machine-wide file with","--global. Other keys in the file are left untouched. The binding keys","(projectId, workspaceId, apiUrl) are written by init/import and are","refused here."].join(`
|
|
115
|
+
`),supportsJson:!0,options:["global"],args:{min:2,max:2},async run(j){let T=br(j.args[0]),O=So(T,j.args[1]),N=j.flags.global===!0?"global":"project",F=h({key:T,value:O,scope:N,cwd:j.cwd,env:j.env});if(j.json)return j.stdout(re(oe(Or.name,{key:T,value:O,scope:N,path:F}))),0;return j.stdout(`${T} = ${O} (${N}: ${F})
|
|
116
|
+
`),0}};function st(j,T){if(typeof j!=="object"||j===null)return"";let O=j[T];return O===null||O===void 0?"":String(O)}var Nr={name:"projects list",summary:"List the projects in your workspace",usage:"Usage: hlix projects list [--json]",supportsJson:!0,async run(j){let T=await j.requireClient().projects.list();if(j.json)return j.stdout(re(oe(Nr.name,T))),0;let O=Array.isArray(T)?T:[];if(O.length===0)return j.stdout(`No projects.
|
|
117
|
+
`),0;return j.stdout(`${Je(["ID","NAME","STACK"],O.map((N)=>[st(N,"id"),st(N,"name"),st(N,"stack")]))}
|
|
118
|
+
`),0}},Fr={name:"projects get",summary:"Show one project, defaulting to the one this folder is bound to",usage:["Usage: hlix projects get [project-id] [--json]","","With no id, the project this folder is bound to is used."].join(`
|
|
119
|
+
`),supportsJson:!0,args:{min:0,max:1},async run(j){let T=j.args[0]??t(j.cwd)?.config.projectId;if(!T)throw new e("missing_argument","A project id is required, or run this inside a folder bound to a project.");let O=await j.requireClient().projects.get(T);if(j.json)return j.stdout(re(oe(Fr.name,O))),0;let N=O.repos;return j.stdout(`${ke([["id",st(O,"id")],["name",st(O,"name")],["stack",st(O,"stack")],["status",st(O,"status")],["repos",Array.isArray(N)?String(N.length):""]].filter(([,F])=>F!==""))}
|
|
120
|
+
`),0}},Lr={name:"projects delete",summary:"Delete a project from your workspace",usage:"Usage: hlix projects delete <id|name> [--yes] [--json]",supportsJson:!0,options:["yes"],args:{min:1,max:1},async run(j){let T=j.requireClient(),O=j.args[0],N=await T.projects.list(),F=N.find((D)=>D.id===O),L=F?[F]:N.filter((D)=>D.name===O);if(L.length===0)throw new e("not_found",`No project named or identified by "${O}".`);if(L.length>1)throw new e("invalid_usage",`More than one project is named "${O}". Use its ID.`);let H=L[0],M=`Delete project "${H.name}"?`;if(j.stderr(`${M}
|
|
121
|
+
`),j.flags.yes!==!0){if(t(j.cwd)?.config.projectId===H.id)throw new e("approval_required","This folder is bound to that project. Pass --yes to delete it.");if(j.json||!j.confirm)throw new e("approval_required","Project deletion requires --yes when not interactive.");if(!await j.confirm(M))throw new e("cancelled","Project deletion cancelled.")}let U=await T.projects.delete(H.id);if(j.json)j.stdout(re(oe(Lr.name,U)));else j.stdout(`Deleted project "${H.name}".
|
|
122
|
+
`);return 0}};function Hr(j,T){let O=j.args[0];if(!O)throw new e("missing_argument",`A ${T} id is required.`);return O}function Do(j,T){let O=j.flags[T];return typeof O==="string"&&O.trim()?O.trim():void 0}function Be(j,T){if(typeof j!=="object"||j===null)return"";let O=j[T];return O===null||O===void 0?"":String(O)}var Mr={name:"tasks list",summary:"List tasks, defaulting to the project this folder is bound to",usage:["Usage: hlix tasks list [--project <id>] [--status <status>] [--json]","","With no --project, a folder bound to a project lists that project's tasks;","anywhere else it lists the workspace's tasks."].join(`
|
|
123
|
+
`),supportsJson:!0,options:["project","status"],async run(j){let T=Do(j,"project")??t(j.cwd)?.config.projectId,O=Do(j,"status"),N=await j.requireClient().tasks.list({...T?{projectId:T}:{},...O?{status:O}:{}});if(j.json)return j.stdout(re(oe(Mr.name,N))),0;let F=Array.isArray(N)?N:[];if(F.length===0)return j.stdout(`No tasks.
|
|
124
|
+
`),0;return j.stdout(`${Je(["ID","STATUS","TITLE"],F.map((L)=>[Be(L,"id"),Be(L,"status"),Be(L,"title")||Be(L,"description").split(`
|
|
125
|
+
`)[0]||""]))}
|
|
126
|
+
`),0}},Ur={name:"tasks get",summary:"Show one task",usage:"Usage: hlix tasks get <task-id> [--json]",supportsJson:!0,args:{min:1,max:1},async run(j){let T=Hr(j,"task"),O=await j.requireClient().tasks.get(T);if(j.json)return j.stdout(re(oe(Ur.name,O))),0;return j.stdout(`${ke([["id",Be(O,"id")],["status",Be(O,"status")],["title",Be(O,"title")],["project",Be(O,"projectId")],["description",Be(O,"description")]])}
|
|
127
|
+
`),0}},Dr={name:"tasks review",summary:"Show the verified review evidence for a task",usage:"Usage: hlix tasks review <task-id> [--json]",supportsJson:!0,args:{min:1,max:1},async run(j){let T=Hr(j,"task"),O=await j.requireClient().tasks.review(T);if(j.json)return j.stdout(re(oe(Dr.name,O))),0;return j.stdout(`${JSON.stringify(O,null,2)}
|
|
128
|
+
`),0}},Jr={name:"tasks watch",summary:"Stream a task's status changes until it finishes",usage:["Usage: hlix tasks watch <task-id> [--json]","","Prints the task's status each time it changes and exits when the task is","over: finished, or left unfinished by a cycle that ended (with the reason).","A task the reviewer failed is retried while its cycle is in review, so","watching continues through it.","","With --json, each change is printed as one envelope per line (JSONL) so a","consumer can read them as they arrive: data is { state, task, reason? },","where state is running, finished or unmet."].join(`
|
|
129
|
+
`),supportsJson:!0,args:{min:1,max:1},async run(j){let T=Hr(j,"task"),O=j.requireClient(),{projectId:N}=await O.tasks.get(T),F;for await(let L of O.live.task(N,T))if(j.json)j.stdout(`${JSON.stringify(oe(Jr.name,L))}
|
|
130
|
+
`);else if(L.state==="unmet")j.stdout(`error: ${L.reason}
|
|
131
|
+
`);else if(L.task&&L.task.status!==F)F=L.task.status,j.stdout(`${F}
|
|
132
|
+
`);return 0}};import{realpath as ip}from"node:fs/promises";import{resolve as ap}from"node:path";import{parse as Xc}from"jsonc-parser";import{parse as Yc}from"smol-toml";import{parse as Zc}from"yaml";var Cn={install:null,previewCommand:null,previewPort:null,verifyCommand:null,packageManager:null};var _c=[["next",3000],["nuxt",3000],["@remix-run/dev",5173],["@sveltejs/kit",5173],["astro",4321],["@angular/cli",4200],["gatsby",8000],["react-scripts",3000],["vite",5173],["hono",3000]],Cc=["vite","next","webpack","react-scripts","@rsbuild/core","parcel"],Xt=8080,_n=8000,Ic=String.raw`import http.server as h, urllib.parse as u, sys, os, re, io
|
|
133
|
+
B = (sys.argv[2] if len(sys.argv) > 2 else "").rstrip("/")
|
|
134
|
+
D = os.path.abspath(sys.argv[3] if len(sys.argv) > 3 and sys.argv[3] else ".")
|
|
135
|
+
E = sys.argv[4] if len(sys.argv) > 4 else "index.html"
|
|
136
|
+
P = int(os.environ.get("PORT") or ${Xt})
|
|
137
|
+
L = re.compile(rb"((?:src|href|action|poster)\s*=\s*[\"'])/(?!/)" + (rb"(?!" + re.escape(B[1:].encode()) + rb"(?:/|[\"']))" if B else b""))
|
|
138
|
+
class H(h.SimpleHTTPRequestHandler):
|
|
139
|
+
def __init__(s, *a, **k):
|
|
140
|
+
super().__init__(*a, directory=D, **k)
|
|
141
|
+
def send_head(s):
|
|
142
|
+
raw = u.urlsplit(s.path).path
|
|
143
|
+
if B and (raw == B or raw.startswith(B + "/")):
|
|
144
|
+
s.path = s.path[len(B):] or "/"
|
|
145
|
+
p = u.unquote(u.urlsplit(s.path).path).replace(chr(92), "/")
|
|
146
|
+
if any(x.startswith(".") for x in p.split("/")):
|
|
147
|
+
s.send_error(404)
|
|
148
|
+
return None
|
|
149
|
+
f = s.translate_path(s.path)
|
|
150
|
+
if os.path.isdir(f) and p.endswith("/"):
|
|
151
|
+
f = os.path.join(f, E if os.path.abspath(f) == D else "index.html")
|
|
152
|
+
elif not os.path.exists(f) and "." not in p.rsplit("/", 1)[-1]:
|
|
153
|
+
f = f + ".html" if os.path.isfile(f + ".html") else os.path.join(D, E)
|
|
154
|
+
if not (f.lower().endswith((".html", ".htm")) and os.path.isfile(f)):
|
|
155
|
+
return super().send_head()
|
|
156
|
+
with open(f, "rb") as fh:
|
|
157
|
+
body = fh.read()
|
|
158
|
+
if B:
|
|
159
|
+
body = L.sub(lambda m: m.group(1) + B.encode() + b"/", body)
|
|
160
|
+
s.send_response(200)
|
|
161
|
+
s.send_header("Content-Type", "text/html; charset=utf-8")
|
|
162
|
+
s.send_header("Content-Length", str(len(body)))
|
|
163
|
+
s.end_headers()
|
|
164
|
+
return io.BytesIO(body)
|
|
165
|
+
def list_directory(s, path):
|
|
166
|
+
s.send_error(404)
|
|
167
|
+
return None
|
|
168
|
+
h.ThreadingHTTPServer(("", P), H).serve_forever()
|
|
169
|
+
`;function Tn(j=".",T="index.html"){return`python3 -c 'import base64,sys;exec(base64.b64decode(sys.argv[1]))' ${Yt(Ic)} "$PREVIEW_PUBLIC_PATH" ${j}${T==="index.html"?"":` ${Ko(T)}`}`}function Wo(j){if(j.has("index.html"))return"index.html";let T=[...j].filter((O)=>!O.startsWith(".")&&!/[\\/]/.test(O)&&/\.html?$/i.test(O));return T.length===1?T[0]:null}var zo="HLIX_PREVIEW_FAILURE";function In(j){return`{ echo "${zo}=${j}"; exit 1; }`}var Rc=`const handler = {
|
|
170
|
+
get(target, key) {
|
|
171
|
+
if (key === 'then' || key === 'prototype' || key === '$$typeof') return undefined
|
|
172
|
+
if (key === '__esModule') return false
|
|
173
|
+
if (key === Symbol.toPrimitive) return () => ''
|
|
174
|
+
if (key === 'displayName' || key === 'name') return 'Unavailable'
|
|
175
|
+
return stub
|
|
176
|
+
},
|
|
177
|
+
apply(target, self, args) {
|
|
178
|
+
const props = args[0]
|
|
179
|
+
return props !== null && typeof props === 'object' && !Array.isArray(props) ? null : stub
|
|
180
|
+
},
|
|
181
|
+
}
|
|
182
|
+
const stub = new Proxy(function Unavailable() {}, handler)
|
|
183
|
+
module.exports = stub
|
|
184
|
+
`,Tc=`const path = require('path')
|
|
185
|
+
const loaded = __CONFIG__
|
|
186
|
+
const dir = path.join(__dirname, 'hlix-web')
|
|
187
|
+
// React Native Web's own names, as imported directly and as Expo rewrites them.
|
|
188
|
+
const WEB_ROOT = new Set(['react-native', 'react-native-web', 'react-native-web/dist/index'])
|
|
189
|
+
function withNativeStubs(config) {
|
|
190
|
+
const upstream = config.resolver.resolveRequest
|
|
191
|
+
config.resolver.resolveRequest = (context, moduleName, platform) => {
|
|
192
|
+
if (platform === 'web' && !context.originModulePath.startsWith(dir)) {
|
|
193
|
+
if (WEB_ROOT.has(moduleName)) return { type: 'sourceFile', filePath: path.join(dir, 'react-native.js') }
|
|
194
|
+
if (moduleName.startsWith('react-native/Libraries/')) return { type: 'sourceFile', filePath: path.join(dir, 'native-stub.js') }
|
|
195
|
+
}
|
|
196
|
+
return (upstream || context.resolveRequest)(context, moduleName, platform)
|
|
197
|
+
}
|
|
198
|
+
return config
|
|
199
|
+
}
|
|
200
|
+
module.exports = typeof loaded === 'function'
|
|
201
|
+
? async (...args) => withNativeStubs(await loaded(...args))
|
|
202
|
+
: loaded && typeof loaded.then === 'function' ? loaded.then(withNativeStubs) : withNativeStubs(loaded)
|
|
203
|
+
`,Ac=[[86,57],[85,56],[83,55],[81,54],[79,53],[76,52],[74,51]],Oc=String.raw`const fs = require("fs"), cp = require("child_process")
|
|
204
|
+
const [base, pm] = process.argv.slice(-2)
|
|
205
|
+
// No preview path: not the preview's own copy. Prepared already: a restart.
|
|
206
|
+
if (!base || fs.existsSync("hlix-web/native-stub.js")) process.exit(0)
|
|
207
|
+
const fail = (code, why) => { console.error("hlix: " + why); console.log("${zo}=" + code); process.exit(1) }
|
|
208
|
+
const run = (cmd, args) => {
|
|
209
|
+
const res = cp.spawnSync(cmd, args, { stdio: "inherit", env: { ...process.env, CI: "1", EXPO_NO_TELEMETRY: "1" } })
|
|
210
|
+
if (res.status !== 0) fail("packages_unavailable", "could not install " + args.join(" "))
|
|
211
|
+
}
|
|
212
|
+
const pkg = JSON.parse(fs.readFileSync("package.json", "utf8"))
|
|
213
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies }
|
|
214
|
+
const bare = !("expo" in deps)
|
|
215
|
+
// npm refuses a React Native major change over peer ranges; the others only warn.
|
|
216
|
+
const peers = pm === "npm" ? ["--", "--legacy-peer-deps"] : []
|
|
217
|
+
if (bare) {
|
|
218
|
+
const minor = Number((String(deps["react-native"] || "").match(/0\.(\d+)/) || [])[1] || 0)
|
|
219
|
+
const sdk = (${JSON.stringify(Ac)}).find(([m]) => minor >= m)
|
|
220
|
+
if (!sdk) fail("react_native_too_old", "React Native 0." + minor + " is older than any release with web support")
|
|
221
|
+
const add = { npm: ["install", "--legacy-peer-deps", "--no-audit", "--no-fund"], pnpm: ["add"], yarn: ["add"], bun: ["add"] }[pm] || ["install"]
|
|
222
|
+
run(pm, [...add, "expo@~" + sdk[1] + ".0.0"])
|
|
223
|
+
}
|
|
224
|
+
const missing = ["react-dom", "react-native-web", "@expo/metro-runtime", "babel-preset-expo"].filter((name) => !(name in deps))
|
|
225
|
+
if (missing.length) run("npx", ["expo", "install", ...missing, ...peers])
|
|
226
|
+
if (bare) {
|
|
227
|
+
run("npx", ["expo", "install", "--fix", ...peers])
|
|
228
|
+
fs.mkdirSync("hlix-web", { recursive: true })
|
|
229
|
+
fs.writeFileSync("hlix-web/entry.js", "import 'expo'\nimport { AppRegistry } from 'react-native'\nimport '../index'\nconst rootTag = document.getElementById('root') || document.body.appendChild(document.createElement('div'))\nAppRegistry.runApplication(AppRegistry.getAppKeys()[0], { rootTag })\n")
|
|
230
|
+
const next = JSON.parse(fs.readFileSync("package.json", "utf8"))
|
|
231
|
+
next.main = "hlix-web/entry.js"
|
|
232
|
+
fs.writeFileSync("package.json", JSON.stringify(next, null, 2))
|
|
233
|
+
for (const file of ["babel.config.js", ".babelrc", ".babelrc.js", "babel.config.cjs"]) {
|
|
234
|
+
if (!fs.existsSync(file)) continue
|
|
235
|
+
fs.writeFileSync(file, fs.readFileSync(file, "utf8").replace(/module:(?:@react-native\/babel-preset|metro-react-native-babel-preset)/g, "babel-preset-expo"))
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
fs.mkdirSync("hlix-web", { recursive: true })
|
|
239
|
+
fs.writeFileSync("hlix-web/native-stub.js", ${JSON.stringify(Rc)})
|
|
240
|
+
fs.writeFileSync("hlix-web/react-native.js", "const web = require('react-native-web/dist/index')\nconst stub = require('./native-stub')\nmodule.exports = new Proxy(web, { get: (target, key) => (key in target ? target[key] : stub) })\n")
|
|
241
|
+
const own = ["metro.config.js", "metro.config.cjs"].find((file) => fs.existsSync(file))
|
|
242
|
+
let config = "require('expo/metro-config').getDefaultConfig(__dirname)"
|
|
243
|
+
if (own && !bare && /expo/.test(fs.readFileSync(own, "utf8"))) {
|
|
244
|
+
// Beside the original, so its own __dirname still names the project.
|
|
245
|
+
fs.renameSync(own, "metro.config.hlix-original.js")
|
|
246
|
+
config = "require('./metro.config.hlix-original.js')"
|
|
247
|
+
}
|
|
248
|
+
if (own) fs.rmSync(own, { force: true })
|
|
249
|
+
fs.writeFileSync("metro.config.js", ${JSON.stringify(Tc)}.replace("__CONFIG__", config))
|
|
250
|
+
`,Nc=String.raw`const fs = require("fs")
|
|
251
|
+
const base = (process.argv[process.argv.length - 1] || "").replace(/\/+$/, "")
|
|
252
|
+
if (!base) process.exit(0)
|
|
253
|
+
const dynamic = ["app.config.ts", "app.config.js"].filter((file) => fs.existsSync(file))
|
|
254
|
+
if (dynamic.length || fs.existsSync("app.json")) {
|
|
255
|
+
const json = dynamic.length ? { expo: require("expo/config").getConfig(process.cwd()).exp } : JSON.parse(fs.readFileSync("app.json", "utf8"))
|
|
256
|
+
const expo = json.expo || json
|
|
257
|
+
expo.experiments = { ...expo.experiments, baseUrl: base }
|
|
258
|
+
fs.writeFileSync("app.json", JSON.stringify(json, null, 2))
|
|
259
|
+
for (const file of dynamic) fs.rmSync(file)
|
|
260
|
+
}
|
|
261
|
+
`,Fc=String.raw`import json, os, shutil, sys, tarfile, tempfile, urllib.request
|
|
262
|
+
root = sys.argv[1]
|
|
263
|
+
base = "https://storage.googleapis.com/flutter_infra_release/releases"
|
|
264
|
+
index = json.load(urllib.request.urlopen(base + "/releases_linux.json", timeout=60))
|
|
265
|
+
stable = index["current_release"]["stable"]
|
|
266
|
+
release = next(r for r in index["releases"] if r["hash"] == stable)
|
|
267
|
+
tmp = tempfile.mkdtemp(dir=root)
|
|
268
|
+
archive = os.path.join(tmp, "flutter.tar.xz")
|
|
269
|
+
with urllib.request.urlopen(base + "/" + release["archive"], timeout=600) as src, open(archive, "wb") as out:
|
|
270
|
+
shutil.copyfileobj(src, out)
|
|
271
|
+
with tarfile.open(archive) as tar:
|
|
272
|
+
tar.extractall(tmp, filter="tar")
|
|
273
|
+
os.remove(archive)
|
|
274
|
+
os.rename(os.path.join(tmp, "flutter"), os.path.join(root, "sdk"))
|
|
275
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
276
|
+
print("hlix: Flutter " + release["version"] + " installed")
|
|
277
|
+
`,Lc=String.raw`import sys, zipfile
|
|
278
|
+
args = [a for a in sys.argv[1:] if a not in ("-o", "-q")]
|
|
279
|
+
dest = args[args.index("-d") + 1] if "-d" in args else "."
|
|
280
|
+
zipfile.ZipFile(args[0]).extractall(dest)
|
|
281
|
+
`;function Jo(j,T){return`python3 -c 'import base64,sys;exec(base64.b64decode(sys.argv[1]))' ${Yt(j)} ${T}`}function Hc(){return['mkdir -p "$HOME/.cache/hlix-flutter"/bin',`{ [ -x "$HOME/.cache/hlix-flutter"/sdk/bin/flutter ] || { echo "hlix: installing the Flutter SDK (first run only)"; ${Jo(Fc,'"$HOME/.cache/hlix-flutter"')}; } || ${In("flutter_sdk_unavailable")}; }`,`{ command -v unzip >/dev/null 2>&1 || { printf '#!/bin/sh\\n%s "$@"\\n' ${Ko(Jo(Lc,""))} > "$HOME/.cache/hlix-flutter"/bin/unzip && chmod +x "$HOME/.cache/hlix-flutter"/bin/unzip; }; }`,'PATH="$HOME/.cache/hlix-flutter"/sdk/bin:"$HOME/.cache/hlix-flutter"/bin:$PATH',"export PATH","{ flutter config --no-analytics >/dev/null 2>&1 || true; }",`{ flutter pub get || ${In("packages_unavailable")}; }`,`{ flutter run -d web-server --web-hostname 0.0.0.0 --web-port "$PORT" </dev/null || { echo "hlix: the dev server stopped; serving a web build instead"; flutter build web --base-href "$PREVIEW_PUBLIC_PATH/" && ${Tn("build/web")}; } || ${In("web_build_failed")}; }`].join(" && ")}function Mc(j){let T=`printf %s ${Yt(Oc)} | base64 -d | node - "$PREVIEW_PUBLIC_PATH" ${j}`,O=`CI=1 npx expo export --platform web --output-dir dist && ${Tn("dist")}`;return`${T} && ${qo(Nc,"PREVIEW_PUBLIC_PATH")} && { BROWSER=none EXPO_NO_TELEMETRY=1 npx expo start --no-dev --port "$PORT" </dev/null || { echo "hlix: the dev server stopped; serving a web build instead"; ${O}; } || ${In("web_build_failed")}; }`}function Ko(j){return`'${j.replace(/'/g,"'\\''")}'`}var Uc=String.raw`const fs = require("fs")
|
|
282
|
+
const base = (process.argv[process.argv.length - 1] || "").replace(/\/+$/, "")
|
|
283
|
+
if (!base) process.exit(0)
|
|
284
|
+
const file = ["next.config.ts", "next.config.mts", "next.config.mjs", "next.config.js", "next.config.cjs"].find((name) => fs.existsSync(name))
|
|
285
|
+
const wrap = (name) => "(async (...args) => { const c = typeof " + name + " === \"function\" ? await " + name + "(...args) : await " + name + "; return { ...c, basePath: " + JSON.stringify(base) + " } })"
|
|
286
|
+
if (!file) {
|
|
287
|
+
fs.writeFileSync("next.config.mjs", "export default { basePath: " + JSON.stringify(base) + " }\n")
|
|
288
|
+
process.exit(0)
|
|
289
|
+
}
|
|
290
|
+
let text = fs.readFileSync(file, "utf8")
|
|
291
|
+
if (text.includes("__hlixPreviewConfig")) process.exit(0)
|
|
292
|
+
if (/\bexport\s+default\b/.test(text)) {
|
|
293
|
+
text = text.replace(/\bexport\s+default\b/, "const __hlixPreviewConfig =") + "\nexport default " + wrap("__hlixPreviewConfig") + "\n"
|
|
294
|
+
} else if (/\bmodule\.exports\s*=/.test(text)) {
|
|
295
|
+
text += "\nconst __hlixPreviewConfig = module.exports\nmodule.exports = " + wrap("__hlixPreviewConfig") + "\n"
|
|
296
|
+
} else {
|
|
297
|
+
process.exit(0)
|
|
298
|
+
}
|
|
299
|
+
fs.writeFileSync(file, text)
|
|
300
|
+
`,Dc=String.raw`import os, re, sys
|
|
301
|
+
hosts = [h for h in (sys.argv[2] if len(sys.argv) > 2 else "").split(",") if h]
|
|
302
|
+
if not hosts:
|
|
303
|
+
sys.exit(0)
|
|
304
|
+
match = re.search(r"DJANGO_SETTINGS_MODULE['\"]\s*,\s*['\"]([\w.]+)['\"]", open("manage.py").read())
|
|
305
|
+
if not match:
|
|
306
|
+
sys.exit(0)
|
|
307
|
+
module = match.group(1).replace(".", "/")
|
|
308
|
+
path = module + ".py" if os.path.isfile(module + ".py") else os.path.join(module, "__init__.py")
|
|
309
|
+
if not os.path.isfile(path) or "# hlix preview hosts" in open(path).read():
|
|
310
|
+
sys.exit(0)
|
|
311
|
+
with open(path, "a") as f:
|
|
312
|
+
f.write("\n# hlix preview hosts\nALLOWED_HOSTS = list(globals().get('ALLOWED_HOSTS') or ['.localhost', '127.0.0.1', '[::1]']) + %r\n" % hosts)
|
|
313
|
+
`;function qo(j,T){return`printf %s ${Yt(j)} | base64 -d | node - "$${T}"`}var Jc=["test","typecheck","check","build","lint"],Bc=/^(?:\.eslintrc(?:\.(?:js|cjs|mjs|json|ya?ml))?|eslint\.config\.(?:js|cjs|mjs|ts|cts|mts))$/;function Gc(j,T){return/\bnext\s+lint\b/.test(j)&&![...T].some((O)=>Bc.test(O))}var em=Object.freeze({CI:"true",DEBIAN_FRONTEND:"noninteractive",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",npm_config_yes:"true",NPM_CONFIG_FUND:"false",NPM_CONFIG_AUDIT:"false",NPM_CONFIG_UPDATE_NOTIFIER:"false",PIP_NO_INPUT:"1",PIP_DISABLE_PIP_VERSION_CHECK:"1",NEXT_TELEMETRY_DISABLED:"1",NO_COLOR:"1",TERM:"dumb"});var Wc=["dev","start","serve","preview"];function Br(j){if(!j)return{};try{let T=JSON.parse(j);return T&&typeof T==="object"?T:{}}catch{return{}}}function zc(j){return{...Ge(j.dependencies)?j.dependencies:{},...Ge(j.devDependencies)?j.devDependencies:{}}}function Kc(j){if(!new Set(j.rootFiles).has("pubspec.yaml"))return!1;let T=j.configFiles?.["pubspec.yaml"];return T===void 0||/^\s+sdk:\s*flutter\s*$/m.test(T)}function Vo(j){let T=new Set(j.rootFiles),O=Br(j.packageJson),N=typeof O.packageManager==="string"?O.packageManager.split("@")[0]:"",F=N==="bun"||T.has("bun.lock")||T.has("bun.lockb")?"bun":N==="pnpm"||T.has("pnpm-lock.yaml")?"pnpm":N==="yarn"||T.has("yarn.lock")?"yarn":N==="npm"||T.has("package.json")?"npm":null,L=Wo(T);if(!F){if(Kc(j))return{...Cn,previewCommand:Hc(),previewPort:Xt,mobile:!0};let D=Vc(T,j.configFiles??{});if(D)return D;return L?{...Cn,previewCommand:Tn(".",L),previewPort:Xt}:Cn}let H=Xo(O,T,F),M={install:`${F} install`,verifyCommand:H.verifyCommand,packageManager:F},U=H.webApp?null:qc(j.workspacePackages??[],F)[0]??null;if(U){let D=(J)=>`cd ${U.dir} && ${J}`;return{...M,previewCommand:D(U.previewCommand),previewPort:U.previewPort,verifyCommand:M.verifyCommand??(U.verifyCommand?D(U.verifyCommand):null),...U.mobile?{mobile:!0}:{}}}return{...M,previewCommand:H.previewCommand,previewPort:H.previewPort,...H.mobile?{mobile:!0}:{}}}function Xo(j,T,O,N){let F=Ge(j.scripts)?j.scripts:{},L=(ne)=>`${O} run ${ne}`,H=(ne,de)=>`${L(ne)}${O==="npm"?" --":""} ${de}`,M=Wc.find((ne)=>typeof F[ne]==="string"),U=Jc.find((ne)=>typeof F[ne]==="string"&&!/no test specified/i.test(String(F[ne]))&&!/(?:^|\s)(?:--watch(?:All)?|-w)(?:\s|=|$)/.test(String(F[ne]))&&!Gc(String(F[ne]),T)),D=U?L(U):null,J=zc(j),B={previewCommand:null,previewPort:null,verifyCommand:D,webApp:!1,mobile:!1,explicitPort:!1};if("expo"in J||"react-native"in J&&!Cc.some((ne)=>(ne in J)))return{previewCommand:Mc(O),previewPort:N??Xt,verifyCommand:D,webApp:!0,mobile:!0,explicitPort:!1};let W=_c.find(([ne])=>(ne in J)),Y=M?Go(String(F[M]))??W?.[1]??null:null,ee=Wo(T);if(!M&&!W&&ee)return{...B,previewCommand:Tn(".",ee),previewPort:N??Xt};if(!M)return B;let X=String(F[M]).trim(),V=N!=null?` --port ${N}`:"",Q=V?H(M,V.trim()):L(M),q=X.split("&&").map((ne)=>ne.trim());if(q.length>1&&q.every((ne)=>/^vite(?:\s|$)/.test(ne))&&!("@sveltejs/kit"in J)){let ne={npm:"npx",bun:"bunx",pnpm:"pnpm exec",yarn:"yarn exec"}[O];Q=q.map((de,me)=>`${ne} ${de} --base "$PREVIEW_BASE_PATH/"${/^vite\s+build\b/.test(de)?"":" --host 0.0.0.0"}${me===q.length-1?V:""}`).join(" && ")}else if(/^vite(?:\s+(?:dev|serve|preview))?(?:\s|$)/.test(X)&&!/&&|;|\|/.test(X)&&!("@sveltejs/kit"in J))Q=H(M,`--base "$PREVIEW_BASE_PATH/" --host 0.0.0.0${V}`);else if(/^astro\s+(?:dev|preview)(?:\s|$)/.test(X))Q=H(M,`--base "$PREVIEW_BASE_PATH"${V}`);else if(/^next\s+(?:dev|start)(?:\s|$)/.test(X))Q=`${qo(Uc,"PREVIEW_BASE_PATH")} && ${Q}`;else if(/^nuxt\s+(?:dev|preview|start)(?:\s|$)/.test(X))Q=`NUXT_APP_BASE_URL="$PREVIEW_BASE_PATH/" ${Q}`;return{previewCommand:Q,previewPort:N??Y,verifyCommand:D,webApp:Boolean(W),mobile:!1,explicitPort:Go(X)!=null}}var Bo=["web","app","frontend","site","www","client","dashboard"];function qc(j,T){let O=j.filter((F)=>Rn(F.dir)).map((F)=>{let L=Br(F.packageJson),H=new Set(F.rootFiles??[]);return{dir:F.dir,pkg:L,files:H,...Xo(L,H,T)}}).filter((F)=>F.webApp&&F.previewCommand&&F.previewPort!=null),N=(F)=>{let L=Bo.indexOf(F.split("/").at(-1)??"");return L<0?Bo.length:L};return O.sort((F,L)=>Number(F.mobile)-Number(L.mobile)||Number(!F.dir.startsWith("apps/"))-Number(!L.dir.startsWith("apps/"))||N(F.dir)-N(L.dir)||(F.dir<L.dir?-1:F.dir>L.dir?1:0))}function Rn(j){return/^[A-Za-z0-9._@-]+(?:\/[A-Za-z0-9._@-]+)*$/.test(j)&&!j.split("/").some((T)=>T===".."||T===".")}function Yo(j){let T=Br(j.packageJson),O=Array.isArray(T.workspaces)?T.workspaces:Ge(T.workspaces)&&Array.isArray(T.workspaces.packages)?T.workspaces.packages:[],N=j.configFiles?.["pnpm-workspace.yaml"]??"";for(let M of N.split(/\r?\n/)){let U=M.match(/^\s*-\s*["']?([^"'#\s]+)["']?/);if(U)O.push(U[1])}let F=O.filter((M)=>typeof M==="string"&&!M.startsWith("!"));if(F.length===0&&new Set(j.rootFiles).has("turbo.json"))F.push("apps/*","packages/*");for(let M of Object.values(Ge(T.scripts)?T.scripts:{})){if(typeof M!=="string")continue;let U=M.match(/^\s*cd\s+([A-Za-z0-9._@/-]+)\s*&&/)?.[1];if(U&&Rn(U))F.push(U)}let L=new Set,H=new Set;for(let M of F){let U=M.replace(/^\.\//,"").replace(/\/$/,"");if(/^[^*]+\/\*$/.test(U)&&Rn(U.slice(0,-2)))L.add(U.slice(0,-2));else if(!U.includes("*")&&Rn(U))H.add(U)}return{parents:[...L].sort(),packages:[...H].sort()}}function Vc(j,T){let O=`${T["requirements.txt"]??""}
|
|
314
|
+
${T["pyproject.toml"]??""}`.toLowerCase(),N=(J)=>new RegExp(`(^|[\\s"'\\[,])${J}\\b`,"m").test(O),F=j.has("requirements.txt")?'"$V/bin/pip" install -q -r requirements.txt':j.has("pyproject.toml")?'"$V/bin/pip" install -q .':null,L=(J,B="")=>F?`V="$HOME/.cache/hlix-venvs/$(cat requirements.txt pyproject.toml 2>/dev/null | cksum | cut -d " " -f1)"; { [ -f "$V/.ready" ] || { rm -rf "$V" && python3 -m venv "$V" && ${F}${B} && touch "$V/.ready"; }; } && "$V/bin/python" ${J}`:null,H=N("pytest")?L("-m pytest",' && "$V/bin/pip" install -q pytest'):null,U=["main.py","app.py","server.py","api.py"].find((J)=>j.has(J))?.replace(/\.py$/,""),D=(J,B=H)=>({...Cn,previewCommand:J,previewPort:_n,verifyCommand:B});if(j.has("manage.py")){let J=`python3 -c 'import base64,sys;exec(base64.b64decode(sys.argv[1]))' ${Yt(Dc)} "$PREVIEW_ALLOWED_HOSTS"`;return D(`${J} && python3 manage.py runserver 0.0.0.0:${_n}`,H??(N("django")?L("manage.py test"):null))}if(U&&N("fastapi"))return D(`python3 -m uvicorn ${U}:app --host 0.0.0.0 --port ${_n} --root-path "$PREVIEW_PUBLIC_PATH"`);if(U&&N("flask"))return D(`python3 -m flask --app ${U} run --host 0.0.0.0 --port ${_n}`);return null}function Yt(j){return btoa(j)}function Go(j){let T=j.match(/(?:--port(?:=|\s+)|-p\s+|\bPORT=)(\d{2,5})\b/),O=T?Number(T[1]):NaN;return Number.isInteger(O)&&O>0&&O<=65535?O:null}function Ge(j){return Boolean(j)&&typeof j==="object"&&!Array.isArray(j)}function Zo(j){let T=new Set(j.rootFiles),O=new Set;if(T.has("package.json")){for(let F of["coverage",".cache"])O.add(F);if(["package-lock.json","pnpm-lock.yaml","yarn.lock","bun.lock","bun.lockb"].some((F)=>T.has(F)))O.add("node_modules")}if(T.has("Cargo.toml"))O.add("target");if(["pyproject.toml","requirements.txt","setup.py"].some((F)=>T.has(F)))O.add("__pycache__");if(T.has("composer.json")&&T.has("composer.lock"))O.add("vendor");for(let F of Gr({...j,rootFiles:T}))O.add(F);return[...O].sort()}function Ue(j,T,O){let N=(j.match(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|\/\*[\s\S]*?\*\/|\/\/[^\n]*|[A-Za-z_$][\w$]*|[^\s]/g)??[]).filter((U)=>!U.startsWith("//")&&!U.startsWith("/*"));if(N[0]!=="{"){let U=N.findIndex((J,B)=>J==="export"&&N[B+1]==="default"),D=N.findIndex((J,B)=>J==="module"&&N.slice(B+1,B+4).join("")===".exports=");if(U<0&&D<0)return null;if(N=N.slice(U>=0?U+2:D+4),["defineConfig","defineNuxtConfig"].includes(N[0]??"")&&N[1]==="(")N=N.slice(2);if(N[0]!=="{")return null}if(N.some((U,D)=>U==="."&&N[D+1]==="."&&N[D+2]==="."))return null;let F=(U="")=>U.replace(/^["']|["']$/g,""),L=[],H,M=0;for(let U=0;U<N.length;U++){let D=N[U];if(D==="{")L.push(N[U-1]===":"?F(N[U-2]):"");if(D==="}")L.pop();if(!L.length)break;if(D==="["&&["{",","].includes(N[U-1]??""))return null;if(T&&L.length===1&&F(D)===T){if(N[U+1]!==":"||N[U+2]!=="{"||++M>1)return null}if(F(D)===O&&(T?L.length===2&&L.at(-1)===T:L.length===1)&&N[U+1]!==":")return null;if(F(D)!==O||N[U+1]!==":"||(T?L.length!==2||L.at(-1)!==T:L.length!==1))continue;let J=N[U+2]??"";if(H!==void 0||!/^["'`][^\\$]*["'`]$/.test(J)||![",","}"].includes(N[U+3]??""))return null;H=J.slice(1,-1)}return H}function Gr(j){let T={};try{let W=JSON.parse(j.packageJson??"{}");if(Ge(W))T=W}catch{}let O={...Ge(T.dependencies)?T.dependencies:{},...Ge(T.devDependencies)?T.devDependencies:{}},N=Ge(T.scripts)?Object.entries(T.scripts).filter((W)=>typeof W[1]==="string"):[],F=(W,Y=W)=>(W in O)||N.some(([,ee])=>new RegExp(`(?:^|[;&|\\s])${Y}(?:\\s|$)`).test(ee)),L=j.configFiles??{},H=new Set,M=(W)=>{if(typeof W!=="string")return null;let Y=W.replace(/^\.\//,"").replace(/\/$/,"");return Y&&!Y.startsWith("/")&&!/[\\:*?\[\]#!$`"'\r\n]/.test(Y)&&!Y.split("/").some((ee)=>!ee||[".","..",".git",".hlix"].includes(ee))?Y:null},U=(W)=>{let Y=M(W);if(Y)H.add(Y)},D=(W,Y)=>{let ee=N.filter(([q,ne])=>/(?:^|:)build(?:$|:)/.test(q)||new RegExp(`\\b${W} build\\b`).test(ne)),X=ee.filter(([,q])=>new RegExp(`(?:^|\\s)${W}(?:\\s|$)`).test(q));if(!X.length&&(ee.length||T.workspaces!==void 0))return null;if(ee.some((q)=>!X.includes(q)&&/--(?:out|dist|root|config|project)|\s-[dpc]\b/.test(q[1])))return null;let V,Q=!1;for(let[,q]of X){if(/[$`\\;|<>\n]/.test(q)||/(?:^|\s)(?:cd|pushd|popd)\s/.test(q))return null;for(let ne of q.split("&&")){let de=ne.match(/"[^"\n]*"|'[^'\n]*'|[^\s]+/g)??[];if(de.some((Z)=>/["']/.test(Z)&&!/^(?:"[^"\n]*"|'[^'\n]*')$/.test(Z)))return null;let me=de.map((Z)=>Z.replace(/^["']|["']$/g,"")),te=me.indexOf(W);if(te<0)continue;if(te!==0&&!(te===1&&["npx","bunx"].includes(me[0])))return null;let z=me.slice(te+1);if(z[0]==="build")z.shift();let G;for(let Z=0;Z<z.length;Z++){let[le,...fe]=z[Z].split("="),ge=fe.length?fe.join("="):void 0;if(!Y.includes(le)||G!==void 0)return null;let je=ge??z[++Z],he=M(je);if(!he)return null;G=he}if(Q&&G!==V)return null;Q=!0,V=G}}return V},J=(W)=>{let Y=[...new Set([...j.rootFiles,...Object.keys(L)])].filter((ee)=>ee.startsWith(`${W}.config.`)||W==="turbo"&&ee==="turbo.json");if(!Y.length)return"{}";return Y.length===1?L[Y[0]]??null:null},B=(W,Y,ee,X,V,Q,q)=>{let ne=J(W),de=D(W,V);if(ne===null||de===null)return;let me=Q?Ue(ne,null,Q):void 0,te=Ue(ne,Y,ee);if(me===null||te===null)return;let z=me===void 0||me==="."||me==="./"?"":M(me);if(z===null)return;let Z=M(de??te??X);if(!Z)return;U(z?`${z}/${Z}`:Z);for(let le of q??[])U(z?`${z}/${le}`:le)};if(F("vite"))B("vite","build","outDir","dist",["--outDir","--out-dir"],"root");if(F("next")){let W=J("next"),Y=W===null?null:Ue(W,null,"output");if(W!==null&&(Y===void 0||Y==="standalone"||Y==="export"&&Ue(W,null,"distDir")===void 0))B("next",null,"distDir",".next",[],void 0,Y==="export"?["out"]:[])}if(F("astro"))B("astro",null,"outDir","dist",["--outDir","--out-dir"],"root");if(F("nuxt")){let W=J("nuxt");if(W!==null&&Ue(W,null,"nitro")===void 0&&Ue(W,null,"extends")===void 0)B("nuxt",null,"buildDir",".nuxt",[],"rootDir",[".output"])}if(F("turbo"))B("turbo",null,"cacheDir",".turbo",["--cache-dir"]);if(F("webpack")){let W=J("webpack");if(W!==null&&Ue(W,null,"context")===void 0)B("webpack","output","path","dist",["--output-path"])}if(F("rollup"))B("rollup","output","dir",void 0,["--dir","-d"]);if(F("parcel")||F("parcel-bundler","parcel")){let W=D("parcel",["--dist-dir"]);if(W!==null&&T.targets===void 0&&!["main","module","browser"].some((Y)=>typeof T[Y]==="string"))U(W??"dist")}if(F("react-scripts")&&D("react-scripts",[])!==null)U("build");if(F("typescript","tsc")){let W=D("tsc",["--outDir"]),Y=Object.keys(L).filter((ee)=>/^tsconfig(?:\.[^/]*)?\.json$/.test(ee));if(W!==null&&Y.length===1&&Y[0]==="tsconfig.json"){let ee=L["tsconfig.json"];if(Ue(ee,null,"extends")===void 0&&Ue(ee,null,"references")===void 0){let X=Ue(ee,"compilerOptions","outDir");if(X!==null)U(W??X)}}}if(Wr(L)){U("build"),U("dist");for(let W of j.rootFiles)if(W.endsWith(".egg-info"))U(W)}return[...H].sort()}function Wr(j){let T=(j["pyproject.toml"]??"").split(/^\[build-system\]\s*$/m)[1]?.split(/^\[/m)[0]??"";return/^build-backend\s*=\s*["'][^"']+["']/m.test(T)||/(?:from\s+(?:setuptools|distutils.core)\s+import\s+.*\bsetup\b|(?:setuptools|distutils.core)\.setup\s*\()/.test(j["setup.py"]??"")}var Ee=(j)=>j&&typeof j==="object"&&!Array.isArray(j)?j:{},xt=(j)=>Array.isArray(j)?j.filter((T)=>typeof T==="string"):[];function Qo(j){let T=[];function O(z,G="json"){let Z=j.get(z);if(!Z)return{};try{if(G==="yaml")return Ee(Zc(Z,{maxAliasCount:50}));if(G==="toml")return Ee(Yc(Z));if(G==="jsonc"){let le=[],fe=Xc(Z,le,{allowTrailingComma:!0});if(le.length)throw Error("invalid JSONC");return Ee(fe)}return Ee(JSON.parse(Z))}catch{return T.push(`Could not parse ${z}`),{}}}let N=[...j.keys()].sort(),F=O("package.json"),L={packageJson:j.get("package.json")??null,rootFiles:N.filter((z)=>!z.includes("/")),configFiles:Object.fromEntries(["requirements.txt","pyproject.toml","pnpm-workspace.yaml"].flatMap((z)=>j.get(z)?[[z,j.get(z)]]:[]))},H=Yo(L),M=N.flatMap((z)=>{let G=z.replace(/\/package\.json$/,""),Z=G!==z&&(H.packages.includes(G)||H.parents.some((fe)=>G.startsWith(`${fe}/`)&&!G.slice(fe.length+1).includes("/"))),le=j.get(z);return Z&&le?[{dir:G,packageJson:le}]:[]}),U=Vo({...L,workspacePackages:M}),D=typeof F.packageManager==="string"?/^(npm|pnpm|yarn|bun)@(.+)$/.exec(F.packageManager):null,J=Object.create(null);for(let[z,G]of Object.entries(Ee(F.engines)))if(typeof G==="string")J[z]=G;if(D)J[D[1]]=D[2].split("+")[0];let B=O("composer.json"),W={...Ee(B["require-dev"]),...Ee(B.require)},Y={...typeof W.php==="string"?{constraint:W.php}:{},extensions:Object.keys(W).filter((z)=>z.startsWith("ext-")).map((z)=>z.slice(4)).sort()};for(let[z,G]of[[".nvmrc","node"],[".node-version","node"],[".python-version","python"],[".php-version","php"],[".bun-version","bun"]]){let Z=j.get(z)?.trim();if(Z)J[G]=Z}for(let z of(j.get(".tool-versions")??"").split(/\r?\n/)){let[G,Z]=z.replace(/#.*/,"").trim().split(/\s+/);if(G&&Z)J[G==="nodejs"?"node":G]=Z}for(let z of[".mise.toml","mise.toml"])for(let[G,Z]of Object.entries(Ee(O(z,"toml").tools)))if(typeof Z==="string"||typeof Z==="number")J[G]=String(Z);else T.push(`Unsupported tool version for ${G} in ${z}`);let ee=[];for(let z of N.filter((G)=>/(^|\/)package.json$/.test(G))){let G=z==="package.json"?F:O(z),Z={...Ee(G.dependencies),...Ee(G.devDependencies)};for(let le of["nuxt","next","astro","@sveltejs/kit","vite"])if(le in Z)ee.push({path:z,name:le})}for(let[z,G]of[["yiisoft/yii2","yii2"],["laravel/framework","laravel"]])if(z in W)ee.push({path:"composer.json",name:G});let X=new Set,V=Object.create(null);function Q(z,G){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(z))return;if(X.add(z),/(?:^|_)HOST$/.test(z)&&typeof G==="string"&&/^[a-zA-Z0-9_.-]+$/.test(G))V[z]=G}for(let z of N.filter((G)=>/(^|\/)\.env\.(example|sample|template)$/.test(G)))for(let G of(j.get(z)??"").split(/\r?\n/)){let Z=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*(?:#.*)?$/.exec(G);if(Z)Q(Z[1],Z[2].replace(/^['"]|['"]$/g,""))}let q=[],ne=[];for(let z of N.filter((G)=>/(^|\/)(?:docker-compose|compose)(?:[.-][^/]*)?\.ya?ml$/.test(G)))for(let[G,Z]of Object.entries(Ee(O(z,"yaml").services))){let le=Ee(Z),fe=typeof le.image==="string"?le.image:"",ge=fe.split("/").at(-1)?.split(/[:@]/)[0],je=ge==="mysql"||ge==="mariadb"?"mysql":ge==="postgres"?"postgres":ge==="redis"?"redis":null;if(je)q.push({file:z,name:G,kind:je,image:fe});else if(ge!=="traefik"&&ge!=="nginx"&&ge!=="caddy")ne.push({file:z,name:G});for(let[he,Se]of Object.entries(Ee(le.environment)))Q(he,Se);for(let he of xt(le.environment)){let Se=he.indexOf("=");Q(Se<0?he:he.slice(0,Se),Se<0?null:he.slice(Se+1))}}let de=N.find((z)=>z===".devcontainer/devcontainer.json")??N.find((z)=>z==="devcontainer.json"),me;if(de){let z=O(de,"jsonc");for(let G of[z.containerEnv,z.remoteEnv])for(let[Z,le]of Object.entries(Ee(G)))Q(Z,le);me={...typeof z.image==="string"?{image:z.image}:{},services:[...typeof z.service==="string"?[z.service]:[],...xt(z.runServices)],ports:Array.isArray(z.forwardPorts)?z.forwardPorts.filter((G)=>Number.isInteger(G)&&Number(G)>0&&Number(G)<=65535):[],commands:[z.onCreateCommand,z.updateContentCommand,z.postCreateCommand,z.postStartCommand].filter((G)=>typeof G==="string")}}let te=xt(F.workspaces).length?xt(F.workspaces):xt(Ee(F.workspaces).packages);return te.push(...xt(O("pnpm-workspace.yaml","yaml").packages)),{language:j.has("package.json")?"typescript":j.has("pyproject.toml")||j.has("requirements.txt")?"python":j.has("go.mod")?"go":j.has("Cargo.toml")?"rust":j.has("composer.json")?"php":j.has("Gemfile")?"ruby":"other",commands:U,packageManager:D?{name:D[1],version:D[2]}:U.packageManager?{name:U.packageManager}:null,lockfiles:N.filter((z)=>/(^|\/)(bun.lockb?|pnpm-lock.yaml|yarn.lock|package-lock.json|composer.lock|uv.lock|poetry.lock|Pipfile.lock|Cargo.lock|Gemfile.lock)$/.test(z)),toolchain:J,php:Y,workspaces:[...new Set(te)].sort(),frameworks:ee,turbo:j.has("turbo.json")||"turbo"in Ee(F.devDependencies)||"turbo"in Ee(F.dependencies),services:q,unsupportedServices:ne,envKeys:[...X].sort(),envHosts:V,...me?{devcontainer:me}:{},warnings:T}}import{createHash as an}from"node:crypto";import{createReadStream as dl}from"node:fs";import{lstat as bi,mkdir as ul,readFile as sn,readdir as ml,readlink as fl,realpath as ki,stat as Si,writeFile as gl}from"node:fs/promises";import{basename as it,dirname as hl,join as cn,relative as Nn,resolve as Fn,sep as yl}from"node:path";import{execFile as wl,spawnSync as vl}from"node:child_process";import rn from"ignore";import{createReadStream as Qc}from"node:fs";import{lstat as Pt,mkdtemp as el,readFile as qr,readdir as An,rename as tl,rm as nl,writeFile as rl}from"node:fs/promises";import{join as Ie}from"node:path";import ni from"ignore";function Zt(j,T){if(Array.isArray(T))return T.some((O)=>Zt(j,O));if(!T||j.split("/").some((O)=>O===".git"||O===".hlix"))return!1;return j===T||j.startsWith(`${T}/`)}function Qt(j,T){if(typeof T!=="string")return T?.some((O)=>Qt(j,O))??!1;return Zt(j,T)||T.startsWith(`${j}/`)}function ei(j,T,O,N){let F=new Map,L=j.length,H=0;for(let J of j){let B=J.path.indexOf("/"),W=B<0?J.path:J.path.slice(0,B+1),Y=F.get(W)??{count:0,bytes:0,included:!1};Y.count++,Y.bytes+=J.size??0,Y.included||=Zt(J.path,N),F.set(W,Y),H+=J.size??0}let M=H>O,U=[...F].sort(([J,B],[W,Y])=>Number(B.included)-Number(Y.included)||(M?Y.bytes-B.bytes:Y.count-B.count)||J.localeCompare(W)),D=[];for(let[J,B]of U){if(L<=T&&H<=O)break;D.push(J),L-=B.count,H-=B.bytes}return D}function zr(j,T){return T.some((O)=>j===O||O.endsWith("/")&&j.startsWith(O))}function Kr(j){return`upload limit; add /${j} to .hlixignore, or try --include ${j.replace(/\/$/,"")}`.slice(0,200)}function ti(j){if(j.length<=5000)return j;return[...j.slice(0,4999),{path:j[4999].path,reason:`${j.length-4999} additional skipped paths (including this path); full list: hlix import --dry-run --json`}]}var oi="# --- managed by Hlix: safe to edit above/below, this block is regenerated ---",Vr="# --- end managed by Hlix ---",On=new Set(["agent-artifacts",".context",".claude/worktrees"]),sl=/(?:^|\/)(?:Makefile|Dockerfile|Containerfile|Justfile|Rakefile|Gemfile)(?:\.[^/]*)?$/i,ol=/\.(?:md|txt|json)$/i,ri=/(?:^|\n)\s*(?:\/\/|\/\*+|\*|#|<!--)\s*(?:@generated\b|generated by\b|do not edit\b)|(?:^|\n)\s*\/\/[#@]\s*sourceMappingURL=/i,si=/\.(?:log(?:\.\d+)?|tmp|cache|pyc|tsbuildinfo|map)$/i;function en(j){let T=[...j.matchAll(new RegExp(`^${oi}\\r?$`,"gm"))],O=[...j.matchAll(new RegExp(`^${Vr}\\r?$`,"gm"))];if(!T.length&&!O.length)return{before:j,after:"",managed:""};if(T.length!==1||O.length!==1||O[0].index<T[0].index)return null;let N=T[0].index,L=O[0].index+Vr.length,H=j.slice(L).match(/^\r?\n/)?.[0]??"";return{before:j.slice(0,N),after:j.slice(L+H.length),managed:j.slice(N,L)}}function Xr(j){let T=en(j);return(T?T.before+`
|
|
315
|
+
`+T.after:j).split(/\r?\n/).filter((O)=>O.startsWith("!")&&O.length>1).map((O)=>O.slice(1))}async function ii(j,T){let O=Ie(j,".hlixignore"),N="";try{let F=await Pt(O).catch((G)=>{if(G.code==="ENOENT")return null;throw G});if(F&&!F.isFile())return{warning:"Kept .hlixignore unchanged: managed rules require a regular file."};if(F)N=await qr(O,"utf8");let L=en(N);if(!L)return{warning:"Kept .hlixignore unchanged: repair its managed-block markers before refreshing."};let H=Xr(N),M=ni().add(H),U=[],D=[],J=ni(),B=new Set;for(let G of T.tracked){let Z=G.split("/");while(Z.length)B.add(Z.join("/")),Z.pop()}let W=0,Y=0,ee=()=>W<30000&&Y<268435456,X=(G)=>B.has(G)||Qt(G,T.includes)||H.some((Z)=>{let le=Z.replace(/^\//,"").split(/[?*[\\]/)[0];return!le||le.startsWith(`${G}/`)||M.ignores(`${G}/`)||M.ignores(G)}),V=async(G,Z,le=!1)=>{if(T.signal?.throwIfAborted(),!ee()||X(G)||T.protectedPath(G,Z))return!1;W++;let fe=await Pt(Ie(j,G));if(fe.isSymbolicLink())return Z;if(fe.isDirectory()){let he=(await An(Ie(j,G))).sort();for(let Se of he){if(Se===".git")continue;if(!await V(`${G}/${Se}`,Z,le))return!1}return!0}if(!fe.isFile()||Y+fe.size>268435456)return!1;let ge="",je="";for await(let he of Qc(Ie(j,G),{encoding:"utf8",signal:T.signal})){if(Y+=Buffer.byteLength(he),ge.length<4096)ge+=he.slice(0,4096-ge.length);let Se=je+he;if(T.protectedContent(G,Se))return!1;je=Se.slice(-4096)}return Z||ri.test(ge)||ri.test(je)||!sl.test(G)&&!/^#!|^<\?php/.test(ge)&&(le&&ol.test(G)||si.test(G))},Q=new Set,q=async(G,Z=[],le=!1)=>{if(T.signal?.throwIfAborted(),!ee())return;let fe=Ie(j,G),ge=await An(fe,{withFileTypes:!0}),je=async(pe)=>ge.find((ve)=>ve.name===pe)?.isFile()&&(await Pt(Ie(fe,pe))).size<1048576?qr(Ie(fe,pe),"utf8"):null,he=await je("package.json"),Se=await je("composer.json"),ye=!1,at=new Set;try{let pe=JSON.parse(await je("composer.lock")??"null");ye=Array.isArray(pe?.packages);for(let ce of[...pe?.packages??[],...pe?.["packages-dev"]??[]]){if(typeof ce.name==="string")at.add(ce.name);if(ce.dist?.type==="path")ye=!1}}catch{}try{let pe=JSON.parse(he??"{}"),ce=Array.isArray(pe.workspaces)?pe.workspaces:pe.workspaces?.packages;for(let ve of Array.isArray(ce)?ce:[]){if(typeof ve!=="string"||ve.startsWith("!"))continue;let Qe=(G?`${G}/`:"")+ve.replace(/^\.\//,"");D.push(Qe),J.add(Qe)}}catch{}let ct=[he,Se].filter(Boolean).join(`
|
|
316
|
+
`),ze={};for(let pe of ge){if(!/^(?:(?:vite|next|nuxt|astro|webpack|rollup)\.config\.[cm]?[jt]s|tsconfig(?:\.[^/]*)?\.json|turbo\.json|pyproject\.toml|setup\.py)$/.test(pe.name))continue;let ce=await je(pe.name);if(ce!==null)ze[pe.name]=ce}let lt={packageJson:he,rootFiles:ge.map((pe)=>pe.name),configFiles:ze};le||=Wr(ze);let un=Zo(lt);for(let pe of Gr(lt))Q.add(G?`${G}/${pe}`:pe);let Ze=new Set([...un,...Z]);for(let pe of ge.sort((ce,ve)=>ce.name<ve.name?-1:ce.name>ve.name?1:0)){if([".git",".hlix",".hlixignore"].includes(pe.name)||pe.isSymbolicLink())continue;let ce=G?`${G}/${pe.name}`:pe.name;if(/[\n\r\\*?[\]!#]/.test(ce)||ce.endsWith(" "))continue;if(W++,!ee())return;if(pe.isDirectory()){let ve=await Pt(Ie(j,ce,".git")).then(()=>T.isRepository(ce),()=>!1),Qe=On.has(ce)||[...On].some((Re)=>ce.startsWith(`${Re}/`)),mn=T.gitIgnored.directories.some((Re)=>`${ce}/`.startsWith(Re)),et=J.ignores(`${ce}/`)||D.some((Re)=>Re.split(/[?*[\\]/)[0].startsWith(`${ce}/`))||ct.includes(pe.name)||/(?:^|\/)(?:src|lib|apps|packages|tests|resources|public)(?:\/|$)/.test(ce),pt=ve&&(Qe||mn)&&!et;if(pe.name==="vendor"&&ye)for(let Re of await An(Ie(j,ce),{withFileTypes:!0})){if(["autoload.php","composer","bin"].includes(Re.name))continue;if(!Re.isDirectory()){ye=!1;break}for(let It of await An(Ie(j,ce,Re.name)))if(!at.has(`${Re.name}/${It}`))ye=!1}let Ke=un.includes(pe.name)&&(pe.name==="node_modules"||pe.name==="vendor"&&ye&&!/"type"\s*:\s*"path"/.test(Se??"")),fn=Q.has(ce)||le&&pe.name.endsWith(".egg-info");if(((pe.name==="node_modules"||pe.name==="vendor"?Ke:Ze.has(pe.name))||On.has(ce)&&!et||["logs","runtime","tmp"].includes(pe.name)||pt||fn)&&!X(ce)&&await V(ce,Ke||pt||fn,Ze.has(pe.name)||On.has(ce))){U.push(`/${ce}/`);continue}if(!ve&&!["node_modules","vendor"].includes(pe.name))await q(ce,Ze.has("__pycache__")?["__pycache__"]:[],le)}else if(pe.isFile()&&(si.test(pe.name)||(await Pt(Ie(j,ce))).size>T.maxFileBytes)&&!X(ce)&&await V(ce,!1))U.push(`/${ce}`)}};await q("");let ne=N.includes(`\r
|
|
317
|
+
`)?`\r
|
|
318
|
+
`:`
|
|
319
|
+
`,de=[oi,...U.sort(),Vr,""].join(ne),te=L.before+(L.before&&!L.before.endsWith(`
|
|
320
|
+
`)?ne:"")+de+L.after;if(T.write!==!1&&te!==N){let G=await el(Ie(j,".hlixignore-"));try{let Z=Ie(G,"rules");await rl(Z,te,{mode:F?.mode??420});let le=await Pt(O).catch((fe)=>{if(fe.code==="ENOENT")return null;throw fe});if(le?!le.isFile()||le.ino!==F?.ino||le.dev!==F?.dev||await qr(O,"utf8")!==N:F!==null)return{warning:"Kept .hlixignore unchanged: it changed while generated paths were being checked."};await tl(Z,O)}finally{await nl(G,{recursive:!0,force:!0})}}let z=U.every((G)=>G.endsWith("/"))?"generated folders":"generated paths";return{rules:U,report:`Hlix ignored ${U.length} ${z} — see .hlixignore`}}catch(F){return T.signal?.throwIfAborted(),{warning:`Kept .hlixignore unchanged: could not safely refresh generated paths (${F.code??"unreadable"}).`}}}import{readFile as al}from"node:fs/promises";import{join as cl}from"node:path";function il(j){let T=j.trim();if(!T||/^[|>[{]/.test(T))return null;let O=T.match(/^(["'])([\s\S]*)\1$/);if(!O&&/^["']/.test(T))return null;return(O?O[2].trim():T.replace(/(?:^|\s)#.*$/,"").trim())||null}function ai(j){let T=j.split(/\r?\n/),O=T.findIndex((H)=>/^tasks:\s*(?:#.*)?$/.test(H));if(O===-1)return{tasks:[],partial:/^tasks:\s*\S/m.test(j)};let N=[],F=!1,L=-1;for(let H of T.slice(O+1)){if(!H.trim()||/^\s*#/.test(H))continue;let M=H.length-H.trimStart().length,U=H.match(/^(\s*-(?:\s+|$))(.*)$/);if(U){if(L!==-1&&M>=L)continue;if(N.push({}),L=U[2]?U[1].length:-1,!U[2])continue}else if(M===0)break;else if(N.length===0)continue;else if(L===-1)L=M;else if(M!==L)continue;let D=(U?U[2]:H.trim()).match(/^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*)$/);if(!D)continue;let J=D[1];if(J!=="name"&&J!=="before"&&J!=="init"&&J!=="command")continue;let B=il(D[2]);if(B===null)F=!0;else N[N.length-1][J]=B}return{tasks:N,partial:F}}async function ot(j,T){try{return await al(cl(j,...T.split("/")),"utf8")}catch(O){if(O.code==="ENOENT")return null;throw O}}function ci(j){try{let T=j.replace(/(^|[^:\\])\/\/.*$/gm,"$1").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,\s*([}\]])/g,"$1");return JSON.parse(T)}catch{return null}}function Ve(j){if(typeof j==="string"&&j.trim())return[j.trim()];if(Array.isArray(j))return j.flatMap(Ve);if(j&&typeof j==="object")return Object.values(j).flatMap(Ve);return[]}function Yr(j){if(!j||typeof j!=="object")return[];return Object.keys(j).filter((T)=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(T))}function ll(j,T){let O=new Set,N=[/\bprocess\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,/\bimport\.meta\.env\.([A-Za-z_][A-Za-z0-9_]*)/g,/\bos\.(?:getenv|environ\.get)\(\s*["']([A-Za-z_][A-Za-z0-9_]*)/g,/\bos\.Getenv\(\s*["']([A-Za-z_][A-Za-z0-9_]*)/g,/\bENV\[\s*["']([A-Za-z_][A-Za-z0-9_]*)/g];if(T)N.push(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::[-?][^}]*)?\}/g);for(let F of N)for(let L of j.matchAll(F))O.add(L[1]);return[...O]}function pl(j,T){if(j.has("bun.lock")||j.has("bun.lockb")||T?.startsWith("bun@"))return"bun install";if(j.has("pnpm-lock.yaml")||T?.startsWith("pnpm@"))return"pnpm install";if(j.has("yarn.lock")||T?.startsWith("yarn@"))return"yarn install";if(j.has("package.json"))return"npm install";return null}function li(j){let T=typeof j==="number"?j:Number(j);return Number.isInteger(T)&&T>0&&T<=65535?T:null}function Oe(j,T,O){if(!j.some((N)=>N.path===T&&N.kind===O))j.push({path:T,kind:O})}async function pi(j,T,O){let N=[],F=[],L=[],H=[],M=new Map,U=new Set,D=new Set,J=[],B={},W=null,Y=0,ee=await ot(j,".cursor/environment.json");if(ee){Oe(N,".cursor/environment.json","cursor");let te=ci(ee);if(!te)J.push("Could not parse .cursor/environment.json; it remains quarantined.");else{F.push(...Ve(te.install));let z=Ve(te.start);if(z[0])W=z[0];if(Array.isArray(te.terminals))for(let G of te.terminals){if(!G||typeof G!=="object")continue;let Z=G;if(typeof Z.command!=="string"||!Z.command.trim())continue;H.push({name:typeof Z.name==="string"&&Z.name.trim()?Z.name.trim():"Terminal",command:Z.command.trim(),...typeof Z.cwd==="string"&&Z.cwd.trim()?{cwd:Z.cwd.trim()}:{}})}}}let X=T.has(".devcontainer/devcontainer.json")?".devcontainer/devcontainer.json":T.has("devcontainer.json")?"devcontainer.json":null;if(X){Oe(N,X,"devcontainer");let te=ci(O.get(X)??await ot(j,X)??"");if(!te)J.push(`Could not parse ${X}; it remains quarantined.`);else{F.push(...Ve(te.onCreateCommand),...Ve(te.updateContentCommand),...Ve(te.postCreateCommand));let z=Ve(te.postStartCommand);if(!W&&z[0])W=z[0];for(let G of Yr(te.secrets))U.add(G);for(let G of[...Yr(te.containerEnv),...Yr(te.remoteEnv)])U.add(G);if(Array.isArray(te.forwardPorts))for(let G of te.forwardPorts){let Z=li(G);if(Z)M.set(Z,{port:Z,visibility:"private"})}}}if(T.has(".gitpod.yml")){Oe(N,".gitpod.yml","gitpod");let te=O.get(".gitpod.yml")??await ot(j,".gitpod.yml");if(te===null)J.push("Could not read .gitpod.yml; its task commands were not imported.");else{let z=ai(te);Y=z.tasks.filter((G)=>G.before).length;for(let G of z.tasks){if(G.before)F.push(G.before);if(G.init)F.push(G.init);if(!G.command)continue;if(!W)W=G.command;else H.push({name:G.name??"Terminal",command:G.command})}if(z.partial)J.push("Some .gitpod.yml task values are not plain `key: value` scalars and were not imported; review .gitpod.yml before approving cloud setup.")}}for(let te of["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml"])if(T.has(te))Oe(N,te,"docker");for(let te of["project.toml","nixpacks.toml","railpack.json","Aptfile"])if(T.has(te))Oe(N,te,"buildpack");for(let te of["fly.toml","railway.json","render.yaml","vercel.json","netlify.toml"])if(T.has(te))Oe(N,te,"platform");let V=O.get("package.json")??await ot(j,"package.json");if(V){Oe(N,"package.json","package");try{let te=JSON.parse(V);if(te.engines?.node)B.node=te.engines.node;let z=pl(T,te.packageManager);if(z&&F.length===Y)F.push(z);if(te.scripts?.build&&L.length===0)L.push(`${te.packageManager?.split("@")[0]??(T.has("bun.lock")?"bun":"npm")} run build`);let G=te.scripts?.dev?`${T.has("bun.lock")?"bun":"npm"} run dev`:null,Z=te.scripts?.start?`${T.has("bun.lock")?"bun":"npm"} run start`:G;if(!W&&Z)W=Z}catch{J.push("Could not parse package.json for environment discovery.")}}if(T.has("uv.lock"))F.push("uv sync --frozen");else if(T.has("poetry.lock"))F.push("poetry install --no-interaction");else if(T.has("requirements.txt"))F.push("python -m pip install -r requirements.txt");if(T.has("go.mod"))F.push("go mod download");if(T.has("Procfile")){Oe(N,"Procfile","procfile");let z=(O.get("Procfile")??"").split(/\r?\n/).find((G)=>/^web\s*:/.test(G));if(z)W=z.replace(/^web\s*:\s*/,"").trim()||W}let Q=[[".node-version","node"],[".nvmrc","node"],[".python-version","python"]];for(let[te,z]of Q){let G=(O.get(te)??await ot(j,te))?.trim();if(G)B[z]=G,Oe(N,te,"tool-version")}let q=O.get(".tool-versions")??await ot(j,".tool-versions");if(q){Oe(N,".tool-versions","tool-version");for(let te of q.split(/\r?\n/)){let[z,G]=te.trim().split(/\s+/,2);if(!G)continue;if(z==="nodejs")B.node=G;else if(z==="python")B.python=G;else if(z==="bun")B.bun=G}}let ne=O.get("mise.toml")??await ot(j,"mise.toml");if(ne){Oe(N,"mise.toml","tool-version");for(let te of ne.matchAll(/^\s*(node|python|bun)\s*=\s*["']([^"']+)["']/gm))B[te[1]]=te[2]}for(let[te,z]of O){let G=/(?:^|\/)(?:Dockerfile|Procfile)$/i.test(te)||/\.(?:jsonc?|ya?ml|toml|ini|conf|config|env|sh|bash|zsh|fish)$/i.test(te);for(let Z of ll(z,G))D.add(Z);for(let Z of z.matchAll(/(?:--port(?:=|\s+)|PORT\s*=\s*)(\d{2,5})/g)){let le=li(Z[1]);if(le)M.set(le,{port:le,visibility:"private"})}}if(N.length===0&&T.size>0)Oe(N,"repository","detected");let de=(te)=>[...new Set(te.filter(Boolean))],me=N.length+F.length+(W?1:0);return{sources:N.sort((te,z)=>te.path.localeCompare(z.path)),toolchain:B,install:de(F),build:de(L),start:W,terminals:H,ports:[...M.values()].sort((te,z)=>te.port-z.port),requiredSecretKeys:[...U].sort(),observedSecretKeys:[...D].sort(),confidence:me>=4?"high":me>=2?"medium":"low",warnings:J}}var di=2;var ji=300000,bl=25000,ui=52428800,kl=524288000,on=1e4,Sl="Potential secrets exist in Git history",jl="Never delete .git folders or files to get past this; use .hlixignore instead.",Ln=1048576,tn=20971520,Ei=[".git/",".hlix/","node_modules/",".next/",".turbo/",".cache/","dist/","build/","coverage/","__pycache__/",".venv/","venv/","target/",".DS_Store"],Am=rn().add(Ei);var ns="Required project environment value was not found locally: ",El=/(^|\/)\.env\.(example|sample|template)$/i,xl=/(^|\/)\.env(?:\.[^/]+)?$/i,Pl=/(^|\/)(?:\.envrc|\.netrc|\.npmrc|\.pypirc|credentials(?:\.[^/]+)?(?:\.json|\.toml)?|service-account[^/]*\.json|firebase-adminsdk[^/]*\.json|application_default_credentials\.json|\.docker\/config\.json|\.cargo\/credentials(?:\.toml)?|\.gem\/credentials|\.bundle\/config|(?:pip|pypi)\.conf|\.aws\/credentials|[^/]+\.(?:pem|key|p12|pfx)|[^/]*\.(?:auto\.)?tfvars(?:\.json)?|application[^/]*\.(?:properties|ya?ml)|(?:local|keystore|gradle|secrets?)\.properties|appsettings[^/]*\.json|local\.settings\.json|config\/database\.ya?ml|wrangler\.toml|fly\.toml|serverless\.ya?ml|(?:credentials|secrets?)[^/]*\.(?:json|ya?ml|toml|ini|conf|cfg))$/i,$l=/\.(?:example|sample|template)$/i,_l=/(^|\/)\.(?:npmrc|yarnrc(?:\.yml)?|pypirc)$/i,Cl=/(?:^|\/)(?:__tests__|tests?|fixtures)\/|\.(?:test|spec)\.[^/]+$|\.snap$/i,Il=/\.(?:md|mdx|txt|rst)$/i,Rl=/fake|dummy|example|placeholder|unused|changeme|xxxx|redacted|your[_-]|<[^>]*>/i,Tl=/^(.)\1+$/,Al=/RegExp\(/,rs="BEGIN (RSA |EC |OPENSSH )?PRIVATE KEY|npm_[A-Za-z0-9]{30,}|gh[opusr]_[A-Za-z0-9_]{30,}|AKIA[0-9A-Z]{16}|xox[baprs]-[A-Za-z0-9-]{20,}",Ol=new RegExp(rs,"g"),Nl=/(^|\/)(?:\.mcp\.json|mcp\.json|claude_desktop_config\.json)$/i,Fl=/(^|\/)(?:AGENTS\.md|CLAUDE\.md|\.cursorrules|\.github\/copilot-instructions\.md)$/i,Ll=/(^|\/)(?:\.agents|\.claude)\/skills\//i,es=/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|npm_[A-Za-z0-9]{30,}|gh[opusr]_[A-Za-z0-9_]{30,}|glpat-[A-Za-z0-9_-]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}|xox[baprs]-[A-Za-z0-9-]{20,}/,Om=new RegExp(es.source,"g"),mi=/\.(?:json|ya?ml|toml|ini|conf|config)$/i,fi=/(?:^|[,{\s])(?:["']?(?:api[_-]?key|access[_-]?token|auth(?:orization)?|client[_-]?secret|password|private[_-]?key|secret|token)["']?)\s*(?::|=)\s*["']?(?!\$\{|process\.env|import\.meta\.env|os\.(?:getenv|environ\.get)|<|replace|example|changeme)[A-Za-z0-9+/_=.:-]{12,}/im,nn=new Set(["HLIX_AGENT_RUN_ID","HLIX_API_KEY","HLIX_API_URL","HLIX_BASE_URL","HLIX_PROJECT_ID","HLIX_SESSION_TOKEN","HLIX_WORKSPACE_ID"]),Zr="Your hlix credentials were left out of the project's secrets — the platform provides them.",Qr=new Set(["CI","HOME","LANG","LOGNAME","NODE_ENV","OLDPWD","PATH","PORT","PWD","SHELL","SHLVL","TERM","TMPDIR","USER","_"]),Hl=100,gi=12;function Ml(j){let T=j.slice(0,gi).join(", "),O=j.length-gi;return j.length===1?`Observed environment reference has no local value: ${j[0]}`:`${j.length} observed environment references have no local value: ${T}${O>0?`, +${O} more`:""}`}var Ul=250;function Xe(j){return j.split(yl).join("/")}function We(j){if(j>=1048576)return`${(j/1048576).toFixed(1)} MB`;if(j>=1024)return`${(j/1024).toFixed(1)} KB`;return`${j} bytes`}function hi(j,T=5){return[...j].sort((O,N)=>N.size-O.size||O.path.localeCompare(N.path)).slice(0,T).map((O)=>`${O.path} (${We(O.size)})`).join(", ")}function Dl(j,T=5){let O=new Map;for(let N of j){let F=N.indexOf("/"),L=F===-1?".":N.slice(0,F);O.set(L,(O.get(L)??0)+1)}return[...O].sort((N,F)=>F[1]-N[1]||N[0].localeCompare(F[0])).slice(0,T).map(([N,F])=>`${N}/ (${F} files)`).join(", ")}function Ne(j,T,O=10485760){return vl("git",["-C",j,...T],{encoding:"utf8",timeout:ji,maxBuffer:O,stdio:["ignore","pipe","pipe"]})}function l(j,T,O={}){return new Promise((N)=>{wl("git",["-C",j,...T],{encoding:"utf8",timeout:ji,maxBuffer:O.maxBuffer??10485760,...O.signal?{signal:O.signal}:{}},(F,L)=>{let H=F?.code;N({status:F===null?0:typeof H==="number"?H:1,stdout:typeof L==="string"?L:""})})})}async function Jl(j){let T=an("sha256");for await(let O of dl(j))T.update(O);return T.digest("hex")}function ts(j){if(Array.isArray(j))return`[${j.map(ts).join(",")}]`;if(j&&typeof j==="object")return`{${Object.entries(j).sort(([T],[O])=>T.localeCompare(O)).map(([T,O])=>`${JSON.stringify(T)}:${ts(O)}`).join(",")}}`;return JSON.stringify(j)}function xi(j){let T={};for(let[O,N]of String(j).replace(/^\uFEFF/,"").split(/\r?\n/).entries()){let F=N.trim();if(!F||F.startsWith("#"))continue;let H=(F.startsWith("export ")?F.slice(7).trimStart():F).match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(!H)throw Error(`Invalid dotenv assignment on line ${O+1}`);let M=H[2]??"";if(M.startsWith('"')){if(!M.endsWith('"'))throw Error(`Unclosed dotenv quote on line ${O+1}`);M=M.slice(1,-1).replace(/\\n/g,`
|
|
321
|
+
`).replace(/\\r/g,"\r")}else if(M.startsWith("'")){if(!M.endsWith("'"))throw Error(`Unclosed dotenv quote on line ${O+1}`);M=M.slice(1,-1)}else M=M.replace(/\s+#.*$/,"").trimEnd();T[H[1]]=M}return T}function Bl(j,T){return j.split(/(?<=\n)/).filter((O)=>{let N=O.trim(),L=(N.startsWith("export ")?N.slice(7).trimStart():N).match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1];return L===void 0||!T.has(L)}).join("")}function Gl(j){let T=null;for(let O=0;O<j.length;O+=1){let N=j[O];if(N==="\\"&&T!=="single"){if(j[O+1]!=="$")return!0;O+=1;continue}if(N==="'"&&T!=="double"){T=T==="single"?null:"single";continue}if(N==='"'&&T!=="single"){T=T==="double"?null:"double";continue}if(T!=="single"&&(N==="$"||N==="`"))return!0;if(T===null&&(N==="<"||N===">")&&j[O+1]==="(")return!0}return T!==null}function Wl(j){let T={},O=new Set,N=new Set;for(let F of String(j).replace(/^\uFEFF/,"").split(/\r?\n/)){let L=F.trim();if(!L||L.startsWith("#"))continue;let M=(L.startsWith("export ")?L.slice(7).trimStart():L).match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(!M)continue;let U=M[1],D=M[2]??"";if(O.add(U),Gl(D)){delete T[U],N.add(U);continue}try{let B=xi(`${U}=${D}`)[U];if(B===void 0)throw Error("missing literal");T[U]=D.trimStart().startsWith("'")?B:B.replace(/\\\$/g,"$"),N.delete(U)}catch{delete T[U],N.add(U)}}return{values:T,keys:[...O].sort(),dynamicKeys:[...N].sort()}}async function zl(j){let T=Ne(j,["rev-parse","--show-toplevel"]);if(T.status!==0)return!1;try{return await ki(T.stdout.trim())===j}catch{return!1}}function Kl(j,T){if(!T)return new Set;let O=Ne(j,["ls-files","-z"]);if(O.status!==0)throw Error("Could not enumerate tracked files.");return new Set(O.stdout.split("\x00").filter(Boolean).map(Xe))}function ql(j,T){if(!T)return[];let O=Ne(j,["config","--get-regexp","^remote\\..*\\.url$"]);if(O.status!==0)return[];let N=[];for(let F of O.stdout.split(`
|
|
322
|
+
`)){let L=F.trim();if(!L)continue;let H=/^remote\.(.*)\.url (.+)$/.exec(L);if(H)N.push({name:H[1],url:H[2]})}return N}function Vl(j,T){if(!T)return{files:new Set,directories:[]};let O=Ne(j,["ls-files","-z","--others","--ignored","--exclude-standard","--directory"]);if(O.status!==0)throw Error("Could not enumerate ignored files.");let N=new Set,F=[];for(let L of O.stdout.split("\x00").filter(Boolean)){let H=Xe(L);if(H.endsWith("/"))F.push(H);else N.add(H)}return{files:N,directories:F}}async function yi(j,T){let O=[],N=[],F=[],L="";for(let D of[".gitignore",".hlixignore"])try{let J=cn(j,D),B=await bi(J);if(D===".gitignore"&&B.isSymbolicLink()){N.push(D);continue}if(B.isFile()||B.isSymbolicLink())try{if(B.isSymbolicLink()&&!(await Si(J)).isFile()){O.push(D);continue}let W=await sn(J,"utf8");if(D===".hlixignore")L=W;let Y=D===".hlixignore"?en(W):null;if(T&&Y?.managed)W=W.replace(Y.managed,T.join(`
|
|
323
|
+
`));F.push(W)}catch{O.push(D)}}catch(J){if(J.code!=="ENOENT")O.push(D)}let H=en(L)?.managed??"",M=H?[".git/",".hlix/"]:Ei,U=Xr(L);return{hardMatcher:rn().add(U.length?[".git/",".hlix/"]:M),matcher:rn().add([...M,...F.flatMap((D)=>D.split(/\r?\n/))]),unignored:rn().add(U),managedMatcher:rn().add(T??H),hasManaged:Boolean(H),unreadable:O,symlinked:N}}function Hn(j){if(Nl.test(j))return"mcp";if(Ll.test(j))return"skill";if(Fl.test(j))return"agent";return null}function Mn(j){if(xl.test(j)&&!El.test(j))return"dotenv";if(Pl.test(j))return"credential";return null}function Xl(j,T){if(T)return[Xe(T)];let O=new Map([[".env",0],[".env.development",1],[".env.local",2],[".env.development.local",3]]),N=j.filter((F)=>O.has(it(F).toLocaleLowerCase("en-US"))).sort((F,L)=>F.slice(0,-it(F).length).localeCompare(L.slice(0,-it(L).length))||O.get(it(F).toLocaleLowerCase("en-US"))-O.get(it(L).toLocaleLowerCase("en-US")));return N.length>0?N:j.length===1?[...j]:[]}function Yl(j,T){try{let O=JSON.parse(T);if(!O.mcpServers||typeof O.mcpServers!=="object")return[];return Object.entries(O.mcpServers).map(([N,F])=>{let L=F&&typeof F==="object"?F:{},H=L.type==="http"||L.type==="sse"||L.type==="stdio"?L.type:typeof L.command==="string"?"stdio":typeof L.url==="string"?"http":"unknown",M=L.env&&typeof L.env==="object"?L.env:{};return{sourcePath:j,name:N,transport:H,...typeof L.command==="string"?{command:L.command}:{},...Array.isArray(L.args)&&L.args.every((U)=>typeof U==="string")?{args:L.args}:{},...typeof L.url==="string"?{url:L.url}:{},envKeys:Object.keys(M).sort(),enabled:!1}})}catch{return[]}}function Zl(j){let T=!1,O=!1;for(let N of j.split(/\r?\n/)){let F=N.trim();if(!F||F.startsWith("#")||F.startsWith(";")||F.startsWith("["))continue;let L=F.indexOf("=");if(L===-1)continue;let H=F.slice(0,L).trim().toLowerCase(),M=F.slice(L+1).trim().replace(/^["']|["']$/g,"");if(!M||/^\$(?:\{[^}]*\}|[A-Za-z_][A-Za-z0-9_]*)$/.test(M))continue;if(H.endsWith("_authtoken")||H.endsWith("_password"))return!0;if(H.endsWith("password"))O=!0;else if(H.endsWith("username"))T=!0}return T&&O}async function Ql(j,T,O,N){if($l.test(O))return!1;if(!_l.test(O))return!0;let F=await l(j,["show",`${T}:${O}`],{...N?{signal:N}:{}});return F.status===0&&Zl(F.stdout)}function ep(j,T,O){let N=j.lastIndexOf("/",T),F=j.indexOf("/",O);return N!==-1&&F!==-1&&!/\s/.test(j.slice(N,T)+j.slice(O,F))}function tp(j){if(Cl.test(j))return"test fixture";if(Il.test(j))return"documentation or pattern definition";return null}function np(j,T){let O=null;for(let N of j.split(/\r?\n/))for(let F of N.matchAll(T)){let L=F[0],H=F.index??0,M=Al.test(N)||ep(N,H,H+L.length)?"documentation or pattern definition":Rl.test(L)||Tl.test(L)?"placeholder value":null;if(M===null)return null;O??=M}return O}async function rp(j,T,O,N){let F=tp(O);if(F!==null)return F;let L=await l(j,["show",`${T}:${O}`],{...N?{signal:N}:{}});return L.status===0?np(L.stdout,Ol):null}async function wi(j,T,O){let N=[],F="unknown";for(let L of j.split(/\r?\n/)){if(L.startsWith("@@"))F=L.slice(2);else if(L.trim()){let H=Xe(L.trim());if(await O(F,H))N.push({commit:F,path:H,reason:T})}if(N.length>=100)break}return N}async function vi(j,T,O={}){if(!T)return{head:null,branch:null,refs:[],commitCount:0,complete:!0,findings:[],blockingFindings:[],waivedReasons:[]};let N=Ne(j,["rev-parse","HEAD"]).stdout.trim()||null,F=Ne(j,["symbolic-ref","--short","-q","HEAD"]),L=F.status===0?F.stdout.trim()||null:null,H=Number.parseInt(Ne(j,["rev-list","--count","--all"]).stdout.trim(),10)||0,M=Ne(j,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/tags"]),U=M.stdout.split(`
|
|
324
|
+
`).filter(Boolean).map((Q)=>{let[q,ne]=Q.split("\x00");return{name:q,oid:ne}}).filter(({name:Q,oid:q})=>/^refs\/(?:heads|tags)\/.+/.test(Q)&&/^[0-9a-f]{40,64}$/.test(q)).sort((Q,q)=>Q.name.localeCompare(q.name)),D=O.signal,J=D?{signal:D}:{};O.onProgress?.(`history: ${H} commit${H===1?"":"s"}…`);let B=["log","--all",`--max-count=${on}`,"--pretty=format:@@%H","--name-only"],W=await l(j,[...B,"--",".env",".env.*","*.pem","*.key",".npmrc","*.tfvars"],J),Y=await l(j,["log","--all",`--max-count=${on}`,"-G",rs,"--pretty=format:@@%H","--name-only"],J);D?.throwIfAborted();let ee=new Map;for(let Q of[...await wi(W.stdout,"sensitive-path",(q,ne)=>Ql(j,q,ne,D)),...await wi(Y.stdout,"secret-pattern",async()=>!0)])ee.set(`${Q.commit}:${Q.path}:${Q.reason}`,Q);let X=[...ee.values()].slice(0,100),V=new Map;for(let Q of X){if(Q.reason!=="secret-pattern")continue;let q=await rp(j,Q.commit,Q.path,D);if(q!==null)V.set(Q,q)}return O.onProgress?.(`history: ${H} commit${H===1?"":"s"} scanned`),{head:N,branch:L,refs:U,commitCount:H,complete:H<=on&&U.length<=1000&&M.status===0&&W.status===0&&Y.status===0,findings:X,blockingFindings:X.filter((Q)=>!V.has(Q)),waivedReasons:[...V.values()]}}function sp(j,T){let O=T?.XDG_CACHE_HOME??(T?.HOME?cn(T.HOME,".cache"):null);if(!O)return null;return cn(O,"hlix","history",`${an("sha256").update(j).digest("hex")}.json`)}async function op(j,T,O){let N=T?sp(j,O.environment):null;if(!N)return vi(j,T,O);let F=an("sha256").update([Ne(j,["for-each-ref","--format=%(refname)%00%(objectname)"]).stdout,Ne(j,["rev-parse","HEAD"]).stdout,Ne(j,["symbolic-ref","--short","-q","HEAD"]).stdout,rs,String(on)].join("\x00")).digest("hex");try{let H=JSON.parse(await sn(N,"utf8"));if(H.key===F&&H.history)return O.onProgress?.(`history: ${H.history.commitCount} commits, unchanged since the last scan`),H.history}catch{}let L=await vi(j,T,O);if(L.complete)try{await ul(hl(N),{recursive:!0,mode:448}),await gl(N,JSON.stringify({key:F,history:L}),{mode:384})}catch{}return L}async function De(j,T={}){let O=await ki(Fn(j));if(!(await Si(O)).isDirectory())throw Error("Import target must be a directory.");let N=await zl(O),F=ql(O,N),L=Kl(O,N),H=new Set(N?(await l(O,["ls-files","--stage","-z"])).stdout.split("\x00").filter((K)=>K.startsWith("160000 ")).map((K)=>K.slice(K.indexOf("\t")+1)):[]),M=Vl(O,N),U=[...new Set([...s(O)?.includedPaths??[],...T.include?[T.include]:[]].map((K)=>K.replace(/^\.\//,"").replace(/\/$/,"")))],D=await yi(O),J=T.refreshIgnore||D.hasManaged?await ii(O,{write:T.refreshIgnore===!0,tracked:N?L:new Set((await l(O,["ls-files","-z"])).stdout.split("\x00").filter(Boolean)),includes:U,gitIgnored:M,signal:T.signal,maxFileBytes:T.maxFileBytes??ui,isRepository:async(K)=>{let se=await l(cn(O,K),["rev-parse","--show-toplevel"]);return se.status===0&&Fn(se.stdout.trim())===Fn(O,K)},protectedPath:(K,se)=>Boolean(Mn(K)||!se&&Hn(K)),protectedContent:(K,se)=>es.test(se)||mi.test(K)&&fi.test(se)}):void 0,{hardMatcher:B,matcher:W,unignored:Y,managedMatcher:ee,unreadable:X,symlinked:V}=J?await yi(O,J.rules??[]):D,Q=X.length?`Upload left unchanged: cannot read ${X.join(", ")}; check the ignore file target and permissions before retrying.`:void 0,q=[],ne=[],de=[],me=[],te=[],z=[],G=[],Z=[],le=T.envFile?Xe(Nn(O,Fn(O,T.envFile))):void 0,fe=le!==void 0&&le!==""&&le!==".."&&!le.startsWith("../");if(T.envFile&&!fe)Z.push(`Selected environment file must stay inside the project: ${T.envFile}`);let ge=new Map,je=new Map,he=new Map,Se=new Map,ye=J?.warning?[J.warning]:[],at=new Set,ct=[],ze=[],lt=new Map,un=T.maxFiles??bl,Ze=T.maxFileBytes??ui,pe=T.maxTotalBytes??kl,ce=T.historyMode==="sanitize",ve=0,Qe=0,mn=async(K,se=!1)=>{let be=await ml(K,{withFileTypes:!0}).catch((Pe)=>{let $e=Xe(Nn(O,K))||"repository";if(G.push({path:$e,reason:`Cannot read folder (${Pe.code??"unreadable"}); check read and search permissions`}),ye.push(`Cannot read folder ${$e}; check its read and search permissions. Existing cloud files are preserved.`),K===O)Q="Upload left unchanged: cannot read the project folder; check its permissions.";return[]});be.sort((Pe,$e)=>Pe.name.localeCompare($e.name));for(let Pe of be){if(T.signal?.throwIfAborted(),Qe+=1,Qe%Ul===0)T.onProgress?.(`scanning … ${q.length} files`);let $e=cn(K,Pe.name),ae=Xe(Nn(O,$e));if(Pe.name===".git"){if(ae!==".git"&&!se)at.add(Xe(Nn(O,K)));continue}if(ae.length>1000||ae.includes("\\")||ae.includes("\x00")){ye.push(`Skipped a path that cannot be represented safely: ${ae.slice(0,350)}`);continue}try{let xe=await bi($e),Rt=Pe.isDirectory()?`${ae}/`:ae,Ds=L.has(ae)&&!H.has(ae),Tt=!(Zt(ae,U)||Y.ignores(Rt))&&!Ds&&(W.ignores(Rt)||M.files.has(ae)||M.directories.some((we)=>Rt.startsWith(we))),Js=!Qt(ae,U)&&B.ignores(Rt);if(Js){if(ae!==".hlix")G.push({path:ae,reason:"built-in ignore"});continue}if(Tt&&ee.ignores(Rt))G.push({path:ae,reason:"Hlix-managed ignore"});if(xe.isSymbolicLink()){if(Tt)continue;if(ne.push({path:ae,target:await fl($e)}),Hn(ae)||Mn(ae))de.push(ae);continue}if(Pe.isDirectory()){if(Js)continue;if(H.has(ae)&&!Tt)at.add(ae);await mn($e,Tt);continue}let dt=Hn(ae),ut=Mn(ae);if(Tt&&!dt&&!ut)continue;if(!Pe.isFile()){G.push({path:ae,reason:"non-regular-file"});continue}if(xe.size>Ze&&!dt&&!ut){G.push({path:ae,reason:Kr(ae)});continue}if(xe.size>Ze){Z.push(`File ${ae} is ${We(xe.size)}, over the ${We(Ze)} per-file limit. Exclude it with .hlixignore.`);continue}let At=await Jl($e);if(dt){if(xe.size>Ln){Z.push(`Protected configuration ${ae} is ${We(xe.size)}, over the ${We(Ln)} per-file limit. Move the large content out of it, or exclude it with .hlixignore.`);continue}let we=await sn($e);if(ve+=we.byteLength,ze.push({path:ae,size:we.byteLength}),ve>tn)continue;if(te.push({path:ae,kind:dt,size:xe.size,sha256:At}),ct.push({path:ae,kind:dt,contentBase64:we.toString("base64")}),dt==="mcp")z.push(...Yl(ae,we.toString("utf8")));continue}if(ut){if(xe.size>Ln){Z.push(`Protected file ${ae} is ${We(xe.size)}, over the ${We(Ln)} per-file limit. Move the large content out of it, or exclude it with .hlixignore.`);continue}let we=await sn($e);if(ve+=we.byteLength,ze.push({path:ae,size:we.byteLength}),ve>tn)continue;let tt=[],mt=new Set;if(ut==="dotenv")try{let hn=xi(we),ft={};for(let[qe,gt]of Object.entries(hn)){if(nn.has(qe)){mt.add(qe);continue}ft[qe]=gt}ge.set(ae,ft),tt=Object.keys(ft).sort()}catch{Z.push(`Could not parse environment file: ${ae}`)}else if(it(ae)===".envrc"){let hn=Wl(we),ft={},qe=new Set,gt=[];for(let[_e,na]of Object.entries(hn.values)){if(nn.has(_e)){mt.add(_e);continue}if(Qr.has(_e)){ye.push(`Ignored ambient runtime assignment in ${ae}: ${_e}`);continue}qe.add(_e),ft[_e]=na}je.set(ae,ft);for(let _e of hn.dynamicKeys){if(nn.has(_e)){mt.add(_e);continue}if(Qr.has(_e)){ye.push(`Ignored ambient runtime assignment in ${ae}: ${_e}`);continue}qe.add(_e),gt.push(_e)}if(he.set(ae,[...qe].sort()),Se.set(ae,gt.sort()),tt=[...qe].sort(),gt.length>0)ye.push(`Did not execute dynamic .envrc assignments; collect their resolved local values when available: ${gt.join(", ")}`)}if(mt.size>0)ye.push(Zr),we=Buffer.from(Bl(we.toString("utf8"),mt),"utf8"),At=an("sha256").update(we).digest("hex");me.push({path:ae,kind:ut,keys:tt,size:we.byteLength,sha256:At}),ct.push({path:ae,kind:ut,contentBase64:we.toString("base64")});continue}if(xe.size<=1048576){let we=await sn($e),tt=we.toString("utf8");if(lt.set(ae,tt),es.test(tt)||mi.test(ae)&&fi.test(tt)){if(ve+=we.byteLength,ze.push({path:ae,size:we.byteLength}),ve>tn)continue;me.push({path:ae,kind:"detected-content",keys:[],size:xe.size,sha256:At}),ct.push({path:ae,kind:"detected-content",contentBase64:we.toString("base64")});continue}}q.push({path:ae,size:xe.size,sha256:At,tracked:Ds,executable:(xe.mode&73)!==0})}catch(xe){if(T.signal?.throwIfAborted(),Mn(ae)||Hn(ae))throw xe;G.push({path:ae,reason:`Cannot read file (${xe.code??"unreadable"})`})}}};await mn(O);let et=ei([...q,...ne],Math.max(0,un-me.length-te.length),pe,U);if(et.length)q=q.filter((K)=>!zr(K.path,et)),ne=ne.filter((K)=>!zr(K.path,et)),G.push(...et.map((K)=>({path:K.replace(/\/$/,""),reason:Kr(K)})));if(T.onProgress?.(`scanning … ${q.length} files`),T.onProgress?.(`secrets: ${me.length+te.length} files`),T.signal?.throwIfAborted(),de.length>0){let K=de.slice(0,5).join(", "),se=de.length-5;ye.push(`Imported as symlinks, so no content was read or uploaded for them and the cloud recreates the link: ${K}${se>0?`, +${se} more`:""}`)}for(let K of V)ye.push(`Ignore file ${K} is a symlink, so its rules were not applied. Replace it with a regular file inside the project.`);if(Q)ye.push(Q);if(ve>tn)Z.push(`Protected project files total ${We(ve)}, over the ${We(tn)} limit. Largest: ${hi(ze)}. Move large assets out of skill and config folders, or add them to .hlixignore.`);if(me.length>2000)Z.push(`Project has ${me.length} environment and credential files, over the 2000 limit. Largest: ${hi(me)}. Exclude the ones the cloud project does not need with .hlixignore.`);if(te.length>5000)Z.push(`Project has ${te.length} agent, skill and MCP files, over the 5000 limit. Largest folders: ${Dl(te.map((K)=>K.path))}. Exclude the ones the cloud project does not need with .hlixignore.`);q.sort((K,se)=>K.path.localeCompare(se.path)),ne.sort((K,se)=>K.path.localeCompare(se.path)),me.sort((K,se)=>K.path.localeCompare(se.path)),te.sort((K,se)=>K.path.localeCompare(se.path)),z.sort((K,se)=>`${K.sourcePath}:${K.name}`.localeCompare(`${se.sourcePath}:${se.name}`));let pt=Xl([...ge.keys()].sort(),fe?le:void 0);if(T.envFile&&fe&&!ge.has(pt[0]))Z.push(`Selected environment file was not found or is not a dotenv file: ${T.envFile}`);let Ke=new Map;for(let[K,se]of ge)for(let be of Object.keys(se))Ke.set(be,[...Ke.get(be)??[],K]);for(let[K,se]of he)for(let be of se)Ke.set(be,[...Ke.get(be)??[],K]);let fn=[...Ke].filter(([,K])=>K.length>1).map(([K,se])=>({key:K,paths:se.sort()})).sort((K,se)=>K.key.localeCompare(se.key)),Le={};for(let K of pt)Object.assign(Le,ge.get(K)??{});let Re=[...je.keys()].sort((K,se)=>{if(K===".envrc")return 1;if(se===".envrc")return-1;return K.localeCompare(se)}),It=new Set;for(let K of Re){let se=new Set(Se.get(K)??[]);for(let be of he.get(K)??[]){if(se.has(be)){delete Le[be],It.add(be);continue}let Pe=je.get(K)?.[be];if(Pe!==void 0)Le[be]=Pe;It.delete(be)}}for(let K of at)ye.push(`${K} has its own Git repository — uploaded as files, its history not included`);let Zi=T.historyMode==="abort_on_findings"?"abort_on_findings":"preserve";if(ce)ye.push("Git history omitted; uploading a snapshot of the current files.");let Te=await op(O,N,T);if(!Te.complete)ye.push(`Git history scan exceeded ${on} commits or failed; history is preserved, but the findings may be incomplete.`);if(N&&!Te.head)ce=!0,ye.push("Git has no readable HEAD; uploading the current files as a snapshot.");let Fs=Te.waivedReasons;for(let K of[...new Set(Fs)].sort()){let se=Fs.filter((Pe)=>Pe===K).length,be=se===1;ye.push(`${se} Git history finding${be?"":"s"} did not block this import — ${K}, not ${be?"a real credential":"real credentials"}; --history preserve is not needed for ${be?"it":"them"}.`)}if(Te.blockingFindings.length>0){let K=Te.blockingFindings.length;ye.unshift([`${Sl} (${K} finding${K===1?"":"s"}${K>5?", first 5 shown":""}); ${ce?"history is omitted":"history is preserved"}:`,...Te.blockingFindings.slice(0,5).map((se)=>` ${se.commit.slice(0,7)} ${se.path} — ${se.reason}`)," To exclude old commits, use --history sanitize; local Git history stays intact."].join(`
|
|
325
|
+
`))}let Ls=new Set(q.map((K)=>K.path)),Qi=await pi(O,Ls,lt),{observedSecretKeys:ea,...He}=Qi;He.warnings.unshift(...ye);let gn=new Set(He.requiredSecretKeys);for(let K of It)gn.add(K);for(let K of z)for(let se of K.envKeys)gn.add(se);for(let K of nn)if(gn.delete(K))He.warnings.push(Zr);He.requiredSecretKeys=[...gn].sort();for(let K of He.requiredSecretKeys){if(Le[K]!==void 0)continue;let se=T.environment?.[K];if(se===void 0){Z.push(`${ns}${K}`);continue}Le[K]=se}let zn=[];for(let K of ea){if(nn.has(K)){He.warnings.push(Zr);continue}if(Qr.has(K))continue;if(Le[K]!==void 0)continue;let se=T.environment?.[K];if(se===void 0){zn.push(K);continue}Le[K]=se}if(zn.length>0)He.warnings.push(Ml(zn.sort()));He.warnings=[...new Set(He.warnings.flatMap((K)=>K.split(`
|
|
326
|
+
`)))].map((K)=>K.slice(0,500)).slice(0,Hl);let Hs=Qo(new Map([...Ls].map((K)=>[K,lt.get(K)??null]))),Ms={schemaVersion:di,rootName:T.rootName??it(O),stack:Hs.language,git:{detected:N&&!ce,head:ce?null:Te.head,branch:ce?null:Te.branch,refs:ce?[]:Te.refs,commitCount:ce?0:Te.commitCount,historyScanComplete:Te.complete,historyMode:Zi},files:q,symlinks:ne,secretFiles:me,activeEnvFiles:pt,secretKeys:Object.keys(Le).sort(),envCollisions:fn,quarantinedResources:te,mcpServers:z,historicalSecretFindings:Te.blockingFindings,skipped:ti(G),environment:He,totals:{files:q.length,bytes:q.reduce((K,se)=>K+se.size,0)}},Us=ts(Ms),ta=an("sha256").update(Us).digest("hex");return{root:O,includedPaths:U,ignoreReport:T.refreshIgnore?J?.report??J?.warning:void 0,uploadWarning:Q,stackFacts:Hs,manifest:Ms,...G.length>5000?{skippedEntries:G}:{},manifestJson:Us,manifestSha256:ta,secretValues:Le,protectedFiles:ct.sort((K,se)=>K.path.localeCompare(se.path)),blocking:[...new Set(Z)].map((K)=>`${K}
|
|
327
|
+
${jl}`),blockingHistoryFindings:[],gitRemotes:F}}var ss={name:"init",summary:"Configure a local folder for Hlix",usage:["Usage: hlix init [folder] [--project <id>] [--json]","","Creates .hlix/config.json, .hlix/.gitignore, and .hlixignore.","Project configuration is safe to commit; local revision state is ignored.",""," --project <id> Bind the folder to an existing cloud project"," Then `hlix pull`, or `hlix push` if it has no files yet"].join(`
|
|
328
|
+
`),supportsJson:!0,options:["project"],args:{min:0,max:1},async run(j){if(j.args.length>1)throw Error("init accepts at most one folder.");let T=await ip(ap(j.cwd,j.args[0]??".")),O=r({env:j.env,flags:j.flags,cwd:T});if(O.conflict)throw new e("workspace_mismatch",O.conflict);if(!O.workspaceId)throw Error("No workspace selected. Run `hlix auth login --workspace <id>` first.");let N=j.requireClient(T);await N.projects.list();let F=ht(T),L=typeof j.flags.project==="string"?j.flags.project:void 0;if(L&&F?.projectId&&F.projectId!==L)throw new e("workspace_mismatch",`This folder is bound to project ${F.projectId}; refusing to rebind it to ${L}.`);if(L)await N.projects.get(L);let H={...F??{schemaVersion:1,workspaceId:O.workspaceId,apiUrl:O.baseUrl},...L?{projectId:L}:{}};bn(T,H);let M=await De(T,{environment:j.env,refreshIgnore:!0}),U={root:T,config:H,ignoreReport:M.ignoreReport,scan:{files:M.manifest.totals.files,bytes:M.manifest.totals.bytes,secretFiles:M.manifest.secretFiles.map((D)=>D.path),quarantinedResources:M.manifest.quarantinedResources.map((D)=>D.path),blocking:M.blocking}};if(j.json)j.stdout(re(oe(ss.name,U)));else{if(M.ignoreReport)j.stdout(`${M.ignoreReport}
|
|
329
|
+
`);if(j.stdout(`Initialized ${T}
|
|
330
|
+
Project: ${H.projectId??"not imported yet"}
|
|
331
|
+
Workspace: ${H.workspaceId}
|
|
332
|
+
`),M.blocking.length)j.stdout(`
|
|
333
|
+
Review before import:
|
|
334
|
+
${M.blocking.map((D)=>`- ${D}`).join(`
|
|
335
|
+
`)}
|
|
336
|
+
`)}return 0}};import{basename as Mp,resolve as Up}from"node:path";import{realpath as Dp}from"node:fs/promises";import{mkdtemp as Ip,rm as Jn,readFile as Rp,writeFile as Tp,chmod as Ap,symlink as Op,lstat as Np}from"node:fs/promises";import{tmpdir as Fp}from"node:os";import{join as as}from"node:path";import{createHash as cp}from"node:crypto";import{createReadStream as lp}from"node:fs";import{chmod as Pi,copyFile as pp,lstat as dp,mkdir as os,mkdtemp as up,readdir as mp,readlink as fp,rm as is,symlink as gp}from"node:fs/promises";import{tmpdir as hp}from"node:os";import{dirname as $i,join as Ye}from"node:path";import{spawnSync as Un}from"node:child_process";var Dn=300000;function Fe(j,T){let O=Un("git",["-c","core.hooksPath=/dev/null","-C",j,...T],{encoding:"utf8",timeout:Dn,maxBuffer:20971520,stdio:["ignore","pipe","pipe"]});if(O.status!==0){let N=O.stderr.trim().split(`
|
|
337
|
+
`).at(-1)??"git command failed";throw Error(N)}return O.stdout.trim()}async function yp(j){let T=cp("sha256");for await(let O of lp(j))T.update(O);return T.digest("hex")}async function wp(j){for(let T of await mp(j)){if(T===".git")continue;await is(Ye(j,T),{recursive:!0,force:!0})}}async function _i(j){if(j.manifest.git.detected&&(j.manifest.historicalSecretFindings.length||!j.manifest.git.historyScanComplete))throw Error("Git history has secrets or could not be fully scanned. Use --history sanitize to import current files.");if(j.uploadWarning)throw Error(j.uploadWarning);if(j.blocking.length>0)throw Error(`Project scan has blocking findings:
|
|
338
|
+
- ${j.blocking.join(`
|
|
339
|
+
- `)}`);let T=await up(Ye(hp(),"hlix-snapshot-"));await Pi(T,448);let O=Ye(T,"repo"),N=Ye(T,"source.git");try{if(j.manifest.git.detected){let M=Un("git",["clone","--mirror","--no-hardlinks",j.root,N],{encoding:"utf8",timeout:Dn,stdio:["ignore","pipe","pipe"]});if(M.status!==0)throw Error(M.stderr.trim()||"Could not mirror repository.");let U=new Map(Fe(N,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/tags"]).split(`
|
|
340
|
+
`).filter(Boolean).map((J)=>J.split("\x00",2)));for(let J of j.manifest.git.refs)if(U.get(J.name)!==J.oid)throw Error(`Git ref changed after scan: ${J.name}`);let D=Un("git",["clone","--no-hardlinks",N,O],{encoding:"utf8",timeout:Dn,stdio:["ignore","pipe","pipe"]});if(D.status!==0)throw Error(D.stderr.trim()||"Could not create snapshot clone.");if(!j.manifest.git.head)throw Error("Git repository has no HEAD commit.");Fe(O,["checkout","-B","main",j.manifest.git.head])}else await os(O,{recursive:!0,mode:448}),Fe(O,["init","-b","main"]);await wp(O);for(let M of j.manifest.files){let U=Ye(j.root,...M.path.split("/")),D=await dp(U);if(!D.isFile()||D.isSymbolicLink())throw Error(`Source changed after scan: ${M.path}`);if(D.size!==M.size||await yp(U)!==M.sha256)throw Error(`Source changed after scan: ${M.path}`);let J=Ye(O,...M.path.split("/"));await os($i(J),{recursive:!0,mode:493}),await pp(U,J),await Pi(J,M.executable?493:420)}for(let M of j.manifest.symlinks){let U=Ye(j.root,...M.path.split("/"));if(await fp(U).catch(()=>null)!==M.target)throw Error(`Source changed after scan: ${M.path}`);let D=Ye(O,...M.path.split("/"));await os($i(D),{recursive:!0,mode:493}),await gp(M.target,D)}Fe(O,["config","user.name","Hlix Import"]),Fe(O,["config","user.email","import@hlix.ai"]),Fe(O,["read-tree","--empty"]),Fe(O,["add","--force","-A"]),Fe(O,["commit","--allow-empty","-m","chore(hlix): import snapshot"]);let F=Fe(O,["rev-parse","HEAD"]),L=new Set(j.manifest.git.refs.map((M)=>M.name));for(let M of Fe(O,["for-each-ref","--format=%(refname)","refs/heads","refs/tags"]).split(`
|
|
341
|
+
`).filter(Boolean))if(M!=="refs/heads/main"&&!L.has(M))Fe(O,["update-ref","-d",M]);let H=j.manifest.git.refs.filter((M)=>M.name!=="refs/heads/main");if(H.length>0){let M=Un("git",["-C",O,"update-ref","--stdin"],{encoding:"utf8",timeout:Dn,input:H.map((U)=>`update ${U.name} ${U.oid}`).join(`
|
|
342
|
+
`)+`
|
|
343
|
+
`,stdio:["pipe","pipe","pipe"]});if(M.status!==0)throw Error(M.stderr.trim()||"Could not recreate the approved Git refs.")}return{directory:O,commitSha:F,dispose:()=>is(T,{recursive:!0,force:!0})}}catch(F){throw await is(T,{recursive:!0,force:!0}),F}}import{lstat as Ii,mkdir as vp,realpath as bp}from"node:fs/promises";import{dirname as kp,join as Sp,relative as jp,resolve as Ep,sep as Ci}from"node:path";function Ri(j,T){let O=j;if(typeof O==="string")try{O=JSON.parse(O)}catch{return[]}if(!O||typeof O!=="object")return[];let N=O[T];if(!Array.isArray(N))return[];return N.filter((F)=>!!F&&typeof F==="object")}function Ti(j){return Ri(j,"files").flatMap((T)=>typeof T.path==="string"&&typeof T.sha256==="string"?[{path:T.path,sha256:T.sha256}]:[])}function Ai(j){return Ri(j,"symlinks").flatMap((T)=>typeof T.path==="string"&&typeof T.target==="string"?[{path:T.path,target:T.target}]:[])}async function ln(j,T,O){let N=await bp(j),F=Ep(N,...T.split("/"));if(F!==N&&!F.startsWith(N+Ci))throw Error(`Protected path escapes the project: ${T}`);let L=jp(N,kp(F)),H=N;for(let M of L.split(Ci).filter(Boolean)){H=Sp(H,M);try{let U=await Ii(H);if(U.isSymbolicLink()&&O){O.push(H);break}if(!U.isDirectory()||U.isSymbolicLink())throw Error(`Protected path crosses a non-directory: ${T}`)}catch(U){if(U.code!=="ENOENT")throw U;if(!O)await vp(H,{mode:448})}}return F}async function Oi(j,T,O){let N=O.length,F=await ln(j,T,O);if(O.length>N)return;try{let L=await Ii(F);if(L.isSymbolicLink()){O.push(F);return}if(!L.isFile())throw Error(`Refusing to replace non-regular project file: ${T}`)}catch(L){if(L.code!=="ENOENT")throw L}}import{spawnSync as xp}from"node:child_process";import{mkdtemp as Pp,writeFile as $p,rm as _p}from"node:fs/promises";import{tmpdir as Cp}from"node:os";import{join as Ni}from"node:path";function Fi(j,T,O){let N=xp("git",["-c","core.hooksPath=/dev/null","-C",j,...T],{encoding:"utf8",timeout:120000,maxBuffer:41943040,env:{PATH:process.env.PATH,GIT_CONFIG_GLOBAL:O??"/dev/null",GIT_CONFIG_NOSYSTEM:"1",GIT_TERMINAL_PROMPT:"0",GIT_AUTHOR_NAME:"HLIX",GIT_AUTHOR_EMAIL:"repos@hlix.ai",GIT_COMMITTER_NAME:"HLIX",GIT_COMMITTER_EMAIL:"repos@hlix.ai"}});if(N.status!==0)throw Error("HLIX Repos Git operation failed. The remote may have changed; refresh and retry.");return N.stdout.trim()}async function Li(j,T){let O=new URL(j.cloneUrl);if(O.href!==j.cloneUrl||/[\r\n"\\]/.test(j.cloneUrl)||O.protocol!=="https:"||O.username||O.password||O.search||O.hash||O.port||!(O.hostname==="github.com"||/^[a-f0-9]{32}\.artifacts\.cloudflare\.net$/.test(O.hostname)))throw Error("Invalid HLIX Repos remote");if(/[\r\n]/.test(j.token))throw Error("Invalid repository credential");let N=await Pp(Ni(Cp(),"hlix-git-auth-")),F=Ni(N,"config"),L=j.token.replace(/\?expires=\d+$/,""),H=Buffer.from(`x-access-token:${L}`).toString("base64");try{return await $p(F,`[http "${j.cloneUrl}"]
|
|
344
|
+
extraHeader = Authorization: Basic ${H}
|
|
345
|
+
followRedirects = false
|
|
346
|
+
`,{mode:384}),await T(F)}finally{await _p(N,{recursive:!0,force:!0})}}function $t(j){return new Map([...Ti(j).map((T)=>[T.path,`blob:${T.sha256}`]),...Ai(j).map((T)=>[T.path,`link:${T.target}`])])}var Hi={git:Fi,access:Li};async function _t(j){let T=t(j);if(!T?.config.projectId)throw new e("not_initialized","Run hlix import or hlix init to bind this folder to a project.");return{...T,state:s(T.root)}}async function Mi(j,T){let O=await De(j,{environment:T,historyMode:"sanitize",maxFiles:50000,maxFileBytes:33554432,maxTotalBytes:1073741824});if(O.manifest.files=O.manifest.files.filter((N)=>N.path!==".hlixignore"),O.blocking.length)throw new e("scan_blocked",O.blocking.join(`
|
|
347
|
+
`));return O}function Lp(j,T){let O=Object.fromEntries($t(j.manifest));return!T?.files?j.manifest.files.length+j.manifest.symlinks.length>0:JSON.stringify(Object.entries(O).sort())!==JSON.stringify(Object.entries(T.files).sort())}async function cs(j,T,O){let N=await j.projects.get(T),F=O?N.repos.find((L)=>L.id===O):N.repos.find((L)=>L.isPrimary)??(N.repos.length===1?N.repos[0]:void 0);if(!F)throw new e("conflict","Select a primary repository for this project before syncing.");return F}async function ls(j,T,O,N,F=!1,L=Hi){let{config:H,state:M}=await _t(j),U=await cs(T,H.projectId,M?.repoId),D=await T.repos.head(H.projectId,U.id);if((N??M?.commitSha)&&D.commitSha!==(N??M?.commitSha))throw new e("conflict","HLIX Repos changed. Pull or sync before pushing.");let J=await _i(O);try{let B=await T.repos.access(H.projectId,U.id,"write"),W=await L.access(B,async(Y)=>{L.git(J.directory,["fetch","--no-tags",B.cloneUrl,`refs/heads/${U.defaultBranch}`],Y);let ee=L.git(J.directory,["rev-parse","FETCH_HEAD"]);if(ee!==D.commitSha)throw new e("conflict","HLIX Repos changed during upload. Retry sync.");let X=L.git(J.directory,["rev-parse",`${J.commitSha}^{tree}`]),V=L.git(J.directory,["commit-tree",X,"-p",ee,...F&&O.manifest.git.detected?["-p",J.commitSha]:[],"-m","Update HLIX Repos files"]);return L.git(J.directory,["push",`--force-with-lease=refs/heads/${U.defaultBranch}:${ee}`,B.cloneUrl,`${V}:refs/heads/${U.defaultBranch}`],Y),V});return er(j,{schemaVersion:1,repoId:U.id,commitSha:W,files:Object.fromEntries($t(O.manifest)),snapshotOnly:!0,rootName:O.manifest.rootName}),{action:"push",commitSha:W}}finally{await J.dispose()}}async function Hp(j,T,O,N,F,L){let{config:H}=await _t(j),M=await cs(T,H.projectId,O),U=await Ip(as(Fp(),"hlix-pull-"));try{let D=await T.repos.access(H.projectId,O,"read");await L.access(D,async(V)=>{L.git(U,["init"]),L.git(U,["fetch","--no-tags",D.cloneUrl,`refs/heads/${M.defaultBranch}`],V),L.git(U,["checkout","--detach",N])});let J=await Mi(U),B=[],W=[...J.manifest.files,...J.manifest.symlinks],Y=[...F.manifest.files,...F.manifest.symlinks].filter((V)=>!W.some((Q)=>Q.path===V.path)),ee=new Set([...F.manifest.files,...F.manifest.symlinks].map((V)=>V.path));for(let V of W){let Q=V.path.split("/");for(let q=1;q<=Q.length;q++){let ne=Q.slice(0,q).join("/"),de=await Np(as(j,ne)).catch((me)=>{if(me.code!=="ENOENT")throw me;return null});if(de&&!de.isDirectory()&&!ee.has(ne))throw new e("conflict",`Incoming repository file would replace an excluded local file: ${ne}`)}}for(let V of[...W,...Y])await Oi(j,V.path,B);let X=await Promise.all(J.manifest.files.map(async(V)=>({...V,bytes:await Rp(as(U,V.path))})));for(let V of[...new Set(B)].sort((Q,q)=>Q.length-q.length))await Jn(V,{force:!0});for(let V of Y)await Jn(await ln(j,V.path),{force:!0});for(let V of X){let Q=await ln(j,V.path);await Tp(Q,V.bytes,{mode:V.executable?493:420}),await Ap(Q,V.executable?493:420)}for(let V of J.manifest.symlinks){let Q=await ln(j,V.path);await Jn(Q,{force:!0}),await Op(V.target,Q)}return er(j,{schemaVersion:1,repoId:O,commitSha:N,files:Object.fromEntries($t(J.manifest)),snapshotOnly:!0,rootName:F.manifest.rootName}),{action:"pull",commitSha:N}}finally{await Jn(U,{recursive:!0,force:!0})}}async function ps(j,T,O,N="sync",F=!1,L=Hi){let{config:H,state:M}=await _t(j),U=await cs(T,H.projectId,M?.repoId),[D,J]=await Promise.all([Mi(j,O),T.repos.head(H.projectId,U.id)]),B=Lp(D,M),W=M?.commitSha!==J.commitSha,Y=!M&&B&&!J.isEmpty?"conflict":N==="push"?W&&M?"conflict":B?"push":"none":N==="pull"?B?"conflict":W?"pull":"none":B&&W&&M?"conflict":B?"push":W?"pull":"none";if(F)return{action:Y,localChanged:B,cloudChanged:W,commitSha:J.commitSha};if(Y==="conflict")throw new e("conflict","This folder and HLIX Repos have both changed. Resolve the differences before syncing; no files were replaced.");if(Y==="push")return ls(j,T,D,J.commitSha,!1,L);if(Y==="pull")return Hp(j,T,U.id,J.commitSha,D,L);return{action:"none",commitSha:J.commitSha}}function ds(j){return{name:j,summary:`${j} files with HLIX Repos`,usage:`Usage: hlix ${j} [--dry-run] [--json]`,supportsJson:!0,options:["dry-run"],async run(T){let{root:O}=await _t(T.cwd),N=await ps(O,T.requireClient(),T.env,j,T.flags["dry-run"]===!0);return T.stdout(T.json?re(oe(`hlix ${j}`,N)):`HLIX Repos: ${N.action} (${N.commitSha})
|
|
348
|
+
`),N.action==="conflict"?1:0}}}var Ui=ds("push"),Di=ds("pull"),Ji=ds("sync");var Bi={name:"import",summary:"Import a local project into HLIX Repos",usage:"Usage: hlix import [folder] [--history preserve|sanitize] [--name name] [--stack stack] [--dry-run] [--yes] [--json]",supportsJson:!0,options:["history","name","stack","dry-run","yes","env-file","include"],args:{min:0,max:1},async run(j){let T=await Dp(Up(j.cwd,j.args[0]??".")),O=r({env:j.env,flags:j.flags,cwd:T});if(O.conflict)throw new e("conflict",O.conflict);if(!O.workspaceId||!O.credential)throw new e("workspace_required","Run hlix auth login to select a workspace.");if(ht(T)?.projectId)throw new e("conflict","This folder is already bound to a project. Use hlix push or sync.");let F=j.flags.history??"preserve";if(F!=="preserve"&&F!=="sanitize")throw new e("invalid_usage","--history accepts preserve or sanitize.");let L=await De(T,{environment:j.env,historyMode:F,envFile:typeof j.flags["env-file"]==="string"?j.flags["env-file"]:void 0,maxFiles:50000,maxFileBytes:33554432,maxTotalBytes:1073741824,include:typeof j.flags.include==="string"?j.flags.include:void 0});if(L.blocking.length)throw new e("scan_blocked",L.blocking.join(`
|
|
349
|
+
`));if(L.manifest.git.detected&&(L.manifest.historicalSecretFindings.length||!L.manifest.git.historyScanComplete))throw new e("scan_blocked","History contains potential secrets or was not completely scanned. Review it or use --history sanitize.");let H={files:L.manifest.totals.files,bytes:L.manifest.totals.bytes,protectedFiles:L.protectedFiles.length,history:F};if(j.flags["dry-run"]===!0)return j.stdout(re(oe("hlix import",H))),0;if(j.flags.yes!==!0&&!await j.confirm?.(`Import ${H.files} files into HLIX Repos and encrypt ${H.protectedFiles} protected files?`))throw new e("invalid_usage","Import requires approval. Review --dry-run, then use --yes.");let M=j.requireClient(T),U=await M.projects.create({name:typeof j.flags.name==="string"?j.flags.name:Mp(T),stack:typeof j.flags.stack==="string"?j.flags.stack:L.manifest.stack,repos:[]});bn(T,{schemaVersion:1,projectId:U.id,workspaceId:O.workspaceId,apiUrl:O.baseUrl});for(let J=0;J<L.protectedFiles.length;J+=64)await M.secrets.importFiles(U.id,L.protectedFiles.slice(J,J+64).map((B)=>({path:B.path,contentBase64:B.contentBase64})));let D=await ls(T,M,L,void 0,F==="preserve");return j.stdout(j.json?re(oe("hlix import",{...H,projectId:U.id,commitSha:D.commitSha})):`Imported into HLIX Repos: ${U.name} (${D.commitSha})
|
|
350
|
+
`),0}};import{spawnSync as Jp}from"node:child_process";import{existsSync as Bp,mkdirSync as Gp,writeFileSync as Wp}from"node:fs";import{dirname as zp}from"node:path";function Kp(j){return j==="global"?["# My rules","","Hlix Code reads this file in every project you open, before the project's","own rules. Write how you want an agent to work with you: the tone, the","things to always do, the things to never do.",""].join(`
|
|
351
|
+
`):["# Project rules","","Hlix Code and every other coding agent that opens this repository read","this file. Write the rules that are true of THIS project: how to run its","tests, its conventions, what not to touch.",""].join(`
|
|
352
|
+
`)}function qp(j){return j.VISUAL?.trim()||j.EDITOR?.trim()||"vi"}var us={name:"rules",summary:"Show or edit the rules files the coding agent reads",usage:["Usage: hlix rules [--edit] [--global] [--cwd <dir>] [--json]","","Without --edit it reports which files Hlix Code loads and how big they are.","","--edit opens one in $EDITOR, creating it with a short header if it does not","exist yet. --global edits your own rules (~/.hlix/AGENTS.md, read in every",`project); without it the project's file (${f.join(", then ")}).`].join(`
|
|
353
|
+
`),supportsJson:!0,options:["edit","global"],async run(j){let T=y({cwd:j.cwd,configDir:".hlix",env:j.env}),O=j.flags.global===!0;if(j.flags.edit===!0){if(j.json)throw new e("invalid_usage","`hlix rules --edit` opens an editor, so it has no --json form.");let N=O?Er(j.env):jr(j.cwd,".hlix")?.path??`${j.cwd}/AGENTS.md`;if(!Bp(N))Gp(zp(N),{recursive:!0}),Wp(N,Kp(O?"global":"project"),"utf8"),j.stdout(`Created ${N}.
|
|
354
|
+
`);let F=qp(j.env),L=Jp(F,[N],{stdio:"inherit"});if(L.error)throw new e("invalid_usage",`Could not run ${F}: ${L.error.message}`);return L.status??0}if(j.json){let N=(F)=>F?{path:F.path,characters:F.content.length}:null;return j.stdout(re(oe(us.name,{user:N(T.global),project:N(T.project)}))),0}return j.stdout(`${w(T,j.cwd)}
|
|
355
|
+
`),0}};var ms={name:"standards",summary:"Show the standards other agent tools left in this folder",usage:["Usage: hlix standards [--cwd <dir>] [--json]","","Reads the instruction files, skills, slash commands, MCP servers and","subagents this project already carries for Claude Code, Cursor, Windsurf,","Gemini, Codex, Cline, Copilot and VS Code, and shows where each came from.","Hlix Code loads all of it at startup; nothing has to be copied or rewritten.","","Server urls, headers and environment values are never printed."].join(`
|
|
356
|
+
`),supportsJson:!0,async run(j){let T=b(j.cwd,i(j.env),{env:j.env});if(j.json)return j.stdout(re(oe(ms.name,{instructions:T.instructions.map((O)=>({path:O.path,source:O.source,scope:O.scope,characters:O.content.length,...O.note?{note:O.note}:{}})),skills:T.skills,commands:[...T.commands.map((O)=>({path:O.path,source:O.source,scope:O.scope})),...T.generatedCommands.map((O)=>({path:O.path,source:O.source,scope:O.scope,command:O.name}))],mcpServers:T.mcpServers.map((O)=>({path:O.path,source:O.source,scope:O.scope,name:O.name,transport:"command"in O.config?"stdio":"http"})),subagents:T.subagents.map((O)=>({path:O.path,source:O.source,scope:O.scope,name:O.name,description:O.description,...O.model?{model:O.model}:{}})),skipped:T.skipped}))),0;return j.stdout(No(T,j.cwd)),0}};var Wi=(j)=>j instanceof Error?j.message:String(j),Gi=(j)=>j.split(/\s*\n\s*/).join(" ").trim();async function x(j,T,O,N,F){try{let L=await De(T,{historyMode:O,environment:j.env,rootName:N}),H=s(T)?.files,M=$t(L.manifest);return{changedFiles:H?[...new Set([...Object.keys(H),...M.keys()])].filter((D)=>H[D]!==M.get(D)).length:null,files:L.manifest.totals.files,manifestSha256:L.manifestSha256,changed:F?L.manifestSha256!==F:null,blocking:L.blocking,error:null}}catch(L){return{changedFiles:null,files:null,manifestSha256:null,changed:null,blocking:[],error:Wi(L)}}}var fs={name:"status",summary:"Show the workspace, folder binding, and local-vs-cloud drift",usage:["Usage: hlix status [--cwd <dir>] [--json]","","Reports the resolved workspace and API with the source that decided each,","whether this folder is bound to a project, and whether the working tree or","the cloud head has moved since the last sync. Every finding is a line in","the output, so the command itself always exits 0; only an argument error","(rejected before it runs) exits 2."].join(`
|
|
357
|
+
`),supportsJson:!0,async run(j){let T=r({env:j.env,flags:j.flags,cwd:j.cwd}),O=T.binding,N=O?s(O.root):null,F=O?await x(j,O.root,N?.snapshotOnly?"sanitize":N?.historyMode??"preserve",N?.rootName,N?.manifestSha256):null,L=null;if(O?.config.projectId&&T.credential&&!T.conflict)try{let D=j.requireClient(),J=await D.projects.get(O.config.projectId),B=N?.repoId??J.repos.find((Y)=>Y.isPrimary)?.id??J.repos[0]?.id;if(!B)throw Error("Select a primary HLIX Repos");let W=await D.repos.head(O.config.projectId,B);L={commitSha:W.commitSha,changed:N?W.commitSha!==N.commitSha:null,error:null,errorMessage:null}}catch(D){L={commitSha:"",changed:null,error:yr(D).code,errorMessage:D instanceof nt?"no HLIX Repos commit yet — `hlix push` publishes this folder":Wi(D)}}let H=Cr(j.env),M={cwd:j.cwd,workspace:{id:T.workspaceId,source:T.workspaceSource},api:{baseUrl:T.baseUrl,source:T.baseUrlSource},credential:{present:T.credential!==null,source:T.credentialSource,path:T.credentialPath},conflict:T.conflict,project:O?{root:O.root,projectId:O.config.projectId??null,workspaceId:O.config.workspaceId,apiUrl:O.config.apiUrl}:null,repository:N?{repoId:N.repoId,commitSha:N.commitSha}:null,local:F,cloud:L,install:{channel:H.running?.channel??null,path:H.running?.path??null,copies:H.copies.map(({path:D,channel:J})=>({path:D,channel:J})),duplicate:H.duplicate}};if(j.json)return j.stdout(re(oe(fs.name,M))),0;let U=[["folder",j.cwd],["workspace",T.workspaceId?`${T.workspaceId} (from ${T.workspaceSource})`:"none — run `hlix auth login --workspace <id>`"],["api",`${T.baseUrl} (from ${T.baseUrlSource})`],["credential",p(T)??"none — run `hlix auth login`"],["project",O?O.config.projectId??`initialized at ${O.root}, not imported yet`:"none — run `hlix import .` to bind this folder"]];if(N)U.push(["HLIX Repos",N.commitSha]);if(F){if(U.push(["local",F.error?`could not scan: ${F.error}`:F.changed===null?`${F.files} files, no synced base commit`:F.changed?`${F.files} files, modified since the last sync`:`${F.files} files, matches the last sync`]),F.blocking.length>0)U.push(["blocking",F.blocking.join("; ")])}if(L)U.push(["cloud",L.error==="not_found"?Gi(L.errorMessage??L.error):L.error?`not checked — ${Gi(L.errorMessage??L.error)}`:L.changed?`commit ${L.commitSha} available — run \`hlix pull\``:`commit ${L.commitSha}, up to date`]);if(T.conflict)U.push(["conflict",T.conflict]);if(H.running)U.push(["installed",$n(H.running)]);if(H.duplicate)U.push(["duplicate",H.duplicate]);return j.stdout(`${ke(U)}
|
|
358
|
+
`),0}};import{spawnSync as zi}from"node:child_process";var gs={name:"terminal",summary:"Open a shell into the project's Coding Workspace",usage:["Usage: hlix terminal [project-id] [--print] [--web] [--json]","","With no id, the project this folder is bound to is used."," --print Show the ssh command and browser url instead of connecting"," --web Open the browser terminal instead of ssh"].join(`
|
|
359
|
+
`),supportsJson:!0,options:["print","web"],args:{min:0,max:1},async run(j){let T=j.args[0]??t(j.cwd)?.config.projectId;if(!T)throw new e("missing_argument","A project id is required, or run this inside a folder bound to a project.");let O=await j.requireClient().projects.terminal(T);if(j.json)return j.stdout(re(oe(gs.name,O))),O.available?0:1;if(!O.available){let H=O.environmentState?` (environment: ${O.environmentState})`:"";throw new e("not_found",`${O.reason??"Terminal unavailable"}${H}`)}let N=j.flags.print===!0,F=j.flags.web===!0;if(N||F&&!O.webTerminalUrl||!F&&!O.sshCommand)return j.stdout(`${ke([["ssh",O.sshCommand??"not available"],["browser",O.webTerminalUrl??"not available"]])}
|
|
360
|
+
`),0;if(F){if(zi(process.platform==="darwin"?"open":"xdg-open",[O.webTerminalUrl],{stdio:"ignore"}).status!==0)j.stdout(`${O.webTerminalUrl}
|
|
361
|
+
`);return 0}return zi("sh",["-c",O.sshCommand],{stdio:"inherit"}).status??1}};import{rmSync as Ki}from"node:fs";import{dirname as Vp}from"node:path";var hs={name:"uninstall",summary:"Remove this hlix if the installer put it here (keeps your login)",usage:["Usage: hlix uninstall [--yes] [--json]","","Removes the executable the one-line installer installed, and its notices.","Your login in ~/.config/hlix is kept. A copy installed with Homebrew or npm","is removed with that tool instead; this command names it."].join(`
|
|
362
|
+
`),supportsJson:!0,options:["yes"],async run(j){let T=$r(j.env);if(!T||T.channel!=="installer")throw new e("invalid_request",T&&T.channel!=="unknown"?`This hlix was installed with ${T.channel==="homebrew"?"Homebrew":"npm"}. Remove it with: ${_r(T)}`:"Only an hlix installed by the one-line installer can remove itself.");if(j.flags.yes!==!0){if(j.json||!j.confirm)throw new e("approval_required","Removing hlix needs approval. Repeat with `--yes`.");if(!await j.confirm(`Remove ${T.path}? Your login is kept.`))throw new e("cancelled","Uninstall cancelled.")}let O=Pr(j.env);Ki(T.path,{force:!0}),Ki(O,{recursive:!0,force:!0});let N=Vp(Me(j.env));if(j.json)j.stdout(re(oe(hs.name,{removed:[T.path,O],kept:N})));else j.stdout(`Removed ${T.path}
|
|
363
|
+
Your login in ${N} is kept.
|
|
364
|
+
`);return 0}};function S(j){return[...j.pulled?[`HLIX Repos: pulled ${j.pulled}`]:[],...j.pushed?[`HLIX Repos: pushed ${j.pushed}`]:[]]}async function k(j,T,O){let N=!1;while(!O.signal?.aborted){try{let F=await ps(j,T.client,T.env);if(O.onReport({conflicts:[],...F.action==="push"?{pushed:F.commitSha}:F.action==="pull"?{pulled:F.commitSha}:{}}),!N)N=!0,O.onCaughtUp?.()}catch(F){O.onError(F)}await Kt(15000,O.signal)}}var qi={name:"mirror",summary:"Follow HLIX Repos using Git",usage:"Usage: hlix mirror [--json]",supportsJson:!0,options:[],agentTool:!1,async run(j){let{root:T}=await _t(j.cwd);return await k(T,{client:j.requireClient(),env:j.env},{signal:j.signal,onReport:(O)=>{if(j.json)j.stdout(re(oe("hlix mirror",O)));else for(let N of S(O))j.stdout(`${N}
|
|
365
|
+
`)},onError:(O)=>j.stderr(`${O instanceof Error?O.message:String(O)}
|
|
366
|
+
`)}),0}};import{lstat as ws,readFile as Xp,realpath as Yp}from"node:fs/promises";import{basename as ys,dirname as Zp,extname as Qp,join as Bn,parse as Vi,resolve as Gn}from"node:path";function Ct(j,T){let O=j.flags[T];return typeof O==="string"&&O.trim()?O.trim():void 0}function vs(j){let T=Ct(j,"project");if(T)return{root:j.cwd,projectId:T};return ed(j.cwd)}function ed(j){let T=t(j);if(!T?.config.projectId)throw new e("not_initialized","This folder is not bound to an Hlix project. Run `hlix import .` first.");return{root:T.root,projectId:T.config.projectId}}async function bs(j,T){let O=await ws(j);if(O.isSymbolicLink()||!O.isFile())throw Error(`Refusing to import a non-regular file: ${j}`);if(O.size>T)throw Error(`Import file exceeds ${T} bytes: ${j}`);return{path:await Yp(j),content:await Xp(j,"utf8")}}function ks(j,T,O,N){if(j.json)j.stdout(re(oe(T,O)));else j.stdout(`${N}
|
|
367
|
+
`)}function td(j){let T=/^---\r?\n([\s\S]*?)\r?\n---/.exec(j)?.[1];return(T?/^name:\s*(.+?)\s*$/m.exec(T)?.[1]:void 0)?.replace(/^["']|["']$/g,"").trim()||void 0}var nd=[Bn(".claude","skills"),Bn(".agents","skills"),Bn(".hlix","skills")];async function rd(j,T){let O=[Gn(j,T),...nd.map((N)=>Gn(j,N,T))];for(let N of O)if(await ws(N).then(()=>!0,()=>!1))return N;throw new e("not_found",`No skill at ${T}. Pass the SKILL.md or its folder, for example .claude/skills/${T}.`)}var Ss={name:"skill import",summary:"Activate a local skill for the bound cloud project",usage:"Usage: hlix skill import <SKILL.md|folder> [--name <slug>] [--project <id>] [--json]",supportsJson:!0,options:["name","project"],args:{min:1,max:1},async run(j){if(j.args.length!==1)throw Error("skill import requires one file or folder.");let T=vs(j),O=await rd(j.cwd,j.args[0]),N=await ws(O);if(N.isSymbolicLink())throw Error(`Refusing to import a symlink: ${O}`);let F=N.isDirectory()?Bn(O,"SKILL.md"):O,L=await bs(F,200000),H=N.isDirectory()?ys(O):ys(F)==="SKILL.md"?ys(Zp(F)):Vi(F).name,M=Ct(j,"name")??H;if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(M))throw Error("Skill name must be a lowercase kebab-case slug.");let U=await j.requireClient().resources.importSkill(T.projectId,{slug:M,content:L.content});return ks(j,Ss.name,U.skill,`Imported skill ${M}`),0}},js={name:"agent import",summary:"Create a project-scoped agent from a local Markdown brief",usage:"Usage: hlix agent import <markdown-file> [--name <name>] [--runtime <runtime>] [--duty <duty>] [--profile <profile>] [--project <id>] [--json]",supportsJson:!0,options:["name","runtime","duty","profile","project"],args:{min:1,max:1},async run(j){if(j.args.length!==1)throw Error("agent import requires one Markdown file.");let T=vs(j),O=Gn(j.cwd,j.args[0]);if(![".md",".mdx"].includes(Qp(O).toLowerCase()))throw Error("Agent imports must be Markdown files.");let N=await bs(O,20000),F=Ct(j,"runtime")??m;if(!o.includes(F)){let U=new Intl.ListFormat("en",{type:"disjunction"}).format(o);throw Error(`--runtime must be ${U}.`)}let L=Ct(j,"duty")??"executor";if(L!=="executor"&&L!=="intake")throw Error("--duty must be executor or intake.");let H=Ct(j,"name")??td(N.content)??Vi(O).name.replace(/[-_]+/g," "),M=await j.requireClient().resources.importAgent(T.projectId,{name:H,instructions:N.content,runtimeKind:F,duty:L});return ks(j,js.name,M.agent,M.agent.duty==="intake"?`Imported agent ${M.agent.name} as this project's intake agent`:`Imported agent ${M.agent.name}`),0}},Es={name:"mcp import",summary:"Explicitly activate one validated local MCP server",usage:"Usage: hlix mcp import <.mcp.json> [--server <name>] [--allow-stdio] [--project <id>] [--json]",supportsJson:!0,options:["server","allow-stdio","project"],args:{min:1,max:1},async run(j){if(j.args.length!==1)throw Error("mcp import requires one MCP JSON file.");let T=vs(j),O=await bs(Gn(j.cwd,j.args[0]),200000),N;try{N=JSON.parse(O.content)}catch{throw Error("MCP config is not valid JSON.")}let F=Object.entries(N.mcpServers??{});if(F.length===0)throw Error("MCP config contains no servers.");let L=Ct(j,"server");if(!L&&F.length>1)throw Error("MCP config contains multiple servers; select one with --server <name>.");let H=L?F.find(([X])=>X===L):F[0];if(!H)throw Error(`MCP server not found: ${L}`);let[M,U]=H,D=U.type==="http"||U.type==="sse"?U.type:typeof U.command==="string"?"stdio":typeof U.url==="string"?"http":null;if(!D)throw Error(`MCP server ${M} has no supported transport.`);if(D==="stdio"&&j.flags["allow-stdio"]!==!0)throw Error("Stdio MCP servers execute a local command in the cloud; repeat with --allow-stdio.");let J=U.env&&typeof U.env==="object"&&!Array.isArray(U.env)?U.env:{},B=U.headers&&typeof U.headers==="object"&&!Array.isArray(U.headers)?U.headers:{};if(Object.values(B).some((X)=>typeof X!=="string"))throw Error(`MCP server ${M} headers must be strings.`);for(let[X,V]of Object.entries(J)){if(typeof V!=="string")continue;let Q=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(V)?.[1];if(Q&&Q!==X)throw new e("invalid_usage",`MCP server ${M}: env ${X} references \${${Q}}, but a placeholder must be the variable's own name — write "${X}": "\${${X}}" and store the secret as ${X}.`)}let W=Object.values(B).flatMap((X)=>[...X.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((V)=>V[1]));if(Object.keys(B).length>0&&W.length===0)throw Error("MCP remote headers must use ${KEY} placeholders; literal credentials are refused.");let Y=/^(?:(?:Bearer|Basic|Token) )?\$\{[A-Za-z_][A-Za-z0-9_]*\}$/i;if(Object.values(B).some((X)=>!Y.test(X)))throw Error("MCP remote headers must be ${KEY} or an approved auth scheme followed by ${KEY}.");let ee=await j.requireClient().resources.importMcp(T.projectId,{name:M,transport:D,...typeof U.command==="string"?{command:U.command}:{},...Array.isArray(U.args)&&U.args.every((X)=>typeof X==="string")?{args:U.args}:{},...typeof U.url==="string"?{url:U.url}:{},...Object.keys(B).length>0?{headers:B}:{},envKeys:[...new Set([...Object.keys(J),...W])].sort()});return ks(j,Es.name,ee.mcpServer,`Imported MCP server ${M}`),0}};import{spawnSync as sd}from"node:child_process";import{chmod as od,realpath as id,writeFile as ad}from"node:fs/promises";import{basename as cd,dirname as ld,relative as pd,resolve as Yi,sep as dd}from"node:path";var Xi=64;function dn(j){let T=t(j.cwd),N=(typeof j.flags.project==="string"?j.flags.project:void 0)??T?.config.projectId;if(!N)throw new e("not_initialized","This folder is not bound to a Hlix project. Run `hlix import .`, or pass --project <id>.");return{projectId:N,root:T?.root??j.cwd}}var pn=(j,T)=>typeof j[T]==="string"?j[T]:void 0,xs={name:"secrets list",summary:"Show every secret the project holds, masked, with its source file",usage:["Usage: hlix secrets list [--project <id>] [--json]","","One row per (key, source file). Values are masked to their last four","characters and there is no flag that unmasks them — `hlix secrets export`","is the one command that returns plaintext, and it is audited."].join(`
|
|
368
|
+
`),supportsJson:!0,options:["project"],async run(j){let{projectId:T}=dn(j),O=await j.requireClient().secrets.listEntries(T);if(j.json)return j.stdout(re(oe(xs.name,O))),0;if(O.entries.length===0)j.stdout(`No secrets stored for this project.
|
|
369
|
+
`);else j.stdout(`${Je(["key","source","format","value","updated"],O.entries.map((N)=>[N.key,N.source,N.format||"-",N.maskedValue,N.updatedAt?.slice(0,10)??"-"]))}
|
|
370
|
+
`);for(let N of O.warnings)j.stderr(`warning: ${N}
|
|
371
|
+
`);return 0}},Ps={name:"secrets set",summary:"Create or replace one secret in the store",usage:["Usage: hlix secrets set <KEY> [value] [--from-stdin] [--source <file>] [--project <id>] [--json]",""," --from-stdin Read the value from stdin instead of the argument, so it"," never reaches shell history or `ps`. Use this for real"," credentials: `pbpaste | hlix secrets set API_KEY --from-stdin`."," --source The file the value belongs to, e.g. apps/api/.env.local."," Omitted means the project root .env.","","Exactly one trailing newline is stripped from stdin, so a piped value does","not acquire the shell's."].join(`
|
|
372
|
+
`),supportsJson:!0,options:["from-stdin","source","project"],args:{min:1,max:2},async run(j){let{projectId:T}=dn(j),O=j.args[0],N=j.flags["from-stdin"]===!0;if(N&&j.args.length>1)throw new e("invalid_usage","Pass the value as an argument or with --from-stdin, not both.");if(!N&&j.args.length<2)throw new e("missing_argument","A value is required. Pass it as an argument, or pipe it with --from-stdin.");let F;if(N){if(!j.readStdin)throw new e("invalid_usage","--from-stdin is not available in this context.");F=(await j.readStdin()).replace(/\r?\n$/,"")}else F=j.args[1];let L=pn(j.flags,"source"),H=await j.requireClient().secrets.upsertEntries(T,{entries:[{key:O,value:F,...L?{source:L}:{}}]});if(j.json)return j.stdout(re(oe(Ps.name,H))),H.written>0?0:1;if(H.written===0)throw new e("bad_request",`The store refused ${O}: --source must be a project-relative file path.`);return j.stdout(`${ke([["key",O],["source",L??".env"]])}
|
|
373
|
+
`),0}},$s={name:"secrets delete",summary:"Remove one secret from the store",usage:["Usage: hlix secrets delete <KEY> [--source <file>] [--project <id>] [--json]","","Without --source the key is removed from EVERY file that declares it,",'which is what "delete this secret" usually means. Removing nothing exits 1.'].join(`
|
|
374
|
+
`),supportsJson:!0,options:["source","project"],args:{min:1,max:1},async run(j){let{projectId:T}=dn(j),O=j.args[0],N=pn(j.flags,"source"),F=await j.requireClient().secrets.deleteEntry(T,O,N);if(j.json)return j.stdout(re(oe($s.name,F))),F.removed>0?0:1;if(F.removed===0)return j.stderr(`No stored secret named ${O}${N?` in ${N}`:""}.
|
|
375
|
+
`),1;return j.stdout(`Removed ${F.removed} entr${F.removed===1?"y":"ies"} for ${O}.
|
|
376
|
+
`),0}},Wn={name:"secrets import",summary:"Load this folder's secret files into the project secrets store",usage:["Usage: hlix secrets import [file...] [--project <id>] [--json]","","With no arguments, every secret file the project scanner detects. Naming","files narrows it to those; a named file the scanner does not consider a","secret is refused rather than uploaded.","","The files are uploaded as bytes and the server parses them, so every shape","it knows lands here: dotenv and .envrc, Terraform variables, Java","properties, Spring YAML, .NET appsettings, Azure Functions local settings,","npm credentials, Rails database.yml, wrangler/fly TOML and Serverless all","become readable entries under their own path. An opaque credential (a","private key, a keystore, a service-account JSON) is kept byte-exact","instead. A file whose plaintext this platform does not hold — SOPS,","Ansible Vault, git-crypt — and a .env.example are reported as skipped.","","A file that holds key/value pairs REPLACES what the store held for that","path: the file on this machine is the truth."].join(`
|
|
377
|
+
`),supportsJson:!0,options:["project"],args:{min:0,max:64},async run(j){let{projectId:T,root:O}=dn(j),N=await De(O,{historyMode:"preserve",environment:j.env}),F=N.blocking.filter((B)=>!B.startsWith(ns));if(F.length>0)throw new e("scan_blocked",`Project scan blocked the import:
|
|
378
|
+
- ${F.join(`
|
|
379
|
+
- `)}`);let L=N.protectedFiles.filter((B)=>B.kind==="dotenv"||B.kind==="credential"),H=await id(j.cwd),M=j.args.map((B)=>pd(N.root,Yi(H,B)).split(dd).join("/")),U=M.filter((B)=>!L.some((W)=>W.path===B));if(U.length>0)throw new e("invalid_usage",`Not a secret file in this project: ${U.join(", ")}`);let D=M.length>0?L.filter((B)=>M.includes(B.path)):L;if(D.length===0)return j.stdout(j.json?re(oe(Wn.name,{imported:[],skipped:[],warnings:[],written:0,rejected:[]})):`No secret files found in this project.
|
|
380
|
+
`),0;if(D.length>Xi)throw new e("invalid_usage",`${D.length} secret files exceeds the ${Xi} the store accepts in one request. Name the files to import, a batch at a time.`);let J=await j.requireClient().secrets.importFiles(T,D.map((B)=>({path:B.path,contentBase64:B.contentBase64})));if(j.json)return j.stdout(re(oe(Wn.name,J))),0;if(J.imported.length>0)j.stdout(`${Je(["source","format","stored"],J.imported.map((B)=>[B.path,B.format||"-",B.kind==="file"?"as file":`${B.entries} entr${B.entries===1?"y":"ies"}`]))}
|
|
381
|
+
`);if(j.stdout(`${J.written} value${J.written===1?"":"s"} stored.
|
|
382
|
+
`),J.imported.some((B)=>B.kind!=="file"))j.stdout(`Each imported file replaced what the store held under its path; keys the file no longer has are gone.
|
|
383
|
+
`);for(let B of J.skipped)j.stderr(`skipped ${B.path}: ${B.reason}
|
|
384
|
+
`);for(let B of J.warnings)j.stderr(`warning: ${B}
|
|
385
|
+
`);for(let B of J.rejected)j.stderr(`rejected ${B}: the store refused its source path
|
|
386
|
+
`);return 0}};function ud(j){return sd("git",["-C",ld(j),"ls-files","--error-unmatch","--",cd(j)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).status===0}var _s={name:"secrets export",summary:"Render one source file back out of the store, values in clear",usage:["Usage: hlix secrets export [--source <file>] [--format <id>] [--out <path>] [--project <id>] [--json]",""," --source Which stored file to render. Omitted means the root .env."," --format Re-render it as a different shape (dotenv, tfvars, …)."," Omitted means the shape the values were parsed as."," --out Write it to this path, mode 0600, instead of stdout. A path"," git TRACKS is refused: an exported file carries plaintext and"," must not become a commit.","","This is the one command that returns secret values, and the server writes","an audit row for every call."].join(`
|
|
387
|
+
`),supportsJson:!0,options:["source","format","out","project"],async run(j){let{projectId:T}=dn(j),O=pn(j.flags,"source"),N=pn(j.flags,"format"),F=pn(j.flags,"out"),L=F===void 0?void 0:Yi(j.cwd,F);if(L!==void 0&&ud(L))throw new e("invalid_usage",`Refusing to overwrite a git-tracked file with secret values: ${L}`);let H=await j.requireClient().secrets.exportEntries(T,{...O?{source:O}:{},...N?{format:N}:{}});if(L!==void 0)await ad(L,H,{mode:384}),await od(L,384);if(j.json)return j.stdout(re(oe(_s.name,{source:O??null,format:N??null,out:L??null,bytes:Buffer.byteLength(H),...L===void 0?{content:H}:{}}))),0;if(L===void 0)j.stdout(H);else j.stdout(`${ke([["wrote",L],["mode","0600"],["bytes",String(Buffer.byteLength(H))]])}
|
|
388
|
+
`);return 0}};function Is(j){let T=j.flags.project;if(typeof T==="string"&&T)return T;return t(j.cwd)?.config.projectId??void 0}function Cs(j,T){let O=j[T];if(typeof O!=="string"||O.trim()==="")throw new e("missing_argument",`--${T} is required.`);return O}var Rs={name:"cycles create",summary:"Propose a cycle, which starts the project working on it",usage:["Usage: hlix cycles create <project-id> --title <t> --description <d> [--json]","","This is the command that DISPATCHES work. The proposal enters the project's","own loop, which plans the cycle, creates its tasks and starts the coders —","using the project's harness (see `hlix harness get`).","","`adopted` is true when the loop took it on this call, false when it was","recorded and will be planned on the next pass. Neither is an error. The API","returns no cycle id: the roadmap owns cycles, so find it with `hlix tasks","list --project <id>` once planning has run."].join(`
|
|
389
|
+
`),supportsJson:!0,options:["title","description"],args:{min:1,max:1},async run(j){let T=j.args[0],O=Cs(j.flags,"title"),N=Cs(j.flags,"description"),F=await j.requireClient().cycles.propose({projectId:T,title:O,description:N});if(j.json)return j.stdout(re(oe(Rs.name,F))),0;return j.stdout(`${ke([["project",T],["title",O],["status",F.adopted?"adopted — the project is planning it now":"recorded — it will be planned on the next pass"]])}
|
|
390
|
+
`),0}},Ts={name:"tasks create",summary:"Add a task to a project's board",usage:["Usage: hlix tasks create <project-id> --description <d> [--title <t>] [--json]","","Creates the task row. It does NOT start it: standalone task execution is","not implemented server-side and answers 501 by design. Work is dispatched","by its cycle — use `hlix cycles create` for that."].join(`
|
|
391
|
+
`),supportsJson:!0,options:["title","description"],args:{min:1,max:1},async run(j){let T=j.args[0],O=Cs(j.flags,"description"),N=typeof j.flags.title==="string"?j.flags.title:void 0,F=await j.requireClient().tasks.create({projectId:T,description:O,...N?{title:N}:{}});if(j.json)return j.stdout(re(oe(Ts.name,F))),0;return j.stdout(`${ke([["task",F.id],["project",T],["status",F.status??"queued"],["note","not started — dispatch with `hlix cycles create`"]])}
|
|
392
|
+
`),0}},As={name:"harness get",summary:"Show which coder runs, and which setting chose it",usage:["Usage: hlix harness get [project-id] [--project <id>] [--json]","","With a project id — or from a bound folder — what that project would run.","Otherwise the workspace-wide answer. `source` names the setting that","decided: a project preference, the workspace preference, or the system","default."].join(`
|
|
393
|
+
`),supportsJson:!0,options:["project"],args:{min:0,max:1},async run(j){let T=j.args[0]??Is(j),O=j.requireClient(),N=T?await O.modelConfig.resolvedProjectHarness(T):await O.modelConfig.resolvedHarness();if(j.json)return j.stdout(re(oe(As.name,N))),0;return j.stdout(`${ke([["scope",T?`project ${T}`:"workspace"],["harness",N.harness],["source",N.source]])}
|
|
394
|
+
`),0}},Os={name:"harness set",summary:"Choose the coder a project or the workspace runs",usage:[`Usage: hlix harness set <${o.join("|")}> [project-id] [--org] [--json]`,"","With a project id, sets that project's preference. With --org, the","workspace-wide one that projects fall back to. This is a PERSISTENT server","setting that every future run on that scope uses, and it is audited.","","It is not the same thing as the local `harness` config key, which only","picks the coder Hlix Code spawns on this machine."].join(`
|
|
395
|
+
`),supportsJson:!0,options:["org"],args:{min:1,max:2},async run(j){let T=j.args[0];if(!o.includes(T))throw new e("invalid_usage",`harness must be one of ${o.join(", ")}; got "${T}".`);let O=j.flags.org===!0,N=j.args[1]??(O?void 0:Is(j));if(N&&O)throw new e("invalid_usage","Name a project or pass --org, not both: they are different scopes.");if(!N&&!O)throw new e("invalid_usage","Name the project to set, or pass --org for the whole workspace.");let F=j.requireClient(),L=N?await F.modelConfig.setProjectHarness(N,T):await F.modelConfig.setHarness(T);if(j.json)return j.stdout(re(oe(Os.name,L))),0;return j.stdout(`${ke([["scope",N?`project ${N}`:"workspace"],["harness",T]])}
|
|
396
|
+
`),0}},Ns={name:"harness clear",summary:"Remove a harness preference so the scope below it decides",usage:["Usage: hlix harness clear [project-id] [--org] [--json]","","With a project id, drops that project's preference so it inherits the","workspace's answer (or the system default). With --org, drops the","workspace-wide one. Audited, like every write on this setting.","","Answers `not_found` when that scope had no preference to clear — the","setting is already off, and saying so beats reporting a change that was","never made. Check the result with `hlix harness get`."].join(`
|
|
397
|
+
`),supportsJson:!0,options:["org"],args:{min:0,max:1},async run(j){let T=j.flags.org===!0,O=j.args[0]??(T?void 0:Is(j));if(O&&T)throw new e("invalid_usage","Name a project or pass --org, not both: they are different scopes.");if(!O&&!T)throw new e("invalid_usage","Name the project to clear, or pass --org for the whole workspace.");let N=j.requireClient(),F=O?await N.modelConfig.clearProjectHarness(O):await N.modelConfig.clearHarness();if(j.json)return j.stdout(re(oe(Ns.name,F))),0;return j.stdout(`${ke([["scope",O?`project ${O}`:"workspace"],["harness","cleared — the scope below decides now"]])}
|
|
398
|
+
`),0}};var d=[Ir,Rr,Et,fs,hs,gs,ms,us,Tr,Ar,Or,ss,Bi,Ji,Di,Ui,qi,Ss,js,Es,xs,Ps,$s,Wn,_s,Nr,Fr,Lr,Mr,Ur,Dr,Jr,Ts,Rs,As,Os,Ns];
|
|
399
|
+
export{e,R,s,p,t,r,n,a,u,c,o,m,g,v,h,l,i,E,f,y,_,w,b,I,A,C,P,x,S,k,d};
|