@hlix/cli 0.5.0 → 0.5.2

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