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