@hlix/cli 0.5.5 → 0.5.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/index-8g4x8tv8.js +213 -0
- package/dist/index.js +2 -2
- package/dist/main-g9zc6npj.js +67 -0
- package/dist/{package-3gbcdmyy.js → package-q1pwa5fr.js} +1 -1
- package/package.json +1 -1
- package/skills/hlix/SKILL.md +10 -0
- package/dist/index-cadye5bs.js +0 -209
- package/dist/main-a2ajghxb.js +0 -63
package/README.md
CHANGED
|
@@ -44,8 +44,8 @@ For CI, and for anything else that must not change underneath you, pin the
|
|
|
44
44
|
version instead of floating to `latest`:
|
|
45
45
|
|
|
46
46
|
```bash
|
|
47
|
-
npm install --global @hlix/cli@0.5.
|
|
48
|
-
npx @hlix/cli@0.5.
|
|
47
|
+
npm install --global @hlix/cli@0.5.6
|
|
48
|
+
npx @hlix/cli@0.5.6 status --json
|
|
49
49
|
```
|
|
50
50
|
|
|
51
51
|
## Authenticate
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
class e extends Error{code;details;constructor(j,E,P){super(E);if(this.name="CliError",this.code=j,P!==void 0)this.details=P}}var k=1,q=(j,E)=>({schemaVersion:1,command:j,data:E}),tt=(j,E)=>({schemaVersion:1,command:j,error:E});function J(j){return`${JSON.stringify(j,null,2)}
|
|
3
|
+
`}function se(j){let E=Math.max(0,...j.map(([P])=>P.length));return j.map(([P,C])=>`${P.padEnd(E)} ${C}`).join(`
|
|
4
|
+
`)}function ve(j,E){let P=j.map((R,I)=>Math.max(R.length,...E.map((_)=>(_[I]??"").length))),C=(R)=>R.map((I,_)=>I.padEnd(P[_])).join(" ").trimEnd();return[C(j),C(P.map((R)=>"-".repeat(R))),...E.map(C)].join(`
|
|
5
|
+
`)}import{statSync as zo}from"node:fs";import{dirname as Ko,resolve as Jo}from"node:path";import{closeSync as mn,constants as nt,existsSync as Ft,fsyncSync as Jr,lstatSync as fn,mkdirSync as _o,openSync as Gr,readFileSync as qr,renameSync as To,statSync as Wr,unlinkSync as Vr,writeFileSync as Oo}from"node:fs";import{homedir as Ao}from"node:os";import{dirname as Fo,join as gn}from"node:path";function He(j=process.env){let E=j.HLIX_CONFIG_HOME??j.XDG_CONFIG_HOME??gn(Ao(),".config");return gn(E,"hlix","credentials.json")}function Xr(j=process.env){let E=j.HLIX_API_KEY;if(!E&&j.HLIX_SESSION_TOKEN)return{baseUrl:j.HLIX_BASE_URL??"https://server.hlix.ai",apiKey:"",sessionToken:j.HLIX_SESSION_TOKEN,...j.HLIX_WORKSPACE_ID?{organizationId:j.HLIX_WORKSPACE_ID}:{}};if(E)return{baseUrl:j.HLIX_BASE_URL??"https://server.hlix.ai",apiKey:E,...j.HLIX_WORKSPACE_ID?{organizationId:j.HLIX_WORKSPACE_ID}:{}};try{let P=JSON.parse(qr(He(j),"utf8"));return P.apiKey&&P.baseUrl?P:null}catch{return null}}function Yr(j=process.env){let E=He(j);return Ft(E)?E:null}function hn(j=process.env){let E=He(j);if(!Ft(E))return{path:E,removed:!1,reason:"absent"};let P=fn(E);if(P.isSymbolicLink()||!P.isFile())throw Error("Refusing to remove a credential path that is not a regular file.");let C=process.getuid?.();if(C!==void 0&&Wr(E).uid!==C)throw Error("Refusing to remove a credential file owned by another user.");let R;try{R=JSON.parse(qr(E,"utf8"))}catch{R=null}let I=R;if(!I||typeof I.apiKey!=="string"||typeof I.baseUrl!=="string")throw Error(`Refusing to remove ${E}: it is not a credential written by this CLI.`);return Vr(E),{path:E,removed:!0,reason:"removed"}}function Zr(j,E=process.env){let P=He(E),C=Fo(P);if(_o(C,{recursive:!0,mode:448}),fn(C).isSymbolicLink())throw Error("Refusing to write credentials through a symlinked directory.");if(Ft(P)){let _=fn(P);if(_.isSymbolicLink()||!_.isFile())throw Error("Refusing to replace a credential path that is not a regular file.");let O=process.getuid?.();if(O!==void 0&&Wr(P).uid!==O)throw Error("Refusing to replace a credential file owned by another user.")}let R=gn(C,`.credentials.${process.pid}.${crypto.randomUUID()}.tmp`),I;try{I=Gr(R,nt.O_WRONLY|nt.O_CREAT|nt.O_EXCL|nt.O_NOFOLLOW,384),Oo(I,`${JSON.stringify(j,null,2)}
|
|
6
|
+
`,"utf8"),Jr(I),mn(I),I=void 0,To(R,P);let _=Gr(C,nt.O_RDONLY);try{try{Jr(_)}catch(O){let T=O.code;if(T!=="EINVAL"&&T!=="ENOTSUP")throw O}}finally{mn(_)}}catch(_){if(I!==void 0)mn(I);if(Ft(R))Vr(R);throw _}return P}import{constants as Nt,existsSync as Ht,lstatSync as es,mkdirSync as No,openSync as Ho,closeSync as Qr,fsyncSync as Lo,readFileSync as ts,renameSync as Mo,unlinkSync as Uo,writeFileSync as yn}from"node:fs";import{dirname as Bo,join as rt,resolve as Lt}from"node:path";function Do(j){if(!Ht(j))return;let E=es(j);if(E.isSymbolicLink()||!E.isFile())throw Error(`Refusing to replace a non-regular Hlix file: ${j}`)}function st(j,E){let P=Bo(j);if(No(P,{recursive:!0,mode:448}),es(P).isSymbolicLink())throw Error(`Refusing to write through a symlinked Hlix directory: ${P}`);Do(j);let C=rt(P,`.hlix-${process.pid}-${crypto.randomUUID()}.tmp`),R;try{R=Ho(C,Nt.O_WRONLY|Nt.O_CREAT|Nt.O_EXCL|Nt.O_NOFOLLOW,384),yn(R,`${JSON.stringify(E,null,2)}
|
|
7
|
+
`,"utf8"),Lo(R),Qr(R),R=void 0,Mo(C,j)}catch(I){if(R!==void 0)Qr(R);if(Ht(C))Uo(C);throw I}}function ot(j){return rt(Lt(j),".hlix","config.json")}function ns(j){return rt(Lt(j),".hlix","state.json")}function Le(j){try{let E=JSON.parse(ts(ot(j),"utf8"));return E.schemaVersion===1&&E.workspaceId&&E.apiUrl?E:null}catch{return null}}function it(j,E){st(ot(j),E);let P=rt(Lt(j),".hlix",".gitignore");if(!Ht(P))yn(P,`state.json
|
|
8
|
+
`,{mode:420,flag:"wx"});let C=rt(Lt(j),".hlixignore");if(!Ht(C))yn(C,`# Additional project-local paths to exclude from Hlix snapshots.
|
|
9
|
+
`,{mode:420,flag:"wx"})}function at(j,E){st(ns(j),E)}function Mt(j){try{let E=JSON.parse(ts(ns(j),"utf8"));return E.schemaVersion===1&&E.revisionId&&E.generation>0?E:null}catch{return null}}var wn="https://server.hlix.ai";function Bt(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 E=Jo(j);for(;;){let P=Le(E);if(P)return{root:E,config:P};let C=Ko(E);if(C===E)return null;E=C}}function ss(j){try{return zo(j).isDirectory()}catch{return!1}}function Ut(j){if(typeof j!=="string")return;let E=j.trim();return E?E:void 0}var rs=(j,E)=>j.replace(/\/+$/,"")===E.replace(/\/+$/,"");function n(j){let{env:E,flags:P,cwd:C}=j,R=t(C),I=Xr(E),_=I?E.HLIX_API_KEY?"env":E.HLIX_SESSION_TOKEN?"session":"file":null,O=_==="file"?I:null,T=Ut(P["base-url"]),A=Ut(E.HLIX_BASE_URL),N=Ut(P.workspace),F=Ut(E.HLIX_WORKSPACE_ID),M=T??A??R?.config.apiUrl??O?.baseUrl??wn,G=T?"flag":A?"env":R?.config.apiUrl?"project":O?.baseUrl?"credential":"default",U=N??F??R?.config.workspaceId??O?.organizationId??null,H=N?"flag":F?"env":R?.config.workspaceId?"project":O?.organizationId?"credential":null;return{baseUrl:M,baseUrlSource:G,workspaceId:U,workspaceSource:H,credential:I,credentialSource:_,credentialPath:He(E),binding:R,conflict:Go(R,{flagBaseUrl:T,envBaseUrl:A,flagWorkspace:N,envWorkspace:F})}}function Go(j,E){if(!j)return null;let P=`${j.root} is bound to`,C="Drop the override, or point --cwd at a folder bound to it.";if(E.flagWorkspace&&E.flagWorkspace!==j.config.workspaceId)return`${P} workspace ${j.config.workspaceId}, but --workspace names ${E.flagWorkspace}. ${C}`;if(E.envWorkspace&&E.envWorkspace!==j.config.workspaceId)return`${P} workspace ${j.config.workspaceId}, but HLIX_WORKSPACE_ID names ${E.envWorkspace}. ${C}`;if(E.flagBaseUrl&&!rs(E.flagBaseUrl,j.config.apiUrl))return`${P} ${j.config.apiUrl}, but --base-url names ${E.flagBaseUrl}. ${C}`;if(E.envBaseUrl&&!rs(E.envBaseUrl,j.config.apiUrl))return`${P} ${j.config.apiUrl}, but HLIX_BASE_URL names ${E.envBaseUrl}. ${C}`;return null}import{resolve as oi}from"node:path";import{parseArgs as ii}from"node:util";import qo from"openapi-fetch";function vn(j){return qo({baseUrl:j.baseUrl,headers:j.headers,fetch:j.fetch})}var Me=(j)=>({kind:"apiKey",apiKey:j});var Sn=(j)=>({kind:"bearer",token:j});function Wo(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 Vo(j){return j?{"X-Organization-Id":j}:{}}function os(j,E){return{...Wo(j),...Vo(E)}}function Xo(j){if(typeof j!=="object"||j===null)return null;let{error:E}=j;return typeof E==="string"?E:null}class ue extends Error{status;body;requestId;method;url;constructor(j,E){super(j);this.name=new.target.name,this.status=E.status,this.body=E.body,this.requestId=E.requestId??null,this.method=E.method,this.url=E.url}}class Ue extends ue{issues;constructor(j,E,P){super(j,E);this.issues=P}}class ct extends ue{}class lt extends ue{}class dt extends ue{}class Se extends ue{}class ut extends ue{}class pt extends ue{retryAfter;constructor(j,E,P){super(j,E);this.retryAfter=P}}class mt extends ue{}class ft extends ue{}class Be extends Error{method;url;constructor(j,E){super(j,{cause:E.cause});this.name="HlixTransportError",this.method=E.method,this.url=E.url}}function Yo(j){if(typeof j!=="object"||j===null)return null;let E=j;if(E.success!==!1)return null;let P=E.error?.message;if(typeof P!=="string")return null;try{let C=JSON.parse(P);return Array.isArray(C)?C:[]}catch{return[]}}function Zo(j){let E=j.get("retry-after");if(!E)return null;let P=Number(E);return Number.isFinite(P)&&P>=0?P:null}function De(j,E,P){let C={status:j.status,body:E,requestId:j.headers.get("x-request-id"),method:P.method,url:P.url},R=Xo(E),I=`${P.method} ${P.url} failed with ${j.status}`,_=Yo(E);if(_)return new Ue(`${P.method} ${P.url}: request body failed validation`,C,_);let O=R??I;switch(j.status){case 400:return new ct(O,C);case 401:return new lt(O,C);case 403:return new dt(O,C);case 404:return new Se(O,C);case 409:return new ut(O,C);case 429:return new pt(O,C,Zo(j.headers));case 501:return new mt(O,C);default:return j.status>=500?new ft(O,C):new ue(O,C)}}var is=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function Dt(j){return is.has(j.toUpperCase())}var Qo=new Set([429,500,502,503,504]);function ei(j){return Qo.has(j)}var bn={attempts:3,baseDelayMs:200,maxDelayMs:5000};function kn(j,E,P,C=Math.random){if(P!==null)return Math.min(P*1000,E.maxDelayMs);let R=Math.min(E.baseDelayMs*2**j,E.maxDelayMs);return Math.round(C()*R)}function jn(j){if(!Dt(j.method))return!1;if(j.attempt+1>=j.policy.attempts)return!1;return j.status===null||ei(j.status)}var ti=(j)=>new Promise((E)=>setTimeout(E,j));function ni(j){let E=j.headers.get("retry-after");if(!E)return null;let P=Number(E);return Number.isFinite(P)&&P>=0?P:null}function as(j){let{base:E,policy:P}=j,C=j.sleep??ti,R=j.random??Math.random;return async(I)=>{let _=I.method.toUpperCase(),O=Dt(_)?I.clone():null;for(let T=0;;T+=1){let A=T===0?I:O.clone(),N;try{N=await E(A)}catch(F){if(!O||!jn({method:_,attempt:T,policy:P,status:null}))throw new Be(`${_} ${I.url}: ${F instanceof Error?F.message:String(F)}`,{method:_,url:I.url,cause:F});await C(kn(T,P,null,R));continue}if(!jn({method:_,attempt:T,policy:P,status:N.status}))return N;if(!O)return N;await C(kn(T,P,ni(N),R))}}}function W(j,E){if(j.response.ok)return j.data;throw De(j.response,j.error??j.data,E)}var gt=(j)=>typeof j==="string"?j:"";function En(j){let E;try{E=JSON.parse(j)}catch{return null}if(typeof E!=="object"||E===null)return null;let P=E;switch(P.type){case"idle":return{type:"idle"};case"done":return{type:"done"};case"active":return typeof P.runId==="string"?{type:"active",runId:P.runId}:{type:"active"};case"on_chat_model_stream":return{type:"on_chat_model_stream",delta:gt(P.delta)};case"reasoning":return{type:"reasoning",delta:gt(P.delta)};case"on_tool_start":return{type:"on_tool_start",name:gt(P.name),input:P.input};case"on_tool_end":return{type:"on_tool_end",name:gt(P.name),output:P.output};case"error":return{type:"error",message:gt(P.message)};default:return null}}var $n=(j)=>j.type==="done"||j.type==="idle"||j.type==="error";var ri=()=>({event:null,data:[],id:null,retry:null});function cs(j,E,P){switch(E){case"event":j.event=P;return;case"data":j.data.push(P);return;case"id":if(!P.includes("\x00"))j.id=P;return;case"retry":{if(/^\d+$/.test(P))j.retry=Number(P);return}default:return}}function ds(j){let E=j.data.join(`
|
|
10
|
+
`),{event:P,id:C}=j;if(j.data=[],j.event=null,E==="")return null;return{event:P,data:E,id:C,retry:j.retry}}function ls(j,E){if(E==="")return ds(j);if(E.startsWith(":"))return null;let P=E.indexOf(":");if(P===-1)return cs(j,E,""),null;let C=E.slice(0,P),R=E.slice(P+1);if(R.startsWith(" "))R=R.slice(1);return cs(j,C,R),null}function si(j){let E=[],P=0;for(let C=0;C<j.length;C+=1){let R=j[C];if(R!==`
|
|
11
|
+
`&&R!=="\r")continue;if(E.push(j.slice(P,C)),R==="\r"&&j[C+1]===`
|
|
12
|
+
`)C+=1;P=C+1}return{lines:E,rest:j.slice(P)}}async function*Pn(j,E){let P=j.getReader(),C=new TextDecoder,R=ri(),I="",_=()=>void P.cancel().catch(()=>{});E?.addEventListener("abort",_,{once:!0});try{for(;;){let{done:T,value:A}=await P.read();if(T)break;I+=C.decode(A,{stream:!0});let{lines:N,rest:F}=si(I);I=F;for(let M of N){let G=ls(R,M);if(G)yield G}if(E?.aborted)return}if(I+=C.decode(),I!==""){let T=ls(R,I);if(T)yield T}let O=ds(R);if(O)yield O}finally{E?.removeEventListener("abort",_),P.releaseLock()}}class ze{raw;baseUrl;headers;fetcher;constructor(j){this.baseUrl=j.baseUrl.replace(/\/+$/,""),this.headers=os(j.credential,j.organizationId);let E={...bn,...j.retry},P=j.fetch??((C)=>globalThis.fetch(C));this.fetcher=as({base:P,policy:E}),this.raw=vn({baseUrl:this.baseUrl,headers:this.headers,fetch:this.fetcher})}at(j,E){return{method:j,url:`${this.baseUrl}${E}`}}workspaces={list:async()=>W(await this.raw.GET("/v1/api/workspaces"),this.at("GET","/v1/api/workspaces"))};projects={list:async()=>W(await this.raw.GET("/v1/api/projects"),this.at("GET","/v1/api/projects")),get:async(j)=>W(await this.raw.GET("/v1/api/projects/{id}",{params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}`)),create:async(j)=>W(await this.raw.POST("/v1/api/projects",{body:j}),this.at("POST","/v1/api/projects")),delete:async(j)=>W(await this.raw.DELETE("/v1/api/projects/{id}",{params:{path:{id:j}}}),this.at("DELETE",`/v1/api/projects/${j}`)),start:async(j,E)=>W(await this.raw.POST("/v1/api/projects/{id}/start",{params:{path:{id:j}},body:E}),this.at("POST",`/v1/api/projects/${j}/start`)),refreshPreview:async(j)=>W(await this.raw.POST("/v1/api/projects/{id}/preview/refresh",{params:{path:{id:j}}}),this.at("POST",`/v1/api/projects/${j}/preview/refresh`)),terminal:async(j)=>W(await this.raw.GET("/v1/api/projects/{id}/terminal",{params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}/terminal`)),observeAgent:(j,E,P)=>this.observeAgent(j,E,P),workspace:(j)=>({environment:async()=>W(await this.raw.GET("/v1/api/projects/{id}/environment",{params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}/environment`)),fs:async(E)=>W(await this.raw.POST("/v1/api/projects/{id}/workspace/fs",{params:{path:{id:j}},body:E}),this.at("POST",`/v1/api/projects/${j}/workspace/fs`)),exec:async(E)=>W(await this.raw.POST("/v1/api/projects/{id}/workspace/exec",{params:{path:{id:j}},body:E}),this.at("POST",`/v1/api/projects/${j}/workspace/exec`))})};secrets={listEntries:async(j)=>W(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,E)=>W(await this.raw.PUT("/v1/api/secrets/project/{projectId}/entries",{params:{path:{projectId:j}},body:E}),this.at("PUT",`/v1/api/secrets/project/${j}/entries`)),importFiles:async(j,E)=>W(await this.raw.PUT("/v1/api/secrets/project/{projectId}/files",{params:{path:{projectId:j}},body:{files:E}}),this.at("PUT",`/v1/api/secrets/project/${j}/files`)),deleteEntry:async(j,E,P)=>W(await this.raw.DELETE("/v1/api/secrets/project/{projectId}/entries/{key}",{params:{path:{projectId:j,key:E},...P===void 0?{}:{query:{source:P}}}}),this.at("DELETE",`/v1/api/secrets/project/${j}/entries/${encodeURIComponent(E)}`)),exportEntries:async(j,E={})=>{let P=`/v1/api/secrets/project/${j}/export`,C=`${this.baseUrl}${P}`,R=await this.fetcher(new Request(C,{method:"POST",headers:{...this.headers,"content-type":"application/json"},body:JSON.stringify({...E.source===void 0?{}:{source:E.source},...E.format===void 0?{}:{format:E.format}})}));if(!R.ok)throw De(R,await R.json().catch(()=>{return}),{method:"POST",url:C});return R.text()}};imports={create:async(j)=>{let E=await this.raw.POST("/v1/api/imports",{body:j});return W(E,this.at("POST","/v1/api/imports"))},get:async(j)=>W(await this.raw.GET("/v1/api/imports/{id}",{params:{path:{id:j}}}),this.at("GET",`/v1/api/imports/${j}`)),finalize:async(j,E)=>{let P=await this.raw.POST("/v1/api/imports/{id}/finalize",{params:{path:{id:j}},body:E});return W(P,this.at("POST",`/v1/api/imports/${j}/finalize`))},uploadBundle:async(j,E,P={})=>{let C=P.chunkSize??8388608;if(C<=0||C%262144!==0)throw Error("Import upload chunkSize must be a positive multiple of 256 KiB");let R=j.url.startsWith("/")?`${this.baseUrl}${j.url}`:j.url;if(j.kind==="hlix-stream"){let _=new Request(R,{method:"PUT",headers:{...this.headers,"content-type":"application/x-git-bundle","content-length":String(E.size)},body:E,signal:P.signal}),O=await this.fetcher(_);if(!O.ok)await this.throwUploadError(O,R);P.onProgress?.(E.size,E.size);return}let I=0;while(I<E.size){let _=Math.min(I+C,E.size),O=new Request(R,{method:"PUT",headers:{"content-type":"application/x-git-bundle","content-length":String(_-I),"content-range":`bytes ${I}-${_-1}/${E.size}`},body:E.slice(I,_),signal:P.signal}),T=await this.fetcher(O);if(T.status!==308&&!T.ok)await this.throwUploadError(T,R);let A=T.headers.get("range")?.match(/bytes=0-(\d+)/)?.[1];if(I=A?Number(A)+1:_,!Number.isSafeInteger(I)||I<_||I>E.size)throw Error("Import upload server returned an invalid acknowledged range");P.onProgress?.(I,E.size)}}};revisions={head:async(j)=>W(await this.raw.GET("/v1/api/projects/{id}/revisions/head",{params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}/revisions/head`)),protectedFiles:async(j)=>W(await this.raw.GET("/v1/api/projects/{id}/protected-files",{params:{path:{id:j}}}),this.at("GET",`/v1/api/projects/${j}/protected-files`)),createUpload:async(j,E)=>{let P=await this.raw.POST("/v1/api/projects/{id}/revisions/uploads",{params:{path:{id:j}},body:E});return W(P,this.at("POST",`/v1/api/projects/${j}/revisions/uploads`))},finalize:async(j,E,P)=>{let C=await this.raw.POST("/v1/api/projects/{id}/revisions/uploads/{uploadId}/finalize",{params:{path:{id:j,uploadId:E}},body:P});return W(C,this.at("POST",`/v1/api/projects/${j}/revisions/uploads/${E}/finalize`))},uploadBundle:async(j,E,P={})=>this.imports.uploadBundle(j,E,P),downloadBundle:async(j,E)=>{let P=`/v1/api/projects/${j}/revisions/${E}/bundle`,C=new Request(`${this.baseUrl}${P}`,{method:"GET",headers:this.headers}),R=await this.fetcher(C);if(!R.ok)await this.throwUploadError(R,`${this.baseUrl}${P}`);return R.blob()}};resources={importSkill:async(j,E)=>W(await this.raw.POST("/v1/api/projects/{id}/resources/skill",{params:{path:{id:j}},body:E}),this.at("POST",`/v1/api/projects/${j}/resources/skill`)),importAgent:async(j,E)=>W(await this.raw.POST("/v1/api/projects/{id}/resources/agent",{params:{path:{id:j}},body:E}),this.at("POST",`/v1/api/projects/${j}/resources/agent`)),importMcp:async(j,E)=>W(await this.raw.POST("/v1/api/projects/{id}/resources/mcp",{params:{path:{id:j}},body:E}),this.at("POST",`/v1/api/projects/${j}/resources/mcp`))};async throwUploadError(j,E){let P=null;try{P=await j.json()}catch{P=await j.text().catch(()=>null)}throw De(j,P,{method:"PUT",url:E})}tasks={list:async(j)=>W(await this.raw.GET("/v1/api/tasks",{params:{query:j??{}}}),this.at("GET","/v1/api/tasks")),get:async(j)=>W(await this.raw.GET("/v1/api/tasks/{id}",{params:{path:{id:j}}}),this.at("GET",`/v1/api/tasks/${j}`)),create:async(j)=>W(await this.raw.POST("/v1/api/tasks",{body:j}),this.at("POST","/v1/api/tasks")),update:async(j,E)=>W(await this.raw.PATCH("/v1/api/tasks/{id}",{params:{path:{id:j}},body:E}),this.at("PATCH",`/v1/api/tasks/${j}`)),listComments:async(j)=>W(await this.raw.GET("/v1/api/tasks/{id}/comments",{params:{path:{id:j}}}),this.at("GET",`/v1/api/tasks/${j}/comments`)),addComment:async(j,E)=>W(await this.raw.POST("/v1/api/tasks/{id}/comments",{params:{path:{id:j}},body:E}),this.at("POST",`/v1/api/tasks/${j}/comments`)),review:async(j)=>W(await this.raw.GET("/v1/api/tasks/{id}/review",{params:{path:{id:j}}}),this.at("GET",`/v1/api/tasks/${j}/review`)),stream:(j,E)=>this.stream(`/v1/api/tasks/${j}/stream`,E)};modelConfig={setProjectHarness:async(j,E)=>W(await this.raw.PUT("/v1/api/model-config/harness/{projectId}",{params:{path:{projectId:j}},body:{harness:E}}),this.at("PUT",`/v1/api/model-config/harness/${j}`)),clearProjectHarness:async(j)=>W(await this.raw.DELETE("/v1/api/model-config/harness/{projectId}",{params:{path:{projectId:j}}}),this.at("DELETE",`/v1/api/model-config/harness/${j}`)),setHarness:async(j)=>W(await this.raw.PUT("/v1/api/model-config/harness",{body:{harness:j}}),this.at("PUT","/v1/api/model-config/harness")),clearHarness:async()=>W(await this.raw.DELETE("/v1/api/model-config/harness"),this.at("DELETE","/v1/api/model-config/harness")),resolvedHarness:async()=>W(await this.raw.GET("/v1/api/model-config/harness/resolved"),this.at("GET","/v1/api/model-config/harness/resolved")),resolvedProjectHarness:async(j)=>W(await this.raw.GET("/v1/api/model-config/harness/{projectId}/resolved",{params:{path:{projectId:j}}}),this.at("GET",`/v1/api/model-config/harness/${j}/resolved`))};ai={models:async(j,E)=>W(await this.raw.GET("/v1/api/ai/w/{workspaceId}/models",{params:{path:{workspaceId:j}},...E?.signal?{signal:E.signal}:{}}),this.at("GET",`/v1/api/ai/w/${j}/models`))};cycles={list:async(j)=>W(await this.raw.GET("/v1/api/cycles",{params:{query:j??{}}}),this.at("GET","/v1/api/cycles")),get:async(j)=>W(await this.raw.GET("/v1/api/cycles/{id}",{params:{path:{id:j}}}),this.at("GET",`/v1/api/cycles/${j}`)),propose:async(j)=>W(await this.raw.POST("/v1/api/cycles",{body:j}),this.at("POST","/v1/api/cycles")),stream:(j,E)=>this.stream(`/v1/api/cycles/${j}/stream`,E)};clientInvoices={list:async(j)=>W(await this.raw.GET("/v1/api/client-billing/invoices",{params:{query:j??{}}}),this.at("GET","/v1/api/client-billing/invoices")),get:async(j)=>W(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)=>W(await this.raw.POST("/v1/api/client-billing/invoices",{body:j}),this.at("POST","/v1/api/client-billing/invoices")),issue:async(j)=>W(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,E)=>W(await this.raw.POST("/v1/api/client-billing/invoices/{id}/void",{params:{path:{id:j}},body:{reason:E}}),this.at("POST",`/v1/api/client-billing/invoices/${j}/void`)),pay:async(j)=>W(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,E={})=>W(await this.raw.POST("/v1/api/client-billing/invoices/{id}/payment-link",{params:{path:{id:j}},body:E}),this.at("POST",`/v1/api/client-billing/invoices/${j}/payment-link`))};async*observeAgent(j,E,P){let C=`/v1/api/projects/${j}/agents/${E}/observe`;for await(let R of this.stream(C,P)){let I=En(R.data);if(!I)continue;if(yield I,$n(I))return}}async*stream(j,E){let P=`${this.baseUrl}${j}`,C=new Request(P,{headers:{...this.headers,accept:"text/event-stream"},signal:E?.signal}),R=await globalThis.fetch(C);if(!R.ok||!R.body){let I=null;try{I=await R.json()}catch{I=null}throw De(R,I,{method:"GET",url:P})}yield*Pn(R.body,E?.signal)}}function Cn(j){if(j instanceof e)return{code:j.code,status:null};if(j instanceof Ue)return{code:"invalid_request",status:400};if(j instanceof ct)return{code:"bad_request",status:400};if(j instanceof lt)return{code:"unauthenticated",status:401};if(j instanceof dt)return{code:"forbidden",status:403};if(j instanceof Se)return{code:"not_found",status:404};if(j instanceof ut)return{code:"conflict",status:409};if(j instanceof pt)return{code:"rate_limited",status:429};if(j instanceof mt)return{code:"not_implemented",status:501};if(j instanceof ft)return{code:"server_error",status:j.status};if(j instanceof Be)return{code:"unreachable",status:null};return{code:"unknown",status:null}}var zt=(j)=>{if(j instanceof Ue&&j.issues.length>0){let E=j.issues.slice(0,5).map((C)=>{let R=C;return` - ${Array.isArray(R.path)&&R.path.length>0?`${R.path.join(".")}: `:""}${typeof R.message==="string"?R.message:JSON.stringify(C)}`}),P=j.issues.length-E.length;return`${j.message}
|
|
13
|
+
${E.join(`
|
|
14
|
+
`)}${P>0?`
|
|
15
|
+
… ${P} more`:""}`}return j instanceof Error?j.message:String(j)};function o(j,E){let P=n({env:j,flags:E.flags,cwd:E.cwd});if(P.conflict)throw new e("workspace_mismatch",P.conflict);if(!P.credential)throw new e("unauthenticated","No credential. Run `hlix auth login`, or set HLIX_API_KEY for CI.");return new ze({baseUrl:P.baseUrl,credential:P.credential.sessionToken?Sn(P.credential.sessionToken):Me(P.credential.apiKey),...P.workspaceId?{organizationId:P.workspaceId}:{}})}function us(j){let E=Math.max(...j.map((C)=>C.name.length));return`hlix — the hlix control-plane CLI
|
|
16
|
+
|
|
17
|
+
Usage:
|
|
18
|
+
hlix <command> [options]
|
|
19
|
+
|
|
20
|
+
Commands:
|
|
21
|
+
${[` hlix ${"".padEnd(E)} Open Hlix Code (interactive)`,...j.map((C)=>` hlix ${C.name.padEnd(E)} ${C.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 ms(j,E){let P=[...Array(E.length+1).keys()];for(let C=1;C<=j.length;C+=1){let R=[C];for(let I=1;I<=E.length;I+=1)R[I]=Math.min(P[I]+1,R[I-1]+1,P[I-1]+(j[C-1]===E[I-1]?0:1));P=R}return P[E.length]}function ai(j,E,P){let C=/Unknown option '--([^'=]+)/.exec(P)?.[1];if(!C)return P;let R=E.findIndex((T)=>T.startsWith("-")),I=R===-1?E:E.slice(0,R),_=new Set(["json","help","version","cwd","workspace","base-url",...Kt(j,I)?.command.options??[]]),O=null;for(let T of _){let A=ms(C,T);if(A<=2&&(!O||A<O.distance))O={name:T,distance:A}}return O?`${P}
|
|
46
|
+
Did you mean --${O.name}?`:P}function ps(j,E){let P=new Set;for(let I of j)P.add(I.name),P.add(I.name.split(" ")[0]);let C=null;for(let I of P){let _=ms(E,I);if(_<=2&&(!C||_<C.distance))C={name:I,distance:_}}if(!C)return null;if(j.some((I)=>I.name===C.name))return C.name;let R=j.filter((I)=>I.name.startsWith(`${C.name} `)).sort((I,_)=>I.name.length-_.name.length)[0];return R?R.name:C.name}function Kt(j,E){for(let P of[...j].sort((C,R)=>R.name.length-C.name.length)){let C=P.name.split(" ");if(C.every((R,I)=>E[I]===R))return{command:P,rest:E.slice(C.length)}}return null}function ci(j,E,P){let C=ai(j,E,P);if(!/^Unknown option '/.test(P))return C;let R=C.replace(/\. To specify a positional argument[\s\S]*?after '--'[^\n]*/,"."),I=Kt(j,E.filter((_)=>!_.startsWith("-")));return I?`${R}
|
|
47
|
+
|
|
48
|
+
${I.command.usage}`:R}async function s(j,E,P){if(E.some((B)=>B==="--api-key"||B.startsWith("--api-key=")))return P.stderr("error: API keys are never accepted as command-line arguments. Run `hlix auth login` and use the hidden prompt.\n"),2;let C;try{C=ii({args:E,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"},print:{type:"boolean"},web:{type:"boolean"},"env-file":{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"}}})}catch(B){let ee=E.includes("--json"),oe=ci(j,E,zt(B));if(P.onFailure?.({code:"invalid_usage",message:oe,status:null}),ee)P.stdout(J(tt("cli",{code:"invalid_usage",message:oe,status:null})));else P.stderr(`${oe}
|
|
49
|
+
`);return 2}let R=C.values.json===!0,I=C.positionals;if(C.values.version===!0){let{version:B}=await import("./package-q1pwa5fr.js");return P.stdout(`${B}
|
|
50
|
+
`),0}if(I.length===0||C.values.help===!0){let B=Kt(j,I);return P.stdout(B?`${B.command.usage}
|
|
51
|
+
`:us(j)),I.length===0&&C.values.help!==!0?1:0}let _=Kt(j,I);if(!_){let B=I.join(" "),ee=ps(j,B)??ps(j,I[0]),oe=ee?`Unknown command: ${B}
|
|
52
|
+
Did you mean \`hlix ${ee}\`?`:`Unknown command: ${B}`;if(P.onFailure?.({code:"unknown_command",message:oe,status:null}),R)P.stdout(J(tt(B,{code:"unknown_command",message:oe,status:null})));else P.stderr(`${oe}
|
|
53
|
+
|
|
54
|
+
${us(j)}`);return 2}let O=new Set(["json","help","version","cwd","workspace","base-url"]),T=new Set(_.command.options??[]),A=Object.entries(C.values).filter(([B,ee])=>ee!==void 0&&!O.has(B)&&!T.has(B)).map(([B])=>`--${B}`),N=_.command.args??{min:0,max:0},F=_.rest.length<N.min?{code:"missing_argument",message:_.command.usage.split(`
|
|
55
|
+
`)[0]}:_.rest.length>N.max?{code:"invalid_usage",message:_.command.usage.split(`
|
|
56
|
+
`)[0]}:null,M=typeof C.values.cwd==="string"?C.values.cwd:void 0,G=oi(M??"."),U=M!==void 0&&!ss(G)?{code:"invalid_usage",message:`--cwd is not a directory: ${G}`}:null,H=A.length>0?{code:"invalid_usage",message:`Unsupported option for ${_.command.name}: ${A.join(", ")}`}:U??F;if(H){if(P.onFailure?.({...H,status:null}),R)P.stdout(J(tt(_.command.name,{...H,status:null})));else{let B=_.command.usage.startsWith(H.message)?_.command.usage:`${H.message}
|
|
57
|
+
|
|
58
|
+
${_.command.usage}`;P.stderr(`error: ${B}
|
|
59
|
+
`)}return 2}let L=C.values,z={...P,args:_.rest,json:R,flags:L,cwd:G,requireClient:(B)=>o(P.env,{cwd:B??G,flags:L})};try{return await _.command.run(z)}catch(B){let{code:ee,status:oe}=Cn(B);if(P.onFailure?.({code:ee,message:zt(B),status:oe,...B instanceof e&&B.details!==void 0?{details:B.details}:{}}),R)P.stdout(J(tt(_.command.name,{code:ee,message:zt(B),status:oe})));else if(P.stderr(`error: ${zt(B)}
|
|
60
|
+
`),process.env.HLIX_DEBUG&&B instanceof Error&&B.stack)P.stderr(`${B.stack}
|
|
61
|
+
`);return ee==="unauthenticated"||ee==="forbidden"?3:1}}import{readFileSync as li}from"node:fs";import{homedir as di}from"node:os";import{join as ui}from"node:path";var fs=20000;function l(j){if(j===void 0)return;let E=typeof j==="number"?j:Number(j.trim());return Number.isInteger(E)&&E>=fs?E:void 0}var i=["cloud","docker","local"],r=["claude-code","codex","cursor-agent","hlix"],h="hlix",gs={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"},Ke=["dockerImage","harness","memoryTokens","model","sandbox","yolo"],In=["projectId","workspaceId","apiUrl"];function xn(j=process.env){return ui(j.HLIX_CONFIG_HOME??di(),".hlix","config.json")}function hs(j=process.env){try{let E=JSON.parse(li(xn(j),"utf8"));return E.schemaVersion===1?E:null}catch{return null}}function d(j,E=process.env){let P=hs(E),C=t(j),R=C?.root??null,I=C?.config??null,_={},O={},T=(A)=>{let N=I?.[A],F=P?.[A];if(N!==void 0)_[A]=N,O[A]="project";else if(F!==void 0)_[A]=F,O[A]="global"};for(let A of Ke)T(A);for(let A of In){let N=I?.[A];if(N!==void 0)_[A]=N,O[A]="project"}return{merged:_,sources:O,global:P,project:I,paths:{global:xn(E),project:R?ot(R):null}}}function ys(j){return[...Ke,...In].map((P)=>({key:P,value:j.merged[P]??null,source:j.sources[P]??"default"}))}function pi(j,E){if(j==="sandbox"&&!i.includes(E))return`sandbox must be one of ${i.join(", ")}; got "${E}".`;if(j==="harness"&&!r.includes(E))return`harness must be one of ${r.join(", ")}; got "${E}".`;if(j==="model"&&E.trim()==="")return"model must not be empty.";if(j==="memoryTokens"&&l(E)===void 0)return`memoryTokens must be a whole number of tokens, at least ${fs}; got "${E}".`;if(j==="dockerImage"&&E.trim()==="")return"dockerImage must not be empty.";if(j==="yolo"&&y(E)===void 0)return`yolo must be true or false; got "${E}".`;return null}function y(j){if(j===void 0)return;let E=j.trim().toLowerCase();if(["true","1","yes","on"].includes(E))return!0;if(["false","0","no","off"].includes(E))return!1;return}function Rn(j){if(Ke.includes(j))return j;let E=In.includes(j);throw new e("invalid_usage",E?`${j} is written by \`hlix init\` and \`hlix import\`, not by \`hlix config set\`.`:`Unknown setting: ${j}. Known settings: ${Ke.join(", ")}.`)}function ws(j,E){let P=pi(j,E);if(P)throw new e("invalid_usage",P);return E}function u(j){if(j.scope==="global"){let C=xn(j.env),R=hs(j.env)??{schemaVersion:1};return st(C,{...R,[j.key]:j.value}),C}let E=t(j.cwd);if(!E)throw new e("not_initialized","This folder is not bound to hlix. Run `hlix init` here, or set it machine-wide with --global.");let P=ot(E.root);return st(P,{...E.config,[j.key]:j.value}),P}import{createHash as mi}from"node:crypto";import{mkdirSync as fi,readdirSync as Es,readFileSync as gi,rmSync as hi,statSync as $s,writeFileSync as yi}from"node:fs";import{homedir as wi,tmpdir as vi}from"node:os";import{basename as Ps,isAbsolute as Si,join as Z,relative as bi}from"node:path";var c=(j=process.env)=>j.HOME??j.USERPROFILE??wi();function le(j){try{if(!$s(j).isFile())return null;return gi(j,"utf8")}catch{return null}}function ki(j){try{return $s(j).isDirectory()}catch{return!1}}function Je(j,E){try{return Es(j,{withFileTypes:!0}).filter((P)=>P.isFile()&&P.name.endsWith(E)).map((P)=>Z(j,P.name)).sort()}catch{return[]}}function ji(j){try{return Es(j,{withFileTypes:!0}).filter((E)=>E.isDirectory()||E.isSymbolicLink()).map((E)=>Z(j,E.name)).sort()}catch{return[]}}function Tn(j){let E=j.replace(/^\uFEFF/,""),P=E.indexOf(`
|
|
62
|
+
`);if(!E.startsWith("---")||P===-1)return{fields:{},body:E.trim()};let C=E.indexOf(`
|
|
63
|
+
---`,P);if(C===-1)return{fields:{},body:E.trim()};let R={};for(let _ of E.slice(P+1,C).split(`
|
|
64
|
+
`)){let O=/^([A-Za-z_][\w-]*)\s*:\s*(.*)$/.exec(_);if(!O)continue;R[O[1]]=O[2].trim().replace(/^["']|["']$/g,"")}let I=E.indexOf(`
|
|
65
|
+
`,C+1);return{fields:R,body:I===-1?"":E.slice(I+1).trim()}}function Ei(j){let E=j.trimStart(),P=/^"((?:[^"\\]|\\.)*)"/.exec(E)??/^'([^']*)'/.exec(E);if(P)return P[1].replace(/\\"/g,'"').replace(/\\n/g,`
|
|
66
|
+
`);if(E.startsWith("["))return[...E.matchAll(/"((?:[^"\\]|\\.)*)"|'([^']*)'/g)].map((R)=>R[1]??R[2]??"");if(E.startsWith("{")){let R={};for(let I of E.matchAll(/([A-Za-z0-9_.-]+)\s*=\s*"((?:[^"\\]|\\.)*)"/g))R[I[1]]=I[2].replace(/\\"/g,'"');return R}let C=/^[^\s#]+/.exec(E)?.[0];if(C===void 0)return;if(C==="true"||C==="false")return C==="true";if(/^-?\d+(\.\d+)?$/.test(C))return Number(C);return C}function Cs(j){let E={"":{}},P="",C=j.split(`
|
|
67
|
+
`);for(let R=0;R<C.length;R+=1){let _=C[R].trim();if(!_||_.startsWith("#"))continue;let O=/^\[\[?([^\]]+)\]\]?$/.exec(_);if(O){P=O[1].trim(),E[P]??={};continue}let T=/^([A-Za-z0-9_.-]+|"[^"]+")\s*=\s*(.*)$/.exec(_);if(!T)continue;let A=T[1].replace(/^"|"$/g,""),N=T[2];if(N.startsWith('"""')){let M=[],G=N.slice(3);if(G.includes('"""'))M.push(G.slice(0,G.indexOf('"""')));else{if(G)M.push(G);while(R+1<C.length){R+=1;let U=C[R],H=U.indexOf('"""');if(H===-1){M.push(U);continue}M.push(U.slice(0,H));break}}E[P][A]=M.join(`
|
|
68
|
+
`).replace(/^\n/,"");continue}let F=Ei(N);if(F!==void 0)E[P][A]=F}return E}function _n(j,E){return j.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g,(P,C,R)=>{let I=E[C];return I!==void 0&&I!==""?I:R??""})}var vs=(j,E)=>{let P={};for(let[C,R]of Object.entries(j))if(typeof R==="string")P[C]=_n(R,E);return P},$i=[{relative:"GEMINI.md",source:"gemini"},{relative:Z(".gemini","GEMINI.md"),source:"gemini"},{relative:".cursorrules",source:"cursor"},{relative:".windsurfrules",source:"windsurf"},{relative:Z(".github","copilot-instructions.md"),source:"copilot"}],Pi=[{relative:Z(".gemini","GEMINI.md"),source:"gemini"}],Ci=[{relative:Z(".cursor","rules"),source:"cursor",extension:".mdc"},{relative:Z(".windsurf","rules"),source:"windsurf",extension:".md"}];function Ii(j,E){let P=Z(j,".clinerules"),C=ki(P)?Je(P,".md"):[P],R=[];for(let I of C){let _=le(I)?.trim();if(_)R.push({path:I,source:"cline",scope:E,content:_})}return R}function xi(j,E,P){let{fields:C,body:R}=Tn(E);if(C.alwaysApply==="false")return{path:j,source:"cursor",scope:P,reason:"alwaysApply: false"};if(!R)return{path:j,source:"cursor",scope:P,reason:"no rule body"};let I=C.globs?.replace(/^\[|\]$/g,"").trim();return{path:j,source:"cursor",scope:P,content:R,...I?{note:`Applies to: ${I}`}:{}}}var Ri=["AGENTS.md","CLAUDE.md"],Is=["",".claude"],w=["commands"];function _i(j,E){let P=[],C=new Set;for(let R of[...Is,E])for(let I of Ri){let _=Z(j,R,I),O=le(_)?.trim();if(!O||C.has(O))continue;C.add(O),P.push({path:_,content:O})}return P}function Ss(j,E){return _i(j,E).map((P)=>P.content)}var p=["AGENTS.md","CLAUDE.md","GEMINI.md"];function On(j,E){for(let P of p)for(let C of[...Is,E]){let R=Z(j,C,P),I=le(R)?.trim();if(I)return{path:R,content:I}}return null}var An=(j=process.env)=>Z(j.HLIX_CONFIG_HOME??Z(c(j),".hlix"),"AGENTS.md");function m(j){let E=j.env??process.env,P=An(E),C=le(P)?.trim();return{global:C?{path:P,content:C}:null,project:On(j.cwd,j.configDir)}}var bs=(j)=>{let E=Math.round(j.length/4);return E>=1000?`${(E/1000).toFixed(1)}k tokens`:`${E} tokens`};function v(j,E,P=process.env){let C=[...j.global?[Rs(j.global.path,P)]:[],...j.project?[yt(j.project.path,E)]:[]];return C.length===0?"":`rules: ${C.join(" + ")}`}function g(j,E,P=process.env,C=[]){let R=(I,_,O)=>_?`${I.padEnd(8)} ${O(_.path)} (${bs(_.content)})`:`${I.padEnd(8)} none`;return[R("user",j.global,(I)=>Rs(I,P)),R("project",j.project,(I)=>yt(I,E)),...C.map((I)=>`${"nested".padEnd(8)} ${yt(I.path,E)} (${bs(I.content)})`),"","User rules go first, the project's after, so the project wins a conflict.",C.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 ks=[{dir:".claude",source:"claude",harnessReads:!0},{dir:".agents",source:"agents",harnessReads:!0},{dir:".hlix",source:"hlix",harnessReads:!0},{dir:".codex",source:"codex",harnessReads:!1}],Ti=[{relative:Z(".cursor","commands"),source:"cursor"},{relative:Z(".codex","prompts"),source:"codex"}],Oi=[{relative:Z(".cursor","mcp.json"),source:"cursor",key:"mcpServers",format:"json"},{relative:Z(".windsurf","mcp.json"),source:"windsurf",key:"mcpServers",format:"json"},{relative:Z(".gemini","settings.json"),source:"gemini",key:"mcpServers",format:"json"},{relative:Z(".vscode","mcp.json"),source:"vscode",key:"servers",format:"json"},{relative:Z(".codex","config.toml"),source:"codex",key:"mcp_servers",format:"toml"},{relative:".mcp.json",source:"claude",key:"mcpServers",format:"json"}];function xs(j){return[...Oi,{relative:Z(j,"mcp.json"),source:"hlix",key:"mcpServers",format:"json"}]}var Ai="found, not loaded (machine-wide; enable per project by copying into .hlix/mcp.json)",Fi=(j)=>xs(j).filter((E)=>E.source!=="vscode");function Ni(j,E){if(!j||typeof j!=="object"||Array.isArray(j))return{reason:"not an object"};let P=j;if(P.enabled===!1||P.disabled===!0)return{reason:"disabled"};let C=typeof P.command==="string"&&P.command!=="",R=typeof P.url==="string"&&P.url!=="";if(C&&R)return{reason:'has both "command" and "url"'};if(C){let T=Array.isArray(P.args)?P.args.filter((N)=>typeof N==="string"):void 0,A=P.env&&typeof P.env==="object"&&!Array.isArray(P.env)?vs(P.env,E):void 0;return{config:{command:P.command,...T&&T.length>0?{args:T}:{},...A&&Object.keys(A).length>0?{env:A}:{}}}}if(!R)return{reason:'missing "command" or "url"'};let I=P.headers??P.http_headers,_=I&&typeof I==="object"&&!Array.isArray(I)?vs(I,E):{},O=P.bearer_token_env_var;if(typeof O==="string"&&/^[A-Za-z_][A-Za-z0-9_]*$/.test(O)&&!Object.keys(_).some((T)=>T.toLowerCase()==="authorization"))_.Authorization=`Bearer ${_n(`\${${O}}`,E)}`;return{config:{url:_n(P.url,E),...Object.keys(_).length>0?{headers:_}:{}}}}function js(j,E,P,C){let R=le(j),I=[],_=[];if(R===null)return{servers:I,skipped:_};let O=[];if(E.format==="toml"){let T=Cs(R);O=Object.entries(T).filter(([A])=>A.startsWith(`${E.key}.`)).map(([A,N])=>[A.slice(E.key.length+1),N])}else try{let A=JSON.parse(R)?.[E.key];if(A&&typeof A==="object"&&!Array.isArray(A))O=Object.entries(A)}catch{return _.push({path:j,source:E.source,scope:P,reason:"not valid JSON"}),{servers:I,skipped:_}}for(let[T,A]of O){let N=Ni(A,C);if("reason"in N){_.push({path:j,source:E.source,scope:P,reason:`${T}: ${N.reason}`});continue}I.push({path:j,source:E.source,scope:P,name:T,config:N.config})}return{servers:I,skipped:_}}function Hi(j,E,P){let{fields:C,body:R}=Tn(E);if(!R)return{path:j,source:"claude",scope:P,reason:"no instructions"};let I=C.tools?.replace(/^\[|\]$/g,"").split(",").map((_)=>_.trim()).filter(Boolean);return{path:j,source:"claude",scope:P,name:C.name||Ps(j,".md"),description:C.description??"",instructions:R,...I&&I.length>0&&I[0]!=="*"?{tools:I}:{},...C.model?{model:C.model}:{}}}function Li(j){let E=Cs(j)[""]??{},P=typeof E.prompt==="string"?E.prompt.trim():"";if(!P)return null;return{description:typeof E.description==="string"?E.description:"",body:P}}function f(j,E,P={}){let C=P.configDir??".hlix",R=P.env??process.env,I={instructions:[],skills:[],commands:[],generatedCommands:[],mcpServers:[],subagents:[],skipped:[]},_=(U)=>{if("reason"in U)I.skipped.push(U);else I.instructions.push(U)};for(let U of $i){let H=Z(j,U.relative),L=le(H)?.trim();if(L)I.instructions.push({path:H,source:U.source,scope:"project",content:L})}for(let U of Ci)for(let H of Je(Z(j,U.relative),U.extension)){let L=le(H);if(L===null)continue;if(U.source==="cursor"){_(xi(H,L,"project"));continue}let{body:z}=Tn(L);if(z)I.instructions.push({path:H,source:U.source,scope:"project",content:z})}for(let U of Ii(j,"project"))_(U);let O=Ss(j,C),T=Z(j,".codex","AGENTS.md"),A=le(T)?.trim();if(A&&O.includes(A))I.skipped.push({path:T,source:"codex",scope:"project",reason:"same content as the project's AGENTS.md"});else if(A)I.instructions.push({path:T,source:"codex",scope:"project",content:A});for(let U of Pi){let H=Z(E,U.relative),L=le(H)?.trim();if(L)I.instructions.push({path:H,source:U.source,scope:"global",content:L})}let N=Z(E,".codex","AGENTS.md"),F=le(N)?.trim(),M=Ss(E,C);if(F&&M.includes(F))I.skipped.push({path:N,source:"codex",scope:"global",reason:"same content as the machine's AGENTS.md"});else if(F)I.instructions.push({path:N,source:"codex",scope:"global",content:F});for(let[U,H]of[[j,"project"],[E,"global"]])for(let L of ks){let z=Z(U,L.dir===".hlix"?C:L.dir,"skills");if(!ji(z).some((ee)=>le(Z(ee,"SKILL.md"))!==null))continue;I.skills.push({path:z,source:L.source,scope:H,harnessReads:L.harnessReads})}for(let[U,H]of[[j,"project"],[E,"global"]]){for(let L of ks){if(!L.harnessReads)continue;let z=Z(U,L.dir,"commands");if(Je(z,".md").length===0)continue;I.commands.push({path:z,source:L.source,scope:H,harnessReads:!0})}for(let L of Ti){let z=Z(U,L.relative);if(Je(z,".md").length===0)continue;I.commands.push({path:z,source:L.source,scope:H})}for(let L of Je(Z(U,".gemini","commands"),".toml")){let z=le(L),B=z===null?null:Li(z);if(!B){I.skipped.push({path:L,source:"gemini",scope:H,reason:"no prompt field"});continue}I.generatedCommands.push({path:L,source:"gemini",scope:H,name:Ps(L,".toml"),body:`---
|
|
70
|
+
description: ${B.description}
|
|
71
|
+
---
|
|
72
|
+
|
|
73
|
+
${B.body}
|
|
74
|
+
`})}}for(let U of xs(C)){let H=js(Z(j,U.relative),U,"project",R);I.skipped.push(...H.skipped);for(let L of H.servers){let z=I.mcpServers.findIndex((B)=>B.name===L.name);if(z===-1)I.mcpServers.push(L);else I.mcpServers[z]=L}}for(let U of Fi(C)){let H=js(Z(E,U.relative),U,"global",R);for(let L of H.servers)I.skipped.push({path:L.path,source:L.source,scope:"global",reason:`${L.name}: ${Ai}`})}let G=[{dir:Z(".claude","agents"),source:"claude"},{dir:Z(C,"agents"),source:"hlix"}];for(let[U,H]of[[j,"project"],[E,"global"]])for(let L of G.flatMap((z)=>Je(Z(U,z.dir),".md"))){let z=le(L);if(z===null)continue;let B=Hi(L,z,H);if("reason"in B)I.skipped.push(B);else if(I.subagents.some((ee)=>ee.name===B.name))I.skipped.push({path:L,source:"claude",scope:H,reason:`a project agent already claims the name ${B.name}`});else I.subagents.push(B)}return I}function b(j,E){if(j.length===0)return null;let P=Z(vi(),"hlix-standards-commands",mi("sha256").update(E).digest("hex").slice(0,16));try{hi(P,{recursive:!0,force:!0}),fi(P,{recursive:!0});for(let C of j)yi(Z(P,`${C.name}.md`),C.body,"utf8");return P}catch{return null}}var Mi=60000,yt=(j,E)=>{let P=bi(E,j);return!P||P.startsWith("..")||Si(P)?j:P},Rs=(j,E=process.env)=>{let P=E.HLIX_CONFIG_HOME;if(P&&j.startsWith(`${P}/`))return`~/.hlix/${j.slice(P.length+1)}`;let C=c(E);return C&&j.startsWith(`${C}/`)?`~/${j.slice(C.length+1)}`:j};function S(j,E,P=Mi){if(j.length===0)return"";let C=["# 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
|
+
`),R=[],I=C.length,_=!1;for(let T of j){let A=`# From ${yt(T.path,E)} (${T.source})`,N=T.note?`${A}
|
|
76
|
+
${T.note}`:A,F=P-I-N.length-4;if(F<=0){_=!0;break}let M=T.content.length<=F?T.content:`${T.content.slice(0,F)}
|
|
77
|
+
[truncated]`;if(M.length<T.content.length)_=!0;R.push(`${N}
|
|
78
|
+
|
|
79
|
+
${M}`),I+=N.length+M.length+4}let O=_?`
|
|
80
|
+
|
|
81
|
+
[The standards block reached its ${P}-character cap; some rules above are cut short or omitted.]`:"";return`${C}
|
|
82
|
+
|
|
83
|
+
${R.join(`
|
|
84
|
+
|
|
85
|
+
`)}${O}`}var ht=(j,E,P)=>`${j} ${j===1?E:P}`;function x(j){let E=[];if(j.instructions.length>0)E.push(ht(j.instructions.length,"instruction file","instruction files"));if(j.skills.length>0)E.push(ht(j.skills.length,"skill directory","skill directories"));let P=j.commands.length+j.generatedCommands.length;if(P>0)E.push(ht(P,"command source","command sources"));if(j.mcpServers.length>0)E.push(ht(j.mcpServers.length,"mcp server","mcp servers"));if(j.subagents.length>0)E.push(ht(j.subagents.length,"subagent","subagents"));if(E.length===0)return"";let C=[...new Set([...j.instructions,...j.skills,...j.commands,...j.generatedCommands,...j.mcpServers,...j.subagents].map((R)=>R.source))].sort();return`standards: ${E.join(" · ")} (${C.join(", ")})`}function _s(j,E){let P=[],C=(I,_)=>{if(_.length===0)return;P.push(I,..._.map((O)=>` ${O}`),"")},R=(I)=>`${I.source}${I.scope==="global"?" (global)":""} ${yt(I.path,E)}`;if(C("Instructions",j.instructions.map((I)=>`${R(I)}${I.note?` — ${I.note}`:""}`)),C("Skills",j.skills.map((I)=>`${R(I)}${I.harnessReads?" — already read by the harness":""}`)),C("Commands",[...j.commands.map((I)=>`${R(I)}${I.harnessReads?" — already read by the harness":""}`),...j.generatedCommands.map((I)=>`${R(I)} → /${I.name}`)]),C("MCP servers",j.mcpServers.map((I)=>`${R(I)} → ${I.name} (${"command"in I.config?"stdio":"http"})`)),C("Subagents",j.subagents.map((I)=>`${R(I)} → ${I.name}`)),C("Skipped",j.skipped.map((I)=>`${R(I)} — ${I.reason}`)),P.length===0)return`No standards from other agent tools were found in this folder.
|
|
86
|
+
`;return`${P.join(`
|
|
87
|
+
`).trimEnd()}
|
|
88
|
+
`}async function Ui(j,E,P){let C=E.map((O)=>O.id);if(P){if(!C.includes(P))throw new e("workspace_mismatch",E.length===0?`This key belongs to a user who is not a member of any workspace, including ${P}.`:`This key cannot act in workspace ${P}. Available: ${C.join(", ")}.`);return P}if(E.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 R=E[0];if(R&&E.length===1)return j.stderr(`Using your only workspace: ${R.name} (${R.id})
|
|
89
|
+
`),R.id;if(j.json||!j.promptChoice)throw new e("missing_argument",`--workspace is required here: this key can act in ${E.length} workspaces. Pass one of: ${C.join(", ")}.`);let I=Math.max(...E.map((O)=>O.name.length));j.stderr(`${E.map((O,T)=>` ${T+1}) ${O.name.padEnd(I)} ${O.slug} ${O.role} ${O.id}`).join(`
|
|
90
|
+
`)}
|
|
91
|
+
`);let _=await j.promptChoice(`Workspace [1-${E.length}]: `,E.length);return C[_]}var Fn={name:"auth login",summary:"Verify and store a credential for this machine",usage:["Usage: hlix auth login [--workspace <id>] [--base-url <url>]",""," --base-url Defaults to https://server.hlix.ai"," --workspace Workspace (organization) id to act in. Optional: the key's"," own workspaces are listed after it is read, and the only"," one is taken automatically.","","The API key is read from a hidden prompt and never accepted as an argument.","For CI, set HLIX_API_KEY and HLIX_WORKSPACE_ID in the environment."].join(`
|
|
92
|
+
`),supportsJson:!0,options:["base-url","workspace"],async run(j){let E=typeof j.flags.workspace==="string"?j.flags.workspace:j.env.HLIX_WORKSPACE_ID,P=j.env.HLIX_API_KEY??await j.readSecret?.("Hlix API key: ")??"";if(!P)throw new e("missing_credential","No API key entered. Run from a terminal or set HLIX_API_KEY for CI.");let C=typeof j.flags["base-url"]==="string"?j.flags["base-url"]:j.env.HLIX_BASE_URL??wn,R=new URL(C),I=R.hostname==="localhost"||R.hostname==="127.0.0.1"||R.hostname==="::1";if(R.protocol!=="https:"&&!(R.protocol==="http:"&&I))throw new e("invalid_base_url","--base-url must use HTTPS (HTTP is allowed only for localhost).");let _=new ze({baseUrl:C,credential:Me(P),retry:{attempts:1}}),O=await Ui(j,await _.workspaces.list(),E);await new ze({baseUrl:C,credential:Me(P),organizationId:O,retry:{attempts:1}}).projects.list();let A=Zr({baseUrl:C,apiKey:P,organizationId:O},j.env);if(j.json)j.stdout(J(q(Fn.name,{baseUrl:C,organizationId:O,credentialPath:A})));else j.stdout(`Signed in to ${C}
|
|
93
|
+
Credential stored at ${A}
|
|
94
|
+
`);return 0}},Nn={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(`
|
|
95
|
+
`),supportsJson:!0,async run(j){let E=n({env:j.env,flags:j.flags,cwd:j.cwd});if(E.conflict)throw new e("workspace_mismatch",E.conflict);if(!E.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(C){throw j.stderr(`credential from ${E.credentialSource}, workspace ${E.workspaceId??"none"}, api ${E.baseUrl}
|
|
96
|
+
`),C}let P={credentialSource:E.credentialSource,credentialPath:E.credentialSource==="file"?E.credentialPath:null,baseUrl:E.baseUrl,baseUrlSource:E.baseUrlSource,workspaceId:E.workspaceId,workspaceSource:E.workspaceSource,valid:!0};if(j.json)return j.stdout(J(q(Nn.name,P))),0;return j.stdout(`${se([["credential",Bt(E)??"none"],["api",`${E.baseUrl} (from ${E.baseUrlSource})`],["workspace",E.workspaceId?`${E.workspaceId} (from ${E.workspaceSource})`:"none"],["status","valid"]])}
|
|
97
|
+
`),0}},Ge={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(`
|
|
98
|
+
`),supportsJson:!0,options:["yes"],async run(j){let E=n({env:j.env,flags:j.flags,cwd:j.cwd});if(E.credentialSource==="env"||E.credentialSource==="session"){let C=E.credentialSource==="session",R=C?"session":"environment",I=C?"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.",_=Yr(j.env);if(!_){let T={removed:!1,reason:R,path:null};if(j.json)j.stdout(J(q(Ge.name,T)));else j.stdout(`${I}
|
|
99
|
+
`);return 0}if(j.flags.yes!==!0){let T={removed:!1,reason:R,path:_};if(j.json)j.stdout(J(q(Ge.name,T)));else j.stdout(`${I}
|
|
100
|
+
A stored credential also exists at ${_} — repeat with --yes to remove it.
|
|
101
|
+
`);return 0}let O=hn(j.env);if(j.json)j.stdout(J(q(Ge.name,O)));else j.stdout(`Removed ${O.path}
|
|
102
|
+
${C?"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."}
|
|
103
|
+
`);return 0}if(j.flags.yes!==!0&&E.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 ${E.credentialPath}? Signing back in needs the API key again.`))throw new e("cancelled","Logout cancelled.")}let P=hn(j.env);if(j.json)j.stdout(J(q(Ge.name,P)));else j.stdout(P.removed?`Removed ${P.path}
|
|
104
|
+
`:`No stored credential at ${P.path}
|
|
105
|
+
`);return 0}};var Ts=Ke.join(" | "),Hn={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(`
|
|
106
|
+
`),supportsJson:!0,async run(j){let E=d(j.cwd,j.env),P=ys(E);if(j.json)return j.stdout(J(q(Hn.name,{settings:P,paths:E.paths}))),0;return j.stdout(`${ve(["setting","value","source","applies to"],P.map((C)=>[C.key,C.value??"-",C.source,gs[C.key]??"this folder's binding"]))}
|
|
107
|
+
`),j.stdout(`
|
|
108
|
+
global ${E.paths.global}
|
|
109
|
+
`),j.stdout(`project ${E.paths.project??"- (this folder is not bound to hlix)"}
|
|
110
|
+
`),0}},Ln={name:"config get",summary:"Print one setting's effective value",usage:[`Usage: hlix config get <${Ts}> [--cwd <dir>] [--json]`,"","Prints the value the cascade resolves for one key, or exits 1 when no","file names it."].join(`
|
|
111
|
+
`),supportsJson:!0,args:{min:1,max:1},async run(j){let E=Rn(j.args[0]),P=d(j.cwd,j.env),C=P.merged[E]??null,R=P.sources[E]??"default";if(j.json)return j.stdout(J(q(Ln.name,{key:E,value:C,source:R}))),C===null?1:0;if(C===null)return j.stderr(`${E} is not set. Set it with \`hlix config set ${E} <value>\`.
|
|
112
|
+
`),1;return j.stdout(`${C}
|
|
113
|
+
`),0}},Mn={name:"config set",summary:"Set one setting for this folder, or for the machine with --global",usage:[`Usage: hlix config set <${Ts}> <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(`
|
|
114
|
+
`),supportsJson:!0,options:["global"],args:{min:2,max:2},async run(j){let E=Rn(j.args[0]),P=ws(E,j.args[1]),C=j.flags.global===!0?"global":"project",R=u({key:E,value:P,scope:C,cwd:j.cwd,env:j.env});if(j.json)return j.stdout(J(q(Mn.name,{key:E,value:P,scope:C,path:R}))),0;return j.stdout(`${E} = ${P} (${C}: ${R})
|
|
115
|
+
`),0}};function Ie(j,E){if(typeof j!=="object"||j===null)return"";let P=j[E];return P===null||P===void 0?"":String(P)}var Un={name:"projects list",summary:"List the projects in your workspace",usage:"Usage: hlix projects list [--json]",supportsJson:!0,async run(j){let E=await j.requireClient().projects.list();if(j.json)return j.stdout(J(q(Un.name,E))),0;let P=Array.isArray(E)?E:[];if(P.length===0)return j.stdout(`No projects.
|
|
116
|
+
`),0;return j.stdout(`${ve(["ID","NAME","STACK"],P.map((C)=>[Ie(C,"id"),Ie(C,"name"),Ie(C,"stack")]))}
|
|
117
|
+
`),0}},Bn={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(`
|
|
118
|
+
`),supportsJson:!0,args:{min:0,max:1},async run(j){let E=j.args[0]??t(j.cwd)?.config.projectId;if(!E)throw new e("missing_argument","A project id is required, or run this inside a folder bound to a project.");let P=await j.requireClient().projects.get(E);if(j.json)return j.stdout(J(q(Bn.name,P))),0;let C=P.repos;return j.stdout(`${se([["id",Ie(P,"id")],["name",Ie(P,"name")],["stack",Ie(P,"stack")],["status",Ie(P,"status")],["repos",Array.isArray(C)?String(C.length):""]].filter(([,R])=>R!==""))}
|
|
119
|
+
`),0}};function Dn(j,E){let P=j.args[0];if(!P)throw new e("missing_argument",`A ${E} id is required.`);return P}function Os(j,E){let P=j.flags[E];return typeof P==="string"&&P.trim()?P.trim():void 0}function me(j,E){if(typeof j!=="object"||j===null)return"";let P=j[E];return P===null||P===void 0?"":String(P)}var zn={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(`
|
|
120
|
+
`),supportsJson:!0,options:["project","status"],async run(j){let E=Os(j,"project")??t(j.cwd)?.config.projectId,P=Os(j,"status"),C=await j.requireClient().tasks.list({...E?{projectId:E}:{},...P?{status:P}:{}});if(j.json)return j.stdout(J(q(zn.name,C))),0;let R=Array.isArray(C)?C:[];if(R.length===0)return j.stdout(`No tasks.
|
|
121
|
+
`),0;return j.stdout(`${ve(["ID","STATUS","TITLE"],R.map((I)=>[me(I,"id"),me(I,"status"),me(I,"title")||me(I,"description").split(`
|
|
122
|
+
`)[0]||""]))}
|
|
123
|
+
`),0}},Kn={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 E=Dn(j,"task"),P=await j.requireClient().tasks.get(E);if(j.json)return j.stdout(J(q(Kn.name,P))),0;return j.stdout(`${se([["id",me(P,"id")],["status",me(P,"status")],["title",me(P,"title")],["project",me(P,"projectId")],["description",me(P,"description")]])}
|
|
124
|
+
`),0}},Jn={name:"tasks review",summary:"Show the verified review evidence for a task",usage:"Usage: hlix tasks review <task-id> [--json]",supportsJson:!0,args:{min:1,max:1},async run(j){let E=Dn(j,"task"),P=await j.requireClient().tasks.review(E);if(j.json)return j.stdout(J(q(Jn.name,P))),0;return j.stdout(`${JSON.stringify(P,null,2)}
|
|
125
|
+
`),0}},Gn={name:"tasks watch",summary:"Stream a task's status changes until it finishes",usage:["Usage: hlix tasks watch <task-id> [--json]","","Streams the task's server-sent status frames and exits when the task","reaches a terminal status or the server closes the stream.","","With --json, each frame is printed as one envelope per line (JSONL) so a","consumer can read them as they arrive."].join(`
|
|
126
|
+
`),supportsJson:!0,args:{min:1,max:1},async run(j){let E=Dn(j,"task"),P=j.requireClient();for await(let C of P.tasks.stream(E)){let R;try{R=JSON.parse(C.data)}catch{R=C.data}if(j.json)j.stdout(`${JSON.stringify(q(Gn.name,R))}
|
|
127
|
+
`);else{let I=me(R,"status"),_=me(R,"error");j.stdout(_?`error: ${_}
|
|
128
|
+
`:`${I||C.data}
|
|
129
|
+
`)}}return 0}};import{realpath as za}from"node:fs/promises";import{resolve as Ka}from"node:path";import{createHash as kt}from"node:crypto";import{createReadStream as Gi}from"node:fs";import{lstat as Ws,mkdir as qi,readFile as St,readdir as Wi,readlink as Vi,realpath as Vs,stat as Xi,writeFile as Yi}from"node:fs/promises";import{basename as Re,dirname as Zi,join as Gt,relative as Ms,resolve as Us,sep as Qi}from"node:path";import{execFile as ea,spawnSync as ta}from"node:child_process";import Bs from"ignore";import{readFile as Di}from"node:fs/promises";import{join as zi}from"node:path";function Bi(j){let E=j.trim();if(!E||/^[|>[{]/.test(E))return null;let P=E.match(/^(["'])([\s\S]*)\1$/);if(!P&&/^["']/.test(E))return null;return(P?P[2].trim():E.replace(/(?:^|\s)#.*$/,"").trim())||null}function As(j){let E=j.split(/\r?\n/),P=E.findIndex((_)=>/^tasks:\s*(?:#.*)?$/.test(_));if(P===-1)return{tasks:[],partial:/^tasks:\s*\S/m.test(j)};let C=[],R=!1,I=-1;for(let _ of E.slice(P+1)){if(!_.trim()||/^\s*#/.test(_))continue;let O=_.length-_.trimStart().length,T=_.match(/^(\s*-(?:\s+|$))(.*)$/);if(T){if(I!==-1&&O>=I)continue;if(C.push({}),I=T[2]?T[1].length:-1,!T[2])continue}else if(O===0)break;else if(C.length===0)continue;else if(I===-1)I=O;else if(O!==I)continue;let A=(T?T[2]:_.trim()).match(/^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*)$/);if(!A)continue;let N=A[1];if(N!=="name"&&N!=="before"&&N!=="init"&&N!=="command")continue;let F=Bi(A[2]);if(F===null)R=!0;else C[C.length-1][N]=F}return{tasks:C,partial:R}}async function xe(j,E){try{return await Di(zi(j,...E.split("/")),"utf8")}catch(P){if(P.code==="ENOENT")return null;throw P}}function Fs(j){try{let E=j.replace(/(^|[^:\\])\/\/.*$/gm,"$1").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,\s*([}\]])/g,"$1");return JSON.parse(E)}catch{return null}}function Pe(j){if(typeof j==="string"&&j.trim())return[j.trim()];if(Array.isArray(j))return j.flatMap(Pe);if(j&&typeof j==="object")return Object.values(j).flatMap(Pe);return[]}function qn(j){if(!j||typeof j!=="object")return[];return Object.keys(j).filter((E)=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(E))}function Ki(j,E){let P=new Set,C=[/\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(E)C.push(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::[-?][^}]*)?\}/g);for(let R of C)for(let I of j.matchAll(R))P.add(I[1]);return[...P]}function Ji(j,E){if(j.has("bun.lock")||j.has("bun.lockb")||E?.startsWith("bun@"))return"bun install --frozen-lockfile";if(j.has("pnpm-lock.yaml")||E?.startsWith("pnpm@"))return"pnpm install --frozen-lockfile";if(j.has("yarn.lock")||E?.startsWith("yarn@"))return"yarn install --immutable";if(j.has("package-lock.json")||j.has("npm-shrinkwrap.json"))return"npm ci";if(j.has("package.json"))return"npm install";return null}function Ns(j){let E=typeof j==="number"?j:Number(j);return Number.isInteger(E)&&E>0&&E<=65535?E:null}function pe(j,E,P){if(!j.some((C)=>C.path===E&&C.kind===P))j.push({path:E,kind:P})}async function Hs(j,E,P){let C=[],R=[],I=[],_=[],O=new Map,T=new Set,A=new Set,N=[],F={},M=null,G=0,U=await xe(j,".cursor/environment.json");if(U){pe(C,".cursor/environment.json","cursor");let K=Fs(U);if(!K)N.push("Could not parse .cursor/environment.json; it remains quarantined.");else{R.push(...Pe(K.install));let Q=Pe(K.start);if(Q[0])M=Q[0];if(Array.isArray(K.terminals))for(let Y of K.terminals){if(!Y||typeof Y!=="object")continue;let te=Y;if(typeof te.command!=="string"||!te.command.trim())continue;_.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 H=E.has(".devcontainer/devcontainer.json")?".devcontainer/devcontainer.json":E.has("devcontainer.json")?"devcontainer.json":null;if(H){pe(C,H,"devcontainer");let K=Fs(P.get(H)??await xe(j,H)??"");if(!K)N.push(`Could not parse ${H}; it remains quarantined.`);else{R.push(...Pe(K.onCreateCommand),...Pe(K.updateContentCommand),...Pe(K.postCreateCommand));let Q=Pe(K.postStartCommand);if(!M&&Q[0])M=Q[0];for(let Y of qn(K.secrets))T.add(Y);for(let Y of[...qn(K.containerEnv),...qn(K.remoteEnv)])T.add(Y);if(Array.isArray(K.forwardPorts))for(let Y of K.forwardPorts){let te=Ns(Y);if(te)O.set(te,{port:te,visibility:"private"})}}}if(E.has(".gitpod.yml")){pe(C,".gitpod.yml","gitpod");let K=P.get(".gitpod.yml")??await xe(j,".gitpod.yml");if(K===null)N.push("Could not read .gitpod.yml; its task commands were not imported.");else{let Q=As(K);G=Q.tasks.filter((Y)=>Y.before).length;for(let Y of Q.tasks){if(Y.before)R.push(Y.before);if(Y.init)R.push(Y.init);if(!Y.command)continue;if(!M)M=Y.command;else _.push({name:Y.name??"Terminal",command:Y.command})}if(Q.partial)N.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 K of["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml"])if(E.has(K))pe(C,K,"docker");for(let K of["project.toml","nixpacks.toml","railpack.json","Aptfile"])if(E.has(K))pe(C,K,"buildpack");for(let K of["fly.toml","railway.json","render.yaml","vercel.json","netlify.toml"])if(E.has(K))pe(C,K,"platform");let L=P.get("package.json")??await xe(j,"package.json");if(L){pe(C,"package.json","package");try{let K=JSON.parse(L);if(K.engines?.node)F.node=K.engines.node;let Q=Ji(E,K.packageManager);if(Q&&R.length===G)R.push(Q);if(K.scripts?.build&&I.length===0)I.push(`${K.packageManager?.split("@")[0]??(E.has("bun.lock")?"bun":"npm")} run build`);let Y=K.scripts?.dev?`${E.has("bun.lock")?"bun":"npm"} run dev`:null,te=K.scripts?.start?`${E.has("bun.lock")?"bun":"npm"} run start`:Y;if(!M&&te)M=te}catch{N.push("Could not parse package.json for environment discovery.")}}if(E.has("uv.lock"))R.push("uv sync --frozen");else if(E.has("poetry.lock"))R.push("poetry install --no-interaction");else if(E.has("requirements.txt"))R.push("python -m pip install -r requirements.txt");if(E.has("go.mod"))R.push("go mod download");if(E.has("Procfile")){pe(C,"Procfile","procfile");let Q=(P.get("Procfile")??"").split(/\r?\n/).find((Y)=>/^web\s*:/.test(Y));if(Q)M=Q.replace(/^web\s*:\s*/,"").trim()||M}let z=[[".node-version","node"],[".nvmrc","node"],[".python-version","python"]];for(let[K,Q]of z){let Y=(P.get(K)??await xe(j,K))?.trim();if(Y)F[Q]=Y,pe(C,K,"tool-version")}let B=P.get(".tool-versions")??await xe(j,".tool-versions");if(B){pe(C,".tool-versions","tool-version");for(let K of B.split(/\r?\n/)){let[Q,Y]=K.trim().split(/\s+/,2);if(!Y)continue;if(Q==="nodejs")F.node=Y;else if(Q==="python")F.python=Y;else if(Q==="bun")F.bun=Y}}let ee=P.get("mise.toml")??await xe(j,"mise.toml");if(ee){pe(C,"mise.toml","tool-version");for(let K of ee.matchAll(/^\s*(node|python|bun)\s*=\s*["']([^"']+)["']/gm))F[K[1]]=K[2]}for(let[K,Q]of P){let Y=/(?:^|\/)(?:Dockerfile|Procfile)$/i.test(K)||/\.(?:jsonc?|ya?ml|toml|ini|conf|config|env|sh|bash|zsh|fish)$/i.test(K);for(let te of Ki(Q,Y))A.add(te);for(let te of Q.matchAll(/(?:--port(?:=|\s+)|PORT\s*=\s*)(\d{2,5})/g)){let Oe=Ns(te[1]);if(Oe)O.set(Oe,{port:Oe,visibility:"private"})}}if(C.length===0&&E.size>0)pe(C,"repository","detected");let oe=(K)=>[...new Set(K.filter(Boolean))],Te=C.length+R.length+(M?1:0);return{sources:C.sort((K,Q)=>K.path.localeCompare(Q.path)),toolchain:F,install:oe(R),build:oe(I),start:M,terminals:_,ports:[...O.values()].sort((K,Q)=>K.port-Q.port),requiredSecretKeys:[...T].sort(),observedSecretKeys:[...A].sort(),confidence:Te>=4?"high":Te>=2?"medium":"low",warnings:N}}var Ls=2;var Xs=300000,na=25000,ra=52428800,sa=524288000,bt=1e4,Qn="Potential secrets exist in Git history",Jt=1048576,wt=20971520,Ds=[".git/",".hlix/","node_modules/",".next/",".turbo/",".cache/","dist/","build/","coverage/","__pycache__/",".venv/","venv/","target/",".DS_Store"],er="Required project environment value was not found locally: ",oa=/(^|\/)\.env\.(example|sample|template)$/i,ia=/(^|\/)\.env(?:\.[^/]+)?$/i,aa=/(^|\/)(?:\.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,ca=/\.(?:example|sample|template)$/i,la=/(^|\/)\.(?:npmrc|yarnrc(?:\.yml)?|pypirc)$/i,da=/(?:^|\/)(?:__tests__|tests?|fixtures)\/|\.(?:test|spec)\.[^/]+$|\.snap$/i,ua=/\.(?:md|mdx|txt|rst)$/i,pa=/fake|dummy|example|placeholder|unused|changeme|xxxx|redacted|your[_-]|<[^>]*>/i,ma=/^(.)\1+$/,fa=/RegExp\(/,tr="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,}",ga=new RegExp(tr,"g"),ha=/(^|\/)(?:\.mcp\.json|mcp\.json|claude_desktop_config\.json)$/i,ya=/(^|\/)(?:AGENTS\.md|CLAUDE\.md|\.cursorrules|\.github\/copilot-instructions\.md)$/i,wa=/(^|\/)(?:\.agents|\.claude)\/skills\//i,Ys=/-----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,}/,Gd=new RegExp(Ys.source,"g"),va=/\.(?:json|ya?ml|toml|ini|conf|config)$/i,Sa=/(?:^|[,{\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,vt=new Set(["HLIX_AGENT_RUN_ID","HLIX_API_KEY","HLIX_API_URL","HLIX_BASE_URL","HLIX_PROJECT_ID","HLIX_SESSION_TOKEN","HLIX_WORKSPACE_ID"]),Wn="Your hlix credentials were left out of the project's secrets — the platform provides them.",Vn=new Set(["CI","HOME","LANG","LOGNAME","NODE_ENV","OLDPWD","PATH","PORT","PWD","SHELL","SHLVL","TERM","TMPDIR","USER","_"]),ba=100,zs=12;function ka(j){let E=j.slice(0,zs).join(", "),P=j.length-zs;return j.length===1?`Observed environment reference has no local value: ${j[0]}`:`${j.length} observed environment references have no local value: ${E}${P>0?`, +${P} more`:""}`}var ja=250;function qe(j){return j.split(Qi).join("/")}function fe(j){if(j>=1048576)return`${(j/1048576).toFixed(1)} MB`;if(j>=1024)return`${(j/1024).toFixed(1)} KB`;return`${j} bytes`}function Xn(j,E=5){return[...j].sort((P,C)=>C.size-P.size||P.path.localeCompare(C.path)).slice(0,E).map((P)=>`${P.path} (${fe(P.size)})`).join(", ")}function Yn(j,E=5){let P=new Map;for(let C of j){let R=C.indexOf("/"),I=R===-1?".":C.slice(0,R);P.set(I,(P.get(I)??0)+1)}return[...P].sort((C,R)=>R[1]-C[1]||C[0].localeCompare(R[0])).slice(0,E).map(([C,R])=>`${C}/ (${R} files)`).join(", ")}function he(j,E,P=10485760){return ta("git",["-C",j,...E],{encoding:"utf8",timeout:Xs,maxBuffer:P,stdio:["ignore","pipe","pipe"]})}function qt(j,E,P={}){return new Promise((C)=>{ea("git",["-C",j,...E],{encoding:"utf8",timeout:Xs,maxBuffer:P.maxBuffer??10485760,...P.signal?{signal:P.signal}:{}},(R,I)=>{let _=R?.code;C({status:R===null?0:typeof _==="number"?_:1,stdout:typeof I==="string"?I:""})})})}async function Ea(j){let E=kt("sha256");for await(let P of Gi(j))E.update(P);return E.digest("hex")}function Zn(j){if(Array.isArray(j))return`[${j.map(Zn).join(",")}]`;if(j&&typeof j==="object")return`{${Object.entries(j).sort(([E],[P])=>E.localeCompare(P)).map(([E,P])=>`${JSON.stringify(E)}:${Zn(P)}`).join(",")}}`;return JSON.stringify(j)}function Zs(j){let E={};for(let[P,C]of String(j).replace(/^\uFEFF/,"").split(/\r?\n/).entries()){let R=C.trim();if(!R||R.startsWith("#"))continue;let _=(R.startsWith("export ")?R.slice(7).trimStart():R).match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(!_)throw Error(`Invalid dotenv assignment on line ${P+1}`);let O=_[2]??"";if(O.startsWith('"')){if(!O.endsWith('"'))throw Error(`Unclosed dotenv quote on line ${P+1}`);O=O.slice(1,-1).replace(/\\n/g,`
|
|
130
|
+
`).replace(/\\r/g,"\r")}else if(O.startsWith("'")){if(!O.endsWith("'"))throw Error(`Unclosed dotenv quote on line ${P+1}`);O=O.slice(1,-1)}else O=O.replace(/\s+#.*$/,"").trimEnd();E[_[1]]=O}return E}function $a(j,E){return j.split(/(?<=\n)/).filter((P)=>{let C=P.trim(),I=(C.startsWith("export ")?C.slice(7).trimStart():C).match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=/)?.[1];return I===void 0||!E.has(I)}).join("")}function Pa(j){let E=null;for(let P=0;P<j.length;P+=1){let C=j[P];if(C==="\\"&&E!=="single"){if(j[P+1]!=="$")return!0;P+=1;continue}if(C==="'"&&E!=="double"){E=E==="single"?null:"single";continue}if(C==='"'&&E!=="single"){E=E==="double"?null:"double";continue}if(E!=="single"&&(C==="$"||C==="`"))return!0;if(E===null&&(C==="<"||C===">")&&j[P+1]==="(")return!0}return E!==null}function Ca(j){let E={},P=new Set,C=new Set;for(let R of String(j).replace(/^\uFEFF/,"").split(/\r?\n/)){let I=R.trim();if(!I||I.startsWith("#"))continue;let O=(I.startsWith("export ")?I.slice(7).trimStart():I).match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(!O)continue;let T=O[1],A=O[2]??"";if(P.add(T),Pa(A)){delete E[T],C.add(T);continue}try{let F=Zs(`${T}=${A}`)[T];if(F===void 0)throw Error("missing literal");E[T]=A.trimStart().startsWith("'")?F:F.replace(/\\\$/g,"$"),C.delete(T)}catch{delete E[T],C.add(T)}}return{values:E,keys:[...P].sort(),dynamicKeys:[...C].sort()}}async function Ia(j){let E=he(j,["rev-parse","--show-toplevel"]);if(E.status!==0)return!1;try{return await Vs(E.stdout.trim())===j}catch{return!1}}function xa(j,E){if(!E)return new Set;let P=he(j,["ls-files","-z"]);if(P.status!==0)throw Error("Could not enumerate tracked files.");return new Set(P.stdout.split("\x00").filter(Boolean).map(qe))}function Ra(j,E){if(!E)return{files:new Set,directories:[]};let P=he(j,["ls-files","-z","--others","--ignored","--exclude-standard","--directory"]);if(P.status!==0)throw Error("Could not enumerate ignored files.");let C=new Set,R=[];for(let I of P.stdout.split("\x00").filter(Boolean)){let _=qe(I);if(_.endsWith("/"))R.push(_);else C.add(_)}return{files:C,directories:R}}async function _a(j){let E=Bs().add(Ds),P=Bs().add(Ds),C=[];for(let R of[".gitignore",".hlixignore"])try{let I=Gt(j,R),_=await Ws(I);if(_.isFile())P.add(await St(I,"utf8"));else if(_.isSymbolicLink())C.push(R)}catch(I){if(I.code!=="ENOENT")throw I}return{hardMatcher:E,matcher:P,symlinked:C}}function Ks(j){if(ha.test(j))return"mcp";if(wa.test(j))return"skill";if(ya.test(j))return"agent";return null}function Js(j){if(ia.test(j)&&!oa.test(j))return"dotenv";if(aa.test(j))return"credential";return null}function Ta(j){if(j.has("package.json"))return"typescript";if(j.has("pyproject.toml")||j.has("requirements.txt"))return"python";if(j.has("go.mod"))return"go";if(j.has("Cargo.toml"))return"rust";if(j.has("composer.json"))return"php";if(j.has("Gemfile"))return"ruby";return"other"}function Oa(j,E){if(E)return[qe(E)];let P=new Map([[".env",0],[".env.development",1],[".env.local",2],[".env.development.local",3]]),C=j.filter((R)=>P.has(Re(R).toLocaleLowerCase("en-US"))).sort((R,I)=>R.slice(0,-Re(R).length).localeCompare(I.slice(0,-Re(I).length))||P.get(Re(R).toLocaleLowerCase("en-US"))-P.get(Re(I).toLocaleLowerCase("en-US")));return C.length>0?C:j.length===1?[...j]:[]}function Aa(j,E){try{let P=JSON.parse(E);if(!P.mcpServers||typeof P.mcpServers!=="object")return[];return Object.entries(P.mcpServers).map(([C,R])=>{let I=R&&typeof R==="object"?R:{},_=I.type==="http"||I.type==="sse"||I.type==="stdio"?I.type:typeof I.command==="string"?"stdio":typeof I.url==="string"?"http":"unknown",O=I.env&&typeof I.env==="object"?I.env:{};return{sourcePath:j,name:C,transport:_,...typeof I.command==="string"?{command:I.command}:{},...Array.isArray(I.args)&&I.args.every((T)=>typeof T==="string")?{args:I.args}:{},...typeof I.url==="string"?{url:I.url}:{},envKeys:Object.keys(O).sort(),enabled:!1}})}catch{return[]}}function Fa(j){let E=!1,P=!1;for(let C of j.split(/\r?\n/)){let R=C.trim();if(!R||R.startsWith("#")||R.startsWith(";")||R.startsWith("["))continue;let I=R.indexOf("=");if(I===-1)continue;let _=R.slice(0,I).trim().toLowerCase(),O=R.slice(I+1).trim().replace(/^["']|["']$/g,"");if(!O||/^\$(?:\{[^}]*\}|[A-Za-z_][A-Za-z0-9_]*)$/.test(O))continue;if(_.endsWith("_authtoken")||_.endsWith("_password"))return!0;if(_.endsWith("password"))P=!0;else if(_.endsWith("username"))E=!0}return E&&P}async function Na(j,E,P,C){if(ca.test(P))return!1;if(!la.test(P))return!0;let R=await qt(j,["show",`${E}:${P}`],{...C?{signal:C}:{}});return R.status===0&&Fa(R.stdout)}function Ha(j,E,P){let C=j.lastIndexOf("/",E),R=j.indexOf("/",P);return C!==-1&&R!==-1&&!/\s/.test(j.slice(C,E)+j.slice(P,R))}function La(j){if(da.test(j))return"test fixture";if(ua.test(j))return"documentation or pattern definition";return null}function Ma(j,E){let P=null;for(let C of j.split(/\r?\n/))for(let R of C.matchAll(E)){let I=R[0],_=R.index??0,O=fa.test(C)||Ha(C,_,_+I.length)?"documentation or pattern definition":pa.test(I)||ma.test(I)?"placeholder value":null;if(O===null)return null;P??=O}return P}async function Ua(j,E,P,C){let R=La(P);if(R!==null)return R;let I=await qt(j,["show",`${E}:${P}`],{...C?{signal:C}:{}});return I.status===0?Ma(I.stdout,ga):null}async function Gs(j,E,P){let C=[],R="unknown";for(let I of j.split(/\r?\n/)){if(I.startsWith("@@"))R=I.slice(2);else if(I.trim()){let _=qe(I.trim());if(await P(R,_))C.push({commit:R,path:_,reason:E})}if(C.length>=100)break}return C}async function qs(j,E,P={}){if(!E)return{head:null,branch:null,refs:[],commitCount:0,complete:!0,findings:[],blockingFindings:[],waivedReasons:[]};let C=he(j,["rev-parse","HEAD"]).stdout.trim()||null,R=he(j,["symbolic-ref","--short","-q","HEAD"]),I=R.status===0?R.stdout.trim()||null:null,_=Number.parseInt(he(j,["rev-list","--count","--all"]).stdout.trim(),10)||0,O=he(j,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/tags"]),T=O.stdout.split(`
|
|
131
|
+
`).filter(Boolean).map((z)=>{let[B,ee]=z.split("\x00");return{name:B,oid:ee}}).filter(({name:z,oid:B})=>/^refs\/(?:heads|tags)\/.+/.test(z)&&/^[0-9a-f]{40,64}$/.test(B)).sort((z,B)=>z.name.localeCompare(B.name)),A=P.signal,N=A?{signal:A}:{};P.onProgress?.(`history: ${_} commit${_===1?"":"s"}…`);let F=["log","--all",`--max-count=${bt}`,"--pretty=format:@@%H","--name-only"],M=await qt(j,[...F,"--",".env",".env.*","*.pem","*.key",".npmrc","*.tfvars"],N),G=await qt(j,["log","--all",`--max-count=${bt}`,"-G",tr,"--pretty=format:@@%H","--name-only"],N);A?.throwIfAborted();let U=new Map;for(let z of[...await Gs(M.stdout,"sensitive-path",(B,ee)=>Na(j,B,ee,A)),...await Gs(G.stdout,"secret-pattern",async()=>!0)])U.set(`${z.commit}:${z.path}:${z.reason}`,z);let H=[...U.values()].slice(0,100),L=new Map;for(let z of H){if(z.reason!=="secret-pattern")continue;let B=await Ua(j,z.commit,z.path,A);if(B!==null)L.set(z,B)}return P.onProgress?.(`history: ${_} commit${_===1?"":"s"} scanned`),{head:C,branch:I,refs:T,commitCount:_,complete:_<=bt&&T.length<=1000&&O.status===0&&M.status===0&&G.status===0,findings:H,blockingFindings:H.filter((z)=>!L.has(z)),waivedReasons:[...L.values()]}}function Ba(j,E){let P=E?.XDG_CACHE_HOME??(E?.HOME?Gt(E.HOME,".cache"):null);if(!P)return null;return Gt(P,"hlix","history",`${kt("sha256").update(j).digest("hex")}.json`)}async function Da(j,E,P){let C=E?Ba(j,P.environment):null;if(!C)return qs(j,E,P);let R=kt("sha256").update([he(j,["for-each-ref","--format=%(refname)%00%(objectname)"]).stdout,he(j,["rev-parse","HEAD"]).stdout,he(j,["symbolic-ref","--short","-q","HEAD"]).stdout,tr,String(bt)].join("\x00")).digest("hex");try{let _=JSON.parse(await St(C,"utf8"));if(_.key===R&&_.history)return P.onProgress?.(`history: ${_.history.commitCount} commits, unchanged since the last scan`),_.history}catch{}let I=await qs(j,E,P);if(I.complete)try{await qi(Zi(C),{recursive:!0,mode:448}),await Yi(C,JSON.stringify({key:R,history:I}),{mode:384})}catch{}return I}async function ye(j,E={}){let P=await Vs(Us(j));if(!(await Xi(P)).isDirectory())throw Error("Import target must be a directory.");let C=await Ia(P),R=xa(P,C),I=Ra(P,C),{hardMatcher:_,matcher:O,symlinked:T}=await _a(P),A=[],N=[],F=[],M=[],G=[],U=[],H=[],L=[],z=E.envFile?qe(Ms(P,Us(P,E.envFile))):void 0,B=z!==void 0&&z!==""&&z!==".."&&!z.startsWith("../");if(E.envFile&&!B)L.push(`Selected environment file must stay inside the project: ${E.envFile}`);let ee=new Map,oe=new Map,Te=new Map,K=new Map,Q=[],Y=[],te=[],Oe=new Map,Rt=E.maxFiles??na,Nr=E.maxFileBytes??ra,Hr=E.maxTotalBytes??sa,an=0,Ee=0,Lr=()=>A.length+N.length+M.length+G.length,Mr=0,Ur=async(D)=>{let V=await Wi(D,{withFileTypes:!0});V.sort((re,ie)=>re.name.localeCompare(ie.name));for(let re of V){if(E.signal?.throwIfAborted(),Mr+=1,Mr%ja===0)E.onProgress?.(`scanning … ${A.length} files`);let ie=Gt(D,re.name),X=qe(Ms(P,ie));if(re.name===".git"){if(X!==".git")L.push(`Nested Git repository is not supported: ${X}`);continue}let ae=await Ws(ie),un=re.isDirectory()?`${X}/`:X,pn=R.has(X),Kr=!pn&&(O.ignores(un)||I.files.has(X)||I.directories.some((ne)=>un.startsWith(ne))),xo=!pn&&_.ignores(un);if(ae.isSymbolicLink()){if(Kr)continue;if(Lr()>=Rt){L.push(`Project exceeds the ${Rt} file limit, reached at ${X}. Largest folders: ${Yn(A.map((ne)=>ne.path))}. Exclude generated folders with .hlixignore.`);return}if(N.push({path:X,target:await Vi(ie)}),Ks(X)||Js(X))F.push(X);continue}if(re.isDirectory()){if(xo)continue;await Ur(ie);continue}let Ze=Ks(X),Qe=Js(X);if(Kr&&!Ze&&!Qe)continue;if(!re.isFile()){H.push({path:X,reason:"non-regular-file"});continue}if(Lr()>=Rt){L.push(`Project exceeds the ${Rt} file limit, reached at ${X}. Largest folders: ${Yn(A.map((ne)=>ne.path))}. Exclude generated folders with .hlixignore.`);return}if(ae.size>Nr){L.push(`File ${X} is ${fe(ae.size)}, over the ${fe(Nr)} per-file limit. Exclude it with .hlixignore.`);continue}if(an+=ae.size,an>Hr){L.push(`Project files total at least ${fe(an)}, over the ${fe(Hr)} limit. Largest so far: ${Xn([...A,{path:X,size:ae.size}])}. Exclude large files with .hlixignore.`);return}let et=await Ea(ie);if(Ze){if(ae.size>Jt){L.push(`Protected configuration ${X} is ${fe(ae.size)}, over the ${fe(Jt)} per-file limit. Move the large content out of it, or exclude it with .hlixignore.`);continue}let ne=await St(ie);if(Ee+=ne.byteLength,te.push({path:X,size:ne.byteLength}),Ee>wt)continue;if(G.push({path:X,kind:Ze,size:ae.size,sha256:et}),Y.push({path:X,kind:Ze,contentBase64:ne.toString("base64")}),Ze==="mcp")U.push(...Aa(X,ne.toString("utf8")));continue}if(Qe){if(ae.size>Jt){L.push(`Protected file ${X} is ${fe(ae.size)}, over the ${fe(Jt)} per-file limit. Move the large content out of it, or exclude it with .hlixignore.`);continue}let ne=await St(ie);if(Ee+=ne.byteLength,te.push({path:X,size:ne.byteLength}),Ee>wt)continue;let Ce=[],Ae=new Set;if(Qe==="dotenv")try{let At=Zs(ne),Fe={};for(let[$e,Ne]of Object.entries(At)){if(vt.has($e)){Ae.add($e);continue}Fe[$e]=Ne}ee.set(X,Fe),Ce=Object.keys(Fe).sort()}catch{L.push(`Could not parse environment file: ${X}`)}else if(Re(X)===".envrc"){let At=Ca(ne),Fe={},$e=new Set,Ne=[];for(let[ce,Ro]of Object.entries(At.values)){if(vt.has(ce)){Ae.add(ce);continue}if(Vn.has(ce)){Q.push(`Ignored ambient runtime assignment in ${X}: ${ce}`);continue}$e.add(ce),Fe[ce]=Ro}oe.set(X,Fe);for(let ce of At.dynamicKeys){if(vt.has(ce)){Ae.add(ce);continue}if(Vn.has(ce)){Q.push(`Ignored ambient runtime assignment in ${X}: ${ce}`);continue}$e.add(ce),Ne.push(ce)}if(Te.set(X,[...$e].sort()),K.set(X,Ne.sort()),Ce=[...$e].sort(),Ne.length>0)Q.push(`Did not execute dynamic .envrc assignments; collect their resolved local values when available: ${Ne.join(", ")}`)}if(Ae.size>0)Q.push(Wn),ne=Buffer.from($a(ne.toString("utf8"),Ae),"utf8"),et=kt("sha256").update(ne).digest("hex");M.push({path:X,kind:Qe,keys:Ce,size:ne.byteLength,sha256:et}),Y.push({path:X,kind:Qe,contentBase64:ne.toString("base64")});continue}if(ae.size<=1048576){let ne=await St(ie),Ce=ne.toString("utf8");if(Oe.set(X,Ce),Ys.test(Ce)||va.test(X)&&Sa.test(Ce)){if(Ee+=ne.byteLength,te.push({path:X,size:ne.byteLength}),Ee>wt)continue;M.push({path:X,kind:"detected-content",keys:[],size:ae.size,sha256:et}),Y.push({path:X,kind:"detected-content",contentBase64:ne.toString("base64")});continue}}A.push({path:X,size:ae.size,sha256:et,tracked:pn,executable:(ae.mode&73)!==0})}};if(await Ur(P),E.onProgress?.(`scanning … ${A.length} files`),E.onProgress?.(`secrets: ${M.length+G.length} files`),E.signal?.throwIfAborted(),F.length>0){let D=F.slice(0,5).join(", "),V=F.length-5;Q.push(`Imported as symlinks, so no content was read or uploaded for them and the cloud recreates the link: ${D}${V>0?`, +${V} more`:""}`)}for(let D of T)L.push(`Ignore file ${D} is a symlink, so its rules were not applied. Replace it with a regular file inside the project.`);if(Ee>wt)L.push(`Protected project files total ${fe(Ee)}, over the ${fe(wt)} limit. Largest: ${Xn(te)}. Move large assets out of skill and config folders, or add them to .hlixignore.`);if(M.length>2000)L.push(`Project has ${M.length} environment and credential files, over the 2000 limit. Largest: ${Xn(M)}. Exclude the ones the cloud project does not need with .hlixignore.`);if(G.length>5000)L.push(`Project has ${G.length} agent, skill and MCP files, over the 5000 limit. Largest folders: ${Yn(G.map((D)=>D.path))}. Exclude the ones the cloud project does not need with .hlixignore.`);A.sort((D,V)=>D.path.localeCompare(V.path)),N.sort((D,V)=>D.path.localeCompare(V.path)),M.sort((D,V)=>D.path.localeCompare(V.path)),G.sort((D,V)=>D.path.localeCompare(V.path)),U.sort((D,V)=>`${D.sourcePath}:${D.name}`.localeCompare(`${V.sourcePath}:${V.name}`));let cn=Oa([...ee.keys()].sort(),B?z:void 0);if(E.envFile&&B&&!ee.has(cn[0]))L.push(`Selected environment file was not found or is not a dotenv file: ${E.envFile}`);let Ye=new Map;for(let[D,V]of ee)for(let re of Object.keys(V))Ye.set(re,[...Ye.get(re)??[],D]);for(let[D,V]of Te)for(let re of V)Ye.set(re,[...Ye.get(re)??[],D]);let Eo=[...Ye].filter(([,D])=>D.length>1).map(([D,V])=>({key:D,paths:V.sort()})).sort((D,V)=>D.key.localeCompare(V.key)),we={};for(let D of cn)Object.assign(we,ee.get(D)??{});let $o=[...oe.keys()].sort((D,V)=>{if(D===".envrc")return 1;if(V===".envrc")return-1;return D.localeCompare(V)}),ln=new Set;for(let D of $o){let V=new Set(K.get(D)??[]);for(let re of Te.get(D)??[]){if(V.has(re)){delete we[re],ln.add(re);continue}let ie=oe.get(D)?.[re];if(ie!==void 0)we[re]=ie;ln.delete(re)}}let _t=E.historyMode??"abort_on_findings",de=await Da(P,C,E);if(!de.complete&&_t!=="preserve")L.push(`Git history scan exceeded ${bt} commits or failed; import requires explicit --history preserve.`);let Tt=de.waivedReasons;for(let D of[...new Set(Tt)].sort()){let V=Tt.filter((ie)=>ie===D).length,re=V===1;Q.push(`${V} Git history finding${re?"":"s"} did not block this import — ${D}, not ${re?"a real credential":"real credentials"}; --history preserve is not needed for ${re?"it":"them"}.`)}if(de.blockingFindings.length>0&&_t==="abort_on_findings"){let D=de.blockingFindings.length;L.push([`${Qn} (${D} finding${D===1?"":"s"}${D>10?", first 10 shown":""}):`,...de.blockingFindings.slice(0,10).map((V)=>` ${V.commit.slice(0,7)} ${V.path} — ${V.reason}`),...Tt.length>0?[` ${Tt.length} more look like test fixtures, placeholders or documentation (not blocking)`]:[]," Sanitize the repository, or re-run with --history preserve to import it as it is."].join(`
|
|
132
|
+
`))}let Br=new Set(A.map((D)=>D.path)),Po=await Hs(P,Br,Oe),{observedSecretKeys:Co,...ge}=Po;ge.warnings.push(...Q);let Ot=new Set(ge.requiredSecretKeys);for(let D of ln)Ot.add(D);for(let D of U)for(let V of D.envKeys)Ot.add(V);for(let D of vt)if(Ot.delete(D))ge.warnings.push(Wn);ge.requiredSecretKeys=[...Ot].sort();for(let D of ge.requiredSecretKeys){if(we[D]!==void 0)continue;let V=E.environment?.[D];if(V===void 0){L.push(`${er}${D}`);continue}we[D]=V}let dn=[];for(let D of Co){if(vt.has(D)){ge.warnings.push(Wn);continue}if(Vn.has(D))continue;if(we[D]!==void 0)continue;let V=E.environment?.[D];if(V===void 0){dn.push(D);continue}we[D]=V}if(dn.length>0)ge.warnings.push(ka(dn.sort()));ge.warnings=[...new Set(ge.warnings)].sort().slice(0,ba);let Dr={schemaVersion:Ls,rootName:E.rootName??Re(P),stack:Ta(Br),git:{detected:C,head:de.head,branch:de.branch,refs:de.refs,commitCount:de.commitCount,historyScanComplete:de.complete,historyMode:_t},files:A,symlinks:N,secretFiles:M,activeEnvFiles:cn,secretKeys:Object.keys(we).sort(),envCollisions:Eo,quarantinedResources:G,mcpServers:U,historicalSecretFindings:de.blockingFindings,skipped:H,environment:ge,totals:{files:A.length,bytes:A.reduce((D,V)=>D+V.size,0)}},zr=Zn(Dr),Io=kt("sha256").update(zr).digest("hex");return{root:P,manifest:Dr,manifestJson:zr,manifestSha256:Io,secretValues:we,protectedFiles:Y.sort((D,V)=>D.path.localeCompare(V.path)),blocking:[...new Set(L)],blockingHistoryFindings:_t==="abort_on_findings"?de.blockingFindings:[]}}var nr={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(`
|
|
133
|
+
`),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 E=await za(Ka(j.cwd,j.args[0]??".")),P=n({env:j.env,flags:j.flags,cwd:E});if(P.conflict)throw new e("workspace_mismatch",P.conflict);if(!P.workspaceId)throw Error("No workspace selected. Run `hlix auth login --workspace <id>` first.");let C=j.requireClient(E);await C.projects.list();let R=Le(E),I=typeof j.flags.project==="string"?j.flags.project:void 0;if(I&&R?.projectId&&R.projectId!==I)throw new e("workspace_mismatch",`This folder is bound to project ${R.projectId}; refusing to rebind it to ${I}.`);if(I)await C.projects.get(I);let _={...R??{schemaVersion:1,workspaceId:P.workspaceId,apiUrl:P.baseUrl},...I?{projectId:I}:{}};it(E,_);let O=await ye(E,{environment:j.env}),T={root:E,config:_,scan:{files:O.manifest.totals.files,bytes:O.manifest.totals.bytes,secretFiles:O.manifest.secretFiles.map((A)=>A.path),quarantinedResources:O.manifest.quarantinedResources.map((A)=>A.path),blocking:O.blocking}};if(j.json)j.stdout(J(q(nr.name,T)));else if(j.stdout(`Initialized ${E}
|
|
134
|
+
Project: ${_.projectId??"not imported yet"}
|
|
135
|
+
Workspace: ${_.workspaceId}
|
|
136
|
+
`),O.blocking.length)j.stdout(`
|
|
137
|
+
Review before import:
|
|
138
|
+
${O.blocking.map((A)=>`- ${A}`).join(`
|
|
139
|
+
`)}
|
|
140
|
+
`);return 0}};import{createHash as ec}from"node:crypto";import{existsSync as tc,rmSync as nc,rmdirSync as rc}from"node:fs";import{readFile as sc,realpath as oc}from"node:fs/promises";import{basename as ic,join as Vt,resolve as ac}from"node:path";import{createHash as Ja}from"node:crypto";import{createReadStream as Ga}from"node:fs";import{chmod as rr,copyFile as qa,lstat as Qs,mkdir as sr,mkdtemp as Wa,readdir as Va,readlink as Xa,rm as or,symlink as Ya}from"node:fs/promises";import{tmpdir as Za}from"node:os";import{dirname as eo,join as ke}from"node:path";import{spawnSync as jt}from"node:child_process";var Et=300000;function be(j,E){let P=jt("git",["-C",j,...E],{encoding:"utf8",timeout:Et,maxBuffer:20971520,stdio:["ignore","pipe","pipe"]});if(P.status!==0){let C=P.stderr.trim().split(`
|
|
141
|
+
`).at(-1)??"git command failed";throw Error(C)}return P.stdout.trim()}async function to(j){let E=Ja("sha256");for await(let P of Ga(j))E.update(P);return E.digest("hex")}async function Qa(j){for(let E of await Va(j)){if(E===".git")continue;await or(ke(j,E),{recursive:!0,force:!0})}}async function Wt(j){if(j.blocking.length>0)throw Error(`Project scan has blocking findings:
|
|
142
|
+
- ${j.blocking.join(`
|
|
143
|
+
- `)}`);let E=await Wa(ke(Za(),"hlix-snapshot-"));await rr(E,448);let P=ke(E,"repo"),C=ke(E,"source.git"),R=ke(E,"project.bundle");try{if(j.manifest.git.detected){let F=jt("git",["clone","--mirror","--no-hardlinks",j.root,C],{encoding:"utf8",timeout:Et,stdio:["ignore","pipe","pipe"]});if(F.status!==0)throw Error(F.stderr.trim()||"Could not mirror repository.");let M=new Map(be(C,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/tags"]).split(`
|
|
144
|
+
`).filter(Boolean).map((U)=>U.split("\x00",2)));for(let U of j.manifest.git.refs)if(M.get(U.name)!==U.oid)throw Error(`Git ref changed after scan: ${U.name}`);let G=jt("git",["clone","--no-hardlinks",C,P],{encoding:"utf8",timeout:Et,stdio:["ignore","pipe","pipe"]});if(G.status!==0)throw Error(G.stderr.trim()||"Could not create snapshot clone.");if(!j.manifest.git.head)throw Error("Git repository has no HEAD commit.");be(P,["checkout","-B","main",j.manifest.git.head])}else await sr(P,{recursive:!0,mode:448}),be(P,["init","-b","main"]);await Qa(P);for(let F of j.manifest.files){let M=ke(j.root,...F.path.split("/")),G=await Qs(M);if(!G.isFile()||G.isSymbolicLink())throw Error(`Source changed after scan: ${F.path}`);if(G.size!==F.size||await to(M)!==F.sha256)throw Error(`Source changed after scan: ${F.path}`);let U=ke(P,...F.path.split("/"));await sr(eo(U),{recursive:!0,mode:493}),await qa(M,U),await rr(U,F.executable?493:420)}for(let F of j.manifest.symlinks){let M=ke(j.root,...F.path.split("/"));if(await Xa(M).catch(()=>null)!==F.target)throw Error(`Source changed after scan: ${F.path}`);let G=ke(P,...F.path.split("/"));await sr(eo(G),{recursive:!0,mode:493}),await Ya(F.target,G)}be(P,["config","user.name","Hlix Import"]),be(P,["config","user.email","import@hlix.ai"]),be(P,["add","-A"]),be(P,["commit","--allow-empty","-m","chore(hlix): import snapshot"]);let I=be(P,["rev-parse","HEAD"]),_=j.manifest.git.refs.filter((F)=>F.name!=="refs/heads/main");if(_.length>0){let F=jt("git",["-C",P,"update-ref","--stdin"],{encoding:"utf8",timeout:Et,input:_.map((M)=>`update ${M.name} ${M.oid}`).join(`
|
|
145
|
+
`)+`
|
|
146
|
+
`,stdio:["pipe","pipe","pipe"]});if(F.status!==0)throw Error(F.stderr.trim()||"Could not recreate the approved Git refs.")}let O=_.map((F)=>F.name),T=jt("git",["-C",P,"bundle","create",R,"--stdin"],{encoding:"utf8",timeout:Et,input:["refs/heads/main",...O].join(`
|
|
147
|
+
`)+`
|
|
148
|
+
`,stdio:["pipe","pipe","pipe"]});if(T.status!==0)throw Error(T.stderr.trim()||"Could not create the approved Git bundle.");be(P,["bundle","verify",R]),await rr(R,384);let A=(await Qs(R)).size,N=await to(R);return{bundlePath:R,bundleSha256:N,bundleSize:A,commitSha:I,dispose:()=>or(E,{recursive:!0,force:!0})}}catch(I){throw await or(E,{recursive:!0,force:!0}),I}}function $t(j,E){let P=j[E];return typeof P==="string"&&P.trim()?P.trim():void 0}function cc(j){return[Vt(j,".hlix","config.json"),Vt(j,".hlix",".gitignore"),Vt(j,".hlixignore")].filter((E)=>!tc(E))}function no(j,E){for(let P of E)nc(P,{force:!0});if(E.length===0)return;try{rc(Vt(j,".hlix"))}catch{}}var lc=44,ro=(j)=>`${j.padEnd(lc)}\r`;function dc(j,E){return ec("sha256").update(`project-import-v1\x00${j}\x00${E}`).digest("hex")}function uc(j){let E=j.manifest.environment.install,P=j.manifest.secretFiles.length+j.manifest.quarantinedResources.length;if(E.length===0&&P===0&&j.manifest.secretKeys.length===0)return null;let C=["Hlix will upload this project and encrypted protected files to your selected workspace."];if(E.length>0)C.push("Detected cloud setup commands:",...E.map((R)=>`- ${R}`));if(j.manifest.secretKeys.length>0)C.push("Project secret keys available to cloud tasks:",...j.manifest.secretKeys.map((R)=>`- ${R}`));if(j.manifest.quarantinedResources.length>0)C.push("Quarantined resources (preserved but not activated):",...j.manifest.quarantinedResources.map((R)=>`- ${R.kind}: ${R.path}`));if(j.manifest.environment.warnings.length>0)C.push("Environment warnings:",...j.manifest.environment.warnings.map((R)=>`- ${R}`));return C.push("Setup runs inside the isolated Coding Workspace and may access project secrets."),C.join(`
|
|
149
|
+
`)}var Xt={name:"import",summary:"Import a local project into your Hlix workspace",usage:["Usage: hlix import [folder] [options]","","Options:"," --dry-run Scan and report without uploading"," --env-file <path> Override automatic development dotenv precedence"," --history <mode> abort-on-findings (default) or preserve"," --name <name> Cloud project name (defaults to folder name)"," --stack <stack> Override detected stack"," --yes Approve the reviewed upload and cloud setup"," --json Machine-readable output (never contains secret values)"].join(`
|
|
150
|
+
`),supportsJson:!0,options:["dry-run","env-file","history","name","stack","yes"],args:{min:0,max:1},async run(j){if(j.args.length>1)throw Error("import accepts at most one folder.");let E=await oc(ac(j.cwd,j.args[0]??".")),P=n({env:j.env,flags:j.flags,cwd:E});if(P.conflict)throw new e("workspace_mismatch",P.conflict);if(!P.workspaceId||!P.credential)throw new e("workspace_required","No workspace selected. Run `hlix auth login` first.");let C=Le(E);if(C?.projectId)throw new e("already_imported","This folder is already bound to an Hlix project. Use `hlix push`.");let R=$t(j.flags,"history");if(R&&R!=="preserve"&&R!=="abort-on-findings")throw Error("--history must be `abort-on-findings` or `preserve`.");let I=[];if(!C&&j.flags["dry-run"]!==!0)I=cc(E),it(E,{schemaVersion:1,workspaceId:P.workspaceId,apiUrl:P.baseUrl});try{return await pc(j,{root:E,workspaceId:P.workspaceId,apiUrl:P.baseUrl,historyFlag:R})}catch(_){if(j.signal?.aborted)throw no(E,I),new e("cancelled","Import cancelled.");if(_ instanceof e&&_.code==="cancelled")no(E,I);throw _}}};async function pc(j,E){let{root:P,historyFlag:C}=E,R=j.json?void 0:(T)=>j.stderr(ro(T)),I=await ye(P,{...$t(j.flags,"env-file")?{envFile:$t(j.flags,"env-file")}:{},environment:j.env,historyMode:C==="preserve"?"preserve":"abort_on_findings",...R?{onProgress:R}:{},...j.signal?{signal:j.signal}:{}});if(R)j.stderr(`
|
|
151
|
+
`);if(j.signal?.throwIfAborted(),j.flags["dry-run"]!==!0&&I.blocking.length===0){let T=uc(I);if(T&&j.flags.yes!==!0){if(j.json||!j.confirm)throw new e("approval_required","Import needs approval for protected files or cloud setup. Review with `hlix import --dry-run`, then repeat with `--yes`.");if(!await j.confirm(T))throw new e("cancelled","Import cancelled.")}}let _={root:P,name:$t(j.flags,"name")??ic(P),stack:$t(j.flags,"stack")??I.manifest.stack,files:I.manifest.totals.files,bytes:I.manifest.totals.bytes,symlinks:I.manifest.symlinks,activeEnvFiles:I.manifest.activeEnvFiles,secretKeys:I.manifest.secretKeys,protectedFiles:I.manifest.secretFiles.length+I.manifest.quarantinedResources.length,environment:I.manifest.environment,historicalSecretFindings:I.manifest.historicalSecretFindings,quarantinedResources:I.manifest.quarantinedResources,mcpServers:I.manifest.mcpServers,skipped:I.manifest.skipped,blocking:I.blocking,manifestSha256:I.manifestSha256};if(j.flags["dry-run"]===!0){if(j.json)j.stdout(J(q(Xt.name,_)));else{let T=[...I.manifest.secretFiles.map((A)=>`${A.kind}: ${A.path}`),...I.manifest.quarantinedResources.map((A)=>`${A.kind}: ${A.path}`)];j.stdout([`Project: ${_.name}`,`Stack: ${_.stack}`,`Files: ${_.files}`,`Bytes: ${_.bytes}`,`Environment confidence: ${_.environment.confidence}`,`History findings: ${_.historicalSecretFindings.length}`,"","Environment evidence:",..._.environment.sources.length?_.environment.sources.map((A)=>`- ${A.kind}: ${A.path}`):["- none detected"],"","Cloud setup commands:",..._.environment.install.length?_.environment.install.map((A)=>`- ${A}`):["- none detected"],"","Required secret keys:",..._.environment.requiredSecretKeys.length?_.environment.requiredSecretKeys.map((A)=>`- ${A}`):["- none detected"],"","Collected secret keys:",..._.secretKeys.length?_.secretKeys.map((A)=>`- ${A}`):["- none detected"],"","Protected and quarantined paths:",...T.length?T.map((A)=>`- ${A}`):["- none"],"","Environment warnings:",..._.environment.warnings.length?_.environment.warnings.map((A)=>`- ${A}`):["- none"],"","Symlinks (stored as links, targets never read):",..._.symlinks.length?_.symlinks.map((A)=>`- ${A.path} -> ${A.target}`):["- none"],"","Skipped paths:",..._.skipped.length?_.skipped.map((A)=>`- ${A.reason}: ${A.path}`):["- none"],..._.blocking.length?["","Blocking findings:",..._.blocking.map((A)=>`- ${A}`)]:[]].join(`
|
|
152
|
+
`)+`
|
|
153
|
+
`)}return I.blocking.length?1:0}if(I.blocking.length)throw new e("scan_blocked",`Project scan blocked import:
|
|
154
|
+
- ${I.blocking.join(`
|
|
155
|
+
- `)}`,{findings:I.blockingHistoryFindings,fixtureFindings:I.manifest.historicalSecretFindings.length-I.blockingHistoryFindings.length,blocking:I.blocking.filter((T)=>!T.startsWith(Qn))});j.signal?.throwIfAborted();let O=await Wt(I);try{j.signal?.throwIfAborted();let T=j.requireClient(P),A=await T.imports.create({idempotencyKey:dc(I.manifestSha256,O.bundleSha256),name:_.name,stack:_.stack,defaultBranch:"main",historyMode:I.manifest.git.historyMode,manifest:I.manifest,manifestSha256:I.manifestSha256,bundleSha256:O.bundleSha256,bundleSize:O.bundleSize,commitSha:O.commitSha});if(A.import.status==="pending_upload"){if(!A.upload)throw Error(`Import ${A.import.id} is ${A.import.status} but has no upload target.`);await T.imports.uploadBundle(A.upload,new Blob([Uint8Array.from(await sc(O.bundlePath))]),{onProgress:(U,H)=>{if(!j.json)j.stderr(ro(`uploading ${U}/${H} bytes`))}})}let F=(A.import.status==="ready"?{import:A.import}:await T.imports.finalize(A.import.id,{secrets:I.secretValues,protectedFiles:I.protectedFiles})).import,M=F.projectId??F.requestedProjectId;if(!M||!F.revisionId||!F.generation)throw Error("Import completed without project revision metadata.");j.signal?.throwIfAborted(),it(P,{schemaVersion:1,projectId:M,workspaceId:E.workspaceId,apiUrl:E.apiUrl}),at(P,{schemaVersion:1,revisionId:F.revisionId,generation:F.generation,commitSha:O.commitSha,manifestSha256:I.manifestSha256,historyMode:I.manifest.git.historyMode,rootName:I.manifest.rootName});let G={projectId:M,revisionId:F.revisionId,generation:F.generation,commitSha:O.commitSha,files:I.manifest.totals.files,bytes:I.manifest.totals.bytes};if(j.json)j.stdout(J(q(Xt.name,G)));else j.stderr(`
|
|
156
|
+
`),j.stdout(`Imported ${_.name}
|
|
157
|
+
Project ID: ${M}
|
|
158
|
+
Revision: ${F.generation}
|
|
159
|
+
`);return 0}finally{await O.dispose()}}import{spawnSync as mc}from"node:child_process";import{existsSync as fc,mkdirSync as gc,writeFileSync as hc}from"node:fs";import{dirname as yc}from"node:path";function wc(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(`
|
|
160
|
+
`):["# 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(`
|
|
161
|
+
`)}function vc(j){return j.VISUAL?.trim()||j.EDITOR?.trim()||"vi"}var ir={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 (${p.join(", then ")}).`].join(`
|
|
162
|
+
`),supportsJson:!0,options:["edit","global"],async run(j){let E=m({cwd:j.cwd,configDir:".hlix",env:j.env}),P=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 C=P?An(j.env):On(j.cwd,".hlix")?.path??`${j.cwd}/AGENTS.md`;if(!fc(C))gc(yc(C),{recursive:!0}),hc(C,wc(P?"global":"project"),"utf8"),j.stdout(`Created ${C}.
|
|
163
|
+
`);let R=vc(j.env),I=mc(R,[C],{stdio:"inherit"});if(I.error)throw new e("invalid_usage",`Could not run ${R}: ${I.error.message}`);return I.status??0}if(j.json){let C=(R)=>R?{path:R.path,characters:R.content.length}:null;return j.stdout(J(q(ir.name,{user:C(E.global),project:C(E.project)}))),0}return j.stdout(`${g(E,j.cwd)}
|
|
164
|
+
`),0}};var ar={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(`
|
|
165
|
+
`),supportsJson:!0,async run(j){let E=f(j.cwd,c(j.env),{env:j.env});if(j.json)return j.stdout(J(q(ar.name,{instructions:E.instructions.map((P)=>({path:P.path,source:P.source,scope:P.scope,characters:P.content.length,...P.note?{note:P.note}:{}})),skills:E.skills,commands:[...E.commands.map((P)=>({path:P.path,source:P.source,scope:P.scope})),...E.generatedCommands.map((P)=>({path:P.path,source:P.source,scope:P.scope,command:P.name}))],mcpServers:E.mcpServers.map((P)=>({path:P.path,source:P.source,scope:P.scope,name:P.name,transport:"command"in P.config?"stdio":"http"})),subagents:E.subagents.map((P)=>({path:P.path,source:P.source,scope:P.scope,name:P.name,description:P.description,...P.model?{model:P.model}:{}})),skipped:E.skipped}))),0;return j.stdout(_s(E,j.cwd)),0}};var oo=(j)=>j instanceof Error?j.message:String(j),so=(j)=>j.split(/\s*\n\s*/).join(" ").trim();async function Sc(j,E,P,C,R){try{let I=await ye(E,{historyMode:P,environment:j.env,rootName:C});return{files:I.manifest.totals.files,manifestSha256:I.manifestSha256,changed:R?I.manifestSha256!==R:null,blocking:I.blocking,error:null}}catch(I){return{files:null,manifestSha256:null,changed:null,blocking:[],error:oo(I)}}}var cr={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(`
|
|
166
|
+
`),supportsJson:!0,async run(j){let E=n({env:j.env,flags:j.flags,cwd:j.cwd}),P=E.binding,C=P?Mt(P.root):null,R=P?await Sc(j,P.root,C?.historyMode??"preserve",C?.rootName,C?.manifestSha256):null,I=null;if(P?.config.projectId&&E.credential&&!E.conflict)try{let T=(await j.requireClient().revisions.head(P.config.projectId)).revision;I={revisionId:T.id,generation:T.generation,changed:C?T.id!==C.revisionId||T.generation!==C.generation:null,error:null,errorMessage:null}}catch(T){I={revisionId:"",generation:0,changed:null,error:Cn(T).code,errorMessage:T instanceof Se?"no cloud revision yet — `hlix push` uploads this folder as revision 1":oo(T)}}let _={cwd:j.cwd,workspace:{id:E.workspaceId,source:E.workspaceSource},api:{baseUrl:E.baseUrl,source:E.baseUrlSource},credential:{present:E.credential!==null,source:E.credentialSource,path:E.credentialPath},conflict:E.conflict,project:P?{root:P.root,projectId:P.config.projectId??null,workspaceId:P.config.workspaceId,apiUrl:P.config.apiUrl}:null,revision:C?{id:C.revisionId,generation:C.generation,commitSha:C.commitSha}:null,local:R,cloud:I};if(j.json)return j.stdout(J(q(cr.name,_))),0;let O=[["folder",j.cwd],["workspace",E.workspaceId?`${E.workspaceId} (from ${E.workspaceSource})`:"none — run `hlix auth login --workspace <id>`"],["api",`${E.baseUrl} (from ${E.baseUrlSource})`],["credential",Bt(E)??"none — run `hlix auth login`"],["project",P?P.config.projectId??`initialized at ${P.root}, not imported yet`:"none — run `hlix import .` to bind this folder"]];if(C)O.push(["revision",`generation ${C.generation} (${C.revisionId})`]);if(R){if(O.push(["local",R.error?`could not scan: ${R.error}`:R.changed===null?`${R.files} files, no synced base revision`:R.changed?`${R.files} files, modified since the last sync`:`${R.files} files, matches the last sync`]),R.blocking.length>0)O.push(["blocking",R.blocking.join("; ")])}if(I)O.push(["cloud",I.error==="not_found"?so(I.errorMessage??I.error):I.error?`not checked — ${so(I.errorMessage??I.error)}`:I.changed?`generation ${I.generation} available — run \`hlix pull\``:`generation ${I.generation}, up to date`]);if(E.conflict)O.push(["conflict",E.conflict]);return j.stdout(`${se(O)}
|
|
167
|
+
`),0}};import{spawnSync as io}from"node:child_process";var lr={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(`
|
|
168
|
+
`),supportsJson:!0,options:["print","web"],args:{min:0,max:1},async run(j){let E=j.args[0]??t(j.cwd)?.config.projectId;if(!E)throw new e("missing_argument","A project id is required, or run this inside a folder bound to a project.");let P=await j.requireClient().projects.terminal(E);if(j.json)return j.stdout(J(q(lr.name,P))),P.available?0:1;if(!P.available){let _=P.environmentState?` (environment: ${P.environmentState})`:"";throw new e("not_found",`${P.reason??"Terminal unavailable"}${_}`)}let C=j.flags.print===!0,R=j.flags.web===!0;if(C||R&&!P.webTerminalUrl||!R&&!P.sshCommand)return j.stdout(`${se([["ssh",P.sshCommand??"not available"],["browser",P.webTerminalUrl??"not available"]])}
|
|
169
|
+
`),0;if(R){if(io(process.platform==="darwin"?"open":"xdg-open",[P.webTerminalUrl],{stdio:"ignore"}).status!==0)j.stdout(`${P.webTerminalUrl}
|
|
170
|
+
`);return 0}return io("sh",["-c",P.sshCommand],{stdio:"inherit"}).status??1}};import{createHash as Lc}from"node:crypto";import{readFile as Mc,realpath as Uc}from"node:fs/promises";import{createHash as bc}from"node:crypto";import{constants as Yt}from"node:fs";import{chmod as ao,copyFile as kc,lstat as dr,mkdir as jc,mkdtemp as Ec,open as $c,realpath as Pc,rename as Cc,rm as _e,symlink as Ic,writeFile as xc}from"node:fs/promises";import{tmpdir as Rc}from"node:os";import{dirname as po,join as je,relative as _c,resolve as Tc,sep as co}from"node:path";import{spawnSync as Oc}from"node:child_process";var Ac=300000;function mo(j){let E=j;if(typeof E==="string")try{E=JSON.parse(E)}catch{return{}}if(!E||typeof E!=="object")return{};let P=E,C=P.git&&typeof P.git==="object"?P.git:{},R=C.historyMode==="preserve"||C.historyMode==="abort_on_findings"?C.historyMode:void 0,I=typeof P.rootName==="string"&&P.rootName.trim()?P.rootName:void 0;return{historyMode:R,rootName:I}}function fo(j,E){let P=j;if(typeof P==="string")try{P=JSON.parse(P)}catch{return[]}if(!P||typeof P!=="object")return[];let C=P[E];if(!Array.isArray(C))return[];return C.filter((R)=>!!R&&typeof R==="object")}function go(j){return fo(j,"files").flatMap((E)=>typeof E.path==="string"&&typeof E.sha256==="string"?[{path:E.path,sha256:E.sha256}]:[])}function ur(j){return fo(j,"symlinks").flatMap((E)=>typeof E.path==="string"&&typeof E.target==="string"?[{path:E.path,target:E.target}]:[])}function Pt(j,E){let P=Oc("git",["-C",j,...E],{encoding:"utf8",timeout:Ac,maxBuffer:52428800,stdio:["ignore","pipe","pipe"]});if(P.status!==0)throw Error(P.stderr.trim().split(`
|
|
171
|
+
`).at(-1)??"Git command failed");return P.stdout.trim()}function lo(j){return bc("sha256").update(j).digest("hex")}async function Zt(j,E,P){let C=await Pc(j),R=Tc(C,...E.split("/"));if(R!==C&&!R.startsWith(C+co))throw Error(`Protected path escapes the project: ${E}`);let I=_c(C,po(R)),_=C;for(let O of I.split(co).filter(Boolean)){_=je(_,O);try{let T=await dr(_);if(T.isSymbolicLink()&&P){P.push(_);break}if(!T.isDirectory()||T.isSymbolicLink())throw Error(`Protected path crosses a non-directory: ${E}`)}catch(T){if(T.code!=="ENOENT")throw T;if(!P)await jc(_,{mode:448})}}return R}async function uo(j,E,P){let C=await Zt(j,E);try{let _=await dr(C);if(!_.isFile()||_.isSymbolicLink())throw Error(`Refusing to replace non-regular protected file: ${E}`)}catch(_){if(_.code!=="ENOENT")throw _}let R=je(po(C),`.hlix-pull-${crypto.randomUUID()}.tmp`),I=await $c(R,Yt.O_WRONLY|Yt.O_CREAT|Yt.O_EXCL|Yt.O_NOFOLLOW,384);try{await I.writeFile(P),await I.sync()}finally{await I.close()}try{await Cc(R,C)}catch(_){throw await _e(R,{force:!0}),_}}async function Fc(j,E,P){let C=P.length,R=await Zt(j,E,P);if(P.length>C)return;try{let I=await dr(R);if(I.isSymbolicLink()){P.push(R);return}if(!I.isFile())throw Error(`Refusing to replace non-regular project file: ${E}`)}catch(I){if(I.code!=="ENOENT")throw I}}async function ho(j,E,P,C,R){let I=await Ec(je(Rc(),"hlix-pull-"));await ao(I,448);let _=je(I,"project.bundle"),O=je(I,"checkout");try{let T=Buffer.from(await C.arrayBuffer());if(T.byteLength!==P.bundleSize||lo(T)!==P.bundleSha256)throw Error("Downloaded revision bundle failed integrity verification.");if(await xc(_,T,{mode:384}),Pt(I,["clone","--no-hardlinks","--branch","main",_,O]),Pt(O,["bundle","verify",_]),Pt(O,["rev-parse","HEAD"])!==P.commitSha)throw Error("Downloaded revision bundle does not match the cloud commit.");let A=P.manifest,N=new Map;for(let H of[...A.secretFiles,...A.quarantinedResources])N.set(H.path,H);if(R.files.length!==N.size)throw Error("Cloud protected files do not match the revision manifest.");let F=new Map;for(let H of R.files){let L=N.get(H.path),z=Buffer.from(H.contentBase64,"base64");if(z.toString("base64").replace(/=+$/,"")!==H.contentBase64.replace(/=+$/,"")||!L||L.kind!==H.kind||z.byteLength!==L.size||lo(z)!==L.sha256)throw Error(`Cloud protected file failed integrity verification: ${H.path}`);F.set(H.path,z)}let M=ur(P.manifest),G=new Set([...A.files.map((H)=>H.path),...M.map((H)=>H.path),...E.manifest.secretFiles.map((H)=>H.path),...E.manifest.quarantinedResources.map((H)=>H.path),...F.keys()]),U=[];for(let H of[...G].sort())await Fc(j,H,U);for(let[H,L]of F)await uo(O,H,L);for(let H of[...new Set(U)].sort())await _e(H,{force:!0});if(E.manifest.git.detected){Pt(j,["fetch",_,"refs/heads/main"]),Pt(j,["reset","--hard","FETCH_HEAD"]);let H=new Set([...A.files.map((L)=>L.path),...M.map((L)=>L.path)]);for(let L of[...E.manifest.files,...E.manifest.symlinks])if(!H.has(L.path))await _e(je(j,...L.path.split("/")),{force:!0})}else{for(let H of[...E.manifest.files,...E.manifest.symlinks])await _e(je(j,...H.path.split("/")),{force:!0});for(let H of A.files){let L=await Zt(j,H.path);await kc(je(O,...H.path.split("/")),L),await ao(L,H.executable?493:420)}for(let H of M){let L=await Zt(j,H.path);await _e(L,{force:!0}),await Ic(H.target,L)}}for(let H of[...E.manifest.secretFiles,...E.manifest.quarantinedResources])if(!F.has(H.path))await _e(je(j,...H.path.split("/")),{force:!0});for(let[H,L]of F)await uo(j,H,L)}finally{await _e(I,{recursive:!0,force:!0})}}function We(j,E,P){let C=new Map([...go(P.manifest).map((T)=>[T.path,`blob:${T.sha256}`]),...ur(P.manifest).map((T)=>[T.path,`link:${T.target}`])]),R=new Map([...j.manifest.files.map((T)=>[T.path,`blob:${T.sha256}`]),...j.manifest.symlinks.map((T)=>[T.path,`link:${T.target}`])]),I=0,_=0;for(let[T,A]of R){let N=C.get(T);if(N===void 0)I+=1;else if(N!==A)_+=1}let O=0;for(let T of C.keys())if(!R.has(T))O+=1;return{localChanged:!E.manifestSha256||j.manifestSha256!==E.manifestSha256,cloudChanged:P.id!==E.revisionId||P.generation!==E.generation,local:{revisionId:E.revisionId,generation:E.generation},cloud:{revisionId:P.id,generation:P.generation,commitSha:P.commitSha},files:{local:R.size,cloud:C.size,localOnly:I,cloudOnly:O,differing:_}}}function pr(j,E,P){let{localChanged:C,cloudChanged:R}=E;if(j==="push")return R?"conflict":C?"push":"none";if(j==="pull"){if(!R)return"none";return C&&!P?"conflict":"pull"}if(C&&R)return"conflict";return C?"push":R?"pull":"none"}function mr(j,E,P){return j==="pull"&&E.localChanged&&!P}var Nc={push:{push:"Would push the local changes as a new cloud revision.",pull:"",none:"Nothing to push — local matches the last synced revision.",conflict:"Would refuse: the cloud changed since this folder's base revision."},pull:{push:"",pull:"Would replace local files with the cloud revision.",none:"Nothing to pull — the cloud head is the local base revision.",conflict:"Would refuse: local files changed. Re-run with --force to replace them."},sync:{push:"Would push the local changes as a new cloud revision.",pull:"Would pull the cloud revision into this folder.",none:"Already in sync.",conflict:"Would refuse: local and cloud both changed since the last sync."}};function Hc(j,E,P){if(E==="push"&&P.cloud.generation===0)return`Would push ${P.files.local} files as revision 1 — this project has no cloud revision yet.`;return Nc[j][E]}function yo(j,E,P,C){let R=P.files;return[`${j} --dry-run: ${Hc(j,E,P)}`,...C?["Requires --yes (or interactive approval) to execute."]:[],"",se([["local",`generation ${P.local.generation} (${P.local.revisionId})${P.localChanged?" — modified":""}`],["cloud",`generation ${P.cloud.generation} (${P.cloud.revisionId})${P.cloudChanged?" — ahead":""}`],["files",`${R.local} local, ${R.cloud} cloud — ${R.localOnly} local-only, ${R.cloudOnly} cloud-only, ${R.differing} differing`]])].join(`
|
|
172
|
+
`)}function Bc(j,E,P){return Lc("sha256").update(`project-push-v1\x00${j}\x00${E}\x00${P}`).digest("hex")}var Dc={schemaVersion:1,revisionId:"",generation:0,commitSha:""},fr={id:"",generation:0,commitSha:"",manifest:{}};async function nn(j,E){try{return await j.revisions.head(E)}catch(P){if(P instanceof Se)return null;throw P}}async function wo(j,E){let P=await nn(j,E);if(P)return P;throw new e("not_found","This project has no cloud files yet, so there is nothing to pull or push against. Import the folder into a new project with `hlix import`, or create the first revision from the dashboard.")}async function Ve(j,{allowUnsynced:E=!1}={}){let P=t(j);if(!P?.config.projectId)throw new e("not_initialized","This folder is not bound to an imported Hlix project. Run `hlix import .` first.");let C=Mt(P.root)??(E?Dc:null);if(!C)throw new e("not_initialized","This folder is bound to a project but has never been pulled. Run `hlix pull` first.");return{root:await Uc(P.root),config:P.config,state:C}}async function Ct(j,E,P,C){let R=await ye(j,{historyMode:P,environment:E,rootName:C});if(R.blocking.length>0)throw new e("scan_blocked",`Project scan blocked sync:
|
|
173
|
+
- ${R.blocking.join(`
|
|
174
|
+
- `)}`);return R}async function gr(j,E,P,C){let{state:R,config:I}=await Ve(C,{allowUnsynced:!0}),_=j.requireClient(),[O,T]=await Promise.all([Ct(C,j.env,R.historyMode??"preserve",R.rootName),P==="pull"?wo(_,I.projectId):nn(_,I.projectId)]),A=We(O,R,T?.revision??fr),N=pr(P,A,j.flags.force===!0),F=mr(N,A,j.flags.yes===!0);if(j.json)j.stdout(J(q(E,{dryRun:!0,action:N,approvalRequired:F,...A})));else j.stdout(`${yo(P,N,A,F)}
|
|
175
|
+
`);return N==="conflict"?1:0}async function zc(j,E){if(j.flags.yes===!0)return;if(j.json||!j.confirm)throw new e("approval_required","`pull --force` replaces local files. Review with `hlix pull --dry-run`, then repeat with `--yes`.");let P=[`hlix pull --force will replace this folder with cloud revision ${E.cloud.generation}.`,`Local-only files to delete: ${E.files.localOnly}`,`Files to replace with the cloud copy: ${E.files.differing}`,"Local changes that were never pushed cannot be recovered by Hlix."].join(`
|
|
176
|
+
`);if(!await j.confirm(P))throw new e("cancelled","Pull cancelled.")}async function vo(j,E,P,C){let{state:R,config:I}=await Ve(j,{allowUnsynced:!0}),_=E.requireClient(),O=R.historyMode??"preserve",T=P??await Ct(j,E.env,O,R.rootName),A=C??(await nn(_,I.projectId))?.revision??fr;if(A.id!==R.revisionId||A.generation!==R.generation)throw new e("conflict","Cloud changed since the local base. Run `hlix pull` or resolve with `hlix sync`.");if(R.manifestSha256&&T.manifestSha256===R.manifestSha256)return{action:"none",revisionId:R.revisionId,generation:R.generation};let N=await Wt(T);try{let F=await _.revisions.createUpload(I.projectId,{idempotencyKey:Bc(R.revisionId,T.manifestSha256,N.bundleSha256),expectedRevisionId:R.revisionId||null,expectedGeneration:R.generation,manifest:T.manifest,manifestSha256:T.manifestSha256,bundleSha256:N.bundleSha256,bundleSize:N.bundleSize,commitSha:N.commitSha});if(F.revisionUpload.status==="pending_upload"){if(!F.upload)throw Error("Revision upload has no bundle target.");await _.revisions.uploadBundle(F.upload,new Blob([Uint8Array.from(await Mc(N.bundlePath))]),{onProgress:(G,U)=>{if(!E.json)E.stderr(`Uploading ${G}/${U} bytes\r`)}})}let M=await _.revisions.finalize(I.projectId,F.revisionUpload.id,{secrets:T.secretValues,protectedFiles:T.protectedFiles});if(!M.revision)throw Error("Revision finalized without head metadata.");return at(j,{schemaVersion:1,revisionId:M.revision.id,generation:M.revision.generation,commitSha:M.revision.commitSha,manifestSha256:M.revision.manifestSha256,historyMode:O,rootName:R.rootName??T.manifest.rootName}),{action:"push",...M.revision}}finally{await N.dispose()}}async function So(j,E,P,C,R){let{state:I,config:_}=await Ve(j,{allowUnsynced:!0}),O=E.requireClient(),T=I.historyMode??"preserve",A=C??await Ct(j,E.env,T,I.rootName),N=R??(await wo(O,_.projectId)).revision;if(N.id===I.revisionId&&N.generation===I.generation)return{action:"none",revisionId:I.revisionId,generation:I.generation};let F=I.manifestSha256?A.manifestSha256!==I.manifestSha256:(()=>{let{files:B}=We(A,I,N);return B.localOnly+B.differing>0})();if(F&&!P)throw new e("conflict","Local files changed since the last sync. Push them, or use `hlix pull --force` to replace them.");if(F)await zc(E,We(A,I,N));let[M,G]=await Promise.all([O.revisions.downloadBundle(_.projectId,N.id),O.revisions.protectedFiles(_.projectId)]);await ho(j,A,N,M,G);let U=mo(N.manifest),H=U.historyMode??T,L=U.rootName??I.rootName??A.manifest.rootName,z=await Ct(j,E.env,H,L);return at(j,{schemaVersion:1,revisionId:N.id,generation:N.generation,commitSha:N.commitSha,manifestSha256:z.manifestSha256,historyMode:H,rootName:L}),{action:"pull",revisionId:N.id,generation:N.generation,commitSha:N.commitSha}}function hr(j,E,P){if(j.json)j.stdout(J(q(E,P)));else if("action"in P&&P.action==="none")j.stdout(`Already in sync.
|
|
177
|
+
`);else j.stdout(`${String("action"in P?P.action:"sync")} complete.
|
|
178
|
+
`)}var Qt={name:"push",summary:"Push local changes as an immutable cloud revision",usage:["Usage: hlix push [--dry-run] [--json]","","Uploads this folder as the next cloud revision of the bound project.","A project with no cloud revision yet takes this folder as revision 1."," --dry-run Show what would change, upload nothing"," --json Machine-readable output"].join(`
|
|
179
|
+
`),supportsJson:!0,options:["dry-run"],async run(j){if(j.args.length)throw Error("push accepts no positional arguments.");let{root:E}=await Ve(j.cwd,{allowUnsynced:!0});if(j.flags["dry-run"]===!0)return gr(j,Qt.name,"push",E);return hr(j,Qt.name,await vo(E,j)),0}},en={name:"pull",summary:"Pull the cloud head into the local project",usage:["Usage: hlix pull [--force] [--yes] [--dry-run] [--json]",""," --force Replace local changes with the cloud revision"," --yes Skip the confirmation --force otherwise requires"," --dry-run Report the divergence and change nothing"].join(`
|
|
180
|
+
`),supportsJson:!0,options:["force","yes","dry-run"],async run(j){if(j.args.length)throw Error("pull accepts no positional arguments.");let{root:E}=await Ve(j.cwd,{allowUnsynced:!0});if(j.flags["dry-run"]===!0)return gr(j,en.name,"pull",E);return hr(j,en.name,await So(E,j,j.flags.force===!0)),0}},tn={name:"sync",summary:"Reconcile local and cloud changes without guessing conflicts",usage:"Usage: hlix sync [--dry-run] [--json]",supportsJson:!0,options:["dry-run"],async run(j){if(j.args.length)throw Error("sync accepts no positional arguments.");let{root:E,state:P,config:C}=await Ve(j.cwd,{allowUnsynced:!0});if(j.flags["dry-run"]===!0)return gr(j,tn.name,"sync",E);let R=j.requireClient(),[I,_]=await Promise.all([Ct(E,j.env,P.historyMode??"preserve",P.rootName),nn(R,C.projectId)]),O=_?.revision??fr,T=We(I,P,O);if(T.localChanged&&T.cloudChanged)throw new e("conflict","Both local and cloud changed since the last sync. Pull or push explicitly after reviewing the conflict.");let A=T.localChanged?await vo(E,j,I,O):T.cloudChanged?await So(E,j,!1,I,_?.revision):{action:"none",revisionId:P.revisionId,generation:P.generation};return hr(j,tn.name,A),0}};import{lstat as wr,readFile as Kc,realpath as Jc}from"node:fs/promises";import{basename as yr,dirname as Gc,extname as qc,join as rn,parse as bo,resolve as sn}from"node:path";function Xe(j,E){let P=j.flags[E];return typeof P==="string"&&P.trim()?P.trim():void 0}function vr(j){let E=Xe(j,"project");if(E)return{root:j.cwd,projectId:E};return Wc(j.cwd)}function Wc(j){let E=t(j);if(!E?.config.projectId)throw new e("not_initialized","This folder is not bound to an Hlix project. Run `hlix import .` first.");return{root:E.root,projectId:E.config.projectId}}async function Sr(j,E){let P=await wr(j);if(P.isSymbolicLink()||!P.isFile())throw Error(`Refusing to import a non-regular file: ${j}`);if(P.size>E)throw Error(`Import file exceeds ${E} bytes: ${j}`);return{path:await Jc(j),content:await Kc(j,"utf8")}}function br(j,E,P,C){if(j.json)j.stdout(J(q(E,P)));else j.stdout(`${C}
|
|
181
|
+
`)}function Vc(j){let E=/^---\r?\n([\s\S]*?)\r?\n---/.exec(j)?.[1];return(E?/^name:\s*(.+?)\s*$/m.exec(E)?.[1]:void 0)?.replace(/^["']|["']$/g,"").trim()||void 0}var Xc=[rn(".claude","skills"),rn(".agents","skills"),rn(".hlix","skills")];async function Yc(j,E){let P=[sn(j,E),...Xc.map((C)=>sn(j,C,E))];for(let C of P)if(await wr(C).then(()=>!0,()=>!1))return C;throw new e("not_found",`No skill at ${E}. Pass the SKILL.md or its folder, for example .claude/skills/${E}.`)}var kr={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 E=vr(j),P=await Yc(j.cwd,j.args[0]),C=await wr(P);if(C.isSymbolicLink())throw Error(`Refusing to import a symlink: ${P}`);let R=C.isDirectory()?rn(P,"SKILL.md"):P,I=await Sr(R,200000),_=C.isDirectory()?yr(P):yr(R)==="SKILL.md"?yr(Gc(R)):bo(R).name,O=Xe(j,"name")??_;if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(O))throw Error("Skill name must be a lowercase kebab-case slug.");let T=await j.requireClient().resources.importSkill(E.projectId,{slug:O,content:I.content});return br(j,kr.name,T.skill,`Imported skill ${O}`),0}},jr={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 E=vr(j),P=sn(j.cwd,j.args[0]);if(![".md",".mdx"].includes(qc(P).toLowerCase()))throw Error("Agent imports must be Markdown files.");let C=await Sr(P,20000),R=Xe(j,"runtime")??"hlix";if(!["claude-code","codex","cursor-agent","hlix"].includes(R))throw Error("--runtime must be claude-code, codex, cursor-agent, or hlix.");let I=Xe(j,"duty")??"executor";if(I!=="executor"&&I!=="intake")throw Error("--duty must be executor or intake.");let _=Xe(j,"name")??Vc(C.content)??bo(P).name.replace(/[-_]+/g," "),O=await j.requireClient().resources.importAgent(E.projectId,{name:_,instructions:C.content,runtimeKind:R,duty:I});return br(j,jr.name,O.agent,O.agent.duty==="intake"?`Imported agent ${O.agent.name} as this project's intake agent`:`Imported agent ${O.agent.name}`),0}},Er={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 E=vr(j),P=await Sr(sn(j.cwd,j.args[0]),200000),C;try{C=JSON.parse(P.content)}catch{throw Error("MCP config is not valid JSON.")}let R=Object.entries(C.mcpServers??{});if(R.length===0)throw Error("MCP config contains no servers.");let I=Xe(j,"server");if(!I&&R.length>1)throw Error("MCP config contains multiple servers; select one with --server <name>.");let _=I?R.find(([H])=>H===I):R[0];if(!_)throw Error(`MCP server not found: ${I}`);let[O,T]=_,A=T.type==="http"||T.type==="sse"?T.type:typeof T.command==="string"?"stdio":typeof T.url==="string"?"http":null;if(!A)throw Error(`MCP server ${O} has no supported transport.`);if(A==="stdio"&&j.flags["allow-stdio"]!==!0)throw Error("Stdio MCP servers execute a local command in the cloud; repeat with --allow-stdio.");let N=T.env&&typeof T.env==="object"&&!Array.isArray(T.env)?T.env:{},F=T.headers&&typeof T.headers==="object"&&!Array.isArray(T.headers)?T.headers:{};if(Object.values(F).some((H)=>typeof H!=="string"))throw Error(`MCP server ${O} headers must be strings.`);for(let[H,L]of Object.entries(N)){if(typeof L!=="string")continue;let z=/^\$\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(L)?.[1];if(z&&z!==H)throw new e("invalid_usage",`MCP server ${O}: env ${H} references \${${z}}, but a placeholder must be the variable's own name — write "${H}": "\${${H}}" and store the secret as ${H}.`)}let M=Object.values(F).flatMap((H)=>[...H.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((L)=>L[1]));if(Object.keys(F).length>0&&M.length===0)throw Error("MCP remote headers must use ${KEY} placeholders; literal credentials are refused.");let G=/^(?:(?:Bearer|Basic|Token) )?\$\{[A-Za-z_][A-Za-z0-9_]*\}$/i;if(Object.values(F).some((H)=>!G.test(H)))throw Error("MCP remote headers must be ${KEY} or an approved auth scheme followed by ${KEY}.");let U=await j.requireClient().resources.importMcp(E.projectId,{name:O,transport:A,...typeof T.command==="string"?{command:T.command}:{},...Array.isArray(T.args)&&T.args.every((H)=>typeof H==="string")?{args:T.args}:{},...typeof T.url==="string"?{url:T.url}:{},...Object.keys(F).length>0?{headers:F}:{},envKeys:[...new Set([...Object.keys(N),...M])].sort()});return br(j,Er.name,U.mcpServer,`Imported MCP server ${O}`),0}};import{spawnSync as Zc}from"node:child_process";import{chmod as Qc,realpath as el,writeFile as tl}from"node:fs/promises";import{basename as nl,dirname as rl,relative as sl,resolve as jo,sep as ol}from"node:path";var ko=64;function xt(j){let E=t(j.cwd),C=(typeof j.flags.project==="string"?j.flags.project:void 0)??E?.config.projectId;if(!C)throw new e("not_initialized","This folder is not bound to a Hlix project. Run `hlix import .`, or pass --project <id>.");return{projectId:C,root:E?.root??j.cwd}}var It=(j,E)=>typeof j[E]==="string"?j[E]:void 0,$r={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(`
|
|
182
|
+
`),supportsJson:!0,options:["project"],async run(j){let{projectId:E}=xt(j),P=await j.requireClient().secrets.listEntries(E);if(j.json)return j.stdout(J(q($r.name,P))),0;if(P.entries.length===0)j.stdout(`No secrets stored for this project.
|
|
183
|
+
`);else j.stdout(`${ve(["key","source","format","value","updated"],P.entries.map((C)=>[C.key,C.source,C.format||"-",C.maskedValue,C.updatedAt?.slice(0,10)??"-"]))}
|
|
184
|
+
`);for(let C of P.warnings)j.stderr(`warning: ${C}
|
|
185
|
+
`);return 0}},Pr={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(`
|
|
186
|
+
`),supportsJson:!0,options:["from-stdin","source","project"],args:{min:1,max:2},async run(j){let{projectId:E}=xt(j),P=j.args[0],C=j.flags["from-stdin"]===!0;if(C&&j.args.length>1)throw new e("invalid_usage","Pass the value as an argument or with --from-stdin, not both.");if(!C&&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 R;if(C){if(!j.readStdin)throw new e("invalid_usage","--from-stdin is not available in this context.");R=(await j.readStdin()).replace(/\r?\n$/,"")}else R=j.args[1];let I=It(j.flags,"source"),_=await j.requireClient().secrets.upsertEntries(E,{entries:[{key:P,value:R,...I?{source:I}:{}}]});if(j.json)return j.stdout(J(q(Pr.name,_))),_.written>0?0:1;if(_.written===0)throw new e("bad_request",`The store refused ${P}: --source must be a project-relative file path.`);return j.stdout(`${se([["key",P],["source",I??".env"]])}
|
|
187
|
+
`),0}},Cr={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(`
|
|
188
|
+
`),supportsJson:!0,options:["source","project"],args:{min:1,max:1},async run(j){let{projectId:E}=xt(j),P=j.args[0],C=It(j.flags,"source"),R=await j.requireClient().secrets.deleteEntry(E,P,C);if(j.json)return j.stdout(J(q(Cr.name,R))),R.removed>0?0:1;if(R.removed===0)return j.stderr(`No stored secret named ${P}${C?` in ${C}`:""}.
|
|
189
|
+
`),1;return j.stdout(`Removed ${R.removed} entr${R.removed===1?"y":"ies"} for ${P}.
|
|
190
|
+
`),0}},on={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(`
|
|
191
|
+
`),supportsJson:!0,options:["project"],args:{min:0,max:64},async run(j){let{projectId:E,root:P}=xt(j),C=await ye(P,{historyMode:"preserve",environment:j.env}),R=C.blocking.filter((F)=>!F.startsWith(er));if(R.length>0)throw new e("scan_blocked",`Project scan blocked the import:
|
|
192
|
+
- ${R.join(`
|
|
193
|
+
- `)}`);let I=C.protectedFiles.filter((F)=>F.kind==="dotenv"||F.kind==="credential"),_=await el(j.cwd),O=j.args.map((F)=>sl(C.root,jo(_,F)).split(ol).join("/")),T=O.filter((F)=>!I.some((M)=>M.path===F));if(T.length>0)throw new e("invalid_usage",`Not a secret file in this project: ${T.join(", ")}`);let A=O.length>0?I.filter((F)=>O.includes(F.path)):I;if(A.length===0)return j.stdout(j.json?J(q(on.name,{imported:[],skipped:[],warnings:[],written:0,rejected:[]})):`No secret files found in this project.
|
|
194
|
+
`),0;if(A.length>ko)throw new e("invalid_usage",`${A.length} secret files exceeds the ${ko} the store accepts in one request. Name the files to import, a batch at a time.`);let N=await j.requireClient().secrets.importFiles(E,A.map((F)=>({path:F.path,contentBase64:F.contentBase64})));if(j.json)return j.stdout(J(q(on.name,N))),0;if(N.imported.length>0)j.stdout(`${ve(["source","format","stored"],N.imported.map((F)=>[F.path,F.format||"-",F.kind==="file"?"as file":`${F.entries} entr${F.entries===1?"y":"ies"}`]))}
|
|
195
|
+
`);if(j.stdout(`${N.written} value${N.written===1?"":"s"} stored.
|
|
196
|
+
`),N.imported.some((F)=>F.kind!=="file"))j.stdout(`Each imported file replaced what the store held under its path; keys the file no longer has are gone.
|
|
197
|
+
`);for(let F of N.skipped)j.stderr(`skipped ${F.path}: ${F.reason}
|
|
198
|
+
`);for(let F of N.warnings)j.stderr(`warning: ${F}
|
|
199
|
+
`);for(let F of N.rejected)j.stderr(`rejected ${F}: the store refused its source path
|
|
200
|
+
`);return 0}};function il(j){return Zc("git",["-C",rl(j),"ls-files","--error-unmatch","--",nl(j)],{encoding:"utf8",stdio:["ignore","pipe","pipe"]}).status===0}var Ir={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(`
|
|
201
|
+
`),supportsJson:!0,options:["source","format","out","project"],async run(j){let{projectId:E}=xt(j),P=It(j.flags,"source"),C=It(j.flags,"format"),R=It(j.flags,"out"),I=R===void 0?void 0:jo(j.cwd,R);if(I!==void 0&&il(I))throw new e("invalid_usage",`Refusing to overwrite a git-tracked file with secret values: ${I}`);let _=await j.requireClient().secrets.exportEntries(E,{...P?{source:P}:{},...C?{format:C}:{}});if(I!==void 0)await tl(I,_,{mode:384}),await Qc(I,384);if(j.json)return j.stdout(J(q(Ir.name,{source:P??null,format:C??null,out:I??null,bytes:Buffer.byteLength(_),...I===void 0?{content:_}:{}}))),0;if(I===void 0)j.stdout(_);else j.stdout(`${se([["wrote",I],["mode","0600"],["bytes",String(Buffer.byteLength(_))]])}
|
|
202
|
+
`);return 0}};function Rr(j){let E=j.flags.project;if(typeof E==="string"&&E)return E;return t(j.cwd)?.config.projectId??void 0}function xr(j,E){let P=j[E];if(typeof P!=="string"||P.trim()==="")throw new e("missing_argument",`--${E} is required.`);return P}var _r={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(`
|
|
203
|
+
`),supportsJson:!0,options:["title","description"],args:{min:1,max:1},async run(j){let E=j.args[0],P=xr(j.flags,"title"),C=xr(j.flags,"description"),R=await j.requireClient().cycles.propose({projectId:E,title:P,description:C});if(j.json)return j.stdout(J(q(_r.name,R))),0;return j.stdout(`${se([["project",E],["title",P],["status",R.adopted?"adopted — the project is planning it now":"recorded — it will be planned on the next pass"]])}
|
|
204
|
+
`),0}},Tr={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(`
|
|
205
|
+
`),supportsJson:!0,options:["title","description"],args:{min:1,max:1},async run(j){let E=j.args[0],P=xr(j.flags,"description"),C=typeof j.flags.title==="string"?j.flags.title:void 0,R=await j.requireClient().tasks.create({projectId:E,description:P,...C?{title:C}:{}});if(j.json)return j.stdout(J(q(Tr.name,R))),0;return j.stdout(`${se([["task",R.id],["project",E],["status",R.status??"queued"],["note","not started — dispatch with `hlix cycles create`"]])}
|
|
206
|
+
`),0}},Or={name:"harness get",summary:"Show which coder runs, and which setting chose it",usage:["Usage: hlix harness get [project-id] [--project <id>] [--json]","","With a project id — or from a bound folder — what that project would run.","Otherwise the workspace-wide answer. `source` names the setting that","decided: a project preference, the workspace preference, or the system","default."].join(`
|
|
207
|
+
`),supportsJson:!0,options:["project"],args:{min:0,max:1},async run(j){let E=j.args[0]??Rr(j),P=j.requireClient(),C=E?await P.modelConfig.resolvedProjectHarness(E):await P.modelConfig.resolvedHarness();if(j.json)return j.stdout(J(q(Or.name,C))),0;return j.stdout(`${se([["scope",E?`project ${E}`:"workspace"],["harness",C.harness],["source",C.source]])}
|
|
208
|
+
`),0}},Ar={name:"harness set",summary:"Choose the coder a project or the workspace runs",usage:[`Usage: hlix harness set <${r.join("|")}> [project-id] [--org] [--json]`,"","With a project id, sets that project's preference. With --org, the","workspace-wide one that projects fall back to. This is a PERSISTENT server","setting that every future run on that scope uses, and it is audited.","","It is not the same thing as the local `harness` config key, which only","picks the coder Hlix Code spawns on this machine."].join(`
|
|
209
|
+
`),supportsJson:!0,options:["org"],args:{min:1,max:2},async run(j){let E=j.args[0];if(!r.includes(E))throw new e("invalid_usage",`harness must be one of ${r.join(", ")}; got "${E}".`);let P=j.flags.org===!0,C=j.args[1]??(P?void 0:Rr(j));if(C&&P)throw new e("invalid_usage","Name a project or pass --org, not both: they are different scopes.");if(!C&&!P)throw new e("invalid_usage","Name the project to set, or pass --org for the whole workspace.");let R=j.requireClient(),I=C?await R.modelConfig.setProjectHarness(C,E):await R.modelConfig.setHarness(E);if(j.json)return j.stdout(J(q(Ar.name,I))),0;return j.stdout(`${se([["scope",C?`project ${C}`:"workspace"],["harness",E]])}
|
|
210
|
+
`),0}},Fr={name:"harness clear",summary:"Remove a harness preference so the scope below it decides",usage:["Usage: hlix harness clear [project-id] [--org] [--json]","","With a project id, drops that project's preference so it inherits the","workspace's answer (or the system default). With --org, drops the","workspace-wide one. Audited, like every write on this setting.","","Answers `not_found` when that scope had no preference to clear — the","setting is already off, and saying so beats reporting a change that was","never made. Check the result with `hlix harness get`."].join(`
|
|
211
|
+
`),supportsJson:!0,options:["org"],args:{min:0,max:1},async run(j){let E=j.flags.org===!0,P=j.args[0]??(E?void 0:Rr(j));if(P&&E)throw new e("invalid_usage","Name a project or pass --org, not both: they are different scopes.");if(!P&&!E)throw new e("invalid_usage","Name the project to clear, or pass --org for the whole workspace.");let C=j.requireClient(),R=P?await C.modelConfig.clearProjectHarness(P):await C.modelConfig.clearHarness();if(j.json)return j.stdout(J(q(Fr.name,R))),0;return j.stdout(`${se([["scope",P?`project ${P}`:"workspace"],["harness","cleared — the scope below decides now"]])}
|
|
212
|
+
`),0}};var a=[Fn,Nn,Ge,cr,lr,ar,ir,Hn,Ln,Mn,nr,Xt,tn,en,Qt,kr,jr,Er,$r,Pr,Cr,on,Ir,Un,Bn,zn,Kn,Jn,Gn,Tr,_r,Or,Ar,Fr];
|
|
213
|
+
export{e,k,t,n,o,s,l,i,r,h,d,y,u,c,w,p,m,v,g,f,b,S,x,a};
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{k,t,o,s,a}from"./index-
|
|
2
|
+
import{k,t,o,s,a}from"./index-8g4x8tv8.js";import{createRequire as h}from"node:module";var d=h(import.meta.url);import{emitKeypressEvents as T}from"node:readline";import{createInterface as f}from"node:readline/promises";async function l(e){if(!process.stdin.isTTY||!process.stdin.setRawMode)throw Error("Interactive login requires a terminal. Set HLIX_API_KEY for CI.");return process.stderr.write(e),T(process.stdin),process.stdin.setRawMode(!0),process.stdin.resume(),new Promise((r,n)=>{let i="",m=()=>{process.stdin.off("keypress",c),process.stdin.setRawMode(!1),process.stdin.pause(),process.stderr.write(`
|
|
3
3
|
`)},c=(u,p)=>{if(p.ctrl&&p.name==="c"||p.name==="escape"){m(),n(Error("Login cancelled."));return}if(p.name==="return"||p.name==="enter"){m(),r(i);return}if(p.name==="backspace"){i=i.slice(0,-1);return}if(u&&!p.ctrl)i+=u};process.stdin.on("keypress",c)})}async function w(e,r){if(!process.stdin.isTTY||!process.stderr.isTTY)throw Error("Interactive selection requires a terminal. Pass --workspace <id>.");let n=f({input:process.stdin,output:process.stderr});try{for(let i=0;i<3;i+=1){let m=(await n.question(e)).trim(),c=Number(m);if(Number.isInteger(c)&&c>=1&&c<=r)return c-1;process.stderr.write(`Enter a number between 1 and ${r}.
|
|
4
4
|
`)}throw Error("No workspace selected.")}finally{n.close()}}async function g(e){if(!process.stdin.isTTY||!process.stderr.isTTY)throw Error("Interactive approval requires a terminal. Review with --dry-run, then pass --yes.");let r=f({input:process.stdin,output:process.stderr});try{let n=(await r.question(`${e}
|
|
5
|
-
Continue? [y/N] `)).trim().toLowerCase();return n==="y"||n==="yes"}finally{r.close()}}import{readFileSync as b,realpathSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";function x(){if(d.main==d.module===!0)return!0;let e=process.argv[1];if(!e)return!1;try{return y(e)===y(v(import.meta.url))}catch{return!1}}var C={"-h":"--help","-v":"--version"};function S(e){return e.map((r)=>C[r]??r)}function P(e){let r=e[0];if(r===void 0)return!1;if(r in C||r==="--help"||r==="--version")return!0;if(r==="code")return!1;return!r.startsWith("-")}function E(e,r){if(P(e))return r.cli(S(e));return r.code(e[0]==="code"?e.slice(1):e)}if(x()){let e=await E(process.argv.slice(2),{cli:(r)=>s(a,r,{stdout:(n)=>process.stdout.write(n),stderr:(n)=>process.stderr.write(n),env:process.env,readSecret:l,confirm:g,...process.stdin.isTTY&&process.stderr.isTTY?{promptChoice:w}:{},readStdin:async()=>b(0,"utf8")}),code:async(r)=>(await import("./main-
|
|
5
|
+
Continue? [y/N] `)).trim().toLowerCase();return n==="y"||n==="yes"}finally{r.close()}}import{readFileSync as b,realpathSync as y}from"node:fs";import{fileURLToPath as v}from"node:url";function x(){if(d.main==d.module===!0)return!0;let e=process.argv[1];if(!e)return!1;try{return y(e)===y(v(import.meta.url))}catch{return!1}}var C={"-h":"--help","-v":"--version"};function S(e){return e.map((r)=>C[r]??r)}function P(e){let r=e[0];if(r===void 0)return!1;if(r in C||r==="--help"||r==="--version")return!0;if(r==="code")return!1;return!r.startsWith("-")}function E(e,r){if(P(e))return r.cli(S(e));return r.code(e[0]==="code"?e.slice(1):e)}if(x()){let e=await E(process.argv.slice(2),{cli:(r)=>s(a,r,{stdout:(n)=>process.stdout.write(n),stderr:(n)=>process.stderr.write(n),env:process.env,readSecret:l,confirm:g,...process.stdin.isTTY&&process.stderr.isTTY?{promptChoice:w}:{},readStdin:async()=>b(0,"utf8")}),code:async(r)=>(await import("./main-g9zc6npj.js")).runHlixCode(r)});process.exit(e)}export{a as COMMANDS,k as JSON_SCHEMA_VERSION,o as clientFor,E as dispatch,t as findProjectBinding,P as isCliInvocation,S as normalizeCliArgv,s as runCli};
|