@hlix/cli 1.0.0 → 1.0.2

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