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