@hlix/cli 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -195
- package/README.md +21 -10
- package/THIRD_PARTY_NOTICES +86 -1
- package/dist/index-619ayaee.js +130 -0
- package/dist/index-vfqh17y6.js +3 -0
- package/dist/index.js +3 -4700
- package/dist/main-ct6p55pt.js +18 -0
- package/dist/package-12m4e2y1.js +2 -0
- package/package.json +22 -20
- package/skills/hlix/SKILL.md +54 -4
- package/dist/chunk-FYS2JH42.js +0 -31
- package/dist/package-WT5SD5LO.js +0 -88
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{l as wo}from"./index-vfqh17y6.js";class y extends Error{code;constructor(e,t){super(t);this.name="CliError",this.code=e}}var Ys=1,j=(e,t)=>({schemaVersion:1,command:e,data:t}),be=(e,t)=>({schemaVersion:1,command:e,error:t});function v(e){return`${JSON.stringify(e,null,2)}
|
|
3
|
+
`}function R(e){let t=Math.max(0,...e.map(([n])=>n.length));return e.map(([n,r])=>`${n.padEnd(t)} ${r}`).join(`
|
|
4
|
+
`)}function ae(e,t){let n=e.map((o,s)=>Math.max(o.length,...t.map((i)=>(i[s]??"").length))),r=(o)=>o.map((s,i)=>s.padEnd(n[i])).join(" ").trimEnd();return[r(e),r(n.map((o)=>"-".repeat(o))),...t.map(r)].join(`
|
|
5
|
+
`)}import{statSync as to}from"node:fs";import{dirname as no,resolve as ro}from"node:path";import{closeSync as wt,constants as Se,existsSync as Ye,fsyncSync as In,lstatSync as vt,mkdirSync as zr,openSync as _n,readFileSync as On,renameSync as Dr,statSync as Rn,unlinkSync as Tn,writeFileSync as qr}from"node:fs";import{homedir as Jr}from"node:os";import{dirname as Gr,join as kt}from"node:path";function ce(e=process.env){let t=e.HLIX_CONFIG_HOME??e.XDG_CONFIG_HOME??kt(Jr(),".config");return kt(t,"hlix","credentials.json")}function An(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(On(ce(e),"utf8"));return n.apiKey&&n.baseUrl?n:null}catch{return null}}function Hn(e=process.env){let t=ce(e);return Ye(t)?t:null}function bt(e=process.env){let t=ce(e);if(!Ye(t))return{path:t,removed:!1,reason:"absent"};let n=vt(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&&Rn(t).uid!==r)throw Error("Refusing to remove a credential file owned by another user.");let o;try{o=JSON.parse(On(t,"utf8"))}catch{o=null}let s=o;if(!s||typeof s.apiKey!=="string"||typeof s.baseUrl!=="string")throw Error(`Refusing to remove ${t}: it is not a credential written by this CLI.`);return Tn(t),{path:t,removed:!0,reason:"removed"}}function Fn(e,t=process.env){let n=ce(t),r=Gr(n);if(zr(r,{recursive:!0,mode:448}),vt(r).isSymbolicLink())throw Error("Refusing to write credentials through a symlinked directory.");if(Ye(n)){let i=vt(n);if(i.isSymbolicLink()||!i.isFile())throw Error("Refusing to replace a credential path that is not a regular file.");let a=process.getuid?.();if(a!==void 0&&Rn(n).uid!==a)throw Error("Refusing to replace a credential file owned by another user.")}let o=kt(r,`.credentials.${process.pid}.${crypto.randomUUID()}.tmp`),s;try{s=_n(o,Se.O_WRONLY|Se.O_CREAT|Se.O_EXCL|Se.O_NOFOLLOW,384),qr(s,`${JSON.stringify(e,null,2)}
|
|
6
|
+
`,"utf8"),In(s),wt(s),s=void 0,Dr(o,n);let i=_n(r,Se.O_RDONLY);try{try{In(i)}catch(a){let c=a.code;if(c!=="EINVAL"&&c!=="ENOTSUP")throw a}}finally{wt(i)}}catch(i){if(s!==void 0)wt(s);if(Ye(o))Tn(o);throw i}return n}import{constants as Ze,existsSync as Qe,lstatSync as Ln,mkdirSync as Wr,openSync as Vr,closeSync as Nn,fsyncSync as Xr,readFileSync as Un,renameSync as Yr,unlinkSync as Zr,writeFileSync as St}from"node:fs";import{dirname as Qr,join as je,resolve as et}from"node:path";function eo(e){if(!Qe(e))return;let t=Ln(e);if(t.isSymbolicLink()||!t.isFile())throw Error(`Refusing to replace a non-regular Hlix file: ${e}`)}function Ee(e,t){let n=Qr(e);if(Wr(n,{recursive:!0,mode:448}),Ln(n).isSymbolicLink())throw Error(`Refusing to write through a symlinked Hlix directory: ${n}`);eo(e);let r=je(n,`.hlix-${process.pid}-${crypto.randomUUID()}.tmp`),o;try{o=Vr(r,Ze.O_WRONLY|Ze.O_CREAT|Ze.O_EXCL|Ze.O_NOFOLLOW,384),St(o,`${JSON.stringify(t,null,2)}
|
|
7
|
+
`,"utf8"),Xr(o),Nn(o),o=void 0,Yr(r,e)}catch(s){if(o!==void 0)Nn(o);if(Qe(r))Zr(r);throw s}}function Pe(e){return je(et(e),".hlix","config.json")}function Mn(e){return je(et(e),".hlix","state.json")}function le(e){try{let t=JSON.parse(Un(Pe(e),"utf8"));return t.schemaVersion===1&&t.workspaceId&&t.apiUrl?t:null}catch{return null}}function Ce(e,t){Ee(Pe(e),t);let n=je(et(e),".hlix",".gitignore");if(!Qe(n))St(n,`state.json
|
|
8
|
+
`,{mode:420,flag:"wx"});let r=je(et(e),".hlixignore");if(!Qe(r))St(r,`# Additional project-local paths to exclude from Hlix snapshots.
|
|
9
|
+
`,{mode:420,flag:"wx"})}function $e(e,t){Ee(Mn(e),t)}function tt(e){try{let t=JSON.parse(Un(Mn(e),"utf8"));return t.schemaVersion===1&&t.revisionId&&t.generation>0?t:null}catch{return null}}var jt="https://server.hlix.ai";function N(e){let t=ro(e);for(;;){let n=le(t);if(n)return{root:t,config:n};let r=no(t);if(r===t)return null;t=r}}function Kn(e){try{return to(e).isDirectory()}catch{return!1}}function nt(e){if(typeof e!=="string")return;let t=e.trim();return t?t:void 0}var Bn=(e,t)=>e.replace(/\/+$/,"")===t.replace(/\/+$/,"");function B(e){let{env:t,flags:n,cwd:r}=e,o=N(r),s=An(t),i=s?t.HLIX_API_KEY||t.HLIX_SESSION_TOKEN?"env":"file":null,a=i==="file"?s:null,c=nt(n["base-url"]),l=nt(t.HLIX_BASE_URL),p=nt(n.workspace),d=nt(t.HLIX_WORKSPACE_ID),u=c??l??o?.config.apiUrl??a?.baseUrl??jt,m=c?"flag":l?"env":o?.config.apiUrl?"project":a?.baseUrl?"credential":"default",h=p??d??o?.config.workspaceId??a?.organizationId??null,k=p?"flag":d?"env":o?.config.workspaceId?"project":a?.organizationId?"credential":null;return{baseUrl:u,baseUrlSource:m,workspaceId:h,workspaceSource:k,credential:s,credentialSource:i,credentialPath:ce(t),binding:o,conflict:oo(o,{flagBaseUrl:c,envBaseUrl:l,flagWorkspace:p,envWorkspace:d})}}function oo(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&&!Bn(t.flagBaseUrl,e.config.apiUrl))return`${n} ${e.config.apiUrl}, but --base-url names ${t.flagBaseUrl}. ${r}`;if(t.envBaseUrl&&!Bn(t.envBaseUrl,e.config.apiUrl))return`${n} ${e.config.apiUrl}, but HLIX_BASE_URL names ${t.envBaseUrl}. ${r}`;return null}import{resolve as vo}from"node:path";import{parseArgs as ko}from"node:util";import so from"openapi-fetch";function Et(e){return so({baseUrl:e.baseUrl,headers:e.headers,fetch:e.fetch})}var xe=(e)=>({kind:"apiKey",apiKey:e});var Pt=(e)=>({kind:"bearer",token:e});function io(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 ao(e){return e?{"X-Organization-Id":e}:{}}function zn(e,t){return{...io(e),...ao(t)}}function co(e){if(typeof e!=="object"||e===null)return null;let{error:t}=e;return typeof t==="string"?t:null}class L 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 Ie extends L{issues;constructor(e,t,n){super(e,t);this.issues=n}}class _e extends L{}class Oe extends L{}class Re extends L{}class Te extends L{}class Ae extends L{}class He extends L{retryAfter;constructor(e,t,n){super(e,t);this.retryAfter=n}}class Fe extends L{}class Ne extends L{}class de extends Error{method;url;constructor(e,t){super(e,{cause:t.cause});this.name="HlixTransportError",this.method=t.method,this.url=t.url}}function lo(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 po(e){let t=e.get("retry-after");if(!t)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n:null}function Le(e,t,n){let r={status:e.status,body:t,requestId:e.headers.get("x-request-id"),method:n.method,url:n.url},o=co(t),s=`${n.method} ${n.url} failed with ${e.status}`,i=lo(t);if(i)return new Ie(`${n.method} ${n.url}: request body failed validation`,r,i);let a=o??s;switch(e.status){case 400:return new _e(a,r);case 401:return new Oe(a,r);case 403:return new Re(a,r);case 404:return new Te(a,r);case 409:return new Ae(a,r);case 429:return new He(a,r,po(e.headers));case 501:return new Fe(a,r);default:return e.status>=500?new Ne(a,r):new L(a,r)}}var Dn=new Set(["GET","HEAD","PUT","DELETE","OPTIONS","TRACE"]);function rt(e){return Dn.has(e.toUpperCase())}var uo=new Set([429,500,502,503,504]);function mo(e){return uo.has(e)}var Ct={attempts:3,baseDelayMs:200,maxDelayMs:5000};function $t(e,t,n,r=Math.random){if(n!==null)return Math.min(n*1000,t.maxDelayMs);let o=Math.min(t.baseDelayMs*2**e,t.maxDelayMs);return Math.round(r()*o)}function xt(e){if(!rt(e.method))return!1;if(e.attempt+1>=e.policy.attempts)return!1;return e.status===null||mo(e.status)}var fo=(e)=>new Promise((t)=>setTimeout(t,e));function go(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 qn(e){let{base:t,policy:n}=e,r=e.sleep??fo,o=e.random??Math.random;return async(s)=>{let i=s.method.toUpperCase(),a=rt(i)?s.clone():null;for(let c=0;;c+=1){let l=c===0?s:a.clone(),p;try{p=await t(l)}catch(d){if(!a||!xt({method:i,attempt:c,policy:n,status:null}))throw new de(`${i} ${s.url}: ${d instanceof Error?d.message:String(d)}`,{method:i,url:s.url,cause:d});await r($t(c,n,null,o));continue}if(!xt({method:i,attempt:c,policy:n,status:p.status}))return p;if(!a)return p;await r($t(c,n,go(p),o))}}}function w(e,t){if(e.response.ok)return e.data;throw Le(e.response,e.error??e.data,t)}var Ue=(e)=>typeof e==="string"?e:"";function It(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:Ue(n.delta)};case"reasoning":return{type:"reasoning",delta:Ue(n.delta)};case"on_tool_start":return{type:"on_tool_start",name:Ue(n.name),input:n.input};case"on_tool_end":return{type:"on_tool_end",name:Ue(n.name),output:n.output};case"error":return{type:"error",message:Ue(n.message)};default:return null}}var _t=(e)=>e.type==="done"||e.type==="idle"||e.type==="error";var ho=()=>({event:null,data:[],id:null,retry:null});function Jn(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 Wn(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 Gn(e,t){if(t==="")return Wn(e);if(t.startsWith(":"))return null;let n=t.indexOf(":");if(n===-1)return Jn(e,t,""),null;let r=t.slice(0,n),o=t.slice(n+1);if(o.startsWith(" "))o=o.slice(1);return Jn(e,r,o),null}function yo(e){let t=[],n=0;for(let r=0;r<e.length;r+=1){let o=e[r];if(o!==`
|
|
11
|
+
`&&o!=="\r")continue;if(t.push(e.slice(n,r)),o==="\r"&&e[r+1]===`
|
|
12
|
+
`)r+=1;n=r+1}return{lines:t,rest:e.slice(n)}}async function*Ot(e,t){let n=e.getReader(),r=new TextDecoder,o=ho(),s="",i=()=>void n.cancel().catch(()=>{});t?.addEventListener("abort",i,{once:!0});try{for(;;){let{done:c,value:l}=await n.read();if(c)break;s+=r.decode(l,{stream:!0});let{lines:p,rest:d}=yo(s);s=d;for(let u of p){let m=Gn(o,u);if(m)yield m}if(t?.aborted)return}if(s+=r.decode(),s!==""){let c=Gn(o,s);if(c)yield c}let a=Wn(o);if(a)yield a}finally{t?.removeEventListener("abort",i),n.releaseLock()}}class Me{raw;baseUrl;headers;fetcher;constructor(e){this.baseUrl=e.baseUrl.replace(/\/+$/,""),this.headers=zn(e.credential,e.organizationId);let t={...Ct,...e.retry},n=e.fetch??((r)=>globalThis.fetch(r));this.fetcher=qn({base:n,policy:t}),this.raw=Et({baseUrl:this.baseUrl,headers:this.headers,fetch:this.fetcher})}at(e,t){return{method:e,url:`${this.baseUrl}${t}`}}projects={list:async()=>w(await this.raw.GET("/v1/api/projects"),this.at("GET","/v1/api/projects")),get:async(e)=>w(await this.raw.GET("/v1/api/projects/{id}",{params:{path:{id:e}}}),this.at("GET",`/v1/api/projects/${e}`)),create:async(e)=>w(await this.raw.POST("/v1/api/projects",{body:e}),this.at("POST","/v1/api/projects")),delete:async(e)=>w(await this.raw.DELETE("/v1/api/projects/{id}",{params:{path:{id:e}}}),this.at("DELETE",`/v1/api/projects/${e}`)),start:async(e,t)=>w(await this.raw.POST("/v1/api/projects/{id}/start",{params:{path:{id:e}},body:t}),this.at("POST",`/v1/api/projects/${e}/start`)),observeAgent:(e,t,n)=>this.observeAgent(e,t,n),workspace:(e)=>({fs:async(t)=>w(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)=>w(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`))})};imports={create:async(e)=>{let t=await this.raw.POST("/v1/api/imports",{body:e});return w(t,this.at("POST","/v1/api/imports"))},get:async(e)=>w(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 w(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 o=e.url.startsWith("/")?`${this.baseUrl}${e.url}`:e.url;if(e.kind==="hlix-stream"){let i=new Request(o,{method:"PUT",headers:{...this.headers,"content-type":"application/x-git-bundle","content-length":String(t.size)},body:t,signal:n.signal}),a=await this.fetcher(i);if(!a.ok)await this.throwUploadError(a,o);n.onProgress?.(t.size,t.size);return}let s=0;while(s<t.size){let i=Math.min(s+r,t.size),a=new Request(o,{method:"PUT",headers:{"content-type":"application/x-git-bundle","content-length":String(i-s),"content-range":`bytes ${s}-${i-1}/${t.size}`},body:t.slice(s,i),signal:n.signal}),c=await this.fetcher(a);if(c.status!==308&&!c.ok)await this.throwUploadError(c,o);let l=c.headers.get("range")?.match(/bytes=0-(\d+)/)?.[1];if(s=l?Number(l)+1:i,!Number.isSafeInteger(s)||s<i||s>t.size)throw Error("Import upload server returned an invalid acknowledged range");n.onProgress?.(s,t.size)}}};revisions={head:async(e)=>w(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)=>w(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 w(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 w(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}),o=await this.fetcher(r);if(!o.ok)await this.throwUploadError(o,`${this.baseUrl}${n}`);return o.blob()}};resources={importSkill:async(e,t)=>w(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)=>w(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)=>w(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 Le(e,n,{method:"PUT",url:t})}tasks={list:async(e)=>w(await this.raw.GET("/v1/api/tasks",{params:{query:e??{}}}),this.at("GET","/v1/api/tasks")),get:async(e)=>w(await this.raw.GET("/v1/api/tasks/{id}",{params:{path:{id:e}}}),this.at("GET",`/v1/api/tasks/${e}`)),create:async(e)=>w(await this.raw.POST("/v1/api/tasks",{body:e}),this.at("POST","/v1/api/tasks")),update:async(e,t)=>w(await this.raw.PATCH("/v1/api/tasks/{id}",{params:{path:{id:e}},body:t}),this.at("PATCH",`/v1/api/tasks/${e}`)),listComments:async(e)=>w(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)=>w(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)=>w(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)=>w(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)=>w(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)=>w(await this.raw.PUT("/v1/api/model-config/harness",{body:{harness:e}}),this.at("PUT","/v1/api/model-config/harness")),clearHarness:async()=>w(await this.raw.DELETE("/v1/api/model-config/harness"),this.at("DELETE","/v1/api/model-config/harness")),resolvedHarness:async()=>w(await this.raw.GET("/v1/api/model-config/harness/resolved"),this.at("GET","/v1/api/model-config/harness/resolved")),resolvedProjectHarness:async(e)=>w(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`))};cycles={list:async(e)=>w(await this.raw.GET("/v1/api/cycles",{params:{query:e??{}}}),this.at("GET","/v1/api/cycles")),get:async(e)=>w(await this.raw.GET("/v1/api/cycles/{id}",{params:{path:{id:e}}}),this.at("GET",`/v1/api/cycles/${e}`)),propose:async(e)=>w(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)=>w(await this.raw.GET("/v1/api/client-billing/invoices",{params:{query:e??{}}}),this.at("GET","/v1/api/client-billing/invoices")),get:async(e)=>w(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)=>w(await this.raw.POST("/v1/api/client-billing/invoices",{body:e}),this.at("POST","/v1/api/client-billing/invoices")),issue:async(e)=>w(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)=>w(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)=>w(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={})=>w(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 o of this.stream(r,n)){let s=It(o.data);if(!s)continue;if(yield s,_t(s))return}}async*stream(e,t){let n=`${this.baseUrl}${e}`,r=new Request(n,{headers:{...this.headers,accept:"text/event-stream"},signal:t?.signal}),o=await globalThis.fetch(r);if(!o.ok||!o.body){let s=null;try{s=await o.json()}catch{s=null}throw Le(o,s,{method:"GET",url:n})}yield*Ot(o.body,t?.signal)}}function Tt(e){if(e instanceof y)return{code:e.code,status:null};if(e instanceof Ie)return{code:"invalid_request",status:400};if(e instanceof _e)return{code:"bad_request",status:400};if(e instanceof Oe)return{code:"unauthenticated",status:401};if(e instanceof Re)return{code:"forbidden",status:403};if(e instanceof Te)return{code:"not_found",status:404};if(e instanceof Ae)return{code:"conflict",status:409};if(e instanceof He)return{code:"rate_limited",status:429};if(e instanceof Fe)return{code:"not_implemented",status:501};if(e instanceof Ne)return{code:"server_error",status:e.status};if(e instanceof de)return{code:"unreachable",status:null};return{code:"unknown",status:null}}var Rt=(e)=>e instanceof Error?e.message:String(e);function bo(e,t){let n=B({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 Me({baseUrl:n.baseUrl,credential:n.credential.sessionToken?Pt(n.credential.sessionToken):xe(n.credential.apiKey),...n.workspaceId?{organizationId:n.workspaceId}:{}})}function Vn(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
|
+
A command targets the workspace named by, in order: an explicit flag, the
|
|
30
|
+
HLIX_* environment, the nearest .hlix/config.json, then the stored credential.
|
|
31
|
+
Run \`hlix status\` to see which one applied.
|
|
32
|
+
`}function Xn(e,t){for(let n of[...e].sort((r,o)=>o.name.length-r.name.length)){let r=n.name.split(" ");if(r.every((o,s)=>t[s]===o))return{command:n,rest:t.slice(r.length)}}return null}async function Di(e,t,n){if(t.some((E)=>E==="--api-key"||E.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=ko({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"},"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"}}})}catch(E){let O=t.includes("--json"),A=Rt(E);if(O)n.stdout(v(be("cli",{code:"invalid_usage",message:A,status:null})));else n.stderr(`${A}
|
|
33
|
+
`);return 2}let o=r.values.json===!0,s=r.positionals;if(r.values.version===!0){let{version:E}=await import("./package-12m4e2y1.js");return n.stdout(`${E}
|
|
34
|
+
`),0}if(s.length===0||r.values.help===!0){let E=Xn(e,s);return n.stdout(E?`${E.command.usage}
|
|
35
|
+
`:Vn(e)),s.length===0&&r.values.help!==!0?1:0}let i=Xn(e,s);if(!i){let E=s.join(" ");if(o)n.stdout(v(be(E,{code:"unknown_command",message:`Unknown command: ${E}`,status:null})));else n.stderr(`Unknown command: ${E}
|
|
36
|
+
|
|
37
|
+
${Vn(e)}`);return 2}let a=new Set(["json","help","version","cwd","workspace","base-url"]),c=new Set(i.command.options??[]),l=Object.entries(r.values).filter(([E,O])=>O!==void 0&&!a.has(E)&&!c.has(E)).map(([E])=>`--${E}`),p=i.command.args??{min:0,max:0},d=i.rest.length<p.min?{code:"missing_argument",message:i.command.usage.split(`
|
|
38
|
+
`)[0]}:i.rest.length>p.max?{code:"invalid_usage",message:i.command.usage.split(`
|
|
39
|
+
`)[0]}:null,u=typeof r.values.cwd==="string"?r.values.cwd:void 0,m=vo(u??"."),h=u!==void 0&&!Kn(m)?{code:"invalid_usage",message:`--cwd is not a directory: ${m}`}:null,k=l.length>0?{code:"invalid_usage",message:`Unsupported option for ${i.command.name}: ${l.join(", ")}`}:h??d;if(k){if(o)n.stdout(v(be(i.command.name,{...k,status:null})));else n.stderr(`error: ${k.message}
|
|
40
|
+
|
|
41
|
+
${i.command.usage}
|
|
42
|
+
`);return 2}let _=r.values,D={...n,args:i.rest,json:o,flags:_,cwd:m,requireClient:(E)=>bo(n.env,{cwd:E??m,flags:_})};try{return await i.command.run(D)}catch(E){let{code:O,status:A}=Tt(E);if(o)n.stdout(v(be(i.command.name,{code:O,message:Rt(E),status:A})));else n.stderr(`error: ${Rt(E)}
|
|
43
|
+
`);return O==="unauthenticated"||O==="forbidden"?3:1}}import{readFileSync as So}from"node:fs";import{homedir as jo}from"node:os";import{join as Eo}from"node:path";var Yn=["cloud","docker","local"],pe=["claude-code","codex","cursor-agent","hlix"],ea="hlix",Zn={harness:"local and docker sandboxes only",model:"all sandboxes",sandbox:"all sandboxes"},ue=["harness","model","sandbox"],At=["projectId","workspaceId","apiUrl"];function Ht(e=process.env){return Eo(e.HLIX_CONFIG_HOME??jo(),".hlix","config.json")}function Qn(e=process.env){try{let t=JSON.parse(So(Ht(e),"utf8"));return t.schemaVersion===1?t:null}catch{return null}}function Ft(e,t=process.env){let n=Qn(t),r=N(e),o=r?.root??null,s=r?.config??null,i={},a={},c=(l)=>{let p=s?.[l],d=n?.[l];if(p!==void 0)i[l]=p,a[l]="project";else if(d!==void 0)i[l]=d,a[l]="global"};for(let l of ue)c(l);for(let l of At){let p=s?.[l];if(p!==void 0)i[l]=p,a[l]="project"}return{merged:i,sources:a,global:n,project:s,paths:{global:Ht(t),project:o?Pe(o):null}}}function er(e){return[...ue,...At].map((n)=>({key:n,value:e.merged[n]??null,source:e.sources[n]??"default"}))}function Po(e,t){if(e==="sandbox"&&!Yn.includes(t))return`sandbox must be one of ${Yn.join(", ")}; got "${t}".`;if(e==="harness"&&!pe.includes(t))return`harness must be one of ${pe.join(", ")}; got "${t}".`;if(e==="model"&&t.trim()==="")return"model must not be empty.";return null}function Nt(e){if(ue.includes(e))return e;let t=At.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: ${ue.join(", ")}.`)}function tr(e,t){let n=Po(e,t);if(n)throw new y("invalid_usage",n);return t}function nr(e){if(e.scope==="global"){let r=Ht(e.env),o=Qn(e.env)??{schemaVersion:1};return Ee(r,{...o,[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=Pe(t.root);return Ee(n,{...t.config,[e.key]:e.value}),n}var Lt={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 Required. Workspace (organization) id to act in","","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(`
|
|
44
|
+
`),supportsJson:!0,options:["base-url","workspace"],async run(e){let t=typeof e.flags.workspace==="string"?e.flags.workspace:e.env.HLIX_WORKSPACE_ID;if(!t)throw new y("missing_argument","--workspace is required.");let 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??jt,o=new URL(r),s=o.hostname==="localhost"||o.hostname==="127.0.0.1"||o.hostname==="::1";if(o.protocol!=="https:"&&!(o.protocol==="http:"&&s))throw new y("invalid_base_url","--base-url must use HTTPS (HTTP is allowed only for localhost).");await new Me({baseUrl:r,credential:xe(n),organizationId:t,retry:{attempts:1}}).projects.list();let a=Fn({baseUrl:r,apiKey:n,organizationId:t},e.env);if(e.json)e.stdout(v(j(Lt.name,{baseUrl:r,organizationId:t,credentialPath:a})));else e.stdout(`Signed in to ${r}
|
|
45
|
+
Credential stored at ${a}
|
|
46
|
+
`);return 0}},Ut={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 environment or the stored file —","and verifies it against the API. The key itself is never printed, not even","a prefix: machine output gets piped into logs."].join(`
|
|
47
|
+
`),supportsJson:!0,async run(e){let t=B({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}
|
|
48
|
+
`),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(v(j(Ut.name,n))),0;return e.stdout(`${R([["credential",t.credentialSource==="env"?`environment (${t.credential?.sessionToken?"HLIX_SESSION_TOKEN":"HLIX_API_KEY"})`:`file (${t.credentialPath})`],["api",`${t.baseUrl} (from ${t.baseUrlSource})`],["workspace",t.workspaceId?`${t.workspaceId} (from ${t.workspaceSource})`:"none"],["status","valid"]])}
|
|
49
|
+
`),0}},me={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(`
|
|
50
|
+
`),supportsJson:!0,options:["yes"],async run(e){let t=B({env:e.env,flags:e.flags,cwd:e.cwd});if(t.credentialSource==="env"){let r=Hn(e.env);if(!r){let s={removed:!1,reason:"environment",path:null};if(e.json)e.stdout(v(j(me.name,s)));else e.stdout(`HLIX_API_KEY is set in this environment; unset it there to sign out.
|
|
51
|
+
`);return 0}if(e.flags.yes!==!0){let s={removed:!1,reason:"environment",path:r};if(e.json)e.stdout(v(j(me.name,s)));else e.stdout(`HLIX_API_KEY is set in this environment; unset it there to sign out.
|
|
52
|
+
A stored credential also exists at ${r} — repeat with --yes to remove it.
|
|
53
|
+
`);return 0}let o=bt(e.env);if(e.json)e.stdout(v(j(me.name,o)));else e.stdout(`Removed ${o.path}
|
|
54
|
+
HLIX_API_KEY is still set in this environment; unset it there to finish signing out.
|
|
55
|
+
`);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=bt(e.env);if(e.json)e.stdout(v(j(me.name,n)));else e.stdout(n.removed?`Removed ${n.path}
|
|
56
|
+
`:`No stored credential at ${n.path}
|
|
57
|
+
`);return 0}};var rr=ue.join(" | "),Mt={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(`
|
|
58
|
+
`),supportsJson:!0,async run(e){let t=Ft(e.cwd,e.env),n=er(t);if(e.json)return e.stdout(v(j(Mt.name,{settings:n,paths:t.paths}))),0;return e.stdout(`${ae(["setting","value","source","applies to"],n.map((r)=>[r.key,r.value??"-",r.source,Zn[r.key]??"this folder's binding"]))}
|
|
59
|
+
`),e.stdout(`
|
|
60
|
+
global ${t.paths.global}
|
|
61
|
+
`),e.stdout(`project ${t.paths.project??"- (this folder is not bound to hlix)"}
|
|
62
|
+
`),0}},Bt={name:"config get",summary:"Print one setting's effective value",usage:[`Usage: hlix config get <${rr}> [--cwd <dir>] [--json]`,"","Prints the value the cascade resolves for one key, or exits 1 when no","file names it."].join(`
|
|
63
|
+
`),supportsJson:!0,args:{min:1,max:1},async run(e){let t=Nt(e.args[0]),n=Ft(e.cwd,e.env),r=n.merged[t]??null,o=n.sources[t]??"default";if(e.json)return e.stdout(v(j(Bt.name,{key:t,value:r,source:o}))),r===null?1:0;if(r===null)return e.stderr(`${t} is not set. Set it with \`hlix config set ${t} <value>\`.
|
|
64
|
+
`),1;return e.stdout(`${r}
|
|
65
|
+
`),0}},Kt={name:"config set",summary:"Set one setting for this folder, or for the machine with --global",usage:[`Usage: hlix config set <${rr}> <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(`
|
|
66
|
+
`),supportsJson:!0,options:["global"],args:{min:2,max:2},async run(e){let t=Nt(e.args[0]),n=tr(t,e.args[1]),r=e.flags.global===!0?"global":"project",o=nr({key:t,value:n,scope:r,cwd:e.cwd,env:e.env});if(e.json)return e.stdout(v(j(Kt.name,{key:t,value:n,scope:r,path:o}))),0;return e.stdout(`${t} = ${n} (${r}: ${o})
|
|
67
|
+
`),0}};function te(e,t){if(typeof e!=="object"||e===null)return"";let n=e[t];return n===null||n===void 0?"":String(n)}var zt={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(v(j(zt.name,t))),0;let n=Array.isArray(t)?t:[];if(n.length===0)return e.stdout(`No projects.
|
|
68
|
+
`),0;return e.stdout(`${ae(["ID","NAME","STACK"],n.map((r)=>[te(r,"id"),te(r,"name"),te(r,"stack")]))}
|
|
69
|
+
`),0}},Dt={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(`
|
|
70
|
+
`),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(v(j(Dt.name,n))),0;let r=n.repos;return e.stdout(`${R([["id",te(n,"id")],["name",te(n,"name")],["stack",te(n,"stack")],["status",te(n,"status")],["repos",Array.isArray(r)?String(r.length):""]].filter(([,o])=>o!==""))}
|
|
71
|
+
`),0}};function qt(e,t){let n=e.args[0];if(!n)throw new y("missing_argument",`A ${t} id is required.`);return n}function or(e,t){let n=e.flags[t];return typeof n==="string"&&n.trim()?n.trim():void 0}function K(e,t){if(typeof e!=="object"||e===null)return"";let n=e[t];return n===null||n===void 0?"":String(n)}var Jt={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(`
|
|
72
|
+
`),supportsJson:!0,options:["project","status"],async run(e){let t=or(e,"project")??N(e.cwd)?.config.projectId,n=or(e,"status"),r=await e.requireClient().tasks.list({...t?{projectId:t}:{},...n?{status:n}:{}});if(e.json)return e.stdout(v(j(Jt.name,r))),0;let o=Array.isArray(r)?r:[];if(o.length===0)return e.stdout(`No tasks.
|
|
73
|
+
`),0;return e.stdout(`${ae(["ID","STATUS","TITLE"],o.map((s)=>[K(s,"id"),K(s,"status"),K(s,"title")||K(s,"description").split(`
|
|
74
|
+
`)[0]||""]))}
|
|
75
|
+
`),0}},Gt={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=qt(e,"task"),n=await e.requireClient().tasks.get(t);if(e.json)return e.stdout(v(j(Gt.name,n))),0;return e.stdout(`${R([["id",K(n,"id")],["status",K(n,"status")],["title",K(n,"title")],["project",K(n,"projectId")],["description",K(n,"description")]])}
|
|
76
|
+
`),0}},Wt={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=qt(e,"task"),n=await e.requireClient().tasks.review(t);if(e.json)return e.stdout(v(j(Wt.name,n))),0;return e.stdout(`${JSON.stringify(n,null,2)}
|
|
77
|
+
`),0}},Vt={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(`
|
|
78
|
+
`),supportsJson:!0,args:{min:1,max:1},async run(e){let t=qt(e,"task"),n=e.requireClient();for await(let r of n.tasks.stream(t)){let o;try{o=JSON.parse(r.data)}catch{o=r.data}if(e.json)e.stdout(`${JSON.stringify(j(Vt.name,o))}
|
|
79
|
+
`);else{let s=K(o,"status"),i=K(o,"error");e.stdout(i?`error: ${i}
|
|
80
|
+
`:`${s||r.data}
|
|
81
|
+
`)}}return 0}};import{realpath as is}from"node:fs/promises";import{resolve as as}from"node:path";import{createHash as gr}from"node:crypto";import{createReadStream as Oo}from"node:fs";import{lstat as hr,readFile as st,readdir as Ro,realpath as yr,stat as To}from"node:fs/promises";import{basename as re,join as wr,relative as dr,resolve as pr,sep as Ao}from"node:path";import{spawnSync as Ho}from"node:child_process";import ur from"ignore";import{readFile as $o}from"node:fs/promises";import{join as xo}from"node:path";function Co(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 sr(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=[],o=!1,s=-1;for(let i of t.slice(n+1)){if(!i.trim()||/^\s*#/.test(i))continue;let a=i.length-i.trimStart().length,c=i.match(/^(\s*-(?:\s+|$))(.*)$/);if(c){if(s!==-1&&a>=s)continue;if(r.push({}),s=c[2]?c[1].length:-1,!c[2])continue}else if(a===0)break;else if(r.length===0)continue;else if(s===-1)s=a;else if(a!==s)continue;let l=(c?c[2]:i.trim()).match(/^([A-Za-z_][A-Za-z0-9_-]*):\s*(.*)$/);if(!l)continue;let p=l[1];if(p!=="name"&&p!=="before"&&p!=="init"&&p!=="command")continue;let d=Co(l[2]);if(d===null)o=!0;else r[r.length-1][p]=d}return{tasks:r,partial:o}}async function ne(e,t){try{return await $o(xo(e,...t.split("/")),"utf8")}catch(n){if(n.code==="ENOENT")return null;throw n}}function ir(e){try{let t=e.replace(/(^|[^:\\])\/\/.*$/gm,"$1").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,\s*([}\]])/g,"$1");return JSON.parse(t)}catch{return null}}function Y(e){if(typeof e==="string"&&e.trim())return[e.trim()];if(Array.isArray(e))return e.flatMap(Y);if(e&&typeof e==="object")return Object.values(e).flatMap(Y);return[]}function Xt(e){if(!e||typeof e!=="object")return[];return Object.keys(e).filter((t)=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(t))}function Io(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 o of r)for(let s of e.matchAll(o))n.add(s[1]);return[...n]}function _o(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 ar(e){let t=typeof e==="number"?e:Number(e);return Number.isInteger(t)&&t>0&&t<=65535?t:null}function U(e,t,n){if(!e.some((r)=>r.path===t&&r.kind===n))e.push({path:t,kind:n})}async function cr(e,t,n){let r=[],o=[],s=[],i=[],a=new Map,c=new Set,l=new Set,p=[],d={},u=null,m=0,h=await ne(e,".cursor/environment.json");if(h){U(r,".cursor/environment.json","cursor");let f=ir(h);if(!f)p.push("Could not parse .cursor/environment.json; it remains quarantined.");else{o.push(...Y(f.install));let P=Y(f.start);if(P[0])u=P[0];if(Array.isArray(f.terminals))for(let b of f.terminals){if(!b||typeof b!=="object")continue;let x=b;if(typeof x.command!=="string"||!x.command.trim())continue;i.push({name:typeof x.name==="string"&&x.name.trim()?x.name.trim():"Terminal",command:x.command.trim(),...typeof x.cwd==="string"&&x.cwd.trim()?{cwd:x.cwd.trim()}:{}})}}}let k=t.has(".devcontainer/devcontainer.json")?".devcontainer/devcontainer.json":t.has("devcontainer.json")?"devcontainer.json":null;if(k){U(r,k,"devcontainer");let f=ir(n.get(k)??await ne(e,k)??"");if(!f)p.push(`Could not parse ${k}; it remains quarantined.`);else{o.push(...Y(f.onCreateCommand),...Y(f.updateContentCommand),...Y(f.postCreateCommand));let P=Y(f.postStartCommand);if(!u&&P[0])u=P[0];for(let b of Xt(f.secrets))c.add(b);for(let b of[...Xt(f.containerEnv),...Xt(f.remoteEnv)])c.add(b);if(Array.isArray(f.forwardPorts))for(let b of f.forwardPorts){let x=ar(b);if(x)a.set(x,{port:x,visibility:"private"})}}}if(t.has(".gitpod.yml")){U(r,".gitpod.yml","gitpod");let f=n.get(".gitpod.yml")??await ne(e,".gitpod.yml");if(f===null)p.push("Could not read .gitpod.yml; its task commands were not imported.");else{let P=sr(f);m=P.tasks.filter((b)=>b.before).length;for(let b of P.tasks){if(b.before)o.push(b.before);if(b.init)o.push(b.init);if(!b.command)continue;if(!u)u=b.command;else i.push({name:b.name??"Terminal",command:b.command})}if(P.partial)p.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 f of["Dockerfile","docker-compose.yml","docker-compose.yaml","compose.yml","compose.yaml"])if(t.has(f))U(r,f,"docker");for(let f of["project.toml","nixpacks.toml","railpack.json","Aptfile"])if(t.has(f))U(r,f,"buildpack");for(let f of["fly.toml","railway.json","render.yaml","vercel.json","netlify.toml"])if(t.has(f))U(r,f,"platform");let _=n.get("package.json")??await ne(e,"package.json");if(_){U(r,"package.json","package");try{let f=JSON.parse(_);if(f.engines?.node)d.node=f.engines.node;let P=_o(t,f.packageManager);if(P&&o.length===m)o.push(P);if(f.scripts?.build&&s.length===0)s.push(`${f.packageManager?.split("@")[0]??(t.has("bun.lock")?"bun":"npm")} run build`);let b=f.scripts?.dev?`${t.has("bun.lock")?"bun":"npm"} run dev`:null,x=f.scripts?.start?`${t.has("bun.lock")?"bun":"npm"} run start`:b;if(!u&&x)u=x}catch{p.push("Could not parse package.json for environment discovery.")}}if(t.has("uv.lock"))o.push("uv sync --frozen");else if(t.has("poetry.lock"))o.push("poetry install --no-interaction");else if(t.has("requirements.txt"))o.push("python -m pip install -r requirements.txt");if(t.has("go.mod"))o.push("go mod download");if(t.has("Procfile")){U(r,"Procfile","procfile");let P=(n.get("Procfile")??"").split(/\r?\n/).find((b)=>/^web\s*:/.test(b));if(P)u=P.replace(/^web\s*:\s*/,"").trim()||u}let D=[[".node-version","node"],[".nvmrc","node"],[".python-version","python"]];for(let[f,P]of D){let b=(n.get(f)??await ne(e,f))?.trim();if(b)d[P]=b,U(r,f,"tool-version")}let E=n.get(".tool-versions")??await ne(e,".tool-versions");if(E){U(r,".tool-versions","tool-version");for(let f of E.split(/\r?\n/)){let[P,b]=f.trim().split(/\s+/,2);if(!b)continue;if(P==="nodejs")d.node=b;else if(P==="python")d.python=b;else if(P==="bun")d.bun=b}}let O=n.get("mise.toml")??await ne(e,"mise.toml");if(O){U(r,"mise.toml","tool-version");for(let f of O.matchAll(/^\s*(node|python|bun)\s*=\s*["']([^"']+)["']/gm))d[f[1]]=f[2]}for(let[f,P]of n){let b=/(?:^|\/)(?:Dockerfile|Procfile)$/i.test(f)||/\.(?:jsonc?|ya?ml|toml|ini|conf|config|env|sh|bash|zsh|fish)$/i.test(f);for(let x of Io(P,b))l.add(x);for(let x of P.matchAll(/(?:--port(?:=|\s+)|PORT\s*=\s*)(\d{2,5})/g)){let z=ar(x[1]);if(z)a.set(z,{port:z,visibility:"private"})}}if(r.length===0&&t.size>0)U(r,"repository","detected");let A=(f)=>[...new Set(f.filter(Boolean))],ye=r.length+o.length+(u?1:0);return{sources:r.sort((f,P)=>f.path.localeCompare(P.path)),toolchain:d,install:A(o),build:A(s),start:u,terminals:i,ports:[...a.values()].sort((f,P)=>f.port-P.port),requiredSecretKeys:[...c].sort(),observedSecretKeys:[...l].sort(),confidence:ye>=4?"high":ye>=2?"medium":"low",warnings:p}}var lr=2;var Fo=25000,No=52428800,Lo=524288000,it=1e4,ot=1048576,fe=10485760,mr=[".git/",".hlix/","node_modules/",".next/",".turbo/",".cache/","dist/","build/","coverage/","__pycache__/",".venv/","venv/","target/",".DS_Store"],Uo=/(^|\/)\.env\.(example|sample|template)$/i,Mo=/(^|\/)\.env(?:\.[^/]+)?$/i,Bo=/(^|\/)(?:\.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)|terraform\.tfvars(?:\.json)?)$/i,Ko=/(^|\/)(?:\.mcp\.json|mcp\.json|claude_desktop_config\.json)$/i,zo=/(^|\/)(?:AGENTS\.md|CLAUDE\.md|\.cursorrules|\.github\/copilot-instructions\.md)$/i,Do=/(^|\/)(?:\.agents|\.claude)\/skills\//i,qo=/-----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,}/,Jo=/\.(?:json|ya?ml|toml|ini|conf|config)$/i,Go=/(?:^|[,{\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,Be=/^HLIX_[A-Za-z0-9_]*$/,Yt=new Set(["CI","HOME","LANG","LOGNAME","NODE_ENV","OLDPWD","PATH","PORT","PWD","SHELL","SHLVL","TERM","TMPDIR","USER","_"]);function Ke(e){return e.split(Ao).join("/")}function Z(e,t,n=10485760){return Ho("git",["-C",e,...t],{encoding:"utf8",maxBuffer:n,stdio:["ignore","pipe","pipe"]})}async function Wo(e){let t=gr("sha256");for await(let n of Oo(e))t.update(n);return t.digest("hex")}function Zt(e){if(Array.isArray(e))return`[${e.map(Zt).join(",")}]`;if(e&&typeof e==="object")return`{${Object.entries(e).sort(([t],[n])=>t.localeCompare(n)).map(([t,n])=>`${JSON.stringify(t)}:${Zt(n)}`).join(",")}}`;return JSON.stringify(e)}function vr(e){let t={};for(let[n,r]of String(e).replace(/^\uFEFF/,"").split(/\r?\n/).entries()){let o=r.trim();if(!o||o.startsWith("#"))continue;let i=(o.startsWith("export ")?o.slice(7).trimStart():o).match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(!i)throw Error(`Invalid dotenv assignment on line ${n+1}`);let a=i[2]??"";if(a.startsWith('"')){if(!a.endsWith('"'))throw Error(`Unclosed dotenv quote on line ${n+1}`);a=a.slice(1,-1).replace(/\\n/g,`
|
|
82
|
+
`).replace(/\\r/g,"\r")}else if(a.startsWith("'")){if(!a.endsWith("'"))throw Error(`Unclosed dotenv quote on line ${n+1}`);a=a.slice(1,-1)}else a=a.replace(/\s+#.*$/,"").trimEnd();t[i[1]]=a}return t}function Vo(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 Xo(e){let t={},n=new Set,r=new Set;for(let o of String(e).replace(/^\uFEFF/,"").split(/\r?\n/)){let s=o.trim();if(!s||s.startsWith("#"))continue;let a=(s.startsWith("export ")?s.slice(7).trimStart():s).match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);if(!a)continue;let c=a[1],l=a[2]??"";if(n.add(c),Vo(l)){delete t[c],r.add(c);continue}try{let d=vr(`${c}=${l}`)[c];if(d===void 0)throw Error("missing literal");t[c]=l.trimStart().startsWith("'")?d:d.replace(/\\\$/g,"$"),r.delete(c)}catch{delete t[c],r.add(c)}}return{values:t,keys:[...n].sort(),dynamicKeys:[...r].sort()}}async function Yo(e){let t=Z(e,["rev-parse","--show-toplevel"]);if(t.status!==0)return!1;try{return await yr(t.stdout.trim())===e}catch{return!1}}function Zo(e,t){if(!t)return new Set;let n=Z(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(Ke))}async function Qo(e){let t=ur().add(mr),n=ur().add(mr);for(let r of[".gitignore",".hlixignore"])try{let o=wr(e,r);if((await hr(o)).isFile())n.add(await st(o,"utf8"))}catch(o){if(o.code!=="ENOENT")throw o}return{hardMatcher:t,matcher:n}}function es(e){if(Ko.test(e))return"mcp";if(Do.test(e))return"skill";if(zo.test(e))return"agent";return null}function ts(e){if(Mo.test(e)&&!Uo.test(e))return"dotenv";if(Bo.test(e))return"credential";return null}function ns(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 rs(e,t){if(t)return[Ke(t)];let n=new Map([[".env",0],[".env.development",1],[".env.local",2],[".env.development.local",3]]),r=e.filter((o)=>n.has(re(o).toLocaleLowerCase("en-US"))).sort((o,s)=>o.slice(0,-re(o).length).localeCompare(s.slice(0,-re(s).length))||n.get(re(o).toLocaleLowerCase("en-US"))-n.get(re(s).toLocaleLowerCase("en-US")));return r.length>0?r:e.length===1?[...e]:[]}function os(e,t){try{let n=JSON.parse(t);if(!n.mcpServers||typeof n.mcpServers!=="object")return[];return Object.entries(n.mcpServers).map(([r,o])=>{let s=o&&typeof o==="object"?o:{},i=s.type==="http"||s.type==="sse"||s.type==="stdio"?s.type:typeof s.command==="string"?"stdio":typeof s.url==="string"?"http":"unknown",a=s.env&&typeof s.env==="object"?s.env:{};return{sourcePath:e,name:r,transport:i,...typeof s.command==="string"?{command:s.command}:{},...Array.isArray(s.args)&&s.args.every((c)=>typeof c==="string")?{args:s.args}:{},...typeof s.url==="string"?{url:s.url}:{},envKeys:Object.keys(a).sort(),enabled:!1}})}catch{return[]}}function fr(e,t){let n=[],r="unknown";for(let o of e.split(/\r?\n/)){if(o.startsWith("@@"))r=o.slice(2);else if(o.trim())n.push({commit:r,path:Ke(o.trim()),reason:t});if(n.length>=100)break}return n}function ss(e,t){if(!t)return{head:null,branch:null,refs:[],commitCount:0,complete:!0,findings:[]};let n=Z(e,["rev-parse","HEAD"]).stdout.trim()||null,r=Z(e,["symbolic-ref","--short","-q","HEAD"]),o=r.status===0?r.stdout.trim()||null:null,s=Number.parseInt(Z(e,["rev-list","--count","--all"]).stdout.trim(),10)||0,i=Z(e,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/tags"]),a=i.stdout.split(`
|
|
83
|
+
`).filter(Boolean).map((u)=>{let[m,h]=u.split("\x00");return{name:m,oid:h}}).filter(({name:u,oid:m})=>/^refs\/(?:heads|tags)\/.+/.test(u)&&/^[0-9a-f]{40,64}$/.test(m)).sort((u,m)=>u.name.localeCompare(m.name)),c=["log","--all",`--max-count=${it}`,"--pretty=format:@@%H","--name-only"],l=Z(e,[...c,"--",".env",".env.*","*.pem","*.key",".npmrc","*.tfvars"]),p=Z(e,["log","--all",`--max-count=${it}`,"-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 u of[...fr(l.stdout,"sensitive-path"),...fr(p.stdout,"secret-pattern")])d.set(`${u.commit}:${u.path}:${u.reason}`,u);return{head:n,branch:o,refs:a,commitCount:s,complete:s<=it&&a.length<=1000&&i.status===0&&l.status===0&&p.status===0,findings:[...d.values()].slice(0,100)}}async function Q(e,t={}){let n=await yr(pr(e));if(!(await To(n)).isDirectory())throw Error("Import target must be a directory.");let r=await Yo(n),o=Zo(n,r),{hardMatcher:s,matcher:i}=await Qo(n),a=[],c=[],l=[],p=[],d=[],u=[],m=t.envFile?Ke(dr(n,pr(n,t.envFile))):void 0,h=m!==void 0&&m!==""&&m!==".."&&!m.startsWith("../");if(t.envFile&&!h)u.push(`Selected environment file must stay inside the project: ${t.envFile}`);let k=new Map,_=new Map,D=new Map,E=new Map,O=[],A=[],ye=new Map,f=t.maxFiles??Fo,P=t.maxFileBytes??No,b=t.maxTotalBytes??Lo,x=0,z=0,jn=async(g)=>{let S=await Ro(g,{withFileTypes:!0});S.sort((I,H)=>I.name.localeCompare(H.name));for(let I of S){let H=wr(g,I.name),C=Ke(dr(n,H));if(I.name===".git"){if(C!==".git")u.push(`Nested Git repository is not supported: ${C}`);continue}let M=await hr(H),$n=I.isDirectory()?`${C}/`:C,yt=o.has(C),xn=!yt&&i.ignores($n),Br=!yt&&s.ignores($n);if(M.isSymbolicLink()){if(d.push({path:C,reason:"symlink"}),!xn)u.push(`Symlinks are not imported in this release: ${C}`);continue}if(I.isDirectory()){if(Br)continue;await jn(H);continue}let ve=es(C),ke=ts(C);if(xn&&!ve&&!ke)continue;if(!I.isFile()){d.push({path:C,reason:"non-regular-file"});continue}if(a.length+c.length+l.length>=f){u.push(`Project exceeds the ${f} file limit.`);return}if(M.size>P){u.push(`File exceeds the ${P} byte limit: ${C}`);continue}if(x+=M.size,x>b){u.push(`Project exceeds the ${b} byte total limit.`);return}let Ve=await Wo(H);if(ve){if(M.size>ot){u.push(`Protected configuration exceeds the ${ot} byte limit: ${C}`);continue}let F=await st(H);if(z+=F.byteLength,z>fe){u.push(`Protected project files exceed the ${fe} byte total limit.`);continue}if(l.push({path:C,kind:ve,size:M.size,sha256:Ve}),A.push({path:C,kind:ve,contentBase64:F.toString("base64")}),ve==="mcp")p.push(...os(C,F.toString("utf8")));continue}if(ke){if(M.size>ot){u.push(`Protected file exceeds the ${ot} byte limit: ${C}`);continue}let F=await st(H);if(z+=F.byteLength,z>fe){u.push(`Protected project files exceed the ${fe} byte total limit.`);continue}let ee=[];if(ke==="dotenv")try{let Xe=vr(F),se={};for(let[X,ie]of Object.entries(Xe)){if(Be.test(X)){u.push(`Hlix control-plane environment keys cannot be imported into a project: ${X}`);continue}se[X]=ie}k.set(C,se),ee=Object.keys(se).sort()}catch{u.push(`Could not parse environment file: ${C}`)}else if(re(C)===".envrc"){let Xe=Xo(F),se={},X=new Set,ie=[];for(let[T,Kr]of Object.entries(Xe.values)){if(Be.test(T)){u.push(`Hlix control-plane environment keys cannot be imported into a project: ${T}`);continue}if(Yt.has(T)){O.push(`Ignored ambient runtime assignment in ${C}: ${T}`);continue}X.add(T),se[T]=Kr}_.set(C,se);for(let T of Xe.dynamicKeys){if(Be.test(T)){u.push(`Hlix control-plane environment keys cannot be imported into a project: ${T}`);continue}if(Yt.has(T)){O.push(`Ignored ambient runtime assignment in ${C}: ${T}`);continue}X.add(T),ie.push(T)}if(D.set(C,[...X].sort()),E.set(C,ie.sort()),ee=[...X].sort(),ie.length>0)O.push(`Did not execute dynamic .envrc assignments; collect their resolved local values when available: ${ie.join(", ")}`)}c.push({path:C,kind:ke,keys:ee,size:M.size,sha256:Ve}),A.push({path:C,kind:ke,contentBase64:F.toString("base64")});continue}if(M.size<=1048576){let F=await st(H),ee=F.toString("utf8");if(ye.set(C,ee),qo.test(ee)||Jo.test(C)&&Go.test(ee)){if(z+=F.byteLength,z>fe){u.push(`Protected project files exceed the ${fe} byte total limit.`);continue}c.push({path:C,kind:"detected-content",keys:[],size:M.size,sha256:Ve}),A.push({path:C,kind:"detected-content",contentBase64:F.toString("base64")});continue}}a.push({path:C,size:M.size,sha256:Ve,tracked:yt,executable:(M.mode&73)!==0})}};await jn(n),a.sort((g,S)=>g.path.localeCompare(S.path)),c.sort((g,S)=>g.path.localeCompare(S.path)),l.sort((g,S)=>g.path.localeCompare(S.path)),p.sort((g,S)=>`${g.sourcePath}:${g.name}`.localeCompare(`${S.sourcePath}:${S.name}`));let mt=rs([...k.keys()].sort(),h?m:void 0);if(t.envFile&&h&&!k.has(mt[0]))u.push(`Selected environment file was not found or is not a dotenv file: ${t.envFile}`);let we=new Map;for(let[g,S]of k)for(let I of Object.keys(S))we.set(I,[...we.get(I)??[],g]);for(let[g,S]of D)for(let I of S)we.set(I,[...we.get(I)??[],g]);let Fr=[...we].filter(([,g])=>g.length>1).map(([g,S])=>({key:g,paths:S.sort()})).sort((g,S)=>g.key.localeCompare(S.key)),q={};for(let g of mt)Object.assign(q,k.get(g)??{});let Nr=[..._.keys()].sort((g,S)=>{if(g===".envrc")return 1;if(S===".envrc")return-1;return g.localeCompare(S)}),ft=new Set;for(let g of Nr){let S=new Set(E.get(g)??[]);for(let I of D.get(g)??[]){if(S.has(I)){delete q[I],ft.add(I);continue}let H=_.get(g)?.[I];if(H!==void 0)q[I]=H;ft.delete(I)}}let gt=t.historyMode??"abort_on_findings",V=ss(n,r);if(!V.complete&>!=="preserve")u.push(`Git history scan exceeded ${it} commits or failed; import requires explicit --history preserve.`);if(V.findings.length>0&>==="abort_on_findings")u.push("Potential secrets exist in Git history. Abort, sanitize the repository, or explicitly use --history preserve.");let En=new Set(a.map((g)=>g.path)),Lr=await cr(n,En,ye),{observedSecretKeys:Ur,...J}=Lr;J.warnings.push(...O);let ht=new Set(J.requiredSecretKeys);for(let g of ft)ht.add(g);for(let g of p)for(let S of g.envKeys)ht.add(S);J.requiredSecretKeys=[...ht].sort();for(let g of J.requiredSecretKeys){if(Be.test(g)){u.push(`Hlix control-plane environment keys cannot be imported into a project: ${g}`);continue}if(q[g]!==void 0)continue;let S=t.environment?.[g];if(S===void 0){u.push(`Required project environment value was not found locally: ${g}`);continue}q[g]=S}for(let g of Ur){if(Be.test(g)){J.warnings.push(`Ignored reserved Hlix control-plane environment reference: ${g}`);continue}if(Yt.has(g))continue;if(q[g]!==void 0)continue;let S=t.environment?.[g];if(S===void 0){J.warnings.push(`Observed environment reference has no local value: ${g}`);continue}q[g]=S}J.warnings=[...new Set(J.warnings)].sort();let Pn={schemaVersion:lr,rootName:t.rootName??re(n),stack:ns(En),git:{detected:r,head:V.head,branch:V.branch,refs:V.refs,commitCount:V.commitCount,historyScanComplete:V.complete,historyMode:gt},files:a,secretFiles:c,activeEnvFiles:mt,secretKeys:Object.keys(q).sort(),envCollisions:Fr,quarantinedResources:l,mcpServers:p,historicalSecretFindings:V.findings,skipped:d,environment:J,totals:{files:a.length,bytes:a.reduce((g,S)=>g+S.size,0)}},Cn=Zt(Pn),Mr=gr("sha256").update(Cn).digest("hex");return{root:n,manifest:Pn,manifestJson:Cn,manifestSha256:Mr,secretValues:q,protectedFiles:A.sort((g,S)=>g.path.localeCompare(S.path)),blocking:[...new Set(u)]}}var Qt={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(`
|
|
84
|
+
`),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 is(as(e.cwd,e.args[0]??".")),n=B({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 o=le(t),s=typeof e.flags.project==="string"?e.flags.project:void 0;if(s&&o?.projectId&&o.projectId!==s)throw new y("workspace_mismatch",`This folder is bound to project ${o.projectId}; refusing to rebind it to ${s}.`);if(s)await r.projects.get(s);let i={...o??{schemaVersion:1,workspaceId:n.workspaceId,apiUrl:n.baseUrl},...s?{projectId:s}:{}};Ce(t,i);let a=await Q(t,{environment:e.env}),c={root:t,config:i,scan:{files:a.manifest.totals.files,bytes:a.manifest.totals.bytes,secretFiles:a.manifest.secretFiles.map((l)=>l.path),quarantinedResources:a.manifest.quarantinedResources.map((l)=>l.path),blocking:a.blocking}};if(e.json)e.stdout(v(j(Qt.name,c)));else if(e.stdout(`Initialized ${t}
|
|
85
|
+
Project: ${i.projectId??"not imported yet"}
|
|
86
|
+
Workspace: ${i.workspaceId}
|
|
87
|
+
`),a.blocking.length)e.stdout(`
|
|
88
|
+
Review before import:
|
|
89
|
+
${a.blocking.map((l)=>`- ${l}`).join(`
|
|
90
|
+
`)}
|
|
91
|
+
`);return 0}};import{createHash as hs}from"node:crypto";import{readFile as ys,realpath as ws}from"node:fs/promises";import{basename as vs,resolve as ks}from"node:path";import{createHash as cs}from"node:crypto";import{createReadStream as ls}from"node:fs";import{chmod as en,copyFile as ds,lstat as kr,mkdir as br,mkdtemp as ps,readdir as us,rm as tn}from"node:fs/promises";import{tmpdir as ms}from"node:os";import{dirname as fs,join as oe}from"node:path";import{spawnSync as ze}from"node:child_process";function G(e,t){let n=ze("git",["-C",e,...t],{encoding:"utf8",maxBuffer:20971520,stdio:["ignore","pipe","pipe"]});if(n.status!==0){let r=n.stderr.trim().split(`
|
|
92
|
+
`).at(-1)??"git command failed";throw Error(r)}return n.stdout.trim()}async function Sr(e){let t=cs("sha256");for await(let n of ls(e))t.update(n);return t.digest("hex")}async function gs(e){for(let t of await us(e)){if(t===".git")continue;await tn(oe(e,t),{recursive:!0,force:!0})}}async function at(e){if(e.blocking.length>0)throw Error(`Project scan has blocking findings:
|
|
93
|
+
- ${e.blocking.join(`
|
|
94
|
+
- `)}`);let t=await ps(oe(ms(),"hlix-snapshot-"));await en(t,448);let n=oe(t,"repo"),r=oe(t,"source.git"),o=oe(t,"project.bundle");try{if(e.manifest.git.detected){let d=ze("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 u=new Map(G(r,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/tags"]).split(`
|
|
95
|
+
`).filter(Boolean).map((h)=>h.split("\x00",2)));for(let h of e.manifest.git.refs)if(u.get(h.name)!==h.oid)throw Error(`Git ref changed after scan: ${h.name}`);let m=ze("git",["clone","--no-hardlinks",r,n],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(m.status!==0)throw Error(m.stderr.trim()||"Could not create snapshot clone.");if(!e.manifest.git.head)throw Error("Git repository has no HEAD commit.");G(n,["checkout","-B","main",e.manifest.git.head])}else await br(n,{recursive:!0,mode:448}),G(n,["init","-b","main"]);await gs(n);for(let d of e.manifest.files){let u=oe(e.root,...d.path.split("/")),m=await kr(u);if(!m.isFile()||m.isSymbolicLink())throw Error(`Source changed after scan: ${d.path}`);if(m.size!==d.size||await Sr(u)!==d.sha256)throw Error(`Source changed after scan: ${d.path}`);let h=oe(n,...d.path.split("/"));await br(fs(h),{recursive:!0,mode:493}),await ds(u,h),await en(h,d.executable?493:420)}G(n,["config","user.name","Hlix Import"]),G(n,["config","user.email","import@hlix.ai"]),G(n,["add","-A"]),G(n,["commit","--allow-empty","-m","chore(hlix): import snapshot"]);let s=G(n,["rev-parse","HEAD"]),i=e.manifest.git.refs.filter((d)=>d.name!=="refs/heads/main");if(i.length>0){let d=ze("git",["-C",n,"update-ref","--stdin"],{encoding:"utf8",input:i.map((u)=>`update ${u.name} ${u.oid}`).join(`
|
|
96
|
+
`)+`
|
|
97
|
+
`,stdio:["pipe","pipe","pipe"]});if(d.status!==0)throw Error(d.stderr.trim()||"Could not recreate the approved Git refs.")}let a=i.map((d)=>d.name),c=ze("git",["-C",n,"bundle","create",o,"--stdin"],{encoding:"utf8",input:["refs/heads/main",...a].join(`
|
|
98
|
+
`)+`
|
|
99
|
+
`,stdio:["pipe","pipe","pipe"]});if(c.status!==0)throw Error(c.stderr.trim()||"Could not create the approved Git bundle.");G(n,["bundle","verify",o]),await en(o,384);let l=(await kr(o)).size,p=await Sr(o);return{bundlePath:o,bundleSha256:p,bundleSize:l,commitSha:s,dispose:()=>tn(t,{recursive:!0,force:!0})}}catch(s){throw await tn(t,{recursive:!0,force:!0}),s}}function De(e,t){let n=e[t];return typeof n==="string"&&n.trim()?n.trim():void 0}function bs(e,t){return hs("sha256").update(`project-import-v1\x00${e}\x00${t}`).digest("hex")}function Ss(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((o)=>`- ${o}`));if(e.manifest.secretKeys.length>0)r.push("Project secret keys available to cloud tasks:",...e.manifest.secretKeys.map((o)=>`- ${o}`));if(e.manifest.quarantinedResources.length>0)r.push("Quarantined resources (preserved but not activated):",...e.manifest.quarantinedResources.map((o)=>`- ${o.kind}: ${o.path}`));if(e.manifest.environment.warnings.length>0)r.push("Environment warnings:",...e.manifest.environment.warnings.map((o)=>`- ${o}`));return r.push("Setup runs inside the isolated Coding Workspace and may access project secrets."),r.join(`
|
|
100
|
+
`)}var ct={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(`
|
|
101
|
+
`),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 ws(ks(e.cwd,e.args[0]??".")),n=B({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 --workspace <id>` first.");let r=le(t);if(r?.projectId)throw new y("already_imported","This folder is already bound to an Hlix project. Use `hlix push`.");let o=De(e.flags,"history");if(o&&o!=="preserve"&&o!=="abort-on-findings")throw Error("--history must be `abort-on-findings` or `preserve`.");if(!r&&e.flags["dry-run"]!==!0)Ce(t,{schemaVersion:1,workspaceId:n.workspaceId,apiUrl:n.baseUrl});let s=await Q(t,{...De(e.flags,"env-file")?{envFile:De(e.flags,"env-file")}:{},environment:e.env,historyMode:o==="preserve"?"preserve":"abort_on_findings"});if(e.flags["dry-run"]!==!0&&s.blocking.length===0){let c=Ss(s);if(c&&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(c))throw new y("cancelled","Import cancelled.")}}let i={root:t,name:De(e.flags,"name")??vs(t),stack:De(e.flags,"stack")??s.manifest.stack,files:s.manifest.totals.files,bytes:s.manifest.totals.bytes,activeEnvFiles:s.manifest.activeEnvFiles,secretKeys:s.manifest.secretKeys,protectedFiles:s.manifest.secretFiles.length+s.manifest.quarantinedResources.length,environment:s.manifest.environment,historicalSecretFindings:s.manifest.historicalSecretFindings,quarantinedResources:s.manifest.quarantinedResources,mcpServers:s.manifest.mcpServers,skipped:s.manifest.skipped,blocking:s.blocking,manifestSha256:s.manifestSha256};if(e.flags["dry-run"]===!0){if(e.json)e.stdout(v(j(ct.name,i)));else{let c=[...s.manifest.secretFiles.map((l)=>`${l.kind}: ${l.path}`),...s.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:",...c.length?c.map((l)=>`- ${l}`):["- none"],"","Environment warnings:",...i.environment.warnings.length?i.environment.warnings.map((l)=>`- ${l}`):["- none"],...i.blocking.length?["","Blocking findings:",...i.blocking.map((l)=>`- ${l}`)]:[]].join(`
|
|
102
|
+
`)+`
|
|
103
|
+
`)}return s.blocking.length?1:0}if(s.blocking.length)throw new y("scan_blocked",`Project scan blocked import:
|
|
104
|
+
- ${s.blocking.join(`
|
|
105
|
+
- `)}`);let a=await at(s);try{let c=e.requireClient(t),l=await c.imports.create({idempotencyKey:bs(s.manifestSha256,a.bundleSha256),name:i.name,stack:i.stack,defaultBranch:"main",historyMode:s.manifest.git.historyMode,manifest:s.manifest,manifestSha256:s.manifestSha256,bundleSha256:a.bundleSha256,bundleSize:a.bundleSize,commitSha:a.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 c.imports.uploadBundle(l.upload,new Blob([Uint8Array.from(await ys(a.bundlePath))]),{onProgress:(h,k)=>{if(!e.json)e.stderr(`Uploading ${h}/${k} bytes\r`)}})}let d=(l.import.status==="ready"?{import:l.import}:await c.imports.finalize(l.import.id,{secrets:s.secretValues,protectedFiles:s.protectedFiles})).import,u=d.projectId??d.requestedProjectId;if(!u||!d.revisionId||!d.generation)throw Error("Import completed without project revision metadata.");Ce(t,{schemaVersion:1,projectId:u,workspaceId:n.workspaceId,apiUrl:n.baseUrl}),$e(t,{schemaVersion:1,revisionId:d.revisionId,generation:d.generation,commitSha:a.commitSha,manifestSha256:s.manifestSha256,historyMode:s.manifest.git.historyMode,rootName:s.manifest.rootName});let m={projectId:u,revisionId:d.revisionId,generation:d.generation,commitSha:a.commitSha,files:s.manifest.totals.files,bytes:s.manifest.totals.bytes};if(e.json)e.stdout(v(j(ct.name,m)));else e.stderr(`
|
|
106
|
+
`),e.stdout(`Imported ${i.name}
|
|
107
|
+
Project ID: ${u}
|
|
108
|
+
Revision: ${d.generation}
|
|
109
|
+
`);return 0}finally{await a.dispose()}}};var js=(e)=>e instanceof Error?e.message:String(e);async function Es(e,t,n,r,o){try{let s=await Q(t,{historyMode:n,environment:e.env,rootName:r});return{files:s.manifest.totals.files,manifestSha256:s.manifestSha256,changed:o?s.manifestSha256!==o:null,blocking:s.blocking,error:null}}catch(s){return{files:null,manifestSha256:null,changed:null,blocking:[],error:js(s)}}}var nn={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(`
|
|
110
|
+
`),supportsJson:!0,async run(e){let t=B({env:e.env,flags:e.flags,cwd:e.cwd}),n=t.binding,r=n?tt(n.root):null,o=n?await Es(e,n.root,r?.historyMode??"preserve",r?.rootName,r?.manifestSha256):null,s=null;if(n?.config.projectId&&t.credential&&!t.conflict)try{let c=(await e.requireClient().revisions.head(n.config.projectId)).revision;s={revisionId:c.id,generation:c.generation,changed:r?c.id!==r.revisionId||c.generation!==r.generation:null,error:null}}catch(c){s={revisionId:"",generation:0,changed:null,error:Tt(c).code}}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:o,cloud:s};if(e.json)return e.stdout(v(j(nn.name,i))),0;let a=[["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",t.credential?t.credentialSource==="env"?`environment (${t.credential?.sessionToken?"HLIX_SESSION_TOKEN":"HLIX_API_KEY"})`:`file (${t.credentialPath})`:"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)a.push(["revision",`generation ${r.generation} (${r.revisionId})`]);if(o){if(a.push(["local",o.error?`could not scan: ${o.error}`:o.changed===null?`${o.files} files, no synced base revision`:o.changed?`${o.files} files, modified since the last sync`:`${o.files} files, matches the last sync`]),o.blocking.length>0)a.push(["blocking",o.blocking.join("; ")])}if(s)a.push(["cloud",s.error?`not checked: ${s.error}`:s.changed?`generation ${s.generation} available — run \`hlix pull\``:`generation ${s.generation}, up to date`]);if(t.conflict)a.push(["conflict",t.conflict]);return e.stdout(`${R(a)}
|
|
111
|
+
`),0}};import{createHash as Us}from"node:crypto";import{readFile as Ms,realpath as Bs}from"node:fs/promises";import{createHash as Ps}from"node:crypto";import{constants as lt}from"node:fs";import{chmod as jr,copyFile as Cs,lstat as rn,mkdir as $s,mkdtemp as xs,open as Is,realpath as _s,rename as Os,rm as Je,writeFile as Rs}from"node:fs/promises";import{tmpdir as Ts}from"node:os";import{dirname as $r,join as W,relative as As,resolve as Hs,sep as Er}from"node:path";import{spawnSync as Fs}from"node:child_process";function xr(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:{},o=r.historyMode==="preserve"||r.historyMode==="abort_on_findings"?r.historyMode:void 0,s=typeof n.rootName==="string"&&n.rootName.trim()?n.rootName:void 0;return{historyMode:o,rootName:s}}function Ir(e){let t=e;if(typeof t==="string")try{t=JSON.parse(t)}catch{return[]}if(!t||typeof t!=="object")return[];let n=t.files;if(!Array.isArray(n))return[];return n.flatMap((r)=>{if(!r||typeof r!=="object")return[];let o=r;return typeof o.path==="string"&&typeof o.sha256==="string"?[{path:o.path,sha256:o.sha256}]:[]})}function qe(e,t){let n=Fs("git",["-C",e,...t],{encoding:"utf8",maxBuffer:52428800,stdio:["ignore","pipe","pipe"]});if(n.status!==0)throw Error(n.stderr.trim().split(`
|
|
112
|
+
`).at(-1)??"Git command failed");return n.stdout.trim()}function Pr(e){return Ps("sha256").update(e).digest("hex")}async function on(e,t){let n=await _s(e),r=Hs(n,...t.split("/"));if(r!==n&&!r.startsWith(n+Er))throw Error(`Protected path escapes the project: ${t}`);let o=As(n,$r(r)),s=n;for(let i of o.split(Er).filter(Boolean)){s=W(s,i);try{let a=await rn(s);if(!a.isDirectory()||a.isSymbolicLink())throw Error(`Protected path crosses a non-directory: ${t}`)}catch(a){if(a.code!=="ENOENT")throw a;await $s(s,{mode:448})}}return r}async function Cr(e,t,n){let r=await on(e,t);try{let i=await rn(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 o=W($r(r),`.hlix-pull-${crypto.randomUUID()}.tmp`),s=await Is(o,lt.O_WRONLY|lt.O_CREAT|lt.O_EXCL|lt.O_NOFOLLOW,384);try{await s.writeFile(n),await s.sync()}finally{await s.close()}try{await Os(o,r)}catch(i){throw await Je(o,{force:!0}),i}}async function Ns(e,t){let n=await on(e,t);try{let r=await rn(n);if(!r.isFile()||r.isSymbolicLink())throw Error(`Refusing to replace non-regular project file: ${t}`)}catch(r){if(r.code!=="ENOENT")throw r}}async function _r(e,t,n,r,o){let s=await xs(W(Ts(),"hlix-pull-"));await jr(s,448);let i=W(s,"project.bundle"),a=W(s,"checkout");try{let c=Buffer.from(await r.arrayBuffer());if(c.byteLength!==n.bundleSize||Pr(c)!==n.bundleSha256)throw Error("Downloaded revision bundle failed integrity verification.");if(await Rs(i,c,{mode:384}),qe(s,["clone","--no-hardlinks","--branch","main",i,a]),qe(a,["bundle","verify",i]),qe(a,["rev-parse","HEAD"])!==n.commitSha)throw Error("Downloaded revision bundle does not match the cloud commit.");let l=n.manifest,p=new Map;for(let m of[...l.secretFiles,...l.quarantinedResources])p.set(m.path,m);if(o.files.length!==p.size)throw Error("Cloud protected files do not match the revision manifest.");let d=new Map;for(let m of o.files){let h=p.get(m.path),k=Buffer.from(m.contentBase64,"base64");if(k.toString("base64").replace(/=+$/,"")!==m.contentBase64.replace(/=+$/,"")||!h||h.kind!==m.kind||k.byteLength!==h.size||Pr(k)!==h.sha256)throw Error(`Cloud protected file failed integrity verification: ${m.path}`);d.set(m.path,k)}let u=new Set([...l.files.map((m)=>m.path),...t.manifest.secretFiles.map((m)=>m.path),...t.manifest.quarantinedResources.map((m)=>m.path),...d.keys()]);for(let m of[...u].sort())await Ns(e,m);for(let[m,h]of d)await Cr(a,m,h);if(t.manifest.git.detected){qe(e,["fetch",i,"refs/heads/main"]),qe(e,["reset","--hard","FETCH_HEAD"]);let m=new Set(l.files.map((h)=>h.path));for(let h of t.manifest.files)if(!m.has(h.path))await Je(W(e,...h.path.split("/")),{force:!0})}else{for(let m of t.manifest.files)await Je(W(e,...m.path.split("/")),{force:!0});for(let m of l.files){let h=await on(e,m.path);await Cs(W(a,...m.path.split("/")),h),await jr(h,m.executable?493:420)}}for(let m of[...t.manifest.secretFiles,...t.manifest.quarantinedResources])if(!d.has(m.path))await Je(W(e,...m.path.split("/")),{force:!0});for(let[m,h]of d)await Cr(e,m,h)}finally{await Je(s,{recursive:!0,force:!0})}}function ge(e,t,n){let r=new Map(Ir(n.manifest).map((c)=>[c.path,c.sha256])),o=new Map(e.manifest.files.map((c)=>[c.path,c.sha256])),s=0,i=0;for(let[c,l]of o){let p=r.get(c);if(p===void 0)s+=1;else if(p!==l)i+=1}let a=0;for(let c of r.keys())if(!o.has(c))a+=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:o.size,cloud:r.size,localOnly:s,cloudOnly:a,differing:i}}}function sn(e,t,n){let{localChanged:r,cloudChanged:o}=t;if(e==="push")return o?"conflict":r?"push":"none";if(e==="pull"){if(!o)return"none";return r&&!n?"conflict":"pull"}if(r&&o)return"conflict";return r?"push":o?"pull":"none"}function an(e,t,n){return e==="pull"&&t.localChanged&&!n}var Ls={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 Or(e,t,n,r){let o=n.files;return[`${e} --dry-run: ${Ls[e][t]}`,...r?["Requires --yes (or interactive approval) to execute."]:[],"",R([["local",`generation ${n.local.generation} (${n.local.revisionId})${n.localChanged?" — modified":""}`],["cloud",`generation ${n.cloud.generation} (${n.cloud.revisionId})${n.cloudChanged?" — ahead":""}`],["files",`${o.local} local, ${o.cloud} cloud — ${o.localOnly} local-only, ${o.cloudOnly} cloud-only, ${o.differing} differing`]])].join(`
|
|
113
|
+
`)}function Ks(e,t,n){return Us("sha256").update(`project-push-v1\x00${e}\x00${t}\x00${n}`).digest("hex")}var zs={schemaVersion:1,revisionId:"",generation:0,commitSha:""};async function he(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=tt(n.root)??(t?zs: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 Bs(n.root),config:n.config,state:r}}async function Ge(e,t,n,r){let o=await Q(e,{historyMode:n,environment:t,rootName:r});if(o.blocking.length>0)throw new y("scan_blocked",`Project scan blocked sync:
|
|
114
|
+
- ${o.blocking.join(`
|
|
115
|
+
- `)}`);return o}async function cn(e,t,n,r){let{state:o,config:s}=await he(r,{allowUnsynced:n==="pull"}),i=e.requireClient(),[a,c]=await Promise.all([Ge(r,e.env,o.historyMode??"preserve",o.rootName),i.revisions.head(s.projectId)]),l=ge(a,o,c.revision),p=sn(n,l,e.flags.force===!0),d=an(p,l,e.flags.yes===!0);if(e.json)e.stdout(v(j(t,{dryRun:!0,action:p,approvalRequired:d,...l})));else e.stdout(`${Or(n,p,l,d)}
|
|
116
|
+
`);return p==="conflict"?1:0}async function Ds(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(`
|
|
117
|
+
`);if(!await e.confirm(n))throw new y("cancelled","Pull cancelled.")}async function Rr(e,t,n,r){let{state:o,config:s}=await he(e),i=t.requireClient(),a=o.historyMode??"preserve",c=n??await Ge(e,t.env,a,o.rootName),l=r??(await i.revisions.head(s.projectId)).revision;if(l.id!==o.revisionId||l.generation!==o.generation)throw new y("conflict","Cloud changed since the local base. Run `hlix pull` or resolve with `hlix sync`.");if(o.manifestSha256&&c.manifestSha256===o.manifestSha256)return{action:"none",revisionId:o.revisionId,generation:o.generation};let p=await at(c);try{let d=await i.revisions.createUpload(s.projectId,{idempotencyKey:Ks(o.revisionId,c.manifestSha256,p.bundleSha256),expectedRevisionId:o.revisionId,expectedGeneration:o.generation,manifest:c.manifest,manifestSha256:c.manifestSha256,bundleSha256:p.bundleSha256,bundleSize:p.bundleSize,commitSha:p.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 Ms(p.bundlePath))]),{onProgress:(m,h)=>{if(!t.json)t.stderr(`Uploading ${m}/${h} bytes\r`)}})}let u=await i.revisions.finalize(s.projectId,d.revisionUpload.id,{secrets:c.secretValues,protectedFiles:c.protectedFiles});if(!u.revision)throw Error("Revision finalized without head metadata.");return $e(e,{schemaVersion:1,revisionId:u.revision.id,generation:u.revision.generation,commitSha:u.revision.commitSha,manifestSha256:u.revision.manifestSha256,historyMode:a,rootName:o.rootName??c.manifest.rootName}),{action:"push",...u.revision}}finally{await p.dispose()}}async function Tr(e,t,n,r,o){let{state:s,config:i}=await he(e,{allowUnsynced:!0}),a=t.requireClient(),c=s.historyMode??"preserve",l=r??await Ge(e,t.env,c,s.rootName),p=o??(await a.revisions.head(i.projectId)).revision;if(p.id===s.revisionId&&p.generation===s.generation)return{action:"none",revisionId:s.revisionId,generation:s.generation};let d=s.manifestSha256?l.manifestSha256!==s.manifestSha256:(()=>{let{files:E}=ge(l,s,p);return E.localOnly+E.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 Ds(t,ge(l,s,p));let[u,m]=await Promise.all([a.revisions.downloadBundle(i.projectId,p.id),a.revisions.protectedFiles(i.projectId)]);await _r(e,l,p,u,m);let h=xr(p.manifest),k=h.historyMode??c,_=h.rootName??s.rootName??l.manifest.rootName,D=await Ge(e,t.env,k,_);return $e(e,{schemaVersion:1,revisionId:p.id,generation:p.generation,commitSha:p.commitSha,manifestSha256:D.manifestSha256,historyMode:k,rootName:_}),{action:"pull",revisionId:p.id,generation:p.generation,commitSha:p.commitSha}}function ln(e,t,n){if(e.json)e.stdout(v(j(t,n)));else if("action"in n&&n.action==="none")e.stdout(`Already in sync.
|
|
118
|
+
`);else e.stdout(`${String("action"in n?n.action:"sync")} complete.
|
|
119
|
+
`)}var dt={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 he(e.cwd);if(e.flags["dry-run"]===!0)return cn(e,dt.name,"push",t);return ln(e,dt.name,await Rr(t,e)),0}},pt={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(`
|
|
120
|
+
`),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 he(e.cwd,{allowUnsynced:!0});if(e.flags["dry-run"]===!0)return cn(e,pt.name,"pull",t);return ln(e,pt.name,await Tr(t,e,e.flags.force===!0)),0}},ut={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 he(e.cwd);if(e.flags["dry-run"]===!0)return cn(e,ut.name,"sync",t);let o=e.requireClient(),[s,i]=await Promise.all([Ge(t,e.env,n.historyMode??"preserve",n.rootName),o.revisions.head(r.projectId)]),a=i.revision,c=ge(s,n,a);if(c.localChanged&&c.cloudChanged)throw new y("conflict","Both local and cloud changed since the last sync. Pull or push explicitly after reviewing the conflict.");let l=c.localChanged?await Rr(t,e,s,a):c.cloudChanged?await Tr(t,e,!1,s,a):{action:"none",revisionId:n.revisionId,generation:n.generation};return ln(e,ut.name,l),0}};import{lstat as Ar,readFile as qs,realpath as Js}from"node:fs/promises";import{basename as dn,dirname as Gs,extname as Ws,join as Vs,parse as Hr,resolve as pn}from"node:path";function We(e,t){let n=e.flags[t];return typeof n==="string"&&n.trim()?n.trim():void 0}function un(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 mn(e,t){let n=await Ar(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 Js(e),content:await qs(e,"utf8")}}function fn(e,t,n,r){if(e.json)e.stdout(v(j(t,n)));else e.stdout(`${r}
|
|
121
|
+
`)}var gn={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=un(e.cwd),n=pn(e.cwd,e.args[0]),r=await Ar(n);if(r.isSymbolicLink())throw Error(`Refusing to import a symlink: ${n}`);let o=r.isDirectory()?Vs(n,"SKILL.md"):n,s=await mn(o,200000),i=r.isDirectory()?dn(n):dn(o)==="SKILL.md"?dn(Gs(o)):Hr(o).name,a=We(e,"name")??i;if(!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(a))throw Error("Skill name must be a lowercase kebab-case slug.");let c=await e.requireClient().resources.importSkill(t.projectId,{slug:a,content:s.content});return fn(e,gn.name,c.skill,`Imported skill ${a}`),0}},hn={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=un(e.cwd),n=pn(e.cwd,e.args[0]);if(![".md",".mdx"].includes(Ws(n).toLowerCase()))throw Error("Agent imports must be Markdown files.");let r=await mn(n,20000),o=We(e,"runtime")??"hlix";if(!["claude-code","codex","cursor-agent","hlix"].includes(o))throw Error("--runtime must be claude-code, codex, cursor-agent, or hlix.");let s=We(e,"duty")??"executor";if(s!=="executor"&&s!=="intake")throw Error("--duty must be executor or intake.");let i=We(e,"name")??Hr(n).name.replace(/[-_]+/g," "),a=await e.requireClient().resources.importAgent(t.projectId,{name:i,instructions:r.content,runtimeKind:o,duty:s});return fn(e,hn.name,a.agent,a.agent.duty==="intake"?`Imported agent ${a.agent.name} as this project's intake agent`:`Imported agent ${a.agent.name}`),0}},yn={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=un(e.cwd),n=await mn(pn(e.cwd,e.args[0]),200000),r;try{r=JSON.parse(n.content)}catch{throw Error("MCP config is not valid JSON.")}let o=Object.entries(r.mcpServers??{});if(o.length===0)throw Error("MCP config contains no servers.");let s=We(e,"server");if(!s&&o.length>1)throw Error("MCP config contains multiple servers; select one with --server <name>.");let i=s?o.find(([k])=>k===s):o[0];if(!i)throw Error(`MCP server not found: ${s}`);let[a,c]=i,l=c.type==="http"||c.type==="sse"?c.type:typeof c.command==="string"?"stdio":typeof c.url==="string"?"http":null;if(!l)throw Error(`MCP server ${a} 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 p=c.env&&typeof c.env==="object"&&!Array.isArray(c.env)?c.env:{},d=c.headers&&typeof c.headers==="object"&&!Array.isArray(c.headers)?c.headers:{};if(Object.values(d).some((k)=>typeof k!=="string"))throw Error(`MCP server ${a} headers must be strings.`);let u=Object.values(d).flatMap((k)=>[...k.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g)].map((_)=>_[1]));if(Object.keys(d).length>0&&u.length===0)throw Error("MCP remote headers must use ${KEY} placeholders; literal credentials are refused.");let m=/^(?:(?:Bearer|Basic|Token) )?\$\{[A-Za-z_][A-Za-z0-9_]*\}$/i;if(Object.values(d).some((k)=>!m.test(k)))throw Error("MCP remote headers must be ${KEY} or an approved auth scheme followed by ${KEY}.");let h=await e.requireClient().resources.importMcp(t.projectId,{name:a,transport:l,...typeof c.command==="string"?{command:c.command}:{},...Array.isArray(c.args)&&c.args.every((k)=>typeof k==="string")?{args:c.args}:{},...typeof c.url==="string"?{url:c.url}:{},...Object.keys(d).length>0?{headers:d}:{},envKeys:[...new Set([...Object.keys(p),...u])].sort()});return fn(e,yn.name,h.mcpServer,`Imported MCP server ${a}`),0}};function wn(e,t){let n=e[t];if(typeof n!=="string"||n.trim()==="")throw new y("missing_argument",`--${t} is required.`);return n}var vn={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(`
|
|
122
|
+
`),supportsJson:!0,options:["title","description"],args:{min:1,max:1},async run(e){let t=e.args[0],n=wn(e.flags,"title"),r=wn(e.flags,"description"),o=await e.requireClient().cycles.propose({projectId:t,title:n,description:r});if(e.json)return e.stdout(v(j(vn.name,o))),0;return e.stdout(`${R([["project",t],["title",n],["status",o.adopted?"adopted — the project is planning it now":"recorded — it will be planned on the next pass"]])}
|
|
123
|
+
`),0}},kn={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(`
|
|
124
|
+
`),supportsJson:!0,options:["title","description"],args:{min:1,max:1},async run(e){let t=e.args[0],n=wn(e.flags,"description"),r=typeof e.flags.title==="string"?e.flags.title:void 0,o=await e.requireClient().tasks.create({projectId:t,description:n,...r?{title:r}:{}});if(e.json)return e.stdout(v(j(kn.name,o))),0;return e.stdout(`${R([["task",o.id],["project",t],["status",o.status??"queued"],["note","not started — dispatch with `hlix cycles create`"]])}
|
|
125
|
+
`),0}},bn={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(`
|
|
126
|
+
`),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(v(j(bn.name,r))),0;return e.stdout(`${R([["scope",t?`project ${t}`:"workspace"],["harness",r.harness],["source",r.source]])}
|
|
127
|
+
`),0}},Sn={name:"harness set",summary:"Choose the coder a project or the workspace runs",usage:[`Usage: hlix harness set <${pe.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(`
|
|
128
|
+
`),supportsJson:!0,options:["org"],args:{min:1,max:2},async run(e){let t=e.args[0];if(!pe.includes(t))throw new y("invalid_usage",`harness must be one of ${pe.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 o=e.requireClient(),s=n?await o.modelConfig.setProjectHarness(n,t):await o.modelConfig.setHarness(t);if(e.json)return e.stdout(v(j(Sn.name,s))),0;return e.stdout(`${R([["scope",n?`project ${n}`:"workspace"],["harness",t]])}
|
|
129
|
+
`),0}};var Qc=[Lt,Ut,me,nn,Mt,Bt,Kt,Qt,ct,ut,pt,dt,gn,hn,yn,zt,Dt,Jt,Gt,Wt,Vt,kn,vn,bn,Sn];
|
|
130
|
+
export{y as a,Ys as b,N as c,B as d,bo as e,Di as f,Yn as g,pe as h,ea as i,Ft as j,Qc as k};
|